]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Highlight unused and/or uninitialized variables
[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: 20150202
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (require 'cl-lib)
89 (require 'imenu)
90 (require 'cc-cmds) ; for `c-fill-paragraph'
91
92 (eval-and-compile
93 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
94 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
95
96 (defvar electric-layout-rules)
97
98 ;;; Externs (variables presumed to be defined by the host system)
99
100 (defvar js2-ecma-262-externs
101 (mapcar 'symbol-name
102 '(Array Boolean Date Error EvalError Function Infinity JSON
103 Math NaN Number Object RangeError ReferenceError RegExp
104 String SyntaxError TypeError URIError
105 decodeURI decodeURIComponent encodeURI
106 encodeURIComponent escape eval isFinite isNaN
107 parseFloat parseInt undefined unescape))
108 "Ecma-262 externs. Included in `js2-externs' by default.")
109
110 (defvar js2-browser-externs
111 (mapcar 'symbol-name
112 '(;; DOM level 1
113 Attr CDATASection CharacterData Comment DOMException
114 DOMImplementation Document DocumentFragment
115 DocumentType Element Entity EntityReference
116 ExceptionCode NamedNodeMap Node NodeList Notation
117 ProcessingInstruction Text
118
119 ;; DOM level 2
120 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
121 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
122 HTMLBodyElement HTMLButtonElement HTMLCollection
123 HTMLDListElement HTMLDirectoryElement HTMLDivElement
124 HTMLDocument HTMLElement HTMLFieldSetElement
125 HTMLFontElement HTMLFormElement HTMLFrameElement
126 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
127 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
128 HTMLImageElement HTMLInputElement HTMLIsIndexElement
129 HTMLLIElement HTMLLabelElement HTMLLegendElement
130 HTMLLinkElement HTMLMapElement HTMLMenuElement
131 HTMLMetaElement HTMLModElement HTMLOListElement
132 HTMLObjectElement HTMLOptGroupElement
133 HTMLOptionElement HTMLOptionsCollection
134 HTMLParagraphElement HTMLParamElement HTMLPreElement
135 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
136 HTMLStyleElement HTMLTableCaptionElement
137 HTMLTableCellElement HTMLTableColElement
138 HTMLTableElement HTMLTableRowElement
139 HTMLTableSectionElement HTMLTextAreaElement
140 HTMLTitleElement HTMLUListElement
141
142 ;; DOM level 3
143 DOMConfiguration DOMError DOMException
144 DOMImplementationList DOMImplementationSource
145 DOMLocator DOMStringList NameList TypeInfo
146 UserDataHandler
147
148 ;; Window
149 window alert confirm document java navigator prompt screen
150 self top requestAnimationFrame cancelAnimationFrame
151
152 ;; W3C CSS
153 CSSCharsetRule CSSFontFace CSSFontFaceRule
154 CSSImportRule CSSMediaRule CSSPageRule
155 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
156 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
157 CSSValue CSSValueList Counter DOMImplementationCSS
158 DocumentCSS DocumentStyle ElementCSSInlineStyle
159 LinkStyle MediaList RGBColor Rect StyleSheet
160 StyleSheetList ViewCSS
161
162 ;; W3C Event
163 EventListener EventTarget Event DocumentEvent UIEvent
164 MouseEvent MutationEvent KeyboardEvent
165
166 ;; W3C Range
167 DocumentRange Range RangeException
168
169 ;; W3C XML
170 XPathResult XMLHttpRequest
171
172 ;; console object. Provided by at least Chrome and Firefox.
173 console))
174 "Browser externs.
175 You can cause these to be included or excluded with the custom
176 variable `js2-include-browser-externs'.")
177
178 (defvar js2-rhino-externs
179 (mapcar 'symbol-name
180 '(Packages importClass importPackage com org java
181 ;; Global object (shell) externs.
182 defineClass deserialize doctest gc help load
183 loadClass print quit readFile readUrl runCommand seal
184 serialize spawn sync toint32 version))
185 "Mozilla Rhino externs.
186 Set `js2-include-rhino-externs' to t to include them.")
187
188 (defvar js2-node-externs
189 (mapcar 'symbol-name
190 '(__dirname __filename Buffer clearInterval clearTimeout require
191 console exports global module process setInterval setTimeout))
192 "Node.js externs.
193 Set `js2-include-node-externs' to t to include them.")
194
195 (defvar js2-typed-array-externs
196 (mapcar 'symbol-name
197 '(ArrayBuffer Uint8ClampedArray DataView
198 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
199 Float32Array Float64Array))
200 "Khronos typed array externs. Available in most modern browsers and
201 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
202 are enabled, these will also be included.")
203
204 (defvar js2-harmony-externs
205 (mapcar 'symbol-name
206 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
207 "ES6 externs. If `js2-include-browser-externs' is enabled and
208 `js2-language-version' is sufficiently high, these will be included.")
209
210 ;;; Variables
211
212 (defun js2-mark-safe-local (name pred)
213 "Make the variable NAME buffer-local and mark it as safe file-local
214 variable with predicate PRED."
215 (make-variable-buffer-local name)
216 (put name 'safe-local-variable pred))
217
218 (defcustom js2-highlight-level 2
219 "Amount of syntax highlighting to perform.
220 0 or a negative value means none.
221 1 adds basic syntax highlighting.
222 2 adds highlighting of some Ecma built-in properties.
223 3 adds highlighting of many Ecma built-in functions."
224 :group 'js2-mode
225 :type '(choice (const :tag "None" 0)
226 (const :tag "Basic" 1)
227 (const :tag "Include Properties" 2)
228 (const :tag "Include Functions" 3)))
229
230 (defvar js2-mode-dev-mode-p nil
231 "Non-nil if running in development mode. Normally nil.")
232
233 (defgroup js2-mode nil
234 "An improved JavaScript mode."
235 :group 'languages)
236
237 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
238 (numberp c-basic-offset))
239 c-basic-offset
240 4)
241 "Number of spaces to indent nested statements.
242 Similar to `c-basic-offset'."
243 :group 'js2-mode
244 :type 'integer)
245 (js2-mark-safe-local 'js2-basic-offset 'integerp)
246
247 (defcustom js2-bounce-indent-p nil
248 "Non-nil to have indent-line function choose among alternatives.
249 If nil, the indent-line function will indent to a predetermined column
250 based on heuristic guessing. If non-nil, then if the current line is
251 already indented to that predetermined column, indenting will choose
252 another likely column and indent to that spot. Repeated invocation of
253 the indent-line function will cycle among the computed alternatives.
254 See the function `js2-bounce-indent' for details. When it is non-nil,
255 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
256 :type 'boolean
257 :group 'js2-mode)
258
259 (defcustom js2-pretty-multiline-declarations t
260 "Non-nil to line up multiline declarations vertically:
261
262 var a = 10,
263 b = 20,
264 c = 30;
265
266 If the value is t, and the first assigned value in the
267 declaration is a function/array/object literal spanning several
268 lines, it won't be indented additionally:
269
270 var o = { var bar = 2,
271 foo: 3 vs. o = {
272 }, foo: 3
273 bar = 2; };
274
275 If the value is `all', it will always be indented additionally:
276
277 var o = {
278 foo: 3
279 };
280
281 var o = {
282 foo: 3
283 },
284 bar = 2;
285
286 If the value is `dynamic', it will be indented additionally only
287 if the declaration contains more than one variable:
288
289 var o = {
290 foo: 3
291 };
292
293 var o = {
294 foo: 3
295 },
296 bar = 2;"
297 :group 'js2-mode
298 :type 'symbol)
299 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
300
301 (defcustom js2-indent-switch-body nil
302 "When nil, case labels are indented on the same level as the
303 containing switch statement. Otherwise, all lines inside
304 switch statement body are indented one additional level."
305 :type 'boolean
306 :group 'js2-mode)
307 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
308
309 (defcustom js2-idle-timer-delay 0.2
310 "Delay in secs before re-parsing after user makes changes.
311 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
312 :type 'number
313 :group 'js2-mode)
314 (make-variable-buffer-local 'js2-idle-timer-delay)
315
316 (defcustom js2-dynamic-idle-timer-adjust 0
317 "Positive to adjust `js2-idle-timer-delay' based on file size.
318 The idea is that for short files, parsing is faster so we can be
319 more responsive to user edits without interfering with editing.
320 The buffer length in characters (typically bytes) is divided by
321 this value and used to multiply `js2-idle-timer-delay' for the
322 buffer. For example, a 21k file and 10k adjust yields 21k/10k
323 == 2, so js2-idle-timer-delay is multiplied by 2.
324 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
325 `js2-idle-timer-delay' is not dependent on the file size."
326 :type 'number
327 :group 'js2-mode)
328
329 (defcustom js2-concat-multiline-strings t
330 "When non-nil, `js2-line-break' in mid-string will make it a
331 string concatenation. When `eol', the '+' will be inserted at the
332 end of the line, otherwise, at the beginning of the next line."
333 :type '(choice (const t) (const eol) (const nil))
334 :group 'js2-mode)
335
336 (defcustom js2-mode-show-parse-errors t
337 "True to highlight parse errors."
338 :type 'boolean
339 :group 'js2-mode)
340
341 (defcustom js2-mode-show-strict-warnings t
342 "Non-nil to emit Ecma strict-mode warnings.
343 Some of the warnings can be individually disabled by other flags,
344 even if this flag is non-nil."
345 :type 'boolean
346 :group 'js2-mode)
347
348 (defcustom js2-strict-trailing-comma-warning t
349 "Non-nil to warn about trailing commas in array literals.
350 Ecma-262-5.1 allows them, but older versions of IE raise an error."
351 :type 'boolean
352 :group 'js2-mode)
353
354 (defcustom js2-strict-missing-semi-warning t
355 "Non-nil to warn about semicolon auto-insertion after statement.
356 Technically this is legal per Ecma-262, but some style guides disallow
357 depending on it."
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-missing-semi-one-line-override nil
362 "Non-nil to permit missing semicolons in one-line functions.
363 In one-liner functions such as `function identity(x) {return x}'
364 people often omit the semicolon for a cleaner look. If you are
365 such a person, you can suppress the missing-semicolon warning
366 by setting this variable to t."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-strict-inconsistent-return-warning t
371 "Non-nil to warn about mixing returns with value-returns.
372 It's perfectly legal to have a `return' and a `return foo' in the
373 same function, but it's often an indicator of a bug, and it also
374 interferes with type inference (in systems that support it.)"
375 :type 'boolean
376 :group 'js2-mode)
377
378 (defcustom js2-strict-cond-assign-warning t
379 "Non-nil to warn about expressions like if (a = b).
380 This often should have been '==' instead of '='. If the warning
381 is enabled, you can suppress it on a per-expression basis by
382 parenthesizing the expression, e.g. if ((a = b)) ..."
383 :type 'boolean
384 :group 'js2-mode)
385
386 (defcustom js2-strict-var-redeclaration-warning t
387 "Non-nil to warn about redeclaring variables in a script or function."
388 :type 'boolean
389 :group 'js2-mode)
390
391 (defcustom js2-strict-var-hides-function-arg-warning t
392 "Non-nil to warn about a var decl hiding a function argument."
393 :type 'boolean
394 :group 'js2-mode)
395
396 (defcustom js2-skip-preprocessor-directives nil
397 "Non-nil to treat lines beginning with # as comments.
398 Useful for viewing Mozilla JavaScript source code."
399 :type 'boolean
400 :group 'js2-mode)
401
402 (defcustom js2-language-version 200
403 "Configures what JavaScript language version to recognize.
404 Currently versions 150, 160, 170, 180 and 200 are supported,
405 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
406 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
407 yield, and Array comprehensions, and 1.8 adds function closures."
408 :type 'integer
409 :group 'js2-mode)
410
411 (defcustom js2-instanceof-has-side-effects nil
412 "If non-nil, treats the instanceof operator as having side effects.
413 This is useful for xulrunner apps."
414 :type 'boolean
415 :group 'js2-mode)
416
417 (defcustom js2-move-point-on-right-click t
418 "Non-nil to move insertion point when you right-click.
419 This makes right-click context menu behavior a bit more intuitive,
420 since menu operations generally apply to the point. The exception
421 is if there is a region selection, in which case the point does -not-
422 move, so cut/copy/paste can work properly.
423
424 Note that IntelliJ moves the point, and Eclipse leaves it alone,
425 so this behavior is customizable."
426 :group 'js2-mode
427 :type 'boolean)
428
429 (defcustom js2-allow-rhino-new-expr-initializer t
430 "Non-nil to support a Rhino's experimental syntactic construct.
431
432 Rhino supports the ability to follow a `new' expression with an object
433 literal, which is used to set additional properties on the new object
434 after calling its constructor. Syntax:
435
436 new <expr> [ ( arglist ) ] [initializer]
437
438 Hence, this expression:
439
440 new Object {a: 1, b: 2}
441
442 results in an Object with properties a=1 and b=2. This syntax is
443 apparently not configurable in Rhino - it's currently always enabled,
444 as of Rhino version 1.7R2."
445 :type 'boolean
446 :group 'js2-mode)
447
448 (defcustom js2-allow-member-expr-as-function-name nil
449 "Non-nil to support experimental Rhino syntax for function names.
450
451 Rhino supports an experimental syntax configured via the Rhino Context
452 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
453
454 function <member-expr> ( [ arg-list ] ) { <body> }
455
456 Where member-expr is a non-parenthesized 'member expression', which
457 is anything at the grammar level of a new-expression or lower, meaning
458 any expression that does not involve infix or unary operators.
459
460 When <member-expr> is not a simple identifier, then it is syntactic
461 sugar for assigning the anonymous function to the <member-expr>. Hence,
462 this code:
463
464 function a.b().c[2] (x, y) { ... }
465
466 is rewritten as:
467
468 a.b().c[2] = function(x, y) {...}
469
470 which doesn't seem particularly useful, but Rhino permits it."
471 :type 'boolean
472 :group 'js2-mode)
473
474 ;; scanner variables
475
476 (defmacro js2-deflocal (name value &optional comment)
477 "Define a buffer-local variable NAME with VALUE and COMMENT."
478 (declare (debug defvar) (doc-string 3))
479 `(progn
480 (defvar ,name ,value ,comment)
481 (make-variable-buffer-local ',name)))
482
483 (defvar js2-EOF_CHAR -1
484 "Represents end of stream. Distinct from js2-EOF token type.")
485
486 ;; I originally used symbols to represent tokens, but Rhino uses
487 ;; ints and then sets various flag bits in them, so ints it is.
488 ;; The upshot is that we need a `js2-' prefix in front of each name.
489 (defvar js2-ERROR -1)
490 (defvar js2-EOF 0)
491 (defvar js2-EOL 1)
492 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
493 (defvar js2-LEAVEWITH 3)
494 (defvar js2-RETURN 4)
495 (defvar js2-GOTO 5)
496 (defvar js2-IFEQ 6)
497 (defvar js2-IFNE 7)
498 (defvar js2-SETNAME 8)
499 (defvar js2-BITOR 9)
500 (defvar js2-BITXOR 10)
501 (defvar js2-BITAND 11)
502 (defvar js2-EQ 12)
503 (defvar js2-NE 13)
504 (defvar js2-LT 14)
505 (defvar js2-LE 15)
506 (defvar js2-GT 16)
507 (defvar js2-GE 17)
508 (defvar js2-LSH 18)
509 (defvar js2-RSH 19)
510 (defvar js2-URSH 20)
511 (defvar js2-ADD 21) ; infix plus
512 (defvar js2-SUB 22) ; infix minus
513 (defvar js2-MUL 23)
514 (defvar js2-DIV 24)
515 (defvar js2-MOD 25)
516 (defvar js2-NOT 26)
517 (defvar js2-BITNOT 27)
518 (defvar js2-POS 28) ; unary plus
519 (defvar js2-NEG 29) ; unary minus
520 (defvar js2-NEW 30)
521 (defvar js2-DELPROP 31)
522 (defvar js2-TYPEOF 32)
523 (defvar js2-GETPROP 33)
524 (defvar js2-GETPROPNOWARN 34)
525 (defvar js2-SETPROP 35)
526 (defvar js2-GETELEM 36)
527 (defvar js2-SETELEM 37)
528 (defvar js2-CALL 38)
529 (defvar js2-NAME 39) ; an identifier
530 (defvar js2-NUMBER 40)
531 (defvar js2-STRING 41)
532 (defvar js2-NULL 42)
533 (defvar js2-THIS 43)
534 (defvar js2-FALSE 44)
535 (defvar js2-TRUE 45)
536 (defvar js2-SHEQ 46) ; shallow equality (===)
537 (defvar js2-SHNE 47) ; shallow inequality (!==)
538 (defvar js2-REGEXP 48)
539 (defvar js2-BINDNAME 49)
540 (defvar js2-THROW 50)
541 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
542 (defvar js2-IN 52)
543 (defvar js2-INSTANCEOF 53)
544 (defvar js2-LOCAL_LOAD 54)
545 (defvar js2-GETVAR 55)
546 (defvar js2-SETVAR 56)
547 (defvar js2-CATCH_SCOPE 57)
548 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
549 (defvar js2-ENUM_INIT_VALUES 59)
550 (defvar js2-ENUM_INIT_ARRAY 60)
551 (defvar js2-ENUM_NEXT 61)
552 (defvar js2-ENUM_ID 62)
553 (defvar js2-THISFN 63)
554 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
555 (defvar js2-ARRAYLIT 65) ; array literal
556 (defvar js2-OBJECTLIT 66) ; object literal
557 (defvar js2-GET_REF 67) ; *reference
558 (defvar js2-SET_REF 68) ; *reference = something
559 (defvar js2-DEL_REF 69) ; delete reference
560 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
561 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
562 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
563
564 ;; XML support
565 (defvar js2-DEFAULTNAMESPACE 73)
566 (defvar js2-ESCXMLATTR 74)
567 (defvar js2-ESCXMLTEXT 75)
568 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
569 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
570 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
571 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
572
573 (defvar js2-first-bytecode js2-ENTERWITH)
574 (defvar js2-last-bytecode js2-REF_NS_NAME)
575
576 (defvar js2-TRY 80)
577 (defvar js2-SEMI 81) ; semicolon
578 (defvar js2-LB 82) ; left and right brackets
579 (defvar js2-RB 83)
580 (defvar js2-LC 84) ; left and right curly-braces
581 (defvar js2-RC 85)
582 (defvar js2-LP 86) ; left and right parens
583 (defvar js2-RP 87)
584 (defvar js2-COMMA 88) ; comma operator
585
586 (defvar js2-ASSIGN 89) ; simple assignment (=)
587 (defvar js2-ASSIGN_BITOR 90) ; |=
588 (defvar js2-ASSIGN_BITXOR 91) ; ^=
589 (defvar js2-ASSIGN_BITAND 92) ; &=
590 (defvar js2-ASSIGN_LSH 93) ; <<=
591 (defvar js2-ASSIGN_RSH 94) ; >>=
592 (defvar js2-ASSIGN_URSH 95) ; >>>=
593 (defvar js2-ASSIGN_ADD 96) ; +=
594 (defvar js2-ASSIGN_SUB 97) ; -=
595 (defvar js2-ASSIGN_MUL 98) ; *=
596 (defvar js2-ASSIGN_DIV 99) ; /=
597 (defvar js2-ASSIGN_MOD 100) ; %=
598
599 (defvar js2-first-assign js2-ASSIGN)
600 (defvar js2-last-assign js2-ASSIGN_MOD)
601
602 (defvar js2-HOOK 101) ; conditional (?:)
603 (defvar js2-COLON 102)
604 (defvar js2-OR 103) ; logical or (||)
605 (defvar js2-AND 104) ; logical and (&&)
606 (defvar js2-INC 105) ; increment/decrement (++ --)
607 (defvar js2-DEC 106)
608 (defvar js2-DOT 107) ; member operator (.)
609 (defvar js2-FUNCTION 108) ; function keyword
610 (defvar js2-EXPORT 109) ; export keyword
611 (defvar js2-IMPORT 110) ; import keyword
612 (defvar js2-IF 111) ; if keyword
613 (defvar js2-ELSE 112) ; else keyword
614 (defvar js2-SWITCH 113) ; switch keyword
615 (defvar js2-CASE 114) ; case keyword
616 (defvar js2-DEFAULT 115) ; default keyword
617 (defvar js2-WHILE 116) ; while keyword
618 (defvar js2-DO 117) ; do keyword
619 (defvar js2-FOR 118) ; for keyword
620 (defvar js2-BREAK 119) ; break keyword
621 (defvar js2-CONTINUE 120) ; continue keyword
622 (defvar js2-VAR 121) ; var keyword
623 (defvar js2-WITH 122) ; with keyword
624 (defvar js2-CATCH 123) ; catch keyword
625 (defvar js2-FINALLY 124) ; finally keyword
626 (defvar js2-VOID 125) ; void keyword
627 (defvar js2-RESERVED 126) ; reserved keywords
628
629 (defvar js2-EMPTY 127)
630
631 ;; Types used for the parse tree - never returned by scanner.
632
633 (defvar js2-BLOCK 128) ; statement block
634 (defvar js2-LABEL 129) ; label
635 (defvar js2-TARGET 130)
636 (defvar js2-LOOP 131)
637 (defvar js2-EXPR_VOID 132) ; expression statement in functions
638 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
639 (defvar js2-JSR 134)
640 (defvar js2-SCRIPT 135) ; top-level node for entire script
641 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
642 (defvar js2-USE_STACK 137)
643 (defvar js2-SETPROP_OP 138) ; x.y op= something
644 (defvar js2-SETELEM_OP 139) ; x[y] op= something
645 (defvar js2-LOCAL_BLOCK 140)
646 (defvar js2-SET_REF_OP 141) ; *reference op= something
647
648 ;; For XML support:
649 (defvar js2-DOTDOT 142) ; member operator (..)
650 (defvar js2-COLONCOLON 143) ; namespace::name
651 (defvar js2-XML 144) ; XML type
652 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
653 (defvar js2-XMLATTR 146) ; @
654 (defvar js2-XMLEND 147)
655
656 ;; Optimizer-only tokens
657 (defvar js2-TO_OBJECT 148)
658 (defvar js2-TO_DOUBLE 149)
659
660 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
661 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
662 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
663 (defvar js2-CONST 153)
664 (defvar js2-SETCONST 154)
665 (defvar js2-SETCONSTVAR 155)
666 (defvar js2-ARRAYCOMP 156)
667 (defvar js2-LETEXPR 157)
668 (defvar js2-WITHEXPR 158)
669 (defvar js2-DEBUGGER 159)
670
671 (defvar js2-COMMENT 160)
672 (defvar js2-TRIPLEDOT 161) ; for rest parameter
673 (defvar js2-ARROW 162) ; function arrow (=>)
674 (defvar js2-CLASS 163)
675 (defvar js2-EXTENDS 164)
676 (defvar js2-SUPER 165)
677 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
678 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
679 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
680
681 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
682
683 (defconst js2-debug-print-trees nil)
684
685 ;; Rhino accepts any string or stream as input. Emacs character
686 ;; processing works best in buffers, so we'll assume the input is a
687 ;; buffer. JavaScript strings can be copied into temp buffers before
688 ;; scanning them.
689
690 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
691 ;; They're the Emacs equivalent of instance variables, more or less.
692
693 (js2-deflocal js2-ts-dirty-line nil
694 "Token stream buffer-local variable.
695 Indicates stuff other than whitespace since start of line.")
696
697 (js2-deflocal js2-ts-hit-eof nil
698 "Token stream buffer-local variable.")
699
700 ;; FIXME: Unused.
701 (js2-deflocal js2-ts-line-start 0
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-lineno 1
705 "Token stream buffer-local variable.")
706
707 ;; FIXME: Unused.
708 (js2-deflocal js2-ts-line-end-char -1
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
712 "Token stream buffer-local variable.
713 Current scan position.")
714
715 ;; FIXME: Unused.
716 (js2-deflocal js2-ts-is-xml-attribute nil
717 "Token stream buffer-local variable.")
718
719 (js2-deflocal js2-ts-xml-is-tag-content nil
720 "Token stream buffer-local variable.")
721
722 (js2-deflocal js2-ts-xml-open-tags-count 0
723 "Token stream buffer-local variable.")
724
725 (js2-deflocal js2-ts-string-buffer nil
726 "Token stream buffer-local variable.
727 List of chars built up while scanning various tokens.")
728
729 (cl-defstruct (js2-token
730 (:constructor nil)
731 (:constructor make-js2-token (beg)))
732 "Value returned from the token stream."
733 (type js2-EOF)
734 (beg 1)
735 (end -1)
736 (string "")
737 number
738 regexp-flags
739 comment-type
740 follows-eol-p)
741
742 ;; Have to call `js2-init-scanner' to initialize the values.
743 (js2-deflocal js2-ti-tokens nil)
744 (js2-deflocal js2-ti-tokens-cursor nil)
745 (js2-deflocal js2-ti-lookahead nil)
746
747 (cl-defstruct (js2-ts-state
748 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
749 (cursor js2-ts-cursor)
750 (tokens (copy-sequence js2-ti-tokens))
751 (tokens-cursor js2-ti-tokens-cursor)
752 (lookahead js2-ti-lookahead))))
753 lineno
754 cursor
755 tokens
756 tokens-cursor
757 lookahead)
758
759 ;;; Parser variables
760
761 (js2-deflocal js2-parsed-errors nil
762 "List of errors produced during scanning/parsing.")
763
764 (js2-deflocal js2-parsed-warnings nil
765 "List of warnings produced during scanning/parsing.")
766
767 (js2-deflocal js2-recover-from-parse-errors t
768 "Non-nil to continue parsing after a syntax error.
769
770 In recovery mode, the AST will be built in full, and any error
771 nodes will be flagged with appropriate error information. If
772 this flag is nil, a syntax error will result in an error being
773 signaled.
774
775 The variable is automatically buffer-local, because different
776 modes that use the parser will need different settings.")
777
778 (js2-deflocal js2-parse-hook nil
779 "List of callbacks for receiving parsing progress.")
780
781 (defvar js2-parse-finished-hook nil
782 "List of callbacks to notify when parsing finishes.
783 Not called if parsing was interrupted.")
784
785 (js2-deflocal js2-is-eval-code nil
786 "True if we're evaluating code in a string.
787 If non-nil, the tokenizer will record the token text, and the AST nodes
788 will record their source text. Off by default for IDE modes, since the
789 text is available in the buffer.")
790
791 (defvar js2-parse-ide-mode t
792 "Non-nil if the parser is being used for `js2-mode'.
793 If non-nil, the parser will set text properties for fontification
794 and the syntax table. The value should be nil when using the
795 parser as a frontend to an interpreter or byte compiler.")
796
797 ;;; Parser instance variables (buffer-local vars for js2-parse)
798
799 (defconst js2-ti-after-eol (lsh 1 16)
800 "Flag: first token of the source line.")
801
802 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
803
804 (js2-deflocal js2-compiler-generate-debug-info t)
805 (js2-deflocal js2-compiler-use-dynamic-scope nil)
806 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
807 (js2-deflocal js2-compiler-xml-available t)
808 (js2-deflocal js2-compiler-optimization-level 0)
809 (js2-deflocal js2-compiler-generating-source t)
810 (js2-deflocal js2-compiler-strict-mode nil)
811 (js2-deflocal js2-compiler-report-warning-as-error nil)
812 (js2-deflocal js2-compiler-generate-observer-count nil)
813 (js2-deflocal js2-compiler-activation-names nil)
814
815 ;; SKIP: sourceURI
816
817 ;; There's a compileFunction method in Context.java - may need it.
818 (js2-deflocal js2-called-by-compile-function nil
819 "True if `js2-parse' was called by `js2-compile-function'.
820 Will only be used when we finish implementing the interpreter.")
821
822 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
823
824 ;; SKIP: node factory - we're going to just call functions directly,
825 ;; and eventually go to a unified AST format.
826
827 (js2-deflocal js2-nesting-of-function 0)
828
829 (js2-deflocal js2-recorded-identifiers nil
830 "Tracks identifiers found during parsing.")
831
832 (js2-deflocal js2-is-in-destructuring nil
833 "True while parsing destructuring expression.")
834
835 (defcustom js2-global-externs nil
836 "A list of any extern names you'd like to consider always declared.
837 This list is global and is used by all `js2-mode' files.
838 You can create buffer-local externs list using `js2-additional-externs'.
839
840 There is also a buffer-local variable `js2-default-externs',
841 which is initialized by default to include the Ecma-262 externs
842 and the standard browser externs. The three lists are all
843 checked during highlighting."
844 :type 'list
845 :group 'js2-mode)
846
847 (js2-deflocal js2-default-externs nil
848 "Default external declarations.
849
850 These are currently only used for highlighting undeclared variables,
851 which only worries about top-level (unqualified) references.
852 As js2-mode's processing improves, we will flesh out this list.
853
854 The initial value is set to `js2-ecma-262-externs', unless some
855 of the `js2-include-?-externs' variables are set to t, in which
856 case the browser, Rhino and/or Node.js externs are also included.
857
858 See `js2-additional-externs' for more information.")
859
860 (defcustom js2-include-browser-externs t
861 "Non-nil to include browser externs in the master externs list.
862 If you work on JavaScript files that are not intended for browsers,
863 such as Mozilla Rhino server-side JavaScript, set this to nil.
864 See `js2-additional-externs' for more information about externs."
865 :type 'boolean
866 :group 'js2-mode)
867
868 (defcustom js2-include-rhino-externs nil
869 "Non-nil to include Mozilla Rhino externs in the master externs list.
870 See `js2-additional-externs' for more information about externs."
871 :type 'boolean
872 :group 'js2-mode)
873
874 (defcustom js2-include-node-externs nil
875 "Non-nil to include Node.js externs in the master externs list.
876 See `js2-additional-externs' for more information about externs."
877 :type 'boolean
878 :group 'js2-mode)
879
880 (js2-deflocal js2-additional-externs nil
881 "A buffer-local list of additional external declarations.
882 It is used to decide whether variables are considered undeclared
883 for purposes of highlighting.
884
885 Each entry is a Lisp string. The string should be the fully qualified
886 name of an external entity. All externs should be added to this list,
887 so that as js2-mode's processing improves it can take advantage of them.
888
889 You may want to declare your externs in three ways.
890 First, you can add externs that are valid for all your JavaScript files.
891 You should probably do this by adding them to `js2-global-externs', which
892 is a global list used for all js2-mode files.
893
894 Next, you can add a function to `js2-init-hook' that adds additional
895 externs appropriate for the specific file, perhaps based on its path.
896 These should go in `js2-additional-externs', which is buffer-local.
897
898 Third, you can use JSLint's global declaration, as long as
899 `js2-include-jslint-globals' is non-nil, which see.
900
901 Finally, you can add a function to `js2-post-parse-callbacks',
902 which is called after parsing completes, and `js2-mode-ast' is bound to
903 the root of the parse tree. At this stage you can set up an AST
904 node visitor using `js2-visit-ast' and examine the parse tree
905 for specific import patterns that may imply the existence of
906 other externs, possibly tied to your build system. These should also
907 be added to `js2-additional-externs'.
908
909 Your post-parse callback may of course also use the simpler and
910 faster (but perhaps less robust) approach of simply scanning the
911 buffer text for your imports, using regular expressions.")
912
913 ;; SKIP: decompiler
914 ;; SKIP: encoded-source
915
916 ;;; The following variables are per-function and should be saved/restored
917 ;;; during function parsing...
918
919 (js2-deflocal js2-current-script-or-fn nil)
920 (js2-deflocal js2-current-scope nil)
921 (js2-deflocal js2-nesting-of-with 0)
922 (js2-deflocal js2-label-set nil
923 "An alist mapping label names to nodes.")
924
925 (js2-deflocal js2-loop-set nil)
926 (js2-deflocal js2-loop-and-switch-set nil)
927 (js2-deflocal js2-has-return-value nil)
928 (js2-deflocal js2-end-flags 0)
929
930 ;;; ...end of per function variables
931
932 ;; These flags enumerate the possible ways a statement/function can
933 ;; terminate. These flags are used by endCheck() and by the Parser to
934 ;; detect inconsistent return usage.
935 ;;
936 ;; END_UNREACHED is reserved for code paths that are assumed to always be
937 ;; able to execute (example: throw, continue)
938 ;;
939 ;; END_DROPS_OFF indicates if the statement can transfer control to the
940 ;; next one. Statement such as return dont. A compound statement may have
941 ;; some branch that drops off control to the next statement.
942 ;;
943 ;; END_RETURNS indicates that the statement can return (without arguments)
944 ;; END_RETURNS_VALUE indicates that the statement can return a value.
945 ;;
946 ;; A compound statement such as
947 ;; if (condition) {
948 ;; return value;
949 ;; }
950 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
951
952 (defconst js2-end-unreached #x0)
953 (defconst js2-end-drops-off #x1)
954 (defconst js2-end-returns #x2)
955 (defconst js2-end-returns-value #x4)
956
957 ;; Rhino awkwardly passes a statementLabel parameter to the
958 ;; statementHelper() function, the main statement parser, which
959 ;; is then used by quite a few of the sub-parsers. We just make
960 ;; it a buffer-local variable and make sure it's cleaned up properly.
961 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
962
963 ;; Similarly, Rhino passes an inForInit boolean through about half
964 ;; the expression parsers. We use a dynamically-scoped variable,
965 ;; which makes it easier to funcall the parsers individually without
966 ;; worrying about whether they take the parameter or not.
967 (js2-deflocal js2-in-for-init nil)
968 (js2-deflocal js2-temp-name-counter 0)
969 (js2-deflocal js2-parse-stmt-count 0)
970
971 (defsubst js2-get-next-temp-name ()
972 (format "$%d" (cl-incf js2-temp-name-counter)))
973
974 (defvar js2-parse-interruptable-p t
975 "Set this to nil to force parse to continue until finished.
976 This will mostly be useful for interpreters.")
977
978 (defvar js2-statements-per-pause 50
979 "Pause after this many statements to check for user input.
980 If user input is pending, stop the parse and discard the tree.
981 This makes for a smoother user experience for large files.
982 You may have to wait a second or two before the highlighting
983 and error-reporting appear, but you can always type ahead if
984 you wish. This appears to be more or less how Eclipse, IntelliJ
985 and other editors work.")
986
987 (js2-deflocal js2-record-comments t
988 "Instructs the scanner to record comments in `js2-scanned-comments'.")
989
990 (js2-deflocal js2-scanned-comments nil
991 "List of all comments from the current parse.")
992
993 (defcustom js2-mode-indent-inhibit-undo nil
994 "Non-nil to disable collection of Undo information when indenting lines.
995 Some users have requested this behavior. It's nil by default because
996 other Emacs modes don't work this way."
997 :type 'boolean
998 :group 'js2-mode)
999
1000 (defcustom js2-mode-indent-ignore-first-tab nil
1001 "If non-nil, ignore first TAB keypress if we look indented properly.
1002 It's fairly common for users to navigate to an already-indented line
1003 and press TAB for reassurance that it's been indented. For this class
1004 of users, we want the first TAB press on a line to be ignored if the
1005 line is already indented to one of the precomputed alternatives.
1006
1007 This behavior is only partly implemented. If you TAB-indent a line,
1008 navigate to another line, and then navigate back, it fails to clear
1009 the last-indented variable, so it thinks you've already hit TAB once,
1010 and performs the indent. A full solution would involve getting on the
1011 point-motion hooks for the entire buffer. If we come across another
1012 use cases that requires watching point motion, I'll consider doing it.
1013
1014 If you set this variable to nil, then the TAB key will always change
1015 the indentation of the current line, if more than one alternative
1016 indentation spot exists."
1017 :type 'boolean
1018 :group 'js2-mode)
1019
1020 (defvar js2-indent-hook nil
1021 "A hook for user-defined indentation rules.
1022
1023 Functions on this hook should expect two arguments: (LIST INDEX)
1024 The LIST argument is the list of computed indentation points for
1025 the current line. INDEX is the list index of the indentation point
1026 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1027 indent function is not going to change the current line indentation.
1028
1029 If a hook function on this list returns a non-nil value, then
1030 `js2-bounce-indent' assumes the hook function has performed its own
1031 indentation, and will do nothing. If all hook functions on the list
1032 return nil, then `js2-bounce-indent' will use its computed indentation
1033 and reindent the line.
1034
1035 When hook functions on this hook list are called, the variable
1036 `js2-mode-ast' may or may not be set, depending on whether the
1037 parse tree is available. If the variable is nil, you can pass a
1038 callback to `js2-mode-wait-for-parse', and your callback will be
1039 called after the new parse tree is built. This can take some time
1040 in large files.")
1041
1042 (defface js2-warning
1043 `((((class color) (background light))
1044 (:underline "orange"))
1045 (((class color) (background dark))
1046 (:underline "orange"))
1047 (t (:underline t)))
1048 "Face for JavaScript warnings."
1049 :group 'js2-mode)
1050
1051 (defface js2-error
1052 `((((class color) (background light))
1053 (:foreground "red"))
1054 (((class color) (background dark))
1055 (:foreground "red"))
1056 (t (:foreground "red")))
1057 "Face for JavaScript errors."
1058 :group 'js2-mode)
1059
1060 (defface js2-jsdoc-tag
1061 '((t :foreground "SlateGray"))
1062 "Face used to highlight @whatever tags in jsdoc comments."
1063 :group 'js2-mode)
1064
1065 (defface js2-jsdoc-type
1066 '((t :foreground "SteelBlue"))
1067 "Face used to highlight {FooBar} types in jsdoc comments."
1068 :group 'js2-mode)
1069
1070 (defface js2-jsdoc-value
1071 '((t :foreground "PeachPuff3"))
1072 "Face used to highlight tag values in jsdoc comments."
1073 :group 'js2-mode)
1074
1075 (defface js2-function-param
1076 '((t :foreground "SeaGreen"))
1077 "Face used to highlight function parameters in javascript."
1078 :group 'js2-mode)
1079
1080 (defface js2-function-call
1081 '((t :inherit default))
1082 "Face used to highlight function name in calls."
1083 :group 'js2-mode)
1084
1085 (defface js2-instance-member
1086 '((t :foreground "DarkOrchid"))
1087 "Face used to highlight instance variables in javascript.
1088 Not currently used."
1089 :group 'js2-mode)
1090
1091 (defface js2-private-member
1092 '((t :foreground "PeachPuff3"))
1093 "Face used to highlight calls to private methods in javascript.
1094 Not currently used."
1095 :group 'js2-mode)
1096
1097 (defface js2-private-function-call
1098 '((t :foreground "goldenrod"))
1099 "Face used to highlight calls to private functions in javascript.
1100 Not currently used."
1101 :group 'js2-mode)
1102
1103 (defface js2-jsdoc-html-tag-name
1104 '((((class color) (min-colors 88) (background light))
1105 (:foreground "rosybrown"))
1106 (((class color) (min-colors 8) (background dark))
1107 (:foreground "yellow"))
1108 (((class color) (min-colors 8) (background light))
1109 (:foreground "magenta")))
1110 "Face used to highlight jsdoc html tag names"
1111 :group 'js2-mode)
1112
1113 (defface js2-jsdoc-html-tag-delimiter
1114 '((((class color) (min-colors 88) (background light))
1115 (:foreground "dark khaki"))
1116 (((class color) (min-colors 8) (background dark))
1117 (:foreground "green"))
1118 (((class color) (min-colors 8) (background light))
1119 (:foreground "green")))
1120 "Face used to highlight brackets in jsdoc html tags."
1121 :group 'js2-mode)
1122
1123 (defface js2-external-variable
1124 '((t :foreground "orange"))
1125 "Face used to highlight undeclared variable identifiers.")
1126
1127 (defcustom js2-init-hook nil
1128 "List of functions to be called after `js2-mode' or
1129 `js2-minor-mode' has initialized all variables, before parsing
1130 the buffer for the first time."
1131 :type 'hook
1132 :group 'js2-mode
1133 :version "20130608")
1134
1135 (defcustom js2-post-parse-callbacks nil
1136 "List of callback functions invoked after parsing finishes.
1137 Currently, the main use for this function is to add synthetic
1138 declarations to `js2-recorded-identifiers', which see."
1139 :type 'hook
1140 :group 'js2-mode)
1141
1142 (defcustom js2-build-imenu-callbacks nil
1143 "List of functions called during Imenu index generation.
1144 It's a good place to add additional entries to it, using
1145 `js2-record-imenu-entry'."
1146 :type 'hook
1147 :group 'js2-mode)
1148
1149 (defcustom js2-highlight-external-variables t
1150 "Non-nil to highlight undeclared variable identifiers.
1151 An undeclared variable is any variable not declared with var or let
1152 in the current scope or any lexically enclosing scope. If you use
1153 such a variable, then you are either expecting it to originate from
1154 another file, or you've got a potential bug."
1155 :type 'boolean
1156 :group 'js2-mode)
1157
1158 (defcustom js2-warn-about-unused-function-arguments nil
1159 "Non-nil to treat function arguments like declared-but-unused variables."
1160 :type 'booleanp
1161 :group 'js2-mode)
1162
1163 (defcustom js2-include-jslint-globals t
1164 "Non-nil to include the identifiers from JSLint global
1165 declaration (see http://www.jslint.com/lint.html#global) in the
1166 buffer-local externs list. See `js2-additional-externs' for more
1167 information."
1168 :type 'boolean
1169 :group 'js2-mode)
1170
1171 (defvar js2-mode-map
1172 (let ((map (make-sparse-keymap)))
1173 (define-key map [mouse-1] #'js2-mode-show-node)
1174 (define-key map (kbd "M-j") #'js2-line-break)
1175 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1176 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1177 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1178 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1179 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1180 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1181 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1182 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1183 (when js2-bounce-indent-p
1184 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1185
1186 (define-key map [menu-bar javascript]
1187 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1188
1189 (define-key map [menu-bar javascript customize-js2-mode]
1190 '(menu-item "Customize js2-mode" js2-mode-customize
1191 :help "Customize the behavior of this mode"))
1192
1193 (define-key map [menu-bar javascript js2-force-refresh]
1194 '(menu-item "Force buffer refresh" js2-mode-reset
1195 :help "Re-parse the buffer from scratch"))
1196
1197 (define-key map [menu-bar javascript separator-2]
1198 '("--"))
1199
1200 (define-key map [menu-bar javascript next-error]
1201 '(menu-item "Next warning or error" next-error
1202 :enabled (and js2-mode-ast
1203 (or (js2-ast-root-errors js2-mode-ast)
1204 (js2-ast-root-warnings js2-mode-ast)))
1205 :help "Move to next warning or error"))
1206
1207 (define-key map [menu-bar javascript display-errors]
1208 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1209 :visible (not js2-mode-show-parse-errors)
1210 :help "Turn on display of warnings and errors"))
1211
1212 (define-key map [menu-bar javascript hide-errors]
1213 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1214 :visible js2-mode-show-parse-errors
1215 :help "Turn off display of warnings and errors"))
1216
1217 (define-key map [menu-bar javascript separator-1]
1218 '("--"))
1219
1220 (define-key map [menu-bar javascript js2-toggle-function]
1221 '(menu-item "Show/collapse element" js2-mode-toggle-element
1222 :help "Hide or show function body or comment"))
1223
1224 (define-key map [menu-bar javascript show-comments]
1225 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1226 :visible js2-mode-comments-hidden
1227 :help "Expand all hidden block comments"))
1228
1229 (define-key map [menu-bar javascript hide-comments]
1230 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1231 :visible (not js2-mode-comments-hidden)
1232 :help "Show block comments as /*...*/"))
1233
1234 (define-key map [menu-bar javascript show-all-functions]
1235 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1236 :visible js2-mode-functions-hidden
1237 :help "Expand all hidden function bodies"))
1238
1239 (define-key map [menu-bar javascript hide-all-functions]
1240 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1241 :visible (not js2-mode-functions-hidden)
1242 :help "Show {...} for all top-level function bodies"))
1243
1244 map)
1245 "Keymap used in `js2-mode' buffers.")
1246
1247 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1248
1249 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1250 "Matches a //-comment line. Must be first non-whitespace on line.
1251 First match-group is the leading whitespace.")
1252
1253 (defvar js2-mode-hook nil)
1254
1255 (js2-deflocal js2-mode-ast nil "Private variable.")
1256 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1257 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1258 (js2-deflocal js2-mode-parsing nil "Private variable.")
1259 (js2-deflocal js2-mode-node-overlay nil)
1260
1261 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1262 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1263
1264 (js2-deflocal js2-mode-fontifications nil "Private variable")
1265 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1266 (js2-deflocal js2-imenu-recorder nil "Private variable")
1267 (js2-deflocal js2-imenu-function-map nil "Private variable")
1268
1269 (defvar js2-paragraph-start
1270 "\\(@[[:alpha:]]+\\>\\|$\\)")
1271
1272 ;; Note that we also set a 'c-in-sws text property in html comments,
1273 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1274 (defvar js2-syntactic-ws-start
1275 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1276
1277 (defvar js2-syntactic-ws-end
1278 "\\s \\|[\n\r/]\\|\\s!")
1279
1280 (defvar js2-syntactic-eol
1281 (concat "\\s *\\(/\\*[^*\n\r]*"
1282 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1283 "\\*+/\\s *\\)*"
1284 "\\(//\\|/\\*[^*\n\r]*"
1285 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1286 "\\|\\\\$\\|$\\)")
1287 "Copied from `java-mode'. Needed for some cc-engine functions.")
1288
1289 (defvar js2-comment-prefix-regexp
1290 "//+\\|\\**")
1291
1292 (defvar js2-comment-start-skip
1293 "\\(//+\\|/\\*+\\)\\s *")
1294
1295 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1296 "Non-nil to emit status messages during parsing.")
1297
1298 (defvar js2-mode-functions-hidden nil "Private variable.")
1299 (defvar js2-mode-comments-hidden nil "Private variable.")
1300
1301 (defvar js2-mode-syntax-table
1302 (let ((table (make-syntax-table)))
1303 (c-populate-syntax-table table)
1304 (modify-syntax-entry ?` "\"" table)
1305 table)
1306 "Syntax table used in `js2-mode' buffers.")
1307
1308 (defvar js2-mode-abbrev-table nil
1309 "Abbrev table in use in `js2-mode' buffers.")
1310 (define-abbrev-table 'js2-mode-abbrev-table ())
1311
1312 (defvar js2-mode-pending-parse-callbacks nil
1313 "List of functions waiting to be notified that parse is finished.")
1314
1315 (defvar js2-mode-last-indented-line -1)
1316
1317 ;;; Localizable error and warning messages
1318
1319 ;; Messages are copied from Rhino's Messages.properties.
1320 ;; Many of the Java-specific messages have been elided.
1321 ;; Add any js2-specific ones at the end, so we can keep
1322 ;; this file synced with changes to Rhino's.
1323
1324 (defvar js2-message-table
1325 (make-hash-table :test 'equal :size 250)
1326 "Contains localized messages for `js2-mode'.")
1327
1328 ;; TODO(stevey): construct this table at compile-time.
1329 (defmacro js2-msg (key &rest strings)
1330 `(puthash ,key (concat ,@strings)
1331 js2-message-table))
1332
1333 (defun js2-get-msg (msg-key)
1334 "Look up a localized message.
1335 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1336 the correct number of ARGS must be provided."
1337 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1338 (args (if (listp msg-key) (cdr msg-key)))
1339 (msg (gethash key js2-message-table)))
1340 (if msg
1341 (apply #'format msg args)
1342 key))) ; default to showing the key
1343
1344 (js2-msg "msg.dup.parms"
1345 "Duplicate parameter name '%s'.")
1346
1347 (js2-msg "msg.too.big.jump"
1348 "Program too complex: jump offset too big.")
1349
1350 (js2-msg "msg.too.big.index"
1351 "Program too complex: internal index exceeds 64K limit.")
1352
1353 (js2-msg "msg.while.compiling.fn"
1354 "Encountered code generation error while compiling function '%s': %s")
1355
1356 (js2-msg "msg.while.compiling.script"
1357 "Encountered code generation error while compiling script: %s")
1358
1359 ;; Context
1360 (js2-msg "msg.ctor.not.found"
1361 "Constructor for '%s' not found.")
1362
1363 (js2-msg "msg.not.ctor"
1364 "'%s' is not a constructor.")
1365
1366 ;; FunctionObject
1367 (js2-msg "msg.varargs.ctor"
1368 "Method or constructor '%s' must be static "
1369 "with the signature (Context cx, Object[] args, "
1370 "Function ctorObj, boolean inNewExpr) "
1371 "to define a variable arguments constructor.")
1372
1373 (js2-msg "msg.varargs.fun"
1374 "Method '%s' must be static with the signature "
1375 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1376 "to define a variable arguments function.")
1377
1378 (js2-msg "msg.incompat.call"
1379 "Method '%s' called on incompatible object.")
1380
1381 (js2-msg "msg.bad.parms"
1382 "Unsupported parameter type '%s' in method '%s'.")
1383
1384 (js2-msg "msg.bad.method.return"
1385 "Unsupported return type '%s' in method '%s'.")
1386
1387 (js2-msg "msg.bad.ctor.return"
1388 "Construction of objects of type '%s' is not supported.")
1389
1390 (js2-msg "msg.no.overload"
1391 "Method '%s' occurs multiple times in class '%s'.")
1392
1393 (js2-msg "msg.method.not.found"
1394 "Method '%s' not found in '%s'.")
1395
1396 ;; IRFactory
1397
1398 (js2-msg "msg.bad.for.in.lhs"
1399 "Invalid left-hand side of for..in loop.")
1400
1401 (js2-msg "msg.mult.index"
1402 "Only one variable allowed in for..in loop.")
1403
1404 (js2-msg "msg.bad.for.in.destruct"
1405 "Left hand side of for..in loop must be an array of "
1406 "length 2 to accept key/value pair.")
1407
1408 (js2-msg "msg.cant.convert"
1409 "Can't convert to type '%s'.")
1410
1411 (js2-msg "msg.bad.assign.left"
1412 "Invalid assignment left-hand side.")
1413
1414 (js2-msg "msg.bad.decr"
1415 "Invalid decrement operand.")
1416
1417 (js2-msg "msg.bad.incr"
1418 "Invalid increment operand.")
1419
1420 (js2-msg "msg.bad.yield"
1421 "yield must be in a function.")
1422
1423 (js2-msg "msg.yield.parenthesized"
1424 "yield expression must be parenthesized.")
1425
1426 ;; NativeGlobal
1427 (js2-msg "msg.cant.call.indirect"
1428 "Function '%s' must be called directly, and not by way of a "
1429 "function of another name.")
1430
1431 (js2-msg "msg.eval.nonstring"
1432 "Calling eval() with anything other than a primitive "
1433 "string value will simply return the value. "
1434 "Is this what you intended?")
1435
1436 (js2-msg "msg.eval.nonstring.strict"
1437 "Calling eval() with anything other than a primitive "
1438 "string value is not allowed in strict mode.")
1439
1440 (js2-msg "msg.bad.destruct.op"
1441 "Invalid destructuring assignment operator")
1442
1443 ;; NativeCall
1444 (js2-msg "msg.only.from.new"
1445 "'%s' may only be invoked from a `new' expression.")
1446
1447 (js2-msg "msg.deprec.ctor"
1448 "The '%s' constructor is deprecated.")
1449
1450 ;; NativeFunction
1451 (js2-msg "msg.no.function.ref.found"
1452 "no source found to decompile function reference %s")
1453
1454 (js2-msg "msg.arg.isnt.array"
1455 "second argument to Function.prototype.apply must be an array")
1456
1457 ;; NativeGlobal
1458 (js2-msg "msg.bad.esc.mask"
1459 "invalid string escape mask")
1460
1461 ;; NativeRegExp
1462 (js2-msg "msg.bad.quant"
1463 "Invalid quantifier %s")
1464
1465 (js2-msg "msg.overlarge.backref"
1466 "Overly large back reference %s")
1467
1468 (js2-msg "msg.overlarge.min"
1469 "Overly large minimum %s")
1470
1471 (js2-msg "msg.overlarge.max"
1472 "Overly large maximum %s")
1473
1474 (js2-msg "msg.zero.quant"
1475 "Zero quantifier %s")
1476
1477 (js2-msg "msg.max.lt.min"
1478 "Maximum %s less than minimum")
1479
1480 (js2-msg "msg.unterm.quant"
1481 "Unterminated quantifier %s")
1482
1483 (js2-msg "msg.unterm.paren"
1484 "Unterminated parenthetical %s")
1485
1486 (js2-msg "msg.unterm.class"
1487 "Unterminated character class %s")
1488
1489 (js2-msg "msg.bad.range"
1490 "Invalid range in character class.")
1491
1492 (js2-msg "msg.trail.backslash"
1493 "Trailing \\ in regular expression.")
1494
1495 (js2-msg "msg.re.unmatched.right.paren"
1496 "unmatched ) in regular expression.")
1497
1498 (js2-msg "msg.no.regexp"
1499 "Regular expressions are not available.")
1500
1501 (js2-msg "msg.bad.backref"
1502 "back-reference exceeds number of capturing parentheses.")
1503
1504 (js2-msg "msg.bad.regexp.compile"
1505 "Only one argument may be specified if the first "
1506 "argument to RegExp.prototype.compile is a RegExp object.")
1507
1508 ;; Parser
1509 (js2-msg "msg.got.syntax.errors"
1510 "Compilation produced %s syntax errors.")
1511
1512 (js2-msg "msg.var.redecl"
1513 "TypeError: redeclaration of var %s.")
1514
1515 (js2-msg "msg.const.redecl"
1516 "TypeError: redeclaration of const %s.")
1517
1518 (js2-msg "msg.let.redecl"
1519 "TypeError: redeclaration of variable %s.")
1520
1521 (js2-msg "msg.parm.redecl"
1522 "TypeError: redeclaration of formal parameter %s.")
1523
1524 (js2-msg "msg.fn.redecl"
1525 "TypeError: redeclaration of function %s.")
1526
1527 (js2-msg "msg.let.decl.not.in.block"
1528 "SyntaxError: let declaration not directly within block")
1529
1530 (js2-msg "msg.mod.import.decl.at.top.level"
1531 "SyntaxError: import declarations may only appear at the top level")
1532
1533 (js2-msg "msg.mod.as.after.reserved.word"
1534 "SyntaxError: missing keyword 'as' after reserved word %s")
1535
1536 (js2-msg "msg.mod.rc.after.import.spec.list"
1537 "SyntaxError: missing '}' after module specifier list")
1538
1539 (js2-msg "msg.mod.from.after.import.spec.set"
1540 "SyntaxError: missing keyword 'from' after import specifier set")
1541
1542 (js2-msg "msg.mod.declaration.after.import"
1543 "SyntaxError: missing declaration after 'import' keyword")
1544
1545 (js2-msg "msg.mod.spec.after.from"
1546 "SyntaxError: missing module specifier after 'from' keyword")
1547
1548 (js2-msg "msg.mod.export.decl.at.top.level"
1549 "SyntaxError: export declarations may only appear at top level")
1550
1551 (js2-msg "msg.mod.rc.after.export.spec.list"
1552 "SyntaxError: missing '}' after export specifier list")
1553
1554 ;; NodeTransformer
1555 (js2-msg "msg.dup.label"
1556 "duplicated label")
1557
1558 (js2-msg "msg.undef.label"
1559 "undefined label")
1560
1561 (js2-msg "msg.bad.break"
1562 "unlabelled break must be inside loop or switch")
1563
1564 (js2-msg "msg.continue.outside"
1565 "continue must be inside loop")
1566
1567 (js2-msg "msg.continue.nonloop"
1568 "continue can only use labels of iteration statements")
1569
1570 (js2-msg "msg.bad.throw.eol"
1571 "Line terminator is not allowed between the throw "
1572 "keyword and throw expression.")
1573
1574 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1575 "function statement requires a name")
1576
1577 (js2-msg "msg.no.paren.parms"
1578 "missing ( before function parameters.")
1579
1580 (js2-msg "msg.no.parm"
1581 "missing formal parameter")
1582
1583 (js2-msg "msg.no.paren.after.parms"
1584 "missing ) after formal parameters")
1585
1586 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1587 "parameter without default follows parameter with default")
1588
1589 (js2-msg "msg.param.after.rest" ; added by js2-mode
1590 "parameter after rest parameter")
1591
1592 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1593 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1594
1595 (js2-msg "msg.no.brace.body"
1596 "missing '{' before function body")
1597
1598 (js2-msg "msg.no.brace.after.body"
1599 "missing } after function body")
1600
1601 (js2-msg "msg.no.paren.cond"
1602 "missing ( before condition")
1603
1604 (js2-msg "msg.no.paren.after.cond"
1605 "missing ) after condition")
1606
1607 (js2-msg "msg.no.semi.stmt"
1608 "missing ; before statement")
1609
1610 (js2-msg "msg.missing.semi"
1611 "missing ; after statement")
1612
1613 (js2-msg "msg.no.name.after.dot"
1614 "missing name after . operator")
1615
1616 (js2-msg "msg.no.name.after.coloncolon"
1617 "missing name after :: operator")
1618
1619 (js2-msg "msg.no.name.after.dotdot"
1620 "missing name after .. operator")
1621
1622 (js2-msg "msg.no.name.after.xmlAttr"
1623 "missing name after .@")
1624
1625 (js2-msg "msg.no.bracket.index"
1626 "missing ] in index expression")
1627
1628 (js2-msg "msg.no.paren.switch"
1629 "missing ( before switch expression")
1630
1631 (js2-msg "msg.no.paren.after.switch"
1632 "missing ) after switch expression")
1633
1634 (js2-msg "msg.no.brace.switch"
1635 "missing '{' before switch body")
1636
1637 (js2-msg "msg.bad.switch"
1638 "invalid switch statement")
1639
1640 (js2-msg "msg.no.colon.case"
1641 "missing : after case expression")
1642
1643 (js2-msg "msg.double.switch.default"
1644 "double default label in the switch statement")
1645
1646 (js2-msg "msg.no.while.do"
1647 "missing while after do-loop body")
1648
1649 (js2-msg "msg.no.paren.for"
1650 "missing ( after for")
1651
1652 (js2-msg "msg.no.semi.for"
1653 "missing ; after for-loop initializer")
1654
1655 (js2-msg "msg.no.semi.for.cond"
1656 "missing ; after for-loop condition")
1657
1658 (js2-msg "msg.in.after.for.name"
1659 "missing in or of after for")
1660
1661 (js2-msg "msg.no.paren.for.ctrl"
1662 "missing ) after for-loop control")
1663
1664 (js2-msg "msg.no.paren.with"
1665 "missing ( before with-statement object")
1666
1667 (js2-msg "msg.no.paren.after.with"
1668 "missing ) after with-statement object")
1669
1670 (js2-msg "msg.no.paren.after.let"
1671 "missing ( after let")
1672
1673 (js2-msg "msg.no.paren.let"
1674 "missing ) after variable list")
1675
1676 (js2-msg "msg.no.curly.let"
1677 "missing } after let statement")
1678
1679 (js2-msg "msg.bad.return"
1680 "invalid return")
1681
1682 (js2-msg "msg.no.brace.block"
1683 "missing } in compound statement")
1684
1685 (js2-msg "msg.bad.label"
1686 "invalid label")
1687
1688 (js2-msg "msg.bad.var"
1689 "missing variable name")
1690
1691 (js2-msg "msg.bad.var.init"
1692 "invalid variable initialization")
1693
1694 (js2-msg "msg.no.colon.cond"
1695 "missing : in conditional expression")
1696
1697 (js2-msg "msg.no.paren.arg"
1698 "missing ) after argument list")
1699
1700 (js2-msg "msg.no.bracket.arg"
1701 "missing ] after element list")
1702
1703 (js2-msg "msg.bad.prop"
1704 "invalid property id")
1705
1706 (js2-msg "msg.no.colon.prop"
1707 "missing : after property id")
1708
1709 (js2-msg "msg.no.brace.prop"
1710 "missing } after property list")
1711
1712 (js2-msg "msg.no.paren"
1713 "missing ) in parenthetical")
1714
1715 (js2-msg "msg.reserved.id"
1716 "'%s' is a reserved identifier")
1717
1718 (js2-msg "msg.no.paren.catch"
1719 "missing ( before catch-block condition")
1720
1721 (js2-msg "msg.bad.catchcond"
1722 "invalid catch block condition")
1723
1724 (js2-msg "msg.catch.unreachable"
1725 "any catch clauses following an unqualified catch are unreachable")
1726
1727 (js2-msg "msg.no.brace.try"
1728 "missing '{' before try block")
1729
1730 (js2-msg "msg.no.brace.catchblock"
1731 "missing '{' before catch-block body")
1732
1733 (js2-msg "msg.try.no.catchfinally"
1734 "'try' without 'catch' or 'finally'")
1735
1736 (js2-msg "msg.no.return.value"
1737 "function %s does not always return a value")
1738
1739 (js2-msg "msg.anon.no.return.value"
1740 "anonymous function does not always return a value")
1741
1742 (js2-msg "msg.return.inconsistent"
1743 "return statement is inconsistent with previous usage")
1744
1745 (js2-msg "msg.generator.returns"
1746 "TypeError: legacy generator function '%s' returns a value")
1747
1748 (js2-msg "msg.anon.generator.returns"
1749 "TypeError: anonymous legacy generator function returns a value")
1750
1751 (js2-msg "msg.syntax"
1752 "syntax error")
1753
1754 (js2-msg "msg.unexpected.eof"
1755 "Unexpected end of file")
1756
1757 (js2-msg "msg.XML.bad.form"
1758 "illegally formed XML syntax")
1759
1760 (js2-msg "msg.XML.not.available"
1761 "XML runtime not available")
1762
1763 (js2-msg "msg.too.deep.parser.recursion"
1764 "Too deep recursion while parsing")
1765
1766 (js2-msg "msg.no.side.effects"
1767 "Code has no side effects")
1768
1769 (js2-msg "msg.extra.trailing.comma"
1770 "Trailing comma is not supported in some browsers")
1771
1772 (js2-msg "msg.array.trailing.comma"
1773 "Trailing comma yields different behavior across browsers")
1774
1775 (js2-msg "msg.equal.as.assign"
1776 (concat "Test for equality (==) mistyped as assignment (=)?"
1777 " (parenthesize to suppress warning)"))
1778
1779 (js2-msg "msg.var.hides.arg"
1780 "Variable %s hides argument")
1781
1782 (js2-msg "msg.destruct.assign.no.init"
1783 "Missing = in destructuring declaration")
1784
1785 ;; ScriptRuntime
1786 (js2-msg "msg.no.properties"
1787 "%s has no properties.")
1788
1789 (js2-msg "msg.invalid.iterator"
1790 "Invalid iterator value")
1791
1792 (js2-msg "msg.iterator.primitive"
1793 "__iterator__ returned a primitive value")
1794
1795 (js2-msg "msg.assn.create.strict"
1796 "Assignment to undeclared variable %s")
1797
1798 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1799 "Undeclared variable or function '%s'")
1800
1801 (js2-msg "msg.unused.variable" ; added by js2-mode
1802 "Unused variable or function '%s'")
1803
1804 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1805 "Variable '%s' referenced but never initialized")
1806
1807 (js2-msg "msg.ref.undefined.prop"
1808 "Reference to undefined property '%s'")
1809
1810 (js2-msg "msg.prop.not.found"
1811 "Property %s not found.")
1812
1813 (js2-msg "msg.invalid.type"
1814 "Invalid JavaScript value of type %s")
1815
1816 (js2-msg "msg.primitive.expected"
1817 "Primitive type expected (had %s instead)")
1818
1819 (js2-msg "msg.namespace.expected"
1820 "Namespace object expected to left of :: (found %s instead)")
1821
1822 (js2-msg "msg.null.to.object"
1823 "Cannot convert null to an object.")
1824
1825 (js2-msg "msg.undef.to.object"
1826 "Cannot convert undefined to an object.")
1827
1828 (js2-msg "msg.cyclic.value"
1829 "Cyclic %s value not allowed.")
1830
1831 (js2-msg "msg.is.not.defined"
1832 "'%s' is not defined.")
1833
1834 (js2-msg "msg.undef.prop.read"
1835 "Cannot read property '%s' from %s")
1836
1837 (js2-msg "msg.undef.prop.write"
1838 "Cannot set property '%s' of %s to '%s'")
1839
1840 (js2-msg "msg.undef.prop.delete"
1841 "Cannot delete property '%s' of %s")
1842
1843 (js2-msg "msg.undef.method.call"
1844 "Cannot call method '%s' of %s")
1845
1846 (js2-msg "msg.undef.with"
1847 "Cannot apply 'with' to %s")
1848
1849 (js2-msg "msg.isnt.function"
1850 "%s is not a function, it is %s.")
1851
1852 (js2-msg "msg.isnt.function.in"
1853 "Cannot call property %s in object %s. "
1854 "It is not a function, it is '%s'.")
1855
1856 (js2-msg "msg.function.not.found"
1857 "Cannot find function %s.")
1858
1859 (js2-msg "msg.function.not.found.in"
1860 "Cannot find function %s in object %s.")
1861
1862 (js2-msg "msg.isnt.xml.object"
1863 "%s is not an xml object.")
1864
1865 (js2-msg "msg.no.ref.to.get"
1866 "%s is not a reference to read reference value.")
1867
1868 (js2-msg "msg.no.ref.to.set"
1869 "%s is not a reference to set reference value to %s.")
1870
1871 (js2-msg "msg.no.ref.from.function"
1872 "Function %s can not be used as the left-hand "
1873 "side of assignment or as an operand of ++ or -- operator.")
1874
1875 (js2-msg "msg.bad.default.value"
1876 "Object's getDefaultValue() method returned an object.")
1877
1878 (js2-msg "msg.instanceof.not.object"
1879 "Can't use instanceof on a non-object.")
1880
1881 (js2-msg "msg.instanceof.bad.prototype"
1882 "'prototype' property of %s is not an object.")
1883
1884 (js2-msg "msg.bad.radix"
1885 "illegal radix %s.")
1886
1887 ;; ScriptableObject
1888 (js2-msg "msg.default.value"
1889 "Cannot find default value for object.")
1890
1891 (js2-msg "msg.zero.arg.ctor"
1892 "Cannot load class '%s' which has no zero-parameter constructor.")
1893
1894 (js2-msg "msg.ctor.multiple.parms"
1895 "Can't define constructor or class %s since more than "
1896 "one constructor has multiple parameters.")
1897
1898 (js2-msg "msg.extend.scriptable"
1899 "%s must extend ScriptableObject in order to define property %s.")
1900
1901 (js2-msg "msg.bad.getter.parms"
1902 "In order to define a property, getter %s must have zero "
1903 "parameters or a single ScriptableObject parameter.")
1904
1905 (js2-msg "msg.obj.getter.parms"
1906 "Expected static or delegated getter %s to take "
1907 "a ScriptableObject parameter.")
1908
1909 (js2-msg "msg.getter.static"
1910 "Getter and setter must both be static or neither be static.")
1911
1912 (js2-msg "msg.setter.return"
1913 "Setter must have void return type: %s")
1914
1915 (js2-msg "msg.setter2.parms"
1916 "Two-parameter setter must take a ScriptableObject as "
1917 "its first parameter.")
1918
1919 (js2-msg "msg.setter1.parms"
1920 "Expected single parameter setter for %s")
1921
1922 (js2-msg "msg.setter2.expected"
1923 "Expected static or delegated setter %s to take two parameters.")
1924
1925 (js2-msg "msg.setter.parms"
1926 "Expected either one or two parameters for setter.")
1927
1928 (js2-msg "msg.setter.bad.type"
1929 "Unsupported parameter type '%s' in setter '%s'.")
1930
1931 (js2-msg "msg.add.sealed"
1932 "Cannot add a property to a sealed object: %s.")
1933
1934 (js2-msg "msg.remove.sealed"
1935 "Cannot remove a property from a sealed object: %s.")
1936
1937 (js2-msg "msg.modify.sealed"
1938 "Cannot modify a property of a sealed object: %s.")
1939
1940 (js2-msg "msg.modify.readonly"
1941 "Cannot modify readonly property: %s.")
1942
1943 ;; TokenStream
1944 (js2-msg "msg.missing.exponent"
1945 "missing exponent")
1946
1947 (js2-msg "msg.caught.nfe"
1948 "number format error")
1949
1950 (js2-msg "msg.unterminated.string.lit"
1951 "unterminated string literal")
1952
1953 (js2-msg "msg.unterminated.comment"
1954 "unterminated comment")
1955
1956 (js2-msg "msg.unterminated.re.lit"
1957 "unterminated regular expression literal")
1958
1959 (js2-msg "msg.invalid.re.flag"
1960 "invalid flag after regular expression")
1961
1962 (js2-msg "msg.no.re.input.for"
1963 "no input for %s")
1964
1965 (js2-msg "msg.illegal.character"
1966 "illegal character")
1967
1968 (js2-msg "msg.invalid.escape"
1969 "invalid Unicode escape sequence")
1970
1971 (js2-msg "msg.bad.namespace"
1972 "not a valid default namespace statement. "
1973 "Syntax is: default xml namespace = EXPRESSION;")
1974
1975 ;; TokensStream warnings
1976 (js2-msg "msg.bad.octal.literal"
1977 "illegal octal literal digit %s; "
1978 "interpreting it as a decimal digit")
1979
1980 (js2-msg "msg.missing.hex.digits"
1981 "missing hexadecimal digits after '0x'")
1982
1983 (js2-msg "msg.missing.binary.digits"
1984 "missing binary digits after '0b'")
1985
1986 (js2-msg "msg.missing.octal.digits"
1987 "missing octal digits after '0o'")
1988
1989 (js2-msg "msg.script.is.not.constructor"
1990 "Script objects are not constructors.")
1991
1992 ;; Arrays
1993 (js2-msg "msg.arraylength.bad"
1994 "Inappropriate array length.")
1995
1996 ;; Arrays
1997 (js2-msg "msg.arraylength.too.big"
1998 "Array length %s exceeds supported capacity limit.")
1999
2000 ;; URI
2001 (js2-msg "msg.bad.uri"
2002 "Malformed URI sequence.")
2003
2004 ;; Number
2005 (js2-msg "msg.bad.precision"
2006 "Precision %s out of range.")
2007
2008 ;; NativeGenerator
2009 (js2-msg "msg.send.newborn"
2010 "Attempt to send value to newborn generator")
2011
2012 (js2-msg "msg.already.exec.gen"
2013 "Already executing generator")
2014
2015 (js2-msg "msg.StopIteration.invalid"
2016 "StopIteration may not be changed to an arbitrary object.")
2017
2018 ;; Interpreter
2019 (js2-msg "msg.yield.closing"
2020 "Yield from closing generator")
2021
2022 ;; Classes
2023 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
2024 "class statement requires a name")
2025
2026 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
2027 "unexpected ',' between class properties")
2028
2029 (js2-msg "msg.unexpected.static" ; added by js2-mode
2030 "unexpected 'static'")
2031
2032 (js2-msg "msg.missing.extends" ; added by js2-mode
2033 "name is required after extends")
2034
2035 (js2-msg "msg.no.brace.class" ; added by js2-mode
2036 "missing '{' before class body")
2037
2038 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2039 "missing ']' after computed property expression")
2040
2041 ;;; Tokens Buffer
2042
2043 (defconst js2-ti-max-lookahead 2)
2044 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2045
2046 (defun js2-new-token (offset)
2047 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2048 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2049 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2050 token))
2051
2052 (defsubst js2-current-token ()
2053 (aref js2-ti-tokens js2-ti-tokens-cursor))
2054
2055 (defsubst js2-current-token-string ()
2056 (js2-token-string (js2-current-token)))
2057
2058 (defsubst js2-current-token-type ()
2059 (js2-token-type (js2-current-token)))
2060
2061 (defsubst js2-current-token-beg ()
2062 (js2-token-beg (js2-current-token)))
2063
2064 (defsubst js2-current-token-end ()
2065 (js2-token-end (js2-current-token)))
2066
2067 (defun js2-current-token-len ()
2068 (let ((token (js2-current-token)))
2069 (- (js2-token-end token)
2070 (js2-token-beg token))))
2071
2072 (defun js2-ts-seek (state)
2073 (setq js2-ts-lineno (js2-ts-state-lineno state)
2074 js2-ts-cursor (js2-ts-state-cursor state)
2075 js2-ti-tokens (js2-ts-state-tokens state)
2076 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2077 js2-ti-lookahead (js2-ts-state-lookahead state)))
2078
2079 ;;; Utilities
2080
2081 (defun js2-delete-if (predicate list)
2082 "Remove all items satisfying PREDICATE in LIST."
2083 (cl-loop for item in list
2084 if (not (funcall predicate item))
2085 collect item))
2086
2087 (defun js2-position (element list)
2088 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2089 Returns nil if element is not found in the list."
2090 (let ((count 0)
2091 found)
2092 (while (and list (not found))
2093 (if (eq element (car list))
2094 (setq found t)
2095 (setq count (1+ count)
2096 list (cdr list))))
2097 (if found count)))
2098
2099 (defun js2-find-if (predicate list)
2100 "Find first item satisfying PREDICATE in LIST."
2101 (let (result)
2102 (while (and list (not result))
2103 (if (funcall predicate (car list))
2104 (setq result (car list)))
2105 (setq list (cdr list)))
2106 result))
2107
2108 (defmacro js2-time (form)
2109 "Evaluate FORM, discard result, and return elapsed time in sec."
2110 (declare (debug t))
2111 (let ((beg (make-symbol "--js2-time-beg--")))
2112 `(let ((,beg (current-time)))
2113 ,form
2114 (/ (truncate (* (- (float-time (current-time))
2115 (float-time ,beg))
2116 10000))
2117 10000.0))))
2118
2119 (defsubst js2-same-line (pos)
2120 "Return t if POS is on the same line as current point."
2121 (and (>= pos (point-at-bol))
2122 (<= pos (point-at-eol))))
2123
2124 (defun js2-code-bug ()
2125 "Signal an error when we encounter an unexpected code path."
2126 (error "failed assertion"))
2127
2128 (defsubst js2-record-text-property (beg end prop value)
2129 "Record a text property to set when parsing finishes."
2130 (push (list beg end prop value) js2-mode-deferred-properties))
2131
2132 ;; I'd like to associate errors with nodes, but for now the
2133 ;; easiest thing to do is get the context info from the last token.
2134 (defun js2-record-parse-error (msg &optional arg pos len)
2135 (push (list (list msg arg)
2136 (or pos (js2-current-token-beg))
2137 (or len (js2-current-token-len)))
2138 js2-parsed-errors))
2139
2140 (defun js2-report-error (msg &optional msg-arg pos len)
2141 "Signal a syntax error or record a parse error."
2142 (if js2-recover-from-parse-errors
2143 (js2-record-parse-error msg msg-arg pos len)
2144 (signal 'js2-syntax-error
2145 (list msg
2146 js2-ts-lineno
2147 (save-excursion
2148 (goto-char js2-ts-cursor)
2149 (current-column))
2150 js2-ts-hit-eof))))
2151
2152 (defun js2-report-warning (msg &optional msg-arg pos len face)
2153 (if js2-compiler-report-warning-as-error
2154 (js2-report-error msg msg-arg pos len)
2155 (push (list (list msg msg-arg)
2156 (or pos (js2-current-token-beg))
2157 (or len (js2-current-token-len))
2158 face)
2159 js2-parsed-warnings)))
2160
2161 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2162 (if js2-compiler-strict-mode
2163 (js2-report-warning msg-id msg-arg beg
2164 (and beg end (- end beg)))))
2165
2166 (put 'js2-syntax-error 'error-conditions
2167 '(error syntax-error js2-syntax-error))
2168 (put 'js2-syntax-error 'error-message "Syntax error")
2169
2170 (put 'js2-parse-error 'error-conditions
2171 '(error parse-error js2-parse-error))
2172 (put 'js2-parse-error 'error-message "Parse error")
2173
2174 (defmacro js2-clear-flag (flags flag)
2175 `(setq ,flags (logand ,flags (lognot ,flag))))
2176
2177 (defmacro js2-set-flag (flags flag)
2178 "Logical-or FLAG into FLAGS."
2179 `(setq ,flags (logior ,flags ,flag)))
2180
2181 (defsubst js2-flag-set-p (flags flag)
2182 (/= 0 (logand flags flag)))
2183
2184 (defsubst js2-flag-not-set-p (flags flag)
2185 (zerop (logand flags flag)))
2186
2187 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2188 "Evaluate BODY with the _ character set to be word-syntax."
2189 (declare (indent 0) (debug t))
2190 (let ((old-syntax (make-symbol "old-syntax")))
2191 `(let ((,old-syntax (string (char-syntax ?_))))
2192 (unwind-protect
2193 (progn
2194 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2195 ,@body)
2196 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2197
2198 ;;; AST struct and function definitions
2199
2200 ;; flags for ast node property 'member-type (used for e4x operators)
2201 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2202 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2203 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2204
2205 (defsubst js2-relpos (pos anchor)
2206 "Convert POS to be relative to ANCHOR.
2207 If POS is nil, returns nil."
2208 (and pos (- pos anchor)))
2209
2210 (defun js2-make-pad (indent)
2211 (if (zerop indent)
2212 ""
2213 (make-string (* indent js2-basic-offset) ? )))
2214
2215 (defun js2-visit-ast (node callback)
2216 "Visit every node in ast NODE with visitor CALLBACK.
2217
2218 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2219 called twice: once to visit the node, and again after all the node's
2220 children have been processed. The END-P argument is nil on the first
2221 call and non-nil on the second call. The return value of the callback
2222 affects the traversal: if non-nil, the children of NODE are processed.
2223 If the callback returns nil, or if the node has no children, then the
2224 callback is called immediately with a non-nil END-P argument.
2225
2226 The node traversal is approximately lexical-order, although there
2227 are currently no guarantees around this."
2228 (when node
2229 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2230 ;; visit the node
2231 (when (funcall callback node nil)
2232 ;; visit the kids
2233 (cond
2234 ((eq vfunc 'js2-visit-none)
2235 nil) ; don't even bother calling it
2236 ;; Each AST node type has to define a `js2-visitor' function
2237 ;; that takes a node and a callback, and calls `js2-visit-ast'
2238 ;; on each child of the node.
2239 (vfunc
2240 (funcall vfunc node callback))
2241 (t
2242 (error "%s does not define a visitor-traversal function"
2243 (aref node 0)))))
2244 ;; call the end-visit
2245 (funcall callback node t))))
2246
2247 (cl-defstruct (js2-node
2248 (:constructor nil)) ; abstract
2249 "Base AST node type."
2250 (type -1) ; token type
2251 (pos -1) ; start position of this AST node in parsed input
2252 (len 1) ; num characters spanned by the node
2253 props ; optional node property list (an alist)
2254 parent) ; link to parent node; null for root
2255
2256 (defsubst js2-node-get-prop (node prop &optional default)
2257 (or (cadr (assoc prop (js2-node-props node))) default))
2258
2259 (defsubst js2-node-set-prop (node prop value)
2260 (setf (js2-node-props node)
2261 (cons (list prop value) (js2-node-props node))))
2262
2263 (defun js2-fixup-starts (n nodes)
2264 "Adjust the start positions of NODES to be relative to N.
2265 Any node in the list may be nil, for convenience."
2266 (dolist (node nodes)
2267 (when node
2268 (setf (js2-node-pos node) (- (js2-node-pos node)
2269 (js2-node-pos n))))))
2270
2271 (defun js2-node-add-children (parent &rest nodes)
2272 "Set parent node of NODES to PARENT, and return PARENT.
2273 Does nothing if we're not recording parent links.
2274 If any given node in NODES is nil, doesn't record that link."
2275 (js2-fixup-starts parent nodes)
2276 (dolist (node nodes)
2277 (and node
2278 (setf (js2-node-parent node) parent))))
2279
2280 ;; Non-recursive since it's called a frightening number of times.
2281 (defun js2-node-abs-pos (n)
2282 (let ((pos (js2-node-pos n)))
2283 (while (setq n (js2-node-parent n))
2284 (setq pos (+ pos (js2-node-pos n))))
2285 pos))
2286
2287 (defsubst js2-node-abs-end (n)
2288 "Return absolute buffer position of end of N."
2289 (+ (js2-node-abs-pos n) (js2-node-len n)))
2290
2291 ;; It's important to make sure block nodes have a Lisp list for the
2292 ;; child nodes, to limit printing recursion depth in an AST that
2293 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2294 ;; a sufficiently large vector tree.
2295
2296 (cl-defstruct (js2-block-node
2297 (:include js2-node)
2298 (:constructor nil)
2299 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2300 (pos (js2-current-token-beg))
2301 len
2302 props
2303 kids)))
2304 "A block of statements."
2305 kids) ; a Lisp list of the child statement nodes
2306
2307 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2308 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2309
2310 (defun js2-visit-block (ast callback)
2311 "Visit the `js2-block-node' children of AST."
2312 (dolist (kid (js2-block-node-kids ast))
2313 (js2-visit-ast kid callback)))
2314
2315 (defun js2-print-block (n i)
2316 (let ((pad (js2-make-pad i)))
2317 (insert pad "{\n")
2318 (dolist (kid (js2-block-node-kids n))
2319 (js2-print-ast kid (1+ i)))
2320 (insert pad "}")))
2321
2322 (cl-defstruct (js2-scope
2323 (:include js2-block-node)
2324 (:constructor nil)
2325 (:constructor make-js2-scope (&key (type js2-BLOCK)
2326 (pos (js2-current-token-beg))
2327 len
2328 kids)))
2329 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2330 ;; I don't have one of those handy, so I'll use an alist for now.
2331 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2332 ;; and is much lighter-weight to construct (both CPU and mem).
2333 ;; The keys are interned strings (symbols) for faster lookup.
2334 ;; Should switch to hybrid alist/hashtable eventually.
2335 symbol-table ; an alist of (symbol . js2-symbol)
2336 parent-scope ; a `js2-scope'
2337 top) ; top-level `js2-scope' (script/function)
2338
2339 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2340 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2341
2342 (defun js2-node-get-enclosing-scope (node)
2343 "Return the innermost `js2-scope' node surrounding NODE.
2344 Returns nil if there is no enclosing scope node."
2345 (while (and (setq node (js2-node-parent node))
2346 (not (js2-scope-p node))))
2347 node)
2348
2349 (defun js2-get-defining-scope (scope name &optional point)
2350 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2351 Returns `js2-scope' in which NAME is defined, or nil if not found.
2352
2353 If POINT is non-nil, and if the found declaration type is
2354 `js2-LET', also check that the declaration node is before POINT."
2355 (let ((sym (if (symbolp name)
2356 name
2357 (intern name)))
2358 result
2359 (continue t))
2360 (while (and scope continue)
2361 (if (or
2362 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2363 (and entry
2364 (or (not point)
2365 (not (eq js2-LET (js2-symbol-decl-type entry)))
2366 (>= point
2367 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2368 (and (eq sym 'arguments)
2369 (js2-function-node-p scope)))
2370 (setq continue nil
2371 result scope)
2372 (setq scope (js2-scope-parent-scope scope))))
2373 result))
2374
2375 (defun js2-scope-get-symbol (scope name)
2376 "Return symbol table entry for NAME in SCOPE.
2377 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2378 (and (js2-scope-symbol-table scope)
2379 (cdr (assq (if (symbolp name)
2380 name
2381 (intern name))
2382 (js2-scope-symbol-table scope)))))
2383
2384 (defun js2-scope-put-symbol (scope name symbol)
2385 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2386 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2387 (let* ((table (js2-scope-symbol-table scope))
2388 (sym (if (symbolp name) name (intern name)))
2389 (entry (assq sym table)))
2390 (if entry
2391 (setcdr entry symbol)
2392 (push (cons sym symbol)
2393 (js2-scope-symbol-table scope)))))
2394
2395 (cl-defstruct (js2-symbol
2396 (:constructor nil)
2397 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2398 "A symbol table entry."
2399 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2400 ;; js2-LET, or js2-CONST
2401 decl-type
2402 name ; string
2403 ast-node) ; a `js2-node'
2404
2405 (cl-defstruct (js2-error-node
2406 (:include js2-node)
2407 (:constructor nil) ; silence emacs21 byte-compiler
2408 (:constructor make-js2-error-node (&key (type js2-ERROR)
2409 (pos (js2-current-token-beg))
2410 len)))
2411 "AST node representing a parse error.")
2412
2413 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2414 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2415
2416 (cl-defstruct (js2-script-node
2417 (:include js2-scope)
2418 (:constructor nil)
2419 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2420 (pos (js2-current-token-beg))
2421 len
2422 ;; FIXME: What are those?
2423 var-decls
2424 fun-decls)))
2425 functions ; Lisp list of nested functions
2426 regexps ; Lisp list of (string . flags)
2427 symbols ; alist (every symbol gets unique index)
2428 (param-count 0)
2429 var-names ; vector of string names
2430 consts ; bool-vector matching var-decls
2431 (temp-number 0)) ; for generating temp variables
2432
2433 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2434 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2435
2436 (defun js2-print-script (node indent)
2437 (dolist (kid (js2-block-node-kids node))
2438 (js2-print-ast kid indent)))
2439
2440 (cl-defstruct (js2-ast-root
2441 (:include js2-script-node)
2442 (:constructor nil)
2443 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2444 (pos (js2-current-token-beg))
2445 len
2446 buffer)))
2447 "The root node of a js2 AST."
2448 buffer ; the source buffer from which the code was parsed
2449 comments ; a Lisp list of comments, ordered by start position
2450 errors ; a Lisp list of errors found during parsing
2451 warnings ; a Lisp list of warnings found during parsing
2452 node-count) ; number of nodes in the tree, including the root
2453
2454 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2455 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2456
2457 (defun js2-visit-ast-root (ast callback)
2458 (dolist (kid (js2-ast-root-kids ast))
2459 (js2-visit-ast kid callback))
2460 (dolist (comment (js2-ast-root-comments ast))
2461 (js2-visit-ast comment callback)))
2462
2463 (cl-defstruct (js2-comment-node
2464 (:include js2-node)
2465 (:constructor nil)
2466 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2467 (pos (js2-current-token-beg))
2468 len
2469 format)))
2470 format) ; 'line, 'block, 'jsdoc or 'html
2471
2472 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2473 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2474
2475 (defun js2-print-comment (n i)
2476 ;; We really ought to link end-of-line comments to their nodes.
2477 ;; Or maybe we could add a new comment type, 'endline.
2478 (insert (js2-make-pad i)
2479 (js2-node-string n)))
2480
2481 (cl-defstruct (js2-expr-stmt-node
2482 (:include js2-node)
2483 (:constructor nil)
2484 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2485 (pos js2-ts-cursor)
2486 len
2487 expr)))
2488 "An expression statement."
2489 expr)
2490
2491 (defsubst js2-expr-stmt-node-set-has-result (node)
2492 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2493 (setf (js2-node-type node) js2-EXPR_RESULT))
2494
2495 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2496 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2497
2498 (defun js2-visit-expr-stmt-node (n v)
2499 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2500
2501 (defun js2-print-expr-stmt-node (n indent)
2502 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2503 (insert ";\n"))
2504
2505 (cl-defstruct (js2-loop-node
2506 (:include js2-scope)
2507 (:constructor nil))
2508 "Abstract supertype of loop nodes."
2509 body ; a `js2-block-node'
2510 lp ; position of left-paren, nil if omitted
2511 rp) ; position of right-paren, nil if omitted
2512
2513 (cl-defstruct (js2-do-node
2514 (:include js2-loop-node)
2515 (:constructor nil)
2516 (:constructor make-js2-do-node (&key (type js2-DO)
2517 (pos (js2-current-token-beg))
2518 len
2519 body
2520 condition
2521 while-pos
2522 lp
2523 rp)))
2524 "AST node for do-loop."
2525 condition ; while (expression)
2526 while-pos) ; buffer position of 'while' keyword
2527
2528 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2529 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2530
2531 (defun js2-visit-do-node (n v)
2532 (js2-visit-ast (js2-do-node-body n) v)
2533 (js2-visit-ast (js2-do-node-condition n) v))
2534
2535 (defun js2-print-do-node (n i)
2536 (let ((pad (js2-make-pad i)))
2537 (insert pad "do {\n")
2538 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2539 (js2-print-ast kid (1+ i)))
2540 (insert pad "} while (")
2541 (js2-print-ast (js2-do-node-condition n) 0)
2542 (insert ");\n")))
2543
2544 (cl-defstruct (js2-export-node
2545 (:include js2-node)
2546 (:constructor nil)
2547 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2548 (pos (js2-current-token-beg))
2549 len
2550 exports-list
2551 from-clause
2552 declaration
2553 default)))
2554 "AST node for an export statement. There are many things that can be exported,
2555 so many of its properties will be nil.
2556 "
2557 exports-list ; lisp list of js2-export-binding-node to export
2558 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2559 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2560 default) ; js2-function-node or js2-assign-node
2561
2562 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2563 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2564
2565 (defun js2-visit-export-node (n v)
2566 (let ((exports-list (js2-export-node-exports-list n))
2567 (from (js2-export-node-from-clause n))
2568 (declaration (js2-export-node-declaration n))
2569 (default (js2-export-node-default n)))
2570 (when exports-list
2571 (dolist (export exports-list)
2572 (js2-visit-ast export v)))
2573 (when from
2574 (js2-visit-ast from v))
2575 (when declaration
2576 (js2-visit-ast declaration v))
2577 (when default
2578 (js2-visit-ast default v))))
2579
2580 (defun js2-print-export-node (n i)
2581 (let ((pad (js2-make-pad i))
2582 (exports-list (js2-export-node-exports-list n))
2583 (from (js2-export-node-from-clause n))
2584 (declaration (js2-export-node-declaration n))
2585 (default (js2-export-node-default n)))
2586 (insert pad "export ")
2587 (cond
2588 (default
2589 (insert "default ")
2590 (js2-print-ast default i))
2591 (declaration
2592 (js2-print-ast declaration i))
2593 ((and exports-list from)
2594 (js2-print-named-imports exports-list)
2595 (insert " ")
2596 (js2-print-from-clause from))
2597 (from
2598 (insert "* ")
2599 (js2-print-from-clause from))
2600 (exports-list
2601 (js2-print-named-imports exports-list)))
2602 (insert ";\n")))
2603
2604 (cl-defstruct (js2-while-node
2605 (:include js2-loop-node)
2606 (:constructor nil)
2607 (:constructor make-js2-while-node (&key (type js2-WHILE)
2608 (pos (js2-current-token-beg))
2609 len body
2610 condition lp
2611 rp)))
2612 "AST node for while-loop."
2613 condition) ; while-condition
2614
2615 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2616 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2617
2618 (defun js2-visit-while-node (n v)
2619 (js2-visit-ast (js2-while-node-condition n) v)
2620 (js2-visit-ast (js2-while-node-body n) v))
2621
2622 (defun js2-print-while-node (n i)
2623 (let ((pad (js2-make-pad i)))
2624 (insert pad "while (")
2625 (js2-print-ast (js2-while-node-condition n) 0)
2626 (insert ") {\n")
2627 (js2-print-body (js2-while-node-body n) (1+ i))
2628 (insert pad "}\n")))
2629
2630 (cl-defstruct (js2-for-node
2631 (:include js2-loop-node)
2632 (:constructor nil)
2633 (:constructor make-js2-for-node (&key (type js2-FOR)
2634 (pos js2-ts-cursor)
2635 len body init
2636 condition
2637 update lp rp)))
2638 "AST node for a C-style for-loop."
2639 init ; initialization expression
2640 condition ; loop condition
2641 update) ; update clause
2642
2643 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2644 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2645
2646 (defun js2-visit-for-node (n v)
2647 (js2-visit-ast (js2-for-node-init n) v)
2648 (js2-visit-ast (js2-for-node-condition n) v)
2649 (js2-visit-ast (js2-for-node-update n) v)
2650 (js2-visit-ast (js2-for-node-body n) v))
2651
2652 (defun js2-print-for-node (n i)
2653 (let ((pad (js2-make-pad i)))
2654 (insert pad "for (")
2655 (js2-print-ast (js2-for-node-init n) 0)
2656 (insert "; ")
2657 (js2-print-ast (js2-for-node-condition n) 0)
2658 (insert "; ")
2659 (js2-print-ast (js2-for-node-update n) 0)
2660 (insert ") {\n")
2661 (js2-print-body (js2-for-node-body n) (1+ i))
2662 (insert pad "}\n")))
2663
2664 (cl-defstruct (js2-for-in-node
2665 (:include js2-loop-node)
2666 (:constructor nil)
2667 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2668 (pos js2-ts-cursor)
2669 len body
2670 iterator
2671 object
2672 in-pos
2673 each-pos
2674 foreach-p forof-p
2675 lp rp)))
2676 "AST node for a for..in loop."
2677 iterator ; [var] foo in ...
2678 object ; object over which we're iterating
2679 in-pos ; buffer position of 'in' keyword
2680 each-pos ; buffer position of 'each' keyword, if foreach-p
2681 foreach-p ; t if it's a for-each loop
2682 forof-p) ; t if it's a for-of loop
2683
2684 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2685 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2686
2687 (defun js2-visit-for-in-node (n v)
2688 (js2-visit-ast (js2-for-in-node-iterator n) v)
2689 (js2-visit-ast (js2-for-in-node-object n) v)
2690 (js2-visit-ast (js2-for-in-node-body n) v))
2691
2692 (defun js2-print-for-in-node (n i)
2693 (let ((pad (js2-make-pad i))
2694 (foreach (js2-for-in-node-foreach-p n))
2695 (forof (js2-for-in-node-forof-p n)))
2696 (insert pad "for ")
2697 (if foreach
2698 (insert "each "))
2699 (insert "(")
2700 (js2-print-ast (js2-for-in-node-iterator n) 0)
2701 (insert (if forof " of " " in "))
2702 (js2-print-ast (js2-for-in-node-object n) 0)
2703 (insert ") {\n")
2704 (js2-print-body (js2-for-in-node-body n) (1+ i))
2705 (insert pad "}\n")))
2706
2707 (cl-defstruct (js2-return-node
2708 (:include js2-node)
2709 (:constructor nil)
2710 (:constructor make-js2-return-node (&key (type js2-RETURN)
2711 (pos js2-ts-cursor)
2712 len
2713 retval)))
2714 "AST node for a return statement."
2715 retval) ; expression to return, or 'undefined
2716
2717 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2718 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2719
2720 (defun js2-visit-return-node (n v)
2721 (js2-visit-ast (js2-return-node-retval n) v))
2722
2723 (defun js2-print-return-node (n i)
2724 (insert (js2-make-pad i) "return")
2725 (when (js2-return-node-retval n)
2726 (insert " ")
2727 (js2-print-ast (js2-return-node-retval n) 0))
2728 (insert ";\n"))
2729
2730 (cl-defstruct (js2-if-node
2731 (:include js2-node)
2732 (:constructor nil)
2733 (:constructor make-js2-if-node (&key (type js2-IF)
2734 (pos js2-ts-cursor)
2735 len condition
2736 then-part
2737 else-pos
2738 else-part lp
2739 rp)))
2740 "AST node for an if-statement."
2741 condition ; expression
2742 then-part ; statement or block
2743 else-pos ; optional buffer position of 'else' keyword
2744 else-part ; optional statement or block
2745 lp ; position of left-paren, nil if omitted
2746 rp) ; position of right-paren, nil if omitted
2747
2748 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2749 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2750
2751 (defun js2-visit-if-node (n v)
2752 (js2-visit-ast (js2-if-node-condition n) v)
2753 (js2-visit-ast (js2-if-node-then-part n) v)
2754 (js2-visit-ast (js2-if-node-else-part n) v))
2755
2756 (defun js2-print-if-node (n i)
2757 (let ((pad (js2-make-pad i))
2758 (then-part (js2-if-node-then-part n))
2759 (else-part (js2-if-node-else-part n)))
2760 (insert pad "if (")
2761 (js2-print-ast (js2-if-node-condition n) 0)
2762 (insert ") {\n")
2763 (js2-print-body then-part (1+ i))
2764 (insert pad "}")
2765 (cond
2766 ((not else-part)
2767 (insert "\n"))
2768 ((js2-if-node-p else-part)
2769 (insert " else ")
2770 (js2-print-body else-part i))
2771 (t
2772 (insert " else {\n")
2773 (js2-print-body else-part (1+ i))
2774 (insert pad "}\n")))))
2775
2776 (cl-defstruct (js2-export-binding-node
2777 (:include js2-node)
2778 (:constructor nil)
2779 (:constructor make-js2-export-binding-node (&key (type -1)
2780 pos
2781 len
2782 local-name
2783 extern-name)))
2784 "AST node for an external symbol binding.
2785 It contains a local-name node which is the name of the value in the
2786 current scope, and extern-name which is the name of the value in the
2787 imported or exported scope. By default these are the same, but if the
2788 name is aliased as in {foo as bar}, it would have an extern-name node
2789 containing 'foo' and a local-name node containing 'bar'."
2790 local-name ; js2-name-node with the variable name in this scope
2791 extern-name) ; js2-name-node with the value name in the exporting module
2792
2793 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2794 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2795
2796 (defun js2-visit-extern-binding (n v)
2797 "Visit an extern binding node. First visit the local-name, and, if
2798 different, visit the extern-name."
2799 (let ((local-name (js2-export-binding-node-local-name n))
2800 (extern-name (js2-export-binding-node-extern-name n)))
2801 (when local-name
2802 (js2-visit-ast local-name v))
2803 (when (not (equal local-name extern-name))
2804 (js2-visit-ast extern-name v))))
2805
2806 (defun js2-print-extern-binding (n _i)
2807 "Print a representation of a single extern binding. E.g. 'foo' or
2808 'foo as bar'."
2809 (let ((local-name (js2-export-binding-node-local-name n))
2810 (extern-name (js2-export-binding-node-extern-name n)))
2811 (insert (js2-name-node-name extern-name))
2812 (when (not (equal local-name extern-name))
2813 (insert " as ")
2814 (insert (js2-name-node-name local-name)))))
2815
2816
2817 (cl-defstruct (js2-import-node
2818 (:include js2-node)
2819 (:constructor nil)
2820 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2821 (pos (js2-current-token-beg))
2822 len
2823 import
2824 from
2825 module-id)))
2826 "AST node for an import statement. It follows the form
2827
2828 import ModuleSpecifier;
2829 import ImportClause FromClause;"
2830 import ; js2-import-clause-node specifying which names are to imported.
2831 from ; js2-from-clause-node indicating the module from which to import.
2832 module-id) ; module-id of the import. E.g. 'src/mylib'.
2833
2834 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2835 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2836
2837 (defun js2-visit-import (n v)
2838 (let ((import-clause (js2-import-node-import n))
2839 (from-clause (js2-import-node-from n)))
2840 (when import-clause
2841 (js2-visit-ast import-clause v))
2842 (when from-clause
2843 (js2-visit-ast from-clause v))))
2844
2845 (defun js2-print-import (n i)
2846 "Prints a representation of the import node"
2847 (let ((pad (js2-make-pad i))
2848 (import-clause (js2-import-node-import n))
2849 (from-clause (js2-import-node-from n))
2850 (module-id (js2-import-node-module-id n)))
2851 (insert pad "import ")
2852 (if import-clause
2853 (progn
2854 (js2-print-import-clause import-clause)
2855 (insert " ")
2856 (js2-print-from-clause from-clause))
2857 (insert "'")
2858 (insert module-id)
2859 (insert "'"))
2860 (insert ";\n")))
2861
2862 (cl-defstruct (js2-import-clause-node
2863 (:include js2-node)
2864 (:constructor nil)
2865 (:constructor make-js2-import-clause-node (&key (type -1)
2866 pos
2867 len
2868 namespace-import
2869 named-imports
2870 default-binding)))
2871 "AST node corresponding to the import clause of an import statement. This is
2872 the portion of the import that bindings names from the external context to the
2873 local context."
2874 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2875 named-imports ; lisp list of js2-export-binding-node for all named imports.
2876 default-binding) ; js2-export-binding-node for the default import binding
2877
2878 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2879 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2880
2881 (defun js2-visit-import-clause (n v)
2882 (let ((ns-import (js2-import-clause-node-namespace-import n))
2883 (named-imports (js2-import-clause-node-named-imports n))
2884 (default (js2-import-clause-node-default-binding n)))
2885 (when ns-import
2886 (js2-visit-ast ns-import v))
2887 (when named-imports
2888 (dolist (import named-imports)
2889 (js2-visit-ast import v)))
2890 (when default
2891 (js2-visit-ast default v))))
2892
2893 (defun js2-print-import-clause (n)
2894 (let ((ns-import (js2-import-clause-node-namespace-import n))
2895 (named-imports (js2-import-clause-node-named-imports n))
2896 (default (js2-import-clause-node-default-binding n)))
2897 (cond
2898 ((and default ns-import)
2899 (js2-print-ast default)
2900 (insert ", ")
2901 (js2-print-namespace-import ns-import))
2902 ((and default named-imports)
2903 (js2-print-ast default)
2904 (insert ", ")
2905 (js2-print-named-imports named-imports))
2906 (default
2907 (js2-print-ast default))
2908 (ns-import
2909 (js2-print-namespace-import ns-import))
2910 (named-imports
2911 (js2-print-named-imports named-imports)))))
2912
2913 (defun js2-print-namespace-import (node)
2914 (insert "* as ")
2915 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2916
2917 (defun js2-print-named-imports (imports)
2918 (insert "{")
2919 (let ((len (length imports))
2920 (n 0))
2921 (while (< n len)
2922 (js2-print-extern-binding (nth n imports) 0)
2923 (unless (= n (- len 1))
2924 (insert ", "))
2925 (setq n (+ n 1))))
2926 (insert "}"))
2927
2928 (cl-defstruct (js2-namespace-import-node
2929 (:include js2-node)
2930 (:constructor nil)
2931 (:constructor make-js2-namespace-import-node (&key (type -1)
2932 pos
2933 len
2934 name)))
2935 "AST node for a complete namespace import.
2936 E.g. the '* as lib' expression in:
2937
2938 import * as lib from 'src/lib'
2939
2940 It contains a single name node referring to the bound name."
2941 name) ; js2-name-node of the bound name.
2942
2943 (defun js2-visit-namespace-import (n v)
2944 (js2-visit-ast (js2-namespace-import-node-name n) v))
2945
2946 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2947 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2948
2949 (cl-defstruct (js2-from-clause-node
2950 (:include js2-node)
2951 (:constructor nil)
2952 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2953 pos
2954 len
2955 module-id
2956 metadata-p)))
2957 "AST node for the from clause in an import or export statement.
2958 E.g. from 'my/module'. It can refere to either an external module, or to the
2959 modules metadata itself."
2960 module-id ; string containing the module specifier.
2961 metadata-p) ; true if this clause refers to the module's metadata
2962
2963 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2964 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2965
2966 (defun js2-print-from-clause (n)
2967 (insert "from ")
2968 (if (js2-from-clause-node-metadata-p n)
2969 (insert "this module")
2970 (insert "'")
2971 (insert (js2-from-clause-node-module-id n))
2972 (insert "'")))
2973
2974 (cl-defstruct (js2-try-node
2975 (:include js2-node)
2976 (:constructor nil)
2977 (:constructor make-js2-try-node (&key (type js2-TRY)
2978 (pos js2-ts-cursor)
2979 len
2980 try-block
2981 catch-clauses
2982 finally-block)))
2983 "AST node for a try-statement."
2984 try-block
2985 catch-clauses ; a Lisp list of `js2-catch-node'
2986 finally-block) ; a `js2-finally-node'
2987
2988 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2989 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2990
2991 (defun js2-visit-try-node (n v)
2992 (js2-visit-ast (js2-try-node-try-block n) v)
2993 (dolist (clause (js2-try-node-catch-clauses n))
2994 (js2-visit-ast clause v))
2995 (js2-visit-ast (js2-try-node-finally-block n) v))
2996
2997 (defun js2-print-try-node (n i)
2998 (let ((pad (js2-make-pad i))
2999 (catches (js2-try-node-catch-clauses n))
3000 (finally (js2-try-node-finally-block n)))
3001 (insert pad "try {\n")
3002 (js2-print-body (js2-try-node-try-block n) (1+ i))
3003 (insert pad "}")
3004 (when catches
3005 (dolist (catch catches)
3006 (js2-print-ast catch i)))
3007 (if finally
3008 (js2-print-ast finally i)
3009 (insert "\n"))))
3010
3011 (cl-defstruct (js2-catch-node
3012 (:include js2-scope)
3013 (:constructor nil)
3014 (:constructor make-js2-catch-node (&key (type js2-CATCH)
3015 (pos js2-ts-cursor)
3016 len
3017 param
3018 guard-kwd
3019 guard-expr
3020 lp rp)))
3021 "AST node for a catch clause."
3022 param ; destructuring form or simple name node
3023 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
3024 guard-expr ; catch condition, a `js2-node'
3025 lp ; buffer position of left-paren, nil if omitted
3026 rp) ; buffer position of right-paren, nil if omitted
3027
3028 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
3029 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
3030
3031 (defun js2-visit-catch-node (n v)
3032 (js2-visit-ast (js2-catch-node-param n) v)
3033 (when (js2-catch-node-guard-kwd n)
3034 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3035 (js2-visit-block n v))
3036
3037 (defun js2-print-catch-node (n i)
3038 (let ((pad (js2-make-pad i))
3039 (guard-kwd (js2-catch-node-guard-kwd n))
3040 (guard-expr (js2-catch-node-guard-expr n)))
3041 (insert " catch (")
3042 (js2-print-ast (js2-catch-node-param n) 0)
3043 (when guard-kwd
3044 (insert " if ")
3045 (js2-print-ast guard-expr 0))
3046 (insert ") {\n")
3047 (js2-print-body n (1+ i))
3048 (insert pad "}")))
3049
3050 (cl-defstruct (js2-finally-node
3051 (:include js2-node)
3052 (:constructor nil)
3053 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3054 (pos js2-ts-cursor)
3055 len body)))
3056 "AST node for a finally clause."
3057 body) ; a `js2-node', often but not always a block node
3058
3059 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3060 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3061
3062 (defun js2-visit-finally-node (n v)
3063 (js2-visit-ast (js2-finally-node-body n) v))
3064
3065 (defun js2-print-finally-node (n i)
3066 (let ((pad (js2-make-pad i)))
3067 (insert " finally {\n")
3068 (js2-print-body (js2-finally-node-body n) (1+ i))
3069 (insert pad "}\n")))
3070
3071 (cl-defstruct (js2-switch-node
3072 (:include js2-node)
3073 (:constructor nil)
3074 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3075 (pos js2-ts-cursor)
3076 len
3077 discriminant
3078 cases lp
3079 rp)))
3080 "AST node for a switch statement."
3081 discriminant ; a `js2-node' (switch expression)
3082 cases ; a Lisp list of `js2-case-node'
3083 lp ; position of open-paren for discriminant, nil if omitted
3084 rp) ; position of close-paren for discriminant, nil if omitted
3085
3086 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3087 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3088
3089 (defun js2-visit-switch-node (n v)
3090 (js2-visit-ast (js2-switch-node-discriminant n) v)
3091 (dolist (c (js2-switch-node-cases n))
3092 (js2-visit-ast c v)))
3093
3094 (defun js2-print-switch-node (n i)
3095 (let ((pad (js2-make-pad i))
3096 (cases (js2-switch-node-cases n)))
3097 (insert pad "switch (")
3098 (js2-print-ast (js2-switch-node-discriminant n) 0)
3099 (insert ") {\n")
3100 (dolist (case cases)
3101 (js2-print-ast case i))
3102 (insert pad "}\n")))
3103
3104 (cl-defstruct (js2-case-node
3105 (:include js2-block-node)
3106 (:constructor nil)
3107 (:constructor make-js2-case-node (&key (type js2-CASE)
3108 (pos js2-ts-cursor)
3109 len kids expr)))
3110 "AST node for a case clause of a switch statement."
3111 expr) ; the case expression (nil for default)
3112
3113 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3114 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3115
3116 (defun js2-visit-case-node (n v)
3117 (js2-visit-ast (js2-case-node-expr n) v)
3118 (js2-visit-block n v))
3119
3120 (defun js2-print-case-node (n i)
3121 (let ((pad (js2-make-pad i))
3122 (expr (js2-case-node-expr n)))
3123 (insert pad)
3124 (if (null expr)
3125 (insert "default:\n")
3126 (insert "case ")
3127 (js2-print-ast expr 0)
3128 (insert ":\n"))
3129 (dolist (kid (js2-case-node-kids n))
3130 (js2-print-ast kid (1+ i)))))
3131
3132 (cl-defstruct (js2-throw-node
3133 (:include js2-node)
3134 (:constructor nil)
3135 (:constructor make-js2-throw-node (&key (type js2-THROW)
3136 (pos js2-ts-cursor)
3137 len expr)))
3138 "AST node for a throw statement."
3139 expr) ; the expression to throw
3140
3141 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3142 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3143
3144 (defun js2-visit-throw-node (n v)
3145 (js2-visit-ast (js2-throw-node-expr n) v))
3146
3147 (defun js2-print-throw-node (n i)
3148 (insert (js2-make-pad i) "throw ")
3149 (js2-print-ast (js2-throw-node-expr n) 0)
3150 (insert ";\n"))
3151
3152 (cl-defstruct (js2-with-node
3153 (:include js2-node)
3154 (:constructor nil)
3155 (:constructor make-js2-with-node (&key (type js2-WITH)
3156 (pos js2-ts-cursor)
3157 len object
3158 body lp rp)))
3159 "AST node for a with-statement."
3160 object
3161 body
3162 lp ; buffer position of left-paren around object, nil if omitted
3163 rp) ; buffer position of right-paren around object, nil if omitted
3164
3165 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3166 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3167
3168 (defun js2-visit-with-node (n v)
3169 (js2-visit-ast (js2-with-node-object n) v)
3170 (js2-visit-ast (js2-with-node-body n) v))
3171
3172 (defun js2-print-with-node (n i)
3173 (let ((pad (js2-make-pad i)))
3174 (insert pad "with (")
3175 (js2-print-ast (js2-with-node-object n) 0)
3176 (insert ") {\n")
3177 (js2-print-body (js2-with-node-body n) (1+ i))
3178 (insert pad "}\n")))
3179
3180 (cl-defstruct (js2-label-node
3181 (:include js2-node)
3182 (:constructor nil)
3183 (:constructor make-js2-label-node (&key (type js2-LABEL)
3184 (pos js2-ts-cursor)
3185 len name)))
3186 "AST node for a statement label or case label."
3187 name ; a string
3188 loop) ; for validating and code-generating continue-to-label
3189
3190 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3191 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3192
3193 (defun js2-print-label (n i)
3194 (insert (js2-make-pad i)
3195 (js2-label-node-name n)
3196 ":\n"))
3197
3198 (cl-defstruct (js2-labeled-stmt-node
3199 (:include js2-node)
3200 (:constructor nil)
3201 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3202 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3203 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3204 (pos js2-ts-cursor)
3205 len labels stmt)))
3206 "AST node for a statement with one or more labels.
3207 Multiple labels for a statement are collapsed into the labels field."
3208 labels ; Lisp list of `js2-label-node'
3209 stmt) ; the statement these labels are for
3210
3211 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3212 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3213
3214 (defun js2-get-label-by-name (lbl-stmt name)
3215 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3216 Returns nil if no such label is in the list."
3217 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3218 result)
3219 (while (and label-list (not result))
3220 (if (string= (js2-label-node-name (car label-list)) name)
3221 (setq result (car label-list))
3222 (setq label-list (cdr label-list))))
3223 result))
3224
3225 (defun js2-visit-labeled-stmt (n v)
3226 (dolist (label (js2-labeled-stmt-node-labels n))
3227 (js2-visit-ast label v))
3228 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3229
3230 (defun js2-print-labeled-stmt (n i)
3231 (dolist (label (js2-labeled-stmt-node-labels n))
3232 (js2-print-ast label i))
3233 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3234
3235 (defun js2-labeled-stmt-node-contains (node label)
3236 "Return t if NODE contains LABEL in its label set.
3237 NODE is a `js2-labels-node'. LABEL is an identifier."
3238 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3239 if (string= label (js2-label-node-name nl))
3240 return t
3241 finally return nil))
3242
3243 (defsubst js2-labeled-stmt-node-add-label (node label)
3244 "Add a `js2-label-node' to the label set for this statement."
3245 (setf (js2-labeled-stmt-node-labels node)
3246 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3247
3248 (cl-defstruct (js2-jump-node
3249 (:include js2-node)
3250 (:constructor nil))
3251 "Abstract supertype of break and continue nodes."
3252 label ; `js2-name-node' for location of label identifier, if present
3253 target) ; target js2-labels-node or loop/switch statement
3254
3255 (defun js2-visit-jump-node (n v)
3256 ;; We don't visit the target, since it's a back-link.
3257 (js2-visit-ast (js2-jump-node-label n) v))
3258
3259 (cl-defstruct (js2-break-node
3260 (:include js2-jump-node)
3261 (:constructor nil)
3262 (:constructor make-js2-break-node (&key (type js2-BREAK)
3263 (pos js2-ts-cursor)
3264 len label target)))
3265 "AST node for a break statement.
3266 The label field is a `js2-name-node', possibly nil, for the named label
3267 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3268 is the target of the break - a label node or enclosing loop/switch statement.")
3269
3270 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3271 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3272
3273 (defun js2-print-break-node (n i)
3274 (insert (js2-make-pad i) "break")
3275 (when (js2-break-node-label n)
3276 (insert " ")
3277 (js2-print-ast (js2-break-node-label n) 0))
3278 (insert ";\n"))
3279
3280 (cl-defstruct (js2-continue-node
3281 (:include js2-jump-node)
3282 (:constructor nil)
3283 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3284 (pos js2-ts-cursor)
3285 len label target)))
3286 "AST node for a continue statement.
3287 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3288 It is nil if continue specifies no label. The target field is the jump target:
3289 a `js2-label-node' or the innermost enclosing loop.")
3290
3291 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3292 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3293
3294 (defun js2-print-continue-node (n i)
3295 (insert (js2-make-pad i) "continue")
3296 (when (js2-continue-node-label n)
3297 (insert " ")
3298 (js2-print-ast (js2-continue-node-label n) 0))
3299 (insert ";\n"))
3300
3301 (cl-defstruct (js2-function-node
3302 (:include js2-script-node)
3303 (:constructor nil)
3304 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3305 (pos js2-ts-cursor)
3306 len
3307 (ftype 'FUNCTION)
3308 (form 'FUNCTION_STATEMENT)
3309 (name "")
3310 params rest-p
3311 body
3312 generator-type
3313 lp rp)))
3314 "AST node for a function declaration.
3315 The `params' field is a Lisp list of nodes. Each node is either a simple
3316 `js2-name-node', or if it's a destructuring-assignment parameter, a
3317 `js2-array-node' or `js2-object-node'."
3318 ftype ; FUNCTION, GETTER or SETTER
3319 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3320 name ; function name (a `js2-name-node', or nil if anonymous)
3321 params ; a Lisp list of destructuring forms or simple name nodes
3322 rest-p ; if t, the last parameter is rest parameter
3323 body ; a `js2-block-node' or expression node (1.8 only)
3324 lp ; position of arg-list open-paren, or nil if omitted
3325 rp ; position of arg-list close-paren, or nil if omitted
3326 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3327 needs-activation ; t if we need an activation object for this frame
3328 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3329 member-expr) ; nonstandard Ecma extension from Rhino
3330
3331 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3332 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3333
3334 (defun js2-visit-function-node (n v)
3335 (js2-visit-ast (js2-function-node-name n) v)
3336 (dolist (p (js2-function-node-params n))
3337 (js2-visit-ast p v))
3338 (js2-visit-ast (js2-function-node-body n) v))
3339
3340 (defun js2-print-function-node (n i)
3341 (let* ((pad (js2-make-pad i))
3342 (getter (js2-node-get-prop n 'GETTER_SETTER))
3343 (name (or (js2-function-node-name n)
3344 (js2-function-node-member-expr n)))
3345 (params (js2-function-node-params n))
3346 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3347 (rest-p (js2-function-node-rest-p n))
3348 (body (js2-function-node-body n))
3349 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3350 (unless (or getter arrow)
3351 (insert pad "function")
3352 (when (eq (js2-function-node-generator-type n) 'STAR)
3353 (insert "*")))
3354 (when name
3355 (insert " ")
3356 (js2-print-ast name 0))
3357 (insert "(")
3358 (cl-loop with len = (length params)
3359 for param in params
3360 for count from 1
3361 do
3362 (when (and rest-p (= count len))
3363 (insert "..."))
3364 (js2-print-ast param 0)
3365 (when (< count len)
3366 (insert ", ")))
3367 (insert ") ")
3368 (when arrow
3369 (insert "=> "))
3370 (insert "{")
3371 ;; TODO: fix this to be smarter about indenting, etc.
3372 (unless expr
3373 (insert "\n"))
3374 (if (js2-block-node-p body)
3375 (js2-print-body body (1+ i))
3376 (js2-print-ast body 0))
3377 (insert pad "}")
3378 (unless expr
3379 (insert "\n"))))
3380
3381 (defun js2-function-name (node)
3382 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3383 (and (js2-function-node-name node)
3384 (js2-name-node-name (js2-function-node-name node))))
3385
3386 ;; Having this be an expression node makes it more flexible.
3387 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3388 ;; that work better if you assume it's an expression. Whenever we have
3389 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3390 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3391 (cl-defstruct (js2-var-decl-node
3392 (:include js2-node)
3393 (:constructor nil)
3394 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3395 (pos (js2-current-token-beg))
3396 len kids
3397 decl-type)))
3398 "AST node for a variable declaration list (VAR, CONST or LET).
3399 The node bounds differ depending on the declaration type. For VAR or
3400 CONST declarations, the bounds include the var/const keyword. For LET
3401 declarations, the node begins at the position of the first child."
3402 kids ; a Lisp list of `js2-var-init-node' structs.
3403 decl-type) ; js2-VAR, js2-CONST or js2-LET
3404
3405 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3406 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3407
3408 (defun js2-visit-var-decl (n v)
3409 (dolist (kid (js2-var-decl-node-kids n))
3410 (js2-visit-ast kid v)))
3411
3412 (defun js2-print-var-decl (n i)
3413 (let ((pad (js2-make-pad i))
3414 (tt (js2-var-decl-node-decl-type n)))
3415 (insert pad)
3416 (insert (cond
3417 ((= tt js2-VAR) "var ")
3418 ((= tt js2-LET) "let ")
3419 ((= tt js2-CONST) "const ")
3420 (t
3421 (error "malformed var-decl node"))))
3422 (cl-loop with kids = (js2-var-decl-node-kids n)
3423 with len = (length kids)
3424 for kid in kids
3425 for count from 1
3426 do
3427 (js2-print-ast kid 0)
3428 (if (< count len)
3429 (insert ", ")))))
3430
3431 (cl-defstruct (js2-var-init-node
3432 (:include js2-node)
3433 (:constructor nil)
3434 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3435 (pos js2-ts-cursor)
3436 len target
3437 initializer)))
3438 "AST node for a variable declaration.
3439 The type field will be js2-CONST for a const decl."
3440 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3441 initializer) ; initializer expression, a `js2-node'
3442
3443 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3444 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3445
3446 (defun js2-visit-var-init-node (n v)
3447 (js2-visit-ast (js2-var-init-node-target n) v)
3448 (js2-visit-ast (js2-var-init-node-initializer n) v))
3449
3450 (defun js2-print-var-init-node (n i)
3451 (let ((pad (js2-make-pad i))
3452 (name (js2-var-init-node-target n))
3453 (init (js2-var-init-node-initializer n)))
3454 (insert pad)
3455 (js2-print-ast name 0)
3456 (when init
3457 (insert " = ")
3458 (js2-print-ast init 0))))
3459
3460 (cl-defstruct (js2-cond-node
3461 (:include js2-node)
3462 (:constructor nil)
3463 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3464 (pos js2-ts-cursor)
3465 len
3466 test-expr
3467 true-expr
3468 false-expr
3469 q-pos c-pos)))
3470 "AST node for the ternary operator"
3471 test-expr
3472 true-expr
3473 false-expr
3474 q-pos ; buffer position of ?
3475 c-pos) ; buffer position of :
3476
3477 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3478 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3479
3480 (defun js2-visit-cond-node (n v)
3481 (js2-visit-ast (js2-cond-node-test-expr n) v)
3482 (js2-visit-ast (js2-cond-node-true-expr n) v)
3483 (js2-visit-ast (js2-cond-node-false-expr n) v))
3484
3485 (defun js2-print-cond-node (n i)
3486 (let ((pad (js2-make-pad i)))
3487 (insert pad)
3488 (js2-print-ast (js2-cond-node-test-expr n) 0)
3489 (insert " ? ")
3490 (js2-print-ast (js2-cond-node-true-expr n) 0)
3491 (insert " : ")
3492 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3493
3494 (cl-defstruct (js2-infix-node
3495 (:include js2-node)
3496 (:constructor nil)
3497 (:constructor make-js2-infix-node (&key type
3498 (pos js2-ts-cursor)
3499 len op-pos
3500 left right)))
3501 "Represents infix expressions.
3502 Includes assignment ops like `|=', and the comma operator.
3503 The type field inherited from `js2-node' holds the operator."
3504 op-pos ; buffer position where operator begins
3505 left ; any `js2-node'
3506 right) ; any `js2-node'
3507
3508 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3509 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3510
3511 (defun js2-visit-infix-node (n v)
3512 (js2-visit-ast (js2-infix-node-left n) v)
3513 (js2-visit-ast (js2-infix-node-right n) v))
3514
3515 (defconst js2-operator-tokens
3516 (let ((table (make-hash-table :test 'eq))
3517 (tokens
3518 (list (cons js2-IN "in")
3519 (cons js2-TYPEOF "typeof")
3520 (cons js2-INSTANCEOF "instanceof")
3521 (cons js2-DELPROP "delete")
3522 (cons js2-COMMA ",")
3523 (cons js2-COLON ":")
3524 (cons js2-OR "||")
3525 (cons js2-AND "&&")
3526 (cons js2-INC "++")
3527 (cons js2-DEC "--")
3528 (cons js2-BITOR "|")
3529 (cons js2-BITXOR "^")
3530 (cons js2-BITAND "&")
3531 (cons js2-EQ "==")
3532 (cons js2-NE "!=")
3533 (cons js2-LT "<")
3534 (cons js2-LE "<=")
3535 (cons js2-GT ">")
3536 (cons js2-GE ">=")
3537 (cons js2-LSH "<<")
3538 (cons js2-RSH ">>")
3539 (cons js2-URSH ">>>")
3540 (cons js2-ADD "+") ; infix plus
3541 (cons js2-SUB "-") ; infix minus
3542 (cons js2-MUL "*")
3543 (cons js2-DIV "/")
3544 (cons js2-MOD "%")
3545 (cons js2-NOT "!")
3546 (cons js2-BITNOT "~")
3547 (cons js2-POS "+") ; unary plus
3548 (cons js2-NEG "-") ; unary minus
3549 (cons js2-TRIPLEDOT "...")
3550 (cons js2-SHEQ "===") ; shallow equality
3551 (cons js2-SHNE "!==") ; shallow inequality
3552 (cons js2-ASSIGN "=")
3553 (cons js2-ASSIGN_BITOR "|=")
3554 (cons js2-ASSIGN_BITXOR "^=")
3555 (cons js2-ASSIGN_BITAND "&=")
3556 (cons js2-ASSIGN_LSH "<<=")
3557 (cons js2-ASSIGN_RSH ">>=")
3558 (cons js2-ASSIGN_URSH ">>>=")
3559 (cons js2-ASSIGN_ADD "+=")
3560 (cons js2-ASSIGN_SUB "-=")
3561 (cons js2-ASSIGN_MUL "*=")
3562 (cons js2-ASSIGN_DIV "/=")
3563 (cons js2-ASSIGN_MOD "%="))))
3564 (cl-loop for (k . v) in tokens do
3565 (puthash k v table))
3566 table))
3567
3568 (defun js2-print-infix-node (n i)
3569 (let* ((tt (js2-node-type n))
3570 (op (gethash tt js2-operator-tokens)))
3571 (unless op
3572 (error "unrecognized infix operator %s" (js2-node-type n)))
3573 (insert (js2-make-pad i))
3574 (js2-print-ast (js2-infix-node-left n) 0)
3575 (unless (= tt js2-COMMA)
3576 (insert " "))
3577 (insert op)
3578 (insert " ")
3579 (js2-print-ast (js2-infix-node-right n) 0)))
3580
3581 (cl-defstruct (js2-assign-node
3582 (:include js2-infix-node)
3583 (:constructor nil)
3584 (:constructor make-js2-assign-node (&key type
3585 (pos js2-ts-cursor)
3586 len op-pos
3587 left right)))
3588 "Represents any assignment.
3589 The type field holds the actual assignment operator.")
3590
3591 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3592 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3593
3594 (cl-defstruct (js2-unary-node
3595 (:include js2-node)
3596 (:constructor nil)
3597 (:constructor make-js2-unary-node (&key type ; required
3598 (pos js2-ts-cursor)
3599 len operand)))
3600 "AST node type for unary operator nodes.
3601 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3602 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3603 property is added if the operator follows the operand."
3604 operand) ; a `js2-node' expression
3605
3606 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3607 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3608
3609 (defun js2-visit-unary-node (n v)
3610 (js2-visit-ast (js2-unary-node-operand n) v))
3611
3612 (defun js2-print-unary-node (n i)
3613 (let* ((tt (js2-node-type n))
3614 (op (gethash tt js2-operator-tokens))
3615 (postfix (js2-node-get-prop n 'postfix)))
3616 (unless op
3617 (error "unrecognized unary operator %s" tt))
3618 (insert (js2-make-pad i))
3619 (unless postfix
3620 (insert op))
3621 (if (or (= tt js2-TYPEOF)
3622 (= tt js2-DELPROP))
3623 (insert " "))
3624 (js2-print-ast (js2-unary-node-operand n) 0)
3625 (when postfix
3626 (insert op))))
3627
3628 (cl-defstruct (js2-let-node
3629 (:include js2-scope)
3630 (:constructor nil)
3631 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3632 (pos (js2-current-token-beg))
3633 len vars body
3634 lp rp)))
3635 "AST node for a let expression or a let statement.
3636 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3637 vars ; a `js2-var-decl-node'
3638 body ; a `js2-node' representing the expression or body block
3639 lp
3640 rp)
3641
3642 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3643 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3644
3645 (defun js2-visit-let-node (n v)
3646 (js2-visit-ast (js2-let-node-vars n) v)
3647 (js2-visit-ast (js2-let-node-body n) v))
3648
3649 (defun js2-print-let-node (n i)
3650 (insert (js2-make-pad i) "let (")
3651 (let ((p (point)))
3652 (js2-print-ast (js2-let-node-vars n) 0)
3653 (delete-region p (+ p 4)))
3654 (insert ") ")
3655 (js2-print-ast (js2-let-node-body n) i))
3656
3657 (cl-defstruct (js2-keyword-node
3658 (:include js2-node)
3659 (:constructor nil)
3660 (:constructor make-js2-keyword-node (&key type
3661 (pos (js2-current-token-beg))
3662 (len (- js2-ts-cursor pos)))))
3663 "AST node representing a literal keyword such as `null'.
3664 Used for `null', `this', `true', `false' and `debugger'.
3665 The node type is set to js2-NULL, js2-THIS, etc.")
3666
3667 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3668 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3669
3670 (defun js2-print-keyword-node (n i)
3671 (insert (js2-make-pad i)
3672 (let ((tt (js2-node-type n)))
3673 (cond
3674 ((= tt js2-THIS) "this")
3675 ((= tt js2-SUPER) "super")
3676 ((= tt js2-NULL) "null")
3677 ((= tt js2-TRUE) "true")
3678 ((= tt js2-FALSE) "false")
3679 ((= tt js2-DEBUGGER) "debugger")
3680 (t (error "Invalid keyword literal type: %d" tt))))))
3681
3682 (defsubst js2-this-or-super-node-p (node)
3683 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3684 (let ((type (js2-node-type node)))
3685 (or (eq type js2-THIS) (eq type js2-SUPER))))
3686
3687 (cl-defstruct (js2-new-node
3688 (:include js2-node)
3689 (:constructor nil)
3690 (:constructor make-js2-new-node (&key (type js2-NEW)
3691 (pos (js2-current-token-beg))
3692 len target
3693 args initializer
3694 lp rp)))
3695 "AST node for new-expression such as new Foo()."
3696 target ; an identifier or reference
3697 args ; a Lisp list of argument nodes
3698 lp ; position of left-paren, nil if omitted
3699 rp ; position of right-paren, nil if omitted
3700 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3701
3702 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3703 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3704
3705 (defun js2-visit-new-node (n v)
3706 (js2-visit-ast (js2-new-node-target n) v)
3707 (dolist (arg (js2-new-node-args n))
3708 (js2-visit-ast arg v))
3709 (js2-visit-ast (js2-new-node-initializer n) v))
3710
3711 (defun js2-print-new-node (n i)
3712 (insert (js2-make-pad i) "new ")
3713 (js2-print-ast (js2-new-node-target n))
3714 (insert "(")
3715 (js2-print-list (js2-new-node-args n))
3716 (insert ")")
3717 (when (js2-new-node-initializer n)
3718 (insert " ")
3719 (js2-print-ast (js2-new-node-initializer n))))
3720
3721 (cl-defstruct (js2-name-node
3722 (:include js2-node)
3723 (:constructor nil)
3724 (:constructor make-js2-name-node (&key (type js2-NAME)
3725 (pos (js2-current-token-beg))
3726 (len (- js2-ts-cursor
3727 (js2-current-token-beg)))
3728 (name (js2-current-token-string)))))
3729 "AST node for a JavaScript identifier"
3730 name ; a string
3731 scope) ; a `js2-scope' (optional, used for codegen)
3732
3733 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3734 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3735
3736 (defun js2-print-name-node (n i)
3737 (insert (js2-make-pad i)
3738 (js2-name-node-name n)))
3739
3740 (defsubst js2-name-node-length (node)
3741 "Return identifier length of NODE, a `js2-name-node'.
3742 Returns 0 if NODE is nil or its identifier field is nil."
3743 (if node
3744 (length (js2-name-node-name node))
3745 0))
3746
3747 (cl-defstruct (js2-number-node
3748 (:include js2-node)
3749 (:constructor nil)
3750 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3751 (pos (js2-current-token-beg))
3752 (len (- js2-ts-cursor
3753 (js2-current-token-beg)))
3754 (value (js2-current-token-string))
3755 (num-value (js2-token-number
3756 (js2-current-token))))))
3757 "AST node for a number literal."
3758 value ; the original string, e.g. "6.02e23"
3759 num-value) ; the parsed number value
3760
3761 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3762 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3763
3764 (defun js2-print-number-node (n i)
3765 (insert (js2-make-pad i)
3766 (number-to-string (js2-number-node-num-value n))))
3767
3768 (cl-defstruct (js2-regexp-node
3769 (:include js2-node)
3770 (:constructor nil)
3771 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3772 (pos (js2-current-token-beg))
3773 (len (- js2-ts-cursor
3774 (js2-current-token-beg)))
3775 value flags)))
3776 "AST node for a regular expression literal."
3777 value ; the regexp string, without // delimiters
3778 flags) ; a string of flags, e.g. `mi'.
3779
3780 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3781 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3782
3783 (defun js2-print-regexp (n i)
3784 (insert (js2-make-pad i)
3785 "/"
3786 (js2-regexp-node-value n)
3787 "/")
3788 (if (js2-regexp-node-flags n)
3789 (insert (js2-regexp-node-flags n))))
3790
3791 (cl-defstruct (js2-string-node
3792 (:include js2-node)
3793 (:constructor nil)
3794 (:constructor make-js2-string-node (&key (type js2-STRING)
3795 (pos (js2-current-token-beg))
3796 (len (- js2-ts-cursor
3797 (js2-current-token-beg)))
3798 (value (js2-current-token-string)))))
3799 "String literal.
3800 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3801 You can tell the quote type by looking at the first character."
3802 value) ; the characters of the string, including the quotes
3803
3804 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3805 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3806
3807 (defun js2-print-string-node (n i)
3808 (insert (js2-make-pad i)
3809 (js2-node-string n)))
3810
3811 (cl-defstruct (js2-template-node
3812 (:include js2-node)
3813 (:constructor nil)
3814 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3815 beg len kids)))
3816 "Template literal."
3817 kids) ; `js2-string-node' is used for string segments, other nodes
3818 ; for substitutions inside.
3819
3820 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3821 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3822
3823 (defun js2-visit-template (n callback)
3824 (dolist (kid (js2-template-node-kids n))
3825 (js2-visit-ast kid callback)))
3826
3827 (defun js2-print-template (n i)
3828 (insert (js2-make-pad i))
3829 (dolist (kid (js2-template-node-kids n))
3830 (if (js2-string-node-p kid)
3831 (insert (js2-node-string kid))
3832 (js2-print-ast kid))))
3833
3834 (cl-defstruct (js2-tagged-template-node
3835 (:include js2-node)
3836 (:constructor nil)
3837 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3838 beg len tag template)))
3839 "Tagged template literal."
3840 tag ; `js2-node' with the tag expression.
3841 template) ; `js2-template-node' with the template.
3842
3843 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3844 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3845
3846 (defun js2-visit-tagged-template (n callback)
3847 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3848 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3849
3850 (defun js2-print-tagged-template (n i)
3851 (insert (js2-make-pad i))
3852 (js2-print-ast (js2-tagged-template-node-tag n))
3853 (js2-print-ast (js2-tagged-template-node-template n)))
3854
3855 (cl-defstruct (js2-array-node
3856 (:include js2-node)
3857 (:constructor nil)
3858 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3859 (pos js2-ts-cursor)
3860 len elems)))
3861 "AST node for an array literal."
3862 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3863
3864 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3865 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3866
3867 (defun js2-visit-array-node (n v)
3868 (dolist (e (js2-array-node-elems n))
3869 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3870
3871 (defun js2-print-array-node (n i)
3872 (insert (js2-make-pad i) "[")
3873 (let ((elems (js2-array-node-elems n)))
3874 (js2-print-list elems)
3875 (when (and elems (null (car (last elems))))
3876 (insert ",")))
3877 (insert "]"))
3878
3879 (cl-defstruct (js2-class-node
3880 (:include js2-node)
3881 (:constructor nil)
3882 (:constructor make-js2-class-node (&key (type js2-CLASS)
3883 (pos js2-ts-cursor)
3884 (form 'CLASS_STATEMENT)
3885 (name "")
3886 extends len elems)))
3887 "AST node for an class expression.
3888 `elems' is a list of `js2-object-prop-node', and `extends' is an
3889 optional `js2-expr-node'"
3890 form ; CLASS_{STATEMENT|EXPRESSION}
3891 name ; class name (a `js2-node-name', or nil if anonymous)
3892 extends ; class heritage (a `js2-expr-node', or nil if none)
3893 elems)
3894
3895 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3896 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3897
3898 (defun js2-visit-class-node (n v)
3899 (js2-visit-ast (js2-class-node-name n) v)
3900 (js2-visit-ast (js2-class-node-extends n) v)
3901 (dolist (e (js2-class-node-elems n))
3902 (js2-visit-ast e v)))
3903
3904 (defun js2-print-class-node (n i)
3905 (let* ((pad (js2-make-pad i))
3906 (name (js2-class-node-name n))
3907 (extends (js2-class-node-extends n))
3908 (elems (js2-class-node-elems n)))
3909 (insert pad "class")
3910 (when name
3911 (insert " ")
3912 (js2-print-ast name 0))
3913 (when extends
3914 (insert " extends ")
3915 (js2-print-ast extends))
3916 (insert " {")
3917 (dolist (elem elems)
3918 (insert "\n")
3919 (if (js2-node-get-prop elem 'STATIC)
3920 (progn (insert (js2-make-pad (1+ i)) "static ")
3921 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3922 (js2-print-ast elem (1+ i))))
3923 (insert "\n" pad "}")))
3924
3925 (cl-defstruct (js2-object-node
3926 (:include js2-node)
3927 (:constructor nil)
3928 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3929 (pos js2-ts-cursor)
3930 len
3931 elems)))
3932 "AST node for an object literal expression.
3933 `elems' is a list of `js2-object-prop-node'."
3934 elems)
3935
3936 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3937 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3938
3939 (defun js2-visit-object-node (n v)
3940 (dolist (e (js2-object-node-elems n))
3941 (js2-visit-ast e v)))
3942
3943 (defun js2-print-object-node (n i)
3944 (insert (js2-make-pad i) "{")
3945 (js2-print-list (js2-object-node-elems n))
3946 (insert "}"))
3947
3948 (cl-defstruct (js2-object-prop-node
3949 (:include js2-infix-node)
3950 (:constructor nil)
3951 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3952 (pos js2-ts-cursor)
3953 len left
3954 right op-pos)))
3955 "AST node for an object literal prop:value entry.
3956 The `left' field is the property: a name node, string node or number node.
3957 The `right' field is a `js2-node' representing the initializer value.
3958 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3959 and both fields have the same value.")
3960
3961 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3962 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3963
3964 (defun js2-print-object-prop-node (n i)
3965 (let* ((left (js2-object-prop-node-left n))
3966 (right (js2-object-prop-node-right n))
3967 (computed (not (or (js2-string-node-p left)
3968 (js2-number-node-p left)
3969 (js2-name-node-p left)))))
3970 (insert (js2-make-pad i))
3971 (if computed
3972 (insert "["))
3973 (js2-print-ast left 0)
3974 (if computed
3975 (insert "]"))
3976 (if (not (js2-node-get-prop n 'SHORTHAND))
3977 (progn
3978 (insert ": ")
3979 (js2-print-ast right 0)))))
3980
3981 (cl-defstruct (js2-getter-setter-node
3982 (:include js2-infix-node)
3983 (:constructor nil)
3984 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3985 (pos js2-ts-cursor)
3986 len left right)))
3987 "AST node for a getter/setter property in an object literal.
3988 The `left' field is the `js2-name-node' naming the getter/setter prop.
3989 The `right' field is always an anonymous `js2-function-node' with a node
3990 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3991
3992 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3993 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3994
3995 (defun js2-print-getter-setter (n i)
3996 (let* ((pad (js2-make-pad i))
3997 (left (js2-getter-setter-node-left n))
3998 (right (js2-getter-setter-node-right n))
3999 (computed (not (or (js2-string-node-p left)
4000 (js2-number-node-p left)
4001 (js2-name-node-p left)))))
4002 (insert pad)
4003 (if (/= (js2-node-type n) js2-FUNCTION)
4004 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
4005 (when (and (js2-function-node-p right)
4006 (eq 'STAR (js2-function-node-generator-type right)))
4007 (insert "*"))
4008 (when computed
4009 (insert "["))
4010 (js2-print-ast left 0)
4011 (when computed
4012 (insert "]"))
4013 (js2-print-ast right 0)))
4014
4015 (cl-defstruct (js2-prop-get-node
4016 (:include js2-infix-node)
4017 (:constructor nil)
4018 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
4019 (pos js2-ts-cursor)
4020 len left right)))
4021 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
4022
4023 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4024 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4025
4026 (defun js2-visit-prop-get-node (n v)
4027 (js2-visit-ast (js2-prop-get-node-left n) v)
4028 (js2-visit-ast (js2-prop-get-node-right n) v))
4029
4030 (defun js2-print-prop-get-node (n i)
4031 (insert (js2-make-pad i))
4032 (js2-print-ast (js2-prop-get-node-left n) 0)
4033 (insert ".")
4034 (js2-print-ast (js2-prop-get-node-right n) 0))
4035
4036 (cl-defstruct (js2-elem-get-node
4037 (:include js2-node)
4038 (:constructor nil)
4039 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4040 (pos js2-ts-cursor)
4041 len target element
4042 lb rb)))
4043 "AST node for an array index expression such as foo[bar]."
4044 target ; a `js2-node' - the expression preceding the "."
4045 element ; a `js2-node' - the expression in brackets
4046 lb ; position of left-bracket, nil if omitted
4047 rb) ; position of right-bracket, nil if omitted
4048
4049 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4050 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4051
4052 (defun js2-visit-elem-get-node (n v)
4053 (js2-visit-ast (js2-elem-get-node-target n) v)
4054 (js2-visit-ast (js2-elem-get-node-element n) v))
4055
4056 (defun js2-print-elem-get-node (n i)
4057 (insert (js2-make-pad i))
4058 (js2-print-ast (js2-elem-get-node-target n) 0)
4059 (insert "[")
4060 (js2-print-ast (js2-elem-get-node-element n) 0)
4061 (insert "]"))
4062
4063 (cl-defstruct (js2-call-node
4064 (:include js2-node)
4065 (:constructor nil)
4066 (:constructor make-js2-call-node (&key (type js2-CALL)
4067 (pos js2-ts-cursor)
4068 len target args
4069 lp rp)))
4070 "AST node for a JavaScript function call."
4071 target ; a `js2-node' evaluating to the function to call
4072 args ; a Lisp list of `js2-node' arguments
4073 lp ; position of open-paren, or nil if missing
4074 rp) ; position of close-paren, or nil if missing
4075
4076 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4077 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4078
4079 (defun js2-visit-call-node (n v)
4080 (js2-visit-ast (js2-call-node-target n) v)
4081 (dolist (arg (js2-call-node-args n))
4082 (js2-visit-ast arg v)))
4083
4084 (defun js2-print-call-node (n i)
4085 (insert (js2-make-pad i))
4086 (js2-print-ast (js2-call-node-target n) 0)
4087 (insert "(")
4088 (js2-print-list (js2-call-node-args n))
4089 (insert ")"))
4090
4091 (cl-defstruct (js2-yield-node
4092 (:include js2-node)
4093 (:constructor nil)
4094 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4095 (pos js2-ts-cursor)
4096 len value star-p)))
4097 "AST node for yield statement or expression."
4098 star-p ; whether it's yield*
4099 value) ; optional: value to be yielded
4100
4101 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4102 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4103
4104 (defun js2-visit-yield-node (n v)
4105 (js2-visit-ast (js2-yield-node-value n) v))
4106
4107 (defun js2-print-yield-node (n i)
4108 (insert (js2-make-pad i))
4109 (insert "yield")
4110 (when (js2-yield-node-star-p n)
4111 (insert "*"))
4112 (when (js2-yield-node-value n)
4113 (insert " ")
4114 (js2-print-ast (js2-yield-node-value n) 0)))
4115
4116 (cl-defstruct (js2-paren-node
4117 (:include js2-node)
4118 (:constructor nil)
4119 (:constructor make-js2-paren-node (&key (type js2-LP)
4120 (pos js2-ts-cursor)
4121 len expr)))
4122 "AST node for a parenthesized expression.
4123 In particular, used when the parens are syntactically optional,
4124 as opposed to required parens such as those enclosing an if-conditional."
4125 expr) ; `js2-node'
4126
4127 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4128 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4129
4130 (defun js2-visit-paren-node (n v)
4131 (js2-visit-ast (js2-paren-node-expr n) v))
4132
4133 (defun js2-print-paren-node (n i)
4134 (insert (js2-make-pad i))
4135 (insert "(")
4136 (js2-print-ast (js2-paren-node-expr n) 0)
4137 (insert ")"))
4138
4139 (cl-defstruct (js2-comp-node
4140 (:include js2-scope)
4141 (:constructor nil)
4142 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4143 (pos js2-ts-cursor)
4144 len result
4145 loops filters
4146 form)))
4147 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4148 result ; result expression (just after left-bracket)
4149 loops ; a Lisp list of `js2-comp-loop-node'
4150 filters ; a Lisp list of guard/filter expressions
4151 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4152 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4153 )
4154
4155 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4156 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4157
4158 (defun js2-visit-comp-node (n v)
4159 (js2-visit-ast (js2-comp-node-result n) v)
4160 (dolist (l (js2-comp-node-loops n))
4161 (js2-visit-ast l v))
4162 (dolist (f (js2-comp-node-filters n))
4163 (js2-visit-ast f v)))
4164
4165 (defun js2-print-comp-node (n i)
4166 (let ((pad (js2-make-pad i))
4167 (result (js2-comp-node-result n))
4168 (loops (js2-comp-node-loops n))
4169 (filters (js2-comp-node-filters n))
4170 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4171 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4172 (insert pad (if gen-p "(" "["))
4173 (when legacy-p
4174 (js2-print-ast result 0))
4175 (dolist (l loops)
4176 (when legacy-p
4177 (insert " "))
4178 (js2-print-ast l 0)
4179 (unless legacy-p
4180 (insert " ")))
4181 (dolist (f filters)
4182 (when legacy-p
4183 (insert " "))
4184 (insert "if (")
4185 (js2-print-ast f 0)
4186 (insert ")")
4187 (unless legacy-p
4188 (insert " ")))
4189 (unless legacy-p
4190 (js2-print-ast result 0))
4191 (insert (if gen-p ")" "]"))))
4192
4193 (cl-defstruct (js2-comp-loop-node
4194 (:include js2-for-in-node)
4195 (:constructor nil)
4196 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4197 (pos js2-ts-cursor)
4198 len iterator
4199 object in-pos
4200 foreach-p
4201 each-pos
4202 forof-p
4203 lp rp)))
4204 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4205
4206 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4207 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4208
4209 (defun js2-visit-comp-loop (n v)
4210 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4211 (js2-visit-ast (js2-comp-loop-node-object n) v))
4212
4213 (defun js2-print-comp-loop (n _i)
4214 (insert "for ")
4215 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4216 (insert "(")
4217 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4218 (insert (if (js2-comp-loop-node-forof-p n)
4219 " of " " in "))
4220 (js2-print-ast (js2-comp-loop-node-object n) 0)
4221 (insert ")"))
4222
4223 (cl-defstruct (js2-empty-expr-node
4224 (:include js2-node)
4225 (:constructor nil)
4226 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4227 (pos (js2-current-token-beg))
4228 len)))
4229 "AST node for an empty expression.")
4230
4231 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4232 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4233
4234 (cl-defstruct (js2-xml-node
4235 (:include js2-block-node)
4236 (:constructor nil)
4237 (:constructor make-js2-xml-node (&key (type js2-XML)
4238 (pos (js2-current-token-beg))
4239 len kids)))
4240 "AST node for initial parse of E4X literals.
4241 The kids field is a list of XML fragments, each a `js2-string-node' or
4242 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4243
4244 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4245 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4246
4247 (defun js2-print-xml-node (n i)
4248 (dolist (kid (js2-xml-node-kids n))
4249 (js2-print-ast kid i)))
4250
4251 (cl-defstruct (js2-xml-js-expr-node
4252 (:include js2-xml-node)
4253 (:constructor nil)
4254 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4255 (pos js2-ts-cursor)
4256 len expr)))
4257 "AST node for an embedded JavaScript {expression} in an E4X literal.
4258 The start and end fields correspond to the curly-braces."
4259 expr) ; a `js2-expr-node' of some sort
4260
4261 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4262 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4263
4264 (defun js2-visit-xml-js-expr (n v)
4265 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4266
4267 (defun js2-print-xml-js-expr (n i)
4268 (insert (js2-make-pad i))
4269 (insert "{")
4270 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4271 (insert "}"))
4272
4273 (cl-defstruct (js2-xml-dot-query-node
4274 (:include js2-infix-node)
4275 (:constructor nil)
4276 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4277 (pos js2-ts-cursor)
4278 op-pos len left
4279 right rp)))
4280 "AST node for an E4X foo.(bar) filter expression.
4281 Note that the left-paren is automatically the character immediately
4282 following the dot (.) in the operator. No whitespace is permitted
4283 between the dot and the lp by the scanner."
4284 rp)
4285
4286 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4287 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4288
4289 (defun js2-print-xml-dot-query (n i)
4290 (insert (js2-make-pad i))
4291 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4292 (insert ".(")
4293 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4294 (insert ")"))
4295
4296 (cl-defstruct (js2-xml-ref-node
4297 (:include js2-node)
4298 (:constructor nil)) ; abstract
4299 "Base type for E4X XML attribute-access or property-get expressions.
4300 Such expressions can take a variety of forms. The general syntax has
4301 three parts:
4302
4303 - (optional) an @ (specifying an attribute access)
4304 - (optional) a namespace (a `js2-name-node') and double-colon
4305 - (required) either a `js2-name-node' or a bracketed [expression]
4306
4307 The property-name expressions (examples: ns::name, @name) are
4308 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4309 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4310
4311 This node type (or more specifically, its subclasses) will sometimes
4312 be the right-hand child of a `js2-prop-get-node' or a
4313 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4314 The `js2-xml-ref-node' may also be a standalone primary expression with
4315 no explicit target, which is valid in certain expression contexts such as
4316
4317 company..employee.(@id < 100)
4318
4319 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4320 expression whose parent is a `js2-xml-dot-query-node'."
4321 namespace
4322 at-pos
4323 colon-pos)
4324
4325 (defsubst js2-xml-ref-node-attr-access-p (node)
4326 "Return non-nil if this expression began with an @-token."
4327 (and (numberp (js2-xml-ref-node-at-pos node))
4328 (cl-plusp (js2-xml-ref-node-at-pos node))))
4329
4330 (cl-defstruct (js2-xml-prop-ref-node
4331 (:include js2-xml-ref-node)
4332 (:constructor nil)
4333 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4334 (pos (js2-current-token-beg))
4335 len propname
4336 namespace at-pos
4337 colon-pos)))
4338 "AST node for an E4X XML [expr] property-ref expression.
4339 The JavaScript syntax is an optional @, an optional ns::, and a name.
4340
4341 [ '@' ] [ name '::' ] name
4342
4343 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4344 @ns::*, @*::attr, @*::*, and @*.
4345
4346 The node starts at the @ token, if present. Otherwise it starts at the
4347 namespace name. The node bounds extend through the closing right-bracket,
4348 or if it is missing due to a syntax error, through the end of the index
4349 expression."
4350 propname)
4351
4352 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4353 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4354
4355 (defun js2-visit-xml-prop-ref-node (n v)
4356 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4357 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4358
4359 (defun js2-print-xml-prop-ref-node (n i)
4360 (insert (js2-make-pad i))
4361 (if (js2-xml-ref-node-attr-access-p n)
4362 (insert "@"))
4363 (when (js2-xml-prop-ref-node-namespace n)
4364 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4365 (insert "::"))
4366 (if (js2-xml-prop-ref-node-propname n)
4367 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4368
4369 (cl-defstruct (js2-xml-elem-ref-node
4370 (:include js2-xml-ref-node)
4371 (:constructor nil)
4372 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4373 (pos (js2-current-token-beg))
4374 len expr lb rb
4375 namespace at-pos
4376 colon-pos)))
4377 "AST node for an E4X XML [expr] member-ref expression.
4378 Syntax:
4379
4380 [ '@' ] [ name '::' ] '[' expr ']'
4381
4382 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4383
4384 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4385 is not a legal E4X XML element-ref expression, since it's already used
4386 for standard JavaScript element-get array indexing. Hence, a
4387 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4388 non-nil namespace node, or both.
4389
4390 The node starts at the @ token, if present. Otherwise it starts
4391 at the namespace name. The node bounds extend through the closing
4392 right-bracket, or if it is missing due to a syntax error, through the
4393 end of the index expression."
4394 expr ; the bracketed index expression
4395 lb
4396 rb)
4397
4398 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4399 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4400
4401 (defun js2-visit-xml-elem-ref-node (n v)
4402 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4403 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4404
4405 (defun js2-print-xml-elem-ref-node (n i)
4406 (insert (js2-make-pad i))
4407 (if (js2-xml-ref-node-attr-access-p n)
4408 (insert "@"))
4409 (when (js2-xml-elem-ref-node-namespace n)
4410 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4411 (insert "::"))
4412 (insert "[")
4413 (if (js2-xml-elem-ref-node-expr n)
4414 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4415 (insert "]"))
4416
4417 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4418
4419 (cl-defstruct (js2-xml-start-tag-node
4420 (:include js2-xml-node)
4421 (:constructor nil)
4422 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4423 (pos js2-ts-cursor)
4424 len name attrs kids
4425 empty-p)))
4426 "AST node for an XML start-tag. Not currently used.
4427 The `kids' field is a Lisp list of child content nodes."
4428 name ; a `js2-xml-name-node'
4429 attrs ; a Lisp list of `js2-xml-attr-node'
4430 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4431
4432 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4433 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4434
4435 (defun js2-visit-xml-start-tag (n v)
4436 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4437 (dolist (attr (js2-xml-start-tag-node-attrs n))
4438 (js2-visit-ast attr v))
4439 (js2-visit-block n v))
4440
4441 (defun js2-print-xml-start-tag (n i)
4442 (insert (js2-make-pad i) "<")
4443 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4444 (when (js2-xml-start-tag-node-attrs n)
4445 (insert " ")
4446 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4447 (insert ">"))
4448
4449 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4450 ;; and add the end-tag to the kids list of the parent as well.
4451 (cl-defstruct (js2-xml-end-tag-node
4452 (:include js2-xml-node)
4453 (:constructor nil)
4454 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4455 (pos js2-ts-cursor)
4456 len name)))
4457 "AST node for an XML end-tag. Not currently used."
4458 name) ; a `js2-xml-name-node'
4459
4460 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4461 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4462
4463 (defun js2-visit-xml-end-tag (n v)
4464 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4465
4466 (defun js2-print-xml-end-tag (n i)
4467 (insert (js2-make-pad i))
4468 (insert "</")
4469 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4470 (insert ">"))
4471
4472 (cl-defstruct (js2-xml-name-node
4473 (:include js2-xml-node)
4474 (:constructor nil)
4475 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4476 (pos js2-ts-cursor)
4477 len namespace kids)))
4478 "AST node for an E4X XML name. Not currently used.
4479 Any XML name can be qualified with a namespace, hence the namespace field.
4480 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4481 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4482 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4483 namespace) ; a `js2-string-node'
4484
4485 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4486 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4487
4488 (defun js2-visit-xml-name-node (n v)
4489 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4490
4491 (defun js2-print-xml-name-node (n i)
4492 (insert (js2-make-pad i))
4493 (when (js2-xml-name-node-namespace n)
4494 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4495 (insert "::"))
4496 (dolist (kid (js2-xml-name-node-kids n))
4497 (js2-print-ast kid 0)))
4498
4499 (cl-defstruct (js2-xml-pi-node
4500 (:include js2-xml-node)
4501 (:constructor nil)
4502 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4503 (pos js2-ts-cursor)
4504 len name attrs)))
4505 "AST node for an E4X XML processing instruction. Not currently used."
4506 name ; a `js2-xml-name-node'
4507 attrs) ; a list of `js2-xml-attr-node'
4508
4509 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4510 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4511
4512 (defun js2-visit-xml-pi-node (n v)
4513 (js2-visit-ast (js2-xml-pi-node-name n) v)
4514 (dolist (attr (js2-xml-pi-node-attrs n))
4515 (js2-visit-ast attr v)))
4516
4517 (defun js2-print-xml-pi-node (n i)
4518 (insert (js2-make-pad i) "<?")
4519 (js2-print-ast (js2-xml-pi-node-name n))
4520 (when (js2-xml-pi-node-attrs n)
4521 (insert " ")
4522 (js2-print-list (js2-xml-pi-node-attrs n)))
4523 (insert "?>"))
4524
4525 (cl-defstruct (js2-xml-cdata-node
4526 (:include js2-xml-node)
4527 (:constructor nil)
4528 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4529 (pos js2-ts-cursor)
4530 len content)))
4531 "AST node for a CDATA escape section. Not currently used."
4532 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4533
4534 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4535 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4536
4537 (defun js2-visit-xml-cdata-node (n v)
4538 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4539
4540 (defun js2-print-xml-cdata-node (n i)
4541 (insert (js2-make-pad i))
4542 (js2-print-ast (js2-xml-cdata-node-content n)))
4543
4544 (cl-defstruct (js2-xml-attr-node
4545 (:include js2-xml-node)
4546 (:constructor nil)
4547 (:constructor make-js2-attr-node (&key (type js2-XML)
4548 (pos js2-ts-cursor)
4549 len name value
4550 eq-pos quote-type)))
4551 "AST node representing a foo='bar' XML attribute value. Not yet used."
4552 name ; a `js2-xml-name-node'
4553 value ; a `js2-xml-name-node'
4554 eq-pos ; buffer position of "=" sign
4555 quote-type) ; 'single or 'double
4556
4557 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4558 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4559
4560 (defun js2-visit-xml-attr-node (n v)
4561 (js2-visit-ast (js2-xml-attr-node-name n) v)
4562 (js2-visit-ast (js2-xml-attr-node-value n) v))
4563
4564 (defun js2-print-xml-attr-node (n i)
4565 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4566 "'"
4567 "\"")))
4568 (insert (js2-make-pad i))
4569 (js2-print-ast (js2-xml-attr-node-name n) 0)
4570 (insert "=" quote)
4571 (js2-print-ast (js2-xml-attr-node-value n) 0)
4572 (insert quote)))
4573
4574 (cl-defstruct (js2-xml-text-node
4575 (:include js2-xml-node)
4576 (:constructor nil)
4577 (:constructor make-js2-text-node (&key (type js2-XML)
4578 (pos js2-ts-cursor)
4579 len content)))
4580 "AST node for an E4X XML text node. Not currently used."
4581 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4582
4583 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4584 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4585
4586 (defun js2-visit-xml-text-node (n v)
4587 (js2-visit-ast (js2-xml-text-node-content n) v))
4588
4589 (defun js2-print-xml-text-node (n i)
4590 (insert (js2-make-pad i))
4591 (dolist (kid (js2-xml-text-node-content n))
4592 (js2-print-ast kid)))
4593
4594 (cl-defstruct (js2-xml-comment-node
4595 (:include js2-xml-node)
4596 (:constructor nil)
4597 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4598 (pos js2-ts-cursor)
4599 len)))
4600 "AST node for E4X XML comment. Not currently used.")
4601
4602 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4603 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4604
4605 (defun js2-print-xml-comment (n i)
4606 (insert (js2-make-pad i)
4607 (js2-node-string n)))
4608
4609 ;;; Node utilities
4610
4611 (defsubst js2-node-line (n)
4612 "Fetch the source line number at the start of node N.
4613 This is O(n) in the length of the source buffer; use prudently."
4614 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4615
4616 (defsubst js2-block-node-kid (n i)
4617 "Return child I of node N, or nil if there aren't that many."
4618 (nth i (js2-block-node-kids n)))
4619
4620 (defsubst js2-block-node-first (n)
4621 "Return first child of block node N, or nil if there is none."
4622 (cl-first (js2-block-node-kids n)))
4623
4624 (defun js2-node-root (n)
4625 "Return the root of the AST containing N.
4626 If N has no parent pointer, returns N."
4627 (let ((parent (js2-node-parent n)))
4628 (if parent
4629 (js2-node-root parent)
4630 n)))
4631
4632 (defsubst js2-node-short-name (n)
4633 "Return the short name of node N as a string, e.g. `js2-if-node'."
4634 (substring (symbol-name (aref n 0))
4635 (length "cl-struct-")))
4636
4637 (defun js2-node-child-list (node)
4638 "Return the child list for NODE, a Lisp list of nodes.
4639 Works for block nodes, array nodes, obj literals, funarg lists,
4640 var decls and try nodes (for catch clauses). Note that you should call
4641 `js2-block-node-kids' on the function body for the body statements.
4642 Returns nil for zero-length child lists or unsupported nodes."
4643 (cond
4644 ((js2-function-node-p node)
4645 (js2-function-node-params node))
4646 ((js2-block-node-p node)
4647 (js2-block-node-kids node))
4648 ((js2-try-node-p node)
4649 (js2-try-node-catch-clauses node))
4650 ((js2-array-node-p node)
4651 (js2-array-node-elems node))
4652 ((js2-object-node-p node)
4653 (js2-object-node-elems node))
4654 ((js2-call-node-p node)
4655 (js2-call-node-args node))
4656 ((js2-new-node-p node)
4657 (js2-new-node-args node))
4658 ((js2-var-decl-node-p node)
4659 (js2-var-decl-node-kids node))
4660 (t
4661 nil)))
4662
4663 (defun js2-node-set-child-list (node kids)
4664 "Set the child list for NODE to KIDS."
4665 (cond
4666 ((js2-function-node-p node)
4667 (setf (js2-function-node-params node) kids))
4668 ((js2-block-node-p node)
4669 (setf (js2-block-node-kids node) kids))
4670 ((js2-try-node-p node)
4671 (setf (js2-try-node-catch-clauses node) kids))
4672 ((js2-array-node-p node)
4673 (setf (js2-array-node-elems node) kids))
4674 ((js2-object-node-p node)
4675 (setf (js2-object-node-elems node) kids))
4676 ((js2-call-node-p node)
4677 (setf (js2-call-node-args node) kids))
4678 ((js2-new-node-p node)
4679 (setf (js2-new-node-args node) kids))
4680 ((js2-var-decl-node-p node)
4681 (setf (js2-var-decl-node-kids node) kids))
4682 (t
4683 (error "Unsupported node type: %s" (js2-node-short-name node))))
4684 kids)
4685
4686 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4687 (defconst js2-paren-expr-nodes
4688 '(cl-struct-js2-comp-loop-node
4689 cl-struct-js2-comp-node
4690 cl-struct-js2-call-node
4691 cl-struct-js2-catch-node
4692 cl-struct-js2-do-node
4693 cl-struct-js2-elem-get-node
4694 cl-struct-js2-for-in-node
4695 cl-struct-js2-for-node
4696 cl-struct-js2-function-node
4697 cl-struct-js2-if-node
4698 cl-struct-js2-let-node
4699 cl-struct-js2-new-node
4700 cl-struct-js2-paren-node
4701 cl-struct-js2-switch-node
4702 cl-struct-js2-while-node
4703 cl-struct-js2-with-node
4704 cl-struct-js2-xml-dot-query-node)
4705 "Node types that can have a parenthesized child expression.
4706 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4707
4708 (defsubst js2-paren-expr-node-p (node)
4709 "Return t for nodes that typically have a parenthesized child expression.
4710 Useful for computing the indentation anchors for arg-lists and conditions.
4711 Note that it may return a false positive, for instance when NODE is
4712 a `js2-new-node' and there are no arguments or parentheses."
4713 (memq (aref node 0) js2-paren-expr-nodes))
4714
4715 ;; Fake polymorphism... yech.
4716 (defun js2-node-lp (node)
4717 "Return relative left-paren position for NODE, if applicable.
4718 For `js2-elem-get-node' structs, returns left-bracket position.
4719 Note that the position may be nil in the case of a parse error."
4720 (cond
4721 ((js2-elem-get-node-p node)
4722 (js2-elem-get-node-lb node))
4723 ((js2-loop-node-p node)
4724 (js2-loop-node-lp node))
4725 ((js2-function-node-p node)
4726 (js2-function-node-lp node))
4727 ((js2-if-node-p node)
4728 (js2-if-node-lp node))
4729 ((js2-new-node-p node)
4730 (js2-new-node-lp node))
4731 ((js2-call-node-p node)
4732 (js2-call-node-lp node))
4733 ((js2-paren-node-p node)
4734 0)
4735 ((js2-switch-node-p node)
4736 (js2-switch-node-lp node))
4737 ((js2-catch-node-p node)
4738 (js2-catch-node-lp node))
4739 ((js2-let-node-p node)
4740 (js2-let-node-lp node))
4741 ((js2-comp-node-p node)
4742 0)
4743 ((js2-with-node-p node)
4744 (js2-with-node-lp node))
4745 ((js2-xml-dot-query-node-p node)
4746 (1+ (js2-infix-node-op-pos node)))
4747 (t
4748 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4749
4750 ;; Fake polymorphism... blech.
4751 (defun js2-node-rp (node)
4752 "Return relative right-paren position for NODE, if applicable.
4753 For `js2-elem-get-node' structs, returns right-bracket position.
4754 Note that the position may be nil in the case of a parse error."
4755 (cond
4756 ((js2-elem-get-node-p node)
4757 (js2-elem-get-node-rb node))
4758 ((js2-loop-node-p node)
4759 (js2-loop-node-rp node))
4760 ((js2-function-node-p node)
4761 (js2-function-node-rp node))
4762 ((js2-if-node-p node)
4763 (js2-if-node-rp node))
4764 ((js2-new-node-p node)
4765 (js2-new-node-rp node))
4766 ((js2-call-node-p node)
4767 (js2-call-node-rp node))
4768 ((js2-paren-node-p node)
4769 (1- (js2-node-len node)))
4770 ((js2-switch-node-p node)
4771 (js2-switch-node-rp node))
4772 ((js2-catch-node-p node)
4773 (js2-catch-node-rp node))
4774 ((js2-let-node-p node)
4775 (js2-let-node-rp node))
4776 ((js2-comp-node-p node)
4777 (1- (js2-node-len node)))
4778 ((js2-with-node-p node)
4779 (js2-with-node-rp node))
4780 ((js2-xml-dot-query-node-p node)
4781 (1+ (js2-xml-dot-query-node-rp node)))
4782 (t
4783 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4784
4785 (defsubst js2-node-first-child (node)
4786 "Return the first element of `js2-node-child-list' for NODE."
4787 (car (js2-node-child-list node)))
4788
4789 (defsubst js2-node-last-child (node)
4790 "Return the last element of `js2-node-last-child' for NODE."
4791 (car (last (js2-node-child-list node))))
4792
4793 (defun js2-node-prev-sibling (node)
4794 "Return the previous statement in parent.
4795 Works for parents supported by `js2-node-child-list'.
4796 Returns nil if NODE is not in the parent, or PARENT is
4797 not a supported node, or if NODE is the first child."
4798 (let* ((p (js2-node-parent node))
4799 (kids (js2-node-child-list p))
4800 (sib (car kids)))
4801 (while (and kids
4802 (not (eq node (cadr kids))))
4803 (setq kids (cdr kids)
4804 sib (car kids)))
4805 sib))
4806
4807 (defun js2-node-next-sibling (node)
4808 "Return the next statement in parent block.
4809 Returns nil if NODE is not in the block, or PARENT is not
4810 a block node, or if NODE is the last statement."
4811 (let* ((p (js2-node-parent node))
4812 (kids (js2-node-child-list p)))
4813 (while (and kids
4814 (not (eq node (car kids))))
4815 (setq kids (cdr kids)))
4816 (cadr kids)))
4817
4818 (defun js2-node-find-child-before (pos parent &optional after)
4819 "Find the last child that starts before POS in parent.
4820 If AFTER is non-nil, returns first child starting after POS.
4821 POS is an absolute buffer position. PARENT is any node
4822 supported by `js2-node-child-list'.
4823 Returns nil if no applicable child is found."
4824 (let ((kids (if (js2-function-node-p parent)
4825 (js2-block-node-kids (js2-function-node-body parent))
4826 (js2-node-child-list parent)))
4827 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4828 (js2-function-node-body parent)
4829 parent)))
4830 kid result fn
4831 (continue t))
4832 (setq fn (if after '>= '<))
4833 (while (and kids continue)
4834 (setq kid (car kids))
4835 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4836 (setq result kid
4837 continue (not after))
4838 (setq continue after))
4839 (setq kids (cdr kids)))
4840 result))
4841
4842 (defun js2-node-find-child-after (pos parent)
4843 "Find first child that starts after POS in parent.
4844 POS is an absolute buffer position. PARENT is any node
4845 supported by `js2-node-child-list'.
4846 Returns nil if no applicable child is found."
4847 (js2-node-find-child-before pos parent 'after))
4848
4849 (defun js2-node-replace-child (pos parent new-node)
4850 "Replace node at index POS in PARENT with NEW-NODE.
4851 Only works for parents supported by `js2-node-child-list'."
4852 (let ((kids (js2-node-child-list parent))
4853 (i 0))
4854 (while (< i pos)
4855 (setq kids (cdr kids)
4856 i (1+ i)))
4857 (setcar kids new-node)
4858 (js2-node-add-children parent new-node)))
4859
4860 (defun js2-node-buffer (n)
4861 "Return the buffer associated with AST N.
4862 Returns nil if the buffer is not set as a property on the root
4863 node, or if parent links were not recorded during parsing."
4864 (let ((root (js2-node-root n)))
4865 (and root
4866 (js2-ast-root-p root)
4867 (js2-ast-root-buffer root))))
4868
4869 (defun js2-block-node-push (n kid)
4870 "Push js2-node KID onto the end of js2-block-node N's child list.
4871 KID is always added to the -end- of the kids list.
4872 Function also calls `js2-node-add-children' to add the parent link."
4873 (let ((kids (js2-node-child-list n)))
4874 (if kids
4875 (setcdr kids (nconc (cdr kids) (list kid)))
4876 (js2-node-set-child-list n (list kid)))
4877 (js2-node-add-children n kid)))
4878
4879 (defun js2-node-string (node)
4880 (with-current-buffer (or (js2-node-buffer node)
4881 (error "No buffer available for node %s" node))
4882 (let ((pos (js2-node-abs-pos node)))
4883 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4884
4885 ;; Container for storing the node we're looking for in a traversal.
4886 (js2-deflocal js2-discovered-node nil)
4887
4888 ;; Keep track of absolute node position during traversals.
4889 (js2-deflocal js2-visitor-offset nil)
4890
4891 (js2-deflocal js2-node-search-point nil)
4892
4893 (when js2-mode-dev-mode-p
4894 (defun js2-find-node-at-point ()
4895 (interactive)
4896 (let ((node (js2-node-at-point)))
4897 (message "%s" (or node "No node found at point"))))
4898 (defun js2-node-name-at-point ()
4899 (interactive)
4900 (let ((node (js2-node-at-point)))
4901 (message "%s" (if node
4902 (js2-node-short-name node)
4903 "No node found at point.")))))
4904
4905 (defun js2-node-at-point (&optional pos skip-comments)
4906 "Return AST node at POS, a buffer position, defaulting to current point.
4907 The `js2-mode-ast' variable must be set to the current parse tree.
4908 Signals an error if the AST (`js2-mode-ast') is nil.
4909 Always returns a node - if it can't find one, it returns the root.
4910 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4911 (let ((ast js2-mode-ast)
4912 result)
4913 (unless ast
4914 (error "No JavaScript AST available"))
4915 ;; Look through comments first, since they may be inside nodes that
4916 ;; would otherwise report a match.
4917 (setq pos (or pos (point))
4918 result (if (> pos (js2-node-abs-end ast))
4919 ast
4920 (if (not skip-comments)
4921 (js2-comment-at-point pos))))
4922 (unless result
4923 (setq js2-discovered-node nil
4924 js2-visitor-offset 0
4925 js2-node-search-point pos)
4926 (unwind-protect
4927 (catch 'js2-visit-done
4928 (js2-visit-ast ast #'js2-node-at-point-visitor))
4929 (setq js2-visitor-offset nil
4930 js2-node-search-point nil))
4931 (setq result js2-discovered-node))
4932 ;; may have found a comment beyond end of last child node,
4933 ;; since visiting the ast-root looks at the comment-list last.
4934 (if (and skip-comments
4935 (js2-comment-node-p result))
4936 (setq result nil))
4937 (or result js2-mode-ast)))
4938
4939 (defun js2-node-at-point-visitor (node end-p)
4940 (let ((rel-pos (js2-node-pos node))
4941 abs-pos
4942 abs-end
4943 (point js2-node-search-point))
4944 (cond
4945 (end-p
4946 ;; this evaluates to a non-nil return value, even if it's zero
4947 (cl-decf js2-visitor-offset rel-pos))
4948 ;; we already looked for comments before visiting, and don't want them now
4949 ((js2-comment-node-p node)
4950 nil)
4951 (t
4952 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4953 ;; we only want to use the node if the point is before
4954 ;; the last character position in the node, so we decrement
4955 ;; the absolute end by 1.
4956 abs-end (+ abs-pos (js2-node-len node) -1))
4957 (cond
4958 ;; If this node starts after search-point, stop the search.
4959 ((> abs-pos point)
4960 (throw 'js2-visit-done nil))
4961 ;; If this node ends before the search-point, don't check kids.
4962 ((> point abs-end)
4963 nil)
4964 (t
4965 ;; Otherwise point is within this node, possibly in a child.
4966 (setq js2-discovered-node node)
4967 t)))))) ; keep processing kids to look for more specific match
4968
4969 (defsubst js2-block-comment-p (node)
4970 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4971 (and (js2-comment-node-p node)
4972 (memq (js2-comment-node-format node) '(jsdoc block))))
4973
4974 ;; TODO: put the comments in a vector and binary-search them instead
4975 (defun js2-comment-at-point (&optional pos)
4976 "Look through scanned comment nodes for one containing POS.
4977 POS is a buffer position that defaults to current point.
4978 Function returns nil if POS was not in any comment node."
4979 (let ((ast js2-mode-ast)
4980 (x (or pos (point)))
4981 beg end)
4982 (unless ast
4983 (error "No JavaScript AST available"))
4984 (catch 'done
4985 ;; Comments are stored in lexical order.
4986 (dolist (comment (js2-ast-root-comments ast) nil)
4987 (setq beg (js2-node-abs-pos comment)
4988 end (+ beg (js2-node-len comment)))
4989 (if (and (>= x beg)
4990 (<= x end))
4991 (throw 'done comment))))))
4992
4993 (defun js2-mode-find-parent-fn (node)
4994 "Find function enclosing NODE.
4995 Returns nil if NODE is not inside a function."
4996 (setq node (js2-node-parent node))
4997 (while (and node (not (js2-function-node-p node)))
4998 (setq node (js2-node-parent node)))
4999 (and (js2-function-node-p node) node))
5000
5001 (defun js2-mode-find-enclosing-fn (node)
5002 "Find function or root enclosing NODE."
5003 (if (js2-ast-root-p node)
5004 node
5005 (setq node (js2-node-parent node))
5006 (while (not (or (js2-ast-root-p node)
5007 (js2-function-node-p node)))
5008 (setq node (js2-node-parent node)))
5009 node))
5010
5011 (defun js2-mode-find-enclosing-node (beg end)
5012 "Find node fully enclosing BEG and END."
5013 (let ((node (js2-node-at-point beg))
5014 pos
5015 (continue t))
5016 (while continue
5017 (if (or (js2-ast-root-p node)
5018 (and
5019 (<= (setq pos (js2-node-abs-pos node)) beg)
5020 (>= (+ pos (js2-node-len node)) end)))
5021 (setq continue nil)
5022 (setq node (js2-node-parent node))))
5023 node))
5024
5025 (defun js2-node-parent-script-or-fn (node)
5026 "Find script or function immediately enclosing NODE.
5027 If NODE is the ast-root, returns nil."
5028 (if (js2-ast-root-p node)
5029 nil
5030 (setq node (js2-node-parent node))
5031 (while (and node (not (or (js2-function-node-p node)
5032 (js2-script-node-p node))))
5033 (setq node (js2-node-parent node)))
5034 node))
5035
5036 (defun js2-node-is-descendant (node ancestor)
5037 "Return t if NODE is a descendant of ANCESTOR."
5038 (while (and node
5039 (not (eq node ancestor)))
5040 (setq node (js2-node-parent node)))
5041 node)
5042
5043 ;;; visitor infrastructure
5044
5045 (defun js2-visit-none (_node _callback)
5046 "Visitor for AST node that have no node children."
5047 nil)
5048
5049 (defun js2-print-none (_node _indent)
5050 "Visitor for AST node with no printed representation.")
5051
5052 (defun js2-print-body (node indent)
5053 "Print a statement, or a block without braces."
5054 (if (js2-block-node-p node)
5055 (dolist (kid (js2-block-node-kids node))
5056 (js2-print-ast kid indent))
5057 (js2-print-ast node indent)))
5058
5059 (defun js2-print-list (args &optional delimiter)
5060 (cl-loop with len = (length args)
5061 for arg in args
5062 for count from 1
5063 do
5064 (when arg (js2-print-ast arg 0))
5065 (if (< count len)
5066 (insert (or delimiter ", ")))))
5067
5068 (defun js2-print-tree (ast)
5069 "Prints an AST to the current buffer.
5070 Makes `js2-ast-parent-nodes' available to the printer functions."
5071 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5072 (js2-print-ast ast)))
5073
5074 (defun js2-print-ast (node &optional indent)
5075 "Helper function for printing AST nodes.
5076 Requires `js2-ast-parent-nodes' to be non-nil.
5077 You should use `js2-print-tree' instead of this function."
5078 (let ((printer (get (aref node 0) 'js2-printer))
5079 (i (or indent 0)))
5080 ;; TODO: wedge comments in here somewhere
5081 (if printer
5082 (funcall printer node i))))
5083
5084 (defconst js2-side-effecting-tokens
5085 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5086 (dolist (tt (list js2-ASSIGN
5087 js2-ASSIGN_ADD
5088 js2-ASSIGN_BITAND
5089 js2-ASSIGN_BITOR
5090 js2-ASSIGN_BITXOR
5091 js2-ASSIGN_DIV
5092 js2-ASSIGN_LSH
5093 js2-ASSIGN_MOD
5094 js2-ASSIGN_MUL
5095 js2-ASSIGN_RSH
5096 js2-ASSIGN_SUB
5097 js2-ASSIGN_URSH
5098 js2-BLOCK
5099 js2-BREAK
5100 js2-CALL
5101 js2-CATCH
5102 js2-CATCH_SCOPE
5103 js2-CLASS
5104 js2-CONST
5105 js2-CONTINUE
5106 js2-DEBUGGER
5107 js2-DEC
5108 js2-DELPROP
5109 js2-DEL_REF
5110 js2-DO
5111 js2-ELSE
5112 js2-EMPTY
5113 js2-ENTERWITH
5114 js2-EXPORT
5115 js2-EXPR_RESULT
5116 js2-FINALLY
5117 js2-FOR
5118 js2-FUNCTION
5119 js2-GOTO
5120 js2-IF
5121 js2-IFEQ
5122 js2-IFNE
5123 js2-IMPORT
5124 js2-INC
5125 js2-JSR
5126 js2-LABEL
5127 js2-LEAVEWITH
5128 js2-LET
5129 js2-LETEXPR
5130 js2-LOCAL_BLOCK
5131 js2-LOOP
5132 js2-NEW
5133 js2-REF_CALL
5134 js2-RETHROW
5135 js2-RETURN
5136 js2-RETURN_RESULT
5137 js2-SEMI
5138 js2-SETELEM
5139 js2-SETELEM_OP
5140 js2-SETNAME
5141 js2-SETPROP
5142 js2-SETPROP_OP
5143 js2-SETVAR
5144 js2-SET_REF
5145 js2-SET_REF_OP
5146 js2-SWITCH
5147 js2-TARGET
5148 js2-THROW
5149 js2-TRY
5150 js2-VAR
5151 js2-WHILE
5152 js2-WITH
5153 js2-WITHEXPR
5154 js2-YIELD))
5155 (aset tokens tt t))
5156 (if js2-instanceof-has-side-effects
5157 (aset tokens js2-INSTANCEOF t))
5158 tokens))
5159
5160 (defun js2-node-has-side-effects (node)
5161 "Return t if NODE has side effects."
5162 (when node ; makes it easier to handle malformed expressions
5163 (let ((tt (js2-node-type node)))
5164 (cond
5165 ;; This doubtless needs some work, since EXPR_VOID is used
5166 ;; in several ways in Rhino and I may not have caught them all.
5167 ;; I'll wait for people to notice incorrect warnings.
5168 ((and (= tt js2-EXPR_VOID)
5169 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5170 (let ((expr (js2-expr-stmt-node-expr node)))
5171 (or (js2-node-has-side-effects expr)
5172 (when (js2-string-node-p expr)
5173 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5174 ((= tt js2-COMMA)
5175 (js2-node-has-side-effects (js2-infix-node-right node)))
5176 ((or (= tt js2-AND)
5177 (= tt js2-OR))
5178 (or (js2-node-has-side-effects (js2-infix-node-right node))
5179 (js2-node-has-side-effects (js2-infix-node-left node))))
5180 ((= tt js2-HOOK)
5181 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5182 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5183 ((js2-paren-node-p node)
5184 (js2-node-has-side-effects (js2-paren-node-expr node)))
5185 ((= tt js2-ERROR) ; avoid cascaded error messages
5186 nil)
5187 (t
5188 (aref js2-side-effecting-tokens tt))))))
5189
5190 (defconst js2-stmt-node-types
5191 (list js2-BLOCK
5192 js2-BREAK
5193 js2-CONTINUE
5194 js2-DEFAULT ; e4x "default xml namespace" statement
5195 js2-DO
5196 js2-EXPORT
5197 js2-EXPR_RESULT
5198 js2-EXPR_VOID
5199 js2-FOR
5200 js2-IF
5201 js2-IMPORT
5202 js2-RETURN
5203 js2-SWITCH
5204 js2-THROW
5205 js2-TRY
5206 js2-WHILE
5207 js2-WITH)
5208 "Node types that only appear in statement contexts.
5209 The list does not include nodes that always appear as the child
5210 of another specific statement type, such as switch-cases,
5211 catch and finally blocks, and else-clauses. The list also excludes
5212 nodes like yield, let and var, which may appear in either expression
5213 or statement context, and in the latter context always have a
5214 `js2-expr-stmt-node' parent. Finally, the list does not include
5215 functions or scripts, which are treated separately from statements
5216 by the JavaScript parser and runtime.")
5217
5218 (defun js2-stmt-node-p (node)
5219 "Heuristic for figuring out if NODE is a statement.
5220 Some node types can appear in either an expression context or a
5221 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5222 For these node types in a statement context, the parent will be a
5223 `js2-expr-stmt-node'.
5224 Functions aren't included in the check."
5225 (memq (js2-node-type node) js2-stmt-node-types))
5226
5227 (defun js2-mode-find-first-stmt (node)
5228 "Search upward starting from NODE looking for a statement.
5229 For purposes of this function, a `js2-function-node' counts."
5230 (while (not (or (js2-stmt-node-p node)
5231 (js2-function-node-p node)))
5232 (setq node (js2-node-parent node)))
5233 node)
5234
5235 (defun js2-node-parent-stmt (node)
5236 "Return the node's first ancestor that is a statement.
5237 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5238 appearing in a statement context will have a parent that is a
5239 `js2-expr-stmt-node' that will be returned by this function."
5240 (let ((parent (js2-node-parent node)))
5241 (if (or (null parent)
5242 (js2-stmt-node-p parent)
5243 (and (js2-function-node-p parent)
5244 (not (eq (js2-function-node-form parent)
5245 'FUNCTION_EXPRESSION))))
5246 parent
5247 (js2-node-parent-stmt parent))))
5248
5249 ;; In the Mozilla Rhino sources, Roshan James writes:
5250 ;; Does consistent-return analysis on the function body when strict mode is
5251 ;; enabled.
5252 ;;
5253 ;; function (x) { return (x+1) }
5254 ;;
5255 ;; is ok, but
5256 ;;
5257 ;; function (x) { if (x < 0) return (x+1); }
5258 ;;
5259 ;; is not because the function can potentially return a value when the
5260 ;; condition is satisfied and if not, the function does not explicitly
5261 ;; return a value.
5262 ;;
5263 ;; This extends to checking mismatches such as "return" and "return <value>"
5264 ;; used in the same function. Warnings are not emitted if inconsistent
5265 ;; returns exist in code that can be statically shown to be unreachable.
5266 ;; Ex.
5267 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5268 ;;
5269 ;; emits no warning. However if the loop had a break statement, then a
5270 ;; warning would be emitted.
5271 ;;
5272 ;; The consistency analysis looks at control structures such as loops, ifs,
5273 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5274 ;; warns the user about an inconsistent set of termination possibilities.
5275 ;;
5276 ;; These flags enumerate the possible ways a statement/function can
5277 ;; terminate. These flags are used by endCheck() and by the Parser to
5278 ;; detect inconsistent return usage.
5279 ;;
5280 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5281 ;; able to execute (example: throw, continue)
5282 ;;
5283 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5284 ;; next one. Statement such as return dont. A compound statement may have
5285 ;; some branch that drops off control to the next statement.
5286 ;;
5287 ;; END_RETURNS indicates that the statement can return with no value.
5288 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5289 ;;
5290 ;; A compound statement such as
5291 ;; if (condition) {
5292 ;; return value;
5293 ;; }
5294 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5295
5296 (defconst js2-END_UNREACHED 0)
5297 (defconst js2-END_DROPS_OFF 1)
5298 (defconst js2-END_RETURNS 2)
5299 (defconst js2-END_RETURNS_VALUE 4)
5300 (defconst js2-END_YIELDS 8)
5301
5302 (defun js2-has-consistent-return-usage (node)
5303 "Check that every return usage in a function body is consistent.
5304 Returns t if the function satisfies strict mode requirement."
5305 (let ((n (js2-end-check node)))
5306 ;; either it doesn't return a value in any branch...
5307 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5308 ;; or it returns a value (or is unreached) at every branch
5309 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5310 js2-END_RETURNS
5311 js2-END_YIELDS)))))
5312
5313 (defun js2-end-check-if (node)
5314 "Ensure that return usage in then/else blocks is consistent.
5315 If there is no else block, then the return statement can fall through.
5316 Returns logical OR of END_* flags"
5317 (let ((th (js2-if-node-then-part node))
5318 (el (js2-if-node-else-part node)))
5319 (if (null th)
5320 js2-END_UNREACHED
5321 (logior (js2-end-check th) (if el
5322 (js2-end-check el)
5323 js2-END_DROPS_OFF)))))
5324
5325 (defun js2-end-check-switch (node)
5326 "Consistency of return statements is checked between the case statements.
5327 If there is no default, then the switch can fall through. If there is a
5328 default, we check to see if all code paths in the default return or if
5329 there is a code path that can fall through.
5330 Returns logical OR of END_* flags."
5331 (let ((rv js2-END_UNREACHED)
5332 default-case)
5333 ;; examine the cases
5334 (catch 'break
5335 (dolist (c (js2-switch-node-cases node))
5336 (if (js2-case-node-expr c)
5337 (js2-set-flag rv (js2-end-check-block c))
5338 (setq default-case c)
5339 (throw 'break nil))))
5340 ;; we don't care how the cases drop into each other
5341 (js2-clear-flag rv js2-END_DROPS_OFF)
5342 ;; examine the default
5343 (js2-set-flag rv (if default-case
5344 (js2-end-check default-case)
5345 js2-END_DROPS_OFF))
5346 rv))
5347
5348 (defun js2-end-check-try (node)
5349 "If the block has a finally, return consistency is checked in the
5350 finally block. If all code paths in the finally return, then the
5351 returns in the try-catch blocks don't matter. If there is a code path
5352 that does not return or if there is no finally block, the returns
5353 of the try and catch blocks are checked for mismatch.
5354 Returns logical OR of END_* flags."
5355 (let ((finally (js2-try-node-finally-block node))
5356 rv)
5357 ;; check the finally if it exists
5358 (setq rv (if finally
5359 (js2-end-check (js2-finally-node-body finally))
5360 js2-END_DROPS_OFF))
5361 ;; If the finally block always returns, then none of the returns
5362 ;; in the try or catch blocks matter.
5363 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5364 (js2-clear-flag rv js2-END_DROPS_OFF)
5365 ;; examine the try block
5366 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5367 ;; check each catch block
5368 (dolist (cb (js2-try-node-catch-clauses node))
5369 (js2-set-flag rv (js2-end-check cb))))
5370 rv))
5371
5372 (defun js2-end-check-loop (node)
5373 "Return statement in the loop body must be consistent.
5374 The default assumption for any kind of a loop is that it will eventually
5375 terminate. The only exception is a loop with a constant true condition.
5376 Code that follows such a loop is examined only if one can determine
5377 statically that there is a break out of the loop.
5378
5379 for(... ; ... ; ...) {}
5380 for(... in ... ) {}
5381 while(...) { }
5382 do { } while(...)
5383
5384 Returns logical OR of END_* flags."
5385 (let ((rv (js2-end-check (js2-loop-node-body node)))
5386 (condition (cond
5387 ((js2-while-node-p node)
5388 (js2-while-node-condition node))
5389 ((js2-do-node-p node)
5390 (js2-do-node-condition node))
5391 ((js2-for-node-p node)
5392 (js2-for-node-condition node)))))
5393
5394 ;; check to see if the loop condition is always true
5395 (if (and condition
5396 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5397 (js2-clear-flag rv js2-END_DROPS_OFF))
5398
5399 ;; look for effect of breaks
5400 (js2-set-flag rv (js2-node-get-prop node
5401 'CONTROL_BLOCK_PROP
5402 js2-END_UNREACHED))
5403 rv))
5404
5405 (defun js2-end-check-block (node)
5406 "A general block of code is examined statement by statement.
5407 If any statement (even a compound one) returns in all branches, then
5408 subsequent statements are not examined.
5409 Returns logical OR of END_* flags."
5410 (let* ((rv js2-END_DROPS_OFF)
5411 (kids (js2-block-node-kids node))
5412 (n (car kids)))
5413 ;; Check each statement. If the statement can continue onto the next
5414 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5415 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5416 (js2-clear-flag rv js2-END_DROPS_OFF)
5417 (js2-set-flag rv (js2-end-check n))
5418 (setq kids (cdr kids)
5419 n (car kids)))
5420 rv))
5421
5422 (defun js2-end-check-label (node)
5423 "A labeled statement implies that there may be a break to the label.
5424 The function processes the labeled statement and then checks the
5425 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5426 particular label.
5427 Returns logical OR of END_* flags."
5428 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5429 (logior rv (js2-node-get-prop node
5430 'CONTROL_BLOCK_PROP
5431 js2-END_UNREACHED))))
5432
5433 (defun js2-end-check-break (node)
5434 "When a break is encountered annotate the statement being broken
5435 out of by setting its CONTROL_BLOCK_PROP property.
5436 Returns logical OR of END_* flags."
5437 (and (js2-break-node-target node)
5438 (js2-node-set-prop (js2-break-node-target node)
5439 'CONTROL_BLOCK_PROP
5440 js2-END_DROPS_OFF))
5441 js2-END_UNREACHED)
5442
5443 (defun js2-end-check (node)
5444 "Examine the body of a function, doing a basic reachability analysis.
5445 Returns a combination of flags END_* flags that indicate
5446 how the function execution can terminate. These constitute only the
5447 pessimistic set of termination conditions. It is possible that at
5448 runtime certain code paths will never be actually taken. Hence this
5449 analysis will flag errors in cases where there may not be errors.
5450 Returns logical OR of END_* flags"
5451 (let (kid)
5452 (cond
5453 ((js2-break-node-p node)
5454 (js2-end-check-break node))
5455 ((js2-expr-stmt-node-p node)
5456 (if (setq kid (js2-expr-stmt-node-expr node))
5457 (js2-end-check kid)
5458 js2-END_DROPS_OFF))
5459 ((or (js2-continue-node-p node)
5460 (js2-throw-node-p node))
5461 js2-END_UNREACHED)
5462 ((js2-return-node-p node)
5463 (if (setq kid (js2-return-node-retval node))
5464 js2-END_RETURNS_VALUE
5465 js2-END_RETURNS))
5466 ((js2-loop-node-p node)
5467 (js2-end-check-loop node))
5468 ((js2-switch-node-p node)
5469 (js2-end-check-switch node))
5470 ((js2-labeled-stmt-node-p node)
5471 (js2-end-check-label node))
5472 ((js2-if-node-p node)
5473 (js2-end-check-if node))
5474 ((js2-try-node-p node)
5475 (js2-end-check-try node))
5476 ((js2-block-node-p node)
5477 (if (null (js2-block-node-kids node))
5478 js2-END_DROPS_OFF
5479 (js2-end-check-block node)))
5480 ((js2-yield-node-p node)
5481 js2-END_YIELDS)
5482 (t
5483 js2-END_DROPS_OFF))))
5484
5485 (defun js2-always-defined-boolean-p (node)
5486 "Check if NODE always evaluates to true or false in boolean context.
5487 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5488 nor always false."
5489 (let ((tt (js2-node-type node))
5490 num)
5491 (cond
5492 ((or (= tt js2-FALSE) (= tt js2-NULL))
5493 'ALWAYS_FALSE)
5494 ((= tt js2-TRUE)
5495 'ALWAYS_TRUE)
5496 ((= tt js2-NUMBER)
5497 (setq num (js2-number-node-num-value node))
5498 (if (and (not (eq num 0.0e+NaN))
5499 (not (zerop num)))
5500 'ALWAYS_TRUE
5501 'ALWAYS_FALSE))
5502 (t
5503 nil))))
5504
5505 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5506 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5507
5508 (defvar js2-tokens nil
5509 "List of all defined token names.") ; initialized in `js2-token-names'
5510
5511 (defconst js2-token-names
5512 (let* ((names (make-vector js2-num-tokens -1))
5513 (case-fold-search nil) ; only match js2-UPPER_CASE
5514 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5515 (cl-loop for sym in syms
5516 for i from 0
5517 do
5518 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5519 (not (boundp sym)))
5520 (aset names (symbol-value sym) ; code, e.g. 152
5521 (downcase
5522 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5523 (push sym js2-tokens)))
5524 names)
5525 "Vector mapping int values to token string names, sans `js2-' prefix.")
5526
5527 (defun js2-tt-name (tok)
5528 "Return a string name for TOK, a token symbol or code.
5529 Signals an error if it's not a recognized token."
5530 (let ((code tok))
5531 (if (symbolp tok)
5532 (setq code (symbol-value tok)))
5533 (if (eq code -1)
5534 "ERROR"
5535 (if (and (numberp code)
5536 (not (cl-minusp code))
5537 (< code js2-num-tokens))
5538 (aref js2-token-names code)
5539 (error "Invalid token: %s" code)))))
5540
5541 (defsubst js2-tt-sym (tok)
5542 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5543 (intern (js2-tt-name tok)))
5544
5545 (defconst js2-token-codes
5546 (let ((table (make-hash-table :test 'eq :size 256)))
5547 (cl-loop for name across js2-token-names
5548 for sym = (intern (concat "js2-" (upcase name)))
5549 do
5550 (puthash sym (symbol-value sym) table))
5551 ;; clean up a few that are "wrong" in Rhino's token codes
5552 (puthash 'js2-DELETE js2-DELPROP table)
5553 table)
5554 "Hashtable mapping token type symbols to their bytecodes.")
5555
5556 (defsubst js2-tt-code (sym)
5557 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5558 (or (gethash sym js2-token-codes)
5559 (error "Invalid token symbol: %s " sym))) ; signal code bug
5560
5561 (defun js2-report-scan-error (msg &optional no-throw beg len)
5562 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5563 (js2-report-error msg nil
5564 (or beg (js2-current-token-beg))
5565 (or len (js2-current-token-len)))
5566 (unless no-throw
5567 (throw 'return js2-ERROR)))
5568
5569 (defun js2-set-string-from-buffer (token)
5570 "Set `string' and `end' slots for TOKEN, return the string."
5571 (setf (js2-token-end token) js2-ts-cursor
5572 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5573
5574 ;; TODO: could potentially avoid a lot of consing by allocating a
5575 ;; char buffer the way Rhino does.
5576 (defsubst js2-add-to-string (c)
5577 (push c js2-ts-string-buffer))
5578
5579 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5580 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5581 ;; any other character: when it's not part of the current token, we
5582 ;; unget it, allowing it to be read again by the following call.
5583 (defsubst js2-unget-char ()
5584 (cl-decf js2-ts-cursor))
5585
5586 ;; Rhino distinguishes \r and \n line endings. We don't need to
5587 ;; because we only scan from Emacs buffers, which always use \n.
5588 (defun js2-get-char ()
5589 "Read and return the next character from the input buffer.
5590 Increments `js2-ts-lineno' if the return value is a newline char.
5591 Updates `js2-ts-cursor' to the point after the returned char.
5592 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5593 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5594 (let (c)
5595 ;; check for end of buffer
5596 (if (>= js2-ts-cursor (point-max))
5597 (setq js2-ts-hit-eof t
5598 js2-ts-cursor (1+ js2-ts-cursor)
5599 c js2-EOF_CHAR) ; return value
5600 ;; otherwise read next char
5601 (setq c (char-before (cl-incf js2-ts-cursor)))
5602 ;; if we read a newline, update counters
5603 (if (= c ?\n)
5604 (setq js2-ts-line-start js2-ts-cursor
5605 js2-ts-lineno (1+ js2-ts-lineno)))
5606 ;; TODO: skip over format characters
5607 c)))
5608
5609 (defun js2-read-unicode-escape ()
5610 "Read a \\uNNNN sequence from the input.
5611 Assumes the ?\ and ?u have already been read.
5612 Returns the unicode character, or nil if it wasn't a valid character.
5613 Doesn't change the values of any scanner variables."
5614 ;; I really wish I knew a better way to do this, but I can't
5615 ;; find the Emacs function that takes a 16-bit int and converts
5616 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5617 ;; Have to first check that it's 4 hex characters or it may stop
5618 ;; the read early.
5619 (ignore-errors
5620 (let ((s (buffer-substring-no-properties js2-ts-cursor
5621 (+ 4 js2-ts-cursor))))
5622 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5623 (read (concat "?\\u" s))))))
5624
5625 (defun js2-match-char (test)
5626 "Consume and return next character if it matches TEST, a character.
5627 Returns nil and consumes nothing if TEST is not the next character."
5628 (let ((c (js2-get-char)))
5629 (if (eq c test)
5630 t
5631 (js2-unget-char)
5632 nil)))
5633
5634 (defun js2-peek-char ()
5635 (prog1
5636 (js2-get-char)
5637 (js2-unget-char)))
5638
5639 (defun js2-identifier-start-p (c)
5640 "Is C a valid start to an ES5 Identifier?
5641 See http://es5.github.io/#x7.6"
5642 (or
5643 (memq c '(?$ ?_))
5644 (memq (get-char-code-property c 'general-category)
5645 ;; Letters
5646 '(Lu Ll Lt Lm Lo Nl))))
5647
5648 (defun js2-identifier-part-p (c)
5649 "Is C a valid part of an ES5 Identifier?
5650 See http://es5.github.io/#x7.6"
5651 (or
5652 (memq c '(?$ ?_ ?\u200c ?\u200d))
5653 (memq (get-char-code-property c 'general-category)
5654 '(;; Letters
5655 Lu Ll Lt Lm Lo Nl
5656 ;; Combining Marks
5657 Mn Mc
5658 ;; Digits
5659 Nd
5660 ;; Connector Punctuation
5661 Pc))))
5662
5663 (defun js2-alpha-p (c)
5664 (cond ((and (<= ?A c) (<= c ?Z)) t)
5665 ((and (<= ?a c) (<= c ?z)) t)
5666 (t nil)))
5667
5668 (defsubst js2-digit-p (c)
5669 (and (<= ?0 c) (<= c ?9)))
5670
5671 (defun js2-js-space-p (c)
5672 (if (<= c 127)
5673 (memq c '(#x20 #x9 #xB #xC #xD))
5674 (or
5675 (eq c #xA0)
5676 ;; TODO: change this nil to check for Unicode space character
5677 nil)))
5678
5679 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5680
5681 (defun js2-skip-line ()
5682 "Skip to end of line."
5683 (while (not (memq (js2-get-char) js2-eol-chars)))
5684 (js2-unget-char)
5685 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5686
5687 (defun js2-init-scanner (&optional buf line)
5688 "Create token stream for BUF starting on LINE.
5689 BUF defaults to `current-buffer' and LINE defaults to 1.
5690
5691 A buffer can only have one scanner active at a time, which yields
5692 dramatically simpler code than using a defstruct. If you need to
5693 have simultaneous scanners in a buffer, copy the regions to scan
5694 into temp buffers."
5695 (with-current-buffer (or buf (current-buffer))
5696 (setq js2-ts-dirty-line nil
5697 js2-ts-hit-eof nil
5698 js2-ts-line-start 0
5699 js2-ts-lineno (or line 1)
5700 js2-ts-line-end-char -1
5701 js2-ts-cursor (point-min)
5702 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5703 js2-ti-tokens-cursor 0
5704 js2-ti-lookahead 0
5705 js2-ts-is-xml-attribute nil
5706 js2-ts-xml-is-tag-content nil
5707 js2-ts-xml-open-tags-count 0
5708 js2-ts-string-buffer nil)))
5709
5710 ;; This function uses the cached op, string and number fields in
5711 ;; TokenStream; if getToken has been called since the passed token
5712 ;; was scanned, the op or string printed may be incorrect.
5713 (defun js2-token-to-string (token)
5714 ;; Not sure where this function is used in Rhino. Not tested.
5715 (if (not js2-debug-print-trees)
5716 ""
5717 (let ((name (js2-tt-name token)))
5718 (cond
5719 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5720 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5721 (concat name " `" (js2-current-token-string) "'"))
5722 ((eq token js2-NUMBER)
5723 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5724 (t
5725 name)))))
5726
5727 (defconst js2-keywords
5728 '(break
5729 case catch class const continue
5730 debugger default delete do
5731 else extends export
5732 false finally for function
5733 if in instanceof import
5734 let
5735 new null
5736 return
5737 super switch
5738 this throw true try typeof
5739 var void
5740 while with
5741 yield))
5742
5743 ;; Token names aren't exactly the same as the keywords, unfortunately.
5744 ;; E.g. delete is js2-DELPROP.
5745 (defconst js2-kwd-tokens
5746 (let ((table (make-vector js2-num-tokens nil))
5747 (tokens
5748 (list js2-BREAK
5749 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5750 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5751 js2-ELSE js2-EXPORT
5752 js2-ELSE js2-EXTENDS js2-EXPORT
5753 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5754 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5755 js2-LET
5756 js2-NEW js2-NULL
5757 js2-RETURN
5758 js2-SUPER js2-SWITCH
5759 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5760 js2-VAR
5761 js2-WHILE js2-WITH
5762 js2-YIELD)))
5763 (dolist (i tokens)
5764 (aset table i 'font-lock-keyword-face))
5765 (aset table js2-STRING 'font-lock-string-face)
5766 (aset table js2-REGEXP 'font-lock-string-face)
5767 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5768 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5769 (aset table js2-COMMENT 'font-lock-comment-face)
5770 (aset table js2-THIS 'font-lock-builtin-face)
5771 (aset table js2-SUPER 'font-lock-builtin-face)
5772 (aset table js2-VOID 'font-lock-constant-face)
5773 (aset table js2-NULL 'font-lock-constant-face)
5774 (aset table js2-TRUE 'font-lock-constant-face)
5775 (aset table js2-FALSE 'font-lock-constant-face)
5776 (aset table js2-NOT 'font-lock-negation-char-face)
5777 table)
5778 "Vector whose values are non-nil for tokens that are keywords.
5779 The values are default faces to use for highlighting the keywords.")
5780
5781 ;; FIXME: Support strict mode-only future reserved words, after we know
5782 ;; which parts scopes are in strict mode, and which are not.
5783 (defconst js2-reserved-words '(class enum export extends import static super)
5784 "Future reserved keywords in ECMAScript 5.1.")
5785
5786 (defconst js2-keyword-names
5787 (let ((table (make-hash-table :test 'equal)))
5788 (cl-loop for k in js2-keywords
5789 do (puthash
5790 (symbol-name k) ; instanceof
5791 (intern (concat "js2-"
5792 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5793 table))
5794 table)
5795 "JavaScript keywords by name, mapped to their symbols.")
5796
5797 (defconst js2-reserved-word-names
5798 (let ((table (make-hash-table :test 'equal)))
5799 (cl-loop for k in js2-reserved-words
5800 do
5801 (puthash (symbol-name k) 'js2-RESERVED table))
5802 table)
5803 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5804
5805 (defun js2-collect-string (buf)
5806 "Convert BUF, a list of chars, to a string.
5807 Reverses BUF before converting."
5808 (if buf
5809 (apply #'string (nreverse buf))
5810 ""))
5811
5812 (defun js2-string-to-keyword (s)
5813 "Return token for S, a string, if S is a keyword or reserved word.
5814 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5815 (or (gethash s js2-keyword-names)
5816 (gethash s js2-reserved-word-names)))
5817
5818 (defsubst js2-ts-set-char-token-bounds (token)
5819 "Used when next token is one character."
5820 (setf (js2-token-beg token) (1- js2-ts-cursor)
5821 (js2-token-end token) js2-ts-cursor))
5822
5823 (defsubst js2-ts-return (token type)
5824 "Update the `end' and `type' slots of TOKEN,
5825 then throw `return' with value TYPE."
5826 (setf (js2-token-end token) js2-ts-cursor
5827 (js2-token-type token) type)
5828 (throw 'return type))
5829
5830 (defun js2-x-digit-to-int (c accumulator)
5831 "Build up a hex number.
5832 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5833 corresponding number. Otherwise return -1."
5834 (catch 'return
5835 (catch 'check
5836 ;; Use 0..9 < A..Z < a..z
5837 (cond
5838 ((<= c ?9)
5839 (cl-decf c ?0)
5840 (if (<= 0 c)
5841 (throw 'check nil)))
5842 ((<= c ?F)
5843 (when (<= ?A c)
5844 (cl-decf c (- ?A 10))
5845 (throw 'check nil)))
5846 ((<= c ?f)
5847 (when (<= ?a c)
5848 (cl-decf c (- ?a 10))
5849 (throw 'check nil))))
5850 (throw 'return -1))
5851 (logior c (lsh accumulator 4))))
5852
5853 (defun js2-get-token (&optional modifier)
5854 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5855 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5856 next saved token.
5857
5858 This function will not return a newline (js2-EOL) - instead, it
5859 gobbles newlines until it finds a non-newline token. Call
5860 `js2-peek-token-or-eol' when you care about newlines.
5861
5862 This function will also not return a js2-COMMENT. Instead, it
5863 records comments found in `js2-scanned-comments'. If the token
5864 returned by this function immediately follows a jsdoc comment,
5865 the token is flagged as such."
5866 (if (zerop js2-ti-lookahead)
5867 (js2-get-token-internal modifier)
5868 (cl-decf js2-ti-lookahead)
5869 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5870 (let ((tt (js2-current-token-type)))
5871 (cl-assert (not (= tt js2-EOL)))
5872 tt)))
5873
5874 (defun js2-unget-token ()
5875 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5876 (cl-incf js2-ti-lookahead)
5877 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5878
5879 (defun js2-get-token-internal (modifier)
5880 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5881 (tt (js2-token-type token))
5882 saw-eol
5883 face)
5884 ;; process comments
5885 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5886 (if (= tt js2-EOL)
5887 (setq saw-eol t)
5888 (setq saw-eol nil)
5889 (when js2-record-comments
5890 (js2-record-comment token)))
5891 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5892 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5893 tt (js2-token-type token)))
5894
5895 (when saw-eol
5896 (setf (js2-token-follows-eol-p token) t))
5897
5898 ;; perform lexical fontification as soon as token is scanned
5899 (when js2-parse-ide-mode
5900 (cond
5901 ((cl-minusp tt)
5902 (js2-record-face 'js2-error token))
5903 ((setq face (aref js2-kwd-tokens tt))
5904 (js2-record-face face token))
5905 ((and (= tt js2-NAME)
5906 (equal (js2-token-string token) "undefined"))
5907 (js2-record-face 'font-lock-constant-face token))))
5908 tt))
5909
5910 (defsubst js2-string-to-number (str base)
5911 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5912 (condition-case nil
5913 (string-to-number str base)
5914 (overflow-error -1)))
5915
5916 (defun js2-get-token-internal-1 (modifier)
5917 "Return next JavaScript token type, an int such as js2-RETURN.
5918 During operation, creates an instance of `js2-token' struct, sets
5919 its relevant fields and puts it into `js2-ti-tokens'."
5920 (let (identifier-start
5921 is-unicode-escape-start c
5922 contains-escape escape-val str result base
5923 look-for-slash continue tt
5924 (token (js2-new-token 0)))
5925 (setq
5926 tt
5927 (catch 'return
5928 (when (eq modifier 'TEMPLATE_TAIL)
5929 (setf (js2-token-beg token) (1- js2-ts-cursor))
5930 (throw 'return (js2-get-string-or-template-token ?` token)))
5931 (while t
5932 ;; Eat whitespace, possibly sensitive to newlines.
5933 (setq continue t)
5934 (while continue
5935 (setq c (js2-get-char))
5936 (cond
5937 ((eq c js2-EOF_CHAR)
5938 (js2-unget-char)
5939 (js2-ts-set-char-token-bounds token)
5940 (throw 'return js2-EOF))
5941 ((eq c ?\n)
5942 (js2-ts-set-char-token-bounds token)
5943 (setq js2-ts-dirty-line nil)
5944 (throw 'return js2-EOL))
5945 ((not (js2-js-space-p c))
5946 (if (/= c ?-) ; in case end of HTML comment
5947 (setq js2-ts-dirty-line t))
5948 (setq continue nil))))
5949 ;; Assume the token will be 1 char - fixed up below.
5950 (js2-ts-set-char-token-bounds token)
5951 (when (eq c ?@)
5952 (throw 'return js2-XMLATTR))
5953 ;; identifier/keyword/instanceof?
5954 ;; watch out for starting with a <backslash>
5955 (cond
5956 ((eq c ?\\)
5957 (setq c (js2-get-char))
5958 (if (eq c ?u)
5959 (setq identifier-start t
5960 is-unicode-escape-start t
5961 js2-ts-string-buffer nil)
5962 (setq identifier-start nil)
5963 (js2-unget-char)
5964 (setq c ?\\)))
5965 (t
5966 (when (setq identifier-start (js2-identifier-start-p c))
5967 (setq js2-ts-string-buffer nil)
5968 (js2-add-to-string c))))
5969 (when identifier-start
5970 (setq contains-escape is-unicode-escape-start)
5971 (catch 'break
5972 (while t
5973 (if is-unicode-escape-start
5974 ;; strictly speaking we should probably push-back
5975 ;; all the bad characters if the <backslash>uXXXX
5976 ;; sequence is malformed. But since there isn't a
5977 ;; correct context(is there?) for a bad Unicode
5978 ;; escape sequence in an identifier, we can report
5979 ;; an error here.
5980 (progn
5981 (setq escape-val 0)
5982 (dotimes (_ 4)
5983 (setq c (js2-get-char)
5984 escape-val (js2-x-digit-to-int c escape-val))
5985 ;; Next check takes care of c < 0 and bad escape
5986 (if (cl-minusp escape-val)
5987 (throw 'break nil)))
5988 (if (cl-minusp escape-val)
5989 (js2-report-scan-error "msg.invalid.escape" t))
5990 (js2-add-to-string escape-val)
5991 (setq is-unicode-escape-start nil))
5992 (setq c (js2-get-char))
5993 (cond
5994 ((eq c ?\\)
5995 (setq c (js2-get-char))
5996 (if (eq c ?u)
5997 (setq is-unicode-escape-start t
5998 contains-escape t)
5999 (js2-report-scan-error "msg.illegal.character" t)))
6000 (t
6001 (if (or (eq c js2-EOF_CHAR)
6002 (not (js2-identifier-part-p c)))
6003 (throw 'break nil))
6004 (js2-add-to-string c))))))
6005 (js2-unget-char)
6006 (setf str (js2-collect-string js2-ts-string-buffer)
6007 (js2-token-end token) js2-ts-cursor)
6008 ;; FIXME: Invalid in ES5 and ES6, see
6009 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
6010 ;; Probably should just drop this conditional.
6011 (unless contains-escape
6012 ;; OPT we shouldn't have to make a string (object!) to
6013 ;; check if it's a keyword.
6014 ;; Return the corresponding token if it's a keyword
6015 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
6016 (setq result (js2-string-to-keyword str)))
6017 (if (and (< js2-language-version 170)
6018 (memq result '(js2-LET js2-YIELD)))
6019 ;; LET and YIELD are tokens only in 1.7 and later
6020 (setq result 'js2-NAME))
6021 (when (eq result 'js2-RESERVED)
6022 (setf (js2-token-string token) str))
6023 (throw 'return (js2-tt-code result))))
6024 ;; If we want to intern these as Rhino does, just use (intern str)
6025 (setf (js2-token-string token) str)
6026 (throw 'return js2-NAME)) ; end identifier/kwd check
6027 ;; is it a number?
6028 (when (or (js2-digit-p c)
6029 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6030 (setq js2-ts-string-buffer nil
6031 base 10)
6032 (when (eq c ?0)
6033 (setq c (js2-get-char))
6034 (cond
6035 ((or (eq c ?x) (eq c ?X))
6036 (setq base 16)
6037 (setq c (js2-get-char)))
6038 ((and (or (eq c ?b) (eq c ?B))
6039 (>= js2-language-version 200))
6040 (setq base 2)
6041 (setq c (js2-get-char)))
6042 ((and (or (eq c ?o) (eq c ?O))
6043 (>= js2-language-version 200))
6044 (setq base 8)
6045 (setq c (js2-get-char)))
6046 ((js2-digit-p c)
6047 (setq base 'maybe-8))
6048 (t
6049 (js2-add-to-string ?0))))
6050 (cond
6051 ((eq base 16)
6052 (if (> 0 (js2-x-digit-to-int c 0))
6053 (js2-report-scan-error "msg.missing.hex.digits")
6054 (while (<= 0 (js2-x-digit-to-int c 0))
6055 (js2-add-to-string c)
6056 (setq c (js2-get-char)))))
6057 ((eq base 2)
6058 (if (not (memq c '(?0 ?1)))
6059 (js2-report-scan-error "msg.missing.binary.digits")
6060 (while (memq c '(?0 ?1))
6061 (js2-add-to-string c)
6062 (setq c (js2-get-char)))))
6063 ((eq base 8)
6064 (if (or (> ?0 c) (< ?7 c))
6065 (js2-report-scan-error "msg.missing.octal.digits")
6066 (while (and (<= ?0 c) (>= ?7 c))
6067 (js2-add-to-string c)
6068 (setq c (js2-get-char)))))
6069 (t
6070 (while (and (<= ?0 c) (<= c ?9))
6071 ;; We permit 08 and 09 as decimal numbers, which
6072 ;; makes our behavior a superset of the ECMA
6073 ;; numeric grammar. We might not always be so
6074 ;; permissive, so we warn about it.
6075 (when (and (eq base 'maybe-8) (>= c ?8))
6076 (js2-report-warning "msg.bad.octal.literal"
6077 (if (eq c ?8) "8" "9"))
6078 (setq base 10))
6079 (js2-add-to-string c)
6080 (setq c (js2-get-char)))
6081 (when (eq base 'maybe-8)
6082 (setq base 8))))
6083 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6084 (when (eq c ?.)
6085 (cl-loop do
6086 (js2-add-to-string c)
6087 (setq c (js2-get-char))
6088 while (js2-digit-p c)))
6089 (when (memq c '(?e ?E))
6090 (js2-add-to-string c)
6091 (setq c (js2-get-char))
6092 (when (memq c '(?+ ?-))
6093 (js2-add-to-string c)
6094 (setq c (js2-get-char)))
6095 (unless (js2-digit-p c)
6096 (js2-report-scan-error "msg.missing.exponent" t))
6097 (cl-loop do
6098 (js2-add-to-string c)
6099 (setq c (js2-get-char))
6100 while (js2-digit-p c))))
6101 (js2-unget-char)
6102 (let ((str (js2-set-string-from-buffer token)))
6103 (setf (js2-token-number token)
6104 (js2-string-to-number str base)))
6105 (throw 'return js2-NUMBER))
6106 ;; is it a string?
6107 (when (or (memq c '(?\" ?\'))
6108 (and (>= js2-language-version 200)
6109 (= c ?`)))
6110 (throw 'return
6111 (js2-get-string-or-template-token c token)))
6112 (js2-ts-return token
6113 (cl-case c
6114 (?\;
6115 (throw 'return js2-SEMI))
6116 (?\[
6117 (throw 'return js2-LB))
6118 (?\]
6119 (throw 'return js2-RB))
6120 (?{
6121 (throw 'return js2-LC))
6122 (?}
6123 (throw 'return js2-RC))
6124 (?\(
6125 (throw 'return js2-LP))
6126 (?\)
6127 (throw 'return js2-RP))
6128 (?,
6129 (throw 'return js2-COMMA))
6130 (??
6131 (throw 'return js2-HOOK))
6132 (?:
6133 (if (js2-match-char ?:)
6134 js2-COLONCOLON
6135 (throw 'return js2-COLON)))
6136 (?.
6137 (if (js2-match-char ?.)
6138 (if (js2-match-char ?.)
6139 js2-TRIPLEDOT js2-DOTDOT)
6140 (if (js2-match-char ?\()
6141 js2-DOTQUERY
6142 (throw 'return js2-DOT))))
6143 (?|
6144 (if (js2-match-char ?|)
6145 (throw 'return js2-OR)
6146 (if (js2-match-char ?=)
6147 js2-ASSIGN_BITOR
6148 (throw 'return js2-BITOR))))
6149 (?^
6150 (if (js2-match-char ?=)
6151 js2-ASSIGN_BITOR
6152 (throw 'return js2-BITXOR)))
6153 (?&
6154 (if (js2-match-char ?&)
6155 (throw 'return js2-AND)
6156 (if (js2-match-char ?=)
6157 js2-ASSIGN_BITAND
6158 (throw 'return js2-BITAND))))
6159 (?=
6160 (if (js2-match-char ?=)
6161 (if (js2-match-char ?=)
6162 js2-SHEQ
6163 (throw 'return js2-EQ))
6164 (if (js2-match-char ?>)
6165 (js2-ts-return token js2-ARROW)
6166 (throw 'return js2-ASSIGN))))
6167 (?!
6168 (if (js2-match-char ?=)
6169 (if (js2-match-char ?=)
6170 js2-SHNE
6171 js2-NE)
6172 (throw 'return js2-NOT)))
6173 (?<
6174 ;; NB:treat HTML begin-comment as comment-till-eol
6175 (when (js2-match-char ?!)
6176 (when (js2-match-char ?-)
6177 (when (js2-match-char ?-)
6178 (js2-skip-line)
6179 (setf (js2-token-comment-type (js2-current-token)) 'html)
6180 (throw 'return js2-COMMENT)))
6181 (js2-unget-char))
6182 (if (js2-match-char ?<)
6183 (if (js2-match-char ?=)
6184 js2-ASSIGN_LSH
6185 js2-LSH)
6186 (if (js2-match-char ?=)
6187 js2-LE
6188 (throw 'return js2-LT))))
6189 (?>
6190 (if (js2-match-char ?>)
6191 (if (js2-match-char ?>)
6192 (if (js2-match-char ?=)
6193 js2-ASSIGN_URSH
6194 js2-URSH)
6195 (if (js2-match-char ?=)
6196 js2-ASSIGN_RSH
6197 js2-RSH))
6198 (if (js2-match-char ?=)
6199 js2-GE
6200 (throw 'return js2-GT))))
6201 (?*
6202 (if (js2-match-char ?=)
6203 js2-ASSIGN_MUL
6204 (throw 'return js2-MUL)))
6205 (?/
6206 ;; is it a // comment?
6207 (when (js2-match-char ?/)
6208 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6209 (js2-skip-line)
6210 (setf (js2-token-comment-type token) 'line)
6211 ;; include newline so highlighting goes to end of
6212 ;; window, if there actually is a newline; if we
6213 ;; hit eof, then implicitly there isn't
6214 (unless js2-ts-hit-eof
6215 (cl-incf (js2-token-end token)))
6216 (throw 'return js2-COMMENT))
6217 ;; is it a /* comment?
6218 (when (js2-match-char ?*)
6219 (setf look-for-slash nil
6220 (js2-token-beg token) (- js2-ts-cursor 2)
6221 (js2-token-comment-type token)
6222 (if (js2-match-char ?*)
6223 (progn
6224 (setq look-for-slash t)
6225 'jsdoc)
6226 'block))
6227 (while t
6228 (setq c (js2-get-char))
6229 (cond
6230 ((eq c js2-EOF_CHAR)
6231 (setf (js2-token-end token) (1- js2-ts-cursor))
6232 (js2-report-error "msg.unterminated.comment")
6233 (throw 'return js2-COMMENT))
6234 ((eq c ?*)
6235 (setq look-for-slash t))
6236 ((eq c ?/)
6237 (if look-for-slash
6238 (js2-ts-return token js2-COMMENT)))
6239 (t
6240 (setf look-for-slash nil
6241 (js2-token-end token) js2-ts-cursor)))))
6242 (if (js2-match-char ?=)
6243 js2-ASSIGN_DIV
6244 (throw 'return js2-DIV)))
6245 (?#
6246 (when js2-skip-preprocessor-directives
6247 (js2-skip-line)
6248 (setf (js2-token-comment-type token) 'preprocessor
6249 (js2-token-end token) js2-ts-cursor)
6250 (throw 'return js2-COMMENT))
6251 (throw 'return js2-ERROR))
6252 (?%
6253 (if (js2-match-char ?=)
6254 js2-ASSIGN_MOD
6255 (throw 'return js2-MOD)))
6256 (?~
6257 (throw 'return js2-BITNOT))
6258 (?+
6259 (if (js2-match-char ?=)
6260 js2-ASSIGN_ADD
6261 (if (js2-match-char ?+)
6262 js2-INC
6263 (throw 'return js2-ADD))))
6264 (?-
6265 (cond
6266 ((js2-match-char ?=)
6267 (setq c js2-ASSIGN_SUB))
6268 ((js2-match-char ?-)
6269 (unless js2-ts-dirty-line
6270 ;; treat HTML end-comment after possible whitespace
6271 ;; after line start as comment-until-eol
6272 (when (js2-match-char ?>)
6273 (js2-skip-line)
6274 (setf (js2-token-comment-type (js2-current-token)) 'html)
6275 (throw 'return js2-COMMENT)))
6276 (setq c js2-DEC))
6277 (t
6278 (setq c js2-SUB)))
6279 (setq js2-ts-dirty-line t)
6280 c)
6281 (otherwise
6282 (js2-report-scan-error "msg.illegal.character")))))))
6283 (setf (js2-token-type token) tt)
6284 token))
6285
6286 (defun js2-get-string-or-template-token (quote-char token)
6287 ;; We attempt to accumulate a string the fast way, by
6288 ;; building it directly out of the reader. But if there
6289 ;; are any escaped characters in the string, we revert to
6290 ;; building it out of a string buffer.
6291 (let ((c (js2-get-char))
6292 js2-ts-string-buffer
6293 nc c1 val escape-val)
6294 (catch 'break
6295 (while (/= c quote-char)
6296 (catch 'continue
6297 (when (eq c js2-EOF_CHAR)
6298 (js2-unget-char)
6299 (js2-report-error "msg.unterminated.string.lit")
6300 (throw 'break nil))
6301 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6302 (js2-unget-char)
6303 (js2-report-error "msg.unterminated.string.lit")
6304 (throw 'break nil))
6305 (when (eq c ?\\)
6306 ;; We've hit an escaped character
6307 (setq c (js2-get-char))
6308 (cl-case c
6309 (?b (setq c ?\b))
6310 (?f (setq c ?\f))
6311 (?n (setq c ?\n))
6312 (?r (setq c ?\r))
6313 (?t (setq c ?\t))
6314 (?v (setq c ?\v))
6315 (?u
6316 (setq c1 (js2-read-unicode-escape))
6317 (if js2-parse-ide-mode
6318 (if c1
6319 (progn
6320 ;; just copy the string in IDE-mode
6321 (js2-add-to-string ?\\)
6322 (js2-add-to-string ?u)
6323 (dotimes (_ 3)
6324 (js2-add-to-string (js2-get-char)))
6325 (setq c (js2-get-char))) ; added at end of loop
6326 ;; flag it as an invalid escape
6327 (js2-report-warning "msg.invalid.escape"
6328 nil (- js2-ts-cursor 2) 6))
6329 ;; Get 4 hex digits; if the u escape is not
6330 ;; followed by 4 hex digits, use 'u' + the
6331 ;; literal character sequence that follows.
6332 (js2-add-to-string ?u)
6333 (setq escape-val 0)
6334 (dotimes (_ 4)
6335 (setq c (js2-get-char)
6336 escape-val (js2-x-digit-to-int c escape-val))
6337 (if (cl-minusp escape-val)
6338 (throw 'continue nil))
6339 (js2-add-to-string c))
6340 ;; prepare for replace of stored 'u' sequence by escape value
6341 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6342 c escape-val)))
6343 (?x
6344 ;; Get 2 hex digits, defaulting to 'x'+literal
6345 ;; sequence, as above.
6346 (setq c (js2-get-char)
6347 escape-val (js2-x-digit-to-int c 0))
6348 (if (cl-minusp escape-val)
6349 (progn
6350 (js2-add-to-string ?x)
6351 (throw 'continue nil))
6352 (setq c1 c
6353 c (js2-get-char)
6354 escape-val (js2-x-digit-to-int c escape-val))
6355 (if (cl-minusp escape-val)
6356 (progn
6357 (js2-add-to-string ?x)
6358 (js2-add-to-string c1)
6359 (throw 'continue nil))
6360 ;; got 2 hex digits
6361 (setq c escape-val))))
6362 (?\n
6363 ;; Remove line terminator after escape to follow
6364 ;; SpiderMonkey and C/C++
6365 (setq c (js2-get-char))
6366 (throw 'continue nil))
6367 (t
6368 (when (and (<= ?0 c) (< c ?8))
6369 (setq val (- c ?0)
6370 c (js2-get-char))
6371 (when (and (<= ?0 c) (< c ?8))
6372 (setq val (- (+ (* 8 val) c) ?0)
6373 c (js2-get-char))
6374 (when (and (<= ?0 c)
6375 (< c ?8)
6376 (< val #o37))
6377 ;; c is 3rd char of octal sequence only
6378 ;; if the resulting val <= 0377
6379 (setq val (- (+ (* 8 val) c) ?0)
6380 c (js2-get-char))))
6381 (js2-unget-char)
6382 (setq c val)))))
6383 (when (and (eq quote-char ?`) (eq c ?$))
6384 (when (eq (setq nc (js2-get-char)) ?\{)
6385 (throw 'break nil))
6386 (js2-unget-char))
6387 (js2-add-to-string c)
6388 (setq c (js2-get-char)))))
6389 (js2-set-string-from-buffer token)
6390 (if (not (eq quote-char ?`))
6391 js2-STRING
6392 (if (and (eq c ?$) (eq nc ?\{))
6393 js2-TEMPLATE_HEAD
6394 js2-NO_SUBS_TEMPLATE))))
6395
6396 (defun js2-read-regexp (start-tt)
6397 "Called by parser when it gets / or /= in literal context."
6398 (let (c err
6399 in-class ; inside a '[' .. ']' character-class
6400 flags
6401 (continue t)
6402 (token (js2-new-token 0)))
6403 (setq js2-ts-string-buffer nil)
6404 (if (eq start-tt js2-ASSIGN_DIV)
6405 ;; mis-scanned /=
6406 (js2-add-to-string ?=)
6407 (if (not (eq start-tt js2-DIV))
6408 (error "failed assertion")))
6409 (while (and (not err)
6410 (or (/= (setq c (js2-get-char)) ?/)
6411 in-class))
6412 (cond
6413 ((or (= c ?\n)
6414 (= c js2-EOF_CHAR))
6415 (setf (js2-token-end token) (1- js2-ts-cursor)
6416 err t
6417 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6418 (js2-report-error "msg.unterminated.re.lit"))
6419 (t (cond
6420 ((= c ?\\)
6421 (js2-add-to-string c)
6422 (setq c (js2-get-char)))
6423 ((= c ?\[)
6424 (setq in-class t))
6425 ((= c ?\])
6426 (setq in-class nil)))
6427 (js2-add-to-string c))))
6428 (unless err
6429 (while continue
6430 (cond
6431 ((js2-match-char ?g)
6432 (push ?g flags))
6433 ((js2-match-char ?i)
6434 (push ?i flags))
6435 ((js2-match-char ?m)
6436 (push ?m flags))
6437 ((and (js2-match-char ?u)
6438 (>= js2-language-version 200))
6439 (push ?u flags))
6440 ((and (js2-match-char ?y)
6441 (>= js2-language-version 200))
6442 (push ?y flags))
6443 (t
6444 (setq continue nil))))
6445 (if (js2-alpha-p (js2-peek-char))
6446 (js2-report-scan-error "msg.invalid.re.flag" t
6447 js2-ts-cursor 1))
6448 (js2-set-string-from-buffer token))
6449 (js2-collect-string flags)))
6450
6451 (defun js2-get-first-xml-token ()
6452 (setq js2-ts-xml-open-tags-count 0
6453 js2-ts-is-xml-attribute nil
6454 js2-ts-xml-is-tag-content nil)
6455 (js2-unget-char)
6456 (js2-get-next-xml-token))
6457
6458 (defun js2-xml-discard-string (token)
6459 "Throw away the string in progress and flag an XML parse error."
6460 (setf js2-ts-string-buffer nil
6461 (js2-token-string token) nil)
6462 (js2-report-scan-error "msg.XML.bad.form" t))
6463
6464 (defun js2-get-next-xml-token ()
6465 (setq js2-ts-string-buffer nil) ; for recording the XML
6466 (let ((token (js2-new-token 0))
6467 c result)
6468 (setq result
6469 (catch 'return
6470 (while t
6471 (setq c (js2-get-char))
6472 (cond
6473 ((= c js2-EOF_CHAR)
6474 (throw 'return js2-ERROR))
6475 (js2-ts-xml-is-tag-content
6476 (cl-case c
6477 (?>
6478 (js2-add-to-string c)
6479 (setq js2-ts-xml-is-tag-content nil
6480 js2-ts-is-xml-attribute nil))
6481 (?/
6482 (js2-add-to-string c)
6483 (when (eq ?> (js2-peek-char))
6484 (setq c (js2-get-char))
6485 (js2-add-to-string c)
6486 (setq js2-ts-xml-is-tag-content nil)
6487 (cl-decf js2-ts-xml-open-tags-count)))
6488 (?{
6489 (js2-unget-char)
6490 (js2-set-string-from-buffer token)
6491 (throw 'return js2-XML))
6492 ((?\' ?\")
6493 (js2-add-to-string c)
6494 (unless (js2-read-quoted-string c token)
6495 (throw 'return js2-ERROR)))
6496 (?=
6497 (js2-add-to-string c)
6498 (setq js2-ts-is-xml-attribute t))
6499 ((? ?\t ?\r ?\n)
6500 (js2-add-to-string c))
6501 (t
6502 (js2-add-to-string c)
6503 (setq js2-ts-is-xml-attribute nil)))
6504 (when (and (not js2-ts-xml-is-tag-content)
6505 (zerop js2-ts-xml-open-tags-count))
6506 (js2-set-string-from-buffer token)
6507 (throw 'return js2-XMLEND)))
6508 (t
6509 ;; else not tag content
6510 (cl-case c
6511 (?<
6512 (js2-add-to-string c)
6513 (setq c (js2-peek-char))
6514 (cl-case c
6515 (?!
6516 (setq c (js2-get-char)) ;; skip !
6517 (js2-add-to-string c)
6518 (setq c (js2-peek-char))
6519 (cl-case c
6520 (?-
6521 (setq c (js2-get-char)) ;; skip -
6522 (js2-add-to-string c)
6523 (if (eq c ?-)
6524 (progn
6525 (js2-add-to-string c)
6526 (unless (js2-read-xml-comment token)
6527 (throw 'return js2-ERROR)))
6528 (js2-xml-discard-string token)
6529 (throw 'return js2-ERROR)))
6530 (?\[
6531 (setq c (js2-get-char)) ;; skip [
6532 (js2-add-to-string c)
6533 (if (and (= (js2-get-char) ?C)
6534 (= (js2-get-char) ?D)
6535 (= (js2-get-char) ?A)
6536 (= (js2-get-char) ?T)
6537 (= (js2-get-char) ?A)
6538 (= (js2-get-char) ?\[))
6539 (progn
6540 (js2-add-to-string ?C)
6541 (js2-add-to-string ?D)
6542 (js2-add-to-string ?A)
6543 (js2-add-to-string ?T)
6544 (js2-add-to-string ?A)
6545 (js2-add-to-string ?\[)
6546 (unless (js2-read-cdata token)
6547 (throw 'return js2-ERROR)))
6548 (js2-xml-discard-string token)
6549 (throw 'return js2-ERROR)))
6550 (t
6551 (unless (js2-read-entity token)
6552 (throw 'return js2-ERROR))))
6553 ;; Allow bare CDATA section, e.g.:
6554 ;; let xml = <![CDATA[ foo bar baz ]]>;
6555 (when (zerop js2-ts-xml-open-tags-count)
6556 (throw 'return js2-XMLEND)))
6557 (??
6558 (setq c (js2-get-char)) ;; skip ?
6559 (js2-add-to-string c)
6560 (unless (js2-read-PI token)
6561 (throw 'return js2-ERROR)))
6562 (?/
6563 ;; end tag
6564 (setq c (js2-get-char)) ;; skip /
6565 (js2-add-to-string c)
6566 (when (zerop js2-ts-xml-open-tags-count)
6567 (js2-xml-discard-string token)
6568 (throw 'return js2-ERROR))
6569 (setq js2-ts-xml-is-tag-content t)
6570 (cl-decf js2-ts-xml-open-tags-count))
6571 (t
6572 ;; start tag
6573 (setq js2-ts-xml-is-tag-content t)
6574 (cl-incf js2-ts-xml-open-tags-count))))
6575 (?{
6576 (js2-unget-char)
6577 (js2-set-string-from-buffer token)
6578 (throw 'return js2-XML))
6579 (t
6580 (js2-add-to-string c))))))))
6581 (setf (js2-token-end token) js2-ts-cursor)
6582 (setf (js2-token-type token) result)
6583 result))
6584
6585 (defun js2-read-quoted-string (quote token)
6586 (let (c)
6587 (catch 'return
6588 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6589 (js2-add-to-string c)
6590 (if (eq c quote)
6591 (throw 'return t)))
6592 (js2-xml-discard-string token) ;; throw away string in progress
6593 nil)))
6594
6595 (defun js2-read-xml-comment (token)
6596 (let ((c (js2-get-char)))
6597 (catch 'return
6598 (while (/= c js2-EOF_CHAR)
6599 (catch 'continue
6600 (js2-add-to-string c)
6601 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6602 (setq c (js2-get-char))
6603 (js2-add-to-string c)
6604 (if (eq (js2-peek-char) ?>)
6605 (progn
6606 (setq c (js2-get-char)) ;; skip >
6607 (js2-add-to-string c)
6608 (throw 'return t))
6609 (throw 'continue nil)))
6610 (setq c (js2-get-char))))
6611 (js2-xml-discard-string token)
6612 nil)))
6613
6614 (defun js2-read-cdata (token)
6615 (let ((c (js2-get-char)))
6616 (catch 'return
6617 (while (/= c js2-EOF_CHAR)
6618 (catch 'continue
6619 (js2-add-to-string c)
6620 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6621 (setq c (js2-get-char))
6622 (js2-add-to-string c)
6623 (if (eq (js2-peek-char) ?>)
6624 (progn
6625 (setq c (js2-get-char)) ;; Skip >
6626 (js2-add-to-string c)
6627 (throw 'return t))
6628 (throw 'continue nil)))
6629 (setq c (js2-get-char))))
6630 (js2-xml-discard-string token)
6631 nil)))
6632
6633 (defun js2-read-entity (token)
6634 (let ((decl-tags 1)
6635 c)
6636 (catch 'return
6637 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6638 (js2-add-to-string c)
6639 (cl-case c
6640 (?<
6641 (cl-incf decl-tags))
6642 (?>
6643 (cl-decf decl-tags)
6644 (if (zerop decl-tags)
6645 (throw 'return t)))))
6646 (js2-xml-discard-string token)
6647 nil)))
6648
6649 (defun js2-read-PI (token)
6650 "Scan an XML processing instruction."
6651 (let (c)
6652 (catch 'return
6653 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6654 (js2-add-to-string c)
6655 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6656 (setq c (js2-get-char)) ;; Skip >
6657 (js2-add-to-string c)
6658 (throw 'return t)))
6659 (js2-xml-discard-string token)
6660 nil)))
6661
6662 ;;; Highlighting
6663
6664 (defun js2-set-face (beg end face &optional record)
6665 "Fontify a region. If RECORD is non-nil, record for later."
6666 (when (cl-plusp js2-highlight-level)
6667 (setq beg (min (point-max) beg)
6668 beg (max (point-min) beg)
6669 end (min (point-max) end)
6670 end (max (point-min) end))
6671 (if record
6672 (push (list beg end face) js2-mode-fontifications)
6673 (put-text-property beg end 'font-lock-face face))))
6674
6675 (defsubst js2-clear-face (beg end)
6676 (remove-text-properties beg end '(font-lock-face nil
6677 help-echo nil
6678 point-entered nil
6679 cursor-sensor-functions nil
6680 c-in-sws nil)))
6681
6682 (defconst js2-ecma-global-props
6683 (concat "^"
6684 (regexp-opt
6685 '("Infinity" "NaN" "undefined" "arguments") t)
6686 "$")
6687 "Value properties of the Ecma-262 Global Object.
6688 Shown at or above `js2-highlight-level' 2.")
6689
6690 ;; might want to add the name "arguments" to this list?
6691 (defconst js2-ecma-object-props
6692 (concat "^"
6693 (regexp-opt
6694 '("prototype" "__proto__" "__parent__") t)
6695 "$")
6696 "Value properties of the Ecma-262 Object constructor.
6697 Shown at or above `js2-highlight-level' 2.")
6698
6699 (defconst js2-ecma-global-funcs
6700 (concat
6701 "^"
6702 (regexp-opt
6703 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6704 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6705 "$")
6706 "Function properties of the Ecma-262 Global object.
6707 Shown at or above `js2-highlight-level' 2.")
6708
6709 (defconst js2-ecma-number-props
6710 (concat "^"
6711 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6712 "NEGATIVE_INFINITY"
6713 "POSITIVE_INFINITY") t)
6714 "$")
6715 "Properties of the Ecma-262 Number constructor.
6716 Shown at or above `js2-highlight-level' 2.")
6717
6718 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6719 "Properties of the Ecma-262 Date constructor.
6720 Shown at or above `js2-highlight-level' 2.")
6721
6722 (defconst js2-ecma-math-props
6723 (concat "^"
6724 (regexp-opt
6725 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6726 t)
6727 "$")
6728 "Properties of the Ecma-262 Math object.
6729 Shown at or above `js2-highlight-level' 2.")
6730
6731 (defconst js2-ecma-math-funcs
6732 (concat "^"
6733 (regexp-opt
6734 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6735 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6736 "$")
6737 "Function properties of the Ecma-262 Math object.
6738 Shown at or above `js2-highlight-level' 2.")
6739
6740 (defconst js2-ecma-function-props
6741 (concat
6742 "^"
6743 (regexp-opt
6744 '(;; properties of the Object prototype object
6745 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6746 "toLocaleString" "toString" "valueOf"
6747 ;; properties of the Function prototype object
6748 "apply" "call"
6749 ;; properties of the Array prototype object
6750 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6751 "splice" "unshift"
6752 ;; properties of the String prototype object
6753 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6754 "localeCompare" "match" "replace" "search" "split" "substring"
6755 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6756 "toUpperCase"
6757 ;; properties of the Number prototype object
6758 "toExponential" "toFixed" "toPrecision"
6759 ;; properties of the Date prototype object
6760 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6761 "getMinutes" "getMonth" "getSeconds" "getTime"
6762 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6763 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6764 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6765 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6766 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6767 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6768 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6769 "toTimeString" "toUTCString"
6770 ;; properties of the RegExp prototype object
6771 "exec" "test"
6772 ;; properties of the JSON prototype object
6773 "parse" "stringify"
6774 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6775 "toSource" "__defineGetter__" "__defineSetter__"
6776 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6777 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6778 t)
6779 "$")
6780 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6781 Shown at or above `js2-highlight-level' 3.")
6782
6783 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6784 (let ((target-name (and target
6785 (js2-name-node-p target)
6786 (js2-name-node-name target)))
6787 (prop-name (if prop (js2-name-node-name prop)))
6788 (level2 (>= js2-highlight-level 2))
6789 (level3 (>= js2-highlight-level 3)))
6790 (when level2
6791 (let ((face
6792 (if call-p
6793 (cond
6794 ((and target prop)
6795 (cond
6796 ((and level3 (string-match js2-ecma-function-props prop-name))
6797 'font-lock-builtin-face)
6798 ((and target-name prop)
6799 (cond
6800 ((string= target-name "Date")
6801 (if (string-match js2-ecma-date-props prop-name)
6802 'font-lock-builtin-face))
6803 ((string= target-name "Math")
6804 (if (string-match js2-ecma-math-funcs prop-name)
6805 'font-lock-builtin-face))))))
6806 (prop
6807 (if (string-match js2-ecma-global-funcs prop-name)
6808 'font-lock-builtin-face)))
6809 (cond
6810 ((and target prop)
6811 (cond
6812 ((string= target-name "Number")
6813 (if (string-match js2-ecma-number-props prop-name)
6814 'font-lock-constant-face))
6815 ((string= target-name "Math")
6816 (if (string-match js2-ecma-math-props prop-name)
6817 'font-lock-constant-face))))
6818 (prop
6819 (if (string-match js2-ecma-object-props prop-name)
6820 'font-lock-constant-face))))))
6821 (when face
6822 (let ((pos (+ (js2-node-pos parent) ; absolute
6823 (js2-node-pos prop)))) ; relative
6824 (js2-set-face pos
6825 (+ pos (js2-node-len prop))
6826 face 'record)))))))
6827
6828 (defun js2-parse-highlight-member-expr-node (node)
6829 "Perform syntax highlighting of EcmaScript built-in properties.
6830 The variable `js2-highlight-level' governs this highlighting."
6831 (let (face target prop name pos end parent call-p callee)
6832 (cond
6833 ;; case 1: simple name, e.g. foo
6834 ((js2-name-node-p node)
6835 (setq name (js2-name-node-name node))
6836 ;; possible for name to be nil in rare cases - saw it when
6837 ;; running js2-mode on an elisp buffer. Might as well try to
6838 ;; make it so js2-mode never barfs.
6839 (when name
6840 (setq face (if (string-match js2-ecma-global-props name)
6841 'font-lock-constant-face))
6842 (when face
6843 (setq pos (js2-node-pos node)
6844 end (+ pos (js2-node-len node)))
6845 (js2-set-face pos end face 'record))))
6846 ;; case 2: property access or function call
6847 ((or (js2-prop-get-node-p node)
6848 ;; highlight function call if expr is a prop-get node
6849 ;; or a plain name (i.e. unqualified function call)
6850 (and (setq call-p (js2-call-node-p node))
6851 (setq callee (js2-call-node-target node)) ; separate setq!
6852 (or (js2-prop-get-node-p callee)
6853 (js2-name-node-p callee))))
6854 (setq parent node
6855 node (if call-p callee node))
6856 (if (and call-p (js2-name-node-p callee))
6857 (setq prop callee)
6858 (setq target (js2-prop-get-node-left node)
6859 prop (js2-prop-get-node-right node)))
6860 (cond
6861 ((js2-name-node-p prop)
6862 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6863 (js2-parse-highlight-prop-get parent target prop call-p))
6864 ((js2-name-node-p target)
6865 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6866 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6867
6868 (defun js2-parse-highlight-member-expr-fn-name (expr)
6869 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6870 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6871 We currently only handle the case where the last component is a prop-get
6872 of a simple name. Called before EXPR has a parent node."
6873 (let (pos
6874 (name (and (js2-prop-get-node-p expr)
6875 (js2-prop-get-node-right expr))))
6876 (when (js2-name-node-p name)
6877 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6878 (js2-node-pos name)))
6879 (+ pos (js2-node-len name))
6880 'font-lock-function-name-face
6881 'record))))
6882
6883 ;; source: http://jsdoc.sourceforge.net/
6884 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6885 ;; allows type specifications, and needs work before entering the wild.
6886
6887 (defconst js2-jsdoc-param-tag-regexp
6888 (concat "^\\s-*\\*+\\s-*\\(@"
6889 "\\(?:param\\|argument\\)"
6890 "\\)"
6891 "\\s-*\\({[^}]+}\\)?" ; optional type
6892 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6893 "\\>")
6894 "Matches jsdoc tags with optional type and optional param name.")
6895
6896 (defconst js2-jsdoc-typed-tag-regexp
6897 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6898 (regexp-opt
6899 '("enum"
6900 "extends"
6901 "field"
6902 "id"
6903 "implements"
6904 "lends"
6905 "mods"
6906 "requires"
6907 "return"
6908 "returns"
6909 "throw"
6910 "throws"))
6911 "\\)\\)\\s-*\\({[^}]+}\\)?")
6912 "Matches jsdoc tags with optional type.")
6913
6914 (defconst js2-jsdoc-arg-tag-regexp
6915 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6916 (regexp-opt
6917 '("alias"
6918 "augments"
6919 "borrows"
6920 "bug"
6921 "base"
6922 "config"
6923 "default"
6924 "define"
6925 "exception"
6926 "function"
6927 "member"
6928 "memberOf"
6929 "name"
6930 "namespace"
6931 "property"
6932 "since"
6933 "suppress"
6934 "this"
6935 "throws"
6936 "type"
6937 "version"))
6938 "\\)\\)\\s-+\\([^ \t]+\\)")
6939 "Matches jsdoc tags with a single argument.")
6940
6941 (defconst js2-jsdoc-empty-tag-regexp
6942 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6943 (regexp-opt
6944 '("addon"
6945 "author"
6946 "class"
6947 "const"
6948 "constant"
6949 "constructor"
6950 "constructs"
6951 "deprecated"
6952 "desc"
6953 "description"
6954 "event"
6955 "example"
6956 "exec"
6957 "export"
6958 "fileoverview"
6959 "final"
6960 "function"
6961 "hidden"
6962 "ignore"
6963 "implicitCast"
6964 "inheritDoc"
6965 "inner"
6966 "interface"
6967 "license"
6968 "noalias"
6969 "noshadow"
6970 "notypecheck"
6971 "override"
6972 "owner"
6973 "preserve"
6974 "preserveTry"
6975 "private"
6976 "protected"
6977 "public"
6978 "static"
6979 "supported"
6980 ))
6981 "\\)\\)\\s-*")
6982 "Matches empty jsdoc tags.")
6983
6984 (defconst js2-jsdoc-link-tag-regexp
6985 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6986 "Matches a jsdoc link or code tag.")
6987
6988 (defconst js2-jsdoc-see-tag-regexp
6989 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6990 "Matches a jsdoc @see tag.")
6991
6992 (defconst js2-jsdoc-html-tag-regexp
6993 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6994 "Matches a simple (no attributes) html start- or end-tag.")
6995
6996 (defun js2-jsdoc-highlight-helper ()
6997 (js2-set-face (match-beginning 1)
6998 (match-end 1)
6999 'js2-jsdoc-tag)
7000 (if (match-beginning 2)
7001 (if (save-excursion
7002 (goto-char (match-beginning 2))
7003 (= (char-after) ?{))
7004 (js2-set-face (1+ (match-beginning 2))
7005 (1- (match-end 2))
7006 'js2-jsdoc-type)
7007 (js2-set-face (match-beginning 2)
7008 (match-end 2)
7009 'js2-jsdoc-value)))
7010 (if (match-beginning 3)
7011 (js2-set-face (match-beginning 3)
7012 (match-end 3)
7013 'js2-jsdoc-value)))
7014
7015 (defun js2-highlight-jsdoc (ast)
7016 "Highlight doc comment tags."
7017 (let ((comments (js2-ast-root-comments ast))
7018 beg end)
7019 (save-excursion
7020 (dolist (node comments)
7021 (when (eq (js2-comment-node-format node) 'jsdoc)
7022 (setq beg (js2-node-abs-pos node)
7023 end (+ beg (js2-node-len node)))
7024 (save-restriction
7025 (narrow-to-region beg end)
7026 (dolist (re (list js2-jsdoc-param-tag-regexp
7027 js2-jsdoc-typed-tag-regexp
7028 js2-jsdoc-arg-tag-regexp
7029 js2-jsdoc-link-tag-regexp
7030 js2-jsdoc-see-tag-regexp
7031 js2-jsdoc-empty-tag-regexp))
7032 (goto-char beg)
7033 (while (re-search-forward re nil t)
7034 (js2-jsdoc-highlight-helper)))
7035 ;; simple highlighting for html tags
7036 (goto-char beg)
7037 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7038 (js2-set-face (match-beginning 1)
7039 (match-end 1)
7040 'js2-jsdoc-html-tag-delimiter)
7041 (js2-set-face (match-beginning 2)
7042 (match-end 2)
7043 'js2-jsdoc-html-tag-name)
7044 (js2-set-face (match-beginning 3)
7045 (match-end 3)
7046 'js2-jsdoc-html-tag-delimiter))))))))
7047
7048 (defun js2-highlight-assign-targets (_node left right)
7049 "Highlight function properties and external variables."
7050 (let (leftpos name)
7051 ;; highlight vars and props assigned function values
7052 (when (or (js2-function-node-p right)
7053 (js2-class-node-p right))
7054 (cond
7055 ;; var foo = function() {...}
7056 ((js2-name-node-p left)
7057 (setq name left))
7058 ;; foo.bar.baz = function() {...}
7059 ((and (js2-prop-get-node-p left)
7060 (js2-name-node-p (js2-prop-get-node-right left)))
7061 (setq name (js2-prop-get-node-right left))))
7062 (when name
7063 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7064 (+ leftpos (js2-node-len name))
7065 'font-lock-function-name-face
7066 'record)))))
7067
7068 (defun js2-record-name-node (node)
7069 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7070 later. NODE must be a name node."
7071 (let ((leftpos (js2-node-abs-pos node)))
7072 (push (list node js2-current-scope
7073 leftpos
7074 (+ leftpos (js2-node-len node)))
7075 js2-recorded-identifiers)))
7076
7077 (defun js2-highlight-undeclared-vars ()
7078 "After entire parse is finished, look for undeclared variable references.
7079 We have to wait until entire buffer is parsed, since JavaScript permits var
7080 decls to occur after they're used.
7081
7082 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7083 it is considered declared."
7084 (let (name)
7085 (dolist (entry js2-recorded-identifiers)
7086 (cl-destructuring-bind (name-node scope pos end) entry
7087 (setq name (js2-name-node-name name-node))
7088 (unless (or (member name js2-global-externs)
7089 (member name js2-default-externs)
7090 (member name js2-additional-externs)
7091 (js2-get-defining-scope scope name pos))
7092 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7093 'js2-external-variable))))))
7094
7095 (defun js2--add-or-update-symbol (symbol inition used vars)
7096 "Add or update SYMBOL entry in VARS, an hash table.
7097 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7098 respectively meaning that SYMBOL is a mere declaration, an
7099 assignment or a function parameter; when USED is t, the symbol
7100 node is assumed to be an usage and thus added to the list stored
7101 in the cdr of the entry.
7102 "
7103 (let* ((nm (js2-name-node-name symbol))
7104 (es (js2-node-get-enclosing-scope symbol))
7105 (ds (js2-get-defining-scope es nm)))
7106 (when (and ds (not (equal nm "arguments")))
7107 (let* ((sym (js2-scope-get-symbol ds nm))
7108 (var (gethash sym vars))
7109 (err-var-p (js2-catch-node-p ds)))
7110 (unless inition
7111 (setq inition err-var-p))
7112 (if var
7113 (progn
7114 (when (and inition (not (equal (car var) ?P)))
7115 (setcar var inition))
7116 (when used
7117 (push symbol (cdr var))))
7118 ;; do not consider the declaration of catch parameter as an usage
7119 (when (and err-var-p used)
7120 (setq used nil))
7121 (puthash sym (cons inition (if used (list symbol))) vars))))))
7122
7123 (defun js2--classify-variables ()
7124 "Collect and classify variables declared or used within js2-mode-ast.
7125 Traverse the whole ast tree returning a summary of the variables
7126 usage as an hash-table, keyed by their corresponding symbol table
7127 entry.
7128 Each variable is described by a tuple where the car is a flag
7129 indicating whether the variable has been initialized and the cdr
7130 is a possibly empty list of name nodes where it is used. External
7131 symbols, i.e. those not present in the whole scopes hierarchy,
7132 are ignored."
7133 (let ((vars (make-hash-table :test #'eq :size 100)))
7134 (js2-visit-ast
7135 js2-mode-ast
7136 (lambda (node end-p)
7137 (when (null end-p)
7138 (cond
7139 ((js2-var-init-node-p node)
7140 ;; take note about possibly initialized declarations
7141 (let ((target (js2-var-init-node-target node))
7142 (initializer (js2-var-init-node-initializer node)))
7143 (when target
7144 (let* ((parent (js2-node-parent node))
7145 (grandparent (if parent (js2-node-parent parent)))
7146 (inited (not (null initializer))))
7147 (unless inited
7148 (setq inited
7149 (and grandparent
7150 (js2-for-in-node-p grandparent)
7151 (memq target
7152 (mapcar #'js2-var-init-node-target
7153 (js2-var-decl-node-kids
7154 (js2-for-in-node-iterator grandparent)))))))
7155 (js2--add-or-update-symbol target inited nil vars)))))
7156
7157 ((js2-assign-node-p node)
7158 ;; take note about assignments
7159 (let ((left (js2-assign-node-left node)))
7160 (when (js2-name-node-p left)
7161 (js2--add-or-update-symbol left t nil vars))))
7162
7163 ((js2-prop-get-node-p node)
7164 ;; handle x.y.z nodes, considering only x
7165 (let ((left (js2-prop-get-node-left node)))
7166 (when (js2-name-node-p left)
7167 (js2--add-or-update-symbol left nil t vars))))
7168
7169 ((js2-name-node-p node)
7170 ;; take note about used variables
7171 (let ((parent (js2-node-parent node)))
7172 (when parent
7173 (unless (or (and (js2-var-init-node-p parent) ; handled above
7174 (eq node (js2-var-init-node-target parent)))
7175 (and (js2-assign-node-p parent)
7176 (eq node (js2-assign-node-left parent)))
7177 (js2-prop-get-node-p parent))
7178 (let ((used t) inited)
7179 (cond
7180 ((and (js2-function-node-p parent)
7181 (js2-wrapper-function-p parent))
7182 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7183
7184 ((js2-for-in-node-p parent)
7185 (if (eq node (js2-for-in-node-iterator parent))
7186 (setq inited t used nil)))
7187
7188 ((js2-function-node-p parent)
7189 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7190 used nil)))
7191
7192 (unless used
7193 (let ((grandparent (js2-node-parent parent)))
7194 (when grandparent
7195 (setq used (js2-return-node-p grandparent)))))
7196
7197 (js2--add-or-update-symbol node inited used vars))))))))
7198 t))
7199 vars))
7200
7201 (defun js2--get-name-node (node)
7202 (cond
7203 ((js2-name-node-p node) node)
7204 ((js2-function-node-p node)
7205 (js2-function-node-name node))
7206 ((js2-class-node-p node)
7207 (js2-class-node-name node))
7208 ((js2-comp-loop-node-p node)
7209 (js2-comp-loop-node-iterator node))
7210 (t node)))
7211
7212 (defun js2--highlight-unused-variable (symbol info)
7213 (let ((name (js2-symbol-name symbol))
7214 (inited (car info))
7215 (refs (cdr info))
7216 pos len)
7217 (unless (and inited refs)
7218 (if refs
7219 (dolist (ref refs)
7220 (setq pos (js2-node-abs-pos ref))
7221 (setq len (js2-name-node-len ref))
7222 (js2-report-warning "msg.uninitialized.variable" name pos len
7223 'js2-warning))
7224 (when (or js2-warn-about-unused-function-arguments
7225 (not (eq inited ?P)))
7226 (let* ((symn (js2-symbol-ast-node symbol))
7227 (namen (js2--get-name-node symn)))
7228 (unless (js2-node-top-level-decl-p namen)
7229 (setq pos (js2-node-abs-pos namen))
7230 (setq len (js2-name-node-len namen))
7231 (js2-report-warning "msg.unused.variable" name pos len
7232 'js2-warning))))))))
7233
7234 (defun js2-highlight-unused-variables ()
7235 "Highlight unused variables."
7236 (let ((vars (js2--classify-variables)))
7237 (maphash #'js2--highlight-unused-variable vars)))
7238
7239 ;;;###autoload
7240 (define-minor-mode js2-highlight-unused-variables-mode
7241 "Toggle highlight of unused variables."
7242 :lighter ""
7243 (if js2-highlight-unused-variables-mode
7244 (add-hook 'js2-post-parse-callbacks
7245 #'js2-highlight-unused-variables nil t)
7246 (remove-hook 'js2-post-parse-callbacks
7247 #'js2-highlight-unused-variables t)))
7248
7249 (defun js2-set-default-externs ()
7250 "Set the value of `js2-default-externs' based on the various
7251 `js2-include-?-externs' variables."
7252 (setq js2-default-externs
7253 (append js2-ecma-262-externs
7254 (if js2-include-browser-externs js2-browser-externs)
7255 (if (and js2-include-browser-externs
7256 (>= js2-language-version 200)) js2-harmony-externs)
7257 (if js2-include-rhino-externs js2-rhino-externs)
7258 (if js2-include-node-externs js2-node-externs)
7259 (if (or js2-include-browser-externs js2-include-node-externs)
7260 js2-typed-array-externs))))
7261
7262 (defun js2-apply-jslint-globals ()
7263 (setq js2-additional-externs
7264 (nconc (js2-get-jslint-globals)
7265 js2-additional-externs)))
7266
7267 (defun js2-get-jslint-globals ()
7268 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7269 when (and (eq 'block (js2-comment-node-format node))
7270 (save-excursion
7271 (goto-char (js2-node-abs-pos node))
7272 (looking-at "/\\*global ")))
7273 append (js2-get-jslint-globals-in
7274 (match-end 0)
7275 (js2-node-abs-end node))))
7276
7277 (defun js2-get-jslint-globals-in (beg end)
7278 (let (res)
7279 (save-excursion
7280 (goto-char beg)
7281 (while (re-search-forward js2-mode-identifier-re end t)
7282 (let ((match (match-string 0)))
7283 (unless (member match '("true" "false"))
7284 (push match res)))))
7285 (nreverse res)))
7286
7287 ;;; IMenu support
7288
7289 ;; We currently only support imenu, but eventually should support speedbar and
7290 ;; possibly other browsing mechanisms.
7291
7292 ;; The basic strategy is to identify function assignment targets of the form
7293 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7294 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7295 ;; for imenu after parsing is finished.
7296
7297 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7298 ;; JavaScript, and the general problem is undecidable. However, several forms
7299 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7300 ;; include:
7301
7302 ;; function foo() -- function declaration
7303 ;; foo = function() -- function expression assigned to variable
7304 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7305 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7306 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7307 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7308 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7309 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7310 ;; function foo() {function bar() {...}} -- nested function
7311 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7312
7313 ;; This list boils down to a few forms that can be combined recursively.
7314 ;; Top-level named function declarations include both the left-hand (name)
7315 ;; and the right-hand (function value) expressions needed to produce an imenu
7316 ;; entry. The other "right-hand" forms we need to look for are:
7317 ;; - functions declared as props/getters/setters in object literals
7318 ;; - nested named function declarations
7319 ;; The "left-hand" expressions that functions can be assigned to include:
7320 ;; - local/global variables
7321 ;; - nested property-get expressions like a.b.c.d
7322 ;; - element gets like foo[10] or foo['bar'] where the index
7323 ;; expression can be trivially converted to a property name. They
7324 ;; effectively then become property gets.
7325
7326 ;; All the different definition types are canonicalized into the form
7327 ;; foo.bar.baz = position-of-function-keyword
7328
7329 ;; We need to build a trie-like structure for imenu. As an example,
7330 ;; consider the following JavaScript code:
7331
7332 ;; a = function() {...} // function at position 5
7333 ;; b = function() {...} // function at position 25
7334 ;; foo = function() {...} // function at position 100
7335 ;; foo.bar = function() {...} // function at position 200
7336 ;; foo.bar.baz = function() {...} // function at position 300
7337 ;; foo.bar.zab = function() {...} // function at position 400
7338
7339 ;; During parsing we accumulate an entry for each definition in
7340 ;; the variable `js2-imenu-recorder', like so:
7341
7342 ;; '((fn a 5)
7343 ;; (fn b 25)
7344 ;; (fn foo 100)
7345 ;; (fn foo bar 200)
7346 ;; (fn foo bar baz 300)
7347 ;; (fn foo bar zab 400))
7348
7349 ;; Where 'fn' is the respective function node.
7350 ;; After parsing these entries are merged into this alist-trie:
7351
7352 ;; '((a . 1)
7353 ;; (b . 2)
7354 ;; (foo (<definition> . 3)
7355 ;; (bar (<definition> . 6)
7356 ;; (baz . 100)
7357 ;; (zab . 200))))
7358
7359 ;; Note the wacky need for a <definition> name. The token can be anything
7360 ;; that isn't a valid JavaScript identifier, because you might make foo
7361 ;; a function and then start setting properties on it that are also functions.
7362
7363 (defun js2-prop-node-name (node)
7364 "Return the name of a node that may be a property-get/property-name.
7365 If NODE is not a valid name-node, string-node or integral number-node,
7366 returns nil. Otherwise returns the string name/value of the node."
7367 (cond
7368 ((js2-name-node-p node)
7369 (js2-name-node-name node))
7370 ((js2-string-node-p node)
7371 (js2-string-node-value node))
7372 ((and (js2-number-node-p node)
7373 (string-match "^[0-9]+$" (js2-number-node-value node)))
7374 (js2-number-node-value node))
7375 ((eq (js2-node-type node) js2-THIS)
7376 "this")
7377 ((eq (js2-node-type node) js2-SUPER)
7378 "super")))
7379
7380 (defun js2-node-qname-component (node)
7381 "Return the name of this node, if it contributes to a qname.
7382 Returns nil if the node doesn't contribute."
7383 (copy-sequence
7384 (or (js2-prop-node-name node)
7385 (if (and (js2-function-node-p node)
7386 (js2-function-node-name node))
7387 (js2-name-node-name (js2-function-node-name node))))))
7388
7389 (defun js2-record-imenu-entry (fn-node qname pos)
7390 "Add an entry to `js2-imenu-recorder'.
7391 FN-NODE should be the current item's function node.
7392
7393 Associate FN-NODE with its QNAME for later lookup.
7394 This is used in postprocessing the chain list. For each chain, we find
7395 the parent function, look up its qname, then prepend a copy of it to the chain."
7396 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7397 (unless js2-imenu-function-map
7398 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7399 (puthash fn-node qname js2-imenu-function-map))
7400
7401 (defun js2-record-imenu-functions (node &optional var)
7402 "Record function definitions for imenu.
7403 NODE is a function node or an object literal.
7404 VAR, if non-nil, is the expression that NODE is being assigned to.
7405 When passed arguments of wrong type, does nothing."
7406 (when js2-parse-ide-mode
7407 (let ((fun-p (js2-function-node-p node))
7408 qname fname-node)
7409 (cond
7410 ;; non-anonymous function declaration?
7411 ((and fun-p
7412 (not var)
7413 (setq fname-node (js2-function-node-name node)))
7414 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7415 ;; for remaining forms, compute left-side tree branch first
7416 ((and var (setq qname (js2-compute-nested-prop-get var)))
7417 (cond
7418 ;; foo.bar.baz = function
7419 (fun-p
7420 (js2-record-imenu-entry node qname (js2-node-pos node)))
7421 ;; foo.bar.baz = object-literal
7422 ;; look for nested functions: {a: {b: function() {...} }}
7423 ((js2-object-node-p node)
7424 ;; Node position here is still absolute, since the parser
7425 ;; passes the assignment target and value expressions
7426 ;; to us before they are added as children of the assignment node.
7427 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7428
7429 (defun js2-compute-nested-prop-get (node)
7430 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7431 component nodes as a list. Otherwise return nil. Element-gets are treated
7432 as property-gets if the index expression is a string, or a positive integer."
7433 (let (left right head)
7434 (cond
7435 ((or (js2-name-node-p node)
7436 (js2-this-or-super-node-p node))
7437 (list node))
7438 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7439 ((js2-prop-get-node-p node) ; foo.bar
7440 (setq left (js2-prop-get-node-left node)
7441 right (js2-prop-get-node-right node))
7442 (if (setq head (js2-compute-nested-prop-get left))
7443 (nconc head (list right))))
7444 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7445 (setq left (js2-elem-get-node-target node)
7446 right (js2-elem-get-node-element node))
7447 (if (or (js2-string-node-p right) ; ['bar']
7448 (and (js2-number-node-p right) ; [10]
7449 (string-match "^[0-9]+$"
7450 (js2-number-node-value right))))
7451 (if (setq head (js2-compute-nested-prop-get left))
7452 (nconc head (list right))))))))
7453
7454 (defun js2-record-object-literal (node qname pos)
7455 "Recursively process an object literal looking for functions.
7456 NODE is an object literal that is the right-hand child of an assignment
7457 expression. QNAME is a list of nodes representing the assignment target,
7458 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7459 POS is the absolute position of the node.
7460 We do a depth-first traversal of NODE. For any functions we find,
7461 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7462 (let (right)
7463 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7464 (let ((left (js2-infix-node-left e))
7465 ;; Element positions are relative to the parent position.
7466 (pos (+ pos (js2-node-pos e))))
7467 (cond
7468 ;; foo: function() {...}
7469 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7470 (when (js2-prop-node-name left)
7471 ;; As a policy decision, we record the position of the property,
7472 ;; not the position of the `function' keyword, since the property
7473 ;; is effectively the name of the function.
7474 (js2-record-imenu-entry right (append qname (list left)) pos)))
7475 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7476 ((js2-object-node-p right)
7477 (js2-record-object-literal right
7478 (append qname (list (js2-infix-node-left e)))
7479 (+ pos (js2-node-pos right)))))))))
7480
7481 (defun js2-node-top-level-decl-p (node)
7482 "Return t if NODE's name is defined in the top-level scope.
7483 Also returns t if NODE's name is not defined in any scope, since it implies
7484 that it's an external variable, which must also be in the top-level scope."
7485 (let* ((name (js2-prop-node-name node))
7486 (this-scope (js2-node-get-enclosing-scope node))
7487 defining-scope)
7488 (cond
7489 ((js2-this-or-super-node-p node)
7490 nil)
7491 ((null this-scope)
7492 t)
7493 ((setq defining-scope (js2-get-defining-scope this-scope name))
7494 (js2-ast-root-p defining-scope))
7495 (t t))))
7496
7497 (defun js2-wrapper-function-p (node)
7498 "Return t if NODE is a function expression that's immediately invoked.
7499 NODE must be `js2-function-node'."
7500 (let ((parent (js2-node-parent node)))
7501 (or
7502 ;; function(){...}();
7503 (and (js2-call-node-p parent)
7504 (eq node (js2-call-node-target parent)))
7505 (and (js2-paren-node-p parent)
7506 ;; (function(){...})();
7507 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7508 ;; (function(){...}).call(this);
7509 (and (js2-prop-get-node-p parent)
7510 (member (js2-name-node-name (js2-prop-get-node-right parent))
7511 '("call" "apply"))
7512 (js2-call-node-p (js2-node-parent parent))))))))
7513
7514 (defun js2-browse-postprocess-chains ()
7515 "Modify function-declaration name chains after parsing finishes.
7516 Some of the information is only available after the parse tree is complete.
7517 For instance, processing a nested scope requires a parent function node."
7518 (let (result fn parent-qname p elem)
7519 (dolist (entry js2-imenu-recorder)
7520 ;; function node goes first
7521 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7522 ;; Examine head's defining scope:
7523 ;; Pre-processed chain, or top-level/external, keep as-is.
7524 (if (or (stringp head) (js2-node-top-level-decl-p head))
7525 (push chain result)
7526 (when (js2-this-or-super-node-p head)
7527 (setq chain (cdr chain))) ; discard this-node
7528 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7529 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7530 (when (eq parent-qname 'not-found)
7531 ;; anonymous function expressions are not recorded
7532 ;; during the parse, so we need to handle this case here
7533 (setq parent-qname
7534 (if (js2-wrapper-function-p fn)
7535 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7536 (if (js2-ast-root-p grandparent)
7537 nil
7538 (gethash grandparent js2-imenu-function-map 'skip)))
7539 'skip))
7540 (puthash fn parent-qname js2-imenu-function-map))
7541 (if (eq parent-qname 'skip)
7542 ;; We don't show it, let's record that fact.
7543 (remhash current-fn js2-imenu-function-map)
7544 ;; Prepend parent fn qname to this chain.
7545 (let ((qname (append parent-qname chain)))
7546 (puthash current-fn (butlast qname) js2-imenu-function-map)
7547 (push qname result)))))))
7548 ;; Collect chains obtained by third-party code.
7549 (let (js2-imenu-recorder)
7550 (run-hooks 'js2-build-imenu-callbacks)
7551 (dolist (entry js2-imenu-recorder)
7552 (push (cdr entry) result)))
7553 ;; Finally replace each node in each chain with its name.
7554 (dolist (chain result)
7555 (setq p chain)
7556 (while p
7557 (if (js2-node-p (setq elem (car p)))
7558 (setcar p (js2-node-qname-component elem)))
7559 (setq p (cdr p))))
7560 result))
7561
7562 ;; Merge name chains into a trie-like tree structure of nested lists.
7563 ;; To simplify construction of the trie, we first build it out using the rule
7564 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7565 ;; [key, num-or-list]. The second element can be a number; if so, this key
7566 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7567 ;; associated with the key at this level.) Otherwise the second element is
7568 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7569 ;; a simple recursive formulation.
7570 ;;
7571 ;; js2-mode is building the data structure for imenu. The imenu documentation
7572 ;; claims that it's the structure above, but in practice it wants the children
7573 ;; at the same list level as the key for that level, which is how I've drawn
7574 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7575 ;; list wrapper around the children at each level.
7576 ;;
7577 ;; A completed nested imenu-alist entry looks like this:
7578 ;; '(("foo"
7579 ;; ("<definition>" . 7)
7580 ;; ("bar"
7581 ;; ("a" . 40)
7582 ;; ("b" . 60))))
7583 ;;
7584 ;; In particular, the documentation for `imenu--index-alist' says that
7585 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7586 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7587
7588 (defun js2-treeify (lst)
7589 "Convert (a b c d) to (a ((b ((c d)))))."
7590 (if (null (cddr lst)) ; list length <= 2
7591 lst
7592 (list (car lst) (list (js2-treeify (cdr lst))))))
7593
7594 (defun js2-build-alist-trie (chains trie)
7595 "Merge declaration name chains into a trie-like alist structure for imenu.
7596 CHAINS is the qname chain list produced during parsing. TRIE is a
7597 list of elements built up so far."
7598 (let (head tail pos branch kids)
7599 (dolist (chain chains)
7600 (setq head (car chain)
7601 tail (cdr chain)
7602 pos (if (numberp (car tail)) (car tail))
7603 branch (js2-find-if (lambda (n)
7604 (string= (car n) head))
7605 trie)
7606 kids (cl-second branch))
7607 (cond
7608 ;; case 1: this key isn't in the trie yet
7609 ((null branch)
7610 (if trie
7611 (setcdr (last trie) (list (js2-treeify chain)))
7612 (setq trie (list (js2-treeify chain)))))
7613 ;; case 2: key is present with a single number entry: replace w/ list
7614 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7615 ;; ("<definition>" 20)))
7616 ((numberp kids)
7617 (setcar (cdr branch)
7618 (list (list "<definition-1>" kids)
7619 (if pos
7620 (list "<definition-2>" pos)
7621 (js2-treeify tail)))))
7622 ;; case 3: key is there (with kids), and we're a number entry
7623 (pos
7624 (setcdr (last kids)
7625 (list
7626 (list (format "<definition-%d>"
7627 (1+ (cl-loop for kid in kids
7628 count (eq ?< (aref (car kid) 0)))))
7629 pos))))
7630 ;; case 4: key is there with kids, need to merge in our chain
7631 (t
7632 (js2-build-alist-trie (list tail) kids))))
7633 trie))
7634
7635 (defun js2-flatten-trie (trie)
7636 "Convert TRIE to imenu-format.
7637 Recurses through nodes, and for each one whose second element is a list,
7638 appends the list's flattened elements to the current element. Also
7639 changes the tails into conses. For instance, this pre-flattened trie
7640
7641 '(a ((b 20)
7642 (c ((d 30)
7643 (e 40)))))
7644
7645 becomes
7646
7647 '(a (b . 20)
7648 (c (d . 30)
7649 (e . 40)))
7650
7651 Note that the root of the trie has no key, just a list of chains.
7652 This is also true for the value of any key with multiple children,
7653 e.g. key 'c' in the example above."
7654 (cond
7655 ((listp (car trie))
7656 (mapcar #'js2-flatten-trie trie))
7657 (t
7658 (if (numberp (cl-second trie))
7659 (cons (car trie) (cl-second trie))
7660 ;; else pop list and append its kids
7661 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7662
7663 (defun js2-build-imenu-index ()
7664 "Turn `js2-imenu-recorder' into an imenu data structure."
7665 (when (eq js2-imenu-recorder 'empty)
7666 (setq js2-imenu-recorder nil))
7667 (let* ((chains (js2-browse-postprocess-chains))
7668 (result (js2-build-alist-trie chains nil)))
7669 (js2-flatten-trie result)))
7670
7671 (defun js2-test-print-chains (chains)
7672 "Print a list of qname chains.
7673 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7674 i.e. one or more nodes, and an integer position as the list tail."
7675 (mapconcat (lambda (chain)
7676 (concat "("
7677 (mapconcat (lambda (elem)
7678 (if (js2-node-p elem)
7679 (or (js2-node-qname-component elem)
7680 "nil")
7681 (number-to-string elem)))
7682 chain
7683 " ")
7684 ")"))
7685 chains
7686 "\n"))
7687
7688 ;;; Parser
7689
7690 (defconst js2-version "1.8.5"
7691 "Version of JavaScript supported.")
7692
7693 (defun js2-record-face (face &optional token)
7694 "Record a style run of FACE for TOKEN or the current token."
7695 (unless token (setq token (js2-current-token)))
7696 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7697
7698 (defsubst js2-node-end (n)
7699 "Computes the absolute end of node N.
7700 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7701 is only true until the node is added to its parent; i.e., while parsing."
7702 (+ (js2-node-pos n)
7703 (js2-node-len n)))
7704
7705 (defun js2-record-comment (token)
7706 "Record a comment in `js2-scanned-comments'."
7707 (let ((ct (js2-token-comment-type token))
7708 (beg (js2-token-beg token))
7709 (end (js2-token-end token)))
7710 (push (make-js2-comment-node :len (- end beg)
7711 :format ct)
7712 js2-scanned-comments)
7713 (when js2-parse-ide-mode
7714 (js2-record-face (if (eq ct 'jsdoc)
7715 'font-lock-doc-face
7716 'font-lock-comment-face)
7717 token)
7718 (when (memq ct '(html preprocessor))
7719 ;; Tell cc-engine the bounds of the comment.
7720 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7721
7722 (defun js2-peek-token ()
7723 "Return the next token type without consuming it.
7724 If `js2-ti-lookahead' is positive, return the type of next token
7725 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7726 (if (not (zerop js2-ti-lookahead))
7727 (js2-token-type
7728 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7729 (let ((tt (js2-get-token-internal nil)))
7730 (js2-unget-token)
7731 tt)))
7732
7733 (defalias 'js2-next-token 'js2-get-token)
7734
7735 (defun js2-match-token (match &optional dont-unget)
7736 "Get next token and return t if it matches MATCH, a bytecode.
7737 Returns nil and consumes nothing if MATCH is not the next token."
7738 (if (/= (js2-get-token) match)
7739 (ignore (unless dont-unget (js2-unget-token)))
7740 t))
7741
7742 (defun js2-match-contextual-kwd (name)
7743 "Consume and return t if next token is `js2-NAME', and its
7744 string is NAME. Returns nil and keeps current token otherwise."
7745 (if (or (/= (js2-get-token) js2-NAME)
7746 (not (string= (js2-current-token-string) name)))
7747 (progn
7748 (js2-unget-token)
7749 nil)
7750 (js2-record-face 'font-lock-keyword-face)
7751 t))
7752
7753 (defun js2-get-prop-name-token ()
7754 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7755
7756 (defun js2-match-prop-name ()
7757 "Consume token and return t if next token is a valid property name.
7758 If `js2-language-version' is >= 180, a keyword or reserved word
7759 is considered valid name as well."
7760 (if (eq js2-NAME (js2-get-prop-name-token))
7761 t
7762 (js2-unget-token)
7763 nil))
7764
7765 (defun js2-must-match-prop-name (msg-id &optional pos len)
7766 (if (js2-match-prop-name)
7767 t
7768 (js2-report-error msg-id nil pos len)
7769 nil))
7770
7771 (defun js2-peek-token-or-eol ()
7772 "Return js2-EOL if the next token immediately follows a newline.
7773 Else returns the next token. Used in situations where we don't
7774 consider certain token types valid if they are preceded by a newline.
7775 One example is the postfix ++ or -- operator, which has to be on the
7776 same line as its operand."
7777 (let ((tt (js2-get-token))
7778 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7779 (js2-unget-token)
7780 (if follows-eol
7781 js2-EOL
7782 tt)))
7783
7784 (defun js2-must-match (token msg-id &optional pos len)
7785 "Match next token to token code TOKEN, or record a syntax error.
7786 MSG-ID is the error message to report if the match fails.
7787 Returns t on match, nil if no match."
7788 (if (js2-match-token token t)
7789 t
7790 (js2-report-error msg-id nil pos len)
7791 (js2-unget-token)
7792 nil))
7793
7794 (defun js2-must-match-name (msg-id)
7795 (if (js2-match-token js2-NAME t)
7796 t
7797 (if (eq (js2-current-token-type) js2-RESERVED)
7798 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7799 (js2-report-error msg-id)
7800 (js2-unget-token))
7801 nil))
7802
7803 (defsubst js2-inside-function ()
7804 (cl-plusp js2-nesting-of-function))
7805
7806 (defun js2-set-requires-activation ()
7807 (if (js2-function-node-p js2-current-script-or-fn)
7808 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7809
7810 (defun js2-check-activation-name (name _token)
7811 (when (js2-inside-function)
7812 ;; skip language-version 1.2 check from Rhino
7813 (if (or (string= "arguments" name)
7814 (and js2-compiler-activation-names ; only used in codegen
7815 (gethash name js2-compiler-activation-names)))
7816 (js2-set-requires-activation))))
7817
7818 (defun js2-set-is-generator ()
7819 (let ((fn-node js2-current-script-or-fn))
7820 (when (and (js2-function-node-p fn-node)
7821 (not (js2-function-node-generator-type fn-node)))
7822 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7823
7824 (defun js2-must-have-xml ()
7825 (unless js2-compiler-xml-available
7826 (js2-report-error "msg.XML.not.available")))
7827
7828 (defun js2-push-scope (scope)
7829 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7830 (cl-assert (js2-scope-p scope))
7831 (cl-assert (null (js2-scope-parent-scope scope)))
7832 (cl-assert (not (eq js2-current-scope scope)))
7833 (setf (js2-scope-parent-scope scope) js2-current-scope
7834 js2-current-scope scope))
7835
7836 (defsubst js2-pop-scope ()
7837 (setq js2-current-scope
7838 (js2-scope-parent-scope js2-current-scope)))
7839
7840 (defun js2-enter-loop (loop-node)
7841 (push loop-node js2-loop-set)
7842 (push loop-node js2-loop-and-switch-set)
7843 (js2-push-scope loop-node)
7844 ;; Tell the current labeled statement (if any) its statement,
7845 ;; and set the jump target of the first label to the loop.
7846 ;; These are used in `js2-parse-continue' to verify that the
7847 ;; continue target is an actual labeled loop. (And for codegen.)
7848 (when js2-labeled-stmt
7849 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7850 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7851 js2-labeled-stmt))) loop-node)))
7852
7853 (defun js2-exit-loop ()
7854 (pop js2-loop-set)
7855 (pop js2-loop-and-switch-set)
7856 (js2-pop-scope))
7857
7858 (defsubst js2-enter-switch (switch-node)
7859 (push switch-node js2-loop-and-switch-set))
7860
7861 (defsubst js2-exit-switch ()
7862 (pop js2-loop-and-switch-set))
7863
7864 (defun js2-parse (&optional buf cb)
7865 "Tell the js2 parser to parse a region of JavaScript.
7866
7867 BUF is a buffer or buffer name containing the code to parse.
7868 Call `narrow-to-region' first to parse only part of the buffer.
7869
7870 The returned AST root node is given some additional properties:
7871 `node-count' - total number of nodes in the AST
7872 `buffer' - BUF. The buffer it refers to may change or be killed,
7873 so the value is not necessarily reliable.
7874
7875 An optional callback CB can be specified to report parsing
7876 progress. If `(functionp CB)' returns t, it will be called with
7877 the current line number once before parsing begins, then again
7878 each time the lexer reaches a new line number.
7879
7880 CB can also be a list of the form `(symbol cb ...)' to specify
7881 multiple callbacks with different criteria. Each symbol is a
7882 criterion keyword, and the following element is the callback to
7883 call
7884
7885 :line - called whenever the line number changes
7886 :token - called for each new token consumed
7887
7888 The list of criteria could be extended to include entering or
7889 leaving a statement, an expression, or a function definition."
7890 (if (and cb (not (functionp cb)))
7891 (error "criteria callbacks not yet implemented"))
7892 (let ((inhibit-point-motion-hooks t)
7893 (js2-compiler-xml-available (>= js2-language-version 160))
7894 ;; This is a recursive-descent parser, so give it a big stack.
7895 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7896 (max-specpdl-size (max max-specpdl-size 3000))
7897 (case-fold-search nil)
7898 ast)
7899 (with-current-buffer (or buf (current-buffer))
7900 (setq js2-scanned-comments nil
7901 js2-parsed-errors nil
7902 js2-parsed-warnings nil
7903 js2-imenu-recorder nil
7904 js2-imenu-function-map nil
7905 js2-label-set nil)
7906 (js2-init-scanner)
7907 (setq ast (js2-do-parse))
7908 (unless js2-ts-hit-eof
7909 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7910 (setf (js2-ast-root-errors ast) js2-parsed-errors
7911 (js2-ast-root-warnings ast) js2-parsed-warnings)
7912 ;; if we didn't find any declarations, put a dummy in this list so we
7913 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7914 (unless js2-imenu-recorder
7915 (setq js2-imenu-recorder 'empty))
7916 (run-hooks 'js2-parse-finished-hook)
7917 ast)))
7918
7919 ;; Corresponds to Rhino's Parser.parse() method.
7920 (defun js2-do-parse ()
7921 "Parse current buffer starting from current point.
7922 Scanner should be initialized."
7923 (let ((pos js2-ts-cursor)
7924 (end js2-ts-cursor) ; in case file is empty
7925 root n tt)
7926 ;; initialize buffer-local parsing vars
7927 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7928 js2-current-script-or-fn root
7929 js2-current-scope root
7930 js2-nesting-of-function 0
7931 js2-labeled-stmt nil
7932 js2-recorded-identifiers nil) ; for js2-highlight
7933 (while (/= (setq tt (js2-get-token)) js2-EOF)
7934 (if (= tt js2-FUNCTION)
7935 (progn
7936 (setq n (if js2-called-by-compile-function
7937 (js2-parse-function-expr)
7938 (js2-parse-function-stmt))))
7939 ;; not a function - parse a statement
7940 (js2-unget-token)
7941 (setq n (js2-parse-statement)))
7942 ;; add function or statement to script
7943 (setq end (js2-node-end n))
7944 (js2-block-node-push root n))
7945 ;; add comments to root in lexical order
7946 (when js2-scanned-comments
7947 ;; if we find a comment beyond end of normal kids, use its end
7948 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7949 (dolist (comment js2-scanned-comments)
7950 (push comment (js2-ast-root-comments root))
7951 (js2-node-add-children root comment)))
7952 (setf (js2-node-len root) (- end pos))
7953 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7954 ;; Give extensions a chance to muck with things before highlighting starts.
7955 (let ((js2-additional-externs js2-additional-externs))
7956 (save-excursion
7957 (run-hooks 'js2-post-parse-callbacks))
7958 (js2-highlight-undeclared-vars))
7959 root))
7960
7961 (defun js2-parse-function-closure-body (fn-node)
7962 "Parse a JavaScript 1.8 function closure body."
7963 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7964 (if js2-ts-hit-eof
7965 (js2-report-error "msg.no.brace.body" nil
7966 (js2-node-pos fn-node)
7967 (- js2-ts-cursor (js2-node-pos fn-node)))
7968 (js2-node-add-children fn-node
7969 (setf (js2-function-node-body fn-node)
7970 (js2-parse-expr t))))))
7971
7972 (defun js2-parse-function-body (fn-node)
7973 (js2-must-match js2-LC "msg.no.brace.body"
7974 (js2-node-pos fn-node)
7975 (- js2-ts-cursor (js2-node-pos fn-node)))
7976 (let ((pos (js2-current-token-beg)) ; LC position
7977 (pn (make-js2-block-node)) ; starts at LC position
7978 tt
7979 end)
7980 (cl-incf js2-nesting-of-function)
7981 (unwind-protect
7982 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7983 (= tt js2-EOF)
7984 (= tt js2-RC)))
7985 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7986 (js2-parse-statement)
7987 (js2-get-token)
7988 (js2-parse-function-stmt))))
7989 (cl-decf js2-nesting-of-function))
7990 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7991 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7992 (setq end (js2-current-token-end)))
7993 (setf (js2-node-pos pn) pos
7994 (js2-node-len pn) (- end pos))
7995 (setf (js2-function-node-body fn-node) pn)
7996 (js2-node-add-children fn-node pn)
7997 pn))
7998
7999 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8000 "Declare and fontify destructuring parameters inside NODE.
8001 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
8002 (cond
8003 ((js2-name-node-p node)
8004 (let (leftpos)
8005 (js2-define-symbol decl-type (js2-name-node-name node)
8006 node ignore-not-in-block)
8007 (when face
8008 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8009 (+ leftpos (js2-node-len node))
8010 face 'record))))
8011 ((js2-object-node-p node)
8012 (dolist (elem (js2-object-node-elems node))
8013 (js2-define-destruct-symbols
8014 ;; In abbreviated destructuring {a, b}, right == left.
8015 (js2-object-prop-node-right elem)
8016 decl-type face ignore-not-in-block)))
8017 ((js2-array-node-p node)
8018 (dolist (elem (js2-array-node-elems node))
8019 (when elem
8020 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
8021 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8022 (js2-node-len node)))))
8023
8024 (defun js2-parse-function-params (function-type fn-node pos)
8025 (if (js2-match-token js2-RP)
8026 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8027 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8028 (eq (js2-current-token-type) js2-NAME)))
8029 params param default-found rest-param-at)
8030 (when paren-free-arrow
8031 (js2-unget-token))
8032 (cl-loop for tt = (js2-peek-token)
8033 do
8034 (cond
8035 ;; destructuring param
8036 ((and (not paren-free-arrow)
8037 (or (= tt js2-LB) (= tt js2-LC)))
8038 (js2-get-token)
8039 (when default-found
8040 (js2-report-error "msg.no.default.after.default.param"))
8041 (setq param (js2-parse-destruct-primary-expr))
8042 (js2-define-destruct-symbols param
8043 js2-LP
8044 'js2-function-param)
8045 (push param params))
8046 ;; variable name
8047 (t
8048 (when (and (>= js2-language-version 200)
8049 (not paren-free-arrow)
8050 (js2-match-token js2-TRIPLEDOT)
8051 (not rest-param-at))
8052 ;; to report errors if there are more parameters
8053 (setq rest-param-at (length params)))
8054 (js2-must-match-name "msg.no.parm")
8055 (js2-record-face 'js2-function-param)
8056 (setq param (js2-create-name-node))
8057 (js2-define-symbol js2-LP (js2-current-token-string) param)
8058 ;; default parameter value
8059 (when (or (and default-found
8060 (not rest-param-at)
8061 (js2-must-match js2-ASSIGN
8062 "msg.no.default.after.default.param"
8063 (js2-node-pos param)
8064 (js2-node-len param)))
8065 (and (>= js2-language-version 200)
8066 (js2-match-token js2-ASSIGN)))
8067 (cl-assert (not paren-free-arrow))
8068 (let* ((pos (js2-node-pos param))
8069 (tt (js2-current-token-type))
8070 (op-pos (- (js2-current-token-beg) pos))
8071 (left param)
8072 (right (js2-parse-assign-expr))
8073 (len (- (js2-node-end right) pos)))
8074 (setq param (make-js2-assign-node
8075 :type tt :pos pos :len len :op-pos op-pos
8076 :left left :right right)
8077 default-found t)
8078 (js2-node-add-children param left right)))
8079 (push param params)))
8080 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8081 (js2-report-error "msg.param.after.rest" nil
8082 (js2-node-pos param) (js2-node-len param)))
8083 while
8084 (js2-match-token js2-COMMA))
8085 (when (and (not paren-free-arrow)
8086 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8087 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8088 (when rest-param-at
8089 (setf (js2-function-node-rest-p fn-node) t))
8090 (dolist (p params)
8091 (js2-node-add-children fn-node p)
8092 (push p (js2-function-node-params fn-node))))))
8093
8094 (defun js2-check-inconsistent-return-warning (fn-node name)
8095 "Possibly show inconsistent-return warning.
8096 Last token scanned is the close-curly for the function body."
8097 (when (and js2-mode-show-strict-warnings
8098 js2-strict-inconsistent-return-warning
8099 (not (js2-has-consistent-return-usage
8100 (js2-function-node-body fn-node))))
8101 ;; Have it extend from close-curly to bol or beginning of block.
8102 (let ((pos (save-excursion
8103 (goto-char (js2-current-token-end))
8104 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8105 (point-at-bol))))
8106 (end (js2-current-token-end)))
8107 (if (cl-plusp (js2-name-node-length name))
8108 (js2-add-strict-warning "msg.no.return.value"
8109 (js2-name-node-name name) pos end)
8110 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8111
8112 (defun js2-parse-function-stmt ()
8113 (let ((pos (js2-current-token-beg))
8114 (star-p (js2-match-token js2-MUL)))
8115 (js2-must-match-name "msg.unnamed.function.stmt")
8116 (let ((name (js2-create-name-node t))
8117 pn member-expr)
8118 (cond
8119 ((js2-match-token js2-LP)
8120 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8121 (js2-allow-member-expr-as-function-name
8122 (setq member-expr (js2-parse-member-expr-tail nil name))
8123 (js2-parse-highlight-member-expr-fn-name member-expr)
8124 (js2-must-match js2-LP "msg.no.paren.parms")
8125 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8126 (js2-function-node-member-expr pn) member-expr)
8127 pn)
8128 (t
8129 (js2-report-error "msg.no.paren.parms")
8130 (make-js2-error-node))))))
8131
8132 (defun js2-parse-function-expr ()
8133 (let ((pos (js2-current-token-beg))
8134 (star-p (js2-match-token js2-MUL))
8135 name)
8136 (when (js2-match-token js2-NAME)
8137 (setq name (js2-create-name-node t)))
8138 (js2-must-match js2-LP "msg.no.paren.parms")
8139 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8140
8141 (defun js2-parse-function (function-type pos star-p &optional name)
8142 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8143 beginning of the first token (function keyword, unless it's an
8144 arrow function), NAME is js2-name-node."
8145 (let (fn-node lp)
8146 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8147 (setq lp (js2-current-token-beg)))
8148 (setf fn-node (make-js2-function-node :pos pos
8149 :name name
8150 :form function-type
8151 :lp (if lp (- lp pos))
8152 :generator-type (and star-p 'STAR)))
8153 (when name
8154 (js2-set-face (js2-node-pos name) (js2-node-end name)
8155 'font-lock-function-name-face 'record)
8156 (when (and (eq function-type 'FUNCTION_STATEMENT)
8157 (cl-plusp (js2-name-node-length name)))
8158 ;; Function statements define a symbol in the enclosing scope
8159 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
8160 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8161 ;; 1. Nested functions are not affected by the dynamic scope flag
8162 ;; as dynamic scope is already a parent of their scope.
8163 ;; 2. Functions defined under the with statement also immune to
8164 ;; this setup, in which case dynamic scope is ignored in favor
8165 ;; of the with object.
8166 (setf (js2-function-node-ignore-dynamic fn-node) t))
8167 ;; dynamically bind all the per-function variables
8168 (let ((js2-current-script-or-fn fn-node)
8169 (js2-current-scope fn-node)
8170 (js2-nesting-of-with 0)
8171 (js2-end-flags 0)
8172 js2-label-set
8173 js2-loop-set
8174 js2-loop-and-switch-set)
8175 (js2-parse-function-params function-type fn-node pos)
8176 (when (eq function-type 'FUNCTION_ARROW)
8177 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8178 (if (and (>= js2-language-version 180)
8179 (/= (js2-peek-token) js2-LC))
8180 (js2-parse-function-closure-body fn-node)
8181 (js2-parse-function-body fn-node))
8182 (js2-check-inconsistent-return-warning fn-node name)
8183
8184 (when name
8185 (js2-node-add-children fn-node name)
8186 ;; Function expressions define a name only in the body of the
8187 ;; function, and only if not hidden by a parameter name
8188 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8189 (null (js2-scope-get-symbol js2-current-scope
8190 (js2-name-node-name name))))
8191 (js2-define-symbol js2-FUNCTION
8192 (js2-name-node-name name)
8193 fn-node))
8194 (when (eq function-type 'FUNCTION_STATEMENT)
8195 (js2-record-imenu-functions fn-node))))
8196
8197 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8198 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8199 ;; We wait until after parsing the function to set its parent scope,
8200 ;; since `js2-define-symbol' needs the defining-scope check to stop
8201 ;; at the function boundary when checking for redeclarations.
8202 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8203 fn-node))
8204
8205 (defun js2-parse-statements (&optional parent)
8206 "Parse a statement list. Last token consumed must be js2-LC.
8207
8208 PARENT can be a `js2-block-node', in which case the statements are
8209 appended to PARENT. Otherwise a new `js2-block-node' is created
8210 and returned.
8211
8212 This function does not match the closing js2-RC: the caller
8213 matches the RC so it can provide a suitable error message if not
8214 matched. This means it's up to the caller to set the length of
8215 the node to include the closing RC. The node start pos is set to
8216 the absolute buffer start position, and the caller should fix it
8217 up to be relative to the parent node. All children of this block
8218 node are given relative start positions and correct lengths."
8219 (let ((pn (or parent (make-js2-block-node)))
8220 tt)
8221 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8222 (/= tt js2-RC))
8223 (js2-block-node-push pn (js2-parse-statement)))
8224 pn))
8225
8226 (defun js2-parse-statement ()
8227 (let (pn beg end)
8228 ;; coarse-grained user-interrupt check - needs work
8229 (and js2-parse-interruptable-p
8230 (zerop (% (cl-incf js2-parse-stmt-count)
8231 js2-statements-per-pause))
8232 (input-pending-p)
8233 (throw 'interrupted t))
8234 (setq pn (js2-statement-helper))
8235 ;; no-side-effects warning check
8236 (unless (js2-node-has-side-effects pn)
8237 (setq end (js2-node-end pn))
8238 (save-excursion
8239 (goto-char end)
8240 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8241 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8242 pn))
8243
8244 ;; These correspond to the switch cases in Parser.statementHelper
8245 (defconst js2-parsers
8246 (let ((parsers (make-vector js2-num-tokens
8247 #'js2-parse-expr-stmt)))
8248 (aset parsers js2-BREAK #'js2-parse-break)
8249 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8250 (aset parsers js2-CONST #'js2-parse-const-var)
8251 (aset parsers js2-CONTINUE #'js2-parse-continue)
8252 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8253 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8254 (aset parsers js2-DO #'js2-parse-do)
8255 (aset parsers js2-EXPORT #'js2-parse-export)
8256 (aset parsers js2-FOR #'js2-parse-for)
8257 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8258 (aset parsers js2-IF #'js2-parse-if)
8259 (aset parsers js2-IMPORT #'js2-parse-import)
8260 (aset parsers js2-LC #'js2-parse-block)
8261 (aset parsers js2-LET #'js2-parse-let-stmt)
8262 (aset parsers js2-NAME #'js2-parse-name-or-label)
8263 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8264 (aset parsers js2-SEMI #'js2-parse-semi)
8265 (aset parsers js2-SWITCH #'js2-parse-switch)
8266 (aset parsers js2-THROW #'js2-parse-throw)
8267 (aset parsers js2-TRY #'js2-parse-try)
8268 (aset parsers js2-VAR #'js2-parse-const-var)
8269 (aset parsers js2-WHILE #'js2-parse-while)
8270 (aset parsers js2-WITH #'js2-parse-with)
8271 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8272 parsers)
8273 "A vector mapping token types to parser functions.")
8274
8275 (defun js2-parse-warn-missing-semi (beg end)
8276 (and js2-mode-show-strict-warnings
8277 js2-strict-missing-semi-warning
8278 (js2-add-strict-warning
8279 "msg.missing.semi" nil
8280 ;; back up to beginning of statement or line
8281 (max beg (save-excursion
8282 (goto-char end)
8283 (point-at-bol)))
8284 end)))
8285
8286 (defconst js2-no-semi-insertion
8287 (list js2-IF
8288 js2-SWITCH
8289 js2-WHILE
8290 js2-DO
8291 js2-FOR
8292 js2-TRY
8293 js2-WITH
8294 js2-LC
8295 js2-ERROR
8296 js2-SEMI
8297 js2-CLASS
8298 js2-FUNCTION
8299 js2-EXPORT)
8300 "List of tokens that don't do automatic semicolon insertion.")
8301
8302 (defconst js2-autoinsert-semi-and-warn
8303 (list js2-ERROR js2-EOF js2-RC))
8304
8305 (defun js2-statement-helper ()
8306 (let* ((tt (js2-get-token))
8307 (first-tt tt)
8308 (parser (if (= tt js2-ERROR)
8309 #'js2-parse-semi
8310 (aref js2-parsers tt)))
8311 pn)
8312 ;; If the statement is set, then it's been told its label by now.
8313 (and js2-labeled-stmt
8314 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8315 (setq js2-labeled-stmt nil))
8316 (setq pn (funcall parser))
8317 ;; Don't do auto semi insertion for certain statement types.
8318 (unless (or (memq first-tt js2-no-semi-insertion)
8319 (js2-labeled-stmt-node-p pn))
8320 (js2-auto-insert-semicolon pn))
8321 pn))
8322
8323 (defun js2-auto-insert-semicolon (pn)
8324 (let* ((tt (js2-get-token))
8325 (pos (js2-node-pos pn)))
8326 (cond
8327 ((= tt js2-SEMI)
8328 ;; extend the node bounds to include the semicolon.
8329 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8330 ((memq tt js2-autoinsert-semi-and-warn)
8331 (js2-unget-token) ; Not ';', do not consume.
8332 ;; Autoinsert ;
8333 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8334 (t
8335 (if (not (js2-token-follows-eol-p (js2-current-token)))
8336 ;; Report error if no EOL or autoinsert ';' otherwise
8337 (js2-report-error "msg.no.semi.stmt")
8338 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8339 (js2-unget-token) ; Not ';', do not consume.
8340 ))))
8341
8342 (defun js2-parse-condition ()
8343 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8344 The parens are discarded and the expression node is returned.
8345 The `pos' field of the return value is set to an absolute position
8346 that must be fixed up by the caller.
8347 Return value is a list (EXPR LP RP), with absolute paren positions."
8348 (let (pn lp rp)
8349 (if (js2-must-match js2-LP "msg.no.paren.cond")
8350 (setq lp (js2-current-token-beg)))
8351 (setq pn (js2-parse-expr))
8352 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8353 (setq rp (js2-current-token-beg)))
8354 ;; Report strict warning on code like "if (a = 7) ..."
8355 (if (and js2-strict-cond-assign-warning
8356 (js2-assign-node-p pn))
8357 (js2-add-strict-warning "msg.equal.as.assign" nil
8358 (js2-node-pos pn)
8359 (+ (js2-node-pos pn)
8360 (js2-node-len pn))))
8361 (list pn lp rp)))
8362
8363 (defun js2-parse-if ()
8364 "Parser for if-statement. Last matched token must be js2-IF."
8365 (let ((pos (js2-current-token-beg))
8366 cond if-true if-false else-pos end pn)
8367 (setq cond (js2-parse-condition)
8368 if-true (js2-parse-statement)
8369 if-false (if (js2-match-token js2-ELSE)
8370 (progn
8371 (setq else-pos (- (js2-current-token-beg) pos))
8372 (js2-parse-statement)))
8373 end (js2-node-end (or if-false if-true))
8374 pn (make-js2-if-node :pos pos
8375 :len (- end pos)
8376 :condition (car cond)
8377 :then-part if-true
8378 :else-part if-false
8379 :else-pos else-pos
8380 :lp (js2-relpos (cl-second cond) pos)
8381 :rp (js2-relpos (cl-third cond) pos)))
8382 (js2-node-add-children pn (car cond) if-true if-false)
8383 pn))
8384
8385 (defun js2-parse-import ()
8386 "Parse import statement. The current token must be js2-IMPORT."
8387 (unless (js2-ast-root-p js2-current-scope)
8388 (js2-report-error "msg.mod.import.decl.at.top.level"))
8389 (let ((beg (js2-current-token-beg)))
8390 (cond ((js2-match-token js2-STRING)
8391 (make-js2-import-node
8392 :pos beg
8393 :len (- (js2-current-token-end) beg)
8394 :module-id (js2-current-token-string)))
8395 (t
8396 (let* ((import-clause (js2-parse-import-clause))
8397 (from-clause (and import-clause (js2-parse-from-clause)))
8398 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8399 (node (make-js2-import-node
8400 :pos beg
8401 :len (- (js2-current-token-end) beg)
8402 :import import-clause
8403 :from from-clause
8404 :module-id module-id)))
8405 (when import-clause
8406 (js2-node-add-children node import-clause))
8407 (when from-clause
8408 (js2-node-add-children node from-clause))
8409 node)))))
8410
8411 (defun js2-parse-import-clause ()
8412 "Parse the bindings in an import statement.
8413 This can take many forms:
8414
8415 ImportedDefaultBinding -> 'foo'
8416 NameSpaceImport -> '* as lib'
8417 NamedImports -> '{foo as bar, bang}'
8418 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8419 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8420
8421 Try to match namespace imports and named imports first because nothing can
8422 come after them. If it is an imported default binding, then it could have named
8423 imports or a namespace import that follows it.
8424 "
8425 (let* ((beg (js2-current-token-beg))
8426 (clause (make-js2-import-clause-node
8427 :pos beg))
8428 (children (list)))
8429 (cond
8430 ((js2-match-token js2-MUL)
8431 (let ((ns-import (js2-parse-namespace-import)))
8432 (when ns-import
8433 (let ((name-node (js2-namespace-import-node-name ns-import)))
8434 (js2-define-symbol
8435 js2-LET (js2-name-node-name name-node) name-node t)))
8436 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8437 (push ns-import children)))
8438 ((js2-match-token js2-LC)
8439 (let ((imports (js2-parse-export-bindings t)))
8440 (setf (js2-import-clause-node-named-imports clause) imports)
8441 (dolist (import imports)
8442 (push import children)
8443 (let ((name-node (js2-export-binding-node-local-name import)))
8444 (when name-node
8445 (js2-define-symbol
8446 js2-LET (js2-name-node-name name-node) name-node t))))))
8447 ((= (js2-peek-token) js2-NAME)
8448 (let ((binding (js2-maybe-parse-export-binding)))
8449 (let ((node-name (js2-export-binding-node-local-name binding)))
8450 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8451 (setf (js2-import-clause-node-default-binding clause) binding)
8452 (push binding children))
8453 (when (js2-match-token js2-COMMA)
8454 (cond
8455 ((js2-match-token js2-MUL)
8456 (let ((ns-import (js2-parse-namespace-import)))
8457 (let ((name-node (js2-namespace-import-node-name ns-import)))
8458 (js2-define-symbol
8459 js2-LET (js2-name-node-name name-node) name-node t))
8460 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8461 (push ns-import children)))
8462 ((js2-match-token js2-LC)
8463 (let ((imports (js2-parse-export-bindings t)))
8464 (setf (js2-import-clause-node-named-imports clause) imports)
8465 (dolist (import imports)
8466 (push import children)
8467 (let ((name-node (js2-export-binding-node-local-name import)))
8468 (when name-node
8469 (js2-define-symbol
8470 js2-LET (js2-name-node-name name-node) name-node t))))))
8471 (t (js2-report-error "msg.syntax")))))
8472 (t (js2-report-error "msg.mod.declaration.after.import")))
8473 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8474 (apply #'js2-node-add-children clause children)
8475 clause))
8476
8477 (defun js2-parse-namespace-import ()
8478 "Parse a namespace import expression such as '* as bar'.
8479 The current token must be js2-MUL."
8480 (let ((beg (js2-current-token-beg)))
8481 (when (js2-must-match js2-NAME "msg.syntax")
8482 (if (equal "as" (js2-current-token-string))
8483 (when (js2-must-match-prop-name "msg.syntax")
8484 (let ((node (make-js2-namespace-import-node
8485 :pos beg
8486 :len (- (js2-current-token-end) beg)
8487 :name (make-js2-name-node
8488 :pos (js2-current-token-beg)
8489 :len (js2-current-token-end)
8490 :name (js2-current-token-string)))))
8491 (js2-node-add-children node (js2-namespace-import-node-name node))
8492 node))
8493 (js2-unget-token)
8494 (js2-report-error "msg.syntax")))))
8495
8496
8497 (defun js2-parse-from-clause ()
8498 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8499 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8500 (let ((beg (js2-current-token-beg)))
8501 (if (equal "from" (js2-current-token-string))
8502 (cond
8503 ((js2-match-token js2-STRING)
8504 (make-js2-from-clause-node
8505 :pos beg
8506 :len (- (js2-current-token-end) beg)
8507 :module-id (js2-current-token-string)
8508 :metadata-p nil))
8509 ((js2-match-token js2-THIS)
8510 (when (js2-must-match-name "msg.mod.spec.after.from")
8511 (if (equal "module" (js2-current-token-string))
8512 (make-js2-from-clause-node
8513 :pos beg
8514 :len (- (js2-current-token-end) beg)
8515 :module-id "this"
8516 :metadata-p t)
8517 (js2-unget-token)
8518 (js2-unget-token)
8519 (js2-report-error "msg.mod.spec.after.from")
8520 nil)))
8521 (t (js2-report-error "msg.mod.spec.after.from") nil))
8522 (js2-unget-token)
8523 (js2-report-error "msg.mod.from.after.import.spec.set")
8524 nil))))
8525
8526 (defun js2-parse-export-bindings (&optional import-p)
8527 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8528 {foo as bar, baz as bang}. The current token must be
8529 js2-LC. Return a lisp list of js2-export-binding-node"
8530 (let ((bindings (list)))
8531 (while
8532 (let ((binding (js2-maybe-parse-export-binding)))
8533 (when binding
8534 (push binding bindings))
8535 (js2-match-token js2-COMMA)))
8536 (when (js2-must-match js2-RC (if import-p
8537 "msg.mod.rc.after.import.spec.list"
8538 "msg.mod.rc.after.export.spec.list"))
8539 (reverse bindings))))
8540
8541 (defun js2-maybe-parse-export-binding ()
8542 "Attempt to parse a binding expression found inside an import/export statement.
8543 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8544 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8545 js2-export-binding-node and consume all the tokens. If it does not match, it
8546 consumes no tokens."
8547 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8548 (beg (js2-current-token-beg))
8549 (extern-name-len (js2-current-token-len))
8550 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8551 (aref js2-kwd-tokens (js2-current-token-type)))))
8552 (if extern-name
8553 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8554 (if (and as (equal "as" (js2-current-token-string)))
8555 (let ((name
8556 (or
8557 (and (js2-match-token js2-DEFAULT) "default")
8558 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8559 (if name
8560 (let ((node (make-js2-export-binding-node
8561 :pos beg
8562 :len (- (js2-current-token-end) beg)
8563 :local-name (make-js2-name-node
8564 :name name
8565 :pos (js2-current-token-beg)
8566 :len (js2-current-token-len))
8567 :extern-name (make-js2-name-node
8568 :name extern-name
8569 :pos beg
8570 :len extern-name-len))))
8571 (js2-node-add-children
8572 node
8573 (js2-export-binding-node-local-name node)
8574 (js2-export-binding-node-extern-name node))
8575 node)
8576 (js2-unget-token)
8577 nil))
8578 (when as (js2-unget-token))
8579 (let* ((name-node (make-js2-name-node
8580 :name (js2-current-token-string)
8581 :pos (js2-current-token-beg)
8582 :len (js2-current-token-len)))
8583 (node (make-js2-export-binding-node
8584 :pos (js2-current-token-beg)
8585 :len (js2-current-token-len)
8586 :local-name name-node
8587 :extern-name name-node)))
8588 (when is-reserved-name
8589 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8590 (js2-node-add-children node name-node)
8591 node)))
8592 nil)))
8593
8594 (defun js2-parse-switch ()
8595 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8596 (let ((pos (js2-current-token-beg))
8597 tt pn discriminant has-default case-expr case-node
8598 case-pos cases stmt lp)
8599 (if (js2-must-match js2-LP "msg.no.paren.switch")
8600 (setq lp (js2-current-token-beg)))
8601 (setq discriminant (js2-parse-expr)
8602 pn (make-js2-switch-node :discriminant discriminant
8603 :pos pos
8604 :lp (js2-relpos lp pos)))
8605 (js2-node-add-children pn discriminant)
8606 (js2-enter-switch pn)
8607 (unwind-protect
8608 (progn
8609 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8610 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8611 (js2-must-match js2-LC "msg.no.brace.switch")
8612 (catch 'break
8613 (while t
8614 (setq tt (js2-next-token)
8615 case-pos (js2-current-token-beg))
8616 (cond
8617 ((= tt js2-RC)
8618 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8619 (throw 'break nil)) ; done
8620 ((= tt js2-CASE)
8621 (setq case-expr (js2-parse-expr))
8622 (js2-must-match js2-COLON "msg.no.colon.case"))
8623 ((= tt js2-DEFAULT)
8624 (if has-default
8625 (js2-report-error "msg.double.switch.default"))
8626 (setq has-default t
8627 case-expr nil)
8628 (js2-must-match js2-COLON "msg.no.colon.case"))
8629 (t
8630 (js2-report-error "msg.bad.switch")
8631 (throw 'break nil)))
8632 (setq case-node (make-js2-case-node :pos case-pos
8633 :len (- (js2-current-token-end) case-pos)
8634 :expr case-expr))
8635 (js2-node-add-children case-node case-expr)
8636 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8637 (/= tt js2-CASE)
8638 (/= tt js2-DEFAULT)
8639 (/= tt js2-EOF))
8640 (setf stmt (js2-parse-statement)
8641 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8642 (js2-block-node-push case-node stmt))
8643 (push case-node cases)))
8644 ;; add cases last, as pushing reverses the order to be correct
8645 (dolist (kid cases)
8646 (js2-node-add-children pn kid)
8647 (push kid (js2-switch-node-cases pn)))
8648 pn) ; return value
8649 (js2-exit-switch))))
8650
8651 (defun js2-parse-while ()
8652 "Parser for while-statement. Last matched token must be js2-WHILE."
8653 (let ((pos (js2-current-token-beg))
8654 (pn (make-js2-while-node))
8655 cond body)
8656 (js2-enter-loop pn)
8657 (unwind-protect
8658 (progn
8659 (setf cond (js2-parse-condition)
8660 (js2-while-node-condition pn) (car cond)
8661 body (js2-parse-statement)
8662 (js2-while-node-body pn) body
8663 (js2-node-len pn) (- (js2-node-end body) pos)
8664 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8665 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8666 (js2-node-add-children pn body (car cond)))
8667 (js2-exit-loop))
8668 pn))
8669
8670 (defun js2-parse-do ()
8671 "Parser for do-statement. Last matched token must be js2-DO."
8672 (let ((pos (js2-current-token-beg))
8673 (pn (make-js2-do-node))
8674 cond body end)
8675 (js2-enter-loop pn)
8676 (unwind-protect
8677 (progn
8678 (setq body (js2-parse-statement))
8679 (js2-must-match js2-WHILE "msg.no.while.do")
8680 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8681 cond (js2-parse-condition)
8682 (js2-do-node-condition pn) (car cond)
8683 (js2-do-node-body pn) body
8684 end js2-ts-cursor
8685 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8686 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8687 (js2-node-add-children pn (car cond) body))
8688 (js2-exit-loop))
8689 ;; Always auto-insert semicolon to follow SpiderMonkey:
8690 ;; It is required by ECMAScript but is ignored by the rest of
8691 ;; world; see bug 238945
8692 (if (js2-match-token js2-SEMI)
8693 (setq end js2-ts-cursor))
8694 (setf (js2-node-len pn) (- end pos))
8695 pn))
8696
8697 (defun js2-parse-export ()
8698 "Parse an export statement.
8699 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8700 expressions should only be either hoistable expressions (function or generator)
8701 or assignment expressions, but there is no checking to enforce that and so it
8702 will parse without error a small subset of
8703 invalid export statements."
8704 (unless (js2-ast-root-p js2-current-scope)
8705 (js2-report-error "msg.mod.export.decl.at.top.level"))
8706 (let ((beg (js2-current-token-beg))
8707 (children (list))
8708 exports-list from-clause declaration default)
8709 (cond
8710 ((js2-match-token js2-MUL)
8711 (setq from-clause (js2-parse-from-clause))
8712 (when from-clause
8713 (push from-clause children)))
8714 ((js2-match-token js2-LC)
8715 (setq exports-list (js2-parse-export-bindings))
8716 (when exports-list
8717 (dolist (export exports-list)
8718 (push export children)))
8719 (when (js2-match-token js2-NAME)
8720 (if (equal "from" (js2-current-token-string))
8721 (progn
8722 (js2-unget-token)
8723 (setq from-clause (js2-parse-from-clause)))
8724 (js2-unget-token))))
8725 ((js2-match-token js2-DEFAULT)
8726 (setq default (js2-parse-expr)))
8727 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8728 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8729 (t
8730 (setq declaration (js2-parse-expr))))
8731 (when from-clause
8732 (push from-clause children))
8733 (when declaration
8734 (push declaration children)
8735 (when (not (js2-function-node-p declaration))
8736 (js2-auto-insert-semicolon declaration)))
8737 (when default
8738 (push default children)
8739 (when (not (js2-function-node-p default))
8740 (js2-auto-insert-semicolon default)))
8741 (let ((node (make-js2-export-node
8742 :pos beg
8743 :len (- (js2-current-token-end) beg)
8744 :exports-list exports-list
8745 :from-clause from-clause
8746 :declaration declaration
8747 :default default)))
8748 (apply #'js2-node-add-children node children)
8749 node)))
8750
8751 (defun js2-parse-for ()
8752 "Parse a for, for-in or for each-in statement.
8753 Last matched token must be js2-FOR."
8754 (let ((for-pos (js2-current-token-beg))
8755 (tmp-scope (make-js2-scope))
8756 pn is-for-each is-for-in-or-of is-for-of
8757 in-pos each-pos tmp-pos
8758 init ; Node init is also foo in 'foo in object'.
8759 cond ; Node cond is also object in 'foo in object'.
8760 incr ; 3rd section of for-loop initializer.
8761 body tt lp rp)
8762 ;; See if this is a for each () instead of just a for ()
8763 (when (js2-match-token js2-NAME)
8764 (if (string= "each" (js2-current-token-string))
8765 (progn
8766 (setq is-for-each t
8767 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8768 (js2-record-face 'font-lock-keyword-face))
8769 (js2-report-error "msg.no.paren.for")))
8770 (if (js2-must-match js2-LP "msg.no.paren.for")
8771 (setq lp (- (js2-current-token-beg) for-pos)))
8772 (setq tt (js2-get-token))
8773 ;; Capture identifiers inside parens. We can't create the node
8774 ;; (and use it as the current scope) until we know its type.
8775 (js2-push-scope tmp-scope)
8776 (unwind-protect
8777 (progn
8778 ;; parse init clause
8779 (let ((js2-in-for-init t)) ; set as dynamic variable
8780 (cond
8781 ((= tt js2-SEMI)
8782 (js2-unget-token)
8783 (setq init (make-js2-empty-expr-node)))
8784 ((or (= tt js2-VAR) (= tt js2-LET))
8785 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8786 (t
8787 (js2-unget-token)
8788 (setq init (js2-parse-expr)))))
8789 (if (or (js2-match-token js2-IN)
8790 (and (>= js2-language-version 200)
8791 (js2-match-contextual-kwd "of")
8792 (setq is-for-of t)))
8793 (setq is-for-in-or-of t
8794 in-pos (- (js2-current-token-beg) for-pos)
8795 ;; scope of iteration target object is not the scope we've created above.
8796 ;; stash current scope temporary.
8797 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8798 (js2-parse-expr))) ; object over which we're iterating
8799 ;; else ordinary for loop - parse cond and incr
8800 (js2-must-match js2-SEMI "msg.no.semi.for")
8801 (setq cond (if (= (js2-peek-token) js2-SEMI)
8802 (make-js2-empty-expr-node) ; no loop condition
8803 (js2-parse-expr)))
8804 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8805 (setq tmp-pos (js2-current-token-end)
8806 incr (if (= (js2-peek-token) js2-RP)
8807 (make-js2-empty-expr-node :pos tmp-pos)
8808 (js2-parse-expr)))))
8809 (js2-pop-scope))
8810 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8811 (setq rp (- (js2-current-token-beg) for-pos)))
8812 (if (not is-for-in-or-of)
8813 (setq pn (make-js2-for-node :init init
8814 :condition cond
8815 :update incr
8816 :lp lp
8817 :rp rp))
8818 ;; cond could be null if 'in obj' got eaten by the init node.
8819 (if (js2-infix-node-p init)
8820 ;; it was (foo in bar) instead of (var foo in bar)
8821 (setq cond (js2-infix-node-right init)
8822 init (js2-infix-node-left init))
8823 (if (and (js2-var-decl-node-p init)
8824 (> (length (js2-var-decl-node-kids init)) 1))
8825 (js2-report-error "msg.mult.index")))
8826 (setq pn (make-js2-for-in-node :iterator init
8827 :object cond
8828 :in-pos in-pos
8829 :foreach-p is-for-each
8830 :each-pos each-pos
8831 :forof-p is-for-of
8832 :lp lp
8833 :rp rp)))
8834 ;; Transplant the declarations.
8835 (setf (js2-scope-symbol-table pn)
8836 (js2-scope-symbol-table tmp-scope))
8837 (unwind-protect
8838 (progn
8839 (js2-enter-loop pn)
8840 ;; We have to parse the body -after- creating the loop node,
8841 ;; so that the loop node appears in the js2-loop-set, allowing
8842 ;; break/continue statements to find the enclosing loop.
8843 (setf body (js2-parse-statement)
8844 (js2-loop-node-body pn) body
8845 (js2-node-pos pn) for-pos
8846 (js2-node-len pn) (- (js2-node-end body) for-pos))
8847 (js2-node-add-children pn init cond incr body))
8848 ;; finally
8849 (js2-exit-loop))
8850 pn))
8851
8852 (defun js2-parse-try ()
8853 "Parse a try statement. Last matched token must be js2-TRY."
8854 (let ((try-pos (js2-current-token-beg))
8855 try-end
8856 try-block
8857 catch-blocks
8858 finally-block
8859 saw-default-catch
8860 peek)
8861 (if (/= (js2-peek-token) js2-LC)
8862 (js2-report-error "msg.no.brace.try"))
8863 (setq try-block (js2-parse-statement)
8864 try-end (js2-node-end try-block)
8865 peek (js2-peek-token))
8866 (cond
8867 ((= peek js2-CATCH)
8868 (while (js2-match-token js2-CATCH)
8869 (let* ((catch-pos (js2-current-token-beg))
8870 (catch-node (make-js2-catch-node :pos catch-pos))
8871 param
8872 guard-kwd
8873 catch-cond
8874 lp rp)
8875 (if saw-default-catch
8876 (js2-report-error "msg.catch.unreachable"))
8877 (if (js2-must-match js2-LP "msg.no.paren.catch")
8878 (setq lp (- (js2-current-token-beg) catch-pos)))
8879 (js2-push-scope catch-node)
8880 (let ((tt (js2-peek-token)))
8881 (cond
8882 ;; Destructuring pattern:
8883 ;; catch ({ message, file }) { ... }
8884 ((or (= tt js2-LB) (= tt js2-LC))
8885 (js2-get-token)
8886 (setq param (js2-parse-destruct-primary-expr))
8887 (js2-define-destruct-symbols param js2-LET nil))
8888 ;; Simple name.
8889 (t
8890 (js2-must-match-name "msg.bad.catchcond")
8891 (setq param (js2-create-name-node))
8892 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8893 ;; Catch condition.
8894 (if (js2-match-token js2-IF)
8895 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8896 catch-cond (js2-parse-expr))
8897 (setq saw-default-catch t))
8898 (if (js2-must-match js2-RP "msg.bad.catchcond")
8899 (setq rp (- (js2-current-token-beg) catch-pos)))
8900 (js2-must-match js2-LC "msg.no.brace.catchblock")
8901 (js2-parse-statements catch-node)
8902 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8903 (setq try-end (js2-current-token-end)))
8904 (js2-pop-scope)
8905 (setf (js2-node-len catch-node) (- try-end catch-pos)
8906 (js2-catch-node-param catch-node) param
8907 (js2-catch-node-guard-expr catch-node) catch-cond
8908 (js2-catch-node-guard-kwd catch-node) guard-kwd
8909 (js2-catch-node-lp catch-node) lp
8910 (js2-catch-node-rp catch-node) rp)
8911 (js2-node-add-children catch-node param catch-cond)
8912 (push catch-node catch-blocks))))
8913 ((/= peek js2-FINALLY)
8914 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8915 (js2-node-pos try-block)
8916 (- (setq try-end (js2-node-end try-block))
8917 (js2-node-pos try-block)))))
8918 (when (js2-match-token js2-FINALLY)
8919 (let ((finally-pos (js2-current-token-beg))
8920 (block (js2-parse-statement)))
8921 (setq try-end (js2-node-end block)
8922 finally-block (make-js2-finally-node :pos finally-pos
8923 :len (- try-end finally-pos)
8924 :body block))
8925 (js2-node-add-children finally-block block)))
8926 (let ((pn (make-js2-try-node :pos try-pos
8927 :len (- try-end try-pos)
8928 :try-block try-block
8929 :finally-block finally-block)))
8930 (js2-node-add-children pn try-block finally-block)
8931 ;; Push them onto the try-node, which reverses and corrects their order.
8932 (dolist (cb catch-blocks)
8933 (js2-node-add-children pn cb)
8934 (push cb (js2-try-node-catch-clauses pn)))
8935 pn)))
8936
8937 (defun js2-parse-throw ()
8938 "Parser for throw-statement. Last matched token must be js2-THROW."
8939 (let ((pos (js2-current-token-beg))
8940 expr pn)
8941 (if (= (js2-peek-token-or-eol) js2-EOL)
8942 ;; ECMAScript does not allow new lines before throw expression,
8943 ;; see bug 256617
8944 (js2-report-error "msg.bad.throw.eol"))
8945 (setq expr (js2-parse-expr)
8946 pn (make-js2-throw-node :pos pos
8947 :len (- (js2-node-end expr) pos)
8948 :expr expr))
8949 (js2-node-add-children pn expr)
8950 pn))
8951
8952 (defun js2-match-jump-label-name (label-name)
8953 "If break/continue specified a label, return that label's labeled stmt.
8954 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8955 does not match an existing label, reports an error and returns nil."
8956 (let ((bundle (cdr (assoc label-name js2-label-set))))
8957 (if (null bundle)
8958 (js2-report-error "msg.undef.label"))
8959 bundle))
8960
8961 (defun js2-parse-break ()
8962 "Parser for break-statement. Last matched token must be js2-BREAK."
8963 (let ((pos (js2-current-token-beg))
8964 (end (js2-current-token-end))
8965 break-target ; statement to break from
8966 break-label ; in "break foo", name-node representing the foo
8967 labels ; matching labeled statement to break to
8968 pn)
8969 (when (eq (js2-peek-token-or-eol) js2-NAME)
8970 (js2-get-token)
8971 (setq break-label (js2-create-name-node)
8972 end (js2-node-end break-label)
8973 ;; matchJumpLabelName only matches if there is one
8974 labels (js2-match-jump-label-name (js2-current-token-string))
8975 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8976 (unless (or break-target break-label)
8977 ;; no break target specified - try for innermost enclosing loop/switch
8978 (if (null js2-loop-and-switch-set)
8979 (unless break-label
8980 (js2-report-error "msg.bad.break" nil pos (length "break")))
8981 (setq break-target (car js2-loop-and-switch-set))))
8982 (setq pn (make-js2-break-node :pos pos
8983 :len (- end pos)
8984 :label break-label
8985 :target break-target))
8986 (js2-node-add-children pn break-label) ; but not break-target
8987 pn))
8988
8989 (defun js2-parse-continue ()
8990 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8991 (let ((pos (js2-current-token-beg))
8992 (end (js2-current-token-end))
8993 label ; optional user-specified label, a `js2-name-node'
8994 labels ; current matching labeled stmt, if any
8995 target ; the `js2-loop-node' target of this continue stmt
8996 pn)
8997 (when (= (js2-peek-token-or-eol) js2-NAME)
8998 (js2-get-token)
8999 (setq label (js2-create-name-node)
9000 end (js2-node-end label)
9001 ;; matchJumpLabelName only matches if there is one
9002 labels (js2-match-jump-label-name (js2-current-token-string))))
9003 (cond
9004 ((null labels) ; no current label to go to
9005 (if (null js2-loop-set) ; no loop to continue to
9006 (js2-report-error "msg.continue.outside" nil pos
9007 (length "continue"))
9008 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9009 (t
9010 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9011 (setq target (js2-labeled-stmt-node-stmt labels))
9012 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9013 (setq pn (make-js2-continue-node :pos pos
9014 :len (- end pos)
9015 :label label
9016 :target target))
9017 (js2-node-add-children pn label) ; but not target - it's not our child
9018 pn))
9019
9020 (defun js2-parse-with ()
9021 "Parser for with-statement. Last matched token must be js2-WITH."
9022 (let ((pos (js2-current-token-beg))
9023 obj body pn lp rp)
9024 (if (js2-must-match js2-LP "msg.no.paren.with")
9025 (setq lp (js2-current-token-beg)))
9026 (setq obj (js2-parse-expr))
9027 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9028 (setq rp (js2-current-token-beg)))
9029 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9030 (setq body (js2-parse-statement)))
9031 (setq pn (make-js2-with-node :pos pos
9032 :len (- (js2-node-end body) pos)
9033 :object obj
9034 :body body
9035 :lp (js2-relpos lp pos)
9036 :rp (js2-relpos rp pos)))
9037 (js2-node-add-children pn obj body)
9038 pn))
9039
9040 (defun js2-parse-const-var ()
9041 "Parser for var- or const-statement.
9042 Last matched token must be js2-CONST or js2-VAR."
9043 (let ((tt (js2-current-token-type))
9044 (pos (js2-current-token-beg))
9045 expr pn)
9046 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9047 pn (make-js2-expr-stmt-node :pos pos
9048 :len (- (js2-node-end expr) pos)
9049 :expr expr))
9050 (js2-node-add-children pn expr)
9051 pn))
9052
9053 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9054 (let ((pn (make-js2-expr-stmt-node :pos pos
9055 :len (js2-node-len expr)
9056 :type (if (js2-inside-function)
9057 js2-EXPR_VOID
9058 js2-EXPR_RESULT)
9059 :expr expr)))
9060 (if add-child
9061 (js2-node-add-children pn expr))
9062 pn))
9063
9064 (defun js2-parse-let-stmt ()
9065 "Parser for let-statement. Last matched token must be js2-LET."
9066 (let ((pos (js2-current-token-beg))
9067 expr pn)
9068 (if (= (js2-peek-token) js2-LP)
9069 ;; let expression in statement context
9070 (setq expr (js2-parse-let pos 'statement)
9071 pn (js2-wrap-with-expr-stmt pos expr t))
9072 ;; else we're looking at a statement like let x=6, y=7;
9073 (setf expr (js2-parse-variables js2-LET pos)
9074 pn (js2-wrap-with-expr-stmt pos expr t)
9075 (js2-node-type pn) js2-EXPR_RESULT))
9076 pn))
9077
9078 (defun js2-parse-ret-yield ()
9079 (js2-parse-return-or-yield (js2-current-token-type) nil))
9080
9081 (defconst js2-parse-return-stmt-enders
9082 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9083
9084 (defsubst js2-now-all-set (before after mask)
9085 "Return whether or not the bits in the mask have changed to all set.
9086 BEFORE is bits before change, AFTER is bits after change, and MASK is
9087 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9088 but not BEFORE."
9089 (and (/= (logand before mask) mask)
9090 (= (logand after mask) mask)))
9091
9092 (defun js2-parse-return-or-yield (tt expr-context)
9093 (let* ((pos (js2-current-token-beg))
9094 (end (js2-current-token-end))
9095 (before js2-end-flags)
9096 (inside-function (js2-inside-function))
9097 (gen-type (and inside-function (js2-function-node-generator-type
9098 js2-current-script-or-fn)))
9099 e ret name yield-star-p)
9100 (unless inside-function
9101 (js2-report-error (if (eq tt js2-RETURN)
9102 "msg.bad.return"
9103 "msg.bad.yield")))
9104 (when (and inside-function
9105 (eq gen-type 'STAR)
9106 (js2-match-token js2-MUL))
9107 (setq yield-star-p t))
9108 ;; This is ugly, but we don't want to require a semicolon.
9109 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9110 (setq e (js2-parse-expr)
9111 end (js2-node-end e)))
9112 (cond
9113 ((eq tt js2-RETURN)
9114 (js2-set-flag js2-end-flags (if (null e)
9115 js2-end-returns
9116 js2-end-returns-value))
9117 (setq ret (make-js2-return-node :pos pos
9118 :len (- end pos)
9119 :retval e))
9120 (js2-node-add-children ret e)
9121 ;; See if we need a strict mode warning.
9122 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9123 ;; more thorough and accurate than this before/after flag check.
9124 ;; E.g. if there's a finally-block that always returns, we shouldn't
9125 ;; show a warning generated by inconsistent returns in the catch blocks.
9126 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9127 ;; so we know which returns/yields to highlight, and we should get rid of
9128 ;; all the checking in `js2-parse-return-or-yield'.
9129 (if (and js2-strict-inconsistent-return-warning
9130 (js2-now-all-set before js2-end-flags
9131 (logior js2-end-returns js2-end-returns-value)))
9132 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9133 ((eq gen-type 'COMPREHENSION)
9134 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9135 ;; like SpiderMonkey does.
9136 (js2-report-error "msg.syntax" nil pos 5))
9137 (t
9138 (setq ret (make-js2-yield-node :pos pos
9139 :len (- end pos)
9140 :value e
9141 :star-p yield-star-p))
9142 (js2-node-add-children ret e)
9143 (unless expr-context
9144 (setq e ret
9145 ret (js2-wrap-with-expr-stmt pos e t))
9146 (js2-set-requires-activation)
9147 (js2-set-is-generator))))
9148 ;; see if we are mixing yields and value returns.
9149 (when (and inside-function
9150 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9151 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9152 'LEGACY))
9153 (setq name (js2-function-name js2-current-script-or-fn))
9154 (if (zerop (length name))
9155 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9156 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9157 ret))
9158
9159 (defun js2-parse-debugger ()
9160 (make-js2-keyword-node :type js2-DEBUGGER))
9161
9162 (defun js2-parse-block ()
9163 "Parser for a curly-delimited statement block.
9164 Last token matched must be `js2-LC'."
9165 (let ((pos (js2-current-token-beg))
9166 (pn (make-js2-scope)))
9167 (js2-push-scope pn)
9168 (unwind-protect
9169 (progn
9170 (js2-parse-statements pn)
9171 (js2-must-match js2-RC "msg.no.brace.block")
9172 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9173 (js2-pop-scope))
9174 pn))
9175
9176 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9177 (defun js2-parse-semi ()
9178 "Parse a statement or handle an error.
9179 Current token type is `js2-SEMI' or `js2-ERROR'."
9180 (let ((tt (js2-current-token-type)) pos len)
9181 (if (eq tt js2-SEMI)
9182 (make-js2-empty-expr-node :len 1)
9183 (setq pos (js2-current-token-beg)
9184 len (- (js2-current-token-end) pos))
9185 (js2-report-error "msg.syntax" nil pos len)
9186 (make-js2-error-node :pos pos :len len))))
9187
9188 (defun js2-parse-default-xml-namespace ()
9189 "Parse a `default xml namespace = <expr>' e4x statement."
9190 (let ((pos (js2-current-token-beg))
9191 end len expr unary)
9192 (js2-must-have-xml)
9193 (js2-set-requires-activation)
9194 (setq len (- js2-ts-cursor pos))
9195 (unless (and (js2-match-token js2-NAME)
9196 (string= (js2-current-token-string) "xml"))
9197 (js2-report-error "msg.bad.namespace" nil pos len))
9198 (unless (and (js2-match-token js2-NAME)
9199 (string= (js2-current-token-string) "namespace"))
9200 (js2-report-error "msg.bad.namespace" nil pos len))
9201 (unless (js2-match-token js2-ASSIGN)
9202 (js2-report-error "msg.bad.namespace" nil pos len))
9203 (setq expr (js2-parse-expr)
9204 end (js2-node-end expr)
9205 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9206 :pos pos
9207 :len (- end pos)
9208 :operand expr))
9209 (js2-node-add-children unary expr)
9210 (make-js2-expr-stmt-node :pos pos
9211 :len (- end pos)
9212 :expr unary)))
9213
9214 (defun js2-record-label (label bundle)
9215 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9216 (js2-get-token)
9217 (let ((name (js2-label-node-name label))
9218 labeled-stmt
9219 dup)
9220 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9221 ;; flag both labels if possible when used in editing mode
9222 (if (and js2-parse-ide-mode
9223 (setq dup (js2-get-label-by-name labeled-stmt name)))
9224 (js2-report-error "msg.dup.label" nil
9225 (js2-node-abs-pos dup) (js2-node-len dup)))
9226 (js2-report-error "msg.dup.label" nil
9227 (js2-node-pos label) (js2-node-len label)))
9228 (js2-labeled-stmt-node-add-label bundle label)
9229 (js2-node-add-children bundle label)
9230 ;; Add one reference to the bundle per label in `js2-label-set'
9231 (push (cons name bundle) js2-label-set)))
9232
9233 (defun js2-parse-name-or-label ()
9234 "Parser for identifier or label. Last token matched must be js2-NAME.
9235 Called when we found a name in a statement context. If it's a label, we gather
9236 up any following labels and the next non-label statement into a
9237 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9238 expression and return it wrapped in a `js2-expr-stmt-node'."
9239 (let ((pos (js2-current-token-beg))
9240 expr stmt bundle
9241 (continue t))
9242 ;; set check for label and call down to `js2-parse-primary-expr'
9243 (setq expr (js2-maybe-parse-label))
9244 (if (null expr)
9245 ;; Parse the non-label expression and wrap with expression stmt.
9246 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9247 ;; else parsed a label
9248 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9249 (js2-record-label expr bundle)
9250 ;; look for more labels
9251 (while (and continue (= (js2-get-token) js2-NAME))
9252 (if (setq expr (js2-maybe-parse-label))
9253 (js2-record-label expr bundle)
9254 (setq expr (js2-parse-expr)
9255 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9256 continue nil)
9257 (js2-auto-insert-semicolon stmt)))
9258 ;; no more labels; now parse the labeled statement
9259 (unwind-protect
9260 (unless stmt
9261 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9262 (js2-unget-token)
9263 (setq stmt (js2-statement-helper))))
9264 ;; remove the labels for this statement from the global set
9265 (dolist (label (js2-labeled-stmt-node-labels bundle))
9266 (setq js2-label-set (remove label js2-label-set))))
9267 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9268 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9269 (js2-node-add-children bundle stmt)
9270 bundle)))
9271
9272 (defun js2-maybe-parse-label ()
9273 (cl-assert (= (js2-current-token-type) js2-NAME))
9274 (let (label-pos
9275 (next-tt (js2-get-token))
9276 (label-end (js2-current-token-end)))
9277 ;; Do not consume colon, it is used as unwind indicator
9278 ;; to return to statementHelper.
9279 (js2-unget-token)
9280 (if (= next-tt js2-COLON)
9281 (prog2
9282 (setq label-pos (js2-current-token-beg))
9283 (make-js2-label-node :pos label-pos
9284 :len (- label-end label-pos)
9285 :name (js2-current-token-string))
9286 (js2-set-face label-pos
9287 label-end
9288 'font-lock-variable-name-face 'record))
9289 ;; Backtrack from the name token, too.
9290 (js2-unget-token)
9291 nil)))
9292
9293 (defun js2-parse-expr-stmt ()
9294 "Default parser in statement context, if no recognized statement found."
9295 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9296 (progn
9297 (js2-unget-token)
9298 (js2-parse-expr)) t))
9299
9300 (defun js2-parse-variables (decl-type pos)
9301 "Parse a comma-separated list of variable declarations.
9302 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9303
9304 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9305 For 'var' or 'const', the keyword should be the token last scanned.
9306
9307 POS is the position where the node should start. It's sometimes the
9308 var/const/let keyword, and other times the beginning of the first token
9309 in the first variable declaration.
9310
9311 Returns the parsed `js2-var-decl-node' expression node."
9312 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9313 :pos pos))
9314 destructuring kid-pos tt init name end nbeg nend vi
9315 (continue t))
9316 ;; Example:
9317 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9318 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9319 ;; var {a, b} = baz;
9320 (while continue
9321 (setq destructuring nil
9322 name nil
9323 tt (js2-get-token)
9324 kid-pos (js2-current-token-beg)
9325 end (js2-current-token-end)
9326 init nil)
9327 (if (or (= tt js2-LB) (= tt js2-LC))
9328 ;; Destructuring assignment, e.g., var [a, b] = ...
9329 (setq destructuring (js2-parse-destruct-primary-expr)
9330 end (js2-node-end destructuring))
9331 ;; Simple variable name
9332 (js2-unget-token)
9333 (when (js2-must-match-name "msg.bad.var")
9334 (setq name (js2-create-name-node)
9335 nbeg (js2-current-token-beg)
9336 nend (js2-current-token-end)
9337 end nend)
9338 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9339 (when (js2-match-token js2-ASSIGN)
9340 (setq init (js2-parse-assign-expr)
9341 end (js2-node-end init))
9342 (js2-record-imenu-functions init name))
9343 (when name
9344 (js2-set-face nbeg nend (if (js2-function-node-p init)
9345 'font-lock-function-name-face
9346 'font-lock-variable-name-face)
9347 'record))
9348 (setq vi (make-js2-var-init-node :pos kid-pos
9349 :len (- end kid-pos)
9350 :type decl-type))
9351 (if destructuring
9352 (progn
9353 (if (and (null init) (not js2-in-for-init))
9354 (js2-report-error "msg.destruct.assign.no.init"))
9355 (js2-define-destruct-symbols destructuring
9356 decl-type
9357 'font-lock-variable-name-face)
9358 (setf (js2-var-init-node-target vi) destructuring))
9359 (setf (js2-var-init-node-target vi) name))
9360 (setf (js2-var-init-node-initializer vi) init)
9361 (js2-node-add-children vi name destructuring init)
9362 (js2-block-node-push result vi)
9363 (unless (js2-match-token js2-COMMA)
9364 (setq continue nil)))
9365 (setf (js2-node-len result) (- end pos))
9366 result))
9367
9368 (defun js2-parse-let (pos &optional stmt-p)
9369 "Parse a let expression or statement.
9370 A let-expression is of the form `let (vars) expr'.
9371 A let-statement is of the form `let (vars) {statements}'.
9372 The third form of let is a variable declaration list, handled
9373 by `js2-parse-variables'."
9374 (let ((pn (make-js2-let-node :pos pos))
9375 beg vars body)
9376 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9377 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9378 (js2-push-scope pn)
9379 (unwind-protect
9380 (progn
9381 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9382 (if (js2-must-match js2-RP "msg.no.paren.let")
9383 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9384 (if (and stmt-p (js2-match-token js2-LC))
9385 ;; let statement
9386 (progn
9387 (setf beg (js2-current-token-beg) ; position stmt at LC
9388 body (js2-parse-statements))
9389 (js2-must-match js2-RC "msg.no.curly.let")
9390 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9391 (js2-node-len pn) (- (js2-current-token-end) pos)
9392 (js2-let-node-body pn) body
9393 (js2-node-type pn) js2-LET))
9394 ;; let expression
9395 (setf body (js2-parse-expr)
9396 (js2-node-len pn) (- (js2-node-end body) pos)
9397 (js2-let-node-body pn) body))
9398 (setf (js2-let-node-vars pn) vars)
9399 (js2-node-add-children pn vars body))
9400 (js2-pop-scope))
9401 pn))
9402
9403 (defun js2-define-new-symbol (decl-type name node &optional scope)
9404 (js2-scope-put-symbol (or scope js2-current-scope)
9405 name
9406 (make-js2-symbol decl-type name node)))
9407
9408 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9409 "Define a symbol in the current scope.
9410 If NODE is non-nil, it is the AST node associated with the symbol."
9411 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9412 (symbol (if defining-scope
9413 (js2-scope-get-symbol defining-scope name)))
9414 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9415 (pos (if node (js2-node-abs-pos node)))
9416 (len (if node (js2-node-len node))))
9417 (cond
9418 ((and symbol ; already defined
9419 (or (= sdt js2-CONST) ; old version is const
9420 (= decl-type js2-CONST) ; new version is const
9421 ;; two let-bound vars in this block have same name
9422 (and (= sdt js2-LET)
9423 (eq defining-scope js2-current-scope))))
9424 (js2-report-error
9425 (cond
9426 ((= sdt js2-CONST) "msg.const.redecl")
9427 ((= sdt js2-LET) "msg.let.redecl")
9428 ((= sdt js2-VAR) "msg.var.redecl")
9429 ((= sdt js2-FUNCTION) "msg.function.redecl")
9430 (t "msg.parm.redecl"))
9431 name pos len))
9432 ((= decl-type js2-LET)
9433 (if (and (not ignore-not-in-block)
9434 (or (= (js2-node-type js2-current-scope) js2-IF)
9435 (js2-loop-node-p js2-current-scope)))
9436 (js2-report-error "msg.let.decl.not.in.block")
9437 (js2-define-new-symbol decl-type name node)))
9438 ((or (= decl-type js2-VAR)
9439 (= decl-type js2-CONST)
9440 (= decl-type js2-FUNCTION))
9441 (if symbol
9442 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9443 (js2-add-strict-warning "msg.var.redecl" name)
9444 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9445 (js2-add-strict-warning "msg.var.hides.arg" name)))
9446 (js2-define-new-symbol decl-type name node
9447 js2-current-script-or-fn)))
9448 ((= decl-type js2-LP)
9449 (if symbol
9450 ;; must be duplicate parameter. Second parameter hides the
9451 ;; first, so go ahead and add the second pararameter
9452 (js2-report-warning "msg.dup.parms" name))
9453 (js2-define-new-symbol decl-type name node))
9454 (t (js2-code-bug)))))
9455
9456 (defun js2-parse-paren-expr-or-generator-comp ()
9457 (let ((px-pos (js2-current-token-beg)))
9458 (cond
9459 ((and (>= js2-language-version 200)
9460 (js2-match-token js2-FOR))
9461 (js2-parse-generator-comp px-pos))
9462 ((and (>= js2-language-version 200)
9463 (js2-match-token js2-RP))
9464 ;; Not valid expression syntax, but this is valid in an arrow
9465 ;; function with no params: () => body.
9466 (if (eq (js2-peek-token) js2-ARROW)
9467 ;; Return whatever, it will hopefully be rewinded and
9468 ;; reparsed when we reach the =>.
9469 (make-js2-keyword-node :type js2-NULL)
9470 (js2-report-error "msg.syntax")
9471 (make-js2-error-node)))
9472 (t
9473 (let* ((js2-in-for-init nil)
9474 (expr (js2-parse-expr))
9475 (pn (make-js2-paren-node :pos px-pos
9476 :expr expr)))
9477 (js2-node-add-children pn (js2-paren-node-expr pn))
9478 (js2-must-match js2-RP "msg.no.paren")
9479 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9480 pn)))))
9481
9482 (defun js2-parse-expr (&optional oneshot)
9483 (let* ((pn (js2-parse-assign-expr))
9484 (pos (js2-node-pos pn))
9485 left
9486 right
9487 op-pos)
9488 (while (and (not oneshot)
9489 (js2-match-token js2-COMMA))
9490 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9491 (if (= (js2-peek-token) js2-YIELD)
9492 (js2-report-error "msg.yield.parenthesized"))
9493 (setq right (js2-parse-assign-expr)
9494 left pn
9495 pn (make-js2-infix-node :type js2-COMMA
9496 :pos pos
9497 :len (- js2-ts-cursor pos)
9498 :op-pos op-pos
9499 :left left
9500 :right right))
9501 (js2-node-add-children pn left right))
9502 pn))
9503
9504 (defun js2-parse-assign-expr ()
9505 (let ((tt (js2-get-token))
9506 (pos (js2-current-token-beg))
9507 pn left right op-pos
9508 ts-state recorded-identifiers parsed-errors)
9509 (if (= tt js2-YIELD)
9510 (js2-parse-return-or-yield tt t)
9511 ;; Save the tokenizer state in case we find an arrow function
9512 ;; and have to rewind.
9513 (setq ts-state (make-js2-ts-state)
9514 recorded-identifiers js2-recorded-identifiers
9515 parsed-errors js2-parsed-errors)
9516 ;; not yield - parse assignment expression
9517 (setq pn (js2-parse-cond-expr)
9518 tt (js2-get-token))
9519 (cond
9520 ((and (<= js2-first-assign tt)
9521 (<= tt js2-last-assign))
9522 ;; tt express assignment (=, |=, ^=, ..., %=)
9523 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9524 left pn)
9525 (setq right (js2-parse-assign-expr)
9526 pn (make-js2-assign-node :type tt
9527 :pos pos
9528 :len (- (js2-node-end right) pos)
9529 :op-pos op-pos
9530 :left left
9531 :right right))
9532 (when js2-parse-ide-mode
9533 (js2-highlight-assign-targets pn left right)
9534 (js2-record-imenu-functions right left))
9535 ;; do this last so ide checks above can use absolute positions
9536 (js2-node-add-children pn left right))
9537 ((and (= tt js2-ARROW)
9538 (>= js2-language-version 200))
9539 (js2-ts-seek ts-state)
9540 (setq js2-recorded-identifiers recorded-identifiers
9541 js2-parsed-errors parsed-errors)
9542 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9543 (t
9544 (js2-unget-token)))
9545 pn)))
9546
9547 (defun js2-parse-cond-expr ()
9548 (let ((pos (js2-current-token-beg))
9549 (pn (js2-parse-or-expr))
9550 test-expr
9551 if-true
9552 if-false
9553 q-pos
9554 c-pos)
9555 (when (js2-match-token js2-HOOK)
9556 (setq q-pos (- (js2-current-token-beg) pos)
9557 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9558 (js2-must-match js2-COLON "msg.no.colon.cond")
9559 (setq c-pos (- (js2-current-token-beg) pos)
9560 if-false (js2-parse-assign-expr)
9561 test-expr pn
9562 pn (make-js2-cond-node :pos pos
9563 :len (- (js2-node-end if-false) pos)
9564 :test-expr test-expr
9565 :true-expr if-true
9566 :false-expr if-false
9567 :q-pos q-pos
9568 :c-pos c-pos))
9569 (js2-node-add-children pn test-expr if-true if-false))
9570 pn))
9571
9572 (defun js2-make-binary (type left parser)
9573 "Helper for constructing a binary-operator AST node.
9574 LEFT is the left-side-expression, already parsed, and the
9575 binary operator should have just been matched.
9576 PARSER is a function to call to parse the right operand,
9577 or a `js2-node' struct if it has already been parsed.
9578 FIXME: The latter option is unused?"
9579 (let* ((pos (js2-node-pos left))
9580 (op-pos (- (js2-current-token-beg) pos))
9581 (right (if (js2-node-p parser)
9582 parser
9583 (js2-get-token)
9584 (funcall parser)))
9585 (pn (make-js2-infix-node :type type
9586 :pos pos
9587 :len (- (js2-node-end right) pos)
9588 :op-pos op-pos
9589 :left left
9590 :right right)))
9591 (js2-node-add-children pn left right)
9592 pn))
9593
9594 (defun js2-parse-or-expr ()
9595 (let ((pn (js2-parse-and-expr)))
9596 (when (js2-match-token js2-OR)
9597 (setq pn (js2-make-binary js2-OR
9598 pn
9599 'js2-parse-or-expr)))
9600 pn))
9601
9602 (defun js2-parse-and-expr ()
9603 (let ((pn (js2-parse-bit-or-expr)))
9604 (when (js2-match-token js2-AND)
9605 (setq pn (js2-make-binary js2-AND
9606 pn
9607 'js2-parse-and-expr)))
9608 pn))
9609
9610 (defun js2-parse-bit-or-expr ()
9611 (let ((pn (js2-parse-bit-xor-expr)))
9612 (while (js2-match-token js2-BITOR)
9613 (setq pn (js2-make-binary js2-BITOR
9614 pn
9615 'js2-parse-bit-xor-expr)))
9616 pn))
9617
9618 (defun js2-parse-bit-xor-expr ()
9619 (let ((pn (js2-parse-bit-and-expr)))
9620 (while (js2-match-token js2-BITXOR)
9621 (setq pn (js2-make-binary js2-BITXOR
9622 pn
9623 'js2-parse-bit-and-expr)))
9624 pn))
9625
9626 (defun js2-parse-bit-and-expr ()
9627 (let ((pn (js2-parse-eq-expr)))
9628 (while (js2-match-token js2-BITAND)
9629 (setq pn (js2-make-binary js2-BITAND
9630 pn
9631 'js2-parse-eq-expr)))
9632 pn))
9633
9634 (defconst js2-parse-eq-ops
9635 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9636
9637 (defun js2-parse-eq-expr ()
9638 (let ((pn (js2-parse-rel-expr))
9639 tt)
9640 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9641 (setq pn (js2-make-binary tt
9642 pn
9643 'js2-parse-rel-expr)))
9644 (js2-unget-token)
9645 pn))
9646
9647 (defconst js2-parse-rel-ops
9648 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9649
9650 (defun js2-parse-rel-expr ()
9651 (let ((pn (js2-parse-shift-expr))
9652 (continue t)
9653 tt)
9654 (while continue
9655 (setq tt (js2-get-token))
9656 (cond
9657 ((and js2-in-for-init (= tt js2-IN))
9658 (js2-unget-token)
9659 (setq continue nil))
9660 ((memq tt js2-parse-rel-ops)
9661 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9662 (t
9663 (js2-unget-token)
9664 (setq continue nil))))
9665 pn))
9666
9667 (defconst js2-parse-shift-ops
9668 (list js2-LSH js2-URSH js2-RSH))
9669
9670 (defun js2-parse-shift-expr ()
9671 (let ((pn (js2-parse-add-expr))
9672 tt
9673 (continue t))
9674 (while continue
9675 (setq tt (js2-get-token))
9676 (if (memq tt js2-parse-shift-ops)
9677 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9678 (js2-unget-token)
9679 (setq continue nil)))
9680 pn))
9681
9682 (defun js2-parse-add-expr ()
9683 (let ((pn (js2-parse-mul-expr))
9684 tt
9685 (continue t))
9686 (while continue
9687 (setq tt (js2-get-token))
9688 (if (or (= tt js2-ADD) (= tt js2-SUB))
9689 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9690 (js2-unget-token)
9691 (setq continue nil)))
9692 pn))
9693
9694 (defconst js2-parse-mul-ops
9695 (list js2-MUL js2-DIV js2-MOD))
9696
9697 (defun js2-parse-mul-expr ()
9698 (let ((pn (js2-parse-unary-expr))
9699 tt
9700 (continue t))
9701 (while continue
9702 (setq tt (js2-get-token))
9703 (if (memq tt js2-parse-mul-ops)
9704 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9705 (js2-unget-token)
9706 (setq continue nil)))
9707 pn))
9708
9709 (defun js2-make-unary (type parser &rest args)
9710 "Make a unary node of type TYPE.
9711 PARSER is either a node (for postfix operators) or a function to call
9712 to parse the operand (for prefix operators)."
9713 (let* ((pos (js2-current-token-beg))
9714 (postfix (js2-node-p parser))
9715 (expr (if postfix
9716 parser
9717 (apply parser args)))
9718 end
9719 pn)
9720 (if postfix ; e.g. i++
9721 (setq pos (js2-node-pos expr)
9722 end (js2-current-token-end))
9723 (setq end (js2-node-end expr)))
9724 (setq pn (make-js2-unary-node :type type
9725 :pos pos
9726 :len (- end pos)
9727 :operand expr))
9728 (js2-node-add-children pn expr)
9729 pn))
9730
9731 (defconst js2-incrementable-node-types
9732 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9733 "Node types that can be the operand of a ++ or -- operator.")
9734
9735 (defun js2-check-bad-inc-dec (tt beg end unary)
9736 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9737 js2-incrementable-node-types)
9738 (js2-report-error (if (= tt js2-INC)
9739 "msg.bad.incr"
9740 "msg.bad.decr")
9741 nil beg (- end beg))))
9742
9743 (defun js2-parse-unary-expr ()
9744 (let ((tt (js2-current-token-type))
9745 pn expr beg end)
9746 (cond
9747 ((or (= tt js2-VOID)
9748 (= tt js2-NOT)
9749 (= tt js2-BITNOT)
9750 (= tt js2-TYPEOF))
9751 (js2-get-token)
9752 (js2-make-unary tt 'js2-parse-unary-expr))
9753 ((= tt js2-ADD)
9754 (js2-get-token)
9755 ;; Convert to special POS token in decompiler and parse tree
9756 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9757 ((= tt js2-SUB)
9758 (js2-get-token)
9759 ;; Convert to special NEG token in decompiler and parse tree
9760 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9761 ((or (= tt js2-INC)
9762 (= tt js2-DEC))
9763 (js2-get-token)
9764 (prog1
9765 (setq beg (js2-current-token-beg)
9766 end (js2-current-token-end)
9767 expr (js2-make-unary tt 'js2-parse-member-expr t))
9768 (js2-check-bad-inc-dec tt beg end expr)))
9769 ((= tt js2-DELPROP)
9770 (js2-get-token)
9771 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9772 ((= tt js2-ERROR)
9773 (js2-get-token)
9774 (make-js2-error-node)) ; try to continue
9775 ((and (= tt js2-LT)
9776 js2-compiler-xml-available)
9777 ;; XML stream encountered in expression.
9778 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9779 (t
9780 (setq pn (js2-parse-member-expr t)
9781 ;; Don't look across a newline boundary for a postfix incop.
9782 tt (js2-peek-token-or-eol))
9783 (when (or (= tt js2-INC) (= tt js2-DEC))
9784 (js2-get-token)
9785 (setf expr pn
9786 pn (js2-make-unary tt expr))
9787 (js2-node-set-prop pn 'postfix t)
9788 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9789 pn))))
9790
9791 (defun js2-parse-xml-initializer ()
9792 "Parse an E4X XML initializer.
9793 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9794 Then I'll postprocess the result, depending on whether we're in IDE
9795 mode or codegen mode, and generate the appropriate rewritten AST.
9796 IDE mode uses a rich AST that models the XML structure. Codegen mode
9797 just concatenates everything and makes a new XML or XMLList out of it."
9798 (let ((tt (js2-get-first-xml-token))
9799 pn-xml pn expr kids expr-pos
9800 (continue t)
9801 (first-token t))
9802 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9803 (js2-report-error "msg.syntax"))
9804 (setq pn-xml (make-js2-xml-node))
9805 (while continue
9806 (if first-token
9807 (setq first-token nil)
9808 (setq tt (js2-get-next-xml-token)))
9809 (cond
9810 ;; js2-XML means we found a {expr} in the XML stream.
9811 ;; The token string is the XML up to the left-curly.
9812 ((= tt js2-XML)
9813 (push (make-js2-string-node :pos (js2-current-token-beg)
9814 :len (- js2-ts-cursor (js2-current-token-beg)))
9815 kids)
9816 (js2-must-match js2-LC "msg.syntax")
9817 (setq expr-pos js2-ts-cursor
9818 expr (if (eq (js2-peek-token) js2-RC)
9819 (make-js2-empty-expr-node :pos expr-pos)
9820 (js2-parse-expr)))
9821 (js2-must-match js2-RC "msg.syntax")
9822 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9823 :len (js2-node-len expr)
9824 :expr expr))
9825 (js2-node-add-children pn expr)
9826 (push pn kids))
9827 ;; a js2-XMLEND token means we hit the final close-tag.
9828 ((= tt js2-XMLEND)
9829 (push (make-js2-string-node :pos (js2-current-token-beg)
9830 :len (- js2-ts-cursor (js2-current-token-beg)))
9831 kids)
9832 (dolist (kid (nreverse kids))
9833 (js2-block-node-push pn-xml kid))
9834 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9835 (js2-node-pos pn-xml))
9836 continue nil))
9837 (t
9838 (js2-report-error "msg.syntax")
9839 (setq continue nil))))
9840 pn-xml))
9841
9842
9843 (defun js2-parse-argument-list ()
9844 "Parse an argument list and return it as a Lisp list of nodes.
9845 Returns the list in reverse order. Consumes the right-paren token."
9846 (let (result)
9847 (unless (js2-match-token js2-RP)
9848 (cl-loop do
9849 (let ((tt (js2-get-token)))
9850 (if (= tt js2-YIELD)
9851 (js2-report-error "msg.yield.parenthesized"))
9852 (if (and (= tt js2-TRIPLEDOT)
9853 (>= js2-language-version 200))
9854 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9855 (js2-unget-token)
9856 (push (js2-parse-assign-expr) result)))
9857 while
9858 (js2-match-token js2-COMMA))
9859 (js2-must-match js2-RP "msg.no.paren.arg")
9860 result)))
9861
9862 (defun js2-parse-member-expr (&optional allow-call-syntax)
9863 (let ((tt (js2-current-token-type))
9864 pn pos target args beg end init)
9865 (if (/= tt js2-NEW)
9866 (setq pn (js2-parse-primary-expr))
9867 ;; parse a 'new' expression
9868 (js2-get-token)
9869 (setq pos (js2-current-token-beg)
9870 beg pos
9871 target (js2-parse-member-expr)
9872 end (js2-node-end target)
9873 pn (make-js2-new-node :pos pos
9874 :target target
9875 :len (- end pos)))
9876 (js2-highlight-function-call (js2-current-token))
9877 (js2-node-add-children pn target)
9878 (when (js2-match-token js2-LP)
9879 ;; Add the arguments to pn, if any are supplied.
9880 (setf beg pos ; start of "new" keyword
9881 pos (js2-current-token-beg)
9882 args (nreverse (js2-parse-argument-list))
9883 (js2-new-node-args pn) args
9884 end (js2-current-token-end)
9885 (js2-new-node-lp pn) (- pos beg)
9886 (js2-new-node-rp pn) (- end 1 beg))
9887 (apply #'js2-node-add-children pn args))
9888 (when (and js2-allow-rhino-new-expr-initializer
9889 (js2-match-token js2-LC))
9890 (setf init (js2-parse-object-literal)
9891 end (js2-node-end init)
9892 (js2-new-node-initializer pn) init)
9893 (js2-node-add-children pn init))
9894 (setf (js2-node-len pn) (- end beg))) ; end outer if
9895 (js2-parse-member-expr-tail allow-call-syntax pn)))
9896
9897 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9898 "Parse a chain of property/array accesses or function calls.
9899 Includes parsing for E4X operators like `..' and `.@'.
9900 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9901 Returns an expression tree that includes PN, the parent node."
9902 (let (tt
9903 (continue t))
9904 (while continue
9905 (setq tt (js2-get-token))
9906 (cond
9907 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9908 (setq pn (js2-parse-property-access tt pn)))
9909 ((= tt js2-DOTQUERY)
9910 (setq pn (js2-parse-dot-query pn)))
9911 ((= tt js2-LB)
9912 (setq pn (js2-parse-element-get pn)))
9913 ((= tt js2-LP)
9914 (js2-unget-token)
9915 (if allow-call-syntax
9916 (setq pn (js2-parse-function-call pn))
9917 (setq continue nil)))
9918 ((= tt js2-TEMPLATE_HEAD)
9919 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9920 ((= tt js2-NO_SUBS_TEMPLATE)
9921 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9922 (t
9923 (js2-unget-token)
9924 (setq continue nil))))
9925 (if (>= js2-highlight-level 2)
9926 (js2-parse-highlight-member-expr-node pn))
9927 pn))
9928
9929 (defun js2-parse-tagged-template (tag-node tpl-node)
9930 "Parse tagged template expression."
9931 (let* ((beg (js2-node-pos tag-node))
9932 (pn (make-js2-tagged-template-node :beg beg
9933 :len (- (js2-current-token-end) beg)
9934 :tag tag-node
9935 :template tpl-node)))
9936 (js2-node-add-children pn tag-node tpl-node)
9937 pn))
9938
9939 (defun js2-parse-dot-query (pn)
9940 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9941 Last token parsed must be `js2-DOTQUERY'."
9942 (let ((pos (js2-node-pos pn))
9943 op-pos expr end)
9944 (js2-must-have-xml)
9945 (js2-set-requires-activation)
9946 (setq op-pos (js2-current-token-beg)
9947 expr (js2-parse-expr)
9948 end (js2-node-end expr)
9949 pn (make-js2-xml-dot-query-node :left pn
9950 :pos pos
9951 :op-pos op-pos
9952 :right expr))
9953 (js2-node-add-children pn
9954 (js2-xml-dot-query-node-left pn)
9955 (js2-xml-dot-query-node-right pn))
9956 (if (js2-must-match js2-RP "msg.no.paren")
9957 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9958 end (js2-current-token-end)))
9959 (setf (js2-node-len pn) (- end pos))
9960 pn))
9961
9962 (defun js2-parse-element-get (pn)
9963 "Parse an element-get expression, e.g. foo[bar].
9964 Last token parsed must be `js2-RB'."
9965 (let ((lb (js2-current-token-beg))
9966 (pos (js2-node-pos pn))
9967 rb expr)
9968 (setq expr (js2-parse-expr))
9969 (if (js2-must-match js2-RB "msg.no.bracket.index")
9970 (setq rb (js2-current-token-beg)))
9971 (setq pn (make-js2-elem-get-node :target pn
9972 :pos pos
9973 :element expr
9974 :lb (js2-relpos lb pos)
9975 :rb (js2-relpos rb pos)
9976 :len (- (js2-current-token-end) pos)))
9977 (js2-node-add-children pn
9978 (js2-elem-get-node-target pn)
9979 (js2-elem-get-node-element pn))
9980 pn))
9981
9982 (defun js2-highlight-function-call (token)
9983 (when (eq (js2-token-type token) js2-NAME)
9984 (js2-record-face 'js2-function-call token)))
9985
9986 (defun js2-parse-function-call (pn)
9987 (js2-highlight-function-call (js2-current-token))
9988 (js2-get-token)
9989 (let (args
9990 (pos (js2-node-pos pn)))
9991 (setq pn (make-js2-call-node :pos pos
9992 :target pn
9993 :lp (- (js2-current-token-beg) pos)))
9994 (js2-node-add-children pn (js2-call-node-target pn))
9995 ;; Add the arguments to pn, if any are supplied.
9996 (setf args (nreverse (js2-parse-argument-list))
9997 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9998 (js2-call-node-args pn) args)
9999 (apply #'js2-node-add-children pn args)
10000 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10001 pn))
10002
10003 (defun js2-parse-property-access (tt pn)
10004 "Parse a property access, XML descendants access, or XML attr access."
10005 (let ((member-type-flags 0)
10006 (dot-pos (js2-current-token-beg))
10007 (dot-len (if (= tt js2-DOTDOT) 2 1))
10008 name
10009 ref ; right side of . or .. operator
10010 result)
10011 (when (= tt js2-DOTDOT)
10012 (js2-must-have-xml)
10013 (setq member-type-flags js2-descendants-flag))
10014 (if (not js2-compiler-xml-available)
10015 (progn
10016 (js2-must-match-prop-name "msg.no.name.after.dot")
10017 (setq name (js2-create-name-node t js2-GETPROP)
10018 result (make-js2-prop-get-node :left pn
10019 :pos (js2-current-token-beg)
10020 :right name
10021 :len (js2-current-token-len)))
10022 (js2-node-add-children result pn name)
10023 result)
10024 ;; otherwise look for XML operators
10025 (setf result (if (= tt js2-DOT)
10026 (make-js2-prop-get-node)
10027 (make-js2-infix-node :type js2-DOTDOT))
10028 (js2-node-pos result) (js2-node-pos pn)
10029 (js2-infix-node-op-pos result) dot-pos
10030 (js2-infix-node-left result) pn ; do this after setting position
10031 tt (js2-get-prop-name-token))
10032 (cond
10033 ;; handles: name, ns::name, ns::*, ns::[expr]
10034 ((= tt js2-NAME)
10035 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10036 ;; handles: *, *::name, *::*, *::[expr]
10037 ((= tt js2-MUL)
10038 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10039 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10040 ((= tt js2-XMLATTR)
10041 (setq result (js2-parse-attribute-access)))
10042 (t
10043 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10044 (if ref
10045 (setf (js2-node-len result) (- (js2-node-end ref)
10046 (js2-node-pos result))
10047 (js2-infix-node-right result) ref))
10048 (if (js2-infix-node-p result)
10049 (js2-node-add-children result
10050 (js2-infix-node-left result)
10051 (js2-infix-node-right result)))
10052 result)))
10053
10054 (defun js2-parse-attribute-access ()
10055 "Parse an E4X XML attribute expression.
10056 This includes expressions of the forms:
10057
10058 @attr @ns::attr @ns::*
10059 @* @*::attr @*::*
10060 @[expr] @*::[expr] @ns::[expr]
10061
10062 Called if we peeked an '@' token."
10063 (let ((tt (js2-get-prop-name-token))
10064 (at-pos (js2-current-token-beg)))
10065 (cond
10066 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10067 ((= tt js2-NAME)
10068 (js2-parse-property-name at-pos nil 0))
10069 ;; handles: @*, @*::name, @*::*, @*::[expr]
10070 ((= tt js2-MUL)
10071 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10072 ;; handles @[expr]
10073 ((= tt js2-LB)
10074 (js2-parse-xml-elem-ref at-pos))
10075 (t
10076 (js2-report-error "msg.no.name.after.xmlAttr")
10077 ;; Avoid cascaded errors that happen if we make an error node here.
10078 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10079
10080 (defun js2-parse-property-name (at-pos s member-type-flags)
10081 "Check if :: follows name in which case it becomes qualified name.
10082
10083 AT-POS is a natural number if we just read an '@' token, else nil.
10084 S is the name or string that was matched: an identifier, 'throw' or '*'.
10085 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10086
10087 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10088 operator, or the name is followed by ::. For a plain name, returns a
10089 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10090 (let ((pos (or at-pos (js2-current-token-beg)))
10091 colon-pos
10092 (name (js2-create-name-node t (js2-current-token-type) s))
10093 ns tt pn)
10094 (catch 'return
10095 (when (js2-match-token js2-COLONCOLON)
10096 (setq ns name
10097 colon-pos (js2-current-token-beg)
10098 tt (js2-get-prop-name-token))
10099 (cond
10100 ;; handles name::name
10101 ((= tt js2-NAME)
10102 (setq name (js2-create-name-node)))
10103 ;; handles name::*
10104 ((= tt js2-MUL)
10105 (setq name (js2-create-name-node nil nil "*")))
10106 ;; handles name::[expr]
10107 ((= tt js2-LB)
10108 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10109 (t
10110 (js2-report-error "msg.no.name.after.coloncolon"))))
10111 (if (and (null ns) (zerop member-type-flags))
10112 name
10113 (prog1
10114 (setq pn
10115 (make-js2-xml-prop-ref-node :pos pos
10116 :len (- (js2-node-end name) pos)
10117 :at-pos at-pos
10118 :colon-pos colon-pos
10119 :propname name))
10120 (js2-node-add-children pn name))))))
10121
10122 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10123 "Parse the [expr] portion of an xml element reference.
10124 For instance, @[expr], @*::[expr], or ns::[expr]."
10125 (let* ((lb (js2-current-token-beg))
10126 (pos (or at-pos lb))
10127 rb
10128 (expr (js2-parse-expr))
10129 (end (js2-node-end expr))
10130 pn)
10131 (if (js2-must-match js2-RB "msg.no.bracket.index")
10132 (setq rb (js2-current-token-beg)
10133 end (js2-current-token-end)))
10134 (prog1
10135 (setq pn
10136 (make-js2-xml-elem-ref-node :pos pos
10137 :len (- end pos)
10138 :namespace namespace
10139 :colon-pos colon-pos
10140 :at-pos at-pos
10141 :expr expr
10142 :lb (js2-relpos lb pos)
10143 :rb (js2-relpos rb pos)))
10144 (js2-node-add-children pn namespace expr))))
10145
10146 (defun js2-parse-destruct-primary-expr ()
10147 (let ((js2-is-in-destructuring t))
10148 (js2-parse-primary-expr)))
10149
10150 (defun js2-parse-primary-expr ()
10151 "Parse a literal (leaf) expression of some sort.
10152 Includes complex literals such as functions, object-literals,
10153 array-literals, array comprehensions and regular expressions."
10154 (let (tt)
10155 (setq tt (js2-current-token-type))
10156 (cond
10157 ((= tt js2-CLASS)
10158 (js2-parse-class-expr))
10159 ((= tt js2-FUNCTION)
10160 (js2-parse-function-expr))
10161 ((= tt js2-LB)
10162 (js2-parse-array-comp-or-literal))
10163 ((= tt js2-LC)
10164 (js2-parse-object-literal))
10165 ((= tt js2-LET)
10166 (js2-parse-let (js2-current-token-beg)))
10167 ((= tt js2-LP)
10168 (js2-parse-paren-expr-or-generator-comp))
10169 ((= tt js2-XMLATTR)
10170 (js2-must-have-xml)
10171 (js2-parse-attribute-access))
10172 ((= tt js2-NAME)
10173 (js2-parse-name tt))
10174 ((= tt js2-NUMBER)
10175 (make-js2-number-node))
10176 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10177 (make-js2-string-node :type tt))
10178 ((= tt js2-TEMPLATE_HEAD)
10179 (js2-parse-template-literal))
10180 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10181 ;; Got / or /= which in this context means a regexp literal
10182 (let ((px-pos (js2-current-token-beg))
10183 (flags (js2-read-regexp tt))
10184 (end (js2-current-token-end)))
10185 (prog1
10186 (make-js2-regexp-node :pos px-pos
10187 :len (- end px-pos)
10188 :value (js2-current-token-string)
10189 :flags flags)
10190 (js2-set-face px-pos end 'font-lock-string-face 'record)
10191 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10192 ((or (= tt js2-NULL)
10193 (= tt js2-THIS)
10194 (= tt js2-SUPER)
10195 (= tt js2-FALSE)
10196 (= tt js2-TRUE))
10197 (make-js2-keyword-node :type tt))
10198 ((= tt js2-TRIPLEDOT)
10199 ;; Likewise, only valid in an arrow function with a rest param.
10200 (if (and (js2-match-token js2-NAME)
10201 (js2-match-token js2-RP)
10202 (eq (js2-peek-token) js2-ARROW))
10203 (progn
10204 (js2-unget-token) ; Put back the right paren.
10205 ;; See the previous case.
10206 (make-js2-keyword-node :type js2-NULL))
10207 (js2-report-error "msg.syntax")
10208 (make-js2-error-node)))
10209 ((= tt js2-RESERVED)
10210 (js2-report-error "msg.reserved.id")
10211 (make-js2-name-node))
10212 ((= tt js2-ERROR)
10213 ;; the scanner or one of its subroutines reported the error.
10214 (make-js2-error-node))
10215 ((= tt js2-EOF)
10216 (let* ((px-pos (point-at-bol))
10217 (len (- js2-ts-cursor px-pos)))
10218 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10219 (make-js2-error-node :pos (1- js2-ts-cursor)))
10220 (t
10221 (js2-report-error "msg.syntax")
10222 (make-js2-error-node)))))
10223
10224 (defun js2-parse-template-literal ()
10225 (let ((beg (js2-current-token-beg))
10226 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10227 (tt js2-TEMPLATE_HEAD))
10228 (while (eq tt js2-TEMPLATE_HEAD)
10229 (push (js2-parse-expr) kids)
10230 (js2-must-match js2-RC "msg.syntax")
10231 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10232 (push (make-js2-string-node :type tt) kids))
10233 (setq kids (nreverse kids))
10234 (let ((tpl (make-js2-template-node :beg beg
10235 :len (- (js2-current-token-end) beg)
10236 :kids kids)))
10237 (apply #'js2-node-add-children tpl kids)
10238 tpl)))
10239
10240 (defun js2-parse-name (_tt)
10241 (let ((name (js2-current-token-string))
10242 node)
10243 (setq node (if js2-compiler-xml-available
10244 (js2-parse-property-name nil name 0)
10245 (js2-create-name-node 'check-activation nil name)))
10246 (if js2-highlight-external-variables
10247 (js2-record-name-node node))
10248 node))
10249
10250 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10251 (js2-add-strict-warning
10252 msg nil
10253 ;; back up from comma to beginning of line or array/objlit
10254 (max (if elems
10255 (js2-node-pos (car elems))
10256 pos)
10257 (save-excursion
10258 (goto-char comma-pos)
10259 (back-to-indentation)
10260 (point)))
10261 comma-pos))
10262
10263 (defun js2-parse-array-comp-or-literal ()
10264 (let ((pos (js2-current-token-beg)))
10265 (if (and (>= js2-language-version 200)
10266 (js2-match-token js2-FOR))
10267 (js2-parse-array-comp pos)
10268 (js2-parse-array-literal pos))))
10269
10270 (defun js2-parse-array-literal (pos)
10271 (let ((after-lb-or-comma t)
10272 after-comma tt elems pn
10273 (continue t))
10274 (unless js2-is-in-destructuring
10275 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10276 (while continue
10277 (setq tt (js2-get-token))
10278 (cond
10279 ;; comma
10280 ((= tt js2-COMMA)
10281 (setq after-comma (js2-current-token-end))
10282 (if (not after-lb-or-comma)
10283 (setq after-lb-or-comma t)
10284 (push nil elems)))
10285 ;; end of array
10286 ((or (= tt js2-RB)
10287 (= tt js2-EOF)) ; prevent infinite loop
10288 (if (= tt js2-EOF)
10289 (js2-report-error "msg.no.bracket.arg" nil pos))
10290 (when (and after-comma (< js2-language-version 170))
10291 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10292 pos (remove nil elems) after-comma))
10293 (setq continue nil
10294 pn (make-js2-array-node :pos pos
10295 :len (- js2-ts-cursor pos)
10296 :elems (nreverse elems)))
10297 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10298 ;; destructuring binding
10299 (js2-is-in-destructuring
10300 (push (if (or (= tt js2-LC)
10301 (= tt js2-LB)
10302 (= tt js2-NAME))
10303 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10304 (js2-parse-destruct-primary-expr)
10305 ;; invalid pattern
10306 (js2-report-error "msg.bad.var")
10307 (make-js2-error-node))
10308 elems)
10309 (setq after-lb-or-comma nil
10310 after-comma nil))
10311 ;; array comp
10312 ((and (>= js2-language-version 170)
10313 (= tt js2-FOR) ; check for array comprehension
10314 (not after-lb-or-comma) ; "for" can't follow a comma
10315 elems ; must have at least 1 element
10316 (not (cdr elems))) ; but no 2nd element
10317 (js2-unget-token)
10318 (setf continue nil
10319 pn (js2-parse-legacy-array-comp (car elems) pos)))
10320 ;; another element
10321 (t
10322 (unless after-lb-or-comma
10323 (js2-report-error "msg.no.bracket.arg"))
10324 (if (and (= tt js2-TRIPLEDOT)
10325 (>= js2-language-version 200))
10326 ;; spread operator
10327 (push (js2-make-unary tt 'js2-parse-assign-expr)
10328 elems)
10329 (js2-unget-token)
10330 (push (js2-parse-assign-expr) elems))
10331 (setq after-lb-or-comma nil
10332 after-comma nil))))
10333 (unless js2-is-in-destructuring
10334 (js2-pop-scope))
10335 pn))
10336
10337 (defun js2-parse-legacy-array-comp (expr pos)
10338 "Parse a legacy array comprehension (JavaScript 1.7).
10339 EXPR is the first expression after the opening left-bracket.
10340 POS is the beginning of the LB token preceding EXPR.
10341 We should have just parsed the 'for' keyword before calling this function."
10342 (let ((current-scope js2-current-scope)
10343 loops first filter result)
10344 (unwind-protect
10345 (progn
10346 (while (js2-match-token js2-FOR)
10347 (let ((loop (make-js2-comp-loop-node)))
10348 (js2-push-scope loop)
10349 (push loop loops)
10350 (js2-parse-comp-loop loop)))
10351 ;; First loop takes expr scope's parent.
10352 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10353 (js2-scope-parent-scope current-scope))
10354 ;; Set expr scope's parent to the last loop.
10355 (setf (js2-scope-parent-scope current-scope) (car loops))
10356 (if (/= (js2-get-token) js2-IF)
10357 (js2-unget-token)
10358 (setq filter (js2-parse-condition))))
10359 (dotimes (_ (1- (length loops)))
10360 (js2-pop-scope)))
10361 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10362 (setq result (make-js2-comp-node :pos pos
10363 :len (- js2-ts-cursor pos)
10364 :result expr
10365 :loops (nreverse loops)
10366 :filters (and filter (list (car filter)))
10367 :form 'LEGACY_ARRAY))
10368 ;; Set comp loop's parent to the last loop.
10369 ;; TODO: Get rid of the bogus expr scope.
10370 (setf (js2-scope-parent-scope result) first)
10371 (apply #'js2-node-add-children result expr (car filter)
10372 (js2-comp-node-loops result))
10373 result))
10374
10375 (defun js2-parse-array-comp (pos)
10376 "Parse an ES6 array comprehension.
10377 POS is the beginning of the LB token.
10378 We should have just parsed the 'for' keyword before calling this function."
10379 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10380 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10381 pn))
10382
10383 (defun js2-parse-generator-comp (pos)
10384 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10385 (js2-current-script-or-fn
10386 (make-js2-function-node :generator-type 'COMPREHENSION))
10387 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10388 (js2-must-match js2-RP "msg.no.paren" pos)
10389 pn))
10390
10391 (defun js2-parse-comprehension (pos form)
10392 (let (loops filters expr result last)
10393 (unwind-protect
10394 (progn
10395 (js2-unget-token)
10396 (while (js2-match-token js2-FOR)
10397 (let ((loop (make-js2-comp-loop-node)))
10398 (js2-push-scope loop)
10399 (push loop loops)
10400 (js2-parse-comp-loop loop)))
10401 (while (js2-match-token js2-IF)
10402 (push (car (js2-parse-condition)) filters))
10403 (setq expr (js2-parse-assign-expr))
10404 (setq last (car loops)))
10405 (dolist (_ loops)
10406 (js2-pop-scope)))
10407 (setq result (make-js2-comp-node :pos pos
10408 :len (- js2-ts-cursor pos)
10409 :result expr
10410 :loops (nreverse loops)
10411 :filters (nreverse filters)
10412 :form form))
10413 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10414 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10415 (setf (js2-scope-parent-scope result) last)
10416 result))
10417
10418 (defun js2-parse-comp-loop (pn &optional only-of-p)
10419 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10420 The current token should be the initial FOR.
10421 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10422 (let ((pos (js2-comp-loop-node-pos pn))
10423 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10424 (when (and (not only-of-p) (js2-match-token js2-NAME))
10425 (if (string= (js2-current-token-string) "each")
10426 (progn
10427 (setq foreach-p t
10428 each-pos (- (js2-current-token-beg) pos)) ; relative
10429 (js2-record-face 'font-lock-keyword-face))
10430 (js2-report-error "msg.no.paren.for")))
10431 (if (js2-must-match js2-LP "msg.no.paren.for")
10432 (setq lp (- (js2-current-token-beg) pos)))
10433 (setq tt (js2-peek-token))
10434 (cond
10435 ((or (= tt js2-LB)
10436 (= tt js2-LC))
10437 (js2-get-token)
10438 (setq iter (js2-parse-destruct-primary-expr))
10439 (js2-define-destruct-symbols iter js2-LET
10440 'font-lock-variable-name-face t))
10441 ((js2-match-token js2-NAME)
10442 (setq iter (js2-create-name-node)))
10443 (t
10444 (js2-report-error "msg.bad.var")))
10445 ;; Define as a let since we want the scope of the variable to
10446 ;; be restricted to the array comprehension
10447 (if (js2-name-node-p iter)
10448 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10449 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10450 (and (>= js2-language-version 200)
10451 (js2-match-contextual-kwd "of")
10452 (setq forof-p t)))
10453 (setq in-pos (- (js2-current-token-beg) pos))
10454 (js2-report-error "msg.in.after.for.name"))
10455 (setq obj (js2-parse-expr))
10456 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10457 (setq rp (- (js2-current-token-beg) pos)))
10458 (setf (js2-node-pos pn) pos
10459 (js2-node-len pn) (- js2-ts-cursor pos)
10460 (js2-comp-loop-node-iterator pn) iter
10461 (js2-comp-loop-node-object pn) obj
10462 (js2-comp-loop-node-in-pos pn) in-pos
10463 (js2-comp-loop-node-each-pos pn) each-pos
10464 (js2-comp-loop-node-foreach-p pn) foreach-p
10465 (js2-comp-loop-node-forof-p pn) forof-p
10466 (js2-comp-loop-node-lp pn) lp
10467 (js2-comp-loop-node-rp pn) rp)
10468 (js2-node-add-children pn iter obj)
10469 pn))
10470
10471 (defun js2-parse-class-stmt ()
10472 (let ((pos (js2-current-token-beg))
10473 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10474 (name (js2-create-name-node t)))
10475 (js2-set-face (js2-node-pos name) (js2-node-end name)
10476 'font-lock-function-name-face 'record)
10477 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10478 (js2-define-symbol js2-FUNCTION
10479 (js2-name-node-name name)
10480 node)
10481 node)))
10482
10483 (defun js2-parse-class-expr ()
10484 (let ((pos (js2-current-token-beg))
10485 name)
10486 (when (js2-match-token js2-NAME)
10487 (setq name (js2-create-name-node t)))
10488 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10489
10490 (defun js2-parse-class (pos form name)
10491 ;; class X [extends ...] {
10492 (let (pn elems extends)
10493 (if (js2-match-token js2-EXTENDS)
10494 (if (= (js2-peek-token) js2-LC)
10495 (js2-report-error "msg.missing.extends")
10496 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10497 (setq extends (js2-parse-assign-expr))
10498 (if (not extends)
10499 (js2-report-error "msg.bad.extends"))))
10500 (js2-must-match js2-LC "msg.no.brace.class")
10501 (setq elems (js2-parse-object-literal-elems t)
10502 pn (make-js2-class-node :pos pos
10503 :len (- js2-ts-cursor pos)
10504 :form form
10505 :name name
10506 :extends extends
10507 :elems elems))
10508 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10509 pn))
10510
10511 (defun js2-parse-object-literal ()
10512 (let* ((pos (js2-current-token-beg))
10513 (elems (js2-parse-object-literal-elems))
10514 (result (make-js2-object-node :pos pos
10515 :len (- js2-ts-cursor pos)
10516 :elems elems)))
10517 (apply #'js2-node-add-children result (js2-object-node-elems result))
10518 result))
10519
10520 (defun js2-parse-object-literal-elems (&optional class-p)
10521 (let ((pos (js2-current-token-beg))
10522 (static nil)
10523 (continue t)
10524 tt elems elem after-comma previous-token)
10525 (while continue
10526 (setq tt (js2-get-prop-name-token)
10527 static nil
10528 elem nil
10529 previous-token nil)
10530 ;; Handle 'static' keyword only if we're in a class
10531 (when (and class-p (= js2-NAME tt)
10532 (string= "static" (js2-current-token-string)))
10533 (js2-record-face 'font-lock-keyword-face)
10534 (setq static t
10535 tt (js2-get-prop-name-token)))
10536 ;; Handle generator * before the property name for in-line functions
10537 (when (and (>= js2-language-version 200)
10538 (= js2-MUL tt))
10539 (setq previous-token (js2-current-token)
10540 tt (js2-get-prop-name-token)))
10541 ;; Handle 'get' or 'set' keywords
10542 (let ((prop (js2-current-token-string)))
10543 (when (and (>= js2-language-version 200)
10544 (= js2-NAME tt)
10545 (or (string= prop "get")
10546 (string= prop "set"))
10547 (member (js2-peek-token)
10548 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10549 (setq previous-token (js2-current-token)
10550 tt (js2-get-prop-name-token))))
10551 (cond
10552 ;; Found a property (of any sort)
10553 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10554 (setq after-comma nil
10555 elem (js2-parse-named-prop tt pos previous-token))
10556 (if (and (null elem)
10557 (not js2-recover-from-parse-errors))
10558 (setq continue nil)))
10559 ;; Break out of loop, and handle trailing commas.
10560 ((or (= tt js2-RC)
10561 (= tt js2-EOF))
10562 (js2-unget-token)
10563 (setq continue nil)
10564 (if after-comma
10565 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10566 pos elems after-comma)))
10567 (t
10568 (js2-report-error "msg.bad.prop")
10569 (unless js2-recover-from-parse-errors
10570 (setq continue nil)))) ; end switch
10571 ;; Handle static for classes' codegen.
10572 (if static
10573 (if elem (js2-node-set-prop elem 'STATIC t)
10574 (js2-report-error "msg.unexpected.static")))
10575 ;; Handle commas, depending on class-p.
10576 (let ((tok (js2-get-prop-name-token)))
10577 (if (eq tok js2-COMMA)
10578 (if class-p
10579 (js2-report-error "msg.class.unexpected.comma")
10580 (setq after-comma (js2-current-token-end)))
10581 (js2-unget-token)
10582 (unless class-p (setq continue nil))))
10583 ;; Append any parsed element.
10584 (if elem (push elem elems))) ; end loop
10585 (js2-must-match js2-RC "msg.no.brace.prop")
10586 (nreverse elems)))
10587
10588 (defun js2-parse-named-prop (tt pos previous-token)
10589 "Parse a name, string, or getter/setter object property.
10590 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10591 (let ((key (cond
10592 ;; Literal string keys: {'foo': 'bar'}
10593 ((= tt js2-STRING)
10594 (make-js2-string-node))
10595 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10596 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10597 ((and (= tt js2-LB)
10598 (>= js2-language-version 200))
10599 (prog1 (js2-parse-expr)
10600 (js2-must-match js2-RB "msg.missing.computed.rb")))
10601 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10602 ((= tt js2-NUMBER)
10603 (make-js2-number-node))
10604 ;; Unquoted names: {foo: 12}
10605 ((= tt js2-NAME)
10606 (js2-create-name-node))
10607 ;; Anything else is an error
10608 (t (js2-report-error "msg.bad.prop"))))
10609 (prop (and previous-token (js2-token-string previous-token)))
10610 (property-type (when previous-token
10611 (if (= (js2-token-type previous-token) js2-MUL)
10612 "*"
10613 (js2-token-string previous-token)))))
10614 (when (or (string= prop "get")
10615 (string= prop "set"))
10616 (js2-set-face (js2-token-beg previous-token)
10617 (js2-token-end previous-token)
10618 'font-lock-keyword-face 'record)) ; get/set
10619 (cond
10620 ;; method definition: {f() {...}}
10621 ((and (= (js2-peek-token) js2-LP)
10622 (>= js2-language-version 200))
10623 (when (js2-name-node-p key) ; highlight function name properties
10624 (js2-record-face 'font-lock-function-name-face))
10625 (js2-parse-getter-setter-prop pos key property-type))
10626 ;; regular prop
10627 (t
10628 (let ((beg (js2-current-token-beg))
10629 (end (js2-current-token-end))
10630 (expr (js2-parse-plain-property key)))
10631 (when (and (= tt js2-NAME)
10632 (not js2-is-in-destructuring)
10633 js2-highlight-external-variables
10634 (js2-node-get-prop expr 'SHORTHAND))
10635 (js2-record-name-node key))
10636 (js2-set-face beg end
10637 (if (js2-function-node-p
10638 (js2-object-prop-node-right expr))
10639 'font-lock-function-name-face
10640 'font-lock-variable-name-face)
10641 'record)
10642 expr)))))
10643
10644 (defun js2-parse-plain-property (prop)
10645 "Parse a non-getter/setter property in an object literal.
10646 PROP is the node representing the property: a number, name or string."
10647 (let* ((tt (js2-get-token))
10648 (pos (js2-node-pos prop))
10649 colon expr result)
10650 (cond
10651 ;; Abbreviated property, as in {foo, bar}
10652 ((and (>= js2-language-version 200)
10653 (or (= tt js2-COMMA)
10654 (= tt js2-RC))
10655 (not (js2-number-node-p prop)))
10656 (js2-unget-token)
10657 (setq result (make-js2-object-prop-node
10658 :pos pos
10659 :left prop
10660 :right prop
10661 :op-pos (js2-current-token-len)))
10662 (js2-node-add-children result prop)
10663 (js2-node-set-prop result 'SHORTHAND t)
10664 result)
10665 ;; Normal property
10666 (t
10667 (if (= tt js2-COLON)
10668 (setq colon (- (js2-current-token-beg) pos)
10669 expr (js2-parse-assign-expr))
10670 (js2-report-error "msg.no.colon.prop")
10671 (setq expr (make-js2-error-node)))
10672 (setq result (make-js2-object-prop-node
10673 :pos pos
10674 ;; don't include last consumed token in length
10675 :len (- (+ (js2-node-pos expr)
10676 (js2-node-len expr))
10677 pos)
10678 :left prop
10679 :right expr
10680 :op-pos colon))
10681 (js2-node-add-children result prop expr)
10682 result))))
10683
10684 (defun js2-parse-getter-setter-prop (pos prop type-string)
10685 "Parse getter or setter property in an object literal.
10686 JavaScript syntax is:
10687
10688 { get foo() {...}, set foo(x) {...} }
10689
10690 and expression closure style is also supported
10691
10692 { get foo() x, set foo(x) _x = x }
10693
10694 POS is the start position of the `get' or `set' keyword.
10695 PROP is the `js2-name-node' representing the property name.
10696 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10697 (let ((type (cond
10698 ((string= "get" type-string) js2-GET)
10699 ((string= "set" type-string) js2-SET)
10700 (t js2-FUNCTION)))
10701 result end
10702 (fn (js2-parse-function-expr)))
10703 ;; it has to be an anonymous function, as we already parsed the name
10704 (if (/= (js2-node-type fn) js2-FUNCTION)
10705 (js2-report-error "msg.bad.prop")
10706 (if (cl-plusp (length (js2-function-name fn)))
10707 (js2-report-error "msg.bad.prop")))
10708 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10709 (when (string= type-string "*")
10710 (setf (js2-function-node-generator-type fn) 'STAR))
10711 (setq end (js2-node-end fn)
10712 result (make-js2-getter-setter-node :type type
10713 :pos pos
10714 :len (- end pos)
10715 :left prop
10716 :right fn))
10717 (js2-node-add-children result prop fn)
10718 result))
10719
10720 (defun js2-create-name-node (&optional check-activation-p token string)
10721 "Create a name node using the current token and, optionally, STRING.
10722 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10723 (let* ((beg (js2-current-token-beg))
10724 (tt (js2-current-token-type))
10725 (s (or string
10726 (if (= js2-NAME tt)
10727 (js2-current-token-string)
10728 (js2-tt-name tt))))
10729 name)
10730 (setq name (make-js2-name-node :pos beg
10731 :name s
10732 :len (length s)))
10733 (if check-activation-p
10734 (js2-check-activation-name s (or token js2-NAME)))
10735 name))
10736
10737 ;;; Indentation support
10738
10739 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10740 ;; Karl cleverly deduces that the desired indentation level is often a
10741 ;; function of paren/bracket/brace nesting depth, which can be determined
10742 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10743 ;; then does some equally clever checks to see if we're in the context of a
10744 ;; substatement of a possibly braceless statement keyword such as if, while,
10745 ;; or finally. This approach yields pretty good results.
10746
10747 ;; The indenter is often "wrong", however, and needs to be overridden.
10748 ;; The right long-term solution is probably to emulate (or integrate
10749 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10750 ;; parse tree from `js2-parse' is present, which is not true at the
10751 ;; moment the user is typing, computing indentation is still thousands
10752 ;; of lines of code to handle every possible syntactic edge case.
10753
10754 ;; In the meantime, the compromise solution is that we offer a "bounce
10755 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10756 ;; current line indent among various likely guess points. This approach
10757 ;; is far from perfect, but should at least make it slightly easier to
10758 ;; move the line towards its desired indentation when manually
10759 ;; overriding Karl's heuristic nesting guesser.
10760
10761 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10762 ;; extensions such as `let' and Array comprehensions. Major kudos to
10763 ;; Karl for coming up with the initial approach, which packs a lot of
10764 ;; punch for so little code.
10765
10766 (defconst js2-possibly-braceless-keywords-re
10767 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10768 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10769 "try" "while" "with" "let")))
10770 "Regular expression matching keywords that are optionally
10771 followed by an opening brace.")
10772
10773 (defconst js2-indent-operator-re
10774 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10775 (regexp-opt '("in" "instanceof") 'words))
10776 "Regular expression matching operators that affect indentation
10777 of continued expressions.")
10778
10779 (defconst js2-declaration-keyword-re
10780 (regexp-opt '("var" "let" "const") 'words)
10781 "Regular expression matching variable declaration keywords.")
10782
10783 (defun js2-re-search-forward-inner (regexp &optional bound count)
10784 "Auxiliary function for `js2-re-search-forward'."
10785 (let (parse saved-point)
10786 (while (> count 0)
10787 (re-search-forward regexp bound)
10788 (setq parse (if saved-point
10789 (parse-partial-sexp saved-point (point))
10790 (syntax-ppss (point))))
10791 (cond ((nth 3 parse)
10792 (re-search-forward
10793 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10794 (save-excursion (end-of-line) (point)) t))
10795 ((nth 7 parse)
10796 (forward-line))
10797 ((or (nth 4 parse)
10798 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10799 (re-search-forward "\\*/"))
10800 (t
10801 (setq count (1- count))))
10802 (setq saved-point (point))))
10803 (point))
10804
10805 (defun js2-re-search-forward (regexp &optional bound noerror count)
10806 "Search forward but ignore strings and comments.
10807 Invokes `re-search-forward' but treats the buffer as if strings
10808 and comments have been removed."
10809 (let ((saved-point (point)))
10810 (condition-case err
10811 (cond ((null count)
10812 (js2-re-search-forward-inner regexp bound 1))
10813 ((< count 0)
10814 (js2-re-search-backward-inner regexp bound (- count)))
10815 ((> count 0)
10816 (js2-re-search-forward-inner regexp bound count)))
10817 (search-failed
10818 (goto-char saved-point)
10819 (unless noerror
10820 (error (error-message-string err)))))))
10821
10822 (defun js2-re-search-backward-inner (regexp &optional bound count)
10823 "Auxiliary function for `js2-re-search-backward'."
10824 (let (parse)
10825 (while (> count 0)
10826 (re-search-backward regexp bound)
10827 (setq parse (syntax-ppss (point)))
10828 (cond ((nth 3 parse)
10829 (re-search-backward
10830 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10831 (line-beginning-position) t))
10832 ((nth 7 parse)
10833 (goto-char (nth 8 parse)))
10834 ((or (nth 4 parse)
10835 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10836 (re-search-backward "/\\*"))
10837 (t
10838 (setq count (1- count))))))
10839 (point))
10840
10841 (defun js2-re-search-backward (regexp &optional bound noerror count)
10842 "Search backward but ignore strings and comments.
10843 Invokes `re-search-backward' but treats the buffer as if strings
10844 and comments have been removed."
10845 (let ((saved-point (point)))
10846 (condition-case err
10847 (cond ((null count)
10848 (js2-re-search-backward-inner regexp bound 1))
10849 ((< count 0)
10850 (js2-re-search-forward-inner regexp bound (- count)))
10851 ((> count 0)
10852 (js2-re-search-backward-inner regexp bound count)))
10853 (search-failed
10854 (goto-char saved-point)
10855 (unless noerror
10856 (error (error-message-string err)))))))
10857
10858 (defun js2-looking-at-operator-p ()
10859 "Return non-nil if text after point is a non-comma operator."
10860 (and (looking-at js2-indent-operator-re)
10861 (or (not (looking-at ":"))
10862 (save-excursion
10863 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10864 (looking-at "?"))))))
10865
10866 (defun js2-continued-expression-p ()
10867 "Return non-nil if the current line continues an expression."
10868 (save-excursion
10869 (back-to-indentation)
10870 (or (js2-looking-at-operator-p)
10871 (when (catch 'found
10872 (while (and (re-search-backward "\n" nil t)
10873 (let ((state (syntax-ppss)))
10874 (when (nth 4 state)
10875 (goto-char (nth 8 state))) ;; skip comments
10876 (skip-chars-backward " \t")
10877 (if (bolp)
10878 t
10879 (throw 'found t))))))
10880 (backward-char)
10881 (when (js2-looking-at-operator-p)
10882 (backward-char)
10883 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10884
10885 (defun js2-end-of-do-while-loop-p ()
10886 "Return non-nil if word after point is `while' of a do-while
10887 statement, else returns nil. A braceless do-while statement
10888 spanning several lines requires that the start of the loop is
10889 indented to the same column as the current line."
10890 (interactive)
10891 (save-excursion
10892 (when (looking-at "\\s-*\\<while\\>")
10893 (if (save-excursion
10894 (skip-chars-backward "[ \t\n]*}")
10895 (looking-at "[ \t\n]*}"))
10896 (save-excursion
10897 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10898 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10899 (or (looking-at "\\<do\\>")
10900 (let ((saved-indent (current-indentation)))
10901 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10902 (/= (current-indentation) saved-indent)))
10903 (and (looking-at "[ \t]*\\<do\\>")
10904 (not (js2-re-search-forward
10905 "\\<while\\>" (point-at-eol) t))
10906 (= (current-indentation) saved-indent))))))))
10907
10908 (defun js2-multiline-decl-indentation ()
10909 "Return the declaration indentation column if the current line belongs
10910 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10911 (let (forward-sexp-function ; use Lisp version
10912 at-opening-bracket)
10913 (save-excursion
10914 (back-to-indentation)
10915 (when (not (looking-at js2-declaration-keyword-re))
10916 (when (looking-at js2-indent-operator-re)
10917 (goto-char (match-end 0))) ; continued expressions are ok
10918 (while (and (not at-opening-bracket)
10919 (not (bobp))
10920 (let ((pos (point)))
10921 (save-excursion
10922 (js2-backward-sws)
10923 (or (eq (char-before) ?,)
10924 (and (not (eq (char-before) ?\;))
10925 (prog2 (skip-syntax-backward ".")
10926 (looking-at js2-indent-operator-re)
10927 (js2-backward-sws))
10928 (not (eq (char-before) ?\;)))
10929 (js2-same-line pos)))))
10930 (condition-case _
10931 (backward-sexp)
10932 (scan-error (setq at-opening-bracket t))))
10933 (when (looking-at js2-declaration-keyword-re)
10934 (goto-char (match-end 0))
10935 (1+ (current-column)))))))
10936
10937 (defun js2-ctrl-statement-indentation ()
10938 "Return the proper indentation of current line if it is a control statement.
10939 Returns an indentation if this line starts the body of a control
10940 statement without braces, else returns nil."
10941 (let (forward-sexp-function)
10942 (save-excursion
10943 (back-to-indentation)
10944 (when (and (not (js2-same-line (point-min)))
10945 (not (looking-at "{"))
10946 (js2-re-search-backward "[[:graph:]]" nil t)
10947 (not (looking-at "[{([]"))
10948 (progn
10949 (forward-char)
10950 (when (= (char-before) ?\))
10951 ;; scan-sexps sometimes throws an error
10952 (ignore-errors (backward-sexp))
10953 (skip-chars-backward " \t" (point-at-bol)))
10954 (let ((pt (point)))
10955 (back-to-indentation)
10956 (when (looking-at "}[ \t]*")
10957 (goto-char (match-end 0)))
10958 (and (looking-at js2-possibly-braceless-keywords-re)
10959 (= (match-end 0) pt)
10960 (not (js2-end-of-do-while-loop-p))))))
10961 (+ (current-indentation) js2-basic-offset)))))
10962
10963 (defun js2-indent-in-array-comp (parse-status)
10964 "Return non-nil if we think we're in an array comprehension.
10965 In particular, return the buffer position of the first `for' kwd."
10966 (let ((bracket (nth 1 parse-status))
10967 (end (point)))
10968 (when bracket
10969 (save-excursion
10970 (goto-char bracket)
10971 (when (looking-at "\\[")
10972 (forward-char 1)
10973 (js2-forward-sws)
10974 (if (looking-at "[[{]")
10975 (let (forward-sexp-function) ; use Lisp version
10976 (forward-sexp) ; skip destructuring form
10977 (js2-forward-sws)
10978 (if (and (/= (char-after) ?,) ; regular array
10979 (looking-at "for"))
10980 (match-beginning 0)))
10981 ;; to skip arbitrary expressions we need the parser,
10982 ;; so we'll just guess at it.
10983 (if (and (> end (point)) ; not empty literal
10984 (re-search-forward "[^,]]* \\(for\\) " end t)
10985 ;; not inside comment or string literal
10986 (let ((state (parse-partial-sexp bracket (point))))
10987 (not (or (nth 3 state) (nth 4 state)))))
10988 (match-beginning 1))))))))
10989
10990 (defun js2-array-comp-indentation (parse-status for-kwd)
10991 (if (js2-same-line for-kwd)
10992 ;; first continuation line
10993 (save-excursion
10994 (goto-char (nth 1 parse-status))
10995 (forward-char 1)
10996 (skip-chars-forward " \t")
10997 (current-column))
10998 (save-excursion
10999 (goto-char for-kwd)
11000 (current-column))))
11001
11002 (defun js2-maybe-goto-declaration-keyword-end (bracket)
11003 "Helper function for `js2-proper-indentation'.
11004 Depending on the value of `js2-pretty-multiline-declarations',
11005 move point to the end of a variable declaration keyword so that
11006 indentation is aligned to that column."
11007 (cond
11008 ((eq js2-pretty-multiline-declarations 'all)
11009 (when (looking-at js2-declaration-keyword-re)
11010 (goto-char (1+ (match-end 0)))))
11011 ((eq js2-pretty-multiline-declarations 'dynamic)
11012 (let (declaration-keyword-end
11013 at-closing-bracket-p
11014 comma-p)
11015 (when (looking-at js2-declaration-keyword-re)
11016 ;; Preserve the match data lest it somehow be overridden.
11017 (setq declaration-keyword-end (match-end 0))
11018 (save-excursion
11019 (goto-char bracket)
11020 (setq at-closing-bracket-p
11021 ;; Handle scan errors gracefully.
11022 (condition-case nil
11023 (progn
11024 ;; Use the regular `forward-sexp-function' because the
11025 ;; normal one for this mode uses the AST.
11026 (let (forward-sexp-function)
11027 (forward-sexp))
11028 t)
11029 (error nil)))
11030 (when at-closing-bracket-p
11031 (js2-forward-sws)
11032 (setq comma-p (looking-at-p ","))))
11033 (when comma-p
11034 (goto-char (1+ declaration-keyword-end))))))))
11035
11036 (defun js2-proper-indentation (parse-status)
11037 "Return the proper indentation for the current line."
11038 (save-excursion
11039 (back-to-indentation)
11040 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
11041 (at-closing-bracket (looking-at "[]})]"))
11042 (same-indent-p (or at-closing-bracket
11043 (looking-at "\\<case\\>[^:]")
11044 (and (looking-at "\\<default:")
11045 (save-excursion
11046 (js2-backward-sws)
11047 (not (memq (char-before) '(?, ?{)))))))
11048 (continued-expr-p (js2-continued-expression-p))
11049 (declaration-indent (and js2-pretty-multiline-declarations
11050 (js2-multiline-decl-indentation)))
11051 (bracket (nth 1 parse-status))
11052 beg indent)
11053 (cond
11054 ;; indent array comprehension continuation lines specially
11055 ((and bracket
11056 (>= js2-language-version 170)
11057 (not (js2-same-line bracket))
11058 (setq beg (js2-indent-in-array-comp parse-status))
11059 (>= (point) (save-excursion
11060 (goto-char beg)
11061 (point-at-bol)))) ; at or after first loop?
11062 (js2-array-comp-indentation parse-status beg))
11063
11064 (ctrl-stmt-indent)
11065
11066 ((and declaration-indent continued-expr-p)
11067 (+ declaration-indent js2-basic-offset))
11068
11069 (declaration-indent)
11070
11071 (bracket
11072 (goto-char bracket)
11073 (cond
11074 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
11075 (when (save-excursion (skip-chars-backward " \t)")
11076 (looking-at ")"))
11077 (backward-list))
11078 (back-to-indentation)
11079 (js2-maybe-goto-declaration-keyword-end bracket)
11080 (setq indent
11081 (cond (same-indent-p
11082 (current-column))
11083 (continued-expr-p
11084 (+ (current-column) (* 2 js2-basic-offset)))
11085 (t
11086 (+ (current-column) js2-basic-offset))))
11087 (if (and js2-indent-switch-body
11088 (not at-closing-bracket)
11089 (looking-at "\\_<switch\\_>"))
11090 (+ indent js2-basic-offset)
11091 indent))
11092 (t
11093 (unless same-indent-p
11094 (forward-char)
11095 (skip-chars-forward " \t"))
11096 (current-column))))
11097
11098 (continued-expr-p js2-basic-offset)
11099
11100 (t 0)))))
11101
11102 (defun js2-lineup-comment (parse-status)
11103 "Indent a multi-line block comment continuation line."
11104 (let* ((beg (nth 8 parse-status))
11105 (first-line (js2-same-line beg))
11106 (offset (save-excursion
11107 (goto-char beg)
11108 (if (looking-at "/\\*")
11109 (+ 1 (current-column))
11110 0))))
11111 (unless first-line
11112 (indent-line-to offset))))
11113
11114 (defun js2-backward-sws ()
11115 "Move backward through whitespace and comments."
11116 (interactive)
11117 (while (forward-comment -1)))
11118
11119 (defun js2-forward-sws ()
11120 "Move forward through whitespace and comments."
11121 (interactive)
11122 (while (forward-comment 1)))
11123
11124 (defun js2-current-indent (&optional pos)
11125 "Return column of indentation on current line.
11126 If POS is non-nil, go to that point and return indentation for that line."
11127 (save-excursion
11128 (if pos
11129 (goto-char pos))
11130 (back-to-indentation)
11131 (current-column)))
11132
11133 (defun js2-arglist-close ()
11134 "Return non-nil if we're on a line beginning with a close-paren/brace."
11135 (save-excursion
11136 (goto-char (point-at-bol))
11137 (js2-forward-sws)
11138 (looking-at "[])}]")))
11139
11140 (defun js2-indent-looks-like-label-p ()
11141 (goto-char (point-at-bol))
11142 (js2-forward-sws)
11143 (looking-at (concat js2-mode-identifier-re ":")))
11144
11145 (defun js2-indent-in-objlit-p (parse-status)
11146 "Return non-nil if this looks like an object-literal entry."
11147 (let ((start (nth 1 parse-status)))
11148 (and
11149 start
11150 (save-excursion
11151 (and (zerop (forward-line -1))
11152 (not (< (point) start)) ; crossed a {} boundary
11153 (js2-indent-looks-like-label-p)))
11154 (save-excursion
11155 (js2-indent-looks-like-label-p)))))
11156
11157 ;; If prev line looks like foobar({ then we're passing an object
11158 ;; literal to a function call, and people pretty much always want to
11159 ;; de-dent back to the previous line, so move the 'basic-offset'
11160 ;; position to the front.
11161 (defun js2-indent-objlit-arg-p (parse-status)
11162 (save-excursion
11163 (back-to-indentation)
11164 (js2-backward-sws)
11165 (and (eq (1- (point)) (nth 1 parse-status))
11166 (eq (char-before) ?{)
11167 (progn
11168 (forward-char -1)
11169 (skip-chars-backward " \t")
11170 (eq (char-before) ?\()))))
11171
11172 (defun js2-indent-case-block-p ()
11173 (save-excursion
11174 (back-to-indentation)
11175 (js2-backward-sws)
11176 (goto-char (point-at-bol))
11177 (skip-chars-forward " \t")
11178 (looking-at "case\\s-.+:")))
11179
11180 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
11181 "Cycle among alternate computed indentation positions.
11182 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11183 of the buffer to the current point. NORMAL-COL is the indentation
11184 column computed by the heuristic guesser based on current paren,
11185 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11186 in reverse."
11187 (let ((cur-indent (js2-current-indent))
11188 (old-buffer-undo-list buffer-undo-list)
11189 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11190 (current-line (save-excursion
11191 (forward-line 0) ; move to bol
11192 (1+ (count-lines (point-min) (point)))))
11193 positions pos main-pos anchor arglist-cont same-indent
11194 basic-offset computed-pos)
11195 ;; temporarily don't record undo info, if user requested this
11196 (when js2-mode-indent-inhibit-undo
11197 (setq buffer-undo-list t))
11198 (unwind-protect
11199 (progn
11200 ;; First likely point: indent from beginning of previous code line
11201 (push (setq basic-offset
11202 (+ (save-excursion
11203 (back-to-indentation)
11204 (js2-backward-sws)
11205 (back-to-indentation)
11206 (current-column))
11207 js2-basic-offset))
11208 positions)
11209
11210 ;; (First + epsilon) likely point: indent 2x from beginning of
11211 ;; previous code line. Google does it this way.
11212 (push (setq basic-offset
11213 (+ (save-excursion
11214 (back-to-indentation)
11215 (js2-backward-sws)
11216 (back-to-indentation)
11217 (current-column))
11218 (* 2 js2-basic-offset)))
11219 positions)
11220
11221 ;; Second likely point: indent from assign-expr RHS. This
11222 ;; is just a crude guess based on finding " = " on the previous
11223 ;; line containing actual code.
11224 (setq pos (save-excursion
11225 (forward-line -1)
11226 (goto-char (point-at-bol))
11227 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11228 (point-at-eol) t)
11229 (goto-char (match-end 1))
11230 (skip-chars-forward " \t\r\n")
11231 (current-column))))
11232 (when pos
11233 (cl-incf pos js2-basic-offset)
11234 (push pos positions))
11235
11236 ;; Third likely point: same indent as previous line of code.
11237 ;; Make it the first likely point if we're not on an
11238 ;; arglist-close line and previous line ends in a comma, or
11239 ;; both this line and prev line look like object-literal
11240 ;; elements.
11241 (setq pos (save-excursion
11242 (goto-char (point-at-bol))
11243 (js2-backward-sws)
11244 (back-to-indentation)
11245 (prog1
11246 (current-column)
11247 ;; while we're here, look for trailing comma
11248 (if (save-excursion
11249 (goto-char (point-at-eol))
11250 (js2-backward-sws)
11251 (eq (char-before) ?,))
11252 (setq arglist-cont (1- (point)))))))
11253 (when pos
11254 (if (and (or arglist-cont
11255 (js2-indent-in-objlit-p parse-status))
11256 (not (js2-arglist-close)))
11257 (setq same-indent pos))
11258 (push pos positions))
11259
11260 ;; Fourth likely point: first preceding code with less indentation.
11261 ;; than the immediately preceding code line.
11262 (setq pos (save-excursion
11263 (back-to-indentation)
11264 (js2-backward-sws)
11265 (back-to-indentation)
11266 (setq anchor (current-column))
11267 (while (and (zerop (forward-line -1))
11268 (>= (progn
11269 (back-to-indentation)
11270 (current-column))
11271 anchor)))
11272 (setq pos (current-column))))
11273 (push pos positions)
11274
11275 ;; nesting-heuristic position, main by default
11276 (push (setq main-pos normal-col) positions)
11277
11278 ;; delete duplicates and sort positions list
11279 (setq positions (sort (delete-dups positions) '<))
11280
11281 ;; comma-list continuation lines: prev line indent takes precedence
11282 (if same-indent
11283 (setq main-pos same-indent))
11284
11285 ;; common special cases where we want to indent in from previous line
11286 (if (or (js2-indent-case-block-p)
11287 (js2-indent-objlit-arg-p parse-status))
11288 (setq main-pos basic-offset))
11289
11290 ;; if bouncing backwards, reverse positions list
11291 (if backwards
11292 (setq positions (reverse positions)))
11293
11294 ;; record whether we're already sitting on one of the alternatives
11295 (setq pos (member cur-indent positions))
11296
11297 (cond
11298 ;; case 0: we're one one of the alternatives and this is the
11299 ;; first time they've pressed TAB on this line (best-guess).
11300 ((and js2-mode-indent-ignore-first-tab
11301 pos
11302 ;; first time pressing TAB on this line?
11303 (not (eq js2-mode-last-indented-line current-line)))
11304 ;; do nothing
11305 (setq computed-pos nil))
11306 ;; case 1: only one computed position => use it
11307 ((null (cdr positions))
11308 (setq computed-pos 0))
11309 ;; case 2: not on any of the computed spots => use main spot
11310 ((not pos)
11311 (setq computed-pos (js2-position main-pos positions)))
11312 ;; case 3: on last position: cycle to first position
11313 ((null (cdr pos))
11314 (setq computed-pos 0))
11315 ;; case 4: on intermediate position: cycle to next position
11316 (t
11317 (setq computed-pos (js2-position (cl-second pos) positions))))
11318
11319 ;; see if any hooks want to indent; otherwise we do it
11320 (cl-loop with result = nil
11321 for hook in js2-indent-hook
11322 while (null result)
11323 do
11324 (setq result (funcall hook positions computed-pos))
11325 finally do
11326 (unless (or result (null computed-pos))
11327 (indent-line-to (nth computed-pos positions)))))
11328
11329 ;; finally
11330 (if js2-mode-indent-inhibit-undo
11331 (setq buffer-undo-list old-buffer-undo-list))
11332 ;; see commentary for `js2-mode-last-indented-line'
11333 (setq js2-mode-last-indented-line current-line))))
11334
11335 (defun js2-indent-bounce-backwards ()
11336 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11337 cycles between the computed indentation positions in reverse order."
11338 (interactive)
11339 (js2-indent-line t))
11340
11341 (defun js2-1-line-comment-continuation-p ()
11342 "Return t if we're in a 1-line comment continuation.
11343 If so, we don't ever want to use bounce-indent."
11344 (save-excursion
11345 (and (progn
11346 (forward-line 0)
11347 (looking-at "\\s-*//"))
11348 (progn
11349 (forward-line -1)
11350 (forward-line 0)
11351 (when (looking-at "\\s-*$")
11352 (js2-backward-sws)
11353 (forward-line 0))
11354 (looking-at "\\s-*//")))))
11355
11356 (defun js2-indent-line (&optional bounce-backwards)
11357 "Indent the current line as JavaScript source text."
11358 (interactive)
11359 (let (parse-status offset indent-col
11360 ;; Don't whine about errors/warnings when we're indenting.
11361 ;; This has to be set before calling parse-partial-sexp below.
11362 (inhibit-point-motion-hooks t))
11363 (setq parse-status (save-excursion
11364 (syntax-ppss (point-at-bol)))
11365 offset (- (point) (save-excursion
11366 (back-to-indentation)
11367 (point))))
11368 ;; Don't touch multiline strings.
11369 (unless (nth 3 parse-status)
11370 (js2-with-underscore-as-word-syntax
11371 (if (nth 4 parse-status)
11372 (js2-lineup-comment parse-status)
11373 (setq indent-col (js2-proper-indentation parse-status))
11374 ;; See comments below about `js2-mode-last-indented-line'.
11375 (cond
11376 ;; bounce-indenting is disabled during electric-key indent.
11377 ;; It doesn't work well on first line of buffer.
11378 ((and js2-bounce-indent-p
11379 (not (js2-same-line (point-min)))
11380 (not (js2-1-line-comment-continuation-p)))
11381 (js2-bounce-indent indent-col parse-status bounce-backwards))
11382 ;; just indent to the guesser's likely spot
11383 (t (indent-line-to indent-col))))
11384 (when (cl-plusp offset)
11385 (forward-char offset))))))
11386
11387 (defun js2-indent-region (start end)
11388 "Indent the region, but don't use bounce indenting."
11389 (let ((js2-bounce-indent-p nil)
11390 (indent-region-function nil)
11391 (after-change-functions (remq 'js2-mode-edit
11392 after-change-functions)))
11393 (indent-region start end nil) ; nil for byte-compiler
11394 (js2-mode-edit start end (- end start))))
11395
11396 (defvar js2-minor-mode-map
11397 (let ((map (make-sparse-keymap)))
11398 (define-key map (kbd "C-c C-`") #'js2-next-error)
11399 (define-key map [mouse-1] #'js2-mode-show-node)
11400 map)
11401 "Keymap used when `js2-minor-mode' is active.")
11402
11403 ;;;###autoload
11404 (define-minor-mode js2-minor-mode
11405 "Minor mode for running js2 as a background linter.
11406 This allows you to use a different major mode for JavaScript editing,
11407 such as `js-mode', while retaining the asynchronous error/warning
11408 highlighting features of `js2-mode'."
11409 :group 'js2-mode
11410 :lighter " js-lint"
11411 (if js2-minor-mode
11412 (js2-minor-mode-enter)
11413 (js2-minor-mode-exit)))
11414
11415 (defun js2-minor-mode-enter ()
11416 "Initialization for `js2-minor-mode'."
11417 (set (make-local-variable 'max-lisp-eval-depth)
11418 (max max-lisp-eval-depth 3000))
11419 (setq next-error-function #'js2-next-error)
11420 (js2-set-default-externs)
11421 ;; Experiment: make reparse-delay longer for longer files.
11422 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11423 (setq js2-idle-timer-delay
11424 (* js2-idle-timer-delay
11425 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11426 (setq js2-mode-buffer-dirty-p t
11427 js2-mode-parsing nil)
11428 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11429 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11430 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11431 (when js2-include-jslint-globals
11432 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11433 (run-hooks 'js2-init-hook)
11434 (js2-reparse))
11435
11436 (defun js2-minor-mode-exit ()
11437 "Turn off `js2-minor-mode'."
11438 (setq next-error-function nil)
11439 (remove-hook 'after-change-functions #'js2-mode-edit t)
11440 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11441 (when js2-mode-node-overlay
11442 (delete-overlay js2-mode-node-overlay)
11443 (setq js2-mode-node-overlay nil))
11444 (js2-remove-overlays)
11445 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11446 (setq js2-mode-ast nil))
11447
11448 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11449 (make-variable-buffer-local 'js2-source-buffer)
11450
11451 (cl-defun js2-display-error-list ()
11452 "Display a navigable buffer listing parse errors/warnings."
11453 (interactive)
11454 (unless (js2-have-errors-p)
11455 (message "No errors")
11456 (cl-return-from js2-display-error-list))
11457 (cl-labels ((annotate-list
11458 (lst type)
11459 "Add diagnostic TYPE and line number to errs list"
11460 (mapcar (lambda (err)
11461 (list err type (line-number-at-pos (nth 1 err))))
11462 lst)))
11463 (let* ((srcbuf (current-buffer))
11464 (errbuf (get-buffer-create "*js-lint*"))
11465 (errors (annotate-list
11466 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11467 'js2-error)) ; must be a valid face name
11468 (warnings (annotate-list
11469 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11470 'js2-warning)) ; must be a valid face name
11471 (all-errs (sort (append errors warnings)
11472 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11473 (with-current-buffer errbuf
11474 (let ((inhibit-read-only t))
11475 (erase-buffer)
11476 (dolist (err all-errs)
11477 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11478 (insert-text-button
11479 (format "line %d: %s" line (js2-get-msg msg-key))
11480 'face type
11481 'follow-link "\C-m"
11482 'action 'js2-error-buffer-jump
11483 'js2-msg (js2-get-msg msg-key)
11484 'js2-pos beg)
11485 (insert "\n"))))
11486 (js2-error-buffer-mode)
11487 (setq js2-source-buffer srcbuf)
11488 (pop-to-buffer errbuf)
11489 (goto-char (point-min))
11490 (unless (eobp)
11491 (js2-error-buffer-view))))))
11492
11493 (defvar js2-error-buffer-mode-map
11494 (let ((map (make-sparse-keymap)))
11495 (define-key map "n" #'js2-error-buffer-next)
11496 (define-key map "p" #'js2-error-buffer-prev)
11497 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11498 (define-key map "o" #'js2-error-buffer-view)
11499 (define-key map "q" #'js2-error-buffer-quit)
11500 map)
11501 "Keymap used for js2 diagnostics buffers.")
11502
11503 (defun js2-error-buffer-mode ()
11504 "Major mode for js2 diagnostics buffers.
11505 Selecting an error will jump it to the corresponding source-buffer error.
11506 \\{js2-error-buffer-mode-map}"
11507 (interactive)
11508 (setq major-mode 'js2-error-buffer-mode
11509 mode-name "JS Lint Diagnostics")
11510 (use-local-map js2-error-buffer-mode-map)
11511 (setq truncate-lines t)
11512 (set-buffer-modified-p nil)
11513 (setq buffer-read-only t)
11514 (run-hooks 'js2-error-buffer-mode-hook))
11515
11516 (defun js2-error-buffer-next ()
11517 "Move to next error and view it."
11518 (interactive)
11519 (when (zerop (forward-line 1))
11520 (js2-error-buffer-view)))
11521
11522 (defun js2-error-buffer-prev ()
11523 "Move to previous error and view it."
11524 (interactive)
11525 (when (zerop (forward-line -1))
11526 (js2-error-buffer-view)))
11527
11528 (defun js2-error-buffer-quit ()
11529 "Kill the current buffer."
11530 (interactive)
11531 (kill-buffer))
11532
11533 (defun js2-error-buffer-jump (&rest ignored)
11534 "Jump cursor to current error in source buffer."
11535 (interactive)
11536 (when (js2-error-buffer-view)
11537 (pop-to-buffer js2-source-buffer)))
11538
11539 (defun js2-error-buffer-view ()
11540 "Scroll source buffer to show error at current line."
11541 (interactive)
11542 (cond
11543 ((not (eq major-mode 'js2-error-buffer-mode))
11544 (message "Not in a js2 errors buffer"))
11545 ((not (buffer-live-p js2-source-buffer))
11546 (message "Source buffer has been killed"))
11547 ((not (wholenump (get-text-property (point) 'js2-pos)))
11548 (message "There does not seem to be an error here"))
11549 (t
11550 (let ((pos (get-text-property (point) 'js2-pos))
11551 (msg (get-text-property (point) 'js2-msg)))
11552 (save-selected-window
11553 (pop-to-buffer js2-source-buffer)
11554 (goto-char pos)
11555 (message msg))))))
11556
11557 ;;;###autoload
11558 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11559 ;; FIXME: Should derive from js-mode.
11560 "Major mode for editing JavaScript code."
11561 ;; Used by comment-region; don't change it.
11562 (set (make-local-variable 'comment-start) "//")
11563 (set (make-local-variable 'comment-end) "")
11564 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11565 (set (make-local-variable 'max-lisp-eval-depth)
11566 (max max-lisp-eval-depth 3000))
11567 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11568 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11569 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11570 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11571 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11572 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11573 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11574 ;; for characters inside regexp literals.
11575 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11576 ;; this is necessary to make `show-paren-function' work properly
11577 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11578 ;; needed for M-x rgrep, among other things
11579 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11580
11581 (set (make-local-variable 'electric-indent-chars)
11582 (append "{}()[]:;,*." electric-indent-chars))
11583 (set (make-local-variable 'electric-layout-rules)
11584 '((?\; . after) (?\{ . after) (?\} . before)))
11585
11586 ;; some variables needed by cc-engine for paragraph-fill, etc.
11587 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11588 c-comment-start-regexp "/[*/]\\|\\s|"
11589 c-line-comment-starter "//"
11590 c-paragraph-start js2-paragraph-start
11591 c-paragraph-separate "$"
11592 c-syntactic-ws-start js2-syntactic-ws-start
11593 c-syntactic-ws-end js2-syntactic-ws-end
11594 c-syntactic-eol js2-syntactic-eol)
11595
11596 (let ((c-buffer-is-cc-mode t))
11597 ;; Copied from `js-mode'. Also see Bug#6071.
11598 (make-local-variable 'paragraph-start)
11599 (make-local-variable 'paragraph-separate)
11600 (make-local-variable 'paragraph-ignore-fill-prefix)
11601 (make-local-variable 'adaptive-fill-mode)
11602 (make-local-variable 'adaptive-fill-regexp)
11603 (c-setup-paragraph-variables))
11604
11605 (setq font-lock-defaults '(nil t))
11606
11607 ;; Experiment: make reparse-delay longer for longer files.
11608 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11609 (setq js2-idle-timer-delay
11610 (* js2-idle-timer-delay
11611 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11612
11613 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11614 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11615 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11616 (setq next-error-function #'js2-next-error)
11617 (imenu-add-to-menubar (concat "IM-" mode-name))
11618 (add-to-invisibility-spec '(js2-outline . t))
11619 (set (make-local-variable 'line-move-ignore-invisible) t)
11620 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11621 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11622
11623 (setq js2-mode-functions-hidden nil
11624 js2-mode-comments-hidden nil
11625 js2-mode-buffer-dirty-p t
11626 js2-mode-parsing nil)
11627
11628 (js2-set-default-externs)
11629
11630 (when js2-include-jslint-globals
11631 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11632
11633 (run-hooks 'js2-init-hook)
11634
11635 (js2-reparse))
11636
11637 (defun js2-mode-exit ()
11638 "Exit `js2-mode' and clean up."
11639 (interactive)
11640 (when js2-mode-node-overlay
11641 (delete-overlay js2-mode-node-overlay)
11642 (setq js2-mode-node-overlay nil))
11643 (js2-remove-overlays)
11644 (setq js2-mode-ast nil)
11645 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11646 (remove-from-invisibility-spec '(js2-outline . t))
11647 (js2-mode-show-all)
11648 (with-silent-modifications
11649 (js2-clear-face (point-min) (point-max))))
11650
11651 (defun js2-mode-reset-timer ()
11652 "Cancel any existing parse timer and schedule a new one."
11653 (if js2-mode-parse-timer
11654 (cancel-timer js2-mode-parse-timer))
11655 (setq js2-mode-parsing nil)
11656 (let ((timer (timer-create)))
11657 (setq js2-mode-parse-timer timer)
11658 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11659 (timer-set-idle-time timer js2-idle-timer-delay)
11660 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11661 (timer-activate-when-idle timer nil)))
11662
11663 (defun js2-mode-idle-reparse (buffer)
11664 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11665 it to be reparsed when the buffer is selected."
11666 (cond ((eq buffer (current-buffer))
11667 (js2-reparse))
11668 ((buffer-live-p buffer)
11669 ;; reparse when the buffer is selected again
11670 (with-current-buffer buffer
11671 (add-hook 'window-configuration-change-hook
11672 #'js2-mode-idle-reparse-inner
11673 nil t)))))
11674
11675 (defun js2-mode-idle-reparse-inner ()
11676 (remove-hook 'window-configuration-change-hook
11677 #'js2-mode-idle-reparse-inner
11678 t)
11679 (js2-reparse))
11680
11681 (defun js2-mode-edit (_beg _end _len)
11682 "Schedule a new parse after buffer is edited.
11683 Buffer edit spans from BEG to END and is of length LEN."
11684 (setq js2-mode-buffer-dirty-p t)
11685 (js2-mode-hide-overlay)
11686 (js2-mode-reset-timer))
11687
11688 (defun js2-minor-mode-edit (_beg _end _len)
11689 "Callback for buffer edits in `js2-mode'.
11690 Schedules a new parse after buffer is edited.
11691 Buffer edit spans from BEG to END and is of length LEN."
11692 (setq js2-mode-buffer-dirty-p t)
11693 (js2-mode-hide-overlay)
11694 (js2-mode-reset-timer))
11695
11696 (defun js2-reparse (&optional force)
11697 "Re-parse current buffer after user finishes some data entry.
11698 If we get any user input while parsing, including cursor motion,
11699 we discard the parse and reschedule it. If FORCE is nil, then the
11700 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11701 (let (time
11702 interrupted-p
11703 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11704 (unless js2-mode-parsing
11705 (setq js2-mode-parsing t)
11706 (unwind-protect
11707 (when (or js2-mode-buffer-dirty-p force)
11708 (js2-remove-overlays)
11709 (setq js2-mode-buffer-dirty-p nil
11710 js2-mode-fontifications nil
11711 js2-mode-deferred-properties nil)
11712 (if js2-mode-verbose-parse-p
11713 (message "parsing..."))
11714 (setq time
11715 (js2-time
11716 (setq interrupted-p
11717 (catch 'interrupted
11718 (js2-parse)
11719 (with-silent-modifications
11720 ;; if parsing is interrupted, comments and regex
11721 ;; literals stay ignored by `parse-partial-sexp'
11722 (remove-text-properties (point-min) (point-max)
11723 '(syntax-table))
11724 (js2-mode-apply-deferred-properties)
11725 (js2-mode-remove-suppressed-warnings)
11726 (js2-mode-show-warnings)
11727 (js2-mode-show-errors)
11728 (if (>= js2-highlight-level 1)
11729 (js2-highlight-jsdoc js2-mode-ast)))
11730 nil))))
11731 (if interrupted-p
11732 (progn
11733 ;; unfinished parse => try again
11734 (setq js2-mode-buffer-dirty-p t)
11735 (js2-mode-reset-timer))
11736 (if js2-mode-verbose-parse-p
11737 (message "Parse time: %s" time))))
11738 (setq js2-mode-parsing nil)
11739 (unless interrupted-p
11740 (setq js2-mode-parse-timer nil))))))
11741
11742 (defun js2-mode-show-node (event)
11743 "Debugging aid: highlight selected AST node on mouse click."
11744 (interactive "e")
11745 (mouse-set-point event)
11746 (setq deactivate-mark t)
11747 (when js2-mode-show-overlay
11748 (let ((node (js2-node-at-point))
11749 beg end)
11750 (if (null node)
11751 (message "No node found at location %s" (point))
11752 (setq beg (js2-node-abs-pos node)
11753 end (+ beg (js2-node-len node)))
11754 (if js2-mode-node-overlay
11755 (move-overlay js2-mode-node-overlay beg end)
11756 (setq js2-mode-node-overlay (make-overlay beg end))
11757 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11758 (with-silent-modifications
11759 (if (fboundp 'cursor-sensor-mode)
11760 (put-text-property beg end 'cursor-sensor-functions
11761 '(js2-mode-hide-overlay))
11762 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11763 (message "%s, parent: %s"
11764 (js2-node-short-name node)
11765 (if (js2-node-parent node)
11766 (js2-node-short-name (js2-node-parent node))
11767 "nil"))))))
11768
11769 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11770 "Remove the debugging overlay when point moves.
11771 ARG1, ARG2 and ARG3 have different values depending on whether this function
11772 was found on `point-left' or in `cursor-sensor-functions'."
11773 (when js2-mode-node-overlay
11774 (let ((beg (overlay-start js2-mode-node-overlay))
11775 (end (overlay-end js2-mode-node-overlay))
11776 (p2 (if (windowp arg1)
11777 ;; Called from cursor-sensor-functions.
11778 (window-point arg1)
11779 ;; Called from point-left.
11780 arg2)))
11781 ;; Sometimes we're called spuriously.
11782 (unless (and p2
11783 (>= p2 beg)
11784 (<= p2 end))
11785 (with-silent-modifications
11786 (remove-text-properties beg end
11787 '(point-left nil cursor-sensor-functions)))
11788 (delete-overlay js2-mode-node-overlay)
11789 (setq js2-mode-node-overlay nil)))))
11790
11791 (defun js2-mode-reset ()
11792 "Debugging helper: reset everything."
11793 (interactive)
11794 (js2-mode-exit)
11795 (js2-mode))
11796
11797 (defun js2-mode-show-warn-or-err (e face)
11798 "Highlight a warning or error E with FACE.
11799 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11800 The last element is optional. When present, use instead of FACE."
11801 (let* ((key (cl-first e))
11802 (beg (cl-second e))
11803 (end (+ beg (cl-third e)))
11804 ;; Don't inadvertently go out of bounds.
11805 (beg (max (point-min) (min beg (point-max))))
11806 (end (max (point-min) (min end (point-max))))
11807 (ovl (make-overlay beg end)))
11808 ;; FIXME: Why a mix of overlays and text-properties?
11809 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11810 (overlay-put ovl 'js2-error t)
11811 (put-text-property beg end 'help-echo (js2-get-msg key))
11812 (if (fboundp 'cursor-sensor-mode)
11813 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11814 (put-text-property beg end 'point-entered #'js2-echo-error))))
11815
11816 (defun js2-remove-overlays ()
11817 "Remove overlays from buffer that have a `js2-error' property."
11818 (let ((beg (point-min))
11819 (end (point-max)))
11820 (save-excursion
11821 (dolist (o (overlays-in beg end))
11822 (when (overlay-get o 'js2-error)
11823 (delete-overlay o))))))
11824
11825 (defun js2-mode-apply-deferred-properties ()
11826 "Apply fontifications and other text properties recorded during parsing."
11827 (when (cl-plusp js2-highlight-level)
11828 ;; We defer clearing faces as long as possible to eliminate flashing.
11829 (js2-clear-face (point-min) (point-max))
11830 ;; Have to reverse the recorded fontifications list so that errors
11831 ;; and warnings overwrite the normal fontifications.
11832 (dolist (f (nreverse js2-mode-fontifications))
11833 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11834 (setq js2-mode-fontifications nil))
11835 (dolist (p js2-mode-deferred-properties)
11836 (apply #'put-text-property p))
11837 (setq js2-mode-deferred-properties nil))
11838
11839 (defun js2-mode-show-errors ()
11840 "Highlight syntax errors."
11841 (when js2-mode-show-parse-errors
11842 (dolist (e (js2-ast-root-errors js2-mode-ast))
11843 (js2-mode-show-warn-or-err e 'js2-error))))
11844
11845 (defun js2-mode-remove-suppressed-warnings ()
11846 "Take suppressed warnings out of the AST warnings list.
11847 This ensures that the counts and `next-error' are correct."
11848 (setf (js2-ast-root-warnings js2-mode-ast)
11849 (js2-delete-if
11850 (lambda (e)
11851 (let ((key (caar e)))
11852 (or
11853 (and (not js2-strict-trailing-comma-warning)
11854 (string-match "trailing\\.comma" key))
11855 (and (not js2-strict-cond-assign-warning)
11856 (string= key "msg.equal.as.assign"))
11857 (and js2-missing-semi-one-line-override
11858 (string= key "msg.missing.semi")
11859 (let* ((beg (cl-second e))
11860 (node (js2-node-at-point beg))
11861 (fn (js2-mode-find-parent-fn node))
11862 (body (and fn (js2-function-node-body fn)))
11863 (lc (and body (js2-node-abs-pos body)))
11864 (rc (and lc (+ lc (js2-node-len body)))))
11865 (and fn
11866 (or (null body)
11867 (save-excursion
11868 (goto-char beg)
11869 (and (js2-same-line lc)
11870 (js2-same-line rc))))))))))
11871 (js2-ast-root-warnings js2-mode-ast))))
11872
11873 (defun js2-mode-show-warnings ()
11874 "Highlight strict-mode warnings."
11875 (when js2-mode-show-strict-warnings
11876 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11877 (js2-mode-show-warn-or-err e 'js2-warning))))
11878
11879 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11880 "Called by point-motion hooks.
11881 ARG1, ARG2 and ARG3 have different values depending on whether this function
11882 was found on `point-entered' or in `cursor-sensor-functions'."
11883 (let* ((new-point (if (windowp arg1)
11884 ;; Called from cursor-sensor-functions.
11885 (window-point arg1)
11886 ;; Called from point-left.
11887 arg2))
11888 (msg (get-text-property new-point 'help-echo)))
11889 (when (and (stringp msg)
11890 (not (active-minibuffer-window))
11891 (not (current-message)))
11892 (message msg))))
11893
11894 (defun js2-line-break (&optional _soft)
11895 "Break line at point and indent, continuing comment if within one.
11896 If inside a string, and `js2-concat-multiline-strings' is not
11897 nil, turn it into concatenation."
11898 (interactive)
11899 (let ((parse-status (syntax-ppss)))
11900 (cond
11901 ;; Check if we're inside a string.
11902 ((nth 3 parse-status)
11903 (if js2-concat-multiline-strings
11904 (js2-mode-split-string parse-status)
11905 (insert "\n")))
11906 ;; Check if inside a block comment.
11907 ((nth 4 parse-status)
11908 (js2-mode-extend-comment (nth 8 parse-status)))
11909 (t
11910 (newline-and-indent)))))
11911
11912 (defun js2-mode-split-string (parse-status)
11913 "Turn a newline in mid-string into a string concatenation.
11914 PARSE-STATUS is as documented in `parse-partial-sexp'."
11915 (let* ((quote-char (nth 3 parse-status))
11916 (at-eol (eq js2-concat-multiline-strings 'eol)))
11917 (insert quote-char)
11918 (insert (if at-eol " +\n" "\n"))
11919 (unless at-eol
11920 (insert "+ "))
11921 (js2-indent-line)
11922 (insert quote-char)
11923 (when (eolp)
11924 (insert quote-char)
11925 (backward-char 1))))
11926
11927 (defun js2-mode-extend-comment (start-pos)
11928 "Indent the line and, when inside a comment block, add comment prefix."
11929 (let (star single col first-line needs-close)
11930 (save-excursion
11931 (back-to-indentation)
11932 (when (< (point) start-pos)
11933 (goto-char start-pos))
11934 (cond
11935 ((looking-at "\\*[^/]")
11936 (setq star t
11937 col (current-column)))
11938 ((looking-at "/\\*")
11939 (setq star t
11940 first-line t
11941 col (1+ (current-column))))
11942 ((looking-at "//")
11943 (setq single t
11944 col (current-column)))))
11945 ;; Heuristic for whether we need to close the comment:
11946 ;; if we've got a parse error here, assume it's an unterminated
11947 ;; comment.
11948 (setq needs-close
11949 (or
11950 (get-char-property (1- (point)) 'js2-error)
11951 ;; The heuristic above doesn't work well when we're
11952 ;; creating a comment and there's another one downstream,
11953 ;; as our parser thinks this one ends at the end of the
11954 ;; next one. (You can have a /* inside a js block comment.)
11955 ;; So just close it if the next non-ws char isn't a *.
11956 (and first-line
11957 (eolp)
11958 (save-excursion
11959 (skip-chars-forward " \t\r\n")
11960 (not (eq (char-after) ?*))))))
11961 (delete-horizontal-space)
11962 (insert "\n")
11963 (cond
11964 (star
11965 (indent-to col)
11966 (insert "* ")
11967 (if (and first-line needs-close)
11968 (save-excursion
11969 (insert "\n")
11970 (indent-to col)
11971 (insert "*/"))))
11972 ((and single
11973 (save-excursion
11974 (and (zerop (forward-line 1))
11975 (looking-at "\\s-*//"))))
11976 (indent-to col)
11977 (insert "// ")))
11978 ;; Don't need to extend the comment after all.
11979 (js2-indent-line)))
11980
11981 (defun js2-beginning-of-line ()
11982 "Toggle point between bol and first non-whitespace char in line.
11983 Also moves past comment delimiters when inside comments."
11984 (interactive)
11985 (let (node)
11986 (cond
11987 ((bolp)
11988 (back-to-indentation))
11989 ((looking-at "//")
11990 (skip-chars-forward "/ \t"))
11991 ((and (eq (char-after) ?*)
11992 (setq node (js2-comment-at-point))
11993 (memq (js2-comment-node-format node) '(jsdoc block))
11994 (save-excursion
11995 (skip-chars-backward " \t")
11996 (bolp)))
11997 (skip-chars-forward "\* \t"))
11998 (t
11999 (goto-char (point-at-bol))))))
12000
12001 (defun js2-end-of-line ()
12002 "Toggle point between eol and last non-whitespace char in line."
12003 (interactive)
12004 (if (eolp)
12005 (skip-chars-backward " \t")
12006 (goto-char (point-at-eol))))
12007
12008 (defun js2-mode-wait-for-parse (callback)
12009 "Invoke CALLBACK when parsing is finished.
12010 If parsing is already finished, calls CALLBACK immediately."
12011 (if (not js2-mode-buffer-dirty-p)
12012 (funcall callback)
12013 (push callback js2-mode-pending-parse-callbacks)
12014 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
12015
12016 (defun js2-mode-parse-finished ()
12017 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
12018 ;; We can't let errors propagate up, since it prevents the
12019 ;; `js2-parse' method from completing normally and returning
12020 ;; the ast, which makes things mysteriously not work right.
12021 (unwind-protect
12022 (dolist (cb js2-mode-pending-parse-callbacks)
12023 (condition-case err
12024 (funcall cb)
12025 (error (message "%s" err))))
12026 (setq js2-mode-pending-parse-callbacks nil)))
12027
12028 (defun js2-mode-flag-region (from to flag)
12029 "Hide or show text from FROM to TO, according to FLAG.
12030 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
12031 Returns the created overlay if FLAG is non-nil."
12032 (remove-overlays from to 'invisible 'js2-outline)
12033 (when flag
12034 (let ((o (make-overlay from to)))
12035 (overlay-put o 'invisible 'js2-outline)
12036 (overlay-put o 'isearch-open-invisible
12037 'js2-isearch-open-invisible)
12038 o)))
12039
12040 ;; Function to be set as an outline-isearch-open-invisible' property
12041 ;; to the overlay that makes the outline invisible (see
12042 ;; `js2-mode-flag-region').
12043 (defun js2-isearch-open-invisible (_overlay)
12044 ;; We rely on the fact that isearch places point on the matched text.
12045 (js2-mode-show-element))
12046
12047 (defun js2-mode-invisible-overlay-bounds (&optional pos)
12048 "Return cons cell of bounds of folding overlay at POS.
12049 Returns nil if not found."
12050 (let ((overlays (overlays-at (or pos (point))))
12051 o)
12052 (while (and overlays
12053 (not o))
12054 (if (overlay-get (car overlays) 'invisible)
12055 (setq o (car overlays))
12056 (setq overlays (cdr overlays))))
12057 (if o
12058 (cons (overlay-start o) (overlay-end o)))))
12059
12060 (defun js2-mode-function-at-point (&optional pos)
12061 "Return the innermost function node enclosing current point.
12062 Returns nil if point is not in a function."
12063 (let ((node (js2-node-at-point pos)))
12064 (while (and node (not (js2-function-node-p node)))
12065 (setq node (js2-node-parent node)))
12066 (if (js2-function-node-p node)
12067 node)))
12068
12069 (defun js2-mode-toggle-element ()
12070 "Hide or show the foldable element at the point."
12071 (interactive)
12072 (let (comment fn pos)
12073 (save-excursion
12074 (cond
12075 ;; /* ... */ comment?
12076 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
12077 (if (js2-mode-invisible-overlay-bounds
12078 (setq pos (+ 3 (js2-node-abs-pos comment))))
12079 (progn
12080 (goto-char pos)
12081 (js2-mode-show-element))
12082 (js2-mode-hide-element)))
12083 ;; //-comment?
12084 ((save-excursion
12085 (back-to-indentation)
12086 (looking-at js2-mode-//-comment-re))
12087 (js2-mode-toggle-//-comment))
12088 ;; function?
12089 ((setq fn (js2-mode-function-at-point))
12090 (setq pos (and (js2-function-node-body fn)
12091 (js2-node-abs-pos (js2-function-node-body fn))))
12092 (goto-char (1+ pos))
12093 (if (js2-mode-invisible-overlay-bounds)
12094 (js2-mode-show-element)
12095 (js2-mode-hide-element)))
12096 (t
12097 (message "Nothing at point to hide or show"))))))
12098
12099 (defun js2-mode-hide-element ()
12100 "Fold/hide contents of a block, showing ellipses.
12101 Show the hidden text with \\[js2-mode-show-element]."
12102 (interactive)
12103 (if js2-mode-buffer-dirty-p
12104 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12105 (let (node body beg end)
12106 (cond
12107 ((js2-mode-invisible-overlay-bounds)
12108 (message "already hidden"))
12109 (t
12110 (setq node (js2-node-at-point))
12111 (cond
12112 ((js2-block-comment-p node)
12113 (js2-mode-hide-comment node))
12114 (t
12115 (while (and node (not (js2-function-node-p node)))
12116 (setq node (js2-node-parent node)))
12117 (if (and node
12118 (setq body (js2-function-node-body node)))
12119 (progn
12120 (setq beg (js2-node-abs-pos body)
12121 end (+ beg (js2-node-len body)))
12122 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12123 (message "No collapsable element found at point"))))))))
12124
12125 (defun js2-mode-show-element ()
12126 "Show the hidden element at current point."
12127 (interactive)
12128 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12129 (if bounds
12130 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12131 (message "Nothing to un-hide"))))
12132
12133 (defun js2-mode-show-all ()
12134 "Show all of the text in the buffer."
12135 (interactive)
12136 (js2-mode-flag-region (point-min) (point-max) nil))
12137
12138 (defun js2-mode-toggle-hide-functions ()
12139 (interactive)
12140 (if js2-mode-functions-hidden
12141 (js2-mode-show-functions)
12142 (js2-mode-hide-functions)))
12143
12144 (defun js2-mode-hide-functions ()
12145 "Hides all non-nested function bodies in the buffer.
12146 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12147 to open an individual entry."
12148 (interactive)
12149 (if js2-mode-buffer-dirty-p
12150 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12151 (if (null js2-mode-ast)
12152 (message "Oops - parsing failed")
12153 (setq js2-mode-functions-hidden t)
12154 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12155
12156 (defun js2-mode-function-hider (n endp)
12157 (when (not endp)
12158 (let ((tt (js2-node-type n))
12159 body beg end)
12160 (cond
12161 ((and (= tt js2-FUNCTION)
12162 (setq body (js2-function-node-body n)))
12163 (setq beg (js2-node-abs-pos body)
12164 end (+ beg (js2-node-len body)))
12165 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12166 nil) ; don't process children of function
12167 (t
12168 t))))) ; keep processing other AST nodes
12169
12170 (defun js2-mode-show-functions ()
12171 "Un-hide any folded function bodies in the buffer."
12172 (interactive)
12173 (setq js2-mode-functions-hidden nil)
12174 (save-excursion
12175 (goto-char (point-min))
12176 (while (/= (goto-char (next-overlay-change (point)))
12177 (point-max))
12178 (dolist (o (overlays-at (point)))
12179 (when (and (overlay-get o 'invisible)
12180 (not (overlay-get o 'comment)))
12181 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12182
12183 (defun js2-mode-hide-comment (n)
12184 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12185 3 ; /**
12186 2)) ; /*
12187 (beg (+ (js2-node-abs-pos n) head))
12188 (end (- (+ beg (js2-node-len n)) head 2))
12189 (o (js2-mode-flag-region beg end 'hide)))
12190 (overlay-put o 'comment t)))
12191
12192 (defun js2-mode-toggle-hide-comments ()
12193 "Folds all block comments in the buffer.
12194 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12195 to open an individual entry."
12196 (interactive)
12197 (if js2-mode-comments-hidden
12198 (js2-mode-show-comments)
12199 (js2-mode-hide-comments)))
12200
12201 (defun js2-mode-hide-comments ()
12202 (interactive)
12203 (if js2-mode-buffer-dirty-p
12204 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12205 (if (null js2-mode-ast)
12206 (message "Oops - parsing failed")
12207 (setq js2-mode-comments-hidden t)
12208 (dolist (n (js2-ast-root-comments js2-mode-ast))
12209 (when (js2-block-comment-p n)
12210 (js2-mode-hide-comment n)))
12211 (js2-mode-hide-//-comments)))
12212
12213 (defun js2-mode-extend-//-comment (direction)
12214 "Find start or end of a block of similar //-comment lines.
12215 DIRECTION is -1 to look back, 1 to look forward.
12216 INDENT is the indentation level to match.
12217 Returns the end-of-line position of the furthest adjacent
12218 //-comment line with the same indentation as the current line.
12219 If there is no such matching line, returns current end of line."
12220 (let ((pos (point-at-eol))
12221 (indent (current-indentation)))
12222 (save-excursion
12223 (while (and (zerop (forward-line direction))
12224 (looking-at js2-mode-//-comment-re)
12225 (eq indent (length (match-string 1))))
12226 (setq pos (point-at-eol)))
12227 pos)))
12228
12229 (defun js2-mode-hide-//-comments ()
12230 "Fold adjacent 1-line comments, showing only snippet of first one."
12231 (let (beg end)
12232 (save-excursion
12233 (goto-char (point-min))
12234 (while (re-search-forward js2-mode-//-comment-re nil t)
12235 (setq beg (point)
12236 end (js2-mode-extend-//-comment 1))
12237 (unless (eq beg end)
12238 (overlay-put (js2-mode-flag-region beg end 'hide)
12239 'comment t))
12240 (goto-char end)
12241 (forward-char 1)))))
12242
12243 (defun js2-mode-toggle-//-comment ()
12244 "Fold or un-fold any multi-line //-comment at point.
12245 Caller should have determined that this line starts with a //-comment."
12246 (let* ((beg (point-at-eol))
12247 (end beg))
12248 (save-excursion
12249 (goto-char end)
12250 (if (js2-mode-invisible-overlay-bounds)
12251 (js2-mode-show-element)
12252 ;; else hide the comment
12253 (setq beg (js2-mode-extend-//-comment -1)
12254 end (js2-mode-extend-//-comment 1))
12255 (unless (eq beg end)
12256 (overlay-put (js2-mode-flag-region beg end 'hide)
12257 'comment t))))))
12258
12259 (defun js2-mode-show-comments ()
12260 "Un-hide any hidden comments, leaving other hidden elements alone."
12261 (interactive)
12262 (setq js2-mode-comments-hidden nil)
12263 (save-excursion
12264 (goto-char (point-min))
12265 (while (/= (goto-char (next-overlay-change (point)))
12266 (point-max))
12267 (dolist (o (overlays-at (point)))
12268 (when (overlay-get o 'comment)
12269 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12270
12271 (defun js2-mode-display-warnings-and-errors ()
12272 "Turn on display of warnings and errors."
12273 (interactive)
12274 (setq js2-mode-show-parse-errors t
12275 js2-mode-show-strict-warnings t)
12276 (js2-reparse 'force))
12277
12278 (defun js2-mode-hide-warnings-and-errors ()
12279 "Turn off display of warnings and errors."
12280 (interactive)
12281 (setq js2-mode-show-parse-errors nil
12282 js2-mode-show-strict-warnings nil)
12283 (js2-reparse 'force))
12284
12285 (defun js2-mode-toggle-warnings-and-errors ()
12286 "Toggle the display of warnings and errors.
12287 Some users don't like having warnings/errors reported while they type."
12288 (interactive)
12289 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12290 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12291 (if (called-interactively-p 'any)
12292 (message "warnings and errors %s"
12293 (if js2-mode-show-parse-errors
12294 "enabled"
12295 "disabled")))
12296 (js2-reparse 'force))
12297
12298 (defun js2-mode-customize ()
12299 (interactive)
12300 (customize-group 'js2-mode))
12301
12302 (defun js2-mode-forward-sexp (&optional arg)
12303 "Move forward across one statement or balanced expression.
12304 With ARG, do it that many times. Negative arg -N means
12305 move backward across N balanced expressions."
12306 (interactive "p")
12307 (setq arg (or arg 1))
12308 (save-restriction
12309 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12310 (js2-reparse)
12311 (let (forward-sexp-function
12312 node (start (point)) pos lp rp child)
12313 (cond
12314 ;; backward-sexp
12315 ;; could probably make this better for some cases:
12316 ;; - if in statement block (e.g. function body), go to parent
12317 ;; - infix exprs like (foo in bar) - maybe go to beginning
12318 ;; of infix expr if in the right-side expression?
12319 ((and arg (cl-minusp arg))
12320 (dotimes (_ (- arg))
12321 (js2-backward-sws)
12322 (forward-char -1) ; Enter the node we backed up to.
12323 (when (setq node (js2-node-at-point (point) t))
12324 (setq pos (js2-node-abs-pos node))
12325 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12326 (setq lp (car parens)
12327 rp (cdr parens)))
12328 (when (and lp (> start lp))
12329 (if (and rp (<= start rp))
12330 ;; Between parens, check if there's a child node we can jump.
12331 (when (setq child (js2-node-closest-child node (point) lp t))
12332 (setq pos (js2-node-abs-pos child)))
12333 ;; Before both parens.
12334 (setq pos lp)))
12335 (let ((state (parse-partial-sexp start pos)))
12336 (goto-char (if (not (zerop (car state)))
12337 ;; Stumble at the unbalanced paren if < 0, or
12338 ;; jump a bit further if > 0.
12339 (scan-sexps start -1)
12340 pos))))
12341 (unless pos (goto-char (point-min)))))
12342 (t
12343 ;; forward-sexp
12344 (dotimes (_ arg)
12345 (js2-forward-sws)
12346 (when (setq node (js2-node-at-point (point) t))
12347 (setq pos (js2-node-abs-pos node))
12348 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12349 (setq lp (car parens)
12350 rp (cdr parens)))
12351 (or
12352 (when (and rp (<= start rp))
12353 (if (> start lp)
12354 (when (setq child (js2-node-closest-child node (point) rp))
12355 (setq pos (js2-node-abs-end child)))
12356 (setq pos (1+ rp))))
12357 ;; No parens or child nodes, looks for the end of the current node.
12358 (cl-incf pos (js2-node-len
12359 (if (js2-expr-stmt-node-p (js2-node-parent node))
12360 ;; Stop after the semicolon.
12361 (js2-node-parent node)
12362 node))))
12363 (let ((state (save-excursion (parse-partial-sexp start pos))))
12364 (goto-char (if (not (zerop (car state)))
12365 (scan-sexps start 1)
12366 pos))))
12367 (unless pos (goto-char (point-max)))))))))
12368
12369 (defun js2-mode-forward-sexp-parens (node abs-pos)
12370 "Return a cons cell with positions of main parens in NODE."
12371 (cond
12372 ((or (js2-array-node-p node)
12373 (js2-object-node-p node)
12374 (js2-comp-node-p node)
12375 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12376 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12377 ((js2-paren-expr-node-p node)
12378 (let ((lp (js2-node-lp node))
12379 (rp (js2-node-rp node)))
12380 (cons (when lp (+ abs-pos lp))
12381 (when rp (+ abs-pos rp)))))))
12382
12383 (defun js2-node-closest-child (parent point limit &optional before)
12384 (let* ((parent-pos (js2-node-abs-pos parent))
12385 (rpoint (- point parent-pos))
12386 (rlimit (- limit parent-pos))
12387 (min (min rpoint rlimit))
12388 (max (max rpoint rlimit))
12389 found)
12390 (catch 'done
12391 (js2-visit-ast
12392 parent
12393 (lambda (node _end-p)
12394 (if (eq node parent)
12395 t
12396 (let ((pos (js2-node-pos node)) ;; Both relative values.
12397 (end (+ (js2-node-pos node) (js2-node-len node))))
12398 (when (and (>= pos min) (<= end max)
12399 (if before (< pos rpoint) (> end rpoint)))
12400 (setq found node))
12401 (when (> end rpoint)
12402 (throw 'done nil)))
12403 nil))))
12404 found))
12405
12406 (defun js2-errors ()
12407 "Return a list of errors found."
12408 (and js2-mode-ast
12409 (js2-ast-root-errors js2-mode-ast)))
12410
12411 (defun js2-warnings ()
12412 "Return a list of warnings found."
12413 (and js2-mode-ast
12414 (js2-ast-root-warnings js2-mode-ast)))
12415
12416 (defun js2-have-errors-p ()
12417 "Return non-nil if any parse errors or warnings were found."
12418 (or (js2-errors) (js2-warnings)))
12419
12420 (defun js2-errors-and-warnings ()
12421 "Return a copy of the concatenated errors and warnings lists.
12422 They are appended: first the errors, then the warnings.
12423 Entries are of the form (MSG BEG END)."
12424 (when js2-mode-ast
12425 (append (js2-ast-root-errors js2-mode-ast)
12426 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12427
12428 (defun js2-next-error (&optional arg reset)
12429 "Move to next parse error.
12430 Typically invoked via \\[next-error].
12431 ARG is the number of errors, forward or backward, to move.
12432 RESET means start over from the beginning."
12433 (interactive "p")
12434 (if (not (or (js2-errors) (js2-warnings)))
12435 (message "No errors")
12436 (when reset
12437 (goto-char (point-min)))
12438 (let* ((errs (js2-errors-and-warnings))
12439 (continue t)
12440 (start (point))
12441 (count (or arg 1))
12442 (backward (cl-minusp count))
12443 (sorter (if backward '> '<))
12444 (stopper (if backward '< '>))
12445 (count (abs count))
12446 all-errs err)
12447 ;; Sort by start position.
12448 (setq errs (sort errs (lambda (e1 e2)
12449 (funcall sorter (cl-second e1) (cl-second e2))))
12450 all-errs errs)
12451 ;; Find nth error with pos > start.
12452 (while (and errs continue)
12453 (when (funcall stopper (cl-cadar errs) start)
12454 (setq err (car errs))
12455 (if (zerop (cl-decf count))
12456 (setq continue nil)))
12457 (setq errs (cdr errs)))
12458 ;; Clear for `js2-echo-error'.
12459 (message nil)
12460 (if err
12461 (goto-char (cl-second err))
12462 ;; Wrap around to first error.
12463 (goto-char (cl-second (car all-errs)))
12464 ;; If we were already on it, echo msg again.
12465 (if (= (point) start)
12466 (js2-echo-error (point) (point)))))))
12467
12468 (defun js2-down-mouse-3 ()
12469 "Make right-click move the point to the click location.
12470 This makes right-click context menu operations a bit more intuitive.
12471 The point will not move if the region is active, however, to avoid
12472 destroying the region selection."
12473 (interactive)
12474 (when (and js2-move-point-on-right-click
12475 (not mark-active))
12476 (let ((e last-input-event))
12477 (ignore-errors
12478 (goto-char (cl-cadadr e))))))
12479
12480 (defun js2-mode-create-imenu-index ()
12481 "Return an alist for `imenu--index-alist'."
12482 ;; This is built up in `js2-parse-record-imenu' during parsing.
12483 (when js2-mode-ast
12484 ;; if we have an ast but no recorder, they're requesting a rescan
12485 (unless js2-imenu-recorder
12486 (js2-reparse 'force))
12487 (prog1
12488 (js2-build-imenu-index)
12489 (setq js2-imenu-recorder nil
12490 js2-imenu-function-map nil))))
12491
12492 (defun js2-mode-find-tag ()
12493 "Replacement for `find-tag-default'.
12494 `find-tag-default' returns a ridiculous answer inside comments."
12495 (let (beg end)
12496 (js2-with-underscore-as-word-syntax
12497 (save-excursion
12498 (if (and (not (looking-at "[[:alnum:]_$]"))
12499 (looking-back "[[:alnum:]_$]"))
12500 (setq beg (progn (forward-word -1) (point))
12501 end (progn (forward-word 1) (point)))
12502 (setq beg (progn (forward-word 1) (point))
12503 end (progn (forward-word -1) (point))))
12504 (replace-regexp-in-string
12505 "[\"']" ""
12506 (buffer-substring-no-properties beg end))))))
12507
12508 (defun js2-mode-forward-sibling ()
12509 "Move to the end of the sibling following point in parent.
12510 Returns non-nil if successful, or nil if there was no following sibling."
12511 (let* ((node (js2-node-at-point))
12512 (parent (js2-mode-find-enclosing-fn node))
12513 sib)
12514 (when (setq sib (js2-node-find-child-after (point) parent))
12515 (goto-char (+ (js2-node-abs-pos sib)
12516 (js2-node-len sib))))))
12517
12518 (defun js2-mode-backward-sibling ()
12519 "Move to the beginning of the sibling node preceding point in parent.
12520 Parent is defined as the enclosing script or function."
12521 (let* ((node (js2-node-at-point))
12522 (parent (js2-mode-find-enclosing-fn node))
12523 sib)
12524 (when (setq sib (js2-node-find-child-before (point) parent))
12525 (goto-char (js2-node-abs-pos sib)))))
12526
12527 (defun js2-beginning-of-defun (&optional arg)
12528 "Go to line on which current function starts, and return t on success.
12529 If we're not in a function or already at the beginning of one, go
12530 to beginning of previous script-level element.
12531 With ARG N, do that N times. If N is negative, move forward."
12532 (setq arg (or arg 1))
12533 (if (cl-plusp arg)
12534 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12535 (when (cond
12536 ((js2-function-node-p parent)
12537 (goto-char (js2-node-abs-pos parent)))
12538 (t
12539 (js2-mode-backward-sibling)))
12540 (if (> arg 1)
12541 (js2-beginning-of-defun (1- arg))
12542 t)))
12543 (when (js2-end-of-defun)
12544 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12545
12546 (defun js2-end-of-defun ()
12547 "Go to the char after the last position of the current function
12548 or script-level element."
12549 (let* ((node (js2-node-at-point))
12550 (parent (or (and (js2-function-node-p node) node)
12551 (js2-node-parent-script-or-fn node)))
12552 script)
12553 (unless (js2-function-node-p parent)
12554 ;; Use current script-level node, or, if none, the next one.
12555 (setq script (or parent node)
12556 parent (js2-node-find-child-before (point) script))
12557 (when (or (null parent)
12558 (>= (point) (+ (js2-node-abs-pos parent)
12559 (js2-node-len parent))))
12560 (setq parent (js2-node-find-child-after (point) script))))
12561 (when parent
12562 (goto-char (+ (js2-node-abs-pos parent)
12563 (js2-node-len parent))))))
12564
12565 (defun js2-mark-defun (&optional allow-extend)
12566 "Put mark at end of this function, point at beginning.
12567 The function marked is the one that contains point.
12568
12569 Interactively, if this command is repeated,
12570 or (in Transient Mark mode) if the mark is active,
12571 it marks the next defun after the ones already marked."
12572 (interactive "p")
12573 (let (extended)
12574 (when (and allow-extend
12575 (or (and (eq last-command this-command) (mark t))
12576 (and transient-mark-mode mark-active)))
12577 (let ((sib (save-excursion
12578 (goto-char (mark))
12579 (if (js2-mode-forward-sibling)
12580 (point)))))
12581 (if sib
12582 (progn
12583 (set-mark sib)
12584 (setq extended t))
12585 ;; no more siblings - try extending to enclosing node
12586 (goto-char (mark t)))))
12587 (when (not extended)
12588 (let ((node (js2-node-at-point (point) t)) ; skip comments
12589 ast fn stmt parent beg end)
12590 (when (js2-ast-root-p node)
12591 (setq ast node
12592 node (or (js2-node-find-child-after (point) node)
12593 (js2-node-find-child-before (point) node))))
12594 ;; only mark whole buffer if we can't find any children
12595 (if (null node)
12596 (setq node ast))
12597 (if (js2-function-node-p node)
12598 (setq parent node)
12599 (setq fn (js2-mode-find-enclosing-fn node)
12600 stmt (if (or (null fn)
12601 (js2-ast-root-p fn))
12602 (js2-mode-find-first-stmt node))
12603 parent (or stmt fn)))
12604 (setq beg (js2-node-abs-pos parent)
12605 end (+ beg (js2-node-len parent)))
12606 (push-mark beg)
12607 (goto-char end)
12608 (exchange-point-and-mark)))))
12609
12610 (defun js2-narrow-to-defun ()
12611 "Narrow to the function enclosing point."
12612 (interactive)
12613 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12614 (fn (if (js2-script-node-p node)
12615 node
12616 (js2-mode-find-enclosing-fn node)))
12617 (beg (js2-node-abs-pos fn)))
12618 (unless (js2-ast-root-p fn)
12619 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12620
12621 (provide 'js2-mode)
12622
12623 ;;; js2-mode.el ends here