]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
`js2-print-json-path' added
[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 ;; Support for JSX is available via the derived mode `js2-jsx-mode'. If you
64 ;; also want JSX support, use that mode instead:
65
66 ;; (add-to-list 'auto-mode-alist '("\\.jsx?\\'" . js2-jsx-mode))
67 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-jsx-mode))
68
69 ;; To customize how it works:
70 ;; M-x customize-group RET js2-mode RET
71
72 ;; Notes:
73
74 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
75 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
76 ;; `js2-mode' current as the EcmaScript language standard evolves.
77
78 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
79 ;; customizable. It is a surprising amount of work to support customizable
80 ;; indentation. The current compromise is that the tab key lets you cycle among
81 ;; various likely indentation points, similar to the behavior of python-mode.
82
83 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
84 ;; and `mumamo', although it could be made to do so with some effort.
85 ;; This means that `js2-mode' is currently only useful for editing JavaScript
86 ;; files, and not for editing JavaScript within <script> tags or templates.
87
88 ;; The project page on GitHub is used for development and issue tracking.
89 ;; The original homepage at Google Code has outdated information and is mostly
90 ;; unmaintained.
91
92 ;;; Code:
93
94 (require 'cl-lib)
95 (require 'imenu)
96 (require 'js)
97 (require 'etags)
98
99 (eval-and-compile
100 (if (version< emacs-version "25.0")
101 (require 'js2-old-indent)
102 (defvaralias 'js2-basic-offset 'js-indent-level nil)
103 (defalias 'js2-proper-indentation 'js--proper-indentation)
104 (defalias 'js2-jsx-indent-line 'js-jsx-indent-line)
105 (defalias 'js2-indent-line 'js-indent-line)
106 (defalias 'js2-re-search-forward 'js--re-search-forward)))
107
108 ;;; Externs (variables presumed to be defined by the host system)
109
110 (defvar js2-ecma-262-externs
111 (mapcar 'symbol-name
112 '(Array Boolean Date Error EvalError Function Infinity JSON
113 Math NaN Number Object RangeError ReferenceError RegExp
114 String SyntaxError TypeError URIError
115 decodeURI decodeURIComponent encodeURI
116 encodeURIComponent escape eval isFinite isNaN
117 parseFloat parseInt undefined unescape))
118 "Ecma-262 externs. Included in `js2-externs' by default.")
119
120 (defvar js2-browser-externs
121 (mapcar 'symbol-name
122 '(;; DOM level 1
123 Attr CDATASection CharacterData Comment DOMException
124 DOMImplementation Document DocumentFragment
125 DocumentType Element Entity EntityReference
126 ExceptionCode NamedNodeMap Node NodeList Notation
127 ProcessingInstruction Text
128
129 ;; DOM level 2
130 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
131 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
132 HTMLBodyElement HTMLButtonElement HTMLCollection
133 HTMLDListElement HTMLDirectoryElement HTMLDivElement
134 HTMLDocument HTMLElement HTMLFieldSetElement
135 HTMLFontElement HTMLFormElement HTMLFrameElement
136 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
137 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
138 HTMLImageElement HTMLInputElement HTMLIsIndexElement
139 HTMLLIElement HTMLLabelElement HTMLLegendElement
140 HTMLLinkElement HTMLMapElement HTMLMenuElement
141 HTMLMetaElement HTMLModElement HTMLOListElement
142 HTMLObjectElement HTMLOptGroupElement
143 HTMLOptionElement HTMLOptionsCollection
144 HTMLParagraphElement HTMLParamElement HTMLPreElement
145 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
146 HTMLStyleElement HTMLTableCaptionElement
147 HTMLTableCellElement HTMLTableColElement
148 HTMLTableElement HTMLTableRowElement
149 HTMLTableSectionElement HTMLTextAreaElement
150 HTMLTitleElement HTMLUListElement
151
152 ;; DOM level 3
153 DOMConfiguration DOMError DOMException
154 DOMImplementationList DOMImplementationSource
155 DOMLocator DOMStringList NameList TypeInfo
156 UserDataHandler
157
158 ;; Window
159 window alert confirm document java navigator prompt screen
160 self top requestAnimationFrame cancelAnimationFrame
161
162 ;; W3C CSS
163 CSSCharsetRule CSSFontFace CSSFontFaceRule
164 CSSImportRule CSSMediaRule CSSPageRule
165 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
166 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
167 CSSValue CSSValueList Counter DOMImplementationCSS
168 DocumentCSS DocumentStyle ElementCSSInlineStyle
169 LinkStyle MediaList RGBColor Rect StyleSheet
170 StyleSheetList ViewCSS
171
172 ;; W3C Event
173 EventListener EventTarget Event DocumentEvent UIEvent
174 MouseEvent MutationEvent KeyboardEvent
175
176 ;; W3C Range
177 DocumentRange Range RangeException
178
179 ;; W3C XML
180 XPathResult XMLHttpRequest
181
182 ;; console object. Provided by at least Chrome and Firefox.
183 console))
184 "Browser externs.
185 You can cause these to be included or excluded with the custom
186 variable `js2-include-browser-externs'.")
187
188 (defvar js2-rhino-externs
189 (mapcar 'symbol-name
190 '(Packages importClass importPackage com org java
191 ;; Global object (shell) externs.
192 defineClass deserialize doctest gc help load
193 loadClass print quit readFile readUrl runCommand seal
194 serialize spawn sync toint32 version))
195 "Mozilla Rhino externs.
196 Set `js2-include-rhino-externs' to t to include them.")
197
198 (defvar js2-node-externs
199 (mapcar 'symbol-name
200 '(__dirname __filename Buffer clearInterval clearTimeout require
201 console exports global module process setInterval setTimeout
202 querystring))
203 "Node.js externs.
204 Set `js2-include-node-externs' to t to include them.")
205
206 (defvar js2-typed-array-externs
207 (mapcar 'symbol-name
208 '(ArrayBuffer Uint8ClampedArray DataView
209 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
210 Float32Array Float64Array))
211 "Khronos typed array externs. Available in most modern browsers and
212 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
213 are enabled, these will also be included.")
214
215 (defvar js2-harmony-externs
216 (mapcar 'symbol-name
217 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
218 "ES6 externs. If `js2-include-browser-externs' is enabled and
219 `js2-language-version' is sufficiently high, these will be included.")
220
221 ;;; Variables
222
223 (defun js2-mark-safe-local (name pred)
224 "Make the variable NAME buffer-local and mark it as safe file-local
225 variable with predicate PRED."
226 (make-variable-buffer-local name)
227 (put name 'safe-local-variable pred))
228
229 (defcustom js2-highlight-level 2
230 "Amount of syntax highlighting to perform.
231 0 or a negative value means none.
232 1 adds basic syntax highlighting.
233 2 adds highlighting of some Ecma built-in properties.
234 3 adds highlighting of many Ecma built-in functions."
235 :group 'js2-mode
236 :type '(choice (const :tag "None" 0)
237 (const :tag "Basic" 1)
238 (const :tag "Include Properties" 2)
239 (const :tag "Include Functions" 3)))
240
241 (defvar js2-mode-dev-mode-p nil
242 "Non-nil if running in development mode. Normally nil.")
243
244 (defgroup js2-mode nil
245 "An improved JavaScript mode."
246 :group 'languages)
247
248 (defcustom js2-idle-timer-delay 0.2
249 "Delay in secs before re-parsing after user makes changes.
250 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
251 :type 'number
252 :group 'js2-mode)
253 (make-variable-buffer-local 'js2-idle-timer-delay)
254
255 (defcustom js2-dynamic-idle-timer-adjust 0
256 "Positive to adjust `js2-idle-timer-delay' based on file size.
257 The idea is that for short files, parsing is faster so we can be
258 more responsive to user edits without interfering with editing.
259 The buffer length in characters (typically bytes) is divided by
260 this value and used to multiply `js2-idle-timer-delay' for the
261 buffer. For example, a 21k file and 10k adjust yields 21k/10k
262 == 2, so js2-idle-timer-delay is multiplied by 2.
263 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
264 `js2-idle-timer-delay' is not dependent on the file size."
265 :type 'number
266 :group 'js2-mode)
267
268 (defcustom js2-concat-multiline-strings t
269 "When non-nil, `js2-line-break' in mid-string will make it a
270 string concatenation. When `eol', the '+' will be inserted at the
271 end of the line, otherwise, at the beginning of the next line."
272 :type '(choice (const t) (const eol) (const nil))
273 :group 'js2-mode)
274
275 (defcustom js2-mode-show-parse-errors t
276 "True to highlight parse errors."
277 :type 'boolean
278 :group 'js2-mode)
279
280 (defcustom js2-mode-show-strict-warnings t
281 "Non-nil to emit Ecma strict-mode warnings.
282 Some of the warnings can be individually disabled by other flags,
283 even if this flag is non-nil."
284 :type 'boolean
285 :group 'js2-mode)
286
287 (defcustom js2-strict-trailing-comma-warning t
288 "Non-nil to warn about trailing commas in array literals.
289 Ecma-262-5.1 allows them, but older versions of IE raise an error."
290 :type 'boolean
291 :group 'js2-mode)
292
293 (defcustom js2-strict-missing-semi-warning t
294 "Non-nil to warn about semicolon auto-insertion after statement.
295 Technically this is legal per Ecma-262, but some style guides disallow
296 depending on it."
297 :type 'boolean
298 :group 'js2-mode)
299
300 (defcustom js2-missing-semi-one-line-override nil
301 "Non-nil to permit missing semicolons in one-line functions.
302 In one-liner functions such as `function identity(x) {return x}'
303 people often omit the semicolon for a cleaner look. If you are
304 such a person, you can suppress the missing-semicolon warning
305 by setting this variable to t."
306 :type 'boolean
307 :group 'js2-mode)
308
309 (defcustom js2-strict-inconsistent-return-warning t
310 "Non-nil to warn about mixing returns with value-returns.
311 It's perfectly legal to have a `return' and a `return foo' in the
312 same function, but it's often an indicator of a bug, and it also
313 interferes with type inference (in systems that support it.)"
314 :type 'boolean
315 :group 'js2-mode)
316
317 (defcustom js2-strict-cond-assign-warning t
318 "Non-nil to warn about expressions like if (a = b).
319 This often should have been '==' instead of '='. If the warning
320 is enabled, you can suppress it on a per-expression basis by
321 parenthesizing the expression, e.g. if ((a = b)) ..."
322 :type 'boolean
323 :group 'js2-mode)
324
325 (defcustom js2-strict-var-redeclaration-warning t
326 "Non-nil to warn about redeclaring variables in a script or function."
327 :type 'boolean
328 :group 'js2-mode)
329
330 (defcustom js2-strict-var-hides-function-arg-warning t
331 "Non-nil to warn about a var decl hiding a function argument."
332 :type 'boolean
333 :group 'js2-mode)
334
335 (defcustom js2-skip-preprocessor-directives nil
336 "Non-nil to treat lines beginning with # as comments.
337 Useful for viewing Mozilla JavaScript source code."
338 :type 'boolean
339 :group 'js2-mode)
340
341 (defcustom js2-language-version 200
342 "Configures what JavaScript language version to recognize.
343 Currently versions 150, 160, 170, 180 and 200 are supported,
344 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
345 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
346 yield, and Array comprehensions, and 1.8 adds function closures."
347 :type 'integer
348 :group 'js2-mode)
349
350 (defcustom js2-instanceof-has-side-effects nil
351 "If non-nil, treats the instanceof operator as having side effects.
352 This is useful for xulrunner apps."
353 :type 'boolean
354 :group 'js2-mode)
355
356 (defcustom js2-move-point-on-right-click t
357 "Non-nil to move insertion point when you right-click.
358 This makes right-click context menu behavior a bit more intuitive,
359 since menu operations generally apply to the point. The exception
360 is if there is a region selection, in which case the point does -not-
361 move, so cut/copy/paste can work properly.
362
363 Note that IntelliJ moves the point, and Eclipse leaves it alone,
364 so this behavior is customizable."
365 :group 'js2-mode
366 :type 'boolean)
367
368 (defcustom js2-allow-rhino-new-expr-initializer t
369 "Non-nil to support a Rhino's experimental syntactic construct.
370
371 Rhino supports the ability to follow a `new' expression with an object
372 literal, which is used to set additional properties on the new object
373 after calling its constructor. Syntax:
374
375 new <expr> [ ( arglist ) ] [initializer]
376
377 Hence, this expression:
378
379 new Object {a: 1, b: 2}
380
381 results in an Object with properties a=1 and b=2. This syntax is
382 apparently not configurable in Rhino - it's currently always enabled,
383 as of Rhino version 1.7R2."
384 :type 'boolean
385 :group 'js2-mode)
386
387 (defcustom js2-allow-member-expr-as-function-name nil
388 "Non-nil to support experimental Rhino syntax for function names.
389
390 Rhino supports an experimental syntax configured via the Rhino Context
391 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
392
393 function <member-expr> ( [ arg-list ] ) { <body> }
394
395 Where member-expr is a non-parenthesized 'member expression', which
396 is anything at the grammar level of a new-expression or lower, meaning
397 any expression that does not involve infix or unary operators.
398
399 When <member-expr> is not a simple identifier, then it is syntactic
400 sugar for assigning the anonymous function to the <member-expr>. Hence,
401 this code:
402
403 function a.b().c[2] (x, y) { ... }
404
405 is rewritten as:
406
407 a.b().c[2] = function(x, y) {...}
408
409 which doesn't seem particularly useful, but Rhino permits it."
410 :type 'boolean
411 :group 'js2-mode)
412
413 ;; scanner variables
414
415 (defmacro js2-deflocal (name value &optional comment)
416 "Define a buffer-local variable NAME with VALUE and COMMENT."
417 (declare (debug defvar) (doc-string 3))
418 `(progn
419 (defvar ,name ,value ,comment)
420 (make-variable-buffer-local ',name)))
421
422 (defvar js2-EOF_CHAR -1
423 "Represents end of stream. Distinct from js2-EOF token type.")
424
425 ;; I originally used symbols to represent tokens, but Rhino uses
426 ;; ints and then sets various flag bits in them, so ints it is.
427 ;; The upshot is that we need a `js2-' prefix in front of each name.
428 (defvar js2-ERROR -1)
429 (defvar js2-EOF 0)
430 (defvar js2-EOL 1)
431 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
432 (defvar js2-LEAVEWITH 3)
433 (defvar js2-RETURN 4)
434 (defvar js2-GOTO 5)
435 (defvar js2-IFEQ 6)
436 (defvar js2-IFNE 7)
437 (defvar js2-SETNAME 8)
438 (defvar js2-BITOR 9)
439 (defvar js2-BITXOR 10)
440 (defvar js2-BITAND 11)
441 (defvar js2-EQ 12)
442 (defvar js2-NE 13)
443 (defvar js2-LT 14)
444 (defvar js2-LE 15)
445 (defvar js2-GT 16)
446 (defvar js2-GE 17)
447 (defvar js2-LSH 18)
448 (defvar js2-RSH 19)
449 (defvar js2-URSH 20)
450 (defvar js2-ADD 21) ; infix plus
451 (defvar js2-SUB 22) ; infix minus
452 (defvar js2-MUL 23)
453 (defvar js2-DIV 24)
454 (defvar js2-MOD 25)
455 (defvar js2-NOT 26)
456 (defvar js2-BITNOT 27)
457 (defvar js2-POS 28) ; unary plus
458 (defvar js2-NEG 29) ; unary minus
459 (defvar js2-NEW 30)
460 (defvar js2-DELPROP 31)
461 (defvar js2-TYPEOF 32)
462 (defvar js2-GETPROP 33)
463 (defvar js2-GETPROPNOWARN 34)
464 (defvar js2-SETPROP 35)
465 (defvar js2-GETELEM 36)
466 (defvar js2-SETELEM 37)
467 (defvar js2-CALL 38)
468 (defvar js2-NAME 39) ; an identifier
469 (defvar js2-NUMBER 40)
470 (defvar js2-STRING 41)
471 (defvar js2-NULL 42)
472 (defvar js2-THIS 43)
473 (defvar js2-FALSE 44)
474 (defvar js2-TRUE 45)
475 (defvar js2-SHEQ 46) ; shallow equality (===)
476 (defvar js2-SHNE 47) ; shallow inequality (!==)
477 (defvar js2-REGEXP 48)
478 (defvar js2-BINDNAME 49)
479 (defvar js2-THROW 50)
480 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
481 (defvar js2-IN 52)
482 (defvar js2-INSTANCEOF 53)
483 (defvar js2-LOCAL_LOAD 54)
484 (defvar js2-GETVAR 55)
485 (defvar js2-SETVAR 56)
486 (defvar js2-CATCH_SCOPE 57)
487 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
488 (defvar js2-ENUM_INIT_VALUES 59)
489 (defvar js2-ENUM_INIT_ARRAY 60)
490 (defvar js2-ENUM_NEXT 61)
491 (defvar js2-ENUM_ID 62)
492 (defvar js2-THISFN 63)
493 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
494 (defvar js2-ARRAYLIT 65) ; array literal
495 (defvar js2-OBJECTLIT 66) ; object literal
496 (defvar js2-GET_REF 67) ; *reference
497 (defvar js2-SET_REF 68) ; *reference = something
498 (defvar js2-DEL_REF 69) ; delete reference
499 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
500 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
501 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
502
503 ;; XML support
504 (defvar js2-DEFAULTNAMESPACE 73)
505 (defvar js2-ESCXMLATTR 74)
506 (defvar js2-ESCXMLTEXT 75)
507 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
508 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
509 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
510 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
511
512 (defvar js2-first-bytecode js2-ENTERWITH)
513 (defvar js2-last-bytecode js2-REF_NS_NAME)
514
515 (defvar js2-TRY 80)
516 (defvar js2-SEMI 81) ; semicolon
517 (defvar js2-LB 82) ; left and right brackets
518 (defvar js2-RB 83)
519 (defvar js2-LC 84) ; left and right curly-braces
520 (defvar js2-RC 85)
521 (defvar js2-LP 86) ; left and right parens
522 (defvar js2-RP 87)
523 (defvar js2-COMMA 88) ; comma operator
524
525 (defvar js2-ASSIGN 89) ; simple assignment (=)
526 (defvar js2-ASSIGN_BITOR 90) ; |=
527 (defvar js2-ASSIGN_BITXOR 91) ; ^=
528 (defvar js2-ASSIGN_BITAND 92) ; &=
529 (defvar js2-ASSIGN_LSH 93) ; <<=
530 (defvar js2-ASSIGN_RSH 94) ; >>=
531 (defvar js2-ASSIGN_URSH 95) ; >>>=
532 (defvar js2-ASSIGN_ADD 96) ; +=
533 (defvar js2-ASSIGN_SUB 97) ; -=
534 (defvar js2-ASSIGN_MUL 98) ; *=
535 (defvar js2-ASSIGN_DIV 99) ; /=
536 (defvar js2-ASSIGN_MOD 100) ; %=
537
538 (defvar js2-first-assign js2-ASSIGN)
539 (defvar js2-last-assign js2-ASSIGN_MOD)
540
541 (defvar js2-HOOK 101) ; conditional (?:)
542 (defvar js2-COLON 102)
543 (defvar js2-OR 103) ; logical or (||)
544 (defvar js2-AND 104) ; logical and (&&)
545 (defvar js2-INC 105) ; increment/decrement (++ --)
546 (defvar js2-DEC 106)
547 (defvar js2-DOT 107) ; member operator (.)
548 (defvar js2-FUNCTION 108) ; function keyword
549 (defvar js2-EXPORT 109) ; export keyword
550 (defvar js2-IMPORT 110) ; import keyword
551 (defvar js2-IF 111) ; if keyword
552 (defvar js2-ELSE 112) ; else keyword
553 (defvar js2-SWITCH 113) ; switch keyword
554 (defvar js2-CASE 114) ; case keyword
555 (defvar js2-DEFAULT 115) ; default keyword
556 (defvar js2-WHILE 116) ; while keyword
557 (defvar js2-DO 117) ; do keyword
558 (defvar js2-FOR 118) ; for keyword
559 (defvar js2-BREAK 119) ; break keyword
560 (defvar js2-CONTINUE 120) ; continue keyword
561 (defvar js2-VAR 121) ; var keyword
562 (defvar js2-WITH 122) ; with keyword
563 (defvar js2-CATCH 123) ; catch keyword
564 (defvar js2-FINALLY 124) ; finally keyword
565 (defvar js2-VOID 125) ; void keyword
566 (defvar js2-RESERVED 126) ; reserved keywords
567
568 (defvar js2-EMPTY 127)
569
570 ;; Types used for the parse tree - never returned by scanner.
571
572 (defvar js2-BLOCK 128) ; statement block
573 (defvar js2-LABEL 129) ; label
574 (defvar js2-TARGET 130)
575 (defvar js2-LOOP 131)
576 (defvar js2-EXPR_VOID 132) ; expression statement in functions
577 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
578 (defvar js2-JSR 134)
579 (defvar js2-SCRIPT 135) ; top-level node for entire script
580 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
581 (defvar js2-USE_STACK 137)
582 (defvar js2-SETPROP_OP 138) ; x.y op= something
583 (defvar js2-SETELEM_OP 139) ; x[y] op= something
584 (defvar js2-LOCAL_BLOCK 140)
585 (defvar js2-SET_REF_OP 141) ; *reference op= something
586
587 ;; For XML support:
588 (defvar js2-DOTDOT 142) ; member operator (..)
589 (defvar js2-COLONCOLON 143) ; namespace::name
590 (defvar js2-XML 144) ; XML type
591 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
592 (defvar js2-XMLATTR 146) ; @
593 (defvar js2-XMLEND 147)
594
595 ;; Optimizer-only tokens
596 (defvar js2-TO_OBJECT 148)
597 (defvar js2-TO_DOUBLE 149)
598
599 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
600 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
601 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
602 (defvar js2-CONST 153)
603 (defvar js2-SETCONST 154)
604 (defvar js2-SETCONSTVAR 155)
605 (defvar js2-ARRAYCOMP 156)
606 (defvar js2-LETEXPR 157)
607 (defvar js2-WITHEXPR 158)
608 (defvar js2-DEBUGGER 159)
609
610 (defvar js2-COMMENT 160)
611 (defvar js2-TRIPLEDOT 161) ; for rest parameter
612 (defvar js2-ARROW 162) ; function arrow (=>)
613 (defvar js2-CLASS 163)
614 (defvar js2-EXTENDS 164)
615 (defvar js2-SUPER 165)
616 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
617 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
618 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
619
620 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
621
622 (defconst js2-debug-print-trees nil)
623
624 ;; Rhino accepts any string or stream as input. Emacs character
625 ;; processing works best in buffers, so we'll assume the input is a
626 ;; buffer. JavaScript strings can be copied into temp buffers before
627 ;; scanning them.
628
629 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
630 ;; They're the Emacs equivalent of instance variables, more or less.
631
632 (js2-deflocal js2-ts-dirty-line nil
633 "Token stream buffer-local variable.
634 Indicates stuff other than whitespace since start of line.")
635
636 (js2-deflocal js2-ts-hit-eof nil
637 "Token stream buffer-local variable.")
638
639 ;; FIXME: Unused.
640 (js2-deflocal js2-ts-line-start 0
641 "Token stream buffer-local variable.")
642
643 (js2-deflocal js2-ts-lineno 1
644 "Token stream buffer-local variable.")
645
646 ;; FIXME: Unused.
647 (js2-deflocal js2-ts-line-end-char -1
648 "Token stream buffer-local variable.")
649
650 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
651 "Token stream buffer-local variable.
652 Current scan position.")
653
654 ;; FIXME: Unused.
655 (js2-deflocal js2-ts-is-xml-attribute nil
656 "Token stream buffer-local variable.")
657
658 (js2-deflocal js2-ts-xml-is-tag-content nil
659 "Token stream buffer-local variable.")
660
661 (js2-deflocal js2-ts-xml-open-tags-count 0
662 "Token stream buffer-local variable.")
663
664 (js2-deflocal js2-ts-string-buffer nil
665 "Token stream buffer-local variable.
666 List of chars built up while scanning various tokens.")
667
668 (cl-defstruct (js2-token
669 (:constructor nil)
670 (:constructor make-js2-token (beg)))
671 "Value returned from the token stream."
672 (type js2-EOF)
673 (beg 1)
674 (end -1)
675 (string "")
676 number
677 number-base
678 regexp-flags
679 comment-type
680 follows-eol-p)
681
682 ;; Have to call `js2-init-scanner' to initialize the values.
683 (js2-deflocal js2-ti-tokens nil)
684 (js2-deflocal js2-ti-tokens-cursor nil)
685 (js2-deflocal js2-ti-lookahead nil)
686
687 (cl-defstruct (js2-ts-state
688 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
689 (cursor js2-ts-cursor)
690 (tokens (copy-sequence js2-ti-tokens))
691 (tokens-cursor js2-ti-tokens-cursor)
692 (lookahead js2-ti-lookahead))))
693 lineno
694 cursor
695 tokens
696 tokens-cursor
697 lookahead)
698
699 ;;; Parser variables
700
701 (js2-deflocal js2-parsed-errors nil
702 "List of errors produced during scanning/parsing.")
703
704 (js2-deflocal js2-parsed-warnings nil
705 "List of warnings produced during scanning/parsing.")
706
707 (js2-deflocal js2-recover-from-parse-errors t
708 "Non-nil to continue parsing after a syntax error.
709
710 In recovery mode, the AST will be built in full, and any error
711 nodes will be flagged with appropriate error information. If
712 this flag is nil, a syntax error will result in an error being
713 signaled.
714
715 The variable is automatically buffer-local, because different
716 modes that use the parser will need different settings.")
717
718 (js2-deflocal js2-parse-hook nil
719 "List of callbacks for receiving parsing progress.")
720
721 (defvar js2-parse-finished-hook nil
722 "List of callbacks to notify when parsing finishes.
723 Not called if parsing was interrupted.")
724
725 (js2-deflocal js2-is-eval-code nil
726 "True if we're evaluating code in a string.
727 If non-nil, the tokenizer will record the token text, and the AST nodes
728 will record their source text. Off by default for IDE modes, since the
729 text is available in the buffer.")
730
731 (defvar js2-parse-ide-mode t
732 "Non-nil if the parser is being used for `js2-mode'.
733 If non-nil, the parser will set text properties for fontification
734 and the syntax table. The value should be nil when using the
735 parser as a frontend to an interpreter or byte compiler.")
736
737 ;;; Parser instance variables (buffer-local vars for js2-parse)
738
739 (defconst js2-ti-after-eol (lsh 1 16)
740 "Flag: first token of the source line.")
741
742 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
743
744 (js2-deflocal js2-compiler-generate-debug-info t)
745 (js2-deflocal js2-compiler-use-dynamic-scope nil)
746 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
747 (js2-deflocal js2-compiler-xml-available t)
748 (js2-deflocal js2-compiler-optimization-level 0)
749 (js2-deflocal js2-compiler-generating-source t)
750 (js2-deflocal js2-compiler-strict-mode nil)
751 (js2-deflocal js2-compiler-report-warning-as-error nil)
752 (js2-deflocal js2-compiler-generate-observer-count nil)
753 (js2-deflocal js2-compiler-activation-names nil)
754
755 ;; SKIP: sourceURI
756
757 ;; There's a compileFunction method in Context.java - may need it.
758 (js2-deflocal js2-called-by-compile-function nil
759 "True if `js2-parse' was called by `js2-compile-function'.
760 Will only be used when we finish implementing the interpreter.")
761
762 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
763
764 ;; SKIP: node factory - we're going to just call functions directly,
765 ;; and eventually go to a unified AST format.
766
767 (js2-deflocal js2-nesting-of-function 0)
768
769 (js2-deflocal js2-recorded-identifiers nil
770 "Tracks identifiers found during parsing.")
771
772 (js2-deflocal js2-is-in-destructuring nil
773 "True while parsing destructuring expression.")
774
775 (js2-deflocal js2-in-use-strict-directive nil
776 "True while inside a script or function under strict mode.")
777
778 (defcustom js2-global-externs nil
779 "A list of any extern names you'd like to consider always declared.
780 This list is global and is used by all `js2-mode' files.
781 You can create buffer-local externs list using `js2-additional-externs'.
782
783 There is also a buffer-local variable `js2-default-externs',
784 which is initialized by default to include the Ecma-262 externs
785 and the standard browser externs. The three lists are all
786 checked during highlighting."
787 :type 'list
788 :group 'js2-mode)
789
790 (js2-deflocal js2-default-externs nil
791 "Default external declarations.
792
793 These are currently only used for highlighting undeclared variables,
794 which only worries about top-level (unqualified) references.
795 As js2-mode's processing improves, we will flesh out this list.
796
797 The initial value is set to `js2-ecma-262-externs', unless some
798 of the `js2-include-?-externs' variables are set to t, in which
799 case the browser, Rhino and/or Node.js externs are also included.
800
801 See `js2-additional-externs' for more information.")
802
803 (defcustom js2-include-browser-externs t
804 "Non-nil to include browser externs in the master externs list.
805 If you work on JavaScript files that are not intended for browsers,
806 such as Mozilla Rhino server-side JavaScript, set this to nil.
807 See `js2-additional-externs' for more information about externs."
808 :type 'boolean
809 :group 'js2-mode)
810
811 (defcustom js2-include-rhino-externs nil
812 "Non-nil to include Mozilla Rhino 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 (defcustom js2-include-node-externs nil
818 "Non-nil to include Node.js externs in the master externs list.
819 See `js2-additional-externs' for more information about externs."
820 :type 'boolean
821 :group 'js2-mode)
822
823 (js2-deflocal js2-additional-externs nil
824 "A buffer-local list of additional external declarations.
825 It is used to decide whether variables are considered undeclared
826 for purposes of highlighting.
827
828 Each entry is a Lisp string. The string should be the fully qualified
829 name of an external entity. All externs should be added to this list,
830 so that as js2-mode's processing improves it can take advantage of them.
831
832 You may want to declare your externs in three ways.
833 First, you can add externs that are valid for all your JavaScript files.
834 You should probably do this by adding them to `js2-global-externs', which
835 is a global list used for all js2-mode files.
836
837 Next, you can add a function to `js2-init-hook' that adds additional
838 externs appropriate for the specific file, perhaps based on its path.
839 These should go in `js2-additional-externs', which is buffer-local.
840
841 Third, you can use JSLint's global declaration, as long as
842 `js2-include-jslint-globals' is non-nil, which see.
843
844 Finally, you can add a function to `js2-post-parse-callbacks',
845 which is called after parsing completes, and `js2-mode-ast' is bound to
846 the root of the parse tree. At this stage you can set up an AST
847 node visitor using `js2-visit-ast' and examine the parse tree
848 for specific import patterns that may imply the existence of
849 other externs, possibly tied to your build system. These should also
850 be added to `js2-additional-externs'.
851
852 Your post-parse callback may of course also use the simpler and
853 faster (but perhaps less robust) approach of simply scanning the
854 buffer text for your imports, using regular expressions.")
855
856 ;; SKIP: decompiler
857 ;; SKIP: encoded-source
858
859 ;;; The following variables are per-function and should be saved/restored
860 ;;; during function parsing...
861
862 (js2-deflocal js2-current-script-or-fn nil)
863 (js2-deflocal js2-current-scope nil)
864 (js2-deflocal js2-nesting-of-with 0)
865 (js2-deflocal js2-label-set nil
866 "An alist mapping label names to nodes.")
867
868 (js2-deflocal js2-loop-set nil)
869 (js2-deflocal js2-loop-and-switch-set nil)
870 (js2-deflocal js2-has-return-value nil)
871 (js2-deflocal js2-end-flags 0)
872
873 ;;; ...end of per function variables
874
875 ;; These flags enumerate the possible ways a statement/function can
876 ;; terminate. These flags are used by endCheck() and by the Parser to
877 ;; detect inconsistent return usage.
878 ;;
879 ;; END_UNREACHED is reserved for code paths that are assumed to always be
880 ;; able to execute (example: throw, continue)
881 ;;
882 ;; END_DROPS_OFF indicates if the statement can transfer control to the
883 ;; next one. Statement such as return dont. A compound statement may have
884 ;; some branch that drops off control to the next statement.
885 ;;
886 ;; END_RETURNS indicates that the statement can return (without arguments)
887 ;; END_RETURNS_VALUE indicates that the statement can return a value.
888 ;;
889 ;; A compound statement such as
890 ;; if (condition) {
891 ;; return value;
892 ;; }
893 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
894
895 (defconst js2-end-unreached #x0)
896 (defconst js2-end-drops-off #x1)
897 (defconst js2-end-returns #x2)
898 (defconst js2-end-returns-value #x4)
899
900 ;; Rhino awkwardly passes a statementLabel parameter to the
901 ;; statementHelper() function, the main statement parser, which
902 ;; is then used by quite a few of the sub-parsers. We just make
903 ;; it a buffer-local variable and make sure it's cleaned up properly.
904 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
905
906 ;; Similarly, Rhino passes an inForInit boolean through about half
907 ;; the expression parsers. We use a dynamically-scoped variable,
908 ;; which makes it easier to funcall the parsers individually without
909 ;; worrying about whether they take the parameter or not.
910 (js2-deflocal js2-in-for-init nil)
911 (js2-deflocal js2-temp-name-counter 0)
912 (js2-deflocal js2-parse-stmt-count 0)
913
914 (defsubst js2-get-next-temp-name ()
915 (format "$%d" (cl-incf js2-temp-name-counter)))
916
917 (defvar js2-parse-interruptable-p t
918 "Set this to nil to force parse to continue until finished.
919 This will mostly be useful for interpreters.")
920
921 (defvar js2-statements-per-pause 50
922 "Pause after this many statements to check for user input.
923 If user input is pending, stop the parse and discard the tree.
924 This makes for a smoother user experience for large files.
925 You may have to wait a second or two before the highlighting
926 and error-reporting appear, but you can always type ahead if
927 you wish. This appears to be more or less how Eclipse, IntelliJ
928 and other editors work.")
929
930 (js2-deflocal js2-record-comments t
931 "Instructs the scanner to record comments in `js2-scanned-comments'.")
932
933 (js2-deflocal js2-scanned-comments nil
934 "List of all comments from the current parse.")
935
936 (defcustom js2-mode-indent-inhibit-undo nil
937 "Non-nil to disable collection of Undo information when indenting lines.
938 Some users have requested this behavior. It's nil by default because
939 other Emacs modes don't work this way."
940 :type 'boolean
941 :group 'js2-mode)
942
943 (defcustom js2-mode-indent-ignore-first-tab nil
944 "If non-nil, ignore first TAB keypress if we look indented properly.
945 It's fairly common for users to navigate to an already-indented line
946 and press TAB for reassurance that it's been indented. For this class
947 of users, we want the first TAB press on a line to be ignored if the
948 line is already indented to one of the precomputed alternatives.
949
950 This behavior is only partly implemented. If you TAB-indent a line,
951 navigate to another line, and then navigate back, it fails to clear
952 the last-indented variable, so it thinks you've already hit TAB once,
953 and performs the indent. A full solution would involve getting on the
954 point-motion hooks for the entire buffer. If we come across another
955 use cases that requires watching point motion, I'll consider doing it.
956
957 If you set this variable to nil, then the TAB key will always change
958 the indentation of the current line, if more than one alternative
959 indentation spot exists."
960 :type 'boolean
961 :group 'js2-mode)
962
963 (defvar js2-indent-hook nil
964 "A hook for user-defined indentation rules.
965
966 Functions on this hook should expect two arguments: (LIST INDEX)
967 The LIST argument is the list of computed indentation points for
968 the current line. INDEX is the list index of the indentation point
969 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
970 indent function is not going to change the current line indentation.
971
972 If a hook function on this list returns a non-nil value, then
973 `js2-bounce-indent' assumes the hook function has performed its own
974 indentation, and will do nothing. If all hook functions on the list
975 return nil, then `js2-bounce-indent' will use its computed indentation
976 and reindent the line.
977
978 When hook functions on this hook list are called, the variable
979 `js2-mode-ast' may or may not be set, depending on whether the
980 parse tree is available. If the variable is nil, you can pass a
981 callback to `js2-mode-wait-for-parse', and your callback will be
982 called after the new parse tree is built. This can take some time
983 in large files.")
984
985 (defface js2-warning
986 `((((class color) (background light))
987 (:underline "orange"))
988 (((class color) (background dark))
989 (:underline "orange"))
990 (t (:underline t)))
991 "Face for JavaScript warnings."
992 :group 'js2-mode)
993
994 (defface js2-error
995 `((((class color) (background light))
996 (:foreground "red"))
997 (((class color) (background dark))
998 (:foreground "red"))
999 (t (:foreground "red")))
1000 "Face for JavaScript errors."
1001 :group 'js2-mode)
1002
1003 (defface js2-jsdoc-tag
1004 '((t :foreground "SlateGray"))
1005 "Face used to highlight @whatever tags in jsdoc comments."
1006 :group 'js2-mode)
1007
1008 (defface js2-jsdoc-type
1009 '((t :foreground "SteelBlue"))
1010 "Face used to highlight {FooBar} types in jsdoc comments."
1011 :group 'js2-mode)
1012
1013 (defface js2-jsdoc-value
1014 '((t :foreground "PeachPuff3"))
1015 "Face used to highlight tag values in jsdoc comments."
1016 :group 'js2-mode)
1017
1018 (defface js2-function-param
1019 '((t :foreground "SeaGreen"))
1020 "Face used to highlight function parameters in javascript."
1021 :group 'js2-mode)
1022
1023 (defface js2-function-call
1024 '((t :inherit default))
1025 "Face used to highlight function name in calls."
1026 :group 'js2-mode)
1027
1028 (defface js2-object-property
1029 '((t :inherit default))
1030 "Face used to highlight named property in object literal."
1031 :group 'js2-mode)
1032
1033 (defface js2-instance-member
1034 '((t :foreground "DarkOrchid"))
1035 "Face used to highlight instance variables in javascript.
1036 Not currently used."
1037 :group 'js2-mode)
1038
1039 (defface js2-private-member
1040 '((t :foreground "PeachPuff3"))
1041 "Face used to highlight calls to private methods in javascript.
1042 Not currently used."
1043 :group 'js2-mode)
1044
1045 (defface js2-private-function-call
1046 '((t :foreground "goldenrod"))
1047 "Face used to highlight calls to private functions in javascript.
1048 Not currently used."
1049 :group 'js2-mode)
1050
1051 (defface js2-jsdoc-html-tag-name
1052 '((((class color) (min-colors 88) (background light))
1053 (:foreground "rosybrown"))
1054 (((class color) (min-colors 8) (background dark))
1055 (:foreground "yellow"))
1056 (((class color) (min-colors 8) (background light))
1057 (:foreground "magenta")))
1058 "Face used to highlight jsdoc html tag names"
1059 :group 'js2-mode)
1060
1061 (defface js2-jsdoc-html-tag-delimiter
1062 '((((class color) (min-colors 88) (background light))
1063 (:foreground "dark khaki"))
1064 (((class color) (min-colors 8) (background dark))
1065 (:foreground "green"))
1066 (((class color) (min-colors 8) (background light))
1067 (:foreground "green")))
1068 "Face used to highlight brackets in jsdoc html tags."
1069 :group 'js2-mode)
1070
1071 (defface js2-external-variable
1072 '((t :foreground "orange"))
1073 "Face used to highlight undeclared variable identifiers.")
1074
1075 (defcustom js2-init-hook nil
1076 "List of functions to be called after `js2-mode' or
1077 `js2-minor-mode' has initialized all variables, before parsing
1078 the buffer for the first time."
1079 :type 'hook
1080 :group 'js2-mode
1081 :version "20130608")
1082
1083 (defcustom js2-post-parse-callbacks nil
1084 "List of callback functions invoked after parsing finishes.
1085 Currently, the main use for this function is to add synthetic
1086 declarations to `js2-recorded-identifiers', which see."
1087 :type 'hook
1088 :group 'js2-mode)
1089
1090 (defcustom js2-build-imenu-callbacks nil
1091 "List of functions called during Imenu index generation.
1092 It's a good place to add additional entries to it, using
1093 `js2-record-imenu-entry'."
1094 :type 'hook
1095 :group 'js2-mode)
1096
1097 (defcustom js2-highlight-external-variables t
1098 "Non-nil to highlight undeclared variable identifiers.
1099 An undeclared variable is any variable not declared with var or let
1100 in the current scope or any lexically enclosing scope. If you use
1101 such a variable, then you are either expecting it to originate from
1102 another file, or you've got a potential bug."
1103 :type 'boolean
1104 :group 'js2-mode)
1105
1106 (defcustom js2-warn-about-unused-function-arguments nil
1107 "Non-nil to treat function arguments like declared-but-unused variables."
1108 :type 'booleanp
1109 :group 'js2-mode)
1110
1111 (defcustom js2-include-jslint-globals t
1112 "Non-nil to include the identifiers from JSLint global
1113 declaration (see http://www.jslint.com/lint.html#global) in the
1114 buffer-local externs list. See `js2-additional-externs' for more
1115 information."
1116 :type 'boolean
1117 :group 'js2-mode)
1118
1119 (defvar js2-mode-map
1120 (let ((map (make-sparse-keymap)))
1121 (define-key map [mouse-1] #'js2-mode-show-node)
1122 (define-key map (kbd "M-j") #'js2-line-break)
1123 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1124 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1125 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1126 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1127 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1128 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1129 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1130 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1131 (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
1132
1133 (define-key map [menu-bar javascript]
1134 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1135
1136 (define-key map [menu-bar javascript customize-js2-mode]
1137 '(menu-item "Customize js2-mode" js2-mode-customize
1138 :help "Customize the behavior of this mode"))
1139
1140 (define-key map [menu-bar javascript js2-force-refresh]
1141 '(menu-item "Force buffer refresh" js2-mode-reset
1142 :help "Re-parse the buffer from scratch"))
1143
1144 (define-key map [menu-bar javascript separator-2]
1145 '("--"))
1146
1147 (define-key map [menu-bar javascript next-error]
1148 '(menu-item "Next warning or error" next-error
1149 :enabled (and js2-mode-ast
1150 (or (js2-ast-root-errors js2-mode-ast)
1151 (js2-ast-root-warnings js2-mode-ast)))
1152 :help "Move to next warning or error"))
1153
1154 (define-key map [menu-bar javascript display-errors]
1155 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1156 :visible (not js2-mode-show-parse-errors)
1157 :help "Turn on display of warnings and errors"))
1158
1159 (define-key map [menu-bar javascript hide-errors]
1160 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1161 :visible js2-mode-show-parse-errors
1162 :help "Turn off display of warnings and errors"))
1163
1164 (define-key map [menu-bar javascript separator-1]
1165 '("--"))
1166
1167 (define-key map [menu-bar javascript js2-toggle-function]
1168 '(menu-item "Show/collapse element" js2-mode-toggle-element
1169 :help "Hide or show function body or comment"))
1170
1171 (define-key map [menu-bar javascript show-comments]
1172 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1173 :visible js2-mode-comments-hidden
1174 :help "Expand all hidden block comments"))
1175
1176 (define-key map [menu-bar javascript hide-comments]
1177 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1178 :visible (not js2-mode-comments-hidden)
1179 :help "Show block comments as /*...*/"))
1180
1181 (define-key map [menu-bar javascript show-all-functions]
1182 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1183 :visible js2-mode-functions-hidden
1184 :help "Expand all hidden function bodies"))
1185
1186 (define-key map [menu-bar javascript hide-all-functions]
1187 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1188 :visible (not js2-mode-functions-hidden)
1189 :help "Show {...} for all top-level function bodies"))
1190
1191 map)
1192 "Keymap used in `js2-mode' buffers.")
1193
1194 (defcustom js2-bounce-indent-p nil
1195 "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
1196 They will augment the default indent-line behavior with cycling
1197 among several computed alternatives. See the function
1198 `js2-bounce-indent' for details. The above commands will be
1199 bound to TAB and backtab."
1200 :type 'boolean
1201 :group 'js2-mode
1202 :set (lambda (sym value)
1203 (set-default sym value)
1204 (let ((map js2-mode-map))
1205 (if (not value)
1206 (progn
1207 (define-key map "\t" nil)
1208 (define-key map (kbd "<backtab>") nil))
1209 (define-key map "\t" #'js2-indent-bounce)
1210 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
1211
1212 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1213
1214 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1215 "Matches a //-comment line. Must be first non-whitespace on line.
1216 First match-group is the leading whitespace.")
1217
1218 (defvar js2-mode-hook nil)
1219
1220 (js2-deflocal js2-mode-ast nil "Private variable.")
1221 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1222 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1223 (js2-deflocal js2-mode-parsing nil "Private variable.")
1224 (js2-deflocal js2-mode-node-overlay nil)
1225
1226 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1227 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1228
1229 (js2-deflocal js2-mode-fontifications nil "Private variable")
1230 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1231 (js2-deflocal js2-imenu-recorder nil "Private variable")
1232 (js2-deflocal js2-imenu-function-map nil "Private variable")
1233
1234 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1235 "Non-nil to emit status messages during parsing.")
1236
1237 (defvar js2-mode-functions-hidden nil "Private variable.")
1238 (defvar js2-mode-comments-hidden nil "Private variable.")
1239
1240 (defvar js2-mode-syntax-table
1241 (let ((table (make-syntax-table)))
1242 (c-populate-syntax-table table)
1243 (modify-syntax-entry ?` "\"" table)
1244 table)
1245 "Syntax table used in `js2-mode' buffers.")
1246
1247 (defvar js2-mode-abbrev-table nil
1248 "Abbrev table in use in `js2-mode' buffers.")
1249 (define-abbrev-table 'js2-mode-abbrev-table ())
1250
1251 (defvar js2-mode-pending-parse-callbacks nil
1252 "List of functions waiting to be notified that parse is finished.")
1253
1254 (defvar js2-mode-last-indented-line -1)
1255
1256 ;;; Localizable error and warning messages
1257
1258 ;; Messages are copied from Rhino's Messages.properties.
1259 ;; Many of the Java-specific messages have been elided.
1260 ;; Add any js2-specific ones at the end, so we can keep
1261 ;; this file synced with changes to Rhino's.
1262
1263 (defvar js2-message-table
1264 (make-hash-table :test 'equal :size 250)
1265 "Contains localized messages for `js2-mode'.")
1266
1267 ;; TODO(stevey): construct this table at compile-time.
1268 (defmacro js2-msg (key &rest strings)
1269 `(puthash ,key (concat ,@strings)
1270 js2-message-table))
1271
1272 (defun js2-get-msg (msg-key)
1273 "Look up a localized message.
1274 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1275 the correct number of ARGS must be provided."
1276 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1277 (args (if (listp msg-key) (cdr msg-key)))
1278 (msg (gethash key js2-message-table)))
1279 (if msg
1280 (apply #'format msg args)
1281 key))) ; default to showing the key
1282
1283 (js2-msg "msg.dup.parms"
1284 "Duplicate parameter name '%s'.")
1285
1286 (js2-msg "msg.too.big.jump"
1287 "Program too complex: jump offset too big.")
1288
1289 (js2-msg "msg.too.big.index"
1290 "Program too complex: internal index exceeds 64K limit.")
1291
1292 (js2-msg "msg.while.compiling.fn"
1293 "Encountered code generation error while compiling function '%s': %s")
1294
1295 (js2-msg "msg.while.compiling.script"
1296 "Encountered code generation error while compiling script: %s")
1297
1298 ;; Context
1299 (js2-msg "msg.ctor.not.found"
1300 "Constructor for '%s' not found.")
1301
1302 (js2-msg "msg.not.ctor"
1303 "'%s' is not a constructor.")
1304
1305 ;; FunctionObject
1306 (js2-msg "msg.varargs.ctor"
1307 "Method or constructor '%s' must be static "
1308 "with the signature (Context cx, Object[] args, "
1309 "Function ctorObj, boolean inNewExpr) "
1310 "to define a variable arguments constructor.")
1311
1312 (js2-msg "msg.varargs.fun"
1313 "Method '%s' must be static with the signature "
1314 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1315 "to define a variable arguments function.")
1316
1317 (js2-msg "msg.incompat.call"
1318 "Method '%s' called on incompatible object.")
1319
1320 (js2-msg "msg.bad.parms"
1321 "Unsupported parameter type '%s' in method '%s'.")
1322
1323 (js2-msg "msg.bad.method.return"
1324 "Unsupported return type '%s' in method '%s'.")
1325
1326 (js2-msg "msg.bad.ctor.return"
1327 "Construction of objects of type '%s' is not supported.")
1328
1329 (js2-msg "msg.no.overload"
1330 "Method '%s' occurs multiple times in class '%s'.")
1331
1332 (js2-msg "msg.method.not.found"
1333 "Method '%s' not found in '%s'.")
1334
1335 ;; IRFactory
1336
1337 (js2-msg "msg.bad.for.in.lhs"
1338 "Invalid left-hand side of for..in loop.")
1339
1340 (js2-msg "msg.mult.index"
1341 "Only one variable allowed in for..in loop.")
1342
1343 (js2-msg "msg.bad.for.in.destruct"
1344 "Left hand side of for..in loop must be an array of "
1345 "length 2 to accept key/value pair.")
1346
1347 (js2-msg "msg.cant.convert"
1348 "Can't convert to type '%s'.")
1349
1350 (js2-msg "msg.bad.assign.left"
1351 "Invalid assignment left-hand side.")
1352
1353 (js2-msg "msg.bad.decr"
1354 "Invalid decrement operand.")
1355
1356 (js2-msg "msg.bad.incr"
1357 "Invalid increment operand.")
1358
1359 (js2-msg "msg.bad.yield"
1360 "yield must be in a function.")
1361
1362 (js2-msg "msg.yield.parenthesized"
1363 "yield expression must be parenthesized.")
1364
1365 ;; NativeGlobal
1366 (js2-msg "msg.cant.call.indirect"
1367 "Function '%s' must be called directly, and not by way of a "
1368 "function of another name.")
1369
1370 (js2-msg "msg.eval.nonstring"
1371 "Calling eval() with anything other than a primitive "
1372 "string value will simply return the value. "
1373 "Is this what you intended?")
1374
1375 (js2-msg "msg.eval.nonstring.strict"
1376 "Calling eval() with anything other than a primitive "
1377 "string value is not allowed in strict mode.")
1378
1379 (js2-msg "msg.bad.destruct.op"
1380 "Invalid destructuring assignment operator")
1381
1382 ;; NativeCall
1383 (js2-msg "msg.only.from.new"
1384 "'%s' may only be invoked from a `new' expression.")
1385
1386 (js2-msg "msg.deprec.ctor"
1387 "The '%s' constructor is deprecated.")
1388
1389 ;; NativeFunction
1390 (js2-msg "msg.no.function.ref.found"
1391 "no source found to decompile function reference %s")
1392
1393 (js2-msg "msg.arg.isnt.array"
1394 "second argument to Function.prototype.apply must be an array")
1395
1396 ;; NativeGlobal
1397 (js2-msg "msg.bad.esc.mask"
1398 "invalid string escape mask")
1399
1400 ;; NativeRegExp
1401 (js2-msg "msg.bad.quant"
1402 "Invalid quantifier %s")
1403
1404 (js2-msg "msg.overlarge.backref"
1405 "Overly large back reference %s")
1406
1407 (js2-msg "msg.overlarge.min"
1408 "Overly large minimum %s")
1409
1410 (js2-msg "msg.overlarge.max"
1411 "Overly large maximum %s")
1412
1413 (js2-msg "msg.zero.quant"
1414 "Zero quantifier %s")
1415
1416 (js2-msg "msg.max.lt.min"
1417 "Maximum %s less than minimum")
1418
1419 (js2-msg "msg.unterm.quant"
1420 "Unterminated quantifier %s")
1421
1422 (js2-msg "msg.unterm.paren"
1423 "Unterminated parenthetical %s")
1424
1425 (js2-msg "msg.unterm.class"
1426 "Unterminated character class %s")
1427
1428 (js2-msg "msg.bad.range"
1429 "Invalid range in character class.")
1430
1431 (js2-msg "msg.trail.backslash"
1432 "Trailing \\ in regular expression.")
1433
1434 (js2-msg "msg.re.unmatched.right.paren"
1435 "unmatched ) in regular expression.")
1436
1437 (js2-msg "msg.no.regexp"
1438 "Regular expressions are not available.")
1439
1440 (js2-msg "msg.bad.backref"
1441 "back-reference exceeds number of capturing parentheses.")
1442
1443 (js2-msg "msg.bad.regexp.compile"
1444 "Only one argument may be specified if the first "
1445 "argument to RegExp.prototype.compile is a RegExp object.")
1446
1447 ;; Parser
1448 (js2-msg "msg.got.syntax.errors"
1449 "Compilation produced %s syntax errors.")
1450
1451 (js2-msg "msg.var.redecl"
1452 "TypeError: redeclaration of var %s.")
1453
1454 (js2-msg "msg.const.redecl"
1455 "TypeError: redeclaration of const %s.")
1456
1457 (js2-msg "msg.let.redecl"
1458 "TypeError: redeclaration of variable %s.")
1459
1460 (js2-msg "msg.parm.redecl"
1461 "TypeError: redeclaration of formal parameter %s.")
1462
1463 (js2-msg "msg.fn.redecl"
1464 "TypeError: redeclaration of function %s.")
1465
1466 (js2-msg "msg.let.decl.not.in.block"
1467 "SyntaxError: let declaration not directly within block")
1468
1469 (js2-msg "msg.mod.import.decl.at.top.level"
1470 "SyntaxError: import declarations may only appear at the top level")
1471
1472 (js2-msg "msg.mod.as.after.reserved.word"
1473 "SyntaxError: missing keyword 'as' after reserved word %s")
1474
1475 (js2-msg "msg.mod.rc.after.import.spec.list"
1476 "SyntaxError: missing '}' after module specifier list")
1477
1478 (js2-msg "msg.mod.from.after.import.spec.set"
1479 "SyntaxError: missing keyword 'from' after import specifier set")
1480
1481 (js2-msg "msg.mod.declaration.after.import"
1482 "SyntaxError: missing declaration after 'import' keyword")
1483
1484 (js2-msg "msg.mod.spec.after.from"
1485 "SyntaxError: missing module specifier after 'from' keyword")
1486
1487 (js2-msg "msg.mod.export.decl.at.top.level"
1488 "SyntaxError: export declarations may only appear at top level")
1489
1490 (js2-msg "msg.mod.rc.after.export.spec.list"
1491 "SyntaxError: missing '}' after export specifier list")
1492
1493 ;; NodeTransformer
1494 (js2-msg "msg.dup.label"
1495 "duplicated label")
1496
1497 (js2-msg "msg.undef.label"
1498 "undefined label")
1499
1500 (js2-msg "msg.bad.break"
1501 "unlabelled break must be inside loop or switch")
1502
1503 (js2-msg "msg.continue.outside"
1504 "continue must be inside loop")
1505
1506 (js2-msg "msg.continue.nonloop"
1507 "continue can only use labels of iteration statements")
1508
1509 (js2-msg "msg.bad.throw.eol"
1510 "Line terminator is not allowed between the throw "
1511 "keyword and throw expression.")
1512
1513 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1514 "function statement requires a name")
1515
1516 (js2-msg "msg.no.paren.parms"
1517 "missing ( before function parameters.")
1518
1519 (js2-msg "msg.no.parm"
1520 "missing formal parameter")
1521
1522 (js2-msg "msg.no.paren.after.parms"
1523 "missing ) after formal parameters")
1524
1525 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1526 "parameter without default follows parameter with default")
1527
1528 (js2-msg "msg.param.after.rest" ; added by js2-mode
1529 "parameter after rest parameter")
1530
1531 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1532 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1533
1534 (js2-msg "msg.no.brace.body"
1535 "missing '{' before function body")
1536
1537 (js2-msg "msg.no.brace.after.body"
1538 "missing } after function body")
1539
1540 (js2-msg "msg.no.paren.cond"
1541 "missing ( before condition")
1542
1543 (js2-msg "msg.no.paren.after.cond"
1544 "missing ) after condition")
1545
1546 (js2-msg "msg.no.semi.stmt"
1547 "missing ; before statement")
1548
1549 (js2-msg "msg.missing.semi"
1550 "missing ; after statement")
1551
1552 (js2-msg "msg.no.name.after.dot"
1553 "missing name after . operator")
1554
1555 (js2-msg "msg.no.name.after.coloncolon"
1556 "missing name after :: operator")
1557
1558 (js2-msg "msg.no.name.after.dotdot"
1559 "missing name after .. operator")
1560
1561 (js2-msg "msg.no.name.after.xmlAttr"
1562 "missing name after .@")
1563
1564 (js2-msg "msg.no.bracket.index"
1565 "missing ] in index expression")
1566
1567 (js2-msg "msg.no.paren.switch"
1568 "missing ( before switch expression")
1569
1570 (js2-msg "msg.no.paren.after.switch"
1571 "missing ) after switch expression")
1572
1573 (js2-msg "msg.no.brace.switch"
1574 "missing '{' before switch body")
1575
1576 (js2-msg "msg.bad.switch"
1577 "invalid switch statement")
1578
1579 (js2-msg "msg.no.colon.case"
1580 "missing : after case expression")
1581
1582 (js2-msg "msg.double.switch.default"
1583 "double default label in the switch statement")
1584
1585 (js2-msg "msg.no.while.do"
1586 "missing while after do-loop body")
1587
1588 (js2-msg "msg.no.paren.for"
1589 "missing ( after for")
1590
1591 (js2-msg "msg.no.semi.for"
1592 "missing ; after for-loop initializer")
1593
1594 (js2-msg "msg.no.semi.for.cond"
1595 "missing ; after for-loop condition")
1596
1597 (js2-msg "msg.in.after.for.name"
1598 "missing in or of after for")
1599
1600 (js2-msg "msg.no.paren.for.ctrl"
1601 "missing ) after for-loop control")
1602
1603 (js2-msg "msg.no.paren.with"
1604 "missing ( before with-statement object")
1605
1606 (js2-msg "msg.no.paren.after.with"
1607 "missing ) after with-statement object")
1608
1609 (js2-msg "msg.no.with.strict"
1610 "with statements not allowed in strict mode")
1611
1612 (js2-msg "msg.no.paren.after.let"
1613 "missing ( after let")
1614
1615 (js2-msg "msg.no.paren.let"
1616 "missing ) after variable list")
1617
1618 (js2-msg "msg.no.curly.let"
1619 "missing } after let statement")
1620
1621 (js2-msg "msg.bad.return"
1622 "invalid return")
1623
1624 (js2-msg "msg.no.brace.block"
1625 "missing } in compound statement")
1626
1627 (js2-msg "msg.bad.label"
1628 "invalid label")
1629
1630 (js2-msg "msg.bad.var"
1631 "missing variable name")
1632
1633 (js2-msg "msg.bad.var.init"
1634 "invalid variable initialization")
1635
1636 (js2-msg "msg.no.colon.cond"
1637 "missing : in conditional expression")
1638
1639 (js2-msg "msg.no.paren.arg"
1640 "missing ) after argument list")
1641
1642 (js2-msg "msg.no.bracket.arg"
1643 "missing ] after element list")
1644
1645 (js2-msg "msg.bad.prop"
1646 "invalid property id")
1647
1648 (js2-msg "msg.no.colon.prop"
1649 "missing : after property id")
1650
1651 (js2-msg "msg.no.brace.prop"
1652 "missing } after property list")
1653
1654 (js2-msg "msg.no.paren"
1655 "missing ) in parenthetical")
1656
1657 (js2-msg "msg.reserved.id"
1658 "'%s' is a reserved identifier")
1659
1660 (js2-msg "msg.no.paren.catch"
1661 "missing ( before catch-block condition")
1662
1663 (js2-msg "msg.bad.catchcond"
1664 "invalid catch block condition")
1665
1666 (js2-msg "msg.catch.unreachable"
1667 "any catch clauses following an unqualified catch are unreachable")
1668
1669 (js2-msg "msg.no.brace.try"
1670 "missing '{' before try block")
1671
1672 (js2-msg "msg.no.brace.catchblock"
1673 "missing '{' before catch-block body")
1674
1675 (js2-msg "msg.try.no.catchfinally"
1676 "'try' without 'catch' or 'finally'")
1677
1678 (js2-msg "msg.no.return.value"
1679 "function %s does not always return a value")
1680
1681 (js2-msg "msg.anon.no.return.value"
1682 "anonymous function does not always return a value")
1683
1684 (js2-msg "msg.return.inconsistent"
1685 "return statement is inconsistent with previous usage")
1686
1687 (js2-msg "msg.generator.returns"
1688 "TypeError: legacy generator function '%s' returns a value")
1689
1690 (js2-msg "msg.anon.generator.returns"
1691 "TypeError: anonymous legacy generator function returns a value")
1692
1693 (js2-msg "msg.syntax"
1694 "syntax error")
1695
1696 (js2-msg "msg.unexpected.eof"
1697 "Unexpected end of file")
1698
1699 (js2-msg "msg.XML.bad.form"
1700 "illegally formed XML syntax")
1701
1702 (js2-msg "msg.XML.not.available"
1703 "XML runtime not available")
1704
1705 (js2-msg "msg.too.deep.parser.recursion"
1706 "Too deep recursion while parsing")
1707
1708 (js2-msg "msg.no.side.effects"
1709 "Code has no side effects")
1710
1711 (js2-msg "msg.extra.trailing.comma"
1712 "Trailing comma is not supported in some browsers")
1713
1714 (js2-msg "msg.array.trailing.comma"
1715 "Trailing comma yields different behavior across browsers")
1716
1717 (js2-msg "msg.equal.as.assign"
1718 (concat "Test for equality (==) mistyped as assignment (=)?"
1719 " (parenthesize to suppress warning)"))
1720
1721 (js2-msg "msg.var.hides.arg"
1722 "Variable %s hides argument")
1723
1724 (js2-msg "msg.destruct.assign.no.init"
1725 "Missing = in destructuring declaration")
1726
1727 (js2-msg "msg.init.no.destruct"
1728 "Binding initializer not in destructuring assignment")
1729
1730 (js2-msg "msg.no.octal.strict"
1731 "Octal numbers prohibited in strict mode.")
1732
1733 (js2-msg "msg.dup.obj.lit.prop.strict"
1734 "Property '%s' already defined in this object literal.")
1735
1736 (js2-msg "msg.dup.param.strict"
1737 "Parameter '%s' already declared in this function.")
1738
1739 (js2-msg "msg.bad.id.strict"
1740 "'%s' is not a valid identifier for this use in strict mode.")
1741
1742 ;; ScriptRuntime
1743 (js2-msg "msg.no.properties"
1744 "%s has no properties.")
1745
1746 (js2-msg "msg.invalid.iterator"
1747 "Invalid iterator value")
1748
1749 (js2-msg "msg.iterator.primitive"
1750 "__iterator__ returned a primitive value")
1751
1752 (js2-msg "msg.assn.create.strict"
1753 "Assignment to undeclared variable %s")
1754
1755 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1756 "Undeclared variable or function '%s'")
1757
1758 (js2-msg "msg.unused.variable" ; added by js2-mode
1759 "Unused variable or function '%s'")
1760
1761 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1762 "Variable '%s' referenced but never initialized")
1763
1764 (js2-msg "msg.ref.undefined.prop"
1765 "Reference to undefined property '%s'")
1766
1767 (js2-msg "msg.prop.not.found"
1768 "Property %s not found.")
1769
1770 (js2-msg "msg.invalid.type"
1771 "Invalid JavaScript value of type %s")
1772
1773 (js2-msg "msg.primitive.expected"
1774 "Primitive type expected (had %s instead)")
1775
1776 (js2-msg "msg.namespace.expected"
1777 "Namespace object expected to left of :: (found %s instead)")
1778
1779 (js2-msg "msg.null.to.object"
1780 "Cannot convert null to an object.")
1781
1782 (js2-msg "msg.undef.to.object"
1783 "Cannot convert undefined to an object.")
1784
1785 (js2-msg "msg.cyclic.value"
1786 "Cyclic %s value not allowed.")
1787
1788 (js2-msg "msg.is.not.defined"
1789 "'%s' is not defined.")
1790
1791 (js2-msg "msg.undef.prop.read"
1792 "Cannot read property '%s' from %s")
1793
1794 (js2-msg "msg.undef.prop.write"
1795 "Cannot set property '%s' of %s to '%s'")
1796
1797 (js2-msg "msg.undef.prop.delete"
1798 "Cannot delete property '%s' of %s")
1799
1800 (js2-msg "msg.undef.method.call"
1801 "Cannot call method '%s' of %s")
1802
1803 (js2-msg "msg.undef.with"
1804 "Cannot apply 'with' to %s")
1805
1806 (js2-msg "msg.isnt.function"
1807 "%s is not a function, it is %s.")
1808
1809 (js2-msg "msg.isnt.function.in"
1810 "Cannot call property %s in object %s. "
1811 "It is not a function, it is '%s'.")
1812
1813 (js2-msg "msg.function.not.found"
1814 "Cannot find function %s.")
1815
1816 (js2-msg "msg.function.not.found.in"
1817 "Cannot find function %s in object %s.")
1818
1819 (js2-msg "msg.isnt.xml.object"
1820 "%s is not an xml object.")
1821
1822 (js2-msg "msg.no.ref.to.get"
1823 "%s is not a reference to read reference value.")
1824
1825 (js2-msg "msg.no.ref.to.set"
1826 "%s is not a reference to set reference value to %s.")
1827
1828 (js2-msg "msg.no.ref.from.function"
1829 "Function %s can not be used as the left-hand "
1830 "side of assignment or as an operand of ++ or -- operator.")
1831
1832 (js2-msg "msg.bad.default.value"
1833 "Object's getDefaultValue() method returned an object.")
1834
1835 (js2-msg "msg.instanceof.not.object"
1836 "Can't use instanceof on a non-object.")
1837
1838 (js2-msg "msg.instanceof.bad.prototype"
1839 "'prototype' property of %s is not an object.")
1840
1841 (js2-msg "msg.bad.radix"
1842 "illegal radix %s.")
1843
1844 ;; ScriptableObject
1845 (js2-msg "msg.default.value"
1846 "Cannot find default value for object.")
1847
1848 (js2-msg "msg.zero.arg.ctor"
1849 "Cannot load class '%s' which has no zero-parameter constructor.")
1850
1851 (js2-msg "msg.ctor.multiple.parms"
1852 "Can't define constructor or class %s since more than "
1853 "one constructor has multiple parameters.")
1854
1855 (js2-msg "msg.extend.scriptable"
1856 "%s must extend ScriptableObject in order to define property %s.")
1857
1858 (js2-msg "msg.bad.getter.parms"
1859 "In order to define a property, getter %s must have zero "
1860 "parameters or a single ScriptableObject parameter.")
1861
1862 (js2-msg "msg.obj.getter.parms"
1863 "Expected static or delegated getter %s to take "
1864 "a ScriptableObject parameter.")
1865
1866 (js2-msg "msg.getter.static"
1867 "Getter and setter must both be static or neither be static.")
1868
1869 (js2-msg "msg.setter.return"
1870 "Setter must have void return type: %s")
1871
1872 (js2-msg "msg.setter2.parms"
1873 "Two-parameter setter must take a ScriptableObject as "
1874 "its first parameter.")
1875
1876 (js2-msg "msg.setter1.parms"
1877 "Expected single parameter setter for %s")
1878
1879 (js2-msg "msg.setter2.expected"
1880 "Expected static or delegated setter %s to take two parameters.")
1881
1882 (js2-msg "msg.setter.parms"
1883 "Expected either one or two parameters for setter.")
1884
1885 (js2-msg "msg.setter.bad.type"
1886 "Unsupported parameter type '%s' in setter '%s'.")
1887
1888 (js2-msg "msg.add.sealed"
1889 "Cannot add a property to a sealed object: %s.")
1890
1891 (js2-msg "msg.remove.sealed"
1892 "Cannot remove a property from a sealed object: %s.")
1893
1894 (js2-msg "msg.modify.sealed"
1895 "Cannot modify a property of a sealed object: %s.")
1896
1897 (js2-msg "msg.modify.readonly"
1898 "Cannot modify readonly property: %s.")
1899
1900 ;; TokenStream
1901 (js2-msg "msg.missing.exponent"
1902 "missing exponent")
1903
1904 (js2-msg "msg.caught.nfe"
1905 "number format error")
1906
1907 (js2-msg "msg.unterminated.string.lit"
1908 "unterminated string literal")
1909
1910 (js2-msg "msg.unterminated.comment"
1911 "unterminated comment")
1912
1913 (js2-msg "msg.unterminated.re.lit"
1914 "unterminated regular expression literal")
1915
1916 (js2-msg "msg.invalid.re.flag"
1917 "invalid flag after regular expression")
1918
1919 (js2-msg "msg.no.re.input.for"
1920 "no input for %s")
1921
1922 (js2-msg "msg.illegal.character"
1923 "illegal character")
1924
1925 (js2-msg "msg.invalid.escape"
1926 "invalid Unicode escape sequence")
1927
1928 (js2-msg "msg.bad.namespace"
1929 "not a valid default namespace statement. "
1930 "Syntax is: default xml namespace = EXPRESSION;")
1931
1932 ;; TokensStream warnings
1933 (js2-msg "msg.bad.octal.literal"
1934 "illegal octal literal digit %s; "
1935 "interpreting it as a decimal digit")
1936
1937 (js2-msg "msg.missing.hex.digits"
1938 "missing hexadecimal digits after '0x'")
1939
1940 (js2-msg "msg.missing.binary.digits"
1941 "missing binary digits after '0b'")
1942
1943 (js2-msg "msg.missing.octal.digits"
1944 "missing octal digits after '0o'")
1945
1946 (js2-msg "msg.script.is.not.constructor"
1947 "Script objects are not constructors.")
1948
1949 ;; Arrays
1950 (js2-msg "msg.arraylength.bad"
1951 "Inappropriate array length.")
1952
1953 ;; Arrays
1954 (js2-msg "msg.arraylength.too.big"
1955 "Array length %s exceeds supported capacity limit.")
1956
1957 ;; URI
1958 (js2-msg "msg.bad.uri"
1959 "Malformed URI sequence.")
1960
1961 ;; Number
1962 (js2-msg "msg.bad.precision"
1963 "Precision %s out of range.")
1964
1965 ;; NativeGenerator
1966 (js2-msg "msg.send.newborn"
1967 "Attempt to send value to newborn generator")
1968
1969 (js2-msg "msg.already.exec.gen"
1970 "Already executing generator")
1971
1972 (js2-msg "msg.StopIteration.invalid"
1973 "StopIteration may not be changed to an arbitrary object.")
1974
1975 ;; Interpreter
1976 (js2-msg "msg.yield.closing"
1977 "Yield from closing generator")
1978
1979 ;; Classes
1980 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1981 "class statement requires a name")
1982
1983 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1984 "unexpected ',' between class properties")
1985
1986 (js2-msg "msg.unexpected.static" ; added by js2-mode
1987 "unexpected 'static'")
1988
1989 (js2-msg "msg.missing.extends" ; added by js2-mode
1990 "name is required after extends")
1991
1992 (js2-msg "msg.no.brace.class" ; added by js2-mode
1993 "missing '{' before class body")
1994
1995 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1996 "missing ']' after computed property expression")
1997
1998 ;;; Tokens Buffer
1999
2000 (defconst js2-ti-max-lookahead 2)
2001 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2002
2003 (defun js2-new-token (offset)
2004 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2005 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2006 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2007 token))
2008
2009 (defsubst js2-current-token ()
2010 (aref js2-ti-tokens js2-ti-tokens-cursor))
2011
2012 (defsubst js2-current-token-string ()
2013 (js2-token-string (js2-current-token)))
2014
2015 (defsubst js2-current-token-type ()
2016 (js2-token-type (js2-current-token)))
2017
2018 (defsubst js2-current-token-beg ()
2019 (js2-token-beg (js2-current-token)))
2020
2021 (defsubst js2-current-token-end ()
2022 (js2-token-end (js2-current-token)))
2023
2024 (defun js2-current-token-len ()
2025 (let ((token (js2-current-token)))
2026 (- (js2-token-end token)
2027 (js2-token-beg token))))
2028
2029 (defun js2-ts-seek (state)
2030 (setq js2-ts-lineno (js2-ts-state-lineno state)
2031 js2-ts-cursor (js2-ts-state-cursor state)
2032 js2-ti-tokens (js2-ts-state-tokens state)
2033 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2034 js2-ti-lookahead (js2-ts-state-lookahead state)))
2035
2036 ;;; Utilities
2037
2038 (defun js2-delete-if (predicate list)
2039 "Remove all items satisfying PREDICATE in LIST."
2040 (cl-loop for item in list
2041 if (not (funcall predicate item))
2042 collect item))
2043
2044 (defun js2-position (element list)
2045 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2046 Returns nil if element is not found in the list."
2047 (let ((count 0)
2048 found)
2049 (while (and list (not found))
2050 (if (eq element (car list))
2051 (setq found t)
2052 (setq count (1+ count)
2053 list (cdr list))))
2054 (if found count)))
2055
2056 (defun js2-find-if (predicate list)
2057 "Find first item satisfying PREDICATE in LIST."
2058 (let (result)
2059 (while (and list (not result))
2060 (if (funcall predicate (car list))
2061 (setq result (car list)))
2062 (setq list (cdr list)))
2063 result))
2064
2065 (defmacro js2-time (form)
2066 "Evaluate FORM, discard result, and return elapsed time in sec."
2067 (declare (debug t))
2068 (let ((beg (make-symbol "--js2-time-beg--")))
2069 `(let ((,beg (current-time)))
2070 ,form
2071 (/ (truncate (* (- (float-time (current-time))
2072 (float-time ,beg))
2073 10000))
2074 10000.0))))
2075
2076 (defsubst js2-same-line (pos)
2077 "Return t if POS is on the same line as current point."
2078 (and (>= pos (point-at-bol))
2079 (<= pos (point-at-eol))))
2080
2081 (defun js2-code-bug ()
2082 "Signal an error when we encounter an unexpected code path."
2083 (error "failed assertion"))
2084
2085 (defsubst js2-record-text-property (beg end prop value)
2086 "Record a text property to set when parsing finishes."
2087 (push (list beg end prop value) js2-mode-deferred-properties))
2088
2089 ;; I'd like to associate errors with nodes, but for now the
2090 ;; easiest thing to do is get the context info from the last token.
2091 (defun js2-record-parse-error (msg &optional arg pos len)
2092 (push (list (list msg arg)
2093 (or pos (js2-current-token-beg))
2094 (or len (js2-current-token-len)))
2095 js2-parsed-errors))
2096
2097 (defun js2-report-error (msg &optional msg-arg pos len)
2098 "Signal a syntax error or record a parse error."
2099 (if js2-recover-from-parse-errors
2100 (js2-record-parse-error msg msg-arg pos len)
2101 (signal 'js2-syntax-error
2102 (list msg
2103 js2-ts-lineno
2104 (save-excursion
2105 (goto-char js2-ts-cursor)
2106 (current-column))
2107 js2-ts-hit-eof))))
2108
2109 (defun js2-report-warning (msg &optional msg-arg pos len face)
2110 (if js2-compiler-report-warning-as-error
2111 (js2-report-error msg msg-arg pos len)
2112 (push (list (list msg msg-arg)
2113 (or pos (js2-current-token-beg))
2114 (or len (js2-current-token-len))
2115 face)
2116 js2-parsed-warnings)))
2117
2118 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2119 (if js2-compiler-strict-mode
2120 (js2-report-warning msg-id msg-arg beg
2121 (and beg end (- end beg)))))
2122
2123 (put 'js2-syntax-error 'error-conditions
2124 '(error syntax-error js2-syntax-error))
2125 (put 'js2-syntax-error 'error-message "Syntax error")
2126
2127 (put 'js2-parse-error 'error-conditions
2128 '(error parse-error js2-parse-error))
2129 (put 'js2-parse-error 'error-message "Parse error")
2130
2131 (defmacro js2-clear-flag (flags flag)
2132 `(setq ,flags (logand ,flags (lognot ,flag))))
2133
2134 (defmacro js2-set-flag (flags flag)
2135 "Logical-or FLAG into FLAGS."
2136 `(setq ,flags (logior ,flags ,flag)))
2137
2138 (defsubst js2-flag-set-p (flags flag)
2139 (/= 0 (logand flags flag)))
2140
2141 (defsubst js2-flag-not-set-p (flags flag)
2142 (zerop (logand flags flag)))
2143
2144 ;;; AST struct and function definitions
2145
2146 ;; flags for ast node property 'member-type (used for e4x operators)
2147 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2148 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2149 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2150
2151 (defsubst js2-relpos (pos anchor)
2152 "Convert POS to be relative to ANCHOR.
2153 If POS is nil, returns nil."
2154 (and pos (- pos anchor)))
2155
2156 (defun js2-make-pad (indent)
2157 (if (zerop indent)
2158 ""
2159 (make-string (* indent js2-basic-offset) ? )))
2160
2161 (defun js2-visit-ast (node callback)
2162 "Visit every node in ast NODE with visitor CALLBACK.
2163
2164 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2165 called twice: once to visit the node, and again after all the node's
2166 children have been processed. The END-P argument is nil on the first
2167 call and non-nil on the second call. The return value of the callback
2168 affects the traversal: if non-nil, the children of NODE are processed.
2169 If the callback returns nil, or if the node has no children, then the
2170 callback is called immediately with a non-nil END-P argument.
2171
2172 The node traversal is approximately lexical-order, although there
2173 are currently no guarantees around this."
2174 (when node
2175 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2176 ;; visit the node
2177 (when (funcall callback node nil)
2178 ;; visit the kids
2179 (cond
2180 ((eq vfunc 'js2-visit-none)
2181 nil) ; don't even bother calling it
2182 ;; Each AST node type has to define a `js2-visitor' function
2183 ;; that takes a node and a callback, and calls `js2-visit-ast'
2184 ;; on each child of the node.
2185 (vfunc
2186 (funcall vfunc node callback))
2187 (t
2188 (error "%s does not define a visitor-traversal function"
2189 (aref node 0)))))
2190 ;; call the end-visit
2191 (funcall callback node t))))
2192
2193 (cl-defstruct (js2-node
2194 (:constructor nil)) ; abstract
2195 "Base AST node type."
2196 (type -1) ; token type
2197 (pos -1) ; start position of this AST node in parsed input
2198 (len 1) ; num characters spanned by the node
2199 props ; optional node property list (an alist)
2200 parent) ; link to parent node; null for root
2201
2202 (defsubst js2-node-get-prop (node prop &optional default)
2203 (or (cadr (assoc prop (js2-node-props node))) default))
2204
2205 (defsubst js2-node-set-prop (node prop value)
2206 (setf (js2-node-props node)
2207 (cons (list prop value) (js2-node-props node))))
2208
2209 (defun js2-fixup-starts (n nodes)
2210 "Adjust the start positions of NODES to be relative to N.
2211 Any node in the list may be nil, for convenience."
2212 (dolist (node nodes)
2213 (when node
2214 (setf (js2-node-pos node) (- (js2-node-pos node)
2215 (js2-node-pos n))))))
2216
2217 (defun js2-node-add-children (parent &rest nodes)
2218 "Set parent node of NODES to PARENT, and return PARENT.
2219 Does nothing if we're not recording parent links.
2220 If any given node in NODES is nil, doesn't record that link."
2221 (js2-fixup-starts parent nodes)
2222 (dolist (node nodes)
2223 (and node
2224 (setf (js2-node-parent node) parent))))
2225
2226 ;; Non-recursive since it's called a frightening number of times.
2227 (defun js2-node-abs-pos (n)
2228 (let ((pos (js2-node-pos n)))
2229 (while (setq n (js2-node-parent n))
2230 (setq pos (+ pos (js2-node-pos n))))
2231 pos))
2232
2233 (defsubst js2-node-abs-end (n)
2234 "Return absolute buffer position of end of N."
2235 (+ (js2-node-abs-pos n) (js2-node-len n)))
2236
2237 ;; It's important to make sure block nodes have a Lisp list for the
2238 ;; child nodes, to limit printing recursion depth in an AST that
2239 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2240 ;; a sufficiently large vector tree.
2241
2242 (cl-defstruct (js2-block-node
2243 (:include js2-node)
2244 (:constructor nil)
2245 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2246 (pos (js2-current-token-beg))
2247 len
2248 props
2249 kids)))
2250 "A block of statements."
2251 kids) ; a Lisp list of the child statement nodes
2252
2253 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2254 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2255
2256 (defun js2-visit-block (ast callback)
2257 "Visit the `js2-block-node' children of AST."
2258 (dolist (kid (js2-block-node-kids ast))
2259 (js2-visit-ast kid callback)))
2260
2261 (defun js2-print-block (n i)
2262 (let ((pad (js2-make-pad i)))
2263 (insert pad "{\n")
2264 (dolist (kid (js2-block-node-kids n))
2265 (js2-print-ast kid (1+ i)))
2266 (insert pad "}")))
2267
2268 (cl-defstruct (js2-scope
2269 (:include js2-block-node)
2270 (:constructor nil)
2271 (:constructor make-js2-scope (&key (type js2-BLOCK)
2272 (pos (js2-current-token-beg))
2273 len
2274 kids)))
2275 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2276 ;; I don't have one of those handy, so I'll use an alist for now.
2277 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2278 ;; and is much lighter-weight to construct (both CPU and mem).
2279 ;; The keys are interned strings (symbols) for faster lookup.
2280 ;; Should switch to hybrid alist/hashtable eventually.
2281 symbol-table ; an alist of (symbol . js2-symbol)
2282 parent-scope ; a `js2-scope'
2283 top) ; top-level `js2-scope' (script/function)
2284
2285 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2286 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2287
2288 (defun js2-node-get-enclosing-scope (node)
2289 "Return the innermost `js2-scope' node surrounding NODE.
2290 Returns nil if there is no enclosing scope node."
2291 (while (and (setq node (js2-node-parent node))
2292 (not (js2-scope-p node))))
2293 node)
2294
2295 (defun js2-get-defining-scope (scope name &optional point)
2296 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2297 Returns `js2-scope' in which NAME is defined, or nil if not found.
2298
2299 If POINT is non-nil, and if the found declaration type is
2300 `js2-LET', also check that the declaration node is before POINT."
2301 (let ((sym (if (symbolp name)
2302 name
2303 (intern name)))
2304 result
2305 (continue t))
2306 (while (and scope continue)
2307 (if (or
2308 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2309 (and entry
2310 (or (not point)
2311 (not (eq js2-LET (js2-symbol-decl-type entry)))
2312 (>= point
2313 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2314 (and (eq sym 'arguments)
2315 (js2-function-node-p scope)))
2316 (setq continue nil
2317 result scope)
2318 (setq scope (js2-scope-parent-scope scope))))
2319 result))
2320
2321 (defun js2-scope-get-symbol (scope name)
2322 "Return symbol table entry for NAME in SCOPE.
2323 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2324 (and (js2-scope-symbol-table scope)
2325 (cdr (assq (if (symbolp name)
2326 name
2327 (intern name))
2328 (js2-scope-symbol-table scope)))))
2329
2330 (defun js2-scope-put-symbol (scope name symbol)
2331 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2332 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2333 (let* ((table (js2-scope-symbol-table scope))
2334 (sym (if (symbolp name) name (intern name)))
2335 (entry (assq sym table)))
2336 (if entry
2337 (setcdr entry symbol)
2338 (push (cons sym symbol)
2339 (js2-scope-symbol-table scope)))))
2340
2341 (cl-defstruct (js2-symbol
2342 (:constructor nil)
2343 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2344 "A symbol table entry."
2345 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2346 ;; js2-LET, or js2-CONST
2347 decl-type
2348 name ; string
2349 ast-node) ; a `js2-node'
2350
2351 (cl-defstruct (js2-error-node
2352 (:include js2-node)
2353 (:constructor nil) ; silence emacs21 byte-compiler
2354 (:constructor make-js2-error-node (&key (type js2-ERROR)
2355 (pos (js2-current-token-beg))
2356 len)))
2357 "AST node representing a parse error.")
2358
2359 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2360 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2361
2362 (cl-defstruct (js2-script-node
2363 (:include js2-scope)
2364 (:constructor nil)
2365 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2366 (pos (js2-current-token-beg))
2367 len
2368 ;; FIXME: What are those?
2369 var-decls
2370 fun-decls)))
2371 functions ; Lisp list of nested functions
2372 regexps ; Lisp list of (string . flags)
2373 symbols ; alist (every symbol gets unique index)
2374 (param-count 0)
2375 var-names ; vector of string names
2376 consts ; bool-vector matching var-decls
2377 (temp-number 0)) ; for generating temp variables
2378
2379 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2380 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2381
2382 (defun js2-print-script (node indent)
2383 (dolist (kid (js2-block-node-kids node))
2384 (js2-print-ast kid indent)))
2385
2386 (cl-defstruct (js2-ast-root
2387 (:include js2-script-node)
2388 (:constructor nil)
2389 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2390 (pos (js2-current-token-beg))
2391 len
2392 buffer)))
2393 "The root node of a js2 AST."
2394 buffer ; the source buffer from which the code was parsed
2395 comments ; a Lisp list of comments, ordered by start position
2396 errors ; a Lisp list of errors found during parsing
2397 warnings ; a Lisp list of warnings found during parsing
2398 node-count) ; number of nodes in the tree, including the root
2399
2400 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2401 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2402
2403 (defun js2-visit-ast-root (ast callback)
2404 (dolist (kid (js2-ast-root-kids ast))
2405 (js2-visit-ast kid callback))
2406 (dolist (comment (js2-ast-root-comments ast))
2407 (js2-visit-ast comment callback)))
2408
2409 (cl-defstruct (js2-comment-node
2410 (:include js2-node)
2411 (:constructor nil)
2412 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2413 (pos (js2-current-token-beg))
2414 len
2415 format)))
2416 format) ; 'line, 'block, 'jsdoc or 'html
2417
2418 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2419 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2420
2421 (defun js2-print-comment (n i)
2422 ;; We really ought to link end-of-line comments to their nodes.
2423 ;; Or maybe we could add a new comment type, 'endline.
2424 (insert (js2-make-pad i)
2425 (js2-node-string n)))
2426
2427 (cl-defstruct (js2-expr-stmt-node
2428 (:include js2-node)
2429 (:constructor nil)
2430 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2431 (pos js2-ts-cursor)
2432 len
2433 expr)))
2434 "An expression statement."
2435 expr)
2436
2437 (defsubst js2-expr-stmt-node-set-has-result (node)
2438 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2439 (setf (js2-node-type node) js2-EXPR_RESULT))
2440
2441 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2442 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2443
2444 (defun js2-visit-expr-stmt-node (n v)
2445 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2446
2447 (defun js2-print-expr-stmt-node (n indent)
2448 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2449 (insert ";\n"))
2450
2451 (cl-defstruct (js2-loop-node
2452 (:include js2-scope)
2453 (:constructor nil))
2454 "Abstract supertype of loop nodes."
2455 body ; a `js2-block-node'
2456 lp ; position of left-paren, nil if omitted
2457 rp) ; position of right-paren, nil if omitted
2458
2459 (cl-defstruct (js2-do-node
2460 (:include js2-loop-node)
2461 (:constructor nil)
2462 (:constructor make-js2-do-node (&key (type js2-DO)
2463 (pos (js2-current-token-beg))
2464 len
2465 body
2466 condition
2467 while-pos
2468 lp
2469 rp)))
2470 "AST node for do-loop."
2471 condition ; while (expression)
2472 while-pos) ; buffer position of 'while' keyword
2473
2474 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2475 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2476
2477 (defun js2-visit-do-node (n v)
2478 (js2-visit-ast (js2-do-node-body n) v)
2479 (js2-visit-ast (js2-do-node-condition n) v))
2480
2481 (defun js2-print-do-node (n i)
2482 (let ((pad (js2-make-pad i)))
2483 (insert pad "do {\n")
2484 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2485 (js2-print-ast kid (1+ i)))
2486 (insert pad "} while (")
2487 (js2-print-ast (js2-do-node-condition n) 0)
2488 (insert ");\n")))
2489
2490 (cl-defstruct (js2-export-node
2491 (:include js2-node)
2492 (:constructor nil)
2493 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2494 (pos (js2-current-token-beg))
2495 len
2496 exports-list
2497 from-clause
2498 declaration
2499 default)))
2500 "AST node for an export statement. There are many things that can be exported,
2501 so many of its properties will be nil.
2502 "
2503 exports-list ; lisp list of js2-export-binding-node to export
2504 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2505 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2506 default) ; js2-function-node or js2-assign-node
2507
2508 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2509 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2510
2511 (defun js2-visit-export-node (n v)
2512 (let ((exports-list (js2-export-node-exports-list n))
2513 (from (js2-export-node-from-clause n))
2514 (declaration (js2-export-node-declaration n))
2515 (default (js2-export-node-default n)))
2516 (when exports-list
2517 (dolist (export exports-list)
2518 (js2-visit-ast export v)))
2519 (when from
2520 (js2-visit-ast from v))
2521 (when declaration
2522 (js2-visit-ast declaration v))
2523 (when default
2524 (js2-visit-ast default v))))
2525
2526 (defun js2-print-export-node (n i)
2527 (let ((pad (js2-make-pad i))
2528 (exports-list (js2-export-node-exports-list n))
2529 (from (js2-export-node-from-clause n))
2530 (declaration (js2-export-node-declaration n))
2531 (default (js2-export-node-default n)))
2532 (insert pad "export ")
2533 (cond
2534 (default
2535 (insert "default ")
2536 (js2-print-ast default i))
2537 (declaration
2538 (js2-print-ast declaration i))
2539 ((and exports-list from)
2540 (js2-print-named-imports exports-list)
2541 (insert " ")
2542 (js2-print-from-clause from))
2543 (from
2544 (insert "* ")
2545 (js2-print-from-clause from))
2546 (exports-list
2547 (js2-print-named-imports exports-list)))
2548 (insert ";\n")))
2549
2550 (cl-defstruct (js2-while-node
2551 (:include js2-loop-node)
2552 (:constructor nil)
2553 (:constructor make-js2-while-node (&key (type js2-WHILE)
2554 (pos (js2-current-token-beg))
2555 len body
2556 condition lp
2557 rp)))
2558 "AST node for while-loop."
2559 condition) ; while-condition
2560
2561 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2562 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2563
2564 (defun js2-visit-while-node (n v)
2565 (js2-visit-ast (js2-while-node-condition n) v)
2566 (js2-visit-ast (js2-while-node-body n) v))
2567
2568 (defun js2-print-while-node (n i)
2569 (let ((pad (js2-make-pad i)))
2570 (insert pad "while (")
2571 (js2-print-ast (js2-while-node-condition n) 0)
2572 (insert ") {\n")
2573 (js2-print-body (js2-while-node-body n) (1+ i))
2574 (insert pad "}\n")))
2575
2576 (cl-defstruct (js2-for-node
2577 (:include js2-loop-node)
2578 (:constructor nil)
2579 (:constructor make-js2-for-node (&key (type js2-FOR)
2580 (pos js2-ts-cursor)
2581 len body init
2582 condition
2583 update lp rp)))
2584 "AST node for a C-style for-loop."
2585 init ; initialization expression
2586 condition ; loop condition
2587 update) ; update clause
2588
2589 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2590 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2591
2592 (defun js2-visit-for-node (n v)
2593 (js2-visit-ast (js2-for-node-init n) v)
2594 (js2-visit-ast (js2-for-node-condition n) v)
2595 (js2-visit-ast (js2-for-node-update n) v)
2596 (js2-visit-ast (js2-for-node-body n) v))
2597
2598 (defun js2-print-for-node (n i)
2599 (let ((pad (js2-make-pad i)))
2600 (insert pad "for (")
2601 (js2-print-ast (js2-for-node-init n) 0)
2602 (insert "; ")
2603 (js2-print-ast (js2-for-node-condition n) 0)
2604 (insert "; ")
2605 (js2-print-ast (js2-for-node-update n) 0)
2606 (insert ") {\n")
2607 (js2-print-body (js2-for-node-body n) (1+ i))
2608 (insert pad "}\n")))
2609
2610 (cl-defstruct (js2-for-in-node
2611 (:include js2-loop-node)
2612 (:constructor nil)
2613 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2614 (pos js2-ts-cursor)
2615 len body
2616 iterator
2617 object
2618 in-pos
2619 each-pos
2620 foreach-p forof-p
2621 lp rp)))
2622 "AST node for a for..in loop."
2623 iterator ; [var] foo in ...
2624 object ; object over which we're iterating
2625 in-pos ; buffer position of 'in' keyword
2626 each-pos ; buffer position of 'each' keyword, if foreach-p
2627 foreach-p ; t if it's a for-each loop
2628 forof-p) ; t if it's a for-of loop
2629
2630 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2631 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2632
2633 (defun js2-visit-for-in-node (n v)
2634 (js2-visit-ast (js2-for-in-node-iterator n) v)
2635 (js2-visit-ast (js2-for-in-node-object n) v)
2636 (js2-visit-ast (js2-for-in-node-body n) v))
2637
2638 (defun js2-print-for-in-node (n i)
2639 (let ((pad (js2-make-pad i))
2640 (foreach (js2-for-in-node-foreach-p n))
2641 (forof (js2-for-in-node-forof-p n)))
2642 (insert pad "for ")
2643 (if foreach
2644 (insert "each "))
2645 (insert "(")
2646 (js2-print-ast (js2-for-in-node-iterator n) 0)
2647 (insert (if forof " of " " in "))
2648 (js2-print-ast (js2-for-in-node-object n) 0)
2649 (insert ") {\n")
2650 (js2-print-body (js2-for-in-node-body n) (1+ i))
2651 (insert pad "}\n")))
2652
2653 (cl-defstruct (js2-return-node
2654 (:include js2-node)
2655 (:constructor nil)
2656 (:constructor make-js2-return-node (&key (type js2-RETURN)
2657 (pos js2-ts-cursor)
2658 len
2659 retval)))
2660 "AST node for a return statement."
2661 retval) ; expression to return, or 'undefined
2662
2663 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2664 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2665
2666 (defun js2-visit-return-node (n v)
2667 (js2-visit-ast (js2-return-node-retval n) v))
2668
2669 (defun js2-print-return-node (n i)
2670 (insert (js2-make-pad i) "return")
2671 (when (js2-return-node-retval n)
2672 (insert " ")
2673 (js2-print-ast (js2-return-node-retval n) 0))
2674 (insert ";\n"))
2675
2676 (cl-defstruct (js2-if-node
2677 (:include js2-node)
2678 (:constructor nil)
2679 (:constructor make-js2-if-node (&key (type js2-IF)
2680 (pos js2-ts-cursor)
2681 len condition
2682 then-part
2683 else-pos
2684 else-part lp
2685 rp)))
2686 "AST node for an if-statement."
2687 condition ; expression
2688 then-part ; statement or block
2689 else-pos ; optional buffer position of 'else' keyword
2690 else-part ; optional statement or block
2691 lp ; position of left-paren, nil if omitted
2692 rp) ; position of right-paren, nil if omitted
2693
2694 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2695 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2696
2697 (defun js2-visit-if-node (n v)
2698 (js2-visit-ast (js2-if-node-condition n) v)
2699 (js2-visit-ast (js2-if-node-then-part n) v)
2700 (js2-visit-ast (js2-if-node-else-part n) v))
2701
2702 (defun js2-print-if-node (n i)
2703 (let ((pad (js2-make-pad i))
2704 (then-part (js2-if-node-then-part n))
2705 (else-part (js2-if-node-else-part n)))
2706 (insert pad "if (")
2707 (js2-print-ast (js2-if-node-condition n) 0)
2708 (insert ") {\n")
2709 (js2-print-body then-part (1+ i))
2710 (insert pad "}")
2711 (cond
2712 ((not else-part)
2713 (insert "\n"))
2714 ((js2-if-node-p else-part)
2715 (insert " else ")
2716 (js2-print-body else-part i))
2717 (t
2718 (insert " else {\n")
2719 (js2-print-body else-part (1+ i))
2720 (insert pad "}\n")))))
2721
2722 (cl-defstruct (js2-export-binding-node
2723 (:include js2-node)
2724 (:constructor nil)
2725 (:constructor make-js2-export-binding-node (&key (type -1)
2726 pos
2727 len
2728 local-name
2729 extern-name)))
2730 "AST node for an external symbol binding.
2731 It contains a local-name node which is the name of the value in the
2732 current scope, and extern-name which is the name of the value in the
2733 imported or exported scope. By default these are the same, but if the
2734 name is aliased as in {foo as bar}, it would have an extern-name node
2735 containing 'foo' and a local-name node containing 'bar'."
2736 local-name ; js2-name-node with the variable name in this scope
2737 extern-name) ; js2-name-node with the value name in the exporting module
2738
2739 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2740 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2741
2742 (defun js2-visit-extern-binding (n v)
2743 "Visit an extern binding node. First visit the local-name, and, if
2744 different, visit the extern-name."
2745 (let ((local-name (js2-export-binding-node-local-name n))
2746 (extern-name (js2-export-binding-node-extern-name n)))
2747 (when local-name
2748 (js2-visit-ast local-name v))
2749 (when (not (equal local-name extern-name))
2750 (js2-visit-ast extern-name v))))
2751
2752 (defun js2-print-extern-binding (n _i)
2753 "Print a representation of a single extern binding. E.g. 'foo' or
2754 'foo as bar'."
2755 (let ((local-name (js2-export-binding-node-local-name n))
2756 (extern-name (js2-export-binding-node-extern-name n)))
2757 (insert (js2-name-node-name extern-name))
2758 (when (not (equal local-name extern-name))
2759 (insert " as ")
2760 (insert (js2-name-node-name local-name)))))
2761
2762
2763 (cl-defstruct (js2-import-node
2764 (:include js2-node)
2765 (:constructor nil)
2766 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2767 (pos (js2-current-token-beg))
2768 len
2769 import
2770 from
2771 module-id)))
2772 "AST node for an import statement. It follows the form
2773
2774 import ModuleSpecifier;
2775 import ImportClause FromClause;"
2776 import ; js2-import-clause-node specifying which names are to imported.
2777 from ; js2-from-clause-node indicating the module from which to import.
2778 module-id) ; module-id of the import. E.g. 'src/mylib'.
2779
2780 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2781 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2782
2783 (defun js2-visit-import (n v)
2784 (let ((import-clause (js2-import-node-import n))
2785 (from-clause (js2-import-node-from n)))
2786 (when import-clause
2787 (js2-visit-ast import-clause v))
2788 (when from-clause
2789 (js2-visit-ast from-clause v))))
2790
2791 (defun js2-print-import (n i)
2792 "Prints a representation of the import node"
2793 (let ((pad (js2-make-pad i))
2794 (import-clause (js2-import-node-import n))
2795 (from-clause (js2-import-node-from n))
2796 (module-id (js2-import-node-module-id n)))
2797 (insert pad "import ")
2798 (if import-clause
2799 (progn
2800 (js2-print-import-clause import-clause)
2801 (insert " ")
2802 (js2-print-from-clause from-clause))
2803 (insert "'")
2804 (insert module-id)
2805 (insert "'"))
2806 (insert ";\n")))
2807
2808 (cl-defstruct (js2-import-clause-node
2809 (:include js2-node)
2810 (:constructor nil)
2811 (:constructor make-js2-import-clause-node (&key (type -1)
2812 pos
2813 len
2814 namespace-import
2815 named-imports
2816 default-binding)))
2817 "AST node corresponding to the import clause of an import statement. This is
2818 the portion of the import that bindings names from the external context to the
2819 local context."
2820 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2821 named-imports ; lisp list of js2-export-binding-node for all named imports.
2822 default-binding) ; js2-export-binding-node for the default import binding
2823
2824 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2825 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2826
2827 (defun js2-visit-import-clause (n v)
2828 (let ((ns-import (js2-import-clause-node-namespace-import n))
2829 (named-imports (js2-import-clause-node-named-imports n))
2830 (default (js2-import-clause-node-default-binding n)))
2831 (when ns-import
2832 (js2-visit-ast ns-import v))
2833 (when named-imports
2834 (dolist (import named-imports)
2835 (js2-visit-ast import v)))
2836 (when default
2837 (js2-visit-ast default v))))
2838
2839 (defun js2-print-import-clause (n)
2840 (let ((ns-import (js2-import-clause-node-namespace-import n))
2841 (named-imports (js2-import-clause-node-named-imports n))
2842 (default (js2-import-clause-node-default-binding n)))
2843 (cond
2844 ((and default ns-import)
2845 (js2-print-ast default)
2846 (insert ", ")
2847 (js2-print-namespace-import ns-import))
2848 ((and default named-imports)
2849 (js2-print-ast default)
2850 (insert ", ")
2851 (js2-print-named-imports named-imports))
2852 (default
2853 (js2-print-ast default))
2854 (ns-import
2855 (js2-print-namespace-import ns-import))
2856 (named-imports
2857 (js2-print-named-imports named-imports)))))
2858
2859 (defun js2-print-namespace-import (node)
2860 (insert "* as ")
2861 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2862
2863 (defun js2-print-named-imports (imports)
2864 (insert "{")
2865 (let ((len (length imports))
2866 (n 0))
2867 (while (< n len)
2868 (js2-print-extern-binding (nth n imports) 0)
2869 (unless (= n (- len 1))
2870 (insert ", "))
2871 (setq n (+ n 1))))
2872 (insert "}"))
2873
2874 (cl-defstruct (js2-namespace-import-node
2875 (:include js2-node)
2876 (:constructor nil)
2877 (:constructor make-js2-namespace-import-node (&key (type -1)
2878 pos
2879 len
2880 name)))
2881 "AST node for a complete namespace import.
2882 E.g. the '* as lib' expression in:
2883
2884 import * as lib from 'src/lib'
2885
2886 It contains a single name node referring to the bound name."
2887 name) ; js2-name-node of the bound name.
2888
2889 (defun js2-visit-namespace-import (n v)
2890 (js2-visit-ast (js2-namespace-import-node-name n) v))
2891
2892 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2893 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2894
2895 (cl-defstruct (js2-from-clause-node
2896 (:include js2-node)
2897 (:constructor nil)
2898 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2899 pos
2900 len
2901 module-id
2902 metadata-p)))
2903 "AST node for the from clause in an import or export statement.
2904 E.g. from 'my/module'. It can refere to either an external module, or to the
2905 modules metadata itself."
2906 module-id ; string containing the module specifier.
2907 metadata-p) ; true if this clause refers to the module's metadata
2908
2909 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2910 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2911
2912 (defun js2-print-from-clause (n)
2913 (insert "from ")
2914 (if (js2-from-clause-node-metadata-p n)
2915 (insert "this module")
2916 (insert "'")
2917 (insert (js2-from-clause-node-module-id n))
2918 (insert "'")))
2919
2920 (cl-defstruct (js2-try-node
2921 (:include js2-node)
2922 (:constructor nil)
2923 (:constructor make-js2-try-node (&key (type js2-TRY)
2924 (pos js2-ts-cursor)
2925 len
2926 try-block
2927 catch-clauses
2928 finally-block)))
2929 "AST node for a try-statement."
2930 try-block
2931 catch-clauses ; a Lisp list of `js2-catch-node'
2932 finally-block) ; a `js2-finally-node'
2933
2934 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2935 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2936
2937 (defun js2-visit-try-node (n v)
2938 (js2-visit-ast (js2-try-node-try-block n) v)
2939 (dolist (clause (js2-try-node-catch-clauses n))
2940 (js2-visit-ast clause v))
2941 (js2-visit-ast (js2-try-node-finally-block n) v))
2942
2943 (defun js2-print-try-node (n i)
2944 (let ((pad (js2-make-pad i))
2945 (catches (js2-try-node-catch-clauses n))
2946 (finally (js2-try-node-finally-block n)))
2947 (insert pad "try {\n")
2948 (js2-print-body (js2-try-node-try-block n) (1+ i))
2949 (insert pad "}")
2950 (when catches
2951 (dolist (catch catches)
2952 (js2-print-ast catch i)))
2953 (if finally
2954 (js2-print-ast finally i)
2955 (insert "\n"))))
2956
2957 (cl-defstruct (js2-catch-node
2958 (:include js2-scope)
2959 (:constructor nil)
2960 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2961 (pos js2-ts-cursor)
2962 len
2963 param
2964 guard-kwd
2965 guard-expr
2966 lp rp)))
2967 "AST node for a catch clause."
2968 param ; destructuring form or simple name node
2969 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2970 guard-expr ; catch condition, a `js2-node'
2971 lp ; buffer position of left-paren, nil if omitted
2972 rp) ; buffer position of right-paren, nil if omitted
2973
2974 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2975 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2976
2977 (defun js2-visit-catch-node (n v)
2978 (js2-visit-ast (js2-catch-node-param n) v)
2979 (when (js2-catch-node-guard-kwd n)
2980 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2981 (js2-visit-block n v))
2982
2983 (defun js2-print-catch-node (n i)
2984 (let ((pad (js2-make-pad i))
2985 (guard-kwd (js2-catch-node-guard-kwd n))
2986 (guard-expr (js2-catch-node-guard-expr n)))
2987 (insert " catch (")
2988 (js2-print-ast (js2-catch-node-param n) 0)
2989 (when guard-kwd
2990 (insert " if ")
2991 (js2-print-ast guard-expr 0))
2992 (insert ") {\n")
2993 (js2-print-body n (1+ i))
2994 (insert pad "}")))
2995
2996 (cl-defstruct (js2-finally-node
2997 (:include js2-node)
2998 (:constructor nil)
2999 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3000 (pos js2-ts-cursor)
3001 len body)))
3002 "AST node for a finally clause."
3003 body) ; a `js2-node', often but not always a block node
3004
3005 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3006 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3007
3008 (defun js2-visit-finally-node (n v)
3009 (js2-visit-ast (js2-finally-node-body n) v))
3010
3011 (defun js2-print-finally-node (n i)
3012 (let ((pad (js2-make-pad i)))
3013 (insert " finally {\n")
3014 (js2-print-body (js2-finally-node-body n) (1+ i))
3015 (insert pad "}\n")))
3016
3017 (cl-defstruct (js2-switch-node
3018 (:include js2-node)
3019 (:constructor nil)
3020 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3021 (pos js2-ts-cursor)
3022 len
3023 discriminant
3024 cases lp
3025 rp)))
3026 "AST node for a switch statement."
3027 discriminant ; a `js2-node' (switch expression)
3028 cases ; a Lisp list of `js2-case-node'
3029 lp ; position of open-paren for discriminant, nil if omitted
3030 rp) ; position of close-paren for discriminant, nil if omitted
3031
3032 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3033 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3034
3035 (defun js2-visit-switch-node (n v)
3036 (js2-visit-ast (js2-switch-node-discriminant n) v)
3037 (dolist (c (js2-switch-node-cases n))
3038 (js2-visit-ast c v)))
3039
3040 (defun js2-print-switch-node (n i)
3041 (let ((pad (js2-make-pad i))
3042 (cases (js2-switch-node-cases n)))
3043 (insert pad "switch (")
3044 (js2-print-ast (js2-switch-node-discriminant n) 0)
3045 (insert ") {\n")
3046 (dolist (case cases)
3047 (js2-print-ast case i))
3048 (insert pad "}\n")))
3049
3050 (cl-defstruct (js2-case-node
3051 (:include js2-block-node)
3052 (:constructor nil)
3053 (:constructor make-js2-case-node (&key (type js2-CASE)
3054 (pos js2-ts-cursor)
3055 len kids expr)))
3056 "AST node for a case clause of a switch statement."
3057 expr) ; the case expression (nil for default)
3058
3059 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3060 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3061
3062 (defun js2-visit-case-node (n v)
3063 (js2-visit-ast (js2-case-node-expr n) v)
3064 (js2-visit-block n v))
3065
3066 (defun js2-print-case-node (n i)
3067 (let ((pad (js2-make-pad i))
3068 (expr (js2-case-node-expr n)))
3069 (insert pad)
3070 (if (null expr)
3071 (insert "default:\n")
3072 (insert "case ")
3073 (js2-print-ast expr 0)
3074 (insert ":\n"))
3075 (dolist (kid (js2-case-node-kids n))
3076 (js2-print-ast kid (1+ i)))))
3077
3078 (cl-defstruct (js2-throw-node
3079 (:include js2-node)
3080 (:constructor nil)
3081 (:constructor make-js2-throw-node (&key (type js2-THROW)
3082 (pos js2-ts-cursor)
3083 len expr)))
3084 "AST node for a throw statement."
3085 expr) ; the expression to throw
3086
3087 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3088 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3089
3090 (defun js2-visit-throw-node (n v)
3091 (js2-visit-ast (js2-throw-node-expr n) v))
3092
3093 (defun js2-print-throw-node (n i)
3094 (insert (js2-make-pad i) "throw ")
3095 (js2-print-ast (js2-throw-node-expr n) 0)
3096 (insert ";\n"))
3097
3098 (cl-defstruct (js2-with-node
3099 (:include js2-node)
3100 (:constructor nil)
3101 (:constructor make-js2-with-node (&key (type js2-WITH)
3102 (pos js2-ts-cursor)
3103 len object
3104 body lp rp)))
3105 "AST node for a with-statement."
3106 object
3107 body
3108 lp ; buffer position of left-paren around object, nil if omitted
3109 rp) ; buffer position of right-paren around object, nil if omitted
3110
3111 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3112 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3113
3114 (defun js2-visit-with-node (n v)
3115 (js2-visit-ast (js2-with-node-object n) v)
3116 (js2-visit-ast (js2-with-node-body n) v))
3117
3118 (defun js2-print-with-node (n i)
3119 (let ((pad (js2-make-pad i)))
3120 (insert pad "with (")
3121 (js2-print-ast (js2-with-node-object n) 0)
3122 (insert ") {\n")
3123 (js2-print-body (js2-with-node-body n) (1+ i))
3124 (insert pad "}\n")))
3125
3126 (cl-defstruct (js2-label-node
3127 (:include js2-node)
3128 (:constructor nil)
3129 (:constructor make-js2-label-node (&key (type js2-LABEL)
3130 (pos js2-ts-cursor)
3131 len name)))
3132 "AST node for a statement label or case label."
3133 name ; a string
3134 loop) ; for validating and code-generating continue-to-label
3135
3136 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3137 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3138
3139 (defun js2-print-label (n i)
3140 (insert (js2-make-pad i)
3141 (js2-label-node-name n)
3142 ":\n"))
3143
3144 (cl-defstruct (js2-labeled-stmt-node
3145 (:include js2-node)
3146 (:constructor nil)
3147 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3148 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3149 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3150 (pos js2-ts-cursor)
3151 len labels stmt)))
3152 "AST node for a statement with one or more labels.
3153 Multiple labels for a statement are collapsed into the labels field."
3154 labels ; Lisp list of `js2-label-node'
3155 stmt) ; the statement these labels are for
3156
3157 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3158 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3159
3160 (defun js2-get-label-by-name (lbl-stmt name)
3161 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3162 Returns nil if no such label is in the list."
3163 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3164 result)
3165 (while (and label-list (not result))
3166 (if (string= (js2-label-node-name (car label-list)) name)
3167 (setq result (car label-list))
3168 (setq label-list (cdr label-list))))
3169 result))
3170
3171 (defun js2-visit-labeled-stmt (n v)
3172 (dolist (label (js2-labeled-stmt-node-labels n))
3173 (js2-visit-ast label v))
3174 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3175
3176 (defun js2-print-labeled-stmt (n i)
3177 (dolist (label (js2-labeled-stmt-node-labels n))
3178 (js2-print-ast label i))
3179 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3180
3181 (defun js2-labeled-stmt-node-contains (node label)
3182 "Return t if NODE contains LABEL in its label set.
3183 NODE is a `js2-labels-node'. LABEL is an identifier."
3184 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3185 if (string= label (js2-label-node-name nl))
3186 return t
3187 finally return nil))
3188
3189 (defsubst js2-labeled-stmt-node-add-label (node label)
3190 "Add a `js2-label-node' to the label set for this statement."
3191 (setf (js2-labeled-stmt-node-labels node)
3192 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3193
3194 (cl-defstruct (js2-jump-node
3195 (:include js2-node)
3196 (:constructor nil))
3197 "Abstract supertype of break and continue nodes."
3198 label ; `js2-name-node' for location of label identifier, if present
3199 target) ; target js2-labels-node or loop/switch statement
3200
3201 (defun js2-visit-jump-node (n v)
3202 ;; We don't visit the target, since it's a back-link.
3203 (js2-visit-ast (js2-jump-node-label n) v))
3204
3205 (cl-defstruct (js2-break-node
3206 (:include js2-jump-node)
3207 (:constructor nil)
3208 (:constructor make-js2-break-node (&key (type js2-BREAK)
3209 (pos js2-ts-cursor)
3210 len label target)))
3211 "AST node for a break statement.
3212 The label field is a `js2-name-node', possibly nil, for the named label
3213 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3214 is the target of the break - a label node or enclosing loop/switch statement.")
3215
3216 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3217 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3218
3219 (defun js2-print-break-node (n i)
3220 (insert (js2-make-pad i) "break")
3221 (when (js2-break-node-label n)
3222 (insert " ")
3223 (js2-print-ast (js2-break-node-label n) 0))
3224 (insert ";\n"))
3225
3226 (cl-defstruct (js2-continue-node
3227 (:include js2-jump-node)
3228 (:constructor nil)
3229 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3230 (pos js2-ts-cursor)
3231 len label target)))
3232 "AST node for a continue statement.
3233 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3234 It is nil if continue specifies no label. The target field is the jump target:
3235 a `js2-label-node' or the innermost enclosing loop.")
3236
3237 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3238 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3239
3240 (defun js2-print-continue-node (n i)
3241 (insert (js2-make-pad i) "continue")
3242 (when (js2-continue-node-label n)
3243 (insert " ")
3244 (js2-print-ast (js2-continue-node-label n) 0))
3245 (insert ";\n"))
3246
3247 (cl-defstruct (js2-function-node
3248 (:include js2-script-node)
3249 (:constructor nil)
3250 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3251 (pos js2-ts-cursor)
3252 len
3253 (ftype 'FUNCTION)
3254 (form 'FUNCTION_STATEMENT)
3255 (name "")
3256 params rest-p
3257 body
3258 generator-type
3259 lp rp)))
3260 "AST node for a function declaration.
3261 The `params' field is a Lisp list of nodes. Each node is either a simple
3262 `js2-name-node', or if it's a destructuring-assignment parameter, a
3263 `js2-array-node' or `js2-object-node'."
3264 ftype ; FUNCTION, GETTER or SETTER
3265 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3266 name ; function name (a `js2-name-node', or nil if anonymous)
3267 params ; a Lisp list of destructuring forms or simple name nodes
3268 rest-p ; if t, the last parameter is rest parameter
3269 body ; a `js2-block-node' or expression node (1.8 only)
3270 lp ; position of arg-list open-paren, or nil if omitted
3271 rp ; position of arg-list close-paren, or nil if omitted
3272 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3273 needs-activation ; t if we need an activation object for this frame
3274 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3275 member-expr) ; nonstandard Ecma extension from Rhino
3276
3277 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3278 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3279
3280 (defun js2-visit-function-node (n v)
3281 (js2-visit-ast (js2-function-node-name n) v)
3282 (dolist (p (js2-function-node-params n))
3283 (js2-visit-ast p v))
3284 (js2-visit-ast (js2-function-node-body n) v))
3285
3286 (defun js2-print-function-node (n i)
3287 (let* ((pad (js2-make-pad i))
3288 (method (js2-node-get-prop n 'METHOD_TYPE))
3289 (name (or (js2-function-node-name n)
3290 (js2-function-node-member-expr n)))
3291 (params (js2-function-node-params n))
3292 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3293 (rest-p (js2-function-node-rest-p n))
3294 (body (js2-function-node-body n))
3295 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3296 (unless (or method arrow)
3297 (insert pad "function")
3298 (when (eq (js2-function-node-generator-type n) 'STAR)
3299 (insert "*")))
3300 (when name
3301 (insert " ")
3302 (js2-print-ast name 0))
3303 (insert "(")
3304 (cl-loop with len = (length params)
3305 for param in params
3306 for count from 1
3307 do
3308 (when (and rest-p (= count len))
3309 (insert "..."))
3310 (js2-print-ast param 0)
3311 (when (< count len)
3312 (insert ", ")))
3313 (insert ") ")
3314 (when arrow
3315 (insert "=> "))
3316 (insert "{")
3317 ;; TODO: fix this to be smarter about indenting, etc.
3318 (unless expr
3319 (insert "\n"))
3320 (if (js2-block-node-p body)
3321 (js2-print-body body (1+ i))
3322 (js2-print-ast body 0))
3323 (insert pad "}")
3324 (unless expr
3325 (insert "\n"))))
3326
3327 (defun js2-function-name (node)
3328 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3329 (and (js2-function-node-name node)
3330 (js2-name-node-name (js2-function-node-name node))))
3331
3332 ;; Having this be an expression node makes it more flexible.
3333 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3334 ;; that work better if you assume it's an expression. Whenever we have
3335 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3336 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3337 (cl-defstruct (js2-var-decl-node
3338 (:include js2-node)
3339 (:constructor nil)
3340 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3341 (pos (js2-current-token-beg))
3342 len kids
3343 decl-type)))
3344 "AST node for a variable declaration list (VAR, CONST or LET).
3345 The node bounds differ depending on the declaration type. For VAR or
3346 CONST declarations, the bounds include the var/const keyword. For LET
3347 declarations, the node begins at the position of the first child."
3348 kids ; a Lisp list of `js2-var-init-node' structs.
3349 decl-type) ; js2-VAR, js2-CONST or js2-LET
3350
3351 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3352 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3353
3354 (defun js2-visit-var-decl (n v)
3355 (dolist (kid (js2-var-decl-node-kids n))
3356 (js2-visit-ast kid v)))
3357
3358 (defun js2-print-var-decl (n i)
3359 (let ((pad (js2-make-pad i))
3360 (tt (js2-var-decl-node-decl-type n)))
3361 (insert pad)
3362 (insert (cond
3363 ((= tt js2-VAR) "var ")
3364 ((= tt js2-LET) "let ")
3365 ((= tt js2-CONST) "const ")
3366 (t
3367 (error "malformed var-decl node"))))
3368 (cl-loop with kids = (js2-var-decl-node-kids n)
3369 with len = (length kids)
3370 for kid in kids
3371 for count from 1
3372 do
3373 (js2-print-ast kid 0)
3374 (if (< count len)
3375 (insert ", ")))))
3376
3377 (cl-defstruct (js2-var-init-node
3378 (:include js2-node)
3379 (:constructor nil)
3380 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3381 (pos js2-ts-cursor)
3382 len target
3383 initializer)))
3384 "AST node for a variable declaration.
3385 The type field will be js2-CONST for a const decl."
3386 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3387 initializer) ; initializer expression, a `js2-node'
3388
3389 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3390 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3391
3392 (defun js2-visit-var-init-node (n v)
3393 (js2-visit-ast (js2-var-init-node-target n) v)
3394 (js2-visit-ast (js2-var-init-node-initializer n) v))
3395
3396 (defun js2-print-var-init-node (n i)
3397 (let ((pad (js2-make-pad i))
3398 (name (js2-var-init-node-target n))
3399 (init (js2-var-init-node-initializer n)))
3400 (insert pad)
3401 (js2-print-ast name 0)
3402 (when init
3403 (insert " = ")
3404 (js2-print-ast init 0))))
3405
3406 (cl-defstruct (js2-cond-node
3407 (:include js2-node)
3408 (:constructor nil)
3409 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3410 (pos js2-ts-cursor)
3411 len
3412 test-expr
3413 true-expr
3414 false-expr
3415 q-pos c-pos)))
3416 "AST node for the ternary operator"
3417 test-expr
3418 true-expr
3419 false-expr
3420 q-pos ; buffer position of ?
3421 c-pos) ; buffer position of :
3422
3423 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3424 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3425
3426 (defun js2-visit-cond-node (n v)
3427 (js2-visit-ast (js2-cond-node-test-expr n) v)
3428 (js2-visit-ast (js2-cond-node-true-expr n) v)
3429 (js2-visit-ast (js2-cond-node-false-expr n) v))
3430
3431 (defun js2-print-cond-node (n i)
3432 (let ((pad (js2-make-pad i)))
3433 (insert pad)
3434 (js2-print-ast (js2-cond-node-test-expr n) 0)
3435 (insert " ? ")
3436 (js2-print-ast (js2-cond-node-true-expr n) 0)
3437 (insert " : ")
3438 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3439
3440 (cl-defstruct (js2-infix-node
3441 (:include js2-node)
3442 (:constructor nil)
3443 (:constructor make-js2-infix-node (&key type
3444 (pos js2-ts-cursor)
3445 len op-pos
3446 left right)))
3447 "Represents infix expressions.
3448 Includes assignment ops like `|=', and the comma operator.
3449 The type field inherited from `js2-node' holds the operator."
3450 op-pos ; buffer position where operator begins
3451 left ; any `js2-node'
3452 right) ; any `js2-node'
3453
3454 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3455 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3456
3457 (defun js2-visit-infix-node (n v)
3458 (js2-visit-ast (js2-infix-node-left n) v)
3459 (js2-visit-ast (js2-infix-node-right n) v))
3460
3461 (defconst js2-operator-tokens
3462 (let ((table (make-hash-table :test 'eq))
3463 (tokens
3464 (list (cons js2-IN "in")
3465 (cons js2-TYPEOF "typeof")
3466 (cons js2-INSTANCEOF "instanceof")
3467 (cons js2-DELPROP "delete")
3468 (cons js2-COMMA ",")
3469 (cons js2-COLON ":")
3470 (cons js2-OR "||")
3471 (cons js2-AND "&&")
3472 (cons js2-INC "++")
3473 (cons js2-DEC "--")
3474 (cons js2-BITOR "|")
3475 (cons js2-BITXOR "^")
3476 (cons js2-BITAND "&")
3477 (cons js2-EQ "==")
3478 (cons js2-NE "!=")
3479 (cons js2-LT "<")
3480 (cons js2-LE "<=")
3481 (cons js2-GT ">")
3482 (cons js2-GE ">=")
3483 (cons js2-LSH "<<")
3484 (cons js2-RSH ">>")
3485 (cons js2-URSH ">>>")
3486 (cons js2-ADD "+") ; infix plus
3487 (cons js2-SUB "-") ; infix minus
3488 (cons js2-MUL "*")
3489 (cons js2-DIV "/")
3490 (cons js2-MOD "%")
3491 (cons js2-NOT "!")
3492 (cons js2-BITNOT "~")
3493 (cons js2-POS "+") ; unary plus
3494 (cons js2-NEG "-") ; unary minus
3495 (cons js2-TRIPLEDOT "...")
3496 (cons js2-SHEQ "===") ; shallow equality
3497 (cons js2-SHNE "!==") ; shallow inequality
3498 (cons js2-ASSIGN "=")
3499 (cons js2-ASSIGN_BITOR "|=")
3500 (cons js2-ASSIGN_BITXOR "^=")
3501 (cons js2-ASSIGN_BITAND "&=")
3502 (cons js2-ASSIGN_LSH "<<=")
3503 (cons js2-ASSIGN_RSH ">>=")
3504 (cons js2-ASSIGN_URSH ">>>=")
3505 (cons js2-ASSIGN_ADD "+=")
3506 (cons js2-ASSIGN_SUB "-=")
3507 (cons js2-ASSIGN_MUL "*=")
3508 (cons js2-ASSIGN_DIV "/=")
3509 (cons js2-ASSIGN_MOD "%="))))
3510 (cl-loop for (k . v) in tokens do
3511 (puthash k v table))
3512 table))
3513
3514 (defun js2-print-infix-node (n i)
3515 (let* ((tt (js2-node-type n))
3516 (op (gethash tt js2-operator-tokens)))
3517 (unless op
3518 (error "unrecognized infix operator %s" (js2-node-type n)))
3519 (insert (js2-make-pad i))
3520 (js2-print-ast (js2-infix-node-left n) 0)
3521 (unless (= tt js2-COMMA)
3522 (insert " "))
3523 (insert op)
3524 (insert " ")
3525 (js2-print-ast (js2-infix-node-right n) 0)))
3526
3527 (cl-defstruct (js2-assign-node
3528 (:include js2-infix-node)
3529 (:constructor nil)
3530 (:constructor make-js2-assign-node (&key type
3531 (pos js2-ts-cursor)
3532 len op-pos
3533 left right)))
3534 "Represents any assignment.
3535 The type field holds the actual assignment operator.")
3536
3537 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3538 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3539
3540 (cl-defstruct (js2-unary-node
3541 (:include js2-node)
3542 (:constructor nil)
3543 (:constructor make-js2-unary-node (&key type ; required
3544 (pos js2-ts-cursor)
3545 len operand)))
3546 "AST node type for unary operator nodes.
3547 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3548 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3549 property is added if the operator follows the operand."
3550 operand) ; a `js2-node' expression
3551
3552 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3553 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3554
3555 (defun js2-visit-unary-node (n v)
3556 (js2-visit-ast (js2-unary-node-operand n) v))
3557
3558 (defun js2-print-unary-node (n i)
3559 (let* ((tt (js2-node-type n))
3560 (op (gethash tt js2-operator-tokens))
3561 (postfix (js2-node-get-prop n 'postfix)))
3562 (unless op
3563 (error "unrecognized unary operator %s" tt))
3564 (insert (js2-make-pad i))
3565 (unless postfix
3566 (insert op))
3567 (if (or (= tt js2-TYPEOF)
3568 (= tt js2-DELPROP))
3569 (insert " "))
3570 (js2-print-ast (js2-unary-node-operand n) 0)
3571 (when postfix
3572 (insert op))))
3573
3574 (cl-defstruct (js2-let-node
3575 (:include js2-scope)
3576 (:constructor nil)
3577 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3578 (pos (js2-current-token-beg))
3579 len vars body
3580 lp rp)))
3581 "AST node for a let expression or a let statement.
3582 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3583 vars ; a `js2-var-decl-node'
3584 body ; a `js2-node' representing the expression or body block
3585 lp
3586 rp)
3587
3588 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3589 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3590
3591 (defun js2-visit-let-node (n v)
3592 (js2-visit-ast (js2-let-node-vars n) v)
3593 (js2-visit-ast (js2-let-node-body n) v))
3594
3595 (defun js2-print-let-node (n i)
3596 (insert (js2-make-pad i) "let (")
3597 (let ((p (point)))
3598 (js2-print-ast (js2-let-node-vars n) 0)
3599 (delete-region p (+ p 4)))
3600 (insert ") ")
3601 (js2-print-ast (js2-let-node-body n) i))
3602
3603 (cl-defstruct (js2-keyword-node
3604 (:include js2-node)
3605 (:constructor nil)
3606 (:constructor make-js2-keyword-node (&key type
3607 (pos (js2-current-token-beg))
3608 (len (- js2-ts-cursor pos)))))
3609 "AST node representing a literal keyword such as `null'.
3610 Used for `null', `this', `true', `false' and `debugger'.
3611 The node type is set to js2-NULL, js2-THIS, etc.")
3612
3613 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3614 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3615
3616 (defun js2-print-keyword-node (n i)
3617 (insert (js2-make-pad i)
3618 (let ((tt (js2-node-type n)))
3619 (cond
3620 ((= tt js2-THIS) "this")
3621 ((= tt js2-SUPER) "super")
3622 ((= tt js2-NULL) "null")
3623 ((= tt js2-TRUE) "true")
3624 ((= tt js2-FALSE) "false")
3625 ((= tt js2-DEBUGGER) "debugger")
3626 (t (error "Invalid keyword literal type: %d" tt))))))
3627
3628 (defsubst js2-this-or-super-node-p (node)
3629 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3630 (let ((type (js2-node-type node)))
3631 (or (eq type js2-THIS) (eq type js2-SUPER))))
3632
3633 (cl-defstruct (js2-new-node
3634 (:include js2-node)
3635 (:constructor nil)
3636 (:constructor make-js2-new-node (&key (type js2-NEW)
3637 (pos (js2-current-token-beg))
3638 len target
3639 args initializer
3640 lp rp)))
3641 "AST node for new-expression such as new Foo()."
3642 target ; an identifier or reference
3643 args ; a Lisp list of argument nodes
3644 lp ; position of left-paren, nil if omitted
3645 rp ; position of right-paren, nil if omitted
3646 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3647
3648 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3649 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3650
3651 (defun js2-visit-new-node (n v)
3652 (js2-visit-ast (js2-new-node-target n) v)
3653 (dolist (arg (js2-new-node-args n))
3654 (js2-visit-ast arg v))
3655 (js2-visit-ast (js2-new-node-initializer n) v))
3656
3657 (defun js2-print-new-node (n i)
3658 (insert (js2-make-pad i) "new ")
3659 (js2-print-ast (js2-new-node-target n))
3660 (insert "(")
3661 (js2-print-list (js2-new-node-args n))
3662 (insert ")")
3663 (when (js2-new-node-initializer n)
3664 (insert " ")
3665 (js2-print-ast (js2-new-node-initializer n))))
3666
3667 (cl-defstruct (js2-name-node
3668 (:include js2-node)
3669 (:constructor nil)
3670 (:constructor make-js2-name-node (&key (type js2-NAME)
3671 (pos (js2-current-token-beg))
3672 (len (- js2-ts-cursor
3673 (js2-current-token-beg)))
3674 (name (js2-current-token-string)))))
3675 "AST node for a JavaScript identifier"
3676 name ; a string
3677 scope) ; a `js2-scope' (optional, used for codegen)
3678
3679 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3680 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3681
3682 (defun js2-print-name-node (n i)
3683 (insert (js2-make-pad i)
3684 (js2-name-node-name n)))
3685
3686 (defsubst js2-name-node-length (node)
3687 "Return identifier length of NODE, a `js2-name-node'.
3688 Returns 0 if NODE is nil or its identifier field is nil."
3689 (if node
3690 (length (js2-name-node-name node))
3691 0))
3692
3693 (cl-defstruct (js2-number-node
3694 (:include js2-node)
3695 (:constructor nil)
3696 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3697 (pos (js2-current-token-beg))
3698 (len (- js2-ts-cursor
3699 (js2-current-token-beg)))
3700 (value (js2-current-token-string))
3701 (num-value (js2-token-number
3702 (js2-current-token)))
3703 (num-base (js2-token-number-base
3704 (js2-current-token))))))
3705 "AST node for a number literal."
3706 value ; the original string, e.g. "6.02e23"
3707 num-value ; the parsed number value
3708 num-base) ; the number's base
3709
3710 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3711 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3712
3713 (defun js2-print-number-node (n i)
3714 (insert (js2-make-pad i)
3715 (number-to-string (js2-number-node-num-value n))))
3716
3717 (cl-defstruct (js2-regexp-node
3718 (:include js2-node)
3719 (:constructor nil)
3720 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3721 (pos (js2-current-token-beg))
3722 (len (- js2-ts-cursor
3723 (js2-current-token-beg)))
3724 value flags)))
3725 "AST node for a regular expression literal."
3726 value ; the regexp string, without // delimiters
3727 flags) ; a string of flags, e.g. `mi'.
3728
3729 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3730 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3731
3732 (defun js2-print-regexp (n i)
3733 (insert (js2-make-pad i)
3734 "/"
3735 (js2-regexp-node-value n)
3736 "/")
3737 (if (js2-regexp-node-flags n)
3738 (insert (js2-regexp-node-flags n))))
3739
3740 (cl-defstruct (js2-string-node
3741 (:include js2-node)
3742 (:constructor nil)
3743 (:constructor make-js2-string-node (&key (type js2-STRING)
3744 (pos (js2-current-token-beg))
3745 (len (- js2-ts-cursor
3746 (js2-current-token-beg)))
3747 (value (js2-current-token-string)))))
3748 "String literal.
3749 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3750 You can tell the quote type by looking at the first character."
3751 value) ; the characters of the string, including the quotes
3752
3753 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3754 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3755
3756 (defun js2-print-string-node (n i)
3757 (insert (js2-make-pad i)
3758 (js2-node-string n)))
3759
3760 (cl-defstruct (js2-template-node
3761 (:include js2-node)
3762 (:constructor nil)
3763 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3764 beg len kids)))
3765 "Template literal."
3766 kids) ; `js2-string-node' is used for string segments, other nodes
3767 ; for substitutions inside.
3768
3769 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3770 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3771
3772 (defun js2-visit-template (n callback)
3773 (dolist (kid (js2-template-node-kids n))
3774 (js2-visit-ast kid callback)))
3775
3776 (defun js2-print-template (n i)
3777 (insert (js2-make-pad i))
3778 (dolist (kid (js2-template-node-kids n))
3779 (if (js2-string-node-p kid)
3780 (insert (js2-node-string kid))
3781 (js2-print-ast kid))))
3782
3783 (cl-defstruct (js2-tagged-template-node
3784 (:include js2-node)
3785 (:constructor nil)
3786 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3787 beg len tag template)))
3788 "Tagged template literal."
3789 tag ; `js2-node' with the tag expression.
3790 template) ; `js2-template-node' with the template.
3791
3792 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3793 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3794
3795 (defun js2-visit-tagged-template (n callback)
3796 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3797 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3798
3799 (defun js2-print-tagged-template (n i)
3800 (insert (js2-make-pad i))
3801 (js2-print-ast (js2-tagged-template-node-tag n))
3802 (js2-print-ast (js2-tagged-template-node-template n)))
3803
3804 (cl-defstruct (js2-array-node
3805 (:include js2-node)
3806 (:constructor nil)
3807 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3808 (pos js2-ts-cursor)
3809 len elems)))
3810 "AST node for an array literal."
3811 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3812
3813 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3814 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3815
3816 (defun js2-visit-array-node (n v)
3817 (dolist (e (js2-array-node-elems n))
3818 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3819
3820 (defun js2-print-array-node (n i)
3821 (insert (js2-make-pad i) "[")
3822 (let ((elems (js2-array-node-elems n)))
3823 (js2-print-list elems)
3824 (when (and elems (null (car (last elems))))
3825 (insert ",")))
3826 (insert "]"))
3827
3828 (cl-defstruct (js2-class-node
3829 (:include js2-node)
3830 (:constructor nil)
3831 (:constructor make-js2-class-node (&key (type js2-CLASS)
3832 (pos js2-ts-cursor)
3833 (form 'CLASS_STATEMENT)
3834 (name "")
3835 extends len elems)))
3836 "AST node for an class expression.
3837 `elems' is a list of `js2-object-prop-node', and `extends' is an
3838 optional `js2-expr-node'"
3839 form ; CLASS_{STATEMENT|EXPRESSION}
3840 name ; class name (a `js2-node-name', or nil if anonymous)
3841 extends ; class heritage (a `js2-expr-node', or nil if none)
3842 elems)
3843
3844 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3845 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3846
3847 (defun js2-visit-class-node (n v)
3848 (js2-visit-ast (js2-class-node-name n) v)
3849 (js2-visit-ast (js2-class-node-extends n) v)
3850 (dolist (e (js2-class-node-elems n))
3851 (js2-visit-ast e v)))
3852
3853 (defun js2-print-class-node (n i)
3854 (let* ((pad (js2-make-pad i))
3855 (name (js2-class-node-name n))
3856 (extends (js2-class-node-extends n))
3857 (elems (js2-class-node-elems n)))
3858 (insert pad "class")
3859 (when name
3860 (insert " ")
3861 (js2-print-ast name 0))
3862 (when extends
3863 (insert " extends ")
3864 (js2-print-ast extends))
3865 (insert " {")
3866 (dolist (elem elems)
3867 (insert "\n")
3868 (if (js2-node-get-prop elem 'STATIC)
3869 (progn (insert (js2-make-pad (1+ i)) "static ")
3870 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3871 (js2-print-ast elem (1+ i))))
3872 (insert "\n" pad "}")))
3873
3874 (cl-defstruct (js2-object-node
3875 (:include js2-node)
3876 (:constructor nil)
3877 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3878 (pos js2-ts-cursor)
3879 len
3880 elems)))
3881 "AST node for an object literal expression.
3882 `elems' is a list of `js2-object-prop-node'."
3883 elems)
3884
3885 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3886 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3887
3888 (defun js2-visit-object-node (n v)
3889 (dolist (e (js2-object-node-elems n))
3890 (js2-visit-ast e v)))
3891
3892 (defun js2-print-object-node (n i)
3893 (insert (js2-make-pad i) "{")
3894 (js2-print-list (js2-object-node-elems n))
3895 (insert "}"))
3896
3897 (cl-defstruct (js2-computed-prop-name-node
3898 (:include js2-node)
3899 (:constructor nil)
3900 (:constructor make-js2-computed-prop-name-node
3901 (&key
3902 (type js2-LB)
3903 expr
3904 (pos (js2-current-token-beg))
3905 (len (- js2-ts-cursor
3906 (js2-current-token-beg))))))
3907 "AST node for a `ComputedPropertyName'."
3908 expr)
3909
3910 (put 'cl-struct-js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
3911 (put 'cl-struct-js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
3912
3913 (defun js2-visit-computed-prop-name-node (n v)
3914 (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
3915
3916 (defun js2-print-computed-prop-name-node (n i)
3917 (insert (js2-make-pad i) "[")
3918 (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
3919 (insert "]"))
3920
3921 (cl-defstruct (js2-object-prop-node
3922 (:include js2-infix-node)
3923 (:constructor nil)
3924 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3925 (pos js2-ts-cursor)
3926 len left
3927 right op-pos)))
3928 "AST node for an object literal prop:value entry.
3929 The `left' field is the property: a name node, string node,
3930 number node or expression node. The `right' field is a
3931 `js2-node' representing the initializer value. If the property
3932 is abbreviated, the node's `SHORTHAND' property is non-nil and
3933 both fields have the same value.")
3934
3935 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3936 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3937
3938 (defun js2-print-object-prop-node (n i)
3939 (let* ((left (js2-object-prop-node-left n))
3940 (right (js2-object-prop-node-right n)))
3941 (js2-print-ast left i)
3942 (if (not (js2-node-get-prop n 'SHORTHAND))
3943 (progn
3944 (insert ": ")
3945 (js2-print-ast right 0)))))
3946
3947 (cl-defstruct (js2-method-node
3948 (:include js2-infix-node)
3949 (:constructor nil)
3950 (:constructor make-js2-method-node (&key type ; GET, SET, or FUNCTION
3951 (pos js2-ts-cursor)
3952 len left right)))
3953 "AST node for a method in an object literal or a class body.
3954 The `left' field is the `js2-name-node' naming the method.
3955 The `right' field is always an anonymous `js2-function-node' with a node
3956 property `METHOD_TYPE' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3957
3958 (put 'cl-struct-js2-method-node 'js2-visitor 'js2-visit-infix-node)
3959 (put 'cl-struct-js2-method-node 'js2-printer 'js2-print-method)
3960
3961 (defun js2-print-method (n i)
3962 (let* ((pad (js2-make-pad i))
3963 (left (js2-method-node-left n))
3964 (right (js2-method-node-right n)))
3965 (insert pad)
3966 (if (/= (js2-node-type n) js2-FUNCTION)
3967 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3968 (when (and (js2-function-node-p right)
3969 (eq 'STAR (js2-function-node-generator-type right)))
3970 (insert "*"))
3971 (js2-print-ast left 0)
3972 (js2-print-ast right 0)))
3973
3974 (cl-defstruct (js2-prop-get-node
3975 (:include js2-infix-node)
3976 (:constructor nil)
3977 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3978 (pos js2-ts-cursor)
3979 len left right)))
3980 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3981
3982 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3983 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3984
3985 (defun js2-visit-prop-get-node (n v)
3986 (js2-visit-ast (js2-prop-get-node-left n) v)
3987 (js2-visit-ast (js2-prop-get-node-right n) v))
3988
3989 (defun js2-print-prop-get-node (n i)
3990 (insert (js2-make-pad i))
3991 (js2-print-ast (js2-prop-get-node-left n) 0)
3992 (insert ".")
3993 (js2-print-ast (js2-prop-get-node-right n) 0))
3994
3995 (cl-defstruct (js2-elem-get-node
3996 (:include js2-node)
3997 (:constructor nil)
3998 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3999 (pos js2-ts-cursor)
4000 len target element
4001 lb rb)))
4002 "AST node for an array index expression such as foo[bar]."
4003 target ; a `js2-node' - the expression preceding the "."
4004 element ; a `js2-node' - the expression in brackets
4005 lb ; position of left-bracket, nil if omitted
4006 rb) ; position of right-bracket, nil if omitted
4007
4008 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4009 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4010
4011 (defun js2-visit-elem-get-node (n v)
4012 (js2-visit-ast (js2-elem-get-node-target n) v)
4013 (js2-visit-ast (js2-elem-get-node-element n) v))
4014
4015 (defun js2-print-elem-get-node (n i)
4016 (insert (js2-make-pad i))
4017 (js2-print-ast (js2-elem-get-node-target n) 0)
4018 (insert "[")
4019 (js2-print-ast (js2-elem-get-node-element n) 0)
4020 (insert "]"))
4021
4022 (cl-defstruct (js2-call-node
4023 (:include js2-node)
4024 (:constructor nil)
4025 (:constructor make-js2-call-node (&key (type js2-CALL)
4026 (pos js2-ts-cursor)
4027 len target args
4028 lp rp)))
4029 "AST node for a JavaScript function call."
4030 target ; a `js2-node' evaluating to the function to call
4031 args ; a Lisp list of `js2-node' arguments
4032 lp ; position of open-paren, or nil if missing
4033 rp) ; position of close-paren, or nil if missing
4034
4035 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4036 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4037
4038 (defun js2-visit-call-node (n v)
4039 (js2-visit-ast (js2-call-node-target n) v)
4040 (dolist (arg (js2-call-node-args n))
4041 (js2-visit-ast arg v)))
4042
4043 (defun js2-print-call-node (n i)
4044 (insert (js2-make-pad i))
4045 (js2-print-ast (js2-call-node-target n) 0)
4046 (insert "(")
4047 (js2-print-list (js2-call-node-args n))
4048 (insert ")"))
4049
4050 (cl-defstruct (js2-yield-node
4051 (:include js2-node)
4052 (:constructor nil)
4053 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4054 (pos js2-ts-cursor)
4055 len value star-p)))
4056 "AST node for yield statement or expression."
4057 star-p ; whether it's yield*
4058 value) ; optional: value to be yielded
4059
4060 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4061 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4062
4063 (defun js2-visit-yield-node (n v)
4064 (js2-visit-ast (js2-yield-node-value n) v))
4065
4066 (defun js2-print-yield-node (n i)
4067 (insert (js2-make-pad i))
4068 (insert "yield")
4069 (when (js2-yield-node-star-p n)
4070 (insert "*"))
4071 (when (js2-yield-node-value n)
4072 (insert " ")
4073 (js2-print-ast (js2-yield-node-value n) 0)))
4074
4075 (cl-defstruct (js2-paren-node
4076 (:include js2-node)
4077 (:constructor nil)
4078 (:constructor make-js2-paren-node (&key (type js2-LP)
4079 (pos js2-ts-cursor)
4080 len expr)))
4081 "AST node for a parenthesized expression.
4082 In particular, used when the parens are syntactically optional,
4083 as opposed to required parens such as those enclosing an if-conditional."
4084 expr) ; `js2-node'
4085
4086 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4087 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4088
4089 (defun js2-visit-paren-node (n v)
4090 (js2-visit-ast (js2-paren-node-expr n) v))
4091
4092 (defun js2-print-paren-node (n i)
4093 (insert (js2-make-pad i))
4094 (insert "(")
4095 (js2-print-ast (js2-paren-node-expr n) 0)
4096 (insert ")"))
4097
4098 (cl-defstruct (js2-comp-node
4099 (:include js2-scope)
4100 (:constructor nil)
4101 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4102 (pos js2-ts-cursor)
4103 len result
4104 loops filters
4105 form)))
4106 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4107 result ; result expression (just after left-bracket)
4108 loops ; a Lisp list of `js2-comp-loop-node'
4109 filters ; a Lisp list of guard/filter expressions
4110 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4111 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4112 )
4113
4114 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4115 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4116
4117 (defun js2-visit-comp-node (n v)
4118 (js2-visit-ast (js2-comp-node-result n) v)
4119 (dolist (l (js2-comp-node-loops n))
4120 (js2-visit-ast l v))
4121 (dolist (f (js2-comp-node-filters n))
4122 (js2-visit-ast f v)))
4123
4124 (defun js2-print-comp-node (n i)
4125 (let ((pad (js2-make-pad i))
4126 (result (js2-comp-node-result n))
4127 (loops (js2-comp-node-loops n))
4128 (filters (js2-comp-node-filters n))
4129 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4130 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4131 (insert pad (if gen-p "(" "["))
4132 (when legacy-p
4133 (js2-print-ast result 0))
4134 (dolist (l loops)
4135 (when legacy-p
4136 (insert " "))
4137 (js2-print-ast l 0)
4138 (unless legacy-p
4139 (insert " ")))
4140 (dolist (f filters)
4141 (when legacy-p
4142 (insert " "))
4143 (insert "if (")
4144 (js2-print-ast f 0)
4145 (insert ")")
4146 (unless legacy-p
4147 (insert " ")))
4148 (unless legacy-p
4149 (js2-print-ast result 0))
4150 (insert (if gen-p ")" "]"))))
4151
4152 (cl-defstruct (js2-comp-loop-node
4153 (:include js2-for-in-node)
4154 (:constructor nil)
4155 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4156 (pos js2-ts-cursor)
4157 len iterator
4158 object in-pos
4159 foreach-p
4160 each-pos
4161 forof-p
4162 lp rp)))
4163 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4164
4165 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4166 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4167
4168 (defun js2-visit-comp-loop (n v)
4169 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4170 (js2-visit-ast (js2-comp-loop-node-object n) v))
4171
4172 (defun js2-print-comp-loop (n _i)
4173 (insert "for ")
4174 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4175 (insert "(")
4176 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4177 (insert (if (js2-comp-loop-node-forof-p n)
4178 " of " " in "))
4179 (js2-print-ast (js2-comp-loop-node-object n) 0)
4180 (insert ")"))
4181
4182 (cl-defstruct (js2-empty-expr-node
4183 (:include js2-node)
4184 (:constructor nil)
4185 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4186 (pos (js2-current-token-beg))
4187 len)))
4188 "AST node for an empty expression.")
4189
4190 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4191 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4192
4193 (cl-defstruct (js2-xml-node
4194 (:include js2-block-node)
4195 (:constructor nil)
4196 (:constructor make-js2-xml-node (&key (type js2-XML)
4197 (pos (js2-current-token-beg))
4198 len kids)))
4199 "AST node for initial parse of E4X literals.
4200 The kids field is a list of XML fragments, each a `js2-string-node' or
4201 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4202
4203 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4204 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4205
4206 (defun js2-print-xml-node (n i)
4207 (dolist (kid (js2-xml-node-kids n))
4208 (js2-print-ast kid i)))
4209
4210 (cl-defstruct (js2-xml-js-expr-node
4211 (:include js2-xml-node)
4212 (:constructor nil)
4213 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4214 (pos js2-ts-cursor)
4215 len expr)))
4216 "AST node for an embedded JavaScript {expression} in an E4X literal.
4217 The start and end fields correspond to the curly-braces."
4218 expr) ; a `js2-expr-node' of some sort
4219
4220 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4221 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4222
4223 (defun js2-visit-xml-js-expr (n v)
4224 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4225
4226 (defun js2-print-xml-js-expr (n i)
4227 (insert (js2-make-pad i))
4228 (insert "{")
4229 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4230 (insert "}"))
4231
4232 (cl-defstruct (js2-xml-dot-query-node
4233 (:include js2-infix-node)
4234 (:constructor nil)
4235 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4236 (pos js2-ts-cursor)
4237 op-pos len left
4238 right rp)))
4239 "AST node for an E4X foo.(bar) filter expression.
4240 Note that the left-paren is automatically the character immediately
4241 following the dot (.) in the operator. No whitespace is permitted
4242 between the dot and the lp by the scanner."
4243 rp)
4244
4245 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4246 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4247
4248 (defun js2-print-xml-dot-query (n i)
4249 (insert (js2-make-pad i))
4250 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4251 (insert ".(")
4252 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4253 (insert ")"))
4254
4255 (cl-defstruct (js2-xml-ref-node
4256 (:include js2-node)
4257 (:constructor nil)) ; abstract
4258 "Base type for E4X XML attribute-access or property-get expressions.
4259 Such expressions can take a variety of forms. The general syntax has
4260 three parts:
4261
4262 - (optional) an @ (specifying an attribute access)
4263 - (optional) a namespace (a `js2-name-node') and double-colon
4264 - (required) either a `js2-name-node' or a bracketed [expression]
4265
4266 The property-name expressions (examples: ns::name, @name) are
4267 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4268 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4269
4270 This node type (or more specifically, its subclasses) will sometimes
4271 be the right-hand child of a `js2-prop-get-node' or a
4272 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4273 The `js2-xml-ref-node' may also be a standalone primary expression with
4274 no explicit target, which is valid in certain expression contexts such as
4275
4276 company..employee.(@id < 100)
4277
4278 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4279 expression whose parent is a `js2-xml-dot-query-node'."
4280 namespace
4281 at-pos
4282 colon-pos)
4283
4284 (defsubst js2-xml-ref-node-attr-access-p (node)
4285 "Return non-nil if this expression began with an @-token."
4286 (and (numberp (js2-xml-ref-node-at-pos node))
4287 (cl-plusp (js2-xml-ref-node-at-pos node))))
4288
4289 (cl-defstruct (js2-xml-prop-ref-node
4290 (:include js2-xml-ref-node)
4291 (:constructor nil)
4292 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4293 (pos (js2-current-token-beg))
4294 len propname
4295 namespace at-pos
4296 colon-pos)))
4297 "AST node for an E4X XML [expr] property-ref expression.
4298 The JavaScript syntax is an optional @, an optional ns::, and a name.
4299
4300 [ '@' ] [ name '::' ] name
4301
4302 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4303 @ns::*, @*::attr, @*::*, and @*.
4304
4305 The node starts at the @ token, if present. Otherwise it starts at the
4306 namespace name. The node bounds extend through the closing right-bracket,
4307 or if it is missing due to a syntax error, through the end of the index
4308 expression."
4309 propname)
4310
4311 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4312 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4313
4314 (defun js2-visit-xml-prop-ref-node (n v)
4315 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4316 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4317
4318 (defun js2-print-xml-prop-ref-node (n i)
4319 (insert (js2-make-pad i))
4320 (if (js2-xml-ref-node-attr-access-p n)
4321 (insert "@"))
4322 (when (js2-xml-prop-ref-node-namespace n)
4323 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4324 (insert "::"))
4325 (if (js2-xml-prop-ref-node-propname n)
4326 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4327
4328 (cl-defstruct (js2-xml-elem-ref-node
4329 (:include js2-xml-ref-node)
4330 (:constructor nil)
4331 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4332 (pos (js2-current-token-beg))
4333 len expr lb rb
4334 namespace at-pos
4335 colon-pos)))
4336 "AST node for an E4X XML [expr] member-ref expression.
4337 Syntax:
4338
4339 [ '@' ] [ name '::' ] '[' expr ']'
4340
4341 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4342
4343 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4344 is not a legal E4X XML element-ref expression, since it's already used
4345 for standard JavaScript element-get array indexing. Hence, a
4346 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4347 non-nil namespace node, or both.
4348
4349 The node starts at the @ token, if present. Otherwise it starts
4350 at the namespace name. The node bounds extend through the closing
4351 right-bracket, or if it is missing due to a syntax error, through the
4352 end of the index expression."
4353 expr ; the bracketed index expression
4354 lb
4355 rb)
4356
4357 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4358 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4359
4360 (defun js2-visit-xml-elem-ref-node (n v)
4361 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4362 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4363
4364 (defun js2-print-xml-elem-ref-node (n i)
4365 (insert (js2-make-pad i))
4366 (if (js2-xml-ref-node-attr-access-p n)
4367 (insert "@"))
4368 (when (js2-xml-elem-ref-node-namespace n)
4369 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4370 (insert "::"))
4371 (insert "[")
4372 (if (js2-xml-elem-ref-node-expr n)
4373 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4374 (insert "]"))
4375
4376 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4377
4378 (cl-defstruct (js2-xml-start-tag-node
4379 (:include js2-xml-node)
4380 (:constructor nil)
4381 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4382 (pos js2-ts-cursor)
4383 len name attrs kids
4384 empty-p)))
4385 "AST node for an XML start-tag. Not currently used.
4386 The `kids' field is a Lisp list of child content nodes."
4387 name ; a `js2-xml-name-node'
4388 attrs ; a Lisp list of `js2-xml-attr-node'
4389 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4390
4391 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4392 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4393
4394 (defun js2-visit-xml-start-tag (n v)
4395 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4396 (dolist (attr (js2-xml-start-tag-node-attrs n))
4397 (js2-visit-ast attr v))
4398 (js2-visit-block n v))
4399
4400 (defun js2-print-xml-start-tag (n i)
4401 (insert (js2-make-pad i) "<")
4402 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4403 (when (js2-xml-start-tag-node-attrs n)
4404 (insert " ")
4405 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4406 (insert ">"))
4407
4408 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4409 ;; and add the end-tag to the kids list of the parent as well.
4410 (cl-defstruct (js2-xml-end-tag-node
4411 (:include js2-xml-node)
4412 (:constructor nil)
4413 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4414 (pos js2-ts-cursor)
4415 len name)))
4416 "AST node for an XML end-tag. Not currently used."
4417 name) ; a `js2-xml-name-node'
4418
4419 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4420 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4421
4422 (defun js2-visit-xml-end-tag (n v)
4423 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4424
4425 (defun js2-print-xml-end-tag (n i)
4426 (insert (js2-make-pad i))
4427 (insert "</")
4428 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4429 (insert ">"))
4430
4431 (cl-defstruct (js2-xml-name-node
4432 (:include js2-xml-node)
4433 (:constructor nil)
4434 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4435 (pos js2-ts-cursor)
4436 len namespace kids)))
4437 "AST node for an E4X XML name. Not currently used.
4438 Any XML name can be qualified with a namespace, hence the namespace field.
4439 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4440 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4441 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4442 namespace) ; a `js2-string-node'
4443
4444 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4445 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4446
4447 (defun js2-visit-xml-name-node (n v)
4448 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4449
4450 (defun js2-print-xml-name-node (n i)
4451 (insert (js2-make-pad i))
4452 (when (js2-xml-name-node-namespace n)
4453 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4454 (insert "::"))
4455 (dolist (kid (js2-xml-name-node-kids n))
4456 (js2-print-ast kid 0)))
4457
4458 (cl-defstruct (js2-xml-pi-node
4459 (:include js2-xml-node)
4460 (:constructor nil)
4461 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4462 (pos js2-ts-cursor)
4463 len name attrs)))
4464 "AST node for an E4X XML processing instruction. Not currently used."
4465 name ; a `js2-xml-name-node'
4466 attrs) ; a list of `js2-xml-attr-node'
4467
4468 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4469 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4470
4471 (defun js2-visit-xml-pi-node (n v)
4472 (js2-visit-ast (js2-xml-pi-node-name n) v)
4473 (dolist (attr (js2-xml-pi-node-attrs n))
4474 (js2-visit-ast attr v)))
4475
4476 (defun js2-print-xml-pi-node (n i)
4477 (insert (js2-make-pad i) "<?")
4478 (js2-print-ast (js2-xml-pi-node-name n))
4479 (when (js2-xml-pi-node-attrs n)
4480 (insert " ")
4481 (js2-print-list (js2-xml-pi-node-attrs n)))
4482 (insert "?>"))
4483
4484 (cl-defstruct (js2-xml-cdata-node
4485 (:include js2-xml-node)
4486 (:constructor nil)
4487 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4488 (pos js2-ts-cursor)
4489 len content)))
4490 "AST node for a CDATA escape section. Not currently used."
4491 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4492
4493 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4494 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4495
4496 (defun js2-visit-xml-cdata-node (n v)
4497 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4498
4499 (defun js2-print-xml-cdata-node (n i)
4500 (insert (js2-make-pad i))
4501 (js2-print-ast (js2-xml-cdata-node-content n)))
4502
4503 (cl-defstruct (js2-xml-attr-node
4504 (:include js2-xml-node)
4505 (:constructor nil)
4506 (:constructor make-js2-attr-node (&key (type js2-XML)
4507 (pos js2-ts-cursor)
4508 len name value
4509 eq-pos quote-type)))
4510 "AST node representing a foo='bar' XML attribute value. Not yet used."
4511 name ; a `js2-xml-name-node'
4512 value ; a `js2-xml-name-node'
4513 eq-pos ; buffer position of "=" sign
4514 quote-type) ; 'single or 'double
4515
4516 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4517 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4518
4519 (defun js2-visit-xml-attr-node (n v)
4520 (js2-visit-ast (js2-xml-attr-node-name n) v)
4521 (js2-visit-ast (js2-xml-attr-node-value n) v))
4522
4523 (defun js2-print-xml-attr-node (n i)
4524 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4525 "'"
4526 "\"")))
4527 (insert (js2-make-pad i))
4528 (js2-print-ast (js2-xml-attr-node-name n) 0)
4529 (insert "=" quote)
4530 (js2-print-ast (js2-xml-attr-node-value n) 0)
4531 (insert quote)))
4532
4533 (cl-defstruct (js2-xml-text-node
4534 (:include js2-xml-node)
4535 (:constructor nil)
4536 (:constructor make-js2-text-node (&key (type js2-XML)
4537 (pos js2-ts-cursor)
4538 len content)))
4539 "AST node for an E4X XML text node. Not currently used."
4540 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4541
4542 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4543 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4544
4545 (defun js2-visit-xml-text-node (n v)
4546 (js2-visit-ast (js2-xml-text-node-content n) v))
4547
4548 (defun js2-print-xml-text-node (n i)
4549 (insert (js2-make-pad i))
4550 (dolist (kid (js2-xml-text-node-content n))
4551 (js2-print-ast kid)))
4552
4553 (cl-defstruct (js2-xml-comment-node
4554 (:include js2-xml-node)
4555 (:constructor nil)
4556 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4557 (pos js2-ts-cursor)
4558 len)))
4559 "AST node for E4X XML comment. Not currently used.")
4560
4561 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4562 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4563
4564 (defun js2-print-xml-comment (n i)
4565 (insert (js2-make-pad i)
4566 (js2-node-string n)))
4567
4568 ;;; Node utilities
4569
4570 (defsubst js2-node-line (n)
4571 "Fetch the source line number at the start of node N.
4572 This is O(n) in the length of the source buffer; use prudently."
4573 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4574
4575 (defsubst js2-block-node-kid (n i)
4576 "Return child I of node N, or nil if there aren't that many."
4577 (nth i (js2-block-node-kids n)))
4578
4579 (defsubst js2-block-node-first (n)
4580 "Return first child of block node N, or nil if there is none."
4581 (cl-first (js2-block-node-kids n)))
4582
4583 (defun js2-node-root (n)
4584 "Return the root of the AST containing N.
4585 If N has no parent pointer, returns N."
4586 (let ((parent (js2-node-parent n)))
4587 (if parent
4588 (js2-node-root parent)
4589 n)))
4590
4591 (defsubst js2-node-short-name (n)
4592 "Return the short name of node N as a string, e.g. `js2-if-node'."
4593 (substring (symbol-name (aref n 0))
4594 (length "cl-struct-")))
4595
4596 (defun js2-node-child-list (node)
4597 "Return the child list for NODE, a Lisp list of nodes.
4598 Works for block nodes, array nodes, obj literals, funarg lists,
4599 var decls and try nodes (for catch clauses). Note that you should call
4600 `js2-block-node-kids' on the function body for the body statements.
4601 Returns nil for zero-length child lists or unsupported nodes."
4602 (cond
4603 ((js2-function-node-p node)
4604 (js2-function-node-params node))
4605 ((js2-block-node-p node)
4606 (js2-block-node-kids node))
4607 ((js2-try-node-p node)
4608 (js2-try-node-catch-clauses node))
4609 ((js2-array-node-p node)
4610 (js2-array-node-elems node))
4611 ((js2-object-node-p node)
4612 (js2-object-node-elems node))
4613 ((js2-call-node-p node)
4614 (js2-call-node-args node))
4615 ((js2-new-node-p node)
4616 (js2-new-node-args node))
4617 ((js2-var-decl-node-p node)
4618 (js2-var-decl-node-kids node))
4619 (t
4620 nil)))
4621
4622 (defun js2-node-set-child-list (node kids)
4623 "Set the child list for NODE to KIDS."
4624 (cond
4625 ((js2-function-node-p node)
4626 (setf (js2-function-node-params node) kids))
4627 ((js2-block-node-p node)
4628 (setf (js2-block-node-kids node) kids))
4629 ((js2-try-node-p node)
4630 (setf (js2-try-node-catch-clauses node) kids))
4631 ((js2-array-node-p node)
4632 (setf (js2-array-node-elems node) kids))
4633 ((js2-object-node-p node)
4634 (setf (js2-object-node-elems node) kids))
4635 ((js2-call-node-p node)
4636 (setf (js2-call-node-args node) kids))
4637 ((js2-new-node-p node)
4638 (setf (js2-new-node-args node) kids))
4639 ((js2-var-decl-node-p node)
4640 (setf (js2-var-decl-node-kids node) kids))
4641 (t
4642 (error "Unsupported node type: %s" (js2-node-short-name node))))
4643 kids)
4644
4645 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4646 (defconst js2-paren-expr-nodes
4647 '(cl-struct-js2-comp-loop-node
4648 cl-struct-js2-comp-node
4649 cl-struct-js2-call-node
4650 cl-struct-js2-catch-node
4651 cl-struct-js2-do-node
4652 cl-struct-js2-elem-get-node
4653 cl-struct-js2-for-in-node
4654 cl-struct-js2-for-node
4655 cl-struct-js2-function-node
4656 cl-struct-js2-if-node
4657 cl-struct-js2-let-node
4658 cl-struct-js2-new-node
4659 cl-struct-js2-paren-node
4660 cl-struct-js2-switch-node
4661 cl-struct-js2-while-node
4662 cl-struct-js2-with-node
4663 cl-struct-js2-xml-dot-query-node)
4664 "Node types that can have a parenthesized child expression.
4665 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4666
4667 (defsubst js2-paren-expr-node-p (node)
4668 "Return t for nodes that typically have a parenthesized child expression.
4669 Useful for computing the indentation anchors for arg-lists and conditions.
4670 Note that it may return a false positive, for instance when NODE is
4671 a `js2-new-node' and there are no arguments or parentheses."
4672 (memq (aref node 0) js2-paren-expr-nodes))
4673
4674 ;; Fake polymorphism... yech.
4675 (defun js2-node-lp (node)
4676 "Return relative left-paren position for NODE, if applicable.
4677 For `js2-elem-get-node' structs, returns left-bracket position.
4678 Note that the position may be nil in the case of a parse error."
4679 (cond
4680 ((js2-elem-get-node-p node)
4681 (js2-elem-get-node-lb node))
4682 ((js2-loop-node-p node)
4683 (js2-loop-node-lp node))
4684 ((js2-function-node-p node)
4685 (js2-function-node-lp node))
4686 ((js2-if-node-p node)
4687 (js2-if-node-lp node))
4688 ((js2-new-node-p node)
4689 (js2-new-node-lp node))
4690 ((js2-call-node-p node)
4691 (js2-call-node-lp node))
4692 ((js2-paren-node-p node)
4693 0)
4694 ((js2-switch-node-p node)
4695 (js2-switch-node-lp node))
4696 ((js2-catch-node-p node)
4697 (js2-catch-node-lp node))
4698 ((js2-let-node-p node)
4699 (js2-let-node-lp node))
4700 ((js2-comp-node-p node)
4701 0)
4702 ((js2-with-node-p node)
4703 (js2-with-node-lp node))
4704 ((js2-xml-dot-query-node-p node)
4705 (1+ (js2-infix-node-op-pos node)))
4706 (t
4707 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4708
4709 ;; Fake polymorphism... blech.
4710 (defun js2-node-rp (node)
4711 "Return relative right-paren position for NODE, if applicable.
4712 For `js2-elem-get-node' structs, returns right-bracket position.
4713 Note that the position may be nil in the case of a parse error."
4714 (cond
4715 ((js2-elem-get-node-p node)
4716 (js2-elem-get-node-rb node))
4717 ((js2-loop-node-p node)
4718 (js2-loop-node-rp node))
4719 ((js2-function-node-p node)
4720 (js2-function-node-rp node))
4721 ((js2-if-node-p node)
4722 (js2-if-node-rp node))
4723 ((js2-new-node-p node)
4724 (js2-new-node-rp node))
4725 ((js2-call-node-p node)
4726 (js2-call-node-rp node))
4727 ((js2-paren-node-p node)
4728 (1- (js2-node-len node)))
4729 ((js2-switch-node-p node)
4730 (js2-switch-node-rp node))
4731 ((js2-catch-node-p node)
4732 (js2-catch-node-rp node))
4733 ((js2-let-node-p node)
4734 (js2-let-node-rp node))
4735 ((js2-comp-node-p node)
4736 (1- (js2-node-len node)))
4737 ((js2-with-node-p node)
4738 (js2-with-node-rp node))
4739 ((js2-xml-dot-query-node-p node)
4740 (1+ (js2-xml-dot-query-node-rp node)))
4741 (t
4742 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4743
4744 (defsubst js2-node-first-child (node)
4745 "Return the first element of `js2-node-child-list' for NODE."
4746 (car (js2-node-child-list node)))
4747
4748 (defsubst js2-node-last-child (node)
4749 "Return the last element of `js2-node-last-child' for NODE."
4750 (car (last (js2-node-child-list node))))
4751
4752 (defun js2-node-prev-sibling (node)
4753 "Return the previous statement in parent.
4754 Works for parents supported by `js2-node-child-list'.
4755 Returns nil if NODE is not in the parent, or PARENT is
4756 not a supported node, or if NODE is the first child."
4757 (let* ((p (js2-node-parent node))
4758 (kids (js2-node-child-list p))
4759 (sib (car kids)))
4760 (while (and kids
4761 (not (eq node (cadr kids))))
4762 (setq kids (cdr kids)
4763 sib (car kids)))
4764 sib))
4765
4766 (defun js2-node-next-sibling (node)
4767 "Return the next statement in parent block.
4768 Returns nil if NODE is not in the block, or PARENT is not
4769 a block node, or if NODE is the last statement."
4770 (let* ((p (js2-node-parent node))
4771 (kids (js2-node-child-list p)))
4772 (while (and kids
4773 (not (eq node (car kids))))
4774 (setq kids (cdr kids)))
4775 (cadr kids)))
4776
4777 (defun js2-node-find-child-before (pos parent &optional after)
4778 "Find the last child that starts before POS in parent.
4779 If AFTER is non-nil, returns first child starting after POS.
4780 POS is an absolute buffer position. PARENT is any node
4781 supported by `js2-node-child-list'.
4782 Returns nil if no applicable child is found."
4783 (let ((kids (if (js2-function-node-p parent)
4784 (js2-block-node-kids (js2-function-node-body parent))
4785 (js2-node-child-list parent)))
4786 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4787 (js2-function-node-body parent)
4788 parent)))
4789 kid result fn
4790 (continue t))
4791 (setq fn (if after '>= '<))
4792 (while (and kids continue)
4793 (setq kid (car kids))
4794 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4795 (setq result kid
4796 continue (not after))
4797 (setq continue after))
4798 (setq kids (cdr kids)))
4799 result))
4800
4801 (defun js2-node-find-child-after (pos parent)
4802 "Find first child that starts after POS in parent.
4803 POS is an absolute buffer position. PARENT is any node
4804 supported by `js2-node-child-list'.
4805 Returns nil if no applicable child is found."
4806 (js2-node-find-child-before pos parent 'after))
4807
4808 (defun js2-node-replace-child (pos parent new-node)
4809 "Replace node at index POS in PARENT with NEW-NODE.
4810 Only works for parents supported by `js2-node-child-list'."
4811 (let ((kids (js2-node-child-list parent))
4812 (i 0))
4813 (while (< i pos)
4814 (setq kids (cdr kids)
4815 i (1+ i)))
4816 (setcar kids new-node)
4817 (js2-node-add-children parent new-node)))
4818
4819 (defun js2-node-buffer (n)
4820 "Return the buffer associated with AST N.
4821 Returns nil if the buffer is not set as a property on the root
4822 node, or if parent links were not recorded during parsing."
4823 (let ((root (js2-node-root n)))
4824 (and root
4825 (js2-ast-root-p root)
4826 (js2-ast-root-buffer root))))
4827
4828 (defun js2-block-node-push (n kid)
4829 "Push js2-node KID onto the end of js2-block-node N's child list.
4830 KID is always added to the -end- of the kids list.
4831 Function also calls `js2-node-add-children' to add the parent link."
4832 (let ((kids (js2-node-child-list n)))
4833 (if kids
4834 (setcdr kids (nconc (cdr kids) (list kid)))
4835 (js2-node-set-child-list n (list kid)))
4836 (js2-node-add-children n kid)))
4837
4838 (defun js2-node-string (node)
4839 (with-current-buffer (or (js2-node-buffer node)
4840 (error "No buffer available for node %s" node))
4841 (let ((pos (js2-node-abs-pos node)))
4842 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4843
4844 ;; Container for storing the node we're looking for in a traversal.
4845 (js2-deflocal js2-discovered-node nil)
4846
4847 ;; Keep track of absolute node position during traversals.
4848 (js2-deflocal js2-visitor-offset nil)
4849
4850 (js2-deflocal js2-node-search-point nil)
4851
4852 (when js2-mode-dev-mode-p
4853 (defun js2-find-node-at-point ()
4854 (interactive)
4855 (let ((node (js2-node-at-point)))
4856 (message "%s" (or node "No node found at point"))))
4857 (defun js2-node-name-at-point ()
4858 (interactive)
4859 (let ((node (js2-node-at-point)))
4860 (message "%s" (if node
4861 (js2-node-short-name node)
4862 "No node found at point.")))))
4863
4864 (defun js2-node-at-point (&optional pos skip-comments)
4865 "Return AST node at POS, a buffer position, defaulting to current point.
4866 The `js2-mode-ast' variable must be set to the current parse tree.
4867 Signals an error if the AST (`js2-mode-ast') is nil.
4868 Always returns a node - if it can't find one, it returns the root.
4869 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4870 (let ((ast js2-mode-ast)
4871 result)
4872 (unless ast
4873 (error "No JavaScript AST available"))
4874 ;; Look through comments first, since they may be inside nodes that
4875 ;; would otherwise report a match.
4876 (setq pos (or pos (point))
4877 result (if (> pos (js2-node-abs-end ast))
4878 ast
4879 (if (not skip-comments)
4880 (js2-comment-at-point pos))))
4881 (unless result
4882 (setq js2-discovered-node nil
4883 js2-visitor-offset 0
4884 js2-node-search-point pos)
4885 (unwind-protect
4886 (catch 'js2-visit-done
4887 (js2-visit-ast ast #'js2-node-at-point-visitor))
4888 (setq js2-visitor-offset nil
4889 js2-node-search-point nil))
4890 (setq result js2-discovered-node))
4891 ;; may have found a comment beyond end of last child node,
4892 ;; since visiting the ast-root looks at the comment-list last.
4893 (if (and skip-comments
4894 (js2-comment-node-p result))
4895 (setq result nil))
4896 (or result js2-mode-ast)))
4897
4898 (defun js2-node-at-point-visitor (node end-p)
4899 (let ((rel-pos (js2-node-pos node))
4900 abs-pos
4901 abs-end
4902 (point js2-node-search-point))
4903 (cond
4904 (end-p
4905 ;; this evaluates to a non-nil return value, even if it's zero
4906 (cl-decf js2-visitor-offset rel-pos))
4907 ;; we already looked for comments before visiting, and don't want them now
4908 ((js2-comment-node-p node)
4909 nil)
4910 (t
4911 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4912 ;; we only want to use the node if the point is before
4913 ;; the last character position in the node, so we decrement
4914 ;; the absolute end by 1.
4915 abs-end (+ abs-pos (js2-node-len node) -1))
4916 (cond
4917 ;; If this node starts after search-point, stop the search.
4918 ((> abs-pos point)
4919 (throw 'js2-visit-done nil))
4920 ;; If this node ends before the search-point, don't check kids.
4921 ((> point abs-end)
4922 nil)
4923 (t
4924 ;; Otherwise point is within this node, possibly in a child.
4925 (setq js2-discovered-node node)
4926 t)))))) ; keep processing kids to look for more specific match
4927
4928 (defsubst js2-block-comment-p (node)
4929 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4930 (and (js2-comment-node-p node)
4931 (memq (js2-comment-node-format node) '(jsdoc block))))
4932
4933 ;; TODO: put the comments in a vector and binary-search them instead
4934 (defun js2-comment-at-point (&optional pos)
4935 "Look through scanned comment nodes for one containing POS.
4936 POS is a buffer position that defaults to current point.
4937 Function returns nil if POS was not in any comment node."
4938 (let ((ast js2-mode-ast)
4939 (x (or pos (point)))
4940 beg end)
4941 (unless ast
4942 (error "No JavaScript AST available"))
4943 (catch 'done
4944 ;; Comments are stored in lexical order.
4945 (dolist (comment (js2-ast-root-comments ast) nil)
4946 (setq beg (js2-node-abs-pos comment)
4947 end (+ beg (js2-node-len comment)))
4948 (if (and (>= x beg)
4949 (<= x end))
4950 (throw 'done comment))))))
4951
4952 (defun js2-mode-find-parent-fn (node)
4953 "Find function enclosing NODE.
4954 Returns nil if NODE is not inside a function."
4955 (setq node (js2-node-parent node))
4956 (while (and node (not (js2-function-node-p node)))
4957 (setq node (js2-node-parent node)))
4958 (and (js2-function-node-p node) node))
4959
4960 (defun js2-mode-find-enclosing-fn (node)
4961 "Find function or root enclosing NODE."
4962 (if (js2-ast-root-p node)
4963 node
4964 (setq node (js2-node-parent node))
4965 (while (not (or (js2-ast-root-p node)
4966 (js2-function-node-p node)))
4967 (setq node (js2-node-parent node)))
4968 node))
4969
4970 (defun js2-mode-find-enclosing-node (beg end)
4971 "Find node fully enclosing BEG and END."
4972 (let ((node (js2-node-at-point beg))
4973 pos
4974 (continue t))
4975 (while continue
4976 (if (or (js2-ast-root-p node)
4977 (and
4978 (<= (setq pos (js2-node-abs-pos node)) beg)
4979 (>= (+ pos (js2-node-len node)) end)))
4980 (setq continue nil)
4981 (setq node (js2-node-parent node))))
4982 node))
4983
4984 (defun js2-node-parent-script-or-fn (node)
4985 "Find script or function immediately enclosing NODE.
4986 If NODE is the ast-root, returns nil."
4987 (if (js2-ast-root-p node)
4988 nil
4989 (setq node (js2-node-parent node))
4990 (while (and node (not (or (js2-function-node-p node)
4991 (js2-script-node-p node))))
4992 (setq node (js2-node-parent node)))
4993 node))
4994
4995 (defun js2-node-is-descendant (node ancestor)
4996 "Return t if NODE is a descendant of ANCESTOR."
4997 (while (and node
4998 (not (eq node ancestor)))
4999 (setq node (js2-node-parent node)))
5000 node)
5001
5002 ;;; visitor infrastructure
5003
5004 (defun js2-visit-none (_node _callback)
5005 "Visitor for AST node that have no node children."
5006 nil)
5007
5008 (defun js2-print-none (_node _indent)
5009 "Visitor for AST node with no printed representation.")
5010
5011 (defun js2-print-body (node indent)
5012 "Print a statement, or a block without braces."
5013 (if (js2-block-node-p node)
5014 (dolist (kid (js2-block-node-kids node))
5015 (js2-print-ast kid indent))
5016 (js2-print-ast node indent)))
5017
5018 (defun js2-print-list (args &optional delimiter)
5019 (cl-loop with len = (length args)
5020 for arg in args
5021 for count from 1
5022 do
5023 (when arg (js2-print-ast arg 0))
5024 (if (< count len)
5025 (insert (or delimiter ", ")))))
5026
5027 (defun js2-print-tree (ast)
5028 "Prints an AST to the current buffer.
5029 Makes `js2-ast-parent-nodes' available to the printer functions."
5030 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5031 (js2-print-ast ast)))
5032
5033 (defun js2-print-ast (node &optional indent)
5034 "Helper function for printing AST nodes.
5035 Requires `js2-ast-parent-nodes' to be non-nil.
5036 You should use `js2-print-tree' instead of this function."
5037 (let ((printer (get (aref node 0) 'js2-printer))
5038 (i (or indent 0)))
5039 ;; TODO: wedge comments in here somewhere
5040 (if printer
5041 (funcall printer node i))))
5042
5043 (defconst js2-side-effecting-tokens
5044 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5045 (dolist (tt (list js2-ASSIGN
5046 js2-ASSIGN_ADD
5047 js2-ASSIGN_BITAND
5048 js2-ASSIGN_BITOR
5049 js2-ASSIGN_BITXOR
5050 js2-ASSIGN_DIV
5051 js2-ASSIGN_LSH
5052 js2-ASSIGN_MOD
5053 js2-ASSIGN_MUL
5054 js2-ASSIGN_RSH
5055 js2-ASSIGN_SUB
5056 js2-ASSIGN_URSH
5057 js2-BLOCK
5058 js2-BREAK
5059 js2-CALL
5060 js2-CATCH
5061 js2-CATCH_SCOPE
5062 js2-CLASS
5063 js2-CONST
5064 js2-CONTINUE
5065 js2-DEBUGGER
5066 js2-DEC
5067 js2-DELPROP
5068 js2-DEL_REF
5069 js2-DO
5070 js2-ELSE
5071 js2-EMPTY
5072 js2-ENTERWITH
5073 js2-EXPORT
5074 js2-EXPR_RESULT
5075 js2-FINALLY
5076 js2-FOR
5077 js2-FUNCTION
5078 js2-GOTO
5079 js2-IF
5080 js2-IFEQ
5081 js2-IFNE
5082 js2-IMPORT
5083 js2-INC
5084 js2-JSR
5085 js2-LABEL
5086 js2-LEAVEWITH
5087 js2-LET
5088 js2-LETEXPR
5089 js2-LOCAL_BLOCK
5090 js2-LOOP
5091 js2-NEW
5092 js2-REF_CALL
5093 js2-RETHROW
5094 js2-RETURN
5095 js2-RETURN_RESULT
5096 js2-SEMI
5097 js2-SETELEM
5098 js2-SETELEM_OP
5099 js2-SETNAME
5100 js2-SETPROP
5101 js2-SETPROP_OP
5102 js2-SETVAR
5103 js2-SET_REF
5104 js2-SET_REF_OP
5105 js2-SWITCH
5106 js2-TARGET
5107 js2-THROW
5108 js2-TRY
5109 js2-VAR
5110 js2-WHILE
5111 js2-WITH
5112 js2-WITHEXPR
5113 js2-YIELD))
5114 (aset tokens tt t))
5115 (if js2-instanceof-has-side-effects
5116 (aset tokens js2-INSTANCEOF t))
5117 tokens))
5118
5119 (defun js2-node-has-side-effects (node)
5120 "Return t if NODE has side effects."
5121 (when node ; makes it easier to handle malformed expressions
5122 (let ((tt (js2-node-type node)))
5123 (cond
5124 ;; This doubtless needs some work, since EXPR_VOID is used
5125 ;; in several ways in Rhino and I may not have caught them all.
5126 ;; I'll wait for people to notice incorrect warnings.
5127 ((and (= tt js2-EXPR_VOID)
5128 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5129 (let ((expr (js2-expr-stmt-node-expr node)))
5130 (or (js2-node-has-side-effects expr)
5131 (when (js2-string-node-p expr)
5132 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5133 ((= tt js2-COMMA)
5134 (js2-node-has-side-effects (js2-infix-node-right node)))
5135 ((or (= tt js2-AND)
5136 (= tt js2-OR))
5137 (or (js2-node-has-side-effects (js2-infix-node-right node))
5138 (js2-node-has-side-effects (js2-infix-node-left node))))
5139 ((= tt js2-HOOK)
5140 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5141 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5142 ((js2-paren-node-p node)
5143 (js2-node-has-side-effects (js2-paren-node-expr node)))
5144 ((= tt js2-ERROR) ; avoid cascaded error messages
5145 nil)
5146 (t
5147 (aref js2-side-effecting-tokens tt))))))
5148
5149 (defconst js2-stmt-node-types
5150 (list js2-BLOCK
5151 js2-BREAK
5152 js2-CONTINUE
5153 js2-DEFAULT ; e4x "default xml namespace" statement
5154 js2-DO
5155 js2-EXPORT
5156 js2-EXPR_RESULT
5157 js2-EXPR_VOID
5158 js2-FOR
5159 js2-IF
5160 js2-IMPORT
5161 js2-RETURN
5162 js2-SWITCH
5163 js2-THROW
5164 js2-TRY
5165 js2-WHILE
5166 js2-WITH)
5167 "Node types that only appear in statement contexts.
5168 The list does not include nodes that always appear as the child
5169 of another specific statement type, such as switch-cases,
5170 catch and finally blocks, and else-clauses. The list also excludes
5171 nodes like yield, let and var, which may appear in either expression
5172 or statement context, and in the latter context always have a
5173 `js2-expr-stmt-node' parent. Finally, the list does not include
5174 functions or scripts, which are treated separately from statements
5175 by the JavaScript parser and runtime.")
5176
5177 (defun js2-stmt-node-p (node)
5178 "Heuristic for figuring out if NODE is a statement.
5179 Some node types can appear in either an expression context or a
5180 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5181 For these node types in a statement context, the parent will be a
5182 `js2-expr-stmt-node'.
5183 Functions aren't included in the check."
5184 (memq (js2-node-type node) js2-stmt-node-types))
5185
5186 (defun js2-mode-find-first-stmt (node)
5187 "Search upward starting from NODE looking for a statement.
5188 For purposes of this function, a `js2-function-node' counts."
5189 (while (not (or (js2-stmt-node-p node)
5190 (js2-function-node-p node)))
5191 (setq node (js2-node-parent node)))
5192 node)
5193
5194 (defun js2-node-parent-stmt (node)
5195 "Return the node's first ancestor that is a statement.
5196 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5197 appearing in a statement context will have a parent that is a
5198 `js2-expr-stmt-node' that will be returned by this function."
5199 (let ((parent (js2-node-parent node)))
5200 (if (or (null parent)
5201 (js2-stmt-node-p parent)
5202 (and (js2-function-node-p parent)
5203 (not (eq (js2-function-node-form parent)
5204 'FUNCTION_EXPRESSION))))
5205 parent
5206 (js2-node-parent-stmt parent))))
5207
5208 ;; In the Mozilla Rhino sources, Roshan James writes:
5209 ;; Does consistent-return analysis on the function body when strict mode is
5210 ;; enabled.
5211 ;;
5212 ;; function (x) { return (x+1) }
5213 ;;
5214 ;; is ok, but
5215 ;;
5216 ;; function (x) { if (x < 0) return (x+1); }
5217 ;;
5218 ;; is not because the function can potentially return a value when the
5219 ;; condition is satisfied and if not, the function does not explicitly
5220 ;; return a value.
5221 ;;
5222 ;; This extends to checking mismatches such as "return" and "return <value>"
5223 ;; used in the same function. Warnings are not emitted if inconsistent
5224 ;; returns exist in code that can be statically shown to be unreachable.
5225 ;; Ex.
5226 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5227 ;;
5228 ;; emits no warning. However if the loop had a break statement, then a
5229 ;; warning would be emitted.
5230 ;;
5231 ;; The consistency analysis looks at control structures such as loops, ifs,
5232 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5233 ;; warns the user about an inconsistent set of termination possibilities.
5234 ;;
5235 ;; These flags enumerate the possible ways a statement/function can
5236 ;; terminate. These flags are used by endCheck() and by the Parser to
5237 ;; detect inconsistent return usage.
5238 ;;
5239 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5240 ;; able to execute (example: throw, continue)
5241 ;;
5242 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5243 ;; next one. Statement such as return dont. A compound statement may have
5244 ;; some branch that drops off control to the next statement.
5245 ;;
5246 ;; END_RETURNS indicates that the statement can return with no value.
5247 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5248 ;;
5249 ;; A compound statement such as
5250 ;; if (condition) {
5251 ;; return value;
5252 ;; }
5253 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5254
5255 (defconst js2-END_UNREACHED 0)
5256 (defconst js2-END_DROPS_OFF 1)
5257 (defconst js2-END_RETURNS 2)
5258 (defconst js2-END_RETURNS_VALUE 4)
5259 (defconst js2-END_YIELDS 8)
5260
5261 (defun js2-has-consistent-return-usage (node)
5262 "Check that every return usage in a function body is consistent.
5263 Returns t if the function satisfies strict mode requirement."
5264 (let ((n (js2-end-check node)))
5265 ;; either it doesn't return a value in any branch...
5266 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5267 ;; or it returns a value (or is unreached) at every branch
5268 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5269 js2-END_RETURNS
5270 js2-END_YIELDS)))))
5271
5272 (defun js2-end-check-if (node)
5273 "Ensure that return usage in then/else blocks is consistent.
5274 If there is no else block, then the return statement can fall through.
5275 Returns logical OR of END_* flags"
5276 (let ((th (js2-if-node-then-part node))
5277 (el (js2-if-node-else-part node)))
5278 (if (null th)
5279 js2-END_UNREACHED
5280 (logior (js2-end-check th) (if el
5281 (js2-end-check el)
5282 js2-END_DROPS_OFF)))))
5283
5284 (defun js2-end-check-switch (node)
5285 "Consistency of return statements is checked between the case statements.
5286 If there is no default, then the switch can fall through. If there is a
5287 default, we check to see if all code paths in the default return or if
5288 there is a code path that can fall through.
5289 Returns logical OR of END_* flags."
5290 (let ((rv js2-END_UNREACHED)
5291 default-case)
5292 ;; examine the cases
5293 (catch 'break
5294 (dolist (c (js2-switch-node-cases node))
5295 (if (js2-case-node-expr c)
5296 (js2-set-flag rv (js2-end-check-block c))
5297 (setq default-case c)
5298 (throw 'break nil))))
5299 ;; we don't care how the cases drop into each other
5300 (js2-clear-flag rv js2-END_DROPS_OFF)
5301 ;; examine the default
5302 (js2-set-flag rv (if default-case
5303 (js2-end-check default-case)
5304 js2-END_DROPS_OFF))
5305 rv))
5306
5307 (defun js2-end-check-try (node)
5308 "If the block has a finally, return consistency is checked in the
5309 finally block. If all code paths in the finally return, then the
5310 returns in the try-catch blocks don't matter. If there is a code path
5311 that does not return or if there is no finally block, the returns
5312 of the try and catch blocks are checked for mismatch.
5313 Returns logical OR of END_* flags."
5314 (let ((finally (js2-try-node-finally-block node))
5315 rv)
5316 ;; check the finally if it exists
5317 (setq rv (if finally
5318 (js2-end-check (js2-finally-node-body finally))
5319 js2-END_DROPS_OFF))
5320 ;; If the finally block always returns, then none of the returns
5321 ;; in the try or catch blocks matter.
5322 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5323 (js2-clear-flag rv js2-END_DROPS_OFF)
5324 ;; examine the try block
5325 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5326 ;; check each catch block
5327 (dolist (cb (js2-try-node-catch-clauses node))
5328 (js2-set-flag rv (js2-end-check cb))))
5329 rv))
5330
5331 (defun js2-end-check-loop (node)
5332 "Return statement in the loop body must be consistent.
5333 The default assumption for any kind of a loop is that it will eventually
5334 terminate. The only exception is a loop with a constant true condition.
5335 Code that follows such a loop is examined only if one can determine
5336 statically that there is a break out of the loop.
5337
5338 for(... ; ... ; ...) {}
5339 for(... in ... ) {}
5340 while(...) { }
5341 do { } while(...)
5342
5343 Returns logical OR of END_* flags."
5344 (let ((rv (js2-end-check (js2-loop-node-body node)))
5345 (condition (cond
5346 ((js2-while-node-p node)
5347 (js2-while-node-condition node))
5348 ((js2-do-node-p node)
5349 (js2-do-node-condition node))
5350 ((js2-for-node-p node)
5351 (js2-for-node-condition node)))))
5352
5353 ;; check to see if the loop condition is always true
5354 (if (and condition
5355 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5356 (js2-clear-flag rv js2-END_DROPS_OFF))
5357
5358 ;; look for effect of breaks
5359 (js2-set-flag rv (js2-node-get-prop node
5360 'CONTROL_BLOCK_PROP
5361 js2-END_UNREACHED))
5362 rv))
5363
5364 (defun js2-end-check-block (node)
5365 "A general block of code is examined statement by statement.
5366 If any statement (even a compound one) returns in all branches, then
5367 subsequent statements are not examined.
5368 Returns logical OR of END_* flags."
5369 (let* ((rv js2-END_DROPS_OFF)
5370 (kids (js2-block-node-kids node))
5371 (n (car kids)))
5372 ;; Check each statement. If the statement can continue onto the next
5373 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5374 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5375 (js2-clear-flag rv js2-END_DROPS_OFF)
5376 (js2-set-flag rv (js2-end-check n))
5377 (setq kids (cdr kids)
5378 n (car kids)))
5379 rv))
5380
5381 (defun js2-end-check-label (node)
5382 "A labeled statement implies that there may be a break to the label.
5383 The function processes the labeled statement and then checks the
5384 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5385 particular label.
5386 Returns logical OR of END_* flags."
5387 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5388 (logior rv (js2-node-get-prop node
5389 'CONTROL_BLOCK_PROP
5390 js2-END_UNREACHED))))
5391
5392 (defun js2-end-check-break (node)
5393 "When a break is encountered annotate the statement being broken
5394 out of by setting its CONTROL_BLOCK_PROP property.
5395 Returns logical OR of END_* flags."
5396 (and (js2-break-node-target node)
5397 (js2-node-set-prop (js2-break-node-target node)
5398 'CONTROL_BLOCK_PROP
5399 js2-END_DROPS_OFF))
5400 js2-END_UNREACHED)
5401
5402 (defun js2-end-check (node)
5403 "Examine the body of a function, doing a basic reachability analysis.
5404 Returns a combination of flags END_* flags that indicate
5405 how the function execution can terminate. These constitute only the
5406 pessimistic set of termination conditions. It is possible that at
5407 runtime certain code paths will never be actually taken. Hence this
5408 analysis will flag errors in cases where there may not be errors.
5409 Returns logical OR of END_* flags"
5410 (let (kid)
5411 (cond
5412 ((js2-break-node-p node)
5413 (js2-end-check-break node))
5414 ((js2-expr-stmt-node-p node)
5415 (if (setq kid (js2-expr-stmt-node-expr node))
5416 (js2-end-check kid)
5417 js2-END_DROPS_OFF))
5418 ((or (js2-continue-node-p node)
5419 (js2-throw-node-p node))
5420 js2-END_UNREACHED)
5421 ((js2-return-node-p node)
5422 (if (setq kid (js2-return-node-retval node))
5423 js2-END_RETURNS_VALUE
5424 js2-END_RETURNS))
5425 ((js2-loop-node-p node)
5426 (js2-end-check-loop node))
5427 ((js2-switch-node-p node)
5428 (js2-end-check-switch node))
5429 ((js2-labeled-stmt-node-p node)
5430 (js2-end-check-label node))
5431 ((js2-if-node-p node)
5432 (js2-end-check-if node))
5433 ((js2-try-node-p node)
5434 (js2-end-check-try node))
5435 ((js2-block-node-p node)
5436 (if (null (js2-block-node-kids node))
5437 js2-END_DROPS_OFF
5438 (js2-end-check-block node)))
5439 ((js2-yield-node-p node)
5440 js2-END_YIELDS)
5441 (t
5442 js2-END_DROPS_OFF))))
5443
5444 (defun js2-always-defined-boolean-p (node)
5445 "Check if NODE always evaluates to true or false in boolean context.
5446 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5447 nor always false."
5448 (let ((tt (js2-node-type node))
5449 num)
5450 (cond
5451 ((or (= tt js2-FALSE) (= tt js2-NULL))
5452 'ALWAYS_FALSE)
5453 ((= tt js2-TRUE)
5454 'ALWAYS_TRUE)
5455 ((= tt js2-NUMBER)
5456 (setq num (js2-number-node-num-value node))
5457 (if (and (not (eq num 0.0e+NaN))
5458 (not (zerop num)))
5459 'ALWAYS_TRUE
5460 'ALWAYS_FALSE))
5461 (t
5462 nil))))
5463
5464 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5465 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5466
5467 (defvar js2-tokens nil
5468 "List of all defined token names.") ; initialized in `js2-token-names'
5469
5470 (defconst js2-token-names
5471 (let* ((names (make-vector js2-num-tokens -1))
5472 (case-fold-search nil) ; only match js2-UPPER_CASE
5473 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5474 (cl-loop for sym in syms
5475 for i from 0
5476 do
5477 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5478 (not (boundp sym)))
5479 (aset names (symbol-value sym) ; code, e.g. 152
5480 (downcase
5481 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5482 (push sym js2-tokens)))
5483 names)
5484 "Vector mapping int values to token string names, sans `js2-' prefix.")
5485
5486 (defun js2-tt-name (tok)
5487 "Return a string name for TOK, a token symbol or code.
5488 Signals an error if it's not a recognized token."
5489 (let ((code tok))
5490 (if (symbolp tok)
5491 (setq code (symbol-value tok)))
5492 (if (eq code -1)
5493 "ERROR"
5494 (if (and (numberp code)
5495 (not (cl-minusp code))
5496 (< code js2-num-tokens))
5497 (aref js2-token-names code)
5498 (error "Invalid token: %s" code)))))
5499
5500 (defsubst js2-tt-sym (tok)
5501 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5502 (intern (js2-tt-name tok)))
5503
5504 (defconst js2-token-codes
5505 (let ((table (make-hash-table :test 'eq :size 256)))
5506 (cl-loop for name across js2-token-names
5507 for sym = (intern (concat "js2-" (upcase name)))
5508 do
5509 (puthash sym (symbol-value sym) table))
5510 ;; clean up a few that are "wrong" in Rhino's token codes
5511 (puthash 'js2-DELETE js2-DELPROP table)
5512 table)
5513 "Hashtable mapping token type symbols to their bytecodes.")
5514
5515 (defsubst js2-tt-code (sym)
5516 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5517 (or (gethash sym js2-token-codes)
5518 (error "Invalid token symbol: %s " sym))) ; signal code bug
5519
5520 (defun js2-report-scan-error (msg &optional no-throw beg len)
5521 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5522 (js2-report-error msg nil
5523 (or beg (js2-current-token-beg))
5524 (or len (js2-current-token-len)))
5525 (unless no-throw
5526 (throw 'return js2-ERROR)))
5527
5528 (defun js2-set-string-from-buffer (token)
5529 "Set `string' and `end' slots for TOKEN, return the string."
5530 (setf (js2-token-end token) js2-ts-cursor
5531 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5532
5533 ;; TODO: could potentially avoid a lot of consing by allocating a
5534 ;; char buffer the way Rhino does.
5535 (defsubst js2-add-to-string (c)
5536 (push c js2-ts-string-buffer))
5537
5538 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5539 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5540 ;; any other character: when it's not part of the current token, we
5541 ;; unget it, allowing it to be read again by the following call.
5542 (defsubst js2-unget-char ()
5543 (cl-decf js2-ts-cursor))
5544
5545 ;; Rhino distinguishes \r and \n line endings. We don't need to
5546 ;; because we only scan from Emacs buffers, which always use \n.
5547 (defun js2-get-char ()
5548 "Read and return the next character from the input buffer.
5549 Increments `js2-ts-lineno' if the return value is a newline char.
5550 Updates `js2-ts-cursor' to the point after the returned char.
5551 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5552 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5553 (let (c)
5554 ;; check for end of buffer
5555 (if (>= js2-ts-cursor (point-max))
5556 (setq js2-ts-hit-eof t
5557 js2-ts-cursor (1+ js2-ts-cursor)
5558 c js2-EOF_CHAR) ; return value
5559 ;; otherwise read next char
5560 (setq c (char-before (cl-incf js2-ts-cursor)))
5561 ;; if we read a newline, update counters
5562 (if (= c ?\n)
5563 (setq js2-ts-line-start js2-ts-cursor
5564 js2-ts-lineno (1+ js2-ts-lineno)))
5565 ;; TODO: skip over format characters
5566 c)))
5567
5568 (defun js2-read-unicode-escape ()
5569 "Read a \\uNNNN sequence from the input.
5570 Assumes the ?\ and ?u have already been read.
5571 Returns the unicode character, or nil if it wasn't a valid character.
5572 Doesn't change the values of any scanner variables."
5573 ;; I really wish I knew a better way to do this, but I can't
5574 ;; find the Emacs function that takes a 16-bit int and converts
5575 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5576 ;; Have to first check that it's 4 hex characters or it may stop
5577 ;; the read early.
5578 (ignore-errors
5579 (let ((s (buffer-substring-no-properties js2-ts-cursor
5580 (+ 4 js2-ts-cursor))))
5581 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5582 (read (concat "?\\u" s))))))
5583
5584 (defun js2-match-char (test)
5585 "Consume and return next character if it matches TEST, a character.
5586 Returns nil and consumes nothing if TEST is not the next character."
5587 (let ((c (js2-get-char)))
5588 (if (eq c test)
5589 t
5590 (js2-unget-char)
5591 nil)))
5592
5593 (defun js2-peek-char ()
5594 (prog1
5595 (js2-get-char)
5596 (js2-unget-char)))
5597
5598 (defun js2-identifier-start-p (c)
5599 "Is C a valid start to an ES5 Identifier?
5600 See http://es5.github.io/#x7.6"
5601 (or
5602 (memq c '(?$ ?_))
5603 (memq (get-char-code-property c 'general-category)
5604 ;; Letters
5605 '(Lu Ll Lt Lm Lo Nl))))
5606
5607 (defun js2-identifier-part-p (c)
5608 "Is C a valid part of an ES5 Identifier?
5609 See http://es5.github.io/#x7.6"
5610 (or
5611 (memq c '(?$ ?_ ?\u200c ?\u200d))
5612 (memq (get-char-code-property c 'general-category)
5613 '(;; Letters
5614 Lu Ll Lt Lm Lo Nl
5615 ;; Combining Marks
5616 Mn Mc
5617 ;; Digits
5618 Nd
5619 ;; Connector Punctuation
5620 Pc))))
5621
5622 (defun js2-alpha-p (c)
5623 (cond ((and (<= ?A c) (<= c ?Z)) t)
5624 ((and (<= ?a c) (<= c ?z)) t)
5625 (t nil)))
5626
5627 (defsubst js2-digit-p (c)
5628 (and (<= ?0 c) (<= c ?9)))
5629
5630 (defun js2-js-space-p (c)
5631 (if (<= c 127)
5632 (memq c '(#x20 #x9 #xB #xC #xD))
5633 (or
5634 (eq c #xA0)
5635 ;; TODO: change this nil to check for Unicode space character
5636 nil)))
5637
5638 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5639
5640 (defun js2-skip-line ()
5641 "Skip to end of line."
5642 (while (not (memq (js2-get-char) js2-eol-chars)))
5643 (js2-unget-char)
5644 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5645
5646 (defun js2-init-scanner (&optional buf line)
5647 "Create token stream for BUF starting on LINE.
5648 BUF defaults to `current-buffer' and LINE defaults to 1.
5649
5650 A buffer can only have one scanner active at a time, which yields
5651 dramatically simpler code than using a defstruct. If you need to
5652 have simultaneous scanners in a buffer, copy the regions to scan
5653 into temp buffers."
5654 (with-current-buffer (or buf (current-buffer))
5655 (setq js2-ts-dirty-line nil
5656 js2-ts-hit-eof nil
5657 js2-ts-line-start 0
5658 js2-ts-lineno (or line 1)
5659 js2-ts-line-end-char -1
5660 js2-ts-cursor (point-min)
5661 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5662 js2-ti-tokens-cursor 0
5663 js2-ti-lookahead 0
5664 js2-ts-is-xml-attribute nil
5665 js2-ts-xml-is-tag-content nil
5666 js2-ts-xml-open-tags-count 0
5667 js2-ts-string-buffer nil)))
5668
5669 ;; This function uses the cached op, string and number fields in
5670 ;; TokenStream; if getToken has been called since the passed token
5671 ;; was scanned, the op or string printed may be incorrect.
5672 (defun js2-token-to-string (token)
5673 ;; Not sure where this function is used in Rhino. Not tested.
5674 (if (not js2-debug-print-trees)
5675 ""
5676 (let ((name (js2-tt-name token)))
5677 (cond
5678 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5679 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5680 (concat name " `" (js2-current-token-string) "'"))
5681 ((eq token js2-NUMBER)
5682 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5683 (t
5684 name)))))
5685
5686 (defconst js2-keywords
5687 '(break
5688 case catch class const continue
5689 debugger default delete do
5690 else extends export
5691 false finally for function
5692 if in instanceof import
5693 let
5694 new null
5695 return
5696 super switch
5697 this throw true try typeof
5698 var void
5699 while with
5700 yield))
5701
5702 ;; Token names aren't exactly the same as the keywords, unfortunately.
5703 ;; E.g. delete is js2-DELPROP.
5704 (defconst js2-kwd-tokens
5705 (let ((table (make-vector js2-num-tokens nil))
5706 (tokens
5707 (list js2-BREAK
5708 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5709 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5710 js2-ELSE js2-EXPORT
5711 js2-ELSE js2-EXTENDS js2-EXPORT
5712 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5713 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5714 js2-LET
5715 js2-NEW js2-NULL
5716 js2-RETURN
5717 js2-SUPER js2-SWITCH
5718 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5719 js2-VAR
5720 js2-WHILE js2-WITH
5721 js2-YIELD)))
5722 (dolist (i tokens)
5723 (aset table i 'font-lock-keyword-face))
5724 (aset table js2-STRING 'font-lock-string-face)
5725 (aset table js2-REGEXP 'font-lock-string-face)
5726 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5727 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5728 (aset table js2-COMMENT 'font-lock-comment-face)
5729 (aset table js2-THIS 'font-lock-builtin-face)
5730 (aset table js2-SUPER 'font-lock-builtin-face)
5731 (aset table js2-VOID 'font-lock-constant-face)
5732 (aset table js2-NULL 'font-lock-constant-face)
5733 (aset table js2-TRUE 'font-lock-constant-face)
5734 (aset table js2-FALSE 'font-lock-constant-face)
5735 (aset table js2-NOT 'font-lock-negation-char-face)
5736 table)
5737 "Vector whose values are non-nil for tokens that are keywords.
5738 The values are default faces to use for highlighting the keywords.")
5739
5740 ;; FIXME: Support strict mode-only future reserved words, after we know
5741 ;; which parts scopes are in strict mode, and which are not.
5742 (defconst js2-reserved-words '(class enum export extends import static super)
5743 "Future reserved keywords in ECMAScript 5.1.")
5744
5745 (defconst js2-keyword-names
5746 (let ((table (make-hash-table :test 'equal)))
5747 (cl-loop for k in js2-keywords
5748 do (puthash
5749 (symbol-name k) ; instanceof
5750 (intern (concat "js2-"
5751 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5752 table))
5753 table)
5754 "JavaScript keywords by name, mapped to their symbols.")
5755
5756 (defconst js2-reserved-word-names
5757 (let ((table (make-hash-table :test 'equal)))
5758 (cl-loop for k in js2-reserved-words
5759 do
5760 (puthash (symbol-name k) 'js2-RESERVED table))
5761 table)
5762 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5763
5764 (defun js2-collect-string (buf)
5765 "Convert BUF, a list of chars, to a string.
5766 Reverses BUF before converting."
5767 (if buf
5768 (apply #'string (nreverse buf))
5769 ""))
5770
5771 (defun js2-string-to-keyword (s)
5772 "Return token for S, a string, if S is a keyword or reserved word.
5773 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5774 (or (gethash s js2-keyword-names)
5775 (gethash s js2-reserved-word-names)))
5776
5777 (defsubst js2-ts-set-char-token-bounds (token)
5778 "Used when next token is one character."
5779 (setf (js2-token-beg token) (1- js2-ts-cursor)
5780 (js2-token-end token) js2-ts-cursor))
5781
5782 (defsubst js2-ts-return (token type)
5783 "Update the `end' and `type' slots of TOKEN,
5784 then throw `return' with value TYPE."
5785 (setf (js2-token-end token) js2-ts-cursor
5786 (js2-token-type token) type)
5787 (throw 'return type))
5788
5789 (defun js2-x-digit-to-int (c accumulator)
5790 "Build up a hex number.
5791 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5792 corresponding number. Otherwise return -1."
5793 (catch 'return
5794 (catch 'check
5795 ;; Use 0..9 < A..Z < a..z
5796 (cond
5797 ((<= c ?9)
5798 (cl-decf c ?0)
5799 (if (<= 0 c)
5800 (throw 'check nil)))
5801 ((<= c ?F)
5802 (when (<= ?A c)
5803 (cl-decf c (- ?A 10))
5804 (throw 'check nil)))
5805 ((<= c ?f)
5806 (when (<= ?a c)
5807 (cl-decf c (- ?a 10))
5808 (throw 'check nil))))
5809 (throw 'return -1))
5810 (logior c (lsh accumulator 4))))
5811
5812 (defun js2-get-token (&optional modifier)
5813 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5814 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5815 next saved token.
5816
5817 This function will not return a newline (js2-EOL) - instead, it
5818 gobbles newlines until it finds a non-newline token. Call
5819 `js2-peek-token-or-eol' when you care about newlines.
5820
5821 This function will also not return a js2-COMMENT. Instead, it
5822 records comments found in `js2-scanned-comments'. If the token
5823 returned by this function immediately follows a jsdoc comment,
5824 the token is flagged as such."
5825 (if (zerop js2-ti-lookahead)
5826 (js2-get-token-internal modifier)
5827 (cl-decf js2-ti-lookahead)
5828 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5829 (let ((tt (js2-current-token-type)))
5830 (cl-assert (not (= tt js2-EOL)))
5831 tt)))
5832
5833 (defun js2-unget-token ()
5834 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5835 (cl-incf js2-ti-lookahead)
5836 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5837
5838 (defun js2-get-token-internal (modifier)
5839 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5840 (tt (js2-token-type token))
5841 saw-eol
5842 face)
5843 ;; process comments
5844 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5845 (if (= tt js2-EOL)
5846 (setq saw-eol t)
5847 (setq saw-eol nil)
5848 (when js2-record-comments
5849 (js2-record-comment token)))
5850 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5851 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5852 tt (js2-token-type token)))
5853
5854 (when saw-eol
5855 (setf (js2-token-follows-eol-p token) t))
5856
5857 ;; perform lexical fontification as soon as token is scanned
5858 (when js2-parse-ide-mode
5859 (cond
5860 ((cl-minusp tt)
5861 (js2-record-face 'js2-error token))
5862 ((setq face (aref js2-kwd-tokens tt))
5863 (js2-record-face face token))
5864 ((and (= tt js2-NAME)
5865 (equal (js2-token-string token) "undefined"))
5866 (js2-record-face 'font-lock-constant-face token))))
5867 tt))
5868
5869 (defsubst js2-string-to-number (str base)
5870 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5871 (condition-case nil
5872 (string-to-number str base)
5873 (overflow-error -1)))
5874
5875 (defun js2-get-token-internal-1 (modifier)
5876 "Return next JavaScript token type, an int such as js2-RETURN.
5877 During operation, creates an instance of `js2-token' struct, sets
5878 its relevant fields and puts it into `js2-ti-tokens'."
5879 (let (identifier-start
5880 is-unicode-escape-start c
5881 contains-escape escape-val str result base
5882 look-for-slash continue tt
5883 (token (js2-new-token 0)))
5884 (setq
5885 tt
5886 (catch 'return
5887 (when (eq modifier 'TEMPLATE_TAIL)
5888 (setf (js2-token-beg token) (1- js2-ts-cursor))
5889 (throw 'return (js2-get-string-or-template-token ?` token)))
5890 (while t
5891 ;; Eat whitespace, possibly sensitive to newlines.
5892 (setq continue t)
5893 (while continue
5894 (setq c (js2-get-char))
5895 (cond
5896 ((eq c js2-EOF_CHAR)
5897 (js2-unget-char)
5898 (js2-ts-set-char-token-bounds token)
5899 (throw 'return js2-EOF))
5900 ((eq c ?\n)
5901 (js2-ts-set-char-token-bounds token)
5902 (setq js2-ts-dirty-line nil)
5903 (throw 'return js2-EOL))
5904 ((not (js2-js-space-p c))
5905 (if (/= c ?-) ; in case end of HTML comment
5906 (setq js2-ts-dirty-line t))
5907 (setq continue nil))))
5908 ;; Assume the token will be 1 char - fixed up below.
5909 (js2-ts-set-char-token-bounds token)
5910 (when (eq c ?@)
5911 (throw 'return js2-XMLATTR))
5912 ;; identifier/keyword/instanceof?
5913 ;; watch out for starting with a <backslash>
5914 (cond
5915 ((eq c ?\\)
5916 (setq c (js2-get-char))
5917 (if (eq c ?u)
5918 (setq identifier-start t
5919 is-unicode-escape-start t
5920 js2-ts-string-buffer nil)
5921 (setq identifier-start nil)
5922 (js2-unget-char)
5923 (setq c ?\\)))
5924 (t
5925 (when (setq identifier-start (js2-identifier-start-p c))
5926 (setq js2-ts-string-buffer nil)
5927 (js2-add-to-string c))))
5928 (when identifier-start
5929 (setq contains-escape is-unicode-escape-start)
5930 (catch 'break
5931 (while t
5932 (if is-unicode-escape-start
5933 ;; strictly speaking we should probably push-back
5934 ;; all the bad characters if the <backslash>uXXXX
5935 ;; sequence is malformed. But since there isn't a
5936 ;; correct context(is there?) for a bad Unicode
5937 ;; escape sequence in an identifier, we can report
5938 ;; an error here.
5939 (progn
5940 (setq escape-val 0)
5941 (dotimes (_ 4)
5942 (setq c (js2-get-char)
5943 escape-val (js2-x-digit-to-int c escape-val))
5944 ;; Next check takes care of c < 0 and bad escape
5945 (if (cl-minusp escape-val)
5946 (throw 'break nil)))
5947 (if (cl-minusp escape-val)
5948 (js2-report-scan-error "msg.invalid.escape" t))
5949 (js2-add-to-string escape-val)
5950 (setq is-unicode-escape-start nil))
5951 (setq c (js2-get-char))
5952 (cond
5953 ((eq c ?\\)
5954 (setq c (js2-get-char))
5955 (if (eq c ?u)
5956 (setq is-unicode-escape-start t
5957 contains-escape t)
5958 (js2-report-scan-error "msg.illegal.character" t)))
5959 (t
5960 (if (or (eq c js2-EOF_CHAR)
5961 (not (js2-identifier-part-p c)))
5962 (throw 'break nil))
5963 (js2-add-to-string c))))))
5964 (js2-unget-char)
5965 (setf str (js2-collect-string js2-ts-string-buffer)
5966 (js2-token-end token) js2-ts-cursor)
5967 ;; FIXME: Invalid in ES5 and ES6, see
5968 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5969 ;; Probably should just drop this conditional.
5970 (unless contains-escape
5971 ;; OPT we shouldn't have to make a string (object!) to
5972 ;; check if it's a keyword.
5973 ;; Return the corresponding token if it's a keyword
5974 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5975 (setq result (js2-string-to-keyword str)))
5976 (if (and (< js2-language-version 170)
5977 (memq result '(js2-LET js2-YIELD)))
5978 ;; LET and YIELD are tokens only in 1.7 and later
5979 (setq result 'js2-NAME))
5980 (when (eq result 'js2-RESERVED)
5981 (setf (js2-token-string token) str))
5982 (throw 'return (js2-tt-code result))))
5983 ;; If we want to intern these as Rhino does, just use (intern str)
5984 (setf (js2-token-string token) str)
5985 (throw 'return js2-NAME)) ; end identifier/kwd check
5986 ;; is it a number?
5987 (when (or (js2-digit-p c)
5988 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5989 (setq js2-ts-string-buffer nil
5990 base 10)
5991 (when (eq c ?0)
5992 (setq c (js2-get-char))
5993 (cond
5994 ((or (eq c ?x) (eq c ?X))
5995 (setq base 16)
5996 (setq c (js2-get-char)))
5997 ((and (or (eq c ?b) (eq c ?B))
5998 (>= js2-language-version 200))
5999 (setq base 2)
6000 (setq c (js2-get-char)))
6001 ((and (or (eq c ?o) (eq c ?O))
6002 (>= js2-language-version 200))
6003 (setq base 8)
6004 (setq c (js2-get-char)))
6005 ((js2-digit-p c)
6006 (setq base 'maybe-8))
6007 (t
6008 (js2-add-to-string ?0))))
6009 (cond
6010 ((eq base 16)
6011 (if (> 0 (js2-x-digit-to-int c 0))
6012 (js2-report-scan-error "msg.missing.hex.digits")
6013 (while (<= 0 (js2-x-digit-to-int c 0))
6014 (js2-add-to-string c)
6015 (setq c (js2-get-char)))))
6016 ((eq base 2)
6017 (if (not (memq c '(?0 ?1)))
6018 (js2-report-scan-error "msg.missing.binary.digits")
6019 (while (memq c '(?0 ?1))
6020 (js2-add-to-string c)
6021 (setq c (js2-get-char)))))
6022 ((eq base 8)
6023 (if (or (> ?0 c) (< ?7 c))
6024 (js2-report-scan-error "msg.missing.octal.digits")
6025 (while (and (<= ?0 c) (>= ?7 c))
6026 (js2-add-to-string c)
6027 (setq c (js2-get-char)))))
6028 (t
6029 (while (and (<= ?0 c) (<= c ?9))
6030 ;; We permit 08 and 09 as decimal numbers, which
6031 ;; makes our behavior a superset of the ECMA
6032 ;; numeric grammar. We might not always be so
6033 ;; permissive, so we warn about it.
6034 (when (and (eq base 'maybe-8) (>= c ?8))
6035 (js2-report-warning "msg.bad.octal.literal"
6036 (if (eq c ?8) "8" "9"))
6037 (setq base 10))
6038 (js2-add-to-string c)
6039 (setq c (js2-get-char)))
6040 (when (eq base 'maybe-8)
6041 (setq base 8))))
6042 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6043 (when (eq c ?.)
6044 (cl-loop do
6045 (js2-add-to-string c)
6046 (setq c (js2-get-char))
6047 while (js2-digit-p c)))
6048 (when (memq c '(?e ?E))
6049 (js2-add-to-string c)
6050 (setq c (js2-get-char))
6051 (when (memq c '(?+ ?-))
6052 (js2-add-to-string c)
6053 (setq c (js2-get-char)))
6054 (unless (js2-digit-p c)
6055 (js2-report-scan-error "msg.missing.exponent" t))
6056 (cl-loop do
6057 (js2-add-to-string c)
6058 (setq c (js2-get-char))
6059 while (js2-digit-p c))))
6060 (js2-unget-char)
6061 (let ((str (js2-set-string-from-buffer token)))
6062 (setf (js2-token-number token) (js2-string-to-number str base)
6063 (js2-token-number-base token) base))
6064 (throw 'return js2-NUMBER))
6065 ;; is it a string?
6066 (when (or (memq c '(?\" ?\'))
6067 (and (>= js2-language-version 200)
6068 (= c ?`)))
6069 (throw 'return
6070 (js2-get-string-or-template-token c token)))
6071 (js2-ts-return token
6072 (cl-case c
6073 (?\;
6074 (throw 'return js2-SEMI))
6075 (?\[
6076 (throw 'return js2-LB))
6077 (?\]
6078 (throw 'return js2-RB))
6079 (?{
6080 (throw 'return js2-LC))
6081 (?}
6082 (throw 'return js2-RC))
6083 (?\(
6084 (throw 'return js2-LP))
6085 (?\)
6086 (throw 'return js2-RP))
6087 (?,
6088 (throw 'return js2-COMMA))
6089 (??
6090 (throw 'return js2-HOOK))
6091 (?:
6092 (if (js2-match-char ?:)
6093 js2-COLONCOLON
6094 (throw 'return js2-COLON)))
6095 (?.
6096 (if (js2-match-char ?.)
6097 (if (js2-match-char ?.)
6098 js2-TRIPLEDOT js2-DOTDOT)
6099 (if (js2-match-char ?\()
6100 js2-DOTQUERY
6101 (throw 'return js2-DOT))))
6102 (?|
6103 (if (js2-match-char ?|)
6104 (throw 'return js2-OR)
6105 (if (js2-match-char ?=)
6106 js2-ASSIGN_BITOR
6107 (throw 'return js2-BITOR))))
6108 (?^
6109 (if (js2-match-char ?=)
6110 js2-ASSIGN_BITOR
6111 (throw 'return js2-BITXOR)))
6112 (?&
6113 (if (js2-match-char ?&)
6114 (throw 'return js2-AND)
6115 (if (js2-match-char ?=)
6116 js2-ASSIGN_BITAND
6117 (throw 'return js2-BITAND))))
6118 (?=
6119 (if (js2-match-char ?=)
6120 (if (js2-match-char ?=)
6121 js2-SHEQ
6122 (throw 'return js2-EQ))
6123 (if (js2-match-char ?>)
6124 (js2-ts-return token js2-ARROW)
6125 (throw 'return js2-ASSIGN))))
6126 (?!
6127 (if (js2-match-char ?=)
6128 (if (js2-match-char ?=)
6129 js2-SHNE
6130 js2-NE)
6131 (throw 'return js2-NOT)))
6132 (?<
6133 ;; NB:treat HTML begin-comment as comment-till-eol
6134 (when (js2-match-char ?!)
6135 (when (js2-match-char ?-)
6136 (when (js2-match-char ?-)
6137 (js2-skip-line)
6138 (setf (js2-token-comment-type (js2-current-token)) 'html)
6139 (throw 'return js2-COMMENT)))
6140 (js2-unget-char))
6141 (if (js2-match-char ?<)
6142 (if (js2-match-char ?=)
6143 js2-ASSIGN_LSH
6144 js2-LSH)
6145 (if (js2-match-char ?=)
6146 js2-LE
6147 (throw 'return js2-LT))))
6148 (?>
6149 (if (js2-match-char ?>)
6150 (if (js2-match-char ?>)
6151 (if (js2-match-char ?=)
6152 js2-ASSIGN_URSH
6153 js2-URSH)
6154 (if (js2-match-char ?=)
6155 js2-ASSIGN_RSH
6156 js2-RSH))
6157 (if (js2-match-char ?=)
6158 js2-GE
6159 (throw 'return js2-GT))))
6160 (?*
6161 (if (js2-match-char ?=)
6162 js2-ASSIGN_MUL
6163 (throw 'return js2-MUL)))
6164 (?/
6165 ;; is it a // comment?
6166 (when (js2-match-char ?/)
6167 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6168 (js2-skip-line)
6169 (setf (js2-token-comment-type token) 'line)
6170 ;; include newline so highlighting goes to end of
6171 ;; window, if there actually is a newline; if we
6172 ;; hit eof, then implicitly there isn't
6173 (unless js2-ts-hit-eof
6174 (cl-incf (js2-token-end token)))
6175 (throw 'return js2-COMMENT))
6176 ;; is it a /* comment?
6177 (when (js2-match-char ?*)
6178 (setf look-for-slash nil
6179 (js2-token-beg token) (- js2-ts-cursor 2)
6180 (js2-token-comment-type token)
6181 (if (js2-match-char ?*)
6182 (progn
6183 (setq look-for-slash t)
6184 'jsdoc)
6185 'block))
6186 (while t
6187 (setq c (js2-get-char))
6188 (cond
6189 ((eq c js2-EOF_CHAR)
6190 (setf (js2-token-end token) (1- js2-ts-cursor))
6191 (js2-report-error "msg.unterminated.comment")
6192 (throw 'return js2-COMMENT))
6193 ((eq c ?*)
6194 (setq look-for-slash t))
6195 ((eq c ?/)
6196 (if look-for-slash
6197 (js2-ts-return token js2-COMMENT)))
6198 (t
6199 (setf look-for-slash nil
6200 (js2-token-end token) js2-ts-cursor)))))
6201 (if (js2-match-char ?=)
6202 js2-ASSIGN_DIV
6203 (throw 'return js2-DIV)))
6204 (?#
6205 (when js2-skip-preprocessor-directives
6206 (js2-skip-line)
6207 (setf (js2-token-comment-type token) 'preprocessor
6208 (js2-token-end token) js2-ts-cursor)
6209 (throw 'return js2-COMMENT))
6210 (throw 'return js2-ERROR))
6211 (?%
6212 (if (js2-match-char ?=)
6213 js2-ASSIGN_MOD
6214 (throw 'return js2-MOD)))
6215 (?~
6216 (throw 'return js2-BITNOT))
6217 (?+
6218 (if (js2-match-char ?=)
6219 js2-ASSIGN_ADD
6220 (if (js2-match-char ?+)
6221 js2-INC
6222 (throw 'return js2-ADD))))
6223 (?-
6224 (cond
6225 ((js2-match-char ?=)
6226 (setq c js2-ASSIGN_SUB))
6227 ((js2-match-char ?-)
6228 (unless js2-ts-dirty-line
6229 ;; treat HTML end-comment after possible whitespace
6230 ;; after line start as comment-until-eol
6231 (when (js2-match-char ?>)
6232 (js2-skip-line)
6233 (setf (js2-token-comment-type (js2-current-token)) 'html)
6234 (throw 'return js2-COMMENT)))
6235 (setq c js2-DEC))
6236 (t
6237 (setq c js2-SUB)))
6238 (setq js2-ts-dirty-line t)
6239 c)
6240 (otherwise
6241 (js2-report-scan-error "msg.illegal.character")))))))
6242 (setf (js2-token-type token) tt)
6243 token))
6244
6245 (defun js2-get-string-or-template-token (quote-char token)
6246 ;; We attempt to accumulate a string the fast way, by
6247 ;; building it directly out of the reader. But if there
6248 ;; are any escaped characters in the string, we revert to
6249 ;; building it out of a string buffer.
6250 (let ((c (js2-get-char))
6251 js2-ts-string-buffer
6252 nc c1 val escape-val)
6253 (catch 'break
6254 (while (/= c quote-char)
6255 (catch 'continue
6256 (when (eq c js2-EOF_CHAR)
6257 (js2-unget-char)
6258 (js2-report-error "msg.unterminated.string.lit")
6259 (throw 'break nil))
6260 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6261 (js2-unget-char)
6262 (js2-report-error "msg.unterminated.string.lit")
6263 (throw 'break nil))
6264 (when (eq c ?\\)
6265 ;; We've hit an escaped character
6266 (setq c (js2-get-char))
6267 (cl-case c
6268 (?b (setq c ?\b))
6269 (?f (setq c ?\f))
6270 (?n (setq c ?\n))
6271 (?r (setq c ?\r))
6272 (?t (setq c ?\t))
6273 (?v (setq c ?\v))
6274 (?u
6275 (setq c1 (js2-read-unicode-escape))
6276 (if js2-parse-ide-mode
6277 (if c1
6278 (progn
6279 ;; just copy the string in IDE-mode
6280 (js2-add-to-string ?\\)
6281 (js2-add-to-string ?u)
6282 (dotimes (_ 3)
6283 (js2-add-to-string (js2-get-char)))
6284 (setq c (js2-get-char))) ; added at end of loop
6285 ;; flag it as an invalid escape
6286 (js2-report-warning "msg.invalid.escape"
6287 nil (- js2-ts-cursor 2) 6))
6288 ;; Get 4 hex digits; if the u escape is not
6289 ;; followed by 4 hex digits, use 'u' + the
6290 ;; literal character sequence that follows.
6291 (js2-add-to-string ?u)
6292 (setq escape-val 0)
6293 (dotimes (_ 4)
6294 (setq c (js2-get-char)
6295 escape-val (js2-x-digit-to-int c escape-val))
6296 (if (cl-minusp escape-val)
6297 (throw 'continue nil))
6298 (js2-add-to-string c))
6299 ;; prepare for replace of stored 'u' sequence by escape value
6300 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6301 c escape-val)))
6302 (?x
6303 ;; Get 2 hex digits, defaulting to 'x'+literal
6304 ;; sequence, as above.
6305 (setq c (js2-get-char)
6306 escape-val (js2-x-digit-to-int c 0))
6307 (if (cl-minusp escape-val)
6308 (progn
6309 (js2-add-to-string ?x)
6310 (throw 'continue nil))
6311 (setq c1 c
6312 c (js2-get-char)
6313 escape-val (js2-x-digit-to-int c escape-val))
6314 (if (cl-minusp escape-val)
6315 (progn
6316 (js2-add-to-string ?x)
6317 (js2-add-to-string c1)
6318 (throw 'continue nil))
6319 ;; got 2 hex digits
6320 (setq c escape-val))))
6321 (?\n
6322 ;; Remove line terminator after escape to follow
6323 ;; SpiderMonkey and C/C++
6324 (setq c (js2-get-char))
6325 (throw 'continue nil))
6326 (t
6327 (when (and (<= ?0 c) (< c ?8))
6328 (setq val (- c ?0)
6329 c (js2-get-char))
6330 (when (and (<= ?0 c) (< c ?8))
6331 (setq val (- (+ (* 8 val) c) ?0)
6332 c (js2-get-char))
6333 (when (and (<= ?0 c)
6334 (< c ?8)
6335 (< val #o37))
6336 ;; c is 3rd char of octal sequence only
6337 ;; if the resulting val <= 0377
6338 (setq val (- (+ (* 8 val) c) ?0)
6339 c (js2-get-char))))
6340 (js2-unget-char)
6341 (setq c val)))))
6342 (when (and (eq quote-char ?`) (eq c ?$))
6343 (when (eq (setq nc (js2-get-char)) ?\{)
6344 (throw 'break nil))
6345 (js2-unget-char))
6346 (js2-add-to-string c)
6347 (setq c (js2-get-char)))))
6348 (js2-set-string-from-buffer token)
6349 (if (not (eq quote-char ?`))
6350 js2-STRING
6351 (if (and (eq c ?$) (eq nc ?\{))
6352 js2-TEMPLATE_HEAD
6353 js2-NO_SUBS_TEMPLATE))))
6354
6355 (defun js2-read-regexp (start-tt)
6356 "Called by parser when it gets / or /= in literal context."
6357 (let (c err
6358 in-class ; inside a '[' .. ']' character-class
6359 flags
6360 (continue t)
6361 (token (js2-new-token 0)))
6362 (setq js2-ts-string-buffer nil)
6363 (if (eq start-tt js2-ASSIGN_DIV)
6364 ;; mis-scanned /=
6365 (js2-add-to-string ?=)
6366 (if (not (eq start-tt js2-DIV))
6367 (error "failed assertion")))
6368 (while (and (not err)
6369 (or (/= (setq c (js2-get-char)) ?/)
6370 in-class))
6371 (cond
6372 ((or (= c ?\n)
6373 (= c js2-EOF_CHAR))
6374 (setf (js2-token-end token) (1- js2-ts-cursor)
6375 err t
6376 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6377 (js2-report-error "msg.unterminated.re.lit"))
6378 (t (cond
6379 ((= c ?\\)
6380 (js2-add-to-string c)
6381 (setq c (js2-get-char)))
6382 ((= c ?\[)
6383 (setq in-class t))
6384 ((= c ?\])
6385 (setq in-class nil)))
6386 (js2-add-to-string c))))
6387 (unless err
6388 (while continue
6389 (cond
6390 ((js2-match-char ?g)
6391 (push ?g flags))
6392 ((js2-match-char ?i)
6393 (push ?i flags))
6394 ((js2-match-char ?m)
6395 (push ?m flags))
6396 ((and (js2-match-char ?u)
6397 (>= js2-language-version 200))
6398 (push ?u flags))
6399 ((and (js2-match-char ?y)
6400 (>= js2-language-version 200))
6401 (push ?y flags))
6402 (t
6403 (setq continue nil))))
6404 (if (js2-alpha-p (js2-peek-char))
6405 (js2-report-scan-error "msg.invalid.re.flag" t
6406 js2-ts-cursor 1))
6407 (js2-set-string-from-buffer token))
6408 (js2-collect-string flags)))
6409
6410 (defun js2-get-first-xml-token ()
6411 (setq js2-ts-xml-open-tags-count 0
6412 js2-ts-is-xml-attribute nil
6413 js2-ts-xml-is-tag-content nil)
6414 (js2-unget-char)
6415 (js2-get-next-xml-token))
6416
6417 (defun js2-xml-discard-string (token)
6418 "Throw away the string in progress and flag an XML parse error."
6419 (setf js2-ts-string-buffer nil
6420 (js2-token-string token) nil)
6421 (js2-report-scan-error "msg.XML.bad.form" t))
6422
6423 (defun js2-get-next-xml-token ()
6424 (setq js2-ts-string-buffer nil) ; for recording the XML
6425 (let ((token (js2-new-token 0))
6426 c result)
6427 (setq result
6428 (catch 'return
6429 (while t
6430 (setq c (js2-get-char))
6431 (cond
6432 ((= c js2-EOF_CHAR)
6433 (throw 'return js2-ERROR))
6434 (js2-ts-xml-is-tag-content
6435 (cl-case c
6436 (?>
6437 (js2-add-to-string c)
6438 (setq js2-ts-xml-is-tag-content nil
6439 js2-ts-is-xml-attribute nil))
6440 (?/
6441 (js2-add-to-string c)
6442 (when (eq ?> (js2-peek-char))
6443 (setq c (js2-get-char))
6444 (js2-add-to-string c)
6445 (setq js2-ts-xml-is-tag-content nil)
6446 (cl-decf js2-ts-xml-open-tags-count)))
6447 (?{
6448 (js2-unget-char)
6449 (js2-set-string-from-buffer token)
6450 (throw 'return js2-XML))
6451 ((?\' ?\")
6452 (js2-add-to-string c)
6453 (unless (js2-read-quoted-string c token)
6454 (throw 'return js2-ERROR)))
6455 (?=
6456 (js2-add-to-string c)
6457 (setq js2-ts-is-xml-attribute t))
6458 ((? ?\t ?\r ?\n)
6459 (js2-add-to-string c))
6460 (t
6461 (js2-add-to-string c)
6462 (setq js2-ts-is-xml-attribute nil)))
6463 (when (and (not js2-ts-xml-is-tag-content)
6464 (zerop js2-ts-xml-open-tags-count))
6465 (js2-set-string-from-buffer token)
6466 (throw 'return js2-XMLEND)))
6467 (t
6468 ;; else not tag content
6469 (cl-case c
6470 (?<
6471 (js2-add-to-string c)
6472 (setq c (js2-peek-char))
6473 (cl-case c
6474 (?!
6475 (setq c (js2-get-char)) ;; skip !
6476 (js2-add-to-string c)
6477 (setq c (js2-peek-char))
6478 (cl-case c
6479 (?-
6480 (setq c (js2-get-char)) ;; skip -
6481 (js2-add-to-string c)
6482 (if (eq c ?-)
6483 (progn
6484 (js2-add-to-string c)
6485 (unless (js2-read-xml-comment token)
6486 (throw 'return js2-ERROR)))
6487 (js2-xml-discard-string token)
6488 (throw 'return js2-ERROR)))
6489 (?\[
6490 (setq c (js2-get-char)) ;; skip [
6491 (js2-add-to-string c)
6492 (if (and (= (js2-get-char) ?C)
6493 (= (js2-get-char) ?D)
6494 (= (js2-get-char) ?A)
6495 (= (js2-get-char) ?T)
6496 (= (js2-get-char) ?A)
6497 (= (js2-get-char) ?\[))
6498 (progn
6499 (js2-add-to-string ?C)
6500 (js2-add-to-string ?D)
6501 (js2-add-to-string ?A)
6502 (js2-add-to-string ?T)
6503 (js2-add-to-string ?A)
6504 (js2-add-to-string ?\[)
6505 (unless (js2-read-cdata token)
6506 (throw 'return js2-ERROR)))
6507 (js2-xml-discard-string token)
6508 (throw 'return js2-ERROR)))
6509 (t
6510 (unless (js2-read-entity token)
6511 (throw 'return js2-ERROR))))
6512 ;; Allow bare CDATA section, e.g.:
6513 ;; let xml = <![CDATA[ foo bar baz ]]>;
6514 (when (zerop js2-ts-xml-open-tags-count)
6515 (throw 'return js2-XMLEND)))
6516 (??
6517 (setq c (js2-get-char)) ;; skip ?
6518 (js2-add-to-string c)
6519 (unless (js2-read-PI token)
6520 (throw 'return js2-ERROR)))
6521 (?/
6522 ;; end tag
6523 (setq c (js2-get-char)) ;; skip /
6524 (js2-add-to-string c)
6525 (when (zerop js2-ts-xml-open-tags-count)
6526 (js2-xml-discard-string token)
6527 (throw 'return js2-ERROR))
6528 (setq js2-ts-xml-is-tag-content t)
6529 (cl-decf js2-ts-xml-open-tags-count))
6530 (t
6531 ;; start tag
6532 (setq js2-ts-xml-is-tag-content t)
6533 (cl-incf js2-ts-xml-open-tags-count))))
6534 (?{
6535 (js2-unget-char)
6536 (js2-set-string-from-buffer token)
6537 (throw 'return js2-XML))
6538 (t
6539 (js2-add-to-string c))))))))
6540 (setf (js2-token-end token) js2-ts-cursor)
6541 (setf (js2-token-type token) result)
6542 result))
6543
6544 (defun js2-read-quoted-string (quote token)
6545 (let (c)
6546 (catch 'return
6547 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6548 (js2-add-to-string c)
6549 (if (eq c quote)
6550 (throw 'return t)))
6551 (js2-xml-discard-string token) ;; throw away string in progress
6552 nil)))
6553
6554 (defun js2-read-xml-comment (token)
6555 (let ((c (js2-get-char)))
6556 (catch 'return
6557 (while (/= c js2-EOF_CHAR)
6558 (catch 'continue
6559 (js2-add-to-string c)
6560 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6561 (setq c (js2-get-char))
6562 (js2-add-to-string c)
6563 (if (eq (js2-peek-char) ?>)
6564 (progn
6565 (setq c (js2-get-char)) ;; skip >
6566 (js2-add-to-string c)
6567 (throw 'return t))
6568 (throw 'continue nil)))
6569 (setq c (js2-get-char))))
6570 (js2-xml-discard-string token)
6571 nil)))
6572
6573 (defun js2-read-cdata (token)
6574 (let ((c (js2-get-char)))
6575 (catch 'return
6576 (while (/= c js2-EOF_CHAR)
6577 (catch 'continue
6578 (js2-add-to-string c)
6579 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6580 (setq c (js2-get-char))
6581 (js2-add-to-string c)
6582 (if (eq (js2-peek-char) ?>)
6583 (progn
6584 (setq c (js2-get-char)) ;; Skip >
6585 (js2-add-to-string c)
6586 (throw 'return t))
6587 (throw 'continue nil)))
6588 (setq c (js2-get-char))))
6589 (js2-xml-discard-string token)
6590 nil)))
6591
6592 (defun js2-read-entity (token)
6593 (let ((decl-tags 1)
6594 c)
6595 (catch 'return
6596 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6597 (js2-add-to-string c)
6598 (cl-case c
6599 (?<
6600 (cl-incf decl-tags))
6601 (?>
6602 (cl-decf decl-tags)
6603 (if (zerop decl-tags)
6604 (throw 'return t)))))
6605 (js2-xml-discard-string token)
6606 nil)))
6607
6608 (defun js2-read-PI (token)
6609 "Scan an XML processing instruction."
6610 (let (c)
6611 (catch 'return
6612 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6613 (js2-add-to-string c)
6614 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6615 (setq c (js2-get-char)) ;; Skip >
6616 (js2-add-to-string c)
6617 (throw 'return t)))
6618 (js2-xml-discard-string token)
6619 nil)))
6620
6621 ;;; Highlighting
6622
6623 (defun js2-set-face (beg end face &optional record)
6624 "Fontify a region. If RECORD is non-nil, record for later."
6625 (when (cl-plusp js2-highlight-level)
6626 (setq beg (min (point-max) beg)
6627 beg (max (point-min) beg)
6628 end (min (point-max) end)
6629 end (max (point-min) end))
6630 (if record
6631 (push (list beg end face) js2-mode-fontifications)
6632 (put-text-property beg end 'font-lock-face face))))
6633
6634 (defsubst js2-clear-face (beg end)
6635 (remove-text-properties beg end '(font-lock-face nil
6636 help-echo nil
6637 point-entered nil
6638 cursor-sensor-functions nil
6639 c-in-sws nil)))
6640
6641 (defconst js2-ecma-global-props
6642 (concat "^"
6643 (regexp-opt
6644 '("Infinity" "NaN" "undefined" "arguments") t)
6645 "$")
6646 "Value properties of the Ecma-262 Global Object.
6647 Shown at or above `js2-highlight-level' 2.")
6648
6649 ;; might want to add the name "arguments" to this list?
6650 (defconst js2-ecma-object-props
6651 (concat "^"
6652 (regexp-opt
6653 '("prototype" "__proto__" "__parent__") t)
6654 "$")
6655 "Value properties of the Ecma-262 Object constructor.
6656 Shown at or above `js2-highlight-level' 2.")
6657
6658 (defconst js2-ecma-global-funcs
6659 (concat
6660 "^"
6661 (regexp-opt
6662 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6663 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6664 "$")
6665 "Function properties of the Ecma-262 Global object.
6666 Shown at or above `js2-highlight-level' 2.")
6667
6668 (defconst js2-ecma-number-props
6669 (concat "^"
6670 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6671 "NEGATIVE_INFINITY"
6672 "POSITIVE_INFINITY") t)
6673 "$")
6674 "Properties of the Ecma-262 Number constructor.
6675 Shown at or above `js2-highlight-level' 2.")
6676
6677 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6678 "Properties of the Ecma-262 Date constructor.
6679 Shown at or above `js2-highlight-level' 2.")
6680
6681 (defconst js2-ecma-math-props
6682 (concat "^"
6683 (regexp-opt
6684 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6685 t)
6686 "$")
6687 "Properties of the Ecma-262 Math object.
6688 Shown at or above `js2-highlight-level' 2.")
6689
6690 (defconst js2-ecma-math-funcs
6691 (concat "^"
6692 (regexp-opt
6693 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6694 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6695 "$")
6696 "Function properties of the Ecma-262 Math object.
6697 Shown at or above `js2-highlight-level' 2.")
6698
6699 (defconst js2-ecma-function-props
6700 (concat
6701 "^"
6702 (regexp-opt
6703 '(;; properties of the Object prototype object
6704 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6705 "toLocaleString" "toString" "valueOf"
6706 ;; properties of the Function prototype object
6707 "apply" "call"
6708 ;; properties of the Array prototype object
6709 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6710 "splice" "unshift"
6711 ;; properties of the String prototype object
6712 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6713 "localeCompare" "match" "replace" "search" "split" "substring"
6714 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6715 "toUpperCase"
6716 ;; properties of the Number prototype object
6717 "toExponential" "toFixed" "toPrecision"
6718 ;; properties of the Date prototype object
6719 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6720 "getMinutes" "getMonth" "getSeconds" "getTime"
6721 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6722 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6723 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6724 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6725 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6726 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6727 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6728 "toTimeString" "toUTCString"
6729 ;; properties of the RegExp prototype object
6730 "exec" "test"
6731 ;; properties of the JSON prototype object
6732 "parse" "stringify"
6733 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6734 "toSource" "__defineGetter__" "__defineSetter__"
6735 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6736 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6737 t)
6738 "$")
6739 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6740 Shown at or above `js2-highlight-level' 3.")
6741
6742 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6743 (let ((target-name (and target
6744 (js2-name-node-p target)
6745 (js2-name-node-name target)))
6746 (prop-name (if prop (js2-name-node-name prop)))
6747 (level2 (>= js2-highlight-level 2))
6748 (level3 (>= js2-highlight-level 3)))
6749 (when level2
6750 (let ((face
6751 (if call-p
6752 (cond
6753 ((and target prop)
6754 (cond
6755 ((and level3 (string-match js2-ecma-function-props prop-name))
6756 'font-lock-builtin-face)
6757 ((and target-name prop)
6758 (cond
6759 ((string= target-name "Date")
6760 (if (string-match js2-ecma-date-props prop-name)
6761 'font-lock-builtin-face))
6762 ((string= target-name "Math")
6763 (if (string-match js2-ecma-math-funcs prop-name)
6764 'font-lock-builtin-face))))))
6765 (prop
6766 (if (string-match js2-ecma-global-funcs prop-name)
6767 'font-lock-builtin-face)))
6768 (cond
6769 ((and target prop)
6770 (cond
6771 ((string= target-name "Number")
6772 (if (string-match js2-ecma-number-props prop-name)
6773 'font-lock-constant-face))
6774 ((string= target-name "Math")
6775 (if (string-match js2-ecma-math-props prop-name)
6776 'font-lock-constant-face))))
6777 (prop
6778 (if (string-match js2-ecma-object-props prop-name)
6779 'font-lock-constant-face))))))
6780 (when (and (not face) target (not call-p) prop-name)
6781 (setq face 'js2-object-property))
6782 (when face
6783 (let ((pos (+ (js2-node-pos parent) ; absolute
6784 (js2-node-pos prop)))) ; relative
6785 (js2-set-face pos
6786 (+ pos (js2-node-len prop))
6787 face 'record)))))))
6788
6789 (defun js2-parse-highlight-member-expr-node (node)
6790 "Perform syntax highlighting of EcmaScript built-in properties.
6791 The variable `js2-highlight-level' governs this highlighting."
6792 (let (face target prop name pos end parent call-p callee)
6793 (cond
6794 ;; case 1: simple name, e.g. foo
6795 ((js2-name-node-p node)
6796 (setq name (js2-name-node-name node))
6797 ;; possible for name to be nil in rare cases - saw it when
6798 ;; running js2-mode on an elisp buffer. Might as well try to
6799 ;; make it so js2-mode never barfs.
6800 (when name
6801 (setq face (if (string-match js2-ecma-global-props name)
6802 'font-lock-constant-face))
6803 (when face
6804 (setq pos (js2-node-pos node)
6805 end (+ pos (js2-node-len node)))
6806 (js2-set-face pos end face 'record))))
6807 ;; case 2: property access or function call
6808 ((or (js2-prop-get-node-p node)
6809 ;; highlight function call if expr is a prop-get node
6810 ;; or a plain name (i.e. unqualified function call)
6811 (and (setq call-p (js2-call-node-p node))
6812 (setq callee (js2-call-node-target node)) ; separate setq!
6813 (or (js2-prop-get-node-p callee)
6814 (js2-name-node-p callee))))
6815 (setq parent node
6816 node (if call-p callee node))
6817 (if (and call-p (js2-name-node-p callee))
6818 (setq prop callee)
6819 (setq target (js2-prop-get-node-left node)
6820 prop (js2-prop-get-node-right node)))
6821 (cond
6822 ((js2-name-node-p prop)
6823 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6824 (js2-parse-highlight-prop-get parent target prop call-p))
6825 ((js2-name-node-p target)
6826 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6827 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6828
6829 (defun js2-parse-highlight-member-expr-fn-name (expr)
6830 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6831 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6832 We currently only handle the case where the last component is a prop-get
6833 of a simple name. Called before EXPR has a parent node."
6834 (let (pos
6835 (name (and (js2-prop-get-node-p expr)
6836 (js2-prop-get-node-right expr))))
6837 (when (js2-name-node-p name)
6838 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6839 (js2-node-pos name)))
6840 (+ pos (js2-node-len name))
6841 'font-lock-function-name-face
6842 'record))))
6843
6844 ;; source: http://jsdoc.sourceforge.net/
6845 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6846 ;; allows type specifications, and needs work before entering the wild.
6847
6848 (defconst js2-jsdoc-param-tag-regexp
6849 (concat "^\\s-*\\*+\\s-*\\(@"
6850 "\\(?:param\\|arg\\(?:ument\\)?\\|prop\\(?:erty\\)?\\)"
6851 "\\)"
6852 "\\s-*\\({[^}]+}\\)?" ; optional type
6853 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6854 "\\_>")
6855 "Matches jsdoc tags with optional type and optional param name.")
6856
6857 (defconst js2-jsdoc-typed-tag-regexp
6858 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6859 (regexp-opt
6860 '("enum"
6861 "extends"
6862 "field"
6863 "id"
6864 "implements"
6865 "lends"
6866 "mods"
6867 "requires"
6868 "return"
6869 "returns"
6870 "throw"
6871 "throws"))
6872 "\\)\\)\\s-*\\({[^}]+}\\)?")
6873 "Matches jsdoc tags with optional type.")
6874
6875 (defconst js2-jsdoc-arg-tag-regexp
6876 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6877 (regexp-opt
6878 '("alias"
6879 "augments"
6880 "borrows"
6881 "bug"
6882 "base"
6883 "config"
6884 "default"
6885 "define"
6886 "exception"
6887 "function"
6888 "member"
6889 "memberOf"
6890 "name"
6891 "namespace"
6892 "since"
6893 "suppress"
6894 "this"
6895 "throws"
6896 "type"
6897 "version"))
6898 "\\)\\)\\s-+\\([^ \t]+\\)")
6899 "Matches jsdoc tags with a single argument.")
6900
6901 (defconst js2-jsdoc-empty-tag-regexp
6902 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6903 (regexp-opt
6904 '("addon"
6905 "author"
6906 "class"
6907 "const"
6908 "constant"
6909 "constructor"
6910 "constructs"
6911 "deprecated"
6912 "desc"
6913 "description"
6914 "event"
6915 "example"
6916 "exec"
6917 "export"
6918 "fileoverview"
6919 "final"
6920 "function"
6921 "hidden"
6922 "ignore"
6923 "implicitCast"
6924 "inheritDoc"
6925 "inner"
6926 "interface"
6927 "license"
6928 "noalias"
6929 "noshadow"
6930 "notypecheck"
6931 "override"
6932 "owner"
6933 "preserve"
6934 "preserveTry"
6935 "private"
6936 "protected"
6937 "public"
6938 "static"
6939 "supported"
6940 ))
6941 "\\)\\)\\s-*")
6942 "Matches empty jsdoc tags.")
6943
6944 (defconst js2-jsdoc-link-tag-regexp
6945 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6946 "Matches a jsdoc link or code tag.")
6947
6948 (defconst js2-jsdoc-see-tag-regexp
6949 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6950 "Matches a jsdoc @see tag.")
6951
6952 (defconst js2-jsdoc-html-tag-regexp
6953 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6954 "Matches a simple (no attributes) html start- or end-tag.")
6955
6956 (defun js2-jsdoc-highlight-helper ()
6957 (js2-set-face (match-beginning 1)
6958 (match-end 1)
6959 'js2-jsdoc-tag)
6960 (if (match-beginning 2)
6961 (if (save-excursion
6962 (goto-char (match-beginning 2))
6963 (= (char-after) ?{))
6964 (js2-set-face (1+ (match-beginning 2))
6965 (1- (match-end 2))
6966 'js2-jsdoc-type)
6967 (js2-set-face (match-beginning 2)
6968 (match-end 2)
6969 'js2-jsdoc-value)))
6970 (if (match-beginning 3)
6971 (js2-set-face (match-beginning 3)
6972 (match-end 3)
6973 'js2-jsdoc-value)))
6974
6975 (defun js2-highlight-jsdoc (ast)
6976 "Highlight doc comment tags."
6977 (let ((comments (js2-ast-root-comments ast))
6978 beg end)
6979 (save-excursion
6980 (dolist (node comments)
6981 (when (eq (js2-comment-node-format node) 'jsdoc)
6982 (setq beg (js2-node-abs-pos node)
6983 end (+ beg (js2-node-len node)))
6984 (save-restriction
6985 (narrow-to-region beg end)
6986 (dolist (re (list js2-jsdoc-param-tag-regexp
6987 js2-jsdoc-typed-tag-regexp
6988 js2-jsdoc-arg-tag-regexp
6989 js2-jsdoc-link-tag-regexp
6990 js2-jsdoc-see-tag-regexp
6991 js2-jsdoc-empty-tag-regexp))
6992 (goto-char beg)
6993 (while (re-search-forward re nil t)
6994 (js2-jsdoc-highlight-helper)))
6995 ;; simple highlighting for html tags
6996 (goto-char beg)
6997 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6998 (js2-set-face (match-beginning 1)
6999 (match-end 1)
7000 'js2-jsdoc-html-tag-delimiter)
7001 (js2-set-face (match-beginning 2)
7002 (match-end 2)
7003 'js2-jsdoc-html-tag-name)
7004 (js2-set-face (match-beginning 3)
7005 (match-end 3)
7006 'js2-jsdoc-html-tag-delimiter))))))))
7007
7008 (defun js2-highlight-assign-targets (_node left right)
7009 "Highlight function properties and external variables."
7010 (let (leftpos name)
7011 ;; highlight vars and props assigned function values
7012 (when (or (js2-function-node-p right)
7013 (js2-class-node-p right))
7014 (cond
7015 ;; var foo = function() {...}
7016 ((js2-name-node-p left)
7017 (setq name left))
7018 ;; foo.bar.baz = function() {...}
7019 ((and (js2-prop-get-node-p left)
7020 (js2-name-node-p (js2-prop-get-node-right left)))
7021 (setq name (js2-prop-get-node-right left))))
7022 (when name
7023 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7024 (+ leftpos (js2-node-len name))
7025 'font-lock-function-name-face
7026 'record)))))
7027
7028 (defun js2-record-name-node (node)
7029 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7030 later. NODE must be a name node."
7031 (let ((leftpos (js2-node-abs-pos node)))
7032 (push (list node js2-current-scope
7033 leftpos
7034 (+ leftpos (js2-node-len node)))
7035 js2-recorded-identifiers)))
7036
7037 (defun js2-highlight-undeclared-vars ()
7038 "After entire parse is finished, look for undeclared variable references.
7039 We have to wait until entire buffer is parsed, since JavaScript permits var
7040 decls to occur after they're used.
7041
7042 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7043 it is considered declared."
7044 (let (name)
7045 (dolist (entry js2-recorded-identifiers)
7046 (cl-destructuring-bind (name-node scope pos end) entry
7047 (setq name (js2-name-node-name name-node))
7048 (unless (or (member name js2-global-externs)
7049 (member name js2-default-externs)
7050 (member name js2-additional-externs)
7051 (js2-get-defining-scope scope name pos))
7052 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7053 'js2-external-variable))))))
7054
7055 (defun js2--add-or-update-symbol (symbol inition used vars)
7056 "Add or update SYMBOL entry in VARS, an hash table.
7057 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7058 respectively meaning that SYMBOL is a mere declaration, an
7059 assignment or a function parameter; when USED is t, the symbol
7060 node is assumed to be an usage and thus added to the list stored
7061 in the cdr of the entry.
7062 "
7063 (let* ((nm (js2-name-node-name symbol))
7064 (es (js2-node-get-enclosing-scope symbol))
7065 (ds (js2-get-defining-scope es nm)))
7066 (when (and ds (not (equal nm "arguments")))
7067 (let* ((sym (js2-scope-get-symbol ds nm))
7068 (var (gethash sym vars))
7069 (err-var-p (js2-catch-node-p ds)))
7070 (unless inition
7071 (setq inition err-var-p))
7072 (if var
7073 (progn
7074 (when (and inition (not (equal (car var) ?P)))
7075 (setcar var inition))
7076 (when used
7077 (push symbol (cdr var))))
7078 ;; do not consider the declaration of catch parameter as an usage
7079 (when (and err-var-p used)
7080 (setq used nil))
7081 (puthash sym (cons inition (if used (list symbol))) vars))))))
7082
7083 (defun js2--classify-variables ()
7084 "Collect and classify variables declared or used within js2-mode-ast.
7085 Traverse the whole ast tree returning a summary of the variables
7086 usage as an hash-table, keyed by their corresponding symbol table
7087 entry.
7088 Each variable is described by a tuple where the car is a flag
7089 indicating whether the variable has been initialized and the cdr
7090 is a possibly empty list of name nodes where it is used. External
7091 symbols, i.e. those not present in the whole scopes hierarchy,
7092 are ignored."
7093 (let ((vars (make-hash-table :test #'eq :size 100)))
7094 (js2-visit-ast
7095 js2-mode-ast
7096 (lambda (node end-p)
7097 (when (null end-p)
7098 (cond
7099 ((js2-var-init-node-p node)
7100 ;; take note about possibly initialized declarations
7101 (let ((target (js2-var-init-node-target node))
7102 (initializer (js2-var-init-node-initializer node)))
7103 (when target
7104 (let* ((parent (js2-node-parent node))
7105 (grandparent (if parent (js2-node-parent parent)))
7106 (inited (not (null initializer))))
7107 (unless inited
7108 (setq inited
7109 (and grandparent
7110 (js2-for-in-node-p grandparent)
7111 (memq target
7112 (mapcar #'js2-var-init-node-target
7113 (js2-var-decl-node-kids
7114 (js2-for-in-node-iterator grandparent)))))))
7115 (js2--add-or-update-symbol target inited nil vars)))))
7116
7117 ((js2-assign-node-p node)
7118 ;; take note about assignments
7119 (let ((left (js2-assign-node-left node)))
7120 (when (js2-name-node-p left)
7121 (js2--add-or-update-symbol left t nil vars))))
7122
7123 ((js2-prop-get-node-p node)
7124 ;; handle x.y.z nodes, considering only x
7125 (let ((left (js2-prop-get-node-left node)))
7126 (when (js2-name-node-p left)
7127 (js2--add-or-update-symbol left nil t vars))))
7128
7129 ((js2-name-node-p node)
7130 ;; take note about used variables
7131 (let ((parent (js2-node-parent node)))
7132 (when parent
7133 (unless (or (and (js2-var-init-node-p parent) ; handled above
7134 (eq node (js2-var-init-node-target parent)))
7135 (and (js2-assign-node-p parent)
7136 (eq node (js2-assign-node-left parent)))
7137 (js2-prop-get-node-p parent))
7138 (let ((used t) inited)
7139 (cond
7140 ((and (js2-function-node-p parent)
7141 (js2-wrapper-function-p parent))
7142 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7143
7144 ((js2-for-in-node-p parent)
7145 (if (eq node (js2-for-in-node-iterator parent))
7146 (setq inited t used nil)))
7147
7148 ((js2-function-node-p parent)
7149 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7150 used nil)))
7151
7152 (unless used
7153 (let ((grandparent (js2-node-parent parent)))
7154 (when grandparent
7155 (setq used (js2-return-node-p grandparent)))))
7156
7157 (js2--add-or-update-symbol node inited used vars))))))))
7158 t))
7159 vars))
7160
7161 (defun js2--get-name-node (node)
7162 (cond
7163 ((js2-name-node-p node) node)
7164 ((js2-function-node-p node)
7165 (js2-function-node-name node))
7166 ((js2-class-node-p node)
7167 (js2-class-node-name node))
7168 ((js2-comp-loop-node-p node)
7169 (js2-comp-loop-node-iterator node))
7170 (t node)))
7171
7172 (defun js2--highlight-unused-variable (symbol info)
7173 (let ((name (js2-symbol-name symbol))
7174 (inited (car info))
7175 (refs (cdr info))
7176 pos len)
7177 (unless (and inited refs)
7178 (if refs
7179 (dolist (ref refs)
7180 (setq pos (js2-node-abs-pos ref))
7181 (setq len (js2-name-node-len ref))
7182 (js2-report-warning "msg.uninitialized.variable" name pos len
7183 'js2-warning))
7184 (when (or js2-warn-about-unused-function-arguments
7185 (not (eq inited ?P)))
7186 (let* ((symn (js2-symbol-ast-node symbol))
7187 (namen (js2--get-name-node symn)))
7188 (unless (js2-node-top-level-decl-p namen)
7189 (setq pos (js2-node-abs-pos namen))
7190 (setq len (js2-name-node-len namen))
7191 (js2-report-warning "msg.unused.variable" name pos len
7192 'js2-warning))))))))
7193
7194 (defun js2-highlight-unused-variables ()
7195 "Highlight unused variables."
7196 (let ((vars (js2--classify-variables)))
7197 (maphash #'js2--highlight-unused-variable vars)))
7198
7199 ;;;###autoload
7200 (define-minor-mode js2-highlight-unused-variables-mode
7201 "Toggle highlight of unused variables."
7202 :lighter ""
7203 (if js2-highlight-unused-variables-mode
7204 (add-hook 'js2-post-parse-callbacks
7205 #'js2-highlight-unused-variables nil t)
7206 (remove-hook 'js2-post-parse-callbacks
7207 #'js2-highlight-unused-variables t)))
7208
7209 (defun js2-set-default-externs ()
7210 "Set the value of `js2-default-externs' based on the various
7211 `js2-include-?-externs' variables."
7212 (setq js2-default-externs
7213 (append js2-ecma-262-externs
7214 (if js2-include-browser-externs js2-browser-externs)
7215 (if (and js2-include-browser-externs
7216 (>= js2-language-version 200)) js2-harmony-externs)
7217 (if js2-include-rhino-externs js2-rhino-externs)
7218 (if js2-include-node-externs js2-node-externs)
7219 (if (or js2-include-browser-externs js2-include-node-externs)
7220 js2-typed-array-externs))))
7221
7222 (defun js2-apply-jslint-globals ()
7223 (setq js2-additional-externs
7224 (nconc (js2-get-jslint-globals)
7225 js2-additional-externs)))
7226
7227 (defun js2-get-jslint-globals ()
7228 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7229 when (and (eq 'block (js2-comment-node-format node))
7230 (save-excursion
7231 (goto-char (js2-node-abs-pos node))
7232 (looking-at "/\\*global ")))
7233 append (js2-get-jslint-globals-in
7234 (match-end 0)
7235 (js2-node-abs-end node))))
7236
7237 (defun js2-get-jslint-globals-in (beg end)
7238 (let (res)
7239 (save-excursion
7240 (goto-char beg)
7241 (while (re-search-forward js2-mode-identifier-re end t)
7242 (let ((match (match-string 0)))
7243 (unless (member match '("true" "false"))
7244 (push match res)))))
7245 (nreverse res)))
7246
7247 ;;; IMenu support
7248
7249 ;; We currently only support imenu, but eventually should support speedbar and
7250 ;; possibly other browsing mechanisms.
7251
7252 ;; The basic strategy is to identify function assignment targets of the form
7253 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7254 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7255 ;; for imenu after parsing is finished.
7256
7257 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7258 ;; JavaScript, and the general problem is undecidable. However, several forms
7259 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7260 ;; include:
7261
7262 ;; function foo() -- function declaration
7263 ;; foo = function() -- function expression assigned to variable
7264 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7265 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7266 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7267 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7268 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7269 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7270 ;; function foo() {function bar() {...}} -- nested function
7271 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7272
7273 ;; This list boils down to a few forms that can be combined recursively.
7274 ;; Top-level named function declarations include both the left-hand (name)
7275 ;; and the right-hand (function value) expressions needed to produce an imenu
7276 ;; entry. The other "right-hand" forms we need to look for are:
7277 ;; - functions declared as props/getters/setters in object literals
7278 ;; - nested named function declarations
7279 ;; The "left-hand" expressions that functions can be assigned to include:
7280 ;; - local/global variables
7281 ;; - nested property-get expressions like a.b.c.d
7282 ;; - element gets like foo[10] or foo['bar'] where the index
7283 ;; expression can be trivially converted to a property name. They
7284 ;; effectively then become property gets.
7285
7286 ;; All the different definition types are canonicalized into the form
7287 ;; foo.bar.baz = position-of-function-keyword
7288
7289 ;; We need to build a trie-like structure for imenu. As an example,
7290 ;; consider the following JavaScript code:
7291
7292 ;; a = function() {...} // function at position 5
7293 ;; b = function() {...} // function at position 25
7294 ;; foo = function() {...} // function at position 100
7295 ;; foo.bar = function() {...} // function at position 200
7296 ;; foo.bar.baz = function() {...} // function at position 300
7297 ;; foo.bar.zab = function() {...} // function at position 400
7298
7299 ;; During parsing we accumulate an entry for each definition in
7300 ;; the variable `js2-imenu-recorder', like so:
7301
7302 ;; '((fn a 5)
7303 ;; (fn b 25)
7304 ;; (fn foo 100)
7305 ;; (fn foo bar 200)
7306 ;; (fn foo bar baz 300)
7307 ;; (fn foo bar zab 400))
7308
7309 ;; Where 'fn' is the respective function node.
7310 ;; After parsing these entries are merged into this alist-trie:
7311
7312 ;; '((a . 1)
7313 ;; (b . 2)
7314 ;; (foo (<definition> . 3)
7315 ;; (bar (<definition> . 6)
7316 ;; (baz . 100)
7317 ;; (zab . 200))))
7318
7319 ;; Note the wacky need for a <definition> name. The token can be anything
7320 ;; that isn't a valid JavaScript identifier, because you might make foo
7321 ;; a function and then start setting properties on it that are also functions.
7322
7323 (defun js2-prop-node-name (node)
7324 "Return the name of a node that may be a property-get/property-name.
7325 If NODE is not a valid name-node, string-node or integral number-node,
7326 returns nil. Otherwise returns the string name/value of the node."
7327 (cond
7328 ((js2-name-node-p node)
7329 (js2-name-node-name node))
7330 ((js2-string-node-p node)
7331 (js2-string-node-value node))
7332 ((and (js2-number-node-p node)
7333 (string-match "^[0-9]+$" (js2-number-node-value node)))
7334 (js2-number-node-value node))
7335 ((eq (js2-node-type node) js2-THIS)
7336 "this")
7337 ((eq (js2-node-type node) js2-SUPER)
7338 "super")))
7339
7340 (defun js2-node-qname-component (node)
7341 "Return the name of this node, if it contributes to a qname.
7342 Returns nil if the node doesn't contribute."
7343 (copy-sequence
7344 (or (js2-prop-node-name node)
7345 (if (and (js2-function-node-p node)
7346 (js2-function-node-name node))
7347 (js2-name-node-name (js2-function-node-name node))))))
7348
7349 (defun js2-record-imenu-entry (fn-node qname pos)
7350 "Add an entry to `js2-imenu-recorder'.
7351 FN-NODE should be the current item's function node.
7352
7353 Associate FN-NODE with its QNAME for later lookup.
7354 This is used in postprocessing the chain list. For each chain, we find
7355 the parent function, look up its qname, then prepend a copy of it to the chain."
7356 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7357 (unless js2-imenu-function-map
7358 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7359 (puthash fn-node qname js2-imenu-function-map))
7360
7361 (defun js2-record-imenu-functions (node &optional var)
7362 "Record function definitions for imenu.
7363 NODE is a function node or an object literal.
7364 VAR, if non-nil, is the expression that NODE is being assigned to.
7365 When passed arguments of wrong type, does nothing."
7366 (when js2-parse-ide-mode
7367 (let ((fun-p (js2-function-node-p node))
7368 qname fname-node)
7369 (cond
7370 ;; non-anonymous function declaration?
7371 ((and fun-p
7372 (not var)
7373 (setq fname-node (js2-function-node-name node)))
7374 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7375 ;; for remaining forms, compute left-side tree branch first
7376 ((and var (setq qname (js2-compute-nested-prop-get var)))
7377 (cond
7378 ;; foo.bar.baz = function
7379 (fun-p
7380 (js2-record-imenu-entry node qname (js2-node-pos node)))
7381 ;; foo.bar.baz = object-literal
7382 ;; look for nested functions: {a: {b: function() {...} }}
7383 ((js2-object-node-p node)
7384 ;; Node position here is still absolute, since the parser
7385 ;; passes the assignment target and value expressions
7386 ;; to us before they are added as children of the assignment node.
7387 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7388
7389 (defun js2-compute-nested-prop-get (node)
7390 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7391 component nodes as a list. Otherwise return nil. Element-gets are treated
7392 as property-gets if the index expression is a string, or a positive integer."
7393 (let (left right head)
7394 (cond
7395 ((or (js2-name-node-p node)
7396 (js2-this-or-super-node-p node))
7397 (list node))
7398 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7399 ((js2-prop-get-node-p node) ; foo.bar
7400 (setq left (js2-prop-get-node-left node)
7401 right (js2-prop-get-node-right node))
7402 (if (setq head (js2-compute-nested-prop-get left))
7403 (nconc head (list right))))
7404 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7405 (setq left (js2-elem-get-node-target node)
7406 right (js2-elem-get-node-element node))
7407 (if (or (js2-string-node-p right) ; ['bar']
7408 (and (js2-number-node-p right) ; [10]
7409 (string-match "^[0-9]+$"
7410 (js2-number-node-value right))))
7411 (if (setq head (js2-compute-nested-prop-get left))
7412 (nconc head (list right))))))))
7413
7414 (defun js2-record-object-literal (node qname pos)
7415 "Recursively process an object literal looking for functions.
7416 NODE is an object literal that is the right-hand child of an assignment
7417 expression. QNAME is a list of nodes representing the assignment target,
7418 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7419 POS is the absolute position of the node.
7420 We do a depth-first traversal of NODE. For any functions we find,
7421 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7422 (let (right)
7423 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7424 (let ((left (js2-infix-node-left e))
7425 ;; Element positions are relative to the parent position.
7426 (pos (+ pos (js2-node-pos e))))
7427 (cond
7428 ;; foo: function() {...}
7429 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7430 (when (js2-prop-node-name left)
7431 ;; As a policy decision, we record the position of the property,
7432 ;; not the position of the `function' keyword, since the property
7433 ;; is effectively the name of the function.
7434 (js2-record-imenu-entry right (append qname (list left)) pos)))
7435 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7436 ((js2-object-node-p right)
7437 (js2-record-object-literal right
7438 (append qname (list (js2-infix-node-left e)))
7439 (+ pos (js2-node-pos right)))))))))
7440
7441 (defun js2-node-top-level-decl-p (node)
7442 "Return t if NODE's name is defined in the top-level scope.
7443 Also returns t if NODE's name is not defined in any scope, since it implies
7444 that it's an external variable, which must also be in the top-level scope."
7445 (let* ((name (js2-prop-node-name node))
7446 (this-scope (js2-node-get-enclosing-scope node))
7447 defining-scope)
7448 (cond
7449 ((js2-this-or-super-node-p node)
7450 nil)
7451 ((null this-scope)
7452 t)
7453 ((setq defining-scope (js2-get-defining-scope this-scope name))
7454 (js2-ast-root-p defining-scope))
7455 (t t))))
7456
7457 (defun js2-wrapper-function-p (node)
7458 "Return t if NODE is a function expression that's immediately invoked.
7459 NODE must be `js2-function-node'."
7460 (let ((parent (js2-node-parent node)))
7461 (or
7462 ;; function(){...}();
7463 (and (js2-call-node-p parent)
7464 (eq node (js2-call-node-target parent)))
7465 (and (js2-paren-node-p parent)
7466 ;; (function(){...})();
7467 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7468 ;; (function(){...}).call(this);
7469 (and (js2-prop-get-node-p parent)
7470 (member (js2-name-node-name (js2-prop-get-node-right parent))
7471 '("call" "apply"))
7472 (js2-call-node-p (js2-node-parent parent))))))))
7473
7474 (defun js2-browse-postprocess-chains ()
7475 "Modify function-declaration name chains after parsing finishes.
7476 Some of the information is only available after the parse tree is complete.
7477 For instance, processing a nested scope requires a parent function node."
7478 (let (result fn parent-qname p elem)
7479 (dolist (entry js2-imenu-recorder)
7480 ;; function node goes first
7481 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7482 ;; Examine head's defining scope:
7483 ;; Pre-processed chain, or top-level/external, keep as-is.
7484 (if (or (stringp head) (js2-node-top-level-decl-p head))
7485 (push chain result)
7486 (when (js2-this-or-super-node-p head)
7487 (setq chain (cdr chain))) ; discard this-node
7488 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7489 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7490 (when (eq parent-qname 'not-found)
7491 ;; anonymous function expressions are not recorded
7492 ;; during the parse, so we need to handle this case here
7493 (setq parent-qname
7494 (if (js2-wrapper-function-p fn)
7495 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7496 (if (js2-ast-root-p grandparent)
7497 nil
7498 (gethash grandparent js2-imenu-function-map 'skip)))
7499 'skip))
7500 (puthash fn parent-qname js2-imenu-function-map))
7501 (if (eq parent-qname 'skip)
7502 ;; We don't show it, let's record that fact.
7503 (remhash current-fn js2-imenu-function-map)
7504 ;; Prepend parent fn qname to this chain.
7505 (let ((qname (append parent-qname chain)))
7506 (puthash current-fn (butlast qname) js2-imenu-function-map)
7507 (push qname result)))))))
7508 ;; Collect chains obtained by third-party code.
7509 (let (js2-imenu-recorder)
7510 (run-hooks 'js2-build-imenu-callbacks)
7511 (dolist (entry js2-imenu-recorder)
7512 (push (cdr entry) result)))
7513 ;; Finally replace each node in each chain with its name.
7514 (dolist (chain result)
7515 (setq p chain)
7516 (while p
7517 (if (js2-node-p (setq elem (car p)))
7518 (setcar p (js2-node-qname-component elem)))
7519 (setq p (cdr p))))
7520 result))
7521
7522 ;; Merge name chains into a trie-like tree structure of nested lists.
7523 ;; To simplify construction of the trie, we first build it out using the rule
7524 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7525 ;; [key, num-or-list]. The second element can be a number; if so, this key
7526 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7527 ;; associated with the key at this level.) Otherwise the second element is
7528 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7529 ;; a simple recursive formulation.
7530 ;;
7531 ;; js2-mode is building the data structure for imenu. The imenu documentation
7532 ;; claims that it's the structure above, but in practice it wants the children
7533 ;; at the same list level as the key for that level, which is how I've drawn
7534 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7535 ;; list wrapper around the children at each level.
7536 ;;
7537 ;; A completed nested imenu-alist entry looks like this:
7538 ;; '(("foo"
7539 ;; ("<definition>" . 7)
7540 ;; ("bar"
7541 ;; ("a" . 40)
7542 ;; ("b" . 60))))
7543 ;;
7544 ;; In particular, the documentation for `imenu--index-alist' says that
7545 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7546 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7547
7548 (defun js2-treeify (lst)
7549 "Convert (a b c d) to (a ((b ((c d)))))."
7550 (if (null (cddr lst)) ; list length <= 2
7551 lst
7552 (list (car lst) (list (js2-treeify (cdr lst))))))
7553
7554 (defun js2-build-alist-trie (chains trie)
7555 "Merge declaration name chains into a trie-like alist structure for imenu.
7556 CHAINS is the qname chain list produced during parsing. TRIE is a
7557 list of elements built up so far."
7558 (let (head tail pos branch kids)
7559 (dolist (chain chains)
7560 (setq head (car chain)
7561 tail (cdr chain)
7562 pos (if (numberp (car tail)) (car tail))
7563 branch (js2-find-if (lambda (n)
7564 (string= (car n) head))
7565 trie)
7566 kids (cl-second branch))
7567 (cond
7568 ;; case 1: this key isn't in the trie yet
7569 ((null branch)
7570 (if trie
7571 (setcdr (last trie) (list (js2-treeify chain)))
7572 (setq trie (list (js2-treeify chain)))))
7573 ;; case 2: key is present with a single number entry: replace w/ list
7574 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7575 ;; ("<definition>" 20)))
7576 ((numberp kids)
7577 (setcar (cdr branch)
7578 (list (list "<definition-1>" kids)
7579 (if pos
7580 (list "<definition-2>" pos)
7581 (js2-treeify tail)))))
7582 ;; case 3: key is there (with kids), and we're a number entry
7583 (pos
7584 (setcdr (last kids)
7585 (list
7586 (list (format "<definition-%d>"
7587 (1+ (cl-loop for kid in kids
7588 count (eq ?< (aref (car kid) 0)))))
7589 pos))))
7590 ;; case 4: key is there with kids, need to merge in our chain
7591 (t
7592 (js2-build-alist-trie (list tail) kids))))
7593 trie))
7594
7595 (defun js2-flatten-trie (trie)
7596 "Convert TRIE to imenu-format.
7597 Recurses through nodes, and for each one whose second element is a list,
7598 appends the list's flattened elements to the current element. Also
7599 changes the tails into conses. For instance, this pre-flattened trie
7600
7601 '(a ((b 20)
7602 (c ((d 30)
7603 (e 40)))))
7604
7605 becomes
7606
7607 '(a (b . 20)
7608 (c (d . 30)
7609 (e . 40)))
7610
7611 Note that the root of the trie has no key, just a list of chains.
7612 This is also true for the value of any key with multiple children,
7613 e.g. key 'c' in the example above."
7614 (cond
7615 ((listp (car trie))
7616 (mapcar #'js2-flatten-trie trie))
7617 (t
7618 (if (numberp (cl-second trie))
7619 (cons (car trie) (cl-second trie))
7620 ;; else pop list and append its kids
7621 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7622
7623 (defun js2-build-imenu-index ()
7624 "Turn `js2-imenu-recorder' into an imenu data structure."
7625 (when (eq js2-imenu-recorder 'empty)
7626 (setq js2-imenu-recorder nil))
7627 (let* ((chains (js2-browse-postprocess-chains))
7628 (result (js2-build-alist-trie chains nil)))
7629 (js2-flatten-trie result)))
7630
7631 (defun js2-test-print-chains (chains)
7632 "Print a list of qname chains.
7633 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7634 i.e. one or more nodes, and an integer position as the list tail."
7635 (mapconcat (lambda (chain)
7636 (concat "("
7637 (mapconcat (lambda (elem)
7638 (if (js2-node-p elem)
7639 (or (js2-node-qname-component elem)
7640 "nil")
7641 (number-to-string elem)))
7642 chain
7643 " ")
7644 ")"))
7645 chains
7646 "\n"))
7647
7648 ;;; Parser
7649
7650 (defconst js2-version "1.8.5"
7651 "Version of JavaScript supported.")
7652
7653 (defun js2-record-face (face &optional token)
7654 "Record a style run of FACE for TOKEN or the current token."
7655 (unless token (setq token (js2-current-token)))
7656 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7657
7658 (defsubst js2-node-end (n)
7659 "Computes the absolute end of node N.
7660 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7661 is only true until the node is added to its parent; i.e., while parsing."
7662 (+ (js2-node-pos n)
7663 (js2-node-len n)))
7664
7665 (defun js2-record-comment (token)
7666 "Record a comment in `js2-scanned-comments'."
7667 (let ((ct (js2-token-comment-type token))
7668 (beg (js2-token-beg token))
7669 (end (js2-token-end token)))
7670 (push (make-js2-comment-node :len (- end beg)
7671 :format ct)
7672 js2-scanned-comments)
7673 (when js2-parse-ide-mode
7674 (js2-record-face (if (eq ct 'jsdoc)
7675 'font-lock-doc-face
7676 'font-lock-comment-face)
7677 token)
7678 (when (memq ct '(html preprocessor))
7679 ;; Tell cc-engine the bounds of the comment.
7680 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7681
7682 (defun js2-peek-token ()
7683 "Return the next token type without consuming it.
7684 If `js2-ti-lookahead' is positive, return the type of next token
7685 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7686 (if (not (zerop js2-ti-lookahead))
7687 (js2-token-type
7688 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7689 (let ((tt (js2-get-token-internal nil)))
7690 (js2-unget-token)
7691 tt)))
7692
7693 (defalias 'js2-next-token 'js2-get-token)
7694
7695 (defun js2-match-token (match &optional dont-unget)
7696 "Get next token and return t if it matches MATCH, a bytecode.
7697 Returns nil and consumes nothing if MATCH is not the next token."
7698 (if (/= (js2-get-token) match)
7699 (ignore (unless dont-unget (js2-unget-token)))
7700 t))
7701
7702 (defun js2-match-contextual-kwd (name)
7703 "Consume and return t if next token is `js2-NAME', and its
7704 string is NAME. Returns nil and keeps current token otherwise."
7705 (if (or (/= (js2-get-token) js2-NAME)
7706 (not (string= (js2-current-token-string) name)))
7707 (progn
7708 (js2-unget-token)
7709 nil)
7710 (js2-record-face 'font-lock-keyword-face)
7711 t))
7712
7713 (defun js2-get-prop-name-token ()
7714 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7715
7716 (defun js2-match-prop-name ()
7717 "Consume token and return t if next token is a valid property name.
7718 If `js2-language-version' is >= 180, a keyword or reserved word
7719 is considered valid name as well."
7720 (if (eq js2-NAME (js2-get-prop-name-token))
7721 t
7722 (js2-unget-token)
7723 nil))
7724
7725 (defun js2-must-match-prop-name (msg-id &optional pos len)
7726 (if (js2-match-prop-name)
7727 t
7728 (js2-report-error msg-id nil pos len)
7729 nil))
7730
7731 (defun js2-peek-token-or-eol ()
7732 "Return js2-EOL if the next token immediately follows a newline.
7733 Else returns the next token. Used in situations where we don't
7734 consider certain token types valid if they are preceded by a newline.
7735 One example is the postfix ++ or -- operator, which has to be on the
7736 same line as its operand."
7737 (let ((tt (js2-get-token))
7738 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7739 (js2-unget-token)
7740 (if follows-eol
7741 js2-EOL
7742 tt)))
7743
7744 (defun js2-must-match (token msg-id &optional pos len)
7745 "Match next token to token code TOKEN, or record a syntax error.
7746 MSG-ID is the error message to report if the match fails.
7747 Returns t on match, nil if no match."
7748 (if (js2-match-token token t)
7749 t
7750 (js2-report-error msg-id nil pos len)
7751 (js2-unget-token)
7752 nil))
7753
7754 (defun js2-must-match-name (msg-id)
7755 (if (js2-match-token js2-NAME t)
7756 t
7757 (if (eq (js2-current-token-type) js2-RESERVED)
7758 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7759 (js2-report-error msg-id)
7760 (js2-unget-token))
7761 nil))
7762
7763 (defsubst js2-inside-function ()
7764 (cl-plusp js2-nesting-of-function))
7765
7766 (defun js2-set-requires-activation ()
7767 (if (js2-function-node-p js2-current-script-or-fn)
7768 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7769
7770 (defun js2-check-activation-name (name _token)
7771 (when (js2-inside-function)
7772 ;; skip language-version 1.2 check from Rhino
7773 (if (or (string= "arguments" name)
7774 (and js2-compiler-activation-names ; only used in codegen
7775 (gethash name js2-compiler-activation-names)))
7776 (js2-set-requires-activation))))
7777
7778 (defun js2-set-is-generator ()
7779 (let ((fn-node js2-current-script-or-fn))
7780 (when (and (js2-function-node-p fn-node)
7781 (not (js2-function-node-generator-type fn-node)))
7782 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7783
7784 (defun js2-must-have-xml ()
7785 (unless js2-compiler-xml-available
7786 (js2-report-error "msg.XML.not.available")))
7787
7788 (defun js2-push-scope (scope)
7789 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7790 (cl-assert (js2-scope-p scope))
7791 (cl-assert (null (js2-scope-parent-scope scope)))
7792 (cl-assert (not (eq js2-current-scope scope)))
7793 (setf (js2-scope-parent-scope scope) js2-current-scope
7794 js2-current-scope scope))
7795
7796 (defsubst js2-pop-scope ()
7797 (setq js2-current-scope
7798 (js2-scope-parent-scope js2-current-scope)))
7799
7800 (defun js2-enter-loop (loop-node)
7801 (push loop-node js2-loop-set)
7802 (push loop-node js2-loop-and-switch-set)
7803 (js2-push-scope loop-node)
7804 ;; Tell the current labeled statement (if any) its statement,
7805 ;; and set the jump target of the first label to the loop.
7806 ;; These are used in `js2-parse-continue' to verify that the
7807 ;; continue target is an actual labeled loop. (And for codegen.)
7808 (when js2-labeled-stmt
7809 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7810 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7811 js2-labeled-stmt))) loop-node)))
7812
7813 (defun js2-exit-loop ()
7814 (pop js2-loop-set)
7815 (pop js2-loop-and-switch-set)
7816 (js2-pop-scope))
7817
7818 (defsubst js2-enter-switch (switch-node)
7819 (push switch-node js2-loop-and-switch-set))
7820
7821 (defsubst js2-exit-switch ()
7822 (pop js2-loop-and-switch-set))
7823
7824 (defsubst js2-get-directive (node)
7825 "Return NODE's value if it is a directive, nil otherwise.
7826
7827 A directive is an otherwise-meaningless expression statement
7828 consisting of a string literal, such as \"use strict\"."
7829 (and (js2-expr-stmt-node-p node)
7830 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7831 (js2-string-node-value node)))
7832
7833 (defun js2-parse (&optional buf cb)
7834 "Tell the js2 parser to parse a region of JavaScript.
7835
7836 BUF is a buffer or buffer name containing the code to parse.
7837 Call `narrow-to-region' first to parse only part of the buffer.
7838
7839 The returned AST root node is given some additional properties:
7840 `node-count' - total number of nodes in the AST
7841 `buffer' - BUF. The buffer it refers to may change or be killed,
7842 so the value is not necessarily reliable.
7843
7844 An optional callback CB can be specified to report parsing
7845 progress. If `(functionp CB)' returns t, it will be called with
7846 the current line number once before parsing begins, then again
7847 each time the lexer reaches a new line number.
7848
7849 CB can also be a list of the form `(symbol cb ...)' to specify
7850 multiple callbacks with different criteria. Each symbol is a
7851 criterion keyword, and the following element is the callback to
7852 call
7853
7854 :line - called whenever the line number changes
7855 :token - called for each new token consumed
7856
7857 The list of criteria could be extended to include entering or
7858 leaving a statement, an expression, or a function definition."
7859 (if (and cb (not (functionp cb)))
7860 (error "criteria callbacks not yet implemented"))
7861 (let ((inhibit-point-motion-hooks t)
7862 (js2-compiler-xml-available (>= js2-language-version 160))
7863 ;; This is a recursive-descent parser, so give it a big stack.
7864 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7865 (max-specpdl-size (max max-specpdl-size 3000))
7866 (case-fold-search nil)
7867 ast)
7868 (with-current-buffer (or buf (current-buffer))
7869 (setq js2-scanned-comments nil
7870 js2-parsed-errors nil
7871 js2-parsed-warnings nil
7872 js2-imenu-recorder nil
7873 js2-imenu-function-map nil
7874 js2-label-set nil)
7875 (js2-init-scanner)
7876 (setq ast (js2-do-parse))
7877 (unless js2-ts-hit-eof
7878 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7879 (setf (js2-ast-root-errors ast) js2-parsed-errors
7880 (js2-ast-root-warnings ast) js2-parsed-warnings)
7881 ;; if we didn't find any declarations, put a dummy in this list so we
7882 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7883 (unless js2-imenu-recorder
7884 (setq js2-imenu-recorder 'empty))
7885 (run-hooks 'js2-parse-finished-hook)
7886 ast)))
7887
7888 ;; Corresponds to Rhino's Parser.parse() method.
7889 (defun js2-do-parse ()
7890 "Parse current buffer starting from current point.
7891 Scanner should be initialized."
7892 (let ((pos js2-ts-cursor)
7893 (end js2-ts-cursor) ; in case file is empty
7894 root n tt
7895 (in-directive-prologue t)
7896 (js2-in-use-strict-directive js2-in-use-strict-directive)
7897 directive)
7898 ;; initialize buffer-local parsing vars
7899 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7900 js2-current-script-or-fn root
7901 js2-current-scope root
7902 js2-nesting-of-function 0
7903 js2-labeled-stmt nil
7904 js2-recorded-identifiers nil ; for js2-highlight
7905 js2-in-use-strict-directive nil)
7906 (while (/= (setq tt (js2-get-token)) js2-EOF)
7907 (if (= tt js2-FUNCTION)
7908 (progn
7909 (setq n (if js2-called-by-compile-function
7910 (js2-parse-function-expr)
7911 (js2-parse-function-stmt))))
7912 ;; not a function - parse a statement
7913 (js2-unget-token)
7914 (setq n (js2-parse-statement))
7915 (when in-directive-prologue
7916 (setq directive (js2-get-directive n))
7917 (cond
7918 ((null directive)
7919 (setq in-directive-prologue nil))
7920 ((string= directive "use strict")
7921 (setq js2-in-use-strict-directive t)))))
7922 ;; add function or statement to script
7923 (setq end (js2-node-end n))
7924 (js2-block-node-push root n))
7925 ;; add comments to root in lexical order
7926 (when js2-scanned-comments
7927 ;; if we find a comment beyond end of normal kids, use its end
7928 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7929 (dolist (comment js2-scanned-comments)
7930 (push comment (js2-ast-root-comments root))
7931 (js2-node-add-children root comment)))
7932 (setf (js2-node-len root) (- end pos))
7933 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7934 ;; Give extensions a chance to muck with things before highlighting starts.
7935 (let ((js2-additional-externs js2-additional-externs))
7936 (save-excursion
7937 (run-hooks 'js2-post-parse-callbacks))
7938 (js2-highlight-undeclared-vars))
7939 root))
7940
7941 (defun js2-parse-function-closure-body (fn-node)
7942 "Parse a JavaScript 1.8 function closure body."
7943 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7944 (if js2-ts-hit-eof
7945 (js2-report-error "msg.no.brace.body" nil
7946 (js2-node-pos fn-node)
7947 (- js2-ts-cursor (js2-node-pos fn-node)))
7948 (js2-node-add-children fn-node
7949 (setf (js2-function-node-body fn-node)
7950 (js2-parse-expr t))))))
7951
7952 (defun js2-parse-function-body (fn-node)
7953 (js2-must-match js2-LC "msg.no.brace.body"
7954 (js2-node-pos fn-node)
7955 (- js2-ts-cursor (js2-node-pos fn-node)))
7956 (let ((pos (js2-current-token-beg)) ; LC position
7957 (pn (make-js2-block-node)) ; starts at LC position
7958 tt
7959 end
7960 not-in-directive-prologue
7961 node
7962 directive)
7963 (cl-incf js2-nesting-of-function)
7964 (unwind-protect
7965 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7966 (= tt js2-EOF)
7967 (= tt js2-RC)))
7968 (js2-block-node-push
7969 pn
7970 (if (/= tt js2-FUNCTION)
7971 (if not-in-directive-prologue
7972 (js2-parse-statement)
7973 (setq node (js2-parse-statement)
7974 directive (js2-get-directive node))
7975 (cond
7976 ((null directive)
7977 (setq not-in-directive-prologue t))
7978 ((string= directive "use strict")
7979 ;; Back up and reparse the function, because new rules apply
7980 ;; to the function name and parameters.
7981 (when (not js2-in-use-strict-directive)
7982 (setq js2-in-use-strict-directive t)
7983 (throw 'reparse t))))
7984 node)
7985 (js2-get-token)
7986 (js2-parse-function-stmt))))
7987 (cl-decf js2-nesting-of-function))
7988 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7989 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7990 (setq end (js2-current-token-end)))
7991 (setf (js2-node-pos pn) pos
7992 (js2-node-len pn) (- end pos))
7993 (setf (js2-function-node-body fn-node) pn)
7994 (js2-node-add-children fn-node pn)
7995 pn))
7996
7997 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7998 "Declare and fontify destructuring parameters inside NODE.
7999 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8000
8001 Return a list of `js2-name-node' nodes representing the symbols
8002 declared; probably to check them for errors."
8003 (let (name-nodes)
8004 (cond
8005 ((js2-name-node-p node)
8006 (let (leftpos)
8007 (js2-define-symbol decl-type (js2-name-node-name node)
8008 node ignore-not-in-block)
8009 (when face
8010 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8011 (+ leftpos (js2-node-len node))
8012 face 'record))
8013 (list node)))
8014 ((js2-object-node-p node)
8015 (dolist (elem (js2-object-node-elems node))
8016 ;; js2-infix-node-p catches both object prop node and initialized
8017 ;; binding element (which is directly an infix node).
8018 (when (js2-infix-node-p elem)
8019 (push (js2-define-destruct-symbols
8020 (js2-infix-node-left elem)
8021 decl-type face ignore-not-in-block)
8022 name-nodes)))
8023 (apply #'append (nreverse name-nodes)))
8024 ((js2-array-node-p node)
8025 (dolist (elem (js2-array-node-elems node))
8026 (when elem
8027 (if (js2-infix-node-p elem) (setq elem (js2-infix-node-left elem)))
8028 (push (js2-define-destruct-symbols
8029 elem decl-type face ignore-not-in-block)
8030 name-nodes)))
8031 (apply #'append (nreverse name-nodes)))
8032 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8033 (js2-node-len node))
8034 nil))))
8035
8036 (defvar js2-illegal-strict-identifiers
8037 '("eval" "arguments")
8038 "Identifiers not allowed as variables in strict mode.")
8039
8040 (defun js2-check-strict-identifier (name-node)
8041 "Check that NAME-NODE makes a legal strict mode identifier."
8042 (when js2-in-use-strict-directive
8043 (let ((param-name (js2-name-node-name name-node)))
8044 (when (member param-name js2-illegal-strict-identifiers)
8045 (js2-report-error "msg.bad.id.strict" param-name
8046 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8047
8048 (defun js2-check-strict-function-params (preceding-params params)
8049 "Given PRECEDING-PARAMS in a function's parameter list, check
8050 for strict mode errors caused by PARAMS."
8051 (when js2-in-use-strict-directive
8052 (dolist (param params)
8053 (let ((param-name (js2-name-node-name param)))
8054 (js2-check-strict-identifier param)
8055 (when (cl-some (lambda (param)
8056 (string= (js2-name-node-name param) param-name))
8057 preceding-params)
8058 (js2-report-error "msg.dup.param.strict" param-name
8059 (js2-node-abs-pos param) (js2-node-len param)))))))
8060
8061 (defun js2-parse-function-params (function-type fn-node pos)
8062 "Parse the parameters of a function of FUNCTION-TYPE
8063 represented by FN-NODE at POS."
8064 (if (js2-match-token js2-RP)
8065 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8066 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8067 (eq (js2-current-token-type) js2-NAME)))
8068 params param
8069 param-name-nodes new-param-name-nodes
8070 rest-param-at)
8071 (when paren-free-arrow
8072 (js2-unget-token))
8073 (cl-loop for tt = (js2-peek-token)
8074 do
8075 (cond
8076 ;; destructuring param
8077 ((and (not paren-free-arrow)
8078 (or (= tt js2-LB) (= tt js2-LC)))
8079 (js2-get-token)
8080 (setq param (js2-parse-destruct-primary-expr)
8081 new-param-name-nodes (js2-define-destruct-symbols
8082 param js2-LP 'js2-function-param))
8083 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8084 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8085 (push param params))
8086 ;; variable name
8087 (t
8088 (when (and (>= js2-language-version 200)
8089 (not paren-free-arrow)
8090 (js2-match-token js2-TRIPLEDOT)
8091 (not rest-param-at))
8092 ;; to report errors if there are more parameters
8093 (setq rest-param-at (length params)))
8094 (js2-must-match-name "msg.no.parm")
8095 (js2-record-face 'js2-function-param)
8096 (setq param (js2-create-name-node))
8097 (js2-define-symbol js2-LP (js2-current-token-string) param)
8098 (js2-check-strict-function-params param-name-nodes (list param))
8099 (setq param-name-nodes (append param-name-nodes (list param)))
8100 ;; default parameter value
8101 (when (and (>= js2-language-version 200)
8102 (js2-match-token js2-ASSIGN))
8103 (cl-assert (not paren-free-arrow))
8104 (let* ((pos (js2-node-pos param))
8105 (tt (js2-current-token-type))
8106 (op-pos (- (js2-current-token-beg) pos))
8107 (left param)
8108 (right (js2-parse-assign-expr))
8109 (len (- (js2-node-end right) pos)))
8110 (setq param (make-js2-assign-node
8111 :type tt :pos pos :len len :op-pos op-pos
8112 :left left :right right))
8113 (js2-node-add-children param left right)))
8114 (push param params)))
8115 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8116 (js2-report-error "msg.param.after.rest" nil
8117 (js2-node-pos param) (js2-node-len param)))
8118 while
8119 (js2-match-token js2-COMMA))
8120 (when (and (not paren-free-arrow)
8121 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8122 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8123 (when rest-param-at
8124 (setf (js2-function-node-rest-p fn-node) t))
8125 (dolist (p params)
8126 (js2-node-add-children fn-node p)
8127 (push p (js2-function-node-params fn-node))))))
8128
8129 (defun js2-check-inconsistent-return-warning (fn-node name)
8130 "Possibly show inconsistent-return warning.
8131 Last token scanned is the close-curly for the function body."
8132 (when (and js2-mode-show-strict-warnings
8133 js2-strict-inconsistent-return-warning
8134 (not (js2-has-consistent-return-usage
8135 (js2-function-node-body fn-node))))
8136 ;; Have it extend from close-curly to bol or beginning of block.
8137 (let ((pos (save-excursion
8138 (goto-char (js2-current-token-end))
8139 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8140 (point-at-bol))))
8141 (end (js2-current-token-end)))
8142 (if (cl-plusp (js2-name-node-length name))
8143 (js2-add-strict-warning "msg.no.return.value"
8144 (js2-name-node-name name) pos end)
8145 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8146
8147 (defun js2-parse-function-stmt ()
8148 (let ((pos (js2-current-token-beg))
8149 (star-p (js2-match-token js2-MUL)))
8150 (js2-must-match-name "msg.unnamed.function.stmt")
8151 (let ((name (js2-create-name-node t))
8152 pn member-expr)
8153 (cond
8154 ((js2-match-token js2-LP)
8155 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8156 (js2-allow-member-expr-as-function-name
8157 (setq member-expr (js2-parse-member-expr-tail nil name))
8158 (js2-parse-highlight-member-expr-fn-name member-expr)
8159 (js2-must-match js2-LP "msg.no.paren.parms")
8160 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8161 (js2-function-node-member-expr pn) member-expr)
8162 pn)
8163 (t
8164 (js2-report-error "msg.no.paren.parms")
8165 (make-js2-error-node))))))
8166
8167 (defun js2-parse-function-expr ()
8168 (let ((pos (js2-current-token-beg))
8169 (star-p (js2-match-token js2-MUL))
8170 name)
8171 (when (js2-match-token js2-NAME)
8172 (setq name (js2-create-name-node t)))
8173 (js2-must-match js2-LP "msg.no.paren.parms")
8174 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8175
8176 (defun js2-parse-function-internal (function-type pos star-p &optional name)
8177 (let (fn-node lp)
8178 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8179 (setq lp (js2-current-token-beg)))
8180 (setf fn-node (make-js2-function-node :pos pos
8181 :name name
8182 :form function-type
8183 :lp (if lp (- lp pos))
8184 :generator-type (and star-p 'STAR)))
8185 (when name
8186 (js2-set-face (js2-node-pos name) (js2-node-end name)
8187 'font-lock-function-name-face 'record)
8188 (when (and (eq function-type 'FUNCTION_STATEMENT)
8189 (cl-plusp (js2-name-node-length name)))
8190 ;; Function statements define a symbol in the enclosing scope
8191 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8192 (when js2-in-use-strict-directive
8193 (js2-check-strict-identifier name)))
8194 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8195 ;; 1. Nested functions are not affected by the dynamic scope flag
8196 ;; as dynamic scope is already a parent of their scope.
8197 ;; 2. Functions defined under the with statement also immune to
8198 ;; this setup, in which case dynamic scope is ignored in favor
8199 ;; of the with object.
8200 (setf (js2-function-node-ignore-dynamic fn-node) t))
8201 ;; dynamically bind all the per-function variables
8202 (let ((js2-current-script-or-fn fn-node)
8203 (js2-current-scope fn-node)
8204 (js2-nesting-of-with 0)
8205 (js2-end-flags 0)
8206 js2-label-set
8207 js2-loop-set
8208 js2-loop-and-switch-set)
8209 (js2-parse-function-params function-type fn-node pos)
8210 (when (eq function-type 'FUNCTION_ARROW)
8211 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8212 (if (and (>= js2-language-version 180)
8213 (/= (js2-peek-token) js2-LC))
8214 (js2-parse-function-closure-body fn-node)
8215 (js2-parse-function-body fn-node))
8216 (js2-check-inconsistent-return-warning fn-node name)
8217
8218 (when name
8219 (js2-node-add-children fn-node name)
8220 ;; Function expressions define a name only in the body of the
8221 ;; function, and only if not hidden by a parameter name
8222 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8223 (null (js2-scope-get-symbol js2-current-scope
8224 (js2-name-node-name name))))
8225 (js2-define-symbol js2-FUNCTION
8226 (js2-name-node-name name)
8227 fn-node))
8228 (when (eq function-type 'FUNCTION_STATEMENT)
8229 (js2-record-imenu-functions fn-node))))
8230
8231 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8232 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8233 ;; We wait until after parsing the function to set its parent scope,
8234 ;; since `js2-define-symbol' needs the defining-scope check to stop
8235 ;; at the function boundary when checking for redeclarations.
8236 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8237 fn-node))
8238
8239 (defun js2-parse-function (function-type pos star-p &optional name)
8240 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8241 beginning of the first token (function keyword, unless it's an
8242 arrow function), NAME is js2-name-node."
8243 (let ((continue t)
8244 ts-state
8245 fn-node
8246 ;; Preserve strict state outside this function.
8247 (js2-in-use-strict-directive js2-in-use-strict-directive))
8248 ;; Parse multiple times if a new strict mode directive is discovered in the
8249 ;; function body, as new rules will be retroactively applied to the legality
8250 ;; of function names and parameters.
8251 (while continue
8252 (setq ts-state (make-js2-ts-state))
8253 (setq continue (catch 'reparse
8254 (setq fn-node (js2-parse-function-internal
8255 function-type pos star-p name))
8256 ;; Don't continue.
8257 nil))
8258 (when continue
8259 (js2-ts-seek ts-state)))
8260 fn-node))
8261
8262 (defun js2-parse-statements (&optional parent)
8263 "Parse a statement list. Last token consumed must be js2-LC.
8264
8265 PARENT can be a `js2-block-node', in which case the statements are
8266 appended to PARENT. Otherwise a new `js2-block-node' is created
8267 and returned.
8268
8269 This function does not match the closing js2-RC: the caller
8270 matches the RC so it can provide a suitable error message if not
8271 matched. This means it's up to the caller to set the length of
8272 the node to include the closing RC. The node start pos is set to
8273 the absolute buffer start position, and the caller should fix it
8274 up to be relative to the parent node. All children of this block
8275 node are given relative start positions and correct lengths."
8276 (let ((pn (or parent (make-js2-block-node)))
8277 tt)
8278 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8279 (/= tt js2-RC))
8280 (js2-block-node-push pn (js2-parse-statement)))
8281 pn))
8282
8283 (defun js2-parse-statement ()
8284 (let (pn beg end)
8285 ;; coarse-grained user-interrupt check - needs work
8286 (and js2-parse-interruptable-p
8287 (zerop (% (cl-incf js2-parse-stmt-count)
8288 js2-statements-per-pause))
8289 (input-pending-p)
8290 (throw 'interrupted t))
8291 (setq pn (js2-statement-helper))
8292 ;; no-side-effects warning check
8293 (unless (js2-node-has-side-effects pn)
8294 (setq end (js2-node-end pn))
8295 (save-excursion
8296 (goto-char end)
8297 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8298 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8299 pn))
8300
8301 ;; These correspond to the switch cases in Parser.statementHelper
8302 (defconst js2-parsers
8303 (let ((parsers (make-vector js2-num-tokens
8304 #'js2-parse-expr-stmt)))
8305 (aset parsers js2-BREAK #'js2-parse-break)
8306 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8307 (aset parsers js2-CONST #'js2-parse-const-var)
8308 (aset parsers js2-CONTINUE #'js2-parse-continue)
8309 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8310 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8311 (aset parsers js2-DO #'js2-parse-do)
8312 (aset parsers js2-EXPORT #'js2-parse-export)
8313 (aset parsers js2-FOR #'js2-parse-for)
8314 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8315 (aset parsers js2-IF #'js2-parse-if)
8316 (aset parsers js2-IMPORT #'js2-parse-import)
8317 (aset parsers js2-LC #'js2-parse-block)
8318 (aset parsers js2-LET #'js2-parse-let-stmt)
8319 (aset parsers js2-NAME #'js2-parse-name-or-label)
8320 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8321 (aset parsers js2-SEMI #'js2-parse-semi)
8322 (aset parsers js2-SWITCH #'js2-parse-switch)
8323 (aset parsers js2-THROW #'js2-parse-throw)
8324 (aset parsers js2-TRY #'js2-parse-try)
8325 (aset parsers js2-VAR #'js2-parse-const-var)
8326 (aset parsers js2-WHILE #'js2-parse-while)
8327 (aset parsers js2-WITH #'js2-parse-with)
8328 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8329 parsers)
8330 "A vector mapping token types to parser functions.")
8331
8332 (defun js2-parse-warn-missing-semi (beg end)
8333 (and js2-mode-show-strict-warnings
8334 js2-strict-missing-semi-warning
8335 (js2-add-strict-warning
8336 "msg.missing.semi" nil
8337 ;; back up to beginning of statement or line
8338 (max beg (save-excursion
8339 (goto-char end)
8340 (point-at-bol)))
8341 end)))
8342
8343 (defconst js2-no-semi-insertion
8344 (list js2-IF
8345 js2-SWITCH
8346 js2-WHILE
8347 js2-DO
8348 js2-FOR
8349 js2-TRY
8350 js2-WITH
8351 js2-LC
8352 js2-ERROR
8353 js2-SEMI
8354 js2-CLASS
8355 js2-FUNCTION
8356 js2-EXPORT)
8357 "List of tokens that don't do automatic semicolon insertion.")
8358
8359 (defconst js2-autoinsert-semi-and-warn
8360 (list js2-ERROR js2-EOF js2-RC))
8361
8362 (defun js2-statement-helper ()
8363 (let* ((tt (js2-get-token))
8364 (first-tt tt)
8365 (parser (if (= tt js2-ERROR)
8366 #'js2-parse-semi
8367 (aref js2-parsers tt)))
8368 pn)
8369 ;; If the statement is set, then it's been told its label by now.
8370 (and js2-labeled-stmt
8371 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8372 (setq js2-labeled-stmt nil))
8373 (setq pn (funcall parser))
8374 ;; Don't do auto semi insertion for certain statement types.
8375 (unless (or (memq first-tt js2-no-semi-insertion)
8376 (js2-labeled-stmt-node-p pn))
8377 (js2-auto-insert-semicolon pn))
8378 pn))
8379
8380 (defun js2-auto-insert-semicolon (pn)
8381 (let* ((tt (js2-get-token))
8382 (pos (js2-node-pos pn)))
8383 (cond
8384 ((= tt js2-SEMI)
8385 ;; extend the node bounds to include the semicolon.
8386 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8387 ((memq tt js2-autoinsert-semi-and-warn)
8388 (js2-unget-token) ; Not ';', do not consume.
8389 ;; Autoinsert ;
8390 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8391 (t
8392 (if (not (js2-token-follows-eol-p (js2-current-token)))
8393 ;; Report error if no EOL or autoinsert ';' otherwise
8394 (js2-report-error "msg.no.semi.stmt")
8395 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8396 (js2-unget-token) ; Not ';', do not consume.
8397 ))))
8398
8399 (defun js2-parse-condition ()
8400 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8401 The parens are discarded and the expression node is returned.
8402 The `pos' field of the return value is set to an absolute position
8403 that must be fixed up by the caller.
8404 Return value is a list (EXPR LP RP), with absolute paren positions."
8405 (let (pn lp rp)
8406 (if (js2-must-match js2-LP "msg.no.paren.cond")
8407 (setq lp (js2-current-token-beg)))
8408 (setq pn (js2-parse-expr))
8409 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8410 (setq rp (js2-current-token-beg)))
8411 ;; Report strict warning on code like "if (a = 7) ..."
8412 (if (and js2-strict-cond-assign-warning
8413 (js2-assign-node-p pn))
8414 (js2-add-strict-warning "msg.equal.as.assign" nil
8415 (js2-node-pos pn)
8416 (+ (js2-node-pos pn)
8417 (js2-node-len pn))))
8418 (list pn lp rp)))
8419
8420 (defun js2-parse-if ()
8421 "Parser for if-statement. Last matched token must be js2-IF."
8422 (let ((pos (js2-current-token-beg))
8423 cond if-true if-false else-pos end pn)
8424 (setq cond (js2-parse-condition)
8425 if-true (js2-parse-statement)
8426 if-false (if (js2-match-token js2-ELSE)
8427 (progn
8428 (setq else-pos (- (js2-current-token-beg) pos))
8429 (js2-parse-statement)))
8430 end (js2-node-end (or if-false if-true))
8431 pn (make-js2-if-node :pos pos
8432 :len (- end pos)
8433 :condition (car cond)
8434 :then-part if-true
8435 :else-part if-false
8436 :else-pos else-pos
8437 :lp (js2-relpos (cl-second cond) pos)
8438 :rp (js2-relpos (cl-third cond) pos)))
8439 (js2-node-add-children pn (car cond) if-true if-false)
8440 pn))
8441
8442 (defun js2-parse-import ()
8443 "Parse import statement. The current token must be js2-IMPORT."
8444 (unless (js2-ast-root-p js2-current-scope)
8445 (js2-report-error "msg.mod.import.decl.at.top.level"))
8446 (let ((beg (js2-current-token-beg)))
8447 (cond ((js2-match-token js2-STRING)
8448 (make-js2-import-node
8449 :pos beg
8450 :len (- (js2-current-token-end) beg)
8451 :module-id (js2-current-token-string)))
8452 (t
8453 (let* ((import-clause (js2-parse-import-clause))
8454 (from-clause (and import-clause (js2-parse-from-clause)))
8455 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8456 (node (make-js2-import-node
8457 :pos beg
8458 :len (- (js2-current-token-end) beg)
8459 :import import-clause
8460 :from from-clause
8461 :module-id module-id)))
8462 (when import-clause
8463 (js2-node-add-children node import-clause))
8464 (when from-clause
8465 (js2-node-add-children node from-clause))
8466 node)))))
8467
8468 (defun js2-parse-import-clause ()
8469 "Parse the bindings in an import statement.
8470 This can take many forms:
8471
8472 ImportedDefaultBinding -> 'foo'
8473 NameSpaceImport -> '* as lib'
8474 NamedImports -> '{foo as bar, bang}'
8475 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8476 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8477
8478 Try to match namespace imports and named imports first because nothing can
8479 come after them. If it is an imported default binding, then it could have named
8480 imports or a namespace import that follows it.
8481 "
8482 (let* ((beg (js2-current-token-beg))
8483 (clause (make-js2-import-clause-node
8484 :pos beg))
8485 (children (list)))
8486 (cond
8487 ((js2-match-token js2-MUL)
8488 (let ((ns-import (js2-parse-namespace-import)))
8489 (when ns-import
8490 (let ((name-node (js2-namespace-import-node-name ns-import)))
8491 (js2-define-symbol
8492 js2-LET (js2-name-node-name name-node) name-node t)))
8493 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8494 (push ns-import children)))
8495 ((js2-match-token js2-LC)
8496 (let ((imports (js2-parse-export-bindings t)))
8497 (setf (js2-import-clause-node-named-imports clause) imports)
8498 (dolist (import imports)
8499 (push import children)
8500 (let ((name-node (js2-export-binding-node-local-name import)))
8501 (when name-node
8502 (js2-define-symbol
8503 js2-LET (js2-name-node-name name-node) name-node t))))))
8504 ((= (js2-peek-token) js2-NAME)
8505 (let ((binding (js2-maybe-parse-export-binding)))
8506 (let ((node-name (js2-export-binding-node-local-name binding)))
8507 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8508 (setf (js2-import-clause-node-default-binding clause) binding)
8509 (push binding children))
8510 (when (js2-match-token js2-COMMA)
8511 (cond
8512 ((js2-match-token js2-MUL)
8513 (let ((ns-import (js2-parse-namespace-import)))
8514 (let ((name-node (js2-namespace-import-node-name ns-import)))
8515 (js2-define-symbol
8516 js2-LET (js2-name-node-name name-node) name-node t))
8517 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8518 (push ns-import children)))
8519 ((js2-match-token js2-LC)
8520 (let ((imports (js2-parse-export-bindings t)))
8521 (setf (js2-import-clause-node-named-imports clause) imports)
8522 (dolist (import imports)
8523 (push import children)
8524 (let ((name-node (js2-export-binding-node-local-name import)))
8525 (when name-node
8526 (js2-define-symbol
8527 js2-LET (js2-name-node-name name-node) name-node t))))))
8528 (t (js2-report-error "msg.syntax")))))
8529 (t (js2-report-error "msg.mod.declaration.after.import")))
8530 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8531 (apply #'js2-node-add-children clause children)
8532 clause))
8533
8534 (defun js2-parse-namespace-import ()
8535 "Parse a namespace import expression such as '* as bar'.
8536 The current token must be js2-MUL."
8537 (let ((beg (js2-current-token-beg)))
8538 (when (js2-must-match js2-NAME "msg.syntax")
8539 (if (equal "as" (js2-current-token-string))
8540 (when (js2-must-match-prop-name "msg.syntax")
8541 (let ((node (make-js2-namespace-import-node
8542 :pos beg
8543 :len (- (js2-current-token-end) beg)
8544 :name (make-js2-name-node
8545 :pos (js2-current-token-beg)
8546 :len (js2-current-token-end)
8547 :name (js2-current-token-string)))))
8548 (js2-node-add-children node (js2-namespace-import-node-name node))
8549 node))
8550 (js2-unget-token)
8551 (js2-report-error "msg.syntax")))))
8552
8553
8554 (defun js2-parse-from-clause ()
8555 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8556 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8557 (let ((beg (js2-current-token-beg)))
8558 (if (equal "from" (js2-current-token-string))
8559 (cond
8560 ((js2-match-token js2-STRING)
8561 (make-js2-from-clause-node
8562 :pos beg
8563 :len (- (js2-current-token-end) beg)
8564 :module-id (js2-current-token-string)
8565 :metadata-p nil))
8566 ((js2-match-token js2-THIS)
8567 (when (js2-must-match-name "msg.mod.spec.after.from")
8568 (if (equal "module" (js2-current-token-string))
8569 (make-js2-from-clause-node
8570 :pos beg
8571 :len (- (js2-current-token-end) beg)
8572 :module-id "this"
8573 :metadata-p t)
8574 (js2-unget-token)
8575 (js2-unget-token)
8576 (js2-report-error "msg.mod.spec.after.from")
8577 nil)))
8578 (t (js2-report-error "msg.mod.spec.after.from") nil))
8579 (js2-unget-token)
8580 (js2-report-error "msg.mod.from.after.import.spec.set")
8581 nil))))
8582
8583 (defun js2-parse-export-bindings (&optional import-p)
8584 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8585 {foo as bar, baz as bang}. The current token must be
8586 js2-LC. Return a lisp list of js2-export-binding-node"
8587 (let ((bindings (list)))
8588 (while
8589 (let ((binding (js2-maybe-parse-export-binding)))
8590 (when binding
8591 (push binding bindings))
8592 (js2-match-token js2-COMMA)))
8593 (when (js2-must-match js2-RC (if import-p
8594 "msg.mod.rc.after.import.spec.list"
8595 "msg.mod.rc.after.export.spec.list"))
8596 (reverse bindings))))
8597
8598 (defun js2-maybe-parse-export-binding ()
8599 "Attempt to parse a binding expression found inside an import/export statement.
8600 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8601 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8602 js2-export-binding-node and consume all the tokens. If it does not match, it
8603 consumes no tokens."
8604 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8605 (beg (js2-current-token-beg))
8606 (extern-name-len (js2-current-token-len))
8607 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8608 (aref js2-kwd-tokens (js2-current-token-type)))))
8609 (if extern-name
8610 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8611 (if (and as (equal "as" (js2-current-token-string)))
8612 (let ((name
8613 (or
8614 (and (js2-match-token js2-DEFAULT) "default")
8615 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8616 (if name
8617 (let ((node (make-js2-export-binding-node
8618 :pos beg
8619 :len (- (js2-current-token-end) beg)
8620 :local-name (make-js2-name-node
8621 :name name
8622 :pos (js2-current-token-beg)
8623 :len (js2-current-token-len))
8624 :extern-name (make-js2-name-node
8625 :name extern-name
8626 :pos beg
8627 :len extern-name-len))))
8628 (js2-node-add-children
8629 node
8630 (js2-export-binding-node-local-name node)
8631 (js2-export-binding-node-extern-name node))
8632 node)
8633 (js2-unget-token)
8634 nil))
8635 (when as (js2-unget-token))
8636 (let* ((name-node (make-js2-name-node
8637 :name (js2-current-token-string)
8638 :pos (js2-current-token-beg)
8639 :len (js2-current-token-len)))
8640 (node (make-js2-export-binding-node
8641 :pos (js2-current-token-beg)
8642 :len (js2-current-token-len)
8643 :local-name name-node
8644 :extern-name name-node)))
8645 (when is-reserved-name
8646 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8647 (js2-node-add-children node name-node)
8648 node)))
8649 nil)))
8650
8651 (defun js2-parse-switch ()
8652 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8653 (let ((pos (js2-current-token-beg))
8654 tt pn discriminant has-default case-expr case-node
8655 case-pos cases stmt lp)
8656 (if (js2-must-match js2-LP "msg.no.paren.switch")
8657 (setq lp (js2-current-token-beg)))
8658 (setq discriminant (js2-parse-expr)
8659 pn (make-js2-switch-node :discriminant discriminant
8660 :pos pos
8661 :lp (js2-relpos lp pos)))
8662 (js2-node-add-children pn discriminant)
8663 (js2-enter-switch pn)
8664 (unwind-protect
8665 (progn
8666 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8667 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8668 (js2-must-match js2-LC "msg.no.brace.switch")
8669 (catch 'break
8670 (while t
8671 (setq tt (js2-next-token)
8672 case-pos (js2-current-token-beg))
8673 (cond
8674 ((= tt js2-RC)
8675 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8676 (throw 'break nil)) ; done
8677 ((= tt js2-CASE)
8678 (setq case-expr (js2-parse-expr))
8679 (js2-must-match js2-COLON "msg.no.colon.case"))
8680 ((= tt js2-DEFAULT)
8681 (if has-default
8682 (js2-report-error "msg.double.switch.default"))
8683 (setq has-default t
8684 case-expr nil)
8685 (js2-must-match js2-COLON "msg.no.colon.case"))
8686 (t
8687 (js2-report-error "msg.bad.switch")
8688 (throw 'break nil)))
8689 (setq case-node (make-js2-case-node :pos case-pos
8690 :len (- (js2-current-token-end) case-pos)
8691 :expr case-expr))
8692 (js2-node-add-children case-node case-expr)
8693 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8694 (/= tt js2-CASE)
8695 (/= tt js2-DEFAULT)
8696 (/= tt js2-EOF))
8697 (setf stmt (js2-parse-statement)
8698 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8699 (js2-block-node-push case-node stmt))
8700 (push case-node cases)))
8701 ;; add cases last, as pushing reverses the order to be correct
8702 (dolist (kid cases)
8703 (js2-node-add-children pn kid)
8704 (push kid (js2-switch-node-cases pn)))
8705 pn) ; return value
8706 (js2-exit-switch))))
8707
8708 (defun js2-parse-while ()
8709 "Parser for while-statement. Last matched token must be js2-WHILE."
8710 (let ((pos (js2-current-token-beg))
8711 (pn (make-js2-while-node))
8712 cond body)
8713 (js2-enter-loop pn)
8714 (unwind-protect
8715 (progn
8716 (setf cond (js2-parse-condition)
8717 (js2-while-node-condition pn) (car cond)
8718 body (js2-parse-statement)
8719 (js2-while-node-body pn) body
8720 (js2-node-len pn) (- (js2-node-end body) pos)
8721 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8722 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8723 (js2-node-add-children pn body (car cond)))
8724 (js2-exit-loop))
8725 pn))
8726
8727 (defun js2-parse-do ()
8728 "Parser for do-statement. Last matched token must be js2-DO."
8729 (let ((pos (js2-current-token-beg))
8730 (pn (make-js2-do-node))
8731 cond body end)
8732 (js2-enter-loop pn)
8733 (unwind-protect
8734 (progn
8735 (setq body (js2-parse-statement))
8736 (js2-must-match js2-WHILE "msg.no.while.do")
8737 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8738 cond (js2-parse-condition)
8739 (js2-do-node-condition pn) (car cond)
8740 (js2-do-node-body pn) body
8741 end js2-ts-cursor
8742 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8743 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8744 (js2-node-add-children pn (car cond) body))
8745 (js2-exit-loop))
8746 ;; Always auto-insert semicolon to follow SpiderMonkey:
8747 ;; It is required by ECMAScript but is ignored by the rest of
8748 ;; world; see bug 238945
8749 (if (js2-match-token js2-SEMI)
8750 (setq end js2-ts-cursor))
8751 (setf (js2-node-len pn) (- end pos))
8752 pn))
8753
8754 (defun js2-parse-export ()
8755 "Parse an export statement.
8756 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8757 expressions should only be either hoistable expressions (function or generator)
8758 or assignment expressions, but there is no checking to enforce that and so it
8759 will parse without error a small subset of
8760 invalid export statements."
8761 (unless (js2-ast-root-p js2-current-scope)
8762 (js2-report-error "msg.mod.export.decl.at.top.level"))
8763 (let ((beg (js2-current-token-beg))
8764 (children (list))
8765 exports-list from-clause declaration default)
8766 (cond
8767 ((js2-match-token js2-MUL)
8768 (setq from-clause (js2-parse-from-clause))
8769 (when from-clause
8770 (push from-clause children)))
8771 ((js2-match-token js2-LC)
8772 (setq exports-list (js2-parse-export-bindings))
8773 (when exports-list
8774 (dolist (export exports-list)
8775 (push export children)))
8776 (when (js2-match-token js2-NAME)
8777 (if (equal "from" (js2-current-token-string))
8778 (progn
8779 (js2-unget-token)
8780 (setq from-clause (js2-parse-from-clause)))
8781 (js2-unget-token))))
8782 ((js2-match-token js2-DEFAULT)
8783 (setq default (js2-parse-expr)))
8784 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8785 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8786 (t
8787 (setq declaration (js2-parse-expr))))
8788 (when from-clause
8789 (push from-clause children))
8790 (when declaration
8791 (push declaration children)
8792 (when (not (js2-function-node-p declaration))
8793 (js2-auto-insert-semicolon declaration)))
8794 (when default
8795 (push default children)
8796 (when (not (js2-function-node-p default))
8797 (js2-auto-insert-semicolon default)))
8798 (let ((node (make-js2-export-node
8799 :pos beg
8800 :len (- (js2-current-token-end) beg)
8801 :exports-list exports-list
8802 :from-clause from-clause
8803 :declaration declaration
8804 :default default)))
8805 (apply #'js2-node-add-children node children)
8806 node)))
8807
8808 (defun js2-parse-for ()
8809 "Parse a for, for-in or for each-in statement.
8810 Last matched token must be js2-FOR."
8811 (let ((for-pos (js2-current-token-beg))
8812 (tmp-scope (make-js2-scope))
8813 pn is-for-each is-for-in-or-of is-for-of
8814 in-pos each-pos tmp-pos
8815 init ; Node init is also foo in 'foo in object'.
8816 cond ; Node cond is also object in 'foo in object'.
8817 incr ; 3rd section of for-loop initializer.
8818 body tt lp rp)
8819 ;; See if this is a for each () instead of just a for ()
8820 (when (js2-match-token js2-NAME)
8821 (if (string= "each" (js2-current-token-string))
8822 (progn
8823 (setq is-for-each t
8824 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8825 (js2-record-face 'font-lock-keyword-face))
8826 (js2-report-error "msg.no.paren.for")))
8827 (if (js2-must-match js2-LP "msg.no.paren.for")
8828 (setq lp (- (js2-current-token-beg) for-pos)))
8829 (setq tt (js2-get-token))
8830 ;; Capture identifiers inside parens. We can't create the node
8831 ;; (and use it as the current scope) until we know its type.
8832 (js2-push-scope tmp-scope)
8833 (unwind-protect
8834 (progn
8835 ;; parse init clause
8836 (let ((js2-in-for-init t)) ; set as dynamic variable
8837 (cond
8838 ((= tt js2-SEMI)
8839 (js2-unget-token)
8840 (setq init (make-js2-empty-expr-node)))
8841 ((or (= tt js2-VAR) (= tt js2-LET))
8842 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8843 (t
8844 (js2-unget-token)
8845 (setq init (js2-parse-expr)))))
8846 (if (or (js2-match-token js2-IN)
8847 (and (>= js2-language-version 200)
8848 (js2-match-contextual-kwd "of")
8849 (setq is-for-of t)))
8850 (setq is-for-in-or-of t
8851 in-pos (- (js2-current-token-beg) for-pos)
8852 ;; scope of iteration target object is not the scope we've created above.
8853 ;; stash current scope temporary.
8854 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8855 (js2-parse-expr))) ; object over which we're iterating
8856 ;; else ordinary for loop - parse cond and incr
8857 (js2-must-match js2-SEMI "msg.no.semi.for")
8858 (setq cond (if (= (js2-peek-token) js2-SEMI)
8859 (make-js2-empty-expr-node) ; no loop condition
8860 (js2-parse-expr)))
8861 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8862 (setq tmp-pos (js2-current-token-end)
8863 incr (if (= (js2-peek-token) js2-RP)
8864 (make-js2-empty-expr-node :pos tmp-pos)
8865 (js2-parse-expr)))))
8866 (js2-pop-scope))
8867 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8868 (setq rp (- (js2-current-token-beg) for-pos)))
8869 (if (not is-for-in-or-of)
8870 (setq pn (make-js2-for-node :init init
8871 :condition cond
8872 :update incr
8873 :lp lp
8874 :rp rp))
8875 ;; cond could be null if 'in obj' got eaten by the init node.
8876 (if (js2-infix-node-p init)
8877 ;; it was (foo in bar) instead of (var foo in bar)
8878 (setq cond (js2-infix-node-right init)
8879 init (js2-infix-node-left init))
8880 (if (and (js2-var-decl-node-p init)
8881 (> (length (js2-var-decl-node-kids init)) 1))
8882 (js2-report-error "msg.mult.index")))
8883 (setq pn (make-js2-for-in-node :iterator init
8884 :object cond
8885 :in-pos in-pos
8886 :foreach-p is-for-each
8887 :each-pos each-pos
8888 :forof-p is-for-of
8889 :lp lp
8890 :rp rp)))
8891 ;; Transplant the declarations.
8892 (setf (js2-scope-symbol-table pn)
8893 (js2-scope-symbol-table tmp-scope))
8894 (unwind-protect
8895 (progn
8896 (js2-enter-loop pn)
8897 ;; We have to parse the body -after- creating the loop node,
8898 ;; so that the loop node appears in the js2-loop-set, allowing
8899 ;; break/continue statements to find the enclosing loop.
8900 (setf body (js2-parse-statement)
8901 (js2-loop-node-body pn) body
8902 (js2-node-pos pn) for-pos
8903 (js2-node-len pn) (- (js2-node-end body) for-pos))
8904 (js2-node-add-children pn init cond incr body))
8905 ;; finally
8906 (js2-exit-loop))
8907 pn))
8908
8909 (defun js2-parse-try ()
8910 "Parse a try statement. Last matched token must be js2-TRY."
8911 (let ((try-pos (js2-current-token-beg))
8912 try-end
8913 try-block
8914 catch-blocks
8915 finally-block
8916 saw-default-catch
8917 peek)
8918 (if (/= (js2-peek-token) js2-LC)
8919 (js2-report-error "msg.no.brace.try"))
8920 (setq try-block (js2-parse-statement)
8921 try-end (js2-node-end try-block)
8922 peek (js2-peek-token))
8923 (cond
8924 ((= peek js2-CATCH)
8925 (while (js2-match-token js2-CATCH)
8926 (let* ((catch-pos (js2-current-token-beg))
8927 (catch-node (make-js2-catch-node :pos catch-pos))
8928 param
8929 guard-kwd
8930 catch-cond
8931 lp rp)
8932 (if saw-default-catch
8933 (js2-report-error "msg.catch.unreachable"))
8934 (if (js2-must-match js2-LP "msg.no.paren.catch")
8935 (setq lp (- (js2-current-token-beg) catch-pos)))
8936 (js2-push-scope catch-node)
8937 (let ((tt (js2-peek-token)))
8938 (cond
8939 ;; Destructuring pattern:
8940 ;; catch ({ message, file }) { ... }
8941 ((or (= tt js2-LB) (= tt js2-LC))
8942 (js2-get-token)
8943 (setq param (js2-parse-destruct-primary-expr))
8944 (js2-define-destruct-symbols param js2-LET nil))
8945 ;; Simple name.
8946 (t
8947 (js2-must-match-name "msg.bad.catchcond")
8948 (setq param (js2-create-name-node))
8949 (js2-define-symbol js2-LET (js2-current-token-string) param)
8950 (js2-check-strict-identifier param))))
8951 ;; Catch condition.
8952 (if (js2-match-token js2-IF)
8953 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8954 catch-cond (js2-parse-expr))
8955 (setq saw-default-catch t))
8956 (if (js2-must-match js2-RP "msg.bad.catchcond")
8957 (setq rp (- (js2-current-token-beg) catch-pos)))
8958 (js2-must-match js2-LC "msg.no.brace.catchblock")
8959 (js2-parse-statements catch-node)
8960 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8961 (setq try-end (js2-current-token-end)))
8962 (js2-pop-scope)
8963 (setf (js2-node-len catch-node) (- try-end catch-pos)
8964 (js2-catch-node-param catch-node) param
8965 (js2-catch-node-guard-expr catch-node) catch-cond
8966 (js2-catch-node-guard-kwd catch-node) guard-kwd
8967 (js2-catch-node-lp catch-node) lp
8968 (js2-catch-node-rp catch-node) rp)
8969 (js2-node-add-children catch-node param catch-cond)
8970 (push catch-node catch-blocks))))
8971 ((/= peek js2-FINALLY)
8972 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8973 (js2-node-pos try-block)
8974 (- (setq try-end (js2-node-end try-block))
8975 (js2-node-pos try-block)))))
8976 (when (js2-match-token js2-FINALLY)
8977 (let ((finally-pos (js2-current-token-beg))
8978 (block (js2-parse-statement)))
8979 (setq try-end (js2-node-end block)
8980 finally-block (make-js2-finally-node :pos finally-pos
8981 :len (- try-end finally-pos)
8982 :body block))
8983 (js2-node-add-children finally-block block)))
8984 (let ((pn (make-js2-try-node :pos try-pos
8985 :len (- try-end try-pos)
8986 :try-block try-block
8987 :finally-block finally-block)))
8988 (js2-node-add-children pn try-block finally-block)
8989 ;; Push them onto the try-node, which reverses and corrects their order.
8990 (dolist (cb catch-blocks)
8991 (js2-node-add-children pn cb)
8992 (push cb (js2-try-node-catch-clauses pn)))
8993 pn)))
8994
8995 (defun js2-parse-throw ()
8996 "Parser for throw-statement. Last matched token must be js2-THROW."
8997 (let ((pos (js2-current-token-beg))
8998 expr pn)
8999 (if (= (js2-peek-token-or-eol) js2-EOL)
9000 ;; ECMAScript does not allow new lines before throw expression,
9001 ;; see bug 256617
9002 (js2-report-error "msg.bad.throw.eol"))
9003 (setq expr (js2-parse-expr)
9004 pn (make-js2-throw-node :pos pos
9005 :len (- (js2-node-end expr) pos)
9006 :expr expr))
9007 (js2-node-add-children pn expr)
9008 pn))
9009
9010 (defun js2-match-jump-label-name (label-name)
9011 "If break/continue specified a label, return that label's labeled stmt.
9012 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9013 does not match an existing label, reports an error and returns nil."
9014 (let ((bundle (cdr (assoc label-name js2-label-set))))
9015 (if (null bundle)
9016 (js2-report-error "msg.undef.label"))
9017 bundle))
9018
9019 (defun js2-parse-break ()
9020 "Parser for break-statement. Last matched token must be js2-BREAK."
9021 (let ((pos (js2-current-token-beg))
9022 (end (js2-current-token-end))
9023 break-target ; statement to break from
9024 break-label ; in "break foo", name-node representing the foo
9025 labels ; matching labeled statement to break to
9026 pn)
9027 (when (eq (js2-peek-token-or-eol) js2-NAME)
9028 (js2-get-token)
9029 (setq break-label (js2-create-name-node)
9030 end (js2-node-end break-label)
9031 ;; matchJumpLabelName only matches if there is one
9032 labels (js2-match-jump-label-name (js2-current-token-string))
9033 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9034 (unless (or break-target break-label)
9035 ;; no break target specified - try for innermost enclosing loop/switch
9036 (if (null js2-loop-and-switch-set)
9037 (unless break-label
9038 (js2-report-error "msg.bad.break" nil pos (length "break")))
9039 (setq break-target (car js2-loop-and-switch-set))))
9040 (setq pn (make-js2-break-node :pos pos
9041 :len (- end pos)
9042 :label break-label
9043 :target break-target))
9044 (js2-node-add-children pn break-label) ; but not break-target
9045 pn))
9046
9047 (defun js2-parse-continue ()
9048 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9049 (let ((pos (js2-current-token-beg))
9050 (end (js2-current-token-end))
9051 label ; optional user-specified label, a `js2-name-node'
9052 labels ; current matching labeled stmt, if any
9053 target ; the `js2-loop-node' target of this continue stmt
9054 pn)
9055 (when (= (js2-peek-token-or-eol) js2-NAME)
9056 (js2-get-token)
9057 (setq label (js2-create-name-node)
9058 end (js2-node-end label)
9059 ;; matchJumpLabelName only matches if there is one
9060 labels (js2-match-jump-label-name (js2-current-token-string))))
9061 (cond
9062 ((null labels) ; no current label to go to
9063 (if (null js2-loop-set) ; no loop to continue to
9064 (js2-report-error "msg.continue.outside" nil pos
9065 (length "continue"))
9066 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9067 (t
9068 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9069 (setq target (js2-labeled-stmt-node-stmt labels))
9070 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9071 (setq pn (make-js2-continue-node :pos pos
9072 :len (- end pos)
9073 :label label
9074 :target target))
9075 (js2-node-add-children pn label) ; but not target - it's not our child
9076 pn))
9077
9078 (defun js2-parse-with ()
9079 "Parser for with-statement. Last matched token must be js2-WITH."
9080 (when js2-in-use-strict-directive
9081 (js2-report-error "msg.no.with.strict"))
9082 (let ((pos (js2-current-token-beg))
9083 obj body pn lp rp)
9084 (if (js2-must-match js2-LP "msg.no.paren.with")
9085 (setq lp (js2-current-token-beg)))
9086 (setq obj (js2-parse-expr))
9087 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9088 (setq rp (js2-current-token-beg)))
9089 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9090 (setq body (js2-parse-statement)))
9091 (setq pn (make-js2-with-node :pos pos
9092 :len (- (js2-node-end body) pos)
9093 :object obj
9094 :body body
9095 :lp (js2-relpos lp pos)
9096 :rp (js2-relpos rp pos)))
9097 (js2-node-add-children pn obj body)
9098 pn))
9099
9100 (defun js2-parse-const-var ()
9101 "Parser for var- or const-statement.
9102 Last matched token must be js2-CONST or js2-VAR."
9103 (let ((tt (js2-current-token-type))
9104 (pos (js2-current-token-beg))
9105 expr pn)
9106 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9107 pn (make-js2-expr-stmt-node :pos pos
9108 :len (- (js2-node-end expr) pos)
9109 :expr expr))
9110 (js2-node-add-children pn expr)
9111 pn))
9112
9113 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9114 (let ((pn (make-js2-expr-stmt-node :pos pos
9115 :len (js2-node-len expr)
9116 :type (if (js2-inside-function)
9117 js2-EXPR_VOID
9118 js2-EXPR_RESULT)
9119 :expr expr)))
9120 (if add-child
9121 (js2-node-add-children pn expr))
9122 pn))
9123
9124 (defun js2-parse-let-stmt ()
9125 "Parser for let-statement. Last matched token must be js2-LET."
9126 (let ((pos (js2-current-token-beg))
9127 expr pn)
9128 (if (= (js2-peek-token) js2-LP)
9129 ;; let expression in statement context
9130 (setq expr (js2-parse-let pos 'statement)
9131 pn (js2-wrap-with-expr-stmt pos expr t))
9132 ;; else we're looking at a statement like let x=6, y=7;
9133 (setf expr (js2-parse-variables js2-LET pos)
9134 pn (js2-wrap-with-expr-stmt pos expr t)
9135 (js2-node-type pn) js2-EXPR_RESULT))
9136 pn))
9137
9138 (defun js2-parse-ret-yield ()
9139 (js2-parse-return-or-yield (js2-current-token-type) nil))
9140
9141 (defconst js2-parse-return-stmt-enders
9142 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9143
9144 (defsubst js2-now-all-set (before after mask)
9145 "Return whether or not the bits in the mask have changed to all set.
9146 BEFORE is bits before change, AFTER is bits after change, and MASK is
9147 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9148 but not BEFORE."
9149 (and (/= (logand before mask) mask)
9150 (= (logand after mask) mask)))
9151
9152 (defun js2-parse-return-or-yield (tt expr-context)
9153 (let* ((pos (js2-current-token-beg))
9154 (end (js2-current-token-end))
9155 (before js2-end-flags)
9156 (inside-function (js2-inside-function))
9157 (gen-type (and inside-function (js2-function-node-generator-type
9158 js2-current-script-or-fn)))
9159 e ret name yield-star-p)
9160 (unless inside-function
9161 (js2-report-error (if (eq tt js2-RETURN)
9162 "msg.bad.return"
9163 "msg.bad.yield")))
9164 (when (and inside-function
9165 (eq gen-type 'STAR)
9166 (js2-match-token js2-MUL))
9167 (setq yield-star-p t))
9168 ;; This is ugly, but we don't want to require a semicolon.
9169 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9170 (setq e (js2-parse-expr)
9171 end (js2-node-end e)))
9172 (cond
9173 ((eq tt js2-RETURN)
9174 (js2-set-flag js2-end-flags (if (null e)
9175 js2-end-returns
9176 js2-end-returns-value))
9177 (setq ret (make-js2-return-node :pos pos
9178 :len (- end pos)
9179 :retval e))
9180 (js2-node-add-children ret e)
9181 ;; See if we need a strict mode warning.
9182 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9183 ;; more thorough and accurate than this before/after flag check.
9184 ;; E.g. if there's a finally-block that always returns, we shouldn't
9185 ;; show a warning generated by inconsistent returns in the catch blocks.
9186 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9187 ;; so we know which returns/yields to highlight, and we should get rid of
9188 ;; all the checking in `js2-parse-return-or-yield'.
9189 (if (and js2-strict-inconsistent-return-warning
9190 (js2-now-all-set before js2-end-flags
9191 (logior js2-end-returns js2-end-returns-value)))
9192 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9193 ((eq gen-type 'COMPREHENSION)
9194 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9195 ;; like SpiderMonkey does.
9196 (js2-report-error "msg.syntax" nil pos 5))
9197 (t
9198 (setq ret (make-js2-yield-node :pos pos
9199 :len (- end pos)
9200 :value e
9201 :star-p yield-star-p))
9202 (js2-node-add-children ret e)
9203 (unless expr-context
9204 (setq e ret
9205 ret (js2-wrap-with-expr-stmt pos e t))
9206 (js2-set-requires-activation)
9207 (js2-set-is-generator))))
9208 ;; see if we are mixing yields and value returns.
9209 (when (and inside-function
9210 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9211 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9212 'LEGACY))
9213 (setq name (js2-function-name js2-current-script-or-fn))
9214 (if (zerop (length name))
9215 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9216 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9217 ret))
9218
9219 (defun js2-parse-debugger ()
9220 (make-js2-keyword-node :type js2-DEBUGGER))
9221
9222 (defun js2-parse-block ()
9223 "Parser for a curly-delimited statement block.
9224 Last token matched must be `js2-LC'."
9225 (let ((pos (js2-current-token-beg))
9226 (pn (make-js2-scope)))
9227 (js2-push-scope pn)
9228 (unwind-protect
9229 (progn
9230 (js2-parse-statements pn)
9231 (js2-must-match js2-RC "msg.no.brace.block")
9232 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9233 (js2-pop-scope))
9234 pn))
9235
9236 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9237 (defun js2-parse-semi ()
9238 "Parse a statement or handle an error.
9239 Current token type is `js2-SEMI' or `js2-ERROR'."
9240 (let ((tt (js2-current-token-type)) pos len)
9241 (if (eq tt js2-SEMI)
9242 (make-js2-empty-expr-node :len 1)
9243 (setq pos (js2-current-token-beg)
9244 len (- (js2-current-token-end) pos))
9245 (js2-report-error "msg.syntax" nil pos len)
9246 (make-js2-error-node :pos pos :len len))))
9247
9248 (defun js2-parse-default-xml-namespace ()
9249 "Parse a `default xml namespace = <expr>' e4x statement."
9250 (let ((pos (js2-current-token-beg))
9251 end len expr unary)
9252 (js2-must-have-xml)
9253 (js2-set-requires-activation)
9254 (setq len (- js2-ts-cursor pos))
9255 (unless (and (js2-match-token js2-NAME)
9256 (string= (js2-current-token-string) "xml"))
9257 (js2-report-error "msg.bad.namespace" nil pos len))
9258 (unless (and (js2-match-token js2-NAME)
9259 (string= (js2-current-token-string) "namespace"))
9260 (js2-report-error "msg.bad.namespace" nil pos len))
9261 (unless (js2-match-token js2-ASSIGN)
9262 (js2-report-error "msg.bad.namespace" nil pos len))
9263 (setq expr (js2-parse-expr)
9264 end (js2-node-end expr)
9265 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9266 :pos pos
9267 :len (- end pos)
9268 :operand expr))
9269 (js2-node-add-children unary expr)
9270 (make-js2-expr-stmt-node :pos pos
9271 :len (- end pos)
9272 :expr unary)))
9273
9274 (defun js2-record-label (label bundle)
9275 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9276 (js2-get-token)
9277 (let ((name (js2-label-node-name label))
9278 labeled-stmt
9279 dup)
9280 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9281 ;; flag both labels if possible when used in editing mode
9282 (if (and js2-parse-ide-mode
9283 (setq dup (js2-get-label-by-name labeled-stmt name)))
9284 (js2-report-error "msg.dup.label" nil
9285 (js2-node-abs-pos dup) (js2-node-len dup)))
9286 (js2-report-error "msg.dup.label" nil
9287 (js2-node-pos label) (js2-node-len label)))
9288 (js2-labeled-stmt-node-add-label bundle label)
9289 (js2-node-add-children bundle label)
9290 ;; Add one reference to the bundle per label in `js2-label-set'
9291 (push (cons name bundle) js2-label-set)))
9292
9293 (defun js2-parse-name-or-label ()
9294 "Parser for identifier or label. Last token matched must be js2-NAME.
9295 Called when we found a name in a statement context. If it's a label, we gather
9296 up any following labels and the next non-label statement into a
9297 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9298 expression and return it wrapped in a `js2-expr-stmt-node'."
9299 (let ((pos (js2-current-token-beg))
9300 expr stmt bundle
9301 (continue t))
9302 ;; set check for label and call down to `js2-parse-primary-expr'
9303 (setq expr (js2-maybe-parse-label))
9304 (if (null expr)
9305 ;; Parse the non-label expression and wrap with expression stmt.
9306 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9307 ;; else parsed a label
9308 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9309 (js2-record-label expr bundle)
9310 ;; look for more labels
9311 (while (and continue (= (js2-get-token) js2-NAME))
9312 (if (setq expr (js2-maybe-parse-label))
9313 (js2-record-label expr bundle)
9314 (setq expr (js2-parse-expr)
9315 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9316 continue nil)
9317 (js2-auto-insert-semicolon stmt)))
9318 ;; no more labels; now parse the labeled statement
9319 (unwind-protect
9320 (unless stmt
9321 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9322 (js2-unget-token)
9323 (setq stmt (js2-statement-helper))))
9324 ;; remove the labels for this statement from the global set
9325 (dolist (label (js2-labeled-stmt-node-labels bundle))
9326 (setq js2-label-set (remove label js2-label-set))))
9327 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9328 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9329 (js2-node-add-children bundle stmt)
9330 bundle)))
9331
9332 (defun js2-maybe-parse-label ()
9333 (cl-assert (= (js2-current-token-type) js2-NAME))
9334 (let (label-pos
9335 (next-tt (js2-get-token))
9336 (label-end (js2-current-token-end)))
9337 ;; Do not consume colon, it is used as unwind indicator
9338 ;; to return to statementHelper.
9339 (js2-unget-token)
9340 (if (= next-tt js2-COLON)
9341 (prog2
9342 (setq label-pos (js2-current-token-beg))
9343 (make-js2-label-node :pos label-pos
9344 :len (- label-end label-pos)
9345 :name (js2-current-token-string))
9346 (js2-set-face label-pos
9347 label-end
9348 'font-lock-variable-name-face 'record))
9349 ;; Backtrack from the name token, too.
9350 (js2-unget-token)
9351 nil)))
9352
9353 (defun js2-parse-expr-stmt ()
9354 "Default parser in statement context, if no recognized statement found."
9355 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9356 (progn
9357 (js2-unget-token)
9358 (js2-parse-expr)) t))
9359
9360 (defun js2-parse-variables (decl-type pos)
9361 "Parse a comma-separated list of variable declarations.
9362 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9363
9364 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9365 For 'var' or 'const', the keyword should be the token last scanned.
9366
9367 POS is the position where the node should start. It's sometimes the
9368 var/const/let keyword, and other times the beginning of the first token
9369 in the first variable declaration.
9370
9371 Returns the parsed `js2-var-decl-node' expression node."
9372 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9373 :pos pos))
9374 destructuring kid-pos tt init name end nbeg nend vi
9375 (continue t))
9376 ;; Example:
9377 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9378 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9379 ;; var {a, b} = baz;
9380 (while continue
9381 (setq destructuring nil
9382 name nil
9383 tt (js2-get-token)
9384 kid-pos (js2-current-token-beg)
9385 end (js2-current-token-end)
9386 init nil)
9387 (if (or (= tt js2-LB) (= tt js2-LC))
9388 ;; Destructuring assignment, e.g., var [a, b] = ...
9389 (setq destructuring (js2-parse-destruct-primary-expr)
9390 end (js2-node-end destructuring))
9391 ;; Simple variable name
9392 (js2-unget-token)
9393 (when (js2-must-match-name "msg.bad.var")
9394 (setq name (js2-create-name-node)
9395 nbeg (js2-current-token-beg)
9396 nend (js2-current-token-end)
9397 end nend)
9398 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9399 (js2-check-strict-identifier name)))
9400 (when (js2-match-token js2-ASSIGN)
9401 (setq init (js2-parse-assign-expr)
9402 end (js2-node-end init))
9403 (js2-record-imenu-functions init name))
9404 (when name
9405 (js2-set-face nbeg nend (if (js2-function-node-p init)
9406 'font-lock-function-name-face
9407 'font-lock-variable-name-face)
9408 'record))
9409 (setq vi (make-js2-var-init-node :pos kid-pos
9410 :len (- end kid-pos)
9411 :type decl-type))
9412 (if destructuring
9413 (progn
9414 (if (and (null init) (not js2-in-for-init))
9415 (js2-report-error "msg.destruct.assign.no.init"))
9416 (js2-define-destruct-symbols destructuring
9417 decl-type
9418 'font-lock-variable-name-face)
9419 (setf (js2-var-init-node-target vi) destructuring))
9420 (setf (js2-var-init-node-target vi) name))
9421 (setf (js2-var-init-node-initializer vi) init)
9422 (js2-node-add-children vi name destructuring init)
9423 (js2-block-node-push result vi)
9424 (unless (js2-match-token js2-COMMA)
9425 (setq continue nil)))
9426 (setf (js2-node-len result) (- end pos))
9427 result))
9428
9429 (defun js2-parse-let (pos &optional stmt-p)
9430 "Parse a let expression or statement.
9431 A let-expression is of the form `let (vars) expr'.
9432 A let-statement is of the form `let (vars) {statements}'.
9433 The third form of let is a variable declaration list, handled
9434 by `js2-parse-variables'."
9435 (let ((pn (make-js2-let-node :pos pos))
9436 beg vars body)
9437 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9438 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9439 (js2-push-scope pn)
9440 (unwind-protect
9441 (progn
9442 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9443 (if (js2-must-match js2-RP "msg.no.paren.let")
9444 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9445 (if (and stmt-p (js2-match-token js2-LC))
9446 ;; let statement
9447 (progn
9448 (setf beg (js2-current-token-beg) ; position stmt at LC
9449 body (js2-parse-statements))
9450 (js2-must-match js2-RC "msg.no.curly.let")
9451 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9452 (js2-node-len pn) (- (js2-current-token-end) pos)
9453 (js2-let-node-body pn) body
9454 (js2-node-type pn) js2-LET))
9455 ;; let expression
9456 (setf body (js2-parse-expr)
9457 (js2-node-len pn) (- (js2-node-end body) pos)
9458 (js2-let-node-body pn) body))
9459 (setf (js2-let-node-vars pn) vars)
9460 (js2-node-add-children pn vars body))
9461 (js2-pop-scope))
9462 pn))
9463
9464 (defun js2-define-new-symbol (decl-type name node &optional scope)
9465 (js2-scope-put-symbol (or scope js2-current-scope)
9466 name
9467 (make-js2-symbol decl-type name node)))
9468
9469 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9470 "Define a symbol in the current scope.
9471 If NODE is non-nil, it is the AST node associated with the symbol."
9472 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9473 (symbol (if defining-scope
9474 (js2-scope-get-symbol defining-scope name)))
9475 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9476 (pos (if node (js2-node-abs-pos node)))
9477 (len (if node (js2-node-len node))))
9478 (cond
9479 ((and symbol ; already defined
9480 (or (if js2-in-use-strict-directive
9481 ;; two const-bound vars in this block have same name
9482 (and (= sdt js2-CONST)
9483 (eq defining-scope js2-current-scope))
9484 (or (= sdt js2-CONST) ; old version is const
9485 (= decl-type js2-CONST))) ; new version is const
9486 ;; two let-bound vars in this block have same name
9487 (and (= sdt js2-LET)
9488 (eq defining-scope js2-current-scope))))
9489 (js2-report-error
9490 (cond
9491 ((= sdt js2-CONST) "msg.const.redecl")
9492 ((= sdt js2-LET) "msg.let.redecl")
9493 ((= sdt js2-VAR) "msg.var.redecl")
9494 ((= sdt js2-FUNCTION) "msg.function.redecl")
9495 (t "msg.parm.redecl"))
9496 name pos len))
9497 ((or (= decl-type js2-LET)
9498 ;; strict mode const is scoped to the current LexicalEnvironment
9499 (and js2-in-use-strict-directive
9500 (= decl-type js2-CONST)))
9501 (if (and (= decl-type js2-LET)
9502 (not ignore-not-in-block)
9503 (or (= (js2-node-type js2-current-scope) js2-IF)
9504 (js2-loop-node-p js2-current-scope)))
9505 (js2-report-error "msg.let.decl.not.in.block")
9506 (js2-define-new-symbol decl-type name node)))
9507 ((or (= decl-type js2-VAR)
9508 (= decl-type js2-FUNCTION)
9509 ;; sloppy mode const is scoped to the current VariableEnvironment
9510 (and (not js2-in-use-strict-directive)
9511 (= decl-type js2-CONST)))
9512 (if symbol
9513 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9514 (js2-add-strict-warning "msg.var.redecl" name)
9515 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9516 (js2-add-strict-warning "msg.var.hides.arg" name)))
9517 (js2-define-new-symbol decl-type name node
9518 js2-current-script-or-fn)))
9519 ((= decl-type js2-LP)
9520 (if symbol
9521 ;; must be duplicate parameter. Second parameter hides the
9522 ;; first, so go ahead and add the second pararameter
9523 (js2-report-warning "msg.dup.parms" name))
9524 (js2-define-new-symbol decl-type name node))
9525 (t (js2-code-bug)))))
9526
9527 (defun js2-parse-paren-expr-or-generator-comp ()
9528 (let ((px-pos (js2-current-token-beg)))
9529 (cond
9530 ((and (>= js2-language-version 200)
9531 (js2-match-token js2-FOR))
9532 (js2-parse-generator-comp px-pos))
9533 ((and (>= js2-language-version 200)
9534 (js2-match-token js2-RP))
9535 ;; Not valid expression syntax, but this is valid in an arrow
9536 ;; function with no params: () => body.
9537 (if (eq (js2-peek-token) js2-ARROW)
9538 ;; Return whatever, it will hopefully be rewinded and
9539 ;; reparsed when we reach the =>.
9540 (make-js2-keyword-node :type js2-NULL)
9541 (js2-report-error "msg.syntax")
9542 (make-js2-error-node)))
9543 (t
9544 (let* ((js2-in-for-init nil)
9545 (expr (js2-parse-expr))
9546 (pn (make-js2-paren-node :pos px-pos
9547 :expr expr)))
9548 (js2-node-add-children pn (js2-paren-node-expr pn))
9549 (js2-must-match js2-RP "msg.no.paren")
9550 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9551 pn)))))
9552
9553 (defun js2-parse-expr (&optional oneshot)
9554 (let* ((pn (js2-parse-assign-expr))
9555 (pos (js2-node-pos pn))
9556 left
9557 right
9558 op-pos)
9559 (while (and (not oneshot)
9560 (js2-match-token js2-COMMA))
9561 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9562 (if (= (js2-peek-token) js2-YIELD)
9563 (js2-report-error "msg.yield.parenthesized"))
9564 (setq right (js2-parse-assign-expr)
9565 left pn
9566 pn (make-js2-infix-node :type js2-COMMA
9567 :pos pos
9568 :len (- js2-ts-cursor pos)
9569 :op-pos op-pos
9570 :left left
9571 :right right))
9572 (js2-node-add-children pn left right))
9573 pn))
9574
9575 (defun js2-parse-assign-expr ()
9576 (let ((tt (js2-get-token))
9577 (pos (js2-current-token-beg))
9578 pn left right op-pos
9579 ts-state recorded-identifiers parsed-errors)
9580 (if (= tt js2-YIELD)
9581 (js2-parse-return-or-yield tt t)
9582 ;; Save the tokenizer state in case we find an arrow function
9583 ;; and have to rewind.
9584 (setq ts-state (make-js2-ts-state)
9585 recorded-identifiers js2-recorded-identifiers
9586 parsed-errors js2-parsed-errors)
9587 ;; not yield - parse assignment expression
9588 (setq pn (js2-parse-cond-expr)
9589 tt (js2-get-token))
9590 (cond
9591 ((and (<= js2-first-assign tt)
9592 (<= tt js2-last-assign))
9593 ;; tt express assignment (=, |=, ^=, ..., %=)
9594 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9595 left pn)
9596 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9597 ;; care about assignment to strict variable names.
9598 (when (js2-name-node-p left)
9599 (js2-check-strict-identifier left))
9600 (setq right (js2-parse-assign-expr)
9601 pn (make-js2-assign-node :type tt
9602 :pos pos
9603 :len (- (js2-node-end right) pos)
9604 :op-pos op-pos
9605 :left left
9606 :right right))
9607 (when js2-parse-ide-mode
9608 (js2-highlight-assign-targets pn left right)
9609 (js2-record-imenu-functions right left))
9610 ;; do this last so ide checks above can use absolute positions
9611 (js2-node-add-children pn left right))
9612 ((and (= tt js2-ARROW)
9613 (>= js2-language-version 200))
9614 (js2-ts-seek ts-state)
9615 (setq js2-recorded-identifiers recorded-identifiers
9616 js2-parsed-errors parsed-errors)
9617 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9618 (t
9619 (js2-unget-token)))
9620 pn)))
9621
9622 (defun js2-parse-cond-expr ()
9623 (let ((pos (js2-current-token-beg))
9624 (pn (js2-parse-or-expr))
9625 test-expr
9626 if-true
9627 if-false
9628 q-pos
9629 c-pos)
9630 (when (js2-match-token js2-HOOK)
9631 (setq q-pos (- (js2-current-token-beg) pos)
9632 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9633 (js2-must-match js2-COLON "msg.no.colon.cond")
9634 (setq c-pos (- (js2-current-token-beg) pos)
9635 if-false (js2-parse-assign-expr)
9636 test-expr pn
9637 pn (make-js2-cond-node :pos pos
9638 :len (- (js2-node-end if-false) pos)
9639 :test-expr test-expr
9640 :true-expr if-true
9641 :false-expr if-false
9642 :q-pos q-pos
9643 :c-pos c-pos))
9644 (js2-node-add-children pn test-expr if-true if-false))
9645 pn))
9646
9647 (defun js2-make-binary (type left parser &optional no-get)
9648 "Helper for constructing a binary-operator AST node.
9649 LEFT is the left-side-expression, already parsed, and the
9650 binary operator should have just been matched.
9651 PARSER is a function to call to parse the right operand,
9652 or a `js2-node' struct if it has already been parsed.
9653 FIXME: The latter option is unused?"
9654 (let* ((pos (js2-node-pos left))
9655 (op-pos (- (js2-current-token-beg) pos))
9656 (right (if (js2-node-p parser)
9657 parser
9658 (unless no-get (js2-get-token))
9659 (funcall parser)))
9660 (pn (make-js2-infix-node :type type
9661 :pos pos
9662 :len (- (js2-node-end right) pos)
9663 :op-pos op-pos
9664 :left left
9665 :right right)))
9666 (js2-node-add-children pn left right)
9667 pn))
9668
9669 (defun js2-parse-or-expr ()
9670 (let ((pn (js2-parse-and-expr)))
9671 (when (js2-match-token js2-OR)
9672 (setq pn (js2-make-binary js2-OR
9673 pn
9674 'js2-parse-or-expr)))
9675 pn))
9676
9677 (defun js2-parse-and-expr ()
9678 (let ((pn (js2-parse-bit-or-expr)))
9679 (when (js2-match-token js2-AND)
9680 (setq pn (js2-make-binary js2-AND
9681 pn
9682 'js2-parse-and-expr)))
9683 pn))
9684
9685 (defun js2-parse-bit-or-expr ()
9686 (let ((pn (js2-parse-bit-xor-expr)))
9687 (while (js2-match-token js2-BITOR)
9688 (setq pn (js2-make-binary js2-BITOR
9689 pn
9690 'js2-parse-bit-xor-expr)))
9691 pn))
9692
9693 (defun js2-parse-bit-xor-expr ()
9694 (let ((pn (js2-parse-bit-and-expr)))
9695 (while (js2-match-token js2-BITXOR)
9696 (setq pn (js2-make-binary js2-BITXOR
9697 pn
9698 'js2-parse-bit-and-expr)))
9699 pn))
9700
9701 (defun js2-parse-bit-and-expr ()
9702 (let ((pn (js2-parse-eq-expr)))
9703 (while (js2-match-token js2-BITAND)
9704 (setq pn (js2-make-binary js2-BITAND
9705 pn
9706 'js2-parse-eq-expr)))
9707 pn))
9708
9709 (defconst js2-parse-eq-ops
9710 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9711
9712 (defun js2-parse-eq-expr ()
9713 (let ((pn (js2-parse-rel-expr))
9714 tt)
9715 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9716 (setq pn (js2-make-binary tt
9717 pn
9718 'js2-parse-rel-expr)))
9719 (js2-unget-token)
9720 pn))
9721
9722 (defconst js2-parse-rel-ops
9723 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9724
9725 (defun js2-parse-rel-expr ()
9726 (let ((pn (js2-parse-shift-expr))
9727 (continue t)
9728 tt)
9729 (while continue
9730 (setq tt (js2-get-token))
9731 (cond
9732 ((and js2-in-for-init (= tt js2-IN))
9733 (js2-unget-token)
9734 (setq continue nil))
9735 ((memq tt js2-parse-rel-ops)
9736 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9737 (t
9738 (js2-unget-token)
9739 (setq continue nil))))
9740 pn))
9741
9742 (defconst js2-parse-shift-ops
9743 (list js2-LSH js2-URSH js2-RSH))
9744
9745 (defun js2-parse-shift-expr ()
9746 (let ((pn (js2-parse-add-expr))
9747 tt
9748 (continue t))
9749 (while continue
9750 (setq tt (js2-get-token))
9751 (if (memq tt js2-parse-shift-ops)
9752 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9753 (js2-unget-token)
9754 (setq continue nil)))
9755 pn))
9756
9757 (defun js2-parse-add-expr ()
9758 (let ((pn (js2-parse-mul-expr))
9759 tt
9760 (continue t))
9761 (while continue
9762 (setq tt (js2-get-token))
9763 (if (or (= tt js2-ADD) (= tt js2-SUB))
9764 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9765 (js2-unget-token)
9766 (setq continue nil)))
9767 pn))
9768
9769 (defconst js2-parse-mul-ops
9770 (list js2-MUL js2-DIV js2-MOD))
9771
9772 (defun js2-parse-mul-expr ()
9773 (let ((pn (js2-parse-unary-expr))
9774 tt
9775 (continue t))
9776 (while continue
9777 (setq tt (js2-get-token))
9778 (if (memq tt js2-parse-mul-ops)
9779 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9780 (js2-unget-token)
9781 (setq continue nil)))
9782 pn))
9783
9784 (defun js2-make-unary (type parser &rest args)
9785 "Make a unary node of type TYPE.
9786 PARSER is either a node (for postfix operators) or a function to call
9787 to parse the operand (for prefix operators)."
9788 (let* ((pos (js2-current-token-beg))
9789 (postfix (js2-node-p parser))
9790 (expr (if postfix
9791 parser
9792 (apply parser args)))
9793 end
9794 pn)
9795 (if postfix ; e.g. i++
9796 (setq pos (js2-node-pos expr)
9797 end (js2-current-token-end))
9798 (setq end (js2-node-end expr)))
9799 (setq pn (make-js2-unary-node :type type
9800 :pos pos
9801 :len (- end pos)
9802 :operand expr))
9803 (js2-node-add-children pn expr)
9804 pn))
9805
9806 (defconst js2-incrementable-node-types
9807 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9808 "Node types that can be the operand of a ++ or -- operator.")
9809
9810 (defun js2-check-bad-inc-dec (tt beg end unary)
9811 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9812 js2-incrementable-node-types)
9813 (js2-report-error (if (= tt js2-INC)
9814 "msg.bad.incr"
9815 "msg.bad.decr")
9816 nil beg (- end beg))))
9817
9818 (defun js2-parse-unary-expr ()
9819 (let ((tt (js2-current-token-type))
9820 pn expr beg end)
9821 (cond
9822 ((or (= tt js2-VOID)
9823 (= tt js2-NOT)
9824 (= tt js2-BITNOT)
9825 (= tt js2-TYPEOF))
9826 (js2-get-token)
9827 (js2-make-unary tt 'js2-parse-unary-expr))
9828 ((= tt js2-ADD)
9829 (js2-get-token)
9830 ;; Convert to special POS token in decompiler and parse tree
9831 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9832 ((= tt js2-SUB)
9833 (js2-get-token)
9834 ;; Convert to special NEG token in decompiler and parse tree
9835 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9836 ((or (= tt js2-INC)
9837 (= tt js2-DEC))
9838 (js2-get-token)
9839 (prog1
9840 (setq beg (js2-current-token-beg)
9841 end (js2-current-token-end)
9842 expr (js2-make-unary tt 'js2-parse-member-expr t))
9843 (js2-check-bad-inc-dec tt beg end expr)))
9844 ((= tt js2-DELPROP)
9845 (js2-get-token)
9846 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9847 ((= tt js2-ERROR)
9848 (js2-get-token)
9849 (make-js2-error-node)) ; try to continue
9850 ((and (= tt js2-LT)
9851 js2-compiler-xml-available)
9852 ;; XML stream encountered in expression.
9853 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9854 (t
9855 (setq pn (js2-parse-member-expr t)
9856 ;; Don't look across a newline boundary for a postfix incop.
9857 tt (js2-peek-token-or-eol))
9858 (when (or (= tt js2-INC) (= tt js2-DEC))
9859 (js2-get-token)
9860 (setf expr pn
9861 pn (js2-make-unary tt expr))
9862 (js2-node-set-prop pn 'postfix t)
9863 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9864 pn))))
9865
9866 (defun js2-parse-xml-initializer ()
9867 "Parse an E4X XML initializer.
9868 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9869 Then I'll postprocess the result, depending on whether we're in IDE
9870 mode or codegen mode, and generate the appropriate rewritten AST.
9871 IDE mode uses a rich AST that models the XML structure. Codegen mode
9872 just concatenates everything and makes a new XML or XMLList out of it."
9873 (let ((tt (js2-get-first-xml-token))
9874 pn-xml pn expr kids expr-pos
9875 (continue t)
9876 (first-token t))
9877 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9878 (js2-report-error "msg.syntax"))
9879 (setq pn-xml (make-js2-xml-node))
9880 (while continue
9881 (if first-token
9882 (setq first-token nil)
9883 (setq tt (js2-get-next-xml-token)))
9884 (cond
9885 ;; js2-XML means we found a {expr} in the XML stream.
9886 ;; The token string is the XML up to the left-curly.
9887 ((= tt js2-XML)
9888 (push (make-js2-string-node :pos (js2-current-token-beg)
9889 :len (- js2-ts-cursor (js2-current-token-beg)))
9890 kids)
9891 (js2-must-match js2-LC "msg.syntax")
9892 (setq expr-pos js2-ts-cursor
9893 expr (if (eq (js2-peek-token) js2-RC)
9894 (make-js2-empty-expr-node :pos expr-pos)
9895 (js2-parse-expr)))
9896 (js2-must-match js2-RC "msg.syntax")
9897 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9898 :len (js2-node-len expr)
9899 :expr expr))
9900 (js2-node-add-children pn expr)
9901 (push pn kids))
9902 ;; a js2-XMLEND token means we hit the final close-tag.
9903 ((= tt js2-XMLEND)
9904 (push (make-js2-string-node :pos (js2-current-token-beg)
9905 :len (- js2-ts-cursor (js2-current-token-beg)))
9906 kids)
9907 (dolist (kid (nreverse kids))
9908 (js2-block-node-push pn-xml kid))
9909 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9910 (js2-node-pos pn-xml))
9911 continue nil))
9912 (t
9913 (js2-report-error "msg.syntax")
9914 (setq continue nil))))
9915 pn-xml))
9916
9917
9918 (defun js2-parse-argument-list ()
9919 "Parse an argument list and return it as a Lisp list of nodes.
9920 Returns the list in reverse order. Consumes the right-paren token."
9921 (let (result)
9922 (unless (js2-match-token js2-RP)
9923 (cl-loop do
9924 (let ((tt (js2-get-token)))
9925 (if (= tt js2-YIELD)
9926 (js2-report-error "msg.yield.parenthesized"))
9927 (if (and (= tt js2-TRIPLEDOT)
9928 (>= js2-language-version 200))
9929 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9930 (js2-unget-token)
9931 (push (js2-parse-assign-expr) result)))
9932 while
9933 (js2-match-token js2-COMMA))
9934 (js2-must-match js2-RP "msg.no.paren.arg")
9935 result)))
9936
9937 (defun js2-parse-member-expr (&optional allow-call-syntax)
9938 (let ((tt (js2-current-token-type))
9939 pn pos target args beg end init)
9940 (if (/= tt js2-NEW)
9941 (setq pn (js2-parse-primary-expr))
9942 ;; parse a 'new' expression
9943 (js2-get-token)
9944 (setq pos (js2-current-token-beg)
9945 beg pos
9946 target (js2-parse-member-expr)
9947 end (js2-node-end target)
9948 pn (make-js2-new-node :pos pos
9949 :target target
9950 :len (- end pos)))
9951 (js2-highlight-function-call (js2-current-token))
9952 (js2-node-add-children pn target)
9953 (when (js2-match-token js2-LP)
9954 ;; Add the arguments to pn, if any are supplied.
9955 (setf beg pos ; start of "new" keyword
9956 pos (js2-current-token-beg)
9957 args (nreverse (js2-parse-argument-list))
9958 (js2-new-node-args pn) args
9959 end (js2-current-token-end)
9960 (js2-new-node-lp pn) (- pos beg)
9961 (js2-new-node-rp pn) (- end 1 beg))
9962 (apply #'js2-node-add-children pn args))
9963 (when (and js2-allow-rhino-new-expr-initializer
9964 (js2-match-token js2-LC))
9965 (setf init (js2-parse-object-literal)
9966 end (js2-node-end init)
9967 (js2-new-node-initializer pn) init)
9968 (js2-node-add-children pn init))
9969 (setf (js2-node-len pn) (- end beg))) ; end outer if
9970 (js2-parse-member-expr-tail allow-call-syntax pn)))
9971
9972 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9973 "Parse a chain of property/array accesses or function calls.
9974 Includes parsing for E4X operators like `..' and `.@'.
9975 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9976 Returns an expression tree that includes PN, the parent node."
9977 (let (tt
9978 (continue t))
9979 (while continue
9980 (setq tt (js2-get-token))
9981 (cond
9982 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9983 (setq pn (js2-parse-property-access tt pn)))
9984 ((= tt js2-DOTQUERY)
9985 (setq pn (js2-parse-dot-query pn)))
9986 ((= tt js2-LB)
9987 (setq pn (js2-parse-element-get pn)))
9988 ((= tt js2-LP)
9989 (js2-unget-token)
9990 (if allow-call-syntax
9991 (setq pn (js2-parse-function-call pn))
9992 (setq continue nil)))
9993 ((= tt js2-TEMPLATE_HEAD)
9994 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9995 ((= tt js2-NO_SUBS_TEMPLATE)
9996 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9997 (t
9998 (js2-unget-token)
9999 (setq continue nil)))
10000 (if (>= js2-highlight-level 2)
10001 (js2-parse-highlight-member-expr-node pn)))
10002 pn))
10003
10004 (defun js2-parse-tagged-template (tag-node tpl-node)
10005 "Parse tagged template expression."
10006 (let* ((beg (js2-node-pos tag-node))
10007 (pn (make-js2-tagged-template-node :beg beg
10008 :len (- (js2-current-token-end) beg)
10009 :tag tag-node
10010 :template tpl-node)))
10011 (js2-node-add-children pn tag-node tpl-node)
10012 pn))
10013
10014 (defun js2-parse-dot-query (pn)
10015 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10016 Last token parsed must be `js2-DOTQUERY'."
10017 (let ((pos (js2-node-pos pn))
10018 op-pos expr end)
10019 (js2-must-have-xml)
10020 (js2-set-requires-activation)
10021 (setq op-pos (js2-current-token-beg)
10022 expr (js2-parse-expr)
10023 end (js2-node-end expr)
10024 pn (make-js2-xml-dot-query-node :left pn
10025 :pos pos
10026 :op-pos op-pos
10027 :right expr))
10028 (js2-node-add-children pn
10029 (js2-xml-dot-query-node-left pn)
10030 (js2-xml-dot-query-node-right pn))
10031 (if (js2-must-match js2-RP "msg.no.paren")
10032 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10033 end (js2-current-token-end)))
10034 (setf (js2-node-len pn) (- end pos))
10035 pn))
10036
10037 (defun js2-parse-element-get (pn)
10038 "Parse an element-get expression, e.g. foo[bar].
10039 Last token parsed must be `js2-RB'."
10040 (let ((lb (js2-current-token-beg))
10041 (pos (js2-node-pos pn))
10042 rb expr)
10043 (setq expr (js2-parse-expr))
10044 (if (js2-must-match js2-RB "msg.no.bracket.index")
10045 (setq rb (js2-current-token-beg)))
10046 (setq pn (make-js2-elem-get-node :target pn
10047 :pos pos
10048 :element expr
10049 :lb (js2-relpos lb pos)
10050 :rb (js2-relpos rb pos)
10051 :len (- (js2-current-token-end) pos)))
10052 (js2-node-add-children pn
10053 (js2-elem-get-node-target pn)
10054 (js2-elem-get-node-element pn))
10055 pn))
10056
10057 (defun js2-highlight-function-call (token)
10058 (when (eq (js2-token-type token) js2-NAME)
10059 (js2-record-face 'js2-function-call token)))
10060
10061 (defun js2-parse-function-call (pn)
10062 (js2-highlight-function-call (js2-current-token))
10063 (js2-get-token)
10064 (let (args
10065 (pos (js2-node-pos pn)))
10066 (setq pn (make-js2-call-node :pos pos
10067 :target pn
10068 :lp (- (js2-current-token-beg) pos)))
10069 (js2-node-add-children pn (js2-call-node-target pn))
10070 ;; Add the arguments to pn, if any are supplied.
10071 (setf args (nreverse (js2-parse-argument-list))
10072 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10073 (js2-call-node-args pn) args)
10074 (apply #'js2-node-add-children pn args)
10075 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10076 pn))
10077
10078 (defun js2-parse-property-access (tt pn)
10079 "Parse a property access, XML descendants access, or XML attr access."
10080 (let ((member-type-flags 0)
10081 (dot-pos (js2-current-token-beg))
10082 (dot-len (if (= tt js2-DOTDOT) 2 1))
10083 name
10084 ref ; right side of . or .. operator
10085 result)
10086 (when (= tt js2-DOTDOT)
10087 (js2-must-have-xml)
10088 (setq member-type-flags js2-descendants-flag))
10089 (if (not js2-compiler-xml-available)
10090 (progn
10091 (js2-must-match-prop-name "msg.no.name.after.dot")
10092 (setq name (js2-create-name-node t js2-GETPROP)
10093 result (make-js2-prop-get-node :left pn
10094 :pos (js2-current-token-beg)
10095 :right name
10096 :len (js2-current-token-len)))
10097 (js2-node-add-children result pn name)
10098 result)
10099 ;; otherwise look for XML operators
10100 (setf result (if (= tt js2-DOT)
10101 (make-js2-prop-get-node)
10102 (make-js2-infix-node :type js2-DOTDOT))
10103 (js2-node-pos result) (js2-node-pos pn)
10104 (js2-infix-node-op-pos result) dot-pos
10105 (js2-infix-node-left result) pn ; do this after setting position
10106 tt (js2-get-prop-name-token))
10107 (cond
10108 ;; handles: name, ns::name, ns::*, ns::[expr]
10109 ((= tt js2-NAME)
10110 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10111 ;; handles: *, *::name, *::*, *::[expr]
10112 ((= tt js2-MUL)
10113 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10114 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10115 ((= tt js2-XMLATTR)
10116 (setq result (js2-parse-attribute-access)))
10117 (t
10118 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10119 (if ref
10120 (setf (js2-node-len result) (- (js2-node-end ref)
10121 (js2-node-pos result))
10122 (js2-infix-node-right result) ref))
10123 (if (js2-infix-node-p result)
10124 (js2-node-add-children result
10125 (js2-infix-node-left result)
10126 (js2-infix-node-right result)))
10127 result)))
10128
10129 (defun js2-parse-attribute-access ()
10130 "Parse an E4X XML attribute expression.
10131 This includes expressions of the forms:
10132
10133 @attr @ns::attr @ns::*
10134 @* @*::attr @*::*
10135 @[expr] @*::[expr] @ns::[expr]
10136
10137 Called if we peeked an '@' token."
10138 (let ((tt (js2-get-prop-name-token))
10139 (at-pos (js2-current-token-beg)))
10140 (cond
10141 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10142 ((= tt js2-NAME)
10143 (js2-parse-property-name at-pos nil 0))
10144 ;; handles: @*, @*::name, @*::*, @*::[expr]
10145 ((= tt js2-MUL)
10146 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10147 ;; handles @[expr]
10148 ((= tt js2-LB)
10149 (js2-parse-xml-elem-ref at-pos))
10150 (t
10151 (js2-report-error "msg.no.name.after.xmlAttr")
10152 ;; Avoid cascaded errors that happen if we make an error node here.
10153 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10154
10155 (defun js2-parse-property-name (at-pos s member-type-flags)
10156 "Check if :: follows name in which case it becomes qualified name.
10157
10158 AT-POS is a natural number if we just read an '@' token, else nil.
10159 S is the name or string that was matched: an identifier, 'throw' or '*'.
10160 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10161
10162 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10163 operator, or the name is followed by ::. For a plain name, returns a
10164 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10165 (let ((pos (or at-pos (js2-current-token-beg)))
10166 colon-pos
10167 (name (js2-create-name-node t (js2-current-token-type) s))
10168 ns tt pn)
10169 (catch 'return
10170 (when (js2-match-token js2-COLONCOLON)
10171 (setq ns name
10172 colon-pos (js2-current-token-beg)
10173 tt (js2-get-prop-name-token))
10174 (cond
10175 ;; handles name::name
10176 ((= tt js2-NAME)
10177 (setq name (js2-create-name-node)))
10178 ;; handles name::*
10179 ((= tt js2-MUL)
10180 (setq name (js2-create-name-node nil nil "*")))
10181 ;; handles name::[expr]
10182 ((= tt js2-LB)
10183 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10184 (t
10185 (js2-report-error "msg.no.name.after.coloncolon"))))
10186 (if (and (null ns) (zerop member-type-flags))
10187 name
10188 (prog1
10189 (setq pn
10190 (make-js2-xml-prop-ref-node :pos pos
10191 :len (- (js2-node-end name) pos)
10192 :at-pos at-pos
10193 :colon-pos colon-pos
10194 :propname name))
10195 (js2-node-add-children pn name))))))
10196
10197 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10198 "Parse the [expr] portion of an xml element reference.
10199 For instance, @[expr], @*::[expr], or ns::[expr]."
10200 (let* ((lb (js2-current-token-beg))
10201 (pos (or at-pos lb))
10202 rb
10203 (expr (js2-parse-expr))
10204 (end (js2-node-end expr))
10205 pn)
10206 (if (js2-must-match js2-RB "msg.no.bracket.index")
10207 (setq rb (js2-current-token-beg)
10208 end (js2-current-token-end)))
10209 (prog1
10210 (setq pn
10211 (make-js2-xml-elem-ref-node :pos pos
10212 :len (- end pos)
10213 :namespace namespace
10214 :colon-pos colon-pos
10215 :at-pos at-pos
10216 :expr expr
10217 :lb (js2-relpos lb pos)
10218 :rb (js2-relpos rb pos)))
10219 (js2-node-add-children pn namespace expr))))
10220
10221 (defun js2-parse-destruct-primary-expr ()
10222 (let ((js2-is-in-destructuring t))
10223 (js2-parse-primary-expr)))
10224
10225 (defun js2-parse-primary-expr ()
10226 "Parse a literal (leaf) expression of some sort.
10227 Includes complex literals such as functions, object-literals,
10228 array-literals, array comprehensions and regular expressions."
10229 (let (tt node)
10230 (setq tt (js2-current-token-type))
10231 (cond
10232 ((= tt js2-CLASS)
10233 (js2-parse-class-expr))
10234 ((= tt js2-FUNCTION)
10235 (js2-parse-function-expr))
10236 ((= tt js2-LB)
10237 (js2-parse-array-comp-or-literal))
10238 ((= tt js2-LC)
10239 (js2-parse-object-literal))
10240 ((= tt js2-LET)
10241 (js2-parse-let (js2-current-token-beg)))
10242 ((= tt js2-LP)
10243 (js2-parse-paren-expr-or-generator-comp))
10244 ((= tt js2-XMLATTR)
10245 (js2-must-have-xml)
10246 (js2-parse-attribute-access))
10247 ((= tt js2-NAME)
10248 (js2-parse-name tt))
10249 ((= tt js2-NUMBER)
10250 (setq node (make-js2-number-node))
10251 (when (and js2-in-use-strict-directive
10252 (= (js2-number-node-num-base node) 8))
10253 (js2-report-error "msg.no.octal.strict"))
10254 node)
10255 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10256 (make-js2-string-node :type tt))
10257 ((= tt js2-TEMPLATE_HEAD)
10258 (js2-parse-template-literal))
10259 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10260 ;; Got / or /= which in this context means a regexp literal
10261 (let ((px-pos (js2-current-token-beg))
10262 (flags (js2-read-regexp tt))
10263 (end (js2-current-token-end)))
10264 (prog1
10265 (make-js2-regexp-node :pos px-pos
10266 :len (- end px-pos)
10267 :value (js2-current-token-string)
10268 :flags flags)
10269 (js2-set-face px-pos end 'font-lock-string-face 'record)
10270 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10271 ((or (= tt js2-NULL)
10272 (= tt js2-THIS)
10273 (= tt js2-SUPER)
10274 (= tt js2-FALSE)
10275 (= tt js2-TRUE))
10276 (make-js2-keyword-node :type tt))
10277 ((= tt js2-TRIPLEDOT)
10278 ;; Likewise, only valid in an arrow function with a rest param.
10279 (if (and (js2-match-token js2-NAME)
10280 (js2-match-token js2-RP)
10281 (eq (js2-peek-token) js2-ARROW))
10282 (progn
10283 (js2-unget-token) ; Put back the right paren.
10284 ;; See the previous case.
10285 (make-js2-keyword-node :type js2-NULL))
10286 (js2-report-error "msg.syntax")
10287 (make-js2-error-node)))
10288 ((= tt js2-RESERVED)
10289 (js2-report-error "msg.reserved.id")
10290 (make-js2-name-node))
10291 ((= tt js2-ERROR)
10292 ;; the scanner or one of its subroutines reported the error.
10293 (make-js2-error-node))
10294 ((= tt js2-EOF)
10295 (let* ((px-pos (point-at-bol))
10296 (len (- js2-ts-cursor px-pos)))
10297 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10298 (make-js2-error-node :pos (1- js2-ts-cursor)))
10299 (t
10300 (js2-report-error "msg.syntax")
10301 (make-js2-error-node)))))
10302
10303 (defun js2-parse-template-literal ()
10304 (let ((beg (js2-current-token-beg))
10305 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10306 (tt js2-TEMPLATE_HEAD))
10307 (while (eq tt js2-TEMPLATE_HEAD)
10308 (push (js2-parse-expr) kids)
10309 (js2-must-match js2-RC "msg.syntax")
10310 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10311 (push (make-js2-string-node :type tt) kids))
10312 (setq kids (nreverse kids))
10313 (let ((tpl (make-js2-template-node :beg beg
10314 :len (- (js2-current-token-end) beg)
10315 :kids kids)))
10316 (apply #'js2-node-add-children tpl kids)
10317 tpl)))
10318
10319 (defun js2-parse-name (_tt)
10320 (let ((name (js2-current-token-string))
10321 node)
10322 (setq node (if js2-compiler-xml-available
10323 (js2-parse-property-name nil name 0)
10324 (js2-create-name-node 'check-activation nil name)))
10325 (if js2-highlight-external-variables
10326 (js2-record-name-node node))
10327 node))
10328
10329 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10330 (js2-add-strict-warning
10331 msg nil
10332 ;; back up from comma to beginning of line or array/objlit
10333 (max (if elems
10334 (js2-node-pos (car elems))
10335 pos)
10336 (save-excursion
10337 (goto-char comma-pos)
10338 (back-to-indentation)
10339 (point)))
10340 comma-pos))
10341
10342 (defun js2-parse-array-comp-or-literal ()
10343 (let ((pos (js2-current-token-beg)))
10344 (if (and (>= js2-language-version 200)
10345 (js2-match-token js2-FOR))
10346 (js2-parse-array-comp pos)
10347 (js2-parse-array-literal pos))))
10348
10349 (defun js2-parse-array-literal (pos)
10350 (let ((after-lb-or-comma t)
10351 after-comma tt elems pn
10352 (continue t))
10353 (unless js2-is-in-destructuring
10354 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10355 (while continue
10356 (setq tt (js2-get-token))
10357 (cond
10358 ;; comma
10359 ((= tt js2-COMMA)
10360 (setq after-comma (js2-current-token-end))
10361 (if (not after-lb-or-comma)
10362 (setq after-lb-or-comma t)
10363 (push nil elems)))
10364 ;; end of array
10365 ((or (= tt js2-RB)
10366 (= tt js2-EOF)) ; prevent infinite loop
10367 (if (= tt js2-EOF)
10368 (js2-report-error "msg.no.bracket.arg" nil pos))
10369 (when (and after-comma (< js2-language-version 170))
10370 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10371 pos (remove nil elems) after-comma))
10372 (setq continue nil
10373 pn (make-js2-array-node :pos pos
10374 :len (- js2-ts-cursor pos)
10375 :elems (nreverse elems)))
10376 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10377 ;; destructuring binding
10378 (js2-is-in-destructuring
10379 (push (cond
10380 ((and (= tt js2-NAME)
10381 (= js2-ASSIGN (js2-peek-token)))
10382 ;; a=defaultValue
10383 (js2-parse-initialized-binding (js2-parse-name js2-NAME)))
10384 ((or (= tt js2-LC)
10385 (= tt js2-LB)
10386 (= tt js2-NAME))
10387 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10388 (js2-parse-destruct-primary-expr))
10389 ;; invalid pattern
10390 (t
10391 (js2-report-error "msg.bad.var")
10392 (make-js2-error-node)))
10393 elems)
10394 (setq after-lb-or-comma nil
10395 after-comma nil))
10396 ;; array comp
10397 ((and (>= js2-language-version 170)
10398 (= tt js2-FOR) ; check for array comprehension
10399 (not after-lb-or-comma) ; "for" can't follow a comma
10400 elems ; must have at least 1 element
10401 (not (cdr elems))) ; but no 2nd element
10402 (js2-unget-token)
10403 (setf continue nil
10404 pn (js2-parse-legacy-array-comp (car elems) pos)))
10405 ;; another element
10406 (t
10407 (unless after-lb-or-comma
10408 (js2-report-error "msg.no.bracket.arg"))
10409 (if (and (= tt js2-TRIPLEDOT)
10410 (>= js2-language-version 200))
10411 ;; spread operator
10412 (push (js2-make-unary tt 'js2-parse-assign-expr)
10413 elems)
10414 (js2-unget-token)
10415 (push (js2-parse-assign-expr) elems))
10416 (setq after-lb-or-comma nil
10417 after-comma nil))))
10418 (unless js2-is-in-destructuring
10419 (js2-pop-scope))
10420 pn))
10421
10422 (defun js2-parse-legacy-array-comp (expr pos)
10423 "Parse a legacy array comprehension (JavaScript 1.7).
10424 EXPR is the first expression after the opening left-bracket.
10425 POS is the beginning of the LB token preceding EXPR.
10426 We should have just parsed the 'for' keyword before calling this function."
10427 (let ((current-scope js2-current-scope)
10428 loops first filter result)
10429 (unwind-protect
10430 (progn
10431 (while (js2-match-token js2-FOR)
10432 (let ((loop (make-js2-comp-loop-node)))
10433 (js2-push-scope loop)
10434 (push loop loops)
10435 (js2-parse-comp-loop loop)))
10436 ;; First loop takes expr scope's parent.
10437 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10438 (js2-scope-parent-scope current-scope))
10439 ;; Set expr scope's parent to the last loop.
10440 (setf (js2-scope-parent-scope current-scope) (car loops))
10441 (if (/= (js2-get-token) js2-IF)
10442 (js2-unget-token)
10443 (setq filter (js2-parse-condition))))
10444 (dotimes (_ (1- (length loops)))
10445 (js2-pop-scope)))
10446 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10447 (setq result (make-js2-comp-node :pos pos
10448 :len (- js2-ts-cursor pos)
10449 :result expr
10450 :loops (nreverse loops)
10451 :filters (and filter (list (car filter)))
10452 :form 'LEGACY_ARRAY))
10453 ;; Set comp loop's parent to the last loop.
10454 ;; TODO: Get rid of the bogus expr scope.
10455 (setf (js2-scope-parent-scope result) first)
10456 (apply #'js2-node-add-children result expr (car filter)
10457 (js2-comp-node-loops result))
10458 result))
10459
10460 (defun js2-parse-array-comp (pos)
10461 "Parse an ES6 array comprehension.
10462 POS is the beginning of the LB token.
10463 We should have just parsed the 'for' keyword before calling this function."
10464 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10465 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10466 pn))
10467
10468 (defun js2-parse-generator-comp (pos)
10469 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10470 (js2-current-script-or-fn
10471 (make-js2-function-node :generator-type 'COMPREHENSION))
10472 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10473 (js2-must-match js2-RP "msg.no.paren" pos)
10474 pn))
10475
10476 (defun js2-parse-comprehension (pos form)
10477 (let (loops filters expr result last)
10478 (unwind-protect
10479 (progn
10480 (js2-unget-token)
10481 (while (js2-match-token js2-FOR)
10482 (let ((loop (make-js2-comp-loop-node)))
10483 (js2-push-scope loop)
10484 (push loop loops)
10485 (js2-parse-comp-loop loop)))
10486 (while (js2-match-token js2-IF)
10487 (push (car (js2-parse-condition)) filters))
10488 (setq expr (js2-parse-assign-expr))
10489 (setq last (car loops)))
10490 (dolist (_ loops)
10491 (js2-pop-scope)))
10492 (setq result (make-js2-comp-node :pos pos
10493 :len (- js2-ts-cursor pos)
10494 :result expr
10495 :loops (nreverse loops)
10496 :filters (nreverse filters)
10497 :form form))
10498 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10499 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10500 (setf (js2-scope-parent-scope result) last)
10501 result))
10502
10503 (defun js2-parse-comp-loop (pn &optional only-of-p)
10504 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10505 The current token should be the initial FOR.
10506 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10507 (let ((pos (js2-comp-loop-node-pos pn))
10508 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10509 (when (and (not only-of-p) (js2-match-token js2-NAME))
10510 (if (string= (js2-current-token-string) "each")
10511 (progn
10512 (setq foreach-p t
10513 each-pos (- (js2-current-token-beg) pos)) ; relative
10514 (js2-record-face 'font-lock-keyword-face))
10515 (js2-report-error "msg.no.paren.for")))
10516 (if (js2-must-match js2-LP "msg.no.paren.for")
10517 (setq lp (- (js2-current-token-beg) pos)))
10518 (setq tt (js2-peek-token))
10519 (cond
10520 ((or (= tt js2-LB)
10521 (= tt js2-LC))
10522 (js2-get-token)
10523 (setq iter (js2-parse-destruct-primary-expr))
10524 (js2-define-destruct-symbols iter js2-LET
10525 'font-lock-variable-name-face t))
10526 ((js2-match-token js2-NAME)
10527 (setq iter (js2-create-name-node)))
10528 (t
10529 (js2-report-error "msg.bad.var")))
10530 ;; Define as a let since we want the scope of the variable to
10531 ;; be restricted to the array comprehension
10532 (if (js2-name-node-p iter)
10533 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10534 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10535 (and (>= js2-language-version 200)
10536 (js2-match-contextual-kwd "of")
10537 (setq forof-p t)))
10538 (setq in-pos (- (js2-current-token-beg) pos))
10539 (js2-report-error "msg.in.after.for.name"))
10540 (setq obj (js2-parse-expr))
10541 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10542 (setq rp (- (js2-current-token-beg) pos)))
10543 (setf (js2-node-pos pn) pos
10544 (js2-node-len pn) (- js2-ts-cursor pos)
10545 (js2-comp-loop-node-iterator pn) iter
10546 (js2-comp-loop-node-object pn) obj
10547 (js2-comp-loop-node-in-pos pn) in-pos
10548 (js2-comp-loop-node-each-pos pn) each-pos
10549 (js2-comp-loop-node-foreach-p pn) foreach-p
10550 (js2-comp-loop-node-forof-p pn) forof-p
10551 (js2-comp-loop-node-lp pn) lp
10552 (js2-comp-loop-node-rp pn) rp)
10553 (js2-node-add-children pn iter obj)
10554 pn))
10555
10556 (defun js2-parse-class-stmt ()
10557 (let ((pos (js2-current-token-beg))
10558 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10559 (name (js2-create-name-node t)))
10560 (js2-set-face (js2-node-pos name) (js2-node-end name)
10561 'font-lock-function-name-face 'record)
10562 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10563 (js2-define-symbol js2-FUNCTION
10564 (js2-name-node-name name)
10565 node)
10566 node)))
10567
10568 (defun js2-parse-class-expr ()
10569 (let ((pos (js2-current-token-beg))
10570 name)
10571 (when (js2-match-token js2-NAME)
10572 (setq name (js2-create-name-node t)))
10573 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10574
10575 (defun js2-parse-class (pos form name)
10576 ;; class X [extends ...] {
10577 (let (pn elems extends)
10578 (if (js2-match-token js2-EXTENDS)
10579 (if (= (js2-peek-token) js2-LC)
10580 (js2-report-error "msg.missing.extends")
10581 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10582 (setq extends (js2-parse-assign-expr))
10583 (if (not extends)
10584 (js2-report-error "msg.bad.extends"))))
10585 (js2-must-match js2-LC "msg.no.brace.class")
10586 (setq elems (js2-parse-object-literal-elems t)
10587 pn (make-js2-class-node :pos pos
10588 :len (- js2-ts-cursor pos)
10589 :form form
10590 :name name
10591 :extends extends
10592 :elems elems))
10593 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10594 pn))
10595
10596 (defun js2-parse-object-literal ()
10597 (let* ((pos (js2-current-token-beg))
10598 (elems (js2-parse-object-literal-elems))
10599 (result (make-js2-object-node :pos pos
10600 :len (- js2-ts-cursor pos)
10601 :elems elems)))
10602 (apply #'js2-node-add-children result (js2-object-node-elems result))
10603 result))
10604
10605 (defun js2-property-key-string (property-node)
10606 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10607 `js2-method-node') as a string, or nil if it can't be
10608 represented as a string (e.g., the key is computed by an
10609 expression)."
10610 (let ((key (js2-infix-node-left property-node)))
10611 (when (js2-computed-prop-name-node-p key)
10612 (setq key (js2-computed-prop-name-node-expr key)))
10613 (cond
10614 ((js2-name-node-p key)
10615 (js2-name-node-name key))
10616 ((js2-string-node-p key)
10617 (js2-string-node-value key))
10618 ((js2-number-node-p key)
10619 (js2-number-node-value key)))))
10620
10621 (defun js2-parse-object-literal-elems (&optional class-p)
10622 (let ((pos (js2-current-token-beg))
10623 (static nil)
10624 (continue t)
10625 tt elems elem
10626 elem-key-string previous-elem-key-string
10627 after-comma previous-token)
10628 (while continue
10629 (setq tt (js2-get-prop-name-token)
10630 static nil
10631 elem nil
10632 previous-token nil)
10633 ;; Handle 'static' keyword only if we're in a class
10634 (when (and class-p (= js2-NAME tt)
10635 (string= "static" (js2-current-token-string)))
10636 (js2-record-face 'font-lock-keyword-face)
10637 (setq static t
10638 tt (js2-get-prop-name-token)))
10639 ;; Handle generator * before the property name for in-line functions
10640 (when (and (>= js2-language-version 200)
10641 (= js2-MUL tt))
10642 (setq previous-token (js2-current-token)
10643 tt (js2-get-prop-name-token)))
10644 ;; Handle 'get' or 'set' keywords
10645 (let ((prop (js2-current-token-string)))
10646 (when (and (>= js2-language-version 200)
10647 (= js2-NAME tt)
10648 (or (string= prop "get")
10649 (string= prop "set"))
10650 (member (js2-peek-token)
10651 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10652 (setq previous-token (js2-current-token)
10653 tt (js2-get-prop-name-token))))
10654 (cond
10655 ;; Found a property (of any sort)
10656 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10657 (setq after-comma nil
10658 elem (js2-parse-named-prop tt pos previous-token))
10659 (if (and (null elem)
10660 (not js2-recover-from-parse-errors))
10661 (setq continue nil)))
10662 ;; Break out of loop, and handle trailing commas.
10663 ((or (= tt js2-RC)
10664 (= tt js2-EOF))
10665 (js2-unget-token)
10666 (setq continue nil)
10667 (if after-comma
10668 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10669 pos elems after-comma)))
10670 ;; Skip semicolons in a class body
10671 ((and class-p
10672 (= tt js2-SEMI))
10673 nil)
10674 (t
10675 (js2-report-error "msg.bad.prop")
10676 (unless js2-recover-from-parse-errors
10677 (setq continue nil)))) ; end switch
10678 ;; Handle static for classes' codegen.
10679 (if static
10680 (if elem (js2-node-set-prop elem 'STATIC t)
10681 (js2-report-error "msg.unexpected.static")))
10682 ;; Handle commas, depending on class-p.
10683 (let ((tok (js2-get-prop-name-token)))
10684 (if (eq tok js2-COMMA)
10685 (if class-p
10686 (js2-report-error "msg.class.unexpected.comma")
10687 (setq after-comma (js2-current-token-end)))
10688 (js2-unget-token)
10689 (unless class-p (setq continue nil))))
10690 (when elem
10691 (when (and js2-in-use-strict-directive
10692 (setq elem-key-string (js2-property-key-string elem))
10693 (cl-some
10694 (lambda (previous-elem)
10695 (and (setq previous-elem-key-string
10696 (js2-property-key-string previous-elem))
10697 ;; Check if the property is a duplicate.
10698 (string= previous-elem-key-string elem-key-string)
10699 ;; But make an exception for getter / setter pairs.
10700 (not (and (js2-method-node-p elem)
10701 (js2-method-node-p previous-elem)
10702 (/= (js2-method-node-type elem)
10703 (js2-method-node-type previous-elem))))))
10704 elems))
10705 (js2-report-error "msg.dup.obj.lit.prop.strict"
10706 elem-key-string
10707 (js2-node-abs-pos (js2-infix-node-left elem))
10708 (js2-node-len (js2-infix-node-left elem))))
10709 ;; Append any parsed element.
10710 (push elem elems))) ; end loop
10711 (js2-must-match js2-RC "msg.no.brace.prop")
10712 (nreverse elems)))
10713
10714 (defun js2-parse-named-prop (tt pos previous-token)
10715 "Parse a name, string, or getter/setter object property.
10716 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10717 (let ((key (js2-parse-prop-name tt))
10718 (prop (and previous-token (js2-token-string previous-token)))
10719 (property-type (when previous-token
10720 (if (= (js2-token-type previous-token) js2-MUL)
10721 "*"
10722 (js2-token-string previous-token)))))
10723 (when (or (string= prop "get")
10724 (string= prop "set"))
10725 (js2-set-face (js2-token-beg previous-token)
10726 (js2-token-end previous-token)
10727 'font-lock-keyword-face 'record)) ; get/set
10728 (cond
10729 ;; method definition: {f() {...}}
10730 ((and (= (js2-peek-token) js2-LP)
10731 (>= js2-language-version 200))
10732 (when (js2-name-node-p key) ; highlight function name properties
10733 (js2-record-face 'font-lock-function-name-face))
10734 (js2-parse-method-prop pos key property-type))
10735 ;; binding element with initializer
10736 ((and (= (js2-peek-token) js2-ASSIGN)
10737 (>= js2-language-version 200))
10738 (if (not js2-is-in-destructuring)
10739 (js2-report-error "msg.init.no.destruct"))
10740 (js2-parse-initialized-binding key))
10741 ;; regular prop
10742 (t
10743 (let ((beg (js2-current-token-beg))
10744 (end (js2-current-token-end))
10745 (expr (js2-parse-plain-property key)))
10746 (when (and (= tt js2-NAME)
10747 (not js2-is-in-destructuring)
10748 js2-highlight-external-variables
10749 (js2-node-get-prop expr 'SHORTHAND))
10750 (js2-record-name-node key))
10751 (js2-set-face beg end
10752 (if (js2-function-node-p
10753 (js2-object-prop-node-right expr))
10754 'font-lock-function-name-face
10755 'js2-object-property)
10756 'record)
10757 expr)))))
10758
10759 (defun js2-parse-initialized-binding (name)
10760 "Parse a `SingleNameBinding' with initializer.
10761
10762 `name' is the `BindingIdentifier'."
10763 (when (js2-match-token js2-ASSIGN)
10764 (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
10765
10766 (defun js2-parse-prop-name (tt)
10767 (cond
10768 ;; Literal string keys: {'foo': 'bar'}
10769 ((= tt js2-STRING)
10770 (make-js2-string-node))
10771 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10772 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10773 ((and (= tt js2-LB)
10774 (>= js2-language-version 200))
10775 (make-js2-computed-prop-name-node
10776 :expr (prog1 (js2-parse-assign-expr)
10777 (js2-must-match js2-RB "msg.missing.computed.rb"))))
10778 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10779 ((= tt js2-NUMBER)
10780 (make-js2-number-node))
10781 ;; Unquoted names: {foo: 12}
10782 ((= tt js2-NAME)
10783 (js2-create-name-node))
10784 ;; Anything else is an error
10785 (t (js2-report-error "msg.bad.prop"))))
10786
10787 (defun js2-parse-plain-property (prop)
10788 "Parse a non-getter/setter property in an object literal.
10789 PROP is the node representing the property: a number, name,
10790 string or expression."
10791 (let* ((tt (js2-get-token))
10792 (pos (js2-node-pos prop))
10793 colon expr result)
10794 (cond
10795 ;; Abbreviated property, as in {foo, bar}
10796 ((and (>= js2-language-version 200)
10797 (or (= tt js2-COMMA)
10798 (= tt js2-RC))
10799 (not (js2-number-node-p prop)))
10800 (js2-unget-token)
10801 (setq result (make-js2-object-prop-node
10802 :pos pos
10803 :left prop
10804 :right prop
10805 :op-pos (js2-current-token-len)))
10806 (js2-node-add-children result prop)
10807 (js2-node-set-prop result 'SHORTHAND t)
10808 result)
10809 ;; Normal property
10810 (t
10811 (if (= tt js2-COLON)
10812 (setq colon (- (js2-current-token-beg) pos)
10813 expr (js2-parse-assign-expr))
10814 (js2-report-error "msg.no.colon.prop")
10815 (setq expr (make-js2-error-node)))
10816 (setq result (make-js2-object-prop-node
10817 :pos pos
10818 ;; don't include last consumed token in length
10819 :len (- (+ (js2-node-pos expr)
10820 (js2-node-len expr))
10821 pos)
10822 :left prop
10823 :right expr
10824 :op-pos colon))
10825 (js2-node-add-children result prop expr)
10826 result))))
10827
10828 (defun js2-parse-method-prop (pos prop type-string)
10829 "Parse method property in an object literal or a class body.
10830 JavaScript syntax is:
10831
10832 { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...} }
10833
10834 and expression closure style is also supported
10835
10836 { get foo() x, set foo(x) _x = x }
10837
10838 POS is the start position of the `get' or `set' keyword.
10839 PROP is the `js2-name-node' representing the property name.
10840 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10841 (let ((type (cond
10842 ((string= "get" type-string) js2-GET)
10843 ((string= "set" type-string) js2-SET)
10844 (t js2-FUNCTION)))
10845 result end
10846 (fn (js2-parse-function-expr)))
10847 ;; it has to be an anonymous function, as we already parsed the name
10848 (if (/= (js2-node-type fn) js2-FUNCTION)
10849 (js2-report-error "msg.bad.prop")
10850 (if (cl-plusp (length (js2-function-name fn)))
10851 (js2-report-error "msg.bad.prop")))
10852 (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
10853 (when (string= type-string "*")
10854 (setf (js2-function-node-generator-type fn) 'STAR))
10855 (setq end (js2-node-end fn)
10856 result (make-js2-method-node :type type
10857 :pos pos
10858 :len (- end pos)
10859 :left prop
10860 :right fn))
10861 (js2-node-add-children result prop fn)
10862 result))
10863
10864 (defun js2-create-name-node (&optional check-activation-p token string)
10865 "Create a name node using the current token and, optionally, STRING.
10866 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10867 (let* ((beg (js2-current-token-beg))
10868 (tt (js2-current-token-type))
10869 (s (or string
10870 (if (= js2-NAME tt)
10871 (js2-current-token-string)
10872 (js2-tt-name tt))))
10873 name)
10874 (setq name (make-js2-name-node :pos beg
10875 :name s
10876 :len (length s)))
10877 (if check-activation-p
10878 (js2-check-activation-name s (or token js2-NAME)))
10879 name))
10880
10881 ;;; Use AST to extract semantic information
10882
10883 (defun js2-get-element-index-from-array-node (elem array-node &optional hardcoded-array-index)
10884 "Get index of ELEM from ARRAY-NODE or 0 and return it as string."
10885 (let ((idx 0) elems (rlt hardcoded-array-index))
10886 (setq elems (js2-array-node-elems array-node))
10887 (if (and elem (not hardcoded-array-index))
10888 (setq rlt (catch 'nth-elt
10889 (dolist (x elems)
10890 ;; We know the ELEM does belong to ARRAY-NODE,
10891 (if (eq elem x) (throw 'nth-elt idx))
10892 (setq idx (1+ idx)))
10893 0)))
10894 (format "[%s]" rlt)))
10895
10896 (defun js2-print-json-path (&optional hardcoded-array-index)
10897 "Print the path to the JSON value under point, and save it in the kill ring.
10898 If HARDCODED-ARRAY-INDEX provided, array index in JSON path is replaced with it."
10899 (interactive "P")
10900 (let (previous-node current-node
10901 key-name
10902 rlt)
10903
10904 ;; The `js2-node-at-point' starts scanning from AST root node.
10905 ;; So there is no way to optimize it.
10906 (setq current-node (js2-node-at-point))
10907
10908 (while (not (js2-ast-root-p current-node))
10909 (cond
10910 ;; JSON property node
10911 ((js2-object-prop-node-p current-node)
10912 (setq key-name (js2-prop-node-name (js2-object-prop-node-left current-node)))
10913 (if rlt (setq rlt (concat "." key-name rlt))
10914 (setq rlt (concat "." key-name))))
10915
10916 ;; Array node
10917 ((or (js2-array-node-p current-node))
10918 (setq rlt (concat (js2-get-element-index-from-array-node previous-node
10919 current-node
10920 hardcoded-array-index)
10921 rlt)))
10922
10923 ;; Other nodes are ignored
10924 (t))
10925
10926 ;; current node is archived
10927 (setq previous-node current-node)
10928 ;; Get parent node and continue the loop
10929 (setq current-node (js2-node-parent current-node)))
10930
10931 (cond
10932 (rlt
10933 ;; Clean the final result
10934 (setq rlt (replace-regexp-in-string "^\\." "" rlt))
10935 (kill-new rlt)
10936 (message "%s => kill-ring" rlt))
10937 (t
10938 (message "No JSON path found!")))
10939
10940 rlt))
10941
10942 ;;; Indentation support (bouncing)
10943
10944 ;; In recent-enough Emacs, we reuse the indentation code from
10945 ;; `js-mode'. To continue support for the older versions, some code
10946 ;; that was here previously was moved to `js2-old-indent.el'.
10947
10948 ;; Whichever indenter is used, it's often "wrong", however, and needs
10949 ;; to be overridden. The right long-term solution is probably to
10950 ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
10951 ;; of coding. Even when a parse tree from `js2-parse' is present,
10952 ;; which is not true at the moment the user is typing, computing
10953 ;; indentation is still thousands of lines of code to handle every
10954 ;; possible syntactic edge case.
10955
10956 ;; In the meantime, the compromise solution is that we offer a "bounce
10957 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10958 ;; current line indent among various likely guess points. This approach
10959 ;; is far from perfect, but should at least make it slightly easier to
10960 ;; move the line towards its desired indentation when manually
10961 ;; overriding Karl's heuristic nesting guesser.
10962
10963 (defun js2-backward-sws ()
10964 "Move backward through whitespace and comments."
10965 (interactive)
10966 (while (forward-comment -1)))
10967
10968 (defun js2-forward-sws ()
10969 "Move forward through whitespace and comments."
10970 (interactive)
10971 (while (forward-comment 1)))
10972
10973 (defun js2-arglist-close ()
10974 "Return non-nil if we're on a line beginning with a close-paren/brace."
10975 (save-excursion
10976 (goto-char (point-at-bol))
10977 (js2-forward-sws)
10978 (looking-at "[])}]")))
10979
10980 (defun js2-indent-looks-like-label-p ()
10981 (goto-char (point-at-bol))
10982 (js2-forward-sws)
10983 (looking-at (concat js2-mode-identifier-re ":")))
10984
10985 (defun js2-indent-in-objlit-p (parse-status)
10986 "Return non-nil if this looks like an object-literal entry."
10987 (let ((start (nth 1 parse-status)))
10988 (and
10989 start
10990 (save-excursion
10991 (and (zerop (forward-line -1))
10992 (not (< (point) start)) ; crossed a {} boundary
10993 (js2-indent-looks-like-label-p)))
10994 (save-excursion
10995 (js2-indent-looks-like-label-p)))))
10996
10997 ;; If prev line looks like foobar({ then we're passing an object
10998 ;; literal to a function call, and people pretty much always want to
10999 ;; de-dent back to the previous line, so move the 'basic-offset'
11000 ;; position to the front.
11001 (defun js2-indent-objlit-arg-p (parse-status)
11002 (save-excursion
11003 (back-to-indentation)
11004 (js2-backward-sws)
11005 (and (eq (1- (point)) (nth 1 parse-status))
11006 (eq (char-before) ?{)
11007 (progn
11008 (forward-char -1)
11009 (skip-chars-backward " \t")
11010 (eq (char-before) ?\()))))
11011
11012 (defun js2-indent-case-block-p ()
11013 (save-excursion
11014 (back-to-indentation)
11015 (js2-backward-sws)
11016 (goto-char (point-at-bol))
11017 (skip-chars-forward " \t")
11018 (looking-at "case\\s-.+:")))
11019
11020 (defun js2-bounce-indent (normal-col parse-status &optional backward)
11021 "Cycle among alternate computed indentation positions.
11022 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11023 of the buffer to the current point. NORMAL-COL is the indentation
11024 column computed by the heuristic guesser based on current paren,
11025 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11026 in reverse."
11027 (let ((cur-indent (current-indentation))
11028 (old-buffer-undo-list buffer-undo-list)
11029 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11030 (current-line (save-excursion
11031 (forward-line 0) ; move to bol
11032 (1+ (count-lines (point-min) (point)))))
11033 positions pos main-pos anchor arglist-cont same-indent
11034 basic-offset computed-pos)
11035 ;; temporarily don't record undo info, if user requested this
11036 (when js2-mode-indent-inhibit-undo
11037 (setq buffer-undo-list t))
11038 (unwind-protect
11039 (progn
11040 ;; First likely point: indent from beginning of previous code line
11041 (push (setq basic-offset
11042 (+ (save-excursion
11043 (back-to-indentation)
11044 (js2-backward-sws)
11045 (back-to-indentation)
11046 (current-column))
11047 js2-basic-offset))
11048 positions)
11049
11050 ;; (First + epsilon) likely point: indent 2x from beginning of
11051 ;; previous code line. Google does it this way.
11052 (push (setq basic-offset
11053 (+ (save-excursion
11054 (back-to-indentation)
11055 (js2-backward-sws)
11056 (back-to-indentation)
11057 (current-column))
11058 (* 2 js2-basic-offset)))
11059 positions)
11060
11061 ;; Second likely point: indent from assign-expr RHS. This
11062 ;; is just a crude guess based on finding " = " on the previous
11063 ;; line containing actual code.
11064 (setq pos (save-excursion
11065 (forward-line -1)
11066 (goto-char (point-at-bol))
11067 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11068 (point-at-eol) t)
11069 (goto-char (match-end 1))
11070 (skip-chars-forward " \t\r\n")
11071 (current-column))))
11072 (when pos
11073 (cl-incf pos js2-basic-offset)
11074 (push pos positions))
11075
11076 ;; Third likely point: same indent as previous line of code.
11077 ;; Make it the first likely point if we're not on an
11078 ;; arglist-close line and previous line ends in a comma, or
11079 ;; both this line and prev line look like object-literal
11080 ;; elements.
11081 (setq pos (save-excursion
11082 (goto-char (point-at-bol))
11083 (js2-backward-sws)
11084 (back-to-indentation)
11085 (prog1
11086 (current-column)
11087 ;; while we're here, look for trailing comma
11088 (if (save-excursion
11089 (goto-char (point-at-eol))
11090 (js2-backward-sws)
11091 (eq (char-before) ?,))
11092 (setq arglist-cont (1- (point)))))))
11093 (when pos
11094 (if (and (or arglist-cont
11095 (js2-indent-in-objlit-p parse-status))
11096 (not (js2-arglist-close)))
11097 (setq same-indent pos))
11098 (push pos positions))
11099
11100 ;; Fourth likely point: first preceding code with less indentation.
11101 ;; than the immediately preceding code line.
11102 (setq pos (save-excursion
11103 (back-to-indentation)
11104 (js2-backward-sws)
11105 (back-to-indentation)
11106 (setq anchor (current-column))
11107 (while (and (zerop (forward-line -1))
11108 (>= (progn
11109 (back-to-indentation)
11110 (current-column))
11111 anchor)))
11112 (setq pos (current-column))))
11113 (push pos positions)
11114
11115 ;; nesting-heuristic position, main by default
11116 (push (setq main-pos normal-col) positions)
11117
11118 ;; delete duplicates and sort positions list
11119 (setq positions (sort (delete-dups positions) '<))
11120
11121 ;; comma-list continuation lines: prev line indent takes precedence
11122 (if same-indent
11123 (setq main-pos same-indent))
11124
11125 ;; common special cases where we want to indent in from previous line
11126 (if (or (js2-indent-case-block-p)
11127 (js2-indent-objlit-arg-p parse-status))
11128 (setq main-pos basic-offset))
11129
11130 ;; if bouncing backward, reverse positions list
11131 (if backward
11132 (setq positions (reverse positions)))
11133
11134 ;; record whether we're already sitting on one of the alternatives
11135 (setq pos (member cur-indent positions))
11136
11137 (cond
11138 ;; case 0: we're one one of the alternatives and this is the
11139 ;; first time they've pressed TAB on this line (best-guess).
11140 ((and js2-mode-indent-ignore-first-tab
11141 pos
11142 ;; first time pressing TAB on this line?
11143 (not (eq js2-mode-last-indented-line current-line)))
11144 ;; do nothing
11145 (setq computed-pos nil))
11146 ;; case 1: only one computed position => use it
11147 ((null (cdr positions))
11148 (setq computed-pos 0))
11149 ;; case 2: not on any of the computed spots => use main spot
11150 ((not pos)
11151 (setq computed-pos (js2-position main-pos positions)))
11152 ;; case 3: on last position: cycle to first position
11153 ((null (cdr pos))
11154 (setq computed-pos 0))
11155 ;; case 4: on intermediate position: cycle to next position
11156 (t
11157 (setq computed-pos (js2-position (cl-second pos) positions))))
11158
11159 ;; see if any hooks want to indent; otherwise we do it
11160 (cl-loop with result = nil
11161 for hook in js2-indent-hook
11162 while (null result)
11163 do
11164 (setq result (funcall hook positions computed-pos))
11165 finally do
11166 (unless (or result (null computed-pos))
11167 (indent-line-to (nth computed-pos positions)))))
11168
11169 ;; finally
11170 (if js2-mode-indent-inhibit-undo
11171 (setq buffer-undo-list old-buffer-undo-list))
11172 ;; see commentary for `js2-mode-last-indented-line'
11173 (setq js2-mode-last-indented-line current-line))))
11174
11175 (defun js2-1-line-comment-continuation-p ()
11176 "Return t if we're in a 1-line comment continuation.
11177 If so, we don't ever want to use bounce-indent."
11178 (save-excursion
11179 (and (progn
11180 (forward-line 0)
11181 (looking-at "\\s-*//"))
11182 (progn
11183 (forward-line -1)
11184 (forward-line 0)
11185 (when (looking-at "\\s-*$")
11186 (js2-backward-sws)
11187 (forward-line 0))
11188 (looking-at "\\s-*//")))))
11189
11190 (defun js2-indent-bounce (&optional backward)
11191 "Indent the current line, bouncing between several positions."
11192 (interactive)
11193 (let (parse-status offset indent-col
11194 ;; Don't whine about errors/warnings when we're indenting.
11195 ;; This has to be set before calling parse-partial-sexp below.
11196 (inhibit-point-motion-hooks t))
11197 (setq parse-status (save-excursion
11198 (syntax-ppss (point-at-bol)))
11199 offset (- (point) (save-excursion
11200 (back-to-indentation)
11201 (point))))
11202 ;; Don't touch multiline strings.
11203 (unless (nth 3 parse-status)
11204 (setq indent-col (js2-proper-indentation parse-status))
11205 (cond
11206 ;; It doesn't work well on first line of buffer.
11207 ((and (not (nth 4 parse-status))
11208 (not (js2-same-line (point-min)))
11209 (not (js2-1-line-comment-continuation-p)))
11210 (js2-bounce-indent indent-col parse-status backward))
11211 ;; just indent to the guesser's likely spot
11212 (t (indent-line-to indent-col)))
11213 (when (cl-plusp offset)
11214 (forward-char offset)))))
11215
11216 (defun js2-indent-bounce-backward ()
11217 "Indent the current line, bouncing between positions in reverse."
11218 (interactive)
11219 (js2-indent-bounce t))
11220
11221 (defun js2-indent-region (start end)
11222 "Indent the region, but don't use bounce indenting."
11223 (let ((js2-bounce-indent-p nil)
11224 (indent-region-function nil)
11225 (after-change-functions (remq 'js2-mode-edit
11226 after-change-functions)))
11227 (indent-region start end nil) ; nil for byte-compiler
11228 (js2-mode-edit start end (- end start))))
11229
11230 (defvar js2-minor-mode-map
11231 (let ((map (make-sparse-keymap)))
11232 (define-key map (kbd "C-c C-`") #'js2-next-error)
11233 (define-key map [mouse-1] #'js2-mode-show-node)
11234 map)
11235 "Keymap used when `js2-minor-mode' is active.")
11236
11237 ;;;###autoload
11238 (define-minor-mode js2-minor-mode
11239 "Minor mode for running js2 as a background linter.
11240 This allows you to use a different major mode for JavaScript editing,
11241 such as `js-mode', while retaining the asynchronous error/warning
11242 highlighting features of `js2-mode'."
11243 :group 'js2-mode
11244 :lighter " js-lint"
11245 (if (derived-mode-p 'js2-mode)
11246 (setq js2-minor-mode nil)
11247 (if js2-minor-mode
11248 (js2-minor-mode-enter)
11249 (js2-minor-mode-exit))))
11250
11251 (defun js2-minor-mode-enter ()
11252 "Initialization for `js2-minor-mode'."
11253 (set (make-local-variable 'max-lisp-eval-depth)
11254 (max max-lisp-eval-depth 3000))
11255 (setq next-error-function #'js2-next-error)
11256 (js2-set-default-externs)
11257 ;; Experiment: make reparse-delay longer for longer files.
11258 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11259 (setq js2-idle-timer-delay
11260 (* js2-idle-timer-delay
11261 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11262 (setq js2-mode-buffer-dirty-p t
11263 js2-mode-parsing nil)
11264 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11265 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11266 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11267 (when js2-include-jslint-globals
11268 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11269 (run-hooks 'js2-init-hook)
11270 (js2-reparse))
11271
11272 (defun js2-minor-mode-exit ()
11273 "Turn off `js2-minor-mode'."
11274 (setq next-error-function nil)
11275 (remove-hook 'after-change-functions #'js2-mode-edit t)
11276 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11277 (when js2-mode-node-overlay
11278 (delete-overlay js2-mode-node-overlay)
11279 (setq js2-mode-node-overlay nil))
11280 (js2-remove-overlays)
11281 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11282 (setq js2-mode-ast nil))
11283
11284 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11285 (make-variable-buffer-local 'js2-source-buffer)
11286
11287 (cl-defun js2-display-error-list ()
11288 "Display a navigable buffer listing parse errors/warnings."
11289 (interactive)
11290 (unless (js2-have-errors-p)
11291 (message "No errors")
11292 (cl-return-from js2-display-error-list))
11293 (cl-labels ((annotate-list
11294 (lst type)
11295 "Add diagnostic TYPE and line number to errs list"
11296 (mapcar (lambda (err)
11297 (list err type (line-number-at-pos (nth 1 err))))
11298 lst)))
11299 (let* ((srcbuf (current-buffer))
11300 (errbuf (get-buffer-create "*js-lint*"))
11301 (errors (annotate-list
11302 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11303 'js2-error)) ; must be a valid face name
11304 (warnings (annotate-list
11305 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11306 'js2-warning)) ; must be a valid face name
11307 (all-errs (sort (append errors warnings)
11308 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11309 (with-current-buffer errbuf
11310 (let ((inhibit-read-only t))
11311 (erase-buffer)
11312 (dolist (err all-errs)
11313 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11314 (insert-text-button
11315 (format "line %d: %s" line (js2-get-msg msg-key))
11316 'face type
11317 'follow-link "\C-m"
11318 'action 'js2-error-buffer-jump
11319 'js2-msg (js2-get-msg msg-key)
11320 'js2-pos beg)
11321 (insert "\n"))))
11322 (js2-error-buffer-mode)
11323 (setq js2-source-buffer srcbuf)
11324 (pop-to-buffer errbuf)
11325 (goto-char (point-min))
11326 (unless (eobp)
11327 (js2-error-buffer-view))))))
11328
11329 (defvar js2-error-buffer-mode-map
11330 (let ((map (make-sparse-keymap)))
11331 (define-key map "n" #'js2-error-buffer-next)
11332 (define-key map "p" #'js2-error-buffer-prev)
11333 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11334 (define-key map "o" #'js2-error-buffer-view)
11335 (define-key map "q" #'js2-error-buffer-quit)
11336 map)
11337 "Keymap used for js2 diagnostics buffers.")
11338
11339 (defun js2-error-buffer-mode ()
11340 "Major mode for js2 diagnostics buffers.
11341 Selecting an error will jump it to the corresponding source-buffer error.
11342 \\{js2-error-buffer-mode-map}"
11343 (interactive)
11344 (setq major-mode 'js2-error-buffer-mode
11345 mode-name "JS Lint Diagnostics")
11346 (use-local-map js2-error-buffer-mode-map)
11347 (setq truncate-lines t)
11348 (set-buffer-modified-p nil)
11349 (setq buffer-read-only t)
11350 (run-hooks 'js2-error-buffer-mode-hook))
11351
11352 (defun js2-error-buffer-next ()
11353 "Move to next error and view it."
11354 (interactive)
11355 (when (zerop (forward-line 1))
11356 (js2-error-buffer-view)))
11357
11358 (defun js2-error-buffer-prev ()
11359 "Move to previous error and view it."
11360 (interactive)
11361 (when (zerop (forward-line -1))
11362 (js2-error-buffer-view)))
11363
11364 (defun js2-error-buffer-quit ()
11365 "Kill the current buffer."
11366 (interactive)
11367 (kill-buffer))
11368
11369 (defun js2-error-buffer-jump (&rest ignored)
11370 "Jump cursor to current error in source buffer."
11371 (interactive)
11372 (when (js2-error-buffer-view)
11373 (pop-to-buffer js2-source-buffer)))
11374
11375 (defun js2-error-buffer-view ()
11376 "Scroll source buffer to show error at current line."
11377 (interactive)
11378 (cond
11379 ((not (eq major-mode 'js2-error-buffer-mode))
11380 (message "Not in a js2 errors buffer"))
11381 ((not (buffer-live-p js2-source-buffer))
11382 (message "Source buffer has been killed"))
11383 ((not (wholenump (get-text-property (point) 'js2-pos)))
11384 (message "There does not seem to be an error here"))
11385 (t
11386 (let ((pos (get-text-property (point) 'js2-pos))
11387 (msg (get-text-property (point) 'js2-msg)))
11388 (save-selected-window
11389 (pop-to-buffer js2-source-buffer)
11390 (goto-char pos)
11391 (message msg))))))
11392
11393 ;;;###autoload
11394 (define-derived-mode js2-mode js-mode "Javascript-IDE"
11395 "Major mode for editing JavaScript code."
11396 (set (make-local-variable 'max-lisp-eval-depth)
11397 (max max-lisp-eval-depth 3000))
11398 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11399 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11400 (set (make-local-variable 'syntax-propertize-function) nil)
11401 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11402 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11403 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11404 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11405 ;; for characters inside regexp literals.
11406 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11407 ;; this is necessary to make `show-paren-function' work properly
11408 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11409 ;; needed for M-x rgrep, among other things
11410 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11411
11412 (setq font-lock-defaults '(nil t))
11413
11414 ;; Experiment: make reparse-delay longer for longer files.
11415 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11416 (setq js2-idle-timer-delay
11417 (* js2-idle-timer-delay
11418 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11419
11420 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11421 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11422 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11423 (setq next-error-function #'js2-next-error)
11424 (imenu-add-to-menubar (concat "IM-" mode-name))
11425 (add-to-invisibility-spec '(js2-outline . t))
11426 (set (make-local-variable 'line-move-ignore-invisible) t)
11427 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11428 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11429
11430 (setq js2-mode-functions-hidden nil
11431 js2-mode-comments-hidden nil
11432 js2-mode-buffer-dirty-p t
11433 js2-mode-parsing nil)
11434
11435 (js2-set-default-externs)
11436
11437 (when js2-include-jslint-globals
11438 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11439
11440 (run-hooks 'js2-init-hook)
11441
11442 (js2-reparse))
11443
11444 ;; We may eventually want js2-jsx-mode to derive from js-jsx-mode, but that'd be
11445 ;; a bit more complicated and it doesn't net us much yet.
11446 ;;;###autoload
11447 (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
11448 "Major mode for editing JSX code.
11449
11450 To customize the indentation for this mode, set the SGML offset
11451 variables (`sgml-basic-offset' et al) locally, like so:
11452
11453 (defun set-jsx-indentation ()
11454 (setq-local sgml-basic-offset js2-basic-offset))
11455 (add-hook 'js2-jsx-mode-hook #'set-jsx-indentation)"
11456 (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
11457
11458 (defun js2-mode-exit ()
11459 "Exit `js2-mode' and clean up."
11460 (interactive)
11461 (when js2-mode-node-overlay
11462 (delete-overlay js2-mode-node-overlay)
11463 (setq js2-mode-node-overlay nil))
11464 (js2-remove-overlays)
11465 (setq js2-mode-ast nil)
11466 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11467 (remove-from-invisibility-spec '(js2-outline . t))
11468 (js2-mode-show-all)
11469 (with-silent-modifications
11470 (js2-clear-face (point-min) (point-max))))
11471
11472 (defun js2-mode-reset-timer ()
11473 "Cancel any existing parse timer and schedule a new one."
11474 (if js2-mode-parse-timer
11475 (cancel-timer js2-mode-parse-timer))
11476 (setq js2-mode-parsing nil)
11477 (let ((timer (timer-create)))
11478 (setq js2-mode-parse-timer timer)
11479 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11480 (timer-set-idle-time timer js2-idle-timer-delay)
11481 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11482 (timer-activate-when-idle timer nil)))
11483
11484 (defun js2-mode-idle-reparse (buffer)
11485 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11486 it to be reparsed when the buffer is selected."
11487 (cond ((eq buffer (current-buffer))
11488 (js2-reparse))
11489 ((buffer-live-p buffer)
11490 ;; reparse when the buffer is selected again
11491 (with-current-buffer buffer
11492 (add-hook 'window-configuration-change-hook
11493 #'js2-mode-idle-reparse-inner
11494 nil t)))))
11495
11496 (defun js2-mode-idle-reparse-inner ()
11497 (remove-hook 'window-configuration-change-hook
11498 #'js2-mode-idle-reparse-inner
11499 t)
11500 (js2-reparse))
11501
11502 (defun js2-mode-edit (_beg _end _len)
11503 "Schedule a new parse after buffer is edited.
11504 Buffer edit spans from BEG to END and is of length LEN."
11505 (setq js2-mode-buffer-dirty-p t)
11506 (js2-mode-hide-overlay)
11507 (js2-mode-reset-timer))
11508
11509 (defun js2-minor-mode-edit (_beg _end _len)
11510 "Callback for buffer edits in `js2-mode'.
11511 Schedules a new parse after buffer is edited.
11512 Buffer edit spans from BEG to END and is of length LEN."
11513 (setq js2-mode-buffer-dirty-p t)
11514 (js2-mode-hide-overlay)
11515 (js2-mode-reset-timer))
11516
11517 (defun js2-reparse (&optional force)
11518 "Re-parse current buffer after user finishes some data entry.
11519 If we get any user input while parsing, including cursor motion,
11520 we discard the parse and reschedule it. If FORCE is nil, then the
11521 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11522 (let (time
11523 interrupted-p
11524 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11525 (unless js2-mode-parsing
11526 (setq js2-mode-parsing t)
11527 (unwind-protect
11528 (when (or js2-mode-buffer-dirty-p force)
11529 (js2-remove-overlays)
11530 (setq js2-mode-buffer-dirty-p nil
11531 js2-mode-fontifications nil
11532 js2-mode-deferred-properties nil)
11533 (if js2-mode-verbose-parse-p
11534 (message "parsing..."))
11535 (setq time
11536 (js2-time
11537 (setq interrupted-p
11538 (catch 'interrupted
11539 (js2-parse)
11540 (with-silent-modifications
11541 ;; if parsing is interrupted, comments and regex
11542 ;; literals stay ignored by `parse-partial-sexp'
11543 (remove-text-properties (point-min) (point-max)
11544 '(syntax-table))
11545 (js2-mode-apply-deferred-properties)
11546 (js2-mode-remove-suppressed-warnings)
11547 (js2-mode-show-warnings)
11548 (js2-mode-show-errors)
11549 (if (>= js2-highlight-level 1)
11550 (js2-highlight-jsdoc js2-mode-ast)))
11551 nil))))
11552 (if interrupted-p
11553 (progn
11554 ;; unfinished parse => try again
11555 (setq js2-mode-buffer-dirty-p t)
11556 (js2-mode-reset-timer))
11557 (if js2-mode-verbose-parse-p
11558 (message "Parse time: %s" time))))
11559 (setq js2-mode-parsing nil)
11560 (unless interrupted-p
11561 (setq js2-mode-parse-timer nil))))))
11562
11563 (defun js2-mode-show-node (event)
11564 "Debugging aid: highlight selected AST node on mouse click."
11565 (interactive "e")
11566 (mouse-set-point event)
11567 (setq deactivate-mark t)
11568 (when js2-mode-show-overlay
11569 (let ((node (js2-node-at-point))
11570 beg end)
11571 (if (null node)
11572 (message "No node found at location %s" (point))
11573 (setq beg (js2-node-abs-pos node)
11574 end (+ beg (js2-node-len node)))
11575 (if js2-mode-node-overlay
11576 (move-overlay js2-mode-node-overlay beg end)
11577 (setq js2-mode-node-overlay (make-overlay beg end))
11578 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11579 (with-silent-modifications
11580 (if (fboundp 'cursor-sensor-mode)
11581 (put-text-property beg end 'cursor-sensor-functions
11582 '(js2-mode-hide-overlay))
11583 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11584 (message "%s, parent: %s"
11585 (js2-node-short-name node)
11586 (if (js2-node-parent node)
11587 (js2-node-short-name (js2-node-parent node))
11588 "nil"))))))
11589
11590 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11591 "Remove the debugging overlay when point moves.
11592 ARG1, ARG2 and ARG3 have different values depending on whether this function
11593 was found on `point-left' or in `cursor-sensor-functions'."
11594 (when js2-mode-node-overlay
11595 (let ((beg (overlay-start js2-mode-node-overlay))
11596 (end (overlay-end js2-mode-node-overlay))
11597 (p2 (if (windowp arg1)
11598 ;; Called from cursor-sensor-functions.
11599 (window-point arg1)
11600 ;; Called from point-left.
11601 arg2)))
11602 ;; Sometimes we're called spuriously.
11603 (unless (and p2
11604 (>= p2 beg)
11605 (<= p2 end))
11606 (with-silent-modifications
11607 (remove-text-properties beg end
11608 '(point-left nil cursor-sensor-functions)))
11609 (delete-overlay js2-mode-node-overlay)
11610 (setq js2-mode-node-overlay nil)))))
11611
11612 (defun js2-mode-reset ()
11613 "Debugging helper: reset everything."
11614 (interactive)
11615 (js2-mode-exit)
11616 (js2-mode))
11617
11618 (defun js2-mode-show-warn-or-err (e face)
11619 "Highlight a warning or error E with FACE.
11620 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11621 The last element is optional. When present, use instead of FACE."
11622 (let* ((key (cl-first e))
11623 (beg (cl-second e))
11624 (end (+ beg (cl-third e)))
11625 ;; Don't inadvertently go out of bounds.
11626 (beg (max (point-min) (min beg (point-max))))
11627 (end (max (point-min) (min end (point-max))))
11628 (ovl (make-overlay beg end)))
11629 ;; FIXME: Why a mix of overlays and text-properties?
11630 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11631 (overlay-put ovl 'js2-error t)
11632 (put-text-property beg end 'help-echo (js2-get-msg key))
11633 (if (fboundp 'cursor-sensor-mode)
11634 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11635 (put-text-property beg end 'point-entered #'js2-echo-error))))
11636
11637 (defun js2-remove-overlays ()
11638 "Remove overlays from buffer that have a `js2-error' property."
11639 (let ((beg (point-min))
11640 (end (point-max)))
11641 (save-excursion
11642 (dolist (o (overlays-in beg end))
11643 (when (overlay-get o 'js2-error)
11644 (delete-overlay o))))))
11645
11646 (defun js2-mode-apply-deferred-properties ()
11647 "Apply fontifications and other text properties recorded during parsing."
11648 (when (cl-plusp js2-highlight-level)
11649 ;; We defer clearing faces as long as possible to eliminate flashing.
11650 (js2-clear-face (point-min) (point-max))
11651 ;; Have to reverse the recorded fontifications list so that errors
11652 ;; and warnings overwrite the normal fontifications.
11653 (dolist (f (nreverse js2-mode-fontifications))
11654 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11655 (setq js2-mode-fontifications nil))
11656 (dolist (p js2-mode-deferred-properties)
11657 (apply #'put-text-property p))
11658 (setq js2-mode-deferred-properties nil))
11659
11660 (defun js2-mode-show-errors ()
11661 "Highlight syntax errors."
11662 (when js2-mode-show-parse-errors
11663 (dolist (e (js2-ast-root-errors js2-mode-ast))
11664 (js2-mode-show-warn-or-err e 'js2-error))))
11665
11666 (defun js2-mode-remove-suppressed-warnings ()
11667 "Take suppressed warnings out of the AST warnings list.
11668 This ensures that the counts and `next-error' are correct."
11669 (setf (js2-ast-root-warnings js2-mode-ast)
11670 (js2-delete-if
11671 (lambda (e)
11672 (let ((key (caar e)))
11673 (or
11674 (and (not js2-strict-trailing-comma-warning)
11675 (string-match "trailing\\.comma" key))
11676 (and (not js2-strict-cond-assign-warning)
11677 (string= key "msg.equal.as.assign"))
11678 (and js2-missing-semi-one-line-override
11679 (string= key "msg.missing.semi")
11680 (let* ((beg (cl-second e))
11681 (node (js2-node-at-point beg))
11682 (fn (js2-mode-find-parent-fn node))
11683 (body (and fn (js2-function-node-body fn)))
11684 (lc (and body (js2-node-abs-pos body)))
11685 (rc (and lc (+ lc (js2-node-len body)))))
11686 (and fn
11687 (or (null body)
11688 (save-excursion
11689 (goto-char beg)
11690 (and (js2-same-line lc)
11691 (js2-same-line rc))))))))))
11692 (js2-ast-root-warnings js2-mode-ast))))
11693
11694 (defun js2-mode-show-warnings ()
11695 "Highlight strict-mode warnings."
11696 (when js2-mode-show-strict-warnings
11697 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11698 (js2-mode-show-warn-or-err e 'js2-warning))))
11699
11700 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11701 "Called by point-motion hooks.
11702 ARG1, ARG2 and ARG3 have different values depending on whether this function
11703 was found on `point-entered' or in `cursor-sensor-functions'."
11704 (let* ((new-point (if (windowp arg1)
11705 ;; Called from cursor-sensor-functions.
11706 (window-point arg1)
11707 ;; Called from point-left.
11708 arg2))
11709 (msg (get-text-property new-point 'help-echo)))
11710 (when (and (stringp msg)
11711 (not (active-minibuffer-window))
11712 (not (current-message)))
11713 (message msg))))
11714
11715 (defun js2-line-break (&optional _soft)
11716 "Break line at point and indent, continuing comment if within one.
11717 If inside a string, and `js2-concat-multiline-strings' is not
11718 nil, turn it into concatenation."
11719 (interactive)
11720 (let ((parse-status (syntax-ppss)))
11721 (cond
11722 ;; Check if we're inside a string.
11723 ((nth 3 parse-status)
11724 (if js2-concat-multiline-strings
11725 (js2-mode-split-string parse-status)
11726 (insert "\n")))
11727 ;; Check if inside a block comment.
11728 ((nth 4 parse-status)
11729 (js2-mode-extend-comment (nth 8 parse-status)))
11730 (t
11731 (newline-and-indent)))))
11732
11733 (defun js2-mode-split-string (parse-status)
11734 "Turn a newline in mid-string into a string concatenation.
11735 PARSE-STATUS is as documented in `parse-partial-sexp'."
11736 (let* ((quote-char (nth 3 parse-status))
11737 (at-eol (eq js2-concat-multiline-strings 'eol)))
11738 (insert quote-char)
11739 (insert (if at-eol " +\n" "\n"))
11740 (unless at-eol
11741 (insert "+ "))
11742 (js2-indent-line)
11743 (insert quote-char)
11744 (when (eolp)
11745 (insert quote-char)
11746 (backward-char 1))))
11747
11748 (defun js2-mode-extend-comment (start-pos)
11749 "Indent the line and, when inside a comment block, add comment prefix."
11750 (let (star single col first-line needs-close)
11751 (save-excursion
11752 (back-to-indentation)
11753 (when (< (point) start-pos)
11754 (goto-char start-pos))
11755 (cond
11756 ((looking-at "\\*[^/]")
11757 (setq star t
11758 col (current-column)))
11759 ((looking-at "/\\*")
11760 (setq star t
11761 first-line t
11762 col (1+ (current-column))))
11763 ((looking-at "//")
11764 (setq single t
11765 col (current-column)))))
11766 ;; Heuristic for whether we need to close the comment:
11767 ;; if we've got a parse error here, assume it's an unterminated
11768 ;; comment.
11769 (setq needs-close
11770 (or
11771 (get-char-property (1- (point)) 'js2-error)
11772 ;; The heuristic above doesn't work well when we're
11773 ;; creating a comment and there's another one downstream,
11774 ;; as our parser thinks this one ends at the end of the
11775 ;; next one. (You can have a /* inside a js block comment.)
11776 ;; So just close it if the next non-ws char isn't a *.
11777 (and first-line
11778 (eolp)
11779 (save-excursion
11780 (skip-chars-forward " \t\r\n")
11781 (not (eq (char-after) ?*))))))
11782 (delete-horizontal-space)
11783 (insert "\n")
11784 (cond
11785 (star
11786 (indent-to col)
11787 (insert "* ")
11788 (if (and first-line needs-close)
11789 (save-excursion
11790 (insert "\n")
11791 (indent-to col)
11792 (insert "*/"))))
11793 ((and single
11794 (save-excursion
11795 (and (zerop (forward-line 1))
11796 (looking-at "\\s-*//"))))
11797 (indent-to col)
11798 (insert "// ")))
11799 ;; Don't need to extend the comment after all.
11800 (js2-indent-line)))
11801
11802 (defun js2-beginning-of-line ()
11803 "Toggle point between bol and first non-whitespace char in line.
11804 Also moves past comment delimiters when inside comments."
11805 (interactive)
11806 (let (node)
11807 (cond
11808 ((bolp)
11809 (back-to-indentation))
11810 ((looking-at "//")
11811 (skip-chars-forward "/ \t"))
11812 ((and (eq (char-after) ?*)
11813 (setq node (js2-comment-at-point))
11814 (memq (js2-comment-node-format node) '(jsdoc block))
11815 (save-excursion
11816 (skip-chars-backward " \t")
11817 (bolp)))
11818 (skip-chars-forward "\* \t"))
11819 (t
11820 (goto-char (point-at-bol))))))
11821
11822 (defun js2-end-of-line ()
11823 "Toggle point between eol and last non-whitespace char in line."
11824 (interactive)
11825 (if (eolp)
11826 (skip-chars-backward " \t")
11827 (goto-char (point-at-eol))))
11828
11829 (defun js2-mode-wait-for-parse (callback)
11830 "Invoke CALLBACK when parsing is finished.
11831 If parsing is already finished, calls CALLBACK immediately."
11832 (if (not js2-mode-buffer-dirty-p)
11833 (funcall callback)
11834 (push callback js2-mode-pending-parse-callbacks)
11835 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11836
11837 (defun js2-mode-parse-finished ()
11838 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11839 ;; We can't let errors propagate up, since it prevents the
11840 ;; `js2-parse' method from completing normally and returning
11841 ;; the ast, which makes things mysteriously not work right.
11842 (unwind-protect
11843 (dolist (cb js2-mode-pending-parse-callbacks)
11844 (condition-case err
11845 (funcall cb)
11846 (error (message "%s" err))))
11847 (setq js2-mode-pending-parse-callbacks nil)))
11848
11849 (defun js2-mode-flag-region (from to flag)
11850 "Hide or show text from FROM to TO, according to FLAG.
11851 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11852 Returns the created overlay if FLAG is non-nil."
11853 (remove-overlays from to 'invisible 'js2-outline)
11854 (when flag
11855 (let ((o (make-overlay from to)))
11856 (overlay-put o 'invisible 'js2-outline)
11857 (overlay-put o 'isearch-open-invisible
11858 'js2-isearch-open-invisible)
11859 o)))
11860
11861 ;; Function to be set as an outline-isearch-open-invisible' property
11862 ;; to the overlay that makes the outline invisible (see
11863 ;; `js2-mode-flag-region').
11864 (defun js2-isearch-open-invisible (_overlay)
11865 ;; We rely on the fact that isearch places point on the matched text.
11866 (js2-mode-show-element))
11867
11868 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11869 "Return cons cell of bounds of folding overlay at POS.
11870 Returns nil if not found."
11871 (let ((overlays (overlays-at (or pos (point))))
11872 o)
11873 (while (and overlays
11874 (not o))
11875 (if (overlay-get (car overlays) 'invisible)
11876 (setq o (car overlays))
11877 (setq overlays (cdr overlays))))
11878 (if o
11879 (cons (overlay-start o) (overlay-end o)))))
11880
11881 (defun js2-mode-function-at-point (&optional pos)
11882 "Return the innermost function node enclosing current point.
11883 Returns nil if point is not in a function."
11884 (let ((node (js2-node-at-point pos)))
11885 (while (and node (not (js2-function-node-p node)))
11886 (setq node (js2-node-parent node)))
11887 (if (js2-function-node-p node)
11888 node)))
11889
11890 (defun js2-mode-toggle-element ()
11891 "Hide or show the foldable element at the point."
11892 (interactive)
11893 (let (comment fn pos)
11894 (save-excursion
11895 (cond
11896 ;; /* ... */ comment?
11897 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11898 (if (js2-mode-invisible-overlay-bounds
11899 (setq pos (+ 3 (js2-node-abs-pos comment))))
11900 (progn
11901 (goto-char pos)
11902 (js2-mode-show-element))
11903 (js2-mode-hide-element)))
11904 ;; //-comment?
11905 ((save-excursion
11906 (back-to-indentation)
11907 (looking-at js2-mode-//-comment-re))
11908 (js2-mode-toggle-//-comment))
11909 ;; function?
11910 ((setq fn (js2-mode-function-at-point))
11911 (setq pos (and (js2-function-node-body fn)
11912 (js2-node-abs-pos (js2-function-node-body fn))))
11913 (goto-char (1+ pos))
11914 (if (js2-mode-invisible-overlay-bounds)
11915 (js2-mode-show-element)
11916 (js2-mode-hide-element)))
11917 (t
11918 (message "Nothing at point to hide or show"))))))
11919
11920 (defun js2-mode-hide-element ()
11921 "Fold/hide contents of a block, showing ellipses.
11922 Show the hidden text with \\[js2-mode-show-element]."
11923 (interactive)
11924 (if js2-mode-buffer-dirty-p
11925 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11926 (let (node body beg end)
11927 (cond
11928 ((js2-mode-invisible-overlay-bounds)
11929 (message "already hidden"))
11930 (t
11931 (setq node (js2-node-at-point))
11932 (cond
11933 ((js2-block-comment-p node)
11934 (js2-mode-hide-comment node))
11935 (t
11936 (while (and node (not (js2-function-node-p node)))
11937 (setq node (js2-node-parent node)))
11938 (if (and node
11939 (setq body (js2-function-node-body node)))
11940 (progn
11941 (setq beg (js2-node-abs-pos body)
11942 end (+ beg (js2-node-len body)))
11943 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11944 (message "No collapsable element found at point"))))))))
11945
11946 (defun js2-mode-show-element ()
11947 "Show the hidden element at current point."
11948 (interactive)
11949 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11950 (if bounds
11951 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11952 (message "Nothing to un-hide"))))
11953
11954 (defun js2-mode-show-all ()
11955 "Show all of the text in the buffer."
11956 (interactive)
11957 (js2-mode-flag-region (point-min) (point-max) nil))
11958
11959 (defun js2-mode-toggle-hide-functions ()
11960 (interactive)
11961 (if js2-mode-functions-hidden
11962 (js2-mode-show-functions)
11963 (js2-mode-hide-functions)))
11964
11965 (defun js2-mode-hide-functions ()
11966 "Hides all non-nested function bodies in the buffer.
11967 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11968 to open an individual entry."
11969 (interactive)
11970 (if js2-mode-buffer-dirty-p
11971 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11972 (if (null js2-mode-ast)
11973 (message "Oops - parsing failed")
11974 (setq js2-mode-functions-hidden t)
11975 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11976
11977 (defun js2-mode-function-hider (n endp)
11978 (when (not endp)
11979 (let ((tt (js2-node-type n))
11980 body beg end)
11981 (cond
11982 ((and (= tt js2-FUNCTION)
11983 (setq body (js2-function-node-body n)))
11984 (setq beg (js2-node-abs-pos body)
11985 end (+ beg (js2-node-len body)))
11986 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11987 nil) ; don't process children of function
11988 (t
11989 t))))) ; keep processing other AST nodes
11990
11991 (defun js2-mode-show-functions ()
11992 "Un-hide any folded function bodies in the buffer."
11993 (interactive)
11994 (setq js2-mode-functions-hidden nil)
11995 (save-excursion
11996 (goto-char (point-min))
11997 (while (/= (goto-char (next-overlay-change (point)))
11998 (point-max))
11999 (dolist (o (overlays-at (point)))
12000 (when (and (overlay-get o 'invisible)
12001 (not (overlay-get o 'comment)))
12002 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12003
12004 (defun js2-mode-hide-comment (n)
12005 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12006 3 ; /**
12007 2)) ; /*
12008 (beg (+ (js2-node-abs-pos n) head))
12009 (end (- (+ beg (js2-node-len n)) head 2))
12010 (o (js2-mode-flag-region beg end 'hide)))
12011 (overlay-put o 'comment t)))
12012
12013 (defun js2-mode-toggle-hide-comments ()
12014 "Folds all block comments in the buffer.
12015 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12016 to open an individual entry."
12017 (interactive)
12018 (if js2-mode-comments-hidden
12019 (js2-mode-show-comments)
12020 (js2-mode-hide-comments)))
12021
12022 (defun js2-mode-hide-comments ()
12023 (interactive)
12024 (if js2-mode-buffer-dirty-p
12025 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12026 (if (null js2-mode-ast)
12027 (message "Oops - parsing failed")
12028 (setq js2-mode-comments-hidden t)
12029 (dolist (n (js2-ast-root-comments js2-mode-ast))
12030 (when (js2-block-comment-p n)
12031 (js2-mode-hide-comment n)))
12032 (js2-mode-hide-//-comments)))
12033
12034 (defun js2-mode-extend-//-comment (direction)
12035 "Find start or end of a block of similar //-comment lines.
12036 DIRECTION is -1 to look back, 1 to look forward.
12037 INDENT is the indentation level to match.
12038 Returns the end-of-line position of the furthest adjacent
12039 //-comment line with the same indentation as the current line.
12040 If there is no such matching line, returns current end of line."
12041 (let ((pos (point-at-eol))
12042 (indent (current-indentation)))
12043 (save-excursion
12044 (while (and (zerop (forward-line direction))
12045 (looking-at js2-mode-//-comment-re)
12046 (eq indent (length (match-string 1))))
12047 (setq pos (point-at-eol)))
12048 pos)))
12049
12050 (defun js2-mode-hide-//-comments ()
12051 "Fold adjacent 1-line comments, showing only snippet of first one."
12052 (let (beg end)
12053 (save-excursion
12054 (goto-char (point-min))
12055 (while (re-search-forward js2-mode-//-comment-re nil t)
12056 (setq beg (point)
12057 end (js2-mode-extend-//-comment 1))
12058 (unless (eq beg end)
12059 (overlay-put (js2-mode-flag-region beg end 'hide)
12060 'comment t))
12061 (goto-char end)
12062 (forward-char 1)))))
12063
12064 (defun js2-mode-toggle-//-comment ()
12065 "Fold or un-fold any multi-line //-comment at point.
12066 Caller should have determined that this line starts with a //-comment."
12067 (let* ((beg (point-at-eol))
12068 (end beg))
12069 (save-excursion
12070 (goto-char end)
12071 (if (js2-mode-invisible-overlay-bounds)
12072 (js2-mode-show-element)
12073 ;; else hide the comment
12074 (setq beg (js2-mode-extend-//-comment -1)
12075 end (js2-mode-extend-//-comment 1))
12076 (unless (eq beg end)
12077 (overlay-put (js2-mode-flag-region beg end 'hide)
12078 'comment t))))))
12079
12080 (defun js2-mode-show-comments ()
12081 "Un-hide any hidden comments, leaving other hidden elements alone."
12082 (interactive)
12083 (setq js2-mode-comments-hidden nil)
12084 (save-excursion
12085 (goto-char (point-min))
12086 (while (/= (goto-char (next-overlay-change (point)))
12087 (point-max))
12088 (dolist (o (overlays-at (point)))
12089 (when (overlay-get o 'comment)
12090 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12091
12092 (defun js2-mode-display-warnings-and-errors ()
12093 "Turn on display of warnings and errors."
12094 (interactive)
12095 (setq js2-mode-show-parse-errors t
12096 js2-mode-show-strict-warnings t)
12097 (js2-reparse 'force))
12098
12099 (defun js2-mode-hide-warnings-and-errors ()
12100 "Turn off display of warnings and errors."
12101 (interactive)
12102 (setq js2-mode-show-parse-errors nil
12103 js2-mode-show-strict-warnings nil)
12104 (js2-reparse 'force))
12105
12106 (defun js2-mode-toggle-warnings-and-errors ()
12107 "Toggle the display of warnings and errors.
12108 Some users don't like having warnings/errors reported while they type."
12109 (interactive)
12110 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12111 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12112 (if (called-interactively-p 'any)
12113 (message "warnings and errors %s"
12114 (if js2-mode-show-parse-errors
12115 "enabled"
12116 "disabled")))
12117 (js2-reparse 'force))
12118
12119 (defun js2-mode-customize ()
12120 (interactive)
12121 (customize-group 'js2-mode))
12122
12123 (defun js2-mode-forward-sexp (&optional arg)
12124 "Move forward across one statement or balanced expression.
12125 With ARG, do it that many times. Negative arg -N means
12126 move backward across N balanced expressions."
12127 (interactive "p")
12128 (setq arg (or arg 1))
12129 (save-restriction
12130 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12131 (js2-reparse)
12132 (let (forward-sexp-function
12133 node (start (point)) pos lp rp child)
12134 (cond
12135 ;; backward-sexp
12136 ;; could probably make this better for some cases:
12137 ;; - if in statement block (e.g. function body), go to parent
12138 ;; - infix exprs like (foo in bar) - maybe go to beginning
12139 ;; of infix expr if in the right-side expression?
12140 ((and arg (cl-minusp arg))
12141 (dotimes (_ (- arg))
12142 (js2-backward-sws)
12143 (forward-char -1) ; Enter the node we backed up to.
12144 (when (setq node (js2-node-at-point (point) t))
12145 (setq pos (js2-node-abs-pos node))
12146 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12147 (setq lp (car parens)
12148 rp (cdr parens)))
12149 (when (and lp (> start lp))
12150 (if (and rp (<= start rp))
12151 ;; Between parens, check if there's a child node we can jump.
12152 (when (setq child (js2-node-closest-child node (point) lp t))
12153 (setq pos (js2-node-abs-pos child)))
12154 ;; Before both parens.
12155 (setq pos lp)))
12156 (let ((state (parse-partial-sexp start pos)))
12157 (goto-char (if (not (zerop (car state)))
12158 ;; Stumble at the unbalanced paren if < 0, or
12159 ;; jump a bit further if > 0.
12160 (scan-sexps start -1)
12161 pos))))
12162 (unless pos (goto-char (point-min)))))
12163 (t
12164 ;; forward-sexp
12165 (dotimes (_ arg)
12166 (js2-forward-sws)
12167 (when (setq node (js2-node-at-point (point) t))
12168 (setq pos (js2-node-abs-pos node))
12169 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12170 (setq lp (car parens)
12171 rp (cdr parens)))
12172 (or
12173 (when (and rp (<= start rp))
12174 (if (> start lp)
12175 (when (setq child (js2-node-closest-child node (point) rp))
12176 (setq pos (js2-node-abs-end child)))
12177 (setq pos (1+ rp))))
12178 ;; No parens or child nodes, looks for the end of the current node.
12179 (cl-incf pos (js2-node-len
12180 (if (js2-expr-stmt-node-p (js2-node-parent node))
12181 ;; Stop after the semicolon.
12182 (js2-node-parent node)
12183 node))))
12184 (let ((state (save-excursion (parse-partial-sexp start pos))))
12185 (goto-char (if (not (zerop (car state)))
12186 (scan-sexps start 1)
12187 pos))))
12188 (unless pos (goto-char (point-max)))))))))
12189
12190 (defun js2-mode-forward-sexp-parens (node abs-pos)
12191 "Return a cons cell with positions of main parens in NODE."
12192 (cond
12193 ((or (js2-array-node-p node)
12194 (js2-object-node-p node)
12195 (js2-comp-node-p node)
12196 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12197 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12198 ((js2-paren-expr-node-p node)
12199 (let ((lp (js2-node-lp node))
12200 (rp (js2-node-rp node)))
12201 (cons (when lp (+ abs-pos lp))
12202 (when rp (+ abs-pos rp)))))))
12203
12204 (defun js2-node-closest-child (parent point limit &optional before)
12205 (let* ((parent-pos (js2-node-abs-pos parent))
12206 (rpoint (- point parent-pos))
12207 (rlimit (- limit parent-pos))
12208 (min (min rpoint rlimit))
12209 (max (max rpoint rlimit))
12210 found)
12211 (catch 'done
12212 (js2-visit-ast
12213 parent
12214 (lambda (node _end-p)
12215 (if (eq node parent)
12216 t
12217 (let ((pos (js2-node-pos node)) ;; Both relative values.
12218 (end (+ (js2-node-pos node) (js2-node-len node))))
12219 (when (and (>= pos min) (<= end max)
12220 (if before (< pos rpoint) (> end rpoint)))
12221 (setq found node))
12222 (when (> end rpoint)
12223 (throw 'done nil)))
12224 nil))))
12225 found))
12226
12227 (defun js2-errors ()
12228 "Return a list of errors found."
12229 (and js2-mode-ast
12230 (js2-ast-root-errors js2-mode-ast)))
12231
12232 (defun js2-warnings ()
12233 "Return a list of warnings found."
12234 (and js2-mode-ast
12235 (js2-ast-root-warnings js2-mode-ast)))
12236
12237 (defun js2-have-errors-p ()
12238 "Return non-nil if any parse errors or warnings were found."
12239 (or (js2-errors) (js2-warnings)))
12240
12241 (defun js2-errors-and-warnings ()
12242 "Return a copy of the concatenated errors and warnings lists.
12243 They are appended: first the errors, then the warnings.
12244 Entries are of the form (MSG BEG END)."
12245 (when js2-mode-ast
12246 (append (js2-ast-root-errors js2-mode-ast)
12247 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12248
12249 (defun js2-next-error (&optional arg reset)
12250 "Move to next parse error.
12251 Typically invoked via \\[next-error].
12252 ARG is the number of errors, forward or backward, to move.
12253 RESET means start over from the beginning."
12254 (interactive "p")
12255 (if (not (or (js2-errors) (js2-warnings)))
12256 (message "No errors")
12257 (when reset
12258 (goto-char (point-min)))
12259 (let* ((errs (js2-errors-and-warnings))
12260 (continue t)
12261 (start (point))
12262 (count (or arg 1))
12263 (backward (cl-minusp count))
12264 (sorter (if backward '> '<))
12265 (stopper (if backward '< '>))
12266 (count (abs count))
12267 all-errs err)
12268 ;; Sort by start position.
12269 (setq errs (sort errs (lambda (e1 e2)
12270 (funcall sorter (cl-second e1) (cl-second e2))))
12271 all-errs errs)
12272 ;; Find nth error with pos > start.
12273 (while (and errs continue)
12274 (when (funcall stopper (cl-cadar errs) start)
12275 (setq err (car errs))
12276 (if (zerop (cl-decf count))
12277 (setq continue nil)))
12278 (setq errs (cdr errs)))
12279 ;; Clear for `js2-echo-error'.
12280 (message nil)
12281 (if err
12282 (goto-char (cl-second err))
12283 ;; Wrap around to first error.
12284 (goto-char (cl-second (car all-errs)))
12285 ;; If we were already on it, echo msg again.
12286 (if (= (point) start)
12287 (js2-echo-error (point) (point)))))))
12288
12289 (defun js2-down-mouse-3 ()
12290 "Make right-click move the point to the click location.
12291 This makes right-click context menu operations a bit more intuitive.
12292 The point will not move if the region is active, however, to avoid
12293 destroying the region selection."
12294 (interactive)
12295 (when (and js2-move-point-on-right-click
12296 (not mark-active))
12297 (let ((e last-input-event))
12298 (ignore-errors
12299 (goto-char (cl-cadadr e))))))
12300
12301 (defun js2-mode-create-imenu-index ()
12302 "Return an alist for `imenu--index-alist'."
12303 ;; This is built up in `js2-parse-record-imenu' during parsing.
12304 (when js2-mode-ast
12305 ;; if we have an ast but no recorder, they're requesting a rescan
12306 (unless js2-imenu-recorder
12307 (js2-reparse 'force))
12308 (prog1
12309 (js2-build-imenu-index)
12310 (setq js2-imenu-recorder nil
12311 js2-imenu-function-map nil))))
12312
12313 (defun js2-mode-find-tag ()
12314 "Replacement for `find-tag-default'.
12315 `find-tag-default' returns a ridiculous answer inside comments."
12316 (let (beg end)
12317 (save-excursion
12318 (if (looking-at "\\_>")
12319 (setq beg (progn (forward-symbol -1) (point))
12320 end (progn (forward-symbol 1) (point)))
12321 (setq beg (progn (forward-symbol 1) (point))
12322 end (progn (forward-symbol -1) (point))))
12323 (replace-regexp-in-string
12324 "[\"']" ""
12325 (buffer-substring-no-properties beg end)))))
12326
12327 (defun js2-mode-forward-sibling ()
12328 "Move to the end of the sibling following point in parent.
12329 Returns non-nil if successful, or nil if there was no following sibling."
12330 (let* ((node (js2-node-at-point))
12331 (parent (js2-mode-find-enclosing-fn node))
12332 sib)
12333 (when (setq sib (js2-node-find-child-after (point) parent))
12334 (goto-char (+ (js2-node-abs-pos sib)
12335 (js2-node-len sib))))))
12336
12337 (defun js2-mode-backward-sibling ()
12338 "Move to the beginning of the sibling node preceding point in parent.
12339 Parent is defined as the enclosing script or function."
12340 (let* ((node (js2-node-at-point))
12341 (parent (js2-mode-find-enclosing-fn node))
12342 sib)
12343 (when (setq sib (js2-node-find-child-before (point) parent))
12344 (goto-char (js2-node-abs-pos sib)))))
12345
12346 (defun js2-beginning-of-defun (&optional arg)
12347 "Go to line on which current function starts, and return t on success.
12348 If we're not in a function or already at the beginning of one, go
12349 to beginning of previous script-level element.
12350 With ARG N, do that N times. If N is negative, move forward."
12351 (setq arg (or arg 1))
12352 (if (cl-plusp arg)
12353 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12354 (when (cond
12355 ((js2-function-node-p parent)
12356 (goto-char (js2-node-abs-pos parent)))
12357 (t
12358 (js2-mode-backward-sibling)))
12359 (if (> arg 1)
12360 (js2-beginning-of-defun (1- arg))
12361 t)))
12362 (when (js2-end-of-defun)
12363 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12364
12365 (defun js2-end-of-defun ()
12366 "Go to the char after the last position of the current function
12367 or script-level element."
12368 (let* ((node (js2-node-at-point))
12369 (parent (or (and (js2-function-node-p node) node)
12370 (js2-node-parent-script-or-fn node)))
12371 script)
12372 (unless (js2-function-node-p parent)
12373 ;; Use current script-level node, or, if none, the next one.
12374 (setq script (or parent node)
12375 parent (js2-node-find-child-before (point) script))
12376 (when (or (null parent)
12377 (>= (point) (+ (js2-node-abs-pos parent)
12378 (js2-node-len parent))))
12379 (setq parent (js2-node-find-child-after (point) script))))
12380 (when parent
12381 (goto-char (+ (js2-node-abs-pos parent)
12382 (js2-node-len parent))))))
12383
12384 (defun js2-mark-defun (&optional allow-extend)
12385 "Put mark at end of this function, point at beginning.
12386 The function marked is the one that contains point.
12387
12388 Interactively, if this command is repeated,
12389 or (in Transient Mark mode) if the mark is active,
12390 it marks the next defun after the ones already marked."
12391 (interactive "p")
12392 (let (extended)
12393 (when (and allow-extend
12394 (or (and (eq last-command this-command) (mark t))
12395 (and transient-mark-mode mark-active)))
12396 (let ((sib (save-excursion
12397 (goto-char (mark))
12398 (if (js2-mode-forward-sibling)
12399 (point)))))
12400 (if sib
12401 (progn
12402 (set-mark sib)
12403 (setq extended t))
12404 ;; no more siblings - try extending to enclosing node
12405 (goto-char (mark t)))))
12406 (when (not extended)
12407 (let ((node (js2-node-at-point (point) t)) ; skip comments
12408 ast fn stmt parent beg end)
12409 (when (js2-ast-root-p node)
12410 (setq ast node
12411 node (or (js2-node-find-child-after (point) node)
12412 (js2-node-find-child-before (point) node))))
12413 ;; only mark whole buffer if we can't find any children
12414 (if (null node)
12415 (setq node ast))
12416 (if (js2-function-node-p node)
12417 (setq parent node)
12418 (setq fn (js2-mode-find-enclosing-fn node)
12419 stmt (if (or (null fn)
12420 (js2-ast-root-p fn))
12421 (js2-mode-find-first-stmt node))
12422 parent (or stmt fn)))
12423 (setq beg (js2-node-abs-pos parent)
12424 end (+ beg (js2-node-len parent)))
12425 (push-mark beg)
12426 (goto-char end)
12427 (exchange-point-and-mark)))))
12428
12429 (defun js2-narrow-to-defun ()
12430 "Narrow to the function enclosing point."
12431 (interactive)
12432 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12433 (fn (if (js2-script-node-p node)
12434 node
12435 (js2-mode-find-enclosing-fn node)))
12436 (beg (js2-node-abs-pos fn)))
12437 (unless (js2-ast-root-p fn)
12438 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12439
12440 (defun js2-jump-to-definition (&optional arg)
12441 "Jump to the definition of an object's property, variable or function."
12442 (interactive "P")
12443 (ring-insert find-tag-marker-ring (point-marker))
12444 (let* ((node (js2-node-at-point))
12445 (parent (js2-node-parent node))
12446 (names (if (js2-prop-get-node-p parent)
12447 (reverse (let ((temp (js2-compute-nested-prop-get parent)))
12448 (cl-loop for n in temp
12449 with result = '()
12450 do (push n result)
12451 until (equal node n)
12452 finally return result)))))
12453 node-init)
12454 (unless (and (js2-name-node-p node)
12455 (not (js2-var-init-node-p parent))
12456 (not (js2-function-node-p parent)))
12457 (error "Node is not a supported jump node"))
12458 (push (or (and names (pop names))
12459 (unless (and (js2-object-prop-node-p parent)
12460 (eq node (js2-object-prop-node-left parent)))
12461 node)) names)
12462 (setq node-init (js2-search-scope node names))
12463
12464 ;; todo: display list of results in buffer
12465 ;; todo: group found references by buffer
12466 (unless node-init
12467 (switch-to-buffer
12468 (catch 'found
12469 (unless arg
12470 (mapc (lambda (b)
12471 (with-current-buffer b
12472 (when (derived-mode-p 'js2-mode)
12473 (setq node-init (js2-search-scope js2-mode-ast names))
12474 (if node-init
12475 (throw 'found b)))))
12476 (buffer-list)))
12477 nil)))
12478 (setq node-init (if (listp node-init) (car node-init) node-init))
12479 (unless node-init
12480 (pop-tag-mark)
12481 (error "No jump location found"))
12482 (goto-char (js2-node-abs-pos node-init))))
12483
12484 (defun js2-search-object (node name-node)
12485 "Check if object NODE contains element with NAME-NODE."
12486 (cl-assert (js2-object-node-p node))
12487 ;; Only support name-node and nodes for the time being
12488 (cl-loop for elem in (js2-object-node-elems node)
12489 for left = (js2-object-prop-node-left elem)
12490 if (or (and (js2-name-node-p left)
12491 (equal (js2-name-node-name name-node)
12492 (js2-name-node-name left)))
12493 (and (js2-string-node-p left)
12494 (string= (js2-name-node-name name-node)
12495 (js2-string-node-value left))))
12496 return elem))
12497
12498 (defun js2-search-object-for-prop (object prop-names)
12499 "Return node in OBJECT that matches PROP-NAMES or nil.
12500 PROP-NAMES is a list of values representing a path to a value in OBJECT.
12501 i.e. ('name' 'value') = {name : { value: 3}}"
12502 (let (node
12503 (temp-object object)
12504 (temp t) ;temporay node
12505 (names prop-names))
12506 (while (and temp names (js2-object-node-p temp-object))
12507 (setq temp (js2-search-object temp-object (pop names)))
12508 (and (setq node temp)
12509 (setq temp-object (js2-object-prop-node-right temp))))
12510 (unless names node)))
12511
12512 (defun js2-search-scope (node names)
12513 "Searches NODE scope for jump location matching NAMES.
12514 NAMES is a list of property values to search for. For functions
12515 and variables NAMES will contain one element."
12516 (let (node-init
12517 (val (js2-name-node-name (car names))))
12518 (setq node-init (js2-get-symbol-declaration node val))
12519
12520 (when (> (length names) 1)
12521
12522 ;; Check var declarations
12523 (when (and node-init (string= val (js2-name-node-name node-init)))
12524 (let ((parent (js2-node-parent node-init))
12525 (temp-names names))
12526 (pop temp-names) ;; First element is var name
12527 (setq node-init (when (js2-var-init-node-p parent)
12528 (js2-search-object-for-prop
12529 (js2-var-init-node-initializer parent)
12530 temp-names)))))
12531
12532 ;; Check all assign nodes
12533 (js2-visit-ast
12534 js2-mode-ast
12535 (lambda (node endp)
12536 (unless endp
12537 (if (js2-assign-node-p node)
12538 (let ((left (js2-assign-node-left node))
12539 (right (js2-assign-node-right node))
12540 (temp-names names))
12541 (when (js2-prop-get-node-p left)
12542 (let* ((prop-list (js2-compute-nested-prop-get left))
12543 (found (cl-loop for prop in prop-list
12544 until (not (string= (js2-name-node-name
12545 (pop temp-names))
12546 (js2-name-node-name prop)))
12547 if (not temp-names) return prop))
12548 (found-node (or found
12549 (when (js2-object-node-p right)
12550 (js2-search-object-for-prop right
12551 temp-names)))))
12552 (if found-node (push found-node node-init))))))
12553 t))))
12554 node-init))
12555
12556 (defun js2-get-symbol-declaration (node name)
12557 "Find scope for NAME from NODE."
12558 (let ((scope (js2-get-defining-scope
12559 (or (js2-node-get-enclosing-scope node)
12560 node) name)))
12561 (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
12562
12563 (provide 'js2-mode)
12564
12565 ;;; js2-mode.el ends here