]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Copy JSX indentation logic to js2-old-indent.el
[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-jsx-indent-line 'js-jsx-indent-line)
99 (defalias 'js2-indent-line 'js-indent-line)
100 (defalias 'js2-re-search-forward 'js--re-search-forward)))
101
102 ;;; Externs (variables presumed to be defined by the host system)
103
104 (defvar js2-ecma-262-externs
105 (mapcar 'symbol-name
106 '(Array Boolean Date Error EvalError Function Infinity JSON
107 Math NaN Number Object RangeError ReferenceError RegExp
108 String SyntaxError TypeError URIError
109 decodeURI decodeURIComponent encodeURI
110 encodeURIComponent escape eval isFinite isNaN
111 parseFloat parseInt undefined unescape))
112 "Ecma-262 externs. Included in `js2-externs' by default.")
113
114 (defvar js2-browser-externs
115 (mapcar 'symbol-name
116 '(;; DOM level 1
117 Attr CDATASection CharacterData Comment DOMException
118 DOMImplementation Document DocumentFragment
119 DocumentType Element Entity EntityReference
120 ExceptionCode NamedNodeMap Node NodeList Notation
121 ProcessingInstruction Text
122
123 ;; DOM level 2
124 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
125 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
126 HTMLBodyElement HTMLButtonElement HTMLCollection
127 HTMLDListElement HTMLDirectoryElement HTMLDivElement
128 HTMLDocument HTMLElement HTMLFieldSetElement
129 HTMLFontElement HTMLFormElement HTMLFrameElement
130 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
131 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
132 HTMLImageElement HTMLInputElement HTMLIsIndexElement
133 HTMLLIElement HTMLLabelElement HTMLLegendElement
134 HTMLLinkElement HTMLMapElement HTMLMenuElement
135 HTMLMetaElement HTMLModElement HTMLOListElement
136 HTMLObjectElement HTMLOptGroupElement
137 HTMLOptionElement HTMLOptionsCollection
138 HTMLParagraphElement HTMLParamElement HTMLPreElement
139 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
140 HTMLStyleElement HTMLTableCaptionElement
141 HTMLTableCellElement HTMLTableColElement
142 HTMLTableElement HTMLTableRowElement
143 HTMLTableSectionElement HTMLTextAreaElement
144 HTMLTitleElement HTMLUListElement
145
146 ;; DOM level 3
147 DOMConfiguration DOMError DOMException
148 DOMImplementationList DOMImplementationSource
149 DOMLocator DOMStringList NameList TypeInfo
150 UserDataHandler
151
152 ;; Window
153 window alert confirm document java navigator prompt screen
154 self top requestAnimationFrame cancelAnimationFrame
155
156 ;; W3C CSS
157 CSSCharsetRule CSSFontFace CSSFontFaceRule
158 CSSImportRule CSSMediaRule CSSPageRule
159 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
160 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
161 CSSValue CSSValueList Counter DOMImplementationCSS
162 DocumentCSS DocumentStyle ElementCSSInlineStyle
163 LinkStyle MediaList RGBColor Rect StyleSheet
164 StyleSheetList ViewCSS
165
166 ;; W3C Event
167 EventListener EventTarget Event DocumentEvent UIEvent
168 MouseEvent MutationEvent KeyboardEvent
169
170 ;; W3C Range
171 DocumentRange Range RangeException
172
173 ;; W3C XML
174 XPathResult XMLHttpRequest
175
176 ;; console object. Provided by at least Chrome and Firefox.
177 console))
178 "Browser externs.
179 You can cause these to be included or excluded with the custom
180 variable `js2-include-browser-externs'.")
181
182 (defvar js2-rhino-externs
183 (mapcar 'symbol-name
184 '(Packages importClass importPackage com org java
185 ;; Global object (shell) externs.
186 defineClass deserialize doctest gc help load
187 loadClass print quit readFile readUrl runCommand seal
188 serialize spawn sync toint32 version))
189 "Mozilla Rhino externs.
190 Set `js2-include-rhino-externs' to t to include them.")
191
192 (defvar js2-node-externs
193 (mapcar 'symbol-name
194 '(__dirname __filename Buffer clearInterval clearTimeout require
195 console exports global module process setInterval setTimeout
196 querystring))
197 "Node.js externs.
198 Set `js2-include-node-externs' to t to include them.")
199
200 (defvar js2-typed-array-externs
201 (mapcar 'symbol-name
202 '(ArrayBuffer Uint8ClampedArray DataView
203 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
204 Float32Array Float64Array))
205 "Khronos typed array externs. Available in most modern browsers and
206 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
207 are enabled, these will also be included.")
208
209 (defvar js2-harmony-externs
210 (mapcar 'symbol-name
211 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
212 "ES6 externs. If `js2-include-browser-externs' is enabled and
213 `js2-language-version' is sufficiently high, these will be included.")
214
215 ;;; Variables
216
217 (defun js2-mark-safe-local (name pred)
218 "Make the variable NAME buffer-local and mark it as safe file-local
219 variable with predicate PRED."
220 (make-variable-buffer-local name)
221 (put name 'safe-local-variable pred))
222
223 (defcustom js2-highlight-level 2
224 "Amount of syntax highlighting to perform.
225 0 or a negative value means none.
226 1 adds basic syntax highlighting.
227 2 adds highlighting of some Ecma built-in properties.
228 3 adds highlighting of many Ecma built-in functions."
229 :group 'js2-mode
230 :type '(choice (const :tag "None" 0)
231 (const :tag "Basic" 1)
232 (const :tag "Include Properties" 2)
233 (const :tag "Include Functions" 3)))
234
235 (defvar js2-mode-dev-mode-p nil
236 "Non-nil if running in development mode. Normally nil.")
237
238 (defgroup js2-mode nil
239 "An improved JavaScript mode."
240 :group 'languages)
241
242 (defcustom js2-idle-timer-delay 0.2
243 "Delay in secs before re-parsing after user makes changes.
244 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
245 :type 'number
246 :group 'js2-mode)
247 (make-variable-buffer-local 'js2-idle-timer-delay)
248
249 (defcustom js2-dynamic-idle-timer-adjust 0
250 "Positive to adjust `js2-idle-timer-delay' based on file size.
251 The idea is that for short files, parsing is faster so we can be
252 more responsive to user edits without interfering with editing.
253 The buffer length in characters (typically bytes) is divided by
254 this value and used to multiply `js2-idle-timer-delay' for the
255 buffer. For example, a 21k file and 10k adjust yields 21k/10k
256 == 2, so js2-idle-timer-delay is multiplied by 2.
257 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
258 `js2-idle-timer-delay' is not dependent on the file size."
259 :type 'number
260 :group 'js2-mode)
261
262 (defcustom js2-concat-multiline-strings t
263 "When non-nil, `js2-line-break' in mid-string will make it a
264 string concatenation. When `eol', the '+' will be inserted at the
265 end of the line, otherwise, at the beginning of the next line."
266 :type '(choice (const t) (const eol) (const nil))
267 :group 'js2-mode)
268
269 (defcustom js2-mode-show-parse-errors t
270 "True to highlight parse errors."
271 :type 'boolean
272 :group 'js2-mode)
273
274 (defcustom js2-mode-show-strict-warnings t
275 "Non-nil to emit Ecma strict-mode warnings.
276 Some of the warnings can be individually disabled by other flags,
277 even if this flag is non-nil."
278 :type 'boolean
279 :group 'js2-mode)
280
281 (defcustom js2-strict-trailing-comma-warning t
282 "Non-nil to warn about trailing commas in array literals.
283 Ecma-262-5.1 allows them, but older versions of IE raise an error."
284 :type 'boolean
285 :group 'js2-mode)
286
287 (defcustom js2-strict-missing-semi-warning t
288 "Non-nil to warn about semicolon auto-insertion after statement.
289 Technically this is legal per Ecma-262, but some style guides disallow
290 depending on it."
291 :type 'boolean
292 :group 'js2-mode)
293
294 (defcustom js2-missing-semi-one-line-override nil
295 "Non-nil to permit missing semicolons in one-line functions.
296 In one-liner functions such as `function identity(x) {return x}'
297 people often omit the semicolon for a cleaner look. If you are
298 such a person, you can suppress the missing-semicolon warning
299 by setting this variable to t."
300 :type 'boolean
301 :group 'js2-mode)
302
303 (defcustom js2-strict-inconsistent-return-warning t
304 "Non-nil to warn about mixing returns with value-returns.
305 It's perfectly legal to have a `return' and a `return foo' in the
306 same function, but it's often an indicator of a bug, and it also
307 interferes with type inference (in systems that support it.)"
308 :type 'boolean
309 :group 'js2-mode)
310
311 (defcustom js2-strict-cond-assign-warning t
312 "Non-nil to warn about expressions like if (a = b).
313 This often should have been '==' instead of '='. If the warning
314 is enabled, you can suppress it on a per-expression basis by
315 parenthesizing the expression, e.g. if ((a = b)) ..."
316 :type 'boolean
317 :group 'js2-mode)
318
319 (defcustom js2-strict-var-redeclaration-warning t
320 "Non-nil to warn about redeclaring variables in a script or function."
321 :type 'boolean
322 :group 'js2-mode)
323
324 (defcustom js2-strict-var-hides-function-arg-warning t
325 "Non-nil to warn about a var decl hiding a function argument."
326 :type 'boolean
327 :group 'js2-mode)
328
329 (defcustom js2-skip-preprocessor-directives nil
330 "Non-nil to treat lines beginning with # as comments.
331 Useful for viewing Mozilla JavaScript source code."
332 :type 'boolean
333 :group 'js2-mode)
334
335 (defcustom js2-language-version 200
336 "Configures what JavaScript language version to recognize.
337 Currently versions 150, 160, 170, 180 and 200 are supported,
338 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
339 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
340 yield, and Array comprehensions, and 1.8 adds function closures."
341 :type 'integer
342 :group 'js2-mode)
343
344 (defcustom js2-instanceof-has-side-effects nil
345 "If non-nil, treats the instanceof operator as having side effects.
346 This is useful for xulrunner apps."
347 :type 'boolean
348 :group 'js2-mode)
349
350 (defcustom js2-move-point-on-right-click t
351 "Non-nil to move insertion point when you right-click.
352 This makes right-click context menu behavior a bit more intuitive,
353 since menu operations generally apply to the point. The exception
354 is if there is a region selection, in which case the point does -not-
355 move, so cut/copy/paste can work properly.
356
357 Note that IntelliJ moves the point, and Eclipse leaves it alone,
358 so this behavior is customizable."
359 :group 'js2-mode
360 :type 'boolean)
361
362 (defcustom js2-allow-rhino-new-expr-initializer t
363 "Non-nil to support a Rhino's experimental syntactic construct.
364
365 Rhino supports the ability to follow a `new' expression with an object
366 literal, which is used to set additional properties on the new object
367 after calling its constructor. Syntax:
368
369 new <expr> [ ( arglist ) ] [initializer]
370
371 Hence, this expression:
372
373 new Object {a: 1, b: 2}
374
375 results in an Object with properties a=1 and b=2. This syntax is
376 apparently not configurable in Rhino - it's currently always enabled,
377 as of Rhino version 1.7R2."
378 :type 'boolean
379 :group 'js2-mode)
380
381 (defcustom js2-allow-member-expr-as-function-name nil
382 "Non-nil to support experimental Rhino syntax for function names.
383
384 Rhino supports an experimental syntax configured via the Rhino Context
385 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
386
387 function <member-expr> ( [ arg-list ] ) { <body> }
388
389 Where member-expr is a non-parenthesized 'member expression', which
390 is anything at the grammar level of a new-expression or lower, meaning
391 any expression that does not involve infix or unary operators.
392
393 When <member-expr> is not a simple identifier, then it is syntactic
394 sugar for assigning the anonymous function to the <member-expr>. Hence,
395 this code:
396
397 function a.b().c[2] (x, y) { ... }
398
399 is rewritten as:
400
401 a.b().c[2] = function(x, y) {...}
402
403 which doesn't seem particularly useful, but Rhino permits it."
404 :type 'boolean
405 :group 'js2-mode)
406
407 ;; scanner variables
408
409 (defmacro js2-deflocal (name value &optional comment)
410 "Define a buffer-local variable NAME with VALUE and COMMENT."
411 (declare (debug defvar) (doc-string 3))
412 `(progn
413 (defvar ,name ,value ,comment)
414 (make-variable-buffer-local ',name)))
415
416 (defvar js2-EOF_CHAR -1
417 "Represents end of stream. Distinct from js2-EOF token type.")
418
419 ;; I originally used symbols to represent tokens, but Rhino uses
420 ;; ints and then sets various flag bits in them, so ints it is.
421 ;; The upshot is that we need a `js2-' prefix in front of each name.
422 (defvar js2-ERROR -1)
423 (defvar js2-EOF 0)
424 (defvar js2-EOL 1)
425 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
426 (defvar js2-LEAVEWITH 3)
427 (defvar js2-RETURN 4)
428 (defvar js2-GOTO 5)
429 (defvar js2-IFEQ 6)
430 (defvar js2-IFNE 7)
431 (defvar js2-SETNAME 8)
432 (defvar js2-BITOR 9)
433 (defvar js2-BITXOR 10)
434 (defvar js2-BITAND 11)
435 (defvar js2-EQ 12)
436 (defvar js2-NE 13)
437 (defvar js2-LT 14)
438 (defvar js2-LE 15)
439 (defvar js2-GT 16)
440 (defvar js2-GE 17)
441 (defvar js2-LSH 18)
442 (defvar js2-RSH 19)
443 (defvar js2-URSH 20)
444 (defvar js2-ADD 21) ; infix plus
445 (defvar js2-SUB 22) ; infix minus
446 (defvar js2-MUL 23)
447 (defvar js2-DIV 24)
448 (defvar js2-MOD 25)
449 (defvar js2-NOT 26)
450 (defvar js2-BITNOT 27)
451 (defvar js2-POS 28) ; unary plus
452 (defvar js2-NEG 29) ; unary minus
453 (defvar js2-NEW 30)
454 (defvar js2-DELPROP 31)
455 (defvar js2-TYPEOF 32)
456 (defvar js2-GETPROP 33)
457 (defvar js2-GETPROPNOWARN 34)
458 (defvar js2-SETPROP 35)
459 (defvar js2-GETELEM 36)
460 (defvar js2-SETELEM 37)
461 (defvar js2-CALL 38)
462 (defvar js2-NAME 39) ; an identifier
463 (defvar js2-NUMBER 40)
464 (defvar js2-STRING 41)
465 (defvar js2-NULL 42)
466 (defvar js2-THIS 43)
467 (defvar js2-FALSE 44)
468 (defvar js2-TRUE 45)
469 (defvar js2-SHEQ 46) ; shallow equality (===)
470 (defvar js2-SHNE 47) ; shallow inequality (!==)
471 (defvar js2-REGEXP 48)
472 (defvar js2-BINDNAME 49)
473 (defvar js2-THROW 50)
474 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
475 (defvar js2-IN 52)
476 (defvar js2-INSTANCEOF 53)
477 (defvar js2-LOCAL_LOAD 54)
478 (defvar js2-GETVAR 55)
479 (defvar js2-SETVAR 56)
480 (defvar js2-CATCH_SCOPE 57)
481 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
482 (defvar js2-ENUM_INIT_VALUES 59)
483 (defvar js2-ENUM_INIT_ARRAY 60)
484 (defvar js2-ENUM_NEXT 61)
485 (defvar js2-ENUM_ID 62)
486 (defvar js2-THISFN 63)
487 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
488 (defvar js2-ARRAYLIT 65) ; array literal
489 (defvar js2-OBJECTLIT 66) ; object literal
490 (defvar js2-GET_REF 67) ; *reference
491 (defvar js2-SET_REF 68) ; *reference = something
492 (defvar js2-DEL_REF 69) ; delete reference
493 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
494 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
495 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
496
497 ;; XML support
498 (defvar js2-DEFAULTNAMESPACE 73)
499 (defvar js2-ESCXMLATTR 74)
500 (defvar js2-ESCXMLTEXT 75)
501 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
502 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
503 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
504 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
505
506 (defvar js2-first-bytecode js2-ENTERWITH)
507 (defvar js2-last-bytecode js2-REF_NS_NAME)
508
509 (defvar js2-TRY 80)
510 (defvar js2-SEMI 81) ; semicolon
511 (defvar js2-LB 82) ; left and right brackets
512 (defvar js2-RB 83)
513 (defvar js2-LC 84) ; left and right curly-braces
514 (defvar js2-RC 85)
515 (defvar js2-LP 86) ; left and right parens
516 (defvar js2-RP 87)
517 (defvar js2-COMMA 88) ; comma operator
518
519 (defvar js2-ASSIGN 89) ; simple assignment (=)
520 (defvar js2-ASSIGN_BITOR 90) ; |=
521 (defvar js2-ASSIGN_BITXOR 91) ; ^=
522 (defvar js2-ASSIGN_BITAND 92) ; &=
523 (defvar js2-ASSIGN_LSH 93) ; <<=
524 (defvar js2-ASSIGN_RSH 94) ; >>=
525 (defvar js2-ASSIGN_URSH 95) ; >>>=
526 (defvar js2-ASSIGN_ADD 96) ; +=
527 (defvar js2-ASSIGN_SUB 97) ; -=
528 (defvar js2-ASSIGN_MUL 98) ; *=
529 (defvar js2-ASSIGN_DIV 99) ; /=
530 (defvar js2-ASSIGN_MOD 100) ; %=
531
532 (defvar js2-first-assign js2-ASSIGN)
533 (defvar js2-last-assign js2-ASSIGN_MOD)
534
535 (defvar js2-HOOK 101) ; conditional (?:)
536 (defvar js2-COLON 102)
537 (defvar js2-OR 103) ; logical or (||)
538 (defvar js2-AND 104) ; logical and (&&)
539 (defvar js2-INC 105) ; increment/decrement (++ --)
540 (defvar js2-DEC 106)
541 (defvar js2-DOT 107) ; member operator (.)
542 (defvar js2-FUNCTION 108) ; function keyword
543 (defvar js2-EXPORT 109) ; export keyword
544 (defvar js2-IMPORT 110) ; import keyword
545 (defvar js2-IF 111) ; if keyword
546 (defvar js2-ELSE 112) ; else keyword
547 (defvar js2-SWITCH 113) ; switch keyword
548 (defvar js2-CASE 114) ; case keyword
549 (defvar js2-DEFAULT 115) ; default keyword
550 (defvar js2-WHILE 116) ; while keyword
551 (defvar js2-DO 117) ; do keyword
552 (defvar js2-FOR 118) ; for keyword
553 (defvar js2-BREAK 119) ; break keyword
554 (defvar js2-CONTINUE 120) ; continue keyword
555 (defvar js2-VAR 121) ; var keyword
556 (defvar js2-WITH 122) ; with keyword
557 (defvar js2-CATCH 123) ; catch keyword
558 (defvar js2-FINALLY 124) ; finally keyword
559 (defvar js2-VOID 125) ; void keyword
560 (defvar js2-RESERVED 126) ; reserved keywords
561
562 (defvar js2-EMPTY 127)
563
564 ;; Types used for the parse tree - never returned by scanner.
565
566 (defvar js2-BLOCK 128) ; statement block
567 (defvar js2-LABEL 129) ; label
568 (defvar js2-TARGET 130)
569 (defvar js2-LOOP 131)
570 (defvar js2-EXPR_VOID 132) ; expression statement in functions
571 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
572 (defvar js2-JSR 134)
573 (defvar js2-SCRIPT 135) ; top-level node for entire script
574 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
575 (defvar js2-USE_STACK 137)
576 (defvar js2-SETPROP_OP 138) ; x.y op= something
577 (defvar js2-SETELEM_OP 139) ; x[y] op= something
578 (defvar js2-LOCAL_BLOCK 140)
579 (defvar js2-SET_REF_OP 141) ; *reference op= something
580
581 ;; For XML support:
582 (defvar js2-DOTDOT 142) ; member operator (..)
583 (defvar js2-COLONCOLON 143) ; namespace::name
584 (defvar js2-XML 144) ; XML type
585 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
586 (defvar js2-XMLATTR 146) ; @
587 (defvar js2-XMLEND 147)
588
589 ;; Optimizer-only tokens
590 (defvar js2-TO_OBJECT 148)
591 (defvar js2-TO_DOUBLE 149)
592
593 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
594 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
595 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
596 (defvar js2-CONST 153)
597 (defvar js2-SETCONST 154)
598 (defvar js2-SETCONSTVAR 155)
599 (defvar js2-ARRAYCOMP 156)
600 (defvar js2-LETEXPR 157)
601 (defvar js2-WITHEXPR 158)
602 (defvar js2-DEBUGGER 159)
603
604 (defvar js2-COMMENT 160)
605 (defvar js2-TRIPLEDOT 161) ; for rest parameter
606 (defvar js2-ARROW 162) ; function arrow (=>)
607 (defvar js2-CLASS 163)
608 (defvar js2-EXTENDS 164)
609 (defvar js2-SUPER 165)
610 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
611 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
612 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
613
614 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
615
616 (defconst js2-debug-print-trees nil)
617
618 ;; Rhino accepts any string or stream as input. Emacs character
619 ;; processing works best in buffers, so we'll assume the input is a
620 ;; buffer. JavaScript strings can be copied into temp buffers before
621 ;; scanning them.
622
623 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
624 ;; They're the Emacs equivalent of instance variables, more or less.
625
626 (js2-deflocal js2-ts-dirty-line nil
627 "Token stream buffer-local variable.
628 Indicates stuff other than whitespace since start of line.")
629
630 (js2-deflocal js2-ts-hit-eof nil
631 "Token stream buffer-local variable.")
632
633 ;; FIXME: Unused.
634 (js2-deflocal js2-ts-line-start 0
635 "Token stream buffer-local variable.")
636
637 (js2-deflocal js2-ts-lineno 1
638 "Token stream buffer-local variable.")
639
640 ;; FIXME: Unused.
641 (js2-deflocal js2-ts-line-end-char -1
642 "Token stream buffer-local variable.")
643
644 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
645 "Token stream buffer-local variable.
646 Current scan position.")
647
648 ;; FIXME: Unused.
649 (js2-deflocal js2-ts-is-xml-attribute nil
650 "Token stream buffer-local variable.")
651
652 (js2-deflocal js2-ts-xml-is-tag-content nil
653 "Token stream buffer-local variable.")
654
655 (js2-deflocal js2-ts-xml-open-tags-count 0
656 "Token stream buffer-local variable.")
657
658 (js2-deflocal js2-ts-string-buffer nil
659 "Token stream buffer-local variable.
660 List of chars built up while scanning various tokens.")
661
662 (cl-defstruct (js2-token
663 (:constructor nil)
664 (:constructor make-js2-token (beg)))
665 "Value returned from the token stream."
666 (type js2-EOF)
667 (beg 1)
668 (end -1)
669 (string "")
670 number
671 number-base
672 regexp-flags
673 comment-type
674 follows-eol-p)
675
676 ;; Have to call `js2-init-scanner' to initialize the values.
677 (js2-deflocal js2-ti-tokens nil)
678 (js2-deflocal js2-ti-tokens-cursor nil)
679 (js2-deflocal js2-ti-lookahead nil)
680
681 (cl-defstruct (js2-ts-state
682 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
683 (cursor js2-ts-cursor)
684 (tokens (copy-sequence js2-ti-tokens))
685 (tokens-cursor js2-ti-tokens-cursor)
686 (lookahead js2-ti-lookahead))))
687 lineno
688 cursor
689 tokens
690 tokens-cursor
691 lookahead)
692
693 ;;; Parser variables
694
695 (js2-deflocal js2-parsed-errors nil
696 "List of errors produced during scanning/parsing.")
697
698 (js2-deflocal js2-parsed-warnings nil
699 "List of warnings produced during scanning/parsing.")
700
701 (js2-deflocal js2-recover-from-parse-errors t
702 "Non-nil to continue parsing after a syntax error.
703
704 In recovery mode, the AST will be built in full, and any error
705 nodes will be flagged with appropriate error information. If
706 this flag is nil, a syntax error will result in an error being
707 signaled.
708
709 The variable is automatically buffer-local, because different
710 modes that use the parser will need different settings.")
711
712 (js2-deflocal js2-parse-hook nil
713 "List of callbacks for receiving parsing progress.")
714
715 (defvar js2-parse-finished-hook nil
716 "List of callbacks to notify when parsing finishes.
717 Not called if parsing was interrupted.")
718
719 (js2-deflocal js2-is-eval-code nil
720 "True if we're evaluating code in a string.
721 If non-nil, the tokenizer will record the token text, and the AST nodes
722 will record their source text. Off by default for IDE modes, since the
723 text is available in the buffer.")
724
725 (defvar js2-parse-ide-mode t
726 "Non-nil if the parser is being used for `js2-mode'.
727 If non-nil, the parser will set text properties for fontification
728 and the syntax table. The value should be nil when using the
729 parser as a frontend to an interpreter or byte compiler.")
730
731 ;;; Parser instance variables (buffer-local vars for js2-parse)
732
733 (defconst js2-ti-after-eol (lsh 1 16)
734 "Flag: first token of the source line.")
735
736 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
737
738 (js2-deflocal js2-compiler-generate-debug-info t)
739 (js2-deflocal js2-compiler-use-dynamic-scope nil)
740 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
741 (js2-deflocal js2-compiler-xml-available t)
742 (js2-deflocal js2-compiler-optimization-level 0)
743 (js2-deflocal js2-compiler-generating-source t)
744 (js2-deflocal js2-compiler-strict-mode nil)
745 (js2-deflocal js2-compiler-report-warning-as-error nil)
746 (js2-deflocal js2-compiler-generate-observer-count nil)
747 (js2-deflocal js2-compiler-activation-names nil)
748
749 ;; SKIP: sourceURI
750
751 ;; There's a compileFunction method in Context.java - may need it.
752 (js2-deflocal js2-called-by-compile-function nil
753 "True if `js2-parse' was called by `js2-compile-function'.
754 Will only be used when we finish implementing the interpreter.")
755
756 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
757
758 ;; SKIP: node factory - we're going to just call functions directly,
759 ;; and eventually go to a unified AST format.
760
761 (js2-deflocal js2-nesting-of-function 0)
762
763 (js2-deflocal js2-recorded-identifiers nil
764 "Tracks identifiers found during parsing.")
765
766 (js2-deflocal js2-is-in-destructuring nil
767 "True while parsing destructuring expression.")
768
769 (js2-deflocal js2-in-use-strict-directive nil
770 "True while inside a script or function under strict mode.")
771
772 (defcustom js2-global-externs nil
773 "A list of any extern names you'd like to consider always declared.
774 This list is global and is used by all `js2-mode' files.
775 You can create buffer-local externs list using `js2-additional-externs'.
776
777 There is also a buffer-local variable `js2-default-externs',
778 which is initialized by default to include the Ecma-262 externs
779 and the standard browser externs. The three lists are all
780 checked during highlighting."
781 :type 'list
782 :group 'js2-mode)
783
784 (js2-deflocal js2-default-externs nil
785 "Default external declarations.
786
787 These are currently only used for highlighting undeclared variables,
788 which only worries about top-level (unqualified) references.
789 As js2-mode's processing improves, we will flesh out this list.
790
791 The initial value is set to `js2-ecma-262-externs', unless some
792 of the `js2-include-?-externs' variables are set to t, in which
793 case the browser, Rhino and/or Node.js externs are also included.
794
795 See `js2-additional-externs' for more information.")
796
797 (defcustom js2-include-browser-externs t
798 "Non-nil to include browser externs in the master externs list.
799 If you work on JavaScript files that are not intended for browsers,
800 such as Mozilla Rhino server-side JavaScript, set this to nil.
801 See `js2-additional-externs' for more information about externs."
802 :type 'boolean
803 :group 'js2-mode)
804
805 (defcustom js2-include-rhino-externs nil
806 "Non-nil to include Mozilla Rhino externs in the master externs list.
807 See `js2-additional-externs' for more information about externs."
808 :type 'boolean
809 :group 'js2-mode)
810
811 (defcustom js2-include-node-externs nil
812 "Non-nil to include Node.js externs in the master externs list.
813 See `js2-additional-externs' for more information about externs."
814 :type 'boolean
815 :group 'js2-mode)
816
817 (js2-deflocal js2-additional-externs nil
818 "A buffer-local list of additional external declarations.
819 It is used to decide whether variables are considered undeclared
820 for purposes of highlighting.
821
822 Each entry is a Lisp string. The string should be the fully qualified
823 name of an external entity. All externs should be added to this list,
824 so that as js2-mode's processing improves it can take advantage of them.
825
826 You may want to declare your externs in three ways.
827 First, you can add externs that are valid for all your JavaScript files.
828 You should probably do this by adding them to `js2-global-externs', which
829 is a global list used for all js2-mode files.
830
831 Next, you can add a function to `js2-init-hook' that adds additional
832 externs appropriate for the specific file, perhaps based on its path.
833 These should go in `js2-additional-externs', which is buffer-local.
834
835 Third, you can use JSLint's global declaration, as long as
836 `js2-include-jslint-globals' is non-nil, which see.
837
838 Finally, you can add a function to `js2-post-parse-callbacks',
839 which is called after parsing completes, and `js2-mode-ast' is bound to
840 the root of the parse tree. At this stage you can set up an AST
841 node visitor using `js2-visit-ast' and examine the parse tree
842 for specific import patterns that may imply the existence of
843 other externs, possibly tied to your build system. These should also
844 be added to `js2-additional-externs'.
845
846 Your post-parse callback may of course also use the simpler and
847 faster (but perhaps less robust) approach of simply scanning the
848 buffer text for your imports, using regular expressions.")
849
850 ;; SKIP: decompiler
851 ;; SKIP: encoded-source
852
853 ;;; The following variables are per-function and should be saved/restored
854 ;;; during function parsing...
855
856 (js2-deflocal js2-current-script-or-fn nil)
857 (js2-deflocal js2-current-scope nil)
858 (js2-deflocal js2-nesting-of-with 0)
859 (js2-deflocal js2-label-set nil
860 "An alist mapping label names to nodes.")
861
862 (js2-deflocal js2-loop-set nil)
863 (js2-deflocal js2-loop-and-switch-set nil)
864 (js2-deflocal js2-has-return-value nil)
865 (js2-deflocal js2-end-flags 0)
866
867 ;;; ...end of per function variables
868
869 ;; These flags enumerate the possible ways a statement/function can
870 ;; terminate. These flags are used by endCheck() and by the Parser to
871 ;; detect inconsistent return usage.
872 ;;
873 ;; END_UNREACHED is reserved for code paths that are assumed to always be
874 ;; able to execute (example: throw, continue)
875 ;;
876 ;; END_DROPS_OFF indicates if the statement can transfer control to the
877 ;; next one. Statement such as return dont. A compound statement may have
878 ;; some branch that drops off control to the next statement.
879 ;;
880 ;; END_RETURNS indicates that the statement can return (without arguments)
881 ;; END_RETURNS_VALUE indicates that the statement can return a value.
882 ;;
883 ;; A compound statement such as
884 ;; if (condition) {
885 ;; return value;
886 ;; }
887 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
888
889 (defconst js2-end-unreached #x0)
890 (defconst js2-end-drops-off #x1)
891 (defconst js2-end-returns #x2)
892 (defconst js2-end-returns-value #x4)
893
894 ;; Rhino awkwardly passes a statementLabel parameter to the
895 ;; statementHelper() function, the main statement parser, which
896 ;; is then used by quite a few of the sub-parsers. We just make
897 ;; it a buffer-local variable and make sure it's cleaned up properly.
898 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
899
900 ;; Similarly, Rhino passes an inForInit boolean through about half
901 ;; the expression parsers. We use a dynamically-scoped variable,
902 ;; which makes it easier to funcall the parsers individually without
903 ;; worrying about whether they take the parameter or not.
904 (js2-deflocal js2-in-for-init nil)
905 (js2-deflocal js2-temp-name-counter 0)
906 (js2-deflocal js2-parse-stmt-count 0)
907
908 (defsubst js2-get-next-temp-name ()
909 (format "$%d" (cl-incf js2-temp-name-counter)))
910
911 (defvar js2-parse-interruptable-p t
912 "Set this to nil to force parse to continue until finished.
913 This will mostly be useful for interpreters.")
914
915 (defvar js2-statements-per-pause 50
916 "Pause after this many statements to check for user input.
917 If user input is pending, stop the parse and discard the tree.
918 This makes for a smoother user experience for large files.
919 You may have to wait a second or two before the highlighting
920 and error-reporting appear, but you can always type ahead if
921 you wish. This appears to be more or less how Eclipse, IntelliJ
922 and other editors work.")
923
924 (js2-deflocal js2-record-comments t
925 "Instructs the scanner to record comments in `js2-scanned-comments'.")
926
927 (js2-deflocal js2-scanned-comments nil
928 "List of all comments from the current parse.")
929
930 (defcustom js2-mode-indent-inhibit-undo nil
931 "Non-nil to disable collection of Undo information when indenting lines.
932 Some users have requested this behavior. It's nil by default because
933 other Emacs modes don't work this way."
934 :type 'boolean
935 :group 'js2-mode)
936
937 (defcustom js2-mode-indent-ignore-first-tab nil
938 "If non-nil, ignore first TAB keypress if we look indented properly.
939 It's fairly common for users to navigate to an already-indented line
940 and press TAB for reassurance that it's been indented. For this class
941 of users, we want the first TAB press on a line to be ignored if the
942 line is already indented to one of the precomputed alternatives.
943
944 This behavior is only partly implemented. If you TAB-indent a line,
945 navigate to another line, and then navigate back, it fails to clear
946 the last-indented variable, so it thinks you've already hit TAB once,
947 and performs the indent. A full solution would involve getting on the
948 point-motion hooks for the entire buffer. If we come across another
949 use cases that requires watching point motion, I'll consider doing it.
950
951 If you set this variable to nil, then the TAB key will always change
952 the indentation of the current line, if more than one alternative
953 indentation spot exists."
954 :type 'boolean
955 :group 'js2-mode)
956
957 (defvar js2-indent-hook nil
958 "A hook for user-defined indentation rules.
959
960 Functions on this hook should expect two arguments: (LIST INDEX)
961 The LIST argument is the list of computed indentation points for
962 the current line. INDEX is the list index of the indentation point
963 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
964 indent function is not going to change the current line indentation.
965
966 If a hook function on this list returns a non-nil value, then
967 `js2-bounce-indent' assumes the hook function has performed its own
968 indentation, and will do nothing. If all hook functions on the list
969 return nil, then `js2-bounce-indent' will use its computed indentation
970 and reindent the line.
971
972 When hook functions on this hook list are called, the variable
973 `js2-mode-ast' may or may not be set, depending on whether the
974 parse tree is available. If the variable is nil, you can pass a
975 callback to `js2-mode-wait-for-parse', and your callback will be
976 called after the new parse tree is built. This can take some time
977 in large files.")
978
979 (defface js2-warning
980 `((((class color) (background light))
981 (:underline "orange"))
982 (((class color) (background dark))
983 (:underline "orange"))
984 (t (:underline t)))
985 "Face for JavaScript warnings."
986 :group 'js2-mode)
987
988 (defface js2-error
989 `((((class color) (background light))
990 (:foreground "red"))
991 (((class color) (background dark))
992 (:foreground "red"))
993 (t (:foreground "red")))
994 "Face for JavaScript errors."
995 :group 'js2-mode)
996
997 (defface js2-jsdoc-tag
998 '((t :foreground "SlateGray"))
999 "Face used to highlight @whatever tags in jsdoc comments."
1000 :group 'js2-mode)
1001
1002 (defface js2-jsdoc-type
1003 '((t :foreground "SteelBlue"))
1004 "Face used to highlight {FooBar} types in jsdoc comments."
1005 :group 'js2-mode)
1006
1007 (defface js2-jsdoc-value
1008 '((t :foreground "PeachPuff3"))
1009 "Face used to highlight tag values in jsdoc comments."
1010 :group 'js2-mode)
1011
1012 (defface js2-function-param
1013 '((t :foreground "SeaGreen"))
1014 "Face used to highlight function parameters in javascript."
1015 :group 'js2-mode)
1016
1017 (defface js2-function-call
1018 '((t :inherit default))
1019 "Face used to highlight function name in calls."
1020 :group 'js2-mode)
1021
1022 (defface js2-object-property
1023 '((t :inherit default))
1024 "Face used to highlight named property in object literal."
1025 :group 'js2-mode)
1026
1027 (defface js2-instance-member
1028 '((t :foreground "DarkOrchid"))
1029 "Face used to highlight instance variables in javascript.
1030 Not currently used."
1031 :group 'js2-mode)
1032
1033 (defface js2-private-member
1034 '((t :foreground "PeachPuff3"))
1035 "Face used to highlight calls to private methods in javascript.
1036 Not currently used."
1037 :group 'js2-mode)
1038
1039 (defface js2-private-function-call
1040 '((t :foreground "goldenrod"))
1041 "Face used to highlight calls to private functions in javascript.
1042 Not currently used."
1043 :group 'js2-mode)
1044
1045 (defface js2-jsdoc-html-tag-name
1046 '((((class color) (min-colors 88) (background light))
1047 (:foreground "rosybrown"))
1048 (((class color) (min-colors 8) (background dark))
1049 (:foreground "yellow"))
1050 (((class color) (min-colors 8) (background light))
1051 (:foreground "magenta")))
1052 "Face used to highlight jsdoc html tag names"
1053 :group 'js2-mode)
1054
1055 (defface js2-jsdoc-html-tag-delimiter
1056 '((((class color) (min-colors 88) (background light))
1057 (:foreground "dark khaki"))
1058 (((class color) (min-colors 8) (background dark))
1059 (:foreground "green"))
1060 (((class color) (min-colors 8) (background light))
1061 (:foreground "green")))
1062 "Face used to highlight brackets in jsdoc html tags."
1063 :group 'js2-mode)
1064
1065 (defface js2-external-variable
1066 '((t :foreground "orange"))
1067 "Face used to highlight undeclared variable identifiers.")
1068
1069 (defcustom js2-init-hook nil
1070 "List of functions to be called after `js2-mode' or
1071 `js2-minor-mode' has initialized all variables, before parsing
1072 the buffer for the first time."
1073 :type 'hook
1074 :group 'js2-mode
1075 :version "20130608")
1076
1077 (defcustom js2-post-parse-callbacks nil
1078 "List of callback functions invoked after parsing finishes.
1079 Currently, the main use for this function is to add synthetic
1080 declarations to `js2-recorded-identifiers', which see."
1081 :type 'hook
1082 :group 'js2-mode)
1083
1084 (defcustom js2-build-imenu-callbacks nil
1085 "List of functions called during Imenu index generation.
1086 It's a good place to add additional entries to it, using
1087 `js2-record-imenu-entry'."
1088 :type 'hook
1089 :group 'js2-mode)
1090
1091 (defcustom js2-highlight-external-variables t
1092 "Non-nil to highlight undeclared variable identifiers.
1093 An undeclared variable is any variable not declared with var or let
1094 in the current scope or any lexically enclosing scope. If you use
1095 such a variable, then you are either expecting it to originate from
1096 another file, or you've got a potential bug."
1097 :type 'boolean
1098 :group 'js2-mode)
1099
1100 (defcustom js2-warn-about-unused-function-arguments nil
1101 "Non-nil to treat function arguments like declared-but-unused variables."
1102 :type 'booleanp
1103 :group 'js2-mode)
1104
1105 (defcustom js2-include-jslint-globals t
1106 "Non-nil to include the identifiers from JSLint global
1107 declaration (see http://www.jslint.com/lint.html#global) in the
1108 buffer-local externs list. See `js2-additional-externs' for more
1109 information."
1110 :type 'boolean
1111 :group 'js2-mode)
1112
1113 (defvar js2-mode-map
1114 (let ((map (make-sparse-keymap)))
1115 (define-key map [mouse-1] #'js2-mode-show-node)
1116 (define-key map (kbd "M-j") #'js2-line-break)
1117 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1118 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1119 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1120 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1121 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1122 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1123 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1124 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1125 (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
1126
1127 (define-key map [menu-bar javascript]
1128 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1129
1130 (define-key map [menu-bar javascript customize-js2-mode]
1131 '(menu-item "Customize js2-mode" js2-mode-customize
1132 :help "Customize the behavior of this mode"))
1133
1134 (define-key map [menu-bar javascript js2-force-refresh]
1135 '(menu-item "Force buffer refresh" js2-mode-reset
1136 :help "Re-parse the buffer from scratch"))
1137
1138 (define-key map [menu-bar javascript separator-2]
1139 '("--"))
1140
1141 (define-key map [menu-bar javascript next-error]
1142 '(menu-item "Next warning or error" next-error
1143 :enabled (and js2-mode-ast
1144 (or (js2-ast-root-errors js2-mode-ast)
1145 (js2-ast-root-warnings js2-mode-ast)))
1146 :help "Move to next warning or error"))
1147
1148 (define-key map [menu-bar javascript display-errors]
1149 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1150 :visible (not js2-mode-show-parse-errors)
1151 :help "Turn on display of warnings and errors"))
1152
1153 (define-key map [menu-bar javascript hide-errors]
1154 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1155 :visible js2-mode-show-parse-errors
1156 :help "Turn off display of warnings and errors"))
1157
1158 (define-key map [menu-bar javascript separator-1]
1159 '("--"))
1160
1161 (define-key map [menu-bar javascript js2-toggle-function]
1162 '(menu-item "Show/collapse element" js2-mode-toggle-element
1163 :help "Hide or show function body or comment"))
1164
1165 (define-key map [menu-bar javascript show-comments]
1166 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1167 :visible js2-mode-comments-hidden
1168 :help "Expand all hidden block comments"))
1169
1170 (define-key map [menu-bar javascript hide-comments]
1171 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1172 :visible (not js2-mode-comments-hidden)
1173 :help "Show block comments as /*...*/"))
1174
1175 (define-key map [menu-bar javascript show-all-functions]
1176 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1177 :visible js2-mode-functions-hidden
1178 :help "Expand all hidden function bodies"))
1179
1180 (define-key map [menu-bar javascript hide-all-functions]
1181 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1182 :visible (not js2-mode-functions-hidden)
1183 :help "Show {...} for all top-level function bodies"))
1184
1185 map)
1186 "Keymap used in `js2-mode' buffers.")
1187
1188 (defcustom js2-bounce-indent-p nil
1189 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1190 They will augment the default indent-line behavior with cycling
1191 among several computed alternatives. See the function
1192 `js2-bounce-indent' for details. The above commands will be
1193 bound to TAB and backtab."
1194 :type 'boolean
1195 :group 'js2-mode
1196 :set (lambda (sym value)
1197 (set-default sym value)
1198 (let ((map js2-mode-map))
1199 (if (not value)
1200 (progn
1201 (define-key map "\t" nil)
1202 (define-key map (kbd "<backtab>") nil))
1203 (define-key map "\t" #'js2-indent-bounce)
1204 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1205
1206 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1207
1208 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1209 "Matches a //-comment line. Must be first non-whitespace on line.
1210 First match-group is the leading whitespace.")
1211
1212 (defvar js2-mode-hook nil)
1213
1214 (js2-deflocal js2-mode-ast nil "Private variable.")
1215 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1216 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1217 (js2-deflocal js2-mode-parsing nil "Private variable.")
1218 (js2-deflocal js2-mode-node-overlay nil)
1219
1220 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1221 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1222
1223 (js2-deflocal js2-mode-fontifications nil "Private variable")
1224 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1225 (js2-deflocal js2-imenu-recorder nil "Private variable")
1226 (js2-deflocal js2-imenu-function-map nil "Private variable")
1227
1228 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1229 "Non-nil to emit status messages during parsing.")
1230
1231 (defvar js2-mode-functions-hidden nil "Private variable.")
1232 (defvar js2-mode-comments-hidden nil "Private variable.")
1233
1234 (defvar js2-mode-syntax-table
1235 (let ((table (make-syntax-table)))
1236 (c-populate-syntax-table table)
1237 (modify-syntax-entry ?` "\"" table)
1238 table)
1239 "Syntax table used in `js2-mode' buffers.")
1240
1241 (defvar js2-mode-abbrev-table nil
1242 "Abbrev table in use in `js2-mode' buffers.")
1243 (define-abbrev-table 'js2-mode-abbrev-table ())
1244
1245 (defvar js2-mode-pending-parse-callbacks nil
1246 "List of functions waiting to be notified that parse is finished.")
1247
1248 (defvar js2-mode-last-indented-line -1)
1249
1250 ;;; Localizable error and warning messages
1251
1252 ;; Messages are copied from Rhino's Messages.properties.
1253 ;; Many of the Java-specific messages have been elided.
1254 ;; Add any js2-specific ones at the end, so we can keep
1255 ;; this file synced with changes to Rhino's.
1256
1257 (defvar js2-message-table
1258 (make-hash-table :test 'equal :size 250)
1259 "Contains localized messages for `js2-mode'.")
1260
1261 ;; TODO(stevey): construct this table at compile-time.
1262 (defmacro js2-msg (key &rest strings)
1263 `(puthash ,key (concat ,@strings)
1264 js2-message-table))
1265
1266 (defun js2-get-msg (msg-key)
1267 "Look up a localized message.
1268 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1269 the correct number of ARGS must be provided."
1270 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1271 (args (if (listp msg-key) (cdr msg-key)))
1272 (msg (gethash key js2-message-table)))
1273 (if msg
1274 (apply #'format msg args)
1275 key))) ; default to showing the key
1276
1277 (js2-msg "msg.dup.parms"
1278 "Duplicate parameter name '%s'.")
1279
1280 (js2-msg "msg.too.big.jump"
1281 "Program too complex: jump offset too big.")
1282
1283 (js2-msg "msg.too.big.index"
1284 "Program too complex: internal index exceeds 64K limit.")
1285
1286 (js2-msg "msg.while.compiling.fn"
1287 "Encountered code generation error while compiling function '%s': %s")
1288
1289 (js2-msg "msg.while.compiling.script"
1290 "Encountered code generation error while compiling script: %s")
1291
1292 ;; Context
1293 (js2-msg "msg.ctor.not.found"
1294 "Constructor for '%s' not found.")
1295
1296 (js2-msg "msg.not.ctor"
1297 "'%s' is not a constructor.")
1298
1299 ;; FunctionObject
1300 (js2-msg "msg.varargs.ctor"
1301 "Method or constructor '%s' must be static "
1302 "with the signature (Context cx, Object[] args, "
1303 "Function ctorObj, boolean inNewExpr) "
1304 "to define a variable arguments constructor.")
1305
1306 (js2-msg "msg.varargs.fun"
1307 "Method '%s' must be static with the signature "
1308 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1309 "to define a variable arguments function.")
1310
1311 (js2-msg "msg.incompat.call"
1312 "Method '%s' called on incompatible object.")
1313
1314 (js2-msg "msg.bad.parms"
1315 "Unsupported parameter type '%s' in method '%s'.")
1316
1317 (js2-msg "msg.bad.method.return"
1318 "Unsupported return type '%s' in method '%s'.")
1319
1320 (js2-msg "msg.bad.ctor.return"
1321 "Construction of objects of type '%s' is not supported.")
1322
1323 (js2-msg "msg.no.overload"
1324 "Method '%s' occurs multiple times in class '%s'.")
1325
1326 (js2-msg "msg.method.not.found"
1327 "Method '%s' not found in '%s'.")
1328
1329 ;; IRFactory
1330
1331 (js2-msg "msg.bad.for.in.lhs"
1332 "Invalid left-hand side of for..in loop.")
1333
1334 (js2-msg "msg.mult.index"
1335 "Only one variable allowed in for..in loop.")
1336
1337 (js2-msg "msg.bad.for.in.destruct"
1338 "Left hand side of for..in loop must be an array of "
1339 "length 2 to accept key/value pair.")
1340
1341 (js2-msg "msg.cant.convert"
1342 "Can't convert to type '%s'.")
1343
1344 (js2-msg "msg.bad.assign.left"
1345 "Invalid assignment left-hand side.")
1346
1347 (js2-msg "msg.bad.decr"
1348 "Invalid decrement operand.")
1349
1350 (js2-msg "msg.bad.incr"
1351 "Invalid increment operand.")
1352
1353 (js2-msg "msg.bad.yield"
1354 "yield must be in a function.")
1355
1356 (js2-msg "msg.yield.parenthesized"
1357 "yield expression must be parenthesized.")
1358
1359 ;; NativeGlobal
1360 (js2-msg "msg.cant.call.indirect"
1361 "Function '%s' must be called directly, and not by way of a "
1362 "function of another name.")
1363
1364 (js2-msg "msg.eval.nonstring"
1365 "Calling eval() with anything other than a primitive "
1366 "string value will simply return the value. "
1367 "Is this what you intended?")
1368
1369 (js2-msg "msg.eval.nonstring.strict"
1370 "Calling eval() with anything other than a primitive "
1371 "string value is not allowed in strict mode.")
1372
1373 (js2-msg "msg.bad.destruct.op"
1374 "Invalid destructuring assignment operator")
1375
1376 ;; NativeCall
1377 (js2-msg "msg.only.from.new"
1378 "'%s' may only be invoked from a `new' expression.")
1379
1380 (js2-msg "msg.deprec.ctor"
1381 "The '%s' constructor is deprecated.")
1382
1383 ;; NativeFunction
1384 (js2-msg "msg.no.function.ref.found"
1385 "no source found to decompile function reference %s")
1386
1387 (js2-msg "msg.arg.isnt.array"
1388 "second argument to Function.prototype.apply must be an array")
1389
1390 ;; NativeGlobal
1391 (js2-msg "msg.bad.esc.mask"
1392 "invalid string escape mask")
1393
1394 ;; NativeRegExp
1395 (js2-msg "msg.bad.quant"
1396 "Invalid quantifier %s")
1397
1398 (js2-msg "msg.overlarge.backref"
1399 "Overly large back reference %s")
1400
1401 (js2-msg "msg.overlarge.min"
1402 "Overly large minimum %s")
1403
1404 (js2-msg "msg.overlarge.max"
1405 "Overly large maximum %s")
1406
1407 (js2-msg "msg.zero.quant"
1408 "Zero quantifier %s")
1409
1410 (js2-msg "msg.max.lt.min"
1411 "Maximum %s less than minimum")
1412
1413 (js2-msg "msg.unterm.quant"
1414 "Unterminated quantifier %s")
1415
1416 (js2-msg "msg.unterm.paren"
1417 "Unterminated parenthetical %s")
1418
1419 (js2-msg "msg.unterm.class"
1420 "Unterminated character class %s")
1421
1422 (js2-msg "msg.bad.range"
1423 "Invalid range in character class.")
1424
1425 (js2-msg "msg.trail.backslash"
1426 "Trailing \\ in regular expression.")
1427
1428 (js2-msg "msg.re.unmatched.right.paren"
1429 "unmatched ) in regular expression.")
1430
1431 (js2-msg "msg.no.regexp"
1432 "Regular expressions are not available.")
1433
1434 (js2-msg "msg.bad.backref"
1435 "back-reference exceeds number of capturing parentheses.")
1436
1437 (js2-msg "msg.bad.regexp.compile"
1438 "Only one argument may be specified if the first "
1439 "argument to RegExp.prototype.compile is a RegExp object.")
1440
1441 ;; Parser
1442 (js2-msg "msg.got.syntax.errors"
1443 "Compilation produced %s syntax errors.")
1444
1445 (js2-msg "msg.var.redecl"
1446 "TypeError: redeclaration of var %s.")
1447
1448 (js2-msg "msg.const.redecl"
1449 "TypeError: redeclaration of const %s.")
1450
1451 (js2-msg "msg.let.redecl"
1452 "TypeError: redeclaration of variable %s.")
1453
1454 (js2-msg "msg.parm.redecl"
1455 "TypeError: redeclaration of formal parameter %s.")
1456
1457 (js2-msg "msg.fn.redecl"
1458 "TypeError: redeclaration of function %s.")
1459
1460 (js2-msg "msg.let.decl.not.in.block"
1461 "SyntaxError: let declaration not directly within block")
1462
1463 (js2-msg "msg.mod.import.decl.at.top.level"
1464 "SyntaxError: import declarations may only appear at the top level")
1465
1466 (js2-msg "msg.mod.as.after.reserved.word"
1467 "SyntaxError: missing keyword 'as' after reserved word %s")
1468
1469 (js2-msg "msg.mod.rc.after.import.spec.list"
1470 "SyntaxError: missing '}' after module specifier list")
1471
1472 (js2-msg "msg.mod.from.after.import.spec.set"
1473 "SyntaxError: missing keyword 'from' after import specifier set")
1474
1475 (js2-msg "msg.mod.declaration.after.import"
1476 "SyntaxError: missing declaration after 'import' keyword")
1477
1478 (js2-msg "msg.mod.spec.after.from"
1479 "SyntaxError: missing module specifier after 'from' keyword")
1480
1481 (js2-msg "msg.mod.export.decl.at.top.level"
1482 "SyntaxError: export declarations may only appear at top level")
1483
1484 (js2-msg "msg.mod.rc.after.export.spec.list"
1485 "SyntaxError: missing '}' after export specifier list")
1486
1487 ;; NodeTransformer
1488 (js2-msg "msg.dup.label"
1489 "duplicated label")
1490
1491 (js2-msg "msg.undef.label"
1492 "undefined label")
1493
1494 (js2-msg "msg.bad.break"
1495 "unlabelled break must be inside loop or switch")
1496
1497 (js2-msg "msg.continue.outside"
1498 "continue must be inside loop")
1499
1500 (js2-msg "msg.continue.nonloop"
1501 "continue can only use labels of iteration statements")
1502
1503 (js2-msg "msg.bad.throw.eol"
1504 "Line terminator is not allowed between the throw "
1505 "keyword and throw expression.")
1506
1507 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1508 "function statement requires a name")
1509
1510 (js2-msg "msg.no.paren.parms"
1511 "missing ( before function parameters.")
1512
1513 (js2-msg "msg.no.parm"
1514 "missing formal parameter")
1515
1516 (js2-msg "msg.no.paren.after.parms"
1517 "missing ) after formal parameters")
1518
1519 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1520 "parameter without default follows parameter with default")
1521
1522 (js2-msg "msg.param.after.rest" ; added by js2-mode
1523 "parameter after rest parameter")
1524
1525 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1526 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1527
1528 (js2-msg "msg.no.brace.body"
1529 "missing '{' before function body")
1530
1531 (js2-msg "msg.no.brace.after.body"
1532 "missing } after function body")
1533
1534 (js2-msg "msg.no.paren.cond"
1535 "missing ( before condition")
1536
1537 (js2-msg "msg.no.paren.after.cond"
1538 "missing ) after condition")
1539
1540 (js2-msg "msg.no.semi.stmt"
1541 "missing ; before statement")
1542
1543 (js2-msg "msg.missing.semi"
1544 "missing ; after statement")
1545
1546 (js2-msg "msg.no.name.after.dot"
1547 "missing name after . operator")
1548
1549 (js2-msg "msg.no.name.after.coloncolon"
1550 "missing name after :: operator")
1551
1552 (js2-msg "msg.no.name.after.dotdot"
1553 "missing name after .. operator")
1554
1555 (js2-msg "msg.no.name.after.xmlAttr"
1556 "missing name after .@")
1557
1558 (js2-msg "msg.no.bracket.index"
1559 "missing ] in index expression")
1560
1561 (js2-msg "msg.no.paren.switch"
1562 "missing ( before switch expression")
1563
1564 (js2-msg "msg.no.paren.after.switch"
1565 "missing ) after switch expression")
1566
1567 (js2-msg "msg.no.brace.switch"
1568 "missing '{' before switch body")
1569
1570 (js2-msg "msg.bad.switch"
1571 "invalid switch statement")
1572
1573 (js2-msg "msg.no.colon.case"
1574 "missing : after case expression")
1575
1576 (js2-msg "msg.double.switch.default"
1577 "double default label in the switch statement")
1578
1579 (js2-msg "msg.no.while.do"
1580 "missing while after do-loop body")
1581
1582 (js2-msg "msg.no.paren.for"
1583 "missing ( after for")
1584
1585 (js2-msg "msg.no.semi.for"
1586 "missing ; after for-loop initializer")
1587
1588 (js2-msg "msg.no.semi.for.cond"
1589 "missing ; after for-loop condition")
1590
1591 (js2-msg "msg.in.after.for.name"
1592 "missing in or of after for")
1593
1594 (js2-msg "msg.no.paren.for.ctrl"
1595 "missing ) after for-loop control")
1596
1597 (js2-msg "msg.no.paren.with"
1598 "missing ( before with-statement object")
1599
1600 (js2-msg "msg.no.paren.after.with"
1601 "missing ) after with-statement object")
1602
1603 (js2-msg "msg.no.with.strict"
1604 "with statements not allowed in strict mode")
1605
1606 (js2-msg "msg.no.paren.after.let"
1607 "missing ( after let")
1608
1609 (js2-msg "msg.no.paren.let"
1610 "missing ) after variable list")
1611
1612 (js2-msg "msg.no.curly.let"
1613 "missing } after let statement")
1614
1615 (js2-msg "msg.bad.return"
1616 "invalid return")
1617
1618 (js2-msg "msg.no.brace.block"
1619 "missing } in compound statement")
1620
1621 (js2-msg "msg.bad.label"
1622 "invalid label")
1623
1624 (js2-msg "msg.bad.var"
1625 "missing variable name")
1626
1627 (js2-msg "msg.bad.var.init"
1628 "invalid variable initialization")
1629
1630 (js2-msg "msg.no.colon.cond"
1631 "missing : in conditional expression")
1632
1633 (js2-msg "msg.no.paren.arg"
1634 "missing ) after argument list")
1635
1636 (js2-msg "msg.no.bracket.arg"
1637 "missing ] after element list")
1638
1639 (js2-msg "msg.bad.prop"
1640 "invalid property id")
1641
1642 (js2-msg "msg.no.colon.prop"
1643 "missing : after property id")
1644
1645 (js2-msg "msg.no.brace.prop"
1646 "missing } after property list")
1647
1648 (js2-msg "msg.no.paren"
1649 "missing ) in parenthetical")
1650
1651 (js2-msg "msg.reserved.id"
1652 "'%s' is a reserved identifier")
1653
1654 (js2-msg "msg.no.paren.catch"
1655 "missing ( before catch-block condition")
1656
1657 (js2-msg "msg.bad.catchcond"
1658 "invalid catch block condition")
1659
1660 (js2-msg "msg.catch.unreachable"
1661 "any catch clauses following an unqualified catch are unreachable")
1662
1663 (js2-msg "msg.no.brace.try"
1664 "missing '{' before try block")
1665
1666 (js2-msg "msg.no.brace.catchblock"
1667 "missing '{' before catch-block body")
1668
1669 (js2-msg "msg.try.no.catchfinally"
1670 "'try' without 'catch' or 'finally'")
1671
1672 (js2-msg "msg.no.return.value"
1673 "function %s does not always return a value")
1674
1675 (js2-msg "msg.anon.no.return.value"
1676 "anonymous function does not always return a value")
1677
1678 (js2-msg "msg.return.inconsistent"
1679 "return statement is inconsistent with previous usage")
1680
1681 (js2-msg "msg.generator.returns"
1682 "TypeError: legacy generator function '%s' returns a value")
1683
1684 (js2-msg "msg.anon.generator.returns"
1685 "TypeError: anonymous legacy generator function returns a value")
1686
1687 (js2-msg "msg.syntax"
1688 "syntax error")
1689
1690 (js2-msg "msg.unexpected.eof"
1691 "Unexpected end of file")
1692
1693 (js2-msg "msg.XML.bad.form"
1694 "illegally formed XML syntax")
1695
1696 (js2-msg "msg.XML.not.available"
1697 "XML runtime not available")
1698
1699 (js2-msg "msg.too.deep.parser.recursion"
1700 "Too deep recursion while parsing")
1701
1702 (js2-msg "msg.no.side.effects"
1703 "Code has no side effects")
1704
1705 (js2-msg "msg.extra.trailing.comma"
1706 "Trailing comma is not supported in some browsers")
1707
1708 (js2-msg "msg.array.trailing.comma"
1709 "Trailing comma yields different behavior across browsers")
1710
1711 (js2-msg "msg.equal.as.assign"
1712 (concat "Test for equality (==) mistyped as assignment (=)?"
1713 " (parenthesize to suppress warning)"))
1714
1715 (js2-msg "msg.var.hides.arg"
1716 "Variable %s hides argument")
1717
1718 (js2-msg "msg.destruct.assign.no.init"
1719 "Missing = in destructuring declaration")
1720
1721 (js2-msg "msg.init.no.destruct"
1722 "Binding initializer not in destructuring assignment")
1723
1724 (js2-msg "msg.no.octal.strict"
1725 "Octal numbers prohibited in strict mode.")
1726
1727 (js2-msg "msg.dup.obj.lit.prop.strict"
1728 "Property '%s' already defined in this object literal.")
1729
1730 (js2-msg "msg.dup.param.strict"
1731 "Parameter '%s' already declared in this function.")
1732
1733 (js2-msg "msg.bad.id.strict"
1734 "'%s' is not a valid identifier for this use in strict mode.")
1735
1736 ;; ScriptRuntime
1737 (js2-msg "msg.no.properties"
1738 "%s has no properties.")
1739
1740 (js2-msg "msg.invalid.iterator"
1741 "Invalid iterator value")
1742
1743 (js2-msg "msg.iterator.primitive"
1744 "__iterator__ returned a primitive value")
1745
1746 (js2-msg "msg.assn.create.strict"
1747 "Assignment to undeclared variable %s")
1748
1749 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1750 "Undeclared variable or function '%s'")
1751
1752 (js2-msg "msg.unused.variable" ; added by js2-mode
1753 "Unused variable or function '%s'")
1754
1755 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1756 "Variable '%s' referenced but never initialized")
1757
1758 (js2-msg "msg.ref.undefined.prop"
1759 "Reference to undefined property '%s'")
1760
1761 (js2-msg "msg.prop.not.found"
1762 "Property %s not found.")
1763
1764 (js2-msg "msg.invalid.type"
1765 "Invalid JavaScript value of type %s")
1766
1767 (js2-msg "msg.primitive.expected"
1768 "Primitive type expected (had %s instead)")
1769
1770 (js2-msg "msg.namespace.expected"
1771 "Namespace object expected to left of :: (found %s instead)")
1772
1773 (js2-msg "msg.null.to.object"
1774 "Cannot convert null to an object.")
1775
1776 (js2-msg "msg.undef.to.object"
1777 "Cannot convert undefined to an object.")
1778
1779 (js2-msg "msg.cyclic.value"
1780 "Cyclic %s value not allowed.")
1781
1782 (js2-msg "msg.is.not.defined"
1783 "'%s' is not defined.")
1784
1785 (js2-msg "msg.undef.prop.read"
1786 "Cannot read property '%s' from %s")
1787
1788 (js2-msg "msg.undef.prop.write"
1789 "Cannot set property '%s' of %s to '%s'")
1790
1791 (js2-msg "msg.undef.prop.delete"
1792 "Cannot delete property '%s' of %s")
1793
1794 (js2-msg "msg.undef.method.call"
1795 "Cannot call method '%s' of %s")
1796
1797 (js2-msg "msg.undef.with"
1798 "Cannot apply 'with' to %s")
1799
1800 (js2-msg "msg.isnt.function"
1801 "%s is not a function, it is %s.")
1802
1803 (js2-msg "msg.isnt.function.in"
1804 "Cannot call property %s in object %s. "
1805 "It is not a function, it is '%s'.")
1806
1807 (js2-msg "msg.function.not.found"
1808 "Cannot find function %s.")
1809
1810 (js2-msg "msg.function.not.found.in"
1811 "Cannot find function %s in object %s.")
1812
1813 (js2-msg "msg.isnt.xml.object"
1814 "%s is not an xml object.")
1815
1816 (js2-msg "msg.no.ref.to.get"
1817 "%s is not a reference to read reference value.")
1818
1819 (js2-msg "msg.no.ref.to.set"
1820 "%s is not a reference to set reference value to %s.")
1821
1822 (js2-msg "msg.no.ref.from.function"
1823 "Function %s can not be used as the left-hand "
1824 "side of assignment or as an operand of ++ or -- operator.")
1825
1826 (js2-msg "msg.bad.default.value"
1827 "Object's getDefaultValue() method returned an object.")
1828
1829 (js2-msg "msg.instanceof.not.object"
1830 "Can't use instanceof on a non-object.")
1831
1832 (js2-msg "msg.instanceof.bad.prototype"
1833 "'prototype' property of %s is not an object.")
1834
1835 (js2-msg "msg.bad.radix"
1836 "illegal radix %s.")
1837
1838 ;; ScriptableObject
1839 (js2-msg "msg.default.value"
1840 "Cannot find default value for object.")
1841
1842 (js2-msg "msg.zero.arg.ctor"
1843 "Cannot load class '%s' which has no zero-parameter constructor.")
1844
1845 (js2-msg "msg.ctor.multiple.parms"
1846 "Can't define constructor or class %s since more than "
1847 "one constructor has multiple parameters.")
1848
1849 (js2-msg "msg.extend.scriptable"
1850 "%s must extend ScriptableObject in order to define property %s.")
1851
1852 (js2-msg "msg.bad.getter.parms"
1853 "In order to define a property, getter %s must have zero "
1854 "parameters or a single ScriptableObject parameter.")
1855
1856 (js2-msg "msg.obj.getter.parms"
1857 "Expected static or delegated getter %s to take "
1858 "a ScriptableObject parameter.")
1859
1860 (js2-msg "msg.getter.static"
1861 "Getter and setter must both be static or neither be static.")
1862
1863 (js2-msg "msg.setter.return"
1864 "Setter must have void return type: %s")
1865
1866 (js2-msg "msg.setter2.parms"
1867 "Two-parameter setter must take a ScriptableObject as "
1868 "its first parameter.")
1869
1870 (js2-msg "msg.setter1.parms"
1871 "Expected single parameter setter for %s")
1872
1873 (js2-msg "msg.setter2.expected"
1874 "Expected static or delegated setter %s to take two parameters.")
1875
1876 (js2-msg "msg.setter.parms"
1877 "Expected either one or two parameters for setter.")
1878
1879 (js2-msg "msg.setter.bad.type"
1880 "Unsupported parameter type '%s' in setter '%s'.")
1881
1882 (js2-msg "msg.add.sealed"
1883 "Cannot add a property to a sealed object: %s.")
1884
1885 (js2-msg "msg.remove.sealed"
1886 "Cannot remove a property from a sealed object: %s.")
1887
1888 (js2-msg "msg.modify.sealed"
1889 "Cannot modify a property of a sealed object: %s.")
1890
1891 (js2-msg "msg.modify.readonly"
1892 "Cannot modify readonly property: %s.")
1893
1894 ;; TokenStream
1895 (js2-msg "msg.missing.exponent"
1896 "missing exponent")
1897
1898 (js2-msg "msg.caught.nfe"
1899 "number format error")
1900
1901 (js2-msg "msg.unterminated.string.lit"
1902 "unterminated string literal")
1903
1904 (js2-msg "msg.unterminated.comment"
1905 "unterminated comment")
1906
1907 (js2-msg "msg.unterminated.re.lit"
1908 "unterminated regular expression literal")
1909
1910 (js2-msg "msg.invalid.re.flag"
1911 "invalid flag after regular expression")
1912
1913 (js2-msg "msg.no.re.input.for"
1914 "no input for %s")
1915
1916 (js2-msg "msg.illegal.character"
1917 "illegal character")
1918
1919 (js2-msg "msg.invalid.escape"
1920 "invalid Unicode escape sequence")
1921
1922 (js2-msg "msg.bad.namespace"
1923 "not a valid default namespace statement. "
1924 "Syntax is: default xml namespace = EXPRESSION;")
1925
1926 ;; TokensStream warnings
1927 (js2-msg "msg.bad.octal.literal"
1928 "illegal octal literal digit %s; "
1929 "interpreting it as a decimal digit")
1930
1931 (js2-msg "msg.missing.hex.digits"
1932 "missing hexadecimal digits after '0x'")
1933
1934 (js2-msg "msg.missing.binary.digits"
1935 "missing binary digits after '0b'")
1936
1937 (js2-msg "msg.missing.octal.digits"
1938 "missing octal digits after '0o'")
1939
1940 (js2-msg "msg.script.is.not.constructor"
1941 "Script objects are not constructors.")
1942
1943 ;; Arrays
1944 (js2-msg "msg.arraylength.bad"
1945 "Inappropriate array length.")
1946
1947 ;; Arrays
1948 (js2-msg "msg.arraylength.too.big"
1949 "Array length %s exceeds supported capacity limit.")
1950
1951 ;; URI
1952 (js2-msg "msg.bad.uri"
1953 "Malformed URI sequence.")
1954
1955 ;; Number
1956 (js2-msg "msg.bad.precision"
1957 "Precision %s out of range.")
1958
1959 ;; NativeGenerator
1960 (js2-msg "msg.send.newborn"
1961 "Attempt to send value to newborn generator")
1962
1963 (js2-msg "msg.already.exec.gen"
1964 "Already executing generator")
1965
1966 (js2-msg "msg.StopIteration.invalid"
1967 "StopIteration may not be changed to an arbitrary object.")
1968
1969 ;; Interpreter
1970 (js2-msg "msg.yield.closing"
1971 "Yield from closing generator")
1972
1973 ;; Classes
1974 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1975 "class statement requires a name")
1976
1977 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1978 "unexpected ',' between class properties")
1979
1980 (js2-msg "msg.unexpected.static" ; added by js2-mode
1981 "unexpected 'static'")
1982
1983 (js2-msg "msg.missing.extends" ; added by js2-mode
1984 "name is required after extends")
1985
1986 (js2-msg "msg.no.brace.class" ; added by js2-mode
1987 "missing '{' before class body")
1988
1989 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1990 "missing ']' after computed property expression")
1991
1992 ;;; Tokens Buffer
1993
1994 (defconst js2-ti-max-lookahead 2)
1995 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1996
1997 (defun js2-new-token (offset)
1998 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1999 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2000 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2001 token))
2002
2003 (defsubst js2-current-token ()
2004 (aref js2-ti-tokens js2-ti-tokens-cursor))
2005
2006 (defsubst js2-current-token-string ()
2007 (js2-token-string (js2-current-token)))
2008
2009 (defsubst js2-current-token-type ()
2010 (js2-token-type (js2-current-token)))
2011
2012 (defsubst js2-current-token-beg ()
2013 (js2-token-beg (js2-current-token)))
2014
2015 (defsubst js2-current-token-end ()
2016 (js2-token-end (js2-current-token)))
2017
2018 (defun js2-current-token-len ()
2019 (let ((token (js2-current-token)))
2020 (- (js2-token-end token)
2021 (js2-token-beg token))))
2022
2023 (defun js2-ts-seek (state)
2024 (setq js2-ts-lineno (js2-ts-state-lineno state)
2025 js2-ts-cursor (js2-ts-state-cursor state)
2026 js2-ti-tokens (js2-ts-state-tokens state)
2027 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2028 js2-ti-lookahead (js2-ts-state-lookahead state)))
2029
2030 ;;; Utilities
2031
2032 (defun js2-delete-if (predicate list)
2033 "Remove all items satisfying PREDICATE in LIST."
2034 (cl-loop for item in list
2035 if (not (funcall predicate item))
2036 collect item))
2037
2038 (defun js2-position (element list)
2039 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2040 Returns nil if element is not found in the list."
2041 (let ((count 0)
2042 found)
2043 (while (and list (not found))
2044 (if (eq element (car list))
2045 (setq found t)
2046 (setq count (1+ count)
2047 list (cdr list))))
2048 (if found count)))
2049
2050 (defun js2-find-if (predicate list)
2051 "Find first item satisfying PREDICATE in LIST."
2052 (let (result)
2053 (while (and list (not result))
2054 (if (funcall predicate (car list))
2055 (setq result (car list)))
2056 (setq list (cdr list)))
2057 result))
2058
2059 (defmacro js2-time (form)
2060 "Evaluate FORM, discard result, and return elapsed time in sec."
2061 (declare (debug t))
2062 (let ((beg (make-symbol "--js2-time-beg--")))
2063 `(let ((,beg (current-time)))
2064 ,form
2065 (/ (truncate (* (- (float-time (current-time))
2066 (float-time ,beg))
2067 10000))
2068 10000.0))))
2069
2070 (defsubst js2-same-line (pos)
2071 "Return t if POS is on the same line as current point."
2072 (and (>= pos (point-at-bol))
2073 (<= pos (point-at-eol))))
2074
2075 (defun js2-code-bug ()
2076 "Signal an error when we encounter an unexpected code path."
2077 (error "failed assertion"))
2078
2079 (defsubst js2-record-text-property (beg end prop value)
2080 "Record a text property to set when parsing finishes."
2081 (push (list beg end prop value) js2-mode-deferred-properties))
2082
2083 ;; I'd like to associate errors with nodes, but for now the
2084 ;; easiest thing to do is get the context info from the last token.
2085 (defun js2-record-parse-error (msg &optional arg pos len)
2086 (push (list (list msg arg)
2087 (or pos (js2-current-token-beg))
2088 (or len (js2-current-token-len)))
2089 js2-parsed-errors))
2090
2091 (defun js2-report-error (msg &optional msg-arg pos len)
2092 "Signal a syntax error or record a parse error."
2093 (if js2-recover-from-parse-errors
2094 (js2-record-parse-error msg msg-arg pos len)
2095 (signal 'js2-syntax-error
2096 (list msg
2097 js2-ts-lineno
2098 (save-excursion
2099 (goto-char js2-ts-cursor)
2100 (current-column))
2101 js2-ts-hit-eof))))
2102
2103 (defun js2-report-warning (msg &optional msg-arg pos len face)
2104 (if js2-compiler-report-warning-as-error
2105 (js2-report-error msg msg-arg pos len)
2106 (push (list (list msg msg-arg)
2107 (or pos (js2-current-token-beg))
2108 (or len (js2-current-token-len))
2109 face)
2110 js2-parsed-warnings)))
2111
2112 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2113 (if js2-compiler-strict-mode
2114 (js2-report-warning msg-id msg-arg beg
2115 (and beg end (- end beg)))))
2116
2117 (put 'js2-syntax-error 'error-conditions
2118 '(error syntax-error js2-syntax-error))
2119 (put 'js2-syntax-error 'error-message "Syntax error")
2120
2121 (put 'js2-parse-error 'error-conditions
2122 '(error parse-error js2-parse-error))
2123 (put 'js2-parse-error 'error-message "Parse error")
2124
2125 (defmacro js2-clear-flag (flags flag)
2126 `(setq ,flags (logand ,flags (lognot ,flag))))
2127
2128 (defmacro js2-set-flag (flags flag)
2129 "Logical-or FLAG into FLAGS."
2130 `(setq ,flags (logior ,flags ,flag)))
2131
2132 (defsubst js2-flag-set-p (flags flag)
2133 (/= 0 (logand flags flag)))
2134
2135 (defsubst js2-flag-not-set-p (flags flag)
2136 (zerop (logand flags flag)))
2137
2138 ;;; AST struct and function definitions
2139
2140 ;; flags for ast node property 'member-type (used for e4x operators)
2141 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2142 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2143 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2144
2145 (defsubst js2-relpos (pos anchor)
2146 "Convert POS to be relative to ANCHOR.
2147 If POS is nil, returns nil."
2148 (and pos (- pos anchor)))
2149
2150 (defun js2-make-pad (indent)
2151 (if (zerop indent)
2152 ""
2153 (make-string (* indent js2-basic-offset) ? )))
2154
2155 (defun js2-visit-ast (node callback)
2156 "Visit every node in ast NODE with visitor CALLBACK.
2157
2158 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2159 called twice: once to visit the node, and again after all the node's
2160 children have been processed. The END-P argument is nil on the first
2161 call and non-nil on the second call. The return value of the callback
2162 affects the traversal: if non-nil, the children of NODE are processed.
2163 If the callback returns nil, or if the node has no children, then the
2164 callback is called immediately with a non-nil END-P argument.
2165
2166 The node traversal is approximately lexical-order, although there
2167 are currently no guarantees around this."
2168 (when node
2169 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2170 ;; visit the node
2171 (when (funcall callback node nil)
2172 ;; visit the kids
2173 (cond
2174 ((eq vfunc 'js2-visit-none)
2175 nil) ; don't even bother calling it
2176 ;; Each AST node type has to define a `js2-visitor' function
2177 ;; that takes a node and a callback, and calls `js2-visit-ast'
2178 ;; on each child of the node.
2179 (vfunc
2180 (funcall vfunc node callback))
2181 (t
2182 (error "%s does not define a visitor-traversal function"
2183 (aref node 0)))))
2184 ;; call the end-visit
2185 (funcall callback node t))))
2186
2187 (cl-defstruct (js2-node
2188 (:constructor nil)) ; abstract
2189 "Base AST node type."
2190 (type -1) ; token type
2191 (pos -1) ; start position of this AST node in parsed input
2192 (len 1) ; num characters spanned by the node
2193 props ; optional node property list (an alist)
2194 parent) ; link to parent node; null for root
2195
2196 (defsubst js2-node-get-prop (node prop &optional default)
2197 (or (cadr (assoc prop (js2-node-props node))) default))
2198
2199 (defsubst js2-node-set-prop (node prop value)
2200 (setf (js2-node-props node)
2201 (cons (list prop value) (js2-node-props node))))
2202
2203 (defun js2-fixup-starts (n nodes)
2204 "Adjust the start positions of NODES to be relative to N.
2205 Any node in the list may be nil, for convenience."
2206 (dolist (node nodes)
2207 (when node
2208 (setf (js2-node-pos node) (- (js2-node-pos node)
2209 (js2-node-pos n))))))
2210
2211 (defun js2-node-add-children (parent &rest nodes)
2212 "Set parent node of NODES to PARENT, and return PARENT.
2213 Does nothing if we're not recording parent links.
2214 If any given node in NODES is nil, doesn't record that link."
2215 (js2-fixup-starts parent nodes)
2216 (dolist (node nodes)
2217 (and node
2218 (setf (js2-node-parent node) parent))))
2219
2220 ;; Non-recursive since it's called a frightening number of times.
2221 (defun js2-node-abs-pos (n)
2222 (let ((pos (js2-node-pos n)))
2223 (while (setq n (js2-node-parent n))
2224 (setq pos (+ pos (js2-node-pos n))))
2225 pos))
2226
2227 (defsubst js2-node-abs-end (n)
2228 "Return absolute buffer position of end of N."
2229 (+ (js2-node-abs-pos n) (js2-node-len n)))
2230
2231 ;; It's important to make sure block nodes have a Lisp list for the
2232 ;; child nodes, to limit printing recursion depth in an AST that
2233 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2234 ;; a sufficiently large vector tree.
2235
2236 (cl-defstruct (js2-block-node
2237 (:include js2-node)
2238 (:constructor nil)
2239 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2240 (pos (js2-current-token-beg))
2241 len
2242 props
2243 kids)))
2244 "A block of statements."
2245 kids) ; a Lisp list of the child statement nodes
2246
2247 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2248 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2249
2250 (defun js2-visit-block (ast callback)
2251 "Visit the `js2-block-node' children of AST."
2252 (dolist (kid (js2-block-node-kids ast))
2253 (js2-visit-ast kid callback)))
2254
2255 (defun js2-print-block (n i)
2256 (let ((pad (js2-make-pad i)))
2257 (insert pad "{\n")
2258 (dolist (kid (js2-block-node-kids n))
2259 (js2-print-ast kid (1+ i)))
2260 (insert pad "}")))
2261
2262 (cl-defstruct (js2-scope
2263 (:include js2-block-node)
2264 (:constructor nil)
2265 (:constructor make-js2-scope (&key (type js2-BLOCK)
2266 (pos (js2-current-token-beg))
2267 len
2268 kids)))
2269 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2270 ;; I don't have one of those handy, so I'll use an alist for now.
2271 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2272 ;; and is much lighter-weight to construct (both CPU and mem).
2273 ;; The keys are interned strings (symbols) for faster lookup.
2274 ;; Should switch to hybrid alist/hashtable eventually.
2275 symbol-table ; an alist of (symbol . js2-symbol)
2276 parent-scope ; a `js2-scope'
2277 top) ; top-level `js2-scope' (script/function)
2278
2279 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2280 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2281
2282 (defun js2-node-get-enclosing-scope (node)
2283 "Return the innermost `js2-scope' node surrounding NODE.
2284 Returns nil if there is no enclosing scope node."
2285 (while (and (setq node (js2-node-parent node))
2286 (not (js2-scope-p node))))
2287 node)
2288
2289 (defun js2-get-defining-scope (scope name &optional point)
2290 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2291 Returns `js2-scope' in which NAME is defined, or nil if not found.
2292
2293 If POINT is non-nil, and if the found declaration type is
2294 `js2-LET', also check that the declaration node is before POINT."
2295 (let ((sym (if (symbolp name)
2296 name
2297 (intern name)))
2298 result
2299 (continue t))
2300 (while (and scope continue)
2301 (if (or
2302 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2303 (and entry
2304 (or (not point)
2305 (not (eq js2-LET (js2-symbol-decl-type entry)))
2306 (>= point
2307 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2308 (and (eq sym 'arguments)
2309 (js2-function-node-p scope)))
2310 (setq continue nil
2311 result scope)
2312 (setq scope (js2-scope-parent-scope scope))))
2313 result))
2314
2315 (defun js2-scope-get-symbol (scope name)
2316 "Return symbol table entry for NAME in SCOPE.
2317 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2318 (and (js2-scope-symbol-table scope)
2319 (cdr (assq (if (symbolp name)
2320 name
2321 (intern name))
2322 (js2-scope-symbol-table scope)))))
2323
2324 (defun js2-scope-put-symbol (scope name symbol)
2325 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2326 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2327 (let* ((table (js2-scope-symbol-table scope))
2328 (sym (if (symbolp name) name (intern name)))
2329 (entry (assq sym table)))
2330 (if entry
2331 (setcdr entry symbol)
2332 (push (cons sym symbol)
2333 (js2-scope-symbol-table scope)))))
2334
2335 (cl-defstruct (js2-symbol
2336 (:constructor nil)
2337 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2338 "A symbol table entry."
2339 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2340 ;; js2-LET, or js2-CONST
2341 decl-type
2342 name ; string
2343 ast-node) ; a `js2-node'
2344
2345 (cl-defstruct (js2-error-node
2346 (:include js2-node)
2347 (:constructor nil) ; silence emacs21 byte-compiler
2348 (:constructor make-js2-error-node (&key (type js2-ERROR)
2349 (pos (js2-current-token-beg))
2350 len)))
2351 "AST node representing a parse error.")
2352
2353 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2354 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2355
2356 (cl-defstruct (js2-script-node
2357 (:include js2-scope)
2358 (:constructor nil)
2359 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2360 (pos (js2-current-token-beg))
2361 len
2362 ;; FIXME: What are those?
2363 var-decls
2364 fun-decls)))
2365 functions ; Lisp list of nested functions
2366 regexps ; Lisp list of (string . flags)
2367 symbols ; alist (every symbol gets unique index)
2368 (param-count 0)
2369 var-names ; vector of string names
2370 consts ; bool-vector matching var-decls
2371 (temp-number 0)) ; for generating temp variables
2372
2373 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2374 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2375
2376 (defun js2-print-script (node indent)
2377 (dolist (kid (js2-block-node-kids node))
2378 (js2-print-ast kid indent)))
2379
2380 (cl-defstruct (js2-ast-root
2381 (:include js2-script-node)
2382 (:constructor nil)
2383 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2384 (pos (js2-current-token-beg))
2385 len
2386 buffer)))
2387 "The root node of a js2 AST."
2388 buffer ; the source buffer from which the code was parsed
2389 comments ; a Lisp list of comments, ordered by start position
2390 errors ; a Lisp list of errors found during parsing
2391 warnings ; a Lisp list of warnings found during parsing
2392 node-count) ; number of nodes in the tree, including the root
2393
2394 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2395 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2396
2397 (defun js2-visit-ast-root (ast callback)
2398 (dolist (kid (js2-ast-root-kids ast))
2399 (js2-visit-ast kid callback))
2400 (dolist (comment (js2-ast-root-comments ast))
2401 (js2-visit-ast comment callback)))
2402
2403 (cl-defstruct (js2-comment-node
2404 (:include js2-node)
2405 (:constructor nil)
2406 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2407 (pos (js2-current-token-beg))
2408 len
2409 format)))
2410 format) ; 'line, 'block, 'jsdoc or 'html
2411
2412 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2413 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2414
2415 (defun js2-print-comment (n i)
2416 ;; We really ought to link end-of-line comments to their nodes.
2417 ;; Or maybe we could add a new comment type, 'endline.
2418 (insert (js2-make-pad i)
2419 (js2-node-string n)))
2420
2421 (cl-defstruct (js2-expr-stmt-node
2422 (:include js2-node)
2423 (:constructor nil)
2424 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2425 (pos js2-ts-cursor)
2426 len
2427 expr)))
2428 "An expression statement."
2429 expr)
2430
2431 (defsubst js2-expr-stmt-node-set-has-result (node)
2432 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2433 (setf (js2-node-type node) js2-EXPR_RESULT))
2434
2435 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2436 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2437
2438 (defun js2-visit-expr-stmt-node (n v)
2439 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2440
2441 (defun js2-print-expr-stmt-node (n indent)
2442 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2443 (insert ";\n"))
2444
2445 (cl-defstruct (js2-loop-node
2446 (:include js2-scope)
2447 (:constructor nil))
2448 "Abstract supertype of loop nodes."
2449 body ; a `js2-block-node'
2450 lp ; position of left-paren, nil if omitted
2451 rp) ; position of right-paren, nil if omitted
2452
2453 (cl-defstruct (js2-do-node
2454 (:include js2-loop-node)
2455 (:constructor nil)
2456 (:constructor make-js2-do-node (&key (type js2-DO)
2457 (pos (js2-current-token-beg))
2458 len
2459 body
2460 condition
2461 while-pos
2462 lp
2463 rp)))
2464 "AST node for do-loop."
2465 condition ; while (expression)
2466 while-pos) ; buffer position of 'while' keyword
2467
2468 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2469 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2470
2471 (defun js2-visit-do-node (n v)
2472 (js2-visit-ast (js2-do-node-body n) v)
2473 (js2-visit-ast (js2-do-node-condition n) v))
2474
2475 (defun js2-print-do-node (n i)
2476 (let ((pad (js2-make-pad i)))
2477 (insert pad "do {\n")
2478 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2479 (js2-print-ast kid (1+ i)))
2480 (insert pad "} while (")
2481 (js2-print-ast (js2-do-node-condition n) 0)
2482 (insert ");\n")))
2483
2484 (cl-defstruct (js2-export-node
2485 (:include js2-node)
2486 (:constructor nil)
2487 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2488 (pos (js2-current-token-beg))
2489 len
2490 exports-list
2491 from-clause
2492 declaration
2493 default)))
2494 "AST node for an export statement. There are many things that can be exported,
2495 so many of its properties will be nil.
2496 "
2497 exports-list ; lisp list of js2-export-binding-node to export
2498 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2499 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2500 default) ; js2-function-node or js2-assign-node
2501
2502 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2503 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2504
2505 (defun js2-visit-export-node (n v)
2506 (let ((exports-list (js2-export-node-exports-list n))
2507 (from (js2-export-node-from-clause n))
2508 (declaration (js2-export-node-declaration n))
2509 (default (js2-export-node-default n)))
2510 (when exports-list
2511 (dolist (export exports-list)
2512 (js2-visit-ast export v)))
2513 (when from
2514 (js2-visit-ast from v))
2515 (when declaration
2516 (js2-visit-ast declaration v))
2517 (when default
2518 (js2-visit-ast default v))))
2519
2520 (defun js2-print-export-node (n i)
2521 (let ((pad (js2-make-pad i))
2522 (exports-list (js2-export-node-exports-list n))
2523 (from (js2-export-node-from-clause n))
2524 (declaration (js2-export-node-declaration n))
2525 (default (js2-export-node-default n)))
2526 (insert pad "export ")
2527 (cond
2528 (default
2529 (insert "default ")
2530 (js2-print-ast default i))
2531 (declaration
2532 (js2-print-ast declaration i))
2533 ((and exports-list from)
2534 (js2-print-named-imports exports-list)
2535 (insert " ")
2536 (js2-print-from-clause from))
2537 (from
2538 (insert "* ")
2539 (js2-print-from-clause from))
2540 (exports-list
2541 (js2-print-named-imports exports-list)))
2542 (insert ";\n")))
2543
2544 (cl-defstruct (js2-while-node
2545 (:include js2-loop-node)
2546 (:constructor nil)
2547 (:constructor make-js2-while-node (&key (type js2-WHILE)
2548 (pos (js2-current-token-beg))
2549 len body
2550 condition lp
2551 rp)))
2552 "AST node for while-loop."
2553 condition) ; while-condition
2554
2555 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2556 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2557
2558 (defun js2-visit-while-node (n v)
2559 (js2-visit-ast (js2-while-node-condition n) v)
2560 (js2-visit-ast (js2-while-node-body n) v))
2561
2562 (defun js2-print-while-node (n i)
2563 (let ((pad (js2-make-pad i)))
2564 (insert pad "while (")
2565 (js2-print-ast (js2-while-node-condition n) 0)
2566 (insert ") {\n")
2567 (js2-print-body (js2-while-node-body n) (1+ i))
2568 (insert pad "}\n")))
2569
2570 (cl-defstruct (js2-for-node
2571 (:include js2-loop-node)
2572 (:constructor nil)
2573 (:constructor make-js2-for-node (&key (type js2-FOR)
2574 (pos js2-ts-cursor)
2575 len body init
2576 condition
2577 update lp rp)))
2578 "AST node for a C-style for-loop."
2579 init ; initialization expression
2580 condition ; loop condition
2581 update) ; update clause
2582
2583 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2584 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2585
2586 (defun js2-visit-for-node (n v)
2587 (js2-visit-ast (js2-for-node-init n) v)
2588 (js2-visit-ast (js2-for-node-condition n) v)
2589 (js2-visit-ast (js2-for-node-update n) v)
2590 (js2-visit-ast (js2-for-node-body n) v))
2591
2592 (defun js2-print-for-node (n i)
2593 (let ((pad (js2-make-pad i)))
2594 (insert pad "for (")
2595 (js2-print-ast (js2-for-node-init n) 0)
2596 (insert "; ")
2597 (js2-print-ast (js2-for-node-condition n) 0)
2598 (insert "; ")
2599 (js2-print-ast (js2-for-node-update n) 0)
2600 (insert ") {\n")
2601 (js2-print-body (js2-for-node-body n) (1+ i))
2602 (insert pad "}\n")))
2603
2604 (cl-defstruct (js2-for-in-node
2605 (:include js2-loop-node)
2606 (:constructor nil)
2607 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2608 (pos js2-ts-cursor)
2609 len body
2610 iterator
2611 object
2612 in-pos
2613 each-pos
2614 foreach-p forof-p
2615 lp rp)))
2616 "AST node for a for..in loop."
2617 iterator ; [var] foo in ...
2618 object ; object over which we're iterating
2619 in-pos ; buffer position of 'in' keyword
2620 each-pos ; buffer position of 'each' keyword, if foreach-p
2621 foreach-p ; t if it's a for-each loop
2622 forof-p) ; t if it's a for-of loop
2623
2624 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2625 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2626
2627 (defun js2-visit-for-in-node (n v)
2628 (js2-visit-ast (js2-for-in-node-iterator n) v)
2629 (js2-visit-ast (js2-for-in-node-object n) v)
2630 (js2-visit-ast (js2-for-in-node-body n) v))
2631
2632 (defun js2-print-for-in-node (n i)
2633 (let ((pad (js2-make-pad i))
2634 (foreach (js2-for-in-node-foreach-p n))
2635 (forof (js2-for-in-node-forof-p n)))
2636 (insert pad "for ")
2637 (if foreach
2638 (insert "each "))
2639 (insert "(")
2640 (js2-print-ast (js2-for-in-node-iterator n) 0)
2641 (insert (if forof " of " " in "))
2642 (js2-print-ast (js2-for-in-node-object n) 0)
2643 (insert ") {\n")
2644 (js2-print-body (js2-for-in-node-body n) (1+ i))
2645 (insert pad "}\n")))
2646
2647 (cl-defstruct (js2-return-node
2648 (:include js2-node)
2649 (:constructor nil)
2650 (:constructor make-js2-return-node (&key (type js2-RETURN)
2651 (pos js2-ts-cursor)
2652 len
2653 retval)))
2654 "AST node for a return statement."
2655 retval) ; expression to return, or 'undefined
2656
2657 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2658 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2659
2660 (defun js2-visit-return-node (n v)
2661 (js2-visit-ast (js2-return-node-retval n) v))
2662
2663 (defun js2-print-return-node (n i)
2664 (insert (js2-make-pad i) "return")
2665 (when (js2-return-node-retval n)
2666 (insert " ")
2667 (js2-print-ast (js2-return-node-retval n) 0))
2668 (insert ";\n"))
2669
2670 (cl-defstruct (js2-if-node
2671 (:include js2-node)
2672 (:constructor nil)
2673 (:constructor make-js2-if-node (&key (type js2-IF)
2674 (pos js2-ts-cursor)
2675 len condition
2676 then-part
2677 else-pos
2678 else-part lp
2679 rp)))
2680 "AST node for an if-statement."
2681 condition ; expression
2682 then-part ; statement or block
2683 else-pos ; optional buffer position of 'else' keyword
2684 else-part ; optional statement or block
2685 lp ; position of left-paren, nil if omitted
2686 rp) ; position of right-paren, nil if omitted
2687
2688 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2689 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2690
2691 (defun js2-visit-if-node (n v)
2692 (js2-visit-ast (js2-if-node-condition n) v)
2693 (js2-visit-ast (js2-if-node-then-part n) v)
2694 (js2-visit-ast (js2-if-node-else-part n) v))
2695
2696 (defun js2-print-if-node (n i)
2697 (let ((pad (js2-make-pad i))
2698 (then-part (js2-if-node-then-part n))
2699 (else-part (js2-if-node-else-part n)))
2700 (insert pad "if (")
2701 (js2-print-ast (js2-if-node-condition n) 0)
2702 (insert ") {\n")
2703 (js2-print-body then-part (1+ i))
2704 (insert pad "}")
2705 (cond
2706 ((not else-part)
2707 (insert "\n"))
2708 ((js2-if-node-p else-part)
2709 (insert " else ")
2710 (js2-print-body else-part i))
2711 (t
2712 (insert " else {\n")
2713 (js2-print-body else-part (1+ i))
2714 (insert pad "}\n")))))
2715
2716 (cl-defstruct (js2-export-binding-node
2717 (:include js2-node)
2718 (:constructor nil)
2719 (:constructor make-js2-export-binding-node (&key (type -1)
2720 pos
2721 len
2722 local-name
2723 extern-name)))
2724 "AST node for an external symbol binding.
2725 It contains a local-name node which is the name of the value in the
2726 current scope, and extern-name which is the name of the value in the
2727 imported or exported scope. By default these are the same, but if the
2728 name is aliased as in {foo as bar}, it would have an extern-name node
2729 containing 'foo' and a local-name node containing 'bar'."
2730 local-name ; js2-name-node with the variable name in this scope
2731 extern-name) ; js2-name-node with the value name in the exporting module
2732
2733 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2734 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2735
2736 (defun js2-visit-extern-binding (n v)
2737 "Visit an extern binding node. First visit the local-name, and, if
2738 different, visit the extern-name."
2739 (let ((local-name (js2-export-binding-node-local-name n))
2740 (extern-name (js2-export-binding-node-extern-name n)))
2741 (when local-name
2742 (js2-visit-ast local-name v))
2743 (when (not (equal local-name extern-name))
2744 (js2-visit-ast extern-name v))))
2745
2746 (defun js2-print-extern-binding (n _i)
2747 "Print a representation of a single extern binding. E.g. 'foo' or
2748 'foo as bar'."
2749 (let ((local-name (js2-export-binding-node-local-name n))
2750 (extern-name (js2-export-binding-node-extern-name n)))
2751 (insert (js2-name-node-name extern-name))
2752 (when (not (equal local-name extern-name))
2753 (insert " as ")
2754 (insert (js2-name-node-name local-name)))))
2755
2756
2757 (cl-defstruct (js2-import-node
2758 (:include js2-node)
2759 (:constructor nil)
2760 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2761 (pos (js2-current-token-beg))
2762 len
2763 import
2764 from
2765 module-id)))
2766 "AST node for an import statement. It follows the form
2767
2768 import ModuleSpecifier;
2769 import ImportClause FromClause;"
2770 import ; js2-import-clause-node specifying which names are to imported.
2771 from ; js2-from-clause-node indicating the module from which to import.
2772 module-id) ; module-id of the import. E.g. 'src/mylib'.
2773
2774 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2775 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2776
2777 (defun js2-visit-import (n v)
2778 (let ((import-clause (js2-import-node-import n))
2779 (from-clause (js2-import-node-from n)))
2780 (when import-clause
2781 (js2-visit-ast import-clause v))
2782 (when from-clause
2783 (js2-visit-ast from-clause v))))
2784
2785 (defun js2-print-import (n i)
2786 "Prints a representation of the import node"
2787 (let ((pad (js2-make-pad i))
2788 (import-clause (js2-import-node-import n))
2789 (from-clause (js2-import-node-from n))
2790 (module-id (js2-import-node-module-id n)))
2791 (insert pad "import ")
2792 (if import-clause
2793 (progn
2794 (js2-print-import-clause import-clause)
2795 (insert " ")
2796 (js2-print-from-clause from-clause))
2797 (insert "'")
2798 (insert module-id)
2799 (insert "'"))
2800 (insert ";\n")))
2801
2802 (cl-defstruct (js2-import-clause-node
2803 (:include js2-node)
2804 (:constructor nil)
2805 (:constructor make-js2-import-clause-node (&key (type -1)
2806 pos
2807 len
2808 namespace-import
2809 named-imports
2810 default-binding)))
2811 "AST node corresponding to the import clause of an import statement. This is
2812 the portion of the import that bindings names from the external context to the
2813 local context."
2814 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2815 named-imports ; lisp list of js2-export-binding-node for all named imports.
2816 default-binding) ; js2-export-binding-node for the default import binding
2817
2818 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2819 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2820
2821 (defun js2-visit-import-clause (n v)
2822 (let ((ns-import (js2-import-clause-node-namespace-import n))
2823 (named-imports (js2-import-clause-node-named-imports n))
2824 (default (js2-import-clause-node-default-binding n)))
2825 (when ns-import
2826 (js2-visit-ast ns-import v))
2827 (when named-imports
2828 (dolist (import named-imports)
2829 (js2-visit-ast import v)))
2830 (when default
2831 (js2-visit-ast default v))))
2832
2833 (defun js2-print-import-clause (n)
2834 (let ((ns-import (js2-import-clause-node-namespace-import n))
2835 (named-imports (js2-import-clause-node-named-imports n))
2836 (default (js2-import-clause-node-default-binding n)))
2837 (cond
2838 ((and default ns-import)
2839 (js2-print-ast default)
2840 (insert ", ")
2841 (js2-print-namespace-import ns-import))
2842 ((and default named-imports)
2843 (js2-print-ast default)
2844 (insert ", ")
2845 (js2-print-named-imports named-imports))
2846 (default
2847 (js2-print-ast default))
2848 (ns-import
2849 (js2-print-namespace-import ns-import))
2850 (named-imports
2851 (js2-print-named-imports named-imports)))))
2852
2853 (defun js2-print-namespace-import (node)
2854 (insert "* as ")
2855 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2856
2857 (defun js2-print-named-imports (imports)
2858 (insert "{")
2859 (let ((len (length imports))
2860 (n 0))
2861 (while (< n len)
2862 (js2-print-extern-binding (nth n imports) 0)
2863 (unless (= n (- len 1))
2864 (insert ", "))
2865 (setq n (+ n 1))))
2866 (insert "}"))
2867
2868 (cl-defstruct (js2-namespace-import-node
2869 (:include js2-node)
2870 (:constructor nil)
2871 (:constructor make-js2-namespace-import-node (&key (type -1)
2872 pos
2873 len
2874 name)))
2875 "AST node for a complete namespace import.
2876 E.g. the '* as lib' expression in:
2877
2878 import * as lib from 'src/lib'
2879
2880 It contains a single name node referring to the bound name."
2881 name) ; js2-name-node of the bound name.
2882
2883 (defun js2-visit-namespace-import (n v)
2884 (js2-visit-ast (js2-namespace-import-node-name n) v))
2885
2886 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2887 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2888
2889 (cl-defstruct (js2-from-clause-node
2890 (:include js2-node)
2891 (:constructor nil)
2892 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2893 pos
2894 len
2895 module-id
2896 metadata-p)))
2897 "AST node for the from clause in an import or export statement.
2898 E.g. from 'my/module'. It can refere to either an external module, or to the
2899 modules metadata itself."
2900 module-id ; string containing the module specifier.
2901 metadata-p) ; true if this clause refers to the module's metadata
2902
2903 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2904 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2905
2906 (defun js2-print-from-clause (n)
2907 (insert "from ")
2908 (if (js2-from-clause-node-metadata-p n)
2909 (insert "this module")
2910 (insert "'")
2911 (insert (js2-from-clause-node-module-id n))
2912 (insert "'")))
2913
2914 (cl-defstruct (js2-try-node
2915 (:include js2-node)
2916 (:constructor nil)
2917 (:constructor make-js2-try-node (&key (type js2-TRY)
2918 (pos js2-ts-cursor)
2919 len
2920 try-block
2921 catch-clauses
2922 finally-block)))
2923 "AST node for a try-statement."
2924 try-block
2925 catch-clauses ; a Lisp list of `js2-catch-node'
2926 finally-block) ; a `js2-finally-node'
2927
2928 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2929 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2930
2931 (defun js2-visit-try-node (n v)
2932 (js2-visit-ast (js2-try-node-try-block n) v)
2933 (dolist (clause (js2-try-node-catch-clauses n))
2934 (js2-visit-ast clause v))
2935 (js2-visit-ast (js2-try-node-finally-block n) v))
2936
2937 (defun js2-print-try-node (n i)
2938 (let ((pad (js2-make-pad i))
2939 (catches (js2-try-node-catch-clauses n))
2940 (finally (js2-try-node-finally-block n)))
2941 (insert pad "try {\n")
2942 (js2-print-body (js2-try-node-try-block n) (1+ i))
2943 (insert pad "}")
2944 (when catches
2945 (dolist (catch catches)
2946 (js2-print-ast catch i)))
2947 (if finally
2948 (js2-print-ast finally i)
2949 (insert "\n"))))
2950
2951 (cl-defstruct (js2-catch-node
2952 (:include js2-scope)
2953 (:constructor nil)
2954 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2955 (pos js2-ts-cursor)
2956 len
2957 param
2958 guard-kwd
2959 guard-expr
2960 lp rp)))
2961 "AST node for a catch clause."
2962 param ; destructuring form or simple name node
2963 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2964 guard-expr ; catch condition, a `js2-node'
2965 lp ; buffer position of left-paren, nil if omitted
2966 rp) ; buffer position of right-paren, nil if omitted
2967
2968 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2969 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2970
2971 (defun js2-visit-catch-node (n v)
2972 (js2-visit-ast (js2-catch-node-param n) v)
2973 (when (js2-catch-node-guard-kwd n)
2974 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2975 (js2-visit-block n v))
2976
2977 (defun js2-print-catch-node (n i)
2978 (let ((pad (js2-make-pad i))
2979 (guard-kwd (js2-catch-node-guard-kwd n))
2980 (guard-expr (js2-catch-node-guard-expr n)))
2981 (insert " catch (")
2982 (js2-print-ast (js2-catch-node-param n) 0)
2983 (when guard-kwd
2984 (insert " if ")
2985 (js2-print-ast guard-expr 0))
2986 (insert ") {\n")
2987 (js2-print-body n (1+ i))
2988 (insert pad "}")))
2989
2990 (cl-defstruct (js2-finally-node
2991 (:include js2-node)
2992 (:constructor nil)
2993 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2994 (pos js2-ts-cursor)
2995 len body)))
2996 "AST node for a finally clause."
2997 body) ; a `js2-node', often but not always a block node
2998
2999 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3000 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3001
3002 (defun js2-visit-finally-node (n v)
3003 (js2-visit-ast (js2-finally-node-body n) v))
3004
3005 (defun js2-print-finally-node (n i)
3006 (let ((pad (js2-make-pad i)))
3007 (insert " finally {\n")
3008 (js2-print-body (js2-finally-node-body n) (1+ i))
3009 (insert pad "}\n")))
3010
3011 (cl-defstruct (js2-switch-node
3012 (:include js2-node)
3013 (:constructor nil)
3014 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3015 (pos js2-ts-cursor)
3016 len
3017 discriminant
3018 cases lp
3019 rp)))
3020 "AST node for a switch statement."
3021 discriminant ; a `js2-node' (switch expression)
3022 cases ; a Lisp list of `js2-case-node'
3023 lp ; position of open-paren for discriminant, nil if omitted
3024 rp) ; position of close-paren for discriminant, nil if omitted
3025
3026 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3027 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3028
3029 (defun js2-visit-switch-node (n v)
3030 (js2-visit-ast (js2-switch-node-discriminant n) v)
3031 (dolist (c (js2-switch-node-cases n))
3032 (js2-visit-ast c v)))
3033
3034 (defun js2-print-switch-node (n i)
3035 (let ((pad (js2-make-pad i))
3036 (cases (js2-switch-node-cases n)))
3037 (insert pad "switch (")
3038 (js2-print-ast (js2-switch-node-discriminant n) 0)
3039 (insert ") {\n")
3040 (dolist (case cases)
3041 (js2-print-ast case i))
3042 (insert pad "}\n")))
3043
3044 (cl-defstruct (js2-case-node
3045 (:include js2-block-node)
3046 (:constructor nil)
3047 (:constructor make-js2-case-node (&key (type js2-CASE)
3048 (pos js2-ts-cursor)
3049 len kids expr)))
3050 "AST node for a case clause of a switch statement."
3051 expr) ; the case expression (nil for default)
3052
3053 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3054 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3055
3056 (defun js2-visit-case-node (n v)
3057 (js2-visit-ast (js2-case-node-expr n) v)
3058 (js2-visit-block n v))
3059
3060 (defun js2-print-case-node (n i)
3061 (let ((pad (js2-make-pad i))
3062 (expr (js2-case-node-expr n)))
3063 (insert pad)
3064 (if (null expr)
3065 (insert "default:\n")
3066 (insert "case ")
3067 (js2-print-ast expr 0)
3068 (insert ":\n"))
3069 (dolist (kid (js2-case-node-kids n))
3070 (js2-print-ast kid (1+ i)))))
3071
3072 (cl-defstruct (js2-throw-node
3073 (:include js2-node)
3074 (:constructor nil)
3075 (:constructor make-js2-throw-node (&key (type js2-THROW)
3076 (pos js2-ts-cursor)
3077 len expr)))
3078 "AST node for a throw statement."
3079 expr) ; the expression to throw
3080
3081 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3082 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3083
3084 (defun js2-visit-throw-node (n v)
3085 (js2-visit-ast (js2-throw-node-expr n) v))
3086
3087 (defun js2-print-throw-node (n i)
3088 (insert (js2-make-pad i) "throw ")
3089 (js2-print-ast (js2-throw-node-expr n) 0)
3090 (insert ";\n"))
3091
3092 (cl-defstruct (js2-with-node
3093 (:include js2-node)
3094 (:constructor nil)
3095 (:constructor make-js2-with-node (&key (type js2-WITH)
3096 (pos js2-ts-cursor)
3097 len object
3098 body lp rp)))
3099 "AST node for a with-statement."
3100 object
3101 body
3102 lp ; buffer position of left-paren around object, nil if omitted
3103 rp) ; buffer position of right-paren around object, nil if omitted
3104
3105 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3106 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3107
3108 (defun js2-visit-with-node (n v)
3109 (js2-visit-ast (js2-with-node-object n) v)
3110 (js2-visit-ast (js2-with-node-body n) v))
3111
3112 (defun js2-print-with-node (n i)
3113 (let ((pad (js2-make-pad i)))
3114 (insert pad "with (")
3115 (js2-print-ast (js2-with-node-object n) 0)
3116 (insert ") {\n")
3117 (js2-print-body (js2-with-node-body n) (1+ i))
3118 (insert pad "}\n")))
3119
3120 (cl-defstruct (js2-label-node
3121 (:include js2-node)
3122 (:constructor nil)
3123 (:constructor make-js2-label-node (&key (type js2-LABEL)
3124 (pos js2-ts-cursor)
3125 len name)))
3126 "AST node for a statement label or case label."
3127 name ; a string
3128 loop) ; for validating and code-generating continue-to-label
3129
3130 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3131 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3132
3133 (defun js2-print-label (n i)
3134 (insert (js2-make-pad i)
3135 (js2-label-node-name n)
3136 ":\n"))
3137
3138 (cl-defstruct (js2-labeled-stmt-node
3139 (:include js2-node)
3140 (:constructor nil)
3141 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3142 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3143 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3144 (pos js2-ts-cursor)
3145 len labels stmt)))
3146 "AST node for a statement with one or more labels.
3147 Multiple labels for a statement are collapsed into the labels field."
3148 labels ; Lisp list of `js2-label-node'
3149 stmt) ; the statement these labels are for
3150
3151 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3152 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3153
3154 (defun js2-get-label-by-name (lbl-stmt name)
3155 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3156 Returns nil if no such label is in the list."
3157 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3158 result)
3159 (while (and label-list (not result))
3160 (if (string= (js2-label-node-name (car label-list)) name)
3161 (setq result (car label-list))
3162 (setq label-list (cdr label-list))))
3163 result))
3164
3165 (defun js2-visit-labeled-stmt (n v)
3166 (dolist (label (js2-labeled-stmt-node-labels n))
3167 (js2-visit-ast label v))
3168 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3169
3170 (defun js2-print-labeled-stmt (n i)
3171 (dolist (label (js2-labeled-stmt-node-labels n))
3172 (js2-print-ast label i))
3173 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3174
3175 (defun js2-labeled-stmt-node-contains (node label)
3176 "Return t if NODE contains LABEL in its label set.
3177 NODE is a `js2-labels-node'. LABEL is an identifier."
3178 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3179 if (string= label (js2-label-node-name nl))
3180 return t
3181 finally return nil))
3182
3183 (defsubst js2-labeled-stmt-node-add-label (node label)
3184 "Add a `js2-label-node' to the label set for this statement."
3185 (setf (js2-labeled-stmt-node-labels node)
3186 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3187
3188 (cl-defstruct (js2-jump-node
3189 (:include js2-node)
3190 (:constructor nil))
3191 "Abstract supertype of break and continue nodes."
3192 label ; `js2-name-node' for location of label identifier, if present
3193 target) ; target js2-labels-node or loop/switch statement
3194
3195 (defun js2-visit-jump-node (n v)
3196 ;; We don't visit the target, since it's a back-link.
3197 (js2-visit-ast (js2-jump-node-label n) v))
3198
3199 (cl-defstruct (js2-break-node
3200 (:include js2-jump-node)
3201 (:constructor nil)
3202 (:constructor make-js2-break-node (&key (type js2-BREAK)
3203 (pos js2-ts-cursor)
3204 len label target)))
3205 "AST node for a break statement.
3206 The label field is a `js2-name-node', possibly nil, for the named label
3207 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3208 is the target of the break - a label node or enclosing loop/switch statement.")
3209
3210 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3211 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3212
3213 (defun js2-print-break-node (n i)
3214 (insert (js2-make-pad i) "break")
3215 (when (js2-break-node-label n)
3216 (insert " ")
3217 (js2-print-ast (js2-break-node-label n) 0))
3218 (insert ";\n"))
3219
3220 (cl-defstruct (js2-continue-node
3221 (:include js2-jump-node)
3222 (:constructor nil)
3223 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3224 (pos js2-ts-cursor)
3225 len label target)))
3226 "AST node for a continue statement.
3227 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3228 It is nil if continue specifies no label. The target field is the jump target:
3229 a `js2-label-node' or the innermost enclosing loop.")
3230
3231 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3232 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3233
3234 (defun js2-print-continue-node (n i)
3235 (insert (js2-make-pad i) "continue")
3236 (when (js2-continue-node-label n)
3237 (insert " ")
3238 (js2-print-ast (js2-continue-node-label n) 0))
3239 (insert ";\n"))
3240
3241 (cl-defstruct (js2-function-node
3242 (:include js2-script-node)
3243 (:constructor nil)
3244 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3245 (pos js2-ts-cursor)
3246 len
3247 (ftype 'FUNCTION)
3248 (form 'FUNCTION_STATEMENT)
3249 (name "")
3250 params rest-p
3251 body
3252 generator-type
3253 lp rp)))
3254 "AST node for a function declaration.
3255 The `params' field is a Lisp list of nodes. Each node is either a simple
3256 `js2-name-node', or if it's a destructuring-assignment parameter, a
3257 `js2-array-node' or `js2-object-node'."
3258 ftype ; FUNCTION, GETTER or SETTER
3259 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3260 name ; function name (a `js2-name-node', or nil if anonymous)
3261 params ; a Lisp list of destructuring forms or simple name nodes
3262 rest-p ; if t, the last parameter is rest parameter
3263 body ; a `js2-block-node' or expression node (1.8 only)
3264 lp ; position of arg-list open-paren, or nil if omitted
3265 rp ; position of arg-list close-paren, or nil if omitted
3266 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3267 needs-activation ; t if we need an activation object for this frame
3268 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3269 member-expr) ; nonstandard Ecma extension from Rhino
3270
3271 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3272 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3273
3274 (defun js2-visit-function-node (n v)
3275 (js2-visit-ast (js2-function-node-name n) v)
3276 (dolist (p (js2-function-node-params n))
3277 (js2-visit-ast p v))
3278 (js2-visit-ast (js2-function-node-body n) v))
3279
3280 (defun js2-print-function-node (n i)
3281 (let* ((pad (js2-make-pad i))
3282 (method (js2-node-get-prop n 'METHOD_TYPE))
3283 (name (or (js2-function-node-name n)
3284 (js2-function-node-member-expr n)))
3285 (params (js2-function-node-params n))
3286 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3287 (rest-p (js2-function-node-rest-p n))
3288 (body (js2-function-node-body n))
3289 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3290 (unless (or method arrow)
3291 (insert pad "function")
3292 (when (eq (js2-function-node-generator-type n) 'STAR)
3293 (insert "*")))
3294 (when name
3295 (insert " ")
3296 (js2-print-ast name 0))
3297 (insert "(")
3298 (cl-loop with len = (length params)
3299 for param in params
3300 for count from 1
3301 do
3302 (when (and rest-p (= count len))
3303 (insert "..."))
3304 (js2-print-ast param 0)
3305 (when (< count len)
3306 (insert ", ")))
3307 (insert ") ")
3308 (when arrow
3309 (insert "=> "))
3310 (insert "{")
3311 ;; TODO: fix this to be smarter about indenting, etc.
3312 (unless expr
3313 (insert "\n"))
3314 (if (js2-block-node-p body)
3315 (js2-print-body body (1+ i))
3316 (js2-print-ast body 0))
3317 (insert pad "}")
3318 (unless expr
3319 (insert "\n"))))
3320
3321 (defun js2-function-name (node)
3322 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3323 (and (js2-function-node-name node)
3324 (js2-name-node-name (js2-function-node-name node))))
3325
3326 ;; Having this be an expression node makes it more flexible.
3327 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3328 ;; that work better if you assume it's an expression. Whenever we have
3329 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3330 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3331 (cl-defstruct (js2-var-decl-node
3332 (:include js2-node)
3333 (:constructor nil)
3334 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3335 (pos (js2-current-token-beg))
3336 len kids
3337 decl-type)))
3338 "AST node for a variable declaration list (VAR, CONST or LET).
3339 The node bounds differ depending on the declaration type. For VAR or
3340 CONST declarations, the bounds include the var/const keyword. For LET
3341 declarations, the node begins at the position of the first child."
3342 kids ; a Lisp list of `js2-var-init-node' structs.
3343 decl-type) ; js2-VAR, js2-CONST or js2-LET
3344
3345 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3346 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3347
3348 (defun js2-visit-var-decl (n v)
3349 (dolist (kid (js2-var-decl-node-kids n))
3350 (js2-visit-ast kid v)))
3351
3352 (defun js2-print-var-decl (n i)
3353 (let ((pad (js2-make-pad i))
3354 (tt (js2-var-decl-node-decl-type n)))
3355 (insert pad)
3356 (insert (cond
3357 ((= tt js2-VAR) "var ")
3358 ((= tt js2-LET) "let ")
3359 ((= tt js2-CONST) "const ")
3360 (t
3361 (error "malformed var-decl node"))))
3362 (cl-loop with kids = (js2-var-decl-node-kids n)
3363 with len = (length kids)
3364 for kid in kids
3365 for count from 1
3366 do
3367 (js2-print-ast kid 0)
3368 (if (< count len)
3369 (insert ", ")))))
3370
3371 (cl-defstruct (js2-var-init-node
3372 (:include js2-node)
3373 (:constructor nil)
3374 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3375 (pos js2-ts-cursor)
3376 len target
3377 initializer)))
3378 "AST node for a variable declaration.
3379 The type field will be js2-CONST for a const decl."
3380 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3381 initializer) ; initializer expression, a `js2-node'
3382
3383 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3384 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3385
3386 (defun js2-visit-var-init-node (n v)
3387 (js2-visit-ast (js2-var-init-node-target n) v)
3388 (js2-visit-ast (js2-var-init-node-initializer n) v))
3389
3390 (defun js2-print-var-init-node (n i)
3391 (let ((pad (js2-make-pad i))
3392 (name (js2-var-init-node-target n))
3393 (init (js2-var-init-node-initializer n)))
3394 (insert pad)
3395 (js2-print-ast name 0)
3396 (when init
3397 (insert " = ")
3398 (js2-print-ast init 0))))
3399
3400 (cl-defstruct (js2-cond-node
3401 (:include js2-node)
3402 (:constructor nil)
3403 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3404 (pos js2-ts-cursor)
3405 len
3406 test-expr
3407 true-expr
3408 false-expr
3409 q-pos c-pos)))
3410 "AST node for the ternary operator"
3411 test-expr
3412 true-expr
3413 false-expr
3414 q-pos ; buffer position of ?
3415 c-pos) ; buffer position of :
3416
3417 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3418 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3419
3420 (defun js2-visit-cond-node (n v)
3421 (js2-visit-ast (js2-cond-node-test-expr n) v)
3422 (js2-visit-ast (js2-cond-node-true-expr n) v)
3423 (js2-visit-ast (js2-cond-node-false-expr n) v))
3424
3425 (defun js2-print-cond-node (n i)
3426 (let ((pad (js2-make-pad i)))
3427 (insert pad)
3428 (js2-print-ast (js2-cond-node-test-expr n) 0)
3429 (insert " ? ")
3430 (js2-print-ast (js2-cond-node-true-expr n) 0)
3431 (insert " : ")
3432 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3433
3434 (cl-defstruct (js2-infix-node
3435 (:include js2-node)
3436 (:constructor nil)
3437 (:constructor make-js2-infix-node (&key type
3438 (pos js2-ts-cursor)
3439 len op-pos
3440 left right)))
3441 "Represents infix expressions.
3442 Includes assignment ops like `|=', and the comma operator.
3443 The type field inherited from `js2-node' holds the operator."
3444 op-pos ; buffer position where operator begins
3445 left ; any `js2-node'
3446 right) ; any `js2-node'
3447
3448 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3449 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3450
3451 (defun js2-visit-infix-node (n v)
3452 (js2-visit-ast (js2-infix-node-left n) v)
3453 (js2-visit-ast (js2-infix-node-right n) v))
3454
3455 (defconst js2-operator-tokens
3456 (let ((table (make-hash-table :test 'eq))
3457 (tokens
3458 (list (cons js2-IN "in")
3459 (cons js2-TYPEOF "typeof")
3460 (cons js2-INSTANCEOF "instanceof")
3461 (cons js2-DELPROP "delete")
3462 (cons js2-COMMA ",")
3463 (cons js2-COLON ":")
3464 (cons js2-OR "||")
3465 (cons js2-AND "&&")
3466 (cons js2-INC "++")
3467 (cons js2-DEC "--")
3468 (cons js2-BITOR "|")
3469 (cons js2-BITXOR "^")
3470 (cons js2-BITAND "&")
3471 (cons js2-EQ "==")
3472 (cons js2-NE "!=")
3473 (cons js2-LT "<")
3474 (cons js2-LE "<=")
3475 (cons js2-GT ">")
3476 (cons js2-GE ">=")
3477 (cons js2-LSH "<<")
3478 (cons js2-RSH ">>")
3479 (cons js2-URSH ">>>")
3480 (cons js2-ADD "+") ; infix plus
3481 (cons js2-SUB "-") ; infix minus
3482 (cons js2-MUL "*")
3483 (cons js2-DIV "/")
3484 (cons js2-MOD "%")
3485 (cons js2-NOT "!")
3486 (cons js2-BITNOT "~")
3487 (cons js2-POS "+") ; unary plus
3488 (cons js2-NEG "-") ; unary minus
3489 (cons js2-TRIPLEDOT "...")
3490 (cons js2-SHEQ "===") ; shallow equality
3491 (cons js2-SHNE "!==") ; shallow inequality
3492 (cons js2-ASSIGN "=")
3493 (cons js2-ASSIGN_BITOR "|=")
3494 (cons js2-ASSIGN_BITXOR "^=")
3495 (cons js2-ASSIGN_BITAND "&=")
3496 (cons js2-ASSIGN_LSH "<<=")
3497 (cons js2-ASSIGN_RSH ">>=")
3498 (cons js2-ASSIGN_URSH ">>>=")
3499 (cons js2-ASSIGN_ADD "+=")
3500 (cons js2-ASSIGN_SUB "-=")
3501 (cons js2-ASSIGN_MUL "*=")
3502 (cons js2-ASSIGN_DIV "/=")
3503 (cons js2-ASSIGN_MOD "%="))))
3504 (cl-loop for (k . v) in tokens do
3505 (puthash k v table))
3506 table))
3507
3508 (defun js2-print-infix-node (n i)
3509 (let* ((tt (js2-node-type n))
3510 (op (gethash tt js2-operator-tokens)))
3511 (unless op
3512 (error "unrecognized infix operator %s" (js2-node-type n)))
3513 (insert (js2-make-pad i))
3514 (js2-print-ast (js2-infix-node-left n) 0)
3515 (unless (= tt js2-COMMA)
3516 (insert " "))
3517 (insert op)
3518 (insert " ")
3519 (js2-print-ast (js2-infix-node-right n) 0)))
3520
3521 (cl-defstruct (js2-assign-node
3522 (:include js2-infix-node)
3523 (:constructor nil)
3524 (:constructor make-js2-assign-node (&key type
3525 (pos js2-ts-cursor)
3526 len op-pos
3527 left right)))
3528 "Represents any assignment.
3529 The type field holds the actual assignment operator.")
3530
3531 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3532 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3533
3534 (cl-defstruct (js2-unary-node
3535 (:include js2-node)
3536 (:constructor nil)
3537 (:constructor make-js2-unary-node (&key type ; required
3538 (pos js2-ts-cursor)
3539 len operand)))
3540 "AST node type for unary operator nodes.
3541 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3542 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3543 property is added if the operator follows the operand."
3544 operand) ; a `js2-node' expression
3545
3546 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3547 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3548
3549 (defun js2-visit-unary-node (n v)
3550 (js2-visit-ast (js2-unary-node-operand n) v))
3551
3552 (defun js2-print-unary-node (n i)
3553 (let* ((tt (js2-node-type n))
3554 (op (gethash tt js2-operator-tokens))
3555 (postfix (js2-node-get-prop n 'postfix)))
3556 (unless op
3557 (error "unrecognized unary operator %s" tt))
3558 (insert (js2-make-pad i))
3559 (unless postfix
3560 (insert op))
3561 (if (or (= tt js2-TYPEOF)
3562 (= tt js2-DELPROP))
3563 (insert " "))
3564 (js2-print-ast (js2-unary-node-operand n) 0)
3565 (when postfix
3566 (insert op))))
3567
3568 (cl-defstruct (js2-let-node
3569 (:include js2-scope)
3570 (:constructor nil)
3571 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3572 (pos (js2-current-token-beg))
3573 len vars body
3574 lp rp)))
3575 "AST node for a let expression or a let statement.
3576 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3577 vars ; a `js2-var-decl-node'
3578 body ; a `js2-node' representing the expression or body block
3579 lp
3580 rp)
3581
3582 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3583 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3584
3585 (defun js2-visit-let-node (n v)
3586 (js2-visit-ast (js2-let-node-vars n) v)
3587 (js2-visit-ast (js2-let-node-body n) v))
3588
3589 (defun js2-print-let-node (n i)
3590 (insert (js2-make-pad i) "let (")
3591 (let ((p (point)))
3592 (js2-print-ast (js2-let-node-vars n) 0)
3593 (delete-region p (+ p 4)))
3594 (insert ") ")
3595 (js2-print-ast (js2-let-node-body n) i))
3596
3597 (cl-defstruct (js2-keyword-node
3598 (:include js2-node)
3599 (:constructor nil)
3600 (:constructor make-js2-keyword-node (&key type
3601 (pos (js2-current-token-beg))
3602 (len (- js2-ts-cursor pos)))))
3603 "AST node representing a literal keyword such as `null'.
3604 Used for `null', `this', `true', `false' and `debugger'.
3605 The node type is set to js2-NULL, js2-THIS, etc.")
3606
3607 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3608 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3609
3610 (defun js2-print-keyword-node (n i)
3611 (insert (js2-make-pad i)
3612 (let ((tt (js2-node-type n)))
3613 (cond
3614 ((= tt js2-THIS) "this")
3615 ((= tt js2-SUPER) "super")
3616 ((= tt js2-NULL) "null")
3617 ((= tt js2-TRUE) "true")
3618 ((= tt js2-FALSE) "false")
3619 ((= tt js2-DEBUGGER) "debugger")
3620 (t (error "Invalid keyword literal type: %d" tt))))))
3621
3622 (defsubst js2-this-or-super-node-p (node)
3623 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3624 (let ((type (js2-node-type node)))
3625 (or (eq type js2-THIS) (eq type js2-SUPER))))
3626
3627 (cl-defstruct (js2-new-node
3628 (:include js2-node)
3629 (:constructor nil)
3630 (:constructor make-js2-new-node (&key (type js2-NEW)
3631 (pos (js2-current-token-beg))
3632 len target
3633 args initializer
3634 lp rp)))
3635 "AST node for new-expression such as new Foo()."
3636 target ; an identifier or reference
3637 args ; a Lisp list of argument nodes
3638 lp ; position of left-paren, nil if omitted
3639 rp ; position of right-paren, nil if omitted
3640 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3641
3642 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3643 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3644
3645 (defun js2-visit-new-node (n v)
3646 (js2-visit-ast (js2-new-node-target n) v)
3647 (dolist (arg (js2-new-node-args n))
3648 (js2-visit-ast arg v))
3649 (js2-visit-ast (js2-new-node-initializer n) v))
3650
3651 (defun js2-print-new-node (n i)
3652 (insert (js2-make-pad i) "new ")
3653 (js2-print-ast (js2-new-node-target n))
3654 (insert "(")
3655 (js2-print-list (js2-new-node-args n))
3656 (insert ")")
3657 (when (js2-new-node-initializer n)
3658 (insert " ")
3659 (js2-print-ast (js2-new-node-initializer n))))
3660
3661 (cl-defstruct (js2-name-node
3662 (:include js2-node)
3663 (:constructor nil)
3664 (:constructor make-js2-name-node (&key (type js2-NAME)
3665 (pos (js2-current-token-beg))
3666 (len (- js2-ts-cursor
3667 (js2-current-token-beg)))
3668 (name (js2-current-token-string)))))
3669 "AST node for a JavaScript identifier"
3670 name ; a string
3671 scope) ; a `js2-scope' (optional, used for codegen)
3672
3673 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3674 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3675
3676 (defun js2-print-name-node (n i)
3677 (insert (js2-make-pad i)
3678 (js2-name-node-name n)))
3679
3680 (defsubst js2-name-node-length (node)
3681 "Return identifier length of NODE, a `js2-name-node'.
3682 Returns 0 if NODE is nil or its identifier field is nil."
3683 (if node
3684 (length (js2-name-node-name node))
3685 0))
3686
3687 (cl-defstruct (js2-number-node
3688 (:include js2-node)
3689 (:constructor nil)
3690 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3691 (pos (js2-current-token-beg))
3692 (len (- js2-ts-cursor
3693 (js2-current-token-beg)))
3694 (value (js2-current-token-string))
3695 (num-value (js2-token-number
3696 (js2-current-token)))
3697 (num-base (js2-token-number-base
3698 (js2-current-token))))))
3699 "AST node for a number literal."
3700 value ; the original string, e.g. "6.02e23"
3701 num-value ; the parsed number value
3702 num-base) ; the number's base
3703
3704 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3705 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3706
3707 (defun js2-print-number-node (n i)
3708 (insert (js2-make-pad i)
3709 (number-to-string (js2-number-node-num-value n))))
3710
3711 (cl-defstruct (js2-regexp-node
3712 (:include js2-node)
3713 (:constructor nil)
3714 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3715 (pos (js2-current-token-beg))
3716 (len (- js2-ts-cursor
3717 (js2-current-token-beg)))
3718 value flags)))
3719 "AST node for a regular expression literal."
3720 value ; the regexp string, without // delimiters
3721 flags) ; a string of flags, e.g. `mi'.
3722
3723 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3724 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3725
3726 (defun js2-print-regexp (n i)
3727 (insert (js2-make-pad i)
3728 "/"
3729 (js2-regexp-node-value n)
3730 "/")
3731 (if (js2-regexp-node-flags n)
3732 (insert (js2-regexp-node-flags n))))
3733
3734 (cl-defstruct (js2-string-node
3735 (:include js2-node)
3736 (:constructor nil)
3737 (:constructor make-js2-string-node (&key (type js2-STRING)
3738 (pos (js2-current-token-beg))
3739 (len (- js2-ts-cursor
3740 (js2-current-token-beg)))
3741 (value (js2-current-token-string)))))
3742 "String literal.
3743 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3744 You can tell the quote type by looking at the first character."
3745 value) ; the characters of the string, including the quotes
3746
3747 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3748 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3749
3750 (defun js2-print-string-node (n i)
3751 (insert (js2-make-pad i)
3752 (js2-node-string n)))
3753
3754 (cl-defstruct (js2-template-node
3755 (:include js2-node)
3756 (:constructor nil)
3757 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3758 beg len kids)))
3759 "Template literal."
3760 kids) ; `js2-string-node' is used for string segments, other nodes
3761 ; for substitutions inside.
3762
3763 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3764 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3765
3766 (defun js2-visit-template (n callback)
3767 (dolist (kid (js2-template-node-kids n))
3768 (js2-visit-ast kid callback)))
3769
3770 (defun js2-print-template (n i)
3771 (insert (js2-make-pad i))
3772 (dolist (kid (js2-template-node-kids n))
3773 (if (js2-string-node-p kid)
3774 (insert (js2-node-string kid))
3775 (js2-print-ast kid))))
3776
3777 (cl-defstruct (js2-tagged-template-node
3778 (:include js2-node)
3779 (:constructor nil)
3780 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3781 beg len tag template)))
3782 "Tagged template literal."
3783 tag ; `js2-node' with the tag expression.
3784 template) ; `js2-template-node' with the template.
3785
3786 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3787 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3788
3789 (defun js2-visit-tagged-template (n callback)
3790 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3791 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3792
3793 (defun js2-print-tagged-template (n i)
3794 (insert (js2-make-pad i))
3795 (js2-print-ast (js2-tagged-template-node-tag n))
3796 (js2-print-ast (js2-tagged-template-node-template n)))
3797
3798 (cl-defstruct (js2-array-node
3799 (:include js2-node)
3800 (:constructor nil)
3801 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3802 (pos js2-ts-cursor)
3803 len elems)))
3804 "AST node for an array literal."
3805 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3806
3807 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3808 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3809
3810 (defun js2-visit-array-node (n v)
3811 (dolist (e (js2-array-node-elems n))
3812 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3813
3814 (defun js2-print-array-node (n i)
3815 (insert (js2-make-pad i) "[")
3816 (let ((elems (js2-array-node-elems n)))
3817 (js2-print-list elems)
3818 (when (and elems (null (car (last elems))))
3819 (insert ",")))
3820 (insert "]"))
3821
3822 (cl-defstruct (js2-class-node
3823 (:include js2-node)
3824 (:constructor nil)
3825 (:constructor make-js2-class-node (&key (type js2-CLASS)
3826 (pos js2-ts-cursor)
3827 (form 'CLASS_STATEMENT)
3828 (name "")
3829 extends len elems)))
3830 "AST node for an class expression.
3831 `elems' is a list of `js2-object-prop-node', and `extends' is an
3832 optional `js2-expr-node'"
3833 form ; CLASS_{STATEMENT|EXPRESSION}
3834 name ; class name (a `js2-node-name', or nil if anonymous)
3835 extends ; class heritage (a `js2-expr-node', or nil if none)
3836 elems)
3837
3838 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3839 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3840
3841 (defun js2-visit-class-node (n v)
3842 (js2-visit-ast (js2-class-node-name n) v)
3843 (js2-visit-ast (js2-class-node-extends n) v)
3844 (dolist (e (js2-class-node-elems n))
3845 (js2-visit-ast e v)))
3846
3847 (defun js2-print-class-node (n i)
3848 (let* ((pad (js2-make-pad i))
3849 (name (js2-class-node-name n))
3850 (extends (js2-class-node-extends n))
3851 (elems (js2-class-node-elems n)))
3852 (insert pad "class")
3853 (when name
3854 (insert " ")
3855 (js2-print-ast name 0))
3856 (when extends
3857 (insert " extends ")
3858 (js2-print-ast extends))
3859 (insert " {")
3860 (dolist (elem elems)
3861 (insert "\n")
3862 (if (js2-node-get-prop elem 'STATIC)
3863 (progn (insert (js2-make-pad (1+ i)) "static ")
3864 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3865 (js2-print-ast elem (1+ i))))
3866 (insert "\n" pad "}")))
3867
3868 (cl-defstruct (js2-object-node
3869 (:include js2-node)
3870 (:constructor nil)
3871 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3872 (pos js2-ts-cursor)
3873 len
3874 elems)))
3875 "AST node for an object literal expression.
3876 `elems' is a list of `js2-object-prop-node'."
3877 elems)
3878
3879 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3880 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3881
3882 (defun js2-visit-object-node (n v)
3883 (dolist (e (js2-object-node-elems n))
3884 (js2-visit-ast e v)))
3885
3886 (defun js2-print-object-node (n i)
3887 (insert (js2-make-pad i) "{")
3888 (js2-print-list (js2-object-node-elems n))
3889 (insert "}"))
3890
3891 (cl-defstruct (js2-computed-prop-name-node
3892 (:include js2-node)
3893 (:constructor nil)
3894 (:constructor make-js2-computed-prop-name-node
3895 (&key
3896 (type js2-LB)
3897 expr
3898 (pos (js2-current-token-beg))
3899 (len (- js2-ts-cursor
3900 (js2-current-token-beg))))))
3901 "AST node for a `ComputedPropertyName'."
3902 expr)
3903
3904 (put 'cl-struct-js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
3905 (put 'cl-struct-js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
3906
3907 (defun js2-visit-computed-prop-name-node (n v)
3908 (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
3909
3910 (defun js2-print-computed-prop-name-node (n i)
3911 (insert (js2-make-pad i) "[")
3912 (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
3913 (insert "]"))
3914
3915 (cl-defstruct (js2-object-prop-node
3916 (:include js2-infix-node)
3917 (:constructor nil)
3918 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3919 (pos js2-ts-cursor)
3920 len left
3921 right op-pos)))
3922 "AST node for an object literal prop:value entry.
3923 The `left' field is the property: a name node, string node,
3924 number node or expression node. The `right' field is a
3925 `js2-node' representing the initializer value. If the property
3926 is abbreviated, the node's `SHORTHAND' property is non-nil and
3927 both fields have the same value.")
3928
3929 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3930 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3931
3932 (defun js2-print-object-prop-node (n i)
3933 (let* ((left (js2-object-prop-node-left n))
3934 (right (js2-object-prop-node-right n)))
3935 (js2-print-ast left i)
3936 (if (not (js2-node-get-prop n 'SHORTHAND))
3937 (progn
3938 (insert ": ")
3939 (js2-print-ast right 0)))))
3940
3941 (cl-defstruct (js2-method-node
3942 (:include js2-infix-node)
3943 (:constructor nil)
3944 (:constructor make-js2-method-node (&key type ; GET, SET, or FUNCTION
3945 (pos js2-ts-cursor)
3946 len left right)))
3947 "AST node for a method in an object literal or a class body.
3948 The `left' field is the `js2-name-node' naming the method.
3949 The `right' field is always an anonymous `js2-function-node' with a node
3950 property `METHOD_TYPE' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3951
3952 (put 'cl-struct-js2-method-node 'js2-visitor 'js2-visit-infix-node)
3953 (put 'cl-struct-js2-method-node 'js2-printer 'js2-print-method)
3954
3955 (defun js2-print-method (n i)
3956 (let* ((pad (js2-make-pad i))
3957 (left (js2-method-node-left n))
3958 (right (js2-method-node-right n)))
3959 (insert pad)
3960 (if (/= (js2-node-type n) js2-FUNCTION)
3961 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3962 (when (and (js2-function-node-p right)
3963 (eq 'STAR (js2-function-node-generator-type right)))
3964 (insert "*"))
3965 (js2-print-ast left 0)
3966 (js2-print-ast right 0)))
3967
3968 (cl-defstruct (js2-prop-get-node
3969 (:include js2-infix-node)
3970 (:constructor nil)
3971 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3972 (pos js2-ts-cursor)
3973 len left right)))
3974 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3975
3976 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3977 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3978
3979 (defun js2-visit-prop-get-node (n v)
3980 (js2-visit-ast (js2-prop-get-node-left n) v)
3981 (js2-visit-ast (js2-prop-get-node-right n) v))
3982
3983 (defun js2-print-prop-get-node (n i)
3984 (insert (js2-make-pad i))
3985 (js2-print-ast (js2-prop-get-node-left n) 0)
3986 (insert ".")
3987 (js2-print-ast (js2-prop-get-node-right n) 0))
3988
3989 (cl-defstruct (js2-elem-get-node
3990 (:include js2-node)
3991 (:constructor nil)
3992 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3993 (pos js2-ts-cursor)
3994 len target element
3995 lb rb)))
3996 "AST node for an array index expression such as foo[bar]."
3997 target ; a `js2-node' - the expression preceding the "."
3998 element ; a `js2-node' - the expression in brackets
3999 lb ; position of left-bracket, nil if omitted
4000 rb) ; position of right-bracket, nil if omitted
4001
4002 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4003 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4004
4005 (defun js2-visit-elem-get-node (n v)
4006 (js2-visit-ast (js2-elem-get-node-target n) v)
4007 (js2-visit-ast (js2-elem-get-node-element n) v))
4008
4009 (defun js2-print-elem-get-node (n i)
4010 (insert (js2-make-pad i))
4011 (js2-print-ast (js2-elem-get-node-target n) 0)
4012 (insert "[")
4013 (js2-print-ast (js2-elem-get-node-element n) 0)
4014 (insert "]"))
4015
4016 (cl-defstruct (js2-call-node
4017 (:include js2-node)
4018 (:constructor nil)
4019 (:constructor make-js2-call-node (&key (type js2-CALL)
4020 (pos js2-ts-cursor)
4021 len target args
4022 lp rp)))
4023 "AST node for a JavaScript function call."
4024 target ; a `js2-node' evaluating to the function to call
4025 args ; a Lisp list of `js2-node' arguments
4026 lp ; position of open-paren, or nil if missing
4027 rp) ; position of close-paren, or nil if missing
4028
4029 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4030 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4031
4032 (defun js2-visit-call-node (n v)
4033 (js2-visit-ast (js2-call-node-target n) v)
4034 (dolist (arg (js2-call-node-args n))
4035 (js2-visit-ast arg v)))
4036
4037 (defun js2-print-call-node (n i)
4038 (insert (js2-make-pad i))
4039 (js2-print-ast (js2-call-node-target n) 0)
4040 (insert "(")
4041 (js2-print-list (js2-call-node-args n))
4042 (insert ")"))
4043
4044 (cl-defstruct (js2-yield-node
4045 (:include js2-node)
4046 (:constructor nil)
4047 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4048 (pos js2-ts-cursor)
4049 len value star-p)))
4050 "AST node for yield statement or expression."
4051 star-p ; whether it's yield*
4052 value) ; optional: value to be yielded
4053
4054 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4055 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4056
4057 (defun js2-visit-yield-node (n v)
4058 (js2-visit-ast (js2-yield-node-value n) v))
4059
4060 (defun js2-print-yield-node (n i)
4061 (insert (js2-make-pad i))
4062 (insert "yield")
4063 (when (js2-yield-node-star-p n)
4064 (insert "*"))
4065 (when (js2-yield-node-value n)
4066 (insert " ")
4067 (js2-print-ast (js2-yield-node-value n) 0)))
4068
4069 (cl-defstruct (js2-paren-node
4070 (:include js2-node)
4071 (:constructor nil)
4072 (:constructor make-js2-paren-node (&key (type js2-LP)
4073 (pos js2-ts-cursor)
4074 len expr)))
4075 "AST node for a parenthesized expression.
4076 In particular, used when the parens are syntactically optional,
4077 as opposed to required parens such as those enclosing an if-conditional."
4078 expr) ; `js2-node'
4079
4080 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4081 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4082
4083 (defun js2-visit-paren-node (n v)
4084 (js2-visit-ast (js2-paren-node-expr n) v))
4085
4086 (defun js2-print-paren-node (n i)
4087 (insert (js2-make-pad i))
4088 (insert "(")
4089 (js2-print-ast (js2-paren-node-expr n) 0)
4090 (insert ")"))
4091
4092 (cl-defstruct (js2-comp-node
4093 (:include js2-scope)
4094 (:constructor nil)
4095 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4096 (pos js2-ts-cursor)
4097 len result
4098 loops filters
4099 form)))
4100 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4101 result ; result expression (just after left-bracket)
4102 loops ; a Lisp list of `js2-comp-loop-node'
4103 filters ; a Lisp list of guard/filter expressions
4104 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4105 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4106 )
4107
4108 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4109 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4110
4111 (defun js2-visit-comp-node (n v)
4112 (js2-visit-ast (js2-comp-node-result n) v)
4113 (dolist (l (js2-comp-node-loops n))
4114 (js2-visit-ast l v))
4115 (dolist (f (js2-comp-node-filters n))
4116 (js2-visit-ast f v)))
4117
4118 (defun js2-print-comp-node (n i)
4119 (let ((pad (js2-make-pad i))
4120 (result (js2-comp-node-result n))
4121 (loops (js2-comp-node-loops n))
4122 (filters (js2-comp-node-filters n))
4123 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4124 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4125 (insert pad (if gen-p "(" "["))
4126 (when legacy-p
4127 (js2-print-ast result 0))
4128 (dolist (l loops)
4129 (when legacy-p
4130 (insert " "))
4131 (js2-print-ast l 0)
4132 (unless legacy-p
4133 (insert " ")))
4134 (dolist (f filters)
4135 (when legacy-p
4136 (insert " "))
4137 (insert "if (")
4138 (js2-print-ast f 0)
4139 (insert ")")
4140 (unless legacy-p
4141 (insert " ")))
4142 (unless legacy-p
4143 (js2-print-ast result 0))
4144 (insert (if gen-p ")" "]"))))
4145
4146 (cl-defstruct (js2-comp-loop-node
4147 (:include js2-for-in-node)
4148 (:constructor nil)
4149 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4150 (pos js2-ts-cursor)
4151 len iterator
4152 object in-pos
4153 foreach-p
4154 each-pos
4155 forof-p
4156 lp rp)))
4157 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4158
4159 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4160 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4161
4162 (defun js2-visit-comp-loop (n v)
4163 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4164 (js2-visit-ast (js2-comp-loop-node-object n) v))
4165
4166 (defun js2-print-comp-loop (n _i)
4167 (insert "for ")
4168 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4169 (insert "(")
4170 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4171 (insert (if (js2-comp-loop-node-forof-p n)
4172 " of " " in "))
4173 (js2-print-ast (js2-comp-loop-node-object n) 0)
4174 (insert ")"))
4175
4176 (cl-defstruct (js2-empty-expr-node
4177 (:include js2-node)
4178 (:constructor nil)
4179 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4180 (pos (js2-current-token-beg))
4181 len)))
4182 "AST node for an empty expression.")
4183
4184 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4185 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4186
4187 (cl-defstruct (js2-xml-node
4188 (:include js2-block-node)
4189 (:constructor nil)
4190 (:constructor make-js2-xml-node (&key (type js2-XML)
4191 (pos (js2-current-token-beg))
4192 len kids)))
4193 "AST node for initial parse of E4X literals.
4194 The kids field is a list of XML fragments, each a `js2-string-node' or
4195 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4196
4197 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4198 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4199
4200 (defun js2-print-xml-node (n i)
4201 (dolist (kid (js2-xml-node-kids n))
4202 (js2-print-ast kid i)))
4203
4204 (cl-defstruct (js2-xml-js-expr-node
4205 (:include js2-xml-node)
4206 (:constructor nil)
4207 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4208 (pos js2-ts-cursor)
4209 len expr)))
4210 "AST node for an embedded JavaScript {expression} in an E4X literal.
4211 The start and end fields correspond to the curly-braces."
4212 expr) ; a `js2-expr-node' of some sort
4213
4214 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4215 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4216
4217 (defun js2-visit-xml-js-expr (n v)
4218 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4219
4220 (defun js2-print-xml-js-expr (n i)
4221 (insert (js2-make-pad i))
4222 (insert "{")
4223 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4224 (insert "}"))
4225
4226 (cl-defstruct (js2-xml-dot-query-node
4227 (:include js2-infix-node)
4228 (:constructor nil)
4229 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4230 (pos js2-ts-cursor)
4231 op-pos len left
4232 right rp)))
4233 "AST node for an E4X foo.(bar) filter expression.
4234 Note that the left-paren is automatically the character immediately
4235 following the dot (.) in the operator. No whitespace is permitted
4236 between the dot and the lp by the scanner."
4237 rp)
4238
4239 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4240 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4241
4242 (defun js2-print-xml-dot-query (n i)
4243 (insert (js2-make-pad i))
4244 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4245 (insert ".(")
4246 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4247 (insert ")"))
4248
4249 (cl-defstruct (js2-xml-ref-node
4250 (:include js2-node)
4251 (:constructor nil)) ; abstract
4252 "Base type for E4X XML attribute-access or property-get expressions.
4253 Such expressions can take a variety of forms. The general syntax has
4254 three parts:
4255
4256 - (optional) an @ (specifying an attribute access)
4257 - (optional) a namespace (a `js2-name-node') and double-colon
4258 - (required) either a `js2-name-node' or a bracketed [expression]
4259
4260 The property-name expressions (examples: ns::name, @name) are
4261 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4262 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4263
4264 This node type (or more specifically, its subclasses) will sometimes
4265 be the right-hand child of a `js2-prop-get-node' or a
4266 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4267 The `js2-xml-ref-node' may also be a standalone primary expression with
4268 no explicit target, which is valid in certain expression contexts such as
4269
4270 company..employee.(@id < 100)
4271
4272 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4273 expression whose parent is a `js2-xml-dot-query-node'."
4274 namespace
4275 at-pos
4276 colon-pos)
4277
4278 (defsubst js2-xml-ref-node-attr-access-p (node)
4279 "Return non-nil if this expression began with an @-token."
4280 (and (numberp (js2-xml-ref-node-at-pos node))
4281 (cl-plusp (js2-xml-ref-node-at-pos node))))
4282
4283 (cl-defstruct (js2-xml-prop-ref-node
4284 (:include js2-xml-ref-node)
4285 (:constructor nil)
4286 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4287 (pos (js2-current-token-beg))
4288 len propname
4289 namespace at-pos
4290 colon-pos)))
4291 "AST node for an E4X XML [expr] property-ref expression.
4292 The JavaScript syntax is an optional @, an optional ns::, and a name.
4293
4294 [ '@' ] [ name '::' ] name
4295
4296 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4297 @ns::*, @*::attr, @*::*, and @*.
4298
4299 The node starts at the @ token, if present. Otherwise it starts at the
4300 namespace name. The node bounds extend through the closing right-bracket,
4301 or if it is missing due to a syntax error, through the end of the index
4302 expression."
4303 propname)
4304
4305 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4306 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4307
4308 (defun js2-visit-xml-prop-ref-node (n v)
4309 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4310 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4311
4312 (defun js2-print-xml-prop-ref-node (n i)
4313 (insert (js2-make-pad i))
4314 (if (js2-xml-ref-node-attr-access-p n)
4315 (insert "@"))
4316 (when (js2-xml-prop-ref-node-namespace n)
4317 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4318 (insert "::"))
4319 (if (js2-xml-prop-ref-node-propname n)
4320 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4321
4322 (cl-defstruct (js2-xml-elem-ref-node
4323 (:include js2-xml-ref-node)
4324 (:constructor nil)
4325 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4326 (pos (js2-current-token-beg))
4327 len expr lb rb
4328 namespace at-pos
4329 colon-pos)))
4330 "AST node for an E4X XML [expr] member-ref expression.
4331 Syntax:
4332
4333 [ '@' ] [ name '::' ] '[' expr ']'
4334
4335 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4336
4337 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4338 is not a legal E4X XML element-ref expression, since it's already used
4339 for standard JavaScript element-get array indexing. Hence, a
4340 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4341 non-nil namespace node, or both.
4342
4343 The node starts at the @ token, if present. Otherwise it starts
4344 at the namespace name. The node bounds extend through the closing
4345 right-bracket, or if it is missing due to a syntax error, through the
4346 end of the index expression."
4347 expr ; the bracketed index expression
4348 lb
4349 rb)
4350
4351 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4352 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4353
4354 (defun js2-visit-xml-elem-ref-node (n v)
4355 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4356 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4357
4358 (defun js2-print-xml-elem-ref-node (n i)
4359 (insert (js2-make-pad i))
4360 (if (js2-xml-ref-node-attr-access-p n)
4361 (insert "@"))
4362 (when (js2-xml-elem-ref-node-namespace n)
4363 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4364 (insert "::"))
4365 (insert "[")
4366 (if (js2-xml-elem-ref-node-expr n)
4367 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4368 (insert "]"))
4369
4370 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4371
4372 (cl-defstruct (js2-xml-start-tag-node
4373 (:include js2-xml-node)
4374 (:constructor nil)
4375 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4376 (pos js2-ts-cursor)
4377 len name attrs kids
4378 empty-p)))
4379 "AST node for an XML start-tag. Not currently used.
4380 The `kids' field is a Lisp list of child content nodes."
4381 name ; a `js2-xml-name-node'
4382 attrs ; a Lisp list of `js2-xml-attr-node'
4383 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4384
4385 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4386 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4387
4388 (defun js2-visit-xml-start-tag (n v)
4389 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4390 (dolist (attr (js2-xml-start-tag-node-attrs n))
4391 (js2-visit-ast attr v))
4392 (js2-visit-block n v))
4393
4394 (defun js2-print-xml-start-tag (n i)
4395 (insert (js2-make-pad i) "<")
4396 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4397 (when (js2-xml-start-tag-node-attrs n)
4398 (insert " ")
4399 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4400 (insert ">"))
4401
4402 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4403 ;; and add the end-tag to the kids list of the parent as well.
4404 (cl-defstruct (js2-xml-end-tag-node
4405 (:include js2-xml-node)
4406 (:constructor nil)
4407 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4408 (pos js2-ts-cursor)
4409 len name)))
4410 "AST node for an XML end-tag. Not currently used."
4411 name) ; a `js2-xml-name-node'
4412
4413 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4414 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4415
4416 (defun js2-visit-xml-end-tag (n v)
4417 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4418
4419 (defun js2-print-xml-end-tag (n i)
4420 (insert (js2-make-pad i))
4421 (insert "</")
4422 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4423 (insert ">"))
4424
4425 (cl-defstruct (js2-xml-name-node
4426 (:include js2-xml-node)
4427 (:constructor nil)
4428 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4429 (pos js2-ts-cursor)
4430 len namespace kids)))
4431 "AST node for an E4X XML name. Not currently used.
4432 Any XML name can be qualified with a namespace, hence the namespace field.
4433 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4434 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4435 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4436 namespace) ; a `js2-string-node'
4437
4438 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4439 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4440
4441 (defun js2-visit-xml-name-node (n v)
4442 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4443
4444 (defun js2-print-xml-name-node (n i)
4445 (insert (js2-make-pad i))
4446 (when (js2-xml-name-node-namespace n)
4447 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4448 (insert "::"))
4449 (dolist (kid (js2-xml-name-node-kids n))
4450 (js2-print-ast kid 0)))
4451
4452 (cl-defstruct (js2-xml-pi-node
4453 (:include js2-xml-node)
4454 (:constructor nil)
4455 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4456 (pos js2-ts-cursor)
4457 len name attrs)))
4458 "AST node for an E4X XML processing instruction. Not currently used."
4459 name ; a `js2-xml-name-node'
4460 attrs) ; a list of `js2-xml-attr-node'
4461
4462 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4463 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4464
4465 (defun js2-visit-xml-pi-node (n v)
4466 (js2-visit-ast (js2-xml-pi-node-name n) v)
4467 (dolist (attr (js2-xml-pi-node-attrs n))
4468 (js2-visit-ast attr v)))
4469
4470 (defun js2-print-xml-pi-node (n i)
4471 (insert (js2-make-pad i) "<?")
4472 (js2-print-ast (js2-xml-pi-node-name n))
4473 (when (js2-xml-pi-node-attrs n)
4474 (insert " ")
4475 (js2-print-list (js2-xml-pi-node-attrs n)))
4476 (insert "?>"))
4477
4478 (cl-defstruct (js2-xml-cdata-node
4479 (:include js2-xml-node)
4480 (:constructor nil)
4481 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4482 (pos js2-ts-cursor)
4483 len content)))
4484 "AST node for a CDATA escape section. Not currently used."
4485 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4486
4487 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4488 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4489
4490 (defun js2-visit-xml-cdata-node (n v)
4491 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4492
4493 (defun js2-print-xml-cdata-node (n i)
4494 (insert (js2-make-pad i))
4495 (js2-print-ast (js2-xml-cdata-node-content n)))
4496
4497 (cl-defstruct (js2-xml-attr-node
4498 (:include js2-xml-node)
4499 (:constructor nil)
4500 (:constructor make-js2-attr-node (&key (type js2-XML)
4501 (pos js2-ts-cursor)
4502 len name value
4503 eq-pos quote-type)))
4504 "AST node representing a foo='bar' XML attribute value. Not yet used."
4505 name ; a `js2-xml-name-node'
4506 value ; a `js2-xml-name-node'
4507 eq-pos ; buffer position of "=" sign
4508 quote-type) ; 'single or 'double
4509
4510 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4511 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4512
4513 (defun js2-visit-xml-attr-node (n v)
4514 (js2-visit-ast (js2-xml-attr-node-name n) v)
4515 (js2-visit-ast (js2-xml-attr-node-value n) v))
4516
4517 (defun js2-print-xml-attr-node (n i)
4518 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4519 "'"
4520 "\"")))
4521 (insert (js2-make-pad i))
4522 (js2-print-ast (js2-xml-attr-node-name n) 0)
4523 (insert "=" quote)
4524 (js2-print-ast (js2-xml-attr-node-value n) 0)
4525 (insert quote)))
4526
4527 (cl-defstruct (js2-xml-text-node
4528 (:include js2-xml-node)
4529 (:constructor nil)
4530 (:constructor make-js2-text-node (&key (type js2-XML)
4531 (pos js2-ts-cursor)
4532 len content)))
4533 "AST node for an E4X XML text node. Not currently used."
4534 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4535
4536 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4537 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4538
4539 (defun js2-visit-xml-text-node (n v)
4540 (js2-visit-ast (js2-xml-text-node-content n) v))
4541
4542 (defun js2-print-xml-text-node (n i)
4543 (insert (js2-make-pad i))
4544 (dolist (kid (js2-xml-text-node-content n))
4545 (js2-print-ast kid)))
4546
4547 (cl-defstruct (js2-xml-comment-node
4548 (:include js2-xml-node)
4549 (:constructor nil)
4550 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4551 (pos js2-ts-cursor)
4552 len)))
4553 "AST node for E4X XML comment. Not currently used.")
4554
4555 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4556 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4557
4558 (defun js2-print-xml-comment (n i)
4559 (insert (js2-make-pad i)
4560 (js2-node-string n)))
4561
4562 ;;; Node utilities
4563
4564 (defsubst js2-node-line (n)
4565 "Fetch the source line number at the start of node N.
4566 This is O(n) in the length of the source buffer; use prudently."
4567 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4568
4569 (defsubst js2-block-node-kid (n i)
4570 "Return child I of node N, or nil if there aren't that many."
4571 (nth i (js2-block-node-kids n)))
4572
4573 (defsubst js2-block-node-first (n)
4574 "Return first child of block node N, or nil if there is none."
4575 (cl-first (js2-block-node-kids n)))
4576
4577 (defun js2-node-root (n)
4578 "Return the root of the AST containing N.
4579 If N has no parent pointer, returns N."
4580 (let ((parent (js2-node-parent n)))
4581 (if parent
4582 (js2-node-root parent)
4583 n)))
4584
4585 (defsubst js2-node-short-name (n)
4586 "Return the short name of node N as a string, e.g. `js2-if-node'."
4587 (substring (symbol-name (aref n 0))
4588 (length "cl-struct-")))
4589
4590 (defun js2-node-child-list (node)
4591 "Return the child list for NODE, a Lisp list of nodes.
4592 Works for block nodes, array nodes, obj literals, funarg lists,
4593 var decls and try nodes (for catch clauses). Note that you should call
4594 `js2-block-node-kids' on the function body for the body statements.
4595 Returns nil for zero-length child lists or unsupported nodes."
4596 (cond
4597 ((js2-function-node-p node)
4598 (js2-function-node-params node))
4599 ((js2-block-node-p node)
4600 (js2-block-node-kids node))
4601 ((js2-try-node-p node)
4602 (js2-try-node-catch-clauses node))
4603 ((js2-array-node-p node)
4604 (js2-array-node-elems node))
4605 ((js2-object-node-p node)
4606 (js2-object-node-elems node))
4607 ((js2-call-node-p node)
4608 (js2-call-node-args node))
4609 ((js2-new-node-p node)
4610 (js2-new-node-args node))
4611 ((js2-var-decl-node-p node)
4612 (js2-var-decl-node-kids node))
4613 (t
4614 nil)))
4615
4616 (defun js2-node-set-child-list (node kids)
4617 "Set the child list for NODE to KIDS."
4618 (cond
4619 ((js2-function-node-p node)
4620 (setf (js2-function-node-params node) kids))
4621 ((js2-block-node-p node)
4622 (setf (js2-block-node-kids node) kids))
4623 ((js2-try-node-p node)
4624 (setf (js2-try-node-catch-clauses node) kids))
4625 ((js2-array-node-p node)
4626 (setf (js2-array-node-elems node) kids))
4627 ((js2-object-node-p node)
4628 (setf (js2-object-node-elems node) kids))
4629 ((js2-call-node-p node)
4630 (setf (js2-call-node-args node) kids))
4631 ((js2-new-node-p node)
4632 (setf (js2-new-node-args node) kids))
4633 ((js2-var-decl-node-p node)
4634 (setf (js2-var-decl-node-kids node) kids))
4635 (t
4636 (error "Unsupported node type: %s" (js2-node-short-name node))))
4637 kids)
4638
4639 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4640 (defconst js2-paren-expr-nodes
4641 '(cl-struct-js2-comp-loop-node
4642 cl-struct-js2-comp-node
4643 cl-struct-js2-call-node
4644 cl-struct-js2-catch-node
4645 cl-struct-js2-do-node
4646 cl-struct-js2-elem-get-node
4647 cl-struct-js2-for-in-node
4648 cl-struct-js2-for-node
4649 cl-struct-js2-function-node
4650 cl-struct-js2-if-node
4651 cl-struct-js2-let-node
4652 cl-struct-js2-new-node
4653 cl-struct-js2-paren-node
4654 cl-struct-js2-switch-node
4655 cl-struct-js2-while-node
4656 cl-struct-js2-with-node
4657 cl-struct-js2-xml-dot-query-node)
4658 "Node types that can have a parenthesized child expression.
4659 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4660
4661 (defsubst js2-paren-expr-node-p (node)
4662 "Return t for nodes that typically have a parenthesized child expression.
4663 Useful for computing the indentation anchors for arg-lists and conditions.
4664 Note that it may return a false positive, for instance when NODE is
4665 a `js2-new-node' and there are no arguments or parentheses."
4666 (memq (aref node 0) js2-paren-expr-nodes))
4667
4668 ;; Fake polymorphism... yech.
4669 (defun js2-node-lp (node)
4670 "Return relative left-paren position for NODE, if applicable.
4671 For `js2-elem-get-node' structs, returns left-bracket position.
4672 Note that the position may be nil in the case of a parse error."
4673 (cond
4674 ((js2-elem-get-node-p node)
4675 (js2-elem-get-node-lb node))
4676 ((js2-loop-node-p node)
4677 (js2-loop-node-lp node))
4678 ((js2-function-node-p node)
4679 (js2-function-node-lp node))
4680 ((js2-if-node-p node)
4681 (js2-if-node-lp node))
4682 ((js2-new-node-p node)
4683 (js2-new-node-lp node))
4684 ((js2-call-node-p node)
4685 (js2-call-node-lp node))
4686 ((js2-paren-node-p node)
4687 0)
4688 ((js2-switch-node-p node)
4689 (js2-switch-node-lp node))
4690 ((js2-catch-node-p node)
4691 (js2-catch-node-lp node))
4692 ((js2-let-node-p node)
4693 (js2-let-node-lp node))
4694 ((js2-comp-node-p node)
4695 0)
4696 ((js2-with-node-p node)
4697 (js2-with-node-lp node))
4698 ((js2-xml-dot-query-node-p node)
4699 (1+ (js2-infix-node-op-pos node)))
4700 (t
4701 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4702
4703 ;; Fake polymorphism... blech.
4704 (defun js2-node-rp (node)
4705 "Return relative right-paren position for NODE, if applicable.
4706 For `js2-elem-get-node' structs, returns right-bracket position.
4707 Note that the position may be nil in the case of a parse error."
4708 (cond
4709 ((js2-elem-get-node-p node)
4710 (js2-elem-get-node-rb node))
4711 ((js2-loop-node-p node)
4712 (js2-loop-node-rp node))
4713 ((js2-function-node-p node)
4714 (js2-function-node-rp node))
4715 ((js2-if-node-p node)
4716 (js2-if-node-rp node))
4717 ((js2-new-node-p node)
4718 (js2-new-node-rp node))
4719 ((js2-call-node-p node)
4720 (js2-call-node-rp node))
4721 ((js2-paren-node-p node)
4722 (1- (js2-node-len node)))
4723 ((js2-switch-node-p node)
4724 (js2-switch-node-rp node))
4725 ((js2-catch-node-p node)
4726 (js2-catch-node-rp node))
4727 ((js2-let-node-p node)
4728 (js2-let-node-rp node))
4729 ((js2-comp-node-p node)
4730 (1- (js2-node-len node)))
4731 ((js2-with-node-p node)
4732 (js2-with-node-rp node))
4733 ((js2-xml-dot-query-node-p node)
4734 (1+ (js2-xml-dot-query-node-rp node)))
4735 (t
4736 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4737
4738 (defsubst js2-node-first-child (node)
4739 "Return the first element of `js2-node-child-list' for NODE."
4740 (car (js2-node-child-list node)))
4741
4742 (defsubst js2-node-last-child (node)
4743 "Return the last element of `js2-node-last-child' for NODE."
4744 (car (last (js2-node-child-list node))))
4745
4746 (defun js2-node-prev-sibling (node)
4747 "Return the previous statement in parent.
4748 Works for parents supported by `js2-node-child-list'.
4749 Returns nil if NODE is not in the parent, or PARENT is
4750 not a supported node, or if NODE is the first child."
4751 (let* ((p (js2-node-parent node))
4752 (kids (js2-node-child-list p))
4753 (sib (car kids)))
4754 (while (and kids
4755 (not (eq node (cadr kids))))
4756 (setq kids (cdr kids)
4757 sib (car kids)))
4758 sib))
4759
4760 (defun js2-node-next-sibling (node)
4761 "Return the next statement in parent block.
4762 Returns nil if NODE is not in the block, or PARENT is not
4763 a block node, or if NODE is the last statement."
4764 (let* ((p (js2-node-parent node))
4765 (kids (js2-node-child-list p)))
4766 (while (and kids
4767 (not (eq node (car kids))))
4768 (setq kids (cdr kids)))
4769 (cadr kids)))
4770
4771 (defun js2-node-find-child-before (pos parent &optional after)
4772 "Find the last child that starts before POS in parent.
4773 If AFTER is non-nil, returns first child starting after POS.
4774 POS is an absolute buffer position. PARENT is any node
4775 supported by `js2-node-child-list'.
4776 Returns nil if no applicable child is found."
4777 (let ((kids (if (js2-function-node-p parent)
4778 (js2-block-node-kids (js2-function-node-body parent))
4779 (js2-node-child-list parent)))
4780 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4781 (js2-function-node-body parent)
4782 parent)))
4783 kid result fn
4784 (continue t))
4785 (setq fn (if after '>= '<))
4786 (while (and kids continue)
4787 (setq kid (car kids))
4788 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4789 (setq result kid
4790 continue (not after))
4791 (setq continue after))
4792 (setq kids (cdr kids)))
4793 result))
4794
4795 (defun js2-node-find-child-after (pos parent)
4796 "Find first child that starts after POS in parent.
4797 POS is an absolute buffer position. PARENT is any node
4798 supported by `js2-node-child-list'.
4799 Returns nil if no applicable child is found."
4800 (js2-node-find-child-before pos parent 'after))
4801
4802 (defun js2-node-replace-child (pos parent new-node)
4803 "Replace node at index POS in PARENT with NEW-NODE.
4804 Only works for parents supported by `js2-node-child-list'."
4805 (let ((kids (js2-node-child-list parent))
4806 (i 0))
4807 (while (< i pos)
4808 (setq kids (cdr kids)
4809 i (1+ i)))
4810 (setcar kids new-node)
4811 (js2-node-add-children parent new-node)))
4812
4813 (defun js2-node-buffer (n)
4814 "Return the buffer associated with AST N.
4815 Returns nil if the buffer is not set as a property on the root
4816 node, or if parent links were not recorded during parsing."
4817 (let ((root (js2-node-root n)))
4818 (and root
4819 (js2-ast-root-p root)
4820 (js2-ast-root-buffer root))))
4821
4822 (defun js2-block-node-push (n kid)
4823 "Push js2-node KID onto the end of js2-block-node N's child list.
4824 KID is always added to the -end- of the kids list.
4825 Function also calls `js2-node-add-children' to add the parent link."
4826 (let ((kids (js2-node-child-list n)))
4827 (if kids
4828 (setcdr kids (nconc (cdr kids) (list kid)))
4829 (js2-node-set-child-list n (list kid)))
4830 (js2-node-add-children n kid)))
4831
4832 (defun js2-node-string (node)
4833 (with-current-buffer (or (js2-node-buffer node)
4834 (error "No buffer available for node %s" node))
4835 (let ((pos (js2-node-abs-pos node)))
4836 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4837
4838 ;; Container for storing the node we're looking for in a traversal.
4839 (js2-deflocal js2-discovered-node nil)
4840
4841 ;; Keep track of absolute node position during traversals.
4842 (js2-deflocal js2-visitor-offset nil)
4843
4844 (js2-deflocal js2-node-search-point nil)
4845
4846 (when js2-mode-dev-mode-p
4847 (defun js2-find-node-at-point ()
4848 (interactive)
4849 (let ((node (js2-node-at-point)))
4850 (message "%s" (or node "No node found at point"))))
4851 (defun js2-node-name-at-point ()
4852 (interactive)
4853 (let ((node (js2-node-at-point)))
4854 (message "%s" (if node
4855 (js2-node-short-name node)
4856 "No node found at point.")))))
4857
4858 (defun js2-node-at-point (&optional pos skip-comments)
4859 "Return AST node at POS, a buffer position, defaulting to current point.
4860 The `js2-mode-ast' variable must be set to the current parse tree.
4861 Signals an error if the AST (`js2-mode-ast') is nil.
4862 Always returns a node - if it can't find one, it returns the root.
4863 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4864 (let ((ast js2-mode-ast)
4865 result)
4866 (unless ast
4867 (error "No JavaScript AST available"))
4868 ;; Look through comments first, since they may be inside nodes that
4869 ;; would otherwise report a match.
4870 (setq pos (or pos (point))
4871 result (if (> pos (js2-node-abs-end ast))
4872 ast
4873 (if (not skip-comments)
4874 (js2-comment-at-point pos))))
4875 (unless result
4876 (setq js2-discovered-node nil
4877 js2-visitor-offset 0
4878 js2-node-search-point pos)
4879 (unwind-protect
4880 (catch 'js2-visit-done
4881 (js2-visit-ast ast #'js2-node-at-point-visitor))
4882 (setq js2-visitor-offset nil
4883 js2-node-search-point nil))
4884 (setq result js2-discovered-node))
4885 ;; may have found a comment beyond end of last child node,
4886 ;; since visiting the ast-root looks at the comment-list last.
4887 (if (and skip-comments
4888 (js2-comment-node-p result))
4889 (setq result nil))
4890 (or result js2-mode-ast)))
4891
4892 (defun js2-node-at-point-visitor (node end-p)
4893 (let ((rel-pos (js2-node-pos node))
4894 abs-pos
4895 abs-end
4896 (point js2-node-search-point))
4897 (cond
4898 (end-p
4899 ;; this evaluates to a non-nil return value, even if it's zero
4900 (cl-decf js2-visitor-offset rel-pos))
4901 ;; we already looked for comments before visiting, and don't want them now
4902 ((js2-comment-node-p node)
4903 nil)
4904 (t
4905 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4906 ;; we only want to use the node if the point is before
4907 ;; the last character position in the node, so we decrement
4908 ;; the absolute end by 1.
4909 abs-end (+ abs-pos (js2-node-len node) -1))
4910 (cond
4911 ;; If this node starts after search-point, stop the search.
4912 ((> abs-pos point)
4913 (throw 'js2-visit-done nil))
4914 ;; If this node ends before the search-point, don't check kids.
4915 ((> point abs-end)
4916 nil)
4917 (t
4918 ;; Otherwise point is within this node, possibly in a child.
4919 (setq js2-discovered-node node)
4920 t)))))) ; keep processing kids to look for more specific match
4921
4922 (defsubst js2-block-comment-p (node)
4923 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4924 (and (js2-comment-node-p node)
4925 (memq (js2-comment-node-format node) '(jsdoc block))))
4926
4927 ;; TODO: put the comments in a vector and binary-search them instead
4928 (defun js2-comment-at-point (&optional pos)
4929 "Look through scanned comment nodes for one containing POS.
4930 POS is a buffer position that defaults to current point.
4931 Function returns nil if POS was not in any comment node."
4932 (let ((ast js2-mode-ast)
4933 (x (or pos (point)))
4934 beg end)
4935 (unless ast
4936 (error "No JavaScript AST available"))
4937 (catch 'done
4938 ;; Comments are stored in lexical order.
4939 (dolist (comment (js2-ast-root-comments ast) nil)
4940 (setq beg (js2-node-abs-pos comment)
4941 end (+ beg (js2-node-len comment)))
4942 (if (and (>= x beg)
4943 (<= x end))
4944 (throw 'done comment))))))
4945
4946 (defun js2-mode-find-parent-fn (node)
4947 "Find function enclosing NODE.
4948 Returns nil if NODE is not inside a function."
4949 (setq node (js2-node-parent node))
4950 (while (and node (not (js2-function-node-p node)))
4951 (setq node (js2-node-parent node)))
4952 (and (js2-function-node-p node) node))
4953
4954 (defun js2-mode-find-enclosing-fn (node)
4955 "Find function or root enclosing NODE."
4956 (if (js2-ast-root-p node)
4957 node
4958 (setq node (js2-node-parent node))
4959 (while (not (or (js2-ast-root-p node)
4960 (js2-function-node-p node)))
4961 (setq node (js2-node-parent node)))
4962 node))
4963
4964 (defun js2-mode-find-enclosing-node (beg end)
4965 "Find node fully enclosing BEG and END."
4966 (let ((node (js2-node-at-point beg))
4967 pos
4968 (continue t))
4969 (while continue
4970 (if (or (js2-ast-root-p node)
4971 (and
4972 (<= (setq pos (js2-node-abs-pos node)) beg)
4973 (>= (+ pos (js2-node-len node)) end)))
4974 (setq continue nil)
4975 (setq node (js2-node-parent node))))
4976 node))
4977
4978 (defun js2-node-parent-script-or-fn (node)
4979 "Find script or function immediately enclosing NODE.
4980 If NODE is the ast-root, returns nil."
4981 (if (js2-ast-root-p node)
4982 nil
4983 (setq node (js2-node-parent node))
4984 (while (and node (not (or (js2-function-node-p node)
4985 (js2-script-node-p node))))
4986 (setq node (js2-node-parent node)))
4987 node))
4988
4989 (defun js2-node-is-descendant (node ancestor)
4990 "Return t if NODE is a descendant of ANCESTOR."
4991 (while (and node
4992 (not (eq node ancestor)))
4993 (setq node (js2-node-parent node)))
4994 node)
4995
4996 ;;; visitor infrastructure
4997
4998 (defun js2-visit-none (_node _callback)
4999 "Visitor for AST node that have no node children."
5000 nil)
5001
5002 (defun js2-print-none (_node _indent)
5003 "Visitor for AST node with no printed representation.")
5004
5005 (defun js2-print-body (node indent)
5006 "Print a statement, or a block without braces."
5007 (if (js2-block-node-p node)
5008 (dolist (kid (js2-block-node-kids node))
5009 (js2-print-ast kid indent))
5010 (js2-print-ast node indent)))
5011
5012 (defun js2-print-list (args &optional delimiter)
5013 (cl-loop with len = (length args)
5014 for arg in args
5015 for count from 1
5016 do
5017 (when arg (js2-print-ast arg 0))
5018 (if (< count len)
5019 (insert (or delimiter ", ")))))
5020
5021 (defun js2-print-tree (ast)
5022 "Prints an AST to the current buffer.
5023 Makes `js2-ast-parent-nodes' available to the printer functions."
5024 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5025 (js2-print-ast ast)))
5026
5027 (defun js2-print-ast (node &optional indent)
5028 "Helper function for printing AST nodes.
5029 Requires `js2-ast-parent-nodes' to be non-nil.
5030 You should use `js2-print-tree' instead of this function."
5031 (let ((printer (get (aref node 0) 'js2-printer))
5032 (i (or indent 0)))
5033 ;; TODO: wedge comments in here somewhere
5034 (if printer
5035 (funcall printer node i))))
5036
5037 (defconst js2-side-effecting-tokens
5038 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5039 (dolist (tt (list js2-ASSIGN
5040 js2-ASSIGN_ADD
5041 js2-ASSIGN_BITAND
5042 js2-ASSIGN_BITOR
5043 js2-ASSIGN_BITXOR
5044 js2-ASSIGN_DIV
5045 js2-ASSIGN_LSH
5046 js2-ASSIGN_MOD
5047 js2-ASSIGN_MUL
5048 js2-ASSIGN_RSH
5049 js2-ASSIGN_SUB
5050 js2-ASSIGN_URSH
5051 js2-BLOCK
5052 js2-BREAK
5053 js2-CALL
5054 js2-CATCH
5055 js2-CATCH_SCOPE
5056 js2-CLASS
5057 js2-CONST
5058 js2-CONTINUE
5059 js2-DEBUGGER
5060 js2-DEC
5061 js2-DELPROP
5062 js2-DEL_REF
5063 js2-DO
5064 js2-ELSE
5065 js2-EMPTY
5066 js2-ENTERWITH
5067 js2-EXPORT
5068 js2-EXPR_RESULT
5069 js2-FINALLY
5070 js2-FOR
5071 js2-FUNCTION
5072 js2-GOTO
5073 js2-IF
5074 js2-IFEQ
5075 js2-IFNE
5076 js2-IMPORT
5077 js2-INC
5078 js2-JSR
5079 js2-LABEL
5080 js2-LEAVEWITH
5081 js2-LET
5082 js2-LETEXPR
5083 js2-LOCAL_BLOCK
5084 js2-LOOP
5085 js2-NEW
5086 js2-REF_CALL
5087 js2-RETHROW
5088 js2-RETURN
5089 js2-RETURN_RESULT
5090 js2-SEMI
5091 js2-SETELEM
5092 js2-SETELEM_OP
5093 js2-SETNAME
5094 js2-SETPROP
5095 js2-SETPROP_OP
5096 js2-SETVAR
5097 js2-SET_REF
5098 js2-SET_REF_OP
5099 js2-SWITCH
5100 js2-TARGET
5101 js2-THROW
5102 js2-TRY
5103 js2-VAR
5104 js2-WHILE
5105 js2-WITH
5106 js2-WITHEXPR
5107 js2-YIELD))
5108 (aset tokens tt t))
5109 (if js2-instanceof-has-side-effects
5110 (aset tokens js2-INSTANCEOF t))
5111 tokens))
5112
5113 (defun js2-node-has-side-effects (node)
5114 "Return t if NODE has side effects."
5115 (when node ; makes it easier to handle malformed expressions
5116 (let ((tt (js2-node-type node)))
5117 (cond
5118 ;; This doubtless needs some work, since EXPR_VOID is used
5119 ;; in several ways in Rhino and I may not have caught them all.
5120 ;; I'll wait for people to notice incorrect warnings.
5121 ((and (= tt js2-EXPR_VOID)
5122 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5123 (let ((expr (js2-expr-stmt-node-expr node)))
5124 (or (js2-node-has-side-effects expr)
5125 (when (js2-string-node-p expr)
5126 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5127 ((= tt js2-COMMA)
5128 (js2-node-has-side-effects (js2-infix-node-right node)))
5129 ((or (= tt js2-AND)
5130 (= tt js2-OR))
5131 (or (js2-node-has-side-effects (js2-infix-node-right node))
5132 (js2-node-has-side-effects (js2-infix-node-left node))))
5133 ((= tt js2-HOOK)
5134 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5135 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5136 ((js2-paren-node-p node)
5137 (js2-node-has-side-effects (js2-paren-node-expr node)))
5138 ((= tt js2-ERROR) ; avoid cascaded error messages
5139 nil)
5140 (t
5141 (aref js2-side-effecting-tokens tt))))))
5142
5143 (defconst js2-stmt-node-types
5144 (list js2-BLOCK
5145 js2-BREAK
5146 js2-CONTINUE
5147 js2-DEFAULT ; e4x "default xml namespace" statement
5148 js2-DO
5149 js2-EXPORT
5150 js2-EXPR_RESULT
5151 js2-EXPR_VOID
5152 js2-FOR
5153 js2-IF
5154 js2-IMPORT
5155 js2-RETURN
5156 js2-SWITCH
5157 js2-THROW
5158 js2-TRY
5159 js2-WHILE
5160 js2-WITH)
5161 "Node types that only appear in statement contexts.
5162 The list does not include nodes that always appear as the child
5163 of another specific statement type, such as switch-cases,
5164 catch and finally blocks, and else-clauses. The list also excludes
5165 nodes like yield, let and var, which may appear in either expression
5166 or statement context, and in the latter context always have a
5167 `js2-expr-stmt-node' parent. Finally, the list does not include
5168 functions or scripts, which are treated separately from statements
5169 by the JavaScript parser and runtime.")
5170
5171 (defun js2-stmt-node-p (node)
5172 "Heuristic for figuring out if NODE is a statement.
5173 Some node types can appear in either an expression context or a
5174 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5175 For these node types in a statement context, the parent will be a
5176 `js2-expr-stmt-node'.
5177 Functions aren't included in the check."
5178 (memq (js2-node-type node) js2-stmt-node-types))
5179
5180 (defun js2-mode-find-first-stmt (node)
5181 "Search upward starting from NODE looking for a statement.
5182 For purposes of this function, a `js2-function-node' counts."
5183 (while (not (or (js2-stmt-node-p node)
5184 (js2-function-node-p node)))
5185 (setq node (js2-node-parent node)))
5186 node)
5187
5188 (defun js2-node-parent-stmt (node)
5189 "Return the node's first ancestor that is a statement.
5190 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5191 appearing in a statement context will have a parent that is a
5192 `js2-expr-stmt-node' that will be returned by this function."
5193 (let ((parent (js2-node-parent node)))
5194 (if (or (null parent)
5195 (js2-stmt-node-p parent)
5196 (and (js2-function-node-p parent)
5197 (not (eq (js2-function-node-form parent)
5198 'FUNCTION_EXPRESSION))))
5199 parent
5200 (js2-node-parent-stmt parent))))
5201
5202 ;; In the Mozilla Rhino sources, Roshan James writes:
5203 ;; Does consistent-return analysis on the function body when strict mode is
5204 ;; enabled.
5205 ;;
5206 ;; function (x) { return (x+1) }
5207 ;;
5208 ;; is ok, but
5209 ;;
5210 ;; function (x) { if (x < 0) return (x+1); }
5211 ;;
5212 ;; is not because the function can potentially return a value when the
5213 ;; condition is satisfied and if not, the function does not explicitly
5214 ;; return a value.
5215 ;;
5216 ;; This extends to checking mismatches such as "return" and "return <value>"
5217 ;; used in the same function. Warnings are not emitted if inconsistent
5218 ;; returns exist in code that can be statically shown to be unreachable.
5219 ;; Ex.
5220 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5221 ;;
5222 ;; emits no warning. However if the loop had a break statement, then a
5223 ;; warning would be emitted.
5224 ;;
5225 ;; The consistency analysis looks at control structures such as loops, ifs,
5226 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5227 ;; warns the user about an inconsistent set of termination possibilities.
5228 ;;
5229 ;; These flags enumerate the possible ways a statement/function can
5230 ;; terminate. These flags are used by endCheck() and by the Parser to
5231 ;; detect inconsistent return usage.
5232 ;;
5233 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5234 ;; able to execute (example: throw, continue)
5235 ;;
5236 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5237 ;; next one. Statement such as return dont. A compound statement may have
5238 ;; some branch that drops off control to the next statement.
5239 ;;
5240 ;; END_RETURNS indicates that the statement can return with no value.
5241 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5242 ;;
5243 ;; A compound statement such as
5244 ;; if (condition) {
5245 ;; return value;
5246 ;; }
5247 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5248
5249 (defconst js2-END_UNREACHED 0)
5250 (defconst js2-END_DROPS_OFF 1)
5251 (defconst js2-END_RETURNS 2)
5252 (defconst js2-END_RETURNS_VALUE 4)
5253 (defconst js2-END_YIELDS 8)
5254
5255 (defun js2-has-consistent-return-usage (node)
5256 "Check that every return usage in a function body is consistent.
5257 Returns t if the function satisfies strict mode requirement."
5258 (let ((n (js2-end-check node)))
5259 ;; either it doesn't return a value in any branch...
5260 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5261 ;; or it returns a value (or is unreached) at every branch
5262 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5263 js2-END_RETURNS
5264 js2-END_YIELDS)))))
5265
5266 (defun js2-end-check-if (node)
5267 "Ensure that return usage in then/else blocks is consistent.
5268 If there is no else block, then the return statement can fall through.
5269 Returns logical OR of END_* flags"
5270 (let ((th (js2-if-node-then-part node))
5271 (el (js2-if-node-else-part node)))
5272 (if (null th)
5273 js2-END_UNREACHED
5274 (logior (js2-end-check th) (if el
5275 (js2-end-check el)
5276 js2-END_DROPS_OFF)))))
5277
5278 (defun js2-end-check-switch (node)
5279 "Consistency of return statements is checked between the case statements.
5280 If there is no default, then the switch can fall through. If there is a
5281 default, we check to see if all code paths in the default return or if
5282 there is a code path that can fall through.
5283 Returns logical OR of END_* flags."
5284 (let ((rv js2-END_UNREACHED)
5285 default-case)
5286 ;; examine the cases
5287 (catch 'break
5288 (dolist (c (js2-switch-node-cases node))
5289 (if (js2-case-node-expr c)
5290 (js2-set-flag rv (js2-end-check-block c))
5291 (setq default-case c)
5292 (throw 'break nil))))
5293 ;; we don't care how the cases drop into each other
5294 (js2-clear-flag rv js2-END_DROPS_OFF)
5295 ;; examine the default
5296 (js2-set-flag rv (if default-case
5297 (js2-end-check default-case)
5298 js2-END_DROPS_OFF))
5299 rv))
5300
5301 (defun js2-end-check-try (node)
5302 "If the block has a finally, return consistency is checked in the
5303 finally block. If all code paths in the finally return, then the
5304 returns in the try-catch blocks don't matter. If there is a code path
5305 that does not return or if there is no finally block, the returns
5306 of the try and catch blocks are checked for mismatch.
5307 Returns logical OR of END_* flags."
5308 (let ((finally (js2-try-node-finally-block node))
5309 rv)
5310 ;; check the finally if it exists
5311 (setq rv (if finally
5312 (js2-end-check (js2-finally-node-body finally))
5313 js2-END_DROPS_OFF))
5314 ;; If the finally block always returns, then none of the returns
5315 ;; in the try or catch blocks matter.
5316 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5317 (js2-clear-flag rv js2-END_DROPS_OFF)
5318 ;; examine the try block
5319 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5320 ;; check each catch block
5321 (dolist (cb (js2-try-node-catch-clauses node))
5322 (js2-set-flag rv (js2-end-check cb))))
5323 rv))
5324
5325 (defun js2-end-check-loop (node)
5326 "Return statement in the loop body must be consistent.
5327 The default assumption for any kind of a loop is that it will eventually
5328 terminate. The only exception is a loop with a constant true condition.
5329 Code that follows such a loop is examined only if one can determine
5330 statically that there is a break out of the loop.
5331
5332 for(... ; ... ; ...) {}
5333 for(... in ... ) {}
5334 while(...) { }
5335 do { } while(...)
5336
5337 Returns logical OR of END_* flags."
5338 (let ((rv (js2-end-check (js2-loop-node-body node)))
5339 (condition (cond
5340 ((js2-while-node-p node)
5341 (js2-while-node-condition node))
5342 ((js2-do-node-p node)
5343 (js2-do-node-condition node))
5344 ((js2-for-node-p node)
5345 (js2-for-node-condition node)))))
5346
5347 ;; check to see if the loop condition is always true
5348 (if (and condition
5349 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5350 (js2-clear-flag rv js2-END_DROPS_OFF))
5351
5352 ;; look for effect of breaks
5353 (js2-set-flag rv (js2-node-get-prop node
5354 'CONTROL_BLOCK_PROP
5355 js2-END_UNREACHED))
5356 rv))
5357
5358 (defun js2-end-check-block (node)
5359 "A general block of code is examined statement by statement.
5360 If any statement (even a compound one) returns in all branches, then
5361 subsequent statements are not examined.
5362 Returns logical OR of END_* flags."
5363 (let* ((rv js2-END_DROPS_OFF)
5364 (kids (js2-block-node-kids node))
5365 (n (car kids)))
5366 ;; Check each statement. If the statement can continue onto the next
5367 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5368 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5369 (js2-clear-flag rv js2-END_DROPS_OFF)
5370 (js2-set-flag rv (js2-end-check n))
5371 (setq kids (cdr kids)
5372 n (car kids)))
5373 rv))
5374
5375 (defun js2-end-check-label (node)
5376 "A labeled statement implies that there may be a break to the label.
5377 The function processes the labeled statement and then checks the
5378 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5379 particular label.
5380 Returns logical OR of END_* flags."
5381 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5382 (logior rv (js2-node-get-prop node
5383 'CONTROL_BLOCK_PROP
5384 js2-END_UNREACHED))))
5385
5386 (defun js2-end-check-break (node)
5387 "When a break is encountered annotate the statement being broken
5388 out of by setting its CONTROL_BLOCK_PROP property.
5389 Returns logical OR of END_* flags."
5390 (and (js2-break-node-target node)
5391 (js2-node-set-prop (js2-break-node-target node)
5392 'CONTROL_BLOCK_PROP
5393 js2-END_DROPS_OFF))
5394 js2-END_UNREACHED)
5395
5396 (defun js2-end-check (node)
5397 "Examine the body of a function, doing a basic reachability analysis.
5398 Returns a combination of flags END_* flags that indicate
5399 how the function execution can terminate. These constitute only the
5400 pessimistic set of termination conditions. It is possible that at
5401 runtime certain code paths will never be actually taken. Hence this
5402 analysis will flag errors in cases where there may not be errors.
5403 Returns logical OR of END_* flags"
5404 (let (kid)
5405 (cond
5406 ((js2-break-node-p node)
5407 (js2-end-check-break node))
5408 ((js2-expr-stmt-node-p node)
5409 (if (setq kid (js2-expr-stmt-node-expr node))
5410 (js2-end-check kid)
5411 js2-END_DROPS_OFF))
5412 ((or (js2-continue-node-p node)
5413 (js2-throw-node-p node))
5414 js2-END_UNREACHED)
5415 ((js2-return-node-p node)
5416 (if (setq kid (js2-return-node-retval node))
5417 js2-END_RETURNS_VALUE
5418 js2-END_RETURNS))
5419 ((js2-loop-node-p node)
5420 (js2-end-check-loop node))
5421 ((js2-switch-node-p node)
5422 (js2-end-check-switch node))
5423 ((js2-labeled-stmt-node-p node)
5424 (js2-end-check-label node))
5425 ((js2-if-node-p node)
5426 (js2-end-check-if node))
5427 ((js2-try-node-p node)
5428 (js2-end-check-try node))
5429 ((js2-block-node-p node)
5430 (if (null (js2-block-node-kids node))
5431 js2-END_DROPS_OFF
5432 (js2-end-check-block node)))
5433 ((js2-yield-node-p node)
5434 js2-END_YIELDS)
5435 (t
5436 js2-END_DROPS_OFF))))
5437
5438 (defun js2-always-defined-boolean-p (node)
5439 "Check if NODE always evaluates to true or false in boolean context.
5440 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5441 nor always false."
5442 (let ((tt (js2-node-type node))
5443 num)
5444 (cond
5445 ((or (= tt js2-FALSE) (= tt js2-NULL))
5446 'ALWAYS_FALSE)
5447 ((= tt js2-TRUE)
5448 'ALWAYS_TRUE)
5449 ((= tt js2-NUMBER)
5450 (setq num (js2-number-node-num-value node))
5451 (if (and (not (eq num 0.0e+NaN))
5452 (not (zerop num)))
5453 'ALWAYS_TRUE
5454 'ALWAYS_FALSE))
5455 (t
5456 nil))))
5457
5458 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5459 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5460
5461 (defvar js2-tokens nil
5462 "List of all defined token names.") ; initialized in `js2-token-names'
5463
5464 (defconst js2-token-names
5465 (let* ((names (make-vector js2-num-tokens -1))
5466 (case-fold-search nil) ; only match js2-UPPER_CASE
5467 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5468 (cl-loop for sym in syms
5469 for i from 0
5470 do
5471 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5472 (not (boundp sym)))
5473 (aset names (symbol-value sym) ; code, e.g. 152
5474 (downcase
5475 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5476 (push sym js2-tokens)))
5477 names)
5478 "Vector mapping int values to token string names, sans `js2-' prefix.")
5479
5480 (defun js2-tt-name (tok)
5481 "Return a string name for TOK, a token symbol or code.
5482 Signals an error if it's not a recognized token."
5483 (let ((code tok))
5484 (if (symbolp tok)
5485 (setq code (symbol-value tok)))
5486 (if (eq code -1)
5487 "ERROR"
5488 (if (and (numberp code)
5489 (not (cl-minusp code))
5490 (< code js2-num-tokens))
5491 (aref js2-token-names code)
5492 (error "Invalid token: %s" code)))))
5493
5494 (defsubst js2-tt-sym (tok)
5495 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5496 (intern (js2-tt-name tok)))
5497
5498 (defconst js2-token-codes
5499 (let ((table (make-hash-table :test 'eq :size 256)))
5500 (cl-loop for name across js2-token-names
5501 for sym = (intern (concat "js2-" (upcase name)))
5502 do
5503 (puthash sym (symbol-value sym) table))
5504 ;; clean up a few that are "wrong" in Rhino's token codes
5505 (puthash 'js2-DELETE js2-DELPROP table)
5506 table)
5507 "Hashtable mapping token type symbols to their bytecodes.")
5508
5509 (defsubst js2-tt-code (sym)
5510 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5511 (or (gethash sym js2-token-codes)
5512 (error "Invalid token symbol: %s " sym))) ; signal code bug
5513
5514 (defun js2-report-scan-error (msg &optional no-throw beg len)
5515 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5516 (js2-report-error msg nil
5517 (or beg (js2-current-token-beg))
5518 (or len (js2-current-token-len)))
5519 (unless no-throw
5520 (throw 'return js2-ERROR)))
5521
5522 (defun js2-set-string-from-buffer (token)
5523 "Set `string' and `end' slots for TOKEN, return the string."
5524 (setf (js2-token-end token) js2-ts-cursor
5525 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5526
5527 ;; TODO: could potentially avoid a lot of consing by allocating a
5528 ;; char buffer the way Rhino does.
5529 (defsubst js2-add-to-string (c)
5530 (push c js2-ts-string-buffer))
5531
5532 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5533 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5534 ;; any other character: when it's not part of the current token, we
5535 ;; unget it, allowing it to be read again by the following call.
5536 (defsubst js2-unget-char ()
5537 (cl-decf js2-ts-cursor))
5538
5539 ;; Rhino distinguishes \r and \n line endings. We don't need to
5540 ;; because we only scan from Emacs buffers, which always use \n.
5541 (defun js2-get-char ()
5542 "Read and return the next character from the input buffer.
5543 Increments `js2-ts-lineno' if the return value is a newline char.
5544 Updates `js2-ts-cursor' to the point after the returned char.
5545 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5546 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5547 (let (c)
5548 ;; check for end of buffer
5549 (if (>= js2-ts-cursor (point-max))
5550 (setq js2-ts-hit-eof t
5551 js2-ts-cursor (1+ js2-ts-cursor)
5552 c js2-EOF_CHAR) ; return value
5553 ;; otherwise read next char
5554 (setq c (char-before (cl-incf js2-ts-cursor)))
5555 ;; if we read a newline, update counters
5556 (if (= c ?\n)
5557 (setq js2-ts-line-start js2-ts-cursor
5558 js2-ts-lineno (1+ js2-ts-lineno)))
5559 ;; TODO: skip over format characters
5560 c)))
5561
5562 (defun js2-read-unicode-escape ()
5563 "Read a \\uNNNN sequence from the input.
5564 Assumes the ?\ and ?u have already been read.
5565 Returns the unicode character, or nil if it wasn't a valid character.
5566 Doesn't change the values of any scanner variables."
5567 ;; I really wish I knew a better way to do this, but I can't
5568 ;; find the Emacs function that takes a 16-bit int and converts
5569 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5570 ;; Have to first check that it's 4 hex characters or it may stop
5571 ;; the read early.
5572 (ignore-errors
5573 (let ((s (buffer-substring-no-properties js2-ts-cursor
5574 (+ 4 js2-ts-cursor))))
5575 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5576 (read (concat "?\\u" s))))))
5577
5578 (defun js2-match-char (test)
5579 "Consume and return next character if it matches TEST, a character.
5580 Returns nil and consumes nothing if TEST is not the next character."
5581 (let ((c (js2-get-char)))
5582 (if (eq c test)
5583 t
5584 (js2-unget-char)
5585 nil)))
5586
5587 (defun js2-peek-char ()
5588 (prog1
5589 (js2-get-char)
5590 (js2-unget-char)))
5591
5592 (defun js2-identifier-start-p (c)
5593 "Is C a valid start to an ES5 Identifier?
5594 See http://es5.github.io/#x7.6"
5595 (or
5596 (memq c '(?$ ?_))
5597 (memq (get-char-code-property c 'general-category)
5598 ;; Letters
5599 '(Lu Ll Lt Lm Lo Nl))))
5600
5601 (defun js2-identifier-part-p (c)
5602 "Is C a valid part of an ES5 Identifier?
5603 See http://es5.github.io/#x7.6"
5604 (or
5605 (memq c '(?$ ?_ ?\u200c ?\u200d))
5606 (memq (get-char-code-property c 'general-category)
5607 '(;; Letters
5608 Lu Ll Lt Lm Lo Nl
5609 ;; Combining Marks
5610 Mn Mc
5611 ;; Digits
5612 Nd
5613 ;; Connector Punctuation
5614 Pc))))
5615
5616 (defun js2-alpha-p (c)
5617 (cond ((and (<= ?A c) (<= c ?Z)) t)
5618 ((and (<= ?a c) (<= c ?z)) t)
5619 (t nil)))
5620
5621 (defsubst js2-digit-p (c)
5622 (and (<= ?0 c) (<= c ?9)))
5623
5624 (defun js2-js-space-p (c)
5625 (if (<= c 127)
5626 (memq c '(#x20 #x9 #xB #xC #xD))
5627 (or
5628 (eq c #xA0)
5629 ;; TODO: change this nil to check for Unicode space character
5630 nil)))
5631
5632 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5633
5634 (defun js2-skip-line ()
5635 "Skip to end of line."
5636 (while (not (memq (js2-get-char) js2-eol-chars)))
5637 (js2-unget-char)
5638 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5639
5640 (defun js2-init-scanner (&optional buf line)
5641 "Create token stream for BUF starting on LINE.
5642 BUF defaults to `current-buffer' and LINE defaults to 1.
5643
5644 A buffer can only have one scanner active at a time, which yields
5645 dramatically simpler code than using a defstruct. If you need to
5646 have simultaneous scanners in a buffer, copy the regions to scan
5647 into temp buffers."
5648 (with-current-buffer (or buf (current-buffer))
5649 (setq js2-ts-dirty-line nil
5650 js2-ts-hit-eof nil
5651 js2-ts-line-start 0
5652 js2-ts-lineno (or line 1)
5653 js2-ts-line-end-char -1
5654 js2-ts-cursor (point-min)
5655 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5656 js2-ti-tokens-cursor 0
5657 js2-ti-lookahead 0
5658 js2-ts-is-xml-attribute nil
5659 js2-ts-xml-is-tag-content nil
5660 js2-ts-xml-open-tags-count 0
5661 js2-ts-string-buffer nil)))
5662
5663 ;; This function uses the cached op, string and number fields in
5664 ;; TokenStream; if getToken has been called since the passed token
5665 ;; was scanned, the op or string printed may be incorrect.
5666 (defun js2-token-to-string (token)
5667 ;; Not sure where this function is used in Rhino. Not tested.
5668 (if (not js2-debug-print-trees)
5669 ""
5670 (let ((name (js2-tt-name token)))
5671 (cond
5672 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5673 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5674 (concat name " `" (js2-current-token-string) "'"))
5675 ((eq token js2-NUMBER)
5676 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5677 (t
5678 name)))))
5679
5680 (defconst js2-keywords
5681 '(break
5682 case catch class const continue
5683 debugger default delete do
5684 else extends export
5685 false finally for function
5686 if in instanceof import
5687 let
5688 new null
5689 return
5690 super switch
5691 this throw true try typeof
5692 var void
5693 while with
5694 yield))
5695
5696 ;; Token names aren't exactly the same as the keywords, unfortunately.
5697 ;; E.g. delete is js2-DELPROP.
5698 (defconst js2-kwd-tokens
5699 (let ((table (make-vector js2-num-tokens nil))
5700 (tokens
5701 (list js2-BREAK
5702 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5703 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5704 js2-ELSE js2-EXPORT
5705 js2-ELSE js2-EXTENDS js2-EXPORT
5706 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5707 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5708 js2-LET
5709 js2-NEW js2-NULL
5710 js2-RETURN
5711 js2-SUPER js2-SWITCH
5712 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5713 js2-VAR
5714 js2-WHILE js2-WITH
5715 js2-YIELD)))
5716 (dolist (i tokens)
5717 (aset table i 'font-lock-keyword-face))
5718 (aset table js2-STRING 'font-lock-string-face)
5719 (aset table js2-REGEXP 'font-lock-string-face)
5720 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5721 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5722 (aset table js2-COMMENT 'font-lock-comment-face)
5723 (aset table js2-THIS 'font-lock-builtin-face)
5724 (aset table js2-SUPER 'font-lock-builtin-face)
5725 (aset table js2-VOID 'font-lock-constant-face)
5726 (aset table js2-NULL 'font-lock-constant-face)
5727 (aset table js2-TRUE 'font-lock-constant-face)
5728 (aset table js2-FALSE 'font-lock-constant-face)
5729 (aset table js2-NOT 'font-lock-negation-char-face)
5730 table)
5731 "Vector whose values are non-nil for tokens that are keywords.
5732 The values are default faces to use for highlighting the keywords.")
5733
5734 ;; FIXME: Support strict mode-only future reserved words, after we know
5735 ;; which parts scopes are in strict mode, and which are not.
5736 (defconst js2-reserved-words '(class enum export extends import static super)
5737 "Future reserved keywords in ECMAScript 5.1.")
5738
5739 (defconst js2-keyword-names
5740 (let ((table (make-hash-table :test 'equal)))
5741 (cl-loop for k in js2-keywords
5742 do (puthash
5743 (symbol-name k) ; instanceof
5744 (intern (concat "js2-"
5745 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5746 table))
5747 table)
5748 "JavaScript keywords by name, mapped to their symbols.")
5749
5750 (defconst js2-reserved-word-names
5751 (let ((table (make-hash-table :test 'equal)))
5752 (cl-loop for k in js2-reserved-words
5753 do
5754 (puthash (symbol-name k) 'js2-RESERVED table))
5755 table)
5756 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5757
5758 (defun js2-collect-string (buf)
5759 "Convert BUF, a list of chars, to a string.
5760 Reverses BUF before converting."
5761 (if buf
5762 (apply #'string (nreverse buf))
5763 ""))
5764
5765 (defun js2-string-to-keyword (s)
5766 "Return token for S, a string, if S is a keyword or reserved word.
5767 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5768 (or (gethash s js2-keyword-names)
5769 (gethash s js2-reserved-word-names)))
5770
5771 (defsubst js2-ts-set-char-token-bounds (token)
5772 "Used when next token is one character."
5773 (setf (js2-token-beg token) (1- js2-ts-cursor)
5774 (js2-token-end token) js2-ts-cursor))
5775
5776 (defsubst js2-ts-return (token type)
5777 "Update the `end' and `type' slots of TOKEN,
5778 then throw `return' with value TYPE."
5779 (setf (js2-token-end token) js2-ts-cursor
5780 (js2-token-type token) type)
5781 (throw 'return type))
5782
5783 (defun js2-x-digit-to-int (c accumulator)
5784 "Build up a hex number.
5785 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5786 corresponding number. Otherwise return -1."
5787 (catch 'return
5788 (catch 'check
5789 ;; Use 0..9 < A..Z < a..z
5790 (cond
5791 ((<= c ?9)
5792 (cl-decf c ?0)
5793 (if (<= 0 c)
5794 (throw 'check nil)))
5795 ((<= c ?F)
5796 (when (<= ?A c)
5797 (cl-decf c (- ?A 10))
5798 (throw 'check nil)))
5799 ((<= c ?f)
5800 (when (<= ?a c)
5801 (cl-decf c (- ?a 10))
5802 (throw 'check nil))))
5803 (throw 'return -1))
5804 (logior c (lsh accumulator 4))))
5805
5806 (defun js2-get-token (&optional modifier)
5807 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5808 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5809 next saved token.
5810
5811 This function will not return a newline (js2-EOL) - instead, it
5812 gobbles newlines until it finds a non-newline token. Call
5813 `js2-peek-token-or-eol' when you care about newlines.
5814
5815 This function will also not return a js2-COMMENT. Instead, it
5816 records comments found in `js2-scanned-comments'. If the token
5817 returned by this function immediately follows a jsdoc comment,
5818 the token is flagged as such."
5819 (if (zerop js2-ti-lookahead)
5820 (js2-get-token-internal modifier)
5821 (cl-decf js2-ti-lookahead)
5822 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5823 (let ((tt (js2-current-token-type)))
5824 (cl-assert (not (= tt js2-EOL)))
5825 tt)))
5826
5827 (defun js2-unget-token ()
5828 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5829 (cl-incf js2-ti-lookahead)
5830 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5831
5832 (defun js2-get-token-internal (modifier)
5833 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5834 (tt (js2-token-type token))
5835 saw-eol
5836 face)
5837 ;; process comments
5838 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5839 (if (= tt js2-EOL)
5840 (setq saw-eol t)
5841 (setq saw-eol nil)
5842 (when js2-record-comments
5843 (js2-record-comment token)))
5844 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5845 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5846 tt (js2-token-type token)))
5847
5848 (when saw-eol
5849 (setf (js2-token-follows-eol-p token) t))
5850
5851 ;; perform lexical fontification as soon as token is scanned
5852 (when js2-parse-ide-mode
5853 (cond
5854 ((cl-minusp tt)
5855 (js2-record-face 'js2-error token))
5856 ((setq face (aref js2-kwd-tokens tt))
5857 (js2-record-face face token))
5858 ((and (= tt js2-NAME)
5859 (equal (js2-token-string token) "undefined"))
5860 (js2-record-face 'font-lock-constant-face token))))
5861 tt))
5862
5863 (defsubst js2-string-to-number (str base)
5864 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5865 (condition-case nil
5866 (string-to-number str base)
5867 (overflow-error -1)))
5868
5869 (defun js2-get-token-internal-1 (modifier)
5870 "Return next JavaScript token type, an int such as js2-RETURN.
5871 During operation, creates an instance of `js2-token' struct, sets
5872 its relevant fields and puts it into `js2-ti-tokens'."
5873 (let (identifier-start
5874 is-unicode-escape-start c
5875 contains-escape escape-val str result base
5876 look-for-slash continue tt
5877 (token (js2-new-token 0)))
5878 (setq
5879 tt
5880 (catch 'return
5881 (when (eq modifier 'TEMPLATE_TAIL)
5882 (setf (js2-token-beg token) (1- js2-ts-cursor))
5883 (throw 'return (js2-get-string-or-template-token ?` token)))
5884 (while t
5885 ;; Eat whitespace, possibly sensitive to newlines.
5886 (setq continue t)
5887 (while continue
5888 (setq c (js2-get-char))
5889 (cond
5890 ((eq c js2-EOF_CHAR)
5891 (js2-unget-char)
5892 (js2-ts-set-char-token-bounds token)
5893 (throw 'return js2-EOF))
5894 ((eq c ?\n)
5895 (js2-ts-set-char-token-bounds token)
5896 (setq js2-ts-dirty-line nil)
5897 (throw 'return js2-EOL))
5898 ((not (js2-js-space-p c))
5899 (if (/= c ?-) ; in case end of HTML comment
5900 (setq js2-ts-dirty-line t))
5901 (setq continue nil))))
5902 ;; Assume the token will be 1 char - fixed up below.
5903 (js2-ts-set-char-token-bounds token)
5904 (when (eq c ?@)
5905 (throw 'return js2-XMLATTR))
5906 ;; identifier/keyword/instanceof?
5907 ;; watch out for starting with a <backslash>
5908 (cond
5909 ((eq c ?\\)
5910 (setq c (js2-get-char))
5911 (if (eq c ?u)
5912 (setq identifier-start t
5913 is-unicode-escape-start t
5914 js2-ts-string-buffer nil)
5915 (setq identifier-start nil)
5916 (js2-unget-char)
5917 (setq c ?\\)))
5918 (t
5919 (when (setq identifier-start (js2-identifier-start-p c))
5920 (setq js2-ts-string-buffer nil)
5921 (js2-add-to-string c))))
5922 (when identifier-start
5923 (setq contains-escape is-unicode-escape-start)
5924 (catch 'break
5925 (while t
5926 (if is-unicode-escape-start
5927 ;; strictly speaking we should probably push-back
5928 ;; all the bad characters if the <backslash>uXXXX
5929 ;; sequence is malformed. But since there isn't a
5930 ;; correct context(is there?) for a bad Unicode
5931 ;; escape sequence in an identifier, we can report
5932 ;; an error here.
5933 (progn
5934 (setq escape-val 0)
5935 (dotimes (_ 4)
5936 (setq c (js2-get-char)
5937 escape-val (js2-x-digit-to-int c escape-val))
5938 ;; Next check takes care of c < 0 and bad escape
5939 (if (cl-minusp escape-val)
5940 (throw 'break nil)))
5941 (if (cl-minusp escape-val)
5942 (js2-report-scan-error "msg.invalid.escape" t))
5943 (js2-add-to-string escape-val)
5944 (setq is-unicode-escape-start nil))
5945 (setq c (js2-get-char))
5946 (cond
5947 ((eq c ?\\)
5948 (setq c (js2-get-char))
5949 (if (eq c ?u)
5950 (setq is-unicode-escape-start t
5951 contains-escape t)
5952 (js2-report-scan-error "msg.illegal.character" t)))
5953 (t
5954 (if (or (eq c js2-EOF_CHAR)
5955 (not (js2-identifier-part-p c)))
5956 (throw 'break nil))
5957 (js2-add-to-string c))))))
5958 (js2-unget-char)
5959 (setf str (js2-collect-string js2-ts-string-buffer)
5960 (js2-token-end token) js2-ts-cursor)
5961 ;; FIXME: Invalid in ES5 and ES6, see
5962 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5963 ;; Probably should just drop this conditional.
5964 (unless contains-escape
5965 ;; OPT we shouldn't have to make a string (object!) to
5966 ;; check if it's a keyword.
5967 ;; Return the corresponding token if it's a keyword
5968 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5969 (setq result (js2-string-to-keyword str)))
5970 (if (and (< js2-language-version 170)
5971 (memq result '(js2-LET js2-YIELD)))
5972 ;; LET and YIELD are tokens only in 1.7 and later
5973 (setq result 'js2-NAME))
5974 (when (eq result 'js2-RESERVED)
5975 (setf (js2-token-string token) str))
5976 (throw 'return (js2-tt-code result))))
5977 ;; If we want to intern these as Rhino does, just use (intern str)
5978 (setf (js2-token-string token) str)
5979 (throw 'return js2-NAME)) ; end identifier/kwd check
5980 ;; is it a number?
5981 (when (or (js2-digit-p c)
5982 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5983 (setq js2-ts-string-buffer nil
5984 base 10)
5985 (when (eq c ?0)
5986 (setq c (js2-get-char))
5987 (cond
5988 ((or (eq c ?x) (eq c ?X))
5989 (setq base 16)
5990 (setq c (js2-get-char)))
5991 ((and (or (eq c ?b) (eq c ?B))
5992 (>= js2-language-version 200))
5993 (setq base 2)
5994 (setq c (js2-get-char)))
5995 ((and (or (eq c ?o) (eq c ?O))
5996 (>= js2-language-version 200))
5997 (setq base 8)
5998 (setq c (js2-get-char)))
5999 ((js2-digit-p c)
6000 (setq base 'maybe-8))
6001 (t
6002 (js2-add-to-string ?0))))
6003 (cond
6004 ((eq base 16)
6005 (if (> 0 (js2-x-digit-to-int c 0))
6006 (js2-report-scan-error "msg.missing.hex.digits")
6007 (while (<= 0 (js2-x-digit-to-int c 0))
6008 (js2-add-to-string c)
6009 (setq c (js2-get-char)))))
6010 ((eq base 2)
6011 (if (not (memq c '(?0 ?1)))
6012 (js2-report-scan-error "msg.missing.binary.digits")
6013 (while (memq c '(?0 ?1))
6014 (js2-add-to-string c)
6015 (setq c (js2-get-char)))))
6016 ((eq base 8)
6017 (if (or (> ?0 c) (< ?7 c))
6018 (js2-report-scan-error "msg.missing.octal.digits")
6019 (while (and (<= ?0 c) (>= ?7 c))
6020 (js2-add-to-string c)
6021 (setq c (js2-get-char)))))
6022 (t
6023 (while (and (<= ?0 c) (<= c ?9))
6024 ;; We permit 08 and 09 as decimal numbers, which
6025 ;; makes our behavior a superset of the ECMA
6026 ;; numeric grammar. We might not always be so
6027 ;; permissive, so we warn about it.
6028 (when (and (eq base 'maybe-8) (>= c ?8))
6029 (js2-report-warning "msg.bad.octal.literal"
6030 (if (eq c ?8) "8" "9"))
6031 (setq base 10))
6032 (js2-add-to-string c)
6033 (setq c (js2-get-char)))
6034 (when (eq base 'maybe-8)
6035 (setq base 8))))
6036 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6037 (when (eq c ?.)
6038 (cl-loop do
6039 (js2-add-to-string c)
6040 (setq c (js2-get-char))
6041 while (js2-digit-p c)))
6042 (when (memq c '(?e ?E))
6043 (js2-add-to-string c)
6044 (setq c (js2-get-char))
6045 (when (memq c '(?+ ?-))
6046 (js2-add-to-string c)
6047 (setq c (js2-get-char)))
6048 (unless (js2-digit-p c)
6049 (js2-report-scan-error "msg.missing.exponent" t))
6050 (cl-loop do
6051 (js2-add-to-string c)
6052 (setq c (js2-get-char))
6053 while (js2-digit-p c))))
6054 (js2-unget-char)
6055 (let ((str (js2-set-string-from-buffer token)))
6056 (setf (js2-token-number token) (js2-string-to-number str base)
6057 (js2-token-number-base token) base))
6058 (throw 'return js2-NUMBER))
6059 ;; is it a string?
6060 (when (or (memq c '(?\" ?\'))
6061 (and (>= js2-language-version 200)
6062 (= c ?`)))
6063 (throw 'return
6064 (js2-get-string-or-template-token c token)))
6065 (js2-ts-return token
6066 (cl-case c
6067 (?\;
6068 (throw 'return js2-SEMI))
6069 (?\[
6070 (throw 'return js2-LB))
6071 (?\]
6072 (throw 'return js2-RB))
6073 (?{
6074 (throw 'return js2-LC))
6075 (?}
6076 (throw 'return js2-RC))
6077 (?\(
6078 (throw 'return js2-LP))
6079 (?\)
6080 (throw 'return js2-RP))
6081 (?,
6082 (throw 'return js2-COMMA))
6083 (??
6084 (throw 'return js2-HOOK))
6085 (?:
6086 (if (js2-match-char ?:)
6087 js2-COLONCOLON
6088 (throw 'return js2-COLON)))
6089 (?.
6090 (if (js2-match-char ?.)
6091 (if (js2-match-char ?.)
6092 js2-TRIPLEDOT js2-DOTDOT)
6093 (if (js2-match-char ?\()
6094 js2-DOTQUERY
6095 (throw 'return js2-DOT))))
6096 (?|
6097 (if (js2-match-char ?|)
6098 (throw 'return js2-OR)
6099 (if (js2-match-char ?=)
6100 js2-ASSIGN_BITOR
6101 (throw 'return js2-BITOR))))
6102 (?^
6103 (if (js2-match-char ?=)
6104 js2-ASSIGN_BITOR
6105 (throw 'return js2-BITXOR)))
6106 (?&
6107 (if (js2-match-char ?&)
6108 (throw 'return js2-AND)
6109 (if (js2-match-char ?=)
6110 js2-ASSIGN_BITAND
6111 (throw 'return js2-BITAND))))
6112 (?=
6113 (if (js2-match-char ?=)
6114 (if (js2-match-char ?=)
6115 js2-SHEQ
6116 (throw 'return js2-EQ))
6117 (if (js2-match-char ?>)
6118 (js2-ts-return token js2-ARROW)
6119 (throw 'return js2-ASSIGN))))
6120 (?!
6121 (if (js2-match-char ?=)
6122 (if (js2-match-char ?=)
6123 js2-SHNE
6124 js2-NE)
6125 (throw 'return js2-NOT)))
6126 (?<
6127 ;; NB:treat HTML begin-comment as comment-till-eol
6128 (when (js2-match-char ?!)
6129 (when (js2-match-char ?-)
6130 (when (js2-match-char ?-)
6131 (js2-skip-line)
6132 (setf (js2-token-comment-type (js2-current-token)) 'html)
6133 (throw 'return js2-COMMENT)))
6134 (js2-unget-char))
6135 (if (js2-match-char ?<)
6136 (if (js2-match-char ?=)
6137 js2-ASSIGN_LSH
6138 js2-LSH)
6139 (if (js2-match-char ?=)
6140 js2-LE
6141 (throw 'return js2-LT))))
6142 (?>
6143 (if (js2-match-char ?>)
6144 (if (js2-match-char ?>)
6145 (if (js2-match-char ?=)
6146 js2-ASSIGN_URSH
6147 js2-URSH)
6148 (if (js2-match-char ?=)
6149 js2-ASSIGN_RSH
6150 js2-RSH))
6151 (if (js2-match-char ?=)
6152 js2-GE
6153 (throw 'return js2-GT))))
6154 (?*
6155 (if (js2-match-char ?=)
6156 js2-ASSIGN_MUL
6157 (throw 'return js2-MUL)))
6158 (?/
6159 ;; is it a // comment?
6160 (when (js2-match-char ?/)
6161 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6162 (js2-skip-line)
6163 (setf (js2-token-comment-type token) 'line)
6164 ;; include newline so highlighting goes to end of
6165 ;; window, if there actually is a newline; if we
6166 ;; hit eof, then implicitly there isn't
6167 (unless js2-ts-hit-eof
6168 (cl-incf (js2-token-end token)))
6169 (throw 'return js2-COMMENT))
6170 ;; is it a /* comment?
6171 (when (js2-match-char ?*)
6172 (setf look-for-slash nil
6173 (js2-token-beg token) (- js2-ts-cursor 2)
6174 (js2-token-comment-type token)
6175 (if (js2-match-char ?*)
6176 (progn
6177 (setq look-for-slash t)
6178 'jsdoc)
6179 'block))
6180 (while t
6181 (setq c (js2-get-char))
6182 (cond
6183 ((eq c js2-EOF_CHAR)
6184 (setf (js2-token-end token) (1- js2-ts-cursor))
6185 (js2-report-error "msg.unterminated.comment")
6186 (throw 'return js2-COMMENT))
6187 ((eq c ?*)
6188 (setq look-for-slash t))
6189 ((eq c ?/)
6190 (if look-for-slash
6191 (js2-ts-return token js2-COMMENT)))
6192 (t
6193 (setf look-for-slash nil
6194 (js2-token-end token) js2-ts-cursor)))))
6195 (if (js2-match-char ?=)
6196 js2-ASSIGN_DIV
6197 (throw 'return js2-DIV)))
6198 (?#
6199 (when js2-skip-preprocessor-directives
6200 (js2-skip-line)
6201 (setf (js2-token-comment-type token) 'preprocessor
6202 (js2-token-end token) js2-ts-cursor)
6203 (throw 'return js2-COMMENT))
6204 (throw 'return js2-ERROR))
6205 (?%
6206 (if (js2-match-char ?=)
6207 js2-ASSIGN_MOD
6208 (throw 'return js2-MOD)))
6209 (?~
6210 (throw 'return js2-BITNOT))
6211 (?+
6212 (if (js2-match-char ?=)
6213 js2-ASSIGN_ADD
6214 (if (js2-match-char ?+)
6215 js2-INC
6216 (throw 'return js2-ADD))))
6217 (?-
6218 (cond
6219 ((js2-match-char ?=)
6220 (setq c js2-ASSIGN_SUB))
6221 ((js2-match-char ?-)
6222 (unless js2-ts-dirty-line
6223 ;; treat HTML end-comment after possible whitespace
6224 ;; after line start as comment-until-eol
6225 (when (js2-match-char ?>)
6226 (js2-skip-line)
6227 (setf (js2-token-comment-type (js2-current-token)) 'html)
6228 (throw 'return js2-COMMENT)))
6229 (setq c js2-DEC))
6230 (t
6231 (setq c js2-SUB)))
6232 (setq js2-ts-dirty-line t)
6233 c)
6234 (otherwise
6235 (js2-report-scan-error "msg.illegal.character")))))))
6236 (setf (js2-token-type token) tt)
6237 token))
6238
6239 (defun js2-get-string-or-template-token (quote-char token)
6240 ;; We attempt to accumulate a string the fast way, by
6241 ;; building it directly out of the reader. But if there
6242 ;; are any escaped characters in the string, we revert to
6243 ;; building it out of a string buffer.
6244 (let ((c (js2-get-char))
6245 js2-ts-string-buffer
6246 nc c1 val escape-val)
6247 (catch 'break
6248 (while (/= c quote-char)
6249 (catch 'continue
6250 (when (eq c js2-EOF_CHAR)
6251 (js2-unget-char)
6252 (js2-report-error "msg.unterminated.string.lit")
6253 (throw 'break nil))
6254 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6255 (js2-unget-char)
6256 (js2-report-error "msg.unterminated.string.lit")
6257 (throw 'break nil))
6258 (when (eq c ?\\)
6259 ;; We've hit an escaped character
6260 (setq c (js2-get-char))
6261 (cl-case c
6262 (?b (setq c ?\b))
6263 (?f (setq c ?\f))
6264 (?n (setq c ?\n))
6265 (?r (setq c ?\r))
6266 (?t (setq c ?\t))
6267 (?v (setq c ?\v))
6268 (?u
6269 (setq c1 (js2-read-unicode-escape))
6270 (if js2-parse-ide-mode
6271 (if c1
6272 (progn
6273 ;; just copy the string in IDE-mode
6274 (js2-add-to-string ?\\)
6275 (js2-add-to-string ?u)
6276 (dotimes (_ 3)
6277 (js2-add-to-string (js2-get-char)))
6278 (setq c (js2-get-char))) ; added at end of loop
6279 ;; flag it as an invalid escape
6280 (js2-report-warning "msg.invalid.escape"
6281 nil (- js2-ts-cursor 2) 6))
6282 ;; Get 4 hex digits; if the u escape is not
6283 ;; followed by 4 hex digits, use 'u' + the
6284 ;; literal character sequence that follows.
6285 (js2-add-to-string ?u)
6286 (setq escape-val 0)
6287 (dotimes (_ 4)
6288 (setq c (js2-get-char)
6289 escape-val (js2-x-digit-to-int c escape-val))
6290 (if (cl-minusp escape-val)
6291 (throw 'continue nil))
6292 (js2-add-to-string c))
6293 ;; prepare for replace of stored 'u' sequence by escape value
6294 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6295 c escape-val)))
6296 (?x
6297 ;; Get 2 hex digits, defaulting to 'x'+literal
6298 ;; sequence, as above.
6299 (setq c (js2-get-char)
6300 escape-val (js2-x-digit-to-int c 0))
6301 (if (cl-minusp escape-val)
6302 (progn
6303 (js2-add-to-string ?x)
6304 (throw 'continue nil))
6305 (setq c1 c
6306 c (js2-get-char)
6307 escape-val (js2-x-digit-to-int c escape-val))
6308 (if (cl-minusp escape-val)
6309 (progn
6310 (js2-add-to-string ?x)
6311 (js2-add-to-string c1)
6312 (throw 'continue nil))
6313 ;; got 2 hex digits
6314 (setq c escape-val))))
6315 (?\n
6316 ;; Remove line terminator after escape to follow
6317 ;; SpiderMonkey and C/C++
6318 (setq c (js2-get-char))
6319 (throw 'continue nil))
6320 (t
6321 (when (and (<= ?0 c) (< c ?8))
6322 (setq val (- c ?0)
6323 c (js2-get-char))
6324 (when (and (<= ?0 c) (< c ?8))
6325 (setq val (- (+ (* 8 val) c) ?0)
6326 c (js2-get-char))
6327 (when (and (<= ?0 c)
6328 (< c ?8)
6329 (< val #o37))
6330 ;; c is 3rd char of octal sequence only
6331 ;; if the resulting val <= 0377
6332 (setq val (- (+ (* 8 val) c) ?0)
6333 c (js2-get-char))))
6334 (js2-unget-char)
6335 (setq c val)))))
6336 (when (and (eq quote-char ?`) (eq c ?$))
6337 (when (eq (setq nc (js2-get-char)) ?\{)
6338 (throw 'break nil))
6339 (js2-unget-char))
6340 (js2-add-to-string c)
6341 (setq c (js2-get-char)))))
6342 (js2-set-string-from-buffer token)
6343 (if (not (eq quote-char ?`))
6344 js2-STRING
6345 (if (and (eq c ?$) (eq nc ?\{))
6346 js2-TEMPLATE_HEAD
6347 js2-NO_SUBS_TEMPLATE))))
6348
6349 (defun js2-read-regexp (start-tt)
6350 "Called by parser when it gets / or /= in literal context."
6351 (let (c err
6352 in-class ; inside a '[' .. ']' character-class
6353 flags
6354 (continue t)
6355 (token (js2-new-token 0)))
6356 (setq js2-ts-string-buffer nil)
6357 (if (eq start-tt js2-ASSIGN_DIV)
6358 ;; mis-scanned /=
6359 (js2-add-to-string ?=)
6360 (if (not (eq start-tt js2-DIV))
6361 (error "failed assertion")))
6362 (while (and (not err)
6363 (or (/= (setq c (js2-get-char)) ?/)
6364 in-class))
6365 (cond
6366 ((or (= c ?\n)
6367 (= c js2-EOF_CHAR))
6368 (setf (js2-token-end token) (1- js2-ts-cursor)
6369 err t
6370 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6371 (js2-report-error "msg.unterminated.re.lit"))
6372 (t (cond
6373 ((= c ?\\)
6374 (js2-add-to-string c)
6375 (setq c (js2-get-char)))
6376 ((= c ?\[)
6377 (setq in-class t))
6378 ((= c ?\])
6379 (setq in-class nil)))
6380 (js2-add-to-string c))))
6381 (unless err
6382 (while continue
6383 (cond
6384 ((js2-match-char ?g)
6385 (push ?g flags))
6386 ((js2-match-char ?i)
6387 (push ?i flags))
6388 ((js2-match-char ?m)
6389 (push ?m flags))
6390 ((and (js2-match-char ?u)
6391 (>= js2-language-version 200))
6392 (push ?u flags))
6393 ((and (js2-match-char ?y)
6394 (>= js2-language-version 200))
6395 (push ?y flags))
6396 (t
6397 (setq continue nil))))
6398 (if (js2-alpha-p (js2-peek-char))
6399 (js2-report-scan-error "msg.invalid.re.flag" t
6400 js2-ts-cursor 1))
6401 (js2-set-string-from-buffer token))
6402 (js2-collect-string flags)))
6403
6404 (defun js2-get-first-xml-token ()
6405 (setq js2-ts-xml-open-tags-count 0
6406 js2-ts-is-xml-attribute nil
6407 js2-ts-xml-is-tag-content nil)
6408 (js2-unget-char)
6409 (js2-get-next-xml-token))
6410
6411 (defun js2-xml-discard-string (token)
6412 "Throw away the string in progress and flag an XML parse error."
6413 (setf js2-ts-string-buffer nil
6414 (js2-token-string token) nil)
6415 (js2-report-scan-error "msg.XML.bad.form" t))
6416
6417 (defun js2-get-next-xml-token ()
6418 (setq js2-ts-string-buffer nil) ; for recording the XML
6419 (let ((token (js2-new-token 0))
6420 c result)
6421 (setq result
6422 (catch 'return
6423 (while t
6424 (setq c (js2-get-char))
6425 (cond
6426 ((= c js2-EOF_CHAR)
6427 (throw 'return js2-ERROR))
6428 (js2-ts-xml-is-tag-content
6429 (cl-case c
6430 (?>
6431 (js2-add-to-string c)
6432 (setq js2-ts-xml-is-tag-content nil
6433 js2-ts-is-xml-attribute nil))
6434 (?/
6435 (js2-add-to-string c)
6436 (when (eq ?> (js2-peek-char))
6437 (setq c (js2-get-char))
6438 (js2-add-to-string c)
6439 (setq js2-ts-xml-is-tag-content nil)
6440 (cl-decf js2-ts-xml-open-tags-count)))
6441 (?{
6442 (js2-unget-char)
6443 (js2-set-string-from-buffer token)
6444 (throw 'return js2-XML))
6445 ((?\' ?\")
6446 (js2-add-to-string c)
6447 (unless (js2-read-quoted-string c token)
6448 (throw 'return js2-ERROR)))
6449 (?=
6450 (js2-add-to-string c)
6451 (setq js2-ts-is-xml-attribute t))
6452 ((? ?\t ?\r ?\n)
6453 (js2-add-to-string c))
6454 (t
6455 (js2-add-to-string c)
6456 (setq js2-ts-is-xml-attribute nil)))
6457 (when (and (not js2-ts-xml-is-tag-content)
6458 (zerop js2-ts-xml-open-tags-count))
6459 (js2-set-string-from-buffer token)
6460 (throw 'return js2-XMLEND)))
6461 (t
6462 ;; else not tag content
6463 (cl-case c
6464 (?<
6465 (js2-add-to-string c)
6466 (setq c (js2-peek-char))
6467 (cl-case c
6468 (?!
6469 (setq c (js2-get-char)) ;; skip !
6470 (js2-add-to-string c)
6471 (setq c (js2-peek-char))
6472 (cl-case c
6473 (?-
6474 (setq c (js2-get-char)) ;; skip -
6475 (js2-add-to-string c)
6476 (if (eq c ?-)
6477 (progn
6478 (js2-add-to-string c)
6479 (unless (js2-read-xml-comment token)
6480 (throw 'return js2-ERROR)))
6481 (js2-xml-discard-string token)
6482 (throw 'return js2-ERROR)))
6483 (?\[
6484 (setq c (js2-get-char)) ;; skip [
6485 (js2-add-to-string c)
6486 (if (and (= (js2-get-char) ?C)
6487 (= (js2-get-char) ?D)
6488 (= (js2-get-char) ?A)
6489 (= (js2-get-char) ?T)
6490 (= (js2-get-char) ?A)
6491 (= (js2-get-char) ?\[))
6492 (progn
6493 (js2-add-to-string ?C)
6494 (js2-add-to-string ?D)
6495 (js2-add-to-string ?A)
6496 (js2-add-to-string ?T)
6497 (js2-add-to-string ?A)
6498 (js2-add-to-string ?\[)
6499 (unless (js2-read-cdata token)
6500 (throw 'return js2-ERROR)))
6501 (js2-xml-discard-string token)
6502 (throw 'return js2-ERROR)))
6503 (t
6504 (unless (js2-read-entity token)
6505 (throw 'return js2-ERROR))))
6506 ;; Allow bare CDATA section, e.g.:
6507 ;; let xml = <![CDATA[ foo bar baz ]]>;
6508 (when (zerop js2-ts-xml-open-tags-count)
6509 (throw 'return js2-XMLEND)))
6510 (??
6511 (setq c (js2-get-char)) ;; skip ?
6512 (js2-add-to-string c)
6513 (unless (js2-read-PI token)
6514 (throw 'return js2-ERROR)))
6515 (?/
6516 ;; end tag
6517 (setq c (js2-get-char)) ;; skip /
6518 (js2-add-to-string c)
6519 (when (zerop js2-ts-xml-open-tags-count)
6520 (js2-xml-discard-string token)
6521 (throw 'return js2-ERROR))
6522 (setq js2-ts-xml-is-tag-content t)
6523 (cl-decf js2-ts-xml-open-tags-count))
6524 (t
6525 ;; start tag
6526 (setq js2-ts-xml-is-tag-content t)
6527 (cl-incf js2-ts-xml-open-tags-count))))
6528 (?{
6529 (js2-unget-char)
6530 (js2-set-string-from-buffer token)
6531 (throw 'return js2-XML))
6532 (t
6533 (js2-add-to-string c))))))))
6534 (setf (js2-token-end token) js2-ts-cursor)
6535 (setf (js2-token-type token) result)
6536 result))
6537
6538 (defun js2-read-quoted-string (quote token)
6539 (let (c)
6540 (catch 'return
6541 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6542 (js2-add-to-string c)
6543 (if (eq c quote)
6544 (throw 'return t)))
6545 (js2-xml-discard-string token) ;; throw away string in progress
6546 nil)))
6547
6548 (defun js2-read-xml-comment (token)
6549 (let ((c (js2-get-char)))
6550 (catch 'return
6551 (while (/= c js2-EOF_CHAR)
6552 (catch 'continue
6553 (js2-add-to-string c)
6554 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6555 (setq c (js2-get-char))
6556 (js2-add-to-string c)
6557 (if (eq (js2-peek-char) ?>)
6558 (progn
6559 (setq c (js2-get-char)) ;; skip >
6560 (js2-add-to-string c)
6561 (throw 'return t))
6562 (throw 'continue nil)))
6563 (setq c (js2-get-char))))
6564 (js2-xml-discard-string token)
6565 nil)))
6566
6567 (defun js2-read-cdata (token)
6568 (let ((c (js2-get-char)))
6569 (catch 'return
6570 (while (/= c js2-EOF_CHAR)
6571 (catch 'continue
6572 (js2-add-to-string c)
6573 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6574 (setq c (js2-get-char))
6575 (js2-add-to-string c)
6576 (if (eq (js2-peek-char) ?>)
6577 (progn
6578 (setq c (js2-get-char)) ;; Skip >
6579 (js2-add-to-string c)
6580 (throw 'return t))
6581 (throw 'continue nil)))
6582 (setq c (js2-get-char))))
6583 (js2-xml-discard-string token)
6584 nil)))
6585
6586 (defun js2-read-entity (token)
6587 (let ((decl-tags 1)
6588 c)
6589 (catch 'return
6590 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6591 (js2-add-to-string c)
6592 (cl-case c
6593 (?<
6594 (cl-incf decl-tags))
6595 (?>
6596 (cl-decf decl-tags)
6597 (if (zerop decl-tags)
6598 (throw 'return t)))))
6599 (js2-xml-discard-string token)
6600 nil)))
6601
6602 (defun js2-read-PI (token)
6603 "Scan an XML processing instruction."
6604 (let (c)
6605 (catch 'return
6606 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6607 (js2-add-to-string c)
6608 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6609 (setq c (js2-get-char)) ;; Skip >
6610 (js2-add-to-string c)
6611 (throw 'return t)))
6612 (js2-xml-discard-string token)
6613 nil)))
6614
6615 ;;; Highlighting
6616
6617 (defun js2-set-face (beg end face &optional record)
6618 "Fontify a region. If RECORD is non-nil, record for later."
6619 (when (cl-plusp js2-highlight-level)
6620 (setq beg (min (point-max) beg)
6621 beg (max (point-min) beg)
6622 end (min (point-max) end)
6623 end (max (point-min) end))
6624 (if record
6625 (push (list beg end face) js2-mode-fontifications)
6626 (put-text-property beg end 'font-lock-face face))))
6627
6628 (defsubst js2-clear-face (beg end)
6629 (remove-text-properties beg end '(font-lock-face nil
6630 help-echo nil
6631 point-entered nil
6632 cursor-sensor-functions nil
6633 c-in-sws nil)))
6634
6635 (defconst js2-ecma-global-props
6636 (concat "^"
6637 (regexp-opt
6638 '("Infinity" "NaN" "undefined" "arguments") t)
6639 "$")
6640 "Value properties of the Ecma-262 Global Object.
6641 Shown at or above `js2-highlight-level' 2.")
6642
6643 ;; might want to add the name "arguments" to this list?
6644 (defconst js2-ecma-object-props
6645 (concat "^"
6646 (regexp-opt
6647 '("prototype" "__proto__" "__parent__") t)
6648 "$")
6649 "Value properties of the Ecma-262 Object constructor.
6650 Shown at or above `js2-highlight-level' 2.")
6651
6652 (defconst js2-ecma-global-funcs
6653 (concat
6654 "^"
6655 (regexp-opt
6656 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6657 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6658 "$")
6659 "Function properties of the Ecma-262 Global object.
6660 Shown at or above `js2-highlight-level' 2.")
6661
6662 (defconst js2-ecma-number-props
6663 (concat "^"
6664 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6665 "NEGATIVE_INFINITY"
6666 "POSITIVE_INFINITY") t)
6667 "$")
6668 "Properties of the Ecma-262 Number constructor.
6669 Shown at or above `js2-highlight-level' 2.")
6670
6671 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6672 "Properties of the Ecma-262 Date constructor.
6673 Shown at or above `js2-highlight-level' 2.")
6674
6675 (defconst js2-ecma-math-props
6676 (concat "^"
6677 (regexp-opt
6678 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6679 t)
6680 "$")
6681 "Properties of the Ecma-262 Math object.
6682 Shown at or above `js2-highlight-level' 2.")
6683
6684 (defconst js2-ecma-math-funcs
6685 (concat "^"
6686 (regexp-opt
6687 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6688 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6689 "$")
6690 "Function properties of the Ecma-262 Math object.
6691 Shown at or above `js2-highlight-level' 2.")
6692
6693 (defconst js2-ecma-function-props
6694 (concat
6695 "^"
6696 (regexp-opt
6697 '(;; properties of the Object prototype object
6698 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6699 "toLocaleString" "toString" "valueOf"
6700 ;; properties of the Function prototype object
6701 "apply" "call"
6702 ;; properties of the Array prototype object
6703 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6704 "splice" "unshift"
6705 ;; properties of the String prototype object
6706 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6707 "localeCompare" "match" "replace" "search" "split" "substring"
6708 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6709 "toUpperCase"
6710 ;; properties of the Number prototype object
6711 "toExponential" "toFixed" "toPrecision"
6712 ;; properties of the Date prototype object
6713 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6714 "getMinutes" "getMonth" "getSeconds" "getTime"
6715 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6716 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6717 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6718 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6719 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6720 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6721 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6722 "toTimeString" "toUTCString"
6723 ;; properties of the RegExp prototype object
6724 "exec" "test"
6725 ;; properties of the JSON prototype object
6726 "parse" "stringify"
6727 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6728 "toSource" "__defineGetter__" "__defineSetter__"
6729 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6730 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6731 t)
6732 "$")
6733 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6734 Shown at or above `js2-highlight-level' 3.")
6735
6736 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6737 (let ((target-name (and target
6738 (js2-name-node-p target)
6739 (js2-name-node-name target)))
6740 (prop-name (if prop (js2-name-node-name prop)))
6741 (level2 (>= js2-highlight-level 2))
6742 (level3 (>= js2-highlight-level 3)))
6743 (when level2
6744 (let ((face
6745 (if call-p
6746 (cond
6747 ((and target prop)
6748 (cond
6749 ((and level3 (string-match js2-ecma-function-props prop-name))
6750 'font-lock-builtin-face)
6751 ((and target-name prop)
6752 (cond
6753 ((string= target-name "Date")
6754 (if (string-match js2-ecma-date-props prop-name)
6755 'font-lock-builtin-face))
6756 ((string= target-name "Math")
6757 (if (string-match js2-ecma-math-funcs prop-name)
6758 'font-lock-builtin-face))))))
6759 (prop
6760 (if (string-match js2-ecma-global-funcs prop-name)
6761 'font-lock-builtin-face)))
6762 (cond
6763 ((and target prop)
6764 (cond
6765 ((string= target-name "Number")
6766 (if (string-match js2-ecma-number-props prop-name)
6767 'font-lock-constant-face))
6768 ((string= target-name "Math")
6769 (if (string-match js2-ecma-math-props prop-name)
6770 'font-lock-constant-face))))
6771 (prop
6772 (if (string-match js2-ecma-object-props prop-name)
6773 'font-lock-constant-face))))))
6774 (when (and (not face) target (not call-p) prop-name)
6775 (setq face 'js2-object-property))
6776 (when face
6777 (let ((pos (+ (js2-node-pos parent) ; absolute
6778 (js2-node-pos prop)))) ; relative
6779 (js2-set-face pos
6780 (+ pos (js2-node-len prop))
6781 face 'record)))))))
6782
6783 (defun js2-parse-highlight-member-expr-node (node)
6784 "Perform syntax highlighting of EcmaScript built-in properties.
6785 The variable `js2-highlight-level' governs this highlighting."
6786 (let (face target prop name pos end parent call-p callee)
6787 (cond
6788 ;; case 1: simple name, e.g. foo
6789 ((js2-name-node-p node)
6790 (setq name (js2-name-node-name node))
6791 ;; possible for name to be nil in rare cases - saw it when
6792 ;; running js2-mode on an elisp buffer. Might as well try to
6793 ;; make it so js2-mode never barfs.
6794 (when name
6795 (setq face (if (string-match js2-ecma-global-props name)
6796 'font-lock-constant-face))
6797 (when face
6798 (setq pos (js2-node-pos node)
6799 end (+ pos (js2-node-len node)))
6800 (js2-set-face pos end face 'record))))
6801 ;; case 2: property access or function call
6802 ((or (js2-prop-get-node-p node)
6803 ;; highlight function call if expr is a prop-get node
6804 ;; or a plain name (i.e. unqualified function call)
6805 (and (setq call-p (js2-call-node-p node))
6806 (setq callee (js2-call-node-target node)) ; separate setq!
6807 (or (js2-prop-get-node-p callee)
6808 (js2-name-node-p callee))))
6809 (setq parent node
6810 node (if call-p callee node))
6811 (if (and call-p (js2-name-node-p callee))
6812 (setq prop callee)
6813 (setq target (js2-prop-get-node-left node)
6814 prop (js2-prop-get-node-right node)))
6815 (cond
6816 ((js2-name-node-p prop)
6817 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6818 (js2-parse-highlight-prop-get parent target prop call-p))
6819 ((js2-name-node-p target)
6820 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6821 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6822
6823 (defun js2-parse-highlight-member-expr-fn-name (expr)
6824 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6825 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6826 We currently only handle the case where the last component is a prop-get
6827 of a simple name. Called before EXPR has a parent node."
6828 (let (pos
6829 (name (and (js2-prop-get-node-p expr)
6830 (js2-prop-get-node-right expr))))
6831 (when (js2-name-node-p name)
6832 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6833 (js2-node-pos name)))
6834 (+ pos (js2-node-len name))
6835 'font-lock-function-name-face
6836 'record))))
6837
6838 ;; source: http://jsdoc.sourceforge.net/
6839 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6840 ;; allows type specifications, and needs work before entering the wild.
6841
6842 (defconst js2-jsdoc-param-tag-regexp
6843 (concat "^\\s-*\\*+\\s-*\\(@"
6844 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6845 "\\)"
6846 "\\s-*\\({[^}]+}\\)?" ; optional type
6847 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6848 "\\_>")
6849 "Matches jsdoc tags with optional type and optional param name.")
6850
6851 (defconst js2-jsdoc-typed-tag-regexp
6852 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6853 (regexp-opt
6854 '("enum"
6855 "extends"
6856 "field"
6857 "id"
6858 "implements"
6859 "lends"
6860 "mods"
6861 "requires"
6862 "return"
6863 "returns"
6864 "throw"
6865 "throws"))
6866 "\\)\\)\\s-*\\({[^}]+}\\)?")
6867 "Matches jsdoc tags with optional type.")
6868
6869 (defconst js2-jsdoc-arg-tag-regexp
6870 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6871 (regexp-opt
6872 '("alias"
6873 "augments"
6874 "borrows"
6875 "bug"
6876 "base"
6877 "config"
6878 "default"
6879 "define"
6880 "exception"
6881 "function"
6882 "member"
6883 "memberOf"
6884 "name"
6885 "namespace"
6886 "since"
6887 "suppress"
6888 "this"
6889 "throws"
6890 "type"
6891 "version"))
6892 "\\)\\)\\s-+\\([^ \t]+\\)")
6893 "Matches jsdoc tags with a single argument.")
6894
6895 (defconst js2-jsdoc-empty-tag-regexp
6896 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6897 (regexp-opt
6898 '("addon"
6899 "author"
6900 "class"
6901 "const"
6902 "constant"
6903 "constructor"
6904 "constructs"
6905 "deprecated"
6906 "desc"
6907 "description"
6908 "event"
6909 "example"
6910 "exec"
6911 "export"
6912 "fileoverview"
6913 "final"
6914 "function"
6915 "hidden"
6916 "ignore"
6917 "implicitCast"
6918 "inheritDoc"
6919 "inner"
6920 "interface"
6921 "license"
6922 "noalias"
6923 "noshadow"
6924 "notypecheck"
6925 "override"
6926 "owner"
6927 "preserve"
6928 "preserveTry"
6929 "private"
6930 "protected"
6931 "public"
6932 "static"
6933 "supported"
6934 ))
6935 "\\)\\)\\s-*")
6936 "Matches empty jsdoc tags.")
6937
6938 (defconst js2-jsdoc-link-tag-regexp
6939 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6940 "Matches a jsdoc link or code tag.")
6941
6942 (defconst js2-jsdoc-see-tag-regexp
6943 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6944 "Matches a jsdoc @see tag.")
6945
6946 (defconst js2-jsdoc-html-tag-regexp
6947 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6948 "Matches a simple (no attributes) html start- or end-tag.")
6949
6950 (defun js2-jsdoc-highlight-helper ()
6951 (js2-set-face (match-beginning 1)
6952 (match-end 1)
6953 'js2-jsdoc-tag)
6954 (if (match-beginning 2)
6955 (if (save-excursion
6956 (goto-char (match-beginning 2))
6957 (= (char-after) ?{))
6958 (js2-set-face (1+ (match-beginning 2))
6959 (1- (match-end 2))
6960 'js2-jsdoc-type)
6961 (js2-set-face (match-beginning 2)
6962 (match-end 2)
6963 'js2-jsdoc-value)))
6964 (if (match-beginning 3)
6965 (js2-set-face (match-beginning 3)
6966 (match-end 3)
6967 'js2-jsdoc-value)))
6968
6969 (defun js2-highlight-jsdoc (ast)
6970 "Highlight doc comment tags."
6971 (let ((comments (js2-ast-root-comments ast))
6972 beg end)
6973 (save-excursion
6974 (dolist (node comments)
6975 (when (eq (js2-comment-node-format node) 'jsdoc)
6976 (setq beg (js2-node-abs-pos node)
6977 end (+ beg (js2-node-len node)))
6978 (save-restriction
6979 (narrow-to-region beg end)
6980 (dolist (re (list js2-jsdoc-param-tag-regexp
6981 js2-jsdoc-typed-tag-regexp
6982 js2-jsdoc-arg-tag-regexp
6983 js2-jsdoc-link-tag-regexp
6984 js2-jsdoc-see-tag-regexp
6985 js2-jsdoc-empty-tag-regexp))
6986 (goto-char beg)
6987 (while (re-search-forward re nil t)
6988 (js2-jsdoc-highlight-helper)))
6989 ;; simple highlighting for html tags
6990 (goto-char beg)
6991 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6992 (js2-set-face (match-beginning 1)
6993 (match-end 1)
6994 'js2-jsdoc-html-tag-delimiter)
6995 (js2-set-face (match-beginning 2)
6996 (match-end 2)
6997 'js2-jsdoc-html-tag-name)
6998 (js2-set-face (match-beginning 3)
6999 (match-end 3)
7000 'js2-jsdoc-html-tag-delimiter))))))))
7001
7002 (defun js2-highlight-assign-targets (_node left right)
7003 "Highlight function properties and external variables."
7004 (let (leftpos name)
7005 ;; highlight vars and props assigned function values
7006 (when (or (js2-function-node-p right)
7007 (js2-class-node-p right))
7008 (cond
7009 ;; var foo = function() {...}
7010 ((js2-name-node-p left)
7011 (setq name left))
7012 ;; foo.bar.baz = function() {...}
7013 ((and (js2-prop-get-node-p left)
7014 (js2-name-node-p (js2-prop-get-node-right left)))
7015 (setq name (js2-prop-get-node-right left))))
7016 (when name
7017 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7018 (+ leftpos (js2-node-len name))
7019 'font-lock-function-name-face
7020 'record)))))
7021
7022 (defun js2-record-name-node (node)
7023 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7024 later. NODE must be a name node."
7025 (let ((leftpos (js2-node-abs-pos node)))
7026 (push (list node js2-current-scope
7027 leftpos
7028 (+ leftpos (js2-node-len node)))
7029 js2-recorded-identifiers)))
7030
7031 (defun js2-highlight-undeclared-vars ()
7032 "After entire parse is finished, look for undeclared variable references.
7033 We have to wait until entire buffer is parsed, since JavaScript permits var
7034 decls to occur after they're used.
7035
7036 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7037 it is considered declared."
7038 (let (name)
7039 (dolist (entry js2-recorded-identifiers)
7040 (cl-destructuring-bind (name-node scope pos end) entry
7041 (setq name (js2-name-node-name name-node))
7042 (unless (or (member name js2-global-externs)
7043 (member name js2-default-externs)
7044 (member name js2-additional-externs)
7045 (js2-get-defining-scope scope name pos))
7046 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7047 'js2-external-variable))))))
7048
7049 (defun js2--add-or-update-symbol (symbol inition used vars)
7050 "Add or update SYMBOL entry in VARS, an hash table.
7051 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7052 respectively meaning that SYMBOL is a mere declaration, an
7053 assignment or a function parameter; when USED is t, the symbol
7054 node is assumed to be an usage and thus added to the list stored
7055 in the cdr of the entry.
7056 "
7057 (let* ((nm (js2-name-node-name symbol))
7058 (es (js2-node-get-enclosing-scope symbol))
7059 (ds (js2-get-defining-scope es nm)))
7060 (when (and ds (not (equal nm "arguments")))
7061 (let* ((sym (js2-scope-get-symbol ds nm))
7062 (var (gethash sym vars))
7063 (err-var-p (js2-catch-node-p ds)))
7064 (unless inition
7065 (setq inition err-var-p))
7066 (if var
7067 (progn
7068 (when (and inition (not (equal (car var) ?P)))
7069 (setcar var inition))
7070 (when used
7071 (push symbol (cdr var))))
7072 ;; do not consider the declaration of catch parameter as an usage
7073 (when (and err-var-p used)
7074 (setq used nil))
7075 (puthash sym (cons inition (if used (list symbol))) vars))))))
7076
7077 (defun js2--classify-variables ()
7078 "Collect and classify variables declared or used within js2-mode-ast.
7079 Traverse the whole ast tree returning a summary of the variables
7080 usage as an hash-table, keyed by their corresponding symbol table
7081 entry.
7082 Each variable is described by a tuple where the car is a flag
7083 indicating whether the variable has been initialized and the cdr
7084 is a possibly empty list of name nodes where it is used. External
7085 symbols, i.e. those not present in the whole scopes hierarchy,
7086 are ignored."
7087 (let ((vars (make-hash-table :test #'eq :size 100)))
7088 (js2-visit-ast
7089 js2-mode-ast
7090 (lambda (node end-p)
7091 (when (null end-p)
7092 (cond
7093 ((js2-var-init-node-p node)
7094 ;; take note about possibly initialized declarations
7095 (let ((target (js2-var-init-node-target node))
7096 (initializer (js2-var-init-node-initializer node)))
7097 (when target
7098 (let* ((parent (js2-node-parent node))
7099 (grandparent (if parent (js2-node-parent parent)))
7100 (inited (not (null initializer))))
7101 (unless inited
7102 (setq inited
7103 (and grandparent
7104 (js2-for-in-node-p grandparent)
7105 (memq target
7106 (mapcar #'js2-var-init-node-target
7107 (js2-var-decl-node-kids
7108 (js2-for-in-node-iterator grandparent)))))))
7109 (js2--add-or-update-symbol target inited nil vars)))))
7110
7111 ((js2-assign-node-p node)
7112 ;; take note about assignments
7113 (let ((left (js2-assign-node-left node)))
7114 (when (js2-name-node-p left)
7115 (js2--add-or-update-symbol left t nil vars))))
7116
7117 ((js2-prop-get-node-p node)
7118 ;; handle x.y.z nodes, considering only x
7119 (let ((left (js2-prop-get-node-left node)))
7120 (when (js2-name-node-p left)
7121 (js2--add-or-update-symbol left nil t vars))))
7122
7123 ((js2-name-node-p node)
7124 ;; take note about used variables
7125 (let ((parent (js2-node-parent node)))
7126 (when parent
7127 (unless (or (and (js2-var-init-node-p parent) ; handled above
7128 (eq node (js2-var-init-node-target parent)))
7129 (and (js2-assign-node-p parent)
7130 (eq node (js2-assign-node-left parent)))
7131 (js2-prop-get-node-p parent))
7132 (let ((used t) inited)
7133 (cond
7134 ((and (js2-function-node-p parent)
7135 (js2-wrapper-function-p parent))
7136 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7137
7138 ((js2-for-in-node-p parent)
7139 (if (eq node (js2-for-in-node-iterator parent))
7140 (setq inited t used nil)))
7141
7142 ((js2-function-node-p parent)
7143 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7144 used nil)))
7145
7146 (unless used
7147 (let ((grandparent (js2-node-parent parent)))
7148 (when grandparent
7149 (setq used (js2-return-node-p grandparent)))))
7150
7151 (js2--add-or-update-symbol node inited used vars))))))))
7152 t))
7153 vars))
7154
7155 (defun js2--get-name-node (node)
7156 (cond
7157 ((js2-name-node-p node) node)
7158 ((js2-function-node-p node)
7159 (js2-function-node-name node))
7160 ((js2-class-node-p node)
7161 (js2-class-node-name node))
7162 ((js2-comp-loop-node-p node)
7163 (js2-comp-loop-node-iterator node))
7164 (t node)))
7165
7166 (defun js2--highlight-unused-variable (symbol info)
7167 (let ((name (js2-symbol-name symbol))
7168 (inited (car info))
7169 (refs (cdr info))
7170 pos len)
7171 (unless (and inited refs)
7172 (if refs
7173 (dolist (ref refs)
7174 (setq pos (js2-node-abs-pos ref))
7175 (setq len (js2-name-node-len ref))
7176 (js2-report-warning "msg.uninitialized.variable" name pos len
7177 'js2-warning))
7178 (when (or js2-warn-about-unused-function-arguments
7179 (not (eq inited ?P)))
7180 (let* ((symn (js2-symbol-ast-node symbol))
7181 (namen (js2--get-name-node symn)))
7182 (unless (js2-node-top-level-decl-p namen)
7183 (setq pos (js2-node-abs-pos namen))
7184 (setq len (js2-name-node-len namen))
7185 (js2-report-warning "msg.unused.variable" name pos len
7186 'js2-warning))))))))
7187
7188 (defun js2-highlight-unused-variables ()
7189 "Highlight unused variables."
7190 (let ((vars (js2--classify-variables)))
7191 (maphash #'js2--highlight-unused-variable vars)))
7192
7193 ;;;###autoload
7194 (define-minor-mode js2-highlight-unused-variables-mode
7195 "Toggle highlight of unused variables."
7196 :lighter ""
7197 (if js2-highlight-unused-variables-mode
7198 (add-hook 'js2-post-parse-callbacks
7199 #'js2-highlight-unused-variables nil t)
7200 (remove-hook 'js2-post-parse-callbacks
7201 #'js2-highlight-unused-variables t)))
7202
7203 (defun js2-set-default-externs ()
7204 "Set the value of `js2-default-externs' based on the various
7205 `js2-include-?-externs' variables."
7206 (setq js2-default-externs
7207 (append js2-ecma-262-externs
7208 (if js2-include-browser-externs js2-browser-externs)
7209 (if (and js2-include-browser-externs
7210 (>= js2-language-version 200)) js2-harmony-externs)
7211 (if js2-include-rhino-externs js2-rhino-externs)
7212 (if js2-include-node-externs js2-node-externs)
7213 (if (or js2-include-browser-externs js2-include-node-externs)
7214 js2-typed-array-externs))))
7215
7216 (defun js2-apply-jslint-globals ()
7217 (setq js2-additional-externs
7218 (nconc (js2-get-jslint-globals)
7219 js2-additional-externs)))
7220
7221 (defun js2-get-jslint-globals ()
7222 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7223 when (and (eq 'block (js2-comment-node-format node))
7224 (save-excursion
7225 (goto-char (js2-node-abs-pos node))
7226 (looking-at "/\\*global ")))
7227 append (js2-get-jslint-globals-in
7228 (match-end 0)
7229 (js2-node-abs-end node))))
7230
7231 (defun js2-get-jslint-globals-in (beg end)
7232 (let (res)
7233 (save-excursion
7234 (goto-char beg)
7235 (while (re-search-forward js2-mode-identifier-re end t)
7236 (let ((match (match-string 0)))
7237 (unless (member match '("true" "false"))
7238 (push match res)))))
7239 (nreverse res)))
7240
7241 ;;; IMenu support
7242
7243 ;; We currently only support imenu, but eventually should support speedbar and
7244 ;; possibly other browsing mechanisms.
7245
7246 ;; The basic strategy is to identify function assignment targets of the form
7247 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7248 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7249 ;; for imenu after parsing is finished.
7250
7251 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7252 ;; JavaScript, and the general problem is undecidable. However, several forms
7253 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7254 ;; include:
7255
7256 ;; function foo() -- function declaration
7257 ;; foo = function() -- function expression assigned to variable
7258 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7259 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7260 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7261 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7262 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7263 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7264 ;; function foo() {function bar() {...}} -- nested function
7265 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7266
7267 ;; This list boils down to a few forms that can be combined recursively.
7268 ;; Top-level named function declarations include both the left-hand (name)
7269 ;; and the right-hand (function value) expressions needed to produce an imenu
7270 ;; entry. The other "right-hand" forms we need to look for are:
7271 ;; - functions declared as props/getters/setters in object literals
7272 ;; - nested named function declarations
7273 ;; The "left-hand" expressions that functions can be assigned to include:
7274 ;; - local/global variables
7275 ;; - nested property-get expressions like a.b.c.d
7276 ;; - element gets like foo[10] or foo['bar'] where the index
7277 ;; expression can be trivially converted to a property name. They
7278 ;; effectively then become property gets.
7279
7280 ;; All the different definition types are canonicalized into the form
7281 ;; foo.bar.baz = position-of-function-keyword
7282
7283 ;; We need to build a trie-like structure for imenu. As an example,
7284 ;; consider the following JavaScript code:
7285
7286 ;; a = function() {...} // function at position 5
7287 ;; b = function() {...} // function at position 25
7288 ;; foo = function() {...} // function at position 100
7289 ;; foo.bar = function() {...} // function at position 200
7290 ;; foo.bar.baz = function() {...} // function at position 300
7291 ;; foo.bar.zab = function() {...} // function at position 400
7292
7293 ;; During parsing we accumulate an entry for each definition in
7294 ;; the variable `js2-imenu-recorder', like so:
7295
7296 ;; '((fn a 5)
7297 ;; (fn b 25)
7298 ;; (fn foo 100)
7299 ;; (fn foo bar 200)
7300 ;; (fn foo bar baz 300)
7301 ;; (fn foo bar zab 400))
7302
7303 ;; Where 'fn' is the respective function node.
7304 ;; After parsing these entries are merged into this alist-trie:
7305
7306 ;; '((a . 1)
7307 ;; (b . 2)
7308 ;; (foo (<definition> . 3)
7309 ;; (bar (<definition> . 6)
7310 ;; (baz . 100)
7311 ;; (zab . 200))))
7312
7313 ;; Note the wacky need for a <definition> name. The token can be anything
7314 ;; that isn't a valid JavaScript identifier, because you might make foo
7315 ;; a function and then start setting properties on it that are also functions.
7316
7317 (defun js2-prop-node-name (node)
7318 "Return the name of a node that may be a property-get/property-name.
7319 If NODE is not a valid name-node, string-node or integral number-node,
7320 returns nil. Otherwise returns the string name/value of the node."
7321 (cond
7322 ((js2-name-node-p node)
7323 (js2-name-node-name node))
7324 ((js2-string-node-p node)
7325 (js2-string-node-value node))
7326 ((and (js2-number-node-p node)
7327 (string-match "^[0-9]+$" (js2-number-node-value node)))
7328 (js2-number-node-value node))
7329 ((eq (js2-node-type node) js2-THIS)
7330 "this")
7331 ((eq (js2-node-type node) js2-SUPER)
7332 "super")))
7333
7334 (defun js2-node-qname-component (node)
7335 "Return the name of this node, if it contributes to a qname.
7336 Returns nil if the node doesn't contribute."
7337 (copy-sequence
7338 (or (js2-prop-node-name node)
7339 (if (and (js2-function-node-p node)
7340 (js2-function-node-name node))
7341 (js2-name-node-name (js2-function-node-name node))))))
7342
7343 (defun js2-record-imenu-entry (fn-node qname pos)
7344 "Add an entry to `js2-imenu-recorder'.
7345 FN-NODE should be the current item's function node.
7346
7347 Associate FN-NODE with its QNAME for later lookup.
7348 This is used in postprocessing the chain list. For each chain, we find
7349 the parent function, look up its qname, then prepend a copy of it to the chain."
7350 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7351 (unless js2-imenu-function-map
7352 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7353 (puthash fn-node qname js2-imenu-function-map))
7354
7355 (defun js2-record-imenu-functions (node &optional var)
7356 "Record function definitions for imenu.
7357 NODE is a function node or an object literal.
7358 VAR, if non-nil, is the expression that NODE is being assigned to.
7359 When passed arguments of wrong type, does nothing."
7360 (when js2-parse-ide-mode
7361 (let ((fun-p (js2-function-node-p node))
7362 qname fname-node)
7363 (cond
7364 ;; non-anonymous function declaration?
7365 ((and fun-p
7366 (not var)
7367 (setq fname-node (js2-function-node-name node)))
7368 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7369 ;; for remaining forms, compute left-side tree branch first
7370 ((and var (setq qname (js2-compute-nested-prop-get var)))
7371 (cond
7372 ;; foo.bar.baz = function
7373 (fun-p
7374 (js2-record-imenu-entry node qname (js2-node-pos node)))
7375 ;; foo.bar.baz = object-literal
7376 ;; look for nested functions: {a: {b: function() {...} }}
7377 ((js2-object-node-p node)
7378 ;; Node position here is still absolute, since the parser
7379 ;; passes the assignment target and value expressions
7380 ;; to us before they are added as children of the assignment node.
7381 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7382
7383 (defun js2-compute-nested-prop-get (node)
7384 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7385 component nodes as a list. Otherwise return nil. Element-gets are treated
7386 as property-gets if the index expression is a string, or a positive integer."
7387 (let (left right head)
7388 (cond
7389 ((or (js2-name-node-p node)
7390 (js2-this-or-super-node-p node))
7391 (list node))
7392 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7393 ((js2-prop-get-node-p node) ; foo.bar
7394 (setq left (js2-prop-get-node-left node)
7395 right (js2-prop-get-node-right node))
7396 (if (setq head (js2-compute-nested-prop-get left))
7397 (nconc head (list right))))
7398 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7399 (setq left (js2-elem-get-node-target node)
7400 right (js2-elem-get-node-element node))
7401 (if (or (js2-string-node-p right) ; ['bar']
7402 (and (js2-number-node-p right) ; [10]
7403 (string-match "^[0-9]+$"
7404 (js2-number-node-value right))))
7405 (if (setq head (js2-compute-nested-prop-get left))
7406 (nconc head (list right))))))))
7407
7408 (defun js2-record-object-literal (node qname pos)
7409 "Recursively process an object literal looking for functions.
7410 NODE is an object literal that is the right-hand child of an assignment
7411 expression. QNAME is a list of nodes representing the assignment target,
7412 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7413 POS is the absolute position of the node.
7414 We do a depth-first traversal of NODE. For any functions we find,
7415 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7416 (let (right)
7417 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7418 (let ((left (js2-infix-node-left e))
7419 ;; Element positions are relative to the parent position.
7420 (pos (+ pos (js2-node-pos e))))
7421 (cond
7422 ;; foo: function() {...}
7423 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7424 (when (js2-prop-node-name left)
7425 ;; As a policy decision, we record the position of the property,
7426 ;; not the position of the `function' keyword, since the property
7427 ;; is effectively the name of the function.
7428 (js2-record-imenu-entry right (append qname (list left)) pos)))
7429 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7430 ((js2-object-node-p right)
7431 (js2-record-object-literal right
7432 (append qname (list (js2-infix-node-left e)))
7433 (+ pos (js2-node-pos right)))))))))
7434
7435 (defun js2-node-top-level-decl-p (node)
7436 "Return t if NODE's name is defined in the top-level scope.
7437 Also returns t if NODE's name is not defined in any scope, since it implies
7438 that it's an external variable, which must also be in the top-level scope."
7439 (let* ((name (js2-prop-node-name node))
7440 (this-scope (js2-node-get-enclosing-scope node))
7441 defining-scope)
7442 (cond
7443 ((js2-this-or-super-node-p node)
7444 nil)
7445 ((null this-scope)
7446 t)
7447 ((setq defining-scope (js2-get-defining-scope this-scope name))
7448 (js2-ast-root-p defining-scope))
7449 (t t))))
7450
7451 (defun js2-wrapper-function-p (node)
7452 "Return t if NODE is a function expression that's immediately invoked.
7453 NODE must be `js2-function-node'."
7454 (let ((parent (js2-node-parent node)))
7455 (or
7456 ;; function(){...}();
7457 (and (js2-call-node-p parent)
7458 (eq node (js2-call-node-target parent)))
7459 (and (js2-paren-node-p parent)
7460 ;; (function(){...})();
7461 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7462 ;; (function(){...}).call(this);
7463 (and (js2-prop-get-node-p parent)
7464 (member (js2-name-node-name (js2-prop-get-node-right parent))
7465 '("call" "apply"))
7466 (js2-call-node-p (js2-node-parent parent))))))))
7467
7468 (defun js2-browse-postprocess-chains ()
7469 "Modify function-declaration name chains after parsing finishes.
7470 Some of the information is only available after the parse tree is complete.
7471 For instance, processing a nested scope requires a parent function node."
7472 (let (result fn parent-qname p elem)
7473 (dolist (entry js2-imenu-recorder)
7474 ;; function node goes first
7475 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7476 ;; Examine head's defining scope:
7477 ;; Pre-processed chain, or top-level/external, keep as-is.
7478 (if (or (stringp head) (js2-node-top-level-decl-p head))
7479 (push chain result)
7480 (when (js2-this-or-super-node-p head)
7481 (setq chain (cdr chain))) ; discard this-node
7482 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7483 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7484 (when (eq parent-qname 'not-found)
7485 ;; anonymous function expressions are not recorded
7486 ;; during the parse, so we need to handle this case here
7487 (setq parent-qname
7488 (if (js2-wrapper-function-p fn)
7489 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7490 (if (js2-ast-root-p grandparent)
7491 nil
7492 (gethash grandparent js2-imenu-function-map 'skip)))
7493 'skip))
7494 (puthash fn parent-qname js2-imenu-function-map))
7495 (if (eq parent-qname 'skip)
7496 ;; We don't show it, let's record that fact.
7497 (remhash current-fn js2-imenu-function-map)
7498 ;; Prepend parent fn qname to this chain.
7499 (let ((qname (append parent-qname chain)))
7500 (puthash current-fn (butlast qname) js2-imenu-function-map)
7501 (push qname result)))))))
7502 ;; Collect chains obtained by third-party code.
7503 (let (js2-imenu-recorder)
7504 (run-hooks 'js2-build-imenu-callbacks)
7505 (dolist (entry js2-imenu-recorder)
7506 (push (cdr entry) result)))
7507 ;; Finally replace each node in each chain with its name.
7508 (dolist (chain result)
7509 (setq p chain)
7510 (while p
7511 (if (js2-node-p (setq elem (car p)))
7512 (setcar p (js2-node-qname-component elem)))
7513 (setq p (cdr p))))
7514 result))
7515
7516 ;; Merge name chains into a trie-like tree structure of nested lists.
7517 ;; To simplify construction of the trie, we first build it out using the rule
7518 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7519 ;; [key, num-or-list]. The second element can be a number; if so, this key
7520 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7521 ;; associated with the key at this level.) Otherwise the second element is
7522 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7523 ;; a simple recursive formulation.
7524 ;;
7525 ;; js2-mode is building the data structure for imenu. The imenu documentation
7526 ;; claims that it's the structure above, but in practice it wants the children
7527 ;; at the same list level as the key for that level, which is how I've drawn
7528 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7529 ;; list wrapper around the children at each level.
7530 ;;
7531 ;; A completed nested imenu-alist entry looks like this:
7532 ;; '(("foo"
7533 ;; ("<definition>" . 7)
7534 ;; ("bar"
7535 ;; ("a" . 40)
7536 ;; ("b" . 60))))
7537 ;;
7538 ;; In particular, the documentation for `imenu--index-alist' says that
7539 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7540 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7541
7542 (defun js2-treeify (lst)
7543 "Convert (a b c d) to (a ((b ((c d)))))."
7544 (if (null (cddr lst)) ; list length <= 2
7545 lst
7546 (list (car lst) (list (js2-treeify (cdr lst))))))
7547
7548 (defun js2-build-alist-trie (chains trie)
7549 "Merge declaration name chains into a trie-like alist structure for imenu.
7550 CHAINS is the qname chain list produced during parsing. TRIE is a
7551 list of elements built up so far."
7552 (let (head tail pos branch kids)
7553 (dolist (chain chains)
7554 (setq head (car chain)
7555 tail (cdr chain)
7556 pos (if (numberp (car tail)) (car tail))
7557 branch (js2-find-if (lambda (n)
7558 (string= (car n) head))
7559 trie)
7560 kids (cl-second branch))
7561 (cond
7562 ;; case 1: this key isn't in the trie yet
7563 ((null branch)
7564 (if trie
7565 (setcdr (last trie) (list (js2-treeify chain)))
7566 (setq trie (list (js2-treeify chain)))))
7567 ;; case 2: key is present with a single number entry: replace w/ list
7568 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7569 ;; ("<definition>" 20)))
7570 ((numberp kids)
7571 (setcar (cdr branch)
7572 (list (list "<definition-1>" kids)
7573 (if pos
7574 (list "<definition-2>" pos)
7575 (js2-treeify tail)))))
7576 ;; case 3: key is there (with kids), and we're a number entry
7577 (pos
7578 (setcdr (last kids)
7579 (list
7580 (list (format "<definition-%d>"
7581 (1+ (cl-loop for kid in kids
7582 count (eq ?< (aref (car kid) 0)))))
7583 pos))))
7584 ;; case 4: key is there with kids, need to merge in our chain
7585 (t
7586 (js2-build-alist-trie (list tail) kids))))
7587 trie))
7588
7589 (defun js2-flatten-trie (trie)
7590 "Convert TRIE to imenu-format.
7591 Recurses through nodes, and for each one whose second element is a list,
7592 appends the list's flattened elements to the current element. Also
7593 changes the tails into conses. For instance, this pre-flattened trie
7594
7595 '(a ((b 20)
7596 (c ((d 30)
7597 (e 40)))))
7598
7599 becomes
7600
7601 '(a (b . 20)
7602 (c (d . 30)
7603 (e . 40)))
7604
7605 Note that the root of the trie has no key, just a list of chains.
7606 This is also true for the value of any key with multiple children,
7607 e.g. key 'c' in the example above."
7608 (cond
7609 ((listp (car trie))
7610 (mapcar #'js2-flatten-trie trie))
7611 (t
7612 (if (numberp (cl-second trie))
7613 (cons (car trie) (cl-second trie))
7614 ;; else pop list and append its kids
7615 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7616
7617 (defun js2-build-imenu-index ()
7618 "Turn `js2-imenu-recorder' into an imenu data structure."
7619 (when (eq js2-imenu-recorder 'empty)
7620 (setq js2-imenu-recorder nil))
7621 (let* ((chains (js2-browse-postprocess-chains))
7622 (result (js2-build-alist-trie chains nil)))
7623 (js2-flatten-trie result)))
7624
7625 (defun js2-test-print-chains (chains)
7626 "Print a list of qname chains.
7627 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7628 i.e. one or more nodes, and an integer position as the list tail."
7629 (mapconcat (lambda (chain)
7630 (concat "("
7631 (mapconcat (lambda (elem)
7632 (if (js2-node-p elem)
7633 (or (js2-node-qname-component elem)
7634 "nil")
7635 (number-to-string elem)))
7636 chain
7637 " ")
7638 ")"))
7639 chains
7640 "\n"))
7641
7642 ;;; Parser
7643
7644 (defconst js2-version "1.8.5"
7645 "Version of JavaScript supported.")
7646
7647 (defun js2-record-face (face &optional token)
7648 "Record a style run of FACE for TOKEN or the current token."
7649 (unless token (setq token (js2-current-token)))
7650 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7651
7652 (defsubst js2-node-end (n)
7653 "Computes the absolute end of node N.
7654 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7655 is only true until the node is added to its parent; i.e., while parsing."
7656 (+ (js2-node-pos n)
7657 (js2-node-len n)))
7658
7659 (defun js2-record-comment (token)
7660 "Record a comment in `js2-scanned-comments'."
7661 (let ((ct (js2-token-comment-type token))
7662 (beg (js2-token-beg token))
7663 (end (js2-token-end token)))
7664 (push (make-js2-comment-node :len (- end beg)
7665 :format ct)
7666 js2-scanned-comments)
7667 (when js2-parse-ide-mode
7668 (js2-record-face (if (eq ct 'jsdoc)
7669 'font-lock-doc-face
7670 'font-lock-comment-face)
7671 token)
7672 (when (memq ct '(html preprocessor))
7673 ;; Tell cc-engine the bounds of the comment.
7674 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7675
7676 (defun js2-peek-token ()
7677 "Return the next token type without consuming it.
7678 If `js2-ti-lookahead' is positive, return the type of next token
7679 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7680 (if (not (zerop js2-ti-lookahead))
7681 (js2-token-type
7682 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7683 (let ((tt (js2-get-token-internal nil)))
7684 (js2-unget-token)
7685 tt)))
7686
7687 (defalias 'js2-next-token 'js2-get-token)
7688
7689 (defun js2-match-token (match &optional dont-unget)
7690 "Get next token and return t if it matches MATCH, a bytecode.
7691 Returns nil and consumes nothing if MATCH is not the next token."
7692 (if (/= (js2-get-token) match)
7693 (ignore (unless dont-unget (js2-unget-token)))
7694 t))
7695
7696 (defun js2-match-contextual-kwd (name)
7697 "Consume and return t if next token is `js2-NAME', and its
7698 string is NAME. Returns nil and keeps current token otherwise."
7699 (if (or (/= (js2-get-token) js2-NAME)
7700 (not (string= (js2-current-token-string) name)))
7701 (progn
7702 (js2-unget-token)
7703 nil)
7704 (js2-record-face 'font-lock-keyword-face)
7705 t))
7706
7707 (defun js2-get-prop-name-token ()
7708 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7709
7710 (defun js2-match-prop-name ()
7711 "Consume token and return t if next token is a valid property name.
7712 If `js2-language-version' is >= 180, a keyword or reserved word
7713 is considered valid name as well."
7714 (if (eq js2-NAME (js2-get-prop-name-token))
7715 t
7716 (js2-unget-token)
7717 nil))
7718
7719 (defun js2-must-match-prop-name (msg-id &optional pos len)
7720 (if (js2-match-prop-name)
7721 t
7722 (js2-report-error msg-id nil pos len)
7723 nil))
7724
7725 (defun js2-peek-token-or-eol ()
7726 "Return js2-EOL if the next token immediately follows a newline.
7727 Else returns the next token. Used in situations where we don't
7728 consider certain token types valid if they are preceded by a newline.
7729 One example is the postfix ++ or -- operator, which has to be on the
7730 same line as its operand."
7731 (let ((tt (js2-get-token))
7732 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7733 (js2-unget-token)
7734 (if follows-eol
7735 js2-EOL
7736 tt)))
7737
7738 (defun js2-must-match (token msg-id &optional pos len)
7739 "Match next token to token code TOKEN, or record a syntax error.
7740 MSG-ID is the error message to report if the match fails.
7741 Returns t on match, nil if no match."
7742 (if (js2-match-token token t)
7743 t
7744 (js2-report-error msg-id nil pos len)
7745 (js2-unget-token)
7746 nil))
7747
7748 (defun js2-must-match-name (msg-id)
7749 (if (js2-match-token js2-NAME t)
7750 t
7751 (if (eq (js2-current-token-type) js2-RESERVED)
7752 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7753 (js2-report-error msg-id)
7754 (js2-unget-token))
7755 nil))
7756
7757 (defsubst js2-inside-function ()
7758 (cl-plusp js2-nesting-of-function))
7759
7760 (defun js2-set-requires-activation ()
7761 (if (js2-function-node-p js2-current-script-or-fn)
7762 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7763
7764 (defun js2-check-activation-name (name _token)
7765 (when (js2-inside-function)
7766 ;; skip language-version 1.2 check from Rhino
7767 (if (or (string= "arguments" name)
7768 (and js2-compiler-activation-names ; only used in codegen
7769 (gethash name js2-compiler-activation-names)))
7770 (js2-set-requires-activation))))
7771
7772 (defun js2-set-is-generator ()
7773 (let ((fn-node js2-current-script-or-fn))
7774 (when (and (js2-function-node-p fn-node)
7775 (not (js2-function-node-generator-type fn-node)))
7776 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7777
7778 (defun js2-must-have-xml ()
7779 (unless js2-compiler-xml-available
7780 (js2-report-error "msg.XML.not.available")))
7781
7782 (defun js2-push-scope (scope)
7783 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7784 (cl-assert (js2-scope-p scope))
7785 (cl-assert (null (js2-scope-parent-scope scope)))
7786 (cl-assert (not (eq js2-current-scope scope)))
7787 (setf (js2-scope-parent-scope scope) js2-current-scope
7788 js2-current-scope scope))
7789
7790 (defsubst js2-pop-scope ()
7791 (setq js2-current-scope
7792 (js2-scope-parent-scope js2-current-scope)))
7793
7794 (defun js2-enter-loop (loop-node)
7795 (push loop-node js2-loop-set)
7796 (push loop-node js2-loop-and-switch-set)
7797 (js2-push-scope loop-node)
7798 ;; Tell the current labeled statement (if any) its statement,
7799 ;; and set the jump target of the first label to the loop.
7800 ;; These are used in `js2-parse-continue' to verify that the
7801 ;; continue target is an actual labeled loop. (And for codegen.)
7802 (when js2-labeled-stmt
7803 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7804 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7805 js2-labeled-stmt))) loop-node)))
7806
7807 (defun js2-exit-loop ()
7808 (pop js2-loop-set)
7809 (pop js2-loop-and-switch-set)
7810 (js2-pop-scope))
7811
7812 (defsubst js2-enter-switch (switch-node)
7813 (push switch-node js2-loop-and-switch-set))
7814
7815 (defsubst js2-exit-switch ()
7816 (pop js2-loop-and-switch-set))
7817
7818 (defsubst js2-get-directive (node)
7819 "Return NODE's value if it is a directive, nil otherwise.
7820
7821 A directive is an otherwise-meaningless expression statement
7822 consisting of a string literal, such as \"use strict\"."
7823 (and (js2-expr-stmt-node-p node)
7824 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7825 (js2-string-node-value node)))
7826
7827 (defun js2-parse (&optional buf cb)
7828 "Tell the js2 parser to parse a region of JavaScript.
7829
7830 BUF is a buffer or buffer name containing the code to parse.
7831 Call `narrow-to-region' first to parse only part of the buffer.
7832
7833 The returned AST root node is given some additional properties:
7834 `node-count' - total number of nodes in the AST
7835 `buffer' - BUF. The buffer it refers to may change or be killed,
7836 so the value is not necessarily reliable.
7837
7838 An optional callback CB can be specified to report parsing
7839 progress. If `(functionp CB)' returns t, it will be called with
7840 the current line number once before parsing begins, then again
7841 each time the lexer reaches a new line number.
7842
7843 CB can also be a list of the form `(symbol cb ...)' to specify
7844 multiple callbacks with different criteria. Each symbol is a
7845 criterion keyword, and the following element is the callback to
7846 call
7847
7848 :line - called whenever the line number changes
7849 :token - called for each new token consumed
7850
7851 The list of criteria could be extended to include entering or
7852 leaving a statement, an expression, or a function definition."
7853 (if (and cb (not (functionp cb)))
7854 (error "criteria callbacks not yet implemented"))
7855 (let ((inhibit-point-motion-hooks t)
7856 (js2-compiler-xml-available (>= js2-language-version 160))
7857 ;; This is a recursive-descent parser, so give it a big stack.
7858 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7859 (max-specpdl-size (max max-specpdl-size 3000))
7860 (case-fold-search nil)
7861 ast)
7862 (with-current-buffer (or buf (current-buffer))
7863 (setq js2-scanned-comments nil
7864 js2-parsed-errors nil
7865 js2-parsed-warnings nil
7866 js2-imenu-recorder nil
7867 js2-imenu-function-map nil
7868 js2-label-set nil)
7869 (js2-init-scanner)
7870 (setq ast (js2-do-parse))
7871 (unless js2-ts-hit-eof
7872 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7873 (setf (js2-ast-root-errors ast) js2-parsed-errors
7874 (js2-ast-root-warnings ast) js2-parsed-warnings)
7875 ;; if we didn't find any declarations, put a dummy in this list so we
7876 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7877 (unless js2-imenu-recorder
7878 (setq js2-imenu-recorder 'empty))
7879 (run-hooks 'js2-parse-finished-hook)
7880 ast)))
7881
7882 ;; Corresponds to Rhino's Parser.parse() method.
7883 (defun js2-do-parse ()
7884 "Parse current buffer starting from current point.
7885 Scanner should be initialized."
7886 (let ((pos js2-ts-cursor)
7887 (end js2-ts-cursor) ; in case file is empty
7888 root n tt
7889 (in-directive-prologue t)
7890 (js2-in-use-strict-directive js2-in-use-strict-directive)
7891 directive)
7892 ;; initialize buffer-local parsing vars
7893 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7894 js2-current-script-or-fn root
7895 js2-current-scope root
7896 js2-nesting-of-function 0
7897 js2-labeled-stmt nil
7898 js2-recorded-identifiers nil ; for js2-highlight
7899 js2-in-use-strict-directive nil)
7900 (while (/= (setq tt (js2-get-token)) js2-EOF)
7901 (if (= tt js2-FUNCTION)
7902 (progn
7903 (setq n (if js2-called-by-compile-function
7904 (js2-parse-function-expr)
7905 (js2-parse-function-stmt))))
7906 ;; not a function - parse a statement
7907 (js2-unget-token)
7908 (setq n (js2-parse-statement))
7909 (when in-directive-prologue
7910 (setq directive (js2-get-directive n))
7911 (cond
7912 ((null directive)
7913 (setq in-directive-prologue nil))
7914 ((string= directive "use strict")
7915 (setq js2-in-use-strict-directive t)))))
7916 ;; add function or statement to script
7917 (setq end (js2-node-end n))
7918 (js2-block-node-push root n))
7919 ;; add comments to root in lexical order
7920 (when js2-scanned-comments
7921 ;; if we find a comment beyond end of normal kids, use its end
7922 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7923 (dolist (comment js2-scanned-comments)
7924 (push comment (js2-ast-root-comments root))
7925 (js2-node-add-children root comment)))
7926 (setf (js2-node-len root) (- end pos))
7927 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7928 ;; Give extensions a chance to muck with things before highlighting starts.
7929 (let ((js2-additional-externs js2-additional-externs))
7930 (save-excursion
7931 (run-hooks 'js2-post-parse-callbacks))
7932 (js2-highlight-undeclared-vars))
7933 root))
7934
7935 (defun js2-parse-function-closure-body (fn-node)
7936 "Parse a JavaScript 1.8 function closure body."
7937 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7938 (if js2-ts-hit-eof
7939 (js2-report-error "msg.no.brace.body" nil
7940 (js2-node-pos fn-node)
7941 (- js2-ts-cursor (js2-node-pos fn-node)))
7942 (js2-node-add-children fn-node
7943 (setf (js2-function-node-body fn-node)
7944 (js2-parse-expr t))))))
7945
7946 (defun js2-parse-function-body (fn-node)
7947 (js2-must-match js2-LC "msg.no.brace.body"
7948 (js2-node-pos fn-node)
7949 (- js2-ts-cursor (js2-node-pos fn-node)))
7950 (let ((pos (js2-current-token-beg)) ; LC position
7951 (pn (make-js2-block-node)) ; starts at LC position
7952 tt
7953 end
7954 not-in-directive-prologue
7955 node
7956 directive)
7957 (cl-incf js2-nesting-of-function)
7958 (unwind-protect
7959 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7960 (= tt js2-EOF)
7961 (= tt js2-RC)))
7962 (js2-block-node-push
7963 pn
7964 (if (/= tt js2-FUNCTION)
7965 (if not-in-directive-prologue
7966 (js2-parse-statement)
7967 (setq node (js2-parse-statement)
7968 directive (js2-get-directive node))
7969 (cond
7970 ((null directive)
7971 (setq not-in-directive-prologue t))
7972 ((string= directive "use strict")
7973 ;; Back up and reparse the function, because new rules apply
7974 ;; to the function name and parameters.
7975 (when (not js2-in-use-strict-directive)
7976 (setq js2-in-use-strict-directive t)
7977 (throw 'reparse t))))
7978 node)
7979 (js2-get-token)
7980 (js2-parse-function-stmt))))
7981 (cl-decf js2-nesting-of-function))
7982 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7983 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7984 (setq end (js2-current-token-end)))
7985 (setf (js2-node-pos pn) pos
7986 (js2-node-len pn) (- end pos))
7987 (setf (js2-function-node-body fn-node) pn)
7988 (js2-node-add-children fn-node pn)
7989 pn))
7990
7991 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7992 "Declare and fontify destructuring parameters inside NODE.
7993 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
7994
7995 Return a list of `js2-name-node' nodes representing the symbols
7996 declared; probably to check them for errors."
7997 (let (name-nodes)
7998 (cond
7999 ((js2-name-node-p node)
8000 (let (leftpos)
8001 (js2-define-symbol decl-type (js2-name-node-name node)
8002 node ignore-not-in-block)
8003 (when face
8004 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8005 (+ leftpos (js2-node-len node))
8006 face 'record))
8007 (list node)))
8008 ((js2-object-node-p node)
8009 (dolist (elem (js2-object-node-elems node))
8010 ;; js2-infix-node-p catches both object prop node and initialized
8011 ;; binding element (which is directly an infix node).
8012 (when (js2-infix-node-p elem)
8013 (push (js2-define-destruct-symbols
8014 (js2-infix-node-left elem)
8015 decl-type face ignore-not-in-block)
8016 name-nodes)))
8017 (apply #'append (nreverse name-nodes)))
8018 ((js2-array-node-p node)
8019 (dolist (elem (js2-array-node-elems node))
8020 (when elem
8021 (if (js2-infix-node-p elem) (setq elem (js2-infix-node-left elem)))
8022 (push (js2-define-destruct-symbols
8023 elem decl-type face ignore-not-in-block)
8024 name-nodes)))
8025 (apply #'append (nreverse name-nodes)))
8026 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8027 (js2-node-len node))
8028 nil))))
8029
8030 (defvar js2-illegal-strict-identifiers
8031 '("eval" "arguments")
8032 "Identifiers not allowed as variables in strict mode.")
8033
8034 (defun js2-check-strict-identifier (name-node)
8035 "Check that NAME-NODE makes a legal strict mode identifier."
8036 (when js2-in-use-strict-directive
8037 (let ((param-name (js2-name-node-name name-node)))
8038 (when (member param-name js2-illegal-strict-identifiers)
8039 (js2-report-error "msg.bad.id.strict" param-name
8040 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8041
8042 (defun js2-check-strict-function-params (preceding-params params)
8043 "Given PRECEDING-PARAMS in a function's parameter list, check
8044 for strict mode errors caused by PARAMS."
8045 (when js2-in-use-strict-directive
8046 (dolist (param params)
8047 (let ((param-name (js2-name-node-name param)))
8048 (js2-check-strict-identifier param)
8049 (when (cl-some (lambda (param)
8050 (string= (js2-name-node-name param) param-name))
8051 preceding-params)
8052 (js2-report-error "msg.dup.param.strict" param-name
8053 (js2-node-abs-pos param) (js2-node-len param)))))))
8054
8055 (defun js2-parse-function-params (function-type fn-node pos)
8056 "Parse the parameters of a function of FUNCTION-TYPE
8057 represented by FN-NODE at POS."
8058 (if (js2-match-token js2-RP)
8059 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8060 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8061 (eq (js2-current-token-type) js2-NAME)))
8062 params param
8063 param-name-nodes new-param-name-nodes
8064 rest-param-at)
8065 (when paren-free-arrow
8066 (js2-unget-token))
8067 (cl-loop for tt = (js2-peek-token)
8068 do
8069 (cond
8070 ;; destructuring param
8071 ((and (not paren-free-arrow)
8072 (or (= tt js2-LB) (= tt js2-LC)))
8073 (js2-get-token)
8074 (setq param (js2-parse-destruct-primary-expr)
8075 new-param-name-nodes (js2-define-destruct-symbols
8076 param js2-LP 'js2-function-param))
8077 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8078 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8079 (push param params))
8080 ;; variable name
8081 (t
8082 (when (and (>= js2-language-version 200)
8083 (not paren-free-arrow)
8084 (js2-match-token js2-TRIPLEDOT)
8085 (not rest-param-at))
8086 ;; to report errors if there are more parameters
8087 (setq rest-param-at (length params)))
8088 (js2-must-match-name "msg.no.parm")
8089 (js2-record-face 'js2-function-param)
8090 (setq param (js2-create-name-node))
8091 (js2-define-symbol js2-LP (js2-current-token-string) param)
8092 (js2-check-strict-function-params param-name-nodes (list param))
8093 (setq param-name-nodes (append param-name-nodes (list param)))
8094 ;; default parameter value
8095 (when (and (>= js2-language-version 200)
8096 (js2-match-token js2-ASSIGN))
8097 (cl-assert (not paren-free-arrow))
8098 (let* ((pos (js2-node-pos param))
8099 (tt (js2-current-token-type))
8100 (op-pos (- (js2-current-token-beg) pos))
8101 (left param)
8102 (right (js2-parse-assign-expr))
8103 (len (- (js2-node-end right) pos)))
8104 (setq param (make-js2-assign-node
8105 :type tt :pos pos :len len :op-pos op-pos
8106 :left left :right right))
8107 (js2-node-add-children param left right)))
8108 (push param params)))
8109 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8110 (js2-report-error "msg.param.after.rest" nil
8111 (js2-node-pos param) (js2-node-len param)))
8112 while
8113 (js2-match-token js2-COMMA))
8114 (when (and (not paren-free-arrow)
8115 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8116 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8117 (when rest-param-at
8118 (setf (js2-function-node-rest-p fn-node) t))
8119 (dolist (p params)
8120 (js2-node-add-children fn-node p)
8121 (push p (js2-function-node-params fn-node))))))
8122
8123 (defun js2-check-inconsistent-return-warning (fn-node name)
8124 "Possibly show inconsistent-return warning.
8125 Last token scanned is the close-curly for the function body."
8126 (when (and js2-mode-show-strict-warnings
8127 js2-strict-inconsistent-return-warning
8128 (not (js2-has-consistent-return-usage
8129 (js2-function-node-body fn-node))))
8130 ;; Have it extend from close-curly to bol or beginning of block.
8131 (let ((pos (save-excursion
8132 (goto-char (js2-current-token-end))
8133 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8134 (point-at-bol))))
8135 (end (js2-current-token-end)))
8136 (if (cl-plusp (js2-name-node-length name))
8137 (js2-add-strict-warning "msg.no.return.value"
8138 (js2-name-node-name name) pos end)
8139 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8140
8141 (defun js2-parse-function-stmt ()
8142 (let ((pos (js2-current-token-beg))
8143 (star-p (js2-match-token js2-MUL)))
8144 (js2-must-match-name "msg.unnamed.function.stmt")
8145 (let ((name (js2-create-name-node t))
8146 pn member-expr)
8147 (cond
8148 ((js2-match-token js2-LP)
8149 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8150 (js2-allow-member-expr-as-function-name
8151 (setq member-expr (js2-parse-member-expr-tail nil name))
8152 (js2-parse-highlight-member-expr-fn-name member-expr)
8153 (js2-must-match js2-LP "msg.no.paren.parms")
8154 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8155 (js2-function-node-member-expr pn) member-expr)
8156 pn)
8157 (t
8158 (js2-report-error "msg.no.paren.parms")
8159 (make-js2-error-node))))))
8160
8161 (defun js2-parse-function-expr ()
8162 (let ((pos (js2-current-token-beg))
8163 (star-p (js2-match-token js2-MUL))
8164 name)
8165 (when (js2-match-token js2-NAME)
8166 (setq name (js2-create-name-node t)))
8167 (js2-must-match js2-LP "msg.no.paren.parms")
8168 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8169
8170 (defun js2-parse-function-internal (function-type pos star-p &optional name)
8171 (let (fn-node lp)
8172 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8173 (setq lp (js2-current-token-beg)))
8174 (setf fn-node (make-js2-function-node :pos pos
8175 :name name
8176 :form function-type
8177 :lp (if lp (- lp pos))
8178 :generator-type (and star-p 'STAR)))
8179 (when name
8180 (js2-set-face (js2-node-pos name) (js2-node-end name)
8181 'font-lock-function-name-face 'record)
8182 (when (and (eq function-type 'FUNCTION_STATEMENT)
8183 (cl-plusp (js2-name-node-length name)))
8184 ;; Function statements define a symbol in the enclosing scope
8185 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8186 (when js2-in-use-strict-directive
8187 (js2-check-strict-identifier name)))
8188 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8189 ;; 1. Nested functions are not affected by the dynamic scope flag
8190 ;; as dynamic scope is already a parent of their scope.
8191 ;; 2. Functions defined under the with statement also immune to
8192 ;; this setup, in which case dynamic scope is ignored in favor
8193 ;; of the with object.
8194 (setf (js2-function-node-ignore-dynamic fn-node) t))
8195 ;; dynamically bind all the per-function variables
8196 (let ((js2-current-script-or-fn fn-node)
8197 (js2-current-scope fn-node)
8198 (js2-nesting-of-with 0)
8199 (js2-end-flags 0)
8200 js2-label-set
8201 js2-loop-set
8202 js2-loop-and-switch-set)
8203 (js2-parse-function-params function-type fn-node pos)
8204 (when (eq function-type 'FUNCTION_ARROW)
8205 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8206 (if (and (>= js2-language-version 180)
8207 (/= (js2-peek-token) js2-LC))
8208 (js2-parse-function-closure-body fn-node)
8209 (js2-parse-function-body fn-node))
8210 (js2-check-inconsistent-return-warning fn-node name)
8211
8212 (when name
8213 (js2-node-add-children fn-node name)
8214 ;; Function expressions define a name only in the body of the
8215 ;; function, and only if not hidden by a parameter name
8216 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8217 (null (js2-scope-get-symbol js2-current-scope
8218 (js2-name-node-name name))))
8219 (js2-define-symbol js2-FUNCTION
8220 (js2-name-node-name name)
8221 fn-node))
8222 (when (eq function-type 'FUNCTION_STATEMENT)
8223 (js2-record-imenu-functions fn-node))))
8224
8225 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8226 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8227 ;; We wait until after parsing the function to set its parent scope,
8228 ;; since `js2-define-symbol' needs the defining-scope check to stop
8229 ;; at the function boundary when checking for redeclarations.
8230 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8231 fn-node))
8232
8233 (defun js2-parse-function (function-type pos star-p &optional name)
8234 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8235 beginning of the first token (function keyword, unless it's an
8236 arrow function), NAME is js2-name-node."
8237 (let ((continue t)
8238 ts-state
8239 fn-node
8240 ;; Preserve strict state outside this function.
8241 (js2-in-use-strict-directive js2-in-use-strict-directive))
8242 ;; Parse multiple times if a new strict mode directive is discovered in the
8243 ;; function body, as new rules will be retroactively applied to the legality
8244 ;; of function names and parameters.
8245 (while continue
8246 (setq ts-state (make-js2-ts-state))
8247 (setq continue (catch 'reparse
8248 (setq fn-node (js2-parse-function-internal
8249 function-type pos star-p name))
8250 ;; Don't continue.
8251 nil))
8252 (when continue
8253 (js2-ts-seek ts-state)))
8254 fn-node))
8255
8256 (defun js2-parse-statements (&optional parent)
8257 "Parse a statement list. Last token consumed must be js2-LC.
8258
8259 PARENT can be a `js2-block-node', in which case the statements are
8260 appended to PARENT. Otherwise a new `js2-block-node' is created
8261 and returned.
8262
8263 This function does not match the closing js2-RC: the caller
8264 matches the RC so it can provide a suitable error message if not
8265 matched. This means it's up to the caller to set the length of
8266 the node to include the closing RC. The node start pos is set to
8267 the absolute buffer start position, and the caller should fix it
8268 up to be relative to the parent node. All children of this block
8269 node are given relative start positions and correct lengths."
8270 (let ((pn (or parent (make-js2-block-node)))
8271 tt)
8272 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8273 (/= tt js2-RC))
8274 (js2-block-node-push pn (js2-parse-statement)))
8275 pn))
8276
8277 (defun js2-parse-statement ()
8278 (let (pn beg end)
8279 ;; coarse-grained user-interrupt check - needs work
8280 (and js2-parse-interruptable-p
8281 (zerop (% (cl-incf js2-parse-stmt-count)
8282 js2-statements-per-pause))
8283 (input-pending-p)
8284 (throw 'interrupted t))
8285 (setq pn (js2-statement-helper))
8286 ;; no-side-effects warning check
8287 (unless (js2-node-has-side-effects pn)
8288 (setq end (js2-node-end pn))
8289 (save-excursion
8290 (goto-char end)
8291 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8292 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8293 pn))
8294
8295 ;; These correspond to the switch cases in Parser.statementHelper
8296 (defconst js2-parsers
8297 (let ((parsers (make-vector js2-num-tokens
8298 #'js2-parse-expr-stmt)))
8299 (aset parsers js2-BREAK #'js2-parse-break)
8300 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8301 (aset parsers js2-CONST #'js2-parse-const-var)
8302 (aset parsers js2-CONTINUE #'js2-parse-continue)
8303 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8304 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8305 (aset parsers js2-DO #'js2-parse-do)
8306 (aset parsers js2-EXPORT #'js2-parse-export)
8307 (aset parsers js2-FOR #'js2-parse-for)
8308 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8309 (aset parsers js2-IF #'js2-parse-if)
8310 (aset parsers js2-IMPORT #'js2-parse-import)
8311 (aset parsers js2-LC #'js2-parse-block)
8312 (aset parsers js2-LET #'js2-parse-let-stmt)
8313 (aset parsers js2-NAME #'js2-parse-name-or-label)
8314 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8315 (aset parsers js2-SEMI #'js2-parse-semi)
8316 (aset parsers js2-SWITCH #'js2-parse-switch)
8317 (aset parsers js2-THROW #'js2-parse-throw)
8318 (aset parsers js2-TRY #'js2-parse-try)
8319 (aset parsers js2-VAR #'js2-parse-const-var)
8320 (aset parsers js2-WHILE #'js2-parse-while)
8321 (aset parsers js2-WITH #'js2-parse-with)
8322 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8323 parsers)
8324 "A vector mapping token types to parser functions.")
8325
8326 (defun js2-parse-warn-missing-semi (beg end)
8327 (and js2-mode-show-strict-warnings
8328 js2-strict-missing-semi-warning
8329 (js2-add-strict-warning
8330 "msg.missing.semi" nil
8331 ;; back up to beginning of statement or line
8332 (max beg (save-excursion
8333 (goto-char end)
8334 (point-at-bol)))
8335 end)))
8336
8337 (defconst js2-no-semi-insertion
8338 (list js2-IF
8339 js2-SWITCH
8340 js2-WHILE
8341 js2-DO
8342 js2-FOR
8343 js2-TRY
8344 js2-WITH
8345 js2-LC
8346 js2-ERROR
8347 js2-SEMI
8348 js2-CLASS
8349 js2-FUNCTION
8350 js2-EXPORT)
8351 "List of tokens that don't do automatic semicolon insertion.")
8352
8353 (defconst js2-autoinsert-semi-and-warn
8354 (list js2-ERROR js2-EOF js2-RC))
8355
8356 (defun js2-statement-helper ()
8357 (let* ((tt (js2-get-token))
8358 (first-tt tt)
8359 (parser (if (= tt js2-ERROR)
8360 #'js2-parse-semi
8361 (aref js2-parsers tt)))
8362 pn)
8363 ;; If the statement is set, then it's been told its label by now.
8364 (and js2-labeled-stmt
8365 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8366 (setq js2-labeled-stmt nil))
8367 (setq pn (funcall parser))
8368 ;; Don't do auto semi insertion for certain statement types.
8369 (unless (or (memq first-tt js2-no-semi-insertion)
8370 (js2-labeled-stmt-node-p pn))
8371 (js2-auto-insert-semicolon pn))
8372 pn))
8373
8374 (defun js2-auto-insert-semicolon (pn)
8375 (let* ((tt (js2-get-token))
8376 (pos (js2-node-pos pn)))
8377 (cond
8378 ((= tt js2-SEMI)
8379 ;; extend the node bounds to include the semicolon.
8380 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8381 ((memq tt js2-autoinsert-semi-and-warn)
8382 (js2-unget-token) ; Not ';', do not consume.
8383 ;; Autoinsert ;
8384 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8385 (t
8386 (if (not (js2-token-follows-eol-p (js2-current-token)))
8387 ;; Report error if no EOL or autoinsert ';' otherwise
8388 (js2-report-error "msg.no.semi.stmt")
8389 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8390 (js2-unget-token) ; Not ';', do not consume.
8391 ))))
8392
8393 (defun js2-parse-condition ()
8394 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8395 The parens are discarded and the expression node is returned.
8396 The `pos' field of the return value is set to an absolute position
8397 that must be fixed up by the caller.
8398 Return value is a list (EXPR LP RP), with absolute paren positions."
8399 (let (pn lp rp)
8400 (if (js2-must-match js2-LP "msg.no.paren.cond")
8401 (setq lp (js2-current-token-beg)))
8402 (setq pn (js2-parse-expr))
8403 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8404 (setq rp (js2-current-token-beg)))
8405 ;; Report strict warning on code like "if (a = 7) ..."
8406 (if (and js2-strict-cond-assign-warning
8407 (js2-assign-node-p pn))
8408 (js2-add-strict-warning "msg.equal.as.assign" nil
8409 (js2-node-pos pn)
8410 (+ (js2-node-pos pn)
8411 (js2-node-len pn))))
8412 (list pn lp rp)))
8413
8414 (defun js2-parse-if ()
8415 "Parser for if-statement. Last matched token must be js2-IF."
8416 (let ((pos (js2-current-token-beg))
8417 cond if-true if-false else-pos end pn)
8418 (setq cond (js2-parse-condition)
8419 if-true (js2-parse-statement)
8420 if-false (if (js2-match-token js2-ELSE)
8421 (progn
8422 (setq else-pos (- (js2-current-token-beg) pos))
8423 (js2-parse-statement)))
8424 end (js2-node-end (or if-false if-true))
8425 pn (make-js2-if-node :pos pos
8426 :len (- end pos)
8427 :condition (car cond)
8428 :then-part if-true
8429 :else-part if-false
8430 :else-pos else-pos
8431 :lp (js2-relpos (cl-second cond) pos)
8432 :rp (js2-relpos (cl-third cond) pos)))
8433 (js2-node-add-children pn (car cond) if-true if-false)
8434 pn))
8435
8436 (defun js2-parse-import ()
8437 "Parse import statement. The current token must be js2-IMPORT."
8438 (unless (js2-ast-root-p js2-current-scope)
8439 (js2-report-error "msg.mod.import.decl.at.top.level"))
8440 (let ((beg (js2-current-token-beg)))
8441 (cond ((js2-match-token js2-STRING)
8442 (make-js2-import-node
8443 :pos beg
8444 :len (- (js2-current-token-end) beg)
8445 :module-id (js2-current-token-string)))
8446 (t
8447 (let* ((import-clause (js2-parse-import-clause))
8448 (from-clause (and import-clause (js2-parse-from-clause)))
8449 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8450 (node (make-js2-import-node
8451 :pos beg
8452 :len (- (js2-current-token-end) beg)
8453 :import import-clause
8454 :from from-clause
8455 :module-id module-id)))
8456 (when import-clause
8457 (js2-node-add-children node import-clause))
8458 (when from-clause
8459 (js2-node-add-children node from-clause))
8460 node)))))
8461
8462 (defun js2-parse-import-clause ()
8463 "Parse the bindings in an import statement.
8464 This can take many forms:
8465
8466 ImportedDefaultBinding -> 'foo'
8467 NameSpaceImport -> '* as lib'
8468 NamedImports -> '{foo as bar, bang}'
8469 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8470 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8471
8472 Try to match namespace imports and named imports first because nothing can
8473 come after them. If it is an imported default binding, then it could have named
8474 imports or a namespace import that follows it.
8475 "
8476 (let* ((beg (js2-current-token-beg))
8477 (clause (make-js2-import-clause-node
8478 :pos beg))
8479 (children (list)))
8480 (cond
8481 ((js2-match-token js2-MUL)
8482 (let ((ns-import (js2-parse-namespace-import)))
8483 (when ns-import
8484 (let ((name-node (js2-namespace-import-node-name ns-import)))
8485 (js2-define-symbol
8486 js2-LET (js2-name-node-name name-node) name-node t)))
8487 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8488 (push ns-import children)))
8489 ((js2-match-token js2-LC)
8490 (let ((imports (js2-parse-export-bindings t)))
8491 (setf (js2-import-clause-node-named-imports clause) imports)
8492 (dolist (import imports)
8493 (push import children)
8494 (let ((name-node (js2-export-binding-node-local-name import)))
8495 (when name-node
8496 (js2-define-symbol
8497 js2-LET (js2-name-node-name name-node) name-node t))))))
8498 ((= (js2-peek-token) js2-NAME)
8499 (let ((binding (js2-maybe-parse-export-binding)))
8500 (let ((node-name (js2-export-binding-node-local-name binding)))
8501 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8502 (setf (js2-import-clause-node-default-binding clause) binding)
8503 (push binding children))
8504 (when (js2-match-token js2-COMMA)
8505 (cond
8506 ((js2-match-token js2-MUL)
8507 (let ((ns-import (js2-parse-namespace-import)))
8508 (let ((name-node (js2-namespace-import-node-name ns-import)))
8509 (js2-define-symbol
8510 js2-LET (js2-name-node-name name-node) name-node t))
8511 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8512 (push ns-import children)))
8513 ((js2-match-token js2-LC)
8514 (let ((imports (js2-parse-export-bindings t)))
8515 (setf (js2-import-clause-node-named-imports clause) imports)
8516 (dolist (import imports)
8517 (push import children)
8518 (let ((name-node (js2-export-binding-node-local-name import)))
8519 (when name-node
8520 (js2-define-symbol
8521 js2-LET (js2-name-node-name name-node) name-node t))))))
8522 (t (js2-report-error "msg.syntax")))))
8523 (t (js2-report-error "msg.mod.declaration.after.import")))
8524 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8525 (apply #'js2-node-add-children clause children)
8526 clause))
8527
8528 (defun js2-parse-namespace-import ()
8529 "Parse a namespace import expression such as '* as bar'.
8530 The current token must be js2-MUL."
8531 (let ((beg (js2-current-token-beg)))
8532 (when (js2-must-match js2-NAME "msg.syntax")
8533 (if (equal "as" (js2-current-token-string))
8534 (when (js2-must-match-prop-name "msg.syntax")
8535 (let ((node (make-js2-namespace-import-node
8536 :pos beg
8537 :len (- (js2-current-token-end) beg)
8538 :name (make-js2-name-node
8539 :pos (js2-current-token-beg)
8540 :len (js2-current-token-end)
8541 :name (js2-current-token-string)))))
8542 (js2-node-add-children node (js2-namespace-import-node-name node))
8543 node))
8544 (js2-unget-token)
8545 (js2-report-error "msg.syntax")))))
8546
8547
8548 (defun js2-parse-from-clause ()
8549 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8550 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8551 (let ((beg (js2-current-token-beg)))
8552 (if (equal "from" (js2-current-token-string))
8553 (cond
8554 ((js2-match-token js2-STRING)
8555 (make-js2-from-clause-node
8556 :pos beg
8557 :len (- (js2-current-token-end) beg)
8558 :module-id (js2-current-token-string)
8559 :metadata-p nil))
8560 ((js2-match-token js2-THIS)
8561 (when (js2-must-match-name "msg.mod.spec.after.from")
8562 (if (equal "module" (js2-current-token-string))
8563 (make-js2-from-clause-node
8564 :pos beg
8565 :len (- (js2-current-token-end) beg)
8566 :module-id "this"
8567 :metadata-p t)
8568 (js2-unget-token)
8569 (js2-unget-token)
8570 (js2-report-error "msg.mod.spec.after.from")
8571 nil)))
8572 (t (js2-report-error "msg.mod.spec.after.from") nil))
8573 (js2-unget-token)
8574 (js2-report-error "msg.mod.from.after.import.spec.set")
8575 nil))))
8576
8577 (defun js2-parse-export-bindings (&optional import-p)
8578 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8579 {foo as bar, baz as bang}. The current token must be
8580 js2-LC. Return a lisp list of js2-export-binding-node"
8581 (let ((bindings (list)))
8582 (while
8583 (let ((binding (js2-maybe-parse-export-binding)))
8584 (when binding
8585 (push binding bindings))
8586 (js2-match-token js2-COMMA)))
8587 (when (js2-must-match js2-RC (if import-p
8588 "msg.mod.rc.after.import.spec.list"
8589 "msg.mod.rc.after.export.spec.list"))
8590 (reverse bindings))))
8591
8592 (defun js2-maybe-parse-export-binding ()
8593 "Attempt to parse a binding expression found inside an import/export statement.
8594 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8595 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8596 js2-export-binding-node and consume all the tokens. If it does not match, it
8597 consumes no tokens."
8598 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8599 (beg (js2-current-token-beg))
8600 (extern-name-len (js2-current-token-len))
8601 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8602 (aref js2-kwd-tokens (js2-current-token-type)))))
8603 (if extern-name
8604 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8605 (if (and as (equal "as" (js2-current-token-string)))
8606 (let ((name
8607 (or
8608 (and (js2-match-token js2-DEFAULT) "default")
8609 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8610 (if name
8611 (let ((node (make-js2-export-binding-node
8612 :pos beg
8613 :len (- (js2-current-token-end) beg)
8614 :local-name (make-js2-name-node
8615 :name name
8616 :pos (js2-current-token-beg)
8617 :len (js2-current-token-len))
8618 :extern-name (make-js2-name-node
8619 :name extern-name
8620 :pos beg
8621 :len extern-name-len))))
8622 (js2-node-add-children
8623 node
8624 (js2-export-binding-node-local-name node)
8625 (js2-export-binding-node-extern-name node))
8626 node)
8627 (js2-unget-token)
8628 nil))
8629 (when as (js2-unget-token))
8630 (let* ((name-node (make-js2-name-node
8631 :name (js2-current-token-string)
8632 :pos (js2-current-token-beg)
8633 :len (js2-current-token-len)))
8634 (node (make-js2-export-binding-node
8635 :pos (js2-current-token-beg)
8636 :len (js2-current-token-len)
8637 :local-name name-node
8638 :extern-name name-node)))
8639 (when is-reserved-name
8640 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8641 (js2-node-add-children node name-node)
8642 node)))
8643 nil)))
8644
8645 (defun js2-parse-switch ()
8646 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8647 (let ((pos (js2-current-token-beg))
8648 tt pn discriminant has-default case-expr case-node
8649 case-pos cases stmt lp)
8650 (if (js2-must-match js2-LP "msg.no.paren.switch")
8651 (setq lp (js2-current-token-beg)))
8652 (setq discriminant (js2-parse-expr)
8653 pn (make-js2-switch-node :discriminant discriminant
8654 :pos pos
8655 :lp (js2-relpos lp pos)))
8656 (js2-node-add-children pn discriminant)
8657 (js2-enter-switch pn)
8658 (unwind-protect
8659 (progn
8660 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8661 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8662 (js2-must-match js2-LC "msg.no.brace.switch")
8663 (catch 'break
8664 (while t
8665 (setq tt (js2-next-token)
8666 case-pos (js2-current-token-beg))
8667 (cond
8668 ((= tt js2-RC)
8669 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8670 (throw 'break nil)) ; done
8671 ((= tt js2-CASE)
8672 (setq case-expr (js2-parse-expr))
8673 (js2-must-match js2-COLON "msg.no.colon.case"))
8674 ((= tt js2-DEFAULT)
8675 (if has-default
8676 (js2-report-error "msg.double.switch.default"))
8677 (setq has-default t
8678 case-expr nil)
8679 (js2-must-match js2-COLON "msg.no.colon.case"))
8680 (t
8681 (js2-report-error "msg.bad.switch")
8682 (throw 'break nil)))
8683 (setq case-node (make-js2-case-node :pos case-pos
8684 :len (- (js2-current-token-end) case-pos)
8685 :expr case-expr))
8686 (js2-node-add-children case-node case-expr)
8687 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8688 (/= tt js2-CASE)
8689 (/= tt js2-DEFAULT)
8690 (/= tt js2-EOF))
8691 (setf stmt (js2-parse-statement)
8692 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8693 (js2-block-node-push case-node stmt))
8694 (push case-node cases)))
8695 ;; add cases last, as pushing reverses the order to be correct
8696 (dolist (kid cases)
8697 (js2-node-add-children pn kid)
8698 (push kid (js2-switch-node-cases pn)))
8699 pn) ; return value
8700 (js2-exit-switch))))
8701
8702 (defun js2-parse-while ()
8703 "Parser for while-statement. Last matched token must be js2-WHILE."
8704 (let ((pos (js2-current-token-beg))
8705 (pn (make-js2-while-node))
8706 cond body)
8707 (js2-enter-loop pn)
8708 (unwind-protect
8709 (progn
8710 (setf cond (js2-parse-condition)
8711 (js2-while-node-condition pn) (car cond)
8712 body (js2-parse-statement)
8713 (js2-while-node-body pn) body
8714 (js2-node-len pn) (- (js2-node-end body) pos)
8715 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8716 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8717 (js2-node-add-children pn body (car cond)))
8718 (js2-exit-loop))
8719 pn))
8720
8721 (defun js2-parse-do ()
8722 "Parser for do-statement. Last matched token must be js2-DO."
8723 (let ((pos (js2-current-token-beg))
8724 (pn (make-js2-do-node))
8725 cond body end)
8726 (js2-enter-loop pn)
8727 (unwind-protect
8728 (progn
8729 (setq body (js2-parse-statement))
8730 (js2-must-match js2-WHILE "msg.no.while.do")
8731 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8732 cond (js2-parse-condition)
8733 (js2-do-node-condition pn) (car cond)
8734 (js2-do-node-body pn) body
8735 end js2-ts-cursor
8736 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8737 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8738 (js2-node-add-children pn (car cond) body))
8739 (js2-exit-loop))
8740 ;; Always auto-insert semicolon to follow SpiderMonkey:
8741 ;; It is required by ECMAScript but is ignored by the rest of
8742 ;; world; see bug 238945
8743 (if (js2-match-token js2-SEMI)
8744 (setq end js2-ts-cursor))
8745 (setf (js2-node-len pn) (- end pos))
8746 pn))
8747
8748 (defun js2-parse-export ()
8749 "Parse an export statement.
8750 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8751 expressions should only be either hoistable expressions (function or generator)
8752 or assignment expressions, but there is no checking to enforce that and so it
8753 will parse without error a small subset of
8754 invalid export statements."
8755 (unless (js2-ast-root-p js2-current-scope)
8756 (js2-report-error "msg.mod.export.decl.at.top.level"))
8757 (let ((beg (js2-current-token-beg))
8758 (children (list))
8759 exports-list from-clause declaration default)
8760 (cond
8761 ((js2-match-token js2-MUL)
8762 (setq from-clause (js2-parse-from-clause))
8763 (when from-clause
8764 (push from-clause children)))
8765 ((js2-match-token js2-LC)
8766 (setq exports-list (js2-parse-export-bindings))
8767 (when exports-list
8768 (dolist (export exports-list)
8769 (push export children)))
8770 (when (js2-match-token js2-NAME)
8771 (if (equal "from" (js2-current-token-string))
8772 (progn
8773 (js2-unget-token)
8774 (setq from-clause (js2-parse-from-clause)))
8775 (js2-unget-token))))
8776 ((js2-match-token js2-DEFAULT)
8777 (setq default (js2-parse-expr)))
8778 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8779 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8780 (t
8781 (setq declaration (js2-parse-expr))))
8782 (when from-clause
8783 (push from-clause children))
8784 (when declaration
8785 (push declaration children)
8786 (when (not (js2-function-node-p declaration))
8787 (js2-auto-insert-semicolon declaration)))
8788 (when default
8789 (push default children)
8790 (when (not (js2-function-node-p default))
8791 (js2-auto-insert-semicolon default)))
8792 (let ((node (make-js2-export-node
8793 :pos beg
8794 :len (- (js2-current-token-end) beg)
8795 :exports-list exports-list
8796 :from-clause from-clause
8797 :declaration declaration
8798 :default default)))
8799 (apply #'js2-node-add-children node children)
8800 node)))
8801
8802 (defun js2-parse-for ()
8803 "Parse a for, for-in or for each-in statement.
8804 Last matched token must be js2-FOR."
8805 (let ((for-pos (js2-current-token-beg))
8806 (tmp-scope (make-js2-scope))
8807 pn is-for-each is-for-in-or-of is-for-of
8808 in-pos each-pos tmp-pos
8809 init ; Node init is also foo in 'foo in object'.
8810 cond ; Node cond is also object in 'foo in object'.
8811 incr ; 3rd section of for-loop initializer.
8812 body tt lp rp)
8813 ;; See if this is a for each () instead of just a for ()
8814 (when (js2-match-token js2-NAME)
8815 (if (string= "each" (js2-current-token-string))
8816 (progn
8817 (setq is-for-each t
8818 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8819 (js2-record-face 'font-lock-keyword-face))
8820 (js2-report-error "msg.no.paren.for")))
8821 (if (js2-must-match js2-LP "msg.no.paren.for")
8822 (setq lp (- (js2-current-token-beg) for-pos)))
8823 (setq tt (js2-get-token))
8824 ;; Capture identifiers inside parens. We can't create the node
8825 ;; (and use it as the current scope) until we know its type.
8826 (js2-push-scope tmp-scope)
8827 (unwind-protect
8828 (progn
8829 ;; parse init clause
8830 (let ((js2-in-for-init t)) ; set as dynamic variable
8831 (cond
8832 ((= tt js2-SEMI)
8833 (js2-unget-token)
8834 (setq init (make-js2-empty-expr-node)))
8835 ((or (= tt js2-VAR) (= tt js2-LET))
8836 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8837 (t
8838 (js2-unget-token)
8839 (setq init (js2-parse-expr)))))
8840 (if (or (js2-match-token js2-IN)
8841 (and (>= js2-language-version 200)
8842 (js2-match-contextual-kwd "of")
8843 (setq is-for-of t)))
8844 (setq is-for-in-or-of t
8845 in-pos (- (js2-current-token-beg) for-pos)
8846 ;; scope of iteration target object is not the scope we've created above.
8847 ;; stash current scope temporary.
8848 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8849 (js2-parse-expr))) ; object over which we're iterating
8850 ;; else ordinary for loop - parse cond and incr
8851 (js2-must-match js2-SEMI "msg.no.semi.for")
8852 (setq cond (if (= (js2-peek-token) js2-SEMI)
8853 (make-js2-empty-expr-node) ; no loop condition
8854 (js2-parse-expr)))
8855 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8856 (setq tmp-pos (js2-current-token-end)
8857 incr (if (= (js2-peek-token) js2-RP)
8858 (make-js2-empty-expr-node :pos tmp-pos)
8859 (js2-parse-expr)))))
8860 (js2-pop-scope))
8861 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8862 (setq rp (- (js2-current-token-beg) for-pos)))
8863 (if (not is-for-in-or-of)
8864 (setq pn (make-js2-for-node :init init
8865 :condition cond
8866 :update incr
8867 :lp lp
8868 :rp rp))
8869 ;; cond could be null if 'in obj' got eaten by the init node.
8870 (if (js2-infix-node-p init)
8871 ;; it was (foo in bar) instead of (var foo in bar)
8872 (setq cond (js2-infix-node-right init)
8873 init (js2-infix-node-left init))
8874 (if (and (js2-var-decl-node-p init)
8875 (> (length (js2-var-decl-node-kids init)) 1))
8876 (js2-report-error "msg.mult.index")))
8877 (setq pn (make-js2-for-in-node :iterator init
8878 :object cond
8879 :in-pos in-pos
8880 :foreach-p is-for-each
8881 :each-pos each-pos
8882 :forof-p is-for-of
8883 :lp lp
8884 :rp rp)))
8885 ;; Transplant the declarations.
8886 (setf (js2-scope-symbol-table pn)
8887 (js2-scope-symbol-table tmp-scope))
8888 (unwind-protect
8889 (progn
8890 (js2-enter-loop pn)
8891 ;; We have to parse the body -after- creating the loop node,
8892 ;; so that the loop node appears in the js2-loop-set, allowing
8893 ;; break/continue statements to find the enclosing loop.
8894 (setf body (js2-parse-statement)
8895 (js2-loop-node-body pn) body
8896 (js2-node-pos pn) for-pos
8897 (js2-node-len pn) (- (js2-node-end body) for-pos))
8898 (js2-node-add-children pn init cond incr body))
8899 ;; finally
8900 (js2-exit-loop))
8901 pn))
8902
8903 (defun js2-parse-try ()
8904 "Parse a try statement. Last matched token must be js2-TRY."
8905 (let ((try-pos (js2-current-token-beg))
8906 try-end
8907 try-block
8908 catch-blocks
8909 finally-block
8910 saw-default-catch
8911 peek)
8912 (if (/= (js2-peek-token) js2-LC)
8913 (js2-report-error "msg.no.brace.try"))
8914 (setq try-block (js2-parse-statement)
8915 try-end (js2-node-end try-block)
8916 peek (js2-peek-token))
8917 (cond
8918 ((= peek js2-CATCH)
8919 (while (js2-match-token js2-CATCH)
8920 (let* ((catch-pos (js2-current-token-beg))
8921 (catch-node (make-js2-catch-node :pos catch-pos))
8922 param
8923 guard-kwd
8924 catch-cond
8925 lp rp)
8926 (if saw-default-catch
8927 (js2-report-error "msg.catch.unreachable"))
8928 (if (js2-must-match js2-LP "msg.no.paren.catch")
8929 (setq lp (- (js2-current-token-beg) catch-pos)))
8930 (js2-push-scope catch-node)
8931 (let ((tt (js2-peek-token)))
8932 (cond
8933 ;; Destructuring pattern:
8934 ;; catch ({ message, file }) { ... }
8935 ((or (= tt js2-LB) (= tt js2-LC))
8936 (js2-get-token)
8937 (setq param (js2-parse-destruct-primary-expr))
8938 (js2-define-destruct-symbols param js2-LET nil))
8939 ;; Simple name.
8940 (t
8941 (js2-must-match-name "msg.bad.catchcond")
8942 (setq param (js2-create-name-node))
8943 (js2-define-symbol js2-LET (js2-current-token-string) param)
8944 (js2-check-strict-identifier param))))
8945 ;; Catch condition.
8946 (if (js2-match-token js2-IF)
8947 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8948 catch-cond (js2-parse-expr))
8949 (setq saw-default-catch t))
8950 (if (js2-must-match js2-RP "msg.bad.catchcond")
8951 (setq rp (- (js2-current-token-beg) catch-pos)))
8952 (js2-must-match js2-LC "msg.no.brace.catchblock")
8953 (js2-parse-statements catch-node)
8954 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8955 (setq try-end (js2-current-token-end)))
8956 (js2-pop-scope)
8957 (setf (js2-node-len catch-node) (- try-end catch-pos)
8958 (js2-catch-node-param catch-node) param
8959 (js2-catch-node-guard-expr catch-node) catch-cond
8960 (js2-catch-node-guard-kwd catch-node) guard-kwd
8961 (js2-catch-node-lp catch-node) lp
8962 (js2-catch-node-rp catch-node) rp)
8963 (js2-node-add-children catch-node param catch-cond)
8964 (push catch-node catch-blocks))))
8965 ((/= peek js2-FINALLY)
8966 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8967 (js2-node-pos try-block)
8968 (- (setq try-end (js2-node-end try-block))
8969 (js2-node-pos try-block)))))
8970 (when (js2-match-token js2-FINALLY)
8971 (let ((finally-pos (js2-current-token-beg))
8972 (block (js2-parse-statement)))
8973 (setq try-end (js2-node-end block)
8974 finally-block (make-js2-finally-node :pos finally-pos
8975 :len (- try-end finally-pos)
8976 :body block))
8977 (js2-node-add-children finally-block block)))
8978 (let ((pn (make-js2-try-node :pos try-pos
8979 :len (- try-end try-pos)
8980 :try-block try-block
8981 :finally-block finally-block)))
8982 (js2-node-add-children pn try-block finally-block)
8983 ;; Push them onto the try-node, which reverses and corrects their order.
8984 (dolist (cb catch-blocks)
8985 (js2-node-add-children pn cb)
8986 (push cb (js2-try-node-catch-clauses pn)))
8987 pn)))
8988
8989 (defun js2-parse-throw ()
8990 "Parser for throw-statement. Last matched token must be js2-THROW."
8991 (let ((pos (js2-current-token-beg))
8992 expr pn)
8993 (if (= (js2-peek-token-or-eol) js2-EOL)
8994 ;; ECMAScript does not allow new lines before throw expression,
8995 ;; see bug 256617
8996 (js2-report-error "msg.bad.throw.eol"))
8997 (setq expr (js2-parse-expr)
8998 pn (make-js2-throw-node :pos pos
8999 :len (- (js2-node-end expr) pos)
9000 :expr expr))
9001 (js2-node-add-children pn expr)
9002 pn))
9003
9004 (defun js2-match-jump-label-name (label-name)
9005 "If break/continue specified a label, return that label's labeled stmt.
9006 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9007 does not match an existing label, reports an error and returns nil."
9008 (let ((bundle (cdr (assoc label-name js2-label-set))))
9009 (if (null bundle)
9010 (js2-report-error "msg.undef.label"))
9011 bundle))
9012
9013 (defun js2-parse-break ()
9014 "Parser for break-statement. Last matched token must be js2-BREAK."
9015 (let ((pos (js2-current-token-beg))
9016 (end (js2-current-token-end))
9017 break-target ; statement to break from
9018 break-label ; in "break foo", name-node representing the foo
9019 labels ; matching labeled statement to break to
9020 pn)
9021 (when (eq (js2-peek-token-or-eol) js2-NAME)
9022 (js2-get-token)
9023 (setq break-label (js2-create-name-node)
9024 end (js2-node-end break-label)
9025 ;; matchJumpLabelName only matches if there is one
9026 labels (js2-match-jump-label-name (js2-current-token-string))
9027 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9028 (unless (or break-target break-label)
9029 ;; no break target specified - try for innermost enclosing loop/switch
9030 (if (null js2-loop-and-switch-set)
9031 (unless break-label
9032 (js2-report-error "msg.bad.break" nil pos (length "break")))
9033 (setq break-target (car js2-loop-and-switch-set))))
9034 (setq pn (make-js2-break-node :pos pos
9035 :len (- end pos)
9036 :label break-label
9037 :target break-target))
9038 (js2-node-add-children pn break-label) ; but not break-target
9039 pn))
9040
9041 (defun js2-parse-continue ()
9042 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9043 (let ((pos (js2-current-token-beg))
9044 (end (js2-current-token-end))
9045 label ; optional user-specified label, a `js2-name-node'
9046 labels ; current matching labeled stmt, if any
9047 target ; the `js2-loop-node' target of this continue stmt
9048 pn)
9049 (when (= (js2-peek-token-or-eol) js2-NAME)
9050 (js2-get-token)
9051 (setq label (js2-create-name-node)
9052 end (js2-node-end label)
9053 ;; matchJumpLabelName only matches if there is one
9054 labels (js2-match-jump-label-name (js2-current-token-string))))
9055 (cond
9056 ((null labels) ; no current label to go to
9057 (if (null js2-loop-set) ; no loop to continue to
9058 (js2-report-error "msg.continue.outside" nil pos
9059 (length "continue"))
9060 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9061 (t
9062 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9063 (setq target (js2-labeled-stmt-node-stmt labels))
9064 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9065 (setq pn (make-js2-continue-node :pos pos
9066 :len (- end pos)
9067 :label label
9068 :target target))
9069 (js2-node-add-children pn label) ; but not target - it's not our child
9070 pn))
9071
9072 (defun js2-parse-with ()
9073 "Parser for with-statement. Last matched token must be js2-WITH."
9074 (when js2-in-use-strict-directive
9075 (js2-report-error "msg.no.with.strict"))
9076 (let ((pos (js2-current-token-beg))
9077 obj body pn lp rp)
9078 (if (js2-must-match js2-LP "msg.no.paren.with")
9079 (setq lp (js2-current-token-beg)))
9080 (setq obj (js2-parse-expr))
9081 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9082 (setq rp (js2-current-token-beg)))
9083 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9084 (setq body (js2-parse-statement)))
9085 (setq pn (make-js2-with-node :pos pos
9086 :len (- (js2-node-end body) pos)
9087 :object obj
9088 :body body
9089 :lp (js2-relpos lp pos)
9090 :rp (js2-relpos rp pos)))
9091 (js2-node-add-children pn obj body)
9092 pn))
9093
9094 (defun js2-parse-const-var ()
9095 "Parser for var- or const-statement.
9096 Last matched token must be js2-CONST or js2-VAR."
9097 (let ((tt (js2-current-token-type))
9098 (pos (js2-current-token-beg))
9099 expr pn)
9100 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9101 pn (make-js2-expr-stmt-node :pos pos
9102 :len (- (js2-node-end expr) pos)
9103 :expr expr))
9104 (js2-node-add-children pn expr)
9105 pn))
9106
9107 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9108 (let ((pn (make-js2-expr-stmt-node :pos pos
9109 :len (js2-node-len expr)
9110 :type (if (js2-inside-function)
9111 js2-EXPR_VOID
9112 js2-EXPR_RESULT)
9113 :expr expr)))
9114 (if add-child
9115 (js2-node-add-children pn expr))
9116 pn))
9117
9118 (defun js2-parse-let-stmt ()
9119 "Parser for let-statement. Last matched token must be js2-LET."
9120 (let ((pos (js2-current-token-beg))
9121 expr pn)
9122 (if (= (js2-peek-token) js2-LP)
9123 ;; let expression in statement context
9124 (setq expr (js2-parse-let pos 'statement)
9125 pn (js2-wrap-with-expr-stmt pos expr t))
9126 ;; else we're looking at a statement like let x=6, y=7;
9127 (setf expr (js2-parse-variables js2-LET pos)
9128 pn (js2-wrap-with-expr-stmt pos expr t)
9129 (js2-node-type pn) js2-EXPR_RESULT))
9130 pn))
9131
9132 (defun js2-parse-ret-yield ()
9133 (js2-parse-return-or-yield (js2-current-token-type) nil))
9134
9135 (defconst js2-parse-return-stmt-enders
9136 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9137
9138 (defsubst js2-now-all-set (before after mask)
9139 "Return whether or not the bits in the mask have changed to all set.
9140 BEFORE is bits before change, AFTER is bits after change, and MASK is
9141 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9142 but not BEFORE."
9143 (and (/= (logand before mask) mask)
9144 (= (logand after mask) mask)))
9145
9146 (defun js2-parse-return-or-yield (tt expr-context)
9147 (let* ((pos (js2-current-token-beg))
9148 (end (js2-current-token-end))
9149 (before js2-end-flags)
9150 (inside-function (js2-inside-function))
9151 (gen-type (and inside-function (js2-function-node-generator-type
9152 js2-current-script-or-fn)))
9153 e ret name yield-star-p)
9154 (unless inside-function
9155 (js2-report-error (if (eq tt js2-RETURN)
9156 "msg.bad.return"
9157 "msg.bad.yield")))
9158 (when (and inside-function
9159 (eq gen-type 'STAR)
9160 (js2-match-token js2-MUL))
9161 (setq yield-star-p t))
9162 ;; This is ugly, but we don't want to require a semicolon.
9163 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9164 (setq e (js2-parse-expr)
9165 end (js2-node-end e)))
9166 (cond
9167 ((eq tt js2-RETURN)
9168 (js2-set-flag js2-end-flags (if (null e)
9169 js2-end-returns
9170 js2-end-returns-value))
9171 (setq ret (make-js2-return-node :pos pos
9172 :len (- end pos)
9173 :retval e))
9174 (js2-node-add-children ret e)
9175 ;; See if we need a strict mode warning.
9176 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9177 ;; more thorough and accurate than this before/after flag check.
9178 ;; E.g. if there's a finally-block that always returns, we shouldn't
9179 ;; show a warning generated by inconsistent returns in the catch blocks.
9180 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9181 ;; so we know which returns/yields to highlight, and we should get rid of
9182 ;; all the checking in `js2-parse-return-or-yield'.
9183 (if (and js2-strict-inconsistent-return-warning
9184 (js2-now-all-set before js2-end-flags
9185 (logior js2-end-returns js2-end-returns-value)))
9186 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9187 ((eq gen-type 'COMPREHENSION)
9188 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9189 ;; like SpiderMonkey does.
9190 (js2-report-error "msg.syntax" nil pos 5))
9191 (t
9192 (setq ret (make-js2-yield-node :pos pos
9193 :len (- end pos)
9194 :value e
9195 :star-p yield-star-p))
9196 (js2-node-add-children ret e)
9197 (unless expr-context
9198 (setq e ret
9199 ret (js2-wrap-with-expr-stmt pos e t))
9200 (js2-set-requires-activation)
9201 (js2-set-is-generator))))
9202 ;; see if we are mixing yields and value returns.
9203 (when (and inside-function
9204 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9205 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9206 'LEGACY))
9207 (setq name (js2-function-name js2-current-script-or-fn))
9208 (if (zerop (length name))
9209 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9210 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9211 ret))
9212
9213 (defun js2-parse-debugger ()
9214 (make-js2-keyword-node :type js2-DEBUGGER))
9215
9216 (defun js2-parse-block ()
9217 "Parser for a curly-delimited statement block.
9218 Last token matched must be `js2-LC'."
9219 (let ((pos (js2-current-token-beg))
9220 (pn (make-js2-scope)))
9221 (js2-push-scope pn)
9222 (unwind-protect
9223 (progn
9224 (js2-parse-statements pn)
9225 (js2-must-match js2-RC "msg.no.brace.block")
9226 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9227 (js2-pop-scope))
9228 pn))
9229
9230 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9231 (defun js2-parse-semi ()
9232 "Parse a statement or handle an error.
9233 Current token type is `js2-SEMI' or `js2-ERROR'."
9234 (let ((tt (js2-current-token-type)) pos len)
9235 (if (eq tt js2-SEMI)
9236 (make-js2-empty-expr-node :len 1)
9237 (setq pos (js2-current-token-beg)
9238 len (- (js2-current-token-end) pos))
9239 (js2-report-error "msg.syntax" nil pos len)
9240 (make-js2-error-node :pos pos :len len))))
9241
9242 (defun js2-parse-default-xml-namespace ()
9243 "Parse a `default xml namespace = <expr>' e4x statement."
9244 (let ((pos (js2-current-token-beg))
9245 end len expr unary)
9246 (js2-must-have-xml)
9247 (js2-set-requires-activation)
9248 (setq len (- js2-ts-cursor pos))
9249 (unless (and (js2-match-token js2-NAME)
9250 (string= (js2-current-token-string) "xml"))
9251 (js2-report-error "msg.bad.namespace" nil pos len))
9252 (unless (and (js2-match-token js2-NAME)
9253 (string= (js2-current-token-string) "namespace"))
9254 (js2-report-error "msg.bad.namespace" nil pos len))
9255 (unless (js2-match-token js2-ASSIGN)
9256 (js2-report-error "msg.bad.namespace" nil pos len))
9257 (setq expr (js2-parse-expr)
9258 end (js2-node-end expr)
9259 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9260 :pos pos
9261 :len (- end pos)
9262 :operand expr))
9263 (js2-node-add-children unary expr)
9264 (make-js2-expr-stmt-node :pos pos
9265 :len (- end pos)
9266 :expr unary)))
9267
9268 (defun js2-record-label (label bundle)
9269 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9270 (js2-get-token)
9271 (let ((name (js2-label-node-name label))
9272 labeled-stmt
9273 dup)
9274 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9275 ;; flag both labels if possible when used in editing mode
9276 (if (and js2-parse-ide-mode
9277 (setq dup (js2-get-label-by-name labeled-stmt name)))
9278 (js2-report-error "msg.dup.label" nil
9279 (js2-node-abs-pos dup) (js2-node-len dup)))
9280 (js2-report-error "msg.dup.label" nil
9281 (js2-node-pos label) (js2-node-len label)))
9282 (js2-labeled-stmt-node-add-label bundle label)
9283 (js2-node-add-children bundle label)
9284 ;; Add one reference to the bundle per label in `js2-label-set'
9285 (push (cons name bundle) js2-label-set)))
9286
9287 (defun js2-parse-name-or-label ()
9288 "Parser for identifier or label. Last token matched must be js2-NAME.
9289 Called when we found a name in a statement context. If it's a label, we gather
9290 up any following labels and the next non-label statement into a
9291 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9292 expression and return it wrapped in a `js2-expr-stmt-node'."
9293 (let ((pos (js2-current-token-beg))
9294 expr stmt bundle
9295 (continue t))
9296 ;; set check for label and call down to `js2-parse-primary-expr'
9297 (setq expr (js2-maybe-parse-label))
9298 (if (null expr)
9299 ;; Parse the non-label expression and wrap with expression stmt.
9300 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9301 ;; else parsed a label
9302 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9303 (js2-record-label expr bundle)
9304 ;; look for more labels
9305 (while (and continue (= (js2-get-token) js2-NAME))
9306 (if (setq expr (js2-maybe-parse-label))
9307 (js2-record-label expr bundle)
9308 (setq expr (js2-parse-expr)
9309 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9310 continue nil)
9311 (js2-auto-insert-semicolon stmt)))
9312 ;; no more labels; now parse the labeled statement
9313 (unwind-protect
9314 (unless stmt
9315 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9316 (js2-unget-token)
9317 (setq stmt (js2-statement-helper))))
9318 ;; remove the labels for this statement from the global set
9319 (dolist (label (js2-labeled-stmt-node-labels bundle))
9320 (setq js2-label-set (remove label js2-label-set))))
9321 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9322 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9323 (js2-node-add-children bundle stmt)
9324 bundle)))
9325
9326 (defun js2-maybe-parse-label ()
9327 (cl-assert (= (js2-current-token-type) js2-NAME))
9328 (let (label-pos
9329 (next-tt (js2-get-token))
9330 (label-end (js2-current-token-end)))
9331 ;; Do not consume colon, it is used as unwind indicator
9332 ;; to return to statementHelper.
9333 (js2-unget-token)
9334 (if (= next-tt js2-COLON)
9335 (prog2
9336 (setq label-pos (js2-current-token-beg))
9337 (make-js2-label-node :pos label-pos
9338 :len (- label-end label-pos)
9339 :name (js2-current-token-string))
9340 (js2-set-face label-pos
9341 label-end
9342 'font-lock-variable-name-face 'record))
9343 ;; Backtrack from the name token, too.
9344 (js2-unget-token)
9345 nil)))
9346
9347 (defun js2-parse-expr-stmt ()
9348 "Default parser in statement context, if no recognized statement found."
9349 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9350 (progn
9351 (js2-unget-token)
9352 (js2-parse-expr)) t))
9353
9354 (defun js2-parse-variables (decl-type pos)
9355 "Parse a comma-separated list of variable declarations.
9356 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9357
9358 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9359 For 'var' or 'const', the keyword should be the token last scanned.
9360
9361 POS is the position where the node should start. It's sometimes the
9362 var/const/let keyword, and other times the beginning of the first token
9363 in the first variable declaration.
9364
9365 Returns the parsed `js2-var-decl-node' expression node."
9366 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9367 :pos pos))
9368 destructuring kid-pos tt init name end nbeg nend vi
9369 (continue t))
9370 ;; Example:
9371 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9372 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9373 ;; var {a, b} = baz;
9374 (while continue
9375 (setq destructuring nil
9376 name nil
9377 tt (js2-get-token)
9378 kid-pos (js2-current-token-beg)
9379 end (js2-current-token-end)
9380 init nil)
9381 (if (or (= tt js2-LB) (= tt js2-LC))
9382 ;; Destructuring assignment, e.g., var [a, b] = ...
9383 (setq destructuring (js2-parse-destruct-primary-expr)
9384 end (js2-node-end destructuring))
9385 ;; Simple variable name
9386 (js2-unget-token)
9387 (when (js2-must-match-name "msg.bad.var")
9388 (setq name (js2-create-name-node)
9389 nbeg (js2-current-token-beg)
9390 nend (js2-current-token-end)
9391 end nend)
9392 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9393 (js2-check-strict-identifier name)))
9394 (when (js2-match-token js2-ASSIGN)
9395 (setq init (js2-parse-assign-expr)
9396 end (js2-node-end init))
9397 (js2-record-imenu-functions init name))
9398 (when name
9399 (js2-set-face nbeg nend (if (js2-function-node-p init)
9400 'font-lock-function-name-face
9401 'font-lock-variable-name-face)
9402 'record))
9403 (setq vi (make-js2-var-init-node :pos kid-pos
9404 :len (- end kid-pos)
9405 :type decl-type))
9406 (if destructuring
9407 (progn
9408 (if (and (null init) (not js2-in-for-init))
9409 (js2-report-error "msg.destruct.assign.no.init"))
9410 (js2-define-destruct-symbols destructuring
9411 decl-type
9412 'font-lock-variable-name-face)
9413 (setf (js2-var-init-node-target vi) destructuring))
9414 (setf (js2-var-init-node-target vi) name))
9415 (setf (js2-var-init-node-initializer vi) init)
9416 (js2-node-add-children vi name destructuring init)
9417 (js2-block-node-push result vi)
9418 (unless (js2-match-token js2-COMMA)
9419 (setq continue nil)))
9420 (setf (js2-node-len result) (- end pos))
9421 result))
9422
9423 (defun js2-parse-let (pos &optional stmt-p)
9424 "Parse a let expression or statement.
9425 A let-expression is of the form `let (vars) expr'.
9426 A let-statement is of the form `let (vars) {statements}'.
9427 The third form of let is a variable declaration list, handled
9428 by `js2-parse-variables'."
9429 (let ((pn (make-js2-let-node :pos pos))
9430 beg vars body)
9431 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9432 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9433 (js2-push-scope pn)
9434 (unwind-protect
9435 (progn
9436 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9437 (if (js2-must-match js2-RP "msg.no.paren.let")
9438 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9439 (if (and stmt-p (js2-match-token js2-LC))
9440 ;; let statement
9441 (progn
9442 (setf beg (js2-current-token-beg) ; position stmt at LC
9443 body (js2-parse-statements))
9444 (js2-must-match js2-RC "msg.no.curly.let")
9445 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9446 (js2-node-len pn) (- (js2-current-token-end) pos)
9447 (js2-let-node-body pn) body
9448 (js2-node-type pn) js2-LET))
9449 ;; let expression
9450 (setf body (js2-parse-expr)
9451 (js2-node-len pn) (- (js2-node-end body) pos)
9452 (js2-let-node-body pn) body))
9453 (setf (js2-let-node-vars pn) vars)
9454 (js2-node-add-children pn vars body))
9455 (js2-pop-scope))
9456 pn))
9457
9458 (defun js2-define-new-symbol (decl-type name node &optional scope)
9459 (js2-scope-put-symbol (or scope js2-current-scope)
9460 name
9461 (make-js2-symbol decl-type name node)))
9462
9463 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9464 "Define a symbol in the current scope.
9465 If NODE is non-nil, it is the AST node associated with the symbol."
9466 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9467 (symbol (if defining-scope
9468 (js2-scope-get-symbol defining-scope name)))
9469 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9470 (pos (if node (js2-node-abs-pos node)))
9471 (len (if node (js2-node-len node))))
9472 (cond
9473 ((and symbol ; already defined
9474 (or (if js2-in-use-strict-directive
9475 ;; two const-bound vars in this block have same name
9476 (and (= sdt js2-CONST)
9477 (eq defining-scope js2-current-scope))
9478 (or (= sdt js2-CONST) ; old version is const
9479 (= decl-type js2-CONST))) ; new version is const
9480 ;; two let-bound vars in this block have same name
9481 (and (= sdt js2-LET)
9482 (eq defining-scope js2-current-scope))))
9483 (js2-report-error
9484 (cond
9485 ((= sdt js2-CONST) "msg.const.redecl")
9486 ((= sdt js2-LET) "msg.let.redecl")
9487 ((= sdt js2-VAR) "msg.var.redecl")
9488 ((= sdt js2-FUNCTION) "msg.function.redecl")
9489 (t "msg.parm.redecl"))
9490 name pos len))
9491 ((or (= decl-type js2-LET)
9492 ;; strict mode const is scoped to the current LexicalEnvironment
9493 (and js2-in-use-strict-directive
9494 (= decl-type js2-CONST)))
9495 (if (and (= decl-type js2-LET)
9496 (not ignore-not-in-block)
9497 (or (= (js2-node-type js2-current-scope) js2-IF)
9498 (js2-loop-node-p js2-current-scope)))
9499 (js2-report-error "msg.let.decl.not.in.block")
9500 (js2-define-new-symbol decl-type name node)))
9501 ((or (= decl-type js2-VAR)
9502 (= decl-type js2-FUNCTION)
9503 ;; sloppy mode const is scoped to the current VariableEnvironment
9504 (and (not js2-in-use-strict-directive)
9505 (= decl-type js2-CONST)))
9506 (if symbol
9507 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9508 (js2-add-strict-warning "msg.var.redecl" name)
9509 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9510 (js2-add-strict-warning "msg.var.hides.arg" name)))
9511 (js2-define-new-symbol decl-type name node
9512 js2-current-script-or-fn)))
9513 ((= decl-type js2-LP)
9514 (if symbol
9515 ;; must be duplicate parameter. Second parameter hides the
9516 ;; first, so go ahead and add the second pararameter
9517 (js2-report-warning "msg.dup.parms" name))
9518 (js2-define-new-symbol decl-type name node))
9519 (t (js2-code-bug)))))
9520
9521 (defun js2-parse-paren-expr-or-generator-comp ()
9522 (let ((px-pos (js2-current-token-beg)))
9523 (cond
9524 ((and (>= js2-language-version 200)
9525 (js2-match-token js2-FOR))
9526 (js2-parse-generator-comp px-pos))
9527 ((and (>= js2-language-version 200)
9528 (js2-match-token js2-RP))
9529 ;; Not valid expression syntax, but this is valid in an arrow
9530 ;; function with no params: () => body.
9531 (if (eq (js2-peek-token) js2-ARROW)
9532 ;; Return whatever, it will hopefully be rewinded and
9533 ;; reparsed when we reach the =>.
9534 (make-js2-keyword-node :type js2-NULL)
9535 (js2-report-error "msg.syntax")
9536 (make-js2-error-node)))
9537 (t
9538 (let* ((js2-in-for-init nil)
9539 (expr (js2-parse-expr))
9540 (pn (make-js2-paren-node :pos px-pos
9541 :expr expr)))
9542 (js2-node-add-children pn (js2-paren-node-expr pn))
9543 (js2-must-match js2-RP "msg.no.paren")
9544 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9545 pn)))))
9546
9547 (defun js2-parse-expr (&optional oneshot)
9548 (let* ((pn (js2-parse-assign-expr))
9549 (pos (js2-node-pos pn))
9550 left
9551 right
9552 op-pos)
9553 (while (and (not oneshot)
9554 (js2-match-token js2-COMMA))
9555 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9556 (if (= (js2-peek-token) js2-YIELD)
9557 (js2-report-error "msg.yield.parenthesized"))
9558 (setq right (js2-parse-assign-expr)
9559 left pn
9560 pn (make-js2-infix-node :type js2-COMMA
9561 :pos pos
9562 :len (- js2-ts-cursor pos)
9563 :op-pos op-pos
9564 :left left
9565 :right right))
9566 (js2-node-add-children pn left right))
9567 pn))
9568
9569 (defun js2-parse-assign-expr ()
9570 (let ((tt (js2-get-token))
9571 (pos (js2-current-token-beg))
9572 pn left right op-pos
9573 ts-state recorded-identifiers parsed-errors)
9574 (if (= tt js2-YIELD)
9575 (js2-parse-return-or-yield tt t)
9576 ;; Save the tokenizer state in case we find an arrow function
9577 ;; and have to rewind.
9578 (setq ts-state (make-js2-ts-state)
9579 recorded-identifiers js2-recorded-identifiers
9580 parsed-errors js2-parsed-errors)
9581 ;; not yield - parse assignment expression
9582 (setq pn (js2-parse-cond-expr)
9583 tt (js2-get-token))
9584 (cond
9585 ((and (<= js2-first-assign tt)
9586 (<= tt js2-last-assign))
9587 ;; tt express assignment (=, |=, ^=, ..., %=)
9588 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9589 left pn)
9590 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9591 ;; care about assignment to strict variable names.
9592 (when (js2-name-node-p left)
9593 (js2-check-strict-identifier left))
9594 (setq right (js2-parse-assign-expr)
9595 pn (make-js2-assign-node :type tt
9596 :pos pos
9597 :len (- (js2-node-end right) pos)
9598 :op-pos op-pos
9599 :left left
9600 :right right))
9601 (when js2-parse-ide-mode
9602 (js2-highlight-assign-targets pn left right)
9603 (js2-record-imenu-functions right left))
9604 ;; do this last so ide checks above can use absolute positions
9605 (js2-node-add-children pn left right))
9606 ((and (= tt js2-ARROW)
9607 (>= js2-language-version 200))
9608 (js2-ts-seek ts-state)
9609 (setq js2-recorded-identifiers recorded-identifiers
9610 js2-parsed-errors parsed-errors)
9611 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9612 (t
9613 (js2-unget-token)))
9614 pn)))
9615
9616 (defun js2-parse-cond-expr ()
9617 (let ((pos (js2-current-token-beg))
9618 (pn (js2-parse-or-expr))
9619 test-expr
9620 if-true
9621 if-false
9622 q-pos
9623 c-pos)
9624 (when (js2-match-token js2-HOOK)
9625 (setq q-pos (- (js2-current-token-beg) pos)
9626 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9627 (js2-must-match js2-COLON "msg.no.colon.cond")
9628 (setq c-pos (- (js2-current-token-beg) pos)
9629 if-false (js2-parse-assign-expr)
9630 test-expr pn
9631 pn (make-js2-cond-node :pos pos
9632 :len (- (js2-node-end if-false) pos)
9633 :test-expr test-expr
9634 :true-expr if-true
9635 :false-expr if-false
9636 :q-pos q-pos
9637 :c-pos c-pos))
9638 (js2-node-add-children pn test-expr if-true if-false))
9639 pn))
9640
9641 (defun js2-make-binary (type left parser &optional no-get)
9642 "Helper for constructing a binary-operator AST node.
9643 LEFT is the left-side-expression, already parsed, and the
9644 binary operator should have just been matched.
9645 PARSER is a function to call to parse the right operand,
9646 or a `js2-node' struct if it has already been parsed.
9647 FIXME: The latter option is unused?"
9648 (let* ((pos (js2-node-pos left))
9649 (op-pos (- (js2-current-token-beg) pos))
9650 (right (if (js2-node-p parser)
9651 parser
9652 (unless no-get (js2-get-token))
9653 (funcall parser)))
9654 (pn (make-js2-infix-node :type type
9655 :pos pos
9656 :len (- (js2-node-end right) pos)
9657 :op-pos op-pos
9658 :left left
9659 :right right)))
9660 (js2-node-add-children pn left right)
9661 pn))
9662
9663 (defun js2-parse-or-expr ()
9664 (let ((pn (js2-parse-and-expr)))
9665 (when (js2-match-token js2-OR)
9666 (setq pn (js2-make-binary js2-OR
9667 pn
9668 'js2-parse-or-expr)))
9669 pn))
9670
9671 (defun js2-parse-and-expr ()
9672 (let ((pn (js2-parse-bit-or-expr)))
9673 (when (js2-match-token js2-AND)
9674 (setq pn (js2-make-binary js2-AND
9675 pn
9676 'js2-parse-and-expr)))
9677 pn))
9678
9679 (defun js2-parse-bit-or-expr ()
9680 (let ((pn (js2-parse-bit-xor-expr)))
9681 (while (js2-match-token js2-BITOR)
9682 (setq pn (js2-make-binary js2-BITOR
9683 pn
9684 'js2-parse-bit-xor-expr)))
9685 pn))
9686
9687 (defun js2-parse-bit-xor-expr ()
9688 (let ((pn (js2-parse-bit-and-expr)))
9689 (while (js2-match-token js2-BITXOR)
9690 (setq pn (js2-make-binary js2-BITXOR
9691 pn
9692 'js2-parse-bit-and-expr)))
9693 pn))
9694
9695 (defun js2-parse-bit-and-expr ()
9696 (let ((pn (js2-parse-eq-expr)))
9697 (while (js2-match-token js2-BITAND)
9698 (setq pn (js2-make-binary js2-BITAND
9699 pn
9700 'js2-parse-eq-expr)))
9701 pn))
9702
9703 (defconst js2-parse-eq-ops
9704 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9705
9706 (defun js2-parse-eq-expr ()
9707 (let ((pn (js2-parse-rel-expr))
9708 tt)
9709 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9710 (setq pn (js2-make-binary tt
9711 pn
9712 'js2-parse-rel-expr)))
9713 (js2-unget-token)
9714 pn))
9715
9716 (defconst js2-parse-rel-ops
9717 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9718
9719 (defun js2-parse-rel-expr ()
9720 (let ((pn (js2-parse-shift-expr))
9721 (continue t)
9722 tt)
9723 (while continue
9724 (setq tt (js2-get-token))
9725 (cond
9726 ((and js2-in-for-init (= tt js2-IN))
9727 (js2-unget-token)
9728 (setq continue nil))
9729 ((memq tt js2-parse-rel-ops)
9730 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9731 (t
9732 (js2-unget-token)
9733 (setq continue nil))))
9734 pn))
9735
9736 (defconst js2-parse-shift-ops
9737 (list js2-LSH js2-URSH js2-RSH))
9738
9739 (defun js2-parse-shift-expr ()
9740 (let ((pn (js2-parse-add-expr))
9741 tt
9742 (continue t))
9743 (while continue
9744 (setq tt (js2-get-token))
9745 (if (memq tt js2-parse-shift-ops)
9746 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9747 (js2-unget-token)
9748 (setq continue nil)))
9749 pn))
9750
9751 (defun js2-parse-add-expr ()
9752 (let ((pn (js2-parse-mul-expr))
9753 tt
9754 (continue t))
9755 (while continue
9756 (setq tt (js2-get-token))
9757 (if (or (= tt js2-ADD) (= tt js2-SUB))
9758 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9759 (js2-unget-token)
9760 (setq continue nil)))
9761 pn))
9762
9763 (defconst js2-parse-mul-ops
9764 (list js2-MUL js2-DIV js2-MOD))
9765
9766 (defun js2-parse-mul-expr ()
9767 (let ((pn (js2-parse-unary-expr))
9768 tt
9769 (continue t))
9770 (while continue
9771 (setq tt (js2-get-token))
9772 (if (memq tt js2-parse-mul-ops)
9773 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9774 (js2-unget-token)
9775 (setq continue nil)))
9776 pn))
9777
9778 (defun js2-make-unary (type parser &rest args)
9779 "Make a unary node of type TYPE.
9780 PARSER is either a node (for postfix operators) or a function to call
9781 to parse the operand (for prefix operators)."
9782 (let* ((pos (js2-current-token-beg))
9783 (postfix (js2-node-p parser))
9784 (expr (if postfix
9785 parser
9786 (apply parser args)))
9787 end
9788 pn)
9789 (if postfix ; e.g. i++
9790 (setq pos (js2-node-pos expr)
9791 end (js2-current-token-end))
9792 (setq end (js2-node-end expr)))
9793 (setq pn (make-js2-unary-node :type type
9794 :pos pos
9795 :len (- end pos)
9796 :operand expr))
9797 (js2-node-add-children pn expr)
9798 pn))
9799
9800 (defconst js2-incrementable-node-types
9801 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9802 "Node types that can be the operand of a ++ or -- operator.")
9803
9804 (defun js2-check-bad-inc-dec (tt beg end unary)
9805 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9806 js2-incrementable-node-types)
9807 (js2-report-error (if (= tt js2-INC)
9808 "msg.bad.incr"
9809 "msg.bad.decr")
9810 nil beg (- end beg))))
9811
9812 (defun js2-parse-unary-expr ()
9813 (let ((tt (js2-current-token-type))
9814 pn expr beg end)
9815 (cond
9816 ((or (= tt js2-VOID)
9817 (= tt js2-NOT)
9818 (= tt js2-BITNOT)
9819 (= tt js2-TYPEOF))
9820 (js2-get-token)
9821 (js2-make-unary tt 'js2-parse-unary-expr))
9822 ((= tt js2-ADD)
9823 (js2-get-token)
9824 ;; Convert to special POS token in decompiler and parse tree
9825 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9826 ((= tt js2-SUB)
9827 (js2-get-token)
9828 ;; Convert to special NEG token in decompiler and parse tree
9829 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9830 ((or (= tt js2-INC)
9831 (= tt js2-DEC))
9832 (js2-get-token)
9833 (prog1
9834 (setq beg (js2-current-token-beg)
9835 end (js2-current-token-end)
9836 expr (js2-make-unary tt 'js2-parse-member-expr t))
9837 (js2-check-bad-inc-dec tt beg end expr)))
9838 ((= tt js2-DELPROP)
9839 (js2-get-token)
9840 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9841 ((= tt js2-ERROR)
9842 (js2-get-token)
9843 (make-js2-error-node)) ; try to continue
9844 ((and (= tt js2-LT)
9845 js2-compiler-xml-available)
9846 ;; XML stream encountered in expression.
9847 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9848 (t
9849 (setq pn (js2-parse-member-expr t)
9850 ;; Don't look across a newline boundary for a postfix incop.
9851 tt (js2-peek-token-or-eol))
9852 (when (or (= tt js2-INC) (= tt js2-DEC))
9853 (js2-get-token)
9854 (setf expr pn
9855 pn (js2-make-unary tt expr))
9856 (js2-node-set-prop pn 'postfix t)
9857 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9858 pn))))
9859
9860 (defun js2-parse-xml-initializer ()
9861 "Parse an E4X XML initializer.
9862 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9863 Then I'll postprocess the result, depending on whether we're in IDE
9864 mode or codegen mode, and generate the appropriate rewritten AST.
9865 IDE mode uses a rich AST that models the XML structure. Codegen mode
9866 just concatenates everything and makes a new XML or XMLList out of it."
9867 (let ((tt (js2-get-first-xml-token))
9868 pn-xml pn expr kids expr-pos
9869 (continue t)
9870 (first-token t))
9871 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9872 (js2-report-error "msg.syntax"))
9873 (setq pn-xml (make-js2-xml-node))
9874 (while continue
9875 (if first-token
9876 (setq first-token nil)
9877 (setq tt (js2-get-next-xml-token)))
9878 (cond
9879 ;; js2-XML means we found a {expr} in the XML stream.
9880 ;; The token string is the XML up to the left-curly.
9881 ((= tt js2-XML)
9882 (push (make-js2-string-node :pos (js2-current-token-beg)
9883 :len (- js2-ts-cursor (js2-current-token-beg)))
9884 kids)
9885 (js2-must-match js2-LC "msg.syntax")
9886 (setq expr-pos js2-ts-cursor
9887 expr (if (eq (js2-peek-token) js2-RC)
9888 (make-js2-empty-expr-node :pos expr-pos)
9889 (js2-parse-expr)))
9890 (js2-must-match js2-RC "msg.syntax")
9891 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9892 :len (js2-node-len expr)
9893 :expr expr))
9894 (js2-node-add-children pn expr)
9895 (push pn kids))
9896 ;; a js2-XMLEND token means we hit the final close-tag.
9897 ((= tt js2-XMLEND)
9898 (push (make-js2-string-node :pos (js2-current-token-beg)
9899 :len (- js2-ts-cursor (js2-current-token-beg)))
9900 kids)
9901 (dolist (kid (nreverse kids))
9902 (js2-block-node-push pn-xml kid))
9903 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9904 (js2-node-pos pn-xml))
9905 continue nil))
9906 (t
9907 (js2-report-error "msg.syntax")
9908 (setq continue nil))))
9909 pn-xml))
9910
9911
9912 (defun js2-parse-argument-list ()
9913 "Parse an argument list and return it as a Lisp list of nodes.
9914 Returns the list in reverse order. Consumes the right-paren token."
9915 (let (result)
9916 (unless (js2-match-token js2-RP)
9917 (cl-loop do
9918 (let ((tt (js2-get-token)))
9919 (if (= tt js2-YIELD)
9920 (js2-report-error "msg.yield.parenthesized"))
9921 (if (and (= tt js2-TRIPLEDOT)
9922 (>= js2-language-version 200))
9923 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9924 (js2-unget-token)
9925 (push (js2-parse-assign-expr) result)))
9926 while
9927 (js2-match-token js2-COMMA))
9928 (js2-must-match js2-RP "msg.no.paren.arg")
9929 result)))
9930
9931 (defun js2-parse-member-expr (&optional allow-call-syntax)
9932 (let ((tt (js2-current-token-type))
9933 pn pos target args beg end init)
9934 (if (/= tt js2-NEW)
9935 (setq pn (js2-parse-primary-expr))
9936 ;; parse a 'new' expression
9937 (js2-get-token)
9938 (setq pos (js2-current-token-beg)
9939 beg pos
9940 target (js2-parse-member-expr)
9941 end (js2-node-end target)
9942 pn (make-js2-new-node :pos pos
9943 :target target
9944 :len (- end pos)))
9945 (js2-highlight-function-call (js2-current-token))
9946 (js2-node-add-children pn target)
9947 (when (js2-match-token js2-LP)
9948 ;; Add the arguments to pn, if any are supplied.
9949 (setf beg pos ; start of "new" keyword
9950 pos (js2-current-token-beg)
9951 args (nreverse (js2-parse-argument-list))
9952 (js2-new-node-args pn) args
9953 end (js2-current-token-end)
9954 (js2-new-node-lp pn) (- pos beg)
9955 (js2-new-node-rp pn) (- end 1 beg))
9956 (apply #'js2-node-add-children pn args))
9957 (when (and js2-allow-rhino-new-expr-initializer
9958 (js2-match-token js2-LC))
9959 (setf init (js2-parse-object-literal)
9960 end (js2-node-end init)
9961 (js2-new-node-initializer pn) init)
9962 (js2-node-add-children pn init))
9963 (setf (js2-node-len pn) (- end beg))) ; end outer if
9964 (js2-parse-member-expr-tail allow-call-syntax pn)))
9965
9966 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9967 "Parse a chain of property/array accesses or function calls.
9968 Includes parsing for E4X operators like `..' and `.@'.
9969 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9970 Returns an expression tree that includes PN, the parent node."
9971 (let (tt
9972 (continue t))
9973 (while continue
9974 (setq tt (js2-get-token))
9975 (cond
9976 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9977 (setq pn (js2-parse-property-access tt pn)))
9978 ((= tt js2-DOTQUERY)
9979 (setq pn (js2-parse-dot-query pn)))
9980 ((= tt js2-LB)
9981 (setq pn (js2-parse-element-get pn)))
9982 ((= tt js2-LP)
9983 (js2-unget-token)
9984 (if allow-call-syntax
9985 (setq pn (js2-parse-function-call pn))
9986 (setq continue nil)))
9987 ((= tt js2-TEMPLATE_HEAD)
9988 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9989 ((= tt js2-NO_SUBS_TEMPLATE)
9990 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9991 (t
9992 (js2-unget-token)
9993 (setq continue nil)))
9994 (if (>= js2-highlight-level 2)
9995 (js2-parse-highlight-member-expr-node pn)))
9996 pn))
9997
9998 (defun js2-parse-tagged-template (tag-node tpl-node)
9999 "Parse tagged template expression."
10000 (let* ((beg (js2-node-pos tag-node))
10001 (pn (make-js2-tagged-template-node :beg beg
10002 :len (- (js2-current-token-end) beg)
10003 :tag tag-node
10004 :template tpl-node)))
10005 (js2-node-add-children pn tag-node tpl-node)
10006 pn))
10007
10008 (defun js2-parse-dot-query (pn)
10009 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10010 Last token parsed must be `js2-DOTQUERY'."
10011 (let ((pos (js2-node-pos pn))
10012 op-pos expr end)
10013 (js2-must-have-xml)
10014 (js2-set-requires-activation)
10015 (setq op-pos (js2-current-token-beg)
10016 expr (js2-parse-expr)
10017 end (js2-node-end expr)
10018 pn (make-js2-xml-dot-query-node :left pn
10019 :pos pos
10020 :op-pos op-pos
10021 :right expr))
10022 (js2-node-add-children pn
10023 (js2-xml-dot-query-node-left pn)
10024 (js2-xml-dot-query-node-right pn))
10025 (if (js2-must-match js2-RP "msg.no.paren")
10026 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10027 end (js2-current-token-end)))
10028 (setf (js2-node-len pn) (- end pos))
10029 pn))
10030
10031 (defun js2-parse-element-get (pn)
10032 "Parse an element-get expression, e.g. foo[bar].
10033 Last token parsed must be `js2-RB'."
10034 (let ((lb (js2-current-token-beg))
10035 (pos (js2-node-pos pn))
10036 rb expr)
10037 (setq expr (js2-parse-expr))
10038 (if (js2-must-match js2-RB "msg.no.bracket.index")
10039 (setq rb (js2-current-token-beg)))
10040 (setq pn (make-js2-elem-get-node :target pn
10041 :pos pos
10042 :element expr
10043 :lb (js2-relpos lb pos)
10044 :rb (js2-relpos rb pos)
10045 :len (- (js2-current-token-end) pos)))
10046 (js2-node-add-children pn
10047 (js2-elem-get-node-target pn)
10048 (js2-elem-get-node-element pn))
10049 pn))
10050
10051 (defun js2-highlight-function-call (token)
10052 (when (eq (js2-token-type token) js2-NAME)
10053 (js2-record-face 'js2-function-call token)))
10054
10055 (defun js2-parse-function-call (pn)
10056 (js2-highlight-function-call (js2-current-token))
10057 (js2-get-token)
10058 (let (args
10059 (pos (js2-node-pos pn)))
10060 (setq pn (make-js2-call-node :pos pos
10061 :target pn
10062 :lp (- (js2-current-token-beg) pos)))
10063 (js2-node-add-children pn (js2-call-node-target pn))
10064 ;; Add the arguments to pn, if any are supplied.
10065 (setf args (nreverse (js2-parse-argument-list))
10066 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10067 (js2-call-node-args pn) args)
10068 (apply #'js2-node-add-children pn args)
10069 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10070 pn))
10071
10072 (defun js2-parse-property-access (tt pn)
10073 "Parse a property access, XML descendants access, or XML attr access."
10074 (let ((member-type-flags 0)
10075 (dot-pos (js2-current-token-beg))
10076 (dot-len (if (= tt js2-DOTDOT) 2 1))
10077 name
10078 ref ; right side of . or .. operator
10079 result)
10080 (when (= tt js2-DOTDOT)
10081 (js2-must-have-xml)
10082 (setq member-type-flags js2-descendants-flag))
10083 (if (not js2-compiler-xml-available)
10084 (progn
10085 (js2-must-match-prop-name "msg.no.name.after.dot")
10086 (setq name (js2-create-name-node t js2-GETPROP)
10087 result (make-js2-prop-get-node :left pn
10088 :pos (js2-current-token-beg)
10089 :right name
10090 :len (js2-current-token-len)))
10091 (js2-node-add-children result pn name)
10092 result)
10093 ;; otherwise look for XML operators
10094 (setf result (if (= tt js2-DOT)
10095 (make-js2-prop-get-node)
10096 (make-js2-infix-node :type js2-DOTDOT))
10097 (js2-node-pos result) (js2-node-pos pn)
10098 (js2-infix-node-op-pos result) dot-pos
10099 (js2-infix-node-left result) pn ; do this after setting position
10100 tt (js2-get-prop-name-token))
10101 (cond
10102 ;; handles: name, ns::name, ns::*, ns::[expr]
10103 ((= tt js2-NAME)
10104 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10105 ;; handles: *, *::name, *::*, *::[expr]
10106 ((= tt js2-MUL)
10107 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10108 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10109 ((= tt js2-XMLATTR)
10110 (setq result (js2-parse-attribute-access)))
10111 (t
10112 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10113 (if ref
10114 (setf (js2-node-len result) (- (js2-node-end ref)
10115 (js2-node-pos result))
10116 (js2-infix-node-right result) ref))
10117 (if (js2-infix-node-p result)
10118 (js2-node-add-children result
10119 (js2-infix-node-left result)
10120 (js2-infix-node-right result)))
10121 result)))
10122
10123 (defun js2-parse-attribute-access ()
10124 "Parse an E4X XML attribute expression.
10125 This includes expressions of the forms:
10126
10127 @attr @ns::attr @ns::*
10128 @* @*::attr @*::*
10129 @[expr] @*::[expr] @ns::[expr]
10130
10131 Called if we peeked an '@' token."
10132 (let ((tt (js2-get-prop-name-token))
10133 (at-pos (js2-current-token-beg)))
10134 (cond
10135 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10136 ((= tt js2-NAME)
10137 (js2-parse-property-name at-pos nil 0))
10138 ;; handles: @*, @*::name, @*::*, @*::[expr]
10139 ((= tt js2-MUL)
10140 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10141 ;; handles @[expr]
10142 ((= tt js2-LB)
10143 (js2-parse-xml-elem-ref at-pos))
10144 (t
10145 (js2-report-error "msg.no.name.after.xmlAttr")
10146 ;; Avoid cascaded errors that happen if we make an error node here.
10147 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10148
10149 (defun js2-parse-property-name (at-pos s member-type-flags)
10150 "Check if :: follows name in which case it becomes qualified name.
10151
10152 AT-POS is a natural number if we just read an '@' token, else nil.
10153 S is the name or string that was matched: an identifier, 'throw' or '*'.
10154 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10155
10156 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10157 operator, or the name is followed by ::. For a plain name, returns a
10158 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10159 (let ((pos (or at-pos (js2-current-token-beg)))
10160 colon-pos
10161 (name (js2-create-name-node t (js2-current-token-type) s))
10162 ns tt pn)
10163 (catch 'return
10164 (when (js2-match-token js2-COLONCOLON)
10165 (setq ns name
10166 colon-pos (js2-current-token-beg)
10167 tt (js2-get-prop-name-token))
10168 (cond
10169 ;; handles name::name
10170 ((= tt js2-NAME)
10171 (setq name (js2-create-name-node)))
10172 ;; handles name::*
10173 ((= tt js2-MUL)
10174 (setq name (js2-create-name-node nil nil "*")))
10175 ;; handles name::[expr]
10176 ((= tt js2-LB)
10177 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10178 (t
10179 (js2-report-error "msg.no.name.after.coloncolon"))))
10180 (if (and (null ns) (zerop member-type-flags))
10181 name
10182 (prog1
10183 (setq pn
10184 (make-js2-xml-prop-ref-node :pos pos
10185 :len (- (js2-node-end name) pos)
10186 :at-pos at-pos
10187 :colon-pos colon-pos
10188 :propname name))
10189 (js2-node-add-children pn name))))))
10190
10191 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10192 "Parse the [expr] portion of an xml element reference.
10193 For instance, @[expr], @*::[expr], or ns::[expr]."
10194 (let* ((lb (js2-current-token-beg))
10195 (pos (or at-pos lb))
10196 rb
10197 (expr (js2-parse-expr))
10198 (end (js2-node-end expr))
10199 pn)
10200 (if (js2-must-match js2-RB "msg.no.bracket.index")
10201 (setq rb (js2-current-token-beg)
10202 end (js2-current-token-end)))
10203 (prog1
10204 (setq pn
10205 (make-js2-xml-elem-ref-node :pos pos
10206 :len (- end pos)
10207 :namespace namespace
10208 :colon-pos colon-pos
10209 :at-pos at-pos
10210 :expr expr
10211 :lb (js2-relpos lb pos)
10212 :rb (js2-relpos rb pos)))
10213 (js2-node-add-children pn namespace expr))))
10214
10215 (defun js2-parse-destruct-primary-expr ()
10216 (let ((js2-is-in-destructuring t))
10217 (js2-parse-primary-expr)))
10218
10219 (defun js2-parse-primary-expr ()
10220 "Parse a literal (leaf) expression of some sort.
10221 Includes complex literals such as functions, object-literals,
10222 array-literals, array comprehensions and regular expressions."
10223 (let (tt node)
10224 (setq tt (js2-current-token-type))
10225 (cond
10226 ((= tt js2-CLASS)
10227 (js2-parse-class-expr))
10228 ((= tt js2-FUNCTION)
10229 (js2-parse-function-expr))
10230 ((= tt js2-LB)
10231 (js2-parse-array-comp-or-literal))
10232 ((= tt js2-LC)
10233 (js2-parse-object-literal))
10234 ((= tt js2-LET)
10235 (js2-parse-let (js2-current-token-beg)))
10236 ((= tt js2-LP)
10237 (js2-parse-paren-expr-or-generator-comp))
10238 ((= tt js2-XMLATTR)
10239 (js2-must-have-xml)
10240 (js2-parse-attribute-access))
10241 ((= tt js2-NAME)
10242 (js2-parse-name tt))
10243 ((= tt js2-NUMBER)
10244 (setq node (make-js2-number-node))
10245 (when (and js2-in-use-strict-directive
10246 (= (js2-number-node-num-base node) 8))
10247 (js2-report-error "msg.no.octal.strict"))
10248 node)
10249 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10250 (make-js2-string-node :type tt))
10251 ((= tt js2-TEMPLATE_HEAD)
10252 (js2-parse-template-literal))
10253 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10254 ;; Got / or /= which in this context means a regexp literal
10255 (let ((px-pos (js2-current-token-beg))
10256 (flags (js2-read-regexp tt))
10257 (end (js2-current-token-end)))
10258 (prog1
10259 (make-js2-regexp-node :pos px-pos
10260 :len (- end px-pos)
10261 :value (js2-current-token-string)
10262 :flags flags)
10263 (js2-set-face px-pos end 'font-lock-string-face 'record)
10264 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10265 ((or (= tt js2-NULL)
10266 (= tt js2-THIS)
10267 (= tt js2-SUPER)
10268 (= tt js2-FALSE)
10269 (= tt js2-TRUE))
10270 (make-js2-keyword-node :type tt))
10271 ((= tt js2-TRIPLEDOT)
10272 ;; Likewise, only valid in an arrow function with a rest param.
10273 (if (and (js2-match-token js2-NAME)
10274 (js2-match-token js2-RP)
10275 (eq (js2-peek-token) js2-ARROW))
10276 (progn
10277 (js2-unget-token) ; Put back the right paren.
10278 ;; See the previous case.
10279 (make-js2-keyword-node :type js2-NULL))
10280 (js2-report-error "msg.syntax")
10281 (make-js2-error-node)))
10282 ((= tt js2-RESERVED)
10283 (js2-report-error "msg.reserved.id")
10284 (make-js2-name-node))
10285 ((= tt js2-ERROR)
10286 ;; the scanner or one of its subroutines reported the error.
10287 (make-js2-error-node))
10288 ((= tt js2-EOF)
10289 (let* ((px-pos (point-at-bol))
10290 (len (- js2-ts-cursor px-pos)))
10291 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10292 (make-js2-error-node :pos (1- js2-ts-cursor)))
10293 (t
10294 (js2-report-error "msg.syntax")
10295 (make-js2-error-node)))))
10296
10297 (defun js2-parse-template-literal ()
10298 (let ((beg (js2-current-token-beg))
10299 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10300 (tt js2-TEMPLATE_HEAD))
10301 (while (eq tt js2-TEMPLATE_HEAD)
10302 (push (js2-parse-expr) kids)
10303 (js2-must-match js2-RC "msg.syntax")
10304 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10305 (push (make-js2-string-node :type tt) kids))
10306 (setq kids (nreverse kids))
10307 (let ((tpl (make-js2-template-node :beg beg
10308 :len (- (js2-current-token-end) beg)
10309 :kids kids)))
10310 (apply #'js2-node-add-children tpl kids)
10311 tpl)))
10312
10313 (defun js2-parse-name (_tt)
10314 (let ((name (js2-current-token-string))
10315 node)
10316 (setq node (if js2-compiler-xml-available
10317 (js2-parse-property-name nil name 0)
10318 (js2-create-name-node 'check-activation nil name)))
10319 (if js2-highlight-external-variables
10320 (js2-record-name-node node))
10321 node))
10322
10323 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10324 (js2-add-strict-warning
10325 msg nil
10326 ;; back up from comma to beginning of line or array/objlit
10327 (max (if elems
10328 (js2-node-pos (car elems))
10329 pos)
10330 (save-excursion
10331 (goto-char comma-pos)
10332 (back-to-indentation)
10333 (point)))
10334 comma-pos))
10335
10336 (defun js2-parse-array-comp-or-literal ()
10337 (let ((pos (js2-current-token-beg)))
10338 (if (and (>= js2-language-version 200)
10339 (js2-match-token js2-FOR))
10340 (js2-parse-array-comp pos)
10341 (js2-parse-array-literal pos))))
10342
10343 (defun js2-parse-array-literal (pos)
10344 (let ((after-lb-or-comma t)
10345 after-comma tt elems pn
10346 (continue t))
10347 (unless js2-is-in-destructuring
10348 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10349 (while continue
10350 (setq tt (js2-get-token))
10351 (cond
10352 ;; comma
10353 ((= tt js2-COMMA)
10354 (setq after-comma (js2-current-token-end))
10355 (if (not after-lb-or-comma)
10356 (setq after-lb-or-comma t)
10357 (push nil elems)))
10358 ;; end of array
10359 ((or (= tt js2-RB)
10360 (= tt js2-EOF)) ; prevent infinite loop
10361 (if (= tt js2-EOF)
10362 (js2-report-error "msg.no.bracket.arg" nil pos))
10363 (when (and after-comma (< js2-language-version 170))
10364 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10365 pos (remove nil elems) after-comma))
10366 (setq continue nil
10367 pn (make-js2-array-node :pos pos
10368 :len (- js2-ts-cursor pos)
10369 :elems (nreverse elems)))
10370 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10371 ;; destructuring binding
10372 (js2-is-in-destructuring
10373 (push (cond
10374 ((and (= tt js2-NAME)
10375 (= js2-ASSIGN (js2-peek-token)))
10376 ;; a=defaultValue
10377 (js2-parse-initialized-binding (js2-parse-name js2-NAME)))
10378 ((or (= tt js2-LC)
10379 (= tt js2-LB)
10380 (= tt js2-NAME))
10381 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10382 (js2-parse-destruct-primary-expr))
10383 ;; invalid pattern
10384 (t
10385 (js2-report-error "msg.bad.var")
10386 (make-js2-error-node)))
10387 elems)
10388 (setq after-lb-or-comma nil
10389 after-comma nil))
10390 ;; array comp
10391 ((and (>= js2-language-version 170)
10392 (= tt js2-FOR) ; check for array comprehension
10393 (not after-lb-or-comma) ; "for" can't follow a comma
10394 elems ; must have at least 1 element
10395 (not (cdr elems))) ; but no 2nd element
10396 (js2-unget-token)
10397 (setf continue nil
10398 pn (js2-parse-legacy-array-comp (car elems) pos)))
10399 ;; another element
10400 (t
10401 (unless after-lb-or-comma
10402 (js2-report-error "msg.no.bracket.arg"))
10403 (if (and (= tt js2-TRIPLEDOT)
10404 (>= js2-language-version 200))
10405 ;; spread operator
10406 (push (js2-make-unary tt 'js2-parse-assign-expr)
10407 elems)
10408 (js2-unget-token)
10409 (push (js2-parse-assign-expr) elems))
10410 (setq after-lb-or-comma nil
10411 after-comma nil))))
10412 (unless js2-is-in-destructuring
10413 (js2-pop-scope))
10414 pn))
10415
10416 (defun js2-parse-legacy-array-comp (expr pos)
10417 "Parse a legacy array comprehension (JavaScript 1.7).
10418 EXPR is the first expression after the opening left-bracket.
10419 POS is the beginning of the LB token preceding EXPR.
10420 We should have just parsed the 'for' keyword before calling this function."
10421 (let ((current-scope js2-current-scope)
10422 loops first filter result)
10423 (unwind-protect
10424 (progn
10425 (while (js2-match-token js2-FOR)
10426 (let ((loop (make-js2-comp-loop-node)))
10427 (js2-push-scope loop)
10428 (push loop loops)
10429 (js2-parse-comp-loop loop)))
10430 ;; First loop takes expr scope's parent.
10431 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10432 (js2-scope-parent-scope current-scope))
10433 ;; Set expr scope's parent to the last loop.
10434 (setf (js2-scope-parent-scope current-scope) (car loops))
10435 (if (/= (js2-get-token) js2-IF)
10436 (js2-unget-token)
10437 (setq filter (js2-parse-condition))))
10438 (dotimes (_ (1- (length loops)))
10439 (js2-pop-scope)))
10440 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10441 (setq result (make-js2-comp-node :pos pos
10442 :len (- js2-ts-cursor pos)
10443 :result expr
10444 :loops (nreverse loops)
10445 :filters (and filter (list (car filter)))
10446 :form 'LEGACY_ARRAY))
10447 ;; Set comp loop's parent to the last loop.
10448 ;; TODO: Get rid of the bogus expr scope.
10449 (setf (js2-scope-parent-scope result) first)
10450 (apply #'js2-node-add-children result expr (car filter)
10451 (js2-comp-node-loops result))
10452 result))
10453
10454 (defun js2-parse-array-comp (pos)
10455 "Parse an ES6 array comprehension.
10456 POS is the beginning of the LB token.
10457 We should have just parsed the 'for' keyword before calling this function."
10458 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10459 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10460 pn))
10461
10462 (defun js2-parse-generator-comp (pos)
10463 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10464 (js2-current-script-or-fn
10465 (make-js2-function-node :generator-type 'COMPREHENSION))
10466 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10467 (js2-must-match js2-RP "msg.no.paren" pos)
10468 pn))
10469
10470 (defun js2-parse-comprehension (pos form)
10471 (let (loops filters expr result last)
10472 (unwind-protect
10473 (progn
10474 (js2-unget-token)
10475 (while (js2-match-token js2-FOR)
10476 (let ((loop (make-js2-comp-loop-node)))
10477 (js2-push-scope loop)
10478 (push loop loops)
10479 (js2-parse-comp-loop loop)))
10480 (while (js2-match-token js2-IF)
10481 (push (car (js2-parse-condition)) filters))
10482 (setq expr (js2-parse-assign-expr))
10483 (setq last (car loops)))
10484 (dolist (_ loops)
10485 (js2-pop-scope)))
10486 (setq result (make-js2-comp-node :pos pos
10487 :len (- js2-ts-cursor pos)
10488 :result expr
10489 :loops (nreverse loops)
10490 :filters (nreverse filters)
10491 :form form))
10492 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10493 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10494 (setf (js2-scope-parent-scope result) last)
10495 result))
10496
10497 (defun js2-parse-comp-loop (pn &optional only-of-p)
10498 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10499 The current token should be the initial FOR.
10500 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10501 (let ((pos (js2-comp-loop-node-pos pn))
10502 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10503 (when (and (not only-of-p) (js2-match-token js2-NAME))
10504 (if (string= (js2-current-token-string) "each")
10505 (progn
10506 (setq foreach-p t
10507 each-pos (- (js2-current-token-beg) pos)) ; relative
10508 (js2-record-face 'font-lock-keyword-face))
10509 (js2-report-error "msg.no.paren.for")))
10510 (if (js2-must-match js2-LP "msg.no.paren.for")
10511 (setq lp (- (js2-current-token-beg) pos)))
10512 (setq tt (js2-peek-token))
10513 (cond
10514 ((or (= tt js2-LB)
10515 (= tt js2-LC))
10516 (js2-get-token)
10517 (setq iter (js2-parse-destruct-primary-expr))
10518 (js2-define-destruct-symbols iter js2-LET
10519 'font-lock-variable-name-face t))
10520 ((js2-match-token js2-NAME)
10521 (setq iter (js2-create-name-node)))
10522 (t
10523 (js2-report-error "msg.bad.var")))
10524 ;; Define as a let since we want the scope of the variable to
10525 ;; be restricted to the array comprehension
10526 (if (js2-name-node-p iter)
10527 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10528 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10529 (and (>= js2-language-version 200)
10530 (js2-match-contextual-kwd "of")
10531 (setq forof-p t)))
10532 (setq in-pos (- (js2-current-token-beg) pos))
10533 (js2-report-error "msg.in.after.for.name"))
10534 (setq obj (js2-parse-expr))
10535 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10536 (setq rp (- (js2-current-token-beg) pos)))
10537 (setf (js2-node-pos pn) pos
10538 (js2-node-len pn) (- js2-ts-cursor pos)
10539 (js2-comp-loop-node-iterator pn) iter
10540 (js2-comp-loop-node-object pn) obj
10541 (js2-comp-loop-node-in-pos pn) in-pos
10542 (js2-comp-loop-node-each-pos pn) each-pos
10543 (js2-comp-loop-node-foreach-p pn) foreach-p
10544 (js2-comp-loop-node-forof-p pn) forof-p
10545 (js2-comp-loop-node-lp pn) lp
10546 (js2-comp-loop-node-rp pn) rp)
10547 (js2-node-add-children pn iter obj)
10548 pn))
10549
10550 (defun js2-parse-class-stmt ()
10551 (let ((pos (js2-current-token-beg))
10552 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10553 (name (js2-create-name-node t)))
10554 (js2-set-face (js2-node-pos name) (js2-node-end name)
10555 'font-lock-function-name-face 'record)
10556 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10557 (js2-define-symbol js2-FUNCTION
10558 (js2-name-node-name name)
10559 node)
10560 node)))
10561
10562 (defun js2-parse-class-expr ()
10563 (let ((pos (js2-current-token-beg))
10564 name)
10565 (when (js2-match-token js2-NAME)
10566 (setq name (js2-create-name-node t)))
10567 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10568
10569 (defun js2-parse-class (pos form name)
10570 ;; class X [extends ...] {
10571 (let (pn elems extends)
10572 (if (js2-match-token js2-EXTENDS)
10573 (if (= (js2-peek-token) js2-LC)
10574 (js2-report-error "msg.missing.extends")
10575 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10576 (setq extends (js2-parse-assign-expr))
10577 (if (not extends)
10578 (js2-report-error "msg.bad.extends"))))
10579 (js2-must-match js2-LC "msg.no.brace.class")
10580 (setq elems (js2-parse-object-literal-elems t)
10581 pn (make-js2-class-node :pos pos
10582 :len (- js2-ts-cursor pos)
10583 :form form
10584 :name name
10585 :extends extends
10586 :elems elems))
10587 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10588 pn))
10589
10590 (defun js2-parse-object-literal ()
10591 (let* ((pos (js2-current-token-beg))
10592 (elems (js2-parse-object-literal-elems))
10593 (result (make-js2-object-node :pos pos
10594 :len (- js2-ts-cursor pos)
10595 :elems elems)))
10596 (apply #'js2-node-add-children result (js2-object-node-elems result))
10597 result))
10598
10599 (defun js2-property-key-string (property-node)
10600 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10601 `js2-method-node') as a string, or nil if it can't be
10602 represented as a string (e.g., the key is computed by an
10603 expression)."
10604 (let ((key (js2-infix-node-left property-node)))
10605 (when (js2-computed-prop-name-node-p key)
10606 (setq key (js2-computed-prop-name-node-expr key)))
10607 (cond
10608 ((js2-name-node-p key)
10609 (js2-name-node-name key))
10610 ((js2-string-node-p key)
10611 (js2-string-node-value key))
10612 ((js2-number-node-p key)
10613 (js2-number-node-value key)))))
10614
10615 (defun js2-parse-object-literal-elems (&optional class-p)
10616 (let ((pos (js2-current-token-beg))
10617 (static nil)
10618 (continue t)
10619 tt elems elem
10620 elem-key-string previous-elem-key-string
10621 after-comma previous-token)
10622 (while continue
10623 (setq tt (js2-get-prop-name-token)
10624 static nil
10625 elem nil
10626 previous-token nil)
10627 ;; Handle 'static' keyword only if we're in a class
10628 (when (and class-p (= js2-NAME tt)
10629 (string= "static" (js2-current-token-string)))
10630 (js2-record-face 'font-lock-keyword-face)
10631 (setq static t
10632 tt (js2-get-prop-name-token)))
10633 ;; Handle generator * before the property name for in-line functions
10634 (when (and (>= js2-language-version 200)
10635 (= js2-MUL tt))
10636 (setq previous-token (js2-current-token)
10637 tt (js2-get-prop-name-token)))
10638 ;; Handle 'get' or 'set' keywords
10639 (let ((prop (js2-current-token-string)))
10640 (when (and (>= js2-language-version 200)
10641 (= js2-NAME tt)
10642 (or (string= prop "get")
10643 (string= prop "set"))
10644 (member (js2-peek-token)
10645 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10646 (setq previous-token (js2-current-token)
10647 tt (js2-get-prop-name-token))))
10648 (cond
10649 ;; Found a property (of any sort)
10650 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10651 (setq after-comma nil
10652 elem (js2-parse-named-prop tt pos previous-token))
10653 (if (and (null elem)
10654 (not js2-recover-from-parse-errors))
10655 (setq continue nil)))
10656 ;; Break out of loop, and handle trailing commas.
10657 ((or (= tt js2-RC)
10658 (= tt js2-EOF))
10659 (js2-unget-token)
10660 (setq continue nil)
10661 (if after-comma
10662 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10663 pos elems after-comma)))
10664 ;; Skip semicolons in a class body
10665 ((and class-p
10666 (= tt js2-SEMI))
10667 nil)
10668 (t
10669 (js2-report-error "msg.bad.prop")
10670 (unless js2-recover-from-parse-errors
10671 (setq continue nil)))) ; end switch
10672 ;; Handle static for classes' codegen.
10673 (if static
10674 (if elem (js2-node-set-prop elem 'STATIC t)
10675 (js2-report-error "msg.unexpected.static")))
10676 ;; Handle commas, depending on class-p.
10677 (let ((tok (js2-get-prop-name-token)))
10678 (if (eq tok js2-COMMA)
10679 (if class-p
10680 (js2-report-error "msg.class.unexpected.comma")
10681 (setq after-comma (js2-current-token-end)))
10682 (js2-unget-token)
10683 (unless class-p (setq continue nil))))
10684 (when elem
10685 (when (and js2-in-use-strict-directive
10686 (setq elem-key-string (js2-property-key-string elem))
10687 (cl-some
10688 (lambda (previous-elem)
10689 (and (setq previous-elem-key-string
10690 (js2-property-key-string previous-elem))
10691 ;; Check if the property is a duplicate.
10692 (string= previous-elem-key-string elem-key-string)
10693 ;; But make an exception for getter / setter pairs.
10694 (not (and (js2-method-node-p elem)
10695 (js2-method-node-p previous-elem)
10696 (/= (js2-method-node-type elem)
10697 (js2-method-node-type previous-elem))))))
10698 elems))
10699 (js2-report-error "msg.dup.obj.lit.prop.strict"
10700 elem-key-string
10701 (js2-node-abs-pos (js2-infix-node-left elem))
10702 (js2-node-len (js2-infix-node-left elem))))
10703 ;; Append any parsed element.
10704 (push elem elems))) ; end loop
10705 (js2-must-match js2-RC "msg.no.brace.prop")
10706 (nreverse elems)))
10707
10708 (defun js2-parse-named-prop (tt pos previous-token)
10709 "Parse a name, string, or getter/setter object property.
10710 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10711 (let ((key (js2-parse-prop-name tt))
10712 (prop (and previous-token (js2-token-string previous-token)))
10713 (property-type (when previous-token
10714 (if (= (js2-token-type previous-token) js2-MUL)
10715 "*"
10716 (js2-token-string previous-token)))))
10717 (when (or (string= prop "get")
10718 (string= prop "set"))
10719 (js2-set-face (js2-token-beg previous-token)
10720 (js2-token-end previous-token)
10721 'font-lock-keyword-face 'record)) ; get/set
10722 (cond
10723 ;; method definition: {f() {...}}
10724 ((and (= (js2-peek-token) js2-LP)
10725 (>= js2-language-version 200))
10726 (when (js2-name-node-p key) ; highlight function name properties
10727 (js2-record-face 'font-lock-function-name-face))
10728 (js2-parse-method-prop pos key property-type))
10729 ;; binding element with initializer
10730 ((and (= (js2-peek-token) js2-ASSIGN)
10731 (>= js2-language-version 200))
10732 (if (not js2-is-in-destructuring)
10733 (js2-report-error "msg.init.no.destruct"))
10734 (js2-parse-initialized-binding key))
10735 ;; regular prop
10736 (t
10737 (let ((beg (js2-current-token-beg))
10738 (end (js2-current-token-end))
10739 (expr (js2-parse-plain-property key)))
10740 (when (and (= tt js2-NAME)
10741 (not js2-is-in-destructuring)
10742 js2-highlight-external-variables
10743 (js2-node-get-prop expr 'SHORTHAND))
10744 (js2-record-name-node key))
10745 (js2-set-face beg end
10746 (if (js2-function-node-p
10747 (js2-object-prop-node-right expr))
10748 'font-lock-function-name-face
10749 'js2-object-property)
10750 'record)
10751 expr)))))
10752
10753 (defun js2-parse-initialized-binding (name)
10754 "Parse a `SingleNameBinding' with initializer.
10755
10756 `name' is the `BindingIdentifier'."
10757 (when (js2-match-token js2-ASSIGN)
10758 (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
10759
10760 (defun js2-parse-prop-name (tt)
10761 (cond
10762 ;; Literal string keys: {'foo': 'bar'}
10763 ((= tt js2-STRING)
10764 (make-js2-string-node))
10765 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10766 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10767 ((and (= tt js2-LB)
10768 (>= js2-language-version 200))
10769 (make-js2-computed-prop-name-node
10770 :expr (prog1 (js2-parse-assign-expr)
10771 (js2-must-match js2-RB "msg.missing.computed.rb"))))
10772 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10773 ((= tt js2-NUMBER)
10774 (make-js2-number-node))
10775 ;; Unquoted names: {foo: 12}
10776 ((= tt js2-NAME)
10777 (js2-create-name-node))
10778 ;; Anything else is an error
10779 (t (js2-report-error "msg.bad.prop"))))
10780
10781 (defun js2-parse-plain-property (prop)
10782 "Parse a non-getter/setter property in an object literal.
10783 PROP is the node representing the property: a number, name,
10784 string or expression."
10785 (let* ((tt (js2-get-token))
10786 (pos (js2-node-pos prop))
10787 colon expr result)
10788 (cond
10789 ;; Abbreviated property, as in {foo, bar}
10790 ((and (>= js2-language-version 200)
10791 (or (= tt js2-COMMA)
10792 (= tt js2-RC))
10793 (not (js2-number-node-p prop)))
10794 (js2-unget-token)
10795 (setq result (make-js2-object-prop-node
10796 :pos pos
10797 :left prop
10798 :right prop
10799 :op-pos (js2-current-token-len)))
10800 (js2-node-add-children result prop)
10801 (js2-node-set-prop result 'SHORTHAND t)
10802 result)
10803 ;; Normal property
10804 (t
10805 (if (= tt js2-COLON)
10806 (setq colon (- (js2-current-token-beg) pos)
10807 expr (js2-parse-assign-expr))
10808 (js2-report-error "msg.no.colon.prop")
10809 (setq expr (make-js2-error-node)))
10810 (setq result (make-js2-object-prop-node
10811 :pos pos
10812 ;; don't include last consumed token in length
10813 :len (- (+ (js2-node-pos expr)
10814 (js2-node-len expr))
10815 pos)
10816 :left prop
10817 :right expr
10818 :op-pos colon))
10819 (js2-node-add-children result prop expr)
10820 result))))
10821
10822 (defun js2-parse-method-prop (pos prop type-string)
10823 "Parse method property in an object literal or a class body.
10824 JavaScript syntax is:
10825
10826 { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...} }
10827
10828 and expression closure style is also supported
10829
10830 { get foo() x, set foo(x) _x = x }
10831
10832 POS is the start position of the `get' or `set' keyword.
10833 PROP is the `js2-name-node' representing the property name.
10834 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10835 (let ((type (cond
10836 ((string= "get" type-string) js2-GET)
10837 ((string= "set" type-string) js2-SET)
10838 (t js2-FUNCTION)))
10839 result end
10840 (fn (js2-parse-function-expr)))
10841 ;; it has to be an anonymous function, as we already parsed the name
10842 (if (/= (js2-node-type fn) js2-FUNCTION)
10843 (js2-report-error "msg.bad.prop")
10844 (if (cl-plusp (length (js2-function-name fn)))
10845 (js2-report-error "msg.bad.prop")))
10846 (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
10847 (when (string= type-string "*")
10848 (setf (js2-function-node-generator-type fn) 'STAR))
10849 (setq end (js2-node-end fn)
10850 result (make-js2-method-node :type type
10851 :pos pos
10852 :len (- end pos)
10853 :left prop
10854 :right fn))
10855 (js2-node-add-children result prop fn)
10856 result))
10857
10858 (defun js2-create-name-node (&optional check-activation-p token string)
10859 "Create a name node using the current token and, optionally, STRING.
10860 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10861 (let* ((beg (js2-current-token-beg))
10862 (tt (js2-current-token-type))
10863 (s (or string
10864 (if (= js2-NAME tt)
10865 (js2-current-token-string)
10866 (js2-tt-name tt))))
10867 name)
10868 (setq name (make-js2-name-node :pos beg
10869 :name s
10870 :len (length s)))
10871 (if check-activation-p
10872 (js2-check-activation-name s (or token js2-NAME)))
10873 name))
10874
10875 ;;; Indentation support (bouncing)
10876
10877 ;; In recent-enough Emacs, we reuse the indentation code from
10878 ;; `js-mode'. To continue support for the older versions, some code
10879 ;; that was here previously was moved to `js2-old-indent.el'.
10880
10881 ;; Whichever indenter is used, it's often "wrong", however, and needs
10882 ;; to be overridden. The right long-term solution is probably to
10883 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
10884 ;; of coding. Even when a parse tree from `js2-parse' is present,
10885 ;; which is not true at the moment the user is typing, computing
10886 ;; indentation is still thousands of lines of code to handle every
10887 ;; possible syntactic edge case.
10888
10889 ;; In the meantime, the compromise solution is that we offer a "bounce
10890 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10891 ;; current line indent among various likely guess points. This approach
10892 ;; is far from perfect, but should at least make it slightly easier to
10893 ;; move the line towards its desired indentation when manually
10894 ;; overriding Karl's heuristic nesting guesser.
10895
10896 (defun js2-backward-sws ()
10897 "Move backward through whitespace and comments."
10898 (interactive)
10899 (while (forward-comment -1)))
10900
10901 (defun js2-forward-sws ()
10902 "Move forward through whitespace and comments."
10903 (interactive)
10904 (while (forward-comment 1)))
10905
10906 (defun js2-arglist-close ()
10907 "Return non-nil if we're on a line beginning with a close-paren/brace."
10908 (save-excursion
10909 (goto-char (point-at-bol))
10910 (js2-forward-sws)
10911 (looking-at "[])}]")))
10912
10913 (defun js2-indent-looks-like-label-p ()
10914 (goto-char (point-at-bol))
10915 (js2-forward-sws)
10916 (looking-at (concat js2-mode-identifier-re ":")))
10917
10918 (defun js2-indent-in-objlit-p (parse-status)
10919 "Return non-nil if this looks like an object-literal entry."
10920 (let ((start (nth 1 parse-status)))
10921 (and
10922 start
10923 (save-excursion
10924 (and (zerop (forward-line -1))
10925 (not (< (point) start)) ; crossed a {} boundary
10926 (js2-indent-looks-like-label-p)))
10927 (save-excursion
10928 (js2-indent-looks-like-label-p)))))
10929
10930 ;; If prev line looks like foobar({ then we're passing an object
10931 ;; literal to a function call, and people pretty much always want to
10932 ;; de-dent back to the previous line, so move the 'basic-offset'
10933 ;; position to the front.
10934 (defun js2-indent-objlit-arg-p (parse-status)
10935 (save-excursion
10936 (back-to-indentation)
10937 (js2-backward-sws)
10938 (and (eq (1- (point)) (nth 1 parse-status))
10939 (eq (char-before) ?{)
10940 (progn
10941 (forward-char -1)
10942 (skip-chars-backward " \t")
10943 (eq (char-before) ?\()))))
10944
10945 (defun js2-indent-case-block-p ()
10946 (save-excursion
10947 (back-to-indentation)
10948 (js2-backward-sws)
10949 (goto-char (point-at-bol))
10950 (skip-chars-forward " \t")
10951 (looking-at "case\\s-.+:")))
10952
10953 (defun js2-bounce-indent (normal-col parse-status &optional backward)
10954 "Cycle among alternate computed indentation positions.
10955 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10956 of the buffer to the current point. NORMAL-COL is the indentation
10957 column computed by the heuristic guesser based on current paren,
10958 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10959 in reverse."
10960 (let ((cur-indent (current-indentation))
10961 (old-buffer-undo-list buffer-undo-list)
10962 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10963 (current-line (save-excursion
10964 (forward-line 0) ; move to bol
10965 (1+ (count-lines (point-min) (point)))))
10966 positions pos main-pos anchor arglist-cont same-indent
10967 basic-offset computed-pos)
10968 ;; temporarily don't record undo info, if user requested this
10969 (when js2-mode-indent-inhibit-undo
10970 (setq buffer-undo-list t))
10971 (unwind-protect
10972 (progn
10973 ;; First likely point: indent from beginning of previous code line
10974 (push (setq basic-offset
10975 (+ (save-excursion
10976 (back-to-indentation)
10977 (js2-backward-sws)
10978 (back-to-indentation)
10979 (current-column))
10980 js2-basic-offset))
10981 positions)
10982
10983 ;; (First + epsilon) likely point: indent 2x from beginning of
10984 ;; previous code line. Google does it this way.
10985 (push (setq basic-offset
10986 (+ (save-excursion
10987 (back-to-indentation)
10988 (js2-backward-sws)
10989 (back-to-indentation)
10990 (current-column))
10991 (* 2 js2-basic-offset)))
10992 positions)
10993
10994 ;; Second likely point: indent from assign-expr RHS. This
10995 ;; is just a crude guess based on finding " = " on the previous
10996 ;; line containing actual code.
10997 (setq pos (save-excursion
10998 (forward-line -1)
10999 (goto-char (point-at-bol))
11000 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11001 (point-at-eol) t)
11002 (goto-char (match-end 1))
11003 (skip-chars-forward " \t\r\n")
11004 (current-column))))
11005 (when pos
11006 (cl-incf pos js2-basic-offset)
11007 (push pos positions))
11008
11009 ;; Third likely point: same indent as previous line of code.
11010 ;; Make it the first likely point if we're not on an
11011 ;; arglist-close line and previous line ends in a comma, or
11012 ;; both this line and prev line look like object-literal
11013 ;; elements.
11014 (setq pos (save-excursion
11015 (goto-char (point-at-bol))
11016 (js2-backward-sws)
11017 (back-to-indentation)
11018 (prog1
11019 (current-column)
11020 ;; while we're here, look for trailing comma
11021 (if (save-excursion
11022 (goto-char (point-at-eol))
11023 (js2-backward-sws)
11024 (eq (char-before) ?,))
11025 (setq arglist-cont (1- (point)))))))
11026 (when pos
11027 (if (and (or arglist-cont
11028 (js2-indent-in-objlit-p parse-status))
11029 (not (js2-arglist-close)))
11030 (setq same-indent pos))
11031 (push pos positions))
11032
11033 ;; Fourth likely point: first preceding code with less indentation.
11034 ;; than the immediately preceding code line.
11035 (setq pos (save-excursion
11036 (back-to-indentation)
11037 (js2-backward-sws)
11038 (back-to-indentation)
11039 (setq anchor (current-column))
11040 (while (and (zerop (forward-line -1))
11041 (>= (progn
11042 (back-to-indentation)
11043 (current-column))
11044 anchor)))
11045 (setq pos (current-column))))
11046 (push pos positions)
11047
11048 ;; nesting-heuristic position, main by default
11049 (push (setq main-pos normal-col) positions)
11050
11051 ;; delete duplicates and sort positions list
11052 (setq positions (sort (delete-dups positions) '<))
11053
11054 ;; comma-list continuation lines: prev line indent takes precedence
11055 (if same-indent
11056 (setq main-pos same-indent))
11057
11058 ;; common special cases where we want to indent in from previous line
11059 (if (or (js2-indent-case-block-p)
11060 (js2-indent-objlit-arg-p parse-status))
11061 (setq main-pos basic-offset))
11062
11063 ;; if bouncing backward, reverse positions list
11064 (if backward
11065 (setq positions (reverse positions)))
11066
11067 ;; record whether we're already sitting on one of the alternatives
11068 (setq pos (member cur-indent positions))
11069
11070 (cond
11071 ;; case 0: we're one one of the alternatives and this is the
11072 ;; first time they've pressed TAB on this line (best-guess).
11073 ((and js2-mode-indent-ignore-first-tab
11074 pos
11075 ;; first time pressing TAB on this line?
11076 (not (eq js2-mode-last-indented-line current-line)))
11077 ;; do nothing
11078 (setq computed-pos nil))
11079 ;; case 1: only one computed position => use it
11080 ((null (cdr positions))
11081 (setq computed-pos 0))
11082 ;; case 2: not on any of the computed spots => use main spot
11083 ((not pos)
11084 (setq computed-pos (js2-position main-pos positions)))
11085 ;; case 3: on last position: cycle to first position
11086 ((null (cdr pos))
11087 (setq computed-pos 0))
11088 ;; case 4: on intermediate position: cycle to next position
11089 (t
11090 (setq computed-pos (js2-position (cl-second pos) positions))))
11091
11092 ;; see if any hooks want to indent; otherwise we do it
11093 (cl-loop with result = nil
11094 for hook in js2-indent-hook
11095 while (null result)
11096 do
11097 (setq result (funcall hook positions computed-pos))
11098 finally do
11099 (unless (or result (null computed-pos))
11100 (indent-line-to (nth computed-pos positions)))))
11101
11102 ;; finally
11103 (if js2-mode-indent-inhibit-undo
11104 (setq buffer-undo-list old-buffer-undo-list))
11105 ;; see commentary for `js2-mode-last-indented-line'
11106 (setq js2-mode-last-indented-line current-line))))
11107
11108 (defun js2-1-line-comment-continuation-p ()
11109 "Return t if we're in a 1-line comment continuation.
11110 If so, we don't ever want to use bounce-indent."
11111 (save-excursion
11112 (and (progn
11113 (forward-line 0)
11114 (looking-at "\\s-*//"))
11115 (progn
11116 (forward-line -1)
11117 (forward-line 0)
11118 (when (looking-at "\\s-*$")
11119 (js2-backward-sws)
11120 (forward-line 0))
11121 (looking-at "\\s-*//")))))
11122
11123 (defun js2-indent-bounce (&optional backward)
11124 "Indent the current line, bouncing between several positions."
11125 (interactive)
11126 (let (parse-status offset indent-col
11127 ;; Don't whine about errors/warnings when we're indenting.
11128 ;; This has to be set before calling parse-partial-sexp below.
11129 (inhibit-point-motion-hooks t))
11130 (setq parse-status (save-excursion
11131 (syntax-ppss (point-at-bol)))
11132 offset (- (point) (save-excursion
11133 (back-to-indentation)
11134 (point))))
11135 ;; Don't touch multiline strings.
11136 (unless (nth 3 parse-status)
11137 (setq indent-col (js2-proper-indentation parse-status))
11138 (cond
11139 ;; It doesn't work well on first line of buffer.
11140 ((and (not (nth 4 parse-status))
11141 (not (js2-same-line (point-min)))
11142 (not (js2-1-line-comment-continuation-p)))
11143 (js2-bounce-indent indent-col parse-status backward))
11144 ;; just indent to the guesser's likely spot
11145 (t (indent-line-to indent-col)))
11146 (when (cl-plusp offset)
11147 (forward-char offset)))))
11148
11149 (defun js2-indent-bounce-backward ()
11150 "Indent the current line, bouncing between positions in reverse."
11151 (interactive)
11152 (js2-indent-bounce t))
11153
11154 (defun js2-indent-region (start end)
11155 "Indent the region, but don't use bounce indenting."
11156 (let ((js2-bounce-indent-p nil)
11157 (indent-region-function nil)
11158 (after-change-functions (remq 'js2-mode-edit
11159 after-change-functions)))
11160 (indent-region start end nil) ; nil for byte-compiler
11161 (js2-mode-edit start end (- end start))))
11162
11163 (defvar js2-minor-mode-map
11164 (let ((map (make-sparse-keymap)))
11165 (define-key map (kbd "C-c C-`") #'js2-next-error)
11166 (define-key map [mouse-1] #'js2-mode-show-node)
11167 map)
11168 "Keymap used when `js2-minor-mode' is active.")
11169
11170 ;;;###autoload
11171 (define-minor-mode js2-minor-mode
11172 "Minor mode for running js2 as a background linter.
11173 This allows you to use a different major mode for JavaScript editing,
11174 such as `js-mode', while retaining the asynchronous error/warning
11175 highlighting features of `js2-mode'."
11176 :group 'js2-mode
11177 :lighter " js-lint"
11178 (if (derived-mode-p 'js2-mode)
11179 (setq js2-minor-mode nil)
11180 (if js2-minor-mode
11181 (js2-minor-mode-enter)
11182 (js2-minor-mode-exit))))
11183
11184 (defun js2-minor-mode-enter ()
11185 "Initialization for `js2-minor-mode'."
11186 (set (make-local-variable 'max-lisp-eval-depth)
11187 (max max-lisp-eval-depth 3000))
11188 (setq next-error-function #'js2-next-error)
11189 (js2-set-default-externs)
11190 ;; Experiment: make reparse-delay longer for longer files.
11191 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11192 (setq js2-idle-timer-delay
11193 (* js2-idle-timer-delay
11194 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11195 (setq js2-mode-buffer-dirty-p t
11196 js2-mode-parsing nil)
11197 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11198 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11199 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11200 (when js2-include-jslint-globals
11201 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11202 (run-hooks 'js2-init-hook)
11203 (js2-reparse))
11204
11205 (defun js2-minor-mode-exit ()
11206 "Turn off `js2-minor-mode'."
11207 (setq next-error-function nil)
11208 (remove-hook 'after-change-functions #'js2-mode-edit t)
11209 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11210 (when js2-mode-node-overlay
11211 (delete-overlay js2-mode-node-overlay)
11212 (setq js2-mode-node-overlay nil))
11213 (js2-remove-overlays)
11214 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11215 (setq js2-mode-ast nil))
11216
11217 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11218 (make-variable-buffer-local 'js2-source-buffer)
11219
11220 (cl-defun js2-display-error-list ()
11221 "Display a navigable buffer listing parse errors/warnings."
11222 (interactive)
11223 (unless (js2-have-errors-p)
11224 (message "No errors")
11225 (cl-return-from js2-display-error-list))
11226 (cl-labels ((annotate-list
11227 (lst type)
11228 "Add diagnostic TYPE and line number to errs list"
11229 (mapcar (lambda (err)
11230 (list err type (line-number-at-pos (nth 1 err))))
11231 lst)))
11232 (let* ((srcbuf (current-buffer))
11233 (errbuf (get-buffer-create "*js-lint*"))
11234 (errors (annotate-list
11235 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11236 'js2-error)) ; must be a valid face name
11237 (warnings (annotate-list
11238 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11239 'js2-warning)) ; must be a valid face name
11240 (all-errs (sort (append errors warnings)
11241 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11242 (with-current-buffer errbuf
11243 (let ((inhibit-read-only t))
11244 (erase-buffer)
11245 (dolist (err all-errs)
11246 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11247 (insert-text-button
11248 (format "line %d: %s" line (js2-get-msg msg-key))
11249 'face type
11250 'follow-link "\C-m"
11251 'action 'js2-error-buffer-jump
11252 'js2-msg (js2-get-msg msg-key)
11253 'js2-pos beg)
11254 (insert "\n"))))
11255 (js2-error-buffer-mode)
11256 (setq js2-source-buffer srcbuf)
11257 (pop-to-buffer errbuf)
11258 (goto-char (point-min))
11259 (unless (eobp)
11260 (js2-error-buffer-view))))))
11261
11262 (defvar js2-error-buffer-mode-map
11263 (let ((map (make-sparse-keymap)))
11264 (define-key map "n" #'js2-error-buffer-next)
11265 (define-key map "p" #'js2-error-buffer-prev)
11266 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11267 (define-key map "o" #'js2-error-buffer-view)
11268 (define-key map "q" #'js2-error-buffer-quit)
11269 map)
11270 "Keymap used for js2 diagnostics buffers.")
11271
11272 (defun js2-error-buffer-mode ()
11273 "Major mode for js2 diagnostics buffers.
11274 Selecting an error will jump it to the corresponding source-buffer error.
11275 \\{js2-error-buffer-mode-map}"
11276 (interactive)
11277 (setq major-mode 'js2-error-buffer-mode
11278 mode-name "JS Lint Diagnostics")
11279 (use-local-map js2-error-buffer-mode-map)
11280 (setq truncate-lines t)
11281 (set-buffer-modified-p nil)
11282 (setq buffer-read-only t)
11283 (run-hooks 'js2-error-buffer-mode-hook))
11284
11285 (defun js2-error-buffer-next ()
11286 "Move to next error and view it."
11287 (interactive)
11288 (when (zerop (forward-line 1))
11289 (js2-error-buffer-view)))
11290
11291 (defun js2-error-buffer-prev ()
11292 "Move to previous error and view it."
11293 (interactive)
11294 (when (zerop (forward-line -1))
11295 (js2-error-buffer-view)))
11296
11297 (defun js2-error-buffer-quit ()
11298 "Kill the current buffer."
11299 (interactive)
11300 (kill-buffer))
11301
11302 (defun js2-error-buffer-jump (&rest ignored)
11303 "Jump cursor to current error in source buffer."
11304 (interactive)
11305 (when (js2-error-buffer-view)
11306 (pop-to-buffer js2-source-buffer)))
11307
11308 (defun js2-error-buffer-view ()
11309 "Scroll source buffer to show error at current line."
11310 (interactive)
11311 (cond
11312 ((not (eq major-mode 'js2-error-buffer-mode))
11313 (message "Not in a js2 errors buffer"))
11314 ((not (buffer-live-p js2-source-buffer))
11315 (message "Source buffer has been killed"))
11316 ((not (wholenump (get-text-property (point) 'js2-pos)))
11317 (message "There does not seem to be an error here"))
11318 (t
11319 (let ((pos (get-text-property (point) 'js2-pos))
11320 (msg (get-text-property (point) 'js2-msg)))
11321 (save-selected-window
11322 (pop-to-buffer js2-source-buffer)
11323 (goto-char pos)
11324 (message msg))))))
11325
11326 ;;;###autoload
11327 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11328 "Major mode for editing JavaScript code."
11329 (set (make-local-variable 'max-lisp-eval-depth)
11330 (max max-lisp-eval-depth 3000))
11331 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11332 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11333 (set (make-local-variable 'syntax-propertize-function) nil)
11334 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11335 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11336 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11337 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11338 ;; for characters inside regexp literals.
11339 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11340 ;; this is necessary to make `show-paren-function' work properly
11341 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11342 ;; needed for M-x rgrep, among other things
11343 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11344
11345 (setq font-lock-defaults '(nil t))
11346
11347 ;; Experiment: make reparse-delay longer for longer files.
11348 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11349 (setq js2-idle-timer-delay
11350 (* js2-idle-timer-delay
11351 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11352
11353 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11354 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11355 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11356 (setq next-error-function #'js2-next-error)
11357 (imenu-add-to-menubar (concat "IM-" mode-name))
11358 (add-to-invisibility-spec '(js2-outline . t))
11359 (set (make-local-variable 'line-move-ignore-invisible) t)
11360 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11361 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11362
11363 (setq js2-mode-functions-hidden nil
11364 js2-mode-comments-hidden nil
11365 js2-mode-buffer-dirty-p t
11366 js2-mode-parsing nil)
11367
11368 (js2-set-default-externs)
11369
11370 (when js2-include-jslint-globals
11371 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11372
11373 (run-hooks 'js2-init-hook)
11374
11375 (js2-reparse))
11376
11377 ;; We may eventually want js2-jsx-mode to derive from js-jsx-mode, but that'd be
11378 ;; a bit more complicated and it doesn't net us much yet.
11379 ;;;###autoload
11380 (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
11381 "Major mode for editing JSX code.
11382
11383 To customize the indentation for this mode, set the SGML offset
11384 variables (`sgml-basic-offset' et al) locally, like so:
11385
11386 (defun set-jsx-indentation ()
11387 (setq-local sgml-basic-offset js2-basic-offset))
11388 (add-hook 'js2-jsx-mode-hook #'set-jsx-indentation)"
11389 (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
11390
11391 (defun js2-mode-exit ()
11392 "Exit `js2-mode' and clean up."
11393 (interactive)
11394 (when js2-mode-node-overlay
11395 (delete-overlay js2-mode-node-overlay)
11396 (setq js2-mode-node-overlay nil))
11397 (js2-remove-overlays)
11398 (setq js2-mode-ast nil)
11399 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11400 (remove-from-invisibility-spec '(js2-outline . t))
11401 (js2-mode-show-all)
11402 (with-silent-modifications
11403 (js2-clear-face (point-min) (point-max))))
11404
11405 (defun js2-mode-reset-timer ()
11406 "Cancel any existing parse timer and schedule a new one."
11407 (if js2-mode-parse-timer
11408 (cancel-timer js2-mode-parse-timer))
11409 (setq js2-mode-parsing nil)
11410 (let ((timer (timer-create)))
11411 (setq js2-mode-parse-timer timer)
11412 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11413 (timer-set-idle-time timer js2-idle-timer-delay)
11414 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11415 (timer-activate-when-idle timer nil)))
11416
11417 (defun js2-mode-idle-reparse (buffer)
11418 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11419 it to be reparsed when the buffer is selected."
11420 (cond ((eq buffer (current-buffer))
11421 (js2-reparse))
11422 ((buffer-live-p buffer)
11423 ;; reparse when the buffer is selected again
11424 (with-current-buffer buffer
11425 (add-hook 'window-configuration-change-hook
11426 #'js2-mode-idle-reparse-inner
11427 nil t)))))
11428
11429 (defun js2-mode-idle-reparse-inner ()
11430 (remove-hook 'window-configuration-change-hook
11431 #'js2-mode-idle-reparse-inner
11432 t)
11433 (js2-reparse))
11434
11435 (defun js2-mode-edit (_beg _end _len)
11436 "Schedule a new parse after buffer is edited.
11437 Buffer edit spans from BEG to END and is of length LEN."
11438 (setq js2-mode-buffer-dirty-p t)
11439 (js2-mode-hide-overlay)
11440 (js2-mode-reset-timer))
11441
11442 (defun js2-minor-mode-edit (_beg _end _len)
11443 "Callback for buffer edits in `js2-mode'.
11444 Schedules a new parse after buffer is edited.
11445 Buffer edit spans from BEG to END and is of length LEN."
11446 (setq js2-mode-buffer-dirty-p t)
11447 (js2-mode-hide-overlay)
11448 (js2-mode-reset-timer))
11449
11450 (defun js2-reparse (&optional force)
11451 "Re-parse current buffer after user finishes some data entry.
11452 If we get any user input while parsing, including cursor motion,
11453 we discard the parse and reschedule it. If FORCE is nil, then the
11454 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11455 (let (time
11456 interrupted-p
11457 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11458 (unless js2-mode-parsing
11459 (setq js2-mode-parsing t)
11460 (unwind-protect
11461 (when (or js2-mode-buffer-dirty-p force)
11462 (js2-remove-overlays)
11463 (setq js2-mode-buffer-dirty-p nil
11464 js2-mode-fontifications nil
11465 js2-mode-deferred-properties nil)
11466 (if js2-mode-verbose-parse-p
11467 (message "parsing..."))
11468 (setq time
11469 (js2-time
11470 (setq interrupted-p
11471 (catch 'interrupted
11472 (js2-parse)
11473 (with-silent-modifications
11474 ;; if parsing is interrupted, comments and regex
11475 ;; literals stay ignored by `parse-partial-sexp'
11476 (remove-text-properties (point-min) (point-max)
11477 '(syntax-table))
11478 (js2-mode-apply-deferred-properties)
11479 (js2-mode-remove-suppressed-warnings)
11480 (js2-mode-show-warnings)
11481 (js2-mode-show-errors)
11482 (if (>= js2-highlight-level 1)
11483 (js2-highlight-jsdoc js2-mode-ast)))
11484 nil))))
11485 (if interrupted-p
11486 (progn
11487 ;; unfinished parse => try again
11488 (setq js2-mode-buffer-dirty-p t)
11489 (js2-mode-reset-timer))
11490 (if js2-mode-verbose-parse-p
11491 (message "Parse time: %s" time))))
11492 (setq js2-mode-parsing nil)
11493 (unless interrupted-p
11494 (setq js2-mode-parse-timer nil))))))
11495
11496 (defun js2-mode-show-node (event)
11497 "Debugging aid: highlight selected AST node on mouse click."
11498 (interactive "e")
11499 (mouse-set-point event)
11500 (setq deactivate-mark t)
11501 (when js2-mode-show-overlay
11502 (let ((node (js2-node-at-point))
11503 beg end)
11504 (if (null node)
11505 (message "No node found at location %s" (point))
11506 (setq beg (js2-node-abs-pos node)
11507 end (+ beg (js2-node-len node)))
11508 (if js2-mode-node-overlay
11509 (move-overlay js2-mode-node-overlay beg end)
11510 (setq js2-mode-node-overlay (make-overlay beg end))
11511 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11512 (with-silent-modifications
11513 (if (fboundp 'cursor-sensor-mode)
11514 (put-text-property beg end 'cursor-sensor-functions
11515 '(js2-mode-hide-overlay))
11516 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11517 (message "%s, parent: %s"
11518 (js2-node-short-name node)
11519 (if (js2-node-parent node)
11520 (js2-node-short-name (js2-node-parent node))
11521 "nil"))))))
11522
11523 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11524 "Remove the debugging overlay when point moves.
11525 ARG1, ARG2 and ARG3 have different values depending on whether this function
11526 was found on `point-left' or in `cursor-sensor-functions'."
11527 (when js2-mode-node-overlay
11528 (let ((beg (overlay-start js2-mode-node-overlay))
11529 (end (overlay-end js2-mode-node-overlay))
11530 (p2 (if (windowp arg1)
11531 ;; Called from cursor-sensor-functions.
11532 (window-point arg1)
11533 ;; Called from point-left.
11534 arg2)))
11535 ;; Sometimes we're called spuriously.
11536 (unless (and p2
11537 (>= p2 beg)
11538 (<= p2 end))
11539 (with-silent-modifications
11540 (remove-text-properties beg end
11541 '(point-left nil cursor-sensor-functions)))
11542 (delete-overlay js2-mode-node-overlay)
11543 (setq js2-mode-node-overlay nil)))))
11544
11545 (defun js2-mode-reset ()
11546 "Debugging helper: reset everything."
11547 (interactive)
11548 (js2-mode-exit)
11549 (js2-mode))
11550
11551 (defun js2-mode-show-warn-or-err (e face)
11552 "Highlight a warning or error E with FACE.
11553 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11554 The last element is optional. When present, use instead of FACE."
11555 (let* ((key (cl-first e))
11556 (beg (cl-second e))
11557 (end (+ beg (cl-third e)))
11558 ;; Don't inadvertently go out of bounds.
11559 (beg (max (point-min) (min beg (point-max))))
11560 (end (max (point-min) (min end (point-max))))
11561 (ovl (make-overlay beg end)))
11562 ;; FIXME: Why a mix of overlays and text-properties?
11563 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11564 (overlay-put ovl 'js2-error t)
11565 (put-text-property beg end 'help-echo (js2-get-msg key))
11566 (if (fboundp 'cursor-sensor-mode)
11567 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11568 (put-text-property beg end 'point-entered #'js2-echo-error))))
11569
11570 (defun js2-remove-overlays ()
11571 "Remove overlays from buffer that have a `js2-error' property."
11572 (let ((beg (point-min))
11573 (end (point-max)))
11574 (save-excursion
11575 (dolist (o (overlays-in beg end))
11576 (when (overlay-get o 'js2-error)
11577 (delete-overlay o))))))
11578
11579 (defun js2-mode-apply-deferred-properties ()
11580 "Apply fontifications and other text properties recorded during parsing."
11581 (when (cl-plusp js2-highlight-level)
11582 ;; We defer clearing faces as long as possible to eliminate flashing.
11583 (js2-clear-face (point-min) (point-max))
11584 ;; Have to reverse the recorded fontifications list so that errors
11585 ;; and warnings overwrite the normal fontifications.
11586 (dolist (f (nreverse js2-mode-fontifications))
11587 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11588 (setq js2-mode-fontifications nil))
11589 (dolist (p js2-mode-deferred-properties)
11590 (apply #'put-text-property p))
11591 (setq js2-mode-deferred-properties nil))
11592
11593 (defun js2-mode-show-errors ()
11594 "Highlight syntax errors."
11595 (when js2-mode-show-parse-errors
11596 (dolist (e (js2-ast-root-errors js2-mode-ast))
11597 (js2-mode-show-warn-or-err e 'js2-error))))
11598
11599 (defun js2-mode-remove-suppressed-warnings ()
11600 "Take suppressed warnings out of the AST warnings list.
11601 This ensures that the counts and `next-error' are correct."
11602 (setf (js2-ast-root-warnings js2-mode-ast)
11603 (js2-delete-if
11604 (lambda (e)
11605 (let ((key (caar e)))
11606 (or
11607 (and (not js2-strict-trailing-comma-warning)
11608 (string-match "trailing\\.comma" key))
11609 (and (not js2-strict-cond-assign-warning)
11610 (string= key "msg.equal.as.assign"))
11611 (and js2-missing-semi-one-line-override
11612 (string= key "msg.missing.semi")
11613 (let* ((beg (cl-second e))
11614 (node (js2-node-at-point beg))
11615 (fn (js2-mode-find-parent-fn node))
11616 (body (and fn (js2-function-node-body fn)))
11617 (lc (and body (js2-node-abs-pos body)))
11618 (rc (and lc (+ lc (js2-node-len body)))))
11619 (and fn
11620 (or (null body)
11621 (save-excursion
11622 (goto-char beg)
11623 (and (js2-same-line lc)
11624 (js2-same-line rc))))))))))
11625 (js2-ast-root-warnings js2-mode-ast))))
11626
11627 (defun js2-mode-show-warnings ()
11628 "Highlight strict-mode warnings."
11629 (when js2-mode-show-strict-warnings
11630 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11631 (js2-mode-show-warn-or-err e 'js2-warning))))
11632
11633 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11634 "Called by point-motion hooks.
11635 ARG1, ARG2 and ARG3 have different values depending on whether this function
11636 was found on `point-entered' or in `cursor-sensor-functions'."
11637 (let* ((new-point (if (windowp arg1)
11638 ;; Called from cursor-sensor-functions.
11639 (window-point arg1)
11640 ;; Called from point-left.
11641 arg2))
11642 (msg (get-text-property new-point 'help-echo)))
11643 (when (and (stringp msg)
11644 (not (active-minibuffer-window))
11645 (not (current-message)))
11646 (message msg))))
11647
11648 (defun js2-line-break (&optional _soft)
11649 "Break line at point and indent, continuing comment if within one.
11650 If inside a string, and `js2-concat-multiline-strings' is not
11651 nil, turn it into concatenation."
11652 (interactive)
11653 (let ((parse-status (syntax-ppss)))
11654 (cond
11655 ;; Check if we're inside a string.
11656 ((nth 3 parse-status)
11657 (if js2-concat-multiline-strings
11658 (js2-mode-split-string parse-status)
11659 (insert "\n")))
11660 ;; Check if inside a block comment.
11661 ((nth 4 parse-status)
11662 (js2-mode-extend-comment (nth 8 parse-status)))
11663 (t
11664 (newline-and-indent)))))
11665
11666 (defun js2-mode-split-string (parse-status)
11667 "Turn a newline in mid-string into a string concatenation.
11668 PARSE-STATUS is as documented in `parse-partial-sexp'."
11669 (let* ((quote-char (nth 3 parse-status))
11670 (at-eol (eq js2-concat-multiline-strings 'eol)))
11671 (insert quote-char)
11672 (insert (if at-eol " +\n" "\n"))
11673 (unless at-eol
11674 (insert "+ "))
11675 (js2-indent-line)
11676 (insert quote-char)
11677 (when (eolp)
11678 (insert quote-char)
11679 (backward-char 1))))
11680
11681 (defun js2-mode-extend-comment (start-pos)
11682 "Indent the line and, when inside a comment block, add comment prefix."
11683 (let (star single col first-line needs-close)
11684 (save-excursion
11685 (back-to-indentation)
11686 (when (< (point) start-pos)
11687 (goto-char start-pos))
11688 (cond
11689 ((looking-at "\\*[^/]")
11690 (setq star t
11691 col (current-column)))
11692 ((looking-at "/\\*")
11693 (setq star t
11694 first-line t
11695 col (1+ (current-column))))
11696 ((looking-at "//")
11697 (setq single t
11698 col (current-column)))))
11699 ;; Heuristic for whether we need to close the comment:
11700 ;; if we've got a parse error here, assume it's an unterminated
11701 ;; comment.
11702 (setq needs-close
11703 (or
11704 (get-char-property (1- (point)) 'js2-error)
11705 ;; The heuristic above doesn't work well when we're
11706 ;; creating a comment and there's another one downstream,
11707 ;; as our parser thinks this one ends at the end of the
11708 ;; next one. (You can have a /* inside a js block comment.)
11709 ;; So just close it if the next non-ws char isn't a *.
11710 (and first-line
11711 (eolp)
11712 (save-excursion
11713 (skip-chars-forward " \t\r\n")
11714 (not (eq (char-after) ?*))))))
11715 (delete-horizontal-space)
11716 (insert "\n")
11717 (cond
11718 (star
11719 (indent-to col)
11720 (insert "* ")
11721 (if (and first-line needs-close)
11722 (save-excursion
11723 (insert "\n")
11724 (indent-to col)
11725 (insert "*/"))))
11726 ((and single
11727 (save-excursion
11728 (and (zerop (forward-line 1))
11729 (looking-at "\\s-*//"))))
11730 (indent-to col)
11731 (insert "// ")))
11732 ;; Don't need to extend the comment after all.
11733 (js2-indent-line)))
11734
11735 (defun js2-beginning-of-line ()
11736 "Toggle point between bol and first non-whitespace char in line.
11737 Also moves past comment delimiters when inside comments."
11738 (interactive)
11739 (let (node)
11740 (cond
11741 ((bolp)
11742 (back-to-indentation))
11743 ((looking-at "//")
11744 (skip-chars-forward "/ \t"))
11745 ((and (eq (char-after) ?*)
11746 (setq node (js2-comment-at-point))
11747 (memq (js2-comment-node-format node) '(jsdoc block))
11748 (save-excursion
11749 (skip-chars-backward " \t")
11750 (bolp)))
11751 (skip-chars-forward "\* \t"))
11752 (t
11753 (goto-char (point-at-bol))))))
11754
11755 (defun js2-end-of-line ()
11756 "Toggle point between eol and last non-whitespace char in line."
11757 (interactive)
11758 (if (eolp)
11759 (skip-chars-backward " \t")
11760 (goto-char (point-at-eol))))
11761
11762 (defun js2-mode-wait-for-parse (callback)
11763 "Invoke CALLBACK when parsing is finished.
11764 If parsing is already finished, calls CALLBACK immediately."
11765 (if (not js2-mode-buffer-dirty-p)
11766 (funcall callback)
11767 (push callback js2-mode-pending-parse-callbacks)
11768 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11769
11770 (defun js2-mode-parse-finished ()
11771 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11772 ;; We can't let errors propagate up, since it prevents the
11773 ;; `js2-parse' method from completing normally and returning
11774 ;; the ast, which makes things mysteriously not work right.
11775 (unwind-protect
11776 (dolist (cb js2-mode-pending-parse-callbacks)
11777 (condition-case err
11778 (funcall cb)
11779 (error (message "%s" err))))
11780 (setq js2-mode-pending-parse-callbacks nil)))
11781
11782 (defun js2-mode-flag-region (from to flag)
11783 "Hide or show text from FROM to TO, according to FLAG.
11784 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11785 Returns the created overlay if FLAG is non-nil."
11786 (remove-overlays from to 'invisible 'js2-outline)
11787 (when flag
11788 (let ((o (make-overlay from to)))
11789 (overlay-put o 'invisible 'js2-outline)
11790 (overlay-put o 'isearch-open-invisible
11791 'js2-isearch-open-invisible)
11792 o)))
11793
11794 ;; Function to be set as an outline-isearch-open-invisible' property
11795 ;; to the overlay that makes the outline invisible (see
11796 ;; `js2-mode-flag-region').
11797 (defun js2-isearch-open-invisible (_overlay)
11798 ;; We rely on the fact that isearch places point on the matched text.
11799 (js2-mode-show-element))
11800
11801 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11802 "Return cons cell of bounds of folding overlay at POS.
11803 Returns nil if not found."
11804 (let ((overlays (overlays-at (or pos (point))))
11805 o)
11806 (while (and overlays
11807 (not o))
11808 (if (overlay-get (car overlays) 'invisible)
11809 (setq o (car overlays))
11810 (setq overlays (cdr overlays))))
11811 (if o
11812 (cons (overlay-start o) (overlay-end o)))))
11813
11814 (defun js2-mode-function-at-point (&optional pos)
11815 "Return the innermost function node enclosing current point.
11816 Returns nil if point is not in a function."
11817 (let ((node (js2-node-at-point pos)))
11818 (while (and node (not (js2-function-node-p node)))
11819 (setq node (js2-node-parent node)))
11820 (if (js2-function-node-p node)
11821 node)))
11822
11823 (defun js2-mode-toggle-element ()
11824 "Hide or show the foldable element at the point."
11825 (interactive)
11826 (let (comment fn pos)
11827 (save-excursion
11828 (cond
11829 ;; /* ... */ comment?
11830 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11831 (if (js2-mode-invisible-overlay-bounds
11832 (setq pos (+ 3 (js2-node-abs-pos comment))))
11833 (progn
11834 (goto-char pos)
11835 (js2-mode-show-element))
11836 (js2-mode-hide-element)))
11837 ;; //-comment?
11838 ((save-excursion
11839 (back-to-indentation)
11840 (looking-at js2-mode-//-comment-re))
11841 (js2-mode-toggle-//-comment))
11842 ;; function?
11843 ((setq fn (js2-mode-function-at-point))
11844 (setq pos (and (js2-function-node-body fn)
11845 (js2-node-abs-pos (js2-function-node-body fn))))
11846 (goto-char (1+ pos))
11847 (if (js2-mode-invisible-overlay-bounds)
11848 (js2-mode-show-element)
11849 (js2-mode-hide-element)))
11850 (t
11851 (message "Nothing at point to hide or show"))))))
11852
11853 (defun js2-mode-hide-element ()
11854 "Fold/hide contents of a block, showing ellipses.
11855 Show the hidden text with \\[js2-mode-show-element]."
11856 (interactive)
11857 (if js2-mode-buffer-dirty-p
11858 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11859 (let (node body beg end)
11860 (cond
11861 ((js2-mode-invisible-overlay-bounds)
11862 (message "already hidden"))
11863 (t
11864 (setq node (js2-node-at-point))
11865 (cond
11866 ((js2-block-comment-p node)
11867 (js2-mode-hide-comment node))
11868 (t
11869 (while (and node (not (js2-function-node-p node)))
11870 (setq node (js2-node-parent node)))
11871 (if (and node
11872 (setq body (js2-function-node-body node)))
11873 (progn
11874 (setq beg (js2-node-abs-pos body)
11875 end (+ beg (js2-node-len body)))
11876 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11877 (message "No collapsable element found at point"))))))))
11878
11879 (defun js2-mode-show-element ()
11880 "Show the hidden element at current point."
11881 (interactive)
11882 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11883 (if bounds
11884 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11885 (message "Nothing to un-hide"))))
11886
11887 (defun js2-mode-show-all ()
11888 "Show all of the text in the buffer."
11889 (interactive)
11890 (js2-mode-flag-region (point-min) (point-max) nil))
11891
11892 (defun js2-mode-toggle-hide-functions ()
11893 (interactive)
11894 (if js2-mode-functions-hidden
11895 (js2-mode-show-functions)
11896 (js2-mode-hide-functions)))
11897
11898 (defun js2-mode-hide-functions ()
11899 "Hides all non-nested function bodies in the buffer.
11900 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11901 to open an individual entry."
11902 (interactive)
11903 (if js2-mode-buffer-dirty-p
11904 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11905 (if (null js2-mode-ast)
11906 (message "Oops - parsing failed")
11907 (setq js2-mode-functions-hidden t)
11908 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11909
11910 (defun js2-mode-function-hider (n endp)
11911 (when (not endp)
11912 (let ((tt (js2-node-type n))
11913 body beg end)
11914 (cond
11915 ((and (= tt js2-FUNCTION)
11916 (setq body (js2-function-node-body n)))
11917 (setq beg (js2-node-abs-pos body)
11918 end (+ beg (js2-node-len body)))
11919 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11920 nil) ; don't process children of function
11921 (t
11922 t))))) ; keep processing other AST nodes
11923
11924 (defun js2-mode-show-functions ()
11925 "Un-hide any folded function bodies in the buffer."
11926 (interactive)
11927 (setq js2-mode-functions-hidden nil)
11928 (save-excursion
11929 (goto-char (point-min))
11930 (while (/= (goto-char (next-overlay-change (point)))
11931 (point-max))
11932 (dolist (o (overlays-at (point)))
11933 (when (and (overlay-get o 'invisible)
11934 (not (overlay-get o 'comment)))
11935 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11936
11937 (defun js2-mode-hide-comment (n)
11938 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11939 3 ; /**
11940 2)) ; /*
11941 (beg (+ (js2-node-abs-pos n) head))
11942 (end (- (+ beg (js2-node-len n)) head 2))
11943 (o (js2-mode-flag-region beg end 'hide)))
11944 (overlay-put o 'comment t)))
11945
11946 (defun js2-mode-toggle-hide-comments ()
11947 "Folds all block comments in the buffer.
11948 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11949 to open an individual entry."
11950 (interactive)
11951 (if js2-mode-comments-hidden
11952 (js2-mode-show-comments)
11953 (js2-mode-hide-comments)))
11954
11955 (defun js2-mode-hide-comments ()
11956 (interactive)
11957 (if js2-mode-buffer-dirty-p
11958 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11959 (if (null js2-mode-ast)
11960 (message "Oops - parsing failed")
11961 (setq js2-mode-comments-hidden t)
11962 (dolist (n (js2-ast-root-comments js2-mode-ast))
11963 (when (js2-block-comment-p n)
11964 (js2-mode-hide-comment n)))
11965 (js2-mode-hide-//-comments)))
11966
11967 (defun js2-mode-extend-//-comment (direction)
11968 "Find start or end of a block of similar //-comment lines.
11969 DIRECTION is -1 to look back, 1 to look forward.
11970 INDENT is the indentation level to match.
11971 Returns the end-of-line position of the furthest adjacent
11972 //-comment line with the same indentation as the current line.
11973 If there is no such matching line, returns current end of line."
11974 (let ((pos (point-at-eol))
11975 (indent (current-indentation)))
11976 (save-excursion
11977 (while (and (zerop (forward-line direction))
11978 (looking-at js2-mode-//-comment-re)
11979 (eq indent (length (match-string 1))))
11980 (setq pos (point-at-eol)))
11981 pos)))
11982
11983 (defun js2-mode-hide-//-comments ()
11984 "Fold adjacent 1-line comments, showing only snippet of first one."
11985 (let (beg end)
11986 (save-excursion
11987 (goto-char (point-min))
11988 (while (re-search-forward js2-mode-//-comment-re nil t)
11989 (setq beg (point)
11990 end (js2-mode-extend-//-comment 1))
11991 (unless (eq beg end)
11992 (overlay-put (js2-mode-flag-region beg end 'hide)
11993 'comment t))
11994 (goto-char end)
11995 (forward-char 1)))))
11996
11997 (defun js2-mode-toggle-//-comment ()
11998 "Fold or un-fold any multi-line //-comment at point.
11999 Caller should have determined that this line starts with a //-comment."
12000 (let* ((beg (point-at-eol))
12001 (end beg))
12002 (save-excursion
12003 (goto-char end)
12004 (if (js2-mode-invisible-overlay-bounds)
12005 (js2-mode-show-element)
12006 ;; else hide the comment
12007 (setq beg (js2-mode-extend-//-comment -1)
12008 end (js2-mode-extend-//-comment 1))
12009 (unless (eq beg end)
12010 (overlay-put (js2-mode-flag-region beg end 'hide)
12011 'comment t))))))
12012
12013 (defun js2-mode-show-comments ()
12014 "Un-hide any hidden comments, leaving other hidden elements alone."
12015 (interactive)
12016 (setq js2-mode-comments-hidden nil)
12017 (save-excursion
12018 (goto-char (point-min))
12019 (while (/= (goto-char (next-overlay-change (point)))
12020 (point-max))
12021 (dolist (o (overlays-at (point)))
12022 (when (overlay-get o 'comment)
12023 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12024
12025 (defun js2-mode-display-warnings-and-errors ()
12026 "Turn on display of warnings and errors."
12027 (interactive)
12028 (setq js2-mode-show-parse-errors t
12029 js2-mode-show-strict-warnings t)
12030 (js2-reparse 'force))
12031
12032 (defun js2-mode-hide-warnings-and-errors ()
12033 "Turn off display of warnings and errors."
12034 (interactive)
12035 (setq js2-mode-show-parse-errors nil
12036 js2-mode-show-strict-warnings nil)
12037 (js2-reparse 'force))
12038
12039 (defun js2-mode-toggle-warnings-and-errors ()
12040 "Toggle the display of warnings and errors.
12041 Some users don't like having warnings/errors reported while they type."
12042 (interactive)
12043 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12044 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12045 (if (called-interactively-p 'any)
12046 (message "warnings and errors %s"
12047 (if js2-mode-show-parse-errors
12048 "enabled"
12049 "disabled")))
12050 (js2-reparse 'force))
12051
12052 (defun js2-mode-customize ()
12053 (interactive)
12054 (customize-group 'js2-mode))
12055
12056 (defun js2-mode-forward-sexp (&optional arg)
12057 "Move forward across one statement or balanced expression.
12058 With ARG, do it that many times. Negative arg -N means
12059 move backward across N balanced expressions."
12060 (interactive "p")
12061 (setq arg (or arg 1))
12062 (save-restriction
12063 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12064 (js2-reparse)
12065 (let (forward-sexp-function
12066 node (start (point)) pos lp rp child)
12067 (cond
12068 ;; backward-sexp
12069 ;; could probably make this better for some cases:
12070 ;; - if in statement block (e.g. function body), go to parent
12071 ;; - infix exprs like (foo in bar) - maybe go to beginning
12072 ;; of infix expr if in the right-side expression?
12073 ((and arg (cl-minusp arg))
12074 (dotimes (_ (- arg))
12075 (js2-backward-sws)
12076 (forward-char -1) ; Enter the node we backed up to.
12077 (when (setq node (js2-node-at-point (point) t))
12078 (setq pos (js2-node-abs-pos node))
12079 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12080 (setq lp (car parens)
12081 rp (cdr parens)))
12082 (when (and lp (> start lp))
12083 (if (and rp (<= start rp))
12084 ;; Between parens, check if there's a child node we can jump.
12085 (when (setq child (js2-node-closest-child node (point) lp t))
12086 (setq pos (js2-node-abs-pos child)))
12087 ;; Before both parens.
12088 (setq pos lp)))
12089 (let ((state (parse-partial-sexp start pos)))
12090 (goto-char (if (not (zerop (car state)))
12091 ;; Stumble at the unbalanced paren if < 0, or
12092 ;; jump a bit further if > 0.
12093 (scan-sexps start -1)
12094 pos))))
12095 (unless pos (goto-char (point-min)))))
12096 (t
12097 ;; forward-sexp
12098 (dotimes (_ arg)
12099 (js2-forward-sws)
12100 (when (setq node (js2-node-at-point (point) t))
12101 (setq pos (js2-node-abs-pos node))
12102 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12103 (setq lp (car parens)
12104 rp (cdr parens)))
12105 (or
12106 (when (and rp (<= start rp))
12107 (if (> start lp)
12108 (when (setq child (js2-node-closest-child node (point) rp))
12109 (setq pos (js2-node-abs-end child)))
12110 (setq pos (1+ rp))))
12111 ;; No parens or child nodes, looks for the end of the current node.
12112 (cl-incf pos (js2-node-len
12113 (if (js2-expr-stmt-node-p (js2-node-parent node))
12114 ;; Stop after the semicolon.
12115 (js2-node-parent node)
12116 node))))
12117 (let ((state (save-excursion (parse-partial-sexp start pos))))
12118 (goto-char (if (not (zerop (car state)))
12119 (scan-sexps start 1)
12120 pos))))
12121 (unless pos (goto-char (point-max)))))))))
12122
12123 (defun js2-mode-forward-sexp-parens (node abs-pos)
12124 "Return a cons cell with positions of main parens in NODE."
12125 (cond
12126 ((or (js2-array-node-p node)
12127 (js2-object-node-p node)
12128 (js2-comp-node-p node)
12129 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12130 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12131 ((js2-paren-expr-node-p node)
12132 (let ((lp (js2-node-lp node))
12133 (rp (js2-node-rp node)))
12134 (cons (when lp (+ abs-pos lp))
12135 (when rp (+ abs-pos rp)))))))
12136
12137 (defun js2-node-closest-child (parent point limit &optional before)
12138 (let* ((parent-pos (js2-node-abs-pos parent))
12139 (rpoint (- point parent-pos))
12140 (rlimit (- limit parent-pos))
12141 (min (min rpoint rlimit))
12142 (max (max rpoint rlimit))
12143 found)
12144 (catch 'done
12145 (js2-visit-ast
12146 parent
12147 (lambda (node _end-p)
12148 (if (eq node parent)
12149 t
12150 (let ((pos (js2-node-pos node)) ;; Both relative values.
12151 (end (+ (js2-node-pos node) (js2-node-len node))))
12152 (when (and (>= pos min) (<= end max)
12153 (if before (< pos rpoint) (> end rpoint)))
12154 (setq found node))
12155 (when (> end rpoint)
12156 (throw 'done nil)))
12157 nil))))
12158 found))
12159
12160 (defun js2-errors ()
12161 "Return a list of errors found."
12162 (and js2-mode-ast
12163 (js2-ast-root-errors js2-mode-ast)))
12164
12165 (defun js2-warnings ()
12166 "Return a list of warnings found."
12167 (and js2-mode-ast
12168 (js2-ast-root-warnings js2-mode-ast)))
12169
12170 (defun js2-have-errors-p ()
12171 "Return non-nil if any parse errors or warnings were found."
12172 (or (js2-errors) (js2-warnings)))
12173
12174 (defun js2-errors-and-warnings ()
12175 "Return a copy of the concatenated errors and warnings lists.
12176 They are appended: first the errors, then the warnings.
12177 Entries are of the form (MSG BEG END)."
12178 (when js2-mode-ast
12179 (append (js2-ast-root-errors js2-mode-ast)
12180 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12181
12182 (defun js2-next-error (&optional arg reset)
12183 "Move to next parse error.
12184 Typically invoked via \\[next-error].
12185 ARG is the number of errors, forward or backward, to move.
12186 RESET means start over from the beginning."
12187 (interactive "p")
12188 (if (not (or (js2-errors) (js2-warnings)))
12189 (message "No errors")
12190 (when reset
12191 (goto-char (point-min)))
12192 (let* ((errs (js2-errors-and-warnings))
12193 (continue t)
12194 (start (point))
12195 (count (or arg 1))
12196 (backward (cl-minusp count))
12197 (sorter (if backward '> '<))
12198 (stopper (if backward '< '>))
12199 (count (abs count))
12200 all-errs err)
12201 ;; Sort by start position.
12202 (setq errs (sort errs (lambda (e1 e2)
12203 (funcall sorter (cl-second e1) (cl-second e2))))
12204 all-errs errs)
12205 ;; Find nth error with pos > start.
12206 (while (and errs continue)
12207 (when (funcall stopper (cl-cadar errs) start)
12208 (setq err (car errs))
12209 (if (zerop (cl-decf count))
12210 (setq continue nil)))
12211 (setq errs (cdr errs)))
12212 ;; Clear for `js2-echo-error'.
12213 (message nil)
12214 (if err
12215 (goto-char (cl-second err))
12216 ;; Wrap around to first error.
12217 (goto-char (cl-second (car all-errs)))
12218 ;; If we were already on it, echo msg again.
12219 (if (= (point) start)
12220 (js2-echo-error (point) (point)))))))
12221
12222 (defun js2-down-mouse-3 ()
12223 "Make right-click move the point to the click location.
12224 This makes right-click context menu operations a bit more intuitive.
12225 The point will not move if the region is active, however, to avoid
12226 destroying the region selection."
12227 (interactive)
12228 (when (and js2-move-point-on-right-click
12229 (not mark-active))
12230 (let ((e last-input-event))
12231 (ignore-errors
12232 (goto-char (cl-cadadr e))))))
12233
12234 (defun js2-mode-create-imenu-index ()
12235 "Return an alist for `imenu--index-alist'."
12236 ;; This is built up in `js2-parse-record-imenu' during parsing.
12237 (when js2-mode-ast
12238 ;; if we have an ast but no recorder, they're requesting a rescan
12239 (unless js2-imenu-recorder
12240 (js2-reparse 'force))
12241 (prog1
12242 (js2-build-imenu-index)
12243 (setq js2-imenu-recorder nil
12244 js2-imenu-function-map nil))))
12245
12246 (defun js2-mode-find-tag ()
12247 "Replacement for `find-tag-default'.
12248 `find-tag-default' returns a ridiculous answer inside comments."
12249 (let (beg end)
12250 (save-excursion
12251 (if (looking-at "\\_>")
12252 (setq beg (progn (forward-symbol -1) (point))
12253 end (progn (forward-symbol 1) (point)))
12254 (setq beg (progn (forward-symbol 1) (point))
12255 end (progn (forward-symbol -1) (point))))
12256 (replace-regexp-in-string
12257 "[\"']" ""
12258 (buffer-substring-no-properties beg end)))))
12259
12260 (defun js2-mode-forward-sibling ()
12261 "Move to the end of the sibling following point in parent.
12262 Returns non-nil if successful, or nil if there was no following sibling."
12263 (let* ((node (js2-node-at-point))
12264 (parent (js2-mode-find-enclosing-fn node))
12265 sib)
12266 (when (setq sib (js2-node-find-child-after (point) parent))
12267 (goto-char (+ (js2-node-abs-pos sib)
12268 (js2-node-len sib))))))
12269
12270 (defun js2-mode-backward-sibling ()
12271 "Move to the beginning of the sibling node preceding point in parent.
12272 Parent is defined as the enclosing script or function."
12273 (let* ((node (js2-node-at-point))
12274 (parent (js2-mode-find-enclosing-fn node))
12275 sib)
12276 (when (setq sib (js2-node-find-child-before (point) parent))
12277 (goto-char (js2-node-abs-pos sib)))))
12278
12279 (defun js2-beginning-of-defun (&optional arg)
12280 "Go to line on which current function starts, and return t on success.
12281 If we're not in a function or already at the beginning of one, go
12282 to beginning of previous script-level element.
12283 With ARG N, do that N times. If N is negative, move forward."
12284 (setq arg (or arg 1))
12285 (if (cl-plusp arg)
12286 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12287 (when (cond
12288 ((js2-function-node-p parent)
12289 (goto-char (js2-node-abs-pos parent)))
12290 (t
12291 (js2-mode-backward-sibling)))
12292 (if (> arg 1)
12293 (js2-beginning-of-defun (1- arg))
12294 t)))
12295 (when (js2-end-of-defun)
12296 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12297
12298 (defun js2-end-of-defun ()
12299 "Go to the char after the last position of the current function
12300 or script-level element."
12301 (let* ((node (js2-node-at-point))
12302 (parent (or (and (js2-function-node-p node) node)
12303 (js2-node-parent-script-or-fn node)))
12304 script)
12305 (unless (js2-function-node-p parent)
12306 ;; Use current script-level node, or, if none, the next one.
12307 (setq script (or parent node)
12308 parent (js2-node-find-child-before (point) script))
12309 (when (or (null parent)
12310 (>= (point) (+ (js2-node-abs-pos parent)
12311 (js2-node-len parent))))
12312 (setq parent (js2-node-find-child-after (point) script))))
12313 (when parent
12314 (goto-char (+ (js2-node-abs-pos parent)
12315 (js2-node-len parent))))))
12316
12317 (defun js2-mark-defun (&optional allow-extend)
12318 "Put mark at end of this function, point at beginning.
12319 The function marked is the one that contains point.
12320
12321 Interactively, if this command is repeated,
12322 or (in Transient Mark mode) if the mark is active,
12323 it marks the next defun after the ones already marked."
12324 (interactive "p")
12325 (let (extended)
12326 (when (and allow-extend
12327 (or (and (eq last-command this-command) (mark t))
12328 (and transient-mark-mode mark-active)))
12329 (let ((sib (save-excursion
12330 (goto-char (mark))
12331 (if (js2-mode-forward-sibling)
12332 (point)))))
12333 (if sib
12334 (progn
12335 (set-mark sib)
12336 (setq extended t))
12337 ;; no more siblings - try extending to enclosing node
12338 (goto-char (mark t)))))
12339 (when (not extended)
12340 (let ((node (js2-node-at-point (point) t)) ; skip comments
12341 ast fn stmt parent beg end)
12342 (when (js2-ast-root-p node)
12343 (setq ast node
12344 node (or (js2-node-find-child-after (point) node)
12345 (js2-node-find-child-before (point) node))))
12346 ;; only mark whole buffer if we can't find any children
12347 (if (null node)
12348 (setq node ast))
12349 (if (js2-function-node-p node)
12350 (setq parent node)
12351 (setq fn (js2-mode-find-enclosing-fn node)
12352 stmt (if (or (null fn)
12353 (js2-ast-root-p fn))
12354 (js2-mode-find-first-stmt node))
12355 parent (or stmt fn)))
12356 (setq beg (js2-node-abs-pos parent)
12357 end (+ beg (js2-node-len parent)))
12358 (push-mark beg)
12359 (goto-char end)
12360 (exchange-point-and-mark)))))
12361
12362 (defun js2-narrow-to-defun ()
12363 "Narrow to the function enclosing point."
12364 (interactive)
12365 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12366 (fn (if (js2-script-node-p node)
12367 node
12368 (js2-mode-find-enclosing-fn node)))
12369 (beg (js2-node-abs-pos fn)))
12370 (unless (js2-ast-root-p fn)
12371 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12372
12373 (defun js2-jump-to-definition (&optional arg)
12374 "Jump to the definition of an object's property, variable or function."
12375 (interactive "P")
12376 (ring-insert find-tag-marker-ring (point-marker))
12377 (let* ((node (js2-node-at-point))
12378 (parent (js2-node-parent node))
12379 (names (if (js2-prop-get-node-p parent)
12380 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12381 (cl-loop for n in temp
12382 with result = '()
12383 do (push n result)
12384 until (equal node n)
12385 finally return result)))))
12386 node-init)
12387 (unless (and (js2-name-node-p node)
12388 (not (js2-var-init-node-p parent))
12389 (not (js2-function-node-p parent)))
12390 (error "Node is not a supported jump node"))
12391 (push (or (and names (pop names))
12392 (unless (and (js2-object-prop-node-p parent)
12393 (eq node (js2-object-prop-node-left parent)))
12394 node)) names)
12395 (setq node-init (js2-search-scope node names))
12396
12397 ;; todo: display list of results in buffer
12398 ;; todo: group found references by buffer
12399 (unless node-init
12400 (switch-to-buffer
12401 (catch 'found
12402 (unless arg
12403 (mapc (lambda (b)
12404 (with-current-buffer b
12405 (when (derived-mode-p 'js2-mode)
12406 (setq node-init (js2-search-scope js2-mode-ast names))
12407 (if node-init
12408 (throw 'found b)))))
12409 (buffer-list)))
12410 nil)))
12411 (setq node-init (if (listp node-init) (car node-init) node-init))
12412 (unless node-init
12413 (pop-tag-mark)
12414 (error "No jump location found"))
12415 (goto-char (js2-node-abs-pos node-init))))
12416
12417 (defun js2-search-object (node name-node)
12418 "Check if object NODE contains element with NAME-NODE."
12419 (cl-assert (js2-object-node-p node))
12420 ;; Only support name-node and nodes for the time being
12421 (cl-loop for elem in (js2-object-node-elems node)
12422 for left = (js2-object-prop-node-left elem)
12423 if (or (and (js2-name-node-p left)
12424 (equal (js2-name-node-name name-node)
12425 (js2-name-node-name left)))
12426 (and (js2-string-node-p left)
12427 (string= (js2-name-node-name name-node)
12428 (js2-string-node-value left))))
12429 return elem))
12430
12431 (defun js2-search-object-for-prop (object prop-names)
12432 "Return node in OBJECT that matches PROP-NAMES or nil.
12433 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12434 i.e. ('name' 'value') = {name : { value: 3}}"
12435 (let (node
12436 (temp-object object)
12437 (temp t) ;temporay node
12438 (names prop-names))
12439 (while (and temp names (js2-object-node-p temp-object))
12440 (setq temp (js2-search-object temp-object (pop names)))
12441 (and (setq node temp)
12442 (setq temp-object (js2-object-prop-node-right temp))))
12443 (unless names node)))
12444
12445 (defun js2-search-scope (node names)
12446 "Searches NODE scope for jump location matching NAMES.
12447 NAMES is a list of property values to search for. For functions
12448 and variables NAMES will contain one element."
12449 (let (node-init
12450 (val (js2-name-node-name (car names))))
12451 (setq node-init (js2-get-symbol-declaration node val))
12452
12453 (when (> (length names) 1)
12454
12455 ;; Check var declarations
12456 (when (and node-init (string= val (js2-name-node-name node-init)))
12457 (let ((parent (js2-node-parent node-init))
12458 (temp-names names))
12459 (pop temp-names) ;; First element is var name
12460 (setq node-init (when (js2-var-init-node-p parent)
12461 (js2-search-object-for-prop
12462 (js2-var-init-node-initializer parent)
12463 temp-names)))))
12464
12465 ;; Check all assign nodes
12466 (js2-visit-ast
12467 js2-mode-ast
12468 (lambda (node endp)
12469 (unless endp
12470 (if (js2-assign-node-p node)
12471 (let ((left (js2-assign-node-left node))
12472 (right (js2-assign-node-right node))
12473 (temp-names names))
12474 (when (js2-prop-get-node-p left)
12475 (let* ((prop-list (js2-compute-nested-prop-get left))
12476 (found (cl-loop for prop in prop-list
12477 until (not (string= (js2-name-node-name
12478 (pop temp-names))
12479 (js2-name-node-name prop)))
12480 if (not temp-names) return prop))
12481 (found-node (or found
12482 (when (js2-object-node-p right)
12483 (js2-search-object-for-prop right
12484 temp-names)))))
12485 (if found-node (push found-node node-init))))))
12486 t))))
12487 node-init))
12488
12489 (defun js2-get-symbol-declaration (node name)
12490 "Find scope for NAME from NODE."
12491 (let ((scope (js2-get-defining-scope
12492 (or (js2-node-get-enclosing-scope node)
12493 node) name)))
12494 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12495
12496 (provide 'js2-mode)
12497
12498 ;;; js2-mode.el ends here