]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Support initializer in destructuring
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2015 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20150909
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (require 'cl-lib)
89 (require 'imenu)
90 (require 'js)
91 (require 'etags)
92
93 (eval-and-compile
94 (if (version< emacs-version "25.0")
95 (require 'js2-old-indent)
96 (defvaralias 'js2-basic-offset 'js-indent-level nil)
97 (defalias 'js2-proper-indentation 'js--proper-indentation)
98 (defalias 'js2-indent-line 'js-indent-line)
99 (defalias 'js2-re-search-forward 'js--re-search-forward)))
100
101 ;;; Externs (variables presumed to be defined by the host system)
102
103 (defvar js2-ecma-262-externs
104 (mapcar 'symbol-name
105 '(Array Boolean Date Error EvalError Function Infinity JSON
106 Math NaN Number Object RangeError ReferenceError RegExp
107 String SyntaxError TypeError URIError
108 decodeURI decodeURIComponent encodeURI
109 encodeURIComponent escape eval isFinite isNaN
110 parseFloat parseInt undefined unescape))
111 "Ecma-262 externs. Included in `js2-externs' by default.")
112
113 (defvar js2-browser-externs
114 (mapcar 'symbol-name
115 '(;; DOM level 1
116 Attr CDATASection CharacterData Comment DOMException
117 DOMImplementation Document DocumentFragment
118 DocumentType Element Entity EntityReference
119 ExceptionCode NamedNodeMap Node NodeList Notation
120 ProcessingInstruction Text
121
122 ;; DOM level 2
123 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
124 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
125 HTMLBodyElement HTMLButtonElement HTMLCollection
126 HTMLDListElement HTMLDirectoryElement HTMLDivElement
127 HTMLDocument HTMLElement HTMLFieldSetElement
128 HTMLFontElement HTMLFormElement HTMLFrameElement
129 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
130 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
131 HTMLImageElement HTMLInputElement HTMLIsIndexElement
132 HTMLLIElement HTMLLabelElement HTMLLegendElement
133 HTMLLinkElement HTMLMapElement HTMLMenuElement
134 HTMLMetaElement HTMLModElement HTMLOListElement
135 HTMLObjectElement HTMLOptGroupElement
136 HTMLOptionElement HTMLOptionsCollection
137 HTMLParagraphElement HTMLParamElement HTMLPreElement
138 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
139 HTMLStyleElement HTMLTableCaptionElement
140 HTMLTableCellElement HTMLTableColElement
141 HTMLTableElement HTMLTableRowElement
142 HTMLTableSectionElement HTMLTextAreaElement
143 HTMLTitleElement HTMLUListElement
144
145 ;; DOM level 3
146 DOMConfiguration DOMError DOMException
147 DOMImplementationList DOMImplementationSource
148 DOMLocator DOMStringList NameList TypeInfo
149 UserDataHandler
150
151 ;; Window
152 window alert confirm document java navigator prompt screen
153 self top requestAnimationFrame cancelAnimationFrame
154
155 ;; W3C CSS
156 CSSCharsetRule CSSFontFace CSSFontFaceRule
157 CSSImportRule CSSMediaRule CSSPageRule
158 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
159 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
160 CSSValue CSSValueList Counter DOMImplementationCSS
161 DocumentCSS DocumentStyle ElementCSSInlineStyle
162 LinkStyle MediaList RGBColor Rect StyleSheet
163 StyleSheetList ViewCSS
164
165 ;; W3C Event
166 EventListener EventTarget Event DocumentEvent UIEvent
167 MouseEvent MutationEvent KeyboardEvent
168
169 ;; W3C Range
170 DocumentRange Range RangeException
171
172 ;; W3C XML
173 XPathResult XMLHttpRequest
174
175 ;; console object. Provided by at least Chrome and Firefox.
176 console))
177 "Browser externs.
178 You can cause these to be included or excluded with the custom
179 variable `js2-include-browser-externs'.")
180
181 (defvar js2-rhino-externs
182 (mapcar 'symbol-name
183 '(Packages importClass importPackage com org java
184 ;; Global object (shell) externs.
185 defineClass deserialize doctest gc help load
186 loadClass print quit readFile readUrl runCommand seal
187 serialize spawn sync toint32 version))
188 "Mozilla Rhino externs.
189 Set `js2-include-rhino-externs' to t to include them.")
190
191 (defvar js2-node-externs
192 (mapcar 'symbol-name
193 '(__dirname __filename Buffer clearInterval clearTimeout require
194 console exports global module process setInterval setTimeout
195 querystring))
196 "Node.js externs.
197 Set `js2-include-node-externs' to t to include them.")
198
199 (defvar js2-typed-array-externs
200 (mapcar 'symbol-name
201 '(ArrayBuffer Uint8ClampedArray DataView
202 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
203 Float32Array Float64Array))
204 "Khronos typed array externs. Available in most modern browsers and
205 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
206 are enabled, these will also be included.")
207
208 (defvar js2-harmony-externs
209 (mapcar 'symbol-name
210 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
211 "ES6 externs. If `js2-include-browser-externs' is enabled and
212 `js2-language-version' is sufficiently high, these will be included.")
213
214 ;;; Variables
215
216 (defun js2-mark-safe-local (name pred)
217 "Make the variable NAME buffer-local and mark it as safe file-local
218 variable with predicate PRED."
219 (make-variable-buffer-local name)
220 (put name 'safe-local-variable pred))
221
222 (defcustom js2-highlight-level 2
223 "Amount of syntax highlighting to perform.
224 0 or a negative value means none.
225 1 adds basic syntax highlighting.
226 2 adds highlighting of some Ecma built-in properties.
227 3 adds highlighting of many Ecma built-in functions."
228 :group 'js2-mode
229 :type '(choice (const :tag "None" 0)
230 (const :tag "Basic" 1)
231 (const :tag "Include Properties" 2)
232 (const :tag "Include Functions" 3)))
233
234 (defvar js2-mode-dev-mode-p nil
235 "Non-nil if running in development mode. Normally nil.")
236
237 (defgroup js2-mode nil
238 "An improved JavaScript mode."
239 :group 'languages)
240
241 (defcustom js2-idle-timer-delay 0.2
242 "Delay in secs before re-parsing after user makes changes.
243 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
244 :type 'number
245 :group 'js2-mode)
246 (make-variable-buffer-local 'js2-idle-timer-delay)
247
248 (defcustom js2-dynamic-idle-timer-adjust 0
249 "Positive to adjust `js2-idle-timer-delay' based on file size.
250 The idea is that for short files, parsing is faster so we can be
251 more responsive to user edits without interfering with editing.
252 The buffer length in characters (typically bytes) is divided by
253 this value and used to multiply `js2-idle-timer-delay' for the
254 buffer. For example, a 21k file and 10k adjust yields 21k/10k
255 == 2, so js2-idle-timer-delay is multiplied by 2.
256 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
257 `js2-idle-timer-delay' is not dependent on the file size."
258 :type 'number
259 :group 'js2-mode)
260
261 (defcustom js2-concat-multiline-strings t
262 "When non-nil, `js2-line-break' in mid-string will make it a
263 string concatenation. When `eol', the '+' will be inserted at the
264 end of the line, otherwise, at the beginning of the next line."
265 :type '(choice (const t) (const eol) (const nil))
266 :group 'js2-mode)
267
268 (defcustom js2-mode-show-parse-errors t
269 "True to highlight parse errors."
270 :type 'boolean
271 :group 'js2-mode)
272
273 (defcustom js2-mode-show-strict-warnings t
274 "Non-nil to emit Ecma strict-mode warnings.
275 Some of the warnings can be individually disabled by other flags,
276 even if this flag is non-nil."
277 :type 'boolean
278 :group 'js2-mode)
279
280 (defcustom js2-strict-trailing-comma-warning t
281 "Non-nil to warn about trailing commas in array literals.
282 Ecma-262-5.1 allows them, but older versions of IE raise an error."
283 :type 'boolean
284 :group 'js2-mode)
285
286 (defcustom js2-strict-missing-semi-warning t
287 "Non-nil to warn about semicolon auto-insertion after statement.
288 Technically this is legal per Ecma-262, but some style guides disallow
289 depending on it."
290 :type 'boolean
291 :group 'js2-mode)
292
293 (defcustom js2-missing-semi-one-line-override nil
294 "Non-nil to permit missing semicolons in one-line functions.
295 In one-liner functions such as `function identity(x) {return x}'
296 people often omit the semicolon for a cleaner look. If you are
297 such a person, you can suppress the missing-semicolon warning
298 by setting this variable to t."
299 :type 'boolean
300 :group 'js2-mode)
301
302 (defcustom js2-strict-inconsistent-return-warning t
303 "Non-nil to warn about mixing returns with value-returns.
304 It's perfectly legal to have a `return' and a `return foo' in the
305 same function, but it's often an indicator of a bug, and it also
306 interferes with type inference (in systems that support it.)"
307 :type 'boolean
308 :group 'js2-mode)
309
310 (defcustom js2-strict-cond-assign-warning t
311 "Non-nil to warn about expressions like if (a = b).
312 This often should have been '==' instead of '='. If the warning
313 is enabled, you can suppress it on a per-expression basis by
314 parenthesizing the expression, e.g. if ((a = b)) ..."
315 :type 'boolean
316 :group 'js2-mode)
317
318 (defcustom js2-strict-var-redeclaration-warning t
319 "Non-nil to warn about redeclaring variables in a script or function."
320 :type 'boolean
321 :group 'js2-mode)
322
323 (defcustom js2-strict-var-hides-function-arg-warning t
324 "Non-nil to warn about a var decl hiding a function argument."
325 :type 'boolean
326 :group 'js2-mode)
327
328 (defcustom js2-skip-preprocessor-directives nil
329 "Non-nil to treat lines beginning with # as comments.
330 Useful for viewing Mozilla JavaScript source code."
331 :type 'boolean
332 :group 'js2-mode)
333
334 (defcustom js2-language-version 200
335 "Configures what JavaScript language version to recognize.
336 Currently versions 150, 160, 170, 180 and 200 are supported,
337 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
338 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
339 yield, and Array comprehensions, and 1.8 adds function closures."
340 :type 'integer
341 :group 'js2-mode)
342
343 (defcustom js2-instanceof-has-side-effects nil
344 "If non-nil, treats the instanceof operator as having side effects.
345 This is useful for xulrunner apps."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-move-point-on-right-click t
350 "Non-nil to move insertion point when you right-click.
351 This makes right-click context menu behavior a bit more intuitive,
352 since menu operations generally apply to the point. The exception
353 is if there is a region selection, in which case the point does -not-
354 move, so cut/copy/paste can work properly.
355
356 Note that IntelliJ moves the point, and Eclipse leaves it alone,
357 so this behavior is customizable."
358 :group 'js2-mode
359 :type 'boolean)
360
361 (defcustom js2-allow-rhino-new-expr-initializer t
362 "Non-nil to support a Rhino's experimental syntactic construct.
363
364 Rhino supports the ability to follow a `new' expression with an object
365 literal, which is used to set additional properties on the new object
366 after calling its constructor. Syntax:
367
368 new <expr> [ ( arglist ) ] [initializer]
369
370 Hence, this expression:
371
372 new Object {a: 1, b: 2}
373
374 results in an Object with properties a=1 and b=2. This syntax is
375 apparently not configurable in Rhino - it's currently always enabled,
376 as of Rhino version 1.7R2."
377 :type 'boolean
378 :group 'js2-mode)
379
380 (defcustom js2-allow-member-expr-as-function-name nil
381 "Non-nil to support experimental Rhino syntax for function names.
382
383 Rhino supports an experimental syntax configured via the Rhino Context
384 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
385
386 function <member-expr> ( [ arg-list ] ) { <body> }
387
388 Where member-expr is a non-parenthesized 'member expression', which
389 is anything at the grammar level of a new-expression or lower, meaning
390 any expression that does not involve infix or unary operators.
391
392 When <member-expr> is not a simple identifier, then it is syntactic
393 sugar for assigning the anonymous function to the <member-expr>. Hence,
394 this code:
395
396 function a.b().c[2] (x, y) { ... }
397
398 is rewritten as:
399
400 a.b().c[2] = function(x, y) {...}
401
402 which doesn't seem particularly useful, but Rhino permits it."
403 :type 'boolean
404 :group 'js2-mode)
405
406 ;; scanner variables
407
408 (defmacro js2-deflocal (name value &optional comment)
409 "Define a buffer-local variable NAME with VALUE and COMMENT."
410 (declare (debug defvar) (doc-string 3))
411 `(progn
412 (defvar ,name ,value ,comment)
413 (make-variable-buffer-local ',name)))
414
415 (defvar js2-EOF_CHAR -1
416 "Represents end of stream. Distinct from js2-EOF token type.")
417
418 ;; I originally used symbols to represent tokens, but Rhino uses
419 ;; ints and then sets various flag bits in them, so ints it is.
420 ;; The upshot is that we need a `js2-' prefix in front of each name.
421 (defvar js2-ERROR -1)
422 (defvar js2-EOF 0)
423 (defvar js2-EOL 1)
424 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
425 (defvar js2-LEAVEWITH 3)
426 (defvar js2-RETURN 4)
427 (defvar js2-GOTO 5)
428 (defvar js2-IFEQ 6)
429 (defvar js2-IFNE 7)
430 (defvar js2-SETNAME 8)
431 (defvar js2-BITOR 9)
432 (defvar js2-BITXOR 10)
433 (defvar js2-BITAND 11)
434 (defvar js2-EQ 12)
435 (defvar js2-NE 13)
436 (defvar js2-LT 14)
437 (defvar js2-LE 15)
438 (defvar js2-GT 16)
439 (defvar js2-GE 17)
440 (defvar js2-LSH 18)
441 (defvar js2-RSH 19)
442 (defvar js2-URSH 20)
443 (defvar js2-ADD 21) ; infix plus
444 (defvar js2-SUB 22) ; infix minus
445 (defvar js2-MUL 23)
446 (defvar js2-DIV 24)
447 (defvar js2-MOD 25)
448 (defvar js2-NOT 26)
449 (defvar js2-BITNOT 27)
450 (defvar js2-POS 28) ; unary plus
451 (defvar js2-NEG 29) ; unary minus
452 (defvar js2-NEW 30)
453 (defvar js2-DELPROP 31)
454 (defvar js2-TYPEOF 32)
455 (defvar js2-GETPROP 33)
456 (defvar js2-GETPROPNOWARN 34)
457 (defvar js2-SETPROP 35)
458 (defvar js2-GETELEM 36)
459 (defvar js2-SETELEM 37)
460 (defvar js2-CALL 38)
461 (defvar js2-NAME 39) ; an identifier
462 (defvar js2-NUMBER 40)
463 (defvar js2-STRING 41)
464 (defvar js2-NULL 42)
465 (defvar js2-THIS 43)
466 (defvar js2-FALSE 44)
467 (defvar js2-TRUE 45)
468 (defvar js2-SHEQ 46) ; shallow equality (===)
469 (defvar js2-SHNE 47) ; shallow inequality (!==)
470 (defvar js2-REGEXP 48)
471 (defvar js2-BINDNAME 49)
472 (defvar js2-THROW 50)
473 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
474 (defvar js2-IN 52)
475 (defvar js2-INSTANCEOF 53)
476 (defvar js2-LOCAL_LOAD 54)
477 (defvar js2-GETVAR 55)
478 (defvar js2-SETVAR 56)
479 (defvar js2-CATCH_SCOPE 57)
480 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
481 (defvar js2-ENUM_INIT_VALUES 59)
482 (defvar js2-ENUM_INIT_ARRAY 60)
483 (defvar js2-ENUM_NEXT 61)
484 (defvar js2-ENUM_ID 62)
485 (defvar js2-THISFN 63)
486 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
487 (defvar js2-ARRAYLIT 65) ; array literal
488 (defvar js2-OBJECTLIT 66) ; object literal
489 (defvar js2-GET_REF 67) ; *reference
490 (defvar js2-SET_REF 68) ; *reference = something
491 (defvar js2-DEL_REF 69) ; delete reference
492 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
493 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
494 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
495
496 ;; XML support
497 (defvar js2-DEFAULTNAMESPACE 73)
498 (defvar js2-ESCXMLATTR 74)
499 (defvar js2-ESCXMLTEXT 75)
500 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
501 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
502 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
503 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
504
505 (defvar js2-first-bytecode js2-ENTERWITH)
506 (defvar js2-last-bytecode js2-REF_NS_NAME)
507
508 (defvar js2-TRY 80)
509 (defvar js2-SEMI 81) ; semicolon
510 (defvar js2-LB 82) ; left and right brackets
511 (defvar js2-RB 83)
512 (defvar js2-LC 84) ; left and right curly-braces
513 (defvar js2-RC 85)
514 (defvar js2-LP 86) ; left and right parens
515 (defvar js2-RP 87)
516 (defvar js2-COMMA 88) ; comma operator
517
518 (defvar js2-ASSIGN 89) ; simple assignment (=)
519 (defvar js2-ASSIGN_BITOR 90) ; |=
520 (defvar js2-ASSIGN_BITXOR 91) ; ^=
521 (defvar js2-ASSIGN_BITAND 92) ; &=
522 (defvar js2-ASSIGN_LSH 93) ; <<=
523 (defvar js2-ASSIGN_RSH 94) ; >>=
524 (defvar js2-ASSIGN_URSH 95) ; >>>=
525 (defvar js2-ASSIGN_ADD 96) ; +=
526 (defvar js2-ASSIGN_SUB 97) ; -=
527 (defvar js2-ASSIGN_MUL 98) ; *=
528 (defvar js2-ASSIGN_DIV 99) ; /=
529 (defvar js2-ASSIGN_MOD 100) ; %=
530
531 (defvar js2-first-assign js2-ASSIGN)
532 (defvar js2-last-assign js2-ASSIGN_MOD)
533
534 (defvar js2-HOOK 101) ; conditional (?:)
535 (defvar js2-COLON 102)
536 (defvar js2-OR 103) ; logical or (||)
537 (defvar js2-AND 104) ; logical and (&&)
538 (defvar js2-INC 105) ; increment/decrement (++ --)
539 (defvar js2-DEC 106)
540 (defvar js2-DOT 107) ; member operator (.)
541 (defvar js2-FUNCTION 108) ; function keyword
542 (defvar js2-EXPORT 109) ; export keyword
543 (defvar js2-IMPORT 110) ; import keyword
544 (defvar js2-IF 111) ; if keyword
545 (defvar js2-ELSE 112) ; else keyword
546 (defvar js2-SWITCH 113) ; switch keyword
547 (defvar js2-CASE 114) ; case keyword
548 (defvar js2-DEFAULT 115) ; default keyword
549 (defvar js2-WHILE 116) ; while keyword
550 (defvar js2-DO 117) ; do keyword
551 (defvar js2-FOR 118) ; for keyword
552 (defvar js2-BREAK 119) ; break keyword
553 (defvar js2-CONTINUE 120) ; continue keyword
554 (defvar js2-VAR 121) ; var keyword
555 (defvar js2-WITH 122) ; with keyword
556 (defvar js2-CATCH 123) ; catch keyword
557 (defvar js2-FINALLY 124) ; finally keyword
558 (defvar js2-VOID 125) ; void keyword
559 (defvar js2-RESERVED 126) ; reserved keywords
560
561 (defvar js2-EMPTY 127)
562
563 ;; Types used for the parse tree - never returned by scanner.
564
565 (defvar js2-BLOCK 128) ; statement block
566 (defvar js2-LABEL 129) ; label
567 (defvar js2-TARGET 130)
568 (defvar js2-LOOP 131)
569 (defvar js2-EXPR_VOID 132) ; expression statement in functions
570 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
571 (defvar js2-JSR 134)
572 (defvar js2-SCRIPT 135) ; top-level node for entire script
573 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
574 (defvar js2-USE_STACK 137)
575 (defvar js2-SETPROP_OP 138) ; x.y op= something
576 (defvar js2-SETELEM_OP 139) ; x[y] op= something
577 (defvar js2-LOCAL_BLOCK 140)
578 (defvar js2-SET_REF_OP 141) ; *reference op= something
579
580 ;; For XML support:
581 (defvar js2-DOTDOT 142) ; member operator (..)
582 (defvar js2-COLONCOLON 143) ; namespace::name
583 (defvar js2-XML 144) ; XML type
584 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
585 (defvar js2-XMLATTR 146) ; @
586 (defvar js2-XMLEND 147)
587
588 ;; Optimizer-only tokens
589 (defvar js2-TO_OBJECT 148)
590 (defvar js2-TO_DOUBLE 149)
591
592 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
593 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
594 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
595 (defvar js2-CONST 153)
596 (defvar js2-SETCONST 154)
597 (defvar js2-SETCONSTVAR 155)
598 (defvar js2-ARRAYCOMP 156)
599 (defvar js2-LETEXPR 157)
600 (defvar js2-WITHEXPR 158)
601 (defvar js2-DEBUGGER 159)
602
603 (defvar js2-COMMENT 160)
604 (defvar js2-TRIPLEDOT 161) ; for rest parameter
605 (defvar js2-ARROW 162) ; function arrow (=>)
606 (defvar js2-CLASS 163)
607 (defvar js2-EXTENDS 164)
608 (defvar js2-SUPER 165)
609 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
610 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
611 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
612
613 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
614
615 (defconst js2-debug-print-trees nil)
616
617 ;; Rhino accepts any string or stream as input. Emacs character
618 ;; processing works best in buffers, so we'll assume the input is a
619 ;; buffer. JavaScript strings can be copied into temp buffers before
620 ;; scanning them.
621
622 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
623 ;; They're the Emacs equivalent of instance variables, more or less.
624
625 (js2-deflocal js2-ts-dirty-line nil
626 "Token stream buffer-local variable.
627 Indicates stuff other than whitespace since start of line.")
628
629 (js2-deflocal js2-ts-hit-eof nil
630 "Token stream buffer-local variable.")
631
632 ;; FIXME: Unused.
633 (js2-deflocal js2-ts-line-start 0
634 "Token stream buffer-local variable.")
635
636 (js2-deflocal js2-ts-lineno 1
637 "Token stream buffer-local variable.")
638
639 ;; FIXME: Unused.
640 (js2-deflocal js2-ts-line-end-char -1
641 "Token stream buffer-local variable.")
642
643 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
644 "Token stream buffer-local variable.
645 Current scan position.")
646
647 ;; FIXME: Unused.
648 (js2-deflocal js2-ts-is-xml-attribute nil
649 "Token stream buffer-local variable.")
650
651 (js2-deflocal js2-ts-xml-is-tag-content nil
652 "Token stream buffer-local variable.")
653
654 (js2-deflocal js2-ts-xml-open-tags-count 0
655 "Token stream buffer-local variable.")
656
657 (js2-deflocal js2-ts-string-buffer nil
658 "Token stream buffer-local variable.
659 List of chars built up while scanning various tokens.")
660
661 (cl-defstruct (js2-token
662 (:constructor nil)
663 (:constructor make-js2-token (beg)))
664 "Value returned from the token stream."
665 (type js2-EOF)
666 (beg 1)
667 (end -1)
668 (string "")
669 number
670 number-base
671 regexp-flags
672 comment-type
673 follows-eol-p)
674
675 ;; Have to call `js2-init-scanner' to initialize the values.
676 (js2-deflocal js2-ti-tokens nil)
677 (js2-deflocal js2-ti-tokens-cursor nil)
678 (js2-deflocal js2-ti-lookahead nil)
679
680 (cl-defstruct (js2-ts-state
681 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
682 (cursor js2-ts-cursor)
683 (tokens (copy-sequence js2-ti-tokens))
684 (tokens-cursor js2-ti-tokens-cursor)
685 (lookahead js2-ti-lookahead))))
686 lineno
687 cursor
688 tokens
689 tokens-cursor
690 lookahead)
691
692 ;;; Parser variables
693
694 (js2-deflocal js2-parsed-errors nil
695 "List of errors produced during scanning/parsing.")
696
697 (js2-deflocal js2-parsed-warnings nil
698 "List of warnings produced during scanning/parsing.")
699
700 (js2-deflocal js2-recover-from-parse-errors t
701 "Non-nil to continue parsing after a syntax error.
702
703 In recovery mode, the AST will be built in full, and any error
704 nodes will be flagged with appropriate error information. If
705 this flag is nil, a syntax error will result in an error being
706 signaled.
707
708 The variable is automatically buffer-local, because different
709 modes that use the parser will need different settings.")
710
711 (js2-deflocal js2-parse-hook nil
712 "List of callbacks for receiving parsing progress.")
713
714 (defvar js2-parse-finished-hook nil
715 "List of callbacks to notify when parsing finishes.
716 Not called if parsing was interrupted.")
717
718 (js2-deflocal js2-is-eval-code nil
719 "True if we're evaluating code in a string.
720 If non-nil, the tokenizer will record the token text, and the AST nodes
721 will record their source text. Off by default for IDE modes, since the
722 text is available in the buffer.")
723
724 (defvar js2-parse-ide-mode t
725 "Non-nil if the parser is being used for `js2-mode'.
726 If non-nil, the parser will set text properties for fontification
727 and the syntax table. The value should be nil when using the
728 parser as a frontend to an interpreter or byte compiler.")
729
730 ;;; Parser instance variables (buffer-local vars for js2-parse)
731
732 (defconst js2-ti-after-eol (lsh 1 16)
733 "Flag: first token of the source line.")
734
735 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
736
737 (js2-deflocal js2-compiler-generate-debug-info t)
738 (js2-deflocal js2-compiler-use-dynamic-scope nil)
739 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
740 (js2-deflocal js2-compiler-xml-available t)
741 (js2-deflocal js2-compiler-optimization-level 0)
742 (js2-deflocal js2-compiler-generating-source t)
743 (js2-deflocal js2-compiler-strict-mode nil)
744 (js2-deflocal js2-compiler-report-warning-as-error nil)
745 (js2-deflocal js2-compiler-generate-observer-count nil)
746 (js2-deflocal js2-compiler-activation-names nil)
747
748 ;; SKIP: sourceURI
749
750 ;; There's a compileFunction method in Context.java - may need it.
751 (js2-deflocal js2-called-by-compile-function nil
752 "True if `js2-parse' was called by `js2-compile-function'.
753 Will only be used when we finish implementing the interpreter.")
754
755 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
756
757 ;; SKIP: node factory - we're going to just call functions directly,
758 ;; and eventually go to a unified AST format.
759
760 (js2-deflocal js2-nesting-of-function 0)
761
762 (js2-deflocal js2-recorded-identifiers nil
763 "Tracks identifiers found during parsing.")
764
765 (js2-deflocal js2-is-in-destructuring nil
766 "True while parsing destructuring expression.")
767
768 (js2-deflocal js2-in-use-strict-directive nil
769 "True while inside a script or function under strict mode.")
770
771 (defcustom js2-global-externs nil
772 "A list of any extern names you'd like to consider always declared.
773 This list is global and is used by all `js2-mode' files.
774 You can create buffer-local externs list using `js2-additional-externs'.
775
776 There is also a buffer-local variable `js2-default-externs',
777 which is initialized by default to include the Ecma-262 externs
778 and the standard browser externs. The three lists are all
779 checked during highlighting."
780 :type 'list
781 :group 'js2-mode)
782
783 (js2-deflocal js2-default-externs nil
784 "Default external declarations.
785
786 These are currently only used for highlighting undeclared variables,
787 which only worries about top-level (unqualified) references.
788 As js2-mode's processing improves, we will flesh out this list.
789
790 The initial value is set to `js2-ecma-262-externs', unless some
791 of the `js2-include-?-externs' variables are set to t, in which
792 case the browser, Rhino and/or Node.js externs are also included.
793
794 See `js2-additional-externs' for more information.")
795
796 (defcustom js2-include-browser-externs t
797 "Non-nil to include browser externs in the master externs list.
798 If you work on JavaScript files that are not intended for browsers,
799 such as Mozilla Rhino server-side JavaScript, set this to nil.
800 See `js2-additional-externs' for more information about externs."
801 :type 'boolean
802 :group 'js2-mode)
803
804 (defcustom js2-include-rhino-externs nil
805 "Non-nil to include Mozilla Rhino externs in the master externs list.
806 See `js2-additional-externs' for more information about externs."
807 :type 'boolean
808 :group 'js2-mode)
809
810 (defcustom js2-include-node-externs nil
811 "Non-nil to include Node.js externs in the master externs list.
812 See `js2-additional-externs' for more information about externs."
813 :type 'boolean
814 :group 'js2-mode)
815
816 (js2-deflocal js2-additional-externs nil
817 "A buffer-local list of additional external declarations.
818 It is used to decide whether variables are considered undeclared
819 for purposes of highlighting.
820
821 Each entry is a Lisp string. The string should be the fully qualified
822 name of an external entity. All externs should be added to this list,
823 so that as js2-mode's processing improves it can take advantage of them.
824
825 You may want to declare your externs in three ways.
826 First, you can add externs that are valid for all your JavaScript files.
827 You should probably do this by adding them to `js2-global-externs', which
828 is a global list used for all js2-mode files.
829
830 Next, you can add a function to `js2-init-hook' that adds additional
831 externs appropriate for the specific file, perhaps based on its path.
832 These should go in `js2-additional-externs', which is buffer-local.
833
834 Third, you can use JSLint's global declaration, as long as
835 `js2-include-jslint-globals' is non-nil, which see.
836
837 Finally, you can add a function to `js2-post-parse-callbacks',
838 which is called after parsing completes, and `js2-mode-ast' is bound to
839 the root of the parse tree. At this stage you can set up an AST
840 node visitor using `js2-visit-ast' and examine the parse tree
841 for specific import patterns that may imply the existence of
842 other externs, possibly tied to your build system. These should also
843 be added to `js2-additional-externs'.
844
845 Your post-parse callback may of course also use the simpler and
846 faster (but perhaps less robust) approach of simply scanning the
847 buffer text for your imports, using regular expressions.")
848
849 ;; SKIP: decompiler
850 ;; SKIP: encoded-source
851
852 ;;; The following variables are per-function and should be saved/restored
853 ;;; during function parsing...
854
855 (js2-deflocal js2-current-script-or-fn nil)
856 (js2-deflocal js2-current-scope nil)
857 (js2-deflocal js2-nesting-of-with 0)
858 (js2-deflocal js2-label-set nil
859 "An alist mapping label names to nodes.")
860
861 (js2-deflocal js2-loop-set nil)
862 (js2-deflocal js2-loop-and-switch-set nil)
863 (js2-deflocal js2-has-return-value nil)
864 (js2-deflocal js2-end-flags 0)
865
866 ;;; ...end of per function variables
867
868 ;; These flags enumerate the possible ways a statement/function can
869 ;; terminate. These flags are used by endCheck() and by the Parser to
870 ;; detect inconsistent return usage.
871 ;;
872 ;; END_UNREACHED is reserved for code paths that are assumed to always be
873 ;; able to execute (example: throw, continue)
874 ;;
875 ;; END_DROPS_OFF indicates if the statement can transfer control to the
876 ;; next one. Statement such as return dont. A compound statement may have
877 ;; some branch that drops off control to the next statement.
878 ;;
879 ;; END_RETURNS indicates that the statement can return (without arguments)
880 ;; END_RETURNS_VALUE indicates that the statement can return a value.
881 ;;
882 ;; A compound statement such as
883 ;; if (condition) {
884 ;; return value;
885 ;; }
886 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
887
888 (defconst js2-end-unreached #x0)
889 (defconst js2-end-drops-off #x1)
890 (defconst js2-end-returns #x2)
891 (defconst js2-end-returns-value #x4)
892
893 ;; Rhino awkwardly passes a statementLabel parameter to the
894 ;; statementHelper() function, the main statement parser, which
895 ;; is then used by quite a few of the sub-parsers. We just make
896 ;; it a buffer-local variable and make sure it's cleaned up properly.
897 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
898
899 ;; Similarly, Rhino passes an inForInit boolean through about half
900 ;; the expression parsers. We use a dynamically-scoped variable,
901 ;; which makes it easier to funcall the parsers individually without
902 ;; worrying about whether they take the parameter or not.
903 (js2-deflocal js2-in-for-init nil)
904 (js2-deflocal js2-temp-name-counter 0)
905 (js2-deflocal js2-parse-stmt-count 0)
906
907 (defsubst js2-get-next-temp-name ()
908 (format "$%d" (cl-incf js2-temp-name-counter)))
909
910 (defvar js2-parse-interruptable-p t
911 "Set this to nil to force parse to continue until finished.
912 This will mostly be useful for interpreters.")
913
914 (defvar js2-statements-per-pause 50
915 "Pause after this many statements to check for user input.
916 If user input is pending, stop the parse and discard the tree.
917 This makes for a smoother user experience for large files.
918 You may have to wait a second or two before the highlighting
919 and error-reporting appear, but you can always type ahead if
920 you wish. This appears to be more or less how Eclipse, IntelliJ
921 and other editors work.")
922
923 (js2-deflocal js2-record-comments t
924 "Instructs the scanner to record comments in `js2-scanned-comments'.")
925
926 (js2-deflocal js2-scanned-comments nil
927 "List of all comments from the current parse.")
928
929 (defcustom js2-mode-indent-inhibit-undo nil
930 "Non-nil to disable collection of Undo information when indenting lines.
931 Some users have requested this behavior. It's nil by default because
932 other Emacs modes don't work this way."
933 :type 'boolean
934 :group 'js2-mode)
935
936 (defcustom js2-mode-indent-ignore-first-tab nil
937 "If non-nil, ignore first TAB keypress if we look indented properly.
938 It's fairly common for users to navigate to an already-indented line
939 and press TAB for reassurance that it's been indented. For this class
940 of users, we want the first TAB press on a line to be ignored if the
941 line is already indented to one of the precomputed alternatives.
942
943 This behavior is only partly implemented. If you TAB-indent a line,
944 navigate to another line, and then navigate back, it fails to clear
945 the last-indented variable, so it thinks you've already hit TAB once,
946 and performs the indent. A full solution would involve getting on the
947 point-motion hooks for the entire buffer. If we come across another
948 use cases that requires watching point motion, I'll consider doing it.
949
950 If you set this variable to nil, then the TAB key will always change
951 the indentation of the current line, if more than one alternative
952 indentation spot exists."
953 :type 'boolean
954 :group 'js2-mode)
955
956 (defvar js2-indent-hook nil
957 "A hook for user-defined indentation rules.
958
959 Functions on this hook should expect two arguments: (LIST INDEX)
960 The LIST argument is the list of computed indentation points for
961 the current line. INDEX is the list index of the indentation point
962 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
963 indent function is not going to change the current line indentation.
964
965 If a hook function on this list returns a non-nil value, then
966 `js2-bounce-indent' assumes the hook function has performed its own
967 indentation, and will do nothing. If all hook functions on the list
968 return nil, then `js2-bounce-indent' will use its computed indentation
969 and reindent the line.
970
971 When hook functions on this hook list are called, the variable
972 `js2-mode-ast' may or may not be set, depending on whether the
973 parse tree is available. If the variable is nil, you can pass a
974 callback to `js2-mode-wait-for-parse', and your callback will be
975 called after the new parse tree is built. This can take some time
976 in large files.")
977
978 (defface js2-warning
979 `((((class color) (background light))
980 (:underline "orange"))
981 (((class color) (background dark))
982 (:underline "orange"))
983 (t (:underline t)))
984 "Face for JavaScript warnings."
985 :group 'js2-mode)
986
987 (defface js2-error
988 `((((class color) (background light))
989 (:foreground "red"))
990 (((class color) (background dark))
991 (:foreground "red"))
992 (t (:foreground "red")))
993 "Face for JavaScript errors."
994 :group 'js2-mode)
995
996 (defface js2-jsdoc-tag
997 '((t :foreground "SlateGray"))
998 "Face used to highlight @whatever tags in jsdoc comments."
999 :group 'js2-mode)
1000
1001 (defface js2-jsdoc-type
1002 '((t :foreground "SteelBlue"))
1003 "Face used to highlight {FooBar} types in jsdoc comments."
1004 :group 'js2-mode)
1005
1006 (defface js2-jsdoc-value
1007 '((t :foreground "PeachPuff3"))
1008 "Face used to highlight tag values in jsdoc comments."
1009 :group 'js2-mode)
1010
1011 (defface js2-function-param
1012 '((t :foreground "SeaGreen"))
1013 "Face used to highlight function parameters in javascript."
1014 :group 'js2-mode)
1015
1016 (defface js2-function-call
1017 '((t :inherit default))
1018 "Face used to highlight function name in calls."
1019 :group 'js2-mode)
1020
1021 (defface js2-object-property
1022 '((t :inherit default))
1023 "Face used to highlight named property in object literal."
1024 :group 'js2-mode)
1025
1026 (defface js2-instance-member
1027 '((t :foreground "DarkOrchid"))
1028 "Face used to highlight instance variables in javascript.
1029 Not currently used."
1030 :group 'js2-mode)
1031
1032 (defface js2-private-member
1033 '((t :foreground "PeachPuff3"))
1034 "Face used to highlight calls to private methods in javascript.
1035 Not currently used."
1036 :group 'js2-mode)
1037
1038 (defface js2-private-function-call
1039 '((t :foreground "goldenrod"))
1040 "Face used to highlight calls to private functions in javascript.
1041 Not currently used."
1042 :group 'js2-mode)
1043
1044 (defface js2-jsdoc-html-tag-name
1045 '((((class color) (min-colors 88) (background light))
1046 (:foreground "rosybrown"))
1047 (((class color) (min-colors 8) (background dark))
1048 (:foreground "yellow"))
1049 (((class color) (min-colors 8) (background light))
1050 (:foreground "magenta")))
1051 "Face used to highlight jsdoc html tag names"
1052 :group 'js2-mode)
1053
1054 (defface js2-jsdoc-html-tag-delimiter
1055 '((((class color) (min-colors 88) (background light))
1056 (:foreground "dark khaki"))
1057 (((class color) (min-colors 8) (background dark))
1058 (:foreground "green"))
1059 (((class color) (min-colors 8) (background light))
1060 (:foreground "green")))
1061 "Face used to highlight brackets in jsdoc html tags."
1062 :group 'js2-mode)
1063
1064 (defface js2-external-variable
1065 '((t :foreground "orange"))
1066 "Face used to highlight undeclared variable identifiers.")
1067
1068 (defcustom js2-init-hook nil
1069 "List of functions to be called after `js2-mode' or
1070 `js2-minor-mode' has initialized all variables, before parsing
1071 the buffer for the first time."
1072 :type 'hook
1073 :group 'js2-mode
1074 :version "20130608")
1075
1076 (defcustom js2-post-parse-callbacks nil
1077 "List of callback functions invoked after parsing finishes.
1078 Currently, the main use for this function is to add synthetic
1079 declarations to `js2-recorded-identifiers', which see."
1080 :type 'hook
1081 :group 'js2-mode)
1082
1083 (defcustom js2-build-imenu-callbacks nil
1084 "List of functions called during Imenu index generation.
1085 It's a good place to add additional entries to it, using
1086 `js2-record-imenu-entry'."
1087 :type 'hook
1088 :group 'js2-mode)
1089
1090 (defcustom js2-highlight-external-variables t
1091 "Non-nil to highlight undeclared variable identifiers.
1092 An undeclared variable is any variable not declared with var or let
1093 in the current scope or any lexically enclosing scope. If you use
1094 such a variable, then you are either expecting it to originate from
1095 another file, or you've got a potential bug."
1096 :type 'boolean
1097 :group 'js2-mode)
1098
1099 (defcustom js2-warn-about-unused-function-arguments nil
1100 "Non-nil to treat function arguments like declared-but-unused variables."
1101 :type 'booleanp
1102 :group 'js2-mode)
1103
1104 (defcustom js2-include-jslint-globals t
1105 "Non-nil to include the identifiers from JSLint global
1106 declaration (see http://www.jslint.com/lint.html#global) in the
1107 buffer-local externs list. See `js2-additional-externs' for more
1108 information."
1109 :type 'boolean
1110 :group 'js2-mode)
1111
1112 (defvar js2-mode-map
1113 (let ((map (make-sparse-keymap)))
1114 (define-key map [mouse-1] #'js2-mode-show-node)
1115 (define-key map (kbd "M-j") #'js2-line-break)
1116 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1117 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1118 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1119 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1120 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1121 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1122 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1123 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1124 (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
1125
1126 (define-key map [menu-bar javascript]
1127 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1128
1129 (define-key map [menu-bar javascript customize-js2-mode]
1130 '(menu-item "Customize js2-mode" js2-mode-customize
1131 :help "Customize the behavior of this mode"))
1132
1133 (define-key map [menu-bar javascript js2-force-refresh]
1134 '(menu-item "Force buffer refresh" js2-mode-reset
1135 :help "Re-parse the buffer from scratch"))
1136
1137 (define-key map [menu-bar javascript separator-2]
1138 '("--"))
1139
1140 (define-key map [menu-bar javascript next-error]
1141 '(menu-item "Next warning or error" next-error
1142 :enabled (and js2-mode-ast
1143 (or (js2-ast-root-errors js2-mode-ast)
1144 (js2-ast-root-warnings js2-mode-ast)))
1145 :help "Move to next warning or error"))
1146
1147 (define-key map [menu-bar javascript display-errors]
1148 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1149 :visible (not js2-mode-show-parse-errors)
1150 :help "Turn on display of warnings and errors"))
1151
1152 (define-key map [menu-bar javascript hide-errors]
1153 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1154 :visible js2-mode-show-parse-errors
1155 :help "Turn off display of warnings and errors"))
1156
1157 (define-key map [menu-bar javascript separator-1]
1158 '("--"))
1159
1160 (define-key map [menu-bar javascript js2-toggle-function]
1161 '(menu-item "Show/collapse element" js2-mode-toggle-element
1162 :help "Hide or show function body or comment"))
1163
1164 (define-key map [menu-bar javascript show-comments]
1165 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1166 :visible js2-mode-comments-hidden
1167 :help "Expand all hidden block comments"))
1168
1169 (define-key map [menu-bar javascript hide-comments]
1170 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1171 :visible (not js2-mode-comments-hidden)
1172 :help "Show block comments as /*...*/"))
1173
1174 (define-key map [menu-bar javascript show-all-functions]
1175 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1176 :visible js2-mode-functions-hidden
1177 :help "Expand all hidden function bodies"))
1178
1179 (define-key map [menu-bar javascript hide-all-functions]
1180 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1181 :visible (not js2-mode-functions-hidden)
1182 :help "Show {...} for all top-level function bodies"))
1183
1184 map)
1185 "Keymap used in `js2-mode' buffers.")
1186
1187 (defcustom js2-bounce-indent-p nil
1188 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1189 They will augment the default indent-line behavior with cycling
1190 among several computed alternatives. See the function
1191 `js2-bounce-indent' for details. The above commands will be
1192 bound to TAB and backtab."
1193 :type 'boolean
1194 :group 'js2-mode
1195 :set (lambda (sym value)
1196 (set-default sym value)
1197 (let ((map js2-mode-map))
1198 (if (not value)
1199 (progn
1200 (define-key map "\t" nil)
1201 (define-key map (kbd "<backtab>") nil))
1202 (define-key map "\t" #'js2-indent-bounce)
1203 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1204
1205 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1206
1207 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1208 "Matches a //-comment line. Must be first non-whitespace on line.
1209 First match-group is the leading whitespace.")
1210
1211 (defvar js2-mode-hook nil)
1212
1213 (js2-deflocal js2-mode-ast nil "Private variable.")
1214 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1215 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1216 (js2-deflocal js2-mode-parsing nil "Private variable.")
1217 (js2-deflocal js2-mode-node-overlay nil)
1218
1219 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1220 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1221
1222 (js2-deflocal js2-mode-fontifications nil "Private variable")
1223 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1224 (js2-deflocal js2-imenu-recorder nil "Private variable")
1225 (js2-deflocal js2-imenu-function-map nil "Private variable")
1226
1227 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1228 "Non-nil to emit status messages during parsing.")
1229
1230 (defvar js2-mode-functions-hidden nil "Private variable.")
1231 (defvar js2-mode-comments-hidden nil "Private variable.")
1232
1233 (defvar js2-mode-syntax-table
1234 (let ((table (make-syntax-table)))
1235 (c-populate-syntax-table table)
1236 (modify-syntax-entry ?` "\"" table)
1237 table)
1238 "Syntax table used in `js2-mode' buffers.")
1239
1240 (defvar js2-mode-abbrev-table nil
1241 "Abbrev table in use in `js2-mode' buffers.")
1242 (define-abbrev-table 'js2-mode-abbrev-table ())
1243
1244 (defvar js2-mode-pending-parse-callbacks nil
1245 "List of functions waiting to be notified that parse is finished.")
1246
1247 (defvar js2-mode-last-indented-line -1)
1248
1249 ;;; Localizable error and warning messages
1250
1251 ;; Messages are copied from Rhino's Messages.properties.
1252 ;; Many of the Java-specific messages have been elided.
1253 ;; Add any js2-specific ones at the end, so we can keep
1254 ;; this file synced with changes to Rhino's.
1255
1256 (defvar js2-message-table
1257 (make-hash-table :test 'equal :size 250)
1258 "Contains localized messages for `js2-mode'.")
1259
1260 ;; TODO(stevey): construct this table at compile-time.
1261 (defmacro js2-msg (key &rest strings)
1262 `(puthash ,key (concat ,@strings)
1263 js2-message-table))
1264
1265 (defun js2-get-msg (msg-key)
1266 "Look up a localized message.
1267 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1268 the correct number of ARGS must be provided."
1269 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1270 (args (if (listp msg-key) (cdr msg-key)))
1271 (msg (gethash key js2-message-table)))
1272 (if msg
1273 (apply #'format msg args)
1274 key))) ; default to showing the key
1275
1276 (js2-msg "msg.dup.parms"
1277 "Duplicate parameter name '%s'.")
1278
1279 (js2-msg "msg.too.big.jump"
1280 "Program too complex: jump offset too big.")
1281
1282 (js2-msg "msg.too.big.index"
1283 "Program too complex: internal index exceeds 64K limit.")
1284
1285 (js2-msg "msg.while.compiling.fn"
1286 "Encountered code generation error while compiling function '%s': %s")
1287
1288 (js2-msg "msg.while.compiling.script"
1289 "Encountered code generation error while compiling script: %s")
1290
1291 ;; Context
1292 (js2-msg "msg.ctor.not.found"
1293 "Constructor for '%s' not found.")
1294
1295 (js2-msg "msg.not.ctor"
1296 "'%s' is not a constructor.")
1297
1298 ;; FunctionObject
1299 (js2-msg "msg.varargs.ctor"
1300 "Method or constructor '%s' must be static "
1301 "with the signature (Context cx, Object[] args, "
1302 "Function ctorObj, boolean inNewExpr) "
1303 "to define a variable arguments constructor.")
1304
1305 (js2-msg "msg.varargs.fun"
1306 "Method '%s' must be static with the signature "
1307 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1308 "to define a variable arguments function.")
1309
1310 (js2-msg "msg.incompat.call"
1311 "Method '%s' called on incompatible object.")
1312
1313 (js2-msg "msg.bad.parms"
1314 "Unsupported parameter type '%s' in method '%s'.")
1315
1316 (js2-msg "msg.bad.method.return"
1317 "Unsupported return type '%s' in method '%s'.")
1318
1319 (js2-msg "msg.bad.ctor.return"
1320 "Construction of objects of type '%s' is not supported.")
1321
1322 (js2-msg "msg.no.overload"
1323 "Method '%s' occurs multiple times in class '%s'.")
1324
1325 (js2-msg "msg.method.not.found"
1326 "Method '%s' not found in '%s'.")
1327
1328 ;; IRFactory
1329
1330 (js2-msg "msg.bad.for.in.lhs"
1331 "Invalid left-hand side of for..in loop.")
1332
1333 (js2-msg "msg.mult.index"
1334 "Only one variable allowed in for..in loop.")
1335
1336 (js2-msg "msg.bad.for.in.destruct"
1337 "Left hand side of for..in loop must be an array of "
1338 "length 2 to accept key/value pair.")
1339
1340 (js2-msg "msg.cant.convert"
1341 "Can't convert to type '%s'.")
1342
1343 (js2-msg "msg.bad.assign.left"
1344 "Invalid assignment left-hand side.")
1345
1346 (js2-msg "msg.bad.decr"
1347 "Invalid decrement operand.")
1348
1349 (js2-msg "msg.bad.incr"
1350 "Invalid increment operand.")
1351
1352 (js2-msg "msg.bad.yield"
1353 "yield must be in a function.")
1354
1355 (js2-msg "msg.yield.parenthesized"
1356 "yield expression must be parenthesized.")
1357
1358 ;; NativeGlobal
1359 (js2-msg "msg.cant.call.indirect"
1360 "Function '%s' must be called directly, and not by way of a "
1361 "function of another name.")
1362
1363 (js2-msg "msg.eval.nonstring"
1364 "Calling eval() with anything other than a primitive "
1365 "string value will simply return the value. "
1366 "Is this what you intended?")
1367
1368 (js2-msg "msg.eval.nonstring.strict"
1369 "Calling eval() with anything other than a primitive "
1370 "string value is not allowed in strict mode.")
1371
1372 (js2-msg "msg.bad.destruct.op"
1373 "Invalid destructuring assignment operator")
1374
1375 ;; NativeCall
1376 (js2-msg "msg.only.from.new"
1377 "'%s' may only be invoked from a `new' expression.")
1378
1379 (js2-msg "msg.deprec.ctor"
1380 "The '%s' constructor is deprecated.")
1381
1382 ;; NativeFunction
1383 (js2-msg "msg.no.function.ref.found"
1384 "no source found to decompile function reference %s")
1385
1386 (js2-msg "msg.arg.isnt.array"
1387 "second argument to Function.prototype.apply must be an array")
1388
1389 ;; NativeGlobal
1390 (js2-msg "msg.bad.esc.mask"
1391 "invalid string escape mask")
1392
1393 ;; NativeRegExp
1394 (js2-msg "msg.bad.quant"
1395 "Invalid quantifier %s")
1396
1397 (js2-msg "msg.overlarge.backref"
1398 "Overly large back reference %s")
1399
1400 (js2-msg "msg.overlarge.min"
1401 "Overly large minimum %s")
1402
1403 (js2-msg "msg.overlarge.max"
1404 "Overly large maximum %s")
1405
1406 (js2-msg "msg.zero.quant"
1407 "Zero quantifier %s")
1408
1409 (js2-msg "msg.max.lt.min"
1410 "Maximum %s less than minimum")
1411
1412 (js2-msg "msg.unterm.quant"
1413 "Unterminated quantifier %s")
1414
1415 (js2-msg "msg.unterm.paren"
1416 "Unterminated parenthetical %s")
1417
1418 (js2-msg "msg.unterm.class"
1419 "Unterminated character class %s")
1420
1421 (js2-msg "msg.bad.range"
1422 "Invalid range in character class.")
1423
1424 (js2-msg "msg.trail.backslash"
1425 "Trailing \\ in regular expression.")
1426
1427 (js2-msg "msg.re.unmatched.right.paren"
1428 "unmatched ) in regular expression.")
1429
1430 (js2-msg "msg.no.regexp"
1431 "Regular expressions are not available.")
1432
1433 (js2-msg "msg.bad.backref"
1434 "back-reference exceeds number of capturing parentheses.")
1435
1436 (js2-msg "msg.bad.regexp.compile"
1437 "Only one argument may be specified if the first "
1438 "argument to RegExp.prototype.compile is a RegExp object.")
1439
1440 ;; Parser
1441 (js2-msg "msg.got.syntax.errors"
1442 "Compilation produced %s syntax errors.")
1443
1444 (js2-msg "msg.var.redecl"
1445 "TypeError: redeclaration of var %s.")
1446
1447 (js2-msg "msg.const.redecl"
1448 "TypeError: redeclaration of const %s.")
1449
1450 (js2-msg "msg.let.redecl"
1451 "TypeError: redeclaration of variable %s.")
1452
1453 (js2-msg "msg.parm.redecl"
1454 "TypeError: redeclaration of formal parameter %s.")
1455
1456 (js2-msg "msg.fn.redecl"
1457 "TypeError: redeclaration of function %s.")
1458
1459 (js2-msg "msg.let.decl.not.in.block"
1460 "SyntaxError: let declaration not directly within block")
1461
1462 (js2-msg "msg.mod.import.decl.at.top.level"
1463 "SyntaxError: import declarations may only appear at the top level")
1464
1465 (js2-msg "msg.mod.as.after.reserved.word"
1466 "SyntaxError: missing keyword 'as' after reserved word %s")
1467
1468 (js2-msg "msg.mod.rc.after.import.spec.list"
1469 "SyntaxError: missing '}' after module specifier list")
1470
1471 (js2-msg "msg.mod.from.after.import.spec.set"
1472 "SyntaxError: missing keyword 'from' after import specifier set")
1473
1474 (js2-msg "msg.mod.declaration.after.import"
1475 "SyntaxError: missing declaration after 'import' keyword")
1476
1477 (js2-msg "msg.mod.spec.after.from"
1478 "SyntaxError: missing module specifier after 'from' keyword")
1479
1480 (js2-msg "msg.mod.export.decl.at.top.level"
1481 "SyntaxError: export declarations may only appear at top level")
1482
1483 (js2-msg "msg.mod.rc.after.export.spec.list"
1484 "SyntaxError: missing '}' after export specifier list")
1485
1486 ;; NodeTransformer
1487 (js2-msg "msg.dup.label"
1488 "duplicated label")
1489
1490 (js2-msg "msg.undef.label"
1491 "undefined label")
1492
1493 (js2-msg "msg.bad.break"
1494 "unlabelled break must be inside loop or switch")
1495
1496 (js2-msg "msg.continue.outside"
1497 "continue must be inside loop")
1498
1499 (js2-msg "msg.continue.nonloop"
1500 "continue can only use labels of iteration statements")
1501
1502 (js2-msg "msg.bad.throw.eol"
1503 "Line terminator is not allowed between the throw "
1504 "keyword and throw expression.")
1505
1506 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1507 "function statement requires a name")
1508
1509 (js2-msg "msg.no.paren.parms"
1510 "missing ( before function parameters.")
1511
1512 (js2-msg "msg.no.parm"
1513 "missing formal parameter")
1514
1515 (js2-msg "msg.no.paren.after.parms"
1516 "missing ) after formal parameters")
1517
1518 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1519 "parameter without default follows parameter with default")
1520
1521 (js2-msg "msg.param.after.rest" ; added by js2-mode
1522 "parameter after rest parameter")
1523
1524 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1525 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1526
1527 (js2-msg "msg.no.brace.body"
1528 "missing '{' before function body")
1529
1530 (js2-msg "msg.no.brace.after.body"
1531 "missing } after function body")
1532
1533 (js2-msg "msg.no.paren.cond"
1534 "missing ( before condition")
1535
1536 (js2-msg "msg.no.paren.after.cond"
1537 "missing ) after condition")
1538
1539 (js2-msg "msg.no.semi.stmt"
1540 "missing ; before statement")
1541
1542 (js2-msg "msg.missing.semi"
1543 "missing ; after statement")
1544
1545 (js2-msg "msg.no.name.after.dot"
1546 "missing name after . operator")
1547
1548 (js2-msg "msg.no.name.after.coloncolon"
1549 "missing name after :: operator")
1550
1551 (js2-msg "msg.no.name.after.dotdot"
1552 "missing name after .. operator")
1553
1554 (js2-msg "msg.no.name.after.xmlAttr"
1555 "missing name after .@")
1556
1557 (js2-msg "msg.no.bracket.index"
1558 "missing ] in index expression")
1559
1560 (js2-msg "msg.no.paren.switch"
1561 "missing ( before switch expression")
1562
1563 (js2-msg "msg.no.paren.after.switch"
1564 "missing ) after switch expression")
1565
1566 (js2-msg "msg.no.brace.switch"
1567 "missing '{' before switch body")
1568
1569 (js2-msg "msg.bad.switch"
1570 "invalid switch statement")
1571
1572 (js2-msg "msg.no.colon.case"
1573 "missing : after case expression")
1574
1575 (js2-msg "msg.double.switch.default"
1576 "double default label in the switch statement")
1577
1578 (js2-msg "msg.no.while.do"
1579 "missing while after do-loop body")
1580
1581 (js2-msg "msg.no.paren.for"
1582 "missing ( after for")
1583
1584 (js2-msg "msg.no.semi.for"
1585 "missing ; after for-loop initializer")
1586
1587 (js2-msg "msg.no.semi.for.cond"
1588 "missing ; after for-loop condition")
1589
1590 (js2-msg "msg.in.after.for.name"
1591 "missing in or of after for")
1592
1593 (js2-msg "msg.no.paren.for.ctrl"
1594 "missing ) after for-loop control")
1595
1596 (js2-msg "msg.no.paren.with"
1597 "missing ( before with-statement object")
1598
1599 (js2-msg "msg.no.paren.after.with"
1600 "missing ) after with-statement object")
1601
1602 (js2-msg "msg.no.with.strict"
1603 "with statements not allowed in strict mode")
1604
1605 (js2-msg "msg.no.paren.after.let"
1606 "missing ( after let")
1607
1608 (js2-msg "msg.no.paren.let"
1609 "missing ) after variable list")
1610
1611 (js2-msg "msg.no.curly.let"
1612 "missing } after let statement")
1613
1614 (js2-msg "msg.bad.return"
1615 "invalid return")
1616
1617 (js2-msg "msg.no.brace.block"
1618 "missing } in compound statement")
1619
1620 (js2-msg "msg.bad.label"
1621 "invalid label")
1622
1623 (js2-msg "msg.bad.var"
1624 "missing variable name")
1625
1626 (js2-msg "msg.bad.var.init"
1627 "invalid variable initialization")
1628
1629 (js2-msg "msg.no.colon.cond"
1630 "missing : in conditional expression")
1631
1632 (js2-msg "msg.no.paren.arg"
1633 "missing ) after argument list")
1634
1635 (js2-msg "msg.no.bracket.arg"
1636 "missing ] after element list")
1637
1638 (js2-msg "msg.bad.prop"
1639 "invalid property id")
1640
1641 (js2-msg "msg.no.colon.prop"
1642 "missing : after property id")
1643
1644 (js2-msg "msg.no.brace.prop"
1645 "missing } after property list")
1646
1647 (js2-msg "msg.no.paren"
1648 "missing ) in parenthetical")
1649
1650 (js2-msg "msg.reserved.id"
1651 "'%s' is a reserved identifier")
1652
1653 (js2-msg "msg.no.paren.catch"
1654 "missing ( before catch-block condition")
1655
1656 (js2-msg "msg.bad.catchcond"
1657 "invalid catch block condition")
1658
1659 (js2-msg "msg.catch.unreachable"
1660 "any catch clauses following an unqualified catch are unreachable")
1661
1662 (js2-msg "msg.no.brace.try"
1663 "missing '{' before try block")
1664
1665 (js2-msg "msg.no.brace.catchblock"
1666 "missing '{' before catch-block body")
1667
1668 (js2-msg "msg.try.no.catchfinally"
1669 "'try' without 'catch' or 'finally'")
1670
1671 (js2-msg "msg.no.return.value"
1672 "function %s does not always return a value")
1673
1674 (js2-msg "msg.anon.no.return.value"
1675 "anonymous function does not always return a value")
1676
1677 (js2-msg "msg.return.inconsistent"
1678 "return statement is inconsistent with previous usage")
1679
1680 (js2-msg "msg.generator.returns"
1681 "TypeError: legacy generator function '%s' returns a value")
1682
1683 (js2-msg "msg.anon.generator.returns"
1684 "TypeError: anonymous legacy generator function returns a value")
1685
1686 (js2-msg "msg.syntax"
1687 "syntax error")
1688
1689 (js2-msg "msg.unexpected.eof"
1690 "Unexpected end of file")
1691
1692 (js2-msg "msg.XML.bad.form"
1693 "illegally formed XML syntax")
1694
1695 (js2-msg "msg.XML.not.available"
1696 "XML runtime not available")
1697
1698 (js2-msg "msg.too.deep.parser.recursion"
1699 "Too deep recursion while parsing")
1700
1701 (js2-msg "msg.no.side.effects"
1702 "Code has no side effects")
1703
1704 (js2-msg "msg.extra.trailing.comma"
1705 "Trailing comma is not supported in some browsers")
1706
1707 (js2-msg "msg.array.trailing.comma"
1708 "Trailing comma yields different behavior across browsers")
1709
1710 (js2-msg "msg.equal.as.assign"
1711 (concat "Test for equality (==) mistyped as assignment (=)?"
1712 " (parenthesize to suppress warning)"))
1713
1714 (js2-msg "msg.var.hides.arg"
1715 "Variable %s hides argument")
1716
1717 (js2-msg "msg.destruct.assign.no.init"
1718 "Missing = in destructuring declaration")
1719
1720 (js2-msg "msg.no.octal.strict"
1721 "Octal numbers prohibited in strict mode.")
1722
1723 (js2-msg "msg.dup.obj.lit.prop.strict"
1724 "Property '%s' already defined in this object literal.")
1725
1726 (js2-msg "msg.dup.param.strict"
1727 "Parameter '%s' already declared in this function.")
1728
1729 (js2-msg "msg.bad.id.strict"
1730 "'%s' is not a valid identifier for this use in strict mode.")
1731
1732 ;; ScriptRuntime
1733 (js2-msg "msg.no.properties"
1734 "%s has no properties.")
1735
1736 (js2-msg "msg.invalid.iterator"
1737 "Invalid iterator value")
1738
1739 (js2-msg "msg.iterator.primitive"
1740 "__iterator__ returned a primitive value")
1741
1742 (js2-msg "msg.assn.create.strict"
1743 "Assignment to undeclared variable %s")
1744
1745 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1746 "Undeclared variable or function '%s'")
1747
1748 (js2-msg "msg.unused.variable" ; added by js2-mode
1749 "Unused variable or function '%s'")
1750
1751 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1752 "Variable '%s' referenced but never initialized")
1753
1754 (js2-msg "msg.ref.undefined.prop"
1755 "Reference to undefined property '%s'")
1756
1757 (js2-msg "msg.prop.not.found"
1758 "Property %s not found.")
1759
1760 (js2-msg "msg.invalid.type"
1761 "Invalid JavaScript value of type %s")
1762
1763 (js2-msg "msg.primitive.expected"
1764 "Primitive type expected (had %s instead)")
1765
1766 (js2-msg "msg.namespace.expected"
1767 "Namespace object expected to left of :: (found %s instead)")
1768
1769 (js2-msg "msg.null.to.object"
1770 "Cannot convert null to an object.")
1771
1772 (js2-msg "msg.undef.to.object"
1773 "Cannot convert undefined to an object.")
1774
1775 (js2-msg "msg.cyclic.value"
1776 "Cyclic %s value not allowed.")
1777
1778 (js2-msg "msg.is.not.defined"
1779 "'%s' is not defined.")
1780
1781 (js2-msg "msg.undef.prop.read"
1782 "Cannot read property '%s' from %s")
1783
1784 (js2-msg "msg.undef.prop.write"
1785 "Cannot set property '%s' of %s to '%s'")
1786
1787 (js2-msg "msg.undef.prop.delete"
1788 "Cannot delete property '%s' of %s")
1789
1790 (js2-msg "msg.undef.method.call"
1791 "Cannot call method '%s' of %s")
1792
1793 (js2-msg "msg.undef.with"
1794 "Cannot apply 'with' to %s")
1795
1796 (js2-msg "msg.isnt.function"
1797 "%s is not a function, it is %s.")
1798
1799 (js2-msg "msg.isnt.function.in"
1800 "Cannot call property %s in object %s. "
1801 "It is not a function, it is '%s'.")
1802
1803 (js2-msg "msg.function.not.found"
1804 "Cannot find function %s.")
1805
1806 (js2-msg "msg.function.not.found.in"
1807 "Cannot find function %s in object %s.")
1808
1809 (js2-msg "msg.isnt.xml.object"
1810 "%s is not an xml object.")
1811
1812 (js2-msg "msg.no.ref.to.get"
1813 "%s is not a reference to read reference value.")
1814
1815 (js2-msg "msg.no.ref.to.set"
1816 "%s is not a reference to set reference value to %s.")
1817
1818 (js2-msg "msg.no.ref.from.function"
1819 "Function %s can not be used as the left-hand "
1820 "side of assignment or as an operand of ++ or -- operator.")
1821
1822 (js2-msg "msg.bad.default.value"
1823 "Object's getDefaultValue() method returned an object.")
1824
1825 (js2-msg "msg.instanceof.not.object"
1826 "Can't use instanceof on a non-object.")
1827
1828 (js2-msg "msg.instanceof.bad.prototype"
1829 "'prototype' property of %s is not an object.")
1830
1831 (js2-msg "msg.bad.radix"
1832 "illegal radix %s.")
1833
1834 ;; ScriptableObject
1835 (js2-msg "msg.default.value"
1836 "Cannot find default value for object.")
1837
1838 (js2-msg "msg.zero.arg.ctor"
1839 "Cannot load class '%s' which has no zero-parameter constructor.")
1840
1841 (js2-msg "msg.ctor.multiple.parms"
1842 "Can't define constructor or class %s since more than "
1843 "one constructor has multiple parameters.")
1844
1845 (js2-msg "msg.extend.scriptable"
1846 "%s must extend ScriptableObject in order to define property %s.")
1847
1848 (js2-msg "msg.bad.getter.parms"
1849 "In order to define a property, getter %s must have zero "
1850 "parameters or a single ScriptableObject parameter.")
1851
1852 (js2-msg "msg.obj.getter.parms"
1853 "Expected static or delegated getter %s to take "
1854 "a ScriptableObject parameter.")
1855
1856 (js2-msg "msg.getter.static"
1857 "Getter and setter must both be static or neither be static.")
1858
1859 (js2-msg "msg.setter.return"
1860 "Setter must have void return type: %s")
1861
1862 (js2-msg "msg.setter2.parms"
1863 "Two-parameter setter must take a ScriptableObject as "
1864 "its first parameter.")
1865
1866 (js2-msg "msg.setter1.parms"
1867 "Expected single parameter setter for %s")
1868
1869 (js2-msg "msg.setter2.expected"
1870 "Expected static or delegated setter %s to take two parameters.")
1871
1872 (js2-msg "msg.setter.parms"
1873 "Expected either one or two parameters for setter.")
1874
1875 (js2-msg "msg.setter.bad.type"
1876 "Unsupported parameter type '%s' in setter '%s'.")
1877
1878 (js2-msg "msg.add.sealed"
1879 "Cannot add a property to a sealed object: %s.")
1880
1881 (js2-msg "msg.remove.sealed"
1882 "Cannot remove a property from a sealed object: %s.")
1883
1884 (js2-msg "msg.modify.sealed"
1885 "Cannot modify a property of a sealed object: %s.")
1886
1887 (js2-msg "msg.modify.readonly"
1888 "Cannot modify readonly property: %s.")
1889
1890 ;; TokenStream
1891 (js2-msg "msg.missing.exponent"
1892 "missing exponent")
1893
1894 (js2-msg "msg.caught.nfe"
1895 "number format error")
1896
1897 (js2-msg "msg.unterminated.string.lit"
1898 "unterminated string literal")
1899
1900 (js2-msg "msg.unterminated.comment"
1901 "unterminated comment")
1902
1903 (js2-msg "msg.unterminated.re.lit"
1904 "unterminated regular expression literal")
1905
1906 (js2-msg "msg.invalid.re.flag"
1907 "invalid flag after regular expression")
1908
1909 (js2-msg "msg.no.re.input.for"
1910 "no input for %s")
1911
1912 (js2-msg "msg.illegal.character"
1913 "illegal character")
1914
1915 (js2-msg "msg.invalid.escape"
1916 "invalid Unicode escape sequence")
1917
1918 (js2-msg "msg.bad.namespace"
1919 "not a valid default namespace statement. "
1920 "Syntax is: default xml namespace = EXPRESSION;")
1921
1922 ;; TokensStream warnings
1923 (js2-msg "msg.bad.octal.literal"
1924 "illegal octal literal digit %s; "
1925 "interpreting it as a decimal digit")
1926
1927 (js2-msg "msg.missing.hex.digits"
1928 "missing hexadecimal digits after '0x'")
1929
1930 (js2-msg "msg.missing.binary.digits"
1931 "missing binary digits after '0b'")
1932
1933 (js2-msg "msg.missing.octal.digits"
1934 "missing octal digits after '0o'")
1935
1936 (js2-msg "msg.script.is.not.constructor"
1937 "Script objects are not constructors.")
1938
1939 ;; Arrays
1940 (js2-msg "msg.arraylength.bad"
1941 "Inappropriate array length.")
1942
1943 ;; Arrays
1944 (js2-msg "msg.arraylength.too.big"
1945 "Array length %s exceeds supported capacity limit.")
1946
1947 ;; URI
1948 (js2-msg "msg.bad.uri"
1949 "Malformed URI sequence.")
1950
1951 ;; Number
1952 (js2-msg "msg.bad.precision"
1953 "Precision %s out of range.")
1954
1955 ;; NativeGenerator
1956 (js2-msg "msg.send.newborn"
1957 "Attempt to send value to newborn generator")
1958
1959 (js2-msg "msg.already.exec.gen"
1960 "Already executing generator")
1961
1962 (js2-msg "msg.StopIteration.invalid"
1963 "StopIteration may not be changed to an arbitrary object.")
1964
1965 ;; Interpreter
1966 (js2-msg "msg.yield.closing"
1967 "Yield from closing generator")
1968
1969 ;; Classes
1970 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1971 "class statement requires a name")
1972
1973 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1974 "unexpected ',' between class properties")
1975
1976 (js2-msg "msg.unexpected.static" ; added by js2-mode
1977 "unexpected 'static'")
1978
1979 (js2-msg "msg.missing.extends" ; added by js2-mode
1980 "name is required after extends")
1981
1982 (js2-msg "msg.no.brace.class" ; added by js2-mode
1983 "missing '{' before class body")
1984
1985 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1986 "missing ']' after computed property expression")
1987
1988 ;;; Tokens Buffer
1989
1990 (defconst js2-ti-max-lookahead 2)
1991 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1992
1993 (defun js2-new-token (offset)
1994 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1995 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1996 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1997 token))
1998
1999 (defsubst js2-current-token ()
2000 (aref js2-ti-tokens js2-ti-tokens-cursor))
2001
2002 (defsubst js2-current-token-string ()
2003 (js2-token-string (js2-current-token)))
2004
2005 (defsubst js2-current-token-type ()
2006 (js2-token-type (js2-current-token)))
2007
2008 (defsubst js2-current-token-beg ()
2009 (js2-token-beg (js2-current-token)))
2010
2011 (defsubst js2-current-token-end ()
2012 (js2-token-end (js2-current-token)))
2013
2014 (defun js2-current-token-len ()
2015 (let ((token (js2-current-token)))
2016 (- (js2-token-end token)
2017 (js2-token-beg token))))
2018
2019 (defun js2-ts-seek (state)
2020 (setq js2-ts-lineno (js2-ts-state-lineno state)
2021 js2-ts-cursor (js2-ts-state-cursor state)
2022 js2-ti-tokens (js2-ts-state-tokens state)
2023 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2024 js2-ti-lookahead (js2-ts-state-lookahead state)))
2025
2026 ;;; Utilities
2027
2028 (defun js2-delete-if (predicate list)
2029 "Remove all items satisfying PREDICATE in LIST."
2030 (cl-loop for item in list
2031 if (not (funcall predicate item))
2032 collect item))
2033
2034 (defun js2-position (element list)
2035 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2036 Returns nil if element is not found in the list."
2037 (let ((count 0)
2038 found)
2039 (while (and list (not found))
2040 (if (eq element (car list))
2041 (setq found t)
2042 (setq count (1+ count)
2043 list (cdr list))))
2044 (if found count)))
2045
2046 (defun js2-find-if (predicate list)
2047 "Find first item satisfying PREDICATE in LIST."
2048 (let (result)
2049 (while (and list (not result))
2050 (if (funcall predicate (car list))
2051 (setq result (car list)))
2052 (setq list (cdr list)))
2053 result))
2054
2055 (defmacro js2-time (form)
2056 "Evaluate FORM, discard result, and return elapsed time in sec."
2057 (declare (debug t))
2058 (let ((beg (make-symbol "--js2-time-beg--")))
2059 `(let ((,beg (current-time)))
2060 ,form
2061 (/ (truncate (* (- (float-time (current-time))
2062 (float-time ,beg))
2063 10000))
2064 10000.0))))
2065
2066 (defsubst js2-same-line (pos)
2067 "Return t if POS is on the same line as current point."
2068 (and (>= pos (point-at-bol))
2069 (<= pos (point-at-eol))))
2070
2071 (defun js2-code-bug ()
2072 "Signal an error when we encounter an unexpected code path."
2073 (error "failed assertion"))
2074
2075 (defsubst js2-record-text-property (beg end prop value)
2076 "Record a text property to set when parsing finishes."
2077 (push (list beg end prop value) js2-mode-deferred-properties))
2078
2079 ;; I'd like to associate errors with nodes, but for now the
2080 ;; easiest thing to do is get the context info from the last token.
2081 (defun js2-record-parse-error (msg &optional arg pos len)
2082 (push (list (list msg arg)
2083 (or pos (js2-current-token-beg))
2084 (or len (js2-current-token-len)))
2085 js2-parsed-errors))
2086
2087 (defun js2-report-error (msg &optional msg-arg pos len)
2088 "Signal a syntax error or record a parse error."
2089 (if js2-recover-from-parse-errors
2090 (js2-record-parse-error msg msg-arg pos len)
2091 (signal 'js2-syntax-error
2092 (list msg
2093 js2-ts-lineno
2094 (save-excursion
2095 (goto-char js2-ts-cursor)
2096 (current-column))
2097 js2-ts-hit-eof))))
2098
2099 (defun js2-report-warning (msg &optional msg-arg pos len face)
2100 (if js2-compiler-report-warning-as-error
2101 (js2-report-error msg msg-arg pos len)
2102 (push (list (list msg msg-arg)
2103 (or pos (js2-current-token-beg))
2104 (or len (js2-current-token-len))
2105 face)
2106 js2-parsed-warnings)))
2107
2108 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2109 (if js2-compiler-strict-mode
2110 (js2-report-warning msg-id msg-arg beg
2111 (and beg end (- end beg)))))
2112
2113 (put 'js2-syntax-error 'error-conditions
2114 '(error syntax-error js2-syntax-error))
2115 (put 'js2-syntax-error 'error-message "Syntax error")
2116
2117 (put 'js2-parse-error 'error-conditions
2118 '(error parse-error js2-parse-error))
2119 (put 'js2-parse-error 'error-message "Parse error")
2120
2121 (defmacro js2-clear-flag (flags flag)
2122 `(setq ,flags (logand ,flags (lognot ,flag))))
2123
2124 (defmacro js2-set-flag (flags flag)
2125 "Logical-or FLAG into FLAGS."
2126 `(setq ,flags (logior ,flags ,flag)))
2127
2128 (defsubst js2-flag-set-p (flags flag)
2129 (/= 0 (logand flags flag)))
2130
2131 (defsubst js2-flag-not-set-p (flags flag)
2132 (zerop (logand flags flag)))
2133
2134 ;;; AST struct and function definitions
2135
2136 ;; flags for ast node property 'member-type (used for e4x operators)
2137 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2138 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2139 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2140
2141 (defsubst js2-relpos (pos anchor)
2142 "Convert POS to be relative to ANCHOR.
2143 If POS is nil, returns nil."
2144 (and pos (- pos anchor)))
2145
2146 (defun js2-make-pad (indent)
2147 (if (zerop indent)
2148 ""
2149 (make-string (* indent js2-basic-offset) ? )))
2150
2151 (defun js2-visit-ast (node callback)
2152 "Visit every node in ast NODE with visitor CALLBACK.
2153
2154 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2155 called twice: once to visit the node, and again after all the node's
2156 children have been processed. The END-P argument is nil on the first
2157 call and non-nil on the second call. The return value of the callback
2158 affects the traversal: if non-nil, the children of NODE are processed.
2159 If the callback returns nil, or if the node has no children, then the
2160 callback is called immediately with a non-nil END-P argument.
2161
2162 The node traversal is approximately lexical-order, although there
2163 are currently no guarantees around this."
2164 (when node
2165 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2166 ;; visit the node
2167 (when (funcall callback node nil)
2168 ;; visit the kids
2169 (cond
2170 ((eq vfunc 'js2-visit-none)
2171 nil) ; don't even bother calling it
2172 ;; Each AST node type has to define a `js2-visitor' function
2173 ;; that takes a node and a callback, and calls `js2-visit-ast'
2174 ;; on each child of the node.
2175 (vfunc
2176 (funcall vfunc node callback))
2177 (t
2178 (error "%s does not define a visitor-traversal function"
2179 (aref node 0)))))
2180 ;; call the end-visit
2181 (funcall callback node t))))
2182
2183 (cl-defstruct (js2-node
2184 (:constructor nil)) ; abstract
2185 "Base AST node type."
2186 (type -1) ; token type
2187 (pos -1) ; start position of this AST node in parsed input
2188 (len 1) ; num characters spanned by the node
2189 props ; optional node property list (an alist)
2190 parent) ; link to parent node; null for root
2191
2192 (defsubst js2-node-get-prop (node prop &optional default)
2193 (or (cadr (assoc prop (js2-node-props node))) default))
2194
2195 (defsubst js2-node-set-prop (node prop value)
2196 (setf (js2-node-props node)
2197 (cons (list prop value) (js2-node-props node))))
2198
2199 (defun js2-fixup-starts (n nodes)
2200 "Adjust the start positions of NODES to be relative to N.
2201 Any node in the list may be nil, for convenience."
2202 (dolist (node nodes)
2203 (when node
2204 (setf (js2-node-pos node) (- (js2-node-pos node)
2205 (js2-node-pos n))))))
2206
2207 (defun js2-node-add-children (parent &rest nodes)
2208 "Set parent node of NODES to PARENT, and return PARENT.
2209 Does nothing if we're not recording parent links.
2210 If any given node in NODES is nil, doesn't record that link."
2211 (js2-fixup-starts parent nodes)
2212 (dolist (node nodes)
2213 (and node
2214 (setf (js2-node-parent node) parent))))
2215
2216 ;; Non-recursive since it's called a frightening number of times.
2217 (defun js2-node-abs-pos (n)
2218 (let ((pos (js2-node-pos n)))
2219 (while (setq n (js2-node-parent n))
2220 (setq pos (+ pos (js2-node-pos n))))
2221 pos))
2222
2223 (defsubst js2-node-abs-end (n)
2224 "Return absolute buffer position of end of N."
2225 (+ (js2-node-abs-pos n) (js2-node-len n)))
2226
2227 ;; It's important to make sure block nodes have a Lisp list for the
2228 ;; child nodes, to limit printing recursion depth in an AST that
2229 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2230 ;; a sufficiently large vector tree.
2231
2232 (cl-defstruct (js2-block-node
2233 (:include js2-node)
2234 (:constructor nil)
2235 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2236 (pos (js2-current-token-beg))
2237 len
2238 props
2239 kids)))
2240 "A block of statements."
2241 kids) ; a Lisp list of the child statement nodes
2242
2243 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2244 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2245
2246 (defun js2-visit-block (ast callback)
2247 "Visit the `js2-block-node' children of AST."
2248 (dolist (kid (js2-block-node-kids ast))
2249 (js2-visit-ast kid callback)))
2250
2251 (defun js2-print-block (n i)
2252 (let ((pad (js2-make-pad i)))
2253 (insert pad "{\n")
2254 (dolist (kid (js2-block-node-kids n))
2255 (js2-print-ast kid (1+ i)))
2256 (insert pad "}")))
2257
2258 (cl-defstruct (js2-scope
2259 (:include js2-block-node)
2260 (:constructor nil)
2261 (:constructor make-js2-scope (&key (type js2-BLOCK)
2262 (pos (js2-current-token-beg))
2263 len
2264 kids)))
2265 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2266 ;; I don't have one of those handy, so I'll use an alist for now.
2267 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2268 ;; and is much lighter-weight to construct (both CPU and mem).
2269 ;; The keys are interned strings (symbols) for faster lookup.
2270 ;; Should switch to hybrid alist/hashtable eventually.
2271 symbol-table ; an alist of (symbol . js2-symbol)
2272 parent-scope ; a `js2-scope'
2273 top) ; top-level `js2-scope' (script/function)
2274
2275 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2276 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2277
2278 (defun js2-node-get-enclosing-scope (node)
2279 "Return the innermost `js2-scope' node surrounding NODE.
2280 Returns nil if there is no enclosing scope node."
2281 (while (and (setq node (js2-node-parent node))
2282 (not (js2-scope-p node))))
2283 node)
2284
2285 (defun js2-get-defining-scope (scope name &optional point)
2286 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2287 Returns `js2-scope' in which NAME is defined, or nil if not found.
2288
2289 If POINT is non-nil, and if the found declaration type is
2290 `js2-LET', also check that the declaration node is before POINT."
2291 (let ((sym (if (symbolp name)
2292 name
2293 (intern name)))
2294 result
2295 (continue t))
2296 (while (and scope continue)
2297 (if (or
2298 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2299 (and entry
2300 (or (not point)
2301 (not (eq js2-LET (js2-symbol-decl-type entry)))
2302 (>= point
2303 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2304 (and (eq sym 'arguments)
2305 (js2-function-node-p scope)))
2306 (setq continue nil
2307 result scope)
2308 (setq scope (js2-scope-parent-scope scope))))
2309 result))
2310
2311 (defun js2-scope-get-symbol (scope name)
2312 "Return symbol table entry for NAME in SCOPE.
2313 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2314 (and (js2-scope-symbol-table scope)
2315 (cdr (assq (if (symbolp name)
2316 name
2317 (intern name))
2318 (js2-scope-symbol-table scope)))))
2319
2320 (defun js2-scope-put-symbol (scope name symbol)
2321 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2322 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2323 (let* ((table (js2-scope-symbol-table scope))
2324 (sym (if (symbolp name) name (intern name)))
2325 (entry (assq sym table)))
2326 (if entry
2327 (setcdr entry symbol)
2328 (push (cons sym symbol)
2329 (js2-scope-symbol-table scope)))))
2330
2331 (cl-defstruct (js2-symbol
2332 (:constructor nil)
2333 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2334 "A symbol table entry."
2335 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2336 ;; js2-LET, or js2-CONST
2337 decl-type
2338 name ; string
2339 ast-node) ; a `js2-node'
2340
2341 (cl-defstruct (js2-error-node
2342 (:include js2-node)
2343 (:constructor nil) ; silence emacs21 byte-compiler
2344 (:constructor make-js2-error-node (&key (type js2-ERROR)
2345 (pos (js2-current-token-beg))
2346 len)))
2347 "AST node representing a parse error.")
2348
2349 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2350 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2351
2352 (cl-defstruct (js2-script-node
2353 (:include js2-scope)
2354 (:constructor nil)
2355 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2356 (pos (js2-current-token-beg))
2357 len
2358 ;; FIXME: What are those?
2359 var-decls
2360 fun-decls)))
2361 functions ; Lisp list of nested functions
2362 regexps ; Lisp list of (string . flags)
2363 symbols ; alist (every symbol gets unique index)
2364 (param-count 0)
2365 var-names ; vector of string names
2366 consts ; bool-vector matching var-decls
2367 (temp-number 0)) ; for generating temp variables
2368
2369 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2370 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2371
2372 (defun js2-print-script (node indent)
2373 (dolist (kid (js2-block-node-kids node))
2374 (js2-print-ast kid indent)))
2375
2376 (cl-defstruct (js2-ast-root
2377 (:include js2-script-node)
2378 (:constructor nil)
2379 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2380 (pos (js2-current-token-beg))
2381 len
2382 buffer)))
2383 "The root node of a js2 AST."
2384 buffer ; the source buffer from which the code was parsed
2385 comments ; a Lisp list of comments, ordered by start position
2386 errors ; a Lisp list of errors found during parsing
2387 warnings ; a Lisp list of warnings found during parsing
2388 node-count) ; number of nodes in the tree, including the root
2389
2390 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2391 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2392
2393 (defun js2-visit-ast-root (ast callback)
2394 (dolist (kid (js2-ast-root-kids ast))
2395 (js2-visit-ast kid callback))
2396 (dolist (comment (js2-ast-root-comments ast))
2397 (js2-visit-ast comment callback)))
2398
2399 (cl-defstruct (js2-comment-node
2400 (:include js2-node)
2401 (:constructor nil)
2402 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2403 (pos (js2-current-token-beg))
2404 len
2405 format)))
2406 format) ; 'line, 'block, 'jsdoc or 'html
2407
2408 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2409 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2410
2411 (defun js2-print-comment (n i)
2412 ;; We really ought to link end-of-line comments to their nodes.
2413 ;; Or maybe we could add a new comment type, 'endline.
2414 (insert (js2-make-pad i)
2415 (js2-node-string n)))
2416
2417 (cl-defstruct (js2-expr-stmt-node
2418 (:include js2-node)
2419 (:constructor nil)
2420 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2421 (pos js2-ts-cursor)
2422 len
2423 expr)))
2424 "An expression statement."
2425 expr)
2426
2427 (defsubst js2-expr-stmt-node-set-has-result (node)
2428 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2429 (setf (js2-node-type node) js2-EXPR_RESULT))
2430
2431 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2432 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2433
2434 (defun js2-visit-expr-stmt-node (n v)
2435 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2436
2437 (defun js2-print-expr-stmt-node (n indent)
2438 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2439 (insert ";\n"))
2440
2441 (cl-defstruct (js2-loop-node
2442 (:include js2-scope)
2443 (:constructor nil))
2444 "Abstract supertype of loop nodes."
2445 body ; a `js2-block-node'
2446 lp ; position of left-paren, nil if omitted
2447 rp) ; position of right-paren, nil if omitted
2448
2449 (cl-defstruct (js2-do-node
2450 (:include js2-loop-node)
2451 (:constructor nil)
2452 (:constructor make-js2-do-node (&key (type js2-DO)
2453 (pos (js2-current-token-beg))
2454 len
2455 body
2456 condition
2457 while-pos
2458 lp
2459 rp)))
2460 "AST node for do-loop."
2461 condition ; while (expression)
2462 while-pos) ; buffer position of 'while' keyword
2463
2464 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2465 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2466
2467 (defun js2-visit-do-node (n v)
2468 (js2-visit-ast (js2-do-node-body n) v)
2469 (js2-visit-ast (js2-do-node-condition n) v))
2470
2471 (defun js2-print-do-node (n i)
2472 (let ((pad (js2-make-pad i)))
2473 (insert pad "do {\n")
2474 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2475 (js2-print-ast kid (1+ i)))
2476 (insert pad "} while (")
2477 (js2-print-ast (js2-do-node-condition n) 0)
2478 (insert ");\n")))
2479
2480 (cl-defstruct (js2-export-node
2481 (:include js2-node)
2482 (:constructor nil)
2483 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2484 (pos (js2-current-token-beg))
2485 len
2486 exports-list
2487 from-clause
2488 declaration
2489 default)))
2490 "AST node for an export statement. There are many things that can be exported,
2491 so many of its properties will be nil.
2492 "
2493 exports-list ; lisp list of js2-export-binding-node to export
2494 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2495 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2496 default) ; js2-function-node or js2-assign-node
2497
2498 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2499 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2500
2501 (defun js2-visit-export-node (n v)
2502 (let ((exports-list (js2-export-node-exports-list n))
2503 (from (js2-export-node-from-clause n))
2504 (declaration (js2-export-node-declaration n))
2505 (default (js2-export-node-default n)))
2506 (when exports-list
2507 (dolist (export exports-list)
2508 (js2-visit-ast export v)))
2509 (when from
2510 (js2-visit-ast from v))
2511 (when declaration
2512 (js2-visit-ast declaration v))
2513 (when default
2514 (js2-visit-ast default v))))
2515
2516 (defun js2-print-export-node (n i)
2517 (let ((pad (js2-make-pad i))
2518 (exports-list (js2-export-node-exports-list n))
2519 (from (js2-export-node-from-clause n))
2520 (declaration (js2-export-node-declaration n))
2521 (default (js2-export-node-default n)))
2522 (insert pad "export ")
2523 (cond
2524 (default
2525 (insert "default ")
2526 (js2-print-ast default i))
2527 (declaration
2528 (js2-print-ast declaration i))
2529 ((and exports-list from)
2530 (js2-print-named-imports exports-list)
2531 (insert " ")
2532 (js2-print-from-clause from))
2533 (from
2534 (insert "* ")
2535 (js2-print-from-clause from))
2536 (exports-list
2537 (js2-print-named-imports exports-list)))
2538 (insert ";\n")))
2539
2540 (cl-defstruct (js2-while-node
2541 (:include js2-loop-node)
2542 (:constructor nil)
2543 (:constructor make-js2-while-node (&key (type js2-WHILE)
2544 (pos (js2-current-token-beg))
2545 len body
2546 condition lp
2547 rp)))
2548 "AST node for while-loop."
2549 condition) ; while-condition
2550
2551 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2552 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2553
2554 (defun js2-visit-while-node (n v)
2555 (js2-visit-ast (js2-while-node-condition n) v)
2556 (js2-visit-ast (js2-while-node-body n) v))
2557
2558 (defun js2-print-while-node (n i)
2559 (let ((pad (js2-make-pad i)))
2560 (insert pad "while (")
2561 (js2-print-ast (js2-while-node-condition n) 0)
2562 (insert ") {\n")
2563 (js2-print-body (js2-while-node-body n) (1+ i))
2564 (insert pad "}\n")))
2565
2566 (cl-defstruct (js2-for-node
2567 (:include js2-loop-node)
2568 (:constructor nil)
2569 (:constructor make-js2-for-node (&key (type js2-FOR)
2570 (pos js2-ts-cursor)
2571 len body init
2572 condition
2573 update lp rp)))
2574 "AST node for a C-style for-loop."
2575 init ; initialization expression
2576 condition ; loop condition
2577 update) ; update clause
2578
2579 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2580 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2581
2582 (defun js2-visit-for-node (n v)
2583 (js2-visit-ast (js2-for-node-init n) v)
2584 (js2-visit-ast (js2-for-node-condition n) v)
2585 (js2-visit-ast (js2-for-node-update n) v)
2586 (js2-visit-ast (js2-for-node-body n) v))
2587
2588 (defun js2-print-for-node (n i)
2589 (let ((pad (js2-make-pad i)))
2590 (insert pad "for (")
2591 (js2-print-ast (js2-for-node-init n) 0)
2592 (insert "; ")
2593 (js2-print-ast (js2-for-node-condition n) 0)
2594 (insert "; ")
2595 (js2-print-ast (js2-for-node-update n) 0)
2596 (insert ") {\n")
2597 (js2-print-body (js2-for-node-body n) (1+ i))
2598 (insert pad "}\n")))
2599
2600 (cl-defstruct (js2-for-in-node
2601 (:include js2-loop-node)
2602 (:constructor nil)
2603 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2604 (pos js2-ts-cursor)
2605 len body
2606 iterator
2607 object
2608 in-pos
2609 each-pos
2610 foreach-p forof-p
2611 lp rp)))
2612 "AST node for a for..in loop."
2613 iterator ; [var] foo in ...
2614 object ; object over which we're iterating
2615 in-pos ; buffer position of 'in' keyword
2616 each-pos ; buffer position of 'each' keyword, if foreach-p
2617 foreach-p ; t if it's a for-each loop
2618 forof-p) ; t if it's a for-of loop
2619
2620 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2621 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2622
2623 (defun js2-visit-for-in-node (n v)
2624 (js2-visit-ast (js2-for-in-node-iterator n) v)
2625 (js2-visit-ast (js2-for-in-node-object n) v)
2626 (js2-visit-ast (js2-for-in-node-body n) v))
2627
2628 (defun js2-print-for-in-node (n i)
2629 (let ((pad (js2-make-pad i))
2630 (foreach (js2-for-in-node-foreach-p n))
2631 (forof (js2-for-in-node-forof-p n)))
2632 (insert pad "for ")
2633 (if foreach
2634 (insert "each "))
2635 (insert "(")
2636 (js2-print-ast (js2-for-in-node-iterator n) 0)
2637 (insert (if forof " of " " in "))
2638 (js2-print-ast (js2-for-in-node-object n) 0)
2639 (insert ") {\n")
2640 (js2-print-body (js2-for-in-node-body n) (1+ i))
2641 (insert pad "}\n")))
2642
2643 (cl-defstruct (js2-return-node
2644 (:include js2-node)
2645 (:constructor nil)
2646 (:constructor make-js2-return-node (&key (type js2-RETURN)
2647 (pos js2-ts-cursor)
2648 len
2649 retval)))
2650 "AST node for a return statement."
2651 retval) ; expression to return, or 'undefined
2652
2653 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2654 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2655
2656 (defun js2-visit-return-node (n v)
2657 (js2-visit-ast (js2-return-node-retval n) v))
2658
2659 (defun js2-print-return-node (n i)
2660 (insert (js2-make-pad i) "return")
2661 (when (js2-return-node-retval n)
2662 (insert " ")
2663 (js2-print-ast (js2-return-node-retval n) 0))
2664 (insert ";\n"))
2665
2666 (cl-defstruct (js2-if-node
2667 (:include js2-node)
2668 (:constructor nil)
2669 (:constructor make-js2-if-node (&key (type js2-IF)
2670 (pos js2-ts-cursor)
2671 len condition
2672 then-part
2673 else-pos
2674 else-part lp
2675 rp)))
2676 "AST node for an if-statement."
2677 condition ; expression
2678 then-part ; statement or block
2679 else-pos ; optional buffer position of 'else' keyword
2680 else-part ; optional statement or block
2681 lp ; position of left-paren, nil if omitted
2682 rp) ; position of right-paren, nil if omitted
2683
2684 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2685 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2686
2687 (defun js2-visit-if-node (n v)
2688 (js2-visit-ast (js2-if-node-condition n) v)
2689 (js2-visit-ast (js2-if-node-then-part n) v)
2690 (js2-visit-ast (js2-if-node-else-part n) v))
2691
2692 (defun js2-print-if-node (n i)
2693 (let ((pad (js2-make-pad i))
2694 (then-part (js2-if-node-then-part n))
2695 (else-part (js2-if-node-else-part n)))
2696 (insert pad "if (")
2697 (js2-print-ast (js2-if-node-condition n) 0)
2698 (insert ") {\n")
2699 (js2-print-body then-part (1+ i))
2700 (insert pad "}")
2701 (cond
2702 ((not else-part)
2703 (insert "\n"))
2704 ((js2-if-node-p else-part)
2705 (insert " else ")
2706 (js2-print-body else-part i))
2707 (t
2708 (insert " else {\n")
2709 (js2-print-body else-part (1+ i))
2710 (insert pad "}\n")))))
2711
2712 (cl-defstruct (js2-export-binding-node
2713 (:include js2-node)
2714 (:constructor nil)
2715 (:constructor make-js2-export-binding-node (&key (type -1)
2716 pos
2717 len
2718 local-name
2719 extern-name)))
2720 "AST node for an external symbol binding.
2721 It contains a local-name node which is the name of the value in the
2722 current scope, and extern-name which is the name of the value in the
2723 imported or exported scope. By default these are the same, but if the
2724 name is aliased as in {foo as bar}, it would have an extern-name node
2725 containing 'foo' and a local-name node containing 'bar'."
2726 local-name ; js2-name-node with the variable name in this scope
2727 extern-name) ; js2-name-node with the value name in the exporting module
2728
2729 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2730 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2731
2732 (defun js2-visit-extern-binding (n v)
2733 "Visit an extern binding node. First visit the local-name, and, if
2734 different, visit the extern-name."
2735 (let ((local-name (js2-export-binding-node-local-name n))
2736 (extern-name (js2-export-binding-node-extern-name n)))
2737 (when local-name
2738 (js2-visit-ast local-name v))
2739 (when (not (equal local-name extern-name))
2740 (js2-visit-ast extern-name v))))
2741
2742 (defun js2-print-extern-binding (n _i)
2743 "Print a representation of a single extern binding. E.g. 'foo' or
2744 'foo as bar'."
2745 (let ((local-name (js2-export-binding-node-local-name n))
2746 (extern-name (js2-export-binding-node-extern-name n)))
2747 (insert (js2-name-node-name extern-name))
2748 (when (not (equal local-name extern-name))
2749 (insert " as ")
2750 (insert (js2-name-node-name local-name)))))
2751
2752
2753 (cl-defstruct (js2-import-node
2754 (:include js2-node)
2755 (:constructor nil)
2756 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2757 (pos (js2-current-token-beg))
2758 len
2759 import
2760 from
2761 module-id)))
2762 "AST node for an import statement. It follows the form
2763
2764 import ModuleSpecifier;
2765 import ImportClause FromClause;"
2766 import ; js2-import-clause-node specifying which names are to imported.
2767 from ; js2-from-clause-node indicating the module from which to import.
2768 module-id) ; module-id of the import. E.g. 'src/mylib'.
2769
2770 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2771 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2772
2773 (defun js2-visit-import (n v)
2774 (let ((import-clause (js2-import-node-import n))
2775 (from-clause (js2-import-node-from n)))
2776 (when import-clause
2777 (js2-visit-ast import-clause v))
2778 (when from-clause
2779 (js2-visit-ast from-clause v))))
2780
2781 (defun js2-print-import (n i)
2782 "Prints a representation of the import node"
2783 (let ((pad (js2-make-pad i))
2784 (import-clause (js2-import-node-import n))
2785 (from-clause (js2-import-node-from n))
2786 (module-id (js2-import-node-module-id n)))
2787 (insert pad "import ")
2788 (if import-clause
2789 (progn
2790 (js2-print-import-clause import-clause)
2791 (insert " ")
2792 (js2-print-from-clause from-clause))
2793 (insert "'")
2794 (insert module-id)
2795 (insert "'"))
2796 (insert ";\n")))
2797
2798 (cl-defstruct (js2-import-clause-node
2799 (:include js2-node)
2800 (:constructor nil)
2801 (:constructor make-js2-import-clause-node (&key (type -1)
2802 pos
2803 len
2804 namespace-import
2805 named-imports
2806 default-binding)))
2807 "AST node corresponding to the import clause of an import statement. This is
2808 the portion of the import that bindings names from the external context to the
2809 local context."
2810 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2811 named-imports ; lisp list of js2-export-binding-node for all named imports.
2812 default-binding) ; js2-export-binding-node for the default import binding
2813
2814 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2815 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2816
2817 (defun js2-visit-import-clause (n v)
2818 (let ((ns-import (js2-import-clause-node-namespace-import n))
2819 (named-imports (js2-import-clause-node-named-imports n))
2820 (default (js2-import-clause-node-default-binding n)))
2821 (when ns-import
2822 (js2-visit-ast ns-import v))
2823 (when named-imports
2824 (dolist (import named-imports)
2825 (js2-visit-ast import v)))
2826 (when default
2827 (js2-visit-ast default v))))
2828
2829 (defun js2-print-import-clause (n)
2830 (let ((ns-import (js2-import-clause-node-namespace-import n))
2831 (named-imports (js2-import-clause-node-named-imports n))
2832 (default (js2-import-clause-node-default-binding n)))
2833 (cond
2834 ((and default ns-import)
2835 (js2-print-ast default)
2836 (insert ", ")
2837 (js2-print-namespace-import ns-import))
2838 ((and default named-imports)
2839 (js2-print-ast default)
2840 (insert ", ")
2841 (js2-print-named-imports named-imports))
2842 (default
2843 (js2-print-ast default))
2844 (ns-import
2845 (js2-print-namespace-import ns-import))
2846 (named-imports
2847 (js2-print-named-imports named-imports)))))
2848
2849 (defun js2-print-namespace-import (node)
2850 (insert "* as ")
2851 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2852
2853 (defun js2-print-named-imports (imports)
2854 (insert "{")
2855 (let ((len (length imports))
2856 (n 0))
2857 (while (< n len)
2858 (js2-print-extern-binding (nth n imports) 0)
2859 (unless (= n (- len 1))
2860 (insert ", "))
2861 (setq n (+ n 1))))
2862 (insert "}"))
2863
2864 (cl-defstruct (js2-namespace-import-node
2865 (:include js2-node)
2866 (:constructor nil)
2867 (:constructor make-js2-namespace-import-node (&key (type -1)
2868 pos
2869 len
2870 name)))
2871 "AST node for a complete namespace import.
2872 E.g. the '* as lib' expression in:
2873
2874 import * as lib from 'src/lib'
2875
2876 It contains a single name node referring to the bound name."
2877 name) ; js2-name-node of the bound name.
2878
2879 (defun js2-visit-namespace-import (n v)
2880 (js2-visit-ast (js2-namespace-import-node-name n) v))
2881
2882 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2883 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2884
2885 (cl-defstruct (js2-from-clause-node
2886 (:include js2-node)
2887 (:constructor nil)
2888 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2889 pos
2890 len
2891 module-id
2892 metadata-p)))
2893 "AST node for the from clause in an import or export statement.
2894 E.g. from 'my/module'. It can refere to either an external module, or to the
2895 modules metadata itself."
2896 module-id ; string containing the module specifier.
2897 metadata-p) ; true if this clause refers to the module's metadata
2898
2899 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2900 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2901
2902 (defun js2-print-from-clause (n)
2903 (insert "from ")
2904 (if (js2-from-clause-node-metadata-p n)
2905 (insert "this module")
2906 (insert "'")
2907 (insert (js2-from-clause-node-module-id n))
2908 (insert "'")))
2909
2910 (cl-defstruct (js2-try-node
2911 (:include js2-node)
2912 (:constructor nil)
2913 (:constructor make-js2-try-node (&key (type js2-TRY)
2914 (pos js2-ts-cursor)
2915 len
2916 try-block
2917 catch-clauses
2918 finally-block)))
2919 "AST node for a try-statement."
2920 try-block
2921 catch-clauses ; a Lisp list of `js2-catch-node'
2922 finally-block) ; a `js2-finally-node'
2923
2924 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2925 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2926
2927 (defun js2-visit-try-node (n v)
2928 (js2-visit-ast (js2-try-node-try-block n) v)
2929 (dolist (clause (js2-try-node-catch-clauses n))
2930 (js2-visit-ast clause v))
2931 (js2-visit-ast (js2-try-node-finally-block n) v))
2932
2933 (defun js2-print-try-node (n i)
2934 (let ((pad (js2-make-pad i))
2935 (catches (js2-try-node-catch-clauses n))
2936 (finally (js2-try-node-finally-block n)))
2937 (insert pad "try {\n")
2938 (js2-print-body (js2-try-node-try-block n) (1+ i))
2939 (insert pad "}")
2940 (when catches
2941 (dolist (catch catches)
2942 (js2-print-ast catch i)))
2943 (if finally
2944 (js2-print-ast finally i)
2945 (insert "\n"))))
2946
2947 (cl-defstruct (js2-catch-node
2948 (:include js2-scope)
2949 (:constructor nil)
2950 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2951 (pos js2-ts-cursor)
2952 len
2953 param
2954 guard-kwd
2955 guard-expr
2956 lp rp)))
2957 "AST node for a catch clause."
2958 param ; destructuring form or simple name node
2959 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2960 guard-expr ; catch condition, a `js2-node'
2961 lp ; buffer position of left-paren, nil if omitted
2962 rp) ; buffer position of right-paren, nil if omitted
2963
2964 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2965 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2966
2967 (defun js2-visit-catch-node (n v)
2968 (js2-visit-ast (js2-catch-node-param n) v)
2969 (when (js2-catch-node-guard-kwd n)
2970 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2971 (js2-visit-block n v))
2972
2973 (defun js2-print-catch-node (n i)
2974 (let ((pad (js2-make-pad i))
2975 (guard-kwd (js2-catch-node-guard-kwd n))
2976 (guard-expr (js2-catch-node-guard-expr n)))
2977 (insert " catch (")
2978 (js2-print-ast (js2-catch-node-param n) 0)
2979 (when guard-kwd
2980 (insert " if ")
2981 (js2-print-ast guard-expr 0))
2982 (insert ") {\n")
2983 (js2-print-body n (1+ i))
2984 (insert pad "}")))
2985
2986 (cl-defstruct (js2-finally-node
2987 (:include js2-node)
2988 (:constructor nil)
2989 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2990 (pos js2-ts-cursor)
2991 len body)))
2992 "AST node for a finally clause."
2993 body) ; a `js2-node', often but not always a block node
2994
2995 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2996 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2997
2998 (defun js2-visit-finally-node (n v)
2999 (js2-visit-ast (js2-finally-node-body n) v))
3000
3001 (defun js2-print-finally-node (n i)
3002 (let ((pad (js2-make-pad i)))
3003 (insert " finally {\n")
3004 (js2-print-body (js2-finally-node-body n) (1+ i))
3005 (insert pad "}\n")))
3006
3007 (cl-defstruct (js2-switch-node
3008 (:include js2-node)
3009 (:constructor nil)
3010 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3011 (pos js2-ts-cursor)
3012 len
3013 discriminant
3014 cases lp
3015 rp)))
3016 "AST node for a switch statement."
3017 discriminant ; a `js2-node' (switch expression)
3018 cases ; a Lisp list of `js2-case-node'
3019 lp ; position of open-paren for discriminant, nil if omitted
3020 rp) ; position of close-paren for discriminant, nil if omitted
3021
3022 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3023 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3024
3025 (defun js2-visit-switch-node (n v)
3026 (js2-visit-ast (js2-switch-node-discriminant n) v)
3027 (dolist (c (js2-switch-node-cases n))
3028 (js2-visit-ast c v)))
3029
3030 (defun js2-print-switch-node (n i)
3031 (let ((pad (js2-make-pad i))
3032 (cases (js2-switch-node-cases n)))
3033 (insert pad "switch (")
3034 (js2-print-ast (js2-switch-node-discriminant n) 0)
3035 (insert ") {\n")
3036 (dolist (case cases)
3037 (js2-print-ast case i))
3038 (insert pad "}\n")))
3039
3040 (cl-defstruct (js2-case-node
3041 (:include js2-block-node)
3042 (:constructor nil)
3043 (:constructor make-js2-case-node (&key (type js2-CASE)
3044 (pos js2-ts-cursor)
3045 len kids expr)))
3046 "AST node for a case clause of a switch statement."
3047 expr) ; the case expression (nil for default)
3048
3049 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3050 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3051
3052 (defun js2-visit-case-node (n v)
3053 (js2-visit-ast (js2-case-node-expr n) v)
3054 (js2-visit-block n v))
3055
3056 (defun js2-print-case-node (n i)
3057 (let ((pad (js2-make-pad i))
3058 (expr (js2-case-node-expr n)))
3059 (insert pad)
3060 (if (null expr)
3061 (insert "default:\n")
3062 (insert "case ")
3063 (js2-print-ast expr 0)
3064 (insert ":\n"))
3065 (dolist (kid (js2-case-node-kids n))
3066 (js2-print-ast kid (1+ i)))))
3067
3068 (cl-defstruct (js2-throw-node
3069 (:include js2-node)
3070 (:constructor nil)
3071 (:constructor make-js2-throw-node (&key (type js2-THROW)
3072 (pos js2-ts-cursor)
3073 len expr)))
3074 "AST node for a throw statement."
3075 expr) ; the expression to throw
3076
3077 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3078 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3079
3080 (defun js2-visit-throw-node (n v)
3081 (js2-visit-ast (js2-throw-node-expr n) v))
3082
3083 (defun js2-print-throw-node (n i)
3084 (insert (js2-make-pad i) "throw ")
3085 (js2-print-ast (js2-throw-node-expr n) 0)
3086 (insert ";\n"))
3087
3088 (cl-defstruct (js2-with-node
3089 (:include js2-node)
3090 (:constructor nil)
3091 (:constructor make-js2-with-node (&key (type js2-WITH)
3092 (pos js2-ts-cursor)
3093 len object
3094 body lp rp)))
3095 "AST node for a with-statement."
3096 object
3097 body
3098 lp ; buffer position of left-paren around object, nil if omitted
3099 rp) ; buffer position of right-paren around object, nil if omitted
3100
3101 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3102 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3103
3104 (defun js2-visit-with-node (n v)
3105 (js2-visit-ast (js2-with-node-object n) v)
3106 (js2-visit-ast (js2-with-node-body n) v))
3107
3108 (defun js2-print-with-node (n i)
3109 (let ((pad (js2-make-pad i)))
3110 (insert pad "with (")
3111 (js2-print-ast (js2-with-node-object n) 0)
3112 (insert ") {\n")
3113 (js2-print-body (js2-with-node-body n) (1+ i))
3114 (insert pad "}\n")))
3115
3116 (cl-defstruct (js2-label-node
3117 (:include js2-node)
3118 (:constructor nil)
3119 (:constructor make-js2-label-node (&key (type js2-LABEL)
3120 (pos js2-ts-cursor)
3121 len name)))
3122 "AST node for a statement label or case label."
3123 name ; a string
3124 loop) ; for validating and code-generating continue-to-label
3125
3126 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3127 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3128
3129 (defun js2-print-label (n i)
3130 (insert (js2-make-pad i)
3131 (js2-label-node-name n)
3132 ":\n"))
3133
3134 (cl-defstruct (js2-labeled-stmt-node
3135 (:include js2-node)
3136 (:constructor nil)
3137 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3138 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3139 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3140 (pos js2-ts-cursor)
3141 len labels stmt)))
3142 "AST node for a statement with one or more labels.
3143 Multiple labels for a statement are collapsed into the labels field."
3144 labels ; Lisp list of `js2-label-node'
3145 stmt) ; the statement these labels are for
3146
3147 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3148 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3149
3150 (defun js2-get-label-by-name (lbl-stmt name)
3151 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3152 Returns nil if no such label is in the list."
3153 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3154 result)
3155 (while (and label-list (not result))
3156 (if (string= (js2-label-node-name (car label-list)) name)
3157 (setq result (car label-list))
3158 (setq label-list (cdr label-list))))
3159 result))
3160
3161 (defun js2-visit-labeled-stmt (n v)
3162 (dolist (label (js2-labeled-stmt-node-labels n))
3163 (js2-visit-ast label v))
3164 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3165
3166 (defun js2-print-labeled-stmt (n i)
3167 (dolist (label (js2-labeled-stmt-node-labels n))
3168 (js2-print-ast label i))
3169 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3170
3171 (defun js2-labeled-stmt-node-contains (node label)
3172 "Return t if NODE contains LABEL in its label set.
3173 NODE is a `js2-labels-node'. LABEL is an identifier."
3174 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3175 if (string= label (js2-label-node-name nl))
3176 return t
3177 finally return nil))
3178
3179 (defsubst js2-labeled-stmt-node-add-label (node label)
3180 "Add a `js2-label-node' to the label set for this statement."
3181 (setf (js2-labeled-stmt-node-labels node)
3182 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3183
3184 (cl-defstruct (js2-jump-node
3185 (:include js2-node)
3186 (:constructor nil))
3187 "Abstract supertype of break and continue nodes."
3188 label ; `js2-name-node' for location of label identifier, if present
3189 target) ; target js2-labels-node or loop/switch statement
3190
3191 (defun js2-visit-jump-node (n v)
3192 ;; We don't visit the target, since it's a back-link.
3193 (js2-visit-ast (js2-jump-node-label n) v))
3194
3195 (cl-defstruct (js2-break-node
3196 (:include js2-jump-node)
3197 (:constructor nil)
3198 (:constructor make-js2-break-node (&key (type js2-BREAK)
3199 (pos js2-ts-cursor)
3200 len label target)))
3201 "AST node for a break statement.
3202 The label field is a `js2-name-node', possibly nil, for the named label
3203 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3204 is the target of the break - a label node or enclosing loop/switch statement.")
3205
3206 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3207 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3208
3209 (defun js2-print-break-node (n i)
3210 (insert (js2-make-pad i) "break")
3211 (when (js2-break-node-label n)
3212 (insert " ")
3213 (js2-print-ast (js2-break-node-label n) 0))
3214 (insert ";\n"))
3215
3216 (cl-defstruct (js2-continue-node
3217 (:include js2-jump-node)
3218 (:constructor nil)
3219 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3220 (pos js2-ts-cursor)
3221 len label target)))
3222 "AST node for a continue statement.
3223 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3224 It is nil if continue specifies no label. The target field is the jump target:
3225 a `js2-label-node' or the innermost enclosing loop.")
3226
3227 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3228 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3229
3230 (defun js2-print-continue-node (n i)
3231 (insert (js2-make-pad i) "continue")
3232 (when (js2-continue-node-label n)
3233 (insert " ")
3234 (js2-print-ast (js2-continue-node-label n) 0))
3235 (insert ";\n"))
3236
3237 (cl-defstruct (js2-function-node
3238 (:include js2-script-node)
3239 (:constructor nil)
3240 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3241 (pos js2-ts-cursor)
3242 len
3243 (ftype 'FUNCTION)
3244 (form 'FUNCTION_STATEMENT)
3245 (name "")
3246 params rest-p
3247 body
3248 generator-type
3249 lp rp)))
3250 "AST node for a function declaration.
3251 The `params' field is a Lisp list of nodes. Each node is either a simple
3252 `js2-name-node', or if it's a destructuring-assignment parameter, a
3253 `js2-array-node' or `js2-object-node'."
3254 ftype ; FUNCTION, GETTER or SETTER
3255 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3256 name ; function name (a `js2-name-node', or nil if anonymous)
3257 params ; a Lisp list of destructuring forms or simple name nodes
3258 rest-p ; if t, the last parameter is rest parameter
3259 body ; a `js2-block-node' or expression node (1.8 only)
3260 lp ; position of arg-list open-paren, or nil if omitted
3261 rp ; position of arg-list close-paren, or nil if omitted
3262 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3263 needs-activation ; t if we need an activation object for this frame
3264 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3265 member-expr) ; nonstandard Ecma extension from Rhino
3266
3267 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3268 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3269
3270 (defun js2-visit-function-node (n v)
3271 (js2-visit-ast (js2-function-node-name n) v)
3272 (dolist (p (js2-function-node-params n))
3273 (js2-visit-ast p v))
3274 (js2-visit-ast (js2-function-node-body n) v))
3275
3276 (defun js2-print-function-node (n i)
3277 (let* ((pad (js2-make-pad i))
3278 (method (js2-node-get-prop n 'METHOD_TYPE))
3279 (name (or (js2-function-node-name n)
3280 (js2-function-node-member-expr n)))
3281 (params (js2-function-node-params n))
3282 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3283 (rest-p (js2-function-node-rest-p n))
3284 (body (js2-function-node-body n))
3285 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3286 (unless (or method arrow)
3287 (insert pad "function")
3288 (when (eq (js2-function-node-generator-type n) 'STAR)
3289 (insert "*")))
3290 (when name
3291 (insert " ")
3292 (js2-print-ast name 0))
3293 (insert "(")
3294 (cl-loop with len = (length params)
3295 for param in params
3296 for count from 1
3297 do
3298 (when (and rest-p (= count len))
3299 (insert "..."))
3300 (js2-print-ast param 0)
3301 (when (< count len)
3302 (insert ", ")))
3303 (insert ") ")
3304 (when arrow
3305 (insert "=> "))
3306 (insert "{")
3307 ;; TODO: fix this to be smarter about indenting, etc.
3308 (unless expr
3309 (insert "\n"))
3310 (if (js2-block-node-p body)
3311 (js2-print-body body (1+ i))
3312 (js2-print-ast body 0))
3313 (insert pad "}")
3314 (unless expr
3315 (insert "\n"))))
3316
3317 (defun js2-function-name (node)
3318 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3319 (and (js2-function-node-name node)
3320 (js2-name-node-name (js2-function-node-name node))))
3321
3322 ;; Having this be an expression node makes it more flexible.
3323 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3324 ;; that work better if you assume it's an expression. Whenever we have
3325 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3326 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3327 (cl-defstruct (js2-var-decl-node
3328 (:include js2-node)
3329 (:constructor nil)
3330 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3331 (pos (js2-current-token-beg))
3332 len kids
3333 decl-type)))
3334 "AST node for a variable declaration list (VAR, CONST or LET).
3335 The node bounds differ depending on the declaration type. For VAR or
3336 CONST declarations, the bounds include the var/const keyword. For LET
3337 declarations, the node begins at the position of the first child."
3338 kids ; a Lisp list of `js2-var-init-node' structs.
3339 decl-type) ; js2-VAR, js2-CONST or js2-LET
3340
3341 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3342 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3343
3344 (defun js2-visit-var-decl (n v)
3345 (dolist (kid (js2-var-decl-node-kids n))
3346 (js2-visit-ast kid v)))
3347
3348 (defun js2-print-var-decl (n i)
3349 (let ((pad (js2-make-pad i))
3350 (tt (js2-var-decl-node-decl-type n)))
3351 (insert pad)
3352 (insert (cond
3353 ((= tt js2-VAR) "var ")
3354 ((= tt js2-LET) "let ")
3355 ((= tt js2-CONST) "const ")
3356 (t
3357 (error "malformed var-decl node"))))
3358 (cl-loop with kids = (js2-var-decl-node-kids n)
3359 with len = (length kids)
3360 for kid in kids
3361 for count from 1
3362 do
3363 (js2-print-ast kid 0)
3364 (if (< count len)
3365 (insert ", ")))))
3366
3367 (cl-defstruct (js2-var-init-node
3368 (:include js2-node)
3369 (:constructor nil)
3370 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3371 (pos js2-ts-cursor)
3372 len target
3373 initializer)))
3374 "AST node for a variable declaration.
3375 The type field will be js2-CONST for a const decl."
3376 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3377 initializer) ; initializer expression, a `js2-node'
3378
3379 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3380 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3381
3382 (defun js2-visit-var-init-node (n v)
3383 (js2-visit-ast (js2-var-init-node-target n) v)
3384 (js2-visit-ast (js2-var-init-node-initializer n) v))
3385
3386 (defun js2-print-var-init-node (n i)
3387 (let ((pad (js2-make-pad i))
3388 (name (js2-var-init-node-target n))
3389 (init (js2-var-init-node-initializer n)))
3390 (insert pad)
3391 (js2-print-ast name 0)
3392 (when init
3393 (insert " = ")
3394 (js2-print-ast init 0))))
3395
3396 (cl-defstruct (js2-cond-node
3397 (:include js2-node)
3398 (:constructor nil)
3399 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3400 (pos js2-ts-cursor)
3401 len
3402 test-expr
3403 true-expr
3404 false-expr
3405 q-pos c-pos)))
3406 "AST node for the ternary operator"
3407 test-expr
3408 true-expr
3409 false-expr
3410 q-pos ; buffer position of ?
3411 c-pos) ; buffer position of :
3412
3413 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3414 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3415
3416 (defun js2-visit-cond-node (n v)
3417 (js2-visit-ast (js2-cond-node-test-expr n) v)
3418 (js2-visit-ast (js2-cond-node-true-expr n) v)
3419 (js2-visit-ast (js2-cond-node-false-expr n) v))
3420
3421 (defun js2-print-cond-node (n i)
3422 (let ((pad (js2-make-pad i)))
3423 (insert pad)
3424 (js2-print-ast (js2-cond-node-test-expr n) 0)
3425 (insert " ? ")
3426 (js2-print-ast (js2-cond-node-true-expr n) 0)
3427 (insert " : ")
3428 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3429
3430 (cl-defstruct (js2-infix-node
3431 (:include js2-node)
3432 (:constructor nil)
3433 (:constructor make-js2-infix-node (&key type
3434 (pos js2-ts-cursor)
3435 len op-pos
3436 left right)))
3437 "Represents infix expressions.
3438 Includes assignment ops like `|=', and the comma operator.
3439 The type field inherited from `js2-node' holds the operator."
3440 op-pos ; buffer position where operator begins
3441 left ; any `js2-node'
3442 right) ; any `js2-node'
3443
3444 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3445 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3446
3447 (defun js2-visit-infix-node (n v)
3448 (js2-visit-ast (js2-infix-node-left n) v)
3449 (js2-visit-ast (js2-infix-node-right n) v))
3450
3451 (defconst js2-operator-tokens
3452 (let ((table (make-hash-table :test 'eq))
3453 (tokens
3454 (list (cons js2-IN "in")
3455 (cons js2-TYPEOF "typeof")
3456 (cons js2-INSTANCEOF "instanceof")
3457 (cons js2-DELPROP "delete")
3458 (cons js2-COMMA ",")
3459 (cons js2-COLON ":")
3460 (cons js2-OR "||")
3461 (cons js2-AND "&&")
3462 (cons js2-INC "++")
3463 (cons js2-DEC "--")
3464 (cons js2-BITOR "|")
3465 (cons js2-BITXOR "^")
3466 (cons js2-BITAND "&")
3467 (cons js2-EQ "==")
3468 (cons js2-NE "!=")
3469 (cons js2-LT "<")
3470 (cons js2-LE "<=")
3471 (cons js2-GT ">")
3472 (cons js2-GE ">=")
3473 (cons js2-LSH "<<")
3474 (cons js2-RSH ">>")
3475 (cons js2-URSH ">>>")
3476 (cons js2-ADD "+") ; infix plus
3477 (cons js2-SUB "-") ; infix minus
3478 (cons js2-MUL "*")
3479 (cons js2-DIV "/")
3480 (cons js2-MOD "%")
3481 (cons js2-NOT "!")
3482 (cons js2-BITNOT "~")
3483 (cons js2-POS "+") ; unary plus
3484 (cons js2-NEG "-") ; unary minus
3485 (cons js2-TRIPLEDOT "...")
3486 (cons js2-SHEQ "===") ; shallow equality
3487 (cons js2-SHNE "!==") ; shallow inequality
3488 (cons js2-ASSIGN "=")
3489 (cons js2-ASSIGN_BITOR "|=")
3490 (cons js2-ASSIGN_BITXOR "^=")
3491 (cons js2-ASSIGN_BITAND "&=")
3492 (cons js2-ASSIGN_LSH "<<=")
3493 (cons js2-ASSIGN_RSH ">>=")
3494 (cons js2-ASSIGN_URSH ">>>=")
3495 (cons js2-ASSIGN_ADD "+=")
3496 (cons js2-ASSIGN_SUB "-=")
3497 (cons js2-ASSIGN_MUL "*=")
3498 (cons js2-ASSIGN_DIV "/=")
3499 (cons js2-ASSIGN_MOD "%="))))
3500 (cl-loop for (k . v) in tokens do
3501 (puthash k v table))
3502 table))
3503
3504 (defun js2-print-infix-node (n i)
3505 (let* ((tt (js2-node-type n))
3506 (op (gethash tt js2-operator-tokens)))
3507 (unless op
3508 (error "unrecognized infix operator %s" (js2-node-type n)))
3509 (insert (js2-make-pad i))
3510 (js2-print-ast (js2-infix-node-left n) 0)
3511 (unless (= tt js2-COMMA)
3512 (insert " "))
3513 (insert op)
3514 (insert " ")
3515 (js2-print-ast (js2-infix-node-right n) 0)))
3516
3517 (cl-defstruct (js2-assign-node
3518 (:include js2-infix-node)
3519 (:constructor nil)
3520 (:constructor make-js2-assign-node (&key type
3521 (pos js2-ts-cursor)
3522 len op-pos
3523 left right)))
3524 "Represents any assignment.
3525 The type field holds the actual assignment operator.")
3526
3527 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3528 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3529
3530 (cl-defstruct (js2-unary-node
3531 (:include js2-node)
3532 (:constructor nil)
3533 (:constructor make-js2-unary-node (&key type ; required
3534 (pos js2-ts-cursor)
3535 len operand)))
3536 "AST node type for unary operator nodes.
3537 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3538 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3539 property is added if the operator follows the operand."
3540 operand) ; a `js2-node' expression
3541
3542 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3543 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3544
3545 (defun js2-visit-unary-node (n v)
3546 (js2-visit-ast (js2-unary-node-operand n) v))
3547
3548 (defun js2-print-unary-node (n i)
3549 (let* ((tt (js2-node-type n))
3550 (op (gethash tt js2-operator-tokens))
3551 (postfix (js2-node-get-prop n 'postfix)))
3552 (unless op
3553 (error "unrecognized unary operator %s" tt))
3554 (insert (js2-make-pad i))
3555 (unless postfix
3556 (insert op))
3557 (if (or (= tt js2-TYPEOF)
3558 (= tt js2-DELPROP))
3559 (insert " "))
3560 (js2-print-ast (js2-unary-node-operand n) 0)
3561 (when postfix
3562 (insert op))))
3563
3564 (cl-defstruct (js2-let-node
3565 (:include js2-scope)
3566 (:constructor nil)
3567 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3568 (pos (js2-current-token-beg))
3569 len vars body
3570 lp rp)))
3571 "AST node for a let expression or a let statement.
3572 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3573 vars ; a `js2-var-decl-node'
3574 body ; a `js2-node' representing the expression or body block
3575 lp
3576 rp)
3577
3578 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3579 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3580
3581 (defun js2-visit-let-node (n v)
3582 (js2-visit-ast (js2-let-node-vars n) v)
3583 (js2-visit-ast (js2-let-node-body n) v))
3584
3585 (defun js2-print-let-node (n i)
3586 (insert (js2-make-pad i) "let (")
3587 (let ((p (point)))
3588 (js2-print-ast (js2-let-node-vars n) 0)
3589 (delete-region p (+ p 4)))
3590 (insert ") ")
3591 (js2-print-ast (js2-let-node-body n) i))
3592
3593 (cl-defstruct (js2-keyword-node
3594 (:include js2-node)
3595 (:constructor nil)
3596 (:constructor make-js2-keyword-node (&key type
3597 (pos (js2-current-token-beg))
3598 (len (- js2-ts-cursor pos)))))
3599 "AST node representing a literal keyword such as `null'.
3600 Used for `null', `this', `true', `false' and `debugger'.
3601 The node type is set to js2-NULL, js2-THIS, etc.")
3602
3603 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3604 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3605
3606 (defun js2-print-keyword-node (n i)
3607 (insert (js2-make-pad i)
3608 (let ((tt (js2-node-type n)))
3609 (cond
3610 ((= tt js2-THIS) "this")
3611 ((= tt js2-SUPER) "super")
3612 ((= tt js2-NULL) "null")
3613 ((= tt js2-TRUE) "true")
3614 ((= tt js2-FALSE) "false")
3615 ((= tt js2-DEBUGGER) "debugger")
3616 (t (error "Invalid keyword literal type: %d" tt))))))
3617
3618 (defsubst js2-this-or-super-node-p (node)
3619 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3620 (let ((type (js2-node-type node)))
3621 (or (eq type js2-THIS) (eq type js2-SUPER))))
3622
3623 (cl-defstruct (js2-new-node
3624 (:include js2-node)
3625 (:constructor nil)
3626 (:constructor make-js2-new-node (&key (type js2-NEW)
3627 (pos (js2-current-token-beg))
3628 len target
3629 args initializer
3630 lp rp)))
3631 "AST node for new-expression such as new Foo()."
3632 target ; an identifier or reference
3633 args ; a Lisp list of argument nodes
3634 lp ; position of left-paren, nil if omitted
3635 rp ; position of right-paren, nil if omitted
3636 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3637
3638 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3639 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3640
3641 (defun js2-visit-new-node (n v)
3642 (js2-visit-ast (js2-new-node-target n) v)
3643 (dolist (arg (js2-new-node-args n))
3644 (js2-visit-ast arg v))
3645 (js2-visit-ast (js2-new-node-initializer n) v))
3646
3647 (defun js2-print-new-node (n i)
3648 (insert (js2-make-pad i) "new ")
3649 (js2-print-ast (js2-new-node-target n))
3650 (insert "(")
3651 (js2-print-list (js2-new-node-args n))
3652 (insert ")")
3653 (when (js2-new-node-initializer n)
3654 (insert " ")
3655 (js2-print-ast (js2-new-node-initializer n))))
3656
3657 (cl-defstruct (js2-name-node
3658 (:include js2-node)
3659 (:constructor nil)
3660 (:constructor make-js2-name-node (&key (type js2-NAME)
3661 (pos (js2-current-token-beg))
3662 (len (- js2-ts-cursor
3663 (js2-current-token-beg)))
3664 (name (js2-current-token-string)))))
3665 "AST node for a JavaScript identifier"
3666 name ; a string
3667 scope) ; a `js2-scope' (optional, used for codegen)
3668
3669 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3670 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3671
3672 (defun js2-print-name-node (n i)
3673 (insert (js2-make-pad i)
3674 (js2-name-node-name n)))
3675
3676 (defsubst js2-name-node-length (node)
3677 "Return identifier length of NODE, a `js2-name-node'.
3678 Returns 0 if NODE is nil or its identifier field is nil."
3679 (if node
3680 (length (js2-name-node-name node))
3681 0))
3682
3683 (cl-defstruct (js2-number-node
3684 (:include js2-node)
3685 (:constructor nil)
3686 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3687 (pos (js2-current-token-beg))
3688 (len (- js2-ts-cursor
3689 (js2-current-token-beg)))
3690 (value (js2-current-token-string))
3691 (num-value (js2-token-number
3692 (js2-current-token)))
3693 (num-base (js2-token-number-base
3694 (js2-current-token))))))
3695 "AST node for a number literal."
3696 value ; the original string, e.g. "6.02e23"
3697 num-value ; the parsed number value
3698 num-base) ; the number's base
3699
3700 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3701 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3702
3703 (defun js2-print-number-node (n i)
3704 (insert (js2-make-pad i)
3705 (number-to-string (js2-number-node-num-value n))))
3706
3707 (cl-defstruct (js2-regexp-node
3708 (:include js2-node)
3709 (:constructor nil)
3710 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3711 (pos (js2-current-token-beg))
3712 (len (- js2-ts-cursor
3713 (js2-current-token-beg)))
3714 value flags)))
3715 "AST node for a regular expression literal."
3716 value ; the regexp string, without // delimiters
3717 flags) ; a string of flags, e.g. `mi'.
3718
3719 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3720 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3721
3722 (defun js2-print-regexp (n i)
3723 (insert (js2-make-pad i)
3724 "/"
3725 (js2-regexp-node-value n)
3726 "/")
3727 (if (js2-regexp-node-flags n)
3728 (insert (js2-regexp-node-flags n))))
3729
3730 (cl-defstruct (js2-string-node
3731 (:include js2-node)
3732 (:constructor nil)
3733 (:constructor make-js2-string-node (&key (type js2-STRING)
3734 (pos (js2-current-token-beg))
3735 (len (- js2-ts-cursor
3736 (js2-current-token-beg)))
3737 (value (js2-current-token-string)))))
3738 "String literal.
3739 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3740 You can tell the quote type by looking at the first character."
3741 value) ; the characters of the string, including the quotes
3742
3743 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3744 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3745
3746 (defun js2-print-string-node (n i)
3747 (insert (js2-make-pad i)
3748 (js2-node-string n)))
3749
3750 (cl-defstruct (js2-template-node
3751 (:include js2-node)
3752 (:constructor nil)
3753 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3754 beg len kids)))
3755 "Template literal."
3756 kids) ; `js2-string-node' is used for string segments, other nodes
3757 ; for substitutions inside.
3758
3759 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3760 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3761
3762 (defun js2-visit-template (n callback)
3763 (dolist (kid (js2-template-node-kids n))
3764 (js2-visit-ast kid callback)))
3765
3766 (defun js2-print-template (n i)
3767 (insert (js2-make-pad i))
3768 (dolist (kid (js2-template-node-kids n))
3769 (if (js2-string-node-p kid)
3770 (insert (js2-node-string kid))
3771 (js2-print-ast kid))))
3772
3773 (cl-defstruct (js2-tagged-template-node
3774 (:include js2-node)
3775 (:constructor nil)
3776 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3777 beg len tag template)))
3778 "Tagged template literal."
3779 tag ; `js2-node' with the tag expression.
3780 template) ; `js2-template-node' with the template.
3781
3782 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3783 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3784
3785 (defun js2-visit-tagged-template (n callback)
3786 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3787 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3788
3789 (defun js2-print-tagged-template (n i)
3790 (insert (js2-make-pad i))
3791 (js2-print-ast (js2-tagged-template-node-tag n))
3792 (js2-print-ast (js2-tagged-template-node-template n)))
3793
3794 (cl-defstruct (js2-array-node
3795 (:include js2-node)
3796 (:constructor nil)
3797 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3798 (pos js2-ts-cursor)
3799 len elems)))
3800 "AST node for an array literal."
3801 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3802
3803 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3804 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3805
3806 (defun js2-visit-array-node (n v)
3807 (dolist (e (js2-array-node-elems n))
3808 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3809
3810 (defun js2-print-array-node (n i)
3811 (insert (js2-make-pad i) "[")
3812 (let ((elems (js2-array-node-elems n)))
3813 (js2-print-list elems)
3814 (when (and elems (null (car (last elems))))
3815 (insert ",")))
3816 (insert "]"))
3817
3818 (cl-defstruct (js2-class-node
3819 (:include js2-node)
3820 (:constructor nil)
3821 (:constructor make-js2-class-node (&key (type js2-CLASS)
3822 (pos js2-ts-cursor)
3823 (form 'CLASS_STATEMENT)
3824 (name "")
3825 extends len elems)))
3826 "AST node for an class expression.
3827 `elems' is a list of `js2-object-prop-node', and `extends' is an
3828 optional `js2-expr-node'"
3829 form ; CLASS_{STATEMENT|EXPRESSION}
3830 name ; class name (a `js2-node-name', or nil if anonymous)
3831 extends ; class heritage (a `js2-expr-node', or nil if none)
3832 elems)
3833
3834 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3835 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3836
3837 (defun js2-visit-class-node (n v)
3838 (js2-visit-ast (js2-class-node-name n) v)
3839 (js2-visit-ast (js2-class-node-extends n) v)
3840 (dolist (e (js2-class-node-elems n))
3841 (js2-visit-ast e v)))
3842
3843 (defun js2-print-class-node (n i)
3844 (let* ((pad (js2-make-pad i))
3845 (name (js2-class-node-name n))
3846 (extends (js2-class-node-extends n))
3847 (elems (js2-class-node-elems n)))
3848 (insert pad "class")
3849 (when name
3850 (insert " ")
3851 (js2-print-ast name 0))
3852 (when extends
3853 (insert " extends ")
3854 (js2-print-ast extends))
3855 (insert " {")
3856 (dolist (elem elems)
3857 (insert "\n")
3858 (if (js2-node-get-prop elem 'STATIC)
3859 (progn (insert (js2-make-pad (1+ i)) "static ")
3860 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3861 (js2-print-ast elem (1+ i))))
3862 (insert "\n" pad "}")))
3863
3864 (cl-defstruct (js2-object-node
3865 (:include js2-node)
3866 (:constructor nil)
3867 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3868 (pos js2-ts-cursor)
3869 len
3870 elems)))
3871 "AST node for an object literal expression.
3872 `elems' is a list of `js2-object-prop-node'."
3873 elems)
3874
3875 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3876 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3877
3878 (defun js2-visit-object-node (n v)
3879 (dolist (e (js2-object-node-elems n))
3880 (js2-visit-ast e v)))
3881
3882 (defun js2-print-object-node (n i)
3883 (insert (js2-make-pad i) "{")
3884 (js2-print-list (js2-object-node-elems n))
3885 (insert "}"))
3886
3887 (cl-defstruct (js2-computed-prop-name-node
3888 (:include js2-node)
3889 (:constructor nil)
3890 (:constructor make-js2-computed-prop-name-node
3891 (&key
3892 (type js2-LB)
3893 expr
3894 (pos (js2-current-token-beg))
3895 (len (- js2-ts-cursor
3896 (js2-current-token-beg))))))
3897 "AST node for a `ComputedPropertyName'."
3898 expr)
3899
3900 (put 'cl-struct-js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
3901 (put 'cl-struct-js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
3902
3903 (defun js2-visit-computed-prop-name-node (n v)
3904 (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
3905
3906 (defun js2-print-computed-prop-name-node (n i)
3907 (insert (js2-make-pad i) "[")
3908 (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
3909 (insert "]"))
3910
3911 (cl-defstruct (js2-object-prop-node
3912 (:include js2-infix-node)
3913 (:constructor nil)
3914 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3915 (pos js2-ts-cursor)
3916 len left
3917 right op-pos)))
3918 "AST node for an object literal prop:value entry.
3919 The `left' field is the property: a name node, string node,
3920 number node or expression node. The `right' field is a
3921 `js2-node' representing the initializer value. If the property
3922 is abbreviated, the node's `SHORTHAND' property is non-nil and
3923 both fields have the same value.")
3924
3925 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3926 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3927
3928 (defun js2-print-object-prop-node (n i)
3929 (let* ((left (js2-object-prop-node-left n))
3930 (right (js2-object-prop-node-right n)))
3931 (js2-print-ast left i)
3932 (if (not (js2-node-get-prop n 'SHORTHAND))
3933 (progn
3934 (insert ": ")
3935 (js2-print-ast right 0)))))
3936
3937 (cl-defstruct (js2-method-node
3938 (:include js2-infix-node)
3939 (:constructor nil)
3940 (:constructor make-js2-method-node (&key type ; GET, SET, or FUNCTION
3941 (pos js2-ts-cursor)
3942 len left right)))
3943 "AST node for a method in an object literal or a class body.
3944 The `left' field is the `js2-name-node' naming the method.
3945 The `right' field is always an anonymous `js2-function-node' with a node
3946 property `METHOD_TYPE' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3947
3948 (put 'cl-struct-js2-method-node 'js2-visitor 'js2-visit-infix-node)
3949 (put 'cl-struct-js2-method-node 'js2-printer 'js2-print-method)
3950
3951 (defun js2-print-method (n i)
3952 (let* ((pad (js2-make-pad i))
3953 (left (js2-method-node-left n))
3954 (right (js2-method-node-right n)))
3955 (insert pad)
3956 (if (/= (js2-node-type n) js2-FUNCTION)
3957 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3958 (when (and (js2-function-node-p right)
3959 (eq 'STAR (js2-function-node-generator-type right)))
3960 (insert "*"))
3961 (js2-print-ast left 0)
3962 (js2-print-ast right 0)))
3963
3964 (cl-defstruct (js2-prop-get-node
3965 (:include js2-infix-node)
3966 (:constructor nil)
3967 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3968 (pos js2-ts-cursor)
3969 len left right)))
3970 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3971
3972 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3973 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3974
3975 (defun js2-visit-prop-get-node (n v)
3976 (js2-visit-ast (js2-prop-get-node-left n) v)
3977 (js2-visit-ast (js2-prop-get-node-right n) v))
3978
3979 (defun js2-print-prop-get-node (n i)
3980 (insert (js2-make-pad i))
3981 (js2-print-ast (js2-prop-get-node-left n) 0)
3982 (insert ".")
3983 (js2-print-ast (js2-prop-get-node-right n) 0))
3984
3985 (cl-defstruct (js2-elem-get-node
3986 (:include js2-node)
3987 (:constructor nil)
3988 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3989 (pos js2-ts-cursor)
3990 len target element
3991 lb rb)))
3992 "AST node for an array index expression such as foo[bar]."
3993 target ; a `js2-node' - the expression preceding the "."
3994 element ; a `js2-node' - the expression in brackets
3995 lb ; position of left-bracket, nil if omitted
3996 rb) ; position of right-bracket, nil if omitted
3997
3998 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3999 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4000
4001 (defun js2-visit-elem-get-node (n v)
4002 (js2-visit-ast (js2-elem-get-node-target n) v)
4003 (js2-visit-ast (js2-elem-get-node-element n) v))
4004
4005 (defun js2-print-elem-get-node (n i)
4006 (insert (js2-make-pad i))
4007 (js2-print-ast (js2-elem-get-node-target n) 0)
4008 (insert "[")
4009 (js2-print-ast (js2-elem-get-node-element n) 0)
4010 (insert "]"))
4011
4012 (cl-defstruct (js2-call-node
4013 (:include js2-node)
4014 (:constructor nil)
4015 (:constructor make-js2-call-node (&key (type js2-CALL)
4016 (pos js2-ts-cursor)
4017 len target args
4018 lp rp)))
4019 "AST node for a JavaScript function call."
4020 target ; a `js2-node' evaluating to the function to call
4021 args ; a Lisp list of `js2-node' arguments
4022 lp ; position of open-paren, or nil if missing
4023 rp) ; position of close-paren, or nil if missing
4024
4025 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4026 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4027
4028 (defun js2-visit-call-node (n v)
4029 (js2-visit-ast (js2-call-node-target n) v)
4030 (dolist (arg (js2-call-node-args n))
4031 (js2-visit-ast arg v)))
4032
4033 (defun js2-print-call-node (n i)
4034 (insert (js2-make-pad i))
4035 (js2-print-ast (js2-call-node-target n) 0)
4036 (insert "(")
4037 (js2-print-list (js2-call-node-args n))
4038 (insert ")"))
4039
4040 (cl-defstruct (js2-yield-node
4041 (:include js2-node)
4042 (:constructor nil)
4043 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4044 (pos js2-ts-cursor)
4045 len value star-p)))
4046 "AST node for yield statement or expression."
4047 star-p ; whether it's yield*
4048 value) ; optional: value to be yielded
4049
4050 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4051 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4052
4053 (defun js2-visit-yield-node (n v)
4054 (js2-visit-ast (js2-yield-node-value n) v))
4055
4056 (defun js2-print-yield-node (n i)
4057 (insert (js2-make-pad i))
4058 (insert "yield")
4059 (when (js2-yield-node-star-p n)
4060 (insert "*"))
4061 (when (js2-yield-node-value n)
4062 (insert " ")
4063 (js2-print-ast (js2-yield-node-value n) 0)))
4064
4065 (cl-defstruct (js2-paren-node
4066 (:include js2-node)
4067 (:constructor nil)
4068 (:constructor make-js2-paren-node (&key (type js2-LP)
4069 (pos js2-ts-cursor)
4070 len expr)))
4071 "AST node for a parenthesized expression.
4072 In particular, used when the parens are syntactically optional,
4073 as opposed to required parens such as those enclosing an if-conditional."
4074 expr) ; `js2-node'
4075
4076 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4077 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4078
4079 (defun js2-visit-paren-node (n v)
4080 (js2-visit-ast (js2-paren-node-expr n) v))
4081
4082 (defun js2-print-paren-node (n i)
4083 (insert (js2-make-pad i))
4084 (insert "(")
4085 (js2-print-ast (js2-paren-node-expr n) 0)
4086 (insert ")"))
4087
4088 (cl-defstruct (js2-comp-node
4089 (:include js2-scope)
4090 (:constructor nil)
4091 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4092 (pos js2-ts-cursor)
4093 len result
4094 loops filters
4095 form)))
4096 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4097 result ; result expression (just after left-bracket)
4098 loops ; a Lisp list of `js2-comp-loop-node'
4099 filters ; a Lisp list of guard/filter expressions
4100 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4101 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4102 )
4103
4104 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4105 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4106
4107 (defun js2-visit-comp-node (n v)
4108 (js2-visit-ast (js2-comp-node-result n) v)
4109 (dolist (l (js2-comp-node-loops n))
4110 (js2-visit-ast l v))
4111 (dolist (f (js2-comp-node-filters n))
4112 (js2-visit-ast f v)))
4113
4114 (defun js2-print-comp-node (n i)
4115 (let ((pad (js2-make-pad i))
4116 (result (js2-comp-node-result n))
4117 (loops (js2-comp-node-loops n))
4118 (filters (js2-comp-node-filters n))
4119 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4120 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4121 (insert pad (if gen-p "(" "["))
4122 (when legacy-p
4123 (js2-print-ast result 0))
4124 (dolist (l loops)
4125 (when legacy-p
4126 (insert " "))
4127 (js2-print-ast l 0)
4128 (unless legacy-p
4129 (insert " ")))
4130 (dolist (f filters)
4131 (when legacy-p
4132 (insert " "))
4133 (insert "if (")
4134 (js2-print-ast f 0)
4135 (insert ")")
4136 (unless legacy-p
4137 (insert " ")))
4138 (unless legacy-p
4139 (js2-print-ast result 0))
4140 (insert (if gen-p ")" "]"))))
4141
4142 (cl-defstruct (js2-comp-loop-node
4143 (:include js2-for-in-node)
4144 (:constructor nil)
4145 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4146 (pos js2-ts-cursor)
4147 len iterator
4148 object in-pos
4149 foreach-p
4150 each-pos
4151 forof-p
4152 lp rp)))
4153 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4154
4155 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4156 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4157
4158 (defun js2-visit-comp-loop (n v)
4159 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4160 (js2-visit-ast (js2-comp-loop-node-object n) v))
4161
4162 (defun js2-print-comp-loop (n _i)
4163 (insert "for ")
4164 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4165 (insert "(")
4166 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4167 (insert (if (js2-comp-loop-node-forof-p n)
4168 " of " " in "))
4169 (js2-print-ast (js2-comp-loop-node-object n) 0)
4170 (insert ")"))
4171
4172 (cl-defstruct (js2-empty-expr-node
4173 (:include js2-node)
4174 (:constructor nil)
4175 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4176 (pos (js2-current-token-beg))
4177 len)))
4178 "AST node for an empty expression.")
4179
4180 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4181 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4182
4183 (cl-defstruct (js2-xml-node
4184 (:include js2-block-node)
4185 (:constructor nil)
4186 (:constructor make-js2-xml-node (&key (type js2-XML)
4187 (pos (js2-current-token-beg))
4188 len kids)))
4189 "AST node for initial parse of E4X literals.
4190 The kids field is a list of XML fragments, each a `js2-string-node' or
4191 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4192
4193 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4194 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4195
4196 (defun js2-print-xml-node (n i)
4197 (dolist (kid (js2-xml-node-kids n))
4198 (js2-print-ast kid i)))
4199
4200 (cl-defstruct (js2-xml-js-expr-node
4201 (:include js2-xml-node)
4202 (:constructor nil)
4203 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4204 (pos js2-ts-cursor)
4205 len expr)))
4206 "AST node for an embedded JavaScript {expression} in an E4X literal.
4207 The start and end fields correspond to the curly-braces."
4208 expr) ; a `js2-expr-node' of some sort
4209
4210 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4211 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4212
4213 (defun js2-visit-xml-js-expr (n v)
4214 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4215
4216 (defun js2-print-xml-js-expr (n i)
4217 (insert (js2-make-pad i))
4218 (insert "{")
4219 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4220 (insert "}"))
4221
4222 (cl-defstruct (js2-xml-dot-query-node
4223 (:include js2-infix-node)
4224 (:constructor nil)
4225 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4226 (pos js2-ts-cursor)
4227 op-pos len left
4228 right rp)))
4229 "AST node for an E4X foo.(bar) filter expression.
4230 Note that the left-paren is automatically the character immediately
4231 following the dot (.) in the operator. No whitespace is permitted
4232 between the dot and the lp by the scanner."
4233 rp)
4234
4235 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4236 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4237
4238 (defun js2-print-xml-dot-query (n i)
4239 (insert (js2-make-pad i))
4240 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4241 (insert ".(")
4242 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4243 (insert ")"))
4244
4245 (cl-defstruct (js2-xml-ref-node
4246 (:include js2-node)
4247 (:constructor nil)) ; abstract
4248 "Base type for E4X XML attribute-access or property-get expressions.
4249 Such expressions can take a variety of forms. The general syntax has
4250 three parts:
4251
4252 - (optional) an @ (specifying an attribute access)
4253 - (optional) a namespace (a `js2-name-node') and double-colon
4254 - (required) either a `js2-name-node' or a bracketed [expression]
4255
4256 The property-name expressions (examples: ns::name, @name) are
4257 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4258 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4259
4260 This node type (or more specifically, its subclasses) will sometimes
4261 be the right-hand child of a `js2-prop-get-node' or a
4262 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4263 The `js2-xml-ref-node' may also be a standalone primary expression with
4264 no explicit target, which is valid in certain expression contexts such as
4265
4266 company..employee.(@id < 100)
4267
4268 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4269 expression whose parent is a `js2-xml-dot-query-node'."
4270 namespace
4271 at-pos
4272 colon-pos)
4273
4274 (defsubst js2-xml-ref-node-attr-access-p (node)
4275 "Return non-nil if this expression began with an @-token."
4276 (and (numberp (js2-xml-ref-node-at-pos node))
4277 (cl-plusp (js2-xml-ref-node-at-pos node))))
4278
4279 (cl-defstruct (js2-xml-prop-ref-node
4280 (:include js2-xml-ref-node)
4281 (:constructor nil)
4282 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4283 (pos (js2-current-token-beg))
4284 len propname
4285 namespace at-pos
4286 colon-pos)))
4287 "AST node for an E4X XML [expr] property-ref expression.
4288 The JavaScript syntax is an optional @, an optional ns::, and a name.
4289
4290 [ '@' ] [ name '::' ] name
4291
4292 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4293 @ns::*, @*::attr, @*::*, and @*.
4294
4295 The node starts at the @ token, if present. Otherwise it starts at the
4296 namespace name. The node bounds extend through the closing right-bracket,
4297 or if it is missing due to a syntax error, through the end of the index
4298 expression."
4299 propname)
4300
4301 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4302 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4303
4304 (defun js2-visit-xml-prop-ref-node (n v)
4305 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4306 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4307
4308 (defun js2-print-xml-prop-ref-node (n i)
4309 (insert (js2-make-pad i))
4310 (if (js2-xml-ref-node-attr-access-p n)
4311 (insert "@"))
4312 (when (js2-xml-prop-ref-node-namespace n)
4313 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4314 (insert "::"))
4315 (if (js2-xml-prop-ref-node-propname n)
4316 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4317
4318 (cl-defstruct (js2-xml-elem-ref-node
4319 (:include js2-xml-ref-node)
4320 (:constructor nil)
4321 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4322 (pos (js2-current-token-beg))
4323 len expr lb rb
4324 namespace at-pos
4325 colon-pos)))
4326 "AST node for an E4X XML [expr] member-ref expression.
4327 Syntax:
4328
4329 [ '@' ] [ name '::' ] '[' expr ']'
4330
4331 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4332
4333 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4334 is not a legal E4X XML element-ref expression, since it's already used
4335 for standard JavaScript element-get array indexing. Hence, a
4336 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4337 non-nil namespace node, or both.
4338
4339 The node starts at the @ token, if present. Otherwise it starts
4340 at the namespace name. The node bounds extend through the closing
4341 right-bracket, or if it is missing due to a syntax error, through the
4342 end of the index expression."
4343 expr ; the bracketed index expression
4344 lb
4345 rb)
4346
4347 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4348 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4349
4350 (defun js2-visit-xml-elem-ref-node (n v)
4351 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4352 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4353
4354 (defun js2-print-xml-elem-ref-node (n i)
4355 (insert (js2-make-pad i))
4356 (if (js2-xml-ref-node-attr-access-p n)
4357 (insert "@"))
4358 (when (js2-xml-elem-ref-node-namespace n)
4359 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4360 (insert "::"))
4361 (insert "[")
4362 (if (js2-xml-elem-ref-node-expr n)
4363 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4364 (insert "]"))
4365
4366 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4367
4368 (cl-defstruct (js2-xml-start-tag-node
4369 (:include js2-xml-node)
4370 (:constructor nil)
4371 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4372 (pos js2-ts-cursor)
4373 len name attrs kids
4374 empty-p)))
4375 "AST node for an XML start-tag. Not currently used.
4376 The `kids' field is a Lisp list of child content nodes."
4377 name ; a `js2-xml-name-node'
4378 attrs ; a Lisp list of `js2-xml-attr-node'
4379 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4380
4381 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4382 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4383
4384 (defun js2-visit-xml-start-tag (n v)
4385 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4386 (dolist (attr (js2-xml-start-tag-node-attrs n))
4387 (js2-visit-ast attr v))
4388 (js2-visit-block n v))
4389
4390 (defun js2-print-xml-start-tag (n i)
4391 (insert (js2-make-pad i) "<")
4392 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4393 (when (js2-xml-start-tag-node-attrs n)
4394 (insert " ")
4395 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4396 (insert ">"))
4397
4398 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4399 ;; and add the end-tag to the kids list of the parent as well.
4400 (cl-defstruct (js2-xml-end-tag-node
4401 (:include js2-xml-node)
4402 (:constructor nil)
4403 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4404 (pos js2-ts-cursor)
4405 len name)))
4406 "AST node for an XML end-tag. Not currently used."
4407 name) ; a `js2-xml-name-node'
4408
4409 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4410 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4411
4412 (defun js2-visit-xml-end-tag (n v)
4413 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4414
4415 (defun js2-print-xml-end-tag (n i)
4416 (insert (js2-make-pad i))
4417 (insert "</")
4418 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4419 (insert ">"))
4420
4421 (cl-defstruct (js2-xml-name-node
4422 (:include js2-xml-node)
4423 (:constructor nil)
4424 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4425 (pos js2-ts-cursor)
4426 len namespace kids)))
4427 "AST node for an E4X XML name. Not currently used.
4428 Any XML name can be qualified with a namespace, hence the namespace field.
4429 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4430 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4431 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4432 namespace) ; a `js2-string-node'
4433
4434 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4435 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4436
4437 (defun js2-visit-xml-name-node (n v)
4438 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4439
4440 (defun js2-print-xml-name-node (n i)
4441 (insert (js2-make-pad i))
4442 (when (js2-xml-name-node-namespace n)
4443 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4444 (insert "::"))
4445 (dolist (kid (js2-xml-name-node-kids n))
4446 (js2-print-ast kid 0)))
4447
4448 (cl-defstruct (js2-xml-pi-node
4449 (:include js2-xml-node)
4450 (:constructor nil)
4451 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4452 (pos js2-ts-cursor)
4453 len name attrs)))
4454 "AST node for an E4X XML processing instruction. Not currently used."
4455 name ; a `js2-xml-name-node'
4456 attrs) ; a list of `js2-xml-attr-node'
4457
4458 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4459 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4460
4461 (defun js2-visit-xml-pi-node (n v)
4462 (js2-visit-ast (js2-xml-pi-node-name n) v)
4463 (dolist (attr (js2-xml-pi-node-attrs n))
4464 (js2-visit-ast attr v)))
4465
4466 (defun js2-print-xml-pi-node (n i)
4467 (insert (js2-make-pad i) "<?")
4468 (js2-print-ast (js2-xml-pi-node-name n))
4469 (when (js2-xml-pi-node-attrs n)
4470 (insert " ")
4471 (js2-print-list (js2-xml-pi-node-attrs n)))
4472 (insert "?>"))
4473
4474 (cl-defstruct (js2-xml-cdata-node
4475 (:include js2-xml-node)
4476 (:constructor nil)
4477 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4478 (pos js2-ts-cursor)
4479 len content)))
4480 "AST node for a CDATA escape section. Not currently used."
4481 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4482
4483 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4484 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4485
4486 (defun js2-visit-xml-cdata-node (n v)
4487 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4488
4489 (defun js2-print-xml-cdata-node (n i)
4490 (insert (js2-make-pad i))
4491 (js2-print-ast (js2-xml-cdata-node-content n)))
4492
4493 (cl-defstruct (js2-xml-attr-node
4494 (:include js2-xml-node)
4495 (:constructor nil)
4496 (:constructor make-js2-attr-node (&key (type js2-XML)
4497 (pos js2-ts-cursor)
4498 len name value
4499 eq-pos quote-type)))
4500 "AST node representing a foo='bar' XML attribute value. Not yet used."
4501 name ; a `js2-xml-name-node'
4502 value ; a `js2-xml-name-node'
4503 eq-pos ; buffer position of "=" sign
4504 quote-type) ; 'single or 'double
4505
4506 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4507 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4508
4509 (defun js2-visit-xml-attr-node (n v)
4510 (js2-visit-ast (js2-xml-attr-node-name n) v)
4511 (js2-visit-ast (js2-xml-attr-node-value n) v))
4512
4513 (defun js2-print-xml-attr-node (n i)
4514 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4515 "'"
4516 "\"")))
4517 (insert (js2-make-pad i))
4518 (js2-print-ast (js2-xml-attr-node-name n) 0)
4519 (insert "=" quote)
4520 (js2-print-ast (js2-xml-attr-node-value n) 0)
4521 (insert quote)))
4522
4523 (cl-defstruct (js2-xml-text-node
4524 (:include js2-xml-node)
4525 (:constructor nil)
4526 (:constructor make-js2-text-node (&key (type js2-XML)
4527 (pos js2-ts-cursor)
4528 len content)))
4529 "AST node for an E4X XML text node. Not currently used."
4530 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4531
4532 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4533 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4534
4535 (defun js2-visit-xml-text-node (n v)
4536 (js2-visit-ast (js2-xml-text-node-content n) v))
4537
4538 (defun js2-print-xml-text-node (n i)
4539 (insert (js2-make-pad i))
4540 (dolist (kid (js2-xml-text-node-content n))
4541 (js2-print-ast kid)))
4542
4543 (cl-defstruct (js2-xml-comment-node
4544 (:include js2-xml-node)
4545 (:constructor nil)
4546 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4547 (pos js2-ts-cursor)
4548 len)))
4549 "AST node for E4X XML comment. Not currently used.")
4550
4551 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4552 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4553
4554 (defun js2-print-xml-comment (n i)
4555 (insert (js2-make-pad i)
4556 (js2-node-string n)))
4557
4558 ;;; Node utilities
4559
4560 (defsubst js2-node-line (n)
4561 "Fetch the source line number at the start of node N.
4562 This is O(n) in the length of the source buffer; use prudently."
4563 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4564
4565 (defsubst js2-block-node-kid (n i)
4566 "Return child I of node N, or nil if there aren't that many."
4567 (nth i (js2-block-node-kids n)))
4568
4569 (defsubst js2-block-node-first (n)
4570 "Return first child of block node N, or nil if there is none."
4571 (cl-first (js2-block-node-kids n)))
4572
4573 (defun js2-node-root (n)
4574 "Return the root of the AST containing N.
4575 If N has no parent pointer, returns N."
4576 (let ((parent (js2-node-parent n)))
4577 (if parent
4578 (js2-node-root parent)
4579 n)))
4580
4581 (defsubst js2-node-short-name (n)
4582 "Return the short name of node N as a string, e.g. `js2-if-node'."
4583 (substring (symbol-name (aref n 0))
4584 (length "cl-struct-")))
4585
4586 (defun js2-node-child-list (node)
4587 "Return the child list for NODE, a Lisp list of nodes.
4588 Works for block nodes, array nodes, obj literals, funarg lists,
4589 var decls and try nodes (for catch clauses). Note that you should call
4590 `js2-block-node-kids' on the function body for the body statements.
4591 Returns nil for zero-length child lists or unsupported nodes."
4592 (cond
4593 ((js2-function-node-p node)
4594 (js2-function-node-params node))
4595 ((js2-block-node-p node)
4596 (js2-block-node-kids node))
4597 ((js2-try-node-p node)
4598 (js2-try-node-catch-clauses node))
4599 ((js2-array-node-p node)
4600 (js2-array-node-elems node))
4601 ((js2-object-node-p node)
4602 (js2-object-node-elems node))
4603 ((js2-call-node-p node)
4604 (js2-call-node-args node))
4605 ((js2-new-node-p node)
4606 (js2-new-node-args node))
4607 ((js2-var-decl-node-p node)
4608 (js2-var-decl-node-kids node))
4609 (t
4610 nil)))
4611
4612 (defun js2-node-set-child-list (node kids)
4613 "Set the child list for NODE to KIDS."
4614 (cond
4615 ((js2-function-node-p node)
4616 (setf (js2-function-node-params node) kids))
4617 ((js2-block-node-p node)
4618 (setf (js2-block-node-kids node) kids))
4619 ((js2-try-node-p node)
4620 (setf (js2-try-node-catch-clauses node) kids))
4621 ((js2-array-node-p node)
4622 (setf (js2-array-node-elems node) kids))
4623 ((js2-object-node-p node)
4624 (setf (js2-object-node-elems node) kids))
4625 ((js2-call-node-p node)
4626 (setf (js2-call-node-args node) kids))
4627 ((js2-new-node-p node)
4628 (setf (js2-new-node-args node) kids))
4629 ((js2-var-decl-node-p node)
4630 (setf (js2-var-decl-node-kids node) kids))
4631 (t
4632 (error "Unsupported node type: %s" (js2-node-short-name node))))
4633 kids)
4634
4635 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4636 (defconst js2-paren-expr-nodes
4637 '(cl-struct-js2-comp-loop-node
4638 cl-struct-js2-comp-node
4639 cl-struct-js2-call-node
4640 cl-struct-js2-catch-node
4641 cl-struct-js2-do-node
4642 cl-struct-js2-elem-get-node
4643 cl-struct-js2-for-in-node
4644 cl-struct-js2-for-node
4645 cl-struct-js2-function-node
4646 cl-struct-js2-if-node
4647 cl-struct-js2-let-node
4648 cl-struct-js2-new-node
4649 cl-struct-js2-paren-node
4650 cl-struct-js2-switch-node
4651 cl-struct-js2-while-node
4652 cl-struct-js2-with-node
4653 cl-struct-js2-xml-dot-query-node)
4654 "Node types that can have a parenthesized child expression.
4655 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4656
4657 (defsubst js2-paren-expr-node-p (node)
4658 "Return t for nodes that typically have a parenthesized child expression.
4659 Useful for computing the indentation anchors for arg-lists and conditions.
4660 Note that it may return a false positive, for instance when NODE is
4661 a `js2-new-node' and there are no arguments or parentheses."
4662 (memq (aref node 0) js2-paren-expr-nodes))
4663
4664 ;; Fake polymorphism... yech.
4665 (defun js2-node-lp (node)
4666 "Return relative left-paren position for NODE, if applicable.
4667 For `js2-elem-get-node' structs, returns left-bracket position.
4668 Note that the position may be nil in the case of a parse error."
4669 (cond
4670 ((js2-elem-get-node-p node)
4671 (js2-elem-get-node-lb node))
4672 ((js2-loop-node-p node)
4673 (js2-loop-node-lp node))
4674 ((js2-function-node-p node)
4675 (js2-function-node-lp node))
4676 ((js2-if-node-p node)
4677 (js2-if-node-lp node))
4678 ((js2-new-node-p node)
4679 (js2-new-node-lp node))
4680 ((js2-call-node-p node)
4681 (js2-call-node-lp node))
4682 ((js2-paren-node-p node)
4683 0)
4684 ((js2-switch-node-p node)
4685 (js2-switch-node-lp node))
4686 ((js2-catch-node-p node)
4687 (js2-catch-node-lp node))
4688 ((js2-let-node-p node)
4689 (js2-let-node-lp node))
4690 ((js2-comp-node-p node)
4691 0)
4692 ((js2-with-node-p node)
4693 (js2-with-node-lp node))
4694 ((js2-xml-dot-query-node-p node)
4695 (1+ (js2-infix-node-op-pos node)))
4696 (t
4697 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4698
4699 ;; Fake polymorphism... blech.
4700 (defun js2-node-rp (node)
4701 "Return relative right-paren position for NODE, if applicable.
4702 For `js2-elem-get-node' structs, returns right-bracket position.
4703 Note that the position may be nil in the case of a parse error."
4704 (cond
4705 ((js2-elem-get-node-p node)
4706 (js2-elem-get-node-rb node))
4707 ((js2-loop-node-p node)
4708 (js2-loop-node-rp node))
4709 ((js2-function-node-p node)
4710 (js2-function-node-rp node))
4711 ((js2-if-node-p node)
4712 (js2-if-node-rp node))
4713 ((js2-new-node-p node)
4714 (js2-new-node-rp node))
4715 ((js2-call-node-p node)
4716 (js2-call-node-rp node))
4717 ((js2-paren-node-p node)
4718 (1- (js2-node-len node)))
4719 ((js2-switch-node-p node)
4720 (js2-switch-node-rp node))
4721 ((js2-catch-node-p node)
4722 (js2-catch-node-rp node))
4723 ((js2-let-node-p node)
4724 (js2-let-node-rp node))
4725 ((js2-comp-node-p node)
4726 (1- (js2-node-len node)))
4727 ((js2-with-node-p node)
4728 (js2-with-node-rp node))
4729 ((js2-xml-dot-query-node-p node)
4730 (1+ (js2-xml-dot-query-node-rp node)))
4731 (t
4732 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4733
4734 (defsubst js2-node-first-child (node)
4735 "Return the first element of `js2-node-child-list' for NODE."
4736 (car (js2-node-child-list node)))
4737
4738 (defsubst js2-node-last-child (node)
4739 "Return the last element of `js2-node-last-child' for NODE."
4740 (car (last (js2-node-child-list node))))
4741
4742 (defun js2-node-prev-sibling (node)
4743 "Return the previous statement in parent.
4744 Works for parents supported by `js2-node-child-list'.
4745 Returns nil if NODE is not in the parent, or PARENT is
4746 not a supported node, or if NODE is the first child."
4747 (let* ((p (js2-node-parent node))
4748 (kids (js2-node-child-list p))
4749 (sib (car kids)))
4750 (while (and kids
4751 (not (eq node (cadr kids))))
4752 (setq kids (cdr kids)
4753 sib (car kids)))
4754 sib))
4755
4756 (defun js2-node-next-sibling (node)
4757 "Return the next statement in parent block.
4758 Returns nil if NODE is not in the block, or PARENT is not
4759 a block node, or if NODE is the last statement."
4760 (let* ((p (js2-node-parent node))
4761 (kids (js2-node-child-list p)))
4762 (while (and kids
4763 (not (eq node (car kids))))
4764 (setq kids (cdr kids)))
4765 (cadr kids)))
4766
4767 (defun js2-node-find-child-before (pos parent &optional after)
4768 "Find the last child that starts before POS in parent.
4769 If AFTER is non-nil, returns first child starting after POS.
4770 POS is an absolute buffer position. PARENT is any node
4771 supported by `js2-node-child-list'.
4772 Returns nil if no applicable child is found."
4773 (let ((kids (if (js2-function-node-p parent)
4774 (js2-block-node-kids (js2-function-node-body parent))
4775 (js2-node-child-list parent)))
4776 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4777 (js2-function-node-body parent)
4778 parent)))
4779 kid result fn
4780 (continue t))
4781 (setq fn (if after '>= '<))
4782 (while (and kids continue)
4783 (setq kid (car kids))
4784 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4785 (setq result kid
4786 continue (not after))
4787 (setq continue after))
4788 (setq kids (cdr kids)))
4789 result))
4790
4791 (defun js2-node-find-child-after (pos parent)
4792 "Find first child that starts after POS in parent.
4793 POS is an absolute buffer position. PARENT is any node
4794 supported by `js2-node-child-list'.
4795 Returns nil if no applicable child is found."
4796 (js2-node-find-child-before pos parent 'after))
4797
4798 (defun js2-node-replace-child (pos parent new-node)
4799 "Replace node at index POS in PARENT with NEW-NODE.
4800 Only works for parents supported by `js2-node-child-list'."
4801 (let ((kids (js2-node-child-list parent))
4802 (i 0))
4803 (while (< i pos)
4804 (setq kids (cdr kids)
4805 i (1+ i)))
4806 (setcar kids new-node)
4807 (js2-node-add-children parent new-node)))
4808
4809 (defun js2-node-buffer (n)
4810 "Return the buffer associated with AST N.
4811 Returns nil if the buffer is not set as a property on the root
4812 node, or if parent links were not recorded during parsing."
4813 (let ((root (js2-node-root n)))
4814 (and root
4815 (js2-ast-root-p root)
4816 (js2-ast-root-buffer root))))
4817
4818 (defun js2-block-node-push (n kid)
4819 "Push js2-node KID onto the end of js2-block-node N's child list.
4820 KID is always added to the -end- of the kids list.
4821 Function also calls `js2-node-add-children' to add the parent link."
4822 (let ((kids (js2-node-child-list n)))
4823 (if kids
4824 (setcdr kids (nconc (cdr kids) (list kid)))
4825 (js2-node-set-child-list n (list kid)))
4826 (js2-node-add-children n kid)))
4827
4828 (defun js2-node-string (node)
4829 (with-current-buffer (or (js2-node-buffer node)
4830 (error "No buffer available for node %s" node))
4831 (let ((pos (js2-node-abs-pos node)))
4832 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4833
4834 ;; Container for storing the node we're looking for in a traversal.
4835 (js2-deflocal js2-discovered-node nil)
4836
4837 ;; Keep track of absolute node position during traversals.
4838 (js2-deflocal js2-visitor-offset nil)
4839
4840 (js2-deflocal js2-node-search-point nil)
4841
4842 (when js2-mode-dev-mode-p
4843 (defun js2-find-node-at-point ()
4844 (interactive)
4845 (let ((node (js2-node-at-point)))
4846 (message "%s" (or node "No node found at point"))))
4847 (defun js2-node-name-at-point ()
4848 (interactive)
4849 (let ((node (js2-node-at-point)))
4850 (message "%s" (if node
4851 (js2-node-short-name node)
4852 "No node found at point.")))))
4853
4854 (defun js2-node-at-point (&optional pos skip-comments)
4855 "Return AST node at POS, a buffer position, defaulting to current point.
4856 The `js2-mode-ast' variable must be set to the current parse tree.
4857 Signals an error if the AST (`js2-mode-ast') is nil.
4858 Always returns a node - if it can't find one, it returns the root.
4859 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4860 (let ((ast js2-mode-ast)
4861 result)
4862 (unless ast
4863 (error "No JavaScript AST available"))
4864 ;; Look through comments first, since they may be inside nodes that
4865 ;; would otherwise report a match.
4866 (setq pos (or pos (point))
4867 result (if (> pos (js2-node-abs-end ast))
4868 ast
4869 (if (not skip-comments)
4870 (js2-comment-at-point pos))))
4871 (unless result
4872 (setq js2-discovered-node nil
4873 js2-visitor-offset 0
4874 js2-node-search-point pos)
4875 (unwind-protect
4876 (catch 'js2-visit-done
4877 (js2-visit-ast ast #'js2-node-at-point-visitor))
4878 (setq js2-visitor-offset nil
4879 js2-node-search-point nil))
4880 (setq result js2-discovered-node))
4881 ;; may have found a comment beyond end of last child node,
4882 ;; since visiting the ast-root looks at the comment-list last.
4883 (if (and skip-comments
4884 (js2-comment-node-p result))
4885 (setq result nil))
4886 (or result js2-mode-ast)))
4887
4888 (defun js2-node-at-point-visitor (node end-p)
4889 (let ((rel-pos (js2-node-pos node))
4890 abs-pos
4891 abs-end
4892 (point js2-node-search-point))
4893 (cond
4894 (end-p
4895 ;; this evaluates to a non-nil return value, even if it's zero
4896 (cl-decf js2-visitor-offset rel-pos))
4897 ;; we already looked for comments before visiting, and don't want them now
4898 ((js2-comment-node-p node)
4899 nil)
4900 (t
4901 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4902 ;; we only want to use the node if the point is before
4903 ;; the last character position in the node, so we decrement
4904 ;; the absolute end by 1.
4905 abs-end (+ abs-pos (js2-node-len node) -1))
4906 (cond
4907 ;; If this node starts after search-point, stop the search.
4908 ((> abs-pos point)
4909 (throw 'js2-visit-done nil))
4910 ;; If this node ends before the search-point, don't check kids.
4911 ((> point abs-end)
4912 nil)
4913 (t
4914 ;; Otherwise point is within this node, possibly in a child.
4915 (setq js2-discovered-node node)
4916 t)))))) ; keep processing kids to look for more specific match
4917
4918 (defsubst js2-block-comment-p (node)
4919 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4920 (and (js2-comment-node-p node)
4921 (memq (js2-comment-node-format node) '(jsdoc block))))
4922
4923 ;; TODO: put the comments in a vector and binary-search them instead
4924 (defun js2-comment-at-point (&optional pos)
4925 "Look through scanned comment nodes for one containing POS.
4926 POS is a buffer position that defaults to current point.
4927 Function returns nil if POS was not in any comment node."
4928 (let ((ast js2-mode-ast)
4929 (x (or pos (point)))
4930 beg end)
4931 (unless ast
4932 (error "No JavaScript AST available"))
4933 (catch 'done
4934 ;; Comments are stored in lexical order.
4935 (dolist (comment (js2-ast-root-comments ast) nil)
4936 (setq beg (js2-node-abs-pos comment)
4937 end (+ beg (js2-node-len comment)))
4938 (if (and (>= x beg)
4939 (<= x end))
4940 (throw 'done comment))))))
4941
4942 (defun js2-mode-find-parent-fn (node)
4943 "Find function enclosing NODE.
4944 Returns nil if NODE is not inside a function."
4945 (setq node (js2-node-parent node))
4946 (while (and node (not (js2-function-node-p node)))
4947 (setq node (js2-node-parent node)))
4948 (and (js2-function-node-p node) node))
4949
4950 (defun js2-mode-find-enclosing-fn (node)
4951 "Find function or root enclosing NODE."
4952 (if (js2-ast-root-p node)
4953 node
4954 (setq node (js2-node-parent node))
4955 (while (not (or (js2-ast-root-p node)
4956 (js2-function-node-p node)))
4957 (setq node (js2-node-parent node)))
4958 node))
4959
4960 (defun js2-mode-find-enclosing-node (beg end)
4961 "Find node fully enclosing BEG and END."
4962 (let ((node (js2-node-at-point beg))
4963 pos
4964 (continue t))
4965 (while continue
4966 (if (or (js2-ast-root-p node)
4967 (and
4968 (<= (setq pos (js2-node-abs-pos node)) beg)
4969 (>= (+ pos (js2-node-len node)) end)))
4970 (setq continue nil)
4971 (setq node (js2-node-parent node))))
4972 node))
4973
4974 (defun js2-node-parent-script-or-fn (node)
4975 "Find script or function immediately enclosing NODE.
4976 If NODE is the ast-root, returns nil."
4977 (if (js2-ast-root-p node)
4978 nil
4979 (setq node (js2-node-parent node))
4980 (while (and node (not (or (js2-function-node-p node)
4981 (js2-script-node-p node))))
4982 (setq node (js2-node-parent node)))
4983 node))
4984
4985 (defun js2-node-is-descendant (node ancestor)
4986 "Return t if NODE is a descendant of ANCESTOR."
4987 (while (and node
4988 (not (eq node ancestor)))
4989 (setq node (js2-node-parent node)))
4990 node)
4991
4992 ;;; visitor infrastructure
4993
4994 (defun js2-visit-none (_node _callback)
4995 "Visitor for AST node that have no node children."
4996 nil)
4997
4998 (defun js2-print-none (_node _indent)
4999 "Visitor for AST node with no printed representation.")
5000
5001 (defun js2-print-body (node indent)
5002 "Print a statement, or a block without braces."
5003 (if (js2-block-node-p node)
5004 (dolist (kid (js2-block-node-kids node))
5005 (js2-print-ast kid indent))
5006 (js2-print-ast node indent)))
5007
5008 (defun js2-print-list (args &optional delimiter)
5009 (cl-loop with len = (length args)
5010 for arg in args
5011 for count from 1
5012 do
5013 (when arg (js2-print-ast arg 0))
5014 (if (< count len)
5015 (insert (or delimiter ", ")))))
5016
5017 (defun js2-print-tree (ast)
5018 "Prints an AST to the current buffer.
5019 Makes `js2-ast-parent-nodes' available to the printer functions."
5020 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5021 (js2-print-ast ast)))
5022
5023 (defun js2-print-ast (node &optional indent)
5024 "Helper function for printing AST nodes.
5025 Requires `js2-ast-parent-nodes' to be non-nil.
5026 You should use `js2-print-tree' instead of this function."
5027 (let ((printer (get (aref node 0) 'js2-printer))
5028 (i (or indent 0)))
5029 ;; TODO: wedge comments in here somewhere
5030 (if printer
5031 (funcall printer node i))))
5032
5033 (defconst js2-side-effecting-tokens
5034 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5035 (dolist (tt (list js2-ASSIGN
5036 js2-ASSIGN_ADD
5037 js2-ASSIGN_BITAND
5038 js2-ASSIGN_BITOR
5039 js2-ASSIGN_BITXOR
5040 js2-ASSIGN_DIV
5041 js2-ASSIGN_LSH
5042 js2-ASSIGN_MOD
5043 js2-ASSIGN_MUL
5044 js2-ASSIGN_RSH
5045 js2-ASSIGN_SUB
5046 js2-ASSIGN_URSH
5047 js2-BLOCK
5048 js2-BREAK
5049 js2-CALL
5050 js2-CATCH
5051 js2-CATCH_SCOPE
5052 js2-CLASS
5053 js2-CONST
5054 js2-CONTINUE
5055 js2-DEBUGGER
5056 js2-DEC
5057 js2-DELPROP
5058 js2-DEL_REF
5059 js2-DO
5060 js2-ELSE
5061 js2-EMPTY
5062 js2-ENTERWITH
5063 js2-EXPORT
5064 js2-EXPR_RESULT
5065 js2-FINALLY
5066 js2-FOR
5067 js2-FUNCTION
5068 js2-GOTO
5069 js2-IF
5070 js2-IFEQ
5071 js2-IFNE
5072 js2-IMPORT
5073 js2-INC
5074 js2-JSR
5075 js2-LABEL
5076 js2-LEAVEWITH
5077 js2-LET
5078 js2-LETEXPR
5079 js2-LOCAL_BLOCK
5080 js2-LOOP
5081 js2-NEW
5082 js2-REF_CALL
5083 js2-RETHROW
5084 js2-RETURN
5085 js2-RETURN_RESULT
5086 js2-SEMI
5087 js2-SETELEM
5088 js2-SETELEM_OP
5089 js2-SETNAME
5090 js2-SETPROP
5091 js2-SETPROP_OP
5092 js2-SETVAR
5093 js2-SET_REF
5094 js2-SET_REF_OP
5095 js2-SWITCH
5096 js2-TARGET
5097 js2-THROW
5098 js2-TRY
5099 js2-VAR
5100 js2-WHILE
5101 js2-WITH
5102 js2-WITHEXPR
5103 js2-YIELD))
5104 (aset tokens tt t))
5105 (if js2-instanceof-has-side-effects
5106 (aset tokens js2-INSTANCEOF t))
5107 tokens))
5108
5109 (defun js2-node-has-side-effects (node)
5110 "Return t if NODE has side effects."
5111 (when node ; makes it easier to handle malformed expressions
5112 (let ((tt (js2-node-type node)))
5113 (cond
5114 ;; This doubtless needs some work, since EXPR_VOID is used
5115 ;; in several ways in Rhino and I may not have caught them all.
5116 ;; I'll wait for people to notice incorrect warnings.
5117 ((and (= tt js2-EXPR_VOID)
5118 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5119 (let ((expr (js2-expr-stmt-node-expr node)))
5120 (or (js2-node-has-side-effects expr)
5121 (when (js2-string-node-p expr)
5122 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5123 ((= tt js2-COMMA)
5124 (js2-node-has-side-effects (js2-infix-node-right node)))
5125 ((or (= tt js2-AND)
5126 (= tt js2-OR))
5127 (or (js2-node-has-side-effects (js2-infix-node-right node))
5128 (js2-node-has-side-effects (js2-infix-node-left node))))
5129 ((= tt js2-HOOK)
5130 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5131 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5132 ((js2-paren-node-p node)
5133 (js2-node-has-side-effects (js2-paren-node-expr node)))
5134 ((= tt js2-ERROR) ; avoid cascaded error messages
5135 nil)
5136 (t
5137 (aref js2-side-effecting-tokens tt))))))
5138
5139 (defconst js2-stmt-node-types
5140 (list js2-BLOCK
5141 js2-BREAK
5142 js2-CONTINUE
5143 js2-DEFAULT ; e4x "default xml namespace" statement
5144 js2-DO
5145 js2-EXPORT
5146 js2-EXPR_RESULT
5147 js2-EXPR_VOID
5148 js2-FOR
5149 js2-IF
5150 js2-IMPORT
5151 js2-RETURN
5152 js2-SWITCH
5153 js2-THROW
5154 js2-TRY
5155 js2-WHILE
5156 js2-WITH)
5157 "Node types that only appear in statement contexts.
5158 The list does not include nodes that always appear as the child
5159 of another specific statement type, such as switch-cases,
5160 catch and finally blocks, and else-clauses. The list also excludes
5161 nodes like yield, let and var, which may appear in either expression
5162 or statement context, and in the latter context always have a
5163 `js2-expr-stmt-node' parent. Finally, the list does not include
5164 functions or scripts, which are treated separately from statements
5165 by the JavaScript parser and runtime.")
5166
5167 (defun js2-stmt-node-p (node)
5168 "Heuristic for figuring out if NODE is a statement.
5169 Some node types can appear in either an expression context or a
5170 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5171 For these node types in a statement context, the parent will be a
5172 `js2-expr-stmt-node'.
5173 Functions aren't included in the check."
5174 (memq (js2-node-type node) js2-stmt-node-types))
5175
5176 (defun js2-mode-find-first-stmt (node)
5177 "Search upward starting from NODE looking for a statement.
5178 For purposes of this function, a `js2-function-node' counts."
5179 (while (not (or (js2-stmt-node-p node)
5180 (js2-function-node-p node)))
5181 (setq node (js2-node-parent node)))
5182 node)
5183
5184 (defun js2-node-parent-stmt (node)
5185 "Return the node's first ancestor that is a statement.
5186 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5187 appearing in a statement context will have a parent that is a
5188 `js2-expr-stmt-node' that will be returned by this function."
5189 (let ((parent (js2-node-parent node)))
5190 (if (or (null parent)
5191 (js2-stmt-node-p parent)
5192 (and (js2-function-node-p parent)
5193 (not (eq (js2-function-node-form parent)
5194 'FUNCTION_EXPRESSION))))
5195 parent
5196 (js2-node-parent-stmt parent))))
5197
5198 ;; In the Mozilla Rhino sources, Roshan James writes:
5199 ;; Does consistent-return analysis on the function body when strict mode is
5200 ;; enabled.
5201 ;;
5202 ;; function (x) { return (x+1) }
5203 ;;
5204 ;; is ok, but
5205 ;;
5206 ;; function (x) { if (x < 0) return (x+1); }
5207 ;;
5208 ;; is not because the function can potentially return a value when the
5209 ;; condition is satisfied and if not, the function does not explicitly
5210 ;; return a value.
5211 ;;
5212 ;; This extends to checking mismatches such as "return" and "return <value>"
5213 ;; used in the same function. Warnings are not emitted if inconsistent
5214 ;; returns exist in code that can be statically shown to be unreachable.
5215 ;; Ex.
5216 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5217 ;;
5218 ;; emits no warning. However if the loop had a break statement, then a
5219 ;; warning would be emitted.
5220 ;;
5221 ;; The consistency analysis looks at control structures such as loops, ifs,
5222 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5223 ;; warns the user about an inconsistent set of termination possibilities.
5224 ;;
5225 ;; These flags enumerate the possible ways a statement/function can
5226 ;; terminate. These flags are used by endCheck() and by the Parser to
5227 ;; detect inconsistent return usage.
5228 ;;
5229 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5230 ;; able to execute (example: throw, continue)
5231 ;;
5232 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5233 ;; next one. Statement such as return dont. A compound statement may have
5234 ;; some branch that drops off control to the next statement.
5235 ;;
5236 ;; END_RETURNS indicates that the statement can return with no value.
5237 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5238 ;;
5239 ;; A compound statement such as
5240 ;; if (condition) {
5241 ;; return value;
5242 ;; }
5243 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5244
5245 (defconst js2-END_UNREACHED 0)
5246 (defconst js2-END_DROPS_OFF 1)
5247 (defconst js2-END_RETURNS 2)
5248 (defconst js2-END_RETURNS_VALUE 4)
5249 (defconst js2-END_YIELDS 8)
5250
5251 (defun js2-has-consistent-return-usage (node)
5252 "Check that every return usage in a function body is consistent.
5253 Returns t if the function satisfies strict mode requirement."
5254 (let ((n (js2-end-check node)))
5255 ;; either it doesn't return a value in any branch...
5256 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5257 ;; or it returns a value (or is unreached) at every branch
5258 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5259 js2-END_RETURNS
5260 js2-END_YIELDS)))))
5261
5262 (defun js2-end-check-if (node)
5263 "Ensure that return usage in then/else blocks is consistent.
5264 If there is no else block, then the return statement can fall through.
5265 Returns logical OR of END_* flags"
5266 (let ((th (js2-if-node-then-part node))
5267 (el (js2-if-node-else-part node)))
5268 (if (null th)
5269 js2-END_UNREACHED
5270 (logior (js2-end-check th) (if el
5271 (js2-end-check el)
5272 js2-END_DROPS_OFF)))))
5273
5274 (defun js2-end-check-switch (node)
5275 "Consistency of return statements is checked between the case statements.
5276 If there is no default, then the switch can fall through. If there is a
5277 default, we check to see if all code paths in the default return or if
5278 there is a code path that can fall through.
5279 Returns logical OR of END_* flags."
5280 (let ((rv js2-END_UNREACHED)
5281 default-case)
5282 ;; examine the cases
5283 (catch 'break
5284 (dolist (c (js2-switch-node-cases node))
5285 (if (js2-case-node-expr c)
5286 (js2-set-flag rv (js2-end-check-block c))
5287 (setq default-case c)
5288 (throw 'break nil))))
5289 ;; we don't care how the cases drop into each other
5290 (js2-clear-flag rv js2-END_DROPS_OFF)
5291 ;; examine the default
5292 (js2-set-flag rv (if default-case
5293 (js2-end-check default-case)
5294 js2-END_DROPS_OFF))
5295 rv))
5296
5297 (defun js2-end-check-try (node)
5298 "If the block has a finally, return consistency is checked in the
5299 finally block. If all code paths in the finally return, then the
5300 returns in the try-catch blocks don't matter. If there is a code path
5301 that does not return or if there is no finally block, the returns
5302 of the try and catch blocks are checked for mismatch.
5303 Returns logical OR of END_* flags."
5304 (let ((finally (js2-try-node-finally-block node))
5305 rv)
5306 ;; check the finally if it exists
5307 (setq rv (if finally
5308 (js2-end-check (js2-finally-node-body finally))
5309 js2-END_DROPS_OFF))
5310 ;; If the finally block always returns, then none of the returns
5311 ;; in the try or catch blocks matter.
5312 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5313 (js2-clear-flag rv js2-END_DROPS_OFF)
5314 ;; examine the try block
5315 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5316 ;; check each catch block
5317 (dolist (cb (js2-try-node-catch-clauses node))
5318 (js2-set-flag rv (js2-end-check cb))))
5319 rv))
5320
5321 (defun js2-end-check-loop (node)
5322 "Return statement in the loop body must be consistent.
5323 The default assumption for any kind of a loop is that it will eventually
5324 terminate. The only exception is a loop with a constant true condition.
5325 Code that follows such a loop is examined only if one can determine
5326 statically that there is a break out of the loop.
5327
5328 for(... ; ... ; ...) {}
5329 for(... in ... ) {}
5330 while(...) { }
5331 do { } while(...)
5332
5333 Returns logical OR of END_* flags."
5334 (let ((rv (js2-end-check (js2-loop-node-body node)))
5335 (condition (cond
5336 ((js2-while-node-p node)
5337 (js2-while-node-condition node))
5338 ((js2-do-node-p node)
5339 (js2-do-node-condition node))
5340 ((js2-for-node-p node)
5341 (js2-for-node-condition node)))))
5342
5343 ;; check to see if the loop condition is always true
5344 (if (and condition
5345 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5346 (js2-clear-flag rv js2-END_DROPS_OFF))
5347
5348 ;; look for effect of breaks
5349 (js2-set-flag rv (js2-node-get-prop node
5350 'CONTROL_BLOCK_PROP
5351 js2-END_UNREACHED))
5352 rv))
5353
5354 (defun js2-end-check-block (node)
5355 "A general block of code is examined statement by statement.
5356 If any statement (even a compound one) returns in all branches, then
5357 subsequent statements are not examined.
5358 Returns logical OR of END_* flags."
5359 (let* ((rv js2-END_DROPS_OFF)
5360 (kids (js2-block-node-kids node))
5361 (n (car kids)))
5362 ;; Check each statement. If the statement can continue onto the next
5363 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5364 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5365 (js2-clear-flag rv js2-END_DROPS_OFF)
5366 (js2-set-flag rv (js2-end-check n))
5367 (setq kids (cdr kids)
5368 n (car kids)))
5369 rv))
5370
5371 (defun js2-end-check-label (node)
5372 "A labeled statement implies that there may be a break to the label.
5373 The function processes the labeled statement and then checks the
5374 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5375 particular label.
5376 Returns logical OR of END_* flags."
5377 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5378 (logior rv (js2-node-get-prop node
5379 'CONTROL_BLOCK_PROP
5380 js2-END_UNREACHED))))
5381
5382 (defun js2-end-check-break (node)
5383 "When a break is encountered annotate the statement being broken
5384 out of by setting its CONTROL_BLOCK_PROP property.
5385 Returns logical OR of END_* flags."
5386 (and (js2-break-node-target node)
5387 (js2-node-set-prop (js2-break-node-target node)
5388 'CONTROL_BLOCK_PROP
5389 js2-END_DROPS_OFF))
5390 js2-END_UNREACHED)
5391
5392 (defun js2-end-check (node)
5393 "Examine the body of a function, doing a basic reachability analysis.
5394 Returns a combination of flags END_* flags that indicate
5395 how the function execution can terminate. These constitute only the
5396 pessimistic set of termination conditions. It is possible that at
5397 runtime certain code paths will never be actually taken. Hence this
5398 analysis will flag errors in cases where there may not be errors.
5399 Returns logical OR of END_* flags"
5400 (let (kid)
5401 (cond
5402 ((js2-break-node-p node)
5403 (js2-end-check-break node))
5404 ((js2-expr-stmt-node-p node)
5405 (if (setq kid (js2-expr-stmt-node-expr node))
5406 (js2-end-check kid)
5407 js2-END_DROPS_OFF))
5408 ((or (js2-continue-node-p node)
5409 (js2-throw-node-p node))
5410 js2-END_UNREACHED)
5411 ((js2-return-node-p node)
5412 (if (setq kid (js2-return-node-retval node))
5413 js2-END_RETURNS_VALUE
5414 js2-END_RETURNS))
5415 ((js2-loop-node-p node)
5416 (js2-end-check-loop node))
5417 ((js2-switch-node-p node)
5418 (js2-end-check-switch node))
5419 ((js2-labeled-stmt-node-p node)
5420 (js2-end-check-label node))
5421 ((js2-if-node-p node)
5422 (js2-end-check-if node))
5423 ((js2-try-node-p node)
5424 (js2-end-check-try node))
5425 ((js2-block-node-p node)
5426 (if (null (js2-block-node-kids node))
5427 js2-END_DROPS_OFF
5428 (js2-end-check-block node)))
5429 ((js2-yield-node-p node)
5430 js2-END_YIELDS)
5431 (t
5432 js2-END_DROPS_OFF))))
5433
5434 (defun js2-always-defined-boolean-p (node)
5435 "Check if NODE always evaluates to true or false in boolean context.
5436 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5437 nor always false."
5438 (let ((tt (js2-node-type node))
5439 num)
5440 (cond
5441 ((or (= tt js2-FALSE) (= tt js2-NULL))
5442 'ALWAYS_FALSE)
5443 ((= tt js2-TRUE)
5444 'ALWAYS_TRUE)
5445 ((= tt js2-NUMBER)
5446 (setq num (js2-number-node-num-value node))
5447 (if (and (not (eq num 0.0e+NaN))
5448 (not (zerop num)))
5449 'ALWAYS_TRUE
5450 'ALWAYS_FALSE))
5451 (t
5452 nil))))
5453
5454 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5455 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5456
5457 (defvar js2-tokens nil
5458 "List of all defined token names.") ; initialized in `js2-token-names'
5459
5460 (defconst js2-token-names
5461 (let* ((names (make-vector js2-num-tokens -1))
5462 (case-fold-search nil) ; only match js2-UPPER_CASE
5463 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5464 (cl-loop for sym in syms
5465 for i from 0
5466 do
5467 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5468 (not (boundp sym)))
5469 (aset names (symbol-value sym) ; code, e.g. 152
5470 (downcase
5471 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5472 (push sym js2-tokens)))
5473 names)
5474 "Vector mapping int values to token string names, sans `js2-' prefix.")
5475
5476 (defun js2-tt-name (tok)
5477 "Return a string name for TOK, a token symbol or code.
5478 Signals an error if it's not a recognized token."
5479 (let ((code tok))
5480 (if (symbolp tok)
5481 (setq code (symbol-value tok)))
5482 (if (eq code -1)
5483 "ERROR"
5484 (if (and (numberp code)
5485 (not (cl-minusp code))
5486 (< code js2-num-tokens))
5487 (aref js2-token-names code)
5488 (error "Invalid token: %s" code)))))
5489
5490 (defsubst js2-tt-sym (tok)
5491 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5492 (intern (js2-tt-name tok)))
5493
5494 (defconst js2-token-codes
5495 (let ((table (make-hash-table :test 'eq :size 256)))
5496 (cl-loop for name across js2-token-names
5497 for sym = (intern (concat "js2-" (upcase name)))
5498 do
5499 (puthash sym (symbol-value sym) table))
5500 ;; clean up a few that are "wrong" in Rhino's token codes
5501 (puthash 'js2-DELETE js2-DELPROP table)
5502 table)
5503 "Hashtable mapping token type symbols to their bytecodes.")
5504
5505 (defsubst js2-tt-code (sym)
5506 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5507 (or (gethash sym js2-token-codes)
5508 (error "Invalid token symbol: %s " sym))) ; signal code bug
5509
5510 (defun js2-report-scan-error (msg &optional no-throw beg len)
5511 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5512 (js2-report-error msg nil
5513 (or beg (js2-current-token-beg))
5514 (or len (js2-current-token-len)))
5515 (unless no-throw
5516 (throw 'return js2-ERROR)))
5517
5518 (defun js2-set-string-from-buffer (token)
5519 "Set `string' and `end' slots for TOKEN, return the string."
5520 (setf (js2-token-end token) js2-ts-cursor
5521 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5522
5523 ;; TODO: could potentially avoid a lot of consing by allocating a
5524 ;; char buffer the way Rhino does.
5525 (defsubst js2-add-to-string (c)
5526 (push c js2-ts-string-buffer))
5527
5528 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5529 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5530 ;; any other character: when it's not part of the current token, we
5531 ;; unget it, allowing it to be read again by the following call.
5532 (defsubst js2-unget-char ()
5533 (cl-decf js2-ts-cursor))
5534
5535 ;; Rhino distinguishes \r and \n line endings. We don't need to
5536 ;; because we only scan from Emacs buffers, which always use \n.
5537 (defun js2-get-char ()
5538 "Read and return the next character from the input buffer.
5539 Increments `js2-ts-lineno' if the return value is a newline char.
5540 Updates `js2-ts-cursor' to the point after the returned char.
5541 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5542 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5543 (let (c)
5544 ;; check for end of buffer
5545 (if (>= js2-ts-cursor (point-max))
5546 (setq js2-ts-hit-eof t
5547 js2-ts-cursor (1+ js2-ts-cursor)
5548 c js2-EOF_CHAR) ; return value
5549 ;; otherwise read next char
5550 (setq c (char-before (cl-incf js2-ts-cursor)))
5551 ;; if we read a newline, update counters
5552 (if (= c ?\n)
5553 (setq js2-ts-line-start js2-ts-cursor
5554 js2-ts-lineno (1+ js2-ts-lineno)))
5555 ;; TODO: skip over format characters
5556 c)))
5557
5558 (defun js2-read-unicode-escape ()
5559 "Read a \\uNNNN sequence from the input.
5560 Assumes the ?\ and ?u have already been read.
5561 Returns the unicode character, or nil if it wasn't a valid character.
5562 Doesn't change the values of any scanner variables."
5563 ;; I really wish I knew a better way to do this, but I can't
5564 ;; find the Emacs function that takes a 16-bit int and converts
5565 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5566 ;; Have to first check that it's 4 hex characters or it may stop
5567 ;; the read early.
5568 (ignore-errors
5569 (let ((s (buffer-substring-no-properties js2-ts-cursor
5570 (+ 4 js2-ts-cursor))))
5571 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5572 (read (concat "?\\u" s))))))
5573
5574 (defun js2-match-char (test)
5575 "Consume and return next character if it matches TEST, a character.
5576 Returns nil and consumes nothing if TEST is not the next character."
5577 (let ((c (js2-get-char)))
5578 (if (eq c test)
5579 t
5580 (js2-unget-char)
5581 nil)))
5582
5583 (defun js2-peek-char ()
5584 (prog1
5585 (js2-get-char)
5586 (js2-unget-char)))
5587
5588 (defun js2-identifier-start-p (c)
5589 "Is C a valid start to an ES5 Identifier?
5590 See http://es5.github.io/#x7.6"
5591 (or
5592 (memq c '(?$ ?_))
5593 (memq (get-char-code-property c 'general-category)
5594 ;; Letters
5595 '(Lu Ll Lt Lm Lo Nl))))
5596
5597 (defun js2-identifier-part-p (c)
5598 "Is C a valid part of an ES5 Identifier?
5599 See http://es5.github.io/#x7.6"
5600 (or
5601 (memq c '(?$ ?_ ?\u200c ?\u200d))
5602 (memq (get-char-code-property c 'general-category)
5603 '(;; Letters
5604 Lu Ll Lt Lm Lo Nl
5605 ;; Combining Marks
5606 Mn Mc
5607 ;; Digits
5608 Nd
5609 ;; Connector Punctuation
5610 Pc))))
5611
5612 (defun js2-alpha-p (c)
5613 (cond ((and (<= ?A c) (<= c ?Z)) t)
5614 ((and (<= ?a c) (<= c ?z)) t)
5615 (t nil)))
5616
5617 (defsubst js2-digit-p (c)
5618 (and (<= ?0 c) (<= c ?9)))
5619
5620 (defun js2-js-space-p (c)
5621 (if (<= c 127)
5622 (memq c '(#x20 #x9 #xB #xC #xD))
5623 (or
5624 (eq c #xA0)
5625 ;; TODO: change this nil to check for Unicode space character
5626 nil)))
5627
5628 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5629
5630 (defun js2-skip-line ()
5631 "Skip to end of line."
5632 (while (not (memq (js2-get-char) js2-eol-chars)))
5633 (js2-unget-char)
5634 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5635
5636 (defun js2-init-scanner (&optional buf line)
5637 "Create token stream for BUF starting on LINE.
5638 BUF defaults to `current-buffer' and LINE defaults to 1.
5639
5640 A buffer can only have one scanner active at a time, which yields
5641 dramatically simpler code than using a defstruct. If you need to
5642 have simultaneous scanners in a buffer, copy the regions to scan
5643 into temp buffers."
5644 (with-current-buffer (or buf (current-buffer))
5645 (setq js2-ts-dirty-line nil
5646 js2-ts-hit-eof nil
5647 js2-ts-line-start 0
5648 js2-ts-lineno (or line 1)
5649 js2-ts-line-end-char -1
5650 js2-ts-cursor (point-min)
5651 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5652 js2-ti-tokens-cursor 0
5653 js2-ti-lookahead 0
5654 js2-ts-is-xml-attribute nil
5655 js2-ts-xml-is-tag-content nil
5656 js2-ts-xml-open-tags-count 0
5657 js2-ts-string-buffer nil)))
5658
5659 ;; This function uses the cached op, string and number fields in
5660 ;; TokenStream; if getToken has been called since the passed token
5661 ;; was scanned, the op or string printed may be incorrect.
5662 (defun js2-token-to-string (token)
5663 ;; Not sure where this function is used in Rhino. Not tested.
5664 (if (not js2-debug-print-trees)
5665 ""
5666 (let ((name (js2-tt-name token)))
5667 (cond
5668 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5669 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5670 (concat name " `" (js2-current-token-string) "'"))
5671 ((eq token js2-NUMBER)
5672 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5673 (t
5674 name)))))
5675
5676 (defconst js2-keywords
5677 '(break
5678 case catch class const continue
5679 debugger default delete do
5680 else extends export
5681 false finally for function
5682 if in instanceof import
5683 let
5684 new null
5685 return
5686 super switch
5687 this throw true try typeof
5688 var void
5689 while with
5690 yield))
5691
5692 ;; Token names aren't exactly the same as the keywords, unfortunately.
5693 ;; E.g. delete is js2-DELPROP.
5694 (defconst js2-kwd-tokens
5695 (let ((table (make-vector js2-num-tokens nil))
5696 (tokens
5697 (list js2-BREAK
5698 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5699 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5700 js2-ELSE js2-EXPORT
5701 js2-ELSE js2-EXTENDS js2-EXPORT
5702 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5703 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5704 js2-LET
5705 js2-NEW js2-NULL
5706 js2-RETURN
5707 js2-SUPER js2-SWITCH
5708 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5709 js2-VAR
5710 js2-WHILE js2-WITH
5711 js2-YIELD)))
5712 (dolist (i tokens)
5713 (aset table i 'font-lock-keyword-face))
5714 (aset table js2-STRING 'font-lock-string-face)
5715 (aset table js2-REGEXP 'font-lock-string-face)
5716 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5717 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5718 (aset table js2-COMMENT 'font-lock-comment-face)
5719 (aset table js2-THIS 'font-lock-builtin-face)
5720 (aset table js2-SUPER 'font-lock-builtin-face)
5721 (aset table js2-VOID 'font-lock-constant-face)
5722 (aset table js2-NULL 'font-lock-constant-face)
5723 (aset table js2-TRUE 'font-lock-constant-face)
5724 (aset table js2-FALSE 'font-lock-constant-face)
5725 (aset table js2-NOT 'font-lock-negation-char-face)
5726 table)
5727 "Vector whose values are non-nil for tokens that are keywords.
5728 The values are default faces to use for highlighting the keywords.")
5729
5730 ;; FIXME: Support strict mode-only future reserved words, after we know
5731 ;; which parts scopes are in strict mode, and which are not.
5732 (defconst js2-reserved-words '(class enum export extends import static super)
5733 "Future reserved keywords in ECMAScript 5.1.")
5734
5735 (defconst js2-keyword-names
5736 (let ((table (make-hash-table :test 'equal)))
5737 (cl-loop for k in js2-keywords
5738 do (puthash
5739 (symbol-name k) ; instanceof
5740 (intern (concat "js2-"
5741 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5742 table))
5743 table)
5744 "JavaScript keywords by name, mapped to their symbols.")
5745
5746 (defconst js2-reserved-word-names
5747 (let ((table (make-hash-table :test 'equal)))
5748 (cl-loop for k in js2-reserved-words
5749 do
5750 (puthash (symbol-name k) 'js2-RESERVED table))
5751 table)
5752 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5753
5754 (defun js2-collect-string (buf)
5755 "Convert BUF, a list of chars, to a string.
5756 Reverses BUF before converting."
5757 (if buf
5758 (apply #'string (nreverse buf))
5759 ""))
5760
5761 (defun js2-string-to-keyword (s)
5762 "Return token for S, a string, if S is a keyword or reserved word.
5763 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5764 (or (gethash s js2-keyword-names)
5765 (gethash s js2-reserved-word-names)))
5766
5767 (defsubst js2-ts-set-char-token-bounds (token)
5768 "Used when next token is one character."
5769 (setf (js2-token-beg token) (1- js2-ts-cursor)
5770 (js2-token-end token) js2-ts-cursor))
5771
5772 (defsubst js2-ts-return (token type)
5773 "Update the `end' and `type' slots of TOKEN,
5774 then throw `return' with value TYPE."
5775 (setf (js2-token-end token) js2-ts-cursor
5776 (js2-token-type token) type)
5777 (throw 'return type))
5778
5779 (defun js2-x-digit-to-int (c accumulator)
5780 "Build up a hex number.
5781 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5782 corresponding number. Otherwise return -1."
5783 (catch 'return
5784 (catch 'check
5785 ;; Use 0..9 < A..Z < a..z
5786 (cond
5787 ((<= c ?9)
5788 (cl-decf c ?0)
5789 (if (<= 0 c)
5790 (throw 'check nil)))
5791 ((<= c ?F)
5792 (when (<= ?A c)
5793 (cl-decf c (- ?A 10))
5794 (throw 'check nil)))
5795 ((<= c ?f)
5796 (when (<= ?a c)
5797 (cl-decf c (- ?a 10))
5798 (throw 'check nil))))
5799 (throw 'return -1))
5800 (logior c (lsh accumulator 4))))
5801
5802 (defun js2-get-token (&optional modifier)
5803 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5804 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5805 next saved token.
5806
5807 This function will not return a newline (js2-EOL) - instead, it
5808 gobbles newlines until it finds a non-newline token. Call
5809 `js2-peek-token-or-eol' when you care about newlines.
5810
5811 This function will also not return a js2-COMMENT. Instead, it
5812 records comments found in `js2-scanned-comments'. If the token
5813 returned by this function immediately follows a jsdoc comment,
5814 the token is flagged as such."
5815 (if (zerop js2-ti-lookahead)
5816 (js2-get-token-internal modifier)
5817 (cl-decf js2-ti-lookahead)
5818 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5819 (let ((tt (js2-current-token-type)))
5820 (cl-assert (not (= tt js2-EOL)))
5821 tt)))
5822
5823 (defun js2-unget-token ()
5824 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5825 (cl-incf js2-ti-lookahead)
5826 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5827
5828 (defun js2-get-token-internal (modifier)
5829 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5830 (tt (js2-token-type token))
5831 saw-eol
5832 face)
5833 ;; process comments
5834 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5835 (if (= tt js2-EOL)
5836 (setq saw-eol t)
5837 (setq saw-eol nil)
5838 (when js2-record-comments
5839 (js2-record-comment token)))
5840 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5841 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5842 tt (js2-token-type token)))
5843
5844 (when saw-eol
5845 (setf (js2-token-follows-eol-p token) t))
5846
5847 ;; perform lexical fontification as soon as token is scanned
5848 (when js2-parse-ide-mode
5849 (cond
5850 ((cl-minusp tt)
5851 (js2-record-face 'js2-error token))
5852 ((setq face (aref js2-kwd-tokens tt))
5853 (js2-record-face face token))
5854 ((and (= tt js2-NAME)
5855 (equal (js2-token-string token) "undefined"))
5856 (js2-record-face 'font-lock-constant-face token))))
5857 tt))
5858
5859 (defsubst js2-string-to-number (str base)
5860 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5861 (condition-case nil
5862 (string-to-number str base)
5863 (overflow-error -1)))
5864
5865 (defun js2-get-token-internal-1 (modifier)
5866 "Return next JavaScript token type, an int such as js2-RETURN.
5867 During operation, creates an instance of `js2-token' struct, sets
5868 its relevant fields and puts it into `js2-ti-tokens'."
5869 (let (identifier-start
5870 is-unicode-escape-start c
5871 contains-escape escape-val str result base
5872 look-for-slash continue tt
5873 (token (js2-new-token 0)))
5874 (setq
5875 tt
5876 (catch 'return
5877 (when (eq modifier 'TEMPLATE_TAIL)
5878 (setf (js2-token-beg token) (1- js2-ts-cursor))
5879 (throw 'return (js2-get-string-or-template-token ?` token)))
5880 (while t
5881 ;; Eat whitespace, possibly sensitive to newlines.
5882 (setq continue t)
5883 (while continue
5884 (setq c (js2-get-char))
5885 (cond
5886 ((eq c js2-EOF_CHAR)
5887 (js2-unget-char)
5888 (js2-ts-set-char-token-bounds token)
5889 (throw 'return js2-EOF))
5890 ((eq c ?\n)
5891 (js2-ts-set-char-token-bounds token)
5892 (setq js2-ts-dirty-line nil)
5893 (throw 'return js2-EOL))
5894 ((not (js2-js-space-p c))
5895 (if (/= c ?-) ; in case end of HTML comment
5896 (setq js2-ts-dirty-line t))
5897 (setq continue nil))))
5898 ;; Assume the token will be 1 char - fixed up below.
5899 (js2-ts-set-char-token-bounds token)
5900 (when (eq c ?@)
5901 (throw 'return js2-XMLATTR))
5902 ;; identifier/keyword/instanceof?
5903 ;; watch out for starting with a <backslash>
5904 (cond
5905 ((eq c ?\\)
5906 (setq c (js2-get-char))
5907 (if (eq c ?u)
5908 (setq identifier-start t
5909 is-unicode-escape-start t
5910 js2-ts-string-buffer nil)
5911 (setq identifier-start nil)
5912 (js2-unget-char)
5913 (setq c ?\\)))
5914 (t
5915 (when (setq identifier-start (js2-identifier-start-p c))
5916 (setq js2-ts-string-buffer nil)
5917 (js2-add-to-string c))))
5918 (when identifier-start
5919 (setq contains-escape is-unicode-escape-start)
5920 (catch 'break
5921 (while t
5922 (if is-unicode-escape-start
5923 ;; strictly speaking we should probably push-back
5924 ;; all the bad characters if the <backslash>uXXXX
5925 ;; sequence is malformed. But since there isn't a
5926 ;; correct context(is there?) for a bad Unicode
5927 ;; escape sequence in an identifier, we can report
5928 ;; an error here.
5929 (progn
5930 (setq escape-val 0)
5931 (dotimes (_ 4)
5932 (setq c (js2-get-char)
5933 escape-val (js2-x-digit-to-int c escape-val))
5934 ;; Next check takes care of c < 0 and bad escape
5935 (if (cl-minusp escape-val)
5936 (throw 'break nil)))
5937 (if (cl-minusp escape-val)
5938 (js2-report-scan-error "msg.invalid.escape" t))
5939 (js2-add-to-string escape-val)
5940 (setq is-unicode-escape-start nil))
5941 (setq c (js2-get-char))
5942 (cond
5943 ((eq c ?\\)
5944 (setq c (js2-get-char))
5945 (if (eq c ?u)
5946 (setq is-unicode-escape-start t
5947 contains-escape t)
5948 (js2-report-scan-error "msg.illegal.character" t)))
5949 (t
5950 (if (or (eq c js2-EOF_CHAR)
5951 (not (js2-identifier-part-p c)))
5952 (throw 'break nil))
5953 (js2-add-to-string c))))))
5954 (js2-unget-char)
5955 (setf str (js2-collect-string js2-ts-string-buffer)
5956 (js2-token-end token) js2-ts-cursor)
5957 ;; FIXME: Invalid in ES5 and ES6, see
5958 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5959 ;; Probably should just drop this conditional.
5960 (unless contains-escape
5961 ;; OPT we shouldn't have to make a string (object!) to
5962 ;; check if it's a keyword.
5963 ;; Return the corresponding token if it's a keyword
5964 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5965 (setq result (js2-string-to-keyword str)))
5966 (if (and (< js2-language-version 170)
5967 (memq result '(js2-LET js2-YIELD)))
5968 ;; LET and YIELD are tokens only in 1.7 and later
5969 (setq result 'js2-NAME))
5970 (when (eq result 'js2-RESERVED)
5971 (setf (js2-token-string token) str))
5972 (throw 'return (js2-tt-code result))))
5973 ;; If we want to intern these as Rhino does, just use (intern str)
5974 (setf (js2-token-string token) str)
5975 (throw 'return js2-NAME)) ; end identifier/kwd check
5976 ;; is it a number?
5977 (when (or (js2-digit-p c)
5978 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5979 (setq js2-ts-string-buffer nil
5980 base 10)
5981 (when (eq c ?0)
5982 (setq c (js2-get-char))
5983 (cond
5984 ((or (eq c ?x) (eq c ?X))
5985 (setq base 16)
5986 (setq c (js2-get-char)))
5987 ((and (or (eq c ?b) (eq c ?B))
5988 (>= js2-language-version 200))
5989 (setq base 2)
5990 (setq c (js2-get-char)))
5991 ((and (or (eq c ?o) (eq c ?O))
5992 (>= js2-language-version 200))
5993 (setq base 8)
5994 (setq c (js2-get-char)))
5995 ((js2-digit-p c)
5996 (setq base 'maybe-8))
5997 (t
5998 (js2-add-to-string ?0))))
5999 (cond
6000 ((eq base 16)
6001 (if (> 0 (js2-x-digit-to-int c 0))
6002 (js2-report-scan-error "msg.missing.hex.digits")
6003 (while (<= 0 (js2-x-digit-to-int c 0))
6004 (js2-add-to-string c)
6005 (setq c (js2-get-char)))))
6006 ((eq base 2)
6007 (if (not (memq c '(?0 ?1)))
6008 (js2-report-scan-error "msg.missing.binary.digits")
6009 (while (memq c '(?0 ?1))
6010 (js2-add-to-string c)
6011 (setq c (js2-get-char)))))
6012 ((eq base 8)
6013 (if (or (> ?0 c) (< ?7 c))
6014 (js2-report-scan-error "msg.missing.octal.digits")
6015 (while (and (<= ?0 c) (>= ?7 c))
6016 (js2-add-to-string c)
6017 (setq c (js2-get-char)))))
6018 (t
6019 (while (and (<= ?0 c) (<= c ?9))
6020 ;; We permit 08 and 09 as decimal numbers, which
6021 ;; makes our behavior a superset of the ECMA
6022 ;; numeric grammar. We might not always be so
6023 ;; permissive, so we warn about it.
6024 (when (and (eq base 'maybe-8) (>= c ?8))
6025 (js2-report-warning "msg.bad.octal.literal"
6026 (if (eq c ?8) "8" "9"))
6027 (setq base 10))
6028 (js2-add-to-string c)
6029 (setq c (js2-get-char)))
6030 (when (eq base 'maybe-8)
6031 (setq base 8))))
6032 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6033 (when (eq c ?.)
6034 (cl-loop do
6035 (js2-add-to-string c)
6036 (setq c (js2-get-char))
6037 while (js2-digit-p c)))
6038 (when (memq c '(?e ?E))
6039 (js2-add-to-string c)
6040 (setq c (js2-get-char))
6041 (when (memq c '(?+ ?-))
6042 (js2-add-to-string c)
6043 (setq c (js2-get-char)))
6044 (unless (js2-digit-p c)
6045 (js2-report-scan-error "msg.missing.exponent" t))
6046 (cl-loop do
6047 (js2-add-to-string c)
6048 (setq c (js2-get-char))
6049 while (js2-digit-p c))))
6050 (js2-unget-char)
6051 (let ((str (js2-set-string-from-buffer token)))
6052 (setf (js2-token-number token) (js2-string-to-number str base)
6053 (js2-token-number-base token) base))
6054 (throw 'return js2-NUMBER))
6055 ;; is it a string?
6056 (when (or (memq c '(?\" ?\'))
6057 (and (>= js2-language-version 200)
6058 (= c ?`)))
6059 (throw 'return
6060 (js2-get-string-or-template-token c token)))
6061 (js2-ts-return token
6062 (cl-case c
6063 (?\;
6064 (throw 'return js2-SEMI))
6065 (?\[
6066 (throw 'return js2-LB))
6067 (?\]
6068 (throw 'return js2-RB))
6069 (?{
6070 (throw 'return js2-LC))
6071 (?}
6072 (throw 'return js2-RC))
6073 (?\(
6074 (throw 'return js2-LP))
6075 (?\)
6076 (throw 'return js2-RP))
6077 (?,
6078 (throw 'return js2-COMMA))
6079 (??
6080 (throw 'return js2-HOOK))
6081 (?:
6082 (if (js2-match-char ?:)
6083 js2-COLONCOLON
6084 (throw 'return js2-COLON)))
6085 (?.
6086 (if (js2-match-char ?.)
6087 (if (js2-match-char ?.)
6088 js2-TRIPLEDOT js2-DOTDOT)
6089 (if (js2-match-char ?\()
6090 js2-DOTQUERY
6091 (throw 'return js2-DOT))))
6092 (?|
6093 (if (js2-match-char ?|)
6094 (throw 'return js2-OR)
6095 (if (js2-match-char ?=)
6096 js2-ASSIGN_BITOR
6097 (throw 'return js2-BITOR))))
6098 (?^
6099 (if (js2-match-char ?=)
6100 js2-ASSIGN_BITOR
6101 (throw 'return js2-BITXOR)))
6102 (?&
6103 (if (js2-match-char ?&)
6104 (throw 'return js2-AND)
6105 (if (js2-match-char ?=)
6106 js2-ASSIGN_BITAND
6107 (throw 'return js2-BITAND))))
6108 (?=
6109 (if (js2-match-char ?=)
6110 (if (js2-match-char ?=)
6111 js2-SHEQ
6112 (throw 'return js2-EQ))
6113 (if (js2-match-char ?>)
6114 (js2-ts-return token js2-ARROW)
6115 (throw 'return js2-ASSIGN))))
6116 (?!
6117 (if (js2-match-char ?=)
6118 (if (js2-match-char ?=)
6119 js2-SHNE
6120 js2-NE)
6121 (throw 'return js2-NOT)))
6122 (?<
6123 ;; NB:treat HTML begin-comment as comment-till-eol
6124 (when (js2-match-char ?!)
6125 (when (js2-match-char ?-)
6126 (when (js2-match-char ?-)
6127 (js2-skip-line)
6128 (setf (js2-token-comment-type (js2-current-token)) 'html)
6129 (throw 'return js2-COMMENT)))
6130 (js2-unget-char))
6131 (if (js2-match-char ?<)
6132 (if (js2-match-char ?=)
6133 js2-ASSIGN_LSH
6134 js2-LSH)
6135 (if (js2-match-char ?=)
6136 js2-LE
6137 (throw 'return js2-LT))))
6138 (?>
6139 (if (js2-match-char ?>)
6140 (if (js2-match-char ?>)
6141 (if (js2-match-char ?=)
6142 js2-ASSIGN_URSH
6143 js2-URSH)
6144 (if (js2-match-char ?=)
6145 js2-ASSIGN_RSH
6146 js2-RSH))
6147 (if (js2-match-char ?=)
6148 js2-GE
6149 (throw 'return js2-GT))))
6150 (?*
6151 (if (js2-match-char ?=)
6152 js2-ASSIGN_MUL
6153 (throw 'return js2-MUL)))
6154 (?/
6155 ;; is it a // comment?
6156 (when (js2-match-char ?/)
6157 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6158 (js2-skip-line)
6159 (setf (js2-token-comment-type token) 'line)
6160 ;; include newline so highlighting goes to end of
6161 ;; window, if there actually is a newline; if we
6162 ;; hit eof, then implicitly there isn't
6163 (unless js2-ts-hit-eof
6164 (cl-incf (js2-token-end token)))
6165 (throw 'return js2-COMMENT))
6166 ;; is it a /* comment?
6167 (when (js2-match-char ?*)
6168 (setf look-for-slash nil
6169 (js2-token-beg token) (- js2-ts-cursor 2)
6170 (js2-token-comment-type token)
6171 (if (js2-match-char ?*)
6172 (progn
6173 (setq look-for-slash t)
6174 'jsdoc)
6175 'block))
6176 (while t
6177 (setq c (js2-get-char))
6178 (cond
6179 ((eq c js2-EOF_CHAR)
6180 (setf (js2-token-end token) (1- js2-ts-cursor))
6181 (js2-report-error "msg.unterminated.comment")
6182 (throw 'return js2-COMMENT))
6183 ((eq c ?*)
6184 (setq look-for-slash t))
6185 ((eq c ?/)
6186 (if look-for-slash
6187 (js2-ts-return token js2-COMMENT)))
6188 (t
6189 (setf look-for-slash nil
6190 (js2-token-end token) js2-ts-cursor)))))
6191 (if (js2-match-char ?=)
6192 js2-ASSIGN_DIV
6193 (throw 'return js2-DIV)))
6194 (?#
6195 (when js2-skip-preprocessor-directives
6196 (js2-skip-line)
6197 (setf (js2-token-comment-type token) 'preprocessor
6198 (js2-token-end token) js2-ts-cursor)
6199 (throw 'return js2-COMMENT))
6200 (throw 'return js2-ERROR))
6201 (?%
6202 (if (js2-match-char ?=)
6203 js2-ASSIGN_MOD
6204 (throw 'return js2-MOD)))
6205 (?~
6206 (throw 'return js2-BITNOT))
6207 (?+
6208 (if (js2-match-char ?=)
6209 js2-ASSIGN_ADD
6210 (if (js2-match-char ?+)
6211 js2-INC
6212 (throw 'return js2-ADD))))
6213 (?-
6214 (cond
6215 ((js2-match-char ?=)
6216 (setq c js2-ASSIGN_SUB))
6217 ((js2-match-char ?-)
6218 (unless js2-ts-dirty-line
6219 ;; treat HTML end-comment after possible whitespace
6220 ;; after line start as comment-until-eol
6221 (when (js2-match-char ?>)
6222 (js2-skip-line)
6223 (setf (js2-token-comment-type (js2-current-token)) 'html)
6224 (throw 'return js2-COMMENT)))
6225 (setq c js2-DEC))
6226 (t
6227 (setq c js2-SUB)))
6228 (setq js2-ts-dirty-line t)
6229 c)
6230 (otherwise
6231 (js2-report-scan-error "msg.illegal.character")))))))
6232 (setf (js2-token-type token) tt)
6233 token))
6234
6235 (defun js2-get-string-or-template-token (quote-char token)
6236 ;; We attempt to accumulate a string the fast way, by
6237 ;; building it directly out of the reader. But if there
6238 ;; are any escaped characters in the string, we revert to
6239 ;; building it out of a string buffer.
6240 (let ((c (js2-get-char))
6241 js2-ts-string-buffer
6242 nc c1 val escape-val)
6243 (catch 'break
6244 (while (/= c quote-char)
6245 (catch 'continue
6246 (when (eq c js2-EOF_CHAR)
6247 (js2-unget-char)
6248 (js2-report-error "msg.unterminated.string.lit")
6249 (throw 'break nil))
6250 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6251 (js2-unget-char)
6252 (js2-report-error "msg.unterminated.string.lit")
6253 (throw 'break nil))
6254 (when (eq c ?\\)
6255 ;; We've hit an escaped character
6256 (setq c (js2-get-char))
6257 (cl-case c
6258 (?b (setq c ?\b))
6259 (?f (setq c ?\f))
6260 (?n (setq c ?\n))
6261 (?r (setq c ?\r))
6262 (?t (setq c ?\t))
6263 (?v (setq c ?\v))
6264 (?u
6265 (setq c1 (js2-read-unicode-escape))
6266 (if js2-parse-ide-mode
6267 (if c1
6268 (progn
6269 ;; just copy the string in IDE-mode
6270 (js2-add-to-string ?\\)
6271 (js2-add-to-string ?u)
6272 (dotimes (_ 3)
6273 (js2-add-to-string (js2-get-char)))
6274 (setq c (js2-get-char))) ; added at end of loop
6275 ;; flag it as an invalid escape
6276 (js2-report-warning "msg.invalid.escape"
6277 nil (- js2-ts-cursor 2) 6))
6278 ;; Get 4 hex digits; if the u escape is not
6279 ;; followed by 4 hex digits, use 'u' + the
6280 ;; literal character sequence that follows.
6281 (js2-add-to-string ?u)
6282 (setq escape-val 0)
6283 (dotimes (_ 4)
6284 (setq c (js2-get-char)
6285 escape-val (js2-x-digit-to-int c escape-val))
6286 (if (cl-minusp escape-val)
6287 (throw 'continue nil))
6288 (js2-add-to-string c))
6289 ;; prepare for replace of stored 'u' sequence by escape value
6290 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6291 c escape-val)))
6292 (?x
6293 ;; Get 2 hex digits, defaulting to 'x'+literal
6294 ;; sequence, as above.
6295 (setq c (js2-get-char)
6296 escape-val (js2-x-digit-to-int c 0))
6297 (if (cl-minusp escape-val)
6298 (progn
6299 (js2-add-to-string ?x)
6300 (throw 'continue nil))
6301 (setq c1 c
6302 c (js2-get-char)
6303 escape-val (js2-x-digit-to-int c escape-val))
6304 (if (cl-minusp escape-val)
6305 (progn
6306 (js2-add-to-string ?x)
6307 (js2-add-to-string c1)
6308 (throw 'continue nil))
6309 ;; got 2 hex digits
6310 (setq c escape-val))))
6311 (?\n
6312 ;; Remove line terminator after escape to follow
6313 ;; SpiderMonkey and C/C++
6314 (setq c (js2-get-char))
6315 (throw 'continue nil))
6316 (t
6317 (when (and (<= ?0 c) (< c ?8))
6318 (setq val (- c ?0)
6319 c (js2-get-char))
6320 (when (and (<= ?0 c) (< c ?8))
6321 (setq val (- (+ (* 8 val) c) ?0)
6322 c (js2-get-char))
6323 (when (and (<= ?0 c)
6324 (< c ?8)
6325 (< val #o37))
6326 ;; c is 3rd char of octal sequence only
6327 ;; if the resulting val <= 0377
6328 (setq val (- (+ (* 8 val) c) ?0)
6329 c (js2-get-char))))
6330 (js2-unget-char)
6331 (setq c val)))))
6332 (when (and (eq quote-char ?`) (eq c ?$))
6333 (when (eq (setq nc (js2-get-char)) ?\{)
6334 (throw 'break nil))
6335 (js2-unget-char))
6336 (js2-add-to-string c)
6337 (setq c (js2-get-char)))))
6338 (js2-set-string-from-buffer token)
6339 (if (not (eq quote-char ?`))
6340 js2-STRING
6341 (if (and (eq c ?$) (eq nc ?\{))
6342 js2-TEMPLATE_HEAD
6343 js2-NO_SUBS_TEMPLATE))))
6344
6345 (defun js2-read-regexp (start-tt)
6346 "Called by parser when it gets / or /= in literal context."
6347 (let (c err
6348 in-class ; inside a '[' .. ']' character-class
6349 flags
6350 (continue t)
6351 (token (js2-new-token 0)))
6352 (setq js2-ts-string-buffer nil)
6353 (if (eq start-tt js2-ASSIGN_DIV)
6354 ;; mis-scanned /=
6355 (js2-add-to-string ?=)
6356 (if (not (eq start-tt js2-DIV))
6357 (error "failed assertion")))
6358 (while (and (not err)
6359 (or (/= (setq c (js2-get-char)) ?/)
6360 in-class))
6361 (cond
6362 ((or (= c ?\n)
6363 (= c js2-EOF_CHAR))
6364 (setf (js2-token-end token) (1- js2-ts-cursor)
6365 err t
6366 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6367 (js2-report-error "msg.unterminated.re.lit"))
6368 (t (cond
6369 ((= c ?\\)
6370 (js2-add-to-string c)
6371 (setq c (js2-get-char)))
6372 ((= c ?\[)
6373 (setq in-class t))
6374 ((= c ?\])
6375 (setq in-class nil)))
6376 (js2-add-to-string c))))
6377 (unless err
6378 (while continue
6379 (cond
6380 ((js2-match-char ?g)
6381 (push ?g flags))
6382 ((js2-match-char ?i)
6383 (push ?i flags))
6384 ((js2-match-char ?m)
6385 (push ?m flags))
6386 ((and (js2-match-char ?u)
6387 (>= js2-language-version 200))
6388 (push ?u flags))
6389 ((and (js2-match-char ?y)
6390 (>= js2-language-version 200))
6391 (push ?y flags))
6392 (t
6393 (setq continue nil))))
6394 (if (js2-alpha-p (js2-peek-char))
6395 (js2-report-scan-error "msg.invalid.re.flag" t
6396 js2-ts-cursor 1))
6397 (js2-set-string-from-buffer token))
6398 (js2-collect-string flags)))
6399
6400 (defun js2-get-first-xml-token ()
6401 (setq js2-ts-xml-open-tags-count 0
6402 js2-ts-is-xml-attribute nil
6403 js2-ts-xml-is-tag-content nil)
6404 (js2-unget-char)
6405 (js2-get-next-xml-token))
6406
6407 (defun js2-xml-discard-string (token)
6408 "Throw away the string in progress and flag an XML parse error."
6409 (setf js2-ts-string-buffer nil
6410 (js2-token-string token) nil)
6411 (js2-report-scan-error "msg.XML.bad.form" t))
6412
6413 (defun js2-get-next-xml-token ()
6414 (setq js2-ts-string-buffer nil) ; for recording the XML
6415 (let ((token (js2-new-token 0))
6416 c result)
6417 (setq result
6418 (catch 'return
6419 (while t
6420 (setq c (js2-get-char))
6421 (cond
6422 ((= c js2-EOF_CHAR)
6423 (throw 'return js2-ERROR))
6424 (js2-ts-xml-is-tag-content
6425 (cl-case c
6426 (?>
6427 (js2-add-to-string c)
6428 (setq js2-ts-xml-is-tag-content nil
6429 js2-ts-is-xml-attribute nil))
6430 (?/
6431 (js2-add-to-string c)
6432 (when (eq ?> (js2-peek-char))
6433 (setq c (js2-get-char))
6434 (js2-add-to-string c)
6435 (setq js2-ts-xml-is-tag-content nil)
6436 (cl-decf js2-ts-xml-open-tags-count)))
6437 (?{
6438 (js2-unget-char)
6439 (js2-set-string-from-buffer token)
6440 (throw 'return js2-XML))
6441 ((?\' ?\")
6442 (js2-add-to-string c)
6443 (unless (js2-read-quoted-string c token)
6444 (throw 'return js2-ERROR)))
6445 (?=
6446 (js2-add-to-string c)
6447 (setq js2-ts-is-xml-attribute t))
6448 ((? ?\t ?\r ?\n)
6449 (js2-add-to-string c))
6450 (t
6451 (js2-add-to-string c)
6452 (setq js2-ts-is-xml-attribute nil)))
6453 (when (and (not js2-ts-xml-is-tag-content)
6454 (zerop js2-ts-xml-open-tags-count))
6455 (js2-set-string-from-buffer token)
6456 (throw 'return js2-XMLEND)))
6457 (t
6458 ;; else not tag content
6459 (cl-case c
6460 (?<
6461 (js2-add-to-string c)
6462 (setq c (js2-peek-char))
6463 (cl-case c
6464 (?!
6465 (setq c (js2-get-char)) ;; skip !
6466 (js2-add-to-string c)
6467 (setq c (js2-peek-char))
6468 (cl-case c
6469 (?-
6470 (setq c (js2-get-char)) ;; skip -
6471 (js2-add-to-string c)
6472 (if (eq c ?-)
6473 (progn
6474 (js2-add-to-string c)
6475 (unless (js2-read-xml-comment token)
6476 (throw 'return js2-ERROR)))
6477 (js2-xml-discard-string token)
6478 (throw 'return js2-ERROR)))
6479 (?\[
6480 (setq c (js2-get-char)) ;; skip [
6481 (js2-add-to-string c)
6482 (if (and (= (js2-get-char) ?C)
6483 (= (js2-get-char) ?D)
6484 (= (js2-get-char) ?A)
6485 (= (js2-get-char) ?T)
6486 (= (js2-get-char) ?A)
6487 (= (js2-get-char) ?\[))
6488 (progn
6489 (js2-add-to-string ?C)
6490 (js2-add-to-string ?D)
6491 (js2-add-to-string ?A)
6492 (js2-add-to-string ?T)
6493 (js2-add-to-string ?A)
6494 (js2-add-to-string ?\[)
6495 (unless (js2-read-cdata token)
6496 (throw 'return js2-ERROR)))
6497 (js2-xml-discard-string token)
6498 (throw 'return js2-ERROR)))
6499 (t
6500 (unless (js2-read-entity token)
6501 (throw 'return js2-ERROR))))
6502 ;; Allow bare CDATA section, e.g.:
6503 ;; let xml = <![CDATA[ foo bar baz ]]>;
6504 (when (zerop js2-ts-xml-open-tags-count)
6505 (throw 'return js2-XMLEND)))
6506 (??
6507 (setq c (js2-get-char)) ;; skip ?
6508 (js2-add-to-string c)
6509 (unless (js2-read-PI token)
6510 (throw 'return js2-ERROR)))
6511 (?/
6512 ;; end tag
6513 (setq c (js2-get-char)) ;; skip /
6514 (js2-add-to-string c)
6515 (when (zerop js2-ts-xml-open-tags-count)
6516 (js2-xml-discard-string token)
6517 (throw 'return js2-ERROR))
6518 (setq js2-ts-xml-is-tag-content t)
6519 (cl-decf js2-ts-xml-open-tags-count))
6520 (t
6521 ;; start tag
6522 (setq js2-ts-xml-is-tag-content t)
6523 (cl-incf js2-ts-xml-open-tags-count))))
6524 (?{
6525 (js2-unget-char)
6526 (js2-set-string-from-buffer token)
6527 (throw 'return js2-XML))
6528 (t
6529 (js2-add-to-string c))))))))
6530 (setf (js2-token-end token) js2-ts-cursor)
6531 (setf (js2-token-type token) result)
6532 result))
6533
6534 (defun js2-read-quoted-string (quote token)
6535 (let (c)
6536 (catch 'return
6537 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6538 (js2-add-to-string c)
6539 (if (eq c quote)
6540 (throw 'return t)))
6541 (js2-xml-discard-string token) ;; throw away string in progress
6542 nil)))
6543
6544 (defun js2-read-xml-comment (token)
6545 (let ((c (js2-get-char)))
6546 (catch 'return
6547 (while (/= c js2-EOF_CHAR)
6548 (catch 'continue
6549 (js2-add-to-string c)
6550 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6551 (setq c (js2-get-char))
6552 (js2-add-to-string c)
6553 (if (eq (js2-peek-char) ?>)
6554 (progn
6555 (setq c (js2-get-char)) ;; skip >
6556 (js2-add-to-string c)
6557 (throw 'return t))
6558 (throw 'continue nil)))
6559 (setq c (js2-get-char))))
6560 (js2-xml-discard-string token)
6561 nil)))
6562
6563 (defun js2-read-cdata (token)
6564 (let ((c (js2-get-char)))
6565 (catch 'return
6566 (while (/= c js2-EOF_CHAR)
6567 (catch 'continue
6568 (js2-add-to-string c)
6569 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6570 (setq c (js2-get-char))
6571 (js2-add-to-string c)
6572 (if (eq (js2-peek-char) ?>)
6573 (progn
6574 (setq c (js2-get-char)) ;; Skip >
6575 (js2-add-to-string c)
6576 (throw 'return t))
6577 (throw 'continue nil)))
6578 (setq c (js2-get-char))))
6579 (js2-xml-discard-string token)
6580 nil)))
6581
6582 (defun js2-read-entity (token)
6583 (let ((decl-tags 1)
6584 c)
6585 (catch 'return
6586 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6587 (js2-add-to-string c)
6588 (cl-case c
6589 (?<
6590 (cl-incf decl-tags))
6591 (?>
6592 (cl-decf decl-tags)
6593 (if (zerop decl-tags)
6594 (throw 'return t)))))
6595 (js2-xml-discard-string token)
6596 nil)))
6597
6598 (defun js2-read-PI (token)
6599 "Scan an XML processing instruction."
6600 (let (c)
6601 (catch 'return
6602 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6603 (js2-add-to-string c)
6604 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6605 (setq c (js2-get-char)) ;; Skip >
6606 (js2-add-to-string c)
6607 (throw 'return t)))
6608 (js2-xml-discard-string token)
6609 nil)))
6610
6611 ;;; Highlighting
6612
6613 (defun js2-set-face (beg end face &optional record)
6614 "Fontify a region. If RECORD is non-nil, record for later."
6615 (when (cl-plusp js2-highlight-level)
6616 (setq beg (min (point-max) beg)
6617 beg (max (point-min) beg)
6618 end (min (point-max) end)
6619 end (max (point-min) end))
6620 (if record
6621 (push (list beg end face) js2-mode-fontifications)
6622 (put-text-property beg end 'font-lock-face face))))
6623
6624 (defsubst js2-clear-face (beg end)
6625 (remove-text-properties beg end '(font-lock-face nil
6626 help-echo nil
6627 point-entered nil
6628 cursor-sensor-functions nil
6629 c-in-sws nil)))
6630
6631 (defconst js2-ecma-global-props
6632 (concat "^"
6633 (regexp-opt
6634 '("Infinity" "NaN" "undefined" "arguments") t)
6635 "$")
6636 "Value properties of the Ecma-262 Global Object.
6637 Shown at or above `js2-highlight-level' 2.")
6638
6639 ;; might want to add the name "arguments" to this list?
6640 (defconst js2-ecma-object-props
6641 (concat "^"
6642 (regexp-opt
6643 '("prototype" "__proto__" "__parent__") t)
6644 "$")
6645 "Value properties of the Ecma-262 Object constructor.
6646 Shown at or above `js2-highlight-level' 2.")
6647
6648 (defconst js2-ecma-global-funcs
6649 (concat
6650 "^"
6651 (regexp-opt
6652 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6653 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6654 "$")
6655 "Function properties of the Ecma-262 Global object.
6656 Shown at or above `js2-highlight-level' 2.")
6657
6658 (defconst js2-ecma-number-props
6659 (concat "^"
6660 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6661 "NEGATIVE_INFINITY"
6662 "POSITIVE_INFINITY") t)
6663 "$")
6664 "Properties of the Ecma-262 Number constructor.
6665 Shown at or above `js2-highlight-level' 2.")
6666
6667 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6668 "Properties of the Ecma-262 Date constructor.
6669 Shown at or above `js2-highlight-level' 2.")
6670
6671 (defconst js2-ecma-math-props
6672 (concat "^"
6673 (regexp-opt
6674 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6675 t)
6676 "$")
6677 "Properties of the Ecma-262 Math object.
6678 Shown at or above `js2-highlight-level' 2.")
6679
6680 (defconst js2-ecma-math-funcs
6681 (concat "^"
6682 (regexp-opt
6683 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6684 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6685 "$")
6686 "Function properties of the Ecma-262 Math object.
6687 Shown at or above `js2-highlight-level' 2.")
6688
6689 (defconst js2-ecma-function-props
6690 (concat
6691 "^"
6692 (regexp-opt
6693 '(;; properties of the Object prototype object
6694 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6695 "toLocaleString" "toString" "valueOf"
6696 ;; properties of the Function prototype object
6697 "apply" "call"
6698 ;; properties of the Array prototype object
6699 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6700 "splice" "unshift"
6701 ;; properties of the String prototype object
6702 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6703 "localeCompare" "match" "replace" "search" "split" "substring"
6704 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6705 "toUpperCase"
6706 ;; properties of the Number prototype object
6707 "toExponential" "toFixed" "toPrecision"
6708 ;; properties of the Date prototype object
6709 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6710 "getMinutes" "getMonth" "getSeconds" "getTime"
6711 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6712 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6713 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6714 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6715 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6716 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6717 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6718 "toTimeString" "toUTCString"
6719 ;; properties of the RegExp prototype object
6720 "exec" "test"
6721 ;; properties of the JSON prototype object
6722 "parse" "stringify"
6723 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6724 "toSource" "__defineGetter__" "__defineSetter__"
6725 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6726 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6727 t)
6728 "$")
6729 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6730 Shown at or above `js2-highlight-level' 3.")
6731
6732 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6733 (let ((target-name (and target
6734 (js2-name-node-p target)
6735 (js2-name-node-name target)))
6736 (prop-name (if prop (js2-name-node-name prop)))
6737 (level2 (>= js2-highlight-level 2))
6738 (level3 (>= js2-highlight-level 3)))
6739 (when level2
6740 (let ((face
6741 (if call-p
6742 (cond
6743 ((and target prop)
6744 (cond
6745 ((and level3 (string-match js2-ecma-function-props prop-name))
6746 'font-lock-builtin-face)
6747 ((and target-name prop)
6748 (cond
6749 ((string= target-name "Date")
6750 (if (string-match js2-ecma-date-props prop-name)
6751 'font-lock-builtin-face))
6752 ((string= target-name "Math")
6753 (if (string-match js2-ecma-math-funcs prop-name)
6754 'font-lock-builtin-face))))))
6755 (prop
6756 (if (string-match js2-ecma-global-funcs prop-name)
6757 'font-lock-builtin-face)))
6758 (cond
6759 ((and target prop)
6760 (cond
6761 ((string= target-name "Number")
6762 (if (string-match js2-ecma-number-props prop-name)
6763 'font-lock-constant-face))
6764 ((string= target-name "Math")
6765 (if (string-match js2-ecma-math-props prop-name)
6766 'font-lock-constant-face))))
6767 (prop
6768 (if (string-match js2-ecma-object-props prop-name)
6769 'font-lock-constant-face))))))
6770 (when (and (not face) target (not call-p) prop-name)
6771 (setq face 'js2-object-property))
6772 (when face
6773 (let ((pos (+ (js2-node-pos parent) ; absolute
6774 (js2-node-pos prop)))) ; relative
6775 (js2-set-face pos
6776 (+ pos (js2-node-len prop))
6777 face 'record)))))))
6778
6779 (defun js2-parse-highlight-member-expr-node (node)
6780 "Perform syntax highlighting of EcmaScript built-in properties.
6781 The variable `js2-highlight-level' governs this highlighting."
6782 (let (face target prop name pos end parent call-p callee)
6783 (cond
6784 ;; case 1: simple name, e.g. foo
6785 ((js2-name-node-p node)
6786 (setq name (js2-name-node-name node))
6787 ;; possible for name to be nil in rare cases - saw it when
6788 ;; running js2-mode on an elisp buffer. Might as well try to
6789 ;; make it so js2-mode never barfs.
6790 (when name
6791 (setq face (if (string-match js2-ecma-global-props name)
6792 'font-lock-constant-face))
6793 (when face
6794 (setq pos (js2-node-pos node)
6795 end (+ pos (js2-node-len node)))
6796 (js2-set-face pos end face 'record))))
6797 ;; case 2: property access or function call
6798 ((or (js2-prop-get-node-p node)
6799 ;; highlight function call if expr is a prop-get node
6800 ;; or a plain name (i.e. unqualified function call)
6801 (and (setq call-p (js2-call-node-p node))
6802 (setq callee (js2-call-node-target node)) ; separate setq!
6803 (or (js2-prop-get-node-p callee)
6804 (js2-name-node-p callee))))
6805 (setq parent node
6806 node (if call-p callee node))
6807 (if (and call-p (js2-name-node-p callee))
6808 (setq prop callee)
6809 (setq target (js2-prop-get-node-left node)
6810 prop (js2-prop-get-node-right node)))
6811 (cond
6812 ((js2-name-node-p prop)
6813 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6814 (js2-parse-highlight-prop-get parent target prop call-p))
6815 ((js2-name-node-p target)
6816 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6817 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6818
6819 (defun js2-parse-highlight-member-expr-fn-name (expr)
6820 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6821 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6822 We currently only handle the case where the last component is a prop-get
6823 of a simple name. Called before EXPR has a parent node."
6824 (let (pos
6825 (name (and (js2-prop-get-node-p expr)
6826 (js2-prop-get-node-right expr))))
6827 (when (js2-name-node-p name)
6828 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6829 (js2-node-pos name)))
6830 (+ pos (js2-node-len name))
6831 'font-lock-function-name-face
6832 'record))))
6833
6834 ;; source: http://jsdoc.sourceforge.net/
6835 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6836 ;; allows type specifications, and needs work before entering the wild.
6837
6838 (defconst js2-jsdoc-param-tag-regexp
6839 (concat "^\\s-*\\*+\\s-*\\(@"
6840 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6841 "\\)"
6842 "\\s-*\\({[^}]+}\\)?" ; optional type
6843 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6844 "\\_>")
6845 "Matches jsdoc tags with optional type and optional param name.")
6846
6847 (defconst js2-jsdoc-typed-tag-regexp
6848 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6849 (regexp-opt
6850 '("enum"
6851 "extends"
6852 "field"
6853 "id"
6854 "implements"
6855 "lends"
6856 "mods"
6857 "requires"
6858 "return"
6859 "returns"
6860 "throw"
6861 "throws"))
6862 "\\)\\)\\s-*\\({[^}]+}\\)?")
6863 "Matches jsdoc tags with optional type.")
6864
6865 (defconst js2-jsdoc-arg-tag-regexp
6866 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6867 (regexp-opt
6868 '("alias"
6869 "augments"
6870 "borrows"
6871 "bug"
6872 "base"
6873 "config"
6874 "default"
6875 "define"
6876 "exception"
6877 "function"
6878 "member"
6879 "memberOf"
6880 "name"
6881 "namespace"
6882 "since"
6883 "suppress"
6884 "this"
6885 "throws"
6886 "type"
6887 "version"))
6888 "\\)\\)\\s-+\\([^ \t]+\\)")
6889 "Matches jsdoc tags with a single argument.")
6890
6891 (defconst js2-jsdoc-empty-tag-regexp
6892 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6893 (regexp-opt
6894 '("addon"
6895 "author"
6896 "class"
6897 "const"
6898 "constant"
6899 "constructor"
6900 "constructs"
6901 "deprecated"
6902 "desc"
6903 "description"
6904 "event"
6905 "example"
6906 "exec"
6907 "export"
6908 "fileoverview"
6909 "final"
6910 "function"
6911 "hidden"
6912 "ignore"
6913 "implicitCast"
6914 "inheritDoc"
6915 "inner"
6916 "interface"
6917 "license"
6918 "noalias"
6919 "noshadow"
6920 "notypecheck"
6921 "override"
6922 "owner"
6923 "preserve"
6924 "preserveTry"
6925 "private"
6926 "protected"
6927 "public"
6928 "static"
6929 "supported"
6930 ))
6931 "\\)\\)\\s-*")
6932 "Matches empty jsdoc tags.")
6933
6934 (defconst js2-jsdoc-link-tag-regexp
6935 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6936 "Matches a jsdoc link or code tag.")
6937
6938 (defconst js2-jsdoc-see-tag-regexp
6939 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6940 "Matches a jsdoc @see tag.")
6941
6942 (defconst js2-jsdoc-html-tag-regexp
6943 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6944 "Matches a simple (no attributes) html start- or end-tag.")
6945
6946 (defun js2-jsdoc-highlight-helper ()
6947 (js2-set-face (match-beginning 1)
6948 (match-end 1)
6949 'js2-jsdoc-tag)
6950 (if (match-beginning 2)
6951 (if (save-excursion
6952 (goto-char (match-beginning 2))
6953 (= (char-after) ?{))
6954 (js2-set-face (1+ (match-beginning 2))
6955 (1- (match-end 2))
6956 'js2-jsdoc-type)
6957 (js2-set-face (match-beginning 2)
6958 (match-end 2)
6959 'js2-jsdoc-value)))
6960 (if (match-beginning 3)
6961 (js2-set-face (match-beginning 3)
6962 (match-end 3)
6963 'js2-jsdoc-value)))
6964
6965 (defun js2-highlight-jsdoc (ast)
6966 "Highlight doc comment tags."
6967 (let ((comments (js2-ast-root-comments ast))
6968 beg end)
6969 (save-excursion
6970 (dolist (node comments)
6971 (when (eq (js2-comment-node-format node) 'jsdoc)
6972 (setq beg (js2-node-abs-pos node)
6973 end (+ beg (js2-node-len node)))
6974 (save-restriction
6975 (narrow-to-region beg end)
6976 (dolist (re (list js2-jsdoc-param-tag-regexp
6977 js2-jsdoc-typed-tag-regexp
6978 js2-jsdoc-arg-tag-regexp
6979 js2-jsdoc-link-tag-regexp
6980 js2-jsdoc-see-tag-regexp
6981 js2-jsdoc-empty-tag-regexp))
6982 (goto-char beg)
6983 (while (re-search-forward re nil t)
6984 (js2-jsdoc-highlight-helper)))
6985 ;; simple highlighting for html tags
6986 (goto-char beg)
6987 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6988 (js2-set-face (match-beginning 1)
6989 (match-end 1)
6990 'js2-jsdoc-html-tag-delimiter)
6991 (js2-set-face (match-beginning 2)
6992 (match-end 2)
6993 'js2-jsdoc-html-tag-name)
6994 (js2-set-face (match-beginning 3)
6995 (match-end 3)
6996 'js2-jsdoc-html-tag-delimiter))))))))
6997
6998 (defun js2-highlight-assign-targets (_node left right)
6999 "Highlight function properties and external variables."
7000 (let (leftpos name)
7001 ;; highlight vars and props assigned function values
7002 (when (or (js2-function-node-p right)
7003 (js2-class-node-p right))
7004 (cond
7005 ;; var foo = function() {...}
7006 ((js2-name-node-p left)
7007 (setq name left))
7008 ;; foo.bar.baz = function() {...}
7009 ((and (js2-prop-get-node-p left)
7010 (js2-name-node-p (js2-prop-get-node-right left)))
7011 (setq name (js2-prop-get-node-right left))))
7012 (when name
7013 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7014 (+ leftpos (js2-node-len name))
7015 'font-lock-function-name-face
7016 'record)))))
7017
7018 (defun js2-record-name-node (node)
7019 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7020 later. NODE must be a name node."
7021 (let ((leftpos (js2-node-abs-pos node)))
7022 (push (list node js2-current-scope
7023 leftpos
7024 (+ leftpos (js2-node-len node)))
7025 js2-recorded-identifiers)))
7026
7027 (defun js2-highlight-undeclared-vars ()
7028 "After entire parse is finished, look for undeclared variable references.
7029 We have to wait until entire buffer is parsed, since JavaScript permits var
7030 decls to occur after they're used.
7031
7032 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7033 it is considered declared."
7034 (let (name)
7035 (dolist (entry js2-recorded-identifiers)
7036 (cl-destructuring-bind (name-node scope pos end) entry
7037 (setq name (js2-name-node-name name-node))
7038 (unless (or (member name js2-global-externs)
7039 (member name js2-default-externs)
7040 (member name js2-additional-externs)
7041 (js2-get-defining-scope scope name pos))
7042 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7043 'js2-external-variable))))))
7044
7045 (defun js2--add-or-update-symbol (symbol inition used vars)
7046 "Add or update SYMBOL entry in VARS, an hash table.
7047 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7048 respectively meaning that SYMBOL is a mere declaration, an
7049 assignment or a function parameter; when USED is t, the symbol
7050 node is assumed to be an usage and thus added to the list stored
7051 in the cdr of the entry.
7052 "
7053 (let* ((nm (js2-name-node-name symbol))
7054 (es (js2-node-get-enclosing-scope symbol))
7055 (ds (js2-get-defining-scope es nm)))
7056 (when (and ds (not (equal nm "arguments")))
7057 (let* ((sym (js2-scope-get-symbol ds nm))
7058 (var (gethash sym vars))
7059 (err-var-p (js2-catch-node-p ds)))
7060 (unless inition
7061 (setq inition err-var-p))
7062 (if var
7063 (progn
7064 (when (and inition (not (equal (car var) ?P)))
7065 (setcar var inition))
7066 (when used
7067 (push symbol (cdr var))))
7068 ;; do not consider the declaration of catch parameter as an usage
7069 (when (and err-var-p used)
7070 (setq used nil))
7071 (puthash sym (cons inition (if used (list symbol))) vars))))))
7072
7073 (defun js2--classify-variables ()
7074 "Collect and classify variables declared or used within js2-mode-ast.
7075 Traverse the whole ast tree returning a summary of the variables
7076 usage as an hash-table, keyed by their corresponding symbol table
7077 entry.
7078 Each variable is described by a tuple where the car is a flag
7079 indicating whether the variable has been initialized and the cdr
7080 is a possibly empty list of name nodes where it is used. External
7081 symbols, i.e. those not present in the whole scopes hierarchy,
7082 are ignored."
7083 (let ((vars (make-hash-table :test #'eq :size 100)))
7084 (js2-visit-ast
7085 js2-mode-ast
7086 (lambda (node end-p)
7087 (when (null end-p)
7088 (cond
7089 ((js2-var-init-node-p node)
7090 ;; take note about possibly initialized declarations
7091 (let ((target (js2-var-init-node-target node))
7092 (initializer (js2-var-init-node-initializer node)))
7093 (when target
7094 (let* ((parent (js2-node-parent node))
7095 (grandparent (if parent (js2-node-parent parent)))
7096 (inited (not (null initializer))))
7097 (unless inited
7098 (setq inited
7099 (and grandparent
7100 (js2-for-in-node-p grandparent)
7101 (memq target
7102 (mapcar #'js2-var-init-node-target
7103 (js2-var-decl-node-kids
7104 (js2-for-in-node-iterator grandparent)))))))
7105 (js2--add-or-update-symbol target inited nil vars)))))
7106
7107 ((js2-assign-node-p node)
7108 ;; take note about assignments
7109 (let ((left (js2-assign-node-left node)))
7110 (when (js2-name-node-p left)
7111 (js2--add-or-update-symbol left t nil vars))))
7112
7113 ((js2-prop-get-node-p node)
7114 ;; handle x.y.z nodes, considering only x
7115 (let ((left (js2-prop-get-node-left node)))
7116 (when (js2-name-node-p left)
7117 (js2--add-or-update-symbol left nil t vars))))
7118
7119 ((js2-name-node-p node)
7120 ;; take note about used variables
7121 (let ((parent (js2-node-parent node)))
7122 (when parent
7123 (unless (or (and (js2-var-init-node-p parent) ; handled above
7124 (eq node (js2-var-init-node-target parent)))
7125 (and (js2-assign-node-p parent)
7126 (eq node (js2-assign-node-left parent)))
7127 (js2-prop-get-node-p parent))
7128 (let ((used t) inited)
7129 (cond
7130 ((and (js2-function-node-p parent)
7131 (js2-wrapper-function-p parent))
7132 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7133
7134 ((js2-for-in-node-p parent)
7135 (if (eq node (js2-for-in-node-iterator parent))
7136 (setq inited t used nil)))
7137
7138 ((js2-function-node-p parent)
7139 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7140 used nil)))
7141
7142 (unless used
7143 (let ((grandparent (js2-node-parent parent)))
7144 (when grandparent
7145 (setq used (js2-return-node-p grandparent)))))
7146
7147 (js2--add-or-update-symbol node inited used vars))))))))
7148 t))
7149 vars))
7150
7151 (defun js2--get-name-node (node)
7152 (cond
7153 ((js2-name-node-p node) node)
7154 ((js2-function-node-p node)
7155 (js2-function-node-name node))
7156 ((js2-class-node-p node)
7157 (js2-class-node-name node))
7158 ((js2-comp-loop-node-p node)
7159 (js2-comp-loop-node-iterator node))
7160 (t node)))
7161
7162 (defun js2--highlight-unused-variable (symbol info)
7163 (let ((name (js2-symbol-name symbol))
7164 (inited (car info))
7165 (refs (cdr info))
7166 pos len)
7167 (unless (and inited refs)
7168 (if refs
7169 (dolist (ref refs)
7170 (setq pos (js2-node-abs-pos ref))
7171 (setq len (js2-name-node-len ref))
7172 (js2-report-warning "msg.uninitialized.variable" name pos len
7173 'js2-warning))
7174 (when (or js2-warn-about-unused-function-arguments
7175 (not (eq inited ?P)))
7176 (let* ((symn (js2-symbol-ast-node symbol))
7177 (namen (js2--get-name-node symn)))
7178 (unless (js2-node-top-level-decl-p namen)
7179 (setq pos (js2-node-abs-pos namen))
7180 (setq len (js2-name-node-len namen))
7181 (js2-report-warning "msg.unused.variable" name pos len
7182 'js2-warning))))))))
7183
7184 (defun js2-highlight-unused-variables ()
7185 "Highlight unused variables."
7186 (let ((vars (js2--classify-variables)))
7187 (maphash #'js2--highlight-unused-variable vars)))
7188
7189 ;;;###autoload
7190 (define-minor-mode js2-highlight-unused-variables-mode
7191 "Toggle highlight of unused variables."
7192 :lighter ""
7193 (if js2-highlight-unused-variables-mode
7194 (add-hook 'js2-post-parse-callbacks
7195 #'js2-highlight-unused-variables nil t)
7196 (remove-hook 'js2-post-parse-callbacks
7197 #'js2-highlight-unused-variables t)))
7198
7199 (defun js2-set-default-externs ()
7200 "Set the value of `js2-default-externs' based on the various
7201 `js2-include-?-externs' variables."
7202 (setq js2-default-externs
7203 (append js2-ecma-262-externs
7204 (if js2-include-browser-externs js2-browser-externs)
7205 (if (and js2-include-browser-externs
7206 (>= js2-language-version 200)) js2-harmony-externs)
7207 (if js2-include-rhino-externs js2-rhino-externs)
7208 (if js2-include-node-externs js2-node-externs)
7209 (if (or js2-include-browser-externs js2-include-node-externs)
7210 js2-typed-array-externs))))
7211
7212 (defun js2-apply-jslint-globals ()
7213 (setq js2-additional-externs
7214 (nconc (js2-get-jslint-globals)
7215 js2-additional-externs)))
7216
7217 (defun js2-get-jslint-globals ()
7218 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7219 when (and (eq 'block (js2-comment-node-format node))
7220 (save-excursion
7221 (goto-char (js2-node-abs-pos node))
7222 (looking-at "/\\*global ")))
7223 append (js2-get-jslint-globals-in
7224 (match-end 0)
7225 (js2-node-abs-end node))))
7226
7227 (defun js2-get-jslint-globals-in (beg end)
7228 (let (res)
7229 (save-excursion
7230 (goto-char beg)
7231 (while (re-search-forward js2-mode-identifier-re end t)
7232 (let ((match (match-string 0)))
7233 (unless (member match '("true" "false"))
7234 (push match res)))))
7235 (nreverse res)))
7236
7237 ;;; IMenu support
7238
7239 ;; We currently only support imenu, but eventually should support speedbar and
7240 ;; possibly other browsing mechanisms.
7241
7242 ;; The basic strategy is to identify function assignment targets of the form
7243 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7244 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7245 ;; for imenu after parsing is finished.
7246
7247 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7248 ;; JavaScript, and the general problem is undecidable. However, several forms
7249 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7250 ;; include:
7251
7252 ;; function foo() -- function declaration
7253 ;; foo = function() -- function expression assigned to variable
7254 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7255 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7256 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7257 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7258 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7259 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7260 ;; function foo() {function bar() {...}} -- nested function
7261 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7262
7263 ;; This list boils down to a few forms that can be combined recursively.
7264 ;; Top-level named function declarations include both the left-hand (name)
7265 ;; and the right-hand (function value) expressions needed to produce an imenu
7266 ;; entry. The other "right-hand" forms we need to look for are:
7267 ;; - functions declared as props/getters/setters in object literals
7268 ;; - nested named function declarations
7269 ;; The "left-hand" expressions that functions can be assigned to include:
7270 ;; - local/global variables
7271 ;; - nested property-get expressions like a.b.c.d
7272 ;; - element gets like foo[10] or foo['bar'] where the index
7273 ;; expression can be trivially converted to a property name. They
7274 ;; effectively then become property gets.
7275
7276 ;; All the different definition types are canonicalized into the form
7277 ;; foo.bar.baz = position-of-function-keyword
7278
7279 ;; We need to build a trie-like structure for imenu. As an example,
7280 ;; consider the following JavaScript code:
7281
7282 ;; a = function() {...} // function at position 5
7283 ;; b = function() {...} // function at position 25
7284 ;; foo = function() {...} // function at position 100
7285 ;; foo.bar = function() {...} // function at position 200
7286 ;; foo.bar.baz = function() {...} // function at position 300
7287 ;; foo.bar.zab = function() {...} // function at position 400
7288
7289 ;; During parsing we accumulate an entry for each definition in
7290 ;; the variable `js2-imenu-recorder', like so:
7291
7292 ;; '((fn a 5)
7293 ;; (fn b 25)
7294 ;; (fn foo 100)
7295 ;; (fn foo bar 200)
7296 ;; (fn foo bar baz 300)
7297 ;; (fn foo bar zab 400))
7298
7299 ;; Where 'fn' is the respective function node.
7300 ;; After parsing these entries are merged into this alist-trie:
7301
7302 ;; '((a . 1)
7303 ;; (b . 2)
7304 ;; (foo (<definition> . 3)
7305 ;; (bar (<definition> . 6)
7306 ;; (baz . 100)
7307 ;; (zab . 200))))
7308
7309 ;; Note the wacky need for a <definition> name. The token can be anything
7310 ;; that isn't a valid JavaScript identifier, because you might make foo
7311 ;; a function and then start setting properties on it that are also functions.
7312
7313 (defun js2-prop-node-name (node)
7314 "Return the name of a node that may be a property-get/property-name.
7315 If NODE is not a valid name-node, string-node or integral number-node,
7316 returns nil. Otherwise returns the string name/value of the node."
7317 (cond
7318 ((js2-name-node-p node)
7319 (js2-name-node-name node))
7320 ((js2-string-node-p node)
7321 (js2-string-node-value node))
7322 ((and (js2-number-node-p node)
7323 (string-match "^[0-9]+$" (js2-number-node-value node)))
7324 (js2-number-node-value node))
7325 ((eq (js2-node-type node) js2-THIS)
7326 "this")
7327 ((eq (js2-node-type node) js2-SUPER)
7328 "super")))
7329
7330 (defun js2-node-qname-component (node)
7331 "Return the name of this node, if it contributes to a qname.
7332 Returns nil if the node doesn't contribute."
7333 (copy-sequence
7334 (or (js2-prop-node-name node)
7335 (if (and (js2-function-node-p node)
7336 (js2-function-node-name node))
7337 (js2-name-node-name (js2-function-node-name node))))))
7338
7339 (defun js2-record-imenu-entry (fn-node qname pos)
7340 "Add an entry to `js2-imenu-recorder'.
7341 FN-NODE should be the current item's function node.
7342
7343 Associate FN-NODE with its QNAME for later lookup.
7344 This is used in postprocessing the chain list. For each chain, we find
7345 the parent function, look up its qname, then prepend a copy of it to the chain."
7346 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7347 (unless js2-imenu-function-map
7348 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7349 (puthash fn-node qname js2-imenu-function-map))
7350
7351 (defun js2-record-imenu-functions (node &optional var)
7352 "Record function definitions for imenu.
7353 NODE is a function node or an object literal.
7354 VAR, if non-nil, is the expression that NODE is being assigned to.
7355 When passed arguments of wrong type, does nothing."
7356 (when js2-parse-ide-mode
7357 (let ((fun-p (js2-function-node-p node))
7358 qname fname-node)
7359 (cond
7360 ;; non-anonymous function declaration?
7361 ((and fun-p
7362 (not var)
7363 (setq fname-node (js2-function-node-name node)))
7364 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7365 ;; for remaining forms, compute left-side tree branch first
7366 ((and var (setq qname (js2-compute-nested-prop-get var)))
7367 (cond
7368 ;; foo.bar.baz = function
7369 (fun-p
7370 (js2-record-imenu-entry node qname (js2-node-pos node)))
7371 ;; foo.bar.baz = object-literal
7372 ;; look for nested functions: {a: {b: function() {...} }}
7373 ((js2-object-node-p node)
7374 ;; Node position here is still absolute, since the parser
7375 ;; passes the assignment target and value expressions
7376 ;; to us before they are added as children of the assignment node.
7377 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7378
7379 (defun js2-compute-nested-prop-get (node)
7380 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7381 component nodes as a list. Otherwise return nil. Element-gets are treated
7382 as property-gets if the index expression is a string, or a positive integer."
7383 (let (left right head)
7384 (cond
7385 ((or (js2-name-node-p node)
7386 (js2-this-or-super-node-p node))
7387 (list node))
7388 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7389 ((js2-prop-get-node-p node) ; foo.bar
7390 (setq left (js2-prop-get-node-left node)
7391 right (js2-prop-get-node-right node))
7392 (if (setq head (js2-compute-nested-prop-get left))
7393 (nconc head (list right))))
7394 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7395 (setq left (js2-elem-get-node-target node)
7396 right (js2-elem-get-node-element node))
7397 (if (or (js2-string-node-p right) ; ['bar']
7398 (and (js2-number-node-p right) ; [10]
7399 (string-match "^[0-9]+$"
7400 (js2-number-node-value right))))
7401 (if (setq head (js2-compute-nested-prop-get left))
7402 (nconc head (list right))))))))
7403
7404 (defun js2-record-object-literal (node qname pos)
7405 "Recursively process an object literal looking for functions.
7406 NODE is an object literal that is the right-hand child of an assignment
7407 expression. QNAME is a list of nodes representing the assignment target,
7408 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7409 POS is the absolute position of the node.
7410 We do a depth-first traversal of NODE. For any functions we find,
7411 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7412 (let (right)
7413 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7414 (let ((left (js2-infix-node-left e))
7415 ;; Element positions are relative to the parent position.
7416 (pos (+ pos (js2-node-pos e))))
7417 (cond
7418 ;; foo: function() {...}
7419 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7420 (when (js2-prop-node-name left)
7421 ;; As a policy decision, we record the position of the property,
7422 ;; not the position of the `function' keyword, since the property
7423 ;; is effectively the name of the function.
7424 (js2-record-imenu-entry right (append qname (list left)) pos)))
7425 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7426 ((js2-object-node-p right)
7427 (js2-record-object-literal right
7428 (append qname (list (js2-infix-node-left e)))
7429 (+ pos (js2-node-pos right)))))))))
7430
7431 (defun js2-node-top-level-decl-p (node)
7432 "Return t if NODE's name is defined in the top-level scope.
7433 Also returns t if NODE's name is not defined in any scope, since it implies
7434 that it's an external variable, which must also be in the top-level scope."
7435 (let* ((name (js2-prop-node-name node))
7436 (this-scope (js2-node-get-enclosing-scope node))
7437 defining-scope)
7438 (cond
7439 ((js2-this-or-super-node-p node)
7440 nil)
7441 ((null this-scope)
7442 t)
7443 ((setq defining-scope (js2-get-defining-scope this-scope name))
7444 (js2-ast-root-p defining-scope))
7445 (t t))))
7446
7447 (defun js2-wrapper-function-p (node)
7448 "Return t if NODE is a function expression that's immediately invoked.
7449 NODE must be `js2-function-node'."
7450 (let ((parent (js2-node-parent node)))
7451 (or
7452 ;; function(){...}();
7453 (and (js2-call-node-p parent)
7454 (eq node (js2-call-node-target parent)))
7455 (and (js2-paren-node-p parent)
7456 ;; (function(){...})();
7457 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7458 ;; (function(){...}).call(this);
7459 (and (js2-prop-get-node-p parent)
7460 (member (js2-name-node-name (js2-prop-get-node-right parent))
7461 '("call" "apply"))
7462 (js2-call-node-p (js2-node-parent parent))))))))
7463
7464 (defun js2-browse-postprocess-chains ()
7465 "Modify function-declaration name chains after parsing finishes.
7466 Some of the information is only available after the parse tree is complete.
7467 For instance, processing a nested scope requires a parent function node."
7468 (let (result fn parent-qname p elem)
7469 (dolist (entry js2-imenu-recorder)
7470 ;; function node goes first
7471 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7472 ;; Examine head's defining scope:
7473 ;; Pre-processed chain, or top-level/external, keep as-is.
7474 (if (or (stringp head) (js2-node-top-level-decl-p head))
7475 (push chain result)
7476 (when (js2-this-or-super-node-p head)
7477 (setq chain (cdr chain))) ; discard this-node
7478 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7479 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7480 (when (eq parent-qname 'not-found)
7481 ;; anonymous function expressions are not recorded
7482 ;; during the parse, so we need to handle this case here
7483 (setq parent-qname
7484 (if (js2-wrapper-function-p fn)
7485 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7486 (if (js2-ast-root-p grandparent)
7487 nil
7488 (gethash grandparent js2-imenu-function-map 'skip)))
7489 'skip))
7490 (puthash fn parent-qname js2-imenu-function-map))
7491 (if (eq parent-qname 'skip)
7492 ;; We don't show it, let's record that fact.
7493 (remhash current-fn js2-imenu-function-map)
7494 ;; Prepend parent fn qname to this chain.
7495 (let ((qname (append parent-qname chain)))
7496 (puthash current-fn (butlast qname) js2-imenu-function-map)
7497 (push qname result)))))))
7498 ;; Collect chains obtained by third-party code.
7499 (let (js2-imenu-recorder)
7500 (run-hooks 'js2-build-imenu-callbacks)
7501 (dolist (entry js2-imenu-recorder)
7502 (push (cdr entry) result)))
7503 ;; Finally replace each node in each chain with its name.
7504 (dolist (chain result)
7505 (setq p chain)
7506 (while p
7507 (if (js2-node-p (setq elem (car p)))
7508 (setcar p (js2-node-qname-component elem)))
7509 (setq p (cdr p))))
7510 result))
7511
7512 ;; Merge name chains into a trie-like tree structure of nested lists.
7513 ;; To simplify construction of the trie, we first build it out using the rule
7514 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7515 ;; [key, num-or-list]. The second element can be a number; if so, this key
7516 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7517 ;; associated with the key at this level.) Otherwise the second element is
7518 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7519 ;; a simple recursive formulation.
7520 ;;
7521 ;; js2-mode is building the data structure for imenu. The imenu documentation
7522 ;; claims that it's the structure above, but in practice it wants the children
7523 ;; at the same list level as the key for that level, which is how I've drawn
7524 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7525 ;; list wrapper around the children at each level.
7526 ;;
7527 ;; A completed nested imenu-alist entry looks like this:
7528 ;; '(("foo"
7529 ;; ("<definition>" . 7)
7530 ;; ("bar"
7531 ;; ("a" . 40)
7532 ;; ("b" . 60))))
7533 ;;
7534 ;; In particular, the documentation for `imenu--index-alist' says that
7535 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7536 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7537
7538 (defun js2-treeify (lst)
7539 "Convert (a b c d) to (a ((b ((c d)))))."
7540 (if (null (cddr lst)) ; list length <= 2
7541 lst
7542 (list (car lst) (list (js2-treeify (cdr lst))))))
7543
7544 (defun js2-build-alist-trie (chains trie)
7545 "Merge declaration name chains into a trie-like alist structure for imenu.
7546 CHAINS is the qname chain list produced during parsing. TRIE is a
7547 list of elements built up so far."
7548 (let (head tail pos branch kids)
7549 (dolist (chain chains)
7550 (setq head (car chain)
7551 tail (cdr chain)
7552 pos (if (numberp (car tail)) (car tail))
7553 branch (js2-find-if (lambda (n)
7554 (string= (car n) head))
7555 trie)
7556 kids (cl-second branch))
7557 (cond
7558 ;; case 1: this key isn't in the trie yet
7559 ((null branch)
7560 (if trie
7561 (setcdr (last trie) (list (js2-treeify chain)))
7562 (setq trie (list (js2-treeify chain)))))
7563 ;; case 2: key is present with a single number entry: replace w/ list
7564 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7565 ;; ("<definition>" 20)))
7566 ((numberp kids)
7567 (setcar (cdr branch)
7568 (list (list "<definition-1>" kids)
7569 (if pos
7570 (list "<definition-2>" pos)
7571 (js2-treeify tail)))))
7572 ;; case 3: key is there (with kids), and we're a number entry
7573 (pos
7574 (setcdr (last kids)
7575 (list
7576 (list (format "<definition-%d>"
7577 (1+ (cl-loop for kid in kids
7578 count (eq ?< (aref (car kid) 0)))))
7579 pos))))
7580 ;; case 4: key is there with kids, need to merge in our chain
7581 (t
7582 (js2-build-alist-trie (list tail) kids))))
7583 trie))
7584
7585 (defun js2-flatten-trie (trie)
7586 "Convert TRIE to imenu-format.
7587 Recurses through nodes, and for each one whose second element is a list,
7588 appends the list's flattened elements to the current element. Also
7589 changes the tails into conses. For instance, this pre-flattened trie
7590
7591 '(a ((b 20)
7592 (c ((d 30)
7593 (e 40)))))
7594
7595 becomes
7596
7597 '(a (b . 20)
7598 (c (d . 30)
7599 (e . 40)))
7600
7601 Note that the root of the trie has no key, just a list of chains.
7602 This is also true for the value of any key with multiple children,
7603 e.g. key 'c' in the example above."
7604 (cond
7605 ((listp (car trie))
7606 (mapcar #'js2-flatten-trie trie))
7607 (t
7608 (if (numberp (cl-second trie))
7609 (cons (car trie) (cl-second trie))
7610 ;; else pop list and append its kids
7611 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7612
7613 (defun js2-build-imenu-index ()
7614 "Turn `js2-imenu-recorder' into an imenu data structure."
7615 (when (eq js2-imenu-recorder 'empty)
7616 (setq js2-imenu-recorder nil))
7617 (let* ((chains (js2-browse-postprocess-chains))
7618 (result (js2-build-alist-trie chains nil)))
7619 (js2-flatten-trie result)))
7620
7621 (defun js2-test-print-chains (chains)
7622 "Print a list of qname chains.
7623 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7624 i.e. one or more nodes, and an integer position as the list tail."
7625 (mapconcat (lambda (chain)
7626 (concat "("
7627 (mapconcat (lambda (elem)
7628 (if (js2-node-p elem)
7629 (or (js2-node-qname-component elem)
7630 "nil")
7631 (number-to-string elem)))
7632 chain
7633 " ")
7634 ")"))
7635 chains
7636 "\n"))
7637
7638 ;;; Parser
7639
7640 (defconst js2-version "1.8.5"
7641 "Version of JavaScript supported.")
7642
7643 (defun js2-record-face (face &optional token)
7644 "Record a style run of FACE for TOKEN or the current token."
7645 (unless token (setq token (js2-current-token)))
7646 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7647
7648 (defsubst js2-node-end (n)
7649 "Computes the absolute end of node N.
7650 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7651 is only true until the node is added to its parent; i.e., while parsing."
7652 (+ (js2-node-pos n)
7653 (js2-node-len n)))
7654
7655 (defun js2-record-comment (token)
7656 "Record a comment in `js2-scanned-comments'."
7657 (let ((ct (js2-token-comment-type token))
7658 (beg (js2-token-beg token))
7659 (end (js2-token-end token)))
7660 (push (make-js2-comment-node :len (- end beg)
7661 :format ct)
7662 js2-scanned-comments)
7663 (when js2-parse-ide-mode
7664 (js2-record-face (if (eq ct 'jsdoc)
7665 'font-lock-doc-face
7666 'font-lock-comment-face)
7667 token)
7668 (when (memq ct '(html preprocessor))
7669 ;; Tell cc-engine the bounds of the comment.
7670 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7671
7672 (defun js2-peek-token ()
7673 "Return the next token type without consuming it.
7674 If `js2-ti-lookahead' is positive, return the type of next token
7675 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7676 (if (not (zerop js2-ti-lookahead))
7677 (js2-token-type
7678 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7679 (let ((tt (js2-get-token-internal nil)))
7680 (js2-unget-token)
7681 tt)))
7682
7683 (defalias 'js2-next-token 'js2-get-token)
7684
7685 (defun js2-match-token (match &optional dont-unget)
7686 "Get next token and return t if it matches MATCH, a bytecode.
7687 Returns nil and consumes nothing if MATCH is not the next token."
7688 (if (/= (js2-get-token) match)
7689 (ignore (unless dont-unget (js2-unget-token)))
7690 t))
7691
7692 (defun js2-match-contextual-kwd (name)
7693 "Consume and return t if next token is `js2-NAME', and its
7694 string is NAME. Returns nil and keeps current token otherwise."
7695 (if (or (/= (js2-get-token) js2-NAME)
7696 (not (string= (js2-current-token-string) name)))
7697 (progn
7698 (js2-unget-token)
7699 nil)
7700 (js2-record-face 'font-lock-keyword-face)
7701 t))
7702
7703 (defun js2-get-prop-name-token ()
7704 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7705
7706 (defun js2-match-prop-name ()
7707 "Consume token and return t if next token is a valid property name.
7708 If `js2-language-version' is >= 180, a keyword or reserved word
7709 is considered valid name as well."
7710 (if (eq js2-NAME (js2-get-prop-name-token))
7711 t
7712 (js2-unget-token)
7713 nil))
7714
7715 (defun js2-must-match-prop-name (msg-id &optional pos len)
7716 (if (js2-match-prop-name)
7717 t
7718 (js2-report-error msg-id nil pos len)
7719 nil))
7720
7721 (defun js2-peek-token-or-eol ()
7722 "Return js2-EOL if the next token immediately follows a newline.
7723 Else returns the next token. Used in situations where we don't
7724 consider certain token types valid if they are preceded by a newline.
7725 One example is the postfix ++ or -- operator, which has to be on the
7726 same line as its operand."
7727 (let ((tt (js2-get-token))
7728 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7729 (js2-unget-token)
7730 (if follows-eol
7731 js2-EOL
7732 tt)))
7733
7734 (defun js2-must-match (token msg-id &optional pos len)
7735 "Match next token to token code TOKEN, or record a syntax error.
7736 MSG-ID is the error message to report if the match fails.
7737 Returns t on match, nil if no match."
7738 (if (js2-match-token token t)
7739 t
7740 (js2-report-error msg-id nil pos len)
7741 (js2-unget-token)
7742 nil))
7743
7744 (defun js2-must-match-name (msg-id)
7745 (if (js2-match-token js2-NAME t)
7746 t
7747 (if (eq (js2-current-token-type) js2-RESERVED)
7748 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7749 (js2-report-error msg-id)
7750 (js2-unget-token))
7751 nil))
7752
7753 (defsubst js2-inside-function ()
7754 (cl-plusp js2-nesting-of-function))
7755
7756 (defun js2-set-requires-activation ()
7757 (if (js2-function-node-p js2-current-script-or-fn)
7758 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7759
7760 (defun js2-check-activation-name (name _token)
7761 (when (js2-inside-function)
7762 ;; skip language-version 1.2 check from Rhino
7763 (if (or (string= "arguments" name)
7764 (and js2-compiler-activation-names ; only used in codegen
7765 (gethash name js2-compiler-activation-names)))
7766 (js2-set-requires-activation))))
7767
7768 (defun js2-set-is-generator ()
7769 (let ((fn-node js2-current-script-or-fn))
7770 (when (and (js2-function-node-p fn-node)
7771 (not (js2-function-node-generator-type fn-node)))
7772 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7773
7774 (defun js2-must-have-xml ()
7775 (unless js2-compiler-xml-available
7776 (js2-report-error "msg.XML.not.available")))
7777
7778 (defun js2-push-scope (scope)
7779 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7780 (cl-assert (js2-scope-p scope))
7781 (cl-assert (null (js2-scope-parent-scope scope)))
7782 (cl-assert (not (eq js2-current-scope scope)))
7783 (setf (js2-scope-parent-scope scope) js2-current-scope
7784 js2-current-scope scope))
7785
7786 (defsubst js2-pop-scope ()
7787 (setq js2-current-scope
7788 (js2-scope-parent-scope js2-current-scope)))
7789
7790 (defun js2-enter-loop (loop-node)
7791 (push loop-node js2-loop-set)
7792 (push loop-node js2-loop-and-switch-set)
7793 (js2-push-scope loop-node)
7794 ;; Tell the current labeled statement (if any) its statement,
7795 ;; and set the jump target of the first label to the loop.
7796 ;; These are used in `js2-parse-continue' to verify that the
7797 ;; continue target is an actual labeled loop. (And for codegen.)
7798 (when js2-labeled-stmt
7799 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7800 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7801 js2-labeled-stmt))) loop-node)))
7802
7803 (defun js2-exit-loop ()
7804 (pop js2-loop-set)
7805 (pop js2-loop-and-switch-set)
7806 (js2-pop-scope))
7807
7808 (defsubst js2-enter-switch (switch-node)
7809 (push switch-node js2-loop-and-switch-set))
7810
7811 (defsubst js2-exit-switch ()
7812 (pop js2-loop-and-switch-set))
7813
7814 (defsubst js2-get-directive (node)
7815 "Return NODE's value if it is a directive, nil otherwise.
7816
7817 A directive is an otherwise-meaningless expression statement
7818 consisting of a string literal, such as \"use strict\"."
7819 (and (js2-expr-stmt-node-p node)
7820 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7821 (js2-string-node-value node)))
7822
7823 (defun js2-parse (&optional buf cb)
7824 "Tell the js2 parser to parse a region of JavaScript.
7825
7826 BUF is a buffer or buffer name containing the code to parse.
7827 Call `narrow-to-region' first to parse only part of the buffer.
7828
7829 The returned AST root node is given some additional properties:
7830 `node-count' - total number of nodes in the AST
7831 `buffer' - BUF. The buffer it refers to may change or be killed,
7832 so the value is not necessarily reliable.
7833
7834 An optional callback CB can be specified to report parsing
7835 progress. If `(functionp CB)' returns t, it will be called with
7836 the current line number once before parsing begins, then again
7837 each time the lexer reaches a new line number.
7838
7839 CB can also be a list of the form `(symbol cb ...)' to specify
7840 multiple callbacks with different criteria. Each symbol is a
7841 criterion keyword, and the following element is the callback to
7842 call
7843
7844 :line - called whenever the line number changes
7845 :token - called for each new token consumed
7846
7847 The list of criteria could be extended to include entering or
7848 leaving a statement, an expression, or a function definition."
7849 (if (and cb (not (functionp cb)))
7850 (error "criteria callbacks not yet implemented"))
7851 (let ((inhibit-point-motion-hooks t)
7852 (js2-compiler-xml-available (>= js2-language-version 160))
7853 ;; This is a recursive-descent parser, so give it a big stack.
7854 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7855 (max-specpdl-size (max max-specpdl-size 3000))
7856 (case-fold-search nil)
7857 ast)
7858 (with-current-buffer (or buf (current-buffer))
7859 (setq js2-scanned-comments nil
7860 js2-parsed-errors nil
7861 js2-parsed-warnings nil
7862 js2-imenu-recorder nil
7863 js2-imenu-function-map nil
7864 js2-label-set nil)
7865 (js2-init-scanner)
7866 (setq ast (js2-do-parse))
7867 (unless js2-ts-hit-eof
7868 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7869 (setf (js2-ast-root-errors ast) js2-parsed-errors
7870 (js2-ast-root-warnings ast) js2-parsed-warnings)
7871 ;; if we didn't find any declarations, put a dummy in this list so we
7872 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7873 (unless js2-imenu-recorder
7874 (setq js2-imenu-recorder 'empty))
7875 (run-hooks 'js2-parse-finished-hook)
7876 ast)))
7877
7878 ;; Corresponds to Rhino's Parser.parse() method.
7879 (defun js2-do-parse ()
7880 "Parse current buffer starting from current point.
7881 Scanner should be initialized."
7882 (let ((pos js2-ts-cursor)
7883 (end js2-ts-cursor) ; in case file is empty
7884 root n tt
7885 (in-directive-prologue t)
7886 (js2-in-use-strict-directive js2-in-use-strict-directive)
7887 directive)
7888 ;; initialize buffer-local parsing vars
7889 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7890 js2-current-script-or-fn root
7891 js2-current-scope root
7892 js2-nesting-of-function 0
7893 js2-labeled-stmt nil
7894 js2-recorded-identifiers nil ; for js2-highlight
7895 js2-in-use-strict-directive nil)
7896 (while (/= (setq tt (js2-get-token)) js2-EOF)
7897 (if (= tt js2-FUNCTION)
7898 (progn
7899 (setq n (if js2-called-by-compile-function
7900 (js2-parse-function-expr)
7901 (js2-parse-function-stmt))))
7902 ;; not a function - parse a statement
7903 (js2-unget-token)
7904 (setq n (js2-parse-statement))
7905 (when in-directive-prologue
7906 (setq directive (js2-get-directive n))
7907 (cond
7908 ((null directive)
7909 (setq in-directive-prologue nil))
7910 ((string= directive "use strict")
7911 (setq js2-in-use-strict-directive t)))))
7912 ;; add function or statement to script
7913 (setq end (js2-node-end n))
7914 (js2-block-node-push root n))
7915 ;; add comments to root in lexical order
7916 (when js2-scanned-comments
7917 ;; if we find a comment beyond end of normal kids, use its end
7918 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7919 (dolist (comment js2-scanned-comments)
7920 (push comment (js2-ast-root-comments root))
7921 (js2-node-add-children root comment)))
7922 (setf (js2-node-len root) (- end pos))
7923 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7924 ;; Give extensions a chance to muck with things before highlighting starts.
7925 (let ((js2-additional-externs js2-additional-externs))
7926 (save-excursion
7927 (run-hooks 'js2-post-parse-callbacks))
7928 (js2-highlight-undeclared-vars))
7929 root))
7930
7931 (defun js2-parse-function-closure-body (fn-node)
7932 "Parse a JavaScript 1.8 function closure body."
7933 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7934 (if js2-ts-hit-eof
7935 (js2-report-error "msg.no.brace.body" nil
7936 (js2-node-pos fn-node)
7937 (- js2-ts-cursor (js2-node-pos fn-node)))
7938 (js2-node-add-children fn-node
7939 (setf (js2-function-node-body fn-node)
7940 (js2-parse-expr t))))))
7941
7942 (defun js2-parse-function-body (fn-node)
7943 (js2-must-match js2-LC "msg.no.brace.body"
7944 (js2-node-pos fn-node)
7945 (- js2-ts-cursor (js2-node-pos fn-node)))
7946 (let ((pos (js2-current-token-beg)) ; LC position
7947 (pn (make-js2-block-node)) ; starts at LC position
7948 tt
7949 end
7950 not-in-directive-prologue
7951 node
7952 directive)
7953 (cl-incf js2-nesting-of-function)
7954 (unwind-protect
7955 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7956 (= tt js2-EOF)
7957 (= tt js2-RC)))
7958 (js2-block-node-push
7959 pn
7960 (if (/= tt js2-FUNCTION)
7961 (if not-in-directive-prologue
7962 (js2-parse-statement)
7963 (setq node (js2-parse-statement)
7964 directive (js2-get-directive node))
7965 (cond
7966 ((null directive)
7967 (setq not-in-directive-prologue t))
7968 ((string= directive "use strict")
7969 ;; Back up and reparse the function, because new rules apply
7970 ;; to the function name and parameters.
7971 (when (not js2-in-use-strict-directive)
7972 (setq js2-in-use-strict-directive t)
7973 (throw 'reparse t))))
7974 node)
7975 (js2-get-token)
7976 (js2-parse-function-stmt))))
7977 (cl-decf js2-nesting-of-function))
7978 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7979 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7980 (setq end (js2-current-token-end)))
7981 (setf (js2-node-pos pn) pos
7982 (js2-node-len pn) (- end pos))
7983 (setf (js2-function-node-body fn-node) pn)
7984 (js2-node-add-children fn-node pn)
7985 pn))
7986
7987 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7988 "Declare and fontify destructuring parameters inside NODE.
7989 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
7990
7991 Return a list of `js2-name-node' nodes representing the symbols
7992 declared; probably to check them for errors."
7993 (let (name-nodes)
7994 (cond
7995 ((js2-name-node-p node)
7996 (let (leftpos)
7997 (js2-define-symbol decl-type (js2-name-node-name node)
7998 node ignore-not-in-block)
7999 (when face
8000 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8001 (+ leftpos (js2-node-len node))
8002 face 'record))
8003 (list node)))
8004 ((js2-object-node-p node)
8005 (dolist (elem (js2-object-node-elems node))
8006 ;; js2-infix-node-p catches both object prop node and initialized
8007 ;; binding element (which is directly an infix node).
8008 (when (js2-infix-node-p elem)
8009 (push (js2-define-destruct-symbols
8010 (js2-infix-node-left elem)
8011 decl-type face ignore-not-in-block)
8012 name-nodes)))
8013 (apply #'append (nreverse name-nodes)))
8014 ((js2-array-node-p node)
8015 (dolist (elem (js2-array-node-elems node))
8016 (when elem
8017 (if (js2-infix-node-p elem) (setq elem (js2-infix-node-left elem)))
8018 (push (js2-define-destruct-symbols
8019 elem decl-type face ignore-not-in-block)
8020 name-nodes)))
8021 (apply #'append (nreverse name-nodes)))
8022 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8023 (js2-node-len node))
8024 nil))))
8025
8026 (defvar js2-illegal-strict-identifiers
8027 '("eval" "arguments")
8028 "Identifiers not allowed as variables in strict mode.")
8029
8030 (defun js2-check-strict-identifier (name-node)
8031 "Check that NAME-NODE makes a legal strict mode identifier."
8032 (when js2-in-use-strict-directive
8033 (let ((param-name (js2-name-node-name name-node)))
8034 (when (member param-name js2-illegal-strict-identifiers)
8035 (js2-report-error "msg.bad.id.strict" param-name
8036 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8037
8038 (defun js2-check-strict-function-params (preceding-params params)
8039 "Given PRECEDING-PARAMS in a function's parameter list, check
8040 for strict mode errors caused by PARAMS."
8041 (when js2-in-use-strict-directive
8042 (dolist (param params)
8043 (let ((param-name (js2-name-node-name param)))
8044 (js2-check-strict-identifier param)
8045 (when (cl-some (lambda (param)
8046 (string= (js2-name-node-name param) param-name))
8047 preceding-params)
8048 (js2-report-error "msg.dup.param.strict" param-name
8049 (js2-node-abs-pos param) (js2-node-len param)))))))
8050
8051 (defun js2-parse-function-params (function-type fn-node pos)
8052 "Parse the parameters of a function of FUNCTION-TYPE
8053 represented by FN-NODE at POS."
8054 (if (js2-match-token js2-RP)
8055 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8056 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8057 (eq (js2-current-token-type) js2-NAME)))
8058 params param
8059 param-name-nodes new-param-name-nodes
8060 rest-param-at)
8061 (when paren-free-arrow
8062 (js2-unget-token))
8063 (cl-loop for tt = (js2-peek-token)
8064 do
8065 (cond
8066 ;; destructuring param
8067 ((and (not paren-free-arrow)
8068 (or (= tt js2-LB) (= tt js2-LC)))
8069 (js2-get-token)
8070 (setq param (js2-parse-destruct-primary-expr)
8071 new-param-name-nodes (js2-define-destruct-symbols
8072 param js2-LP 'js2-function-param))
8073 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8074 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8075 (push param params))
8076 ;; variable name
8077 (t
8078 (when (and (>= js2-language-version 200)
8079 (not paren-free-arrow)
8080 (js2-match-token js2-TRIPLEDOT)
8081 (not rest-param-at))
8082 ;; to report errors if there are more parameters
8083 (setq rest-param-at (length params)))
8084 (js2-must-match-name "msg.no.parm")
8085 (js2-record-face 'js2-function-param)
8086 (setq param (js2-create-name-node))
8087 (js2-define-symbol js2-LP (js2-current-token-string) param)
8088 (js2-check-strict-function-params param-name-nodes (list param))
8089 (setq param-name-nodes (append param-name-nodes (list param)))
8090 ;; default parameter value
8091 (when (and (>= js2-language-version 200)
8092 (js2-match-token js2-ASSIGN))
8093 (cl-assert (not paren-free-arrow))
8094 (let* ((pos (js2-node-pos param))
8095 (tt (js2-current-token-type))
8096 (op-pos (- (js2-current-token-beg) pos))
8097 (left param)
8098 (right (js2-parse-assign-expr))
8099 (len (- (js2-node-end right) pos)))
8100 (setq param (make-js2-assign-node
8101 :type tt :pos pos :len len :op-pos op-pos
8102 :left left :right right))
8103 (js2-node-add-children param left right)))
8104 (push param params)))
8105 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8106 (js2-report-error "msg.param.after.rest" nil
8107 (js2-node-pos param) (js2-node-len param)))
8108 while
8109 (js2-match-token js2-COMMA))
8110 (when (and (not paren-free-arrow)
8111 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8112 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8113 (when rest-param-at
8114 (setf (js2-function-node-rest-p fn-node) t))
8115 (dolist (p params)
8116 (js2-node-add-children fn-node p)
8117 (push p (js2-function-node-params fn-node))))))
8118
8119 (defun js2-check-inconsistent-return-warning (fn-node name)
8120 "Possibly show inconsistent-return warning.
8121 Last token scanned is the close-curly for the function body."
8122 (when (and js2-mode-show-strict-warnings
8123 js2-strict-inconsistent-return-warning
8124 (not (js2-has-consistent-return-usage
8125 (js2-function-node-body fn-node))))
8126 ;; Have it extend from close-curly to bol or beginning of block.
8127 (let ((pos (save-excursion
8128 (goto-char (js2-current-token-end))
8129 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8130 (point-at-bol))))
8131 (end (js2-current-token-end)))
8132 (if (cl-plusp (js2-name-node-length name))
8133 (js2-add-strict-warning "msg.no.return.value"
8134 (js2-name-node-name name) pos end)
8135 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8136
8137 (defun js2-parse-function-stmt ()
8138 (let ((pos (js2-current-token-beg))
8139 (star-p (js2-match-token js2-MUL)))
8140 (js2-must-match-name "msg.unnamed.function.stmt")
8141 (let ((name (js2-create-name-node t))
8142 pn member-expr)
8143 (cond
8144 ((js2-match-token js2-LP)
8145 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8146 (js2-allow-member-expr-as-function-name
8147 (setq member-expr (js2-parse-member-expr-tail nil name))
8148 (js2-parse-highlight-member-expr-fn-name member-expr)
8149 (js2-must-match js2-LP "msg.no.paren.parms")
8150 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8151 (js2-function-node-member-expr pn) member-expr)
8152 pn)
8153 (t
8154 (js2-report-error "msg.no.paren.parms")
8155 (make-js2-error-node))))))
8156
8157 (defun js2-parse-function-expr ()
8158 (let ((pos (js2-current-token-beg))
8159 (star-p (js2-match-token js2-MUL))
8160 name)
8161 (when (js2-match-token js2-NAME)
8162 (setq name (js2-create-name-node t)))
8163 (js2-must-match js2-LP "msg.no.paren.parms")
8164 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8165
8166 (defun js2-parse-function-internal (function-type pos star-p &optional name)
8167 (let (fn-node lp)
8168 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8169 (setq lp (js2-current-token-beg)))
8170 (setf fn-node (make-js2-function-node :pos pos
8171 :name name
8172 :form function-type
8173 :lp (if lp (- lp pos))
8174 :generator-type (and star-p 'STAR)))
8175 (when name
8176 (js2-set-face (js2-node-pos name) (js2-node-end name)
8177 'font-lock-function-name-face 'record)
8178 (when (and (eq function-type 'FUNCTION_STATEMENT)
8179 (cl-plusp (js2-name-node-length name)))
8180 ;; Function statements define a symbol in the enclosing scope
8181 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8182 (when js2-in-use-strict-directive
8183 (js2-check-strict-identifier name)))
8184 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8185 ;; 1. Nested functions are not affected by the dynamic scope flag
8186 ;; as dynamic scope is already a parent of their scope.
8187 ;; 2. Functions defined under the with statement also immune to
8188 ;; this setup, in which case dynamic scope is ignored in favor
8189 ;; of the with object.
8190 (setf (js2-function-node-ignore-dynamic fn-node) t))
8191 ;; dynamically bind all the per-function variables
8192 (let ((js2-current-script-or-fn fn-node)
8193 (js2-current-scope fn-node)
8194 (js2-nesting-of-with 0)
8195 (js2-end-flags 0)
8196 js2-label-set
8197 js2-loop-set
8198 js2-loop-and-switch-set)
8199 (js2-parse-function-params function-type fn-node pos)
8200 (when (eq function-type 'FUNCTION_ARROW)
8201 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8202 (if (and (>= js2-language-version 180)
8203 (/= (js2-peek-token) js2-LC))
8204 (js2-parse-function-closure-body fn-node)
8205 (js2-parse-function-body fn-node))
8206 (js2-check-inconsistent-return-warning fn-node name)
8207
8208 (when name
8209 (js2-node-add-children fn-node name)
8210 ;; Function expressions define a name only in the body of the
8211 ;; function, and only if not hidden by a parameter name
8212 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8213 (null (js2-scope-get-symbol js2-current-scope
8214 (js2-name-node-name name))))
8215 (js2-define-symbol js2-FUNCTION
8216 (js2-name-node-name name)
8217 fn-node))
8218 (when (eq function-type 'FUNCTION_STATEMENT)
8219 (js2-record-imenu-functions fn-node))))
8220
8221 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8222 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8223 ;; We wait until after parsing the function to set its parent scope,
8224 ;; since `js2-define-symbol' needs the defining-scope check to stop
8225 ;; at the function boundary when checking for redeclarations.
8226 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8227 fn-node))
8228
8229 (defun js2-parse-function (function-type pos star-p &optional name)
8230 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8231 beginning of the first token (function keyword, unless it's an
8232 arrow function), NAME is js2-name-node."
8233 (let ((continue t)
8234 ts-state
8235 fn-node
8236 ;; Preserve strict state outside this function.
8237 (js2-in-use-strict-directive js2-in-use-strict-directive))
8238 ;; Parse multiple times if a new strict mode directive is discovered in the
8239 ;; function body, as new rules will be retroactively applied to the legality
8240 ;; of function names and parameters.
8241 (while continue
8242 (setq ts-state (make-js2-ts-state))
8243 (setq continue (catch 'reparse
8244 (setq fn-node (js2-parse-function-internal
8245 function-type pos star-p name))
8246 ;; Don't continue.
8247 nil))
8248 (when continue
8249 (js2-ts-seek ts-state)))
8250 fn-node))
8251
8252 (defun js2-parse-statements (&optional parent)
8253 "Parse a statement list. Last token consumed must be js2-LC.
8254
8255 PARENT can be a `js2-block-node', in which case the statements are
8256 appended to PARENT. Otherwise a new `js2-block-node' is created
8257 and returned.
8258
8259 This function does not match the closing js2-RC: the caller
8260 matches the RC so it can provide a suitable error message if not
8261 matched. This means it's up to the caller to set the length of
8262 the node to include the closing RC. The node start pos is set to
8263 the absolute buffer start position, and the caller should fix it
8264 up to be relative to the parent node. All children of this block
8265 node are given relative start positions and correct lengths."
8266 (let ((pn (or parent (make-js2-block-node)))
8267 tt)
8268 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8269 (/= tt js2-RC))
8270 (js2-block-node-push pn (js2-parse-statement)))
8271 pn))
8272
8273 (defun js2-parse-statement ()
8274 (let (pn beg end)
8275 ;; coarse-grained user-interrupt check - needs work
8276 (and js2-parse-interruptable-p
8277 (zerop (% (cl-incf js2-parse-stmt-count)
8278 js2-statements-per-pause))
8279 (input-pending-p)
8280 (throw 'interrupted t))
8281 (setq pn (js2-statement-helper))
8282 ;; no-side-effects warning check
8283 (unless (js2-node-has-side-effects pn)
8284 (setq end (js2-node-end pn))
8285 (save-excursion
8286 (goto-char end)
8287 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8288 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8289 pn))
8290
8291 ;; These correspond to the switch cases in Parser.statementHelper
8292 (defconst js2-parsers
8293 (let ((parsers (make-vector js2-num-tokens
8294 #'js2-parse-expr-stmt)))
8295 (aset parsers js2-BREAK #'js2-parse-break)
8296 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8297 (aset parsers js2-CONST #'js2-parse-const-var)
8298 (aset parsers js2-CONTINUE #'js2-parse-continue)
8299 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8300 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8301 (aset parsers js2-DO #'js2-parse-do)
8302 (aset parsers js2-EXPORT #'js2-parse-export)
8303 (aset parsers js2-FOR #'js2-parse-for)
8304 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8305 (aset parsers js2-IF #'js2-parse-if)
8306 (aset parsers js2-IMPORT #'js2-parse-import)
8307 (aset parsers js2-LC #'js2-parse-block)
8308 (aset parsers js2-LET #'js2-parse-let-stmt)
8309 (aset parsers js2-NAME #'js2-parse-name-or-label)
8310 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8311 (aset parsers js2-SEMI #'js2-parse-semi)
8312 (aset parsers js2-SWITCH #'js2-parse-switch)
8313 (aset parsers js2-THROW #'js2-parse-throw)
8314 (aset parsers js2-TRY #'js2-parse-try)
8315 (aset parsers js2-VAR #'js2-parse-const-var)
8316 (aset parsers js2-WHILE #'js2-parse-while)
8317 (aset parsers js2-WITH #'js2-parse-with)
8318 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8319 parsers)
8320 "A vector mapping token types to parser functions.")
8321
8322 (defun js2-parse-warn-missing-semi (beg end)
8323 (and js2-mode-show-strict-warnings
8324 js2-strict-missing-semi-warning
8325 (js2-add-strict-warning
8326 "msg.missing.semi" nil
8327 ;; back up to beginning of statement or line
8328 (max beg (save-excursion
8329 (goto-char end)
8330 (point-at-bol)))
8331 end)))
8332
8333 (defconst js2-no-semi-insertion
8334 (list js2-IF
8335 js2-SWITCH
8336 js2-WHILE
8337 js2-DO
8338 js2-FOR
8339 js2-TRY
8340 js2-WITH
8341 js2-LC
8342 js2-ERROR
8343 js2-SEMI
8344 js2-CLASS
8345 js2-FUNCTION
8346 js2-EXPORT)
8347 "List of tokens that don't do automatic semicolon insertion.")
8348
8349 (defconst js2-autoinsert-semi-and-warn
8350 (list js2-ERROR js2-EOF js2-RC))
8351
8352 (defun js2-statement-helper ()
8353 (let* ((tt (js2-get-token))
8354 (first-tt tt)
8355 (parser (if (= tt js2-ERROR)
8356 #'js2-parse-semi
8357 (aref js2-parsers tt)))
8358 pn)
8359 ;; If the statement is set, then it's been told its label by now.
8360 (and js2-labeled-stmt
8361 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8362 (setq js2-labeled-stmt nil))
8363 (setq pn (funcall parser))
8364 ;; Don't do auto semi insertion for certain statement types.
8365 (unless (or (memq first-tt js2-no-semi-insertion)
8366 (js2-labeled-stmt-node-p pn))
8367 (js2-auto-insert-semicolon pn))
8368 pn))
8369
8370 (defun js2-auto-insert-semicolon (pn)
8371 (let* ((tt (js2-get-token))
8372 (pos (js2-node-pos pn)))
8373 (cond
8374 ((= tt js2-SEMI)
8375 ;; extend the node bounds to include the semicolon.
8376 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8377 ((memq tt js2-autoinsert-semi-and-warn)
8378 (js2-unget-token) ; Not ';', do not consume.
8379 ;; Autoinsert ;
8380 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8381 (t
8382 (if (not (js2-token-follows-eol-p (js2-current-token)))
8383 ;; Report error if no EOL or autoinsert ';' otherwise
8384 (js2-report-error "msg.no.semi.stmt")
8385 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8386 (js2-unget-token) ; Not ';', do not consume.
8387 ))))
8388
8389 (defun js2-parse-condition ()
8390 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8391 The parens are discarded and the expression node is returned.
8392 The `pos' field of the return value is set to an absolute position
8393 that must be fixed up by the caller.
8394 Return value is a list (EXPR LP RP), with absolute paren positions."
8395 (let (pn lp rp)
8396 (if (js2-must-match js2-LP "msg.no.paren.cond")
8397 (setq lp (js2-current-token-beg)))
8398 (setq pn (js2-parse-expr))
8399 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8400 (setq rp (js2-current-token-beg)))
8401 ;; Report strict warning on code like "if (a = 7) ..."
8402 (if (and js2-strict-cond-assign-warning
8403 (js2-assign-node-p pn))
8404 (js2-add-strict-warning "msg.equal.as.assign" nil
8405 (js2-node-pos pn)
8406 (+ (js2-node-pos pn)
8407 (js2-node-len pn))))
8408 (list pn lp rp)))
8409
8410 (defun js2-parse-if ()
8411 "Parser for if-statement. Last matched token must be js2-IF."
8412 (let ((pos (js2-current-token-beg))
8413 cond if-true if-false else-pos end pn)
8414 (setq cond (js2-parse-condition)
8415 if-true (js2-parse-statement)
8416 if-false (if (js2-match-token js2-ELSE)
8417 (progn
8418 (setq else-pos (- (js2-current-token-beg) pos))
8419 (js2-parse-statement)))
8420 end (js2-node-end (or if-false if-true))
8421 pn (make-js2-if-node :pos pos
8422 :len (- end pos)
8423 :condition (car cond)
8424 :then-part if-true
8425 :else-part if-false
8426 :else-pos else-pos
8427 :lp (js2-relpos (cl-second cond) pos)
8428 :rp (js2-relpos (cl-third cond) pos)))
8429 (js2-node-add-children pn (car cond) if-true if-false)
8430 pn))
8431
8432 (defun js2-parse-import ()
8433 "Parse import statement. The current token must be js2-IMPORT."
8434 (unless (js2-ast-root-p js2-current-scope)
8435 (js2-report-error "msg.mod.import.decl.at.top.level"))
8436 (let ((beg (js2-current-token-beg)))
8437 (cond ((js2-match-token js2-STRING)
8438 (make-js2-import-node
8439 :pos beg
8440 :len (- (js2-current-token-end) beg)
8441 :module-id (js2-current-token-string)))
8442 (t
8443 (let* ((import-clause (js2-parse-import-clause))
8444 (from-clause (and import-clause (js2-parse-from-clause)))
8445 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8446 (node (make-js2-import-node
8447 :pos beg
8448 :len (- (js2-current-token-end) beg)
8449 :import import-clause
8450 :from from-clause
8451 :module-id module-id)))
8452 (when import-clause
8453 (js2-node-add-children node import-clause))
8454 (when from-clause
8455 (js2-node-add-children node from-clause))
8456 node)))))
8457
8458 (defun js2-parse-import-clause ()
8459 "Parse the bindings in an import statement.
8460 This can take many forms:
8461
8462 ImportedDefaultBinding -> 'foo'
8463 NameSpaceImport -> '* as lib'
8464 NamedImports -> '{foo as bar, bang}'
8465 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8466 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8467
8468 Try to match namespace imports and named imports first because nothing can
8469 come after them. If it is an imported default binding, then it could have named
8470 imports or a namespace import that follows it.
8471 "
8472 (let* ((beg (js2-current-token-beg))
8473 (clause (make-js2-import-clause-node
8474 :pos beg))
8475 (children (list)))
8476 (cond
8477 ((js2-match-token js2-MUL)
8478 (let ((ns-import (js2-parse-namespace-import)))
8479 (when ns-import
8480 (let ((name-node (js2-namespace-import-node-name ns-import)))
8481 (js2-define-symbol
8482 js2-LET (js2-name-node-name name-node) name-node t)))
8483 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8484 (push ns-import children)))
8485 ((js2-match-token js2-LC)
8486 (let ((imports (js2-parse-export-bindings t)))
8487 (setf (js2-import-clause-node-named-imports clause) imports)
8488 (dolist (import imports)
8489 (push import children)
8490 (let ((name-node (js2-export-binding-node-local-name import)))
8491 (when name-node
8492 (js2-define-symbol
8493 js2-LET (js2-name-node-name name-node) name-node t))))))
8494 ((= (js2-peek-token) js2-NAME)
8495 (let ((binding (js2-maybe-parse-export-binding)))
8496 (let ((node-name (js2-export-binding-node-local-name binding)))
8497 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8498 (setf (js2-import-clause-node-default-binding clause) binding)
8499 (push binding children))
8500 (when (js2-match-token js2-COMMA)
8501 (cond
8502 ((js2-match-token js2-MUL)
8503 (let ((ns-import (js2-parse-namespace-import)))
8504 (let ((name-node (js2-namespace-import-node-name ns-import)))
8505 (js2-define-symbol
8506 js2-LET (js2-name-node-name name-node) name-node t))
8507 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8508 (push ns-import children)))
8509 ((js2-match-token js2-LC)
8510 (let ((imports (js2-parse-export-bindings t)))
8511 (setf (js2-import-clause-node-named-imports clause) imports)
8512 (dolist (import imports)
8513 (push import children)
8514 (let ((name-node (js2-export-binding-node-local-name import)))
8515 (when name-node
8516 (js2-define-symbol
8517 js2-LET (js2-name-node-name name-node) name-node t))))))
8518 (t (js2-report-error "msg.syntax")))))
8519 (t (js2-report-error "msg.mod.declaration.after.import")))
8520 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8521 (apply #'js2-node-add-children clause children)
8522 clause))
8523
8524 (defun js2-parse-namespace-import ()
8525 "Parse a namespace import expression such as '* as bar'.
8526 The current token must be js2-MUL."
8527 (let ((beg (js2-current-token-beg)))
8528 (when (js2-must-match js2-NAME "msg.syntax")
8529 (if (equal "as" (js2-current-token-string))
8530 (when (js2-must-match-prop-name "msg.syntax")
8531 (let ((node (make-js2-namespace-import-node
8532 :pos beg
8533 :len (- (js2-current-token-end) beg)
8534 :name (make-js2-name-node
8535 :pos (js2-current-token-beg)
8536 :len (js2-current-token-end)
8537 :name (js2-current-token-string)))))
8538 (js2-node-add-children node (js2-namespace-import-node-name node))
8539 node))
8540 (js2-unget-token)
8541 (js2-report-error "msg.syntax")))))
8542
8543
8544 (defun js2-parse-from-clause ()
8545 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8546 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8547 (let ((beg (js2-current-token-beg)))
8548 (if (equal "from" (js2-current-token-string))
8549 (cond
8550 ((js2-match-token js2-STRING)
8551 (make-js2-from-clause-node
8552 :pos beg
8553 :len (- (js2-current-token-end) beg)
8554 :module-id (js2-current-token-string)
8555 :metadata-p nil))
8556 ((js2-match-token js2-THIS)
8557 (when (js2-must-match-name "msg.mod.spec.after.from")
8558 (if (equal "module" (js2-current-token-string))
8559 (make-js2-from-clause-node
8560 :pos beg
8561 :len (- (js2-current-token-end) beg)
8562 :module-id "this"
8563 :metadata-p t)
8564 (js2-unget-token)
8565 (js2-unget-token)
8566 (js2-report-error "msg.mod.spec.after.from")
8567 nil)))
8568 (t (js2-report-error "msg.mod.spec.after.from") nil))
8569 (js2-unget-token)
8570 (js2-report-error "msg.mod.from.after.import.spec.set")
8571 nil))))
8572
8573 (defun js2-parse-export-bindings (&optional import-p)
8574 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8575 {foo as bar, baz as bang}. The current token must be
8576 js2-LC. Return a lisp list of js2-export-binding-node"
8577 (let ((bindings (list)))
8578 (while
8579 (let ((binding (js2-maybe-parse-export-binding)))
8580 (when binding
8581 (push binding bindings))
8582 (js2-match-token js2-COMMA)))
8583 (when (js2-must-match js2-RC (if import-p
8584 "msg.mod.rc.after.import.spec.list"
8585 "msg.mod.rc.after.export.spec.list"))
8586 (reverse bindings))))
8587
8588 (defun js2-maybe-parse-export-binding ()
8589 "Attempt to parse a binding expression found inside an import/export statement.
8590 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8591 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8592 js2-export-binding-node and consume all the tokens. If it does not match, it
8593 consumes no tokens."
8594 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8595 (beg (js2-current-token-beg))
8596 (extern-name-len (js2-current-token-len))
8597 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8598 (aref js2-kwd-tokens (js2-current-token-type)))))
8599 (if extern-name
8600 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8601 (if (and as (equal "as" (js2-current-token-string)))
8602 (let ((name
8603 (or
8604 (and (js2-match-token js2-DEFAULT) "default")
8605 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8606 (if name
8607 (let ((node (make-js2-export-binding-node
8608 :pos beg
8609 :len (- (js2-current-token-end) beg)
8610 :local-name (make-js2-name-node
8611 :name name
8612 :pos (js2-current-token-beg)
8613 :len (js2-current-token-len))
8614 :extern-name (make-js2-name-node
8615 :name extern-name
8616 :pos beg
8617 :len extern-name-len))))
8618 (js2-node-add-children
8619 node
8620 (js2-export-binding-node-local-name node)
8621 (js2-export-binding-node-extern-name node))
8622 node)
8623 (js2-unget-token)
8624 nil))
8625 (when as (js2-unget-token))
8626 (let* ((name-node (make-js2-name-node
8627 :name (js2-current-token-string)
8628 :pos (js2-current-token-beg)
8629 :len (js2-current-token-len)))
8630 (node (make-js2-export-binding-node
8631 :pos (js2-current-token-beg)
8632 :len (js2-current-token-len)
8633 :local-name name-node
8634 :extern-name name-node)))
8635 (when is-reserved-name
8636 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8637 (js2-node-add-children node name-node)
8638 node)))
8639 nil)))
8640
8641 (defun js2-parse-switch ()
8642 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8643 (let ((pos (js2-current-token-beg))
8644 tt pn discriminant has-default case-expr case-node
8645 case-pos cases stmt lp)
8646 (if (js2-must-match js2-LP "msg.no.paren.switch")
8647 (setq lp (js2-current-token-beg)))
8648 (setq discriminant (js2-parse-expr)
8649 pn (make-js2-switch-node :discriminant discriminant
8650 :pos pos
8651 :lp (js2-relpos lp pos)))
8652 (js2-node-add-children pn discriminant)
8653 (js2-enter-switch pn)
8654 (unwind-protect
8655 (progn
8656 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8657 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8658 (js2-must-match js2-LC "msg.no.brace.switch")
8659 (catch 'break
8660 (while t
8661 (setq tt (js2-next-token)
8662 case-pos (js2-current-token-beg))
8663 (cond
8664 ((= tt js2-RC)
8665 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8666 (throw 'break nil)) ; done
8667 ((= tt js2-CASE)
8668 (setq case-expr (js2-parse-expr))
8669 (js2-must-match js2-COLON "msg.no.colon.case"))
8670 ((= tt js2-DEFAULT)
8671 (if has-default
8672 (js2-report-error "msg.double.switch.default"))
8673 (setq has-default t
8674 case-expr nil)
8675 (js2-must-match js2-COLON "msg.no.colon.case"))
8676 (t
8677 (js2-report-error "msg.bad.switch")
8678 (throw 'break nil)))
8679 (setq case-node (make-js2-case-node :pos case-pos
8680 :len (- (js2-current-token-end) case-pos)
8681 :expr case-expr))
8682 (js2-node-add-children case-node case-expr)
8683 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8684 (/= tt js2-CASE)
8685 (/= tt js2-DEFAULT)
8686 (/= tt js2-EOF))
8687 (setf stmt (js2-parse-statement)
8688 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8689 (js2-block-node-push case-node stmt))
8690 (push case-node cases)))
8691 ;; add cases last, as pushing reverses the order to be correct
8692 (dolist (kid cases)
8693 (js2-node-add-children pn kid)
8694 (push kid (js2-switch-node-cases pn)))
8695 pn) ; return value
8696 (js2-exit-switch))))
8697
8698 (defun js2-parse-while ()
8699 "Parser for while-statement. Last matched token must be js2-WHILE."
8700 (let ((pos (js2-current-token-beg))
8701 (pn (make-js2-while-node))
8702 cond body)
8703 (js2-enter-loop pn)
8704 (unwind-protect
8705 (progn
8706 (setf cond (js2-parse-condition)
8707 (js2-while-node-condition pn) (car cond)
8708 body (js2-parse-statement)
8709 (js2-while-node-body pn) body
8710 (js2-node-len pn) (- (js2-node-end body) pos)
8711 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8712 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8713 (js2-node-add-children pn body (car cond)))
8714 (js2-exit-loop))
8715 pn))
8716
8717 (defun js2-parse-do ()
8718 "Parser for do-statement. Last matched token must be js2-DO."
8719 (let ((pos (js2-current-token-beg))
8720 (pn (make-js2-do-node))
8721 cond body end)
8722 (js2-enter-loop pn)
8723 (unwind-protect
8724 (progn
8725 (setq body (js2-parse-statement))
8726 (js2-must-match js2-WHILE "msg.no.while.do")
8727 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8728 cond (js2-parse-condition)
8729 (js2-do-node-condition pn) (car cond)
8730 (js2-do-node-body pn) body
8731 end js2-ts-cursor
8732 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8733 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8734 (js2-node-add-children pn (car cond) body))
8735 (js2-exit-loop))
8736 ;; Always auto-insert semicolon to follow SpiderMonkey:
8737 ;; It is required by ECMAScript but is ignored by the rest of
8738 ;; world; see bug 238945
8739 (if (js2-match-token js2-SEMI)
8740 (setq end js2-ts-cursor))
8741 (setf (js2-node-len pn) (- end pos))
8742 pn))
8743
8744 (defun js2-parse-export ()
8745 "Parse an export statement.
8746 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8747 expressions should only be either hoistable expressions (function or generator)
8748 or assignment expressions, but there is no checking to enforce that and so it
8749 will parse without error a small subset of
8750 invalid export statements."
8751 (unless (js2-ast-root-p js2-current-scope)
8752 (js2-report-error "msg.mod.export.decl.at.top.level"))
8753 (let ((beg (js2-current-token-beg))
8754 (children (list))
8755 exports-list from-clause declaration default)
8756 (cond
8757 ((js2-match-token js2-MUL)
8758 (setq from-clause (js2-parse-from-clause))
8759 (when from-clause
8760 (push from-clause children)))
8761 ((js2-match-token js2-LC)
8762 (setq exports-list (js2-parse-export-bindings))
8763 (when exports-list
8764 (dolist (export exports-list)
8765 (push export children)))
8766 (when (js2-match-token js2-NAME)
8767 (if (equal "from" (js2-current-token-string))
8768 (progn
8769 (js2-unget-token)
8770 (setq from-clause (js2-parse-from-clause)))
8771 (js2-unget-token))))
8772 ((js2-match-token js2-DEFAULT)
8773 (setq default (js2-parse-expr)))
8774 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8775 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8776 (t
8777 (setq declaration (js2-parse-expr))))
8778 (when from-clause
8779 (push from-clause children))
8780 (when declaration
8781 (push declaration children)
8782 (when (not (js2-function-node-p declaration))
8783 (js2-auto-insert-semicolon declaration)))
8784 (when default
8785 (push default children)
8786 (when (not (js2-function-node-p default))
8787 (js2-auto-insert-semicolon default)))
8788 (let ((node (make-js2-export-node
8789 :pos beg
8790 :len (- (js2-current-token-end) beg)
8791 :exports-list exports-list
8792 :from-clause from-clause
8793 :declaration declaration
8794 :default default)))
8795 (apply #'js2-node-add-children node children)
8796 node)))
8797
8798 (defun js2-parse-for ()
8799 "Parse a for, for-in or for each-in statement.
8800 Last matched token must be js2-FOR."
8801 (let ((for-pos (js2-current-token-beg))
8802 (tmp-scope (make-js2-scope))
8803 pn is-for-each is-for-in-or-of is-for-of
8804 in-pos each-pos tmp-pos
8805 init ; Node init is also foo in 'foo in object'.
8806 cond ; Node cond is also object in 'foo in object'.
8807 incr ; 3rd section of for-loop initializer.
8808 body tt lp rp)
8809 ;; See if this is a for each () instead of just a for ()
8810 (when (js2-match-token js2-NAME)
8811 (if (string= "each" (js2-current-token-string))
8812 (progn
8813 (setq is-for-each t
8814 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8815 (js2-record-face 'font-lock-keyword-face))
8816 (js2-report-error "msg.no.paren.for")))
8817 (if (js2-must-match js2-LP "msg.no.paren.for")
8818 (setq lp (- (js2-current-token-beg) for-pos)))
8819 (setq tt (js2-get-token))
8820 ;; Capture identifiers inside parens. We can't create the node
8821 ;; (and use it as the current scope) until we know its type.
8822 (js2-push-scope tmp-scope)
8823 (unwind-protect
8824 (progn
8825 ;; parse init clause
8826 (let ((js2-in-for-init t)) ; set as dynamic variable
8827 (cond
8828 ((= tt js2-SEMI)
8829 (js2-unget-token)
8830 (setq init (make-js2-empty-expr-node)))
8831 ((or (= tt js2-VAR) (= tt js2-LET))
8832 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8833 (t
8834 (js2-unget-token)
8835 (setq init (js2-parse-expr)))))
8836 (if (or (js2-match-token js2-IN)
8837 (and (>= js2-language-version 200)
8838 (js2-match-contextual-kwd "of")
8839 (setq is-for-of t)))
8840 (setq is-for-in-or-of t
8841 in-pos (- (js2-current-token-beg) for-pos)
8842 ;; scope of iteration target object is not the scope we've created above.
8843 ;; stash current scope temporary.
8844 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8845 (js2-parse-expr))) ; object over which we're iterating
8846 ;; else ordinary for loop - parse cond and incr
8847 (js2-must-match js2-SEMI "msg.no.semi.for")
8848 (setq cond (if (= (js2-peek-token) js2-SEMI)
8849 (make-js2-empty-expr-node) ; no loop condition
8850 (js2-parse-expr)))
8851 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8852 (setq tmp-pos (js2-current-token-end)
8853 incr (if (= (js2-peek-token) js2-RP)
8854 (make-js2-empty-expr-node :pos tmp-pos)
8855 (js2-parse-expr)))))
8856 (js2-pop-scope))
8857 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8858 (setq rp (- (js2-current-token-beg) for-pos)))
8859 (if (not is-for-in-or-of)
8860 (setq pn (make-js2-for-node :init init
8861 :condition cond
8862 :update incr
8863 :lp lp
8864 :rp rp))
8865 ;; cond could be null if 'in obj' got eaten by the init node.
8866 (if (js2-infix-node-p init)
8867 ;; it was (foo in bar) instead of (var foo in bar)
8868 (setq cond (js2-infix-node-right init)
8869 init (js2-infix-node-left init))
8870 (if (and (js2-var-decl-node-p init)
8871 (> (length (js2-var-decl-node-kids init)) 1))
8872 (js2-report-error "msg.mult.index")))
8873 (setq pn (make-js2-for-in-node :iterator init
8874 :object cond
8875 :in-pos in-pos
8876 :foreach-p is-for-each
8877 :each-pos each-pos
8878 :forof-p is-for-of
8879 :lp lp
8880 :rp rp)))
8881 ;; Transplant the declarations.
8882 (setf (js2-scope-symbol-table pn)
8883 (js2-scope-symbol-table tmp-scope))
8884 (unwind-protect
8885 (progn
8886 (js2-enter-loop pn)
8887 ;; We have to parse the body -after- creating the loop node,
8888 ;; so that the loop node appears in the js2-loop-set, allowing
8889 ;; break/continue statements to find the enclosing loop.
8890 (setf body (js2-parse-statement)
8891 (js2-loop-node-body pn) body
8892 (js2-node-pos pn) for-pos
8893 (js2-node-len pn) (- (js2-node-end body) for-pos))
8894 (js2-node-add-children pn init cond incr body))
8895 ;; finally
8896 (js2-exit-loop))
8897 pn))
8898
8899 (defun js2-parse-try ()
8900 "Parse a try statement. Last matched token must be js2-TRY."
8901 (let ((try-pos (js2-current-token-beg))
8902 try-end
8903 try-block
8904 catch-blocks
8905 finally-block
8906 saw-default-catch
8907 peek)
8908 (if (/= (js2-peek-token) js2-LC)
8909 (js2-report-error "msg.no.brace.try"))
8910 (setq try-block (js2-parse-statement)
8911 try-end (js2-node-end try-block)
8912 peek (js2-peek-token))
8913 (cond
8914 ((= peek js2-CATCH)
8915 (while (js2-match-token js2-CATCH)
8916 (let* ((catch-pos (js2-current-token-beg))
8917 (catch-node (make-js2-catch-node :pos catch-pos))
8918 param
8919 guard-kwd
8920 catch-cond
8921 lp rp)
8922 (if saw-default-catch
8923 (js2-report-error "msg.catch.unreachable"))
8924 (if (js2-must-match js2-LP "msg.no.paren.catch")
8925 (setq lp (- (js2-current-token-beg) catch-pos)))
8926 (js2-push-scope catch-node)
8927 (let ((tt (js2-peek-token)))
8928 (cond
8929 ;; Destructuring pattern:
8930 ;; catch ({ message, file }) { ... }
8931 ((or (= tt js2-LB) (= tt js2-LC))
8932 (js2-get-token)
8933 (setq param (js2-parse-destruct-primary-expr))
8934 (js2-define-destruct-symbols param js2-LET nil))
8935 ;; Simple name.
8936 (t
8937 (js2-must-match-name "msg.bad.catchcond")
8938 (setq param (js2-create-name-node))
8939 (js2-define-symbol js2-LET (js2-current-token-string) param)
8940 (js2-check-strict-identifier param))))
8941 ;; Catch condition.
8942 (if (js2-match-token js2-IF)
8943 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8944 catch-cond (js2-parse-expr))
8945 (setq saw-default-catch t))
8946 (if (js2-must-match js2-RP "msg.bad.catchcond")
8947 (setq rp (- (js2-current-token-beg) catch-pos)))
8948 (js2-must-match js2-LC "msg.no.brace.catchblock")
8949 (js2-parse-statements catch-node)
8950 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8951 (setq try-end (js2-current-token-end)))
8952 (js2-pop-scope)
8953 (setf (js2-node-len catch-node) (- try-end catch-pos)
8954 (js2-catch-node-param catch-node) param
8955 (js2-catch-node-guard-expr catch-node) catch-cond
8956 (js2-catch-node-guard-kwd catch-node) guard-kwd
8957 (js2-catch-node-lp catch-node) lp
8958 (js2-catch-node-rp catch-node) rp)
8959 (js2-node-add-children catch-node param catch-cond)
8960 (push catch-node catch-blocks))))
8961 ((/= peek js2-FINALLY)
8962 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8963 (js2-node-pos try-block)
8964 (- (setq try-end (js2-node-end try-block))
8965 (js2-node-pos try-block)))))
8966 (when (js2-match-token js2-FINALLY)
8967 (let ((finally-pos (js2-current-token-beg))
8968 (block (js2-parse-statement)))
8969 (setq try-end (js2-node-end block)
8970 finally-block (make-js2-finally-node :pos finally-pos
8971 :len (- try-end finally-pos)
8972 :body block))
8973 (js2-node-add-children finally-block block)))
8974 (let ((pn (make-js2-try-node :pos try-pos
8975 :len (- try-end try-pos)
8976 :try-block try-block
8977 :finally-block finally-block)))
8978 (js2-node-add-children pn try-block finally-block)
8979 ;; Push them onto the try-node, which reverses and corrects their order.
8980 (dolist (cb catch-blocks)
8981 (js2-node-add-children pn cb)
8982 (push cb (js2-try-node-catch-clauses pn)))
8983 pn)))
8984
8985 (defun js2-parse-throw ()
8986 "Parser for throw-statement. Last matched token must be js2-THROW."
8987 (let ((pos (js2-current-token-beg))
8988 expr pn)
8989 (if (= (js2-peek-token-or-eol) js2-EOL)
8990 ;; ECMAScript does not allow new lines before throw expression,
8991 ;; see bug 256617
8992 (js2-report-error "msg.bad.throw.eol"))
8993 (setq expr (js2-parse-expr)
8994 pn (make-js2-throw-node :pos pos
8995 :len (- (js2-node-end expr) pos)
8996 :expr expr))
8997 (js2-node-add-children pn expr)
8998 pn))
8999
9000 (defun js2-match-jump-label-name (label-name)
9001 "If break/continue specified a label, return that label's labeled stmt.
9002 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9003 does not match an existing label, reports an error and returns nil."
9004 (let ((bundle (cdr (assoc label-name js2-label-set))))
9005 (if (null bundle)
9006 (js2-report-error "msg.undef.label"))
9007 bundle))
9008
9009 (defun js2-parse-break ()
9010 "Parser for break-statement. Last matched token must be js2-BREAK."
9011 (let ((pos (js2-current-token-beg))
9012 (end (js2-current-token-end))
9013 break-target ; statement to break from
9014 break-label ; in "break foo", name-node representing the foo
9015 labels ; matching labeled statement to break to
9016 pn)
9017 (when (eq (js2-peek-token-or-eol) js2-NAME)
9018 (js2-get-token)
9019 (setq break-label (js2-create-name-node)
9020 end (js2-node-end break-label)
9021 ;; matchJumpLabelName only matches if there is one
9022 labels (js2-match-jump-label-name (js2-current-token-string))
9023 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9024 (unless (or break-target break-label)
9025 ;; no break target specified - try for innermost enclosing loop/switch
9026 (if (null js2-loop-and-switch-set)
9027 (unless break-label
9028 (js2-report-error "msg.bad.break" nil pos (length "break")))
9029 (setq break-target (car js2-loop-and-switch-set))))
9030 (setq pn (make-js2-break-node :pos pos
9031 :len (- end pos)
9032 :label break-label
9033 :target break-target))
9034 (js2-node-add-children pn break-label) ; but not break-target
9035 pn))
9036
9037 (defun js2-parse-continue ()
9038 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9039 (let ((pos (js2-current-token-beg))
9040 (end (js2-current-token-end))
9041 label ; optional user-specified label, a `js2-name-node'
9042 labels ; current matching labeled stmt, if any
9043 target ; the `js2-loop-node' target of this continue stmt
9044 pn)
9045 (when (= (js2-peek-token-or-eol) js2-NAME)
9046 (js2-get-token)
9047 (setq label (js2-create-name-node)
9048 end (js2-node-end label)
9049 ;; matchJumpLabelName only matches if there is one
9050 labels (js2-match-jump-label-name (js2-current-token-string))))
9051 (cond
9052 ((null labels) ; no current label to go to
9053 (if (null js2-loop-set) ; no loop to continue to
9054 (js2-report-error "msg.continue.outside" nil pos
9055 (length "continue"))
9056 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9057 (t
9058 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9059 (setq target (js2-labeled-stmt-node-stmt labels))
9060 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9061 (setq pn (make-js2-continue-node :pos pos
9062 :len (- end pos)
9063 :label label
9064 :target target))
9065 (js2-node-add-children pn label) ; but not target - it's not our child
9066 pn))
9067
9068 (defun js2-parse-with ()
9069 "Parser for with-statement. Last matched token must be js2-WITH."
9070 (when js2-in-use-strict-directive
9071 (js2-report-error "msg.no.with.strict"))
9072 (let ((pos (js2-current-token-beg))
9073 obj body pn lp rp)
9074 (if (js2-must-match js2-LP "msg.no.paren.with")
9075 (setq lp (js2-current-token-beg)))
9076 (setq obj (js2-parse-expr))
9077 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9078 (setq rp (js2-current-token-beg)))
9079 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9080 (setq body (js2-parse-statement)))
9081 (setq pn (make-js2-with-node :pos pos
9082 :len (- (js2-node-end body) pos)
9083 :object obj
9084 :body body
9085 :lp (js2-relpos lp pos)
9086 :rp (js2-relpos rp pos)))
9087 (js2-node-add-children pn obj body)
9088 pn))
9089
9090 (defun js2-parse-const-var ()
9091 "Parser for var- or const-statement.
9092 Last matched token must be js2-CONST or js2-VAR."
9093 (let ((tt (js2-current-token-type))
9094 (pos (js2-current-token-beg))
9095 expr pn)
9096 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9097 pn (make-js2-expr-stmt-node :pos pos
9098 :len (- (js2-node-end expr) pos)
9099 :expr expr))
9100 (js2-node-add-children pn expr)
9101 pn))
9102
9103 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9104 (let ((pn (make-js2-expr-stmt-node :pos pos
9105 :len (js2-node-len expr)
9106 :type (if (js2-inside-function)
9107 js2-EXPR_VOID
9108 js2-EXPR_RESULT)
9109 :expr expr)))
9110 (if add-child
9111 (js2-node-add-children pn expr))
9112 pn))
9113
9114 (defun js2-parse-let-stmt ()
9115 "Parser for let-statement. Last matched token must be js2-LET."
9116 (let ((pos (js2-current-token-beg))
9117 expr pn)
9118 (if (= (js2-peek-token) js2-LP)
9119 ;; let expression in statement context
9120 (setq expr (js2-parse-let pos 'statement)
9121 pn (js2-wrap-with-expr-stmt pos expr t))
9122 ;; else we're looking at a statement like let x=6, y=7;
9123 (setf expr (js2-parse-variables js2-LET pos)
9124 pn (js2-wrap-with-expr-stmt pos expr t)
9125 (js2-node-type pn) js2-EXPR_RESULT))
9126 pn))
9127
9128 (defun js2-parse-ret-yield ()
9129 (js2-parse-return-or-yield (js2-current-token-type) nil))
9130
9131 (defconst js2-parse-return-stmt-enders
9132 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9133
9134 (defsubst js2-now-all-set (before after mask)
9135 "Return whether or not the bits in the mask have changed to all set.
9136 BEFORE is bits before change, AFTER is bits after change, and MASK is
9137 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9138 but not BEFORE."
9139 (and (/= (logand before mask) mask)
9140 (= (logand after mask) mask)))
9141
9142 (defun js2-parse-return-or-yield (tt expr-context)
9143 (let* ((pos (js2-current-token-beg))
9144 (end (js2-current-token-end))
9145 (before js2-end-flags)
9146 (inside-function (js2-inside-function))
9147 (gen-type (and inside-function (js2-function-node-generator-type
9148 js2-current-script-or-fn)))
9149 e ret name yield-star-p)
9150 (unless inside-function
9151 (js2-report-error (if (eq tt js2-RETURN)
9152 "msg.bad.return"
9153 "msg.bad.yield")))
9154 (when (and inside-function
9155 (eq gen-type 'STAR)
9156 (js2-match-token js2-MUL))
9157 (setq yield-star-p t))
9158 ;; This is ugly, but we don't want to require a semicolon.
9159 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9160 (setq e (js2-parse-expr)
9161 end (js2-node-end e)))
9162 (cond
9163 ((eq tt js2-RETURN)
9164 (js2-set-flag js2-end-flags (if (null e)
9165 js2-end-returns
9166 js2-end-returns-value))
9167 (setq ret (make-js2-return-node :pos pos
9168 :len (- end pos)
9169 :retval e))
9170 (js2-node-add-children ret e)
9171 ;; See if we need a strict mode warning.
9172 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9173 ;; more thorough and accurate than this before/after flag check.
9174 ;; E.g. if there's a finally-block that always returns, we shouldn't
9175 ;; show a warning generated by inconsistent returns in the catch blocks.
9176 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9177 ;; so we know which returns/yields to highlight, and we should get rid of
9178 ;; all the checking in `js2-parse-return-or-yield'.
9179 (if (and js2-strict-inconsistent-return-warning
9180 (js2-now-all-set before js2-end-flags
9181 (logior js2-end-returns js2-end-returns-value)))
9182 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9183 ((eq gen-type 'COMPREHENSION)
9184 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9185 ;; like SpiderMonkey does.
9186 (js2-report-error "msg.syntax" nil pos 5))
9187 (t
9188 (setq ret (make-js2-yield-node :pos pos
9189 :len (- end pos)
9190 :value e
9191 :star-p yield-star-p))
9192 (js2-node-add-children ret e)
9193 (unless expr-context
9194 (setq e ret
9195 ret (js2-wrap-with-expr-stmt pos e t))
9196 (js2-set-requires-activation)
9197 (js2-set-is-generator))))
9198 ;; see if we are mixing yields and value returns.
9199 (when (and inside-function
9200 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9201 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9202 'LEGACY))
9203 (setq name (js2-function-name js2-current-script-or-fn))
9204 (if (zerop (length name))
9205 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9206 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9207 ret))
9208
9209 (defun js2-parse-debugger ()
9210 (make-js2-keyword-node :type js2-DEBUGGER))
9211
9212 (defun js2-parse-block ()
9213 "Parser for a curly-delimited statement block.
9214 Last token matched must be `js2-LC'."
9215 (let ((pos (js2-current-token-beg))
9216 (pn (make-js2-scope)))
9217 (js2-push-scope pn)
9218 (unwind-protect
9219 (progn
9220 (js2-parse-statements pn)
9221 (js2-must-match js2-RC "msg.no.brace.block")
9222 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9223 (js2-pop-scope))
9224 pn))
9225
9226 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9227 (defun js2-parse-semi ()
9228 "Parse a statement or handle an error.
9229 Current token type is `js2-SEMI' or `js2-ERROR'."
9230 (let ((tt (js2-current-token-type)) pos len)
9231 (if (eq tt js2-SEMI)
9232 (make-js2-empty-expr-node :len 1)
9233 (setq pos (js2-current-token-beg)
9234 len (- (js2-current-token-end) pos))
9235 (js2-report-error "msg.syntax" nil pos len)
9236 (make-js2-error-node :pos pos :len len))))
9237
9238 (defun js2-parse-default-xml-namespace ()
9239 "Parse a `default xml namespace = <expr>' e4x statement."
9240 (let ((pos (js2-current-token-beg))
9241 end len expr unary)
9242 (js2-must-have-xml)
9243 (js2-set-requires-activation)
9244 (setq len (- js2-ts-cursor pos))
9245 (unless (and (js2-match-token js2-NAME)
9246 (string= (js2-current-token-string) "xml"))
9247 (js2-report-error "msg.bad.namespace" nil pos len))
9248 (unless (and (js2-match-token js2-NAME)
9249 (string= (js2-current-token-string) "namespace"))
9250 (js2-report-error "msg.bad.namespace" nil pos len))
9251 (unless (js2-match-token js2-ASSIGN)
9252 (js2-report-error "msg.bad.namespace" nil pos len))
9253 (setq expr (js2-parse-expr)
9254 end (js2-node-end expr)
9255 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9256 :pos pos
9257 :len (- end pos)
9258 :operand expr))
9259 (js2-node-add-children unary expr)
9260 (make-js2-expr-stmt-node :pos pos
9261 :len (- end pos)
9262 :expr unary)))
9263
9264 (defun js2-record-label (label bundle)
9265 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9266 (js2-get-token)
9267 (let ((name (js2-label-node-name label))
9268 labeled-stmt
9269 dup)
9270 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9271 ;; flag both labels if possible when used in editing mode
9272 (if (and js2-parse-ide-mode
9273 (setq dup (js2-get-label-by-name labeled-stmt name)))
9274 (js2-report-error "msg.dup.label" nil
9275 (js2-node-abs-pos dup) (js2-node-len dup)))
9276 (js2-report-error "msg.dup.label" nil
9277 (js2-node-pos label) (js2-node-len label)))
9278 (js2-labeled-stmt-node-add-label bundle label)
9279 (js2-node-add-children bundle label)
9280 ;; Add one reference to the bundle per label in `js2-label-set'
9281 (push (cons name bundle) js2-label-set)))
9282
9283 (defun js2-parse-name-or-label ()
9284 "Parser for identifier or label. Last token matched must be js2-NAME.
9285 Called when we found a name in a statement context. If it's a label, we gather
9286 up any following labels and the next non-label statement into a
9287 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9288 expression and return it wrapped in a `js2-expr-stmt-node'."
9289 (let ((pos (js2-current-token-beg))
9290 expr stmt bundle
9291 (continue t))
9292 ;; set check for label and call down to `js2-parse-primary-expr'
9293 (setq expr (js2-maybe-parse-label))
9294 (if (null expr)
9295 ;; Parse the non-label expression and wrap with expression stmt.
9296 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9297 ;; else parsed a label
9298 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9299 (js2-record-label expr bundle)
9300 ;; look for more labels
9301 (while (and continue (= (js2-get-token) js2-NAME))
9302 (if (setq expr (js2-maybe-parse-label))
9303 (js2-record-label expr bundle)
9304 (setq expr (js2-parse-expr)
9305 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9306 continue nil)
9307 (js2-auto-insert-semicolon stmt)))
9308 ;; no more labels; now parse the labeled statement
9309 (unwind-protect
9310 (unless stmt
9311 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9312 (js2-unget-token)
9313 (setq stmt (js2-statement-helper))))
9314 ;; remove the labels for this statement from the global set
9315 (dolist (label (js2-labeled-stmt-node-labels bundle))
9316 (setq js2-label-set (remove label js2-label-set))))
9317 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9318 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9319 (js2-node-add-children bundle stmt)
9320 bundle)))
9321
9322 (defun js2-maybe-parse-label ()
9323 (cl-assert (= (js2-current-token-type) js2-NAME))
9324 (let (label-pos
9325 (next-tt (js2-get-token))
9326 (label-end (js2-current-token-end)))
9327 ;; Do not consume colon, it is used as unwind indicator
9328 ;; to return to statementHelper.
9329 (js2-unget-token)
9330 (if (= next-tt js2-COLON)
9331 (prog2
9332 (setq label-pos (js2-current-token-beg))
9333 (make-js2-label-node :pos label-pos
9334 :len (- label-end label-pos)
9335 :name (js2-current-token-string))
9336 (js2-set-face label-pos
9337 label-end
9338 'font-lock-variable-name-face 'record))
9339 ;; Backtrack from the name token, too.
9340 (js2-unget-token)
9341 nil)))
9342
9343 (defun js2-parse-expr-stmt ()
9344 "Default parser in statement context, if no recognized statement found."
9345 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9346 (progn
9347 (js2-unget-token)
9348 (js2-parse-expr)) t))
9349
9350 (defun js2-parse-variables (decl-type pos)
9351 "Parse a comma-separated list of variable declarations.
9352 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9353
9354 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9355 For 'var' or 'const', the keyword should be the token last scanned.
9356
9357 POS is the position where the node should start. It's sometimes the
9358 var/const/let keyword, and other times the beginning of the first token
9359 in the first variable declaration.
9360
9361 Returns the parsed `js2-var-decl-node' expression node."
9362 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9363 :pos pos))
9364 destructuring kid-pos tt init name end nbeg nend vi
9365 (continue t))
9366 ;; Example:
9367 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9368 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9369 ;; var {a, b} = baz;
9370 (while continue
9371 (setq destructuring nil
9372 name nil
9373 tt (js2-get-token)
9374 kid-pos (js2-current-token-beg)
9375 end (js2-current-token-end)
9376 init nil)
9377 (if (or (= tt js2-LB) (= tt js2-LC))
9378 ;; Destructuring assignment, e.g., var [a, b] = ...
9379 (setq destructuring (js2-parse-destruct-primary-expr)
9380 end (js2-node-end destructuring))
9381 ;; Simple variable name
9382 (js2-unget-token)
9383 (when (js2-must-match-name "msg.bad.var")
9384 (setq name (js2-create-name-node)
9385 nbeg (js2-current-token-beg)
9386 nend (js2-current-token-end)
9387 end nend)
9388 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9389 (js2-check-strict-identifier name)))
9390 (when (js2-match-token js2-ASSIGN)
9391 (setq init (js2-parse-assign-expr)
9392 end (js2-node-end init))
9393 (js2-record-imenu-functions init name))
9394 (when name
9395 (js2-set-face nbeg nend (if (js2-function-node-p init)
9396 'font-lock-function-name-face
9397 'font-lock-variable-name-face)
9398 'record))
9399 (setq vi (make-js2-var-init-node :pos kid-pos
9400 :len (- end kid-pos)
9401 :type decl-type))
9402 (if destructuring
9403 (progn
9404 (if (and (null init) (not js2-in-for-init))
9405 (js2-report-error "msg.destruct.assign.no.init"))
9406 (js2-define-destruct-symbols destructuring
9407 decl-type
9408 'font-lock-variable-name-face)
9409 (setf (js2-var-init-node-target vi) destructuring))
9410 (setf (js2-var-init-node-target vi) name))
9411 (setf (js2-var-init-node-initializer vi) init)
9412 (js2-node-add-children vi name destructuring init)
9413 (js2-block-node-push result vi)
9414 (unless (js2-match-token js2-COMMA)
9415 (setq continue nil)))
9416 (setf (js2-node-len result) (- end pos))
9417 result))
9418
9419 (defun js2-parse-let (pos &optional stmt-p)
9420 "Parse a let expression or statement.
9421 A let-expression is of the form `let (vars) expr'.
9422 A let-statement is of the form `let (vars) {statements}'.
9423 The third form of let is a variable declaration list, handled
9424 by `js2-parse-variables'."
9425 (let ((pn (make-js2-let-node :pos pos))
9426 beg vars body)
9427 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9428 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9429 (js2-push-scope pn)
9430 (unwind-protect
9431 (progn
9432 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9433 (if (js2-must-match js2-RP "msg.no.paren.let")
9434 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9435 (if (and stmt-p (js2-match-token js2-LC))
9436 ;; let statement
9437 (progn
9438 (setf beg (js2-current-token-beg) ; position stmt at LC
9439 body (js2-parse-statements))
9440 (js2-must-match js2-RC "msg.no.curly.let")
9441 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9442 (js2-node-len pn) (- (js2-current-token-end) pos)
9443 (js2-let-node-body pn) body
9444 (js2-node-type pn) js2-LET))
9445 ;; let expression
9446 (setf body (js2-parse-expr)
9447 (js2-node-len pn) (- (js2-node-end body) pos)
9448 (js2-let-node-body pn) body))
9449 (setf (js2-let-node-vars pn) vars)
9450 (js2-node-add-children pn vars body))
9451 (js2-pop-scope))
9452 pn))
9453
9454 (defun js2-define-new-symbol (decl-type name node &optional scope)
9455 (js2-scope-put-symbol (or scope js2-current-scope)
9456 name
9457 (make-js2-symbol decl-type name node)))
9458
9459 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9460 "Define a symbol in the current scope.
9461 If NODE is non-nil, it is the AST node associated with the symbol."
9462 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9463 (symbol (if defining-scope
9464 (js2-scope-get-symbol defining-scope name)))
9465 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9466 (pos (if node (js2-node-abs-pos node)))
9467 (len (if node (js2-node-len node))))
9468 (cond
9469 ((and symbol ; already defined
9470 (or (if js2-in-use-strict-directive
9471 ;; two const-bound vars in this block have same name
9472 (and (= sdt js2-CONST)
9473 (eq defining-scope js2-current-scope))
9474 (or (= sdt js2-CONST) ; old version is const
9475 (= decl-type js2-CONST))) ; new version is const
9476 ;; two let-bound vars in this block have same name
9477 (and (= sdt js2-LET)
9478 (eq defining-scope js2-current-scope))))
9479 (js2-report-error
9480 (cond
9481 ((= sdt js2-CONST) "msg.const.redecl")
9482 ((= sdt js2-LET) "msg.let.redecl")
9483 ((= sdt js2-VAR) "msg.var.redecl")
9484 ((= sdt js2-FUNCTION) "msg.function.redecl")
9485 (t "msg.parm.redecl"))
9486 name pos len))
9487 ((or (= decl-type js2-LET)
9488 ;; strict mode const is scoped to the current LexicalEnvironment
9489 (and js2-in-use-strict-directive
9490 (= decl-type js2-CONST)))
9491 (if (and (= decl-type js2-LET)
9492 (not ignore-not-in-block)
9493 (or (= (js2-node-type js2-current-scope) js2-IF)
9494 (js2-loop-node-p js2-current-scope)))
9495 (js2-report-error "msg.let.decl.not.in.block")
9496 (js2-define-new-symbol decl-type name node)))
9497 ((or (= decl-type js2-VAR)
9498 (= decl-type js2-FUNCTION)
9499 ;; sloppy mode const is scoped to the current VariableEnvironment
9500 (and (not js2-in-use-strict-directive)
9501 (= decl-type js2-CONST)))
9502 (if symbol
9503 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9504 (js2-add-strict-warning "msg.var.redecl" name)
9505 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9506 (js2-add-strict-warning "msg.var.hides.arg" name)))
9507 (js2-define-new-symbol decl-type name node
9508 js2-current-script-or-fn)))
9509 ((= decl-type js2-LP)
9510 (if symbol
9511 ;; must be duplicate parameter. Second parameter hides the
9512 ;; first, so go ahead and add the second pararameter
9513 (js2-report-warning "msg.dup.parms" name))
9514 (js2-define-new-symbol decl-type name node))
9515 (t (js2-code-bug)))))
9516
9517 (defun js2-parse-paren-expr-or-generator-comp ()
9518 (let ((px-pos (js2-current-token-beg)))
9519 (cond
9520 ((and (>= js2-language-version 200)
9521 (js2-match-token js2-FOR))
9522 (js2-parse-generator-comp px-pos))
9523 ((and (>= js2-language-version 200)
9524 (js2-match-token js2-RP))
9525 ;; Not valid expression syntax, but this is valid in an arrow
9526 ;; function with no params: () => body.
9527 (if (eq (js2-peek-token) js2-ARROW)
9528 ;; Return whatever, it will hopefully be rewinded and
9529 ;; reparsed when we reach the =>.
9530 (make-js2-keyword-node :type js2-NULL)
9531 (js2-report-error "msg.syntax")
9532 (make-js2-error-node)))
9533 (t
9534 (let* ((js2-in-for-init nil)
9535 (expr (js2-parse-expr))
9536 (pn (make-js2-paren-node :pos px-pos
9537 :expr expr)))
9538 (js2-node-add-children pn (js2-paren-node-expr pn))
9539 (js2-must-match js2-RP "msg.no.paren")
9540 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9541 pn)))))
9542
9543 (defun js2-parse-expr (&optional oneshot)
9544 (let* ((pn (js2-parse-assign-expr))
9545 (pos (js2-node-pos pn))
9546 left
9547 right
9548 op-pos)
9549 (while (and (not oneshot)
9550 (js2-match-token js2-COMMA))
9551 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9552 (if (= (js2-peek-token) js2-YIELD)
9553 (js2-report-error "msg.yield.parenthesized"))
9554 (setq right (js2-parse-assign-expr)
9555 left pn
9556 pn (make-js2-infix-node :type js2-COMMA
9557 :pos pos
9558 :len (- js2-ts-cursor pos)
9559 :op-pos op-pos
9560 :left left
9561 :right right))
9562 (js2-node-add-children pn left right))
9563 pn))
9564
9565 (defun js2-parse-assign-expr ()
9566 (let ((tt (js2-get-token))
9567 (pos (js2-current-token-beg))
9568 pn left right op-pos
9569 ts-state recorded-identifiers parsed-errors)
9570 (if (= tt js2-YIELD)
9571 (js2-parse-return-or-yield tt t)
9572 ;; Save the tokenizer state in case we find an arrow function
9573 ;; and have to rewind.
9574 (setq ts-state (make-js2-ts-state)
9575 recorded-identifiers js2-recorded-identifiers
9576 parsed-errors js2-parsed-errors)
9577 ;; not yield - parse assignment expression
9578 (setq pn (js2-parse-cond-expr)
9579 tt (js2-get-token))
9580 (cond
9581 ((and (<= js2-first-assign tt)
9582 (<= tt js2-last-assign))
9583 ;; tt express assignment (=, |=, ^=, ..., %=)
9584 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9585 left pn)
9586 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9587 ;; care about assignment to strict variable names.
9588 (when (js2-name-node-p left)
9589 (js2-check-strict-identifier left))
9590 (setq right (js2-parse-assign-expr)
9591 pn (make-js2-assign-node :type tt
9592 :pos pos
9593 :len (- (js2-node-end right) pos)
9594 :op-pos op-pos
9595 :left left
9596 :right right))
9597 (when js2-parse-ide-mode
9598 (js2-highlight-assign-targets pn left right)
9599 (js2-record-imenu-functions right left))
9600 ;; do this last so ide checks above can use absolute positions
9601 (js2-node-add-children pn left right))
9602 ((and (= tt js2-ARROW)
9603 (>= js2-language-version 200))
9604 (js2-ts-seek ts-state)
9605 (setq js2-recorded-identifiers recorded-identifiers
9606 js2-parsed-errors parsed-errors)
9607 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9608 (t
9609 (js2-unget-token)))
9610 pn)))
9611
9612 (defun js2-parse-cond-expr ()
9613 (let ((pos (js2-current-token-beg))
9614 (pn (js2-parse-or-expr))
9615 test-expr
9616 if-true
9617 if-false
9618 q-pos
9619 c-pos)
9620 (when (js2-match-token js2-HOOK)
9621 (setq q-pos (- (js2-current-token-beg) pos)
9622 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9623 (js2-must-match js2-COLON "msg.no.colon.cond")
9624 (setq c-pos (- (js2-current-token-beg) pos)
9625 if-false (js2-parse-assign-expr)
9626 test-expr pn
9627 pn (make-js2-cond-node :pos pos
9628 :len (- (js2-node-end if-false) pos)
9629 :test-expr test-expr
9630 :true-expr if-true
9631 :false-expr if-false
9632 :q-pos q-pos
9633 :c-pos c-pos))
9634 (js2-node-add-children pn test-expr if-true if-false))
9635 pn))
9636
9637 (defun js2-make-binary (type left parser &optional no-get)
9638 "Helper for constructing a binary-operator AST node.
9639 LEFT is the left-side-expression, already parsed, and the
9640 binary operator should have just been matched.
9641 PARSER is a function to call to parse the right operand,
9642 or a `js2-node' struct if it has already been parsed.
9643 FIXME: The latter option is unused?"
9644 (let* ((pos (js2-node-pos left))
9645 (op-pos (- (js2-current-token-beg) pos))
9646 (right (if (js2-node-p parser)
9647 parser
9648 (unless no-get (js2-get-token))
9649 (funcall parser)))
9650 (pn (make-js2-infix-node :type type
9651 :pos pos
9652 :len (- (js2-node-end right) pos)
9653 :op-pos op-pos
9654 :left left
9655 :right right)))
9656 (js2-node-add-children pn left right)
9657 pn))
9658
9659 (defun js2-parse-or-expr ()
9660 (let ((pn (js2-parse-and-expr)))
9661 (when (js2-match-token js2-OR)
9662 (setq pn (js2-make-binary js2-OR
9663 pn
9664 'js2-parse-or-expr)))
9665 pn))
9666
9667 (defun js2-parse-and-expr ()
9668 (let ((pn (js2-parse-bit-or-expr)))
9669 (when (js2-match-token js2-AND)
9670 (setq pn (js2-make-binary js2-AND
9671 pn
9672 'js2-parse-and-expr)))
9673 pn))
9674
9675 (defun js2-parse-bit-or-expr ()
9676 (let ((pn (js2-parse-bit-xor-expr)))
9677 (while (js2-match-token js2-BITOR)
9678 (setq pn (js2-make-binary js2-BITOR
9679 pn
9680 'js2-parse-bit-xor-expr)))
9681 pn))
9682
9683 (defun js2-parse-bit-xor-expr ()
9684 (let ((pn (js2-parse-bit-and-expr)))
9685 (while (js2-match-token js2-BITXOR)
9686 (setq pn (js2-make-binary js2-BITXOR
9687 pn
9688 'js2-parse-bit-and-expr)))
9689 pn))
9690
9691 (defun js2-parse-bit-and-expr ()
9692 (let ((pn (js2-parse-eq-expr)))
9693 (while (js2-match-token js2-BITAND)
9694 (setq pn (js2-make-binary js2-BITAND
9695 pn
9696 'js2-parse-eq-expr)))
9697 pn))
9698
9699 (defconst js2-parse-eq-ops
9700 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9701
9702 (defun js2-parse-eq-expr ()
9703 (let ((pn (js2-parse-rel-expr))
9704 tt)
9705 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9706 (setq pn (js2-make-binary tt
9707 pn
9708 'js2-parse-rel-expr)))
9709 (js2-unget-token)
9710 pn))
9711
9712 (defconst js2-parse-rel-ops
9713 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9714
9715 (defun js2-parse-rel-expr ()
9716 (let ((pn (js2-parse-shift-expr))
9717 (continue t)
9718 tt)
9719 (while continue
9720 (setq tt (js2-get-token))
9721 (cond
9722 ((and js2-in-for-init (= tt js2-IN))
9723 (js2-unget-token)
9724 (setq continue nil))
9725 ((memq tt js2-parse-rel-ops)
9726 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9727 (t
9728 (js2-unget-token)
9729 (setq continue nil))))
9730 pn))
9731
9732 (defconst js2-parse-shift-ops
9733 (list js2-LSH js2-URSH js2-RSH))
9734
9735 (defun js2-parse-shift-expr ()
9736 (let ((pn (js2-parse-add-expr))
9737 tt
9738 (continue t))
9739 (while continue
9740 (setq tt (js2-get-token))
9741 (if (memq tt js2-parse-shift-ops)
9742 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9743 (js2-unget-token)
9744 (setq continue nil)))
9745 pn))
9746
9747 (defun js2-parse-add-expr ()
9748 (let ((pn (js2-parse-mul-expr))
9749 tt
9750 (continue t))
9751 (while continue
9752 (setq tt (js2-get-token))
9753 (if (or (= tt js2-ADD) (= tt js2-SUB))
9754 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9755 (js2-unget-token)
9756 (setq continue nil)))
9757 pn))
9758
9759 (defconst js2-parse-mul-ops
9760 (list js2-MUL js2-DIV js2-MOD))
9761
9762 (defun js2-parse-mul-expr ()
9763 (let ((pn (js2-parse-unary-expr))
9764 tt
9765 (continue t))
9766 (while continue
9767 (setq tt (js2-get-token))
9768 (if (memq tt js2-parse-mul-ops)
9769 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9770 (js2-unget-token)
9771 (setq continue nil)))
9772 pn))
9773
9774 (defun js2-make-unary (type parser &rest args)
9775 "Make a unary node of type TYPE.
9776 PARSER is either a node (for postfix operators) or a function to call
9777 to parse the operand (for prefix operators)."
9778 (let* ((pos (js2-current-token-beg))
9779 (postfix (js2-node-p parser))
9780 (expr (if postfix
9781 parser
9782 (apply parser args)))
9783 end
9784 pn)
9785 (if postfix ; e.g. i++
9786 (setq pos (js2-node-pos expr)
9787 end (js2-current-token-end))
9788 (setq end (js2-node-end expr)))
9789 (setq pn (make-js2-unary-node :type type
9790 :pos pos
9791 :len (- end pos)
9792 :operand expr))
9793 (js2-node-add-children pn expr)
9794 pn))
9795
9796 (defconst js2-incrementable-node-types
9797 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9798 "Node types that can be the operand of a ++ or -- operator.")
9799
9800 (defun js2-check-bad-inc-dec (tt beg end unary)
9801 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9802 js2-incrementable-node-types)
9803 (js2-report-error (if (= tt js2-INC)
9804 "msg.bad.incr"
9805 "msg.bad.decr")
9806 nil beg (- end beg))))
9807
9808 (defun js2-parse-unary-expr ()
9809 (let ((tt (js2-current-token-type))
9810 pn expr beg end)
9811 (cond
9812 ((or (= tt js2-VOID)
9813 (= tt js2-NOT)
9814 (= tt js2-BITNOT)
9815 (= tt js2-TYPEOF))
9816 (js2-get-token)
9817 (js2-make-unary tt 'js2-parse-unary-expr))
9818 ((= tt js2-ADD)
9819 (js2-get-token)
9820 ;; Convert to special POS token in decompiler and parse tree
9821 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9822 ((= tt js2-SUB)
9823 (js2-get-token)
9824 ;; Convert to special NEG token in decompiler and parse tree
9825 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9826 ((or (= tt js2-INC)
9827 (= tt js2-DEC))
9828 (js2-get-token)
9829 (prog1
9830 (setq beg (js2-current-token-beg)
9831 end (js2-current-token-end)
9832 expr (js2-make-unary tt 'js2-parse-member-expr t))
9833 (js2-check-bad-inc-dec tt beg end expr)))
9834 ((= tt js2-DELPROP)
9835 (js2-get-token)
9836 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9837 ((= tt js2-ERROR)
9838 (js2-get-token)
9839 (make-js2-error-node)) ; try to continue
9840 ((and (= tt js2-LT)
9841 js2-compiler-xml-available)
9842 ;; XML stream encountered in expression.
9843 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9844 (t
9845 (setq pn (js2-parse-member-expr t)
9846 ;; Don't look across a newline boundary for a postfix incop.
9847 tt (js2-peek-token-or-eol))
9848 (when (or (= tt js2-INC) (= tt js2-DEC))
9849 (js2-get-token)
9850 (setf expr pn
9851 pn (js2-make-unary tt expr))
9852 (js2-node-set-prop pn 'postfix t)
9853 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9854 pn))))
9855
9856 (defun js2-parse-xml-initializer ()
9857 "Parse an E4X XML initializer.
9858 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9859 Then I'll postprocess the result, depending on whether we're in IDE
9860 mode or codegen mode, and generate the appropriate rewritten AST.
9861 IDE mode uses a rich AST that models the XML structure. Codegen mode
9862 just concatenates everything and makes a new XML or XMLList out of it."
9863 (let ((tt (js2-get-first-xml-token))
9864 pn-xml pn expr kids expr-pos
9865 (continue t)
9866 (first-token t))
9867 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9868 (js2-report-error "msg.syntax"))
9869 (setq pn-xml (make-js2-xml-node))
9870 (while continue
9871 (if first-token
9872 (setq first-token nil)
9873 (setq tt (js2-get-next-xml-token)))
9874 (cond
9875 ;; js2-XML means we found a {expr} in the XML stream.
9876 ;; The token string is the XML up to the left-curly.
9877 ((= tt js2-XML)
9878 (push (make-js2-string-node :pos (js2-current-token-beg)
9879 :len (- js2-ts-cursor (js2-current-token-beg)))
9880 kids)
9881 (js2-must-match js2-LC "msg.syntax")
9882 (setq expr-pos js2-ts-cursor
9883 expr (if (eq (js2-peek-token) js2-RC)
9884 (make-js2-empty-expr-node :pos expr-pos)
9885 (js2-parse-expr)))
9886 (js2-must-match js2-RC "msg.syntax")
9887 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9888 :len (js2-node-len expr)
9889 :expr expr))
9890 (js2-node-add-children pn expr)
9891 (push pn kids))
9892 ;; a js2-XMLEND token means we hit the final close-tag.
9893 ((= tt js2-XMLEND)
9894 (push (make-js2-string-node :pos (js2-current-token-beg)
9895 :len (- js2-ts-cursor (js2-current-token-beg)))
9896 kids)
9897 (dolist (kid (nreverse kids))
9898 (js2-block-node-push pn-xml kid))
9899 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9900 (js2-node-pos pn-xml))
9901 continue nil))
9902 (t
9903 (js2-report-error "msg.syntax")
9904 (setq continue nil))))
9905 pn-xml))
9906
9907
9908 (defun js2-parse-argument-list ()
9909 "Parse an argument list and return it as a Lisp list of nodes.
9910 Returns the list in reverse order. Consumes the right-paren token."
9911 (let (result)
9912 (unless (js2-match-token js2-RP)
9913 (cl-loop do
9914 (let ((tt (js2-get-token)))
9915 (if (= tt js2-YIELD)
9916 (js2-report-error "msg.yield.parenthesized"))
9917 (if (and (= tt js2-TRIPLEDOT)
9918 (>= js2-language-version 200))
9919 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9920 (js2-unget-token)
9921 (push (js2-parse-assign-expr) result)))
9922 while
9923 (js2-match-token js2-COMMA))
9924 (js2-must-match js2-RP "msg.no.paren.arg")
9925 result)))
9926
9927 (defun js2-parse-member-expr (&optional allow-call-syntax)
9928 (let ((tt (js2-current-token-type))
9929 pn pos target args beg end init)
9930 (if (/= tt js2-NEW)
9931 (setq pn (js2-parse-primary-expr))
9932 ;; parse a 'new' expression
9933 (js2-get-token)
9934 (setq pos (js2-current-token-beg)
9935 beg pos
9936 target (js2-parse-member-expr)
9937 end (js2-node-end target)
9938 pn (make-js2-new-node :pos pos
9939 :target target
9940 :len (- end pos)))
9941 (js2-highlight-function-call (js2-current-token))
9942 (js2-node-add-children pn target)
9943 (when (js2-match-token js2-LP)
9944 ;; Add the arguments to pn, if any are supplied.
9945 (setf beg pos ; start of "new" keyword
9946 pos (js2-current-token-beg)
9947 args (nreverse (js2-parse-argument-list))
9948 (js2-new-node-args pn) args
9949 end (js2-current-token-end)
9950 (js2-new-node-lp pn) (- pos beg)
9951 (js2-new-node-rp pn) (- end 1 beg))
9952 (apply #'js2-node-add-children pn args))
9953 (when (and js2-allow-rhino-new-expr-initializer
9954 (js2-match-token js2-LC))
9955 (setf init (js2-parse-object-literal)
9956 end (js2-node-end init)
9957 (js2-new-node-initializer pn) init)
9958 (js2-node-add-children pn init))
9959 (setf (js2-node-len pn) (- end beg))) ; end outer if
9960 (js2-parse-member-expr-tail allow-call-syntax pn)))
9961
9962 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9963 "Parse a chain of property/array accesses or function calls.
9964 Includes parsing for E4X operators like `..' and `.@'.
9965 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9966 Returns an expression tree that includes PN, the parent node."
9967 (let (tt
9968 (continue t))
9969 (while continue
9970 (setq tt (js2-get-token))
9971 (cond
9972 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9973 (setq pn (js2-parse-property-access tt pn)))
9974 ((= tt js2-DOTQUERY)
9975 (setq pn (js2-parse-dot-query pn)))
9976 ((= tt js2-LB)
9977 (setq pn (js2-parse-element-get pn)))
9978 ((= tt js2-LP)
9979 (js2-unget-token)
9980 (if allow-call-syntax
9981 (setq pn (js2-parse-function-call pn))
9982 (setq continue nil)))
9983 ((= tt js2-TEMPLATE_HEAD)
9984 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9985 ((= tt js2-NO_SUBS_TEMPLATE)
9986 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9987 (t
9988 (js2-unget-token)
9989 (setq continue nil)))
9990 (if (>= js2-highlight-level 2)
9991 (js2-parse-highlight-member-expr-node pn)))
9992 pn))
9993
9994 (defun js2-parse-tagged-template (tag-node tpl-node)
9995 "Parse tagged template expression."
9996 (let* ((beg (js2-node-pos tag-node))
9997 (pn (make-js2-tagged-template-node :beg beg
9998 :len (- (js2-current-token-end) beg)
9999 :tag tag-node
10000 :template tpl-node)))
10001 (js2-node-add-children pn tag-node tpl-node)
10002 pn))
10003
10004 (defun js2-parse-dot-query (pn)
10005 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10006 Last token parsed must be `js2-DOTQUERY'."
10007 (let ((pos (js2-node-pos pn))
10008 op-pos expr end)
10009 (js2-must-have-xml)
10010 (js2-set-requires-activation)
10011 (setq op-pos (js2-current-token-beg)
10012 expr (js2-parse-expr)
10013 end (js2-node-end expr)
10014 pn (make-js2-xml-dot-query-node :left pn
10015 :pos pos
10016 :op-pos op-pos
10017 :right expr))
10018 (js2-node-add-children pn
10019 (js2-xml-dot-query-node-left pn)
10020 (js2-xml-dot-query-node-right pn))
10021 (if (js2-must-match js2-RP "msg.no.paren")
10022 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10023 end (js2-current-token-end)))
10024 (setf (js2-node-len pn) (- end pos))
10025 pn))
10026
10027 (defun js2-parse-element-get (pn)
10028 "Parse an element-get expression, e.g. foo[bar].
10029 Last token parsed must be `js2-RB'."
10030 (let ((lb (js2-current-token-beg))
10031 (pos (js2-node-pos pn))
10032 rb expr)
10033 (setq expr (js2-parse-expr))
10034 (if (js2-must-match js2-RB "msg.no.bracket.index")
10035 (setq rb (js2-current-token-beg)))
10036 (setq pn (make-js2-elem-get-node :target pn
10037 :pos pos
10038 :element expr
10039 :lb (js2-relpos lb pos)
10040 :rb (js2-relpos rb pos)
10041 :len (- (js2-current-token-end) pos)))
10042 (js2-node-add-children pn
10043 (js2-elem-get-node-target pn)
10044 (js2-elem-get-node-element pn))
10045 pn))
10046
10047 (defun js2-highlight-function-call (token)
10048 (when (eq (js2-token-type token) js2-NAME)
10049 (js2-record-face 'js2-function-call token)))
10050
10051 (defun js2-parse-function-call (pn)
10052 (js2-highlight-function-call (js2-current-token))
10053 (js2-get-token)
10054 (let (args
10055 (pos (js2-node-pos pn)))
10056 (setq pn (make-js2-call-node :pos pos
10057 :target pn
10058 :lp (- (js2-current-token-beg) pos)))
10059 (js2-node-add-children pn (js2-call-node-target pn))
10060 ;; Add the arguments to pn, if any are supplied.
10061 (setf args (nreverse (js2-parse-argument-list))
10062 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10063 (js2-call-node-args pn) args)
10064 (apply #'js2-node-add-children pn args)
10065 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10066 pn))
10067
10068 (defun js2-parse-property-access (tt pn)
10069 "Parse a property access, XML descendants access, or XML attr access."
10070 (let ((member-type-flags 0)
10071 (dot-pos (js2-current-token-beg))
10072 (dot-len (if (= tt js2-DOTDOT) 2 1))
10073 name
10074 ref ; right side of . or .. operator
10075 result)
10076 (when (= tt js2-DOTDOT)
10077 (js2-must-have-xml)
10078 (setq member-type-flags js2-descendants-flag))
10079 (if (not js2-compiler-xml-available)
10080 (progn
10081 (js2-must-match-prop-name "msg.no.name.after.dot")
10082 (setq name (js2-create-name-node t js2-GETPROP)
10083 result (make-js2-prop-get-node :left pn
10084 :pos (js2-current-token-beg)
10085 :right name
10086 :len (js2-current-token-len)))
10087 (js2-node-add-children result pn name)
10088 result)
10089 ;; otherwise look for XML operators
10090 (setf result (if (= tt js2-DOT)
10091 (make-js2-prop-get-node)
10092 (make-js2-infix-node :type js2-DOTDOT))
10093 (js2-node-pos result) (js2-node-pos pn)
10094 (js2-infix-node-op-pos result) dot-pos
10095 (js2-infix-node-left result) pn ; do this after setting position
10096 tt (js2-get-prop-name-token))
10097 (cond
10098 ;; handles: name, ns::name, ns::*, ns::[expr]
10099 ((= tt js2-NAME)
10100 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10101 ;; handles: *, *::name, *::*, *::[expr]
10102 ((= tt js2-MUL)
10103 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10104 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10105 ((= tt js2-XMLATTR)
10106 (setq result (js2-parse-attribute-access)))
10107 (t
10108 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10109 (if ref
10110 (setf (js2-node-len result) (- (js2-node-end ref)
10111 (js2-node-pos result))
10112 (js2-infix-node-right result) ref))
10113 (if (js2-infix-node-p result)
10114 (js2-node-add-children result
10115 (js2-infix-node-left result)
10116 (js2-infix-node-right result)))
10117 result)))
10118
10119 (defun js2-parse-attribute-access ()
10120 "Parse an E4X XML attribute expression.
10121 This includes expressions of the forms:
10122
10123 @attr @ns::attr @ns::*
10124 @* @*::attr @*::*
10125 @[expr] @*::[expr] @ns::[expr]
10126
10127 Called if we peeked an '@' token."
10128 (let ((tt (js2-get-prop-name-token))
10129 (at-pos (js2-current-token-beg)))
10130 (cond
10131 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10132 ((= tt js2-NAME)
10133 (js2-parse-property-name at-pos nil 0))
10134 ;; handles: @*, @*::name, @*::*, @*::[expr]
10135 ((= tt js2-MUL)
10136 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10137 ;; handles @[expr]
10138 ((= tt js2-LB)
10139 (js2-parse-xml-elem-ref at-pos))
10140 (t
10141 (js2-report-error "msg.no.name.after.xmlAttr")
10142 ;; Avoid cascaded errors that happen if we make an error node here.
10143 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10144
10145 (defun js2-parse-property-name (at-pos s member-type-flags)
10146 "Check if :: follows name in which case it becomes qualified name.
10147
10148 AT-POS is a natural number if we just read an '@' token, else nil.
10149 S is the name or string that was matched: an identifier, 'throw' or '*'.
10150 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10151
10152 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10153 operator, or the name is followed by ::. For a plain name, returns a
10154 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10155 (let ((pos (or at-pos (js2-current-token-beg)))
10156 colon-pos
10157 (name (js2-create-name-node t (js2-current-token-type) s))
10158 ns tt pn)
10159 (catch 'return
10160 (when (js2-match-token js2-COLONCOLON)
10161 (setq ns name
10162 colon-pos (js2-current-token-beg)
10163 tt (js2-get-prop-name-token))
10164 (cond
10165 ;; handles name::name
10166 ((= tt js2-NAME)
10167 (setq name (js2-create-name-node)))
10168 ;; handles name::*
10169 ((= tt js2-MUL)
10170 (setq name (js2-create-name-node nil nil "*")))
10171 ;; handles name::[expr]
10172 ((= tt js2-LB)
10173 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10174 (t
10175 (js2-report-error "msg.no.name.after.coloncolon"))))
10176 (if (and (null ns) (zerop member-type-flags))
10177 name
10178 (prog1
10179 (setq pn
10180 (make-js2-xml-prop-ref-node :pos pos
10181 :len (- (js2-node-end name) pos)
10182 :at-pos at-pos
10183 :colon-pos colon-pos
10184 :propname name))
10185 (js2-node-add-children pn name))))))
10186
10187 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10188 "Parse the [expr] portion of an xml element reference.
10189 For instance, @[expr], @*::[expr], or ns::[expr]."
10190 (let* ((lb (js2-current-token-beg))
10191 (pos (or at-pos lb))
10192 rb
10193 (expr (js2-parse-expr))
10194 (end (js2-node-end expr))
10195 pn)
10196 (if (js2-must-match js2-RB "msg.no.bracket.index")
10197 (setq rb (js2-current-token-beg)
10198 end (js2-current-token-end)))
10199 (prog1
10200 (setq pn
10201 (make-js2-xml-elem-ref-node :pos pos
10202 :len (- end pos)
10203 :namespace namespace
10204 :colon-pos colon-pos
10205 :at-pos at-pos
10206 :expr expr
10207 :lb (js2-relpos lb pos)
10208 :rb (js2-relpos rb pos)))
10209 (js2-node-add-children pn namespace expr))))
10210
10211 (defun js2-parse-destruct-primary-expr ()
10212 (let ((js2-is-in-destructuring t))
10213 (js2-parse-primary-expr)))
10214
10215 (defun js2-parse-primary-expr ()
10216 "Parse a literal (leaf) expression of some sort.
10217 Includes complex literals such as functions, object-literals,
10218 array-literals, array comprehensions and regular expressions."
10219 (let (tt node)
10220 (setq tt (js2-current-token-type))
10221 (cond
10222 ((= tt js2-CLASS)
10223 (js2-parse-class-expr))
10224 ((= tt js2-FUNCTION)
10225 (js2-parse-function-expr))
10226 ((= tt js2-LB)
10227 (js2-parse-array-comp-or-literal))
10228 ((= tt js2-LC)
10229 (js2-parse-object-literal))
10230 ((= tt js2-LET)
10231 (js2-parse-let (js2-current-token-beg)))
10232 ((= tt js2-LP)
10233 (js2-parse-paren-expr-or-generator-comp))
10234 ((= tt js2-XMLATTR)
10235 (js2-must-have-xml)
10236 (js2-parse-attribute-access))
10237 ((= tt js2-NAME)
10238 (js2-parse-name tt))
10239 ((= tt js2-NUMBER)
10240 (setq node (make-js2-number-node))
10241 (when (and js2-in-use-strict-directive
10242 (= (js2-number-node-num-base node) 8))
10243 (js2-report-error "msg.no.octal.strict"))
10244 node)
10245 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10246 (make-js2-string-node :type tt))
10247 ((= tt js2-TEMPLATE_HEAD)
10248 (js2-parse-template-literal))
10249 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10250 ;; Got / or /= which in this context means a regexp literal
10251 (let ((px-pos (js2-current-token-beg))
10252 (flags (js2-read-regexp tt))
10253 (end (js2-current-token-end)))
10254 (prog1
10255 (make-js2-regexp-node :pos px-pos
10256 :len (- end px-pos)
10257 :value (js2-current-token-string)
10258 :flags flags)
10259 (js2-set-face px-pos end 'font-lock-string-face 'record)
10260 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10261 ((or (= tt js2-NULL)
10262 (= tt js2-THIS)
10263 (= tt js2-SUPER)
10264 (= tt js2-FALSE)
10265 (= tt js2-TRUE))
10266 (make-js2-keyword-node :type tt))
10267 ((= tt js2-TRIPLEDOT)
10268 ;; Likewise, only valid in an arrow function with a rest param.
10269 (if (and (js2-match-token js2-NAME)
10270 (js2-match-token js2-RP)
10271 (eq (js2-peek-token) js2-ARROW))
10272 (progn
10273 (js2-unget-token) ; Put back the right paren.
10274 ;; See the previous case.
10275 (make-js2-keyword-node :type js2-NULL))
10276 (js2-report-error "msg.syntax")
10277 (make-js2-error-node)))
10278 ((= tt js2-RESERVED)
10279 (js2-report-error "msg.reserved.id")
10280 (make-js2-name-node))
10281 ((= tt js2-ERROR)
10282 ;; the scanner or one of its subroutines reported the error.
10283 (make-js2-error-node))
10284 ((= tt js2-EOF)
10285 (let* ((px-pos (point-at-bol))
10286 (len (- js2-ts-cursor px-pos)))
10287 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10288 (make-js2-error-node :pos (1- js2-ts-cursor)))
10289 (t
10290 (js2-report-error "msg.syntax")
10291 (make-js2-error-node)))))
10292
10293 (defun js2-parse-template-literal ()
10294 (let ((beg (js2-current-token-beg))
10295 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10296 (tt js2-TEMPLATE_HEAD))
10297 (while (eq tt js2-TEMPLATE_HEAD)
10298 (push (js2-parse-expr) kids)
10299 (js2-must-match js2-RC "msg.syntax")
10300 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10301 (push (make-js2-string-node :type tt) kids))
10302 (setq kids (nreverse kids))
10303 (let ((tpl (make-js2-template-node :beg beg
10304 :len (- (js2-current-token-end) beg)
10305 :kids kids)))
10306 (apply #'js2-node-add-children tpl kids)
10307 tpl)))
10308
10309 (defun js2-parse-name (_tt)
10310 (let ((name (js2-current-token-string))
10311 node)
10312 (setq node (if js2-compiler-xml-available
10313 (js2-parse-property-name nil name 0)
10314 (js2-create-name-node 'check-activation nil name)))
10315 (if js2-highlight-external-variables
10316 (js2-record-name-node node))
10317 node))
10318
10319 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10320 (js2-add-strict-warning
10321 msg nil
10322 ;; back up from comma to beginning of line or array/objlit
10323 (max (if elems
10324 (js2-node-pos (car elems))
10325 pos)
10326 (save-excursion
10327 (goto-char comma-pos)
10328 (back-to-indentation)
10329 (point)))
10330 comma-pos))
10331
10332 (defun js2-parse-array-comp-or-literal ()
10333 (let ((pos (js2-current-token-beg)))
10334 (if (and (>= js2-language-version 200)
10335 (js2-match-token js2-FOR))
10336 (js2-parse-array-comp pos)
10337 (js2-parse-array-literal pos))))
10338
10339 (defun js2-parse-array-literal (pos)
10340 (let ((after-lb-or-comma t)
10341 after-comma tt elems pn
10342 (continue t))
10343 (unless js2-is-in-destructuring
10344 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10345 (while continue
10346 (setq tt (js2-get-token))
10347 (cond
10348 ;; comma
10349 ((= tt js2-COMMA)
10350 (setq after-comma (js2-current-token-end))
10351 (if (not after-lb-or-comma)
10352 (setq after-lb-or-comma t)
10353 (push nil elems)))
10354 ;; end of array
10355 ((or (= tt js2-RB)
10356 (= tt js2-EOF)) ; prevent infinite loop
10357 (if (= tt js2-EOF)
10358 (js2-report-error "msg.no.bracket.arg" nil pos))
10359 (when (and after-comma (< js2-language-version 170))
10360 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10361 pos (remove nil elems) after-comma))
10362 (setq continue nil
10363 pn (make-js2-array-node :pos pos
10364 :len (- js2-ts-cursor pos)
10365 :elems (nreverse elems)))
10366 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10367 ;; destructuring binding
10368 (js2-is-in-destructuring
10369 (push (cond
10370 ((and (= tt js2-NAME)
10371 (= js2-ASSIGN (js2-peek-token)))
10372 ;; a=defaultValue
10373 (js2-parse-initialized-binding (js2-parse-name js2-NAME)))
10374 ((or (= tt js2-LC)
10375 (= tt js2-LB)
10376 (= tt js2-NAME))
10377 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10378 (js2-parse-destruct-primary-expr))
10379 ;; invalid pattern
10380 (t
10381 (js2-report-error "msg.bad.var")
10382 (make-js2-error-node)))
10383 elems)
10384 (setq after-lb-or-comma nil
10385 after-comma nil))
10386 ;; array comp
10387 ((and (>= js2-language-version 170)
10388 (= tt js2-FOR) ; check for array comprehension
10389 (not after-lb-or-comma) ; "for" can't follow a comma
10390 elems ; must have at least 1 element
10391 (not (cdr elems))) ; but no 2nd element
10392 (js2-unget-token)
10393 (setf continue nil
10394 pn (js2-parse-legacy-array-comp (car elems) pos)))
10395 ;; another element
10396 (t
10397 (unless after-lb-or-comma
10398 (js2-report-error "msg.no.bracket.arg"))
10399 (if (and (= tt js2-TRIPLEDOT)
10400 (>= js2-language-version 200))
10401 ;; spread operator
10402 (push (js2-make-unary tt 'js2-parse-assign-expr)
10403 elems)
10404 (js2-unget-token)
10405 (push (js2-parse-assign-expr) elems))
10406 (setq after-lb-or-comma nil
10407 after-comma nil))))
10408 (unless js2-is-in-destructuring
10409 (js2-pop-scope))
10410 pn))
10411
10412 (defun js2-parse-legacy-array-comp (expr pos)
10413 "Parse a legacy array comprehension (JavaScript 1.7).
10414 EXPR is the first expression after the opening left-bracket.
10415 POS is the beginning of the LB token preceding EXPR.
10416 We should have just parsed the 'for' keyword before calling this function."
10417 (let ((current-scope js2-current-scope)
10418 loops first filter result)
10419 (unwind-protect
10420 (progn
10421 (while (js2-match-token js2-FOR)
10422 (let ((loop (make-js2-comp-loop-node)))
10423 (js2-push-scope loop)
10424 (push loop loops)
10425 (js2-parse-comp-loop loop)))
10426 ;; First loop takes expr scope's parent.
10427 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10428 (js2-scope-parent-scope current-scope))
10429 ;; Set expr scope's parent to the last loop.
10430 (setf (js2-scope-parent-scope current-scope) (car loops))
10431 (if (/= (js2-get-token) js2-IF)
10432 (js2-unget-token)
10433 (setq filter (js2-parse-condition))))
10434 (dotimes (_ (1- (length loops)))
10435 (js2-pop-scope)))
10436 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10437 (setq result (make-js2-comp-node :pos pos
10438 :len (- js2-ts-cursor pos)
10439 :result expr
10440 :loops (nreverse loops)
10441 :filters (and filter (list (car filter)))
10442 :form 'LEGACY_ARRAY))
10443 ;; Set comp loop's parent to the last loop.
10444 ;; TODO: Get rid of the bogus expr scope.
10445 (setf (js2-scope-parent-scope result) first)
10446 (apply #'js2-node-add-children result expr (car filter)
10447 (js2-comp-node-loops result))
10448 result))
10449
10450 (defun js2-parse-array-comp (pos)
10451 "Parse an ES6 array comprehension.
10452 POS is the beginning of the LB token.
10453 We should have just parsed the 'for' keyword before calling this function."
10454 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10455 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10456 pn))
10457
10458 (defun js2-parse-generator-comp (pos)
10459 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10460 (js2-current-script-or-fn
10461 (make-js2-function-node :generator-type 'COMPREHENSION))
10462 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10463 (js2-must-match js2-RP "msg.no.paren" pos)
10464 pn))
10465
10466 (defun js2-parse-comprehension (pos form)
10467 (let (loops filters expr result last)
10468 (unwind-protect
10469 (progn
10470 (js2-unget-token)
10471 (while (js2-match-token js2-FOR)
10472 (let ((loop (make-js2-comp-loop-node)))
10473 (js2-push-scope loop)
10474 (push loop loops)
10475 (js2-parse-comp-loop loop)))
10476 (while (js2-match-token js2-IF)
10477 (push (car (js2-parse-condition)) filters))
10478 (setq expr (js2-parse-assign-expr))
10479 (setq last (car loops)))
10480 (dolist (_ loops)
10481 (js2-pop-scope)))
10482 (setq result (make-js2-comp-node :pos pos
10483 :len (- js2-ts-cursor pos)
10484 :result expr
10485 :loops (nreverse loops)
10486 :filters (nreverse filters)
10487 :form form))
10488 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10489 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10490 (setf (js2-scope-parent-scope result) last)
10491 result))
10492
10493 (defun js2-parse-comp-loop (pn &optional only-of-p)
10494 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10495 The current token should be the initial FOR.
10496 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10497 (let ((pos (js2-comp-loop-node-pos pn))
10498 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10499 (when (and (not only-of-p) (js2-match-token js2-NAME))
10500 (if (string= (js2-current-token-string) "each")
10501 (progn
10502 (setq foreach-p t
10503 each-pos (- (js2-current-token-beg) pos)) ; relative
10504 (js2-record-face 'font-lock-keyword-face))
10505 (js2-report-error "msg.no.paren.for")))
10506 (if (js2-must-match js2-LP "msg.no.paren.for")
10507 (setq lp (- (js2-current-token-beg) pos)))
10508 (setq tt (js2-peek-token))
10509 (cond
10510 ((or (= tt js2-LB)
10511 (= tt js2-LC))
10512 (js2-get-token)
10513 (setq iter (js2-parse-destruct-primary-expr))
10514 (js2-define-destruct-symbols iter js2-LET
10515 'font-lock-variable-name-face t))
10516 ((js2-match-token js2-NAME)
10517 (setq iter (js2-create-name-node)))
10518 (t
10519 (js2-report-error "msg.bad.var")))
10520 ;; Define as a let since we want the scope of the variable to
10521 ;; be restricted to the array comprehension
10522 (if (js2-name-node-p iter)
10523 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10524 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10525 (and (>= js2-language-version 200)
10526 (js2-match-contextual-kwd "of")
10527 (setq forof-p t)))
10528 (setq in-pos (- (js2-current-token-beg) pos))
10529 (js2-report-error "msg.in.after.for.name"))
10530 (setq obj (js2-parse-expr))
10531 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10532 (setq rp (- (js2-current-token-beg) pos)))
10533 (setf (js2-node-pos pn) pos
10534 (js2-node-len pn) (- js2-ts-cursor pos)
10535 (js2-comp-loop-node-iterator pn) iter
10536 (js2-comp-loop-node-object pn) obj
10537 (js2-comp-loop-node-in-pos pn) in-pos
10538 (js2-comp-loop-node-each-pos pn) each-pos
10539 (js2-comp-loop-node-foreach-p pn) foreach-p
10540 (js2-comp-loop-node-forof-p pn) forof-p
10541 (js2-comp-loop-node-lp pn) lp
10542 (js2-comp-loop-node-rp pn) rp)
10543 (js2-node-add-children pn iter obj)
10544 pn))
10545
10546 (defun js2-parse-class-stmt ()
10547 (let ((pos (js2-current-token-beg))
10548 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10549 (name (js2-create-name-node t)))
10550 (js2-set-face (js2-node-pos name) (js2-node-end name)
10551 'font-lock-function-name-face 'record)
10552 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10553 (js2-define-symbol js2-FUNCTION
10554 (js2-name-node-name name)
10555 node)
10556 node)))
10557
10558 (defun js2-parse-class-expr ()
10559 (let ((pos (js2-current-token-beg))
10560 name)
10561 (when (js2-match-token js2-NAME)
10562 (setq name (js2-create-name-node t)))
10563 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10564
10565 (defun js2-parse-class (pos form name)
10566 ;; class X [extends ...] {
10567 (let (pn elems extends)
10568 (if (js2-match-token js2-EXTENDS)
10569 (if (= (js2-peek-token) js2-LC)
10570 (js2-report-error "msg.missing.extends")
10571 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10572 (setq extends (js2-parse-assign-expr))
10573 (if (not extends)
10574 (js2-report-error "msg.bad.extends"))))
10575 (js2-must-match js2-LC "msg.no.brace.class")
10576 (setq elems (js2-parse-object-literal-elems t)
10577 pn (make-js2-class-node :pos pos
10578 :len (- js2-ts-cursor pos)
10579 :form form
10580 :name name
10581 :extends extends
10582 :elems elems))
10583 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10584 pn))
10585
10586 (defun js2-parse-object-literal ()
10587 (let* ((pos (js2-current-token-beg))
10588 (elems (js2-parse-object-literal-elems))
10589 (result (make-js2-object-node :pos pos
10590 :len (- js2-ts-cursor pos)
10591 :elems elems)))
10592 (apply #'js2-node-add-children result (js2-object-node-elems result))
10593 result))
10594
10595 (defun js2-property-key-string (property-node)
10596 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10597 `js2-method-node') as a string, or nil if it can't be
10598 represented as a string (e.g., the key is computed by an
10599 expression)."
10600 (let ((key (js2-infix-node-left property-node)))
10601 (when (js2-computed-prop-name-node-p key)
10602 (setq key (js2-computed-prop-name-node-expr key)))
10603 (cond
10604 ((js2-name-node-p key)
10605 (js2-name-node-name key))
10606 ((js2-string-node-p key)
10607 (js2-string-node-value key))
10608 ((js2-number-node-p key)
10609 (js2-number-node-value key)))))
10610
10611 (defun js2-parse-object-literal-elems (&optional class-p)
10612 (let ((pos (js2-current-token-beg))
10613 (static nil)
10614 (continue t)
10615 tt elems elem
10616 elem-key-string previous-elem-key-string
10617 after-comma previous-token)
10618 (while continue
10619 (setq tt (js2-get-prop-name-token)
10620 static nil
10621 elem nil
10622 previous-token nil)
10623 ;; Handle 'static' keyword only if we're in a class
10624 (when (and class-p (= js2-NAME tt)
10625 (string= "static" (js2-current-token-string)))
10626 (js2-record-face 'font-lock-keyword-face)
10627 (setq static t
10628 tt (js2-get-prop-name-token)))
10629 ;; Handle generator * before the property name for in-line functions
10630 (when (and (>= js2-language-version 200)
10631 (= js2-MUL tt))
10632 (setq previous-token (js2-current-token)
10633 tt (js2-get-prop-name-token)))
10634 ;; Handle 'get' or 'set' keywords
10635 (let ((prop (js2-current-token-string)))
10636 (when (and (>= js2-language-version 200)
10637 (= js2-NAME tt)
10638 (or (string= prop "get")
10639 (string= prop "set"))
10640 (member (js2-peek-token)
10641 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10642 (setq previous-token (js2-current-token)
10643 tt (js2-get-prop-name-token))))
10644 (cond
10645 ;; Found a property (of any sort)
10646 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10647 (setq after-comma nil
10648 elem (js2-parse-named-prop tt pos previous-token))
10649 (if (and (null elem)
10650 (not js2-recover-from-parse-errors))
10651 (setq continue nil)))
10652 ;; Break out of loop, and handle trailing commas.
10653 ((or (= tt js2-RC)
10654 (= tt js2-EOF))
10655 (js2-unget-token)
10656 (setq continue nil)
10657 (if after-comma
10658 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10659 pos elems after-comma)))
10660 ;; Skip semicolons in a class body
10661 ((and class-p
10662 (= tt js2-SEMI))
10663 nil)
10664 (t
10665 (js2-report-error "msg.bad.prop")
10666 (unless js2-recover-from-parse-errors
10667 (setq continue nil)))) ; end switch
10668 ;; Handle static for classes' codegen.
10669 (if static
10670 (if elem (js2-node-set-prop elem 'STATIC t)
10671 (js2-report-error "msg.unexpected.static")))
10672 ;; Handle commas, depending on class-p.
10673 (let ((tok (js2-get-prop-name-token)))
10674 (if (eq tok js2-COMMA)
10675 (if class-p
10676 (js2-report-error "msg.class.unexpected.comma")
10677 (setq after-comma (js2-current-token-end)))
10678 (js2-unget-token)
10679 (unless class-p (setq continue nil))))
10680 (when elem
10681 (when (and js2-in-use-strict-directive
10682 (setq elem-key-string (js2-property-key-string elem))
10683 (cl-some
10684 (lambda (previous-elem)
10685 (and (setq previous-elem-key-string
10686 (js2-property-key-string previous-elem))
10687 ;; Check if the property is a duplicate.
10688 (string= previous-elem-key-string elem-key-string)
10689 ;; But make an exception for getter / setter pairs.
10690 (not (and (js2-method-node-p elem)
10691 (js2-method-node-p previous-elem)
10692 (/= (js2-method-node-type elem)
10693 (js2-method-node-type previous-elem))))))
10694 elems))
10695 (js2-report-error "msg.dup.obj.lit.prop.strict"
10696 elem-key-string
10697 (js2-node-abs-pos (js2-infix-node-left elem))
10698 (js2-node-len (js2-infix-node-left elem))))
10699 ;; Append any parsed element.
10700 (push elem elems))) ; end loop
10701 (js2-must-match js2-RC "msg.no.brace.prop")
10702 (nreverse elems)))
10703
10704 (defun js2-parse-named-prop (tt pos previous-token)
10705 "Parse a name, string, or getter/setter object property.
10706 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10707 (let ((key (js2-parse-prop-name tt))
10708 (prop (and previous-token (js2-token-string previous-token)))
10709 (property-type (when previous-token
10710 (if (= (js2-token-type previous-token) js2-MUL)
10711 "*"
10712 (js2-token-string previous-token)))))
10713 (when (or (string= prop "get")
10714 (string= prop "set"))
10715 (js2-set-face (js2-token-beg previous-token)
10716 (js2-token-end previous-token)
10717 'font-lock-keyword-face 'record)) ; get/set
10718 (cond
10719 ;; method definition: {f() {...}}
10720 ((and (= (js2-peek-token) js2-LP)
10721 (>= js2-language-version 200))
10722 (when (js2-name-node-p key) ; highlight function name properties
10723 (js2-record-face 'font-lock-function-name-face))
10724 (js2-parse-method-prop pos key property-type))
10725 ;; binding element with initializer
10726 ((and (= (js2-peek-token) js2-ASSIGN)
10727 (>= js2-language-version 200))
10728 (js2-parse-initialized-binding key))
10729 ;; regular prop
10730 (t
10731 (let ((beg (js2-current-token-beg))
10732 (end (js2-current-token-end))
10733 (expr (js2-parse-plain-property key)))
10734 (when (and (= tt js2-NAME)
10735 (not js2-is-in-destructuring)
10736 js2-highlight-external-variables
10737 (js2-node-get-prop expr 'SHORTHAND))
10738 (js2-record-name-node key))
10739 (js2-set-face beg end
10740 (if (js2-function-node-p
10741 (js2-object-prop-node-right expr))
10742 'font-lock-function-name-face
10743 'js2-object-property)
10744 'record)
10745 expr)))))
10746
10747 (defun js2-parse-initialized-binding (name)
10748 "Parse a `SingleNameBinding' with initializer.
10749
10750 `name' is the `BindingIdentifier'."
10751 (when (js2-match-token js2-ASSIGN)
10752 (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
10753
10754 (defun js2-parse-prop-name (tt)
10755 (cond
10756 ;; Literal string keys: {'foo': 'bar'}
10757 ((= tt js2-STRING)
10758 (make-js2-string-node))
10759 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10760 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10761 ((and (= tt js2-LB)
10762 (>= js2-language-version 200))
10763 (make-js2-computed-prop-name-node
10764 :expr (prog1 (js2-parse-assign-expr)
10765 (js2-must-match js2-RB "msg.missing.computed.rb"))))
10766 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10767 ((= tt js2-NUMBER)
10768 (make-js2-number-node))
10769 ;; Unquoted names: {foo: 12}
10770 ((= tt js2-NAME)
10771 (js2-create-name-node))
10772 ;; Anything else is an error
10773 (t (js2-report-error "msg.bad.prop"))))
10774
10775 (defun js2-parse-plain-property (prop)
10776 "Parse a non-getter/setter property in an object literal.
10777 PROP is the node representing the property: a number, name,
10778 string or expression."
10779 (let* ((tt (js2-get-token))
10780 (pos (js2-node-pos prop))
10781 colon expr result)
10782 (cond
10783 ;; Abbreviated property, as in {foo, bar}
10784 ((and (>= js2-language-version 200)
10785 (or (= tt js2-COMMA)
10786 (= tt js2-RC))
10787 (not (js2-number-node-p prop)))
10788 (js2-unget-token)
10789 (setq result (make-js2-object-prop-node
10790 :pos pos
10791 :left prop
10792 :right prop
10793 :op-pos (js2-current-token-len)))
10794 (js2-node-add-children result prop)
10795 (js2-node-set-prop result 'SHORTHAND t)
10796 result)
10797 ;; Normal property
10798 (t
10799 (if (= tt js2-COLON)
10800 (setq colon (- (js2-current-token-beg) pos)
10801 expr (js2-parse-assign-expr))
10802 (js2-report-error "msg.no.colon.prop")
10803 (setq expr (make-js2-error-node)))
10804 (setq result (make-js2-object-prop-node
10805 :pos pos
10806 ;; don't include last consumed token in length
10807 :len (- (+ (js2-node-pos expr)
10808 (js2-node-len expr))
10809 pos)
10810 :left prop
10811 :right expr
10812 :op-pos colon))
10813 (js2-node-add-children result prop expr)
10814 result))))
10815
10816 (defun js2-parse-method-prop (pos prop type-string)
10817 "Parse method property in an object literal or a class body.
10818 JavaScript syntax is:
10819
10820 { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...} }
10821
10822 and expression closure style is also supported
10823
10824 { get foo() x, set foo(x) _x = x }
10825
10826 POS is the start position of the `get' or `set' keyword.
10827 PROP is the `js2-name-node' representing the property name.
10828 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10829 (let ((type (cond
10830 ((string= "get" type-string) js2-GET)
10831 ((string= "set" type-string) js2-SET)
10832 (t js2-FUNCTION)))
10833 result end
10834 (fn (js2-parse-function-expr)))
10835 ;; it has to be an anonymous function, as we already parsed the name
10836 (if (/= (js2-node-type fn) js2-FUNCTION)
10837 (js2-report-error "msg.bad.prop")
10838 (if (cl-plusp (length (js2-function-name fn)))
10839 (js2-report-error "msg.bad.prop")))
10840 (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
10841 (when (string= type-string "*")
10842 (setf (js2-function-node-generator-type fn) 'STAR))
10843 (setq end (js2-node-end fn)
10844 result (make-js2-method-node :type type
10845 :pos pos
10846 :len (- end pos)
10847 :left prop
10848 :right fn))
10849 (js2-node-add-children result prop fn)
10850 result))
10851
10852 (defun js2-create-name-node (&optional check-activation-p token string)
10853 "Create a name node using the current token and, optionally, STRING.
10854 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10855 (let* ((beg (js2-current-token-beg))
10856 (tt (js2-current-token-type))
10857 (s (or string
10858 (if (= js2-NAME tt)
10859 (js2-current-token-string)
10860 (js2-tt-name tt))))
10861 name)
10862 (setq name (make-js2-name-node :pos beg
10863 :name s
10864 :len (length s)))
10865 (if check-activation-p
10866 (js2-check-activation-name s (or token js2-NAME)))
10867 name))
10868
10869 ;;; Indentation support (bouncing)
10870
10871 ;; In recent-enough Emacs, we reuse the indentation code from
10872 ;; `js-mode'. To continue support for the older versions, some code
10873 ;; that was here previously was moved to `js2-old-indent.el'.
10874
10875 ;; Whichever indenter is used, it's often "wrong", however, and needs
10876 ;; to be overridden. The right long-term solution is probably to
10877 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
10878 ;; of coding. Even when a parse tree from `js2-parse' is present,
10879 ;; which is not true at the moment the user is typing, computing
10880 ;; indentation is still thousands of lines of code to handle every
10881 ;; possible syntactic edge case.
10882
10883 ;; In the meantime, the compromise solution is that we offer a "bounce
10884 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10885 ;; current line indent among various likely guess points. This approach
10886 ;; is far from perfect, but should at least make it slightly easier to
10887 ;; move the line towards its desired indentation when manually
10888 ;; overriding Karl's heuristic nesting guesser.
10889
10890 (defun js2-backward-sws ()
10891 "Move backward through whitespace and comments."
10892 (interactive)
10893 (while (forward-comment -1)))
10894
10895 (defun js2-forward-sws ()
10896 "Move forward through whitespace and comments."
10897 (interactive)
10898 (while (forward-comment 1)))
10899
10900 (defun js2-arglist-close ()
10901 "Return non-nil if we're on a line beginning with a close-paren/brace."
10902 (save-excursion
10903 (goto-char (point-at-bol))
10904 (js2-forward-sws)
10905 (looking-at "[])}]")))
10906
10907 (defun js2-indent-looks-like-label-p ()
10908 (goto-char (point-at-bol))
10909 (js2-forward-sws)
10910 (looking-at (concat js2-mode-identifier-re ":")))
10911
10912 (defun js2-indent-in-objlit-p (parse-status)
10913 "Return non-nil if this looks like an object-literal entry."
10914 (let ((start (nth 1 parse-status)))
10915 (and
10916 start
10917 (save-excursion
10918 (and (zerop (forward-line -1))
10919 (not (< (point) start)) ; crossed a {} boundary
10920 (js2-indent-looks-like-label-p)))
10921 (save-excursion
10922 (js2-indent-looks-like-label-p)))))
10923
10924 ;; If prev line looks like foobar({ then we're passing an object
10925 ;; literal to a function call, and people pretty much always want to
10926 ;; de-dent back to the previous line, so move the 'basic-offset'
10927 ;; position to the front.
10928 (defun js2-indent-objlit-arg-p (parse-status)
10929 (save-excursion
10930 (back-to-indentation)
10931 (js2-backward-sws)
10932 (and (eq (1- (point)) (nth 1 parse-status))
10933 (eq (char-before) ?{)
10934 (progn
10935 (forward-char -1)
10936 (skip-chars-backward " \t")
10937 (eq (char-before) ?\()))))
10938
10939 (defun js2-indent-case-block-p ()
10940 (save-excursion
10941 (back-to-indentation)
10942 (js2-backward-sws)
10943 (goto-char (point-at-bol))
10944 (skip-chars-forward " \t")
10945 (looking-at "case\\s-.+:")))
10946
10947 (defun js2-bounce-indent (normal-col parse-status &optional backward)
10948 "Cycle among alternate computed indentation positions.
10949 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10950 of the buffer to the current point. NORMAL-COL is the indentation
10951 column computed by the heuristic guesser based on current paren,
10952 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10953 in reverse."
10954 (let ((cur-indent (current-indentation))
10955 (old-buffer-undo-list buffer-undo-list)
10956 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10957 (current-line (save-excursion
10958 (forward-line 0) ; move to bol
10959 (1+ (count-lines (point-min) (point)))))
10960 positions pos main-pos anchor arglist-cont same-indent
10961 basic-offset computed-pos)
10962 ;; temporarily don't record undo info, if user requested this
10963 (when js2-mode-indent-inhibit-undo
10964 (setq buffer-undo-list t))
10965 (unwind-protect
10966 (progn
10967 ;; First likely point: indent from beginning of previous code line
10968 (push (setq basic-offset
10969 (+ (save-excursion
10970 (back-to-indentation)
10971 (js2-backward-sws)
10972 (back-to-indentation)
10973 (current-column))
10974 js2-basic-offset))
10975 positions)
10976
10977 ;; (First + epsilon) likely point: indent 2x from beginning of
10978 ;; previous code line. Google does it this way.
10979 (push (setq basic-offset
10980 (+ (save-excursion
10981 (back-to-indentation)
10982 (js2-backward-sws)
10983 (back-to-indentation)
10984 (current-column))
10985 (* 2 js2-basic-offset)))
10986 positions)
10987
10988 ;; Second likely point: indent from assign-expr RHS. This
10989 ;; is just a crude guess based on finding " = " on the previous
10990 ;; line containing actual code.
10991 (setq pos (save-excursion
10992 (forward-line -1)
10993 (goto-char (point-at-bol))
10994 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10995 (point-at-eol) t)
10996 (goto-char (match-end 1))
10997 (skip-chars-forward " \t\r\n")
10998 (current-column))))
10999 (when pos
11000 (cl-incf pos js2-basic-offset)
11001 (push pos positions))
11002
11003 ;; Third likely point: same indent as previous line of code.
11004 ;; Make it the first likely point if we're not on an
11005 ;; arglist-close line and previous line ends in a comma, or
11006 ;; both this line and prev line look like object-literal
11007 ;; elements.
11008 (setq pos (save-excursion
11009 (goto-char (point-at-bol))
11010 (js2-backward-sws)
11011 (back-to-indentation)
11012 (prog1
11013 (current-column)
11014 ;; while we're here, look for trailing comma
11015 (if (save-excursion
11016 (goto-char (point-at-eol))
11017 (js2-backward-sws)
11018 (eq (char-before) ?,))
11019 (setq arglist-cont (1- (point)))))))
11020 (when pos
11021 (if (and (or arglist-cont
11022 (js2-indent-in-objlit-p parse-status))
11023 (not (js2-arglist-close)))
11024 (setq same-indent pos))
11025 (push pos positions))
11026
11027 ;; Fourth likely point: first preceding code with less indentation.
11028 ;; than the immediately preceding code line.
11029 (setq pos (save-excursion
11030 (back-to-indentation)
11031 (js2-backward-sws)
11032 (back-to-indentation)
11033 (setq anchor (current-column))
11034 (while (and (zerop (forward-line -1))
11035 (>= (progn
11036 (back-to-indentation)
11037 (current-column))
11038 anchor)))
11039 (setq pos (current-column))))
11040 (push pos positions)
11041
11042 ;; nesting-heuristic position, main by default
11043 (push (setq main-pos normal-col) positions)
11044
11045 ;; delete duplicates and sort positions list
11046 (setq positions (sort (delete-dups positions) '<))
11047
11048 ;; comma-list continuation lines: prev line indent takes precedence
11049 (if same-indent
11050 (setq main-pos same-indent))
11051
11052 ;; common special cases where we want to indent in from previous line
11053 (if (or (js2-indent-case-block-p)
11054 (js2-indent-objlit-arg-p parse-status))
11055 (setq main-pos basic-offset))
11056
11057 ;; if bouncing backward, reverse positions list
11058 (if backward
11059 (setq positions (reverse positions)))
11060
11061 ;; record whether we're already sitting on one of the alternatives
11062 (setq pos (member cur-indent positions))
11063
11064 (cond
11065 ;; case 0: we're one one of the alternatives and this is the
11066 ;; first time they've pressed TAB on this line (best-guess).
11067 ((and js2-mode-indent-ignore-first-tab
11068 pos
11069 ;; first time pressing TAB on this line?
11070 (not (eq js2-mode-last-indented-line current-line)))
11071 ;; do nothing
11072 (setq computed-pos nil))
11073 ;; case 1: only one computed position => use it
11074 ((null (cdr positions))
11075 (setq computed-pos 0))
11076 ;; case 2: not on any of the computed spots => use main spot
11077 ((not pos)
11078 (setq computed-pos (js2-position main-pos positions)))
11079 ;; case 3: on last position: cycle to first position
11080 ((null (cdr pos))
11081 (setq computed-pos 0))
11082 ;; case 4: on intermediate position: cycle to next position
11083 (t
11084 (setq computed-pos (js2-position (cl-second pos) positions))))
11085
11086 ;; see if any hooks want to indent; otherwise we do it
11087 (cl-loop with result = nil
11088 for hook in js2-indent-hook
11089 while (null result)
11090 do
11091 (setq result (funcall hook positions computed-pos))
11092 finally do
11093 (unless (or result (null computed-pos))
11094 (indent-line-to (nth computed-pos positions)))))
11095
11096 ;; finally
11097 (if js2-mode-indent-inhibit-undo
11098 (setq buffer-undo-list old-buffer-undo-list))
11099 ;; see commentary for `js2-mode-last-indented-line'
11100 (setq js2-mode-last-indented-line current-line))))
11101
11102 (defun js2-1-line-comment-continuation-p ()
11103 "Return t if we're in a 1-line comment continuation.
11104 If so, we don't ever want to use bounce-indent."
11105 (save-excursion
11106 (and (progn
11107 (forward-line 0)
11108 (looking-at "\\s-*//"))
11109 (progn
11110 (forward-line -1)
11111 (forward-line 0)
11112 (when (looking-at "\\s-*$")
11113 (js2-backward-sws)
11114 (forward-line 0))
11115 (looking-at "\\s-*//")))))
11116
11117 (defun js2-indent-bounce (&optional backward)
11118 "Indent the current line, bouncing between several positions."
11119 (interactive)
11120 (let (parse-status offset indent-col
11121 ;; Don't whine about errors/warnings when we're indenting.
11122 ;; This has to be set before calling parse-partial-sexp below.
11123 (inhibit-point-motion-hooks t))
11124 (setq parse-status (save-excursion
11125 (syntax-ppss (point-at-bol)))
11126 offset (- (point) (save-excursion
11127 (back-to-indentation)
11128 (point))))
11129 ;; Don't touch multiline strings.
11130 (unless (nth 3 parse-status)
11131 (setq indent-col (js2-proper-indentation parse-status))
11132 (cond
11133 ;; It doesn't work well on first line of buffer.
11134 ((and (not (nth 4 parse-status))
11135 (not (js2-same-line (point-min)))
11136 (not (js2-1-line-comment-continuation-p)))
11137 (js2-bounce-indent indent-col parse-status backward))
11138 ;; just indent to the guesser's likely spot
11139 (t (indent-line-to indent-col)))
11140 (when (cl-plusp offset)
11141 (forward-char offset)))))
11142
11143 (defun js2-indent-bounce-backward ()
11144 "Indent the current line, bouncing between positions in reverse."
11145 (interactive)
11146 (js2-indent-bounce t))
11147
11148 (defun js2-indent-region (start end)
11149 "Indent the region, but don't use bounce indenting."
11150 (let ((js2-bounce-indent-p nil)
11151 (indent-region-function nil)
11152 (after-change-functions (remq 'js2-mode-edit
11153 after-change-functions)))
11154 (indent-region start end nil) ; nil for byte-compiler
11155 (js2-mode-edit start end (- end start))))
11156
11157 (defvar js2-minor-mode-map
11158 (let ((map (make-sparse-keymap)))
11159 (define-key map (kbd "C-c C-`") #'js2-next-error)
11160 (define-key map [mouse-1] #'js2-mode-show-node)
11161 map)
11162 "Keymap used when `js2-minor-mode' is active.")
11163
11164 ;;;###autoload
11165 (define-minor-mode js2-minor-mode
11166 "Minor mode for running js2 as a background linter.
11167 This allows you to use a different major mode for JavaScript editing,
11168 such as `js-mode', while retaining the asynchronous error/warning
11169 highlighting features of `js2-mode'."
11170 :group 'js2-mode
11171 :lighter " js-lint"
11172 (if (derived-mode-p 'js2-mode)
11173 (setq js2-minor-mode nil)
11174 (if js2-minor-mode
11175 (js2-minor-mode-enter)
11176 (js2-minor-mode-exit))))
11177
11178 (defun js2-minor-mode-enter ()
11179 "Initialization for `js2-minor-mode'."
11180 (set (make-local-variable 'max-lisp-eval-depth)
11181 (max max-lisp-eval-depth 3000))
11182 (setq next-error-function #'js2-next-error)
11183 (js2-set-default-externs)
11184 ;; Experiment: make reparse-delay longer for longer files.
11185 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11186 (setq js2-idle-timer-delay
11187 (* js2-idle-timer-delay
11188 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11189 (setq js2-mode-buffer-dirty-p t
11190 js2-mode-parsing nil)
11191 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11192 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11193 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11194 (when js2-include-jslint-globals
11195 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11196 (run-hooks 'js2-init-hook)
11197 (js2-reparse))
11198
11199 (defun js2-minor-mode-exit ()
11200 "Turn off `js2-minor-mode'."
11201 (setq next-error-function nil)
11202 (remove-hook 'after-change-functions #'js2-mode-edit t)
11203 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11204 (when js2-mode-node-overlay
11205 (delete-overlay js2-mode-node-overlay)
11206 (setq js2-mode-node-overlay nil))
11207 (js2-remove-overlays)
11208 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11209 (setq js2-mode-ast nil))
11210
11211 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11212 (make-variable-buffer-local 'js2-source-buffer)
11213
11214 (cl-defun js2-display-error-list ()
11215 "Display a navigable buffer listing parse errors/warnings."
11216 (interactive)
11217 (unless (js2-have-errors-p)
11218 (message "No errors")
11219 (cl-return-from js2-display-error-list))
11220 (cl-labels ((annotate-list
11221 (lst type)
11222 "Add diagnostic TYPE and line number to errs list"
11223 (mapcar (lambda (err)
11224 (list err type (line-number-at-pos (nth 1 err))))
11225 lst)))
11226 (let* ((srcbuf (current-buffer))
11227 (errbuf (get-buffer-create "*js-lint*"))
11228 (errors (annotate-list
11229 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11230 'js2-error)) ; must be a valid face name
11231 (warnings (annotate-list
11232 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11233 'js2-warning)) ; must be a valid face name
11234 (all-errs (sort (append errors warnings)
11235 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11236 (with-current-buffer errbuf
11237 (let ((inhibit-read-only t))
11238 (erase-buffer)
11239 (dolist (err all-errs)
11240 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11241 (insert-text-button
11242 (format "line %d: %s" line (js2-get-msg msg-key))
11243 'face type
11244 'follow-link "\C-m"
11245 'action 'js2-error-buffer-jump
11246 'js2-msg (js2-get-msg msg-key)
11247 'js2-pos beg)
11248 (insert "\n"))))
11249 (js2-error-buffer-mode)
11250 (setq js2-source-buffer srcbuf)
11251 (pop-to-buffer errbuf)
11252 (goto-char (point-min))
11253 (unless (eobp)
11254 (js2-error-buffer-view))))))
11255
11256 (defvar js2-error-buffer-mode-map
11257 (let ((map (make-sparse-keymap)))
11258 (define-key map "n" #'js2-error-buffer-next)
11259 (define-key map "p" #'js2-error-buffer-prev)
11260 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11261 (define-key map "o" #'js2-error-buffer-view)
11262 (define-key map "q" #'js2-error-buffer-quit)
11263 map)
11264 "Keymap used for js2 diagnostics buffers.")
11265
11266 (defun js2-error-buffer-mode ()
11267 "Major mode for js2 diagnostics buffers.
11268 Selecting an error will jump it to the corresponding source-buffer error.
11269 \\{js2-error-buffer-mode-map}"
11270 (interactive)
11271 (setq major-mode 'js2-error-buffer-mode
11272 mode-name "JS Lint Diagnostics")
11273 (use-local-map js2-error-buffer-mode-map)
11274 (setq truncate-lines t)
11275 (set-buffer-modified-p nil)
11276 (setq buffer-read-only t)
11277 (run-hooks 'js2-error-buffer-mode-hook))
11278
11279 (defun js2-error-buffer-next ()
11280 "Move to next error and view it."
11281 (interactive)
11282 (when (zerop (forward-line 1))
11283 (js2-error-buffer-view)))
11284
11285 (defun js2-error-buffer-prev ()
11286 "Move to previous error and view it."
11287 (interactive)
11288 (when (zerop (forward-line -1))
11289 (js2-error-buffer-view)))
11290
11291 (defun js2-error-buffer-quit ()
11292 "Kill the current buffer."
11293 (interactive)
11294 (kill-buffer))
11295
11296 (defun js2-error-buffer-jump (&rest ignored)
11297 "Jump cursor to current error in source buffer."
11298 (interactive)
11299 (when (js2-error-buffer-view)
11300 (pop-to-buffer js2-source-buffer)))
11301
11302 (defun js2-error-buffer-view ()
11303 "Scroll source buffer to show error at current line."
11304 (interactive)
11305 (cond
11306 ((not (eq major-mode 'js2-error-buffer-mode))
11307 (message "Not in a js2 errors buffer"))
11308 ((not (buffer-live-p js2-source-buffer))
11309 (message "Source buffer has been killed"))
11310 ((not (wholenump (get-text-property (point) 'js2-pos)))
11311 (message "There does not seem to be an error here"))
11312 (t
11313 (let ((pos (get-text-property (point) 'js2-pos))
11314 (msg (get-text-property (point) 'js2-msg)))
11315 (save-selected-window
11316 (pop-to-buffer js2-source-buffer)
11317 (goto-char pos)
11318 (message msg))))))
11319
11320 ;;;###autoload
11321 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11322 "Major mode for editing JavaScript code."
11323 (set (make-local-variable 'max-lisp-eval-depth)
11324 (max max-lisp-eval-depth 3000))
11325 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11326 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11327 (set (make-local-variable 'syntax-propertize-function) nil)
11328 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11329 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11330 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11331 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11332 ;; for characters inside regexp literals.
11333 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11334 ;; this is necessary to make `show-paren-function' work properly
11335 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11336 ;; needed for M-x rgrep, among other things
11337 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11338
11339 (setq font-lock-defaults '(nil t))
11340
11341 ;; Experiment: make reparse-delay longer for longer files.
11342 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11343 (setq js2-idle-timer-delay
11344 (* js2-idle-timer-delay
11345 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11346
11347 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11348 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11349 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11350 (setq next-error-function #'js2-next-error)
11351 (imenu-add-to-menubar (concat "IM-" mode-name))
11352 (add-to-invisibility-spec '(js2-outline . t))
11353 (set (make-local-variable 'line-move-ignore-invisible) t)
11354 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11355 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11356
11357 (setq js2-mode-functions-hidden nil
11358 js2-mode-comments-hidden nil
11359 js2-mode-buffer-dirty-p t
11360 js2-mode-parsing nil)
11361
11362 (js2-set-default-externs)
11363
11364 (when js2-include-jslint-globals
11365 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11366
11367 (run-hooks 'js2-init-hook)
11368
11369 (js2-reparse))
11370
11371 (defun js2-mode-exit ()
11372 "Exit `js2-mode' and clean up."
11373 (interactive)
11374 (when js2-mode-node-overlay
11375 (delete-overlay js2-mode-node-overlay)
11376 (setq js2-mode-node-overlay nil))
11377 (js2-remove-overlays)
11378 (setq js2-mode-ast nil)
11379 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11380 (remove-from-invisibility-spec '(js2-outline . t))
11381 (js2-mode-show-all)
11382 (with-silent-modifications
11383 (js2-clear-face (point-min) (point-max))))
11384
11385 (defun js2-mode-reset-timer ()
11386 "Cancel any existing parse timer and schedule a new one."
11387 (if js2-mode-parse-timer
11388 (cancel-timer js2-mode-parse-timer))
11389 (setq js2-mode-parsing nil)
11390 (let ((timer (timer-create)))
11391 (setq js2-mode-parse-timer timer)
11392 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11393 (timer-set-idle-time timer js2-idle-timer-delay)
11394 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11395 (timer-activate-when-idle timer nil)))
11396
11397 (defun js2-mode-idle-reparse (buffer)
11398 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11399 it to be reparsed when the buffer is selected."
11400 (cond ((eq buffer (current-buffer))
11401 (js2-reparse))
11402 ((buffer-live-p buffer)
11403 ;; reparse when the buffer is selected again
11404 (with-current-buffer buffer
11405 (add-hook 'window-configuration-change-hook
11406 #'js2-mode-idle-reparse-inner
11407 nil t)))))
11408
11409 (defun js2-mode-idle-reparse-inner ()
11410 (remove-hook 'window-configuration-change-hook
11411 #'js2-mode-idle-reparse-inner
11412 t)
11413 (js2-reparse))
11414
11415 (defun js2-mode-edit (_beg _end _len)
11416 "Schedule a new parse after buffer is edited.
11417 Buffer edit spans from BEG to END and is of length LEN."
11418 (setq js2-mode-buffer-dirty-p t)
11419 (js2-mode-hide-overlay)
11420 (js2-mode-reset-timer))
11421
11422 (defun js2-minor-mode-edit (_beg _end _len)
11423 "Callback for buffer edits in `js2-mode'.
11424 Schedules a new parse after buffer is edited.
11425 Buffer edit spans from BEG to END and is of length LEN."
11426 (setq js2-mode-buffer-dirty-p t)
11427 (js2-mode-hide-overlay)
11428 (js2-mode-reset-timer))
11429
11430 (defun js2-reparse (&optional force)
11431 "Re-parse current buffer after user finishes some data entry.
11432 If we get any user input while parsing, including cursor motion,
11433 we discard the parse and reschedule it. If FORCE is nil, then the
11434 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11435 (let (time
11436 interrupted-p
11437 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11438 (unless js2-mode-parsing
11439 (setq js2-mode-parsing t)
11440 (unwind-protect
11441 (when (or js2-mode-buffer-dirty-p force)
11442 (js2-remove-overlays)
11443 (setq js2-mode-buffer-dirty-p nil
11444 js2-mode-fontifications nil
11445 js2-mode-deferred-properties nil)
11446 (if js2-mode-verbose-parse-p
11447 (message "parsing..."))
11448 (setq time
11449 (js2-time
11450 (setq interrupted-p
11451 (catch 'interrupted
11452 (js2-parse)
11453 (with-silent-modifications
11454 ;; if parsing is interrupted, comments and regex
11455 ;; literals stay ignored by `parse-partial-sexp'
11456 (remove-text-properties (point-min) (point-max)
11457 '(syntax-table))
11458 (js2-mode-apply-deferred-properties)
11459 (js2-mode-remove-suppressed-warnings)
11460 (js2-mode-show-warnings)
11461 (js2-mode-show-errors)
11462 (if (>= js2-highlight-level 1)
11463 (js2-highlight-jsdoc js2-mode-ast)))
11464 nil))))
11465 (if interrupted-p
11466 (progn
11467 ;; unfinished parse => try again
11468 (setq js2-mode-buffer-dirty-p t)
11469 (js2-mode-reset-timer))
11470 (if js2-mode-verbose-parse-p
11471 (message "Parse time: %s" time))))
11472 (setq js2-mode-parsing nil)
11473 (unless interrupted-p
11474 (setq js2-mode-parse-timer nil))))))
11475
11476 (defun js2-mode-show-node (event)
11477 "Debugging aid: highlight selected AST node on mouse click."
11478 (interactive "e")
11479 (mouse-set-point event)
11480 (setq deactivate-mark t)
11481 (when js2-mode-show-overlay
11482 (let ((node (js2-node-at-point))
11483 beg end)
11484 (if (null node)
11485 (message "No node found at location %s" (point))
11486 (setq beg (js2-node-abs-pos node)
11487 end (+ beg (js2-node-len node)))
11488 (if js2-mode-node-overlay
11489 (move-overlay js2-mode-node-overlay beg end)
11490 (setq js2-mode-node-overlay (make-overlay beg end))
11491 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11492 (with-silent-modifications
11493 (if (fboundp 'cursor-sensor-mode)
11494 (put-text-property beg end 'cursor-sensor-functions
11495 '(js2-mode-hide-overlay))
11496 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11497 (message "%s, parent: %s"
11498 (js2-node-short-name node)
11499 (if (js2-node-parent node)
11500 (js2-node-short-name (js2-node-parent node))
11501 "nil"))))))
11502
11503 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11504 "Remove the debugging overlay when point moves.
11505 ARG1, ARG2 and ARG3 have different values depending on whether this function
11506 was found on `point-left' or in `cursor-sensor-functions'."
11507 (when js2-mode-node-overlay
11508 (let ((beg (overlay-start js2-mode-node-overlay))
11509 (end (overlay-end js2-mode-node-overlay))
11510 (p2 (if (windowp arg1)
11511 ;; Called from cursor-sensor-functions.
11512 (window-point arg1)
11513 ;; Called from point-left.
11514 arg2)))
11515 ;; Sometimes we're called spuriously.
11516 (unless (and p2
11517 (>= p2 beg)
11518 (<= p2 end))
11519 (with-silent-modifications
11520 (remove-text-properties beg end
11521 '(point-left nil cursor-sensor-functions)))
11522 (delete-overlay js2-mode-node-overlay)
11523 (setq js2-mode-node-overlay nil)))))
11524
11525 (defun js2-mode-reset ()
11526 "Debugging helper: reset everything."
11527 (interactive)
11528 (js2-mode-exit)
11529 (js2-mode))
11530
11531 (defun js2-mode-show-warn-or-err (e face)
11532 "Highlight a warning or error E with FACE.
11533 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11534 The last element is optional. When present, use instead of FACE."
11535 (let* ((key (cl-first e))
11536 (beg (cl-second e))
11537 (end (+ beg (cl-third e)))
11538 ;; Don't inadvertently go out of bounds.
11539 (beg (max (point-min) (min beg (point-max))))
11540 (end (max (point-min) (min end (point-max))))
11541 (ovl (make-overlay beg end)))
11542 ;; FIXME: Why a mix of overlays and text-properties?
11543 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11544 (overlay-put ovl 'js2-error t)
11545 (put-text-property beg end 'help-echo (js2-get-msg key))
11546 (if (fboundp 'cursor-sensor-mode)
11547 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11548 (put-text-property beg end 'point-entered #'js2-echo-error))))
11549
11550 (defun js2-remove-overlays ()
11551 "Remove overlays from buffer that have a `js2-error' property."
11552 (let ((beg (point-min))
11553 (end (point-max)))
11554 (save-excursion
11555 (dolist (o (overlays-in beg end))
11556 (when (overlay-get o 'js2-error)
11557 (delete-overlay o))))))
11558
11559 (defun js2-mode-apply-deferred-properties ()
11560 "Apply fontifications and other text properties recorded during parsing."
11561 (when (cl-plusp js2-highlight-level)
11562 ;; We defer clearing faces as long as possible to eliminate flashing.
11563 (js2-clear-face (point-min) (point-max))
11564 ;; Have to reverse the recorded fontifications list so that errors
11565 ;; and warnings overwrite the normal fontifications.
11566 (dolist (f (nreverse js2-mode-fontifications))
11567 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11568 (setq js2-mode-fontifications nil))
11569 (dolist (p js2-mode-deferred-properties)
11570 (apply #'put-text-property p))
11571 (setq js2-mode-deferred-properties nil))
11572
11573 (defun js2-mode-show-errors ()
11574 "Highlight syntax errors."
11575 (when js2-mode-show-parse-errors
11576 (dolist (e (js2-ast-root-errors js2-mode-ast))
11577 (js2-mode-show-warn-or-err e 'js2-error))))
11578
11579 (defun js2-mode-remove-suppressed-warnings ()
11580 "Take suppressed warnings out of the AST warnings list.
11581 This ensures that the counts and `next-error' are correct."
11582 (setf (js2-ast-root-warnings js2-mode-ast)
11583 (js2-delete-if
11584 (lambda (e)
11585 (let ((key (caar e)))
11586 (or
11587 (and (not js2-strict-trailing-comma-warning)
11588 (string-match "trailing\\.comma" key))
11589 (and (not js2-strict-cond-assign-warning)
11590 (string= key "msg.equal.as.assign"))
11591 (and js2-missing-semi-one-line-override
11592 (string= key "msg.missing.semi")
11593 (let* ((beg (cl-second e))
11594 (node (js2-node-at-point beg))
11595 (fn (js2-mode-find-parent-fn node))
11596 (body (and fn (js2-function-node-body fn)))
11597 (lc (and body (js2-node-abs-pos body)))
11598 (rc (and lc (+ lc (js2-node-len body)))))
11599 (and fn
11600 (or (null body)
11601 (save-excursion
11602 (goto-char beg)
11603 (and (js2-same-line lc)
11604 (js2-same-line rc))))))))))
11605 (js2-ast-root-warnings js2-mode-ast))))
11606
11607 (defun js2-mode-show-warnings ()
11608 "Highlight strict-mode warnings."
11609 (when js2-mode-show-strict-warnings
11610 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11611 (js2-mode-show-warn-or-err e 'js2-warning))))
11612
11613 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11614 "Called by point-motion hooks.
11615 ARG1, ARG2 and ARG3 have different values depending on whether this function
11616 was found on `point-entered' or in `cursor-sensor-functions'."
11617 (let* ((new-point (if (windowp arg1)
11618 ;; Called from cursor-sensor-functions.
11619 (window-point arg1)
11620 ;; Called from point-left.
11621 arg2))
11622 (msg (get-text-property new-point 'help-echo)))
11623 (when (and (stringp msg)
11624 (not (active-minibuffer-window))
11625 (not (current-message)))
11626 (message msg))))
11627
11628 (defun js2-line-break (&optional _soft)
11629 "Break line at point and indent, continuing comment if within one.
11630 If inside a string, and `js2-concat-multiline-strings' is not
11631 nil, turn it into concatenation."
11632 (interactive)
11633 (let ((parse-status (syntax-ppss)))
11634 (cond
11635 ;; Check if we're inside a string.
11636 ((nth 3 parse-status)
11637 (if js2-concat-multiline-strings
11638 (js2-mode-split-string parse-status)
11639 (insert "\n")))
11640 ;; Check if inside a block comment.
11641 ((nth 4 parse-status)
11642 (js2-mode-extend-comment (nth 8 parse-status)))
11643 (t
11644 (newline-and-indent)))))
11645
11646 (defun js2-mode-split-string (parse-status)
11647 "Turn a newline in mid-string into a string concatenation.
11648 PARSE-STATUS is as documented in `parse-partial-sexp'."
11649 (let* ((quote-char (nth 3 parse-status))
11650 (at-eol (eq js2-concat-multiline-strings 'eol)))
11651 (insert quote-char)
11652 (insert (if at-eol " +\n" "\n"))
11653 (unless at-eol
11654 (insert "+ "))
11655 (js2-indent-line)
11656 (insert quote-char)
11657 (when (eolp)
11658 (insert quote-char)
11659 (backward-char 1))))
11660
11661 (defun js2-mode-extend-comment (start-pos)
11662 "Indent the line and, when inside a comment block, add comment prefix."
11663 (let (star single col first-line needs-close)
11664 (save-excursion
11665 (back-to-indentation)
11666 (when (< (point) start-pos)
11667 (goto-char start-pos))
11668 (cond
11669 ((looking-at "\\*[^/]")
11670 (setq star t
11671 col (current-column)))
11672 ((looking-at "/\\*")
11673 (setq star t
11674 first-line t
11675 col (1+ (current-column))))
11676 ((looking-at "//")
11677 (setq single t
11678 col (current-column)))))
11679 ;; Heuristic for whether we need to close the comment:
11680 ;; if we've got a parse error here, assume it's an unterminated
11681 ;; comment.
11682 (setq needs-close
11683 (or
11684 (get-char-property (1- (point)) 'js2-error)
11685 ;; The heuristic above doesn't work well when we're
11686 ;; creating a comment and there's another one downstream,
11687 ;; as our parser thinks this one ends at the end of the
11688 ;; next one. (You can have a /* inside a js block comment.)
11689 ;; So just close it if the next non-ws char isn't a *.
11690 (and first-line
11691 (eolp)
11692 (save-excursion
11693 (skip-chars-forward " \t\r\n")
11694 (not (eq (char-after) ?*))))))
11695 (delete-horizontal-space)
11696 (insert "\n")
11697 (cond
11698 (star
11699 (indent-to col)
11700 (insert "* ")
11701 (if (and first-line needs-close)
11702 (save-excursion
11703 (insert "\n")
11704 (indent-to col)
11705 (insert "*/"))))
11706 ((and single
11707 (save-excursion
11708 (and (zerop (forward-line 1))
11709 (looking-at "\\s-*//"))))
11710 (indent-to col)
11711 (insert "// ")))
11712 ;; Don't need to extend the comment after all.
11713 (js2-indent-line)))
11714
11715 (defun js2-beginning-of-line ()
11716 "Toggle point between bol and first non-whitespace char in line.
11717 Also moves past comment delimiters when inside comments."
11718 (interactive)
11719 (let (node)
11720 (cond
11721 ((bolp)
11722 (back-to-indentation))
11723 ((looking-at "//")
11724 (skip-chars-forward "/ \t"))
11725 ((and (eq (char-after) ?*)
11726 (setq node (js2-comment-at-point))
11727 (memq (js2-comment-node-format node) '(jsdoc block))
11728 (save-excursion
11729 (skip-chars-backward " \t")
11730 (bolp)))
11731 (skip-chars-forward "\* \t"))
11732 (t
11733 (goto-char (point-at-bol))))))
11734
11735 (defun js2-end-of-line ()
11736 "Toggle point between eol and last non-whitespace char in line."
11737 (interactive)
11738 (if (eolp)
11739 (skip-chars-backward " \t")
11740 (goto-char (point-at-eol))))
11741
11742 (defun js2-mode-wait-for-parse (callback)
11743 "Invoke CALLBACK when parsing is finished.
11744 If parsing is already finished, calls CALLBACK immediately."
11745 (if (not js2-mode-buffer-dirty-p)
11746 (funcall callback)
11747 (push callback js2-mode-pending-parse-callbacks)
11748 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11749
11750 (defun js2-mode-parse-finished ()
11751 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11752 ;; We can't let errors propagate up, since it prevents the
11753 ;; `js2-parse' method from completing normally and returning
11754 ;; the ast, which makes things mysteriously not work right.
11755 (unwind-protect
11756 (dolist (cb js2-mode-pending-parse-callbacks)
11757 (condition-case err
11758 (funcall cb)
11759 (error (message "%s" err))))
11760 (setq js2-mode-pending-parse-callbacks nil)))
11761
11762 (defun js2-mode-flag-region (from to flag)
11763 "Hide or show text from FROM to TO, according to FLAG.
11764 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11765 Returns the created overlay if FLAG is non-nil."
11766 (remove-overlays from to 'invisible 'js2-outline)
11767 (when flag
11768 (let ((o (make-overlay from to)))
11769 (overlay-put o 'invisible 'js2-outline)
11770 (overlay-put o 'isearch-open-invisible
11771 'js2-isearch-open-invisible)
11772 o)))
11773
11774 ;; Function to be set as an outline-isearch-open-invisible' property
11775 ;; to the overlay that makes the outline invisible (see
11776 ;; `js2-mode-flag-region').
11777 (defun js2-isearch-open-invisible (_overlay)
11778 ;; We rely on the fact that isearch places point on the matched text.
11779 (js2-mode-show-element))
11780
11781 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11782 "Return cons cell of bounds of folding overlay at POS.
11783 Returns nil if not found."
11784 (let ((overlays (overlays-at (or pos (point))))
11785 o)
11786 (while (and overlays
11787 (not o))
11788 (if (overlay-get (car overlays) 'invisible)
11789 (setq o (car overlays))
11790 (setq overlays (cdr overlays))))
11791 (if o
11792 (cons (overlay-start o) (overlay-end o)))))
11793
11794 (defun js2-mode-function-at-point (&optional pos)
11795 "Return the innermost function node enclosing current point.
11796 Returns nil if point is not in a function."
11797 (let ((node (js2-node-at-point pos)))
11798 (while (and node (not (js2-function-node-p node)))
11799 (setq node (js2-node-parent node)))
11800 (if (js2-function-node-p node)
11801 node)))
11802
11803 (defun js2-mode-toggle-element ()
11804 "Hide or show the foldable element at the point."
11805 (interactive)
11806 (let (comment fn pos)
11807 (save-excursion
11808 (cond
11809 ;; /* ... */ comment?
11810 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11811 (if (js2-mode-invisible-overlay-bounds
11812 (setq pos (+ 3 (js2-node-abs-pos comment))))
11813 (progn
11814 (goto-char pos)
11815 (js2-mode-show-element))
11816 (js2-mode-hide-element)))
11817 ;; //-comment?
11818 ((save-excursion
11819 (back-to-indentation)
11820 (looking-at js2-mode-//-comment-re))
11821 (js2-mode-toggle-//-comment))
11822 ;; function?
11823 ((setq fn (js2-mode-function-at-point))
11824 (setq pos (and (js2-function-node-body fn)
11825 (js2-node-abs-pos (js2-function-node-body fn))))
11826 (goto-char (1+ pos))
11827 (if (js2-mode-invisible-overlay-bounds)
11828 (js2-mode-show-element)
11829 (js2-mode-hide-element)))
11830 (t
11831 (message "Nothing at point to hide or show"))))))
11832
11833 (defun js2-mode-hide-element ()
11834 "Fold/hide contents of a block, showing ellipses.
11835 Show the hidden text with \\[js2-mode-show-element]."
11836 (interactive)
11837 (if js2-mode-buffer-dirty-p
11838 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11839 (let (node body beg end)
11840 (cond
11841 ((js2-mode-invisible-overlay-bounds)
11842 (message "already hidden"))
11843 (t
11844 (setq node (js2-node-at-point))
11845 (cond
11846 ((js2-block-comment-p node)
11847 (js2-mode-hide-comment node))
11848 (t
11849 (while (and node (not (js2-function-node-p node)))
11850 (setq node (js2-node-parent node)))
11851 (if (and node
11852 (setq body (js2-function-node-body node)))
11853 (progn
11854 (setq beg (js2-node-abs-pos body)
11855 end (+ beg (js2-node-len body)))
11856 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11857 (message "No collapsable element found at point"))))))))
11858
11859 (defun js2-mode-show-element ()
11860 "Show the hidden element at current point."
11861 (interactive)
11862 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11863 (if bounds
11864 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11865 (message "Nothing to un-hide"))))
11866
11867 (defun js2-mode-show-all ()
11868 "Show all of the text in the buffer."
11869 (interactive)
11870 (js2-mode-flag-region (point-min) (point-max) nil))
11871
11872 (defun js2-mode-toggle-hide-functions ()
11873 (interactive)
11874 (if js2-mode-functions-hidden
11875 (js2-mode-show-functions)
11876 (js2-mode-hide-functions)))
11877
11878 (defun js2-mode-hide-functions ()
11879 "Hides all non-nested function bodies in the buffer.
11880 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11881 to open an individual entry."
11882 (interactive)
11883 (if js2-mode-buffer-dirty-p
11884 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11885 (if (null js2-mode-ast)
11886 (message "Oops - parsing failed")
11887 (setq js2-mode-functions-hidden t)
11888 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11889
11890 (defun js2-mode-function-hider (n endp)
11891 (when (not endp)
11892 (let ((tt (js2-node-type n))
11893 body beg end)
11894 (cond
11895 ((and (= tt js2-FUNCTION)
11896 (setq body (js2-function-node-body n)))
11897 (setq beg (js2-node-abs-pos body)
11898 end (+ beg (js2-node-len body)))
11899 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11900 nil) ; don't process children of function
11901 (t
11902 t))))) ; keep processing other AST nodes
11903
11904 (defun js2-mode-show-functions ()
11905 "Un-hide any folded function bodies in the buffer."
11906 (interactive)
11907 (setq js2-mode-functions-hidden nil)
11908 (save-excursion
11909 (goto-char (point-min))
11910 (while (/= (goto-char (next-overlay-change (point)))
11911 (point-max))
11912 (dolist (o (overlays-at (point)))
11913 (when (and (overlay-get o 'invisible)
11914 (not (overlay-get o 'comment)))
11915 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11916
11917 (defun js2-mode-hide-comment (n)
11918 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11919 3 ; /**
11920 2)) ; /*
11921 (beg (+ (js2-node-abs-pos n) head))
11922 (end (- (+ beg (js2-node-len n)) head 2))
11923 (o (js2-mode-flag-region beg end 'hide)))
11924 (overlay-put o 'comment t)))
11925
11926 (defun js2-mode-toggle-hide-comments ()
11927 "Folds all block comments in the buffer.
11928 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11929 to open an individual entry."
11930 (interactive)
11931 (if js2-mode-comments-hidden
11932 (js2-mode-show-comments)
11933 (js2-mode-hide-comments)))
11934
11935 (defun js2-mode-hide-comments ()
11936 (interactive)
11937 (if js2-mode-buffer-dirty-p
11938 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11939 (if (null js2-mode-ast)
11940 (message "Oops - parsing failed")
11941 (setq js2-mode-comments-hidden t)
11942 (dolist (n (js2-ast-root-comments js2-mode-ast))
11943 (when (js2-block-comment-p n)
11944 (js2-mode-hide-comment n)))
11945 (js2-mode-hide-//-comments)))
11946
11947 (defun js2-mode-extend-//-comment (direction)
11948 "Find start or end of a block of similar //-comment lines.
11949 DIRECTION is -1 to look back, 1 to look forward.
11950 INDENT is the indentation level to match.
11951 Returns the end-of-line position of the furthest adjacent
11952 //-comment line with the same indentation as the current line.
11953 If there is no such matching line, returns current end of line."
11954 (let ((pos (point-at-eol))
11955 (indent (current-indentation)))
11956 (save-excursion
11957 (while (and (zerop (forward-line direction))
11958 (looking-at js2-mode-//-comment-re)
11959 (eq indent (length (match-string 1))))
11960 (setq pos (point-at-eol)))
11961 pos)))
11962
11963 (defun js2-mode-hide-//-comments ()
11964 "Fold adjacent 1-line comments, showing only snippet of first one."
11965 (let (beg end)
11966 (save-excursion
11967 (goto-char (point-min))
11968 (while (re-search-forward js2-mode-//-comment-re nil t)
11969 (setq beg (point)
11970 end (js2-mode-extend-//-comment 1))
11971 (unless (eq beg end)
11972 (overlay-put (js2-mode-flag-region beg end 'hide)
11973 'comment t))
11974 (goto-char end)
11975 (forward-char 1)))))
11976
11977 (defun js2-mode-toggle-//-comment ()
11978 "Fold or un-fold any multi-line //-comment at point.
11979 Caller should have determined that this line starts with a //-comment."
11980 (let* ((beg (point-at-eol))
11981 (end beg))
11982 (save-excursion
11983 (goto-char end)
11984 (if (js2-mode-invisible-overlay-bounds)
11985 (js2-mode-show-element)
11986 ;; else hide the comment
11987 (setq beg (js2-mode-extend-//-comment -1)
11988 end (js2-mode-extend-//-comment 1))
11989 (unless (eq beg end)
11990 (overlay-put (js2-mode-flag-region beg end 'hide)
11991 'comment t))))))
11992
11993 (defun js2-mode-show-comments ()
11994 "Un-hide any hidden comments, leaving other hidden elements alone."
11995 (interactive)
11996 (setq js2-mode-comments-hidden nil)
11997 (save-excursion
11998 (goto-char (point-min))
11999 (while (/= (goto-char (next-overlay-change (point)))
12000 (point-max))
12001 (dolist (o (overlays-at (point)))
12002 (when (overlay-get o 'comment)
12003 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12004
12005 (defun js2-mode-display-warnings-and-errors ()
12006 "Turn on display of warnings and errors."
12007 (interactive)
12008 (setq js2-mode-show-parse-errors t
12009 js2-mode-show-strict-warnings t)
12010 (js2-reparse 'force))
12011
12012 (defun js2-mode-hide-warnings-and-errors ()
12013 "Turn off display of warnings and errors."
12014 (interactive)
12015 (setq js2-mode-show-parse-errors nil
12016 js2-mode-show-strict-warnings nil)
12017 (js2-reparse 'force))
12018
12019 (defun js2-mode-toggle-warnings-and-errors ()
12020 "Toggle the display of warnings and errors.
12021 Some users don't like having warnings/errors reported while they type."
12022 (interactive)
12023 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12024 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12025 (if (called-interactively-p 'any)
12026 (message "warnings and errors %s"
12027 (if js2-mode-show-parse-errors
12028 "enabled"
12029 "disabled")))
12030 (js2-reparse 'force))
12031
12032 (defun js2-mode-customize ()
12033 (interactive)
12034 (customize-group 'js2-mode))
12035
12036 (defun js2-mode-forward-sexp (&optional arg)
12037 "Move forward across one statement or balanced expression.
12038 With ARG, do it that many times. Negative arg -N means
12039 move backward across N balanced expressions."
12040 (interactive "p")
12041 (setq arg (or arg 1))
12042 (save-restriction
12043 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12044 (js2-reparse)
12045 (let (forward-sexp-function
12046 node (start (point)) pos lp rp child)
12047 (cond
12048 ;; backward-sexp
12049 ;; could probably make this better for some cases:
12050 ;; - if in statement block (e.g. function body), go to parent
12051 ;; - infix exprs like (foo in bar) - maybe go to beginning
12052 ;; of infix expr if in the right-side expression?
12053 ((and arg (cl-minusp arg))
12054 (dotimes (_ (- arg))
12055 (js2-backward-sws)
12056 (forward-char -1) ; Enter the node we backed up to.
12057 (when (setq node (js2-node-at-point (point) t))
12058 (setq pos (js2-node-abs-pos node))
12059 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12060 (setq lp (car parens)
12061 rp (cdr parens)))
12062 (when (and lp (> start lp))
12063 (if (and rp (<= start rp))
12064 ;; Between parens, check if there's a child node we can jump.
12065 (when (setq child (js2-node-closest-child node (point) lp t))
12066 (setq pos (js2-node-abs-pos child)))
12067 ;; Before both parens.
12068 (setq pos lp)))
12069 (let ((state (parse-partial-sexp start pos)))
12070 (goto-char (if (not (zerop (car state)))
12071 ;; Stumble at the unbalanced paren if < 0, or
12072 ;; jump a bit further if > 0.
12073 (scan-sexps start -1)
12074 pos))))
12075 (unless pos (goto-char (point-min)))))
12076 (t
12077 ;; forward-sexp
12078 (dotimes (_ arg)
12079 (js2-forward-sws)
12080 (when (setq node (js2-node-at-point (point) t))
12081 (setq pos (js2-node-abs-pos node))
12082 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12083 (setq lp (car parens)
12084 rp (cdr parens)))
12085 (or
12086 (when (and rp (<= start rp))
12087 (if (> start lp)
12088 (when (setq child (js2-node-closest-child node (point) rp))
12089 (setq pos (js2-node-abs-end child)))
12090 (setq pos (1+ rp))))
12091 ;; No parens or child nodes, looks for the end of the current node.
12092 (cl-incf pos (js2-node-len
12093 (if (js2-expr-stmt-node-p (js2-node-parent node))
12094 ;; Stop after the semicolon.
12095 (js2-node-parent node)
12096 node))))
12097 (let ((state (save-excursion (parse-partial-sexp start pos))))
12098 (goto-char (if (not (zerop (car state)))
12099 (scan-sexps start 1)
12100 pos))))
12101 (unless pos (goto-char (point-max)))))))))
12102
12103 (defun js2-mode-forward-sexp-parens (node abs-pos)
12104 "Return a cons cell with positions of main parens in NODE."
12105 (cond
12106 ((or (js2-array-node-p node)
12107 (js2-object-node-p node)
12108 (js2-comp-node-p node)
12109 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12110 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12111 ((js2-paren-expr-node-p node)
12112 (let ((lp (js2-node-lp node))
12113 (rp (js2-node-rp node)))
12114 (cons (when lp (+ abs-pos lp))
12115 (when rp (+ abs-pos rp)))))))
12116
12117 (defun js2-node-closest-child (parent point limit &optional before)
12118 (let* ((parent-pos (js2-node-abs-pos parent))
12119 (rpoint (- point parent-pos))
12120 (rlimit (- limit parent-pos))
12121 (min (min rpoint rlimit))
12122 (max (max rpoint rlimit))
12123 found)
12124 (catch 'done
12125 (js2-visit-ast
12126 parent
12127 (lambda (node _end-p)
12128 (if (eq node parent)
12129 t
12130 (let ((pos (js2-node-pos node)) ;; Both relative values.
12131 (end (+ (js2-node-pos node) (js2-node-len node))))
12132 (when (and (>= pos min) (<= end max)
12133 (if before (< pos rpoint) (> end rpoint)))
12134 (setq found node))
12135 (when (> end rpoint)
12136 (throw 'done nil)))
12137 nil))))
12138 found))
12139
12140 (defun js2-errors ()
12141 "Return a list of errors found."
12142 (and js2-mode-ast
12143 (js2-ast-root-errors js2-mode-ast)))
12144
12145 (defun js2-warnings ()
12146 "Return a list of warnings found."
12147 (and js2-mode-ast
12148 (js2-ast-root-warnings js2-mode-ast)))
12149
12150 (defun js2-have-errors-p ()
12151 "Return non-nil if any parse errors or warnings were found."
12152 (or (js2-errors) (js2-warnings)))
12153
12154 (defun js2-errors-and-warnings ()
12155 "Return a copy of the concatenated errors and warnings lists.
12156 They are appended: first the errors, then the warnings.
12157 Entries are of the form (MSG BEG END)."
12158 (when js2-mode-ast
12159 (append (js2-ast-root-errors js2-mode-ast)
12160 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12161
12162 (defun js2-next-error (&optional arg reset)
12163 "Move to next parse error.
12164 Typically invoked via \\[next-error].
12165 ARG is the number of errors, forward or backward, to move.
12166 RESET means start over from the beginning."
12167 (interactive "p")
12168 (if (not (or (js2-errors) (js2-warnings)))
12169 (message "No errors")
12170 (when reset
12171 (goto-char (point-min)))
12172 (let* ((errs (js2-errors-and-warnings))
12173 (continue t)
12174 (start (point))
12175 (count (or arg 1))
12176 (backward (cl-minusp count))
12177 (sorter (if backward '> '<))
12178 (stopper (if backward '< '>))
12179 (count (abs count))
12180 all-errs err)
12181 ;; Sort by start position.
12182 (setq errs (sort errs (lambda (e1 e2)
12183 (funcall sorter (cl-second e1) (cl-second e2))))
12184 all-errs errs)
12185 ;; Find nth error with pos > start.
12186 (while (and errs continue)
12187 (when (funcall stopper (cl-cadar errs) start)
12188 (setq err (car errs))
12189 (if (zerop (cl-decf count))
12190 (setq continue nil)))
12191 (setq errs (cdr errs)))
12192 ;; Clear for `js2-echo-error'.
12193 (message nil)
12194 (if err
12195 (goto-char (cl-second err))
12196 ;; Wrap around to first error.
12197 (goto-char (cl-second (car all-errs)))
12198 ;; If we were already on it, echo msg again.
12199 (if (= (point) start)
12200 (js2-echo-error (point) (point)))))))
12201
12202 (defun js2-down-mouse-3 ()
12203 "Make right-click move the point to the click location.
12204 This makes right-click context menu operations a bit more intuitive.
12205 The point will not move if the region is active, however, to avoid
12206 destroying the region selection."
12207 (interactive)
12208 (when (and js2-move-point-on-right-click
12209 (not mark-active))
12210 (let ((e last-input-event))
12211 (ignore-errors
12212 (goto-char (cl-cadadr e))))))
12213
12214 (defun js2-mode-create-imenu-index ()
12215 "Return an alist for `imenu--index-alist'."
12216 ;; This is built up in `js2-parse-record-imenu' during parsing.
12217 (when js2-mode-ast
12218 ;; if we have an ast but no recorder, they're requesting a rescan
12219 (unless js2-imenu-recorder
12220 (js2-reparse 'force))
12221 (prog1
12222 (js2-build-imenu-index)
12223 (setq js2-imenu-recorder nil
12224 js2-imenu-function-map nil))))
12225
12226 (defun js2-mode-find-tag ()
12227 "Replacement for `find-tag-default'.
12228 `find-tag-default' returns a ridiculous answer inside comments."
12229 (let (beg end)
12230 (save-excursion
12231 (if (looking-at "\\_>")
12232 (setq beg (progn (forward-symbol -1) (point))
12233 end (progn (forward-symbol 1) (point)))
12234 (setq beg (progn (forward-symbol 1) (point))
12235 end (progn (forward-symbol -1) (point))))
12236 (replace-regexp-in-string
12237 "[\"']" ""
12238 (buffer-substring-no-properties beg end)))))
12239
12240 (defun js2-mode-forward-sibling ()
12241 "Move to the end of the sibling following point in parent.
12242 Returns non-nil if successful, or nil if there was no following sibling."
12243 (let* ((node (js2-node-at-point))
12244 (parent (js2-mode-find-enclosing-fn node))
12245 sib)
12246 (when (setq sib (js2-node-find-child-after (point) parent))
12247 (goto-char (+ (js2-node-abs-pos sib)
12248 (js2-node-len sib))))))
12249
12250 (defun js2-mode-backward-sibling ()
12251 "Move to the beginning of the sibling node preceding point in parent.
12252 Parent is defined as the enclosing script or function."
12253 (let* ((node (js2-node-at-point))
12254 (parent (js2-mode-find-enclosing-fn node))
12255 sib)
12256 (when (setq sib (js2-node-find-child-before (point) parent))
12257 (goto-char (js2-node-abs-pos sib)))))
12258
12259 (defun js2-beginning-of-defun (&optional arg)
12260 "Go to line on which current function starts, and return t on success.
12261 If we're not in a function or already at the beginning of one, go
12262 to beginning of previous script-level element.
12263 With ARG N, do that N times. If N is negative, move forward."
12264 (setq arg (or arg 1))
12265 (if (cl-plusp arg)
12266 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12267 (when (cond
12268 ((js2-function-node-p parent)
12269 (goto-char (js2-node-abs-pos parent)))
12270 (t
12271 (js2-mode-backward-sibling)))
12272 (if (> arg 1)
12273 (js2-beginning-of-defun (1- arg))
12274 t)))
12275 (when (js2-end-of-defun)
12276 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12277
12278 (defun js2-end-of-defun ()
12279 "Go to the char after the last position of the current function
12280 or script-level element."
12281 (let* ((node (js2-node-at-point))
12282 (parent (or (and (js2-function-node-p node) node)
12283 (js2-node-parent-script-or-fn node)))
12284 script)
12285 (unless (js2-function-node-p parent)
12286 ;; Use current script-level node, or, if none, the next one.
12287 (setq script (or parent node)
12288 parent (js2-node-find-child-before (point) script))
12289 (when (or (null parent)
12290 (>= (point) (+ (js2-node-abs-pos parent)
12291 (js2-node-len parent))))
12292 (setq parent (js2-node-find-child-after (point) script))))
12293 (when parent
12294 (goto-char (+ (js2-node-abs-pos parent)
12295 (js2-node-len parent))))))
12296
12297 (defun js2-mark-defun (&optional allow-extend)
12298 "Put mark at end of this function, point at beginning.
12299 The function marked is the one that contains point.
12300
12301 Interactively, if this command is repeated,
12302 or (in Transient Mark mode) if the mark is active,
12303 it marks the next defun after the ones already marked."
12304 (interactive "p")
12305 (let (extended)
12306 (when (and allow-extend
12307 (or (and (eq last-command this-command) (mark t))
12308 (and transient-mark-mode mark-active)))
12309 (let ((sib (save-excursion
12310 (goto-char (mark))
12311 (if (js2-mode-forward-sibling)
12312 (point)))))
12313 (if sib
12314 (progn
12315 (set-mark sib)
12316 (setq extended t))
12317 ;; no more siblings - try extending to enclosing node
12318 (goto-char (mark t)))))
12319 (when (not extended)
12320 (let ((node (js2-node-at-point (point) t)) ; skip comments
12321 ast fn stmt parent beg end)
12322 (when (js2-ast-root-p node)
12323 (setq ast node
12324 node (or (js2-node-find-child-after (point) node)
12325 (js2-node-find-child-before (point) node))))
12326 ;; only mark whole buffer if we can't find any children
12327 (if (null node)
12328 (setq node ast))
12329 (if (js2-function-node-p node)
12330 (setq parent node)
12331 (setq fn (js2-mode-find-enclosing-fn node)
12332 stmt (if (or (null fn)
12333 (js2-ast-root-p fn))
12334 (js2-mode-find-first-stmt node))
12335 parent (or stmt fn)))
12336 (setq beg (js2-node-abs-pos parent)
12337 end (+ beg (js2-node-len parent)))
12338 (push-mark beg)
12339 (goto-char end)
12340 (exchange-point-and-mark)))))
12341
12342 (defun js2-narrow-to-defun ()
12343 "Narrow to the function enclosing point."
12344 (interactive)
12345 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12346 (fn (if (js2-script-node-p node)
12347 node
12348 (js2-mode-find-enclosing-fn node)))
12349 (beg (js2-node-abs-pos fn)))
12350 (unless (js2-ast-root-p fn)
12351 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12352
12353 (defun js2-jump-to-definition (&optional arg)
12354 "Jump to the definition of an object's property, variable or function."
12355 (interactive "P")
12356 (ring-insert find-tag-marker-ring (point-marker))
12357 (let* ((node (js2-node-at-point))
12358 (parent (js2-node-parent node))
12359 (names (if (js2-prop-get-node-p parent)
12360 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12361 (cl-loop for n in temp
12362 with result = '()
12363 do (push n result)
12364 until (equal node n)
12365 finally return result)))))
12366 node-init)
12367 (unless (and (js2-name-node-p node)
12368 (not (js2-var-init-node-p parent))
12369 (not (js2-function-node-p parent)))
12370 (error "Node is not a supported jump node"))
12371 (push (or (and names (pop names))
12372 (unless (and (js2-object-prop-node-p parent)
12373 (eq node (js2-object-prop-node-left parent)))
12374 node)) names)
12375 (setq node-init (js2-search-scope node names))
12376
12377 ;; todo: display list of results in buffer
12378 ;; todo: group found references by buffer
12379 (unless node-init
12380 (switch-to-buffer
12381 (catch 'found
12382 (unless arg
12383 (mapc (lambda (b)
12384 (with-current-buffer b
12385 (when (derived-mode-p 'js2-mode)
12386 (setq node-init (js2-search-scope js2-mode-ast names))
12387 (if node-init
12388 (throw 'found b)))))
12389 (buffer-list)))
12390 nil)))
12391 (setq node-init (if (listp node-init) (car node-init) node-init))
12392 (unless node-init
12393 (pop-tag-mark)
12394 (error "No jump location found"))
12395 (goto-char (js2-node-abs-pos node-init))))
12396
12397 (defun js2-search-object (node name-node)
12398 "Check if object NODE contains element with NAME-NODE."
12399 (cl-assert (js2-object-node-p node))
12400 ;; Only support name-node and nodes for the time being
12401 (cl-loop for elem in (js2-object-node-elems node)
12402 for left = (js2-object-prop-node-left elem)
12403 if (or (and (js2-name-node-p left)
12404 (equal (js2-name-node-name name-node)
12405 (js2-name-node-name left)))
12406 (and (js2-string-node-p left)
12407 (string= (js2-name-node-name name-node)
12408 (js2-string-node-value left))))
12409 return elem))
12410
12411 (defun js2-search-object-for-prop (object prop-names)
12412 "Return node in OBJECT that matches PROP-NAMES or nil.
12413 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12414 i.e. ('name' 'value') = {name : { value: 3}}"
12415 (let (node
12416 (temp-object object)
12417 (temp t) ;temporay node
12418 (names prop-names))
12419 (while (and temp names (js2-object-node-p temp-object))
12420 (setq temp (js2-search-object temp-object (pop names)))
12421 (and (setq node temp)
12422 (setq temp-object (js2-object-prop-node-right temp))))
12423 (unless names node)))
12424
12425 (defun js2-search-scope (node names)
12426 "Searches NODE scope for jump location matching NAMES.
12427 NAMES is a list of property values to search for. For functions
12428 and variables NAMES will contain one element."
12429 (let (node-init
12430 (val (js2-name-node-name (car names))))
12431 (setq node-init (js2-get-symbol-declaration node val))
12432
12433 (when (> (length names) 1)
12434
12435 ;; Check var declarations
12436 (when (and node-init (string= val (js2-name-node-name node-init)))
12437 (let ((parent (js2-node-parent node-init))
12438 (temp-names names))
12439 (pop temp-names) ;; First element is var name
12440 (setq node-init (when (js2-var-init-node-p parent)
12441 (js2-search-object-for-prop
12442 (js2-var-init-node-initializer parent)
12443 temp-names)))))
12444
12445 ;; Check all assign nodes
12446 (js2-visit-ast
12447 js2-mode-ast
12448 (lambda (node endp)
12449 (unless endp
12450 (if (js2-assign-node-p node)
12451 (let ((left (js2-assign-node-left node))
12452 (right (js2-assign-node-right node))
12453 (temp-names names))
12454 (when (js2-prop-get-node-p left)
12455 (let* ((prop-list (js2-compute-nested-prop-get left))
12456 (found (cl-loop for prop in prop-list
12457 until (not (string= (js2-name-node-name
12458 (pop temp-names))
12459 (js2-name-node-name prop)))
12460 if (not temp-names) return prop))
12461 (found-node (or found
12462 (when (js2-object-node-p right)
12463 (js2-search-object-for-prop right
12464 temp-names)))))
12465 (if found-node (push found-node node-init))))))
12466 t))))
12467 node-init))
12468
12469 (defun js2-get-symbol-declaration (node name)
12470 "Find scope for NAME from NODE."
12471 (let ((scope (js2-get-defining-scope
12472 (or (js2-node-get-enclosing-scope node)
12473 node) name)))
12474 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12475
12476 (provide 'js2-mode)
12477
12478 ;;; js2-mode.el ends here