]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Actually remove the macro
[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: 20150713
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (require 'cl-lib)
89 (require 'imenu)
90 (require '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 querystring))
193 "Node.js externs.
194 Set `js2-include-node-externs' to t to include them.")
195
196 (defvar js2-typed-array-externs
197 (mapcar 'symbol-name
198 '(ArrayBuffer Uint8ClampedArray DataView
199 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
200 Float32Array Float64Array))
201 "Khronos typed array externs. Available in most modern browsers and
202 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
203 are enabled, these will also be included.")
204
205 (defvar js2-harmony-externs
206 (mapcar 'symbol-name
207 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
208 "ES6 externs. If `js2-include-browser-externs' is enabled and
209 `js2-language-version' is sufficiently high, these will be included.")
210
211 ;;; Variables
212
213 (defun js2-mark-safe-local (name pred)
214 "Make the variable NAME buffer-local and mark it as safe file-local
215 variable with predicate PRED."
216 (make-variable-buffer-local name)
217 (put name 'safe-local-variable pred))
218
219 (defcustom js2-highlight-level 2
220 "Amount of syntax highlighting to perform.
221 0 or a negative value means none.
222 1 adds basic syntax highlighting.
223 2 adds highlighting of some Ecma built-in properties.
224 3 adds highlighting of many Ecma built-in functions."
225 :group 'js2-mode
226 :type '(choice (const :tag "None" 0)
227 (const :tag "Basic" 1)
228 (const :tag "Include Properties" 2)
229 (const :tag "Include Functions" 3)))
230
231 (defvar js2-mode-dev-mode-p nil
232 "Non-nil if running in development mode. Normally nil.")
233
234 (defgroup js2-mode nil
235 "An improved JavaScript mode."
236 :group 'languages)
237
238 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
239 (numberp c-basic-offset))
240 c-basic-offset
241 4)
242 "Number of spaces to indent nested statements.
243 Similar to `c-basic-offset'."
244 :group 'js2-mode
245 :type 'integer)
246 (js2-mark-safe-local 'js2-basic-offset 'integerp)
247
248 (defcustom js2-bounce-indent-p nil
249 "Non-nil to have indent-line function choose among alternatives.
250 If nil, the indent-line function will indent to a predetermined column
251 based on heuristic guessing. If non-nil, then if the current line is
252 already indented to that predetermined column, indenting will choose
253 another likely column and indent to that spot. Repeated invocation of
254 the indent-line function will cycle among the computed alternatives.
255 See the function `js2-bounce-indent' for details. When it is non-nil,
256 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
257 :type 'boolean
258 :group 'js2-mode)
259
260 (defcustom js2-pretty-multiline-declarations t
261 "Non-nil to line up multiline declarations vertically:
262
263 var a = 10,
264 b = 20,
265 c = 30;
266
267 If the value is t, and the first assigned value in the
268 declaration is a function/array/object literal spanning several
269 lines, it won't be indented additionally:
270
271 var o = { var bar = 2,
272 foo: 3 vs. o = {
273 }, foo: 3
274 bar = 2; };
275
276 If the value is `all', it will always be indented additionally:
277
278 var o = {
279 foo: 3
280 };
281
282 var o = {
283 foo: 3
284 },
285 bar = 2;
286
287 If the value is `dynamic', it will be indented additionally only
288 if the declaration contains more than one variable:
289
290 var o = {
291 foo: 3
292 };
293
294 var o = {
295 foo: 3
296 },
297 bar = 2;"
298 :group 'js2-mode
299 :type 'symbol)
300 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
301
302 (defcustom js2-indent-switch-body nil
303 "When nil, case labels are indented on the same level as the
304 containing switch statement. Otherwise, all lines inside
305 switch statement body are indented one additional level."
306 :type 'boolean
307 :group 'js2-mode)
308 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
309
310 (defcustom js2-idle-timer-delay 0.2
311 "Delay in secs before re-parsing after user makes changes.
312 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
313 :type 'number
314 :group 'js2-mode)
315 (make-variable-buffer-local 'js2-idle-timer-delay)
316
317 (defcustom js2-dynamic-idle-timer-adjust 0
318 "Positive to adjust `js2-idle-timer-delay' based on file size.
319 The idea is that for short files, parsing is faster so we can be
320 more responsive to user edits without interfering with editing.
321 The buffer length in characters (typically bytes) is divided by
322 this value and used to multiply `js2-idle-timer-delay' for the
323 buffer. For example, a 21k file and 10k adjust yields 21k/10k
324 == 2, so js2-idle-timer-delay is multiplied by 2.
325 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
326 `js2-idle-timer-delay' is not dependent on the file size."
327 :type 'number
328 :group 'js2-mode)
329
330 (defcustom js2-concat-multiline-strings t
331 "When non-nil, `js2-line-break' in mid-string will make it a
332 string concatenation. When `eol', the '+' will be inserted at the
333 end of the line, otherwise, at the beginning of the next line."
334 :type '(choice (const t) (const eol) (const nil))
335 :group 'js2-mode)
336
337 (defcustom js2-mode-show-parse-errors t
338 "True to highlight parse errors."
339 :type 'boolean
340 :group 'js2-mode)
341
342 (defcustom js2-mode-show-strict-warnings t
343 "Non-nil to emit Ecma strict-mode warnings.
344 Some of the warnings can be individually disabled by other flags,
345 even if this flag is non-nil."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-trailing-comma-warning t
350 "Non-nil to warn about trailing commas in array literals.
351 Ecma-262-5.1 allows them, but older versions of IE raise an error."
352 :type 'boolean
353 :group 'js2-mode)
354
355 (defcustom js2-strict-missing-semi-warning t
356 "Non-nil to warn about semicolon auto-insertion after statement.
357 Technically this is legal per Ecma-262, but some style guides disallow
358 depending on it."
359 :type 'boolean
360 :group 'js2-mode)
361
362 (defcustom js2-missing-semi-one-line-override nil
363 "Non-nil to permit missing semicolons in one-line functions.
364 In one-liner functions such as `function identity(x) {return x}'
365 people often omit the semicolon for a cleaner look. If you are
366 such a person, you can suppress the missing-semicolon warning
367 by setting this variable to t."
368 :type 'boolean
369 :group 'js2-mode)
370
371 (defcustom js2-strict-inconsistent-return-warning t
372 "Non-nil to warn about mixing returns with value-returns.
373 It's perfectly legal to have a `return' and a `return foo' in the
374 same function, but it's often an indicator of a bug, and it also
375 interferes with type inference (in systems that support it.)"
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-strict-cond-assign-warning t
380 "Non-nil to warn about expressions like if (a = b).
381 This often should have been '==' instead of '='. If the warning
382 is enabled, you can suppress it on a per-expression basis by
383 parenthesizing the expression, e.g. if ((a = b)) ..."
384 :type 'boolean
385 :group 'js2-mode)
386
387 (defcustom js2-strict-var-redeclaration-warning t
388 "Non-nil to warn about redeclaring variables in a script or function."
389 :type 'boolean
390 :group 'js2-mode)
391
392 (defcustom js2-strict-var-hides-function-arg-warning t
393 "Non-nil to warn about a var decl hiding a function argument."
394 :type 'boolean
395 :group 'js2-mode)
396
397 (defcustom js2-skip-preprocessor-directives nil
398 "Non-nil to treat lines beginning with # as comments.
399 Useful for viewing Mozilla JavaScript source code."
400 :type 'boolean
401 :group 'js2-mode)
402
403 (defcustom js2-language-version 200
404 "Configures what JavaScript language version to recognize.
405 Currently versions 150, 160, 170, 180 and 200 are supported,
406 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
407 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
408 yield, and Array comprehensions, and 1.8 adds function closures."
409 :type 'integer
410 :group 'js2-mode)
411
412 (defcustom js2-instanceof-has-side-effects nil
413 "If non-nil, treats the instanceof operator as having side effects.
414 This is useful for xulrunner apps."
415 :type 'boolean
416 :group 'js2-mode)
417
418 (defcustom js2-move-point-on-right-click t
419 "Non-nil to move insertion point when you right-click.
420 This makes right-click context menu behavior a bit more intuitive,
421 since menu operations generally apply to the point. The exception
422 is if there is a region selection, in which case the point does -not-
423 move, so cut/copy/paste can work properly.
424
425 Note that IntelliJ moves the point, and Eclipse leaves it alone,
426 so this behavior is customizable."
427 :group 'js2-mode
428 :type 'boolean)
429
430 (defcustom js2-allow-rhino-new-expr-initializer t
431 "Non-nil to support a Rhino's experimental syntactic construct.
432
433 Rhino supports the ability to follow a `new' expression with an object
434 literal, which is used to set additional properties on the new object
435 after calling its constructor. Syntax:
436
437 new <expr> [ ( arglist ) ] [initializer]
438
439 Hence, this expression:
440
441 new Object {a: 1, b: 2}
442
443 results in an Object with properties a=1 and b=2. This syntax is
444 apparently not configurable in Rhino - it's currently always enabled,
445 as of Rhino version 1.7R2."
446 :type 'boolean
447 :group 'js2-mode)
448
449 (defcustom js2-allow-member-expr-as-function-name nil
450 "Non-nil to support experimental Rhino syntax for function names.
451
452 Rhino supports an experimental syntax configured via the Rhino Context
453 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
454
455 function <member-expr> ( [ arg-list ] ) { <body> }
456
457 Where member-expr is a non-parenthesized 'member expression', which
458 is anything at the grammar level of a new-expression or lower, meaning
459 any expression that does not involve infix or unary operators.
460
461 When <member-expr> is not a simple identifier, then it is syntactic
462 sugar for assigning the anonymous function to the <member-expr>. Hence,
463 this code:
464
465 function a.b().c[2] (x, y) { ... }
466
467 is rewritten as:
468
469 a.b().c[2] = function(x, y) {...}
470
471 which doesn't seem particularly useful, but Rhino permits it."
472 :type 'boolean
473 :group 'js2-mode)
474
475 ;; scanner variables
476
477 (defmacro js2-deflocal (name value &optional comment)
478 "Define a buffer-local variable NAME with VALUE and COMMENT."
479 (declare (debug defvar) (doc-string 3))
480 `(progn
481 (defvar ,name ,value ,comment)
482 (make-variable-buffer-local ',name)))
483
484 (defvar js2-EOF_CHAR -1
485 "Represents end of stream. Distinct from js2-EOF token type.")
486
487 ;; I originally used symbols to represent tokens, but Rhino uses
488 ;; ints and then sets various flag bits in them, so ints it is.
489 ;; The upshot is that we need a `js2-' prefix in front of each name.
490 (defvar js2-ERROR -1)
491 (defvar js2-EOF 0)
492 (defvar js2-EOL 1)
493 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
494 (defvar js2-LEAVEWITH 3)
495 (defvar js2-RETURN 4)
496 (defvar js2-GOTO 5)
497 (defvar js2-IFEQ 6)
498 (defvar js2-IFNE 7)
499 (defvar js2-SETNAME 8)
500 (defvar js2-BITOR 9)
501 (defvar js2-BITXOR 10)
502 (defvar js2-BITAND 11)
503 (defvar js2-EQ 12)
504 (defvar js2-NE 13)
505 (defvar js2-LT 14)
506 (defvar js2-LE 15)
507 (defvar js2-GT 16)
508 (defvar js2-GE 17)
509 (defvar js2-LSH 18)
510 (defvar js2-RSH 19)
511 (defvar js2-URSH 20)
512 (defvar js2-ADD 21) ; infix plus
513 (defvar js2-SUB 22) ; infix minus
514 (defvar js2-MUL 23)
515 (defvar js2-DIV 24)
516 (defvar js2-MOD 25)
517 (defvar js2-NOT 26)
518 (defvar js2-BITNOT 27)
519 (defvar js2-POS 28) ; unary plus
520 (defvar js2-NEG 29) ; unary minus
521 (defvar js2-NEW 30)
522 (defvar js2-DELPROP 31)
523 (defvar js2-TYPEOF 32)
524 (defvar js2-GETPROP 33)
525 (defvar js2-GETPROPNOWARN 34)
526 (defvar js2-SETPROP 35)
527 (defvar js2-GETELEM 36)
528 (defvar js2-SETELEM 37)
529 (defvar js2-CALL 38)
530 (defvar js2-NAME 39) ; an identifier
531 (defvar js2-NUMBER 40)
532 (defvar js2-STRING 41)
533 (defvar js2-NULL 42)
534 (defvar js2-THIS 43)
535 (defvar js2-FALSE 44)
536 (defvar js2-TRUE 45)
537 (defvar js2-SHEQ 46) ; shallow equality (===)
538 (defvar js2-SHNE 47) ; shallow inequality (!==)
539 (defvar js2-REGEXP 48)
540 (defvar js2-BINDNAME 49)
541 (defvar js2-THROW 50)
542 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
543 (defvar js2-IN 52)
544 (defvar js2-INSTANCEOF 53)
545 (defvar js2-LOCAL_LOAD 54)
546 (defvar js2-GETVAR 55)
547 (defvar js2-SETVAR 56)
548 (defvar js2-CATCH_SCOPE 57)
549 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
550 (defvar js2-ENUM_INIT_VALUES 59)
551 (defvar js2-ENUM_INIT_ARRAY 60)
552 (defvar js2-ENUM_NEXT 61)
553 (defvar js2-ENUM_ID 62)
554 (defvar js2-THISFN 63)
555 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
556 (defvar js2-ARRAYLIT 65) ; array literal
557 (defvar js2-OBJECTLIT 66) ; object literal
558 (defvar js2-GET_REF 67) ; *reference
559 (defvar js2-SET_REF 68) ; *reference = something
560 (defvar js2-DEL_REF 69) ; delete reference
561 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
562 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
563 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
564
565 ;; XML support
566 (defvar js2-DEFAULTNAMESPACE 73)
567 (defvar js2-ESCXMLATTR 74)
568 (defvar js2-ESCXMLTEXT 75)
569 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
570 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
571 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
572 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
573
574 (defvar js2-first-bytecode js2-ENTERWITH)
575 (defvar js2-last-bytecode js2-REF_NS_NAME)
576
577 (defvar js2-TRY 80)
578 (defvar js2-SEMI 81) ; semicolon
579 (defvar js2-LB 82) ; left and right brackets
580 (defvar js2-RB 83)
581 (defvar js2-LC 84) ; left and right curly-braces
582 (defvar js2-RC 85)
583 (defvar js2-LP 86) ; left and right parens
584 (defvar js2-RP 87)
585 (defvar js2-COMMA 88) ; comma operator
586
587 (defvar js2-ASSIGN 89) ; simple assignment (=)
588 (defvar js2-ASSIGN_BITOR 90) ; |=
589 (defvar js2-ASSIGN_BITXOR 91) ; ^=
590 (defvar js2-ASSIGN_BITAND 92) ; &=
591 (defvar js2-ASSIGN_LSH 93) ; <<=
592 (defvar js2-ASSIGN_RSH 94) ; >>=
593 (defvar js2-ASSIGN_URSH 95) ; >>>=
594 (defvar js2-ASSIGN_ADD 96) ; +=
595 (defvar js2-ASSIGN_SUB 97) ; -=
596 (defvar js2-ASSIGN_MUL 98) ; *=
597 (defvar js2-ASSIGN_DIV 99) ; /=
598 (defvar js2-ASSIGN_MOD 100) ; %=
599
600 (defvar js2-first-assign js2-ASSIGN)
601 (defvar js2-last-assign js2-ASSIGN_MOD)
602
603 (defvar js2-HOOK 101) ; conditional (?:)
604 (defvar js2-COLON 102)
605 (defvar js2-OR 103) ; logical or (||)
606 (defvar js2-AND 104) ; logical and (&&)
607 (defvar js2-INC 105) ; increment/decrement (++ --)
608 (defvar js2-DEC 106)
609 (defvar js2-DOT 107) ; member operator (.)
610 (defvar js2-FUNCTION 108) ; function keyword
611 (defvar js2-EXPORT 109) ; export keyword
612 (defvar js2-IMPORT 110) ; import keyword
613 (defvar js2-IF 111) ; if keyword
614 (defvar js2-ELSE 112) ; else keyword
615 (defvar js2-SWITCH 113) ; switch keyword
616 (defvar js2-CASE 114) ; case keyword
617 (defvar js2-DEFAULT 115) ; default keyword
618 (defvar js2-WHILE 116) ; while keyword
619 (defvar js2-DO 117) ; do keyword
620 (defvar js2-FOR 118) ; for keyword
621 (defvar js2-BREAK 119) ; break keyword
622 (defvar js2-CONTINUE 120) ; continue keyword
623 (defvar js2-VAR 121) ; var keyword
624 (defvar js2-WITH 122) ; with keyword
625 (defvar js2-CATCH 123) ; catch keyword
626 (defvar js2-FINALLY 124) ; finally keyword
627 (defvar js2-VOID 125) ; void keyword
628 (defvar js2-RESERVED 126) ; reserved keywords
629
630 (defvar js2-EMPTY 127)
631
632 ;; Types used for the parse tree - never returned by scanner.
633
634 (defvar js2-BLOCK 128) ; statement block
635 (defvar js2-LABEL 129) ; label
636 (defvar js2-TARGET 130)
637 (defvar js2-LOOP 131)
638 (defvar js2-EXPR_VOID 132) ; expression statement in functions
639 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
640 (defvar js2-JSR 134)
641 (defvar js2-SCRIPT 135) ; top-level node for entire script
642 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
643 (defvar js2-USE_STACK 137)
644 (defvar js2-SETPROP_OP 138) ; x.y op= something
645 (defvar js2-SETELEM_OP 139) ; x[y] op= something
646 (defvar js2-LOCAL_BLOCK 140)
647 (defvar js2-SET_REF_OP 141) ; *reference op= something
648
649 ;; For XML support:
650 (defvar js2-DOTDOT 142) ; member operator (..)
651 (defvar js2-COLONCOLON 143) ; namespace::name
652 (defvar js2-XML 144) ; XML type
653 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
654 (defvar js2-XMLATTR 146) ; @
655 (defvar js2-XMLEND 147)
656
657 ;; Optimizer-only tokens
658 (defvar js2-TO_OBJECT 148)
659 (defvar js2-TO_DOUBLE 149)
660
661 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
662 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
663 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
664 (defvar js2-CONST 153)
665 (defvar js2-SETCONST 154)
666 (defvar js2-SETCONSTVAR 155)
667 (defvar js2-ARRAYCOMP 156)
668 (defvar js2-LETEXPR 157)
669 (defvar js2-WITHEXPR 158)
670 (defvar js2-DEBUGGER 159)
671
672 (defvar js2-COMMENT 160)
673 (defvar js2-TRIPLEDOT 161) ; for rest parameter
674 (defvar js2-ARROW 162) ; function arrow (=>)
675 (defvar js2-CLASS 163)
676 (defvar js2-EXTENDS 164)
677 (defvar js2-SUPER 165)
678 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
679 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
680 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
681
682 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
683
684 (defconst js2-debug-print-trees nil)
685
686 ;; Rhino accepts any string or stream as input. Emacs character
687 ;; processing works best in buffers, so we'll assume the input is a
688 ;; buffer. JavaScript strings can be copied into temp buffers before
689 ;; scanning them.
690
691 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
692 ;; They're the Emacs equivalent of instance variables, more or less.
693
694 (js2-deflocal js2-ts-dirty-line nil
695 "Token stream buffer-local variable.
696 Indicates stuff other than whitespace since start of line.")
697
698 (js2-deflocal js2-ts-hit-eof nil
699 "Token stream buffer-local variable.")
700
701 ;; FIXME: Unused.
702 (js2-deflocal js2-ts-line-start 0
703 "Token stream buffer-local variable.")
704
705 (js2-deflocal js2-ts-lineno 1
706 "Token stream buffer-local variable.")
707
708 ;; FIXME: Unused.
709 (js2-deflocal js2-ts-line-end-char -1
710 "Token stream buffer-local variable.")
711
712 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
713 "Token stream buffer-local variable.
714 Current scan position.")
715
716 ;; FIXME: Unused.
717 (js2-deflocal js2-ts-is-xml-attribute nil
718 "Token stream buffer-local variable.")
719
720 (js2-deflocal js2-ts-xml-is-tag-content nil
721 "Token stream buffer-local variable.")
722
723 (js2-deflocal js2-ts-xml-open-tags-count 0
724 "Token stream buffer-local variable.")
725
726 (js2-deflocal js2-ts-string-buffer nil
727 "Token stream buffer-local variable.
728 List of chars built up while scanning various tokens.")
729
730 (cl-defstruct (js2-token
731 (:constructor nil)
732 (:constructor make-js2-token (beg)))
733 "Value returned from the token stream."
734 (type js2-EOF)
735 (beg 1)
736 (end -1)
737 (string "")
738 number
739 number-base
740 regexp-flags
741 comment-type
742 follows-eol-p)
743
744 ;; Have to call `js2-init-scanner' to initialize the values.
745 (js2-deflocal js2-ti-tokens nil)
746 (js2-deflocal js2-ti-tokens-cursor nil)
747 (js2-deflocal js2-ti-lookahead nil)
748
749 (cl-defstruct (js2-ts-state
750 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
751 (cursor js2-ts-cursor)
752 (tokens (copy-sequence js2-ti-tokens))
753 (tokens-cursor js2-ti-tokens-cursor)
754 (lookahead js2-ti-lookahead))))
755 lineno
756 cursor
757 tokens
758 tokens-cursor
759 lookahead)
760
761 ;;; Parser variables
762
763 (js2-deflocal js2-parsed-errors nil
764 "List of errors produced during scanning/parsing.")
765
766 (js2-deflocal js2-parsed-warnings nil
767 "List of warnings produced during scanning/parsing.")
768
769 (js2-deflocal js2-recover-from-parse-errors t
770 "Non-nil to continue parsing after a syntax error.
771
772 In recovery mode, the AST will be built in full, and any error
773 nodes will be flagged with appropriate error information. If
774 this flag is nil, a syntax error will result in an error being
775 signaled.
776
777 The variable is automatically buffer-local, because different
778 modes that use the parser will need different settings.")
779
780 (js2-deflocal js2-parse-hook nil
781 "List of callbacks for receiving parsing progress.")
782
783 (defvar js2-parse-finished-hook nil
784 "List of callbacks to notify when parsing finishes.
785 Not called if parsing was interrupted.")
786
787 (js2-deflocal js2-is-eval-code nil
788 "True if we're evaluating code in a string.
789 If non-nil, the tokenizer will record the token text, and the AST nodes
790 will record their source text. Off by default for IDE modes, since the
791 text is available in the buffer.")
792
793 (defvar js2-parse-ide-mode t
794 "Non-nil if the parser is being used for `js2-mode'.
795 If non-nil, the parser will set text properties for fontification
796 and the syntax table. The value should be nil when using the
797 parser as a frontend to an interpreter or byte compiler.")
798
799 ;;; Parser instance variables (buffer-local vars for js2-parse)
800
801 (defconst js2-ti-after-eol (lsh 1 16)
802 "Flag: first token of the source line.")
803
804 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
805
806 (js2-deflocal js2-compiler-generate-debug-info t)
807 (js2-deflocal js2-compiler-use-dynamic-scope nil)
808 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
809 (js2-deflocal js2-compiler-xml-available t)
810 (js2-deflocal js2-compiler-optimization-level 0)
811 (js2-deflocal js2-compiler-generating-source t)
812 (js2-deflocal js2-compiler-strict-mode nil)
813 (js2-deflocal js2-compiler-report-warning-as-error nil)
814 (js2-deflocal js2-compiler-generate-observer-count nil)
815 (js2-deflocal js2-compiler-activation-names nil)
816
817 ;; SKIP: sourceURI
818
819 ;; There's a compileFunction method in Context.java - may need it.
820 (js2-deflocal js2-called-by-compile-function nil
821 "True if `js2-parse' was called by `js2-compile-function'.
822 Will only be used when we finish implementing the interpreter.")
823
824 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
825
826 ;; SKIP: node factory - we're going to just call functions directly,
827 ;; and eventually go to a unified AST format.
828
829 (js2-deflocal js2-nesting-of-function 0)
830
831 (js2-deflocal js2-recorded-identifiers nil
832 "Tracks identifiers found during parsing.")
833
834 (js2-deflocal js2-is-in-destructuring nil
835 "True while parsing destructuring expression.")
836
837 (js2-deflocal js2-in-use-strict-directive nil
838 "True while inside a script or function under strict mode.")
839
840 (defcustom js2-global-externs nil
841 "A list of any extern names you'd like to consider always declared.
842 This list is global and is used by all `js2-mode' files.
843 You can create buffer-local externs list using `js2-additional-externs'.
844
845 There is also a buffer-local variable `js2-default-externs',
846 which is initialized by default to include the Ecma-262 externs
847 and the standard browser externs. The three lists are all
848 checked during highlighting."
849 :type 'list
850 :group 'js2-mode)
851
852 (js2-deflocal js2-default-externs nil
853 "Default external declarations.
854
855 These are currently only used for highlighting undeclared variables,
856 which only worries about top-level (unqualified) references.
857 As js2-mode's processing improves, we will flesh out this list.
858
859 The initial value is set to `js2-ecma-262-externs', unless some
860 of the `js2-include-?-externs' variables are set to t, in which
861 case the browser, Rhino and/or Node.js externs are also included.
862
863 See `js2-additional-externs' for more information.")
864
865 (defcustom js2-include-browser-externs t
866 "Non-nil to include browser externs in the master externs list.
867 If you work on JavaScript files that are not intended for browsers,
868 such as Mozilla Rhino server-side JavaScript, set this to nil.
869 See `js2-additional-externs' for more information about externs."
870 :type 'boolean
871 :group 'js2-mode)
872
873 (defcustom js2-include-rhino-externs nil
874 "Non-nil to include Mozilla Rhino externs in the master externs list.
875 See `js2-additional-externs' for more information about externs."
876 :type 'boolean
877 :group 'js2-mode)
878
879 (defcustom js2-include-node-externs nil
880 "Non-nil to include Node.js externs in the master externs list.
881 See `js2-additional-externs' for more information about externs."
882 :type 'boolean
883 :group 'js2-mode)
884
885 (js2-deflocal js2-additional-externs nil
886 "A buffer-local list of additional external declarations.
887 It is used to decide whether variables are considered undeclared
888 for purposes of highlighting.
889
890 Each entry is a Lisp string. The string should be the fully qualified
891 name of an external entity. All externs should be added to this list,
892 so that as js2-mode's processing improves it can take advantage of them.
893
894 You may want to declare your externs in three ways.
895 First, you can add externs that are valid for all your JavaScript files.
896 You should probably do this by adding them to `js2-global-externs', which
897 is a global list used for all js2-mode files.
898
899 Next, you can add a function to `js2-init-hook' that adds additional
900 externs appropriate for the specific file, perhaps based on its path.
901 These should go in `js2-additional-externs', which is buffer-local.
902
903 Third, you can use JSLint's global declaration, as long as
904 `js2-include-jslint-globals' is non-nil, which see.
905
906 Finally, you can add a function to `js2-post-parse-callbacks',
907 which is called after parsing completes, and `js2-mode-ast' is bound to
908 the root of the parse tree. At this stage you can set up an AST
909 node visitor using `js2-visit-ast' and examine the parse tree
910 for specific import patterns that may imply the existence of
911 other externs, possibly tied to your build system. These should also
912 be added to `js2-additional-externs'.
913
914 Your post-parse callback may of course also use the simpler and
915 faster (but perhaps less robust) approach of simply scanning the
916 buffer text for your imports, using regular expressions.")
917
918 ;; SKIP: decompiler
919 ;; SKIP: encoded-source
920
921 ;;; The following variables are per-function and should be saved/restored
922 ;;; during function parsing...
923
924 (js2-deflocal js2-current-script-or-fn nil)
925 (js2-deflocal js2-current-scope nil)
926 (js2-deflocal js2-nesting-of-with 0)
927 (js2-deflocal js2-label-set nil
928 "An alist mapping label names to nodes.")
929
930 (js2-deflocal js2-loop-set nil)
931 (js2-deflocal js2-loop-and-switch-set nil)
932 (js2-deflocal js2-has-return-value nil)
933 (js2-deflocal js2-end-flags 0)
934
935 ;;; ...end of per function variables
936
937 ;; These flags enumerate the possible ways a statement/function can
938 ;; terminate. These flags are used by endCheck() and by the Parser to
939 ;; detect inconsistent return usage.
940 ;;
941 ;; END_UNREACHED is reserved for code paths that are assumed to always be
942 ;; able to execute (example: throw, continue)
943 ;;
944 ;; END_DROPS_OFF indicates if the statement can transfer control to the
945 ;; next one. Statement such as return dont. A compound statement may have
946 ;; some branch that drops off control to the next statement.
947 ;;
948 ;; END_RETURNS indicates that the statement can return (without arguments)
949 ;; END_RETURNS_VALUE indicates that the statement can return a value.
950 ;;
951 ;; A compound statement such as
952 ;; if (condition) {
953 ;; return value;
954 ;; }
955 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
956
957 (defconst js2-end-unreached #x0)
958 (defconst js2-end-drops-off #x1)
959 (defconst js2-end-returns #x2)
960 (defconst js2-end-returns-value #x4)
961
962 ;; Rhino awkwardly passes a statementLabel parameter to the
963 ;; statementHelper() function, the main statement parser, which
964 ;; is then used by quite a few of the sub-parsers. We just make
965 ;; it a buffer-local variable and make sure it's cleaned up properly.
966 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
967
968 ;; Similarly, Rhino passes an inForInit boolean through about half
969 ;; the expression parsers. We use a dynamically-scoped variable,
970 ;; which makes it easier to funcall the parsers individually without
971 ;; worrying about whether they take the parameter or not.
972 (js2-deflocal js2-in-for-init nil)
973 (js2-deflocal js2-temp-name-counter 0)
974 (js2-deflocal js2-parse-stmt-count 0)
975
976 (defsubst js2-get-next-temp-name ()
977 (format "$%d" (cl-incf js2-temp-name-counter)))
978
979 (defvar js2-parse-interruptable-p t
980 "Set this to nil to force parse to continue until finished.
981 This will mostly be useful for interpreters.")
982
983 (defvar js2-statements-per-pause 50
984 "Pause after this many statements to check for user input.
985 If user input is pending, stop the parse and discard the tree.
986 This makes for a smoother user experience for large files.
987 You may have to wait a second or two before the highlighting
988 and error-reporting appear, but you can always type ahead if
989 you wish. This appears to be more or less how Eclipse, IntelliJ
990 and other editors work.")
991
992 (js2-deflocal js2-record-comments t
993 "Instructs the scanner to record comments in `js2-scanned-comments'.")
994
995 (js2-deflocal js2-scanned-comments nil
996 "List of all comments from the current parse.")
997
998 (defcustom js2-mode-indent-inhibit-undo nil
999 "Non-nil to disable collection of Undo information when indenting lines.
1000 Some users have requested this behavior. It's nil by default because
1001 other Emacs modes don't work this way."
1002 :type 'boolean
1003 :group 'js2-mode)
1004
1005 (defcustom js2-mode-indent-ignore-first-tab nil
1006 "If non-nil, ignore first TAB keypress if we look indented properly.
1007 It's fairly common for users to navigate to an already-indented line
1008 and press TAB for reassurance that it's been indented. For this class
1009 of users, we want the first TAB press on a line to be ignored if the
1010 line is already indented to one of the precomputed alternatives.
1011
1012 This behavior is only partly implemented. If you TAB-indent a line,
1013 navigate to another line, and then navigate back, it fails to clear
1014 the last-indented variable, so it thinks you've already hit TAB once,
1015 and performs the indent. A full solution would involve getting on the
1016 point-motion hooks for the entire buffer. If we come across another
1017 use cases that requires watching point motion, I'll consider doing it.
1018
1019 If you set this variable to nil, then the TAB key will always change
1020 the indentation of the current line, if more than one alternative
1021 indentation spot exists."
1022 :type 'boolean
1023 :group 'js2-mode)
1024
1025 (defvar js2-indent-hook nil
1026 "A hook for user-defined indentation rules.
1027
1028 Functions on this hook should expect two arguments: (LIST INDEX)
1029 The LIST argument is the list of computed indentation points for
1030 the current line. INDEX is the list index of the indentation point
1031 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1032 indent function is not going to change the current line indentation.
1033
1034 If a hook function on this list returns a non-nil value, then
1035 `js2-bounce-indent' assumes the hook function has performed its own
1036 indentation, and will do nothing. If all hook functions on the list
1037 return nil, then `js2-bounce-indent' will use its computed indentation
1038 and reindent the line.
1039
1040 When hook functions on this hook list are called, the variable
1041 `js2-mode-ast' may or may not be set, depending on whether the
1042 parse tree is available. If the variable is nil, you can pass a
1043 callback to `js2-mode-wait-for-parse', and your callback will be
1044 called after the new parse tree is built. This can take some time
1045 in large files.")
1046
1047 (defface js2-warning
1048 `((((class color) (background light))
1049 (:underline "orange"))
1050 (((class color) (background dark))
1051 (:underline "orange"))
1052 (t (:underline t)))
1053 "Face for JavaScript warnings."
1054 :group 'js2-mode)
1055
1056 (defface js2-error
1057 `((((class color) (background light))
1058 (:foreground "red"))
1059 (((class color) (background dark))
1060 (:foreground "red"))
1061 (t (:foreground "red")))
1062 "Face for JavaScript errors."
1063 :group 'js2-mode)
1064
1065 (defface js2-jsdoc-tag
1066 '((t :foreground "SlateGray"))
1067 "Face used to highlight @whatever tags in jsdoc comments."
1068 :group 'js2-mode)
1069
1070 (defface js2-jsdoc-type
1071 '((t :foreground "SteelBlue"))
1072 "Face used to highlight {FooBar} types in jsdoc comments."
1073 :group 'js2-mode)
1074
1075 (defface js2-jsdoc-value
1076 '((t :foreground "PeachPuff3"))
1077 "Face used to highlight tag values in jsdoc comments."
1078 :group 'js2-mode)
1079
1080 (defface js2-function-param
1081 '((t :foreground "SeaGreen"))
1082 "Face used to highlight function parameters in javascript."
1083 :group 'js2-mode)
1084
1085 (defface js2-function-call
1086 '((t :inherit default))
1087 "Face used to highlight function name in calls."
1088 :group 'js2-mode)
1089
1090 (defface js2-instance-member
1091 '((t :foreground "DarkOrchid"))
1092 "Face used to highlight instance variables in javascript.
1093 Not currently used."
1094 :group 'js2-mode)
1095
1096 (defface js2-private-member
1097 '((t :foreground "PeachPuff3"))
1098 "Face used to highlight calls to private methods in javascript.
1099 Not currently used."
1100 :group 'js2-mode)
1101
1102 (defface js2-private-function-call
1103 '((t :foreground "goldenrod"))
1104 "Face used to highlight calls to private functions in javascript.
1105 Not currently used."
1106 :group 'js2-mode)
1107
1108 (defface js2-jsdoc-html-tag-name
1109 '((((class color) (min-colors 88) (background light))
1110 (:foreground "rosybrown"))
1111 (((class color) (min-colors 8) (background dark))
1112 (:foreground "yellow"))
1113 (((class color) (min-colors 8) (background light))
1114 (:foreground "magenta")))
1115 "Face used to highlight jsdoc html tag names"
1116 :group 'js2-mode)
1117
1118 (defface js2-jsdoc-html-tag-delimiter
1119 '((((class color) (min-colors 88) (background light))
1120 (:foreground "dark khaki"))
1121 (((class color) (min-colors 8) (background dark))
1122 (:foreground "green"))
1123 (((class color) (min-colors 8) (background light))
1124 (:foreground "green")))
1125 "Face used to highlight brackets in jsdoc html tags."
1126 :group 'js2-mode)
1127
1128 (defface js2-external-variable
1129 '((t :foreground "orange"))
1130 "Face used to highlight undeclared variable identifiers.")
1131
1132 (defcustom js2-init-hook nil
1133 "List of functions to be called after `js2-mode' or
1134 `js2-minor-mode' has initialized all variables, before parsing
1135 the buffer for the first time."
1136 :type 'hook
1137 :group 'js2-mode
1138 :version "20130608")
1139
1140 (defcustom js2-post-parse-callbacks nil
1141 "List of callback functions invoked after parsing finishes.
1142 Currently, the main use for this function is to add synthetic
1143 declarations to `js2-recorded-identifiers', which see."
1144 :type 'hook
1145 :group 'js2-mode)
1146
1147 (defcustom js2-build-imenu-callbacks nil
1148 "List of functions called during Imenu index generation.
1149 It's a good place to add additional entries to it, using
1150 `js2-record-imenu-entry'."
1151 :type 'hook
1152 :group 'js2-mode)
1153
1154 (defcustom js2-highlight-external-variables t
1155 "Non-nil to highlight undeclared variable identifiers.
1156 An undeclared variable is any variable not declared with var or let
1157 in the current scope or any lexically enclosing scope. If you use
1158 such a variable, then you are either expecting it to originate from
1159 another file, or you've got a potential bug."
1160 :type 'boolean
1161 :group 'js2-mode)
1162
1163 (defcustom js2-warn-about-unused-function-arguments nil
1164 "Non-nil to treat function arguments like declared-but-unused variables."
1165 :type 'booleanp
1166 :group 'js2-mode)
1167
1168 (defcustom js2-include-jslint-globals t
1169 "Non-nil to include the identifiers from JSLint global
1170 declaration (see http://www.jslint.com/lint.html#global) in the
1171 buffer-local externs list. See `js2-additional-externs' for more
1172 information."
1173 :type 'boolean
1174 :group 'js2-mode)
1175
1176 (defvar js2-mode-map
1177 (let ((map (make-sparse-keymap)))
1178 (define-key map [mouse-1] #'js2-mode-show-node)
1179 (define-key map (kbd "M-j") #'js2-line-break)
1180 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1181 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1182 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1183 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1184 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1185 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1186 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1187 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1188 (when js2-bounce-indent-p
1189 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1190
1191 (define-key map [menu-bar javascript]
1192 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1193
1194 (define-key map [menu-bar javascript customize-js2-mode]
1195 '(menu-item "Customize js2-mode" js2-mode-customize
1196 :help "Customize the behavior of this mode"))
1197
1198 (define-key map [menu-bar javascript js2-force-refresh]
1199 '(menu-item "Force buffer refresh" js2-mode-reset
1200 :help "Re-parse the buffer from scratch"))
1201
1202 (define-key map [menu-bar javascript separator-2]
1203 '("--"))
1204
1205 (define-key map [menu-bar javascript next-error]
1206 '(menu-item "Next warning or error" next-error
1207 :enabled (and js2-mode-ast
1208 (or (js2-ast-root-errors js2-mode-ast)
1209 (js2-ast-root-warnings js2-mode-ast)))
1210 :help "Move to next warning or error"))
1211
1212 (define-key map [menu-bar javascript display-errors]
1213 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1214 :visible (not js2-mode-show-parse-errors)
1215 :help "Turn on display of warnings and errors"))
1216
1217 (define-key map [menu-bar javascript hide-errors]
1218 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1219 :visible js2-mode-show-parse-errors
1220 :help "Turn off display of warnings and errors"))
1221
1222 (define-key map [menu-bar javascript separator-1]
1223 '("--"))
1224
1225 (define-key map [menu-bar javascript js2-toggle-function]
1226 '(menu-item "Show/collapse element" js2-mode-toggle-element
1227 :help "Hide or show function body or comment"))
1228
1229 (define-key map [menu-bar javascript show-comments]
1230 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1231 :visible js2-mode-comments-hidden
1232 :help "Expand all hidden block comments"))
1233
1234 (define-key map [menu-bar javascript hide-comments]
1235 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1236 :visible (not js2-mode-comments-hidden)
1237 :help "Show block comments as /*...*/"))
1238
1239 (define-key map [menu-bar javascript show-all-functions]
1240 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1241 :visible js2-mode-functions-hidden
1242 :help "Expand all hidden function bodies"))
1243
1244 (define-key map [menu-bar javascript hide-all-functions]
1245 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1246 :visible (not js2-mode-functions-hidden)
1247 :help "Show {...} for all top-level function bodies"))
1248
1249 map)
1250 "Keymap used in `js2-mode' buffers.")
1251
1252 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1253
1254 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1255 "Matches a //-comment line. Must be first non-whitespace on line.
1256 First match-group is the leading whitespace.")
1257
1258 (defvar js2-mode-hook nil)
1259
1260 (js2-deflocal js2-mode-ast nil "Private variable.")
1261 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1262 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1263 (js2-deflocal js2-mode-parsing nil "Private variable.")
1264 (js2-deflocal js2-mode-node-overlay nil)
1265
1266 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1267 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1268
1269 (js2-deflocal js2-mode-fontifications nil "Private variable")
1270 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1271 (js2-deflocal js2-imenu-recorder nil "Private variable")
1272 (js2-deflocal js2-imenu-function-map nil "Private variable")
1273
1274 (defvar js2-paragraph-start
1275 "\\(@[[:alpha:]]+\\>\\|$\\)")
1276
1277 ;; Note that we also set a 'c-in-sws text property in html comments,
1278 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1279 (defvar js2-syntactic-ws-start
1280 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1281
1282 (defvar js2-syntactic-ws-end
1283 "\\s \\|[\n\r/]\\|\\s!")
1284
1285 (defvar js2-syntactic-eol
1286 (concat "\\s *\\(/\\*[^*\n\r]*"
1287 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1288 "\\*+/\\s *\\)*"
1289 "\\(//\\|/\\*[^*\n\r]*"
1290 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1291 "\\|\\\\$\\|$\\)")
1292 "Copied from `java-mode'. Needed for some cc-engine functions.")
1293
1294 (defvar js2-comment-prefix-regexp
1295 "//+\\|\\**")
1296
1297 (defvar js2-comment-start-skip
1298 "\\(//+\\|/\\*+\\)\\s *")
1299
1300 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1301 "Non-nil to emit status messages during parsing.")
1302
1303 (defvar js2-mode-functions-hidden nil "Private variable.")
1304 (defvar js2-mode-comments-hidden nil "Private variable.")
1305
1306 (defvar js2-mode-syntax-table
1307 (let ((table (make-syntax-table)))
1308 (c-populate-syntax-table table)
1309 (modify-syntax-entry ?` "\"" table)
1310 table)
1311 "Syntax table used in `js2-mode' buffers.")
1312
1313 (defvar js2-mode-abbrev-table nil
1314 "Abbrev table in use in `js2-mode' buffers.")
1315 (define-abbrev-table 'js2-mode-abbrev-table ())
1316
1317 (defvar js2-mode-pending-parse-callbacks nil
1318 "List of functions waiting to be notified that parse is finished.")
1319
1320 (defvar js2-mode-last-indented-line -1)
1321
1322 ;;; Localizable error and warning messages
1323
1324 ;; Messages are copied from Rhino's Messages.properties.
1325 ;; Many of the Java-specific messages have been elided.
1326 ;; Add any js2-specific ones at the end, so we can keep
1327 ;; this file synced with changes to Rhino's.
1328
1329 (defvar js2-message-table
1330 (make-hash-table :test 'equal :size 250)
1331 "Contains localized messages for `js2-mode'.")
1332
1333 ;; TODO(stevey): construct this table at compile-time.
1334 (defmacro js2-msg (key &rest strings)
1335 `(puthash ,key (concat ,@strings)
1336 js2-message-table))
1337
1338 (defun js2-get-msg (msg-key)
1339 "Look up a localized message.
1340 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1341 the correct number of ARGS must be provided."
1342 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1343 (args (if (listp msg-key) (cdr msg-key)))
1344 (msg (gethash key js2-message-table)))
1345 (if msg
1346 (apply #'format msg args)
1347 key))) ; default to showing the key
1348
1349 (js2-msg "msg.dup.parms"
1350 "Duplicate parameter name '%s'.")
1351
1352 (js2-msg "msg.too.big.jump"
1353 "Program too complex: jump offset too big.")
1354
1355 (js2-msg "msg.too.big.index"
1356 "Program too complex: internal index exceeds 64K limit.")
1357
1358 (js2-msg "msg.while.compiling.fn"
1359 "Encountered code generation error while compiling function '%s': %s")
1360
1361 (js2-msg "msg.while.compiling.script"
1362 "Encountered code generation error while compiling script: %s")
1363
1364 ;; Context
1365 (js2-msg "msg.ctor.not.found"
1366 "Constructor for '%s' not found.")
1367
1368 (js2-msg "msg.not.ctor"
1369 "'%s' is not a constructor.")
1370
1371 ;; FunctionObject
1372 (js2-msg "msg.varargs.ctor"
1373 "Method or constructor '%s' must be static "
1374 "with the signature (Context cx, Object[] args, "
1375 "Function ctorObj, boolean inNewExpr) "
1376 "to define a variable arguments constructor.")
1377
1378 (js2-msg "msg.varargs.fun"
1379 "Method '%s' must be static with the signature "
1380 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1381 "to define a variable arguments function.")
1382
1383 (js2-msg "msg.incompat.call"
1384 "Method '%s' called on incompatible object.")
1385
1386 (js2-msg "msg.bad.parms"
1387 "Unsupported parameter type '%s' in method '%s'.")
1388
1389 (js2-msg "msg.bad.method.return"
1390 "Unsupported return type '%s' in method '%s'.")
1391
1392 (js2-msg "msg.bad.ctor.return"
1393 "Construction of objects of type '%s' is not supported.")
1394
1395 (js2-msg "msg.no.overload"
1396 "Method '%s' occurs multiple times in class '%s'.")
1397
1398 (js2-msg "msg.method.not.found"
1399 "Method '%s' not found in '%s'.")
1400
1401 ;; IRFactory
1402
1403 (js2-msg "msg.bad.for.in.lhs"
1404 "Invalid left-hand side of for..in loop.")
1405
1406 (js2-msg "msg.mult.index"
1407 "Only one variable allowed in for..in loop.")
1408
1409 (js2-msg "msg.bad.for.in.destruct"
1410 "Left hand side of for..in loop must be an array of "
1411 "length 2 to accept key/value pair.")
1412
1413 (js2-msg "msg.cant.convert"
1414 "Can't convert to type '%s'.")
1415
1416 (js2-msg "msg.bad.assign.left"
1417 "Invalid assignment left-hand side.")
1418
1419 (js2-msg "msg.bad.decr"
1420 "Invalid decrement operand.")
1421
1422 (js2-msg "msg.bad.incr"
1423 "Invalid increment operand.")
1424
1425 (js2-msg "msg.bad.yield"
1426 "yield must be in a function.")
1427
1428 (js2-msg "msg.yield.parenthesized"
1429 "yield expression must be parenthesized.")
1430
1431 ;; NativeGlobal
1432 (js2-msg "msg.cant.call.indirect"
1433 "Function '%s' must be called directly, and not by way of a "
1434 "function of another name.")
1435
1436 (js2-msg "msg.eval.nonstring"
1437 "Calling eval() with anything other than a primitive "
1438 "string value will simply return the value. "
1439 "Is this what you intended?")
1440
1441 (js2-msg "msg.eval.nonstring.strict"
1442 "Calling eval() with anything other than a primitive "
1443 "string value is not allowed in strict mode.")
1444
1445 (js2-msg "msg.bad.destruct.op"
1446 "Invalid destructuring assignment operator")
1447
1448 ;; NativeCall
1449 (js2-msg "msg.only.from.new"
1450 "'%s' may only be invoked from a `new' expression.")
1451
1452 (js2-msg "msg.deprec.ctor"
1453 "The '%s' constructor is deprecated.")
1454
1455 ;; NativeFunction
1456 (js2-msg "msg.no.function.ref.found"
1457 "no source found to decompile function reference %s")
1458
1459 (js2-msg "msg.arg.isnt.array"
1460 "second argument to Function.prototype.apply must be an array")
1461
1462 ;; NativeGlobal
1463 (js2-msg "msg.bad.esc.mask"
1464 "invalid string escape mask")
1465
1466 ;; NativeRegExp
1467 (js2-msg "msg.bad.quant"
1468 "Invalid quantifier %s")
1469
1470 (js2-msg "msg.overlarge.backref"
1471 "Overly large back reference %s")
1472
1473 (js2-msg "msg.overlarge.min"
1474 "Overly large minimum %s")
1475
1476 (js2-msg "msg.overlarge.max"
1477 "Overly large maximum %s")
1478
1479 (js2-msg "msg.zero.quant"
1480 "Zero quantifier %s")
1481
1482 (js2-msg "msg.max.lt.min"
1483 "Maximum %s less than minimum")
1484
1485 (js2-msg "msg.unterm.quant"
1486 "Unterminated quantifier %s")
1487
1488 (js2-msg "msg.unterm.paren"
1489 "Unterminated parenthetical %s")
1490
1491 (js2-msg "msg.unterm.class"
1492 "Unterminated character class %s")
1493
1494 (js2-msg "msg.bad.range"
1495 "Invalid range in character class.")
1496
1497 (js2-msg "msg.trail.backslash"
1498 "Trailing \\ in regular expression.")
1499
1500 (js2-msg "msg.re.unmatched.right.paren"
1501 "unmatched ) in regular expression.")
1502
1503 (js2-msg "msg.no.regexp"
1504 "Regular expressions are not available.")
1505
1506 (js2-msg "msg.bad.backref"
1507 "back-reference exceeds number of capturing parentheses.")
1508
1509 (js2-msg "msg.bad.regexp.compile"
1510 "Only one argument may be specified if the first "
1511 "argument to RegExp.prototype.compile is a RegExp object.")
1512
1513 ;; Parser
1514 (js2-msg "msg.got.syntax.errors"
1515 "Compilation produced %s syntax errors.")
1516
1517 (js2-msg "msg.var.redecl"
1518 "TypeError: redeclaration of var %s.")
1519
1520 (js2-msg "msg.const.redecl"
1521 "TypeError: redeclaration of const %s.")
1522
1523 (js2-msg "msg.let.redecl"
1524 "TypeError: redeclaration of variable %s.")
1525
1526 (js2-msg "msg.parm.redecl"
1527 "TypeError: redeclaration of formal parameter %s.")
1528
1529 (js2-msg "msg.fn.redecl"
1530 "TypeError: redeclaration of function %s.")
1531
1532 (js2-msg "msg.let.decl.not.in.block"
1533 "SyntaxError: let declaration not directly within block")
1534
1535 (js2-msg "msg.mod.import.decl.at.top.level"
1536 "SyntaxError: import declarations may only appear at the top level")
1537
1538 (js2-msg "msg.mod.as.after.reserved.word"
1539 "SyntaxError: missing keyword 'as' after reserved word %s")
1540
1541 (js2-msg "msg.mod.rc.after.import.spec.list"
1542 "SyntaxError: missing '}' after module specifier list")
1543
1544 (js2-msg "msg.mod.from.after.import.spec.set"
1545 "SyntaxError: missing keyword 'from' after import specifier set")
1546
1547 (js2-msg "msg.mod.declaration.after.import"
1548 "SyntaxError: missing declaration after 'import' keyword")
1549
1550 (js2-msg "msg.mod.spec.after.from"
1551 "SyntaxError: missing module specifier after 'from' keyword")
1552
1553 (js2-msg "msg.mod.export.decl.at.top.level"
1554 "SyntaxError: export declarations may only appear at top level")
1555
1556 (js2-msg "msg.mod.rc.after.export.spec.list"
1557 "SyntaxError: missing '}' after export specifier list")
1558
1559 ;; NodeTransformer
1560 (js2-msg "msg.dup.label"
1561 "duplicated label")
1562
1563 (js2-msg "msg.undef.label"
1564 "undefined label")
1565
1566 (js2-msg "msg.bad.break"
1567 "unlabelled break must be inside loop or switch")
1568
1569 (js2-msg "msg.continue.outside"
1570 "continue must be inside loop")
1571
1572 (js2-msg "msg.continue.nonloop"
1573 "continue can only use labels of iteration statements")
1574
1575 (js2-msg "msg.bad.throw.eol"
1576 "Line terminator is not allowed between the throw "
1577 "keyword and throw expression.")
1578
1579 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1580 "function statement requires a name")
1581
1582 (js2-msg "msg.no.paren.parms"
1583 "missing ( before function parameters.")
1584
1585 (js2-msg "msg.no.parm"
1586 "missing formal parameter")
1587
1588 (js2-msg "msg.no.paren.after.parms"
1589 "missing ) after formal parameters")
1590
1591 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1592 "parameter without default follows parameter with default")
1593
1594 (js2-msg "msg.param.after.rest" ; added by js2-mode
1595 "parameter after rest parameter")
1596
1597 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1598 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1599
1600 (js2-msg "msg.no.brace.body"
1601 "missing '{' before function body")
1602
1603 (js2-msg "msg.no.brace.after.body"
1604 "missing } after function body")
1605
1606 (js2-msg "msg.no.paren.cond"
1607 "missing ( before condition")
1608
1609 (js2-msg "msg.no.paren.after.cond"
1610 "missing ) after condition")
1611
1612 (js2-msg "msg.no.semi.stmt"
1613 "missing ; before statement")
1614
1615 (js2-msg "msg.missing.semi"
1616 "missing ; after statement")
1617
1618 (js2-msg "msg.no.name.after.dot"
1619 "missing name after . operator")
1620
1621 (js2-msg "msg.no.name.after.coloncolon"
1622 "missing name after :: operator")
1623
1624 (js2-msg "msg.no.name.after.dotdot"
1625 "missing name after .. operator")
1626
1627 (js2-msg "msg.no.name.after.xmlAttr"
1628 "missing name after .@")
1629
1630 (js2-msg "msg.no.bracket.index"
1631 "missing ] in index expression")
1632
1633 (js2-msg "msg.no.paren.switch"
1634 "missing ( before switch expression")
1635
1636 (js2-msg "msg.no.paren.after.switch"
1637 "missing ) after switch expression")
1638
1639 (js2-msg "msg.no.brace.switch"
1640 "missing '{' before switch body")
1641
1642 (js2-msg "msg.bad.switch"
1643 "invalid switch statement")
1644
1645 (js2-msg "msg.no.colon.case"
1646 "missing : after case expression")
1647
1648 (js2-msg "msg.double.switch.default"
1649 "double default label in the switch statement")
1650
1651 (js2-msg "msg.no.while.do"
1652 "missing while after do-loop body")
1653
1654 (js2-msg "msg.no.paren.for"
1655 "missing ( after for")
1656
1657 (js2-msg "msg.no.semi.for"
1658 "missing ; after for-loop initializer")
1659
1660 (js2-msg "msg.no.semi.for.cond"
1661 "missing ; after for-loop condition")
1662
1663 (js2-msg "msg.in.after.for.name"
1664 "missing in or of after for")
1665
1666 (js2-msg "msg.no.paren.for.ctrl"
1667 "missing ) after for-loop control")
1668
1669 (js2-msg "msg.no.paren.with"
1670 "missing ( before with-statement object")
1671
1672 (js2-msg "msg.no.paren.after.with"
1673 "missing ) after with-statement object")
1674
1675 (js2-msg "msg.no.with.strict"
1676 "with statements not allowed in strict mode")
1677
1678 (js2-msg "msg.no.paren.after.let"
1679 "missing ( after let")
1680
1681 (js2-msg "msg.no.paren.let"
1682 "missing ) after variable list")
1683
1684 (js2-msg "msg.no.curly.let"
1685 "missing } after let statement")
1686
1687 (js2-msg "msg.bad.return"
1688 "invalid return")
1689
1690 (js2-msg "msg.no.brace.block"
1691 "missing } in compound statement")
1692
1693 (js2-msg "msg.bad.label"
1694 "invalid label")
1695
1696 (js2-msg "msg.bad.var"
1697 "missing variable name")
1698
1699 (js2-msg "msg.bad.var.init"
1700 "invalid variable initialization")
1701
1702 (js2-msg "msg.no.colon.cond"
1703 "missing : in conditional expression")
1704
1705 (js2-msg "msg.no.paren.arg"
1706 "missing ) after argument list")
1707
1708 (js2-msg "msg.no.bracket.arg"
1709 "missing ] after element list")
1710
1711 (js2-msg "msg.bad.prop"
1712 "invalid property id")
1713
1714 (js2-msg "msg.no.colon.prop"
1715 "missing : after property id")
1716
1717 (js2-msg "msg.no.brace.prop"
1718 "missing } after property list")
1719
1720 (js2-msg "msg.no.paren"
1721 "missing ) in parenthetical")
1722
1723 (js2-msg "msg.reserved.id"
1724 "'%s' is a reserved identifier")
1725
1726 (js2-msg "msg.no.paren.catch"
1727 "missing ( before catch-block condition")
1728
1729 (js2-msg "msg.bad.catchcond"
1730 "invalid catch block condition")
1731
1732 (js2-msg "msg.catch.unreachable"
1733 "any catch clauses following an unqualified catch are unreachable")
1734
1735 (js2-msg "msg.no.brace.try"
1736 "missing '{' before try block")
1737
1738 (js2-msg "msg.no.brace.catchblock"
1739 "missing '{' before catch-block body")
1740
1741 (js2-msg "msg.try.no.catchfinally"
1742 "'try' without 'catch' or 'finally'")
1743
1744 (js2-msg "msg.no.return.value"
1745 "function %s does not always return a value")
1746
1747 (js2-msg "msg.anon.no.return.value"
1748 "anonymous function does not always return a value")
1749
1750 (js2-msg "msg.return.inconsistent"
1751 "return statement is inconsistent with previous usage")
1752
1753 (js2-msg "msg.generator.returns"
1754 "TypeError: legacy generator function '%s' returns a value")
1755
1756 (js2-msg "msg.anon.generator.returns"
1757 "TypeError: anonymous legacy generator function returns a value")
1758
1759 (js2-msg "msg.syntax"
1760 "syntax error")
1761
1762 (js2-msg "msg.unexpected.eof"
1763 "Unexpected end of file")
1764
1765 (js2-msg "msg.XML.bad.form"
1766 "illegally formed XML syntax")
1767
1768 (js2-msg "msg.XML.not.available"
1769 "XML runtime not available")
1770
1771 (js2-msg "msg.too.deep.parser.recursion"
1772 "Too deep recursion while parsing")
1773
1774 (js2-msg "msg.no.side.effects"
1775 "Code has no side effects")
1776
1777 (js2-msg "msg.extra.trailing.comma"
1778 "Trailing comma is not supported in some browsers")
1779
1780 (js2-msg "msg.array.trailing.comma"
1781 "Trailing comma yields different behavior across browsers")
1782
1783 (js2-msg "msg.equal.as.assign"
1784 (concat "Test for equality (==) mistyped as assignment (=)?"
1785 " (parenthesize to suppress warning)"))
1786
1787 (js2-msg "msg.var.hides.arg"
1788 "Variable %s hides argument")
1789
1790 (js2-msg "msg.destruct.assign.no.init"
1791 "Missing = in destructuring declaration")
1792
1793 (js2-msg "msg.no.octal.strict"
1794 "Octal numbers prohibited in strict mode.")
1795
1796 (js2-msg "msg.dup.obj.lit.prop.strict"
1797 "Property '%s' already defined in this object literal.")
1798
1799 (js2-msg "msg.dup.param.strict"
1800 "Parameter '%s' already declared in this function.")
1801
1802 (js2-msg "msg.bad.id.strict"
1803 "'%s' is not a valid identifier for this use in strict mode.")
1804
1805 ;; ScriptRuntime
1806 (js2-msg "msg.no.properties"
1807 "%s has no properties.")
1808
1809 (js2-msg "msg.invalid.iterator"
1810 "Invalid iterator value")
1811
1812 (js2-msg "msg.iterator.primitive"
1813 "__iterator__ returned a primitive value")
1814
1815 (js2-msg "msg.assn.create.strict"
1816 "Assignment to undeclared variable %s")
1817
1818 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1819 "Undeclared variable or function '%s'")
1820
1821 (js2-msg "msg.unused.variable" ; added by js2-mode
1822 "Unused variable or function '%s'")
1823
1824 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1825 "Variable '%s' referenced but never initialized")
1826
1827 (js2-msg "msg.ref.undefined.prop"
1828 "Reference to undefined property '%s'")
1829
1830 (js2-msg "msg.prop.not.found"
1831 "Property %s not found.")
1832
1833 (js2-msg "msg.invalid.type"
1834 "Invalid JavaScript value of type %s")
1835
1836 (js2-msg "msg.primitive.expected"
1837 "Primitive type expected (had %s instead)")
1838
1839 (js2-msg "msg.namespace.expected"
1840 "Namespace object expected to left of :: (found %s instead)")
1841
1842 (js2-msg "msg.null.to.object"
1843 "Cannot convert null to an object.")
1844
1845 (js2-msg "msg.undef.to.object"
1846 "Cannot convert undefined to an object.")
1847
1848 (js2-msg "msg.cyclic.value"
1849 "Cyclic %s value not allowed.")
1850
1851 (js2-msg "msg.is.not.defined"
1852 "'%s' is not defined.")
1853
1854 (js2-msg "msg.undef.prop.read"
1855 "Cannot read property '%s' from %s")
1856
1857 (js2-msg "msg.undef.prop.write"
1858 "Cannot set property '%s' of %s to '%s'")
1859
1860 (js2-msg "msg.undef.prop.delete"
1861 "Cannot delete property '%s' of %s")
1862
1863 (js2-msg "msg.undef.method.call"
1864 "Cannot call method '%s' of %s")
1865
1866 (js2-msg "msg.undef.with"
1867 "Cannot apply 'with' to %s")
1868
1869 (js2-msg "msg.isnt.function"
1870 "%s is not a function, it is %s.")
1871
1872 (js2-msg "msg.isnt.function.in"
1873 "Cannot call property %s in object %s. "
1874 "It is not a function, it is '%s'.")
1875
1876 (js2-msg "msg.function.not.found"
1877 "Cannot find function %s.")
1878
1879 (js2-msg "msg.function.not.found.in"
1880 "Cannot find function %s in object %s.")
1881
1882 (js2-msg "msg.isnt.xml.object"
1883 "%s is not an xml object.")
1884
1885 (js2-msg "msg.no.ref.to.get"
1886 "%s is not a reference to read reference value.")
1887
1888 (js2-msg "msg.no.ref.to.set"
1889 "%s is not a reference to set reference value to %s.")
1890
1891 (js2-msg "msg.no.ref.from.function"
1892 "Function %s can not be used as the left-hand "
1893 "side of assignment or as an operand of ++ or -- operator.")
1894
1895 (js2-msg "msg.bad.default.value"
1896 "Object's getDefaultValue() method returned an object.")
1897
1898 (js2-msg "msg.instanceof.not.object"
1899 "Can't use instanceof on a non-object.")
1900
1901 (js2-msg "msg.instanceof.bad.prototype"
1902 "'prototype' property of %s is not an object.")
1903
1904 (js2-msg "msg.bad.radix"
1905 "illegal radix %s.")
1906
1907 ;; ScriptableObject
1908 (js2-msg "msg.default.value"
1909 "Cannot find default value for object.")
1910
1911 (js2-msg "msg.zero.arg.ctor"
1912 "Cannot load class '%s' which has no zero-parameter constructor.")
1913
1914 (js2-msg "msg.ctor.multiple.parms"
1915 "Can't define constructor or class %s since more than "
1916 "one constructor has multiple parameters.")
1917
1918 (js2-msg "msg.extend.scriptable"
1919 "%s must extend ScriptableObject in order to define property %s.")
1920
1921 (js2-msg "msg.bad.getter.parms"
1922 "In order to define a property, getter %s must have zero "
1923 "parameters or a single ScriptableObject parameter.")
1924
1925 (js2-msg "msg.obj.getter.parms"
1926 "Expected static or delegated getter %s to take "
1927 "a ScriptableObject parameter.")
1928
1929 (js2-msg "msg.getter.static"
1930 "Getter and setter must both be static or neither be static.")
1931
1932 (js2-msg "msg.setter.return"
1933 "Setter must have void return type: %s")
1934
1935 (js2-msg "msg.setter2.parms"
1936 "Two-parameter setter must take a ScriptableObject as "
1937 "its first parameter.")
1938
1939 (js2-msg "msg.setter1.parms"
1940 "Expected single parameter setter for %s")
1941
1942 (js2-msg "msg.setter2.expected"
1943 "Expected static or delegated setter %s to take two parameters.")
1944
1945 (js2-msg "msg.setter.parms"
1946 "Expected either one or two parameters for setter.")
1947
1948 (js2-msg "msg.setter.bad.type"
1949 "Unsupported parameter type '%s' in setter '%s'.")
1950
1951 (js2-msg "msg.add.sealed"
1952 "Cannot add a property to a sealed object: %s.")
1953
1954 (js2-msg "msg.remove.sealed"
1955 "Cannot remove a property from a sealed object: %s.")
1956
1957 (js2-msg "msg.modify.sealed"
1958 "Cannot modify a property of a sealed object: %s.")
1959
1960 (js2-msg "msg.modify.readonly"
1961 "Cannot modify readonly property: %s.")
1962
1963 ;; TokenStream
1964 (js2-msg "msg.missing.exponent"
1965 "missing exponent")
1966
1967 (js2-msg "msg.caught.nfe"
1968 "number format error")
1969
1970 (js2-msg "msg.unterminated.string.lit"
1971 "unterminated string literal")
1972
1973 (js2-msg "msg.unterminated.comment"
1974 "unterminated comment")
1975
1976 (js2-msg "msg.unterminated.re.lit"
1977 "unterminated regular expression literal")
1978
1979 (js2-msg "msg.invalid.re.flag"
1980 "invalid flag after regular expression")
1981
1982 (js2-msg "msg.no.re.input.for"
1983 "no input for %s")
1984
1985 (js2-msg "msg.illegal.character"
1986 "illegal character")
1987
1988 (js2-msg "msg.invalid.escape"
1989 "invalid Unicode escape sequence")
1990
1991 (js2-msg "msg.bad.namespace"
1992 "not a valid default namespace statement. "
1993 "Syntax is: default xml namespace = EXPRESSION;")
1994
1995 ;; TokensStream warnings
1996 (js2-msg "msg.bad.octal.literal"
1997 "illegal octal literal digit %s; "
1998 "interpreting it as a decimal digit")
1999
2000 (js2-msg "msg.missing.hex.digits"
2001 "missing hexadecimal digits after '0x'")
2002
2003 (js2-msg "msg.missing.binary.digits"
2004 "missing binary digits after '0b'")
2005
2006 (js2-msg "msg.missing.octal.digits"
2007 "missing octal digits after '0o'")
2008
2009 (js2-msg "msg.script.is.not.constructor"
2010 "Script objects are not constructors.")
2011
2012 ;; Arrays
2013 (js2-msg "msg.arraylength.bad"
2014 "Inappropriate array length.")
2015
2016 ;; Arrays
2017 (js2-msg "msg.arraylength.too.big"
2018 "Array length %s exceeds supported capacity limit.")
2019
2020 ;; URI
2021 (js2-msg "msg.bad.uri"
2022 "Malformed URI sequence.")
2023
2024 ;; Number
2025 (js2-msg "msg.bad.precision"
2026 "Precision %s out of range.")
2027
2028 ;; NativeGenerator
2029 (js2-msg "msg.send.newborn"
2030 "Attempt to send value to newborn generator")
2031
2032 (js2-msg "msg.already.exec.gen"
2033 "Already executing generator")
2034
2035 (js2-msg "msg.StopIteration.invalid"
2036 "StopIteration may not be changed to an arbitrary object.")
2037
2038 ;; Interpreter
2039 (js2-msg "msg.yield.closing"
2040 "Yield from closing generator")
2041
2042 ;; Classes
2043 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
2044 "class statement requires a name")
2045
2046 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
2047 "unexpected ',' between class properties")
2048
2049 (js2-msg "msg.unexpected.static" ; added by js2-mode
2050 "unexpected 'static'")
2051
2052 (js2-msg "msg.missing.extends" ; added by js2-mode
2053 "name is required after extends")
2054
2055 (js2-msg "msg.no.brace.class" ; added by js2-mode
2056 "missing '{' before class body")
2057
2058 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2059 "missing ']' after computed property expression")
2060
2061 ;;; Tokens Buffer
2062
2063 (defconst js2-ti-max-lookahead 2)
2064 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2065
2066 (defun js2-new-token (offset)
2067 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2068 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2069 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2070 token))
2071
2072 (defsubst js2-current-token ()
2073 (aref js2-ti-tokens js2-ti-tokens-cursor))
2074
2075 (defsubst js2-current-token-string ()
2076 (js2-token-string (js2-current-token)))
2077
2078 (defsubst js2-current-token-type ()
2079 (js2-token-type (js2-current-token)))
2080
2081 (defsubst js2-current-token-beg ()
2082 (js2-token-beg (js2-current-token)))
2083
2084 (defsubst js2-current-token-end ()
2085 (js2-token-end (js2-current-token)))
2086
2087 (defun js2-current-token-len ()
2088 (let ((token (js2-current-token)))
2089 (- (js2-token-end token)
2090 (js2-token-beg token))))
2091
2092 (defun js2-ts-seek (state)
2093 (setq js2-ts-lineno (js2-ts-state-lineno state)
2094 js2-ts-cursor (js2-ts-state-cursor state)
2095 js2-ti-tokens (js2-ts-state-tokens state)
2096 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2097 js2-ti-lookahead (js2-ts-state-lookahead state)))
2098
2099 ;;; Utilities
2100
2101 (defun js2-delete-if (predicate list)
2102 "Remove all items satisfying PREDICATE in LIST."
2103 (cl-loop for item in list
2104 if (not (funcall predicate item))
2105 collect item))
2106
2107 (defun js2-position (element list)
2108 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2109 Returns nil if element is not found in the list."
2110 (let ((count 0)
2111 found)
2112 (while (and list (not found))
2113 (if (eq element (car list))
2114 (setq found t)
2115 (setq count (1+ count)
2116 list (cdr list))))
2117 (if found count)))
2118
2119 (defun js2-find-if (predicate list)
2120 "Find first item satisfying PREDICATE in LIST."
2121 (let (result)
2122 (while (and list (not result))
2123 (if (funcall predicate (car list))
2124 (setq result (car list)))
2125 (setq list (cdr list)))
2126 result))
2127
2128 (defmacro js2-time (form)
2129 "Evaluate FORM, discard result, and return elapsed time in sec."
2130 (declare (debug t))
2131 (let ((beg (make-symbol "--js2-time-beg--")))
2132 `(let ((,beg (current-time)))
2133 ,form
2134 (/ (truncate (* (- (float-time (current-time))
2135 (float-time ,beg))
2136 10000))
2137 10000.0))))
2138
2139 (defsubst js2-same-line (pos)
2140 "Return t if POS is on the same line as current point."
2141 (and (>= pos (point-at-bol))
2142 (<= pos (point-at-eol))))
2143
2144 (defun js2-code-bug ()
2145 "Signal an error when we encounter an unexpected code path."
2146 (error "failed assertion"))
2147
2148 (defsubst js2-record-text-property (beg end prop value)
2149 "Record a text property to set when parsing finishes."
2150 (push (list beg end prop value) js2-mode-deferred-properties))
2151
2152 ;; I'd like to associate errors with nodes, but for now the
2153 ;; easiest thing to do is get the context info from the last token.
2154 (defun js2-record-parse-error (msg &optional arg pos len)
2155 (push (list (list msg arg)
2156 (or pos (js2-current-token-beg))
2157 (or len (js2-current-token-len)))
2158 js2-parsed-errors))
2159
2160 (defun js2-report-error (msg &optional msg-arg pos len)
2161 "Signal a syntax error or record a parse error."
2162 (if js2-recover-from-parse-errors
2163 (js2-record-parse-error msg msg-arg pos len)
2164 (signal 'js2-syntax-error
2165 (list msg
2166 js2-ts-lineno
2167 (save-excursion
2168 (goto-char js2-ts-cursor)
2169 (current-column))
2170 js2-ts-hit-eof))))
2171
2172 (defun js2-report-warning (msg &optional msg-arg pos len face)
2173 (if js2-compiler-report-warning-as-error
2174 (js2-report-error msg msg-arg pos len)
2175 (push (list (list msg msg-arg)
2176 (or pos (js2-current-token-beg))
2177 (or len (js2-current-token-len))
2178 face)
2179 js2-parsed-warnings)))
2180
2181 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2182 (if js2-compiler-strict-mode
2183 (js2-report-warning msg-id msg-arg beg
2184 (and beg end (- end beg)))))
2185
2186 (put 'js2-syntax-error 'error-conditions
2187 '(error syntax-error js2-syntax-error))
2188 (put 'js2-syntax-error 'error-message "Syntax error")
2189
2190 (put 'js2-parse-error 'error-conditions
2191 '(error parse-error js2-parse-error))
2192 (put 'js2-parse-error 'error-message "Parse error")
2193
2194 (defmacro js2-clear-flag (flags flag)
2195 `(setq ,flags (logand ,flags (lognot ,flag))))
2196
2197 (defmacro js2-set-flag (flags flag)
2198 "Logical-or FLAG into FLAGS."
2199 `(setq ,flags (logior ,flags ,flag)))
2200
2201 (defsubst js2-flag-set-p (flags flag)
2202 (/= 0 (logand flags flag)))
2203
2204 (defsubst js2-flag-not-set-p (flags flag)
2205 (zerop (logand flags flag)))
2206
2207 ;;; AST struct and function definitions
2208
2209 ;; flags for ast node property 'member-type (used for e4x operators)
2210 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2211 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2212 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2213
2214 (defsubst js2-relpos (pos anchor)
2215 "Convert POS to be relative to ANCHOR.
2216 If POS is nil, returns nil."
2217 (and pos (- pos anchor)))
2218
2219 (defun js2-make-pad (indent)
2220 (if (zerop indent)
2221 ""
2222 (make-string (* indent js2-basic-offset) ? )))
2223
2224 (defun js2-visit-ast (node callback)
2225 "Visit every node in ast NODE with visitor CALLBACK.
2226
2227 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2228 called twice: once to visit the node, and again after all the node's
2229 children have been processed. The END-P argument is nil on the first
2230 call and non-nil on the second call. The return value of the callback
2231 affects the traversal: if non-nil, the children of NODE are processed.
2232 If the callback returns nil, or if the node has no children, then the
2233 callback is called immediately with a non-nil END-P argument.
2234
2235 The node traversal is approximately lexical-order, although there
2236 are currently no guarantees around this."
2237 (when node
2238 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2239 ;; visit the node
2240 (when (funcall callback node nil)
2241 ;; visit the kids
2242 (cond
2243 ((eq vfunc 'js2-visit-none)
2244 nil) ; don't even bother calling it
2245 ;; Each AST node type has to define a `js2-visitor' function
2246 ;; that takes a node and a callback, and calls `js2-visit-ast'
2247 ;; on each child of the node.
2248 (vfunc
2249 (funcall vfunc node callback))
2250 (t
2251 (error "%s does not define a visitor-traversal function"
2252 (aref node 0)))))
2253 ;; call the end-visit
2254 (funcall callback node t))))
2255
2256 (cl-defstruct (js2-node
2257 (:constructor nil)) ; abstract
2258 "Base AST node type."
2259 (type -1) ; token type
2260 (pos -1) ; start position of this AST node in parsed input
2261 (len 1) ; num characters spanned by the node
2262 props ; optional node property list (an alist)
2263 parent) ; link to parent node; null for root
2264
2265 (defsubst js2-node-get-prop (node prop &optional default)
2266 (or (cadr (assoc prop (js2-node-props node))) default))
2267
2268 (defsubst js2-node-set-prop (node prop value)
2269 (setf (js2-node-props node)
2270 (cons (list prop value) (js2-node-props node))))
2271
2272 (defun js2-fixup-starts (n nodes)
2273 "Adjust the start positions of NODES to be relative to N.
2274 Any node in the list may be nil, for convenience."
2275 (dolist (node nodes)
2276 (when node
2277 (setf (js2-node-pos node) (- (js2-node-pos node)
2278 (js2-node-pos n))))))
2279
2280 (defun js2-node-add-children (parent &rest nodes)
2281 "Set parent node of NODES to PARENT, and return PARENT.
2282 Does nothing if we're not recording parent links.
2283 If any given node in NODES is nil, doesn't record that link."
2284 (js2-fixup-starts parent nodes)
2285 (dolist (node nodes)
2286 (and node
2287 (setf (js2-node-parent node) parent))))
2288
2289 ;; Non-recursive since it's called a frightening number of times.
2290 (defun js2-node-abs-pos (n)
2291 (let ((pos (js2-node-pos n)))
2292 (while (setq n (js2-node-parent n))
2293 (setq pos (+ pos (js2-node-pos n))))
2294 pos))
2295
2296 (defsubst js2-node-abs-end (n)
2297 "Return absolute buffer position of end of N."
2298 (+ (js2-node-abs-pos n) (js2-node-len n)))
2299
2300 ;; It's important to make sure block nodes have a Lisp list for the
2301 ;; child nodes, to limit printing recursion depth in an AST that
2302 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2303 ;; a sufficiently large vector tree.
2304
2305 (cl-defstruct (js2-block-node
2306 (:include js2-node)
2307 (:constructor nil)
2308 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2309 (pos (js2-current-token-beg))
2310 len
2311 props
2312 kids)))
2313 "A block of statements."
2314 kids) ; a Lisp list of the child statement nodes
2315
2316 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2317 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2318
2319 (defun js2-visit-block (ast callback)
2320 "Visit the `js2-block-node' children of AST."
2321 (dolist (kid (js2-block-node-kids ast))
2322 (js2-visit-ast kid callback)))
2323
2324 (defun js2-print-block (n i)
2325 (let ((pad (js2-make-pad i)))
2326 (insert pad "{\n")
2327 (dolist (kid (js2-block-node-kids n))
2328 (js2-print-ast kid (1+ i)))
2329 (insert pad "}")))
2330
2331 (cl-defstruct (js2-scope
2332 (:include js2-block-node)
2333 (:constructor nil)
2334 (:constructor make-js2-scope (&key (type js2-BLOCK)
2335 (pos (js2-current-token-beg))
2336 len
2337 kids)))
2338 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2339 ;; I don't have one of those handy, so I'll use an alist for now.
2340 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2341 ;; and is much lighter-weight to construct (both CPU and mem).
2342 ;; The keys are interned strings (symbols) for faster lookup.
2343 ;; Should switch to hybrid alist/hashtable eventually.
2344 symbol-table ; an alist of (symbol . js2-symbol)
2345 parent-scope ; a `js2-scope'
2346 top) ; top-level `js2-scope' (script/function)
2347
2348 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2349 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2350
2351 (defun js2-node-get-enclosing-scope (node)
2352 "Return the innermost `js2-scope' node surrounding NODE.
2353 Returns nil if there is no enclosing scope node."
2354 (while (and (setq node (js2-node-parent node))
2355 (not (js2-scope-p node))))
2356 node)
2357
2358 (defun js2-get-defining-scope (scope name &optional point)
2359 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2360 Returns `js2-scope' in which NAME is defined, or nil if not found.
2361
2362 If POINT is non-nil, and if the found declaration type is
2363 `js2-LET', also check that the declaration node is before POINT."
2364 (let ((sym (if (symbolp name)
2365 name
2366 (intern name)))
2367 result
2368 (continue t))
2369 (while (and scope continue)
2370 (if (or
2371 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2372 (and entry
2373 (or (not point)
2374 (not (eq js2-LET (js2-symbol-decl-type entry)))
2375 (>= point
2376 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2377 (and (eq sym 'arguments)
2378 (js2-function-node-p scope)))
2379 (setq continue nil
2380 result scope)
2381 (setq scope (js2-scope-parent-scope scope))))
2382 result))
2383
2384 (defun js2-scope-get-symbol (scope name)
2385 "Return symbol table entry for NAME in SCOPE.
2386 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2387 (and (js2-scope-symbol-table scope)
2388 (cdr (assq (if (symbolp name)
2389 name
2390 (intern name))
2391 (js2-scope-symbol-table scope)))))
2392
2393 (defun js2-scope-put-symbol (scope name symbol)
2394 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2395 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2396 (let* ((table (js2-scope-symbol-table scope))
2397 (sym (if (symbolp name) name (intern name)))
2398 (entry (assq sym table)))
2399 (if entry
2400 (setcdr entry symbol)
2401 (push (cons sym symbol)
2402 (js2-scope-symbol-table scope)))))
2403
2404 (cl-defstruct (js2-symbol
2405 (:constructor nil)
2406 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2407 "A symbol table entry."
2408 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2409 ;; js2-LET, or js2-CONST
2410 decl-type
2411 name ; string
2412 ast-node) ; a `js2-node'
2413
2414 (cl-defstruct (js2-error-node
2415 (:include js2-node)
2416 (:constructor nil) ; silence emacs21 byte-compiler
2417 (:constructor make-js2-error-node (&key (type js2-ERROR)
2418 (pos (js2-current-token-beg))
2419 len)))
2420 "AST node representing a parse error.")
2421
2422 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2423 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2424
2425 (cl-defstruct (js2-script-node
2426 (:include js2-scope)
2427 (:constructor nil)
2428 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2429 (pos (js2-current-token-beg))
2430 len
2431 ;; FIXME: What are those?
2432 var-decls
2433 fun-decls)))
2434 functions ; Lisp list of nested functions
2435 regexps ; Lisp list of (string . flags)
2436 symbols ; alist (every symbol gets unique index)
2437 (param-count 0)
2438 var-names ; vector of string names
2439 consts ; bool-vector matching var-decls
2440 (temp-number 0)) ; for generating temp variables
2441
2442 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2443 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2444
2445 (defun js2-print-script (node indent)
2446 (dolist (kid (js2-block-node-kids node))
2447 (js2-print-ast kid indent)))
2448
2449 (cl-defstruct (js2-ast-root
2450 (:include js2-script-node)
2451 (:constructor nil)
2452 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2453 (pos (js2-current-token-beg))
2454 len
2455 buffer)))
2456 "The root node of a js2 AST."
2457 buffer ; the source buffer from which the code was parsed
2458 comments ; a Lisp list of comments, ordered by start position
2459 errors ; a Lisp list of errors found during parsing
2460 warnings ; a Lisp list of warnings found during parsing
2461 node-count) ; number of nodes in the tree, including the root
2462
2463 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2464 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2465
2466 (defun js2-visit-ast-root (ast callback)
2467 (dolist (kid (js2-ast-root-kids ast))
2468 (js2-visit-ast kid callback))
2469 (dolist (comment (js2-ast-root-comments ast))
2470 (js2-visit-ast comment callback)))
2471
2472 (cl-defstruct (js2-comment-node
2473 (:include js2-node)
2474 (:constructor nil)
2475 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2476 (pos (js2-current-token-beg))
2477 len
2478 format)))
2479 format) ; 'line, 'block, 'jsdoc or 'html
2480
2481 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2482 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2483
2484 (defun js2-print-comment (n i)
2485 ;; We really ought to link end-of-line comments to their nodes.
2486 ;; Or maybe we could add a new comment type, 'endline.
2487 (insert (js2-make-pad i)
2488 (js2-node-string n)))
2489
2490 (cl-defstruct (js2-expr-stmt-node
2491 (:include js2-node)
2492 (:constructor nil)
2493 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2494 (pos js2-ts-cursor)
2495 len
2496 expr)))
2497 "An expression statement."
2498 expr)
2499
2500 (defsubst js2-expr-stmt-node-set-has-result (node)
2501 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2502 (setf (js2-node-type node) js2-EXPR_RESULT))
2503
2504 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2505 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2506
2507 (defun js2-visit-expr-stmt-node (n v)
2508 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2509
2510 (defun js2-print-expr-stmt-node (n indent)
2511 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2512 (insert ";\n"))
2513
2514 (cl-defstruct (js2-loop-node
2515 (:include js2-scope)
2516 (:constructor nil))
2517 "Abstract supertype of loop nodes."
2518 body ; a `js2-block-node'
2519 lp ; position of left-paren, nil if omitted
2520 rp) ; position of right-paren, nil if omitted
2521
2522 (cl-defstruct (js2-do-node
2523 (:include js2-loop-node)
2524 (:constructor nil)
2525 (:constructor make-js2-do-node (&key (type js2-DO)
2526 (pos (js2-current-token-beg))
2527 len
2528 body
2529 condition
2530 while-pos
2531 lp
2532 rp)))
2533 "AST node for do-loop."
2534 condition ; while (expression)
2535 while-pos) ; buffer position of 'while' keyword
2536
2537 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2538 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2539
2540 (defun js2-visit-do-node (n v)
2541 (js2-visit-ast (js2-do-node-body n) v)
2542 (js2-visit-ast (js2-do-node-condition n) v))
2543
2544 (defun js2-print-do-node (n i)
2545 (let ((pad (js2-make-pad i)))
2546 (insert pad "do {\n")
2547 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2548 (js2-print-ast kid (1+ i)))
2549 (insert pad "} while (")
2550 (js2-print-ast (js2-do-node-condition n) 0)
2551 (insert ");\n")))
2552
2553 (cl-defstruct (js2-export-node
2554 (:include js2-node)
2555 (:constructor nil)
2556 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2557 (pos (js2-current-token-beg))
2558 len
2559 exports-list
2560 from-clause
2561 declaration
2562 default)))
2563 "AST node for an export statement. There are many things that can be exported,
2564 so many of its properties will be nil.
2565 "
2566 exports-list ; lisp list of js2-export-binding-node to export
2567 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2568 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2569 default) ; js2-function-node or js2-assign-node
2570
2571 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2572 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2573
2574 (defun js2-visit-export-node (n v)
2575 (let ((exports-list (js2-export-node-exports-list n))
2576 (from (js2-export-node-from-clause n))
2577 (declaration (js2-export-node-declaration n))
2578 (default (js2-export-node-default n)))
2579 (when exports-list
2580 (dolist (export exports-list)
2581 (js2-visit-ast export v)))
2582 (when from
2583 (js2-visit-ast from v))
2584 (when declaration
2585 (js2-visit-ast declaration v))
2586 (when default
2587 (js2-visit-ast default v))))
2588
2589 (defun js2-print-export-node (n i)
2590 (let ((pad (js2-make-pad i))
2591 (exports-list (js2-export-node-exports-list n))
2592 (from (js2-export-node-from-clause n))
2593 (declaration (js2-export-node-declaration n))
2594 (default (js2-export-node-default n)))
2595 (insert pad "export ")
2596 (cond
2597 (default
2598 (insert "default ")
2599 (js2-print-ast default i))
2600 (declaration
2601 (js2-print-ast declaration i))
2602 ((and exports-list from)
2603 (js2-print-named-imports exports-list)
2604 (insert " ")
2605 (js2-print-from-clause from))
2606 (from
2607 (insert "* ")
2608 (js2-print-from-clause from))
2609 (exports-list
2610 (js2-print-named-imports exports-list)))
2611 (insert ";\n")))
2612
2613 (cl-defstruct (js2-while-node
2614 (:include js2-loop-node)
2615 (:constructor nil)
2616 (:constructor make-js2-while-node (&key (type js2-WHILE)
2617 (pos (js2-current-token-beg))
2618 len body
2619 condition lp
2620 rp)))
2621 "AST node for while-loop."
2622 condition) ; while-condition
2623
2624 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2625 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2626
2627 (defun js2-visit-while-node (n v)
2628 (js2-visit-ast (js2-while-node-condition n) v)
2629 (js2-visit-ast (js2-while-node-body n) v))
2630
2631 (defun js2-print-while-node (n i)
2632 (let ((pad (js2-make-pad i)))
2633 (insert pad "while (")
2634 (js2-print-ast (js2-while-node-condition n) 0)
2635 (insert ") {\n")
2636 (js2-print-body (js2-while-node-body n) (1+ i))
2637 (insert pad "}\n")))
2638
2639 (cl-defstruct (js2-for-node
2640 (:include js2-loop-node)
2641 (:constructor nil)
2642 (:constructor make-js2-for-node (&key (type js2-FOR)
2643 (pos js2-ts-cursor)
2644 len body init
2645 condition
2646 update lp rp)))
2647 "AST node for a C-style for-loop."
2648 init ; initialization expression
2649 condition ; loop condition
2650 update) ; update clause
2651
2652 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2653 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2654
2655 (defun js2-visit-for-node (n v)
2656 (js2-visit-ast (js2-for-node-init n) v)
2657 (js2-visit-ast (js2-for-node-condition n) v)
2658 (js2-visit-ast (js2-for-node-update n) v)
2659 (js2-visit-ast (js2-for-node-body n) v))
2660
2661 (defun js2-print-for-node (n i)
2662 (let ((pad (js2-make-pad i)))
2663 (insert pad "for (")
2664 (js2-print-ast (js2-for-node-init n) 0)
2665 (insert "; ")
2666 (js2-print-ast (js2-for-node-condition n) 0)
2667 (insert "; ")
2668 (js2-print-ast (js2-for-node-update n) 0)
2669 (insert ") {\n")
2670 (js2-print-body (js2-for-node-body n) (1+ i))
2671 (insert pad "}\n")))
2672
2673 (cl-defstruct (js2-for-in-node
2674 (:include js2-loop-node)
2675 (:constructor nil)
2676 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2677 (pos js2-ts-cursor)
2678 len body
2679 iterator
2680 object
2681 in-pos
2682 each-pos
2683 foreach-p forof-p
2684 lp rp)))
2685 "AST node for a for..in loop."
2686 iterator ; [var] foo in ...
2687 object ; object over which we're iterating
2688 in-pos ; buffer position of 'in' keyword
2689 each-pos ; buffer position of 'each' keyword, if foreach-p
2690 foreach-p ; t if it's a for-each loop
2691 forof-p) ; t if it's a for-of loop
2692
2693 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2694 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2695
2696 (defun js2-visit-for-in-node (n v)
2697 (js2-visit-ast (js2-for-in-node-iterator n) v)
2698 (js2-visit-ast (js2-for-in-node-object n) v)
2699 (js2-visit-ast (js2-for-in-node-body n) v))
2700
2701 (defun js2-print-for-in-node (n i)
2702 (let ((pad (js2-make-pad i))
2703 (foreach (js2-for-in-node-foreach-p n))
2704 (forof (js2-for-in-node-forof-p n)))
2705 (insert pad "for ")
2706 (if foreach
2707 (insert "each "))
2708 (insert "(")
2709 (js2-print-ast (js2-for-in-node-iterator n) 0)
2710 (insert (if forof " of " " in "))
2711 (js2-print-ast (js2-for-in-node-object n) 0)
2712 (insert ") {\n")
2713 (js2-print-body (js2-for-in-node-body n) (1+ i))
2714 (insert pad "}\n")))
2715
2716 (cl-defstruct (js2-return-node
2717 (:include js2-node)
2718 (:constructor nil)
2719 (:constructor make-js2-return-node (&key (type js2-RETURN)
2720 (pos js2-ts-cursor)
2721 len
2722 retval)))
2723 "AST node for a return statement."
2724 retval) ; expression to return, or 'undefined
2725
2726 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2727 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2728
2729 (defun js2-visit-return-node (n v)
2730 (js2-visit-ast (js2-return-node-retval n) v))
2731
2732 (defun js2-print-return-node (n i)
2733 (insert (js2-make-pad i) "return")
2734 (when (js2-return-node-retval n)
2735 (insert " ")
2736 (js2-print-ast (js2-return-node-retval n) 0))
2737 (insert ";\n"))
2738
2739 (cl-defstruct (js2-if-node
2740 (:include js2-node)
2741 (:constructor nil)
2742 (:constructor make-js2-if-node (&key (type js2-IF)
2743 (pos js2-ts-cursor)
2744 len condition
2745 then-part
2746 else-pos
2747 else-part lp
2748 rp)))
2749 "AST node for an if-statement."
2750 condition ; expression
2751 then-part ; statement or block
2752 else-pos ; optional buffer position of 'else' keyword
2753 else-part ; optional statement or block
2754 lp ; position of left-paren, nil if omitted
2755 rp) ; position of right-paren, nil if omitted
2756
2757 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2758 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2759
2760 (defun js2-visit-if-node (n v)
2761 (js2-visit-ast (js2-if-node-condition n) v)
2762 (js2-visit-ast (js2-if-node-then-part n) v)
2763 (js2-visit-ast (js2-if-node-else-part n) v))
2764
2765 (defun js2-print-if-node (n i)
2766 (let ((pad (js2-make-pad i))
2767 (then-part (js2-if-node-then-part n))
2768 (else-part (js2-if-node-else-part n)))
2769 (insert pad "if (")
2770 (js2-print-ast (js2-if-node-condition n) 0)
2771 (insert ") {\n")
2772 (js2-print-body then-part (1+ i))
2773 (insert pad "}")
2774 (cond
2775 ((not else-part)
2776 (insert "\n"))
2777 ((js2-if-node-p else-part)
2778 (insert " else ")
2779 (js2-print-body else-part i))
2780 (t
2781 (insert " else {\n")
2782 (js2-print-body else-part (1+ i))
2783 (insert pad "}\n")))))
2784
2785 (cl-defstruct (js2-export-binding-node
2786 (:include js2-node)
2787 (:constructor nil)
2788 (:constructor make-js2-export-binding-node (&key (type -1)
2789 pos
2790 len
2791 local-name
2792 extern-name)))
2793 "AST node for an external symbol binding.
2794 It contains a local-name node which is the name of the value in the
2795 current scope, and extern-name which is the name of the value in the
2796 imported or exported scope. By default these are the same, but if the
2797 name is aliased as in {foo as bar}, it would have an extern-name node
2798 containing 'foo' and a local-name node containing 'bar'."
2799 local-name ; js2-name-node with the variable name in this scope
2800 extern-name) ; js2-name-node with the value name in the exporting module
2801
2802 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2803 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2804
2805 (defun js2-visit-extern-binding (n v)
2806 "Visit an extern binding node. First visit the local-name, and, if
2807 different, visit the extern-name."
2808 (let ((local-name (js2-export-binding-node-local-name n))
2809 (extern-name (js2-export-binding-node-extern-name n)))
2810 (when local-name
2811 (js2-visit-ast local-name v))
2812 (when (not (equal local-name extern-name))
2813 (js2-visit-ast extern-name v))))
2814
2815 (defun js2-print-extern-binding (n _i)
2816 "Print a representation of a single extern binding. E.g. 'foo' or
2817 'foo as bar'."
2818 (let ((local-name (js2-export-binding-node-local-name n))
2819 (extern-name (js2-export-binding-node-extern-name n)))
2820 (insert (js2-name-node-name extern-name))
2821 (when (not (equal local-name extern-name))
2822 (insert " as ")
2823 (insert (js2-name-node-name local-name)))))
2824
2825
2826 (cl-defstruct (js2-import-node
2827 (:include js2-node)
2828 (:constructor nil)
2829 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2830 (pos (js2-current-token-beg))
2831 len
2832 import
2833 from
2834 module-id)))
2835 "AST node for an import statement. It follows the form
2836
2837 import ModuleSpecifier;
2838 import ImportClause FromClause;"
2839 import ; js2-import-clause-node specifying which names are to imported.
2840 from ; js2-from-clause-node indicating the module from which to import.
2841 module-id) ; module-id of the import. E.g. 'src/mylib'.
2842
2843 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2844 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2845
2846 (defun js2-visit-import (n v)
2847 (let ((import-clause (js2-import-node-import n))
2848 (from-clause (js2-import-node-from n)))
2849 (when import-clause
2850 (js2-visit-ast import-clause v))
2851 (when from-clause
2852 (js2-visit-ast from-clause v))))
2853
2854 (defun js2-print-import (n i)
2855 "Prints a representation of the import node"
2856 (let ((pad (js2-make-pad i))
2857 (import-clause (js2-import-node-import n))
2858 (from-clause (js2-import-node-from n))
2859 (module-id (js2-import-node-module-id n)))
2860 (insert pad "import ")
2861 (if import-clause
2862 (progn
2863 (js2-print-import-clause import-clause)
2864 (insert " ")
2865 (js2-print-from-clause from-clause))
2866 (insert "'")
2867 (insert module-id)
2868 (insert "'"))
2869 (insert ";\n")))
2870
2871 (cl-defstruct (js2-import-clause-node
2872 (:include js2-node)
2873 (:constructor nil)
2874 (:constructor make-js2-import-clause-node (&key (type -1)
2875 pos
2876 len
2877 namespace-import
2878 named-imports
2879 default-binding)))
2880 "AST node corresponding to the import clause of an import statement. This is
2881 the portion of the import that bindings names from the external context to the
2882 local context."
2883 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2884 named-imports ; lisp list of js2-export-binding-node for all named imports.
2885 default-binding) ; js2-export-binding-node for the default import binding
2886
2887 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2888 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2889
2890 (defun js2-visit-import-clause (n v)
2891 (let ((ns-import (js2-import-clause-node-namespace-import n))
2892 (named-imports (js2-import-clause-node-named-imports n))
2893 (default (js2-import-clause-node-default-binding n)))
2894 (when ns-import
2895 (js2-visit-ast ns-import v))
2896 (when named-imports
2897 (dolist (import named-imports)
2898 (js2-visit-ast import v)))
2899 (when default
2900 (js2-visit-ast default v))))
2901
2902 (defun js2-print-import-clause (n)
2903 (let ((ns-import (js2-import-clause-node-namespace-import n))
2904 (named-imports (js2-import-clause-node-named-imports n))
2905 (default (js2-import-clause-node-default-binding n)))
2906 (cond
2907 ((and default ns-import)
2908 (js2-print-ast default)
2909 (insert ", ")
2910 (js2-print-namespace-import ns-import))
2911 ((and default named-imports)
2912 (js2-print-ast default)
2913 (insert ", ")
2914 (js2-print-named-imports named-imports))
2915 (default
2916 (js2-print-ast default))
2917 (ns-import
2918 (js2-print-namespace-import ns-import))
2919 (named-imports
2920 (js2-print-named-imports named-imports)))))
2921
2922 (defun js2-print-namespace-import (node)
2923 (insert "* as ")
2924 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2925
2926 (defun js2-print-named-imports (imports)
2927 (insert "{")
2928 (let ((len (length imports))
2929 (n 0))
2930 (while (< n len)
2931 (js2-print-extern-binding (nth n imports) 0)
2932 (unless (= n (- len 1))
2933 (insert ", "))
2934 (setq n (+ n 1))))
2935 (insert "}"))
2936
2937 (cl-defstruct (js2-namespace-import-node
2938 (:include js2-node)
2939 (:constructor nil)
2940 (:constructor make-js2-namespace-import-node (&key (type -1)
2941 pos
2942 len
2943 name)))
2944 "AST node for a complete namespace import.
2945 E.g. the '* as lib' expression in:
2946
2947 import * as lib from 'src/lib'
2948
2949 It contains a single name node referring to the bound name."
2950 name) ; js2-name-node of the bound name.
2951
2952 (defun js2-visit-namespace-import (n v)
2953 (js2-visit-ast (js2-namespace-import-node-name n) v))
2954
2955 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2956 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2957
2958 (cl-defstruct (js2-from-clause-node
2959 (:include js2-node)
2960 (:constructor nil)
2961 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2962 pos
2963 len
2964 module-id
2965 metadata-p)))
2966 "AST node for the from clause in an import or export statement.
2967 E.g. from 'my/module'. It can refere to either an external module, or to the
2968 modules metadata itself."
2969 module-id ; string containing the module specifier.
2970 metadata-p) ; true if this clause refers to the module's metadata
2971
2972 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2973 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2974
2975 (defun js2-print-from-clause (n)
2976 (insert "from ")
2977 (if (js2-from-clause-node-metadata-p n)
2978 (insert "this module")
2979 (insert "'")
2980 (insert (js2-from-clause-node-module-id n))
2981 (insert "'")))
2982
2983 (cl-defstruct (js2-try-node
2984 (:include js2-node)
2985 (:constructor nil)
2986 (:constructor make-js2-try-node (&key (type js2-TRY)
2987 (pos js2-ts-cursor)
2988 len
2989 try-block
2990 catch-clauses
2991 finally-block)))
2992 "AST node for a try-statement."
2993 try-block
2994 catch-clauses ; a Lisp list of `js2-catch-node'
2995 finally-block) ; a `js2-finally-node'
2996
2997 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2998 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2999
3000 (defun js2-visit-try-node (n v)
3001 (js2-visit-ast (js2-try-node-try-block n) v)
3002 (dolist (clause (js2-try-node-catch-clauses n))
3003 (js2-visit-ast clause v))
3004 (js2-visit-ast (js2-try-node-finally-block n) v))
3005
3006 (defun js2-print-try-node (n i)
3007 (let ((pad (js2-make-pad i))
3008 (catches (js2-try-node-catch-clauses n))
3009 (finally (js2-try-node-finally-block n)))
3010 (insert pad "try {\n")
3011 (js2-print-body (js2-try-node-try-block n) (1+ i))
3012 (insert pad "}")
3013 (when catches
3014 (dolist (catch catches)
3015 (js2-print-ast catch i)))
3016 (if finally
3017 (js2-print-ast finally i)
3018 (insert "\n"))))
3019
3020 (cl-defstruct (js2-catch-node
3021 (:include js2-scope)
3022 (:constructor nil)
3023 (:constructor make-js2-catch-node (&key (type js2-CATCH)
3024 (pos js2-ts-cursor)
3025 len
3026 param
3027 guard-kwd
3028 guard-expr
3029 lp rp)))
3030 "AST node for a catch clause."
3031 param ; destructuring form or simple name node
3032 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
3033 guard-expr ; catch condition, a `js2-node'
3034 lp ; buffer position of left-paren, nil if omitted
3035 rp) ; buffer position of right-paren, nil if omitted
3036
3037 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
3038 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
3039
3040 (defun js2-visit-catch-node (n v)
3041 (js2-visit-ast (js2-catch-node-param n) v)
3042 (when (js2-catch-node-guard-kwd n)
3043 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3044 (js2-visit-block n v))
3045
3046 (defun js2-print-catch-node (n i)
3047 (let ((pad (js2-make-pad i))
3048 (guard-kwd (js2-catch-node-guard-kwd n))
3049 (guard-expr (js2-catch-node-guard-expr n)))
3050 (insert " catch (")
3051 (js2-print-ast (js2-catch-node-param n) 0)
3052 (when guard-kwd
3053 (insert " if ")
3054 (js2-print-ast guard-expr 0))
3055 (insert ") {\n")
3056 (js2-print-body n (1+ i))
3057 (insert pad "}")))
3058
3059 (cl-defstruct (js2-finally-node
3060 (:include js2-node)
3061 (:constructor nil)
3062 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3063 (pos js2-ts-cursor)
3064 len body)))
3065 "AST node for a finally clause."
3066 body) ; a `js2-node', often but not always a block node
3067
3068 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3069 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3070
3071 (defun js2-visit-finally-node (n v)
3072 (js2-visit-ast (js2-finally-node-body n) v))
3073
3074 (defun js2-print-finally-node (n i)
3075 (let ((pad (js2-make-pad i)))
3076 (insert " finally {\n")
3077 (js2-print-body (js2-finally-node-body n) (1+ i))
3078 (insert pad "}\n")))
3079
3080 (cl-defstruct (js2-switch-node
3081 (:include js2-node)
3082 (:constructor nil)
3083 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3084 (pos js2-ts-cursor)
3085 len
3086 discriminant
3087 cases lp
3088 rp)))
3089 "AST node for a switch statement."
3090 discriminant ; a `js2-node' (switch expression)
3091 cases ; a Lisp list of `js2-case-node'
3092 lp ; position of open-paren for discriminant, nil if omitted
3093 rp) ; position of close-paren for discriminant, nil if omitted
3094
3095 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3096 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3097
3098 (defun js2-visit-switch-node (n v)
3099 (js2-visit-ast (js2-switch-node-discriminant n) v)
3100 (dolist (c (js2-switch-node-cases n))
3101 (js2-visit-ast c v)))
3102
3103 (defun js2-print-switch-node (n i)
3104 (let ((pad (js2-make-pad i))
3105 (cases (js2-switch-node-cases n)))
3106 (insert pad "switch (")
3107 (js2-print-ast (js2-switch-node-discriminant n) 0)
3108 (insert ") {\n")
3109 (dolist (case cases)
3110 (js2-print-ast case i))
3111 (insert pad "}\n")))
3112
3113 (cl-defstruct (js2-case-node
3114 (:include js2-block-node)
3115 (:constructor nil)
3116 (:constructor make-js2-case-node (&key (type js2-CASE)
3117 (pos js2-ts-cursor)
3118 len kids expr)))
3119 "AST node for a case clause of a switch statement."
3120 expr) ; the case expression (nil for default)
3121
3122 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3123 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3124
3125 (defun js2-visit-case-node (n v)
3126 (js2-visit-ast (js2-case-node-expr n) v)
3127 (js2-visit-block n v))
3128
3129 (defun js2-print-case-node (n i)
3130 (let ((pad (js2-make-pad i))
3131 (expr (js2-case-node-expr n)))
3132 (insert pad)
3133 (if (null expr)
3134 (insert "default:\n")
3135 (insert "case ")
3136 (js2-print-ast expr 0)
3137 (insert ":\n"))
3138 (dolist (kid (js2-case-node-kids n))
3139 (js2-print-ast kid (1+ i)))))
3140
3141 (cl-defstruct (js2-throw-node
3142 (:include js2-node)
3143 (:constructor nil)
3144 (:constructor make-js2-throw-node (&key (type js2-THROW)
3145 (pos js2-ts-cursor)
3146 len expr)))
3147 "AST node for a throw statement."
3148 expr) ; the expression to throw
3149
3150 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3151 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3152
3153 (defun js2-visit-throw-node (n v)
3154 (js2-visit-ast (js2-throw-node-expr n) v))
3155
3156 (defun js2-print-throw-node (n i)
3157 (insert (js2-make-pad i) "throw ")
3158 (js2-print-ast (js2-throw-node-expr n) 0)
3159 (insert ";\n"))
3160
3161 (cl-defstruct (js2-with-node
3162 (:include js2-node)
3163 (:constructor nil)
3164 (:constructor make-js2-with-node (&key (type js2-WITH)
3165 (pos js2-ts-cursor)
3166 len object
3167 body lp rp)))
3168 "AST node for a with-statement."
3169 object
3170 body
3171 lp ; buffer position of left-paren around object, nil if omitted
3172 rp) ; buffer position of right-paren around object, nil if omitted
3173
3174 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3175 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3176
3177 (defun js2-visit-with-node (n v)
3178 (js2-visit-ast (js2-with-node-object n) v)
3179 (js2-visit-ast (js2-with-node-body n) v))
3180
3181 (defun js2-print-with-node (n i)
3182 (let ((pad (js2-make-pad i)))
3183 (insert pad "with (")
3184 (js2-print-ast (js2-with-node-object n) 0)
3185 (insert ") {\n")
3186 (js2-print-body (js2-with-node-body n) (1+ i))
3187 (insert pad "}\n")))
3188
3189 (cl-defstruct (js2-label-node
3190 (:include js2-node)
3191 (:constructor nil)
3192 (:constructor make-js2-label-node (&key (type js2-LABEL)
3193 (pos js2-ts-cursor)
3194 len name)))
3195 "AST node for a statement label or case label."
3196 name ; a string
3197 loop) ; for validating and code-generating continue-to-label
3198
3199 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3200 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3201
3202 (defun js2-print-label (n i)
3203 (insert (js2-make-pad i)
3204 (js2-label-node-name n)
3205 ":\n"))
3206
3207 (cl-defstruct (js2-labeled-stmt-node
3208 (:include js2-node)
3209 (:constructor nil)
3210 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3211 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3212 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3213 (pos js2-ts-cursor)
3214 len labels stmt)))
3215 "AST node for a statement with one or more labels.
3216 Multiple labels for a statement are collapsed into the labels field."
3217 labels ; Lisp list of `js2-label-node'
3218 stmt) ; the statement these labels are for
3219
3220 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3221 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3222
3223 (defun js2-get-label-by-name (lbl-stmt name)
3224 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3225 Returns nil if no such label is in the list."
3226 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3227 result)
3228 (while (and label-list (not result))
3229 (if (string= (js2-label-node-name (car label-list)) name)
3230 (setq result (car label-list))
3231 (setq label-list (cdr label-list))))
3232 result))
3233
3234 (defun js2-visit-labeled-stmt (n v)
3235 (dolist (label (js2-labeled-stmt-node-labels n))
3236 (js2-visit-ast label v))
3237 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3238
3239 (defun js2-print-labeled-stmt (n i)
3240 (dolist (label (js2-labeled-stmt-node-labels n))
3241 (js2-print-ast label i))
3242 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3243
3244 (defun js2-labeled-stmt-node-contains (node label)
3245 "Return t if NODE contains LABEL in its label set.
3246 NODE is a `js2-labels-node'. LABEL is an identifier."
3247 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3248 if (string= label (js2-label-node-name nl))
3249 return t
3250 finally return nil))
3251
3252 (defsubst js2-labeled-stmt-node-add-label (node label)
3253 "Add a `js2-label-node' to the label set for this statement."
3254 (setf (js2-labeled-stmt-node-labels node)
3255 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3256
3257 (cl-defstruct (js2-jump-node
3258 (:include js2-node)
3259 (:constructor nil))
3260 "Abstract supertype of break and continue nodes."
3261 label ; `js2-name-node' for location of label identifier, if present
3262 target) ; target js2-labels-node or loop/switch statement
3263
3264 (defun js2-visit-jump-node (n v)
3265 ;; We don't visit the target, since it's a back-link.
3266 (js2-visit-ast (js2-jump-node-label n) v))
3267
3268 (cl-defstruct (js2-break-node
3269 (:include js2-jump-node)
3270 (:constructor nil)
3271 (:constructor make-js2-break-node (&key (type js2-BREAK)
3272 (pos js2-ts-cursor)
3273 len label target)))
3274 "AST node for a break statement.
3275 The label field is a `js2-name-node', possibly nil, for the named label
3276 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3277 is the target of the break - a label node or enclosing loop/switch statement.")
3278
3279 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3280 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3281
3282 (defun js2-print-break-node (n i)
3283 (insert (js2-make-pad i) "break")
3284 (when (js2-break-node-label n)
3285 (insert " ")
3286 (js2-print-ast (js2-break-node-label n) 0))
3287 (insert ";\n"))
3288
3289 (cl-defstruct (js2-continue-node
3290 (:include js2-jump-node)
3291 (:constructor nil)
3292 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3293 (pos js2-ts-cursor)
3294 len label target)))
3295 "AST node for a continue statement.
3296 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3297 It is nil if continue specifies no label. The target field is the jump target:
3298 a `js2-label-node' or the innermost enclosing loop.")
3299
3300 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3301 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3302
3303 (defun js2-print-continue-node (n i)
3304 (insert (js2-make-pad i) "continue")
3305 (when (js2-continue-node-label n)
3306 (insert " ")
3307 (js2-print-ast (js2-continue-node-label n) 0))
3308 (insert ";\n"))
3309
3310 (cl-defstruct (js2-function-node
3311 (:include js2-script-node)
3312 (:constructor nil)
3313 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3314 (pos js2-ts-cursor)
3315 len
3316 (ftype 'FUNCTION)
3317 (form 'FUNCTION_STATEMENT)
3318 (name "")
3319 params rest-p
3320 body
3321 generator-type
3322 lp rp)))
3323 "AST node for a function declaration.
3324 The `params' field is a Lisp list of nodes. Each node is either a simple
3325 `js2-name-node', or if it's a destructuring-assignment parameter, a
3326 `js2-array-node' or `js2-object-node'."
3327 ftype ; FUNCTION, GETTER or SETTER
3328 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3329 name ; function name (a `js2-name-node', or nil if anonymous)
3330 params ; a Lisp list of destructuring forms or simple name nodes
3331 rest-p ; if t, the last parameter is rest parameter
3332 body ; a `js2-block-node' or expression node (1.8 only)
3333 lp ; position of arg-list open-paren, or nil if omitted
3334 rp ; position of arg-list close-paren, or nil if omitted
3335 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3336 needs-activation ; t if we need an activation object for this frame
3337 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3338 member-expr) ; nonstandard Ecma extension from Rhino
3339
3340 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3341 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3342
3343 (defun js2-visit-function-node (n v)
3344 (js2-visit-ast (js2-function-node-name n) v)
3345 (dolist (p (js2-function-node-params n))
3346 (js2-visit-ast p v))
3347 (js2-visit-ast (js2-function-node-body n) v))
3348
3349 (defun js2-print-function-node (n i)
3350 (let* ((pad (js2-make-pad i))
3351 (getter (js2-node-get-prop n 'GETTER_SETTER))
3352 (name (or (js2-function-node-name n)
3353 (js2-function-node-member-expr n)))
3354 (params (js2-function-node-params n))
3355 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3356 (rest-p (js2-function-node-rest-p n))
3357 (body (js2-function-node-body n))
3358 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3359 (unless (or getter arrow)
3360 (insert pad "function")
3361 (when (eq (js2-function-node-generator-type n) 'STAR)
3362 (insert "*")))
3363 (when name
3364 (insert " ")
3365 (js2-print-ast name 0))
3366 (insert "(")
3367 (cl-loop with len = (length params)
3368 for param in params
3369 for count from 1
3370 do
3371 (when (and rest-p (= count len))
3372 (insert "..."))
3373 (js2-print-ast param 0)
3374 (when (< count len)
3375 (insert ", ")))
3376 (insert ") ")
3377 (when arrow
3378 (insert "=> "))
3379 (insert "{")
3380 ;; TODO: fix this to be smarter about indenting, etc.
3381 (unless expr
3382 (insert "\n"))
3383 (if (js2-block-node-p body)
3384 (js2-print-body body (1+ i))
3385 (js2-print-ast body 0))
3386 (insert pad "}")
3387 (unless expr
3388 (insert "\n"))))
3389
3390 (defun js2-function-name (node)
3391 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3392 (and (js2-function-node-name node)
3393 (js2-name-node-name (js2-function-node-name node))))
3394
3395 ;; Having this be an expression node makes it more flexible.
3396 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3397 ;; that work better if you assume it's an expression. Whenever we have
3398 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3399 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3400 (cl-defstruct (js2-var-decl-node
3401 (:include js2-node)
3402 (:constructor nil)
3403 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3404 (pos (js2-current-token-beg))
3405 len kids
3406 decl-type)))
3407 "AST node for a variable declaration list (VAR, CONST or LET).
3408 The node bounds differ depending on the declaration type. For VAR or
3409 CONST declarations, the bounds include the var/const keyword. For LET
3410 declarations, the node begins at the position of the first child."
3411 kids ; a Lisp list of `js2-var-init-node' structs.
3412 decl-type) ; js2-VAR, js2-CONST or js2-LET
3413
3414 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3415 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3416
3417 (defun js2-visit-var-decl (n v)
3418 (dolist (kid (js2-var-decl-node-kids n))
3419 (js2-visit-ast kid v)))
3420
3421 (defun js2-print-var-decl (n i)
3422 (let ((pad (js2-make-pad i))
3423 (tt (js2-var-decl-node-decl-type n)))
3424 (insert pad)
3425 (insert (cond
3426 ((= tt js2-VAR) "var ")
3427 ((= tt js2-LET) "let ")
3428 ((= tt js2-CONST) "const ")
3429 (t
3430 (error "malformed var-decl node"))))
3431 (cl-loop with kids = (js2-var-decl-node-kids n)
3432 with len = (length kids)
3433 for kid in kids
3434 for count from 1
3435 do
3436 (js2-print-ast kid 0)
3437 (if (< count len)
3438 (insert ", ")))))
3439
3440 (cl-defstruct (js2-var-init-node
3441 (:include js2-node)
3442 (:constructor nil)
3443 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3444 (pos js2-ts-cursor)
3445 len target
3446 initializer)))
3447 "AST node for a variable declaration.
3448 The type field will be js2-CONST for a const decl."
3449 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3450 initializer) ; initializer expression, a `js2-node'
3451
3452 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3453 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3454
3455 (defun js2-visit-var-init-node (n v)
3456 (js2-visit-ast (js2-var-init-node-target n) v)
3457 (js2-visit-ast (js2-var-init-node-initializer n) v))
3458
3459 (defun js2-print-var-init-node (n i)
3460 (let ((pad (js2-make-pad i))
3461 (name (js2-var-init-node-target n))
3462 (init (js2-var-init-node-initializer n)))
3463 (insert pad)
3464 (js2-print-ast name 0)
3465 (when init
3466 (insert " = ")
3467 (js2-print-ast init 0))))
3468
3469 (cl-defstruct (js2-cond-node
3470 (:include js2-node)
3471 (:constructor nil)
3472 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3473 (pos js2-ts-cursor)
3474 len
3475 test-expr
3476 true-expr
3477 false-expr
3478 q-pos c-pos)))
3479 "AST node for the ternary operator"
3480 test-expr
3481 true-expr
3482 false-expr
3483 q-pos ; buffer position of ?
3484 c-pos) ; buffer position of :
3485
3486 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3487 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3488
3489 (defun js2-visit-cond-node (n v)
3490 (js2-visit-ast (js2-cond-node-test-expr n) v)
3491 (js2-visit-ast (js2-cond-node-true-expr n) v)
3492 (js2-visit-ast (js2-cond-node-false-expr n) v))
3493
3494 (defun js2-print-cond-node (n i)
3495 (let ((pad (js2-make-pad i)))
3496 (insert pad)
3497 (js2-print-ast (js2-cond-node-test-expr n) 0)
3498 (insert " ? ")
3499 (js2-print-ast (js2-cond-node-true-expr n) 0)
3500 (insert " : ")
3501 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3502
3503 (cl-defstruct (js2-infix-node
3504 (:include js2-node)
3505 (:constructor nil)
3506 (:constructor make-js2-infix-node (&key type
3507 (pos js2-ts-cursor)
3508 len op-pos
3509 left right)))
3510 "Represents infix expressions.
3511 Includes assignment ops like `|=', and the comma operator.
3512 The type field inherited from `js2-node' holds the operator."
3513 op-pos ; buffer position where operator begins
3514 left ; any `js2-node'
3515 right) ; any `js2-node'
3516
3517 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3518 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3519
3520 (defun js2-visit-infix-node (n v)
3521 (js2-visit-ast (js2-infix-node-left n) v)
3522 (js2-visit-ast (js2-infix-node-right n) v))
3523
3524 (defconst js2-operator-tokens
3525 (let ((table (make-hash-table :test 'eq))
3526 (tokens
3527 (list (cons js2-IN "in")
3528 (cons js2-TYPEOF "typeof")
3529 (cons js2-INSTANCEOF "instanceof")
3530 (cons js2-DELPROP "delete")
3531 (cons js2-COMMA ",")
3532 (cons js2-COLON ":")
3533 (cons js2-OR "||")
3534 (cons js2-AND "&&")
3535 (cons js2-INC "++")
3536 (cons js2-DEC "--")
3537 (cons js2-BITOR "|")
3538 (cons js2-BITXOR "^")
3539 (cons js2-BITAND "&")
3540 (cons js2-EQ "==")
3541 (cons js2-NE "!=")
3542 (cons js2-LT "<")
3543 (cons js2-LE "<=")
3544 (cons js2-GT ">")
3545 (cons js2-GE ">=")
3546 (cons js2-LSH "<<")
3547 (cons js2-RSH ">>")
3548 (cons js2-URSH ">>>")
3549 (cons js2-ADD "+") ; infix plus
3550 (cons js2-SUB "-") ; infix minus
3551 (cons js2-MUL "*")
3552 (cons js2-DIV "/")
3553 (cons js2-MOD "%")
3554 (cons js2-NOT "!")
3555 (cons js2-BITNOT "~")
3556 (cons js2-POS "+") ; unary plus
3557 (cons js2-NEG "-") ; unary minus
3558 (cons js2-TRIPLEDOT "...")
3559 (cons js2-SHEQ "===") ; shallow equality
3560 (cons js2-SHNE "!==") ; shallow inequality
3561 (cons js2-ASSIGN "=")
3562 (cons js2-ASSIGN_BITOR "|=")
3563 (cons js2-ASSIGN_BITXOR "^=")
3564 (cons js2-ASSIGN_BITAND "&=")
3565 (cons js2-ASSIGN_LSH "<<=")
3566 (cons js2-ASSIGN_RSH ">>=")
3567 (cons js2-ASSIGN_URSH ">>>=")
3568 (cons js2-ASSIGN_ADD "+=")
3569 (cons js2-ASSIGN_SUB "-=")
3570 (cons js2-ASSIGN_MUL "*=")
3571 (cons js2-ASSIGN_DIV "/=")
3572 (cons js2-ASSIGN_MOD "%="))))
3573 (cl-loop for (k . v) in tokens do
3574 (puthash k v table))
3575 table))
3576
3577 (defun js2-print-infix-node (n i)
3578 (let* ((tt (js2-node-type n))
3579 (op (gethash tt js2-operator-tokens)))
3580 (unless op
3581 (error "unrecognized infix operator %s" (js2-node-type n)))
3582 (insert (js2-make-pad i))
3583 (js2-print-ast (js2-infix-node-left n) 0)
3584 (unless (= tt js2-COMMA)
3585 (insert " "))
3586 (insert op)
3587 (insert " ")
3588 (js2-print-ast (js2-infix-node-right n) 0)))
3589
3590 (cl-defstruct (js2-assign-node
3591 (:include js2-infix-node)
3592 (:constructor nil)
3593 (:constructor make-js2-assign-node (&key type
3594 (pos js2-ts-cursor)
3595 len op-pos
3596 left right)))
3597 "Represents any assignment.
3598 The type field holds the actual assignment operator.")
3599
3600 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3601 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3602
3603 (cl-defstruct (js2-unary-node
3604 (:include js2-node)
3605 (:constructor nil)
3606 (:constructor make-js2-unary-node (&key type ; required
3607 (pos js2-ts-cursor)
3608 len operand)))
3609 "AST node type for unary operator nodes.
3610 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3611 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3612 property is added if the operator follows the operand."
3613 operand) ; a `js2-node' expression
3614
3615 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3616 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3617
3618 (defun js2-visit-unary-node (n v)
3619 (js2-visit-ast (js2-unary-node-operand n) v))
3620
3621 (defun js2-print-unary-node (n i)
3622 (let* ((tt (js2-node-type n))
3623 (op (gethash tt js2-operator-tokens))
3624 (postfix (js2-node-get-prop n 'postfix)))
3625 (unless op
3626 (error "unrecognized unary operator %s" tt))
3627 (insert (js2-make-pad i))
3628 (unless postfix
3629 (insert op))
3630 (if (or (= tt js2-TYPEOF)
3631 (= tt js2-DELPROP))
3632 (insert " "))
3633 (js2-print-ast (js2-unary-node-operand n) 0)
3634 (when postfix
3635 (insert op))))
3636
3637 (cl-defstruct (js2-let-node
3638 (:include js2-scope)
3639 (:constructor nil)
3640 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3641 (pos (js2-current-token-beg))
3642 len vars body
3643 lp rp)))
3644 "AST node for a let expression or a let statement.
3645 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3646 vars ; a `js2-var-decl-node'
3647 body ; a `js2-node' representing the expression or body block
3648 lp
3649 rp)
3650
3651 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3652 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3653
3654 (defun js2-visit-let-node (n v)
3655 (js2-visit-ast (js2-let-node-vars n) v)
3656 (js2-visit-ast (js2-let-node-body n) v))
3657
3658 (defun js2-print-let-node (n i)
3659 (insert (js2-make-pad i) "let (")
3660 (let ((p (point)))
3661 (js2-print-ast (js2-let-node-vars n) 0)
3662 (delete-region p (+ p 4)))
3663 (insert ") ")
3664 (js2-print-ast (js2-let-node-body n) i))
3665
3666 (cl-defstruct (js2-keyword-node
3667 (:include js2-node)
3668 (:constructor nil)
3669 (:constructor make-js2-keyword-node (&key type
3670 (pos (js2-current-token-beg))
3671 (len (- js2-ts-cursor pos)))))
3672 "AST node representing a literal keyword such as `null'.
3673 Used for `null', `this', `true', `false' and `debugger'.
3674 The node type is set to js2-NULL, js2-THIS, etc.")
3675
3676 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3677 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3678
3679 (defun js2-print-keyword-node (n i)
3680 (insert (js2-make-pad i)
3681 (let ((tt (js2-node-type n)))
3682 (cond
3683 ((= tt js2-THIS) "this")
3684 ((= tt js2-SUPER) "super")
3685 ((= tt js2-NULL) "null")
3686 ((= tt js2-TRUE) "true")
3687 ((= tt js2-FALSE) "false")
3688 ((= tt js2-DEBUGGER) "debugger")
3689 (t (error "Invalid keyword literal type: %d" tt))))))
3690
3691 (defsubst js2-this-or-super-node-p (node)
3692 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3693 (let ((type (js2-node-type node)))
3694 (or (eq type js2-THIS) (eq type js2-SUPER))))
3695
3696 (cl-defstruct (js2-new-node
3697 (:include js2-node)
3698 (:constructor nil)
3699 (:constructor make-js2-new-node (&key (type js2-NEW)
3700 (pos (js2-current-token-beg))
3701 len target
3702 args initializer
3703 lp rp)))
3704 "AST node for new-expression such as new Foo()."
3705 target ; an identifier or reference
3706 args ; a Lisp list of argument nodes
3707 lp ; position of left-paren, nil if omitted
3708 rp ; position of right-paren, nil if omitted
3709 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3710
3711 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3712 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3713
3714 (defun js2-visit-new-node (n v)
3715 (js2-visit-ast (js2-new-node-target n) v)
3716 (dolist (arg (js2-new-node-args n))
3717 (js2-visit-ast arg v))
3718 (js2-visit-ast (js2-new-node-initializer n) v))
3719
3720 (defun js2-print-new-node (n i)
3721 (insert (js2-make-pad i) "new ")
3722 (js2-print-ast (js2-new-node-target n))
3723 (insert "(")
3724 (js2-print-list (js2-new-node-args n))
3725 (insert ")")
3726 (when (js2-new-node-initializer n)
3727 (insert " ")
3728 (js2-print-ast (js2-new-node-initializer n))))
3729
3730 (cl-defstruct (js2-name-node
3731 (:include js2-node)
3732 (:constructor nil)
3733 (:constructor make-js2-name-node (&key (type js2-NAME)
3734 (pos (js2-current-token-beg))
3735 (len (- js2-ts-cursor
3736 (js2-current-token-beg)))
3737 (name (js2-current-token-string)))))
3738 "AST node for a JavaScript identifier"
3739 name ; a string
3740 scope) ; a `js2-scope' (optional, used for codegen)
3741
3742 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3743 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3744
3745 (defun js2-print-name-node (n i)
3746 (insert (js2-make-pad i)
3747 (js2-name-node-name n)))
3748
3749 (defsubst js2-name-node-length (node)
3750 "Return identifier length of NODE, a `js2-name-node'.
3751 Returns 0 if NODE is nil or its identifier field is nil."
3752 (if node
3753 (length (js2-name-node-name node))
3754 0))
3755
3756 (cl-defstruct (js2-number-node
3757 (:include js2-node)
3758 (:constructor nil)
3759 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3760 (pos (js2-current-token-beg))
3761 (len (- js2-ts-cursor
3762 (js2-current-token-beg)))
3763 (value (js2-current-token-string))
3764 (num-value (js2-token-number
3765 (js2-current-token)))
3766 (num-base (js2-token-number-base
3767 (js2-current-token))))))
3768 "AST node for a number literal."
3769 value ; the original string, e.g. "6.02e23"
3770 num-value ; the parsed number value
3771 num-base) ; the number's base
3772
3773 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3774 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3775
3776 (defun js2-print-number-node (n i)
3777 (insert (js2-make-pad i)
3778 (number-to-string (js2-number-node-num-value n))))
3779
3780 (cl-defstruct (js2-regexp-node
3781 (:include js2-node)
3782 (:constructor nil)
3783 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3784 (pos (js2-current-token-beg))
3785 (len (- js2-ts-cursor
3786 (js2-current-token-beg)))
3787 value flags)))
3788 "AST node for a regular expression literal."
3789 value ; the regexp string, without // delimiters
3790 flags) ; a string of flags, e.g. `mi'.
3791
3792 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3793 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3794
3795 (defun js2-print-regexp (n i)
3796 (insert (js2-make-pad i)
3797 "/"
3798 (js2-regexp-node-value n)
3799 "/")
3800 (if (js2-regexp-node-flags n)
3801 (insert (js2-regexp-node-flags n))))
3802
3803 (cl-defstruct (js2-string-node
3804 (:include js2-node)
3805 (:constructor nil)
3806 (:constructor make-js2-string-node (&key (type js2-STRING)
3807 (pos (js2-current-token-beg))
3808 (len (- js2-ts-cursor
3809 (js2-current-token-beg)))
3810 (value (js2-current-token-string)))))
3811 "String literal.
3812 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3813 You can tell the quote type by looking at the first character."
3814 value) ; the characters of the string, including the quotes
3815
3816 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3817 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3818
3819 (defun js2-print-string-node (n i)
3820 (insert (js2-make-pad i)
3821 (js2-node-string n)))
3822
3823 (cl-defstruct (js2-template-node
3824 (:include js2-node)
3825 (:constructor nil)
3826 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3827 beg len kids)))
3828 "Template literal."
3829 kids) ; `js2-string-node' is used for string segments, other nodes
3830 ; for substitutions inside.
3831
3832 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3833 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3834
3835 (defun js2-visit-template (n callback)
3836 (dolist (kid (js2-template-node-kids n))
3837 (js2-visit-ast kid callback)))
3838
3839 (defun js2-print-template (n i)
3840 (insert (js2-make-pad i))
3841 (dolist (kid (js2-template-node-kids n))
3842 (if (js2-string-node-p kid)
3843 (insert (js2-node-string kid))
3844 (js2-print-ast kid))))
3845
3846 (cl-defstruct (js2-tagged-template-node
3847 (:include js2-node)
3848 (:constructor nil)
3849 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3850 beg len tag template)))
3851 "Tagged template literal."
3852 tag ; `js2-node' with the tag expression.
3853 template) ; `js2-template-node' with the template.
3854
3855 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3856 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3857
3858 (defun js2-visit-tagged-template (n callback)
3859 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3860 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3861
3862 (defun js2-print-tagged-template (n i)
3863 (insert (js2-make-pad i))
3864 (js2-print-ast (js2-tagged-template-node-tag n))
3865 (js2-print-ast (js2-tagged-template-node-template n)))
3866
3867 (cl-defstruct (js2-array-node
3868 (:include js2-node)
3869 (:constructor nil)
3870 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3871 (pos js2-ts-cursor)
3872 len elems)))
3873 "AST node for an array literal."
3874 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3875
3876 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3877 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3878
3879 (defun js2-visit-array-node (n v)
3880 (dolist (e (js2-array-node-elems n))
3881 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3882
3883 (defun js2-print-array-node (n i)
3884 (insert (js2-make-pad i) "[")
3885 (let ((elems (js2-array-node-elems n)))
3886 (js2-print-list elems)
3887 (when (and elems (null (car (last elems))))
3888 (insert ",")))
3889 (insert "]"))
3890
3891 (cl-defstruct (js2-class-node
3892 (:include js2-node)
3893 (:constructor nil)
3894 (:constructor make-js2-class-node (&key (type js2-CLASS)
3895 (pos js2-ts-cursor)
3896 (form 'CLASS_STATEMENT)
3897 (name "")
3898 extends len elems)))
3899 "AST node for an class expression.
3900 `elems' is a list of `js2-object-prop-node', and `extends' is an
3901 optional `js2-expr-node'"
3902 form ; CLASS_{STATEMENT|EXPRESSION}
3903 name ; class name (a `js2-node-name', or nil if anonymous)
3904 extends ; class heritage (a `js2-expr-node', or nil if none)
3905 elems)
3906
3907 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3908 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3909
3910 (defun js2-visit-class-node (n v)
3911 (js2-visit-ast (js2-class-node-name n) v)
3912 (js2-visit-ast (js2-class-node-extends n) v)
3913 (dolist (e (js2-class-node-elems n))
3914 (js2-visit-ast e v)))
3915
3916 (defun js2-print-class-node (n i)
3917 (let* ((pad (js2-make-pad i))
3918 (name (js2-class-node-name n))
3919 (extends (js2-class-node-extends n))
3920 (elems (js2-class-node-elems n)))
3921 (insert pad "class")
3922 (when name
3923 (insert " ")
3924 (js2-print-ast name 0))
3925 (when extends
3926 (insert " extends ")
3927 (js2-print-ast extends))
3928 (insert " {")
3929 (dolist (elem elems)
3930 (insert "\n")
3931 (if (js2-node-get-prop elem 'STATIC)
3932 (progn (insert (js2-make-pad (1+ i)) "static ")
3933 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3934 (js2-print-ast elem (1+ i))))
3935 (insert "\n" pad "}")))
3936
3937 (cl-defstruct (js2-object-node
3938 (:include js2-node)
3939 (:constructor nil)
3940 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3941 (pos js2-ts-cursor)
3942 len
3943 elems)))
3944 "AST node for an object literal expression.
3945 `elems' is a list of `js2-object-prop-node'."
3946 elems)
3947
3948 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3949 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3950
3951 (defun js2-visit-object-node (n v)
3952 (dolist (e (js2-object-node-elems n))
3953 (js2-visit-ast e v)))
3954
3955 (defun js2-print-object-node (n i)
3956 (insert (js2-make-pad i) "{")
3957 (js2-print-list (js2-object-node-elems n))
3958 (insert "}"))
3959
3960 (cl-defstruct (js2-object-prop-node
3961 (:include js2-infix-node)
3962 (:constructor nil)
3963 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3964 (pos js2-ts-cursor)
3965 len left
3966 right op-pos)))
3967 "AST node for an object literal prop:value entry.
3968 The `left' field is the property: a name node, string node,
3969 number node or expression node. The `right' field is a
3970 `js2-node' representing the initializer value. If the property
3971 is abbreviated, the node's `SHORTHAND' property is non-nil and
3972 both fields have the same value.")
3973
3974 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3975 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3976
3977 (defun js2-print-object-prop-node (n i)
3978 (let* ((left (js2-object-prop-node-left n))
3979 (right (js2-object-prop-node-right n))
3980 (computed (not (or (js2-string-node-p left)
3981 (js2-number-node-p left)
3982 (js2-name-node-p left)))))
3983 (insert (js2-make-pad i))
3984 (if computed
3985 (insert "["))
3986 (js2-print-ast left 0)
3987 (if computed
3988 (insert "]"))
3989 (if (not (js2-node-get-prop n 'SHORTHAND))
3990 (progn
3991 (insert ": ")
3992 (js2-print-ast right 0)))))
3993
3994 (cl-defstruct (js2-getter-setter-node
3995 (:include js2-infix-node)
3996 (:constructor nil)
3997 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3998 (pos js2-ts-cursor)
3999 len left right)))
4000 "AST node for a getter/setter property in an object literal.
4001 The `left' field is the `js2-name-node' naming the getter/setter prop.
4002 The `right' field is always an anonymous `js2-function-node' with a node
4003 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
4004
4005 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
4006 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
4007
4008 (defun js2-print-getter-setter (n i)
4009 (let* ((pad (js2-make-pad i))
4010 (left (js2-getter-setter-node-left n))
4011 (right (js2-getter-setter-node-right n))
4012 (computed (not (or (js2-string-node-p left)
4013 (js2-number-node-p left)
4014 (js2-name-node-p left)))))
4015 (insert pad)
4016 (if (/= (js2-node-type n) js2-FUNCTION)
4017 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
4018 (when (and (js2-function-node-p right)
4019 (eq 'STAR (js2-function-node-generator-type right)))
4020 (insert "*"))
4021 (when computed
4022 (insert "["))
4023 (js2-print-ast left 0)
4024 (when computed
4025 (insert "]"))
4026 (js2-print-ast right 0)))
4027
4028 (cl-defstruct (js2-prop-get-node
4029 (:include js2-infix-node)
4030 (:constructor nil)
4031 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
4032 (pos js2-ts-cursor)
4033 len left right)))
4034 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
4035
4036 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4037 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4038
4039 (defun js2-visit-prop-get-node (n v)
4040 (js2-visit-ast (js2-prop-get-node-left n) v)
4041 (js2-visit-ast (js2-prop-get-node-right n) v))
4042
4043 (defun js2-print-prop-get-node (n i)
4044 (insert (js2-make-pad i))
4045 (js2-print-ast (js2-prop-get-node-left n) 0)
4046 (insert ".")
4047 (js2-print-ast (js2-prop-get-node-right n) 0))
4048
4049 (cl-defstruct (js2-elem-get-node
4050 (:include js2-node)
4051 (:constructor nil)
4052 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4053 (pos js2-ts-cursor)
4054 len target element
4055 lb rb)))
4056 "AST node for an array index expression such as foo[bar]."
4057 target ; a `js2-node' - the expression preceding the "."
4058 element ; a `js2-node' - the expression in brackets
4059 lb ; position of left-bracket, nil if omitted
4060 rb) ; position of right-bracket, nil if omitted
4061
4062 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4063 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4064
4065 (defun js2-visit-elem-get-node (n v)
4066 (js2-visit-ast (js2-elem-get-node-target n) v)
4067 (js2-visit-ast (js2-elem-get-node-element n) v))
4068
4069 (defun js2-print-elem-get-node (n i)
4070 (insert (js2-make-pad i))
4071 (js2-print-ast (js2-elem-get-node-target n) 0)
4072 (insert "[")
4073 (js2-print-ast (js2-elem-get-node-element n) 0)
4074 (insert "]"))
4075
4076 (cl-defstruct (js2-call-node
4077 (:include js2-node)
4078 (:constructor nil)
4079 (:constructor make-js2-call-node (&key (type js2-CALL)
4080 (pos js2-ts-cursor)
4081 len target args
4082 lp rp)))
4083 "AST node for a JavaScript function call."
4084 target ; a `js2-node' evaluating to the function to call
4085 args ; a Lisp list of `js2-node' arguments
4086 lp ; position of open-paren, or nil if missing
4087 rp) ; position of close-paren, or nil if missing
4088
4089 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4090 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4091
4092 (defun js2-visit-call-node (n v)
4093 (js2-visit-ast (js2-call-node-target n) v)
4094 (dolist (arg (js2-call-node-args n))
4095 (js2-visit-ast arg v)))
4096
4097 (defun js2-print-call-node (n i)
4098 (insert (js2-make-pad i))
4099 (js2-print-ast (js2-call-node-target n) 0)
4100 (insert "(")
4101 (js2-print-list (js2-call-node-args n))
4102 (insert ")"))
4103
4104 (cl-defstruct (js2-yield-node
4105 (:include js2-node)
4106 (:constructor nil)
4107 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4108 (pos js2-ts-cursor)
4109 len value star-p)))
4110 "AST node for yield statement or expression."
4111 star-p ; whether it's yield*
4112 value) ; optional: value to be yielded
4113
4114 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4115 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4116
4117 (defun js2-visit-yield-node (n v)
4118 (js2-visit-ast (js2-yield-node-value n) v))
4119
4120 (defun js2-print-yield-node (n i)
4121 (insert (js2-make-pad i))
4122 (insert "yield")
4123 (when (js2-yield-node-star-p n)
4124 (insert "*"))
4125 (when (js2-yield-node-value n)
4126 (insert " ")
4127 (js2-print-ast (js2-yield-node-value n) 0)))
4128
4129 (cl-defstruct (js2-paren-node
4130 (:include js2-node)
4131 (:constructor nil)
4132 (:constructor make-js2-paren-node (&key (type js2-LP)
4133 (pos js2-ts-cursor)
4134 len expr)))
4135 "AST node for a parenthesized expression.
4136 In particular, used when the parens are syntactically optional,
4137 as opposed to required parens such as those enclosing an if-conditional."
4138 expr) ; `js2-node'
4139
4140 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4141 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4142
4143 (defun js2-visit-paren-node (n v)
4144 (js2-visit-ast (js2-paren-node-expr n) v))
4145
4146 (defun js2-print-paren-node (n i)
4147 (insert (js2-make-pad i))
4148 (insert "(")
4149 (js2-print-ast (js2-paren-node-expr n) 0)
4150 (insert ")"))
4151
4152 (cl-defstruct (js2-comp-node
4153 (:include js2-scope)
4154 (:constructor nil)
4155 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4156 (pos js2-ts-cursor)
4157 len result
4158 loops filters
4159 form)))
4160 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4161 result ; result expression (just after left-bracket)
4162 loops ; a Lisp list of `js2-comp-loop-node'
4163 filters ; a Lisp list of guard/filter expressions
4164 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4165 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4166 )
4167
4168 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4169 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4170
4171 (defun js2-visit-comp-node (n v)
4172 (js2-visit-ast (js2-comp-node-result n) v)
4173 (dolist (l (js2-comp-node-loops n))
4174 (js2-visit-ast l v))
4175 (dolist (f (js2-comp-node-filters n))
4176 (js2-visit-ast f v)))
4177
4178 (defun js2-print-comp-node (n i)
4179 (let ((pad (js2-make-pad i))
4180 (result (js2-comp-node-result n))
4181 (loops (js2-comp-node-loops n))
4182 (filters (js2-comp-node-filters n))
4183 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4184 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4185 (insert pad (if gen-p "(" "["))
4186 (when legacy-p
4187 (js2-print-ast result 0))
4188 (dolist (l loops)
4189 (when legacy-p
4190 (insert " "))
4191 (js2-print-ast l 0)
4192 (unless legacy-p
4193 (insert " ")))
4194 (dolist (f filters)
4195 (when legacy-p
4196 (insert " "))
4197 (insert "if (")
4198 (js2-print-ast f 0)
4199 (insert ")")
4200 (unless legacy-p
4201 (insert " ")))
4202 (unless legacy-p
4203 (js2-print-ast result 0))
4204 (insert (if gen-p ")" "]"))))
4205
4206 (cl-defstruct (js2-comp-loop-node
4207 (:include js2-for-in-node)
4208 (:constructor nil)
4209 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4210 (pos js2-ts-cursor)
4211 len iterator
4212 object in-pos
4213 foreach-p
4214 each-pos
4215 forof-p
4216 lp rp)))
4217 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4218
4219 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4220 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4221
4222 (defun js2-visit-comp-loop (n v)
4223 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4224 (js2-visit-ast (js2-comp-loop-node-object n) v))
4225
4226 (defun js2-print-comp-loop (n _i)
4227 (insert "for ")
4228 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4229 (insert "(")
4230 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4231 (insert (if (js2-comp-loop-node-forof-p n)
4232 " of " " in "))
4233 (js2-print-ast (js2-comp-loop-node-object n) 0)
4234 (insert ")"))
4235
4236 (cl-defstruct (js2-empty-expr-node
4237 (:include js2-node)
4238 (:constructor nil)
4239 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4240 (pos (js2-current-token-beg))
4241 len)))
4242 "AST node for an empty expression.")
4243
4244 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4245 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4246
4247 (cl-defstruct (js2-xml-node
4248 (:include js2-block-node)
4249 (:constructor nil)
4250 (:constructor make-js2-xml-node (&key (type js2-XML)
4251 (pos (js2-current-token-beg))
4252 len kids)))
4253 "AST node for initial parse of E4X literals.
4254 The kids field is a list of XML fragments, each a `js2-string-node' or
4255 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4256
4257 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4258 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4259
4260 (defun js2-print-xml-node (n i)
4261 (dolist (kid (js2-xml-node-kids n))
4262 (js2-print-ast kid i)))
4263
4264 (cl-defstruct (js2-xml-js-expr-node
4265 (:include js2-xml-node)
4266 (:constructor nil)
4267 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4268 (pos js2-ts-cursor)
4269 len expr)))
4270 "AST node for an embedded JavaScript {expression} in an E4X literal.
4271 The start and end fields correspond to the curly-braces."
4272 expr) ; a `js2-expr-node' of some sort
4273
4274 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4275 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4276
4277 (defun js2-visit-xml-js-expr (n v)
4278 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4279
4280 (defun js2-print-xml-js-expr (n i)
4281 (insert (js2-make-pad i))
4282 (insert "{")
4283 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4284 (insert "}"))
4285
4286 (cl-defstruct (js2-xml-dot-query-node
4287 (:include js2-infix-node)
4288 (:constructor nil)
4289 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4290 (pos js2-ts-cursor)
4291 op-pos len left
4292 right rp)))
4293 "AST node for an E4X foo.(bar) filter expression.
4294 Note that the left-paren is automatically the character immediately
4295 following the dot (.) in the operator. No whitespace is permitted
4296 between the dot and the lp by the scanner."
4297 rp)
4298
4299 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4300 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4301
4302 (defun js2-print-xml-dot-query (n i)
4303 (insert (js2-make-pad i))
4304 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4305 (insert ".(")
4306 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4307 (insert ")"))
4308
4309 (cl-defstruct (js2-xml-ref-node
4310 (:include js2-node)
4311 (:constructor nil)) ; abstract
4312 "Base type for E4X XML attribute-access or property-get expressions.
4313 Such expressions can take a variety of forms. The general syntax has
4314 three parts:
4315
4316 - (optional) an @ (specifying an attribute access)
4317 - (optional) a namespace (a `js2-name-node') and double-colon
4318 - (required) either a `js2-name-node' or a bracketed [expression]
4319
4320 The property-name expressions (examples: ns::name, @name) are
4321 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4322 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4323
4324 This node type (or more specifically, its subclasses) will sometimes
4325 be the right-hand child of a `js2-prop-get-node' or a
4326 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4327 The `js2-xml-ref-node' may also be a standalone primary expression with
4328 no explicit target, which is valid in certain expression contexts such as
4329
4330 company..employee.(@id < 100)
4331
4332 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4333 expression whose parent is a `js2-xml-dot-query-node'."
4334 namespace
4335 at-pos
4336 colon-pos)
4337
4338 (defsubst js2-xml-ref-node-attr-access-p (node)
4339 "Return non-nil if this expression began with an @-token."
4340 (and (numberp (js2-xml-ref-node-at-pos node))
4341 (cl-plusp (js2-xml-ref-node-at-pos node))))
4342
4343 (cl-defstruct (js2-xml-prop-ref-node
4344 (:include js2-xml-ref-node)
4345 (:constructor nil)
4346 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4347 (pos (js2-current-token-beg))
4348 len propname
4349 namespace at-pos
4350 colon-pos)))
4351 "AST node for an E4X XML [expr] property-ref expression.
4352 The JavaScript syntax is an optional @, an optional ns::, and a name.
4353
4354 [ '@' ] [ name '::' ] name
4355
4356 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4357 @ns::*, @*::attr, @*::*, and @*.
4358
4359 The node starts at the @ token, if present. Otherwise it starts at the
4360 namespace name. The node bounds extend through the closing right-bracket,
4361 or if it is missing due to a syntax error, through the end of the index
4362 expression."
4363 propname)
4364
4365 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4366 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4367
4368 (defun js2-visit-xml-prop-ref-node (n v)
4369 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4370 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4371
4372 (defun js2-print-xml-prop-ref-node (n i)
4373 (insert (js2-make-pad i))
4374 (if (js2-xml-ref-node-attr-access-p n)
4375 (insert "@"))
4376 (when (js2-xml-prop-ref-node-namespace n)
4377 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4378 (insert "::"))
4379 (if (js2-xml-prop-ref-node-propname n)
4380 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4381
4382 (cl-defstruct (js2-xml-elem-ref-node
4383 (:include js2-xml-ref-node)
4384 (:constructor nil)
4385 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4386 (pos (js2-current-token-beg))
4387 len expr lb rb
4388 namespace at-pos
4389 colon-pos)))
4390 "AST node for an E4X XML [expr] member-ref expression.
4391 Syntax:
4392
4393 [ '@' ] [ name '::' ] '[' expr ']'
4394
4395 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4396
4397 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4398 is not a legal E4X XML element-ref expression, since it's already used
4399 for standard JavaScript element-get array indexing. Hence, a
4400 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4401 non-nil namespace node, or both.
4402
4403 The node starts at the @ token, if present. Otherwise it starts
4404 at the namespace name. The node bounds extend through the closing
4405 right-bracket, or if it is missing due to a syntax error, through the
4406 end of the index expression."
4407 expr ; the bracketed index expression
4408 lb
4409 rb)
4410
4411 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4412 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4413
4414 (defun js2-visit-xml-elem-ref-node (n v)
4415 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4416 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4417
4418 (defun js2-print-xml-elem-ref-node (n i)
4419 (insert (js2-make-pad i))
4420 (if (js2-xml-ref-node-attr-access-p n)
4421 (insert "@"))
4422 (when (js2-xml-elem-ref-node-namespace n)
4423 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4424 (insert "::"))
4425 (insert "[")
4426 (if (js2-xml-elem-ref-node-expr n)
4427 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4428 (insert "]"))
4429
4430 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4431
4432 (cl-defstruct (js2-xml-start-tag-node
4433 (:include js2-xml-node)
4434 (:constructor nil)
4435 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4436 (pos js2-ts-cursor)
4437 len name attrs kids
4438 empty-p)))
4439 "AST node for an XML start-tag. Not currently used.
4440 The `kids' field is a Lisp list of child content nodes."
4441 name ; a `js2-xml-name-node'
4442 attrs ; a Lisp list of `js2-xml-attr-node'
4443 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4444
4445 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4446 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4447
4448 (defun js2-visit-xml-start-tag (n v)
4449 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4450 (dolist (attr (js2-xml-start-tag-node-attrs n))
4451 (js2-visit-ast attr v))
4452 (js2-visit-block n v))
4453
4454 (defun js2-print-xml-start-tag (n i)
4455 (insert (js2-make-pad i) "<")
4456 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4457 (when (js2-xml-start-tag-node-attrs n)
4458 (insert " ")
4459 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4460 (insert ">"))
4461
4462 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4463 ;; and add the end-tag to the kids list of the parent as well.
4464 (cl-defstruct (js2-xml-end-tag-node
4465 (:include js2-xml-node)
4466 (:constructor nil)
4467 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4468 (pos js2-ts-cursor)
4469 len name)))
4470 "AST node for an XML end-tag. Not currently used."
4471 name) ; a `js2-xml-name-node'
4472
4473 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4474 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4475
4476 (defun js2-visit-xml-end-tag (n v)
4477 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4478
4479 (defun js2-print-xml-end-tag (n i)
4480 (insert (js2-make-pad i))
4481 (insert "</")
4482 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4483 (insert ">"))
4484
4485 (cl-defstruct (js2-xml-name-node
4486 (:include js2-xml-node)
4487 (:constructor nil)
4488 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4489 (pos js2-ts-cursor)
4490 len namespace kids)))
4491 "AST node for an E4X XML name. Not currently used.
4492 Any XML name can be qualified with a namespace, hence the namespace field.
4493 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4494 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4495 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4496 namespace) ; a `js2-string-node'
4497
4498 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4499 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4500
4501 (defun js2-visit-xml-name-node (n v)
4502 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4503
4504 (defun js2-print-xml-name-node (n i)
4505 (insert (js2-make-pad i))
4506 (when (js2-xml-name-node-namespace n)
4507 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4508 (insert "::"))
4509 (dolist (kid (js2-xml-name-node-kids n))
4510 (js2-print-ast kid 0)))
4511
4512 (cl-defstruct (js2-xml-pi-node
4513 (:include js2-xml-node)
4514 (:constructor nil)
4515 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4516 (pos js2-ts-cursor)
4517 len name attrs)))
4518 "AST node for an E4X XML processing instruction. Not currently used."
4519 name ; a `js2-xml-name-node'
4520 attrs) ; a list of `js2-xml-attr-node'
4521
4522 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4523 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4524
4525 (defun js2-visit-xml-pi-node (n v)
4526 (js2-visit-ast (js2-xml-pi-node-name n) v)
4527 (dolist (attr (js2-xml-pi-node-attrs n))
4528 (js2-visit-ast attr v)))
4529
4530 (defun js2-print-xml-pi-node (n i)
4531 (insert (js2-make-pad i) "<?")
4532 (js2-print-ast (js2-xml-pi-node-name n))
4533 (when (js2-xml-pi-node-attrs n)
4534 (insert " ")
4535 (js2-print-list (js2-xml-pi-node-attrs n)))
4536 (insert "?>"))
4537
4538 (cl-defstruct (js2-xml-cdata-node
4539 (:include js2-xml-node)
4540 (:constructor nil)
4541 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4542 (pos js2-ts-cursor)
4543 len content)))
4544 "AST node for a CDATA escape section. Not currently used."
4545 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4546
4547 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4548 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4549
4550 (defun js2-visit-xml-cdata-node (n v)
4551 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4552
4553 (defun js2-print-xml-cdata-node (n i)
4554 (insert (js2-make-pad i))
4555 (js2-print-ast (js2-xml-cdata-node-content n)))
4556
4557 (cl-defstruct (js2-xml-attr-node
4558 (:include js2-xml-node)
4559 (:constructor nil)
4560 (:constructor make-js2-attr-node (&key (type js2-XML)
4561 (pos js2-ts-cursor)
4562 len name value
4563 eq-pos quote-type)))
4564 "AST node representing a foo='bar' XML attribute value. Not yet used."
4565 name ; a `js2-xml-name-node'
4566 value ; a `js2-xml-name-node'
4567 eq-pos ; buffer position of "=" sign
4568 quote-type) ; 'single or 'double
4569
4570 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4571 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4572
4573 (defun js2-visit-xml-attr-node (n v)
4574 (js2-visit-ast (js2-xml-attr-node-name n) v)
4575 (js2-visit-ast (js2-xml-attr-node-value n) v))
4576
4577 (defun js2-print-xml-attr-node (n i)
4578 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4579 "'"
4580 "\"")))
4581 (insert (js2-make-pad i))
4582 (js2-print-ast (js2-xml-attr-node-name n) 0)
4583 (insert "=" quote)
4584 (js2-print-ast (js2-xml-attr-node-value n) 0)
4585 (insert quote)))
4586
4587 (cl-defstruct (js2-xml-text-node
4588 (:include js2-xml-node)
4589 (:constructor nil)
4590 (:constructor make-js2-text-node (&key (type js2-XML)
4591 (pos js2-ts-cursor)
4592 len content)))
4593 "AST node for an E4X XML text node. Not currently used."
4594 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4595
4596 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4597 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4598
4599 (defun js2-visit-xml-text-node (n v)
4600 (js2-visit-ast (js2-xml-text-node-content n) v))
4601
4602 (defun js2-print-xml-text-node (n i)
4603 (insert (js2-make-pad i))
4604 (dolist (kid (js2-xml-text-node-content n))
4605 (js2-print-ast kid)))
4606
4607 (cl-defstruct (js2-xml-comment-node
4608 (:include js2-xml-node)
4609 (:constructor nil)
4610 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4611 (pos js2-ts-cursor)
4612 len)))
4613 "AST node for E4X XML comment. Not currently used.")
4614
4615 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4616 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4617
4618 (defun js2-print-xml-comment (n i)
4619 (insert (js2-make-pad i)
4620 (js2-node-string n)))
4621
4622 ;;; Node utilities
4623
4624 (defsubst js2-node-line (n)
4625 "Fetch the source line number at the start of node N.
4626 This is O(n) in the length of the source buffer; use prudently."
4627 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4628
4629 (defsubst js2-block-node-kid (n i)
4630 "Return child I of node N, or nil if there aren't that many."
4631 (nth i (js2-block-node-kids n)))
4632
4633 (defsubst js2-block-node-first (n)
4634 "Return first child of block node N, or nil if there is none."
4635 (cl-first (js2-block-node-kids n)))
4636
4637 (defun js2-node-root (n)
4638 "Return the root of the AST containing N.
4639 If N has no parent pointer, returns N."
4640 (let ((parent (js2-node-parent n)))
4641 (if parent
4642 (js2-node-root parent)
4643 n)))
4644
4645 (defsubst js2-node-short-name (n)
4646 "Return the short name of node N as a string, e.g. `js2-if-node'."
4647 (substring (symbol-name (aref n 0))
4648 (length "cl-struct-")))
4649
4650 (defun js2-node-child-list (node)
4651 "Return the child list for NODE, a Lisp list of nodes.
4652 Works for block nodes, array nodes, obj literals, funarg lists,
4653 var decls and try nodes (for catch clauses). Note that you should call
4654 `js2-block-node-kids' on the function body for the body statements.
4655 Returns nil for zero-length child lists or unsupported nodes."
4656 (cond
4657 ((js2-function-node-p node)
4658 (js2-function-node-params node))
4659 ((js2-block-node-p node)
4660 (js2-block-node-kids node))
4661 ((js2-try-node-p node)
4662 (js2-try-node-catch-clauses node))
4663 ((js2-array-node-p node)
4664 (js2-array-node-elems node))
4665 ((js2-object-node-p node)
4666 (js2-object-node-elems node))
4667 ((js2-call-node-p node)
4668 (js2-call-node-args node))
4669 ((js2-new-node-p node)
4670 (js2-new-node-args node))
4671 ((js2-var-decl-node-p node)
4672 (js2-var-decl-node-kids node))
4673 (t
4674 nil)))
4675
4676 (defun js2-node-set-child-list (node kids)
4677 "Set the child list for NODE to KIDS."
4678 (cond
4679 ((js2-function-node-p node)
4680 (setf (js2-function-node-params node) kids))
4681 ((js2-block-node-p node)
4682 (setf (js2-block-node-kids node) kids))
4683 ((js2-try-node-p node)
4684 (setf (js2-try-node-catch-clauses node) kids))
4685 ((js2-array-node-p node)
4686 (setf (js2-array-node-elems node) kids))
4687 ((js2-object-node-p node)
4688 (setf (js2-object-node-elems node) kids))
4689 ((js2-call-node-p node)
4690 (setf (js2-call-node-args node) kids))
4691 ((js2-new-node-p node)
4692 (setf (js2-new-node-args node) kids))
4693 ((js2-var-decl-node-p node)
4694 (setf (js2-var-decl-node-kids node) kids))
4695 (t
4696 (error "Unsupported node type: %s" (js2-node-short-name node))))
4697 kids)
4698
4699 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4700 (defconst js2-paren-expr-nodes
4701 '(cl-struct-js2-comp-loop-node
4702 cl-struct-js2-comp-node
4703 cl-struct-js2-call-node
4704 cl-struct-js2-catch-node
4705 cl-struct-js2-do-node
4706 cl-struct-js2-elem-get-node
4707 cl-struct-js2-for-in-node
4708 cl-struct-js2-for-node
4709 cl-struct-js2-function-node
4710 cl-struct-js2-if-node
4711 cl-struct-js2-let-node
4712 cl-struct-js2-new-node
4713 cl-struct-js2-paren-node
4714 cl-struct-js2-switch-node
4715 cl-struct-js2-while-node
4716 cl-struct-js2-with-node
4717 cl-struct-js2-xml-dot-query-node)
4718 "Node types that can have a parenthesized child expression.
4719 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4720
4721 (defsubst js2-paren-expr-node-p (node)
4722 "Return t for nodes that typically have a parenthesized child expression.
4723 Useful for computing the indentation anchors for arg-lists and conditions.
4724 Note that it may return a false positive, for instance when NODE is
4725 a `js2-new-node' and there are no arguments or parentheses."
4726 (memq (aref node 0) js2-paren-expr-nodes))
4727
4728 ;; Fake polymorphism... yech.
4729 (defun js2-node-lp (node)
4730 "Return relative left-paren position for NODE, if applicable.
4731 For `js2-elem-get-node' structs, returns left-bracket position.
4732 Note that the position may be nil in the case of a parse error."
4733 (cond
4734 ((js2-elem-get-node-p node)
4735 (js2-elem-get-node-lb node))
4736 ((js2-loop-node-p node)
4737 (js2-loop-node-lp node))
4738 ((js2-function-node-p node)
4739 (js2-function-node-lp node))
4740 ((js2-if-node-p node)
4741 (js2-if-node-lp node))
4742 ((js2-new-node-p node)
4743 (js2-new-node-lp node))
4744 ((js2-call-node-p node)
4745 (js2-call-node-lp node))
4746 ((js2-paren-node-p node)
4747 0)
4748 ((js2-switch-node-p node)
4749 (js2-switch-node-lp node))
4750 ((js2-catch-node-p node)
4751 (js2-catch-node-lp node))
4752 ((js2-let-node-p node)
4753 (js2-let-node-lp node))
4754 ((js2-comp-node-p node)
4755 0)
4756 ((js2-with-node-p node)
4757 (js2-with-node-lp node))
4758 ((js2-xml-dot-query-node-p node)
4759 (1+ (js2-infix-node-op-pos node)))
4760 (t
4761 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4762
4763 ;; Fake polymorphism... blech.
4764 (defun js2-node-rp (node)
4765 "Return relative right-paren position for NODE, if applicable.
4766 For `js2-elem-get-node' structs, returns right-bracket position.
4767 Note that the position may be nil in the case of a parse error."
4768 (cond
4769 ((js2-elem-get-node-p node)
4770 (js2-elem-get-node-rb node))
4771 ((js2-loop-node-p node)
4772 (js2-loop-node-rp node))
4773 ((js2-function-node-p node)
4774 (js2-function-node-rp node))
4775 ((js2-if-node-p node)
4776 (js2-if-node-rp node))
4777 ((js2-new-node-p node)
4778 (js2-new-node-rp node))
4779 ((js2-call-node-p node)
4780 (js2-call-node-rp node))
4781 ((js2-paren-node-p node)
4782 (1- (js2-node-len node)))
4783 ((js2-switch-node-p node)
4784 (js2-switch-node-rp node))
4785 ((js2-catch-node-p node)
4786 (js2-catch-node-rp node))
4787 ((js2-let-node-p node)
4788 (js2-let-node-rp node))
4789 ((js2-comp-node-p node)
4790 (1- (js2-node-len node)))
4791 ((js2-with-node-p node)
4792 (js2-with-node-rp node))
4793 ((js2-xml-dot-query-node-p node)
4794 (1+ (js2-xml-dot-query-node-rp node)))
4795 (t
4796 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4797
4798 (defsubst js2-node-first-child (node)
4799 "Return the first element of `js2-node-child-list' for NODE."
4800 (car (js2-node-child-list node)))
4801
4802 (defsubst js2-node-last-child (node)
4803 "Return the last element of `js2-node-last-child' for NODE."
4804 (car (last (js2-node-child-list node))))
4805
4806 (defun js2-node-prev-sibling (node)
4807 "Return the previous statement in parent.
4808 Works for parents supported by `js2-node-child-list'.
4809 Returns nil if NODE is not in the parent, or PARENT is
4810 not a supported node, or if NODE is the first child."
4811 (let* ((p (js2-node-parent node))
4812 (kids (js2-node-child-list p))
4813 (sib (car kids)))
4814 (while (and kids
4815 (not (eq node (cadr kids))))
4816 (setq kids (cdr kids)
4817 sib (car kids)))
4818 sib))
4819
4820 (defun js2-node-next-sibling (node)
4821 "Return the next statement in parent block.
4822 Returns nil if NODE is not in the block, or PARENT is not
4823 a block node, or if NODE is the last statement."
4824 (let* ((p (js2-node-parent node))
4825 (kids (js2-node-child-list p)))
4826 (while (and kids
4827 (not (eq node (car kids))))
4828 (setq kids (cdr kids)))
4829 (cadr kids)))
4830
4831 (defun js2-node-find-child-before (pos parent &optional after)
4832 "Find the last child that starts before POS in parent.
4833 If AFTER is non-nil, returns first child starting after POS.
4834 POS is an absolute buffer position. PARENT is any node
4835 supported by `js2-node-child-list'.
4836 Returns nil if no applicable child is found."
4837 (let ((kids (if (js2-function-node-p parent)
4838 (js2-block-node-kids (js2-function-node-body parent))
4839 (js2-node-child-list parent)))
4840 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4841 (js2-function-node-body parent)
4842 parent)))
4843 kid result fn
4844 (continue t))
4845 (setq fn (if after '>= '<))
4846 (while (and kids continue)
4847 (setq kid (car kids))
4848 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4849 (setq result kid
4850 continue (not after))
4851 (setq continue after))
4852 (setq kids (cdr kids)))
4853 result))
4854
4855 (defun js2-node-find-child-after (pos parent)
4856 "Find first child that starts after POS in parent.
4857 POS is an absolute buffer position. PARENT is any node
4858 supported by `js2-node-child-list'.
4859 Returns nil if no applicable child is found."
4860 (js2-node-find-child-before pos parent 'after))
4861
4862 (defun js2-node-replace-child (pos parent new-node)
4863 "Replace node at index POS in PARENT with NEW-NODE.
4864 Only works for parents supported by `js2-node-child-list'."
4865 (let ((kids (js2-node-child-list parent))
4866 (i 0))
4867 (while (< i pos)
4868 (setq kids (cdr kids)
4869 i (1+ i)))
4870 (setcar kids new-node)
4871 (js2-node-add-children parent new-node)))
4872
4873 (defun js2-node-buffer (n)
4874 "Return the buffer associated with AST N.
4875 Returns nil if the buffer is not set as a property on the root
4876 node, or if parent links were not recorded during parsing."
4877 (let ((root (js2-node-root n)))
4878 (and root
4879 (js2-ast-root-p root)
4880 (js2-ast-root-buffer root))))
4881
4882 (defun js2-block-node-push (n kid)
4883 "Push js2-node KID onto the end of js2-block-node N's child list.
4884 KID is always added to the -end- of the kids list.
4885 Function also calls `js2-node-add-children' to add the parent link."
4886 (let ((kids (js2-node-child-list n)))
4887 (if kids
4888 (setcdr kids (nconc (cdr kids) (list kid)))
4889 (js2-node-set-child-list n (list kid)))
4890 (js2-node-add-children n kid)))
4891
4892 (defun js2-node-string (node)
4893 (with-current-buffer (or (js2-node-buffer node)
4894 (error "No buffer available for node %s" node))
4895 (let ((pos (js2-node-abs-pos node)))
4896 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4897
4898 ;; Container for storing the node we're looking for in a traversal.
4899 (js2-deflocal js2-discovered-node nil)
4900
4901 ;; Keep track of absolute node position during traversals.
4902 (js2-deflocal js2-visitor-offset nil)
4903
4904 (js2-deflocal js2-node-search-point nil)
4905
4906 (when js2-mode-dev-mode-p
4907 (defun js2-find-node-at-point ()
4908 (interactive)
4909 (let ((node (js2-node-at-point)))
4910 (message "%s" (or node "No node found at point"))))
4911 (defun js2-node-name-at-point ()
4912 (interactive)
4913 (let ((node (js2-node-at-point)))
4914 (message "%s" (if node
4915 (js2-node-short-name node)
4916 "No node found at point.")))))
4917
4918 (defun js2-node-at-point (&optional pos skip-comments)
4919 "Return AST node at POS, a buffer position, defaulting to current point.
4920 The `js2-mode-ast' variable must be set to the current parse tree.
4921 Signals an error if the AST (`js2-mode-ast') is nil.
4922 Always returns a node - if it can't find one, it returns the root.
4923 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4924 (let ((ast js2-mode-ast)
4925 result)
4926 (unless ast
4927 (error "No JavaScript AST available"))
4928 ;; Look through comments first, since they may be inside nodes that
4929 ;; would otherwise report a match.
4930 (setq pos (or pos (point))
4931 result (if (> pos (js2-node-abs-end ast))
4932 ast
4933 (if (not skip-comments)
4934 (js2-comment-at-point pos))))
4935 (unless result
4936 (setq js2-discovered-node nil
4937 js2-visitor-offset 0
4938 js2-node-search-point pos)
4939 (unwind-protect
4940 (catch 'js2-visit-done
4941 (js2-visit-ast ast #'js2-node-at-point-visitor))
4942 (setq js2-visitor-offset nil
4943 js2-node-search-point nil))
4944 (setq result js2-discovered-node))
4945 ;; may have found a comment beyond end of last child node,
4946 ;; since visiting the ast-root looks at the comment-list last.
4947 (if (and skip-comments
4948 (js2-comment-node-p result))
4949 (setq result nil))
4950 (or result js2-mode-ast)))
4951
4952 (defun js2-node-at-point-visitor (node end-p)
4953 (let ((rel-pos (js2-node-pos node))
4954 abs-pos
4955 abs-end
4956 (point js2-node-search-point))
4957 (cond
4958 (end-p
4959 ;; this evaluates to a non-nil return value, even if it's zero
4960 (cl-decf js2-visitor-offset rel-pos))
4961 ;; we already looked for comments before visiting, and don't want them now
4962 ((js2-comment-node-p node)
4963 nil)
4964 (t
4965 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4966 ;; we only want to use the node if the point is before
4967 ;; the last character position in the node, so we decrement
4968 ;; the absolute end by 1.
4969 abs-end (+ abs-pos (js2-node-len node) -1))
4970 (cond
4971 ;; If this node starts after search-point, stop the search.
4972 ((> abs-pos point)
4973 (throw 'js2-visit-done nil))
4974 ;; If this node ends before the search-point, don't check kids.
4975 ((> point abs-end)
4976 nil)
4977 (t
4978 ;; Otherwise point is within this node, possibly in a child.
4979 (setq js2-discovered-node node)
4980 t)))))) ; keep processing kids to look for more specific match
4981
4982 (defsubst js2-block-comment-p (node)
4983 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4984 (and (js2-comment-node-p node)
4985 (memq (js2-comment-node-format node) '(jsdoc block))))
4986
4987 ;; TODO: put the comments in a vector and binary-search them instead
4988 (defun js2-comment-at-point (&optional pos)
4989 "Look through scanned comment nodes for one containing POS.
4990 POS is a buffer position that defaults to current point.
4991 Function returns nil if POS was not in any comment node."
4992 (let ((ast js2-mode-ast)
4993 (x (or pos (point)))
4994 beg end)
4995 (unless ast
4996 (error "No JavaScript AST available"))
4997 (catch 'done
4998 ;; Comments are stored in lexical order.
4999 (dolist (comment (js2-ast-root-comments ast) nil)
5000 (setq beg (js2-node-abs-pos comment)
5001 end (+ beg (js2-node-len comment)))
5002 (if (and (>= x beg)
5003 (<= x end))
5004 (throw 'done comment))))))
5005
5006 (defun js2-mode-find-parent-fn (node)
5007 "Find function enclosing NODE.
5008 Returns nil if NODE is not inside a function."
5009 (setq node (js2-node-parent node))
5010 (while (and node (not (js2-function-node-p node)))
5011 (setq node (js2-node-parent node)))
5012 (and (js2-function-node-p node) node))
5013
5014 (defun js2-mode-find-enclosing-fn (node)
5015 "Find function or root enclosing NODE."
5016 (if (js2-ast-root-p node)
5017 node
5018 (setq node (js2-node-parent node))
5019 (while (not (or (js2-ast-root-p node)
5020 (js2-function-node-p node)))
5021 (setq node (js2-node-parent node)))
5022 node))
5023
5024 (defun js2-mode-find-enclosing-node (beg end)
5025 "Find node fully enclosing BEG and END."
5026 (let ((node (js2-node-at-point beg))
5027 pos
5028 (continue t))
5029 (while continue
5030 (if (or (js2-ast-root-p node)
5031 (and
5032 (<= (setq pos (js2-node-abs-pos node)) beg)
5033 (>= (+ pos (js2-node-len node)) end)))
5034 (setq continue nil)
5035 (setq node (js2-node-parent node))))
5036 node))
5037
5038 (defun js2-node-parent-script-or-fn (node)
5039 "Find script or function immediately enclosing NODE.
5040 If NODE is the ast-root, returns nil."
5041 (if (js2-ast-root-p node)
5042 nil
5043 (setq node (js2-node-parent node))
5044 (while (and node (not (or (js2-function-node-p node)
5045 (js2-script-node-p node))))
5046 (setq node (js2-node-parent node)))
5047 node))
5048
5049 (defun js2-node-is-descendant (node ancestor)
5050 "Return t if NODE is a descendant of ANCESTOR."
5051 (while (and node
5052 (not (eq node ancestor)))
5053 (setq node (js2-node-parent node)))
5054 node)
5055
5056 ;;; visitor infrastructure
5057
5058 (defun js2-visit-none (_node _callback)
5059 "Visitor for AST node that have no node children."
5060 nil)
5061
5062 (defun js2-print-none (_node _indent)
5063 "Visitor for AST node with no printed representation.")
5064
5065 (defun js2-print-body (node indent)
5066 "Print a statement, or a block without braces."
5067 (if (js2-block-node-p node)
5068 (dolist (kid (js2-block-node-kids node))
5069 (js2-print-ast kid indent))
5070 (js2-print-ast node indent)))
5071
5072 (defun js2-print-list (args &optional delimiter)
5073 (cl-loop with len = (length args)
5074 for arg in args
5075 for count from 1
5076 do
5077 (when arg (js2-print-ast arg 0))
5078 (if (< count len)
5079 (insert (or delimiter ", ")))))
5080
5081 (defun js2-print-tree (ast)
5082 "Prints an AST to the current buffer.
5083 Makes `js2-ast-parent-nodes' available to the printer functions."
5084 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5085 (js2-print-ast ast)))
5086
5087 (defun js2-print-ast (node &optional indent)
5088 "Helper function for printing AST nodes.
5089 Requires `js2-ast-parent-nodes' to be non-nil.
5090 You should use `js2-print-tree' instead of this function."
5091 (let ((printer (get (aref node 0) 'js2-printer))
5092 (i (or indent 0)))
5093 ;; TODO: wedge comments in here somewhere
5094 (if printer
5095 (funcall printer node i))))
5096
5097 (defconst js2-side-effecting-tokens
5098 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5099 (dolist (tt (list js2-ASSIGN
5100 js2-ASSIGN_ADD
5101 js2-ASSIGN_BITAND
5102 js2-ASSIGN_BITOR
5103 js2-ASSIGN_BITXOR
5104 js2-ASSIGN_DIV
5105 js2-ASSIGN_LSH
5106 js2-ASSIGN_MOD
5107 js2-ASSIGN_MUL
5108 js2-ASSIGN_RSH
5109 js2-ASSIGN_SUB
5110 js2-ASSIGN_URSH
5111 js2-BLOCK
5112 js2-BREAK
5113 js2-CALL
5114 js2-CATCH
5115 js2-CATCH_SCOPE
5116 js2-CLASS
5117 js2-CONST
5118 js2-CONTINUE
5119 js2-DEBUGGER
5120 js2-DEC
5121 js2-DELPROP
5122 js2-DEL_REF
5123 js2-DO
5124 js2-ELSE
5125 js2-EMPTY
5126 js2-ENTERWITH
5127 js2-EXPORT
5128 js2-EXPR_RESULT
5129 js2-FINALLY
5130 js2-FOR
5131 js2-FUNCTION
5132 js2-GOTO
5133 js2-IF
5134 js2-IFEQ
5135 js2-IFNE
5136 js2-IMPORT
5137 js2-INC
5138 js2-JSR
5139 js2-LABEL
5140 js2-LEAVEWITH
5141 js2-LET
5142 js2-LETEXPR
5143 js2-LOCAL_BLOCK
5144 js2-LOOP
5145 js2-NEW
5146 js2-REF_CALL
5147 js2-RETHROW
5148 js2-RETURN
5149 js2-RETURN_RESULT
5150 js2-SEMI
5151 js2-SETELEM
5152 js2-SETELEM_OP
5153 js2-SETNAME
5154 js2-SETPROP
5155 js2-SETPROP_OP
5156 js2-SETVAR
5157 js2-SET_REF
5158 js2-SET_REF_OP
5159 js2-SWITCH
5160 js2-TARGET
5161 js2-THROW
5162 js2-TRY
5163 js2-VAR
5164 js2-WHILE
5165 js2-WITH
5166 js2-WITHEXPR
5167 js2-YIELD))
5168 (aset tokens tt t))
5169 (if js2-instanceof-has-side-effects
5170 (aset tokens js2-INSTANCEOF t))
5171 tokens))
5172
5173 (defun js2-node-has-side-effects (node)
5174 "Return t if NODE has side effects."
5175 (when node ; makes it easier to handle malformed expressions
5176 (let ((tt (js2-node-type node)))
5177 (cond
5178 ;; This doubtless needs some work, since EXPR_VOID is used
5179 ;; in several ways in Rhino and I may not have caught them all.
5180 ;; I'll wait for people to notice incorrect warnings.
5181 ((and (= tt js2-EXPR_VOID)
5182 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5183 (let ((expr (js2-expr-stmt-node-expr node)))
5184 (or (js2-node-has-side-effects expr)
5185 (when (js2-string-node-p expr)
5186 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5187 ((= tt js2-COMMA)
5188 (js2-node-has-side-effects (js2-infix-node-right node)))
5189 ((or (= tt js2-AND)
5190 (= tt js2-OR))
5191 (or (js2-node-has-side-effects (js2-infix-node-right node))
5192 (js2-node-has-side-effects (js2-infix-node-left node))))
5193 ((= tt js2-HOOK)
5194 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5195 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5196 ((js2-paren-node-p node)
5197 (js2-node-has-side-effects (js2-paren-node-expr node)))
5198 ((= tt js2-ERROR) ; avoid cascaded error messages
5199 nil)
5200 (t
5201 (aref js2-side-effecting-tokens tt))))))
5202
5203 (defconst js2-stmt-node-types
5204 (list js2-BLOCK
5205 js2-BREAK
5206 js2-CONTINUE
5207 js2-DEFAULT ; e4x "default xml namespace" statement
5208 js2-DO
5209 js2-EXPORT
5210 js2-EXPR_RESULT
5211 js2-EXPR_VOID
5212 js2-FOR
5213 js2-IF
5214 js2-IMPORT
5215 js2-RETURN
5216 js2-SWITCH
5217 js2-THROW
5218 js2-TRY
5219 js2-WHILE
5220 js2-WITH)
5221 "Node types that only appear in statement contexts.
5222 The list does not include nodes that always appear as the child
5223 of another specific statement type, such as switch-cases,
5224 catch and finally blocks, and else-clauses. The list also excludes
5225 nodes like yield, let and var, which may appear in either expression
5226 or statement context, and in the latter context always have a
5227 `js2-expr-stmt-node' parent. Finally, the list does not include
5228 functions or scripts, which are treated separately from statements
5229 by the JavaScript parser and runtime.")
5230
5231 (defun js2-stmt-node-p (node)
5232 "Heuristic for figuring out if NODE is a statement.
5233 Some node types can appear in either an expression context or a
5234 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5235 For these node types in a statement context, the parent will be a
5236 `js2-expr-stmt-node'.
5237 Functions aren't included in the check."
5238 (memq (js2-node-type node) js2-stmt-node-types))
5239
5240 (defun js2-mode-find-first-stmt (node)
5241 "Search upward starting from NODE looking for a statement.
5242 For purposes of this function, a `js2-function-node' counts."
5243 (while (not (or (js2-stmt-node-p node)
5244 (js2-function-node-p node)))
5245 (setq node (js2-node-parent node)))
5246 node)
5247
5248 (defun js2-node-parent-stmt (node)
5249 "Return the node's first ancestor that is a statement.
5250 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5251 appearing in a statement context will have a parent that is a
5252 `js2-expr-stmt-node' that will be returned by this function."
5253 (let ((parent (js2-node-parent node)))
5254 (if (or (null parent)
5255 (js2-stmt-node-p parent)
5256 (and (js2-function-node-p parent)
5257 (not (eq (js2-function-node-form parent)
5258 'FUNCTION_EXPRESSION))))
5259 parent
5260 (js2-node-parent-stmt parent))))
5261
5262 ;; In the Mozilla Rhino sources, Roshan James writes:
5263 ;; Does consistent-return analysis on the function body when strict mode is
5264 ;; enabled.
5265 ;;
5266 ;; function (x) { return (x+1) }
5267 ;;
5268 ;; is ok, but
5269 ;;
5270 ;; function (x) { if (x < 0) return (x+1); }
5271 ;;
5272 ;; is not because the function can potentially return a value when the
5273 ;; condition is satisfied and if not, the function does not explicitly
5274 ;; return a value.
5275 ;;
5276 ;; This extends to checking mismatches such as "return" and "return <value>"
5277 ;; used in the same function. Warnings are not emitted if inconsistent
5278 ;; returns exist in code that can be statically shown to be unreachable.
5279 ;; Ex.
5280 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5281 ;;
5282 ;; emits no warning. However if the loop had a break statement, then a
5283 ;; warning would be emitted.
5284 ;;
5285 ;; The consistency analysis looks at control structures such as loops, ifs,
5286 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5287 ;; warns the user about an inconsistent set of termination possibilities.
5288 ;;
5289 ;; These flags enumerate the possible ways a statement/function can
5290 ;; terminate. These flags are used by endCheck() and by the Parser to
5291 ;; detect inconsistent return usage.
5292 ;;
5293 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5294 ;; able to execute (example: throw, continue)
5295 ;;
5296 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5297 ;; next one. Statement such as return dont. A compound statement may have
5298 ;; some branch that drops off control to the next statement.
5299 ;;
5300 ;; END_RETURNS indicates that the statement can return with no value.
5301 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5302 ;;
5303 ;; A compound statement such as
5304 ;; if (condition) {
5305 ;; return value;
5306 ;; }
5307 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5308
5309 (defconst js2-END_UNREACHED 0)
5310 (defconst js2-END_DROPS_OFF 1)
5311 (defconst js2-END_RETURNS 2)
5312 (defconst js2-END_RETURNS_VALUE 4)
5313 (defconst js2-END_YIELDS 8)
5314
5315 (defun js2-has-consistent-return-usage (node)
5316 "Check that every return usage in a function body is consistent.
5317 Returns t if the function satisfies strict mode requirement."
5318 (let ((n (js2-end-check node)))
5319 ;; either it doesn't return a value in any branch...
5320 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5321 ;; or it returns a value (or is unreached) at every branch
5322 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5323 js2-END_RETURNS
5324 js2-END_YIELDS)))))
5325
5326 (defun js2-end-check-if (node)
5327 "Ensure that return usage in then/else blocks is consistent.
5328 If there is no else block, then the return statement can fall through.
5329 Returns logical OR of END_* flags"
5330 (let ((th (js2-if-node-then-part node))
5331 (el (js2-if-node-else-part node)))
5332 (if (null th)
5333 js2-END_UNREACHED
5334 (logior (js2-end-check th) (if el
5335 (js2-end-check el)
5336 js2-END_DROPS_OFF)))))
5337
5338 (defun js2-end-check-switch (node)
5339 "Consistency of return statements is checked between the case statements.
5340 If there is no default, then the switch can fall through. If there is a
5341 default, we check to see if all code paths in the default return or if
5342 there is a code path that can fall through.
5343 Returns logical OR of END_* flags."
5344 (let ((rv js2-END_UNREACHED)
5345 default-case)
5346 ;; examine the cases
5347 (catch 'break
5348 (dolist (c (js2-switch-node-cases node))
5349 (if (js2-case-node-expr c)
5350 (js2-set-flag rv (js2-end-check-block c))
5351 (setq default-case c)
5352 (throw 'break nil))))
5353 ;; we don't care how the cases drop into each other
5354 (js2-clear-flag rv js2-END_DROPS_OFF)
5355 ;; examine the default
5356 (js2-set-flag rv (if default-case
5357 (js2-end-check default-case)
5358 js2-END_DROPS_OFF))
5359 rv))
5360
5361 (defun js2-end-check-try (node)
5362 "If the block has a finally, return consistency is checked in the
5363 finally block. If all code paths in the finally return, then the
5364 returns in the try-catch blocks don't matter. If there is a code path
5365 that does not return or if there is no finally block, the returns
5366 of the try and catch blocks are checked for mismatch.
5367 Returns logical OR of END_* flags."
5368 (let ((finally (js2-try-node-finally-block node))
5369 rv)
5370 ;; check the finally if it exists
5371 (setq rv (if finally
5372 (js2-end-check (js2-finally-node-body finally))
5373 js2-END_DROPS_OFF))
5374 ;; If the finally block always returns, then none of the returns
5375 ;; in the try or catch blocks matter.
5376 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5377 (js2-clear-flag rv js2-END_DROPS_OFF)
5378 ;; examine the try block
5379 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5380 ;; check each catch block
5381 (dolist (cb (js2-try-node-catch-clauses node))
5382 (js2-set-flag rv (js2-end-check cb))))
5383 rv))
5384
5385 (defun js2-end-check-loop (node)
5386 "Return statement in the loop body must be consistent.
5387 The default assumption for any kind of a loop is that it will eventually
5388 terminate. The only exception is a loop with a constant true condition.
5389 Code that follows such a loop is examined only if one can determine
5390 statically that there is a break out of the loop.
5391
5392 for(... ; ... ; ...) {}
5393 for(... in ... ) {}
5394 while(...) { }
5395 do { } while(...)
5396
5397 Returns logical OR of END_* flags."
5398 (let ((rv (js2-end-check (js2-loop-node-body node)))
5399 (condition (cond
5400 ((js2-while-node-p node)
5401 (js2-while-node-condition node))
5402 ((js2-do-node-p node)
5403 (js2-do-node-condition node))
5404 ((js2-for-node-p node)
5405 (js2-for-node-condition node)))))
5406
5407 ;; check to see if the loop condition is always true
5408 (if (and condition
5409 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5410 (js2-clear-flag rv js2-END_DROPS_OFF))
5411
5412 ;; look for effect of breaks
5413 (js2-set-flag rv (js2-node-get-prop node
5414 'CONTROL_BLOCK_PROP
5415 js2-END_UNREACHED))
5416 rv))
5417
5418 (defun js2-end-check-block (node)
5419 "A general block of code is examined statement by statement.
5420 If any statement (even a compound one) returns in all branches, then
5421 subsequent statements are not examined.
5422 Returns logical OR of END_* flags."
5423 (let* ((rv js2-END_DROPS_OFF)
5424 (kids (js2-block-node-kids node))
5425 (n (car kids)))
5426 ;; Check each statement. If the statement can continue onto the next
5427 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5428 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5429 (js2-clear-flag rv js2-END_DROPS_OFF)
5430 (js2-set-flag rv (js2-end-check n))
5431 (setq kids (cdr kids)
5432 n (car kids)))
5433 rv))
5434
5435 (defun js2-end-check-label (node)
5436 "A labeled statement implies that there may be a break to the label.
5437 The function processes the labeled statement and then checks the
5438 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5439 particular label.
5440 Returns logical OR of END_* flags."
5441 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5442 (logior rv (js2-node-get-prop node
5443 'CONTROL_BLOCK_PROP
5444 js2-END_UNREACHED))))
5445
5446 (defun js2-end-check-break (node)
5447 "When a break is encountered annotate the statement being broken
5448 out of by setting its CONTROL_BLOCK_PROP property.
5449 Returns logical OR of END_* flags."
5450 (and (js2-break-node-target node)
5451 (js2-node-set-prop (js2-break-node-target node)
5452 'CONTROL_BLOCK_PROP
5453 js2-END_DROPS_OFF))
5454 js2-END_UNREACHED)
5455
5456 (defun js2-end-check (node)
5457 "Examine the body of a function, doing a basic reachability analysis.
5458 Returns a combination of flags END_* flags that indicate
5459 how the function execution can terminate. These constitute only the
5460 pessimistic set of termination conditions. It is possible that at
5461 runtime certain code paths will never be actually taken. Hence this
5462 analysis will flag errors in cases where there may not be errors.
5463 Returns logical OR of END_* flags"
5464 (let (kid)
5465 (cond
5466 ((js2-break-node-p node)
5467 (js2-end-check-break node))
5468 ((js2-expr-stmt-node-p node)
5469 (if (setq kid (js2-expr-stmt-node-expr node))
5470 (js2-end-check kid)
5471 js2-END_DROPS_OFF))
5472 ((or (js2-continue-node-p node)
5473 (js2-throw-node-p node))
5474 js2-END_UNREACHED)
5475 ((js2-return-node-p node)
5476 (if (setq kid (js2-return-node-retval node))
5477 js2-END_RETURNS_VALUE
5478 js2-END_RETURNS))
5479 ((js2-loop-node-p node)
5480 (js2-end-check-loop node))
5481 ((js2-switch-node-p node)
5482 (js2-end-check-switch node))
5483 ((js2-labeled-stmt-node-p node)
5484 (js2-end-check-label node))
5485 ((js2-if-node-p node)
5486 (js2-end-check-if node))
5487 ((js2-try-node-p node)
5488 (js2-end-check-try node))
5489 ((js2-block-node-p node)
5490 (if (null (js2-block-node-kids node))
5491 js2-END_DROPS_OFF
5492 (js2-end-check-block node)))
5493 ((js2-yield-node-p node)
5494 js2-END_YIELDS)
5495 (t
5496 js2-END_DROPS_OFF))))
5497
5498 (defun js2-always-defined-boolean-p (node)
5499 "Check if NODE always evaluates to true or false in boolean context.
5500 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5501 nor always false."
5502 (let ((tt (js2-node-type node))
5503 num)
5504 (cond
5505 ((or (= tt js2-FALSE) (= tt js2-NULL))
5506 'ALWAYS_FALSE)
5507 ((= tt js2-TRUE)
5508 'ALWAYS_TRUE)
5509 ((= tt js2-NUMBER)
5510 (setq num (js2-number-node-num-value node))
5511 (if (and (not (eq num 0.0e+NaN))
5512 (not (zerop num)))
5513 'ALWAYS_TRUE
5514 'ALWAYS_FALSE))
5515 (t
5516 nil))))
5517
5518 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5519 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5520
5521 (defvar js2-tokens nil
5522 "List of all defined token names.") ; initialized in `js2-token-names'
5523
5524 (defconst js2-token-names
5525 (let* ((names (make-vector js2-num-tokens -1))
5526 (case-fold-search nil) ; only match js2-UPPER_CASE
5527 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5528 (cl-loop for sym in syms
5529 for i from 0
5530 do
5531 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5532 (not (boundp sym)))
5533 (aset names (symbol-value sym) ; code, e.g. 152
5534 (downcase
5535 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5536 (push sym js2-tokens)))
5537 names)
5538 "Vector mapping int values to token string names, sans `js2-' prefix.")
5539
5540 (defun js2-tt-name (tok)
5541 "Return a string name for TOK, a token symbol or code.
5542 Signals an error if it's not a recognized token."
5543 (let ((code tok))
5544 (if (symbolp tok)
5545 (setq code (symbol-value tok)))
5546 (if (eq code -1)
5547 "ERROR"
5548 (if (and (numberp code)
5549 (not (cl-minusp code))
5550 (< code js2-num-tokens))
5551 (aref js2-token-names code)
5552 (error "Invalid token: %s" code)))))
5553
5554 (defsubst js2-tt-sym (tok)
5555 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5556 (intern (js2-tt-name tok)))
5557
5558 (defconst js2-token-codes
5559 (let ((table (make-hash-table :test 'eq :size 256)))
5560 (cl-loop for name across js2-token-names
5561 for sym = (intern (concat "js2-" (upcase name)))
5562 do
5563 (puthash sym (symbol-value sym) table))
5564 ;; clean up a few that are "wrong" in Rhino's token codes
5565 (puthash 'js2-DELETE js2-DELPROP table)
5566 table)
5567 "Hashtable mapping token type symbols to their bytecodes.")
5568
5569 (defsubst js2-tt-code (sym)
5570 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5571 (or (gethash sym js2-token-codes)
5572 (error "Invalid token symbol: %s " sym))) ; signal code bug
5573
5574 (defun js2-report-scan-error (msg &optional no-throw beg len)
5575 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5576 (js2-report-error msg nil
5577 (or beg (js2-current-token-beg))
5578 (or len (js2-current-token-len)))
5579 (unless no-throw
5580 (throw 'return js2-ERROR)))
5581
5582 (defun js2-set-string-from-buffer (token)
5583 "Set `string' and `end' slots for TOKEN, return the string."
5584 (setf (js2-token-end token) js2-ts-cursor
5585 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5586
5587 ;; TODO: could potentially avoid a lot of consing by allocating a
5588 ;; char buffer the way Rhino does.
5589 (defsubst js2-add-to-string (c)
5590 (push c js2-ts-string-buffer))
5591
5592 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5593 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5594 ;; any other character: when it's not part of the current token, we
5595 ;; unget it, allowing it to be read again by the following call.
5596 (defsubst js2-unget-char ()
5597 (cl-decf js2-ts-cursor))
5598
5599 ;; Rhino distinguishes \r and \n line endings. We don't need to
5600 ;; because we only scan from Emacs buffers, which always use \n.
5601 (defun js2-get-char ()
5602 "Read and return the next character from the input buffer.
5603 Increments `js2-ts-lineno' if the return value is a newline char.
5604 Updates `js2-ts-cursor' to the point after the returned char.
5605 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5606 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5607 (let (c)
5608 ;; check for end of buffer
5609 (if (>= js2-ts-cursor (point-max))
5610 (setq js2-ts-hit-eof t
5611 js2-ts-cursor (1+ js2-ts-cursor)
5612 c js2-EOF_CHAR) ; return value
5613 ;; otherwise read next char
5614 (setq c (char-before (cl-incf js2-ts-cursor)))
5615 ;; if we read a newline, update counters
5616 (if (= c ?\n)
5617 (setq js2-ts-line-start js2-ts-cursor
5618 js2-ts-lineno (1+ js2-ts-lineno)))
5619 ;; TODO: skip over format characters
5620 c)))
5621
5622 (defun js2-read-unicode-escape ()
5623 "Read a \\uNNNN sequence from the input.
5624 Assumes the ?\ and ?u have already been read.
5625 Returns the unicode character, or nil if it wasn't a valid character.
5626 Doesn't change the values of any scanner variables."
5627 ;; I really wish I knew a better way to do this, but I can't
5628 ;; find the Emacs function that takes a 16-bit int and converts
5629 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5630 ;; Have to first check that it's 4 hex characters or it may stop
5631 ;; the read early.
5632 (ignore-errors
5633 (let ((s (buffer-substring-no-properties js2-ts-cursor
5634 (+ 4 js2-ts-cursor))))
5635 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5636 (read (concat "?\\u" s))))))
5637
5638 (defun js2-match-char (test)
5639 "Consume and return next character if it matches TEST, a character.
5640 Returns nil and consumes nothing if TEST is not the next character."
5641 (let ((c (js2-get-char)))
5642 (if (eq c test)
5643 t
5644 (js2-unget-char)
5645 nil)))
5646
5647 (defun js2-peek-char ()
5648 (prog1
5649 (js2-get-char)
5650 (js2-unget-char)))
5651
5652 (defun js2-identifier-start-p (c)
5653 "Is C a valid start to an ES5 Identifier?
5654 See http://es5.github.io/#x7.6"
5655 (or
5656 (memq c '(?$ ?_))
5657 (memq (get-char-code-property c 'general-category)
5658 ;; Letters
5659 '(Lu Ll Lt Lm Lo Nl))))
5660
5661 (defun js2-identifier-part-p (c)
5662 "Is C a valid part of an ES5 Identifier?
5663 See http://es5.github.io/#x7.6"
5664 (or
5665 (memq c '(?$ ?_ ?\u200c ?\u200d))
5666 (memq (get-char-code-property c 'general-category)
5667 '(;; Letters
5668 Lu Ll Lt Lm Lo Nl
5669 ;; Combining Marks
5670 Mn Mc
5671 ;; Digits
5672 Nd
5673 ;; Connector Punctuation
5674 Pc))))
5675
5676 (defun js2-alpha-p (c)
5677 (cond ((and (<= ?A c) (<= c ?Z)) t)
5678 ((and (<= ?a c) (<= c ?z)) t)
5679 (t nil)))
5680
5681 (defsubst js2-digit-p (c)
5682 (and (<= ?0 c) (<= c ?9)))
5683
5684 (defun js2-js-space-p (c)
5685 (if (<= c 127)
5686 (memq c '(#x20 #x9 #xB #xC #xD))
5687 (or
5688 (eq c #xA0)
5689 ;; TODO: change this nil to check for Unicode space character
5690 nil)))
5691
5692 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5693
5694 (defun js2-skip-line ()
5695 "Skip to end of line."
5696 (while (not (memq (js2-get-char) js2-eol-chars)))
5697 (js2-unget-char)
5698 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5699
5700 (defun js2-init-scanner (&optional buf line)
5701 "Create token stream for BUF starting on LINE.
5702 BUF defaults to `current-buffer' and LINE defaults to 1.
5703
5704 A buffer can only have one scanner active at a time, which yields
5705 dramatically simpler code than using a defstruct. If you need to
5706 have simultaneous scanners in a buffer, copy the regions to scan
5707 into temp buffers."
5708 (with-current-buffer (or buf (current-buffer))
5709 (setq js2-ts-dirty-line nil
5710 js2-ts-hit-eof nil
5711 js2-ts-line-start 0
5712 js2-ts-lineno (or line 1)
5713 js2-ts-line-end-char -1
5714 js2-ts-cursor (point-min)
5715 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5716 js2-ti-tokens-cursor 0
5717 js2-ti-lookahead 0
5718 js2-ts-is-xml-attribute nil
5719 js2-ts-xml-is-tag-content nil
5720 js2-ts-xml-open-tags-count 0
5721 js2-ts-string-buffer nil)))
5722
5723 ;; This function uses the cached op, string and number fields in
5724 ;; TokenStream; if getToken has been called since the passed token
5725 ;; was scanned, the op or string printed may be incorrect.
5726 (defun js2-token-to-string (token)
5727 ;; Not sure where this function is used in Rhino. Not tested.
5728 (if (not js2-debug-print-trees)
5729 ""
5730 (let ((name (js2-tt-name token)))
5731 (cond
5732 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5733 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5734 (concat name " `" (js2-current-token-string) "'"))
5735 ((eq token js2-NUMBER)
5736 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5737 (t
5738 name)))))
5739
5740 (defconst js2-keywords
5741 '(break
5742 case catch class const continue
5743 debugger default delete do
5744 else extends export
5745 false finally for function
5746 if in instanceof import
5747 let
5748 new null
5749 return
5750 super switch
5751 this throw true try typeof
5752 var void
5753 while with
5754 yield))
5755
5756 ;; Token names aren't exactly the same as the keywords, unfortunately.
5757 ;; E.g. delete is js2-DELPROP.
5758 (defconst js2-kwd-tokens
5759 (let ((table (make-vector js2-num-tokens nil))
5760 (tokens
5761 (list js2-BREAK
5762 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5763 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5764 js2-ELSE js2-EXPORT
5765 js2-ELSE js2-EXTENDS js2-EXPORT
5766 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5767 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5768 js2-LET
5769 js2-NEW js2-NULL
5770 js2-RETURN
5771 js2-SUPER js2-SWITCH
5772 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5773 js2-VAR
5774 js2-WHILE js2-WITH
5775 js2-YIELD)))
5776 (dolist (i tokens)
5777 (aset table i 'font-lock-keyword-face))
5778 (aset table js2-STRING 'font-lock-string-face)
5779 (aset table js2-REGEXP 'font-lock-string-face)
5780 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5781 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5782 (aset table js2-COMMENT 'font-lock-comment-face)
5783 (aset table js2-THIS 'font-lock-builtin-face)
5784 (aset table js2-SUPER 'font-lock-builtin-face)
5785 (aset table js2-VOID 'font-lock-constant-face)
5786 (aset table js2-NULL 'font-lock-constant-face)
5787 (aset table js2-TRUE 'font-lock-constant-face)
5788 (aset table js2-FALSE 'font-lock-constant-face)
5789 (aset table js2-NOT 'font-lock-negation-char-face)
5790 table)
5791 "Vector whose values are non-nil for tokens that are keywords.
5792 The values are default faces to use for highlighting the keywords.")
5793
5794 ;; FIXME: Support strict mode-only future reserved words, after we know
5795 ;; which parts scopes are in strict mode, and which are not.
5796 (defconst js2-reserved-words '(class enum export extends import static super)
5797 "Future reserved keywords in ECMAScript 5.1.")
5798
5799 (defconst js2-keyword-names
5800 (let ((table (make-hash-table :test 'equal)))
5801 (cl-loop for k in js2-keywords
5802 do (puthash
5803 (symbol-name k) ; instanceof
5804 (intern (concat "js2-"
5805 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5806 table))
5807 table)
5808 "JavaScript keywords by name, mapped to their symbols.")
5809
5810 (defconst js2-reserved-word-names
5811 (let ((table (make-hash-table :test 'equal)))
5812 (cl-loop for k in js2-reserved-words
5813 do
5814 (puthash (symbol-name k) 'js2-RESERVED table))
5815 table)
5816 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5817
5818 (defun js2-collect-string (buf)
5819 "Convert BUF, a list of chars, to a string.
5820 Reverses BUF before converting."
5821 (if buf
5822 (apply #'string (nreverse buf))
5823 ""))
5824
5825 (defun js2-string-to-keyword (s)
5826 "Return token for S, a string, if S is a keyword or reserved word.
5827 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5828 (or (gethash s js2-keyword-names)
5829 (gethash s js2-reserved-word-names)))
5830
5831 (defsubst js2-ts-set-char-token-bounds (token)
5832 "Used when next token is one character."
5833 (setf (js2-token-beg token) (1- js2-ts-cursor)
5834 (js2-token-end token) js2-ts-cursor))
5835
5836 (defsubst js2-ts-return (token type)
5837 "Update the `end' and `type' slots of TOKEN,
5838 then throw `return' with value TYPE."
5839 (setf (js2-token-end token) js2-ts-cursor
5840 (js2-token-type token) type)
5841 (throw 'return type))
5842
5843 (defun js2-x-digit-to-int (c accumulator)
5844 "Build up a hex number.
5845 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5846 corresponding number. Otherwise return -1."
5847 (catch 'return
5848 (catch 'check
5849 ;; Use 0..9 < A..Z < a..z
5850 (cond
5851 ((<= c ?9)
5852 (cl-decf c ?0)
5853 (if (<= 0 c)
5854 (throw 'check nil)))
5855 ((<= c ?F)
5856 (when (<= ?A c)
5857 (cl-decf c (- ?A 10))
5858 (throw 'check nil)))
5859 ((<= c ?f)
5860 (when (<= ?a c)
5861 (cl-decf c (- ?a 10))
5862 (throw 'check nil))))
5863 (throw 'return -1))
5864 (logior c (lsh accumulator 4))))
5865
5866 (defun js2-get-token (&optional modifier)
5867 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5868 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5869 next saved token.
5870
5871 This function will not return a newline (js2-EOL) - instead, it
5872 gobbles newlines until it finds a non-newline token. Call
5873 `js2-peek-token-or-eol' when you care about newlines.
5874
5875 This function will also not return a js2-COMMENT. Instead, it
5876 records comments found in `js2-scanned-comments'. If the token
5877 returned by this function immediately follows a jsdoc comment,
5878 the token is flagged as such."
5879 (if (zerop js2-ti-lookahead)
5880 (js2-get-token-internal modifier)
5881 (cl-decf js2-ti-lookahead)
5882 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5883 (let ((tt (js2-current-token-type)))
5884 (cl-assert (not (= tt js2-EOL)))
5885 tt)))
5886
5887 (defun js2-unget-token ()
5888 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5889 (cl-incf js2-ti-lookahead)
5890 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5891
5892 (defun js2-get-token-internal (modifier)
5893 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5894 (tt (js2-token-type token))
5895 saw-eol
5896 face)
5897 ;; process comments
5898 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5899 (if (= tt js2-EOL)
5900 (setq saw-eol t)
5901 (setq saw-eol nil)
5902 (when js2-record-comments
5903 (js2-record-comment token)))
5904 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5905 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5906 tt (js2-token-type token)))
5907
5908 (when saw-eol
5909 (setf (js2-token-follows-eol-p token) t))
5910
5911 ;; perform lexical fontification as soon as token is scanned
5912 (when js2-parse-ide-mode
5913 (cond
5914 ((cl-minusp tt)
5915 (js2-record-face 'js2-error token))
5916 ((setq face (aref js2-kwd-tokens tt))
5917 (js2-record-face face token))
5918 ((and (= tt js2-NAME)
5919 (equal (js2-token-string token) "undefined"))
5920 (js2-record-face 'font-lock-constant-face token))))
5921 tt))
5922
5923 (defsubst js2-string-to-number (str base)
5924 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5925 (condition-case nil
5926 (string-to-number str base)
5927 (overflow-error -1)))
5928
5929 (defun js2-get-token-internal-1 (modifier)
5930 "Return next JavaScript token type, an int such as js2-RETURN.
5931 During operation, creates an instance of `js2-token' struct, sets
5932 its relevant fields and puts it into `js2-ti-tokens'."
5933 (let (identifier-start
5934 is-unicode-escape-start c
5935 contains-escape escape-val str result base
5936 look-for-slash continue tt
5937 (token (js2-new-token 0)))
5938 (setq
5939 tt
5940 (catch 'return
5941 (when (eq modifier 'TEMPLATE_TAIL)
5942 (setf (js2-token-beg token) (1- js2-ts-cursor))
5943 (throw 'return (js2-get-string-or-template-token ?` token)))
5944 (while t
5945 ;; Eat whitespace, possibly sensitive to newlines.
5946 (setq continue t)
5947 (while continue
5948 (setq c (js2-get-char))
5949 (cond
5950 ((eq c js2-EOF_CHAR)
5951 (js2-unget-char)
5952 (js2-ts-set-char-token-bounds token)
5953 (throw 'return js2-EOF))
5954 ((eq c ?\n)
5955 (js2-ts-set-char-token-bounds token)
5956 (setq js2-ts-dirty-line nil)
5957 (throw 'return js2-EOL))
5958 ((not (js2-js-space-p c))
5959 (if (/= c ?-) ; in case end of HTML comment
5960 (setq js2-ts-dirty-line t))
5961 (setq continue nil))))
5962 ;; Assume the token will be 1 char - fixed up below.
5963 (js2-ts-set-char-token-bounds token)
5964 (when (eq c ?@)
5965 (throw 'return js2-XMLATTR))
5966 ;; identifier/keyword/instanceof?
5967 ;; watch out for starting with a <backslash>
5968 (cond
5969 ((eq c ?\\)
5970 (setq c (js2-get-char))
5971 (if (eq c ?u)
5972 (setq identifier-start t
5973 is-unicode-escape-start t
5974 js2-ts-string-buffer nil)
5975 (setq identifier-start nil)
5976 (js2-unget-char)
5977 (setq c ?\\)))
5978 (t
5979 (when (setq identifier-start (js2-identifier-start-p c))
5980 (setq js2-ts-string-buffer nil)
5981 (js2-add-to-string c))))
5982 (when identifier-start
5983 (setq contains-escape is-unicode-escape-start)
5984 (catch 'break
5985 (while t
5986 (if is-unicode-escape-start
5987 ;; strictly speaking we should probably push-back
5988 ;; all the bad characters if the <backslash>uXXXX
5989 ;; sequence is malformed. But since there isn't a
5990 ;; correct context(is there?) for a bad Unicode
5991 ;; escape sequence in an identifier, we can report
5992 ;; an error here.
5993 (progn
5994 (setq escape-val 0)
5995 (dotimes (_ 4)
5996 (setq c (js2-get-char)
5997 escape-val (js2-x-digit-to-int c escape-val))
5998 ;; Next check takes care of c < 0 and bad escape
5999 (if (cl-minusp escape-val)
6000 (throw 'break nil)))
6001 (if (cl-minusp escape-val)
6002 (js2-report-scan-error "msg.invalid.escape" t))
6003 (js2-add-to-string escape-val)
6004 (setq is-unicode-escape-start nil))
6005 (setq c (js2-get-char))
6006 (cond
6007 ((eq c ?\\)
6008 (setq c (js2-get-char))
6009 (if (eq c ?u)
6010 (setq is-unicode-escape-start t
6011 contains-escape t)
6012 (js2-report-scan-error "msg.illegal.character" t)))
6013 (t
6014 (if (or (eq c js2-EOF_CHAR)
6015 (not (js2-identifier-part-p c)))
6016 (throw 'break nil))
6017 (js2-add-to-string c))))))
6018 (js2-unget-char)
6019 (setf str (js2-collect-string js2-ts-string-buffer)
6020 (js2-token-end token) js2-ts-cursor)
6021 ;; FIXME: Invalid in ES5 and ES6, see
6022 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
6023 ;; Probably should just drop this conditional.
6024 (unless contains-escape
6025 ;; OPT we shouldn't have to make a string (object!) to
6026 ;; check if it's a keyword.
6027 ;; Return the corresponding token if it's a keyword
6028 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
6029 (setq result (js2-string-to-keyword str)))
6030 (if (and (< js2-language-version 170)
6031 (memq result '(js2-LET js2-YIELD)))
6032 ;; LET and YIELD are tokens only in 1.7 and later
6033 (setq result 'js2-NAME))
6034 (when (eq result 'js2-RESERVED)
6035 (setf (js2-token-string token) str))
6036 (throw 'return (js2-tt-code result))))
6037 ;; If we want to intern these as Rhino does, just use (intern str)
6038 (setf (js2-token-string token) str)
6039 (throw 'return js2-NAME)) ; end identifier/kwd check
6040 ;; is it a number?
6041 (when (or (js2-digit-p c)
6042 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6043 (setq js2-ts-string-buffer nil
6044 base 10)
6045 (when (eq c ?0)
6046 (setq c (js2-get-char))
6047 (cond
6048 ((or (eq c ?x) (eq c ?X))
6049 (setq base 16)
6050 (setq c (js2-get-char)))
6051 ((and (or (eq c ?b) (eq c ?B))
6052 (>= js2-language-version 200))
6053 (setq base 2)
6054 (setq c (js2-get-char)))
6055 ((and (or (eq c ?o) (eq c ?O))
6056 (>= js2-language-version 200))
6057 (setq base 8)
6058 (setq c (js2-get-char)))
6059 ((js2-digit-p c)
6060 (setq base 'maybe-8))
6061 (t
6062 (js2-add-to-string ?0))))
6063 (cond
6064 ((eq base 16)
6065 (if (> 0 (js2-x-digit-to-int c 0))
6066 (js2-report-scan-error "msg.missing.hex.digits")
6067 (while (<= 0 (js2-x-digit-to-int c 0))
6068 (js2-add-to-string c)
6069 (setq c (js2-get-char)))))
6070 ((eq base 2)
6071 (if (not (memq c '(?0 ?1)))
6072 (js2-report-scan-error "msg.missing.binary.digits")
6073 (while (memq c '(?0 ?1))
6074 (js2-add-to-string c)
6075 (setq c (js2-get-char)))))
6076 ((eq base 8)
6077 (if (or (> ?0 c) (< ?7 c))
6078 (js2-report-scan-error "msg.missing.octal.digits")
6079 (while (and (<= ?0 c) (>= ?7 c))
6080 (js2-add-to-string c)
6081 (setq c (js2-get-char)))))
6082 (t
6083 (while (and (<= ?0 c) (<= c ?9))
6084 ;; We permit 08 and 09 as decimal numbers, which
6085 ;; makes our behavior a superset of the ECMA
6086 ;; numeric grammar. We might not always be so
6087 ;; permissive, so we warn about it.
6088 (when (and (eq base 'maybe-8) (>= c ?8))
6089 (js2-report-warning "msg.bad.octal.literal"
6090 (if (eq c ?8) "8" "9"))
6091 (setq base 10))
6092 (js2-add-to-string c)
6093 (setq c (js2-get-char)))
6094 (when (eq base 'maybe-8)
6095 (setq base 8))))
6096 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6097 (when (eq c ?.)
6098 (cl-loop do
6099 (js2-add-to-string c)
6100 (setq c (js2-get-char))
6101 while (js2-digit-p c)))
6102 (when (memq c '(?e ?E))
6103 (js2-add-to-string c)
6104 (setq c (js2-get-char))
6105 (when (memq c '(?+ ?-))
6106 (js2-add-to-string c)
6107 (setq c (js2-get-char)))
6108 (unless (js2-digit-p c)
6109 (js2-report-scan-error "msg.missing.exponent" t))
6110 (cl-loop do
6111 (js2-add-to-string c)
6112 (setq c (js2-get-char))
6113 while (js2-digit-p c))))
6114 (js2-unget-char)
6115 (let ((str (js2-set-string-from-buffer token)))
6116 (setf (js2-token-number token) (js2-string-to-number str base)
6117 (js2-token-number-base token) base))
6118 (throw 'return js2-NUMBER))
6119 ;; is it a string?
6120 (when (or (memq c '(?\" ?\'))
6121 (and (>= js2-language-version 200)
6122 (= c ?`)))
6123 (throw 'return
6124 (js2-get-string-or-template-token c token)))
6125 (js2-ts-return token
6126 (cl-case c
6127 (?\;
6128 (throw 'return js2-SEMI))
6129 (?\[
6130 (throw 'return js2-LB))
6131 (?\]
6132 (throw 'return js2-RB))
6133 (?{
6134 (throw 'return js2-LC))
6135 (?}
6136 (throw 'return js2-RC))
6137 (?\(
6138 (throw 'return js2-LP))
6139 (?\)
6140 (throw 'return js2-RP))
6141 (?,
6142 (throw 'return js2-COMMA))
6143 (??
6144 (throw 'return js2-HOOK))
6145 (?:
6146 (if (js2-match-char ?:)
6147 js2-COLONCOLON
6148 (throw 'return js2-COLON)))
6149 (?.
6150 (if (js2-match-char ?.)
6151 (if (js2-match-char ?.)
6152 js2-TRIPLEDOT js2-DOTDOT)
6153 (if (js2-match-char ?\()
6154 js2-DOTQUERY
6155 (throw 'return js2-DOT))))
6156 (?|
6157 (if (js2-match-char ?|)
6158 (throw 'return js2-OR)
6159 (if (js2-match-char ?=)
6160 js2-ASSIGN_BITOR
6161 (throw 'return js2-BITOR))))
6162 (?^
6163 (if (js2-match-char ?=)
6164 js2-ASSIGN_BITOR
6165 (throw 'return js2-BITXOR)))
6166 (?&
6167 (if (js2-match-char ?&)
6168 (throw 'return js2-AND)
6169 (if (js2-match-char ?=)
6170 js2-ASSIGN_BITAND
6171 (throw 'return js2-BITAND))))
6172 (?=
6173 (if (js2-match-char ?=)
6174 (if (js2-match-char ?=)
6175 js2-SHEQ
6176 (throw 'return js2-EQ))
6177 (if (js2-match-char ?>)
6178 (js2-ts-return token js2-ARROW)
6179 (throw 'return js2-ASSIGN))))
6180 (?!
6181 (if (js2-match-char ?=)
6182 (if (js2-match-char ?=)
6183 js2-SHNE
6184 js2-NE)
6185 (throw 'return js2-NOT)))
6186 (?<
6187 ;; NB:treat HTML begin-comment as comment-till-eol
6188 (when (js2-match-char ?!)
6189 (when (js2-match-char ?-)
6190 (when (js2-match-char ?-)
6191 (js2-skip-line)
6192 (setf (js2-token-comment-type (js2-current-token)) 'html)
6193 (throw 'return js2-COMMENT)))
6194 (js2-unget-char))
6195 (if (js2-match-char ?<)
6196 (if (js2-match-char ?=)
6197 js2-ASSIGN_LSH
6198 js2-LSH)
6199 (if (js2-match-char ?=)
6200 js2-LE
6201 (throw 'return js2-LT))))
6202 (?>
6203 (if (js2-match-char ?>)
6204 (if (js2-match-char ?>)
6205 (if (js2-match-char ?=)
6206 js2-ASSIGN_URSH
6207 js2-URSH)
6208 (if (js2-match-char ?=)
6209 js2-ASSIGN_RSH
6210 js2-RSH))
6211 (if (js2-match-char ?=)
6212 js2-GE
6213 (throw 'return js2-GT))))
6214 (?*
6215 (if (js2-match-char ?=)
6216 js2-ASSIGN_MUL
6217 (throw 'return js2-MUL)))
6218 (?/
6219 ;; is it a // comment?
6220 (when (js2-match-char ?/)
6221 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6222 (js2-skip-line)
6223 (setf (js2-token-comment-type token) 'line)
6224 ;; include newline so highlighting goes to end of
6225 ;; window, if there actually is a newline; if we
6226 ;; hit eof, then implicitly there isn't
6227 (unless js2-ts-hit-eof
6228 (cl-incf (js2-token-end token)))
6229 (throw 'return js2-COMMENT))
6230 ;; is it a /* comment?
6231 (when (js2-match-char ?*)
6232 (setf look-for-slash nil
6233 (js2-token-beg token) (- js2-ts-cursor 2)
6234 (js2-token-comment-type token)
6235 (if (js2-match-char ?*)
6236 (progn
6237 (setq look-for-slash t)
6238 'jsdoc)
6239 'block))
6240 (while t
6241 (setq c (js2-get-char))
6242 (cond
6243 ((eq c js2-EOF_CHAR)
6244 (setf (js2-token-end token) (1- js2-ts-cursor))
6245 (js2-report-error "msg.unterminated.comment")
6246 (throw 'return js2-COMMENT))
6247 ((eq c ?*)
6248 (setq look-for-slash t))
6249 ((eq c ?/)
6250 (if look-for-slash
6251 (js2-ts-return token js2-COMMENT)))
6252 (t
6253 (setf look-for-slash nil
6254 (js2-token-end token) js2-ts-cursor)))))
6255 (if (js2-match-char ?=)
6256 js2-ASSIGN_DIV
6257 (throw 'return js2-DIV)))
6258 (?#
6259 (when js2-skip-preprocessor-directives
6260 (js2-skip-line)
6261 (setf (js2-token-comment-type token) 'preprocessor
6262 (js2-token-end token) js2-ts-cursor)
6263 (throw 'return js2-COMMENT))
6264 (throw 'return js2-ERROR))
6265 (?%
6266 (if (js2-match-char ?=)
6267 js2-ASSIGN_MOD
6268 (throw 'return js2-MOD)))
6269 (?~
6270 (throw 'return js2-BITNOT))
6271 (?+
6272 (if (js2-match-char ?=)
6273 js2-ASSIGN_ADD
6274 (if (js2-match-char ?+)
6275 js2-INC
6276 (throw 'return js2-ADD))))
6277 (?-
6278 (cond
6279 ((js2-match-char ?=)
6280 (setq c js2-ASSIGN_SUB))
6281 ((js2-match-char ?-)
6282 (unless js2-ts-dirty-line
6283 ;; treat HTML end-comment after possible whitespace
6284 ;; after line start as comment-until-eol
6285 (when (js2-match-char ?>)
6286 (js2-skip-line)
6287 (setf (js2-token-comment-type (js2-current-token)) 'html)
6288 (throw 'return js2-COMMENT)))
6289 (setq c js2-DEC))
6290 (t
6291 (setq c js2-SUB)))
6292 (setq js2-ts-dirty-line t)
6293 c)
6294 (otherwise
6295 (js2-report-scan-error "msg.illegal.character")))))))
6296 (setf (js2-token-type token) tt)
6297 token))
6298
6299 (defun js2-get-string-or-template-token (quote-char token)
6300 ;; We attempt to accumulate a string the fast way, by
6301 ;; building it directly out of the reader. But if there
6302 ;; are any escaped characters in the string, we revert to
6303 ;; building it out of a string buffer.
6304 (let ((c (js2-get-char))
6305 js2-ts-string-buffer
6306 nc c1 val escape-val)
6307 (catch 'break
6308 (while (/= c quote-char)
6309 (catch 'continue
6310 (when (eq c js2-EOF_CHAR)
6311 (js2-unget-char)
6312 (js2-report-error "msg.unterminated.string.lit")
6313 (throw 'break nil))
6314 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6315 (js2-unget-char)
6316 (js2-report-error "msg.unterminated.string.lit")
6317 (throw 'break nil))
6318 (when (eq c ?\\)
6319 ;; We've hit an escaped character
6320 (setq c (js2-get-char))
6321 (cl-case c
6322 (?b (setq c ?\b))
6323 (?f (setq c ?\f))
6324 (?n (setq c ?\n))
6325 (?r (setq c ?\r))
6326 (?t (setq c ?\t))
6327 (?v (setq c ?\v))
6328 (?u
6329 (setq c1 (js2-read-unicode-escape))
6330 (if js2-parse-ide-mode
6331 (if c1
6332 (progn
6333 ;; just copy the string in IDE-mode
6334 (js2-add-to-string ?\\)
6335 (js2-add-to-string ?u)
6336 (dotimes (_ 3)
6337 (js2-add-to-string (js2-get-char)))
6338 (setq c (js2-get-char))) ; added at end of loop
6339 ;; flag it as an invalid escape
6340 (js2-report-warning "msg.invalid.escape"
6341 nil (- js2-ts-cursor 2) 6))
6342 ;; Get 4 hex digits; if the u escape is not
6343 ;; followed by 4 hex digits, use 'u' + the
6344 ;; literal character sequence that follows.
6345 (js2-add-to-string ?u)
6346 (setq escape-val 0)
6347 (dotimes (_ 4)
6348 (setq c (js2-get-char)
6349 escape-val (js2-x-digit-to-int c escape-val))
6350 (if (cl-minusp escape-val)
6351 (throw 'continue nil))
6352 (js2-add-to-string c))
6353 ;; prepare for replace of stored 'u' sequence by escape value
6354 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6355 c escape-val)))
6356 (?x
6357 ;; Get 2 hex digits, defaulting to 'x'+literal
6358 ;; sequence, as above.
6359 (setq c (js2-get-char)
6360 escape-val (js2-x-digit-to-int c 0))
6361 (if (cl-minusp escape-val)
6362 (progn
6363 (js2-add-to-string ?x)
6364 (throw 'continue nil))
6365 (setq c1 c
6366 c (js2-get-char)
6367 escape-val (js2-x-digit-to-int c escape-val))
6368 (if (cl-minusp escape-val)
6369 (progn
6370 (js2-add-to-string ?x)
6371 (js2-add-to-string c1)
6372 (throw 'continue nil))
6373 ;; got 2 hex digits
6374 (setq c escape-val))))
6375 (?\n
6376 ;; Remove line terminator after escape to follow
6377 ;; SpiderMonkey and C/C++
6378 (setq c (js2-get-char))
6379 (throw 'continue nil))
6380 (t
6381 (when (and (<= ?0 c) (< c ?8))
6382 (setq val (- c ?0)
6383 c (js2-get-char))
6384 (when (and (<= ?0 c) (< c ?8))
6385 (setq val (- (+ (* 8 val) c) ?0)
6386 c (js2-get-char))
6387 (when (and (<= ?0 c)
6388 (< c ?8)
6389 (< val #o37))
6390 ;; c is 3rd char of octal sequence only
6391 ;; if the resulting val <= 0377
6392 (setq val (- (+ (* 8 val) c) ?0)
6393 c (js2-get-char))))
6394 (js2-unget-char)
6395 (setq c val)))))
6396 (when (and (eq quote-char ?`) (eq c ?$))
6397 (when (eq (setq nc (js2-get-char)) ?\{)
6398 (throw 'break nil))
6399 (js2-unget-char))
6400 (js2-add-to-string c)
6401 (setq c (js2-get-char)))))
6402 (js2-set-string-from-buffer token)
6403 (if (not (eq quote-char ?`))
6404 js2-STRING
6405 (if (and (eq c ?$) (eq nc ?\{))
6406 js2-TEMPLATE_HEAD
6407 js2-NO_SUBS_TEMPLATE))))
6408
6409 (defun js2-read-regexp (start-tt)
6410 "Called by parser when it gets / or /= in literal context."
6411 (let (c err
6412 in-class ; inside a '[' .. ']' character-class
6413 flags
6414 (continue t)
6415 (token (js2-new-token 0)))
6416 (setq js2-ts-string-buffer nil)
6417 (if (eq start-tt js2-ASSIGN_DIV)
6418 ;; mis-scanned /=
6419 (js2-add-to-string ?=)
6420 (if (not (eq start-tt js2-DIV))
6421 (error "failed assertion")))
6422 (while (and (not err)
6423 (or (/= (setq c (js2-get-char)) ?/)
6424 in-class))
6425 (cond
6426 ((or (= c ?\n)
6427 (= c js2-EOF_CHAR))
6428 (setf (js2-token-end token) (1- js2-ts-cursor)
6429 err t
6430 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6431 (js2-report-error "msg.unterminated.re.lit"))
6432 (t (cond
6433 ((= c ?\\)
6434 (js2-add-to-string c)
6435 (setq c (js2-get-char)))
6436 ((= c ?\[)
6437 (setq in-class t))
6438 ((= c ?\])
6439 (setq in-class nil)))
6440 (js2-add-to-string c))))
6441 (unless err
6442 (while continue
6443 (cond
6444 ((js2-match-char ?g)
6445 (push ?g flags))
6446 ((js2-match-char ?i)
6447 (push ?i flags))
6448 ((js2-match-char ?m)
6449 (push ?m flags))
6450 ((and (js2-match-char ?u)
6451 (>= js2-language-version 200))
6452 (push ?u flags))
6453 ((and (js2-match-char ?y)
6454 (>= js2-language-version 200))
6455 (push ?y flags))
6456 (t
6457 (setq continue nil))))
6458 (if (js2-alpha-p (js2-peek-char))
6459 (js2-report-scan-error "msg.invalid.re.flag" t
6460 js2-ts-cursor 1))
6461 (js2-set-string-from-buffer token))
6462 (js2-collect-string flags)))
6463
6464 (defun js2-get-first-xml-token ()
6465 (setq js2-ts-xml-open-tags-count 0
6466 js2-ts-is-xml-attribute nil
6467 js2-ts-xml-is-tag-content nil)
6468 (js2-unget-char)
6469 (js2-get-next-xml-token))
6470
6471 (defun js2-xml-discard-string (token)
6472 "Throw away the string in progress and flag an XML parse error."
6473 (setf js2-ts-string-buffer nil
6474 (js2-token-string token) nil)
6475 (js2-report-scan-error "msg.XML.bad.form" t))
6476
6477 (defun js2-get-next-xml-token ()
6478 (setq js2-ts-string-buffer nil) ; for recording the XML
6479 (let ((token (js2-new-token 0))
6480 c result)
6481 (setq result
6482 (catch 'return
6483 (while t
6484 (setq c (js2-get-char))
6485 (cond
6486 ((= c js2-EOF_CHAR)
6487 (throw 'return js2-ERROR))
6488 (js2-ts-xml-is-tag-content
6489 (cl-case c
6490 (?>
6491 (js2-add-to-string c)
6492 (setq js2-ts-xml-is-tag-content nil
6493 js2-ts-is-xml-attribute nil))
6494 (?/
6495 (js2-add-to-string c)
6496 (when (eq ?> (js2-peek-char))
6497 (setq c (js2-get-char))
6498 (js2-add-to-string c)
6499 (setq js2-ts-xml-is-tag-content nil)
6500 (cl-decf js2-ts-xml-open-tags-count)))
6501 (?{
6502 (js2-unget-char)
6503 (js2-set-string-from-buffer token)
6504 (throw 'return js2-XML))
6505 ((?\' ?\")
6506 (js2-add-to-string c)
6507 (unless (js2-read-quoted-string c token)
6508 (throw 'return js2-ERROR)))
6509 (?=
6510 (js2-add-to-string c)
6511 (setq js2-ts-is-xml-attribute t))
6512 ((? ?\t ?\r ?\n)
6513 (js2-add-to-string c))
6514 (t
6515 (js2-add-to-string c)
6516 (setq js2-ts-is-xml-attribute nil)))
6517 (when (and (not js2-ts-xml-is-tag-content)
6518 (zerop js2-ts-xml-open-tags-count))
6519 (js2-set-string-from-buffer token)
6520 (throw 'return js2-XMLEND)))
6521 (t
6522 ;; else not tag content
6523 (cl-case c
6524 (?<
6525 (js2-add-to-string c)
6526 (setq c (js2-peek-char))
6527 (cl-case c
6528 (?!
6529 (setq c (js2-get-char)) ;; skip !
6530 (js2-add-to-string c)
6531 (setq c (js2-peek-char))
6532 (cl-case c
6533 (?-
6534 (setq c (js2-get-char)) ;; skip -
6535 (js2-add-to-string c)
6536 (if (eq c ?-)
6537 (progn
6538 (js2-add-to-string c)
6539 (unless (js2-read-xml-comment token)
6540 (throw 'return js2-ERROR)))
6541 (js2-xml-discard-string token)
6542 (throw 'return js2-ERROR)))
6543 (?\[
6544 (setq c (js2-get-char)) ;; skip [
6545 (js2-add-to-string c)
6546 (if (and (= (js2-get-char) ?C)
6547 (= (js2-get-char) ?D)
6548 (= (js2-get-char) ?A)
6549 (= (js2-get-char) ?T)
6550 (= (js2-get-char) ?A)
6551 (= (js2-get-char) ?\[))
6552 (progn
6553 (js2-add-to-string ?C)
6554 (js2-add-to-string ?D)
6555 (js2-add-to-string ?A)
6556 (js2-add-to-string ?T)
6557 (js2-add-to-string ?A)
6558 (js2-add-to-string ?\[)
6559 (unless (js2-read-cdata token)
6560 (throw 'return js2-ERROR)))
6561 (js2-xml-discard-string token)
6562 (throw 'return js2-ERROR)))
6563 (t
6564 (unless (js2-read-entity token)
6565 (throw 'return js2-ERROR))))
6566 ;; Allow bare CDATA section, e.g.:
6567 ;; let xml = <![CDATA[ foo bar baz ]]>;
6568 (when (zerop js2-ts-xml-open-tags-count)
6569 (throw 'return js2-XMLEND)))
6570 (??
6571 (setq c (js2-get-char)) ;; skip ?
6572 (js2-add-to-string c)
6573 (unless (js2-read-PI token)
6574 (throw 'return js2-ERROR)))
6575 (?/
6576 ;; end tag
6577 (setq c (js2-get-char)) ;; skip /
6578 (js2-add-to-string c)
6579 (when (zerop js2-ts-xml-open-tags-count)
6580 (js2-xml-discard-string token)
6581 (throw 'return js2-ERROR))
6582 (setq js2-ts-xml-is-tag-content t)
6583 (cl-decf js2-ts-xml-open-tags-count))
6584 (t
6585 ;; start tag
6586 (setq js2-ts-xml-is-tag-content t)
6587 (cl-incf js2-ts-xml-open-tags-count))))
6588 (?{
6589 (js2-unget-char)
6590 (js2-set-string-from-buffer token)
6591 (throw 'return js2-XML))
6592 (t
6593 (js2-add-to-string c))))))))
6594 (setf (js2-token-end token) js2-ts-cursor)
6595 (setf (js2-token-type token) result)
6596 result))
6597
6598 (defun js2-read-quoted-string (quote token)
6599 (let (c)
6600 (catch 'return
6601 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6602 (js2-add-to-string c)
6603 (if (eq c quote)
6604 (throw 'return t)))
6605 (js2-xml-discard-string token) ;; throw away string in progress
6606 nil)))
6607
6608 (defun js2-read-xml-comment (token)
6609 (let ((c (js2-get-char)))
6610 (catch 'return
6611 (while (/= c js2-EOF_CHAR)
6612 (catch 'continue
6613 (js2-add-to-string c)
6614 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6615 (setq c (js2-get-char))
6616 (js2-add-to-string c)
6617 (if (eq (js2-peek-char) ?>)
6618 (progn
6619 (setq c (js2-get-char)) ;; skip >
6620 (js2-add-to-string c)
6621 (throw 'return t))
6622 (throw 'continue nil)))
6623 (setq c (js2-get-char))))
6624 (js2-xml-discard-string token)
6625 nil)))
6626
6627 (defun js2-read-cdata (token)
6628 (let ((c (js2-get-char)))
6629 (catch 'return
6630 (while (/= c js2-EOF_CHAR)
6631 (catch 'continue
6632 (js2-add-to-string c)
6633 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6634 (setq c (js2-get-char))
6635 (js2-add-to-string c)
6636 (if (eq (js2-peek-char) ?>)
6637 (progn
6638 (setq c (js2-get-char)) ;; Skip >
6639 (js2-add-to-string c)
6640 (throw 'return t))
6641 (throw 'continue nil)))
6642 (setq c (js2-get-char))))
6643 (js2-xml-discard-string token)
6644 nil)))
6645
6646 (defun js2-read-entity (token)
6647 (let ((decl-tags 1)
6648 c)
6649 (catch 'return
6650 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6651 (js2-add-to-string c)
6652 (cl-case c
6653 (?<
6654 (cl-incf decl-tags))
6655 (?>
6656 (cl-decf decl-tags)
6657 (if (zerop decl-tags)
6658 (throw 'return t)))))
6659 (js2-xml-discard-string token)
6660 nil)))
6661
6662 (defun js2-read-PI (token)
6663 "Scan an XML processing instruction."
6664 (let (c)
6665 (catch 'return
6666 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6667 (js2-add-to-string c)
6668 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6669 (setq c (js2-get-char)) ;; Skip >
6670 (js2-add-to-string c)
6671 (throw 'return t)))
6672 (js2-xml-discard-string token)
6673 nil)))
6674
6675 ;;; Highlighting
6676
6677 (defun js2-set-face (beg end face &optional record)
6678 "Fontify a region. If RECORD is non-nil, record for later."
6679 (when (cl-plusp js2-highlight-level)
6680 (setq beg (min (point-max) beg)
6681 beg (max (point-min) beg)
6682 end (min (point-max) end)
6683 end (max (point-min) end))
6684 (if record
6685 (push (list beg end face) js2-mode-fontifications)
6686 (put-text-property beg end 'font-lock-face face))))
6687
6688 (defsubst js2-clear-face (beg end)
6689 (remove-text-properties beg end '(font-lock-face nil
6690 help-echo nil
6691 point-entered nil
6692 cursor-sensor-functions nil
6693 c-in-sws nil)))
6694
6695 (defconst js2-ecma-global-props
6696 (concat "^"
6697 (regexp-opt
6698 '("Infinity" "NaN" "undefined" "arguments") t)
6699 "$")
6700 "Value properties of the Ecma-262 Global Object.
6701 Shown at or above `js2-highlight-level' 2.")
6702
6703 ;; might want to add the name "arguments" to this list?
6704 (defconst js2-ecma-object-props
6705 (concat "^"
6706 (regexp-opt
6707 '("prototype" "__proto__" "__parent__") t)
6708 "$")
6709 "Value properties of the Ecma-262 Object constructor.
6710 Shown at or above `js2-highlight-level' 2.")
6711
6712 (defconst js2-ecma-global-funcs
6713 (concat
6714 "^"
6715 (regexp-opt
6716 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6717 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6718 "$")
6719 "Function properties of the Ecma-262 Global object.
6720 Shown at or above `js2-highlight-level' 2.")
6721
6722 (defconst js2-ecma-number-props
6723 (concat "^"
6724 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6725 "NEGATIVE_INFINITY"
6726 "POSITIVE_INFINITY") t)
6727 "$")
6728 "Properties of the Ecma-262 Number constructor.
6729 Shown at or above `js2-highlight-level' 2.")
6730
6731 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6732 "Properties of the Ecma-262 Date constructor.
6733 Shown at or above `js2-highlight-level' 2.")
6734
6735 (defconst js2-ecma-math-props
6736 (concat "^"
6737 (regexp-opt
6738 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6739 t)
6740 "$")
6741 "Properties of the Ecma-262 Math object.
6742 Shown at or above `js2-highlight-level' 2.")
6743
6744 (defconst js2-ecma-math-funcs
6745 (concat "^"
6746 (regexp-opt
6747 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6748 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6749 "$")
6750 "Function properties of the Ecma-262 Math object.
6751 Shown at or above `js2-highlight-level' 2.")
6752
6753 (defconst js2-ecma-function-props
6754 (concat
6755 "^"
6756 (regexp-opt
6757 '(;; properties of the Object prototype object
6758 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6759 "toLocaleString" "toString" "valueOf"
6760 ;; properties of the Function prototype object
6761 "apply" "call"
6762 ;; properties of the Array prototype object
6763 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6764 "splice" "unshift"
6765 ;; properties of the String prototype object
6766 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6767 "localeCompare" "match" "replace" "search" "split" "substring"
6768 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6769 "toUpperCase"
6770 ;; properties of the Number prototype object
6771 "toExponential" "toFixed" "toPrecision"
6772 ;; properties of the Date prototype object
6773 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6774 "getMinutes" "getMonth" "getSeconds" "getTime"
6775 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6776 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6777 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6778 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6779 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6780 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6781 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6782 "toTimeString" "toUTCString"
6783 ;; properties of the RegExp prototype object
6784 "exec" "test"
6785 ;; properties of the JSON prototype object
6786 "parse" "stringify"
6787 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6788 "toSource" "__defineGetter__" "__defineSetter__"
6789 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6790 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6791 t)
6792 "$")
6793 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6794 Shown at or above `js2-highlight-level' 3.")
6795
6796 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6797 (let ((target-name (and target
6798 (js2-name-node-p target)
6799 (js2-name-node-name target)))
6800 (prop-name (if prop (js2-name-node-name prop)))
6801 (level2 (>= js2-highlight-level 2))
6802 (level3 (>= js2-highlight-level 3)))
6803 (when level2
6804 (let ((face
6805 (if call-p
6806 (cond
6807 ((and target prop)
6808 (cond
6809 ((and level3 (string-match js2-ecma-function-props prop-name))
6810 'font-lock-builtin-face)
6811 ((and target-name prop)
6812 (cond
6813 ((string= target-name "Date")
6814 (if (string-match js2-ecma-date-props prop-name)
6815 'font-lock-builtin-face))
6816 ((string= target-name "Math")
6817 (if (string-match js2-ecma-math-funcs prop-name)
6818 'font-lock-builtin-face))))))
6819 (prop
6820 (if (string-match js2-ecma-global-funcs prop-name)
6821 'font-lock-builtin-face)))
6822 (cond
6823 ((and target prop)
6824 (cond
6825 ((string= target-name "Number")
6826 (if (string-match js2-ecma-number-props prop-name)
6827 'font-lock-constant-face))
6828 ((string= target-name "Math")
6829 (if (string-match js2-ecma-math-props prop-name)
6830 'font-lock-constant-face))))
6831 (prop
6832 (if (string-match js2-ecma-object-props prop-name)
6833 'font-lock-constant-face))))))
6834 (when face
6835 (let ((pos (+ (js2-node-pos parent) ; absolute
6836 (js2-node-pos prop)))) ; relative
6837 (js2-set-face pos
6838 (+ pos (js2-node-len prop))
6839 face 'record)))))))
6840
6841 (defun js2-parse-highlight-member-expr-node (node)
6842 "Perform syntax highlighting of EcmaScript built-in properties.
6843 The variable `js2-highlight-level' governs this highlighting."
6844 (let (face target prop name pos end parent call-p callee)
6845 (cond
6846 ;; case 1: simple name, e.g. foo
6847 ((js2-name-node-p node)
6848 (setq name (js2-name-node-name node))
6849 ;; possible for name to be nil in rare cases - saw it when
6850 ;; running js2-mode on an elisp buffer. Might as well try to
6851 ;; make it so js2-mode never barfs.
6852 (when name
6853 (setq face (if (string-match js2-ecma-global-props name)
6854 'font-lock-constant-face))
6855 (when face
6856 (setq pos (js2-node-pos node)
6857 end (+ pos (js2-node-len node)))
6858 (js2-set-face pos end face 'record))))
6859 ;; case 2: property access or function call
6860 ((or (js2-prop-get-node-p node)
6861 ;; highlight function call if expr is a prop-get node
6862 ;; or a plain name (i.e. unqualified function call)
6863 (and (setq call-p (js2-call-node-p node))
6864 (setq callee (js2-call-node-target node)) ; separate setq!
6865 (or (js2-prop-get-node-p callee)
6866 (js2-name-node-p callee))))
6867 (setq parent node
6868 node (if call-p callee node))
6869 (if (and call-p (js2-name-node-p callee))
6870 (setq prop callee)
6871 (setq target (js2-prop-get-node-left node)
6872 prop (js2-prop-get-node-right node)))
6873 (cond
6874 ((js2-name-node-p prop)
6875 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6876 (js2-parse-highlight-prop-get parent target prop call-p))
6877 ((js2-name-node-p target)
6878 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6879 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6880
6881 (defun js2-parse-highlight-member-expr-fn-name (expr)
6882 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6883 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6884 We currently only handle the case where the last component is a prop-get
6885 of a simple name. Called before EXPR has a parent node."
6886 (let (pos
6887 (name (and (js2-prop-get-node-p expr)
6888 (js2-prop-get-node-right expr))))
6889 (when (js2-name-node-p name)
6890 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6891 (js2-node-pos name)))
6892 (+ pos (js2-node-len name))
6893 'font-lock-function-name-face
6894 'record))))
6895
6896 ;; source: http://jsdoc.sourceforge.net/
6897 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6898 ;; allows type specifications, and needs work before entering the wild.
6899
6900 (defconst js2-jsdoc-param-tag-regexp
6901 (concat "^\\s-*\\*+\\s-*\\(@"
6902 "\\(?:param\\|argument\\)"
6903 "\\)"
6904 "\\s-*\\({[^}]+}\\)?" ; optional type
6905 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6906 "\\_>")
6907 "Matches jsdoc tags with optional type and optional param name.")
6908
6909 (defconst js2-jsdoc-typed-tag-regexp
6910 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6911 (regexp-opt
6912 '("enum"
6913 "extends"
6914 "field"
6915 "id"
6916 "implements"
6917 "lends"
6918 "mods"
6919 "requires"
6920 "return"
6921 "returns"
6922 "throw"
6923 "throws"))
6924 "\\)\\)\\s-*\\({[^}]+}\\)?")
6925 "Matches jsdoc tags with optional type.")
6926
6927 (defconst js2-jsdoc-arg-tag-regexp
6928 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6929 (regexp-opt
6930 '("alias"
6931 "augments"
6932 "borrows"
6933 "bug"
6934 "base"
6935 "config"
6936 "default"
6937 "define"
6938 "exception"
6939 "function"
6940 "member"
6941 "memberOf"
6942 "name"
6943 "namespace"
6944 "property"
6945 "since"
6946 "suppress"
6947 "this"
6948 "throws"
6949 "type"
6950 "version"))
6951 "\\)\\)\\s-+\\([^ \t]+\\)")
6952 "Matches jsdoc tags with a single argument.")
6953
6954 (defconst js2-jsdoc-empty-tag-regexp
6955 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6956 (regexp-opt
6957 '("addon"
6958 "author"
6959 "class"
6960 "const"
6961 "constant"
6962 "constructor"
6963 "constructs"
6964 "deprecated"
6965 "desc"
6966 "description"
6967 "event"
6968 "example"
6969 "exec"
6970 "export"
6971 "fileoverview"
6972 "final"
6973 "function"
6974 "hidden"
6975 "ignore"
6976 "implicitCast"
6977 "inheritDoc"
6978 "inner"
6979 "interface"
6980 "license"
6981 "noalias"
6982 "noshadow"
6983 "notypecheck"
6984 "override"
6985 "owner"
6986 "preserve"
6987 "preserveTry"
6988 "private"
6989 "protected"
6990 "public"
6991 "static"
6992 "supported"
6993 ))
6994 "\\)\\)\\s-*")
6995 "Matches empty jsdoc tags.")
6996
6997 (defconst js2-jsdoc-link-tag-regexp
6998 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6999 "Matches a jsdoc link or code tag.")
7000
7001 (defconst js2-jsdoc-see-tag-regexp
7002 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
7003 "Matches a jsdoc @see tag.")
7004
7005 (defconst js2-jsdoc-html-tag-regexp
7006 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
7007 "Matches a simple (no attributes) html start- or end-tag.")
7008
7009 (defun js2-jsdoc-highlight-helper ()
7010 (js2-set-face (match-beginning 1)
7011 (match-end 1)
7012 'js2-jsdoc-tag)
7013 (if (match-beginning 2)
7014 (if (save-excursion
7015 (goto-char (match-beginning 2))
7016 (= (char-after) ?{))
7017 (js2-set-face (1+ (match-beginning 2))
7018 (1- (match-end 2))
7019 'js2-jsdoc-type)
7020 (js2-set-face (match-beginning 2)
7021 (match-end 2)
7022 'js2-jsdoc-value)))
7023 (if (match-beginning 3)
7024 (js2-set-face (match-beginning 3)
7025 (match-end 3)
7026 'js2-jsdoc-value)))
7027
7028 (defun js2-highlight-jsdoc (ast)
7029 "Highlight doc comment tags."
7030 (let ((comments (js2-ast-root-comments ast))
7031 beg end)
7032 (save-excursion
7033 (dolist (node comments)
7034 (when (eq (js2-comment-node-format node) 'jsdoc)
7035 (setq beg (js2-node-abs-pos node)
7036 end (+ beg (js2-node-len node)))
7037 (save-restriction
7038 (narrow-to-region beg end)
7039 (dolist (re (list js2-jsdoc-param-tag-regexp
7040 js2-jsdoc-typed-tag-regexp
7041 js2-jsdoc-arg-tag-regexp
7042 js2-jsdoc-link-tag-regexp
7043 js2-jsdoc-see-tag-regexp
7044 js2-jsdoc-empty-tag-regexp))
7045 (goto-char beg)
7046 (while (re-search-forward re nil t)
7047 (js2-jsdoc-highlight-helper)))
7048 ;; simple highlighting for html tags
7049 (goto-char beg)
7050 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7051 (js2-set-face (match-beginning 1)
7052 (match-end 1)
7053 'js2-jsdoc-html-tag-delimiter)
7054 (js2-set-face (match-beginning 2)
7055 (match-end 2)
7056 'js2-jsdoc-html-tag-name)
7057 (js2-set-face (match-beginning 3)
7058 (match-end 3)
7059 'js2-jsdoc-html-tag-delimiter))))))))
7060
7061 (defun js2-highlight-assign-targets (_node left right)
7062 "Highlight function properties and external variables."
7063 (let (leftpos name)
7064 ;; highlight vars and props assigned function values
7065 (when (or (js2-function-node-p right)
7066 (js2-class-node-p right))
7067 (cond
7068 ;; var foo = function() {...}
7069 ((js2-name-node-p left)
7070 (setq name left))
7071 ;; foo.bar.baz = function() {...}
7072 ((and (js2-prop-get-node-p left)
7073 (js2-name-node-p (js2-prop-get-node-right left)))
7074 (setq name (js2-prop-get-node-right left))))
7075 (when name
7076 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7077 (+ leftpos (js2-node-len name))
7078 'font-lock-function-name-face
7079 'record)))))
7080
7081 (defun js2-record-name-node (node)
7082 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7083 later. NODE must be a name node."
7084 (let ((leftpos (js2-node-abs-pos node)))
7085 (push (list node js2-current-scope
7086 leftpos
7087 (+ leftpos (js2-node-len node)))
7088 js2-recorded-identifiers)))
7089
7090 (defun js2-highlight-undeclared-vars ()
7091 "After entire parse is finished, look for undeclared variable references.
7092 We have to wait until entire buffer is parsed, since JavaScript permits var
7093 decls to occur after they're used.
7094
7095 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7096 it is considered declared."
7097 (let (name)
7098 (dolist (entry js2-recorded-identifiers)
7099 (cl-destructuring-bind (name-node scope pos end) entry
7100 (setq name (js2-name-node-name name-node))
7101 (unless (or (member name js2-global-externs)
7102 (member name js2-default-externs)
7103 (member name js2-additional-externs)
7104 (js2-get-defining-scope scope name pos))
7105 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7106 'js2-external-variable))))))
7107
7108 (defun js2--add-or-update-symbol (symbol inition used vars)
7109 "Add or update SYMBOL entry in VARS, an hash table.
7110 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7111 respectively meaning that SYMBOL is a mere declaration, an
7112 assignment or a function parameter; when USED is t, the symbol
7113 node is assumed to be an usage and thus added to the list stored
7114 in the cdr of the entry.
7115 "
7116 (let* ((nm (js2-name-node-name symbol))
7117 (es (js2-node-get-enclosing-scope symbol))
7118 (ds (js2-get-defining-scope es nm)))
7119 (when (and ds (not (equal nm "arguments")))
7120 (let* ((sym (js2-scope-get-symbol ds nm))
7121 (var (gethash sym vars))
7122 (err-var-p (js2-catch-node-p ds)))
7123 (unless inition
7124 (setq inition err-var-p))
7125 (if var
7126 (progn
7127 (when (and inition (not (equal (car var) ?P)))
7128 (setcar var inition))
7129 (when used
7130 (push symbol (cdr var))))
7131 ;; do not consider the declaration of catch parameter as an usage
7132 (when (and err-var-p used)
7133 (setq used nil))
7134 (puthash sym (cons inition (if used (list symbol))) vars))))))
7135
7136 (defun js2--classify-variables ()
7137 "Collect and classify variables declared or used within js2-mode-ast.
7138 Traverse the whole ast tree returning a summary of the variables
7139 usage as an hash-table, keyed by their corresponding symbol table
7140 entry.
7141 Each variable is described by a tuple where the car is a flag
7142 indicating whether the variable has been initialized and the cdr
7143 is a possibly empty list of name nodes where it is used. External
7144 symbols, i.e. those not present in the whole scopes hierarchy,
7145 are ignored."
7146 (let ((vars (make-hash-table :test #'eq :size 100)))
7147 (js2-visit-ast
7148 js2-mode-ast
7149 (lambda (node end-p)
7150 (when (null end-p)
7151 (cond
7152 ((js2-var-init-node-p node)
7153 ;; take note about possibly initialized declarations
7154 (let ((target (js2-var-init-node-target node))
7155 (initializer (js2-var-init-node-initializer node)))
7156 (when target
7157 (let* ((parent (js2-node-parent node))
7158 (grandparent (if parent (js2-node-parent parent)))
7159 (inited (not (null initializer))))
7160 (unless inited
7161 (setq inited
7162 (and grandparent
7163 (js2-for-in-node-p grandparent)
7164 (memq target
7165 (mapcar #'js2-var-init-node-target
7166 (js2-var-decl-node-kids
7167 (js2-for-in-node-iterator grandparent)))))))
7168 (js2--add-or-update-symbol target inited nil vars)))))
7169
7170 ((js2-assign-node-p node)
7171 ;; take note about assignments
7172 (let ((left (js2-assign-node-left node)))
7173 (when (js2-name-node-p left)
7174 (js2--add-or-update-symbol left t nil vars))))
7175
7176 ((js2-prop-get-node-p node)
7177 ;; handle x.y.z nodes, considering only x
7178 (let ((left (js2-prop-get-node-left node)))
7179 (when (js2-name-node-p left)
7180 (js2--add-or-update-symbol left nil t vars))))
7181
7182 ((js2-name-node-p node)
7183 ;; take note about used variables
7184 (let ((parent (js2-node-parent node)))
7185 (when parent
7186 (unless (or (and (js2-var-init-node-p parent) ; handled above
7187 (eq node (js2-var-init-node-target parent)))
7188 (and (js2-assign-node-p parent)
7189 (eq node (js2-assign-node-left parent)))
7190 (js2-prop-get-node-p parent))
7191 (let ((used t) inited)
7192 (cond
7193 ((and (js2-function-node-p parent)
7194 (js2-wrapper-function-p parent))
7195 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7196
7197 ((js2-for-in-node-p parent)
7198 (if (eq node (js2-for-in-node-iterator parent))
7199 (setq inited t used nil)))
7200
7201 ((js2-function-node-p parent)
7202 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7203 used nil)))
7204
7205 (unless used
7206 (let ((grandparent (js2-node-parent parent)))
7207 (when grandparent
7208 (setq used (js2-return-node-p grandparent)))))
7209
7210 (js2--add-or-update-symbol node inited used vars))))))))
7211 t))
7212 vars))
7213
7214 (defun js2--get-name-node (node)
7215 (cond
7216 ((js2-name-node-p node) node)
7217 ((js2-function-node-p node)
7218 (js2-function-node-name node))
7219 ((js2-class-node-p node)
7220 (js2-class-node-name node))
7221 ((js2-comp-loop-node-p node)
7222 (js2-comp-loop-node-iterator node))
7223 (t node)))
7224
7225 (defun js2--highlight-unused-variable (symbol info)
7226 (let ((name (js2-symbol-name symbol))
7227 (inited (car info))
7228 (refs (cdr info))
7229 pos len)
7230 (unless (and inited refs)
7231 (if refs
7232 (dolist (ref refs)
7233 (setq pos (js2-node-abs-pos ref))
7234 (setq len (js2-name-node-len ref))
7235 (js2-report-warning "msg.uninitialized.variable" name pos len
7236 'js2-warning))
7237 (when (or js2-warn-about-unused-function-arguments
7238 (not (eq inited ?P)))
7239 (let* ((symn (js2-symbol-ast-node symbol))
7240 (namen (js2--get-name-node symn)))
7241 (unless (js2-node-top-level-decl-p namen)
7242 (setq pos (js2-node-abs-pos namen))
7243 (setq len (js2-name-node-len namen))
7244 (js2-report-warning "msg.unused.variable" name pos len
7245 'js2-warning))))))))
7246
7247 (defun js2-highlight-unused-variables ()
7248 "Highlight unused variables."
7249 (let ((vars (js2--classify-variables)))
7250 (maphash #'js2--highlight-unused-variable vars)))
7251
7252 ;;;###autoload
7253 (define-minor-mode js2-highlight-unused-variables-mode
7254 "Toggle highlight of unused variables."
7255 :lighter ""
7256 (if js2-highlight-unused-variables-mode
7257 (add-hook 'js2-post-parse-callbacks
7258 #'js2-highlight-unused-variables nil t)
7259 (remove-hook 'js2-post-parse-callbacks
7260 #'js2-highlight-unused-variables t)))
7261
7262 (defun js2-set-default-externs ()
7263 "Set the value of `js2-default-externs' based on the various
7264 `js2-include-?-externs' variables."
7265 (setq js2-default-externs
7266 (append js2-ecma-262-externs
7267 (if js2-include-browser-externs js2-browser-externs)
7268 (if (and js2-include-browser-externs
7269 (>= js2-language-version 200)) js2-harmony-externs)
7270 (if js2-include-rhino-externs js2-rhino-externs)
7271 (if js2-include-node-externs js2-node-externs)
7272 (if (or js2-include-browser-externs js2-include-node-externs)
7273 js2-typed-array-externs))))
7274
7275 (defun js2-apply-jslint-globals ()
7276 (setq js2-additional-externs
7277 (nconc (js2-get-jslint-globals)
7278 js2-additional-externs)))
7279
7280 (defun js2-get-jslint-globals ()
7281 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7282 when (and (eq 'block (js2-comment-node-format node))
7283 (save-excursion
7284 (goto-char (js2-node-abs-pos node))
7285 (looking-at "/\\*global ")))
7286 append (js2-get-jslint-globals-in
7287 (match-end 0)
7288 (js2-node-abs-end node))))
7289
7290 (defun js2-get-jslint-globals-in (beg end)
7291 (let (res)
7292 (save-excursion
7293 (goto-char beg)
7294 (while (re-search-forward js2-mode-identifier-re end t)
7295 (let ((match (match-string 0)))
7296 (unless (member match '("true" "false"))
7297 (push match res)))))
7298 (nreverse res)))
7299
7300 ;;; IMenu support
7301
7302 ;; We currently only support imenu, but eventually should support speedbar and
7303 ;; possibly other browsing mechanisms.
7304
7305 ;; The basic strategy is to identify function assignment targets of the form
7306 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7307 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7308 ;; for imenu after parsing is finished.
7309
7310 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7311 ;; JavaScript, and the general problem is undecidable. However, several forms
7312 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7313 ;; include:
7314
7315 ;; function foo() -- function declaration
7316 ;; foo = function() -- function expression assigned to variable
7317 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7318 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7319 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7320 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7321 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7322 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7323 ;; function foo() {function bar() {...}} -- nested function
7324 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7325
7326 ;; This list boils down to a few forms that can be combined recursively.
7327 ;; Top-level named function declarations include both the left-hand (name)
7328 ;; and the right-hand (function value) expressions needed to produce an imenu
7329 ;; entry. The other "right-hand" forms we need to look for are:
7330 ;; - functions declared as props/getters/setters in object literals
7331 ;; - nested named function declarations
7332 ;; The "left-hand" expressions that functions can be assigned to include:
7333 ;; - local/global variables
7334 ;; - nested property-get expressions like a.b.c.d
7335 ;; - element gets like foo[10] or foo['bar'] where the index
7336 ;; expression can be trivially converted to a property name. They
7337 ;; effectively then become property gets.
7338
7339 ;; All the different definition types are canonicalized into the form
7340 ;; foo.bar.baz = position-of-function-keyword
7341
7342 ;; We need to build a trie-like structure for imenu. As an example,
7343 ;; consider the following JavaScript code:
7344
7345 ;; a = function() {...} // function at position 5
7346 ;; b = function() {...} // function at position 25
7347 ;; foo = function() {...} // function at position 100
7348 ;; foo.bar = function() {...} // function at position 200
7349 ;; foo.bar.baz = function() {...} // function at position 300
7350 ;; foo.bar.zab = function() {...} // function at position 400
7351
7352 ;; During parsing we accumulate an entry for each definition in
7353 ;; the variable `js2-imenu-recorder', like so:
7354
7355 ;; '((fn a 5)
7356 ;; (fn b 25)
7357 ;; (fn foo 100)
7358 ;; (fn foo bar 200)
7359 ;; (fn foo bar baz 300)
7360 ;; (fn foo bar zab 400))
7361
7362 ;; Where 'fn' is the respective function node.
7363 ;; After parsing these entries are merged into this alist-trie:
7364
7365 ;; '((a . 1)
7366 ;; (b . 2)
7367 ;; (foo (<definition> . 3)
7368 ;; (bar (<definition> . 6)
7369 ;; (baz . 100)
7370 ;; (zab . 200))))
7371
7372 ;; Note the wacky need for a <definition> name. The token can be anything
7373 ;; that isn't a valid JavaScript identifier, because you might make foo
7374 ;; a function and then start setting properties on it that are also functions.
7375
7376 (defun js2-prop-node-name (node)
7377 "Return the name of a node that may be a property-get/property-name.
7378 If NODE is not a valid name-node, string-node or integral number-node,
7379 returns nil. Otherwise returns the string name/value of the node."
7380 (cond
7381 ((js2-name-node-p node)
7382 (js2-name-node-name node))
7383 ((js2-string-node-p node)
7384 (js2-string-node-value node))
7385 ((and (js2-number-node-p node)
7386 (string-match "^[0-9]+$" (js2-number-node-value node)))
7387 (js2-number-node-value node))
7388 ((eq (js2-node-type node) js2-THIS)
7389 "this")
7390 ((eq (js2-node-type node) js2-SUPER)
7391 "super")))
7392
7393 (defun js2-node-qname-component (node)
7394 "Return the name of this node, if it contributes to a qname.
7395 Returns nil if the node doesn't contribute."
7396 (copy-sequence
7397 (or (js2-prop-node-name node)
7398 (if (and (js2-function-node-p node)
7399 (js2-function-node-name node))
7400 (js2-name-node-name (js2-function-node-name node))))))
7401
7402 (defun js2-record-imenu-entry (fn-node qname pos)
7403 "Add an entry to `js2-imenu-recorder'.
7404 FN-NODE should be the current item's function node.
7405
7406 Associate FN-NODE with its QNAME for later lookup.
7407 This is used in postprocessing the chain list. For each chain, we find
7408 the parent function, look up its qname, then prepend a copy of it to the chain."
7409 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7410 (unless js2-imenu-function-map
7411 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7412 (puthash fn-node qname js2-imenu-function-map))
7413
7414 (defun js2-record-imenu-functions (node &optional var)
7415 "Record function definitions for imenu.
7416 NODE is a function node or an object literal.
7417 VAR, if non-nil, is the expression that NODE is being assigned to.
7418 When passed arguments of wrong type, does nothing."
7419 (when js2-parse-ide-mode
7420 (let ((fun-p (js2-function-node-p node))
7421 qname fname-node)
7422 (cond
7423 ;; non-anonymous function declaration?
7424 ((and fun-p
7425 (not var)
7426 (setq fname-node (js2-function-node-name node)))
7427 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7428 ;; for remaining forms, compute left-side tree branch first
7429 ((and var (setq qname (js2-compute-nested-prop-get var)))
7430 (cond
7431 ;; foo.bar.baz = function
7432 (fun-p
7433 (js2-record-imenu-entry node qname (js2-node-pos node)))
7434 ;; foo.bar.baz = object-literal
7435 ;; look for nested functions: {a: {b: function() {...} }}
7436 ((js2-object-node-p node)
7437 ;; Node position here is still absolute, since the parser
7438 ;; passes the assignment target and value expressions
7439 ;; to us before they are added as children of the assignment node.
7440 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7441
7442 (defun js2-compute-nested-prop-get (node)
7443 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7444 component nodes as a list. Otherwise return nil. Element-gets are treated
7445 as property-gets if the index expression is a string, or a positive integer."
7446 (let (left right head)
7447 (cond
7448 ((or (js2-name-node-p node)
7449 (js2-this-or-super-node-p node))
7450 (list node))
7451 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7452 ((js2-prop-get-node-p node) ; foo.bar
7453 (setq left (js2-prop-get-node-left node)
7454 right (js2-prop-get-node-right node))
7455 (if (setq head (js2-compute-nested-prop-get left))
7456 (nconc head (list right))))
7457 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7458 (setq left (js2-elem-get-node-target node)
7459 right (js2-elem-get-node-element node))
7460 (if (or (js2-string-node-p right) ; ['bar']
7461 (and (js2-number-node-p right) ; [10]
7462 (string-match "^[0-9]+$"
7463 (js2-number-node-value right))))
7464 (if (setq head (js2-compute-nested-prop-get left))
7465 (nconc head (list right))))))))
7466
7467 (defun js2-record-object-literal (node qname pos)
7468 "Recursively process an object literal looking for functions.
7469 NODE is an object literal that is the right-hand child of an assignment
7470 expression. QNAME is a list of nodes representing the assignment target,
7471 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7472 POS is the absolute position of the node.
7473 We do a depth-first traversal of NODE. For any functions we find,
7474 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7475 (let (right)
7476 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7477 (let ((left (js2-infix-node-left e))
7478 ;; Element positions are relative to the parent position.
7479 (pos (+ pos (js2-node-pos e))))
7480 (cond
7481 ;; foo: function() {...}
7482 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7483 (when (js2-prop-node-name left)
7484 ;; As a policy decision, we record the position of the property,
7485 ;; not the position of the `function' keyword, since the property
7486 ;; is effectively the name of the function.
7487 (js2-record-imenu-entry right (append qname (list left)) pos)))
7488 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7489 ((js2-object-node-p right)
7490 (js2-record-object-literal right
7491 (append qname (list (js2-infix-node-left e)))
7492 (+ pos (js2-node-pos right)))))))))
7493
7494 (defun js2-node-top-level-decl-p (node)
7495 "Return t if NODE's name is defined in the top-level scope.
7496 Also returns t if NODE's name is not defined in any scope, since it implies
7497 that it's an external variable, which must also be in the top-level scope."
7498 (let* ((name (js2-prop-node-name node))
7499 (this-scope (js2-node-get-enclosing-scope node))
7500 defining-scope)
7501 (cond
7502 ((js2-this-or-super-node-p node)
7503 nil)
7504 ((null this-scope)
7505 t)
7506 ((setq defining-scope (js2-get-defining-scope this-scope name))
7507 (js2-ast-root-p defining-scope))
7508 (t t))))
7509
7510 (defun js2-wrapper-function-p (node)
7511 "Return t if NODE is a function expression that's immediately invoked.
7512 NODE must be `js2-function-node'."
7513 (let ((parent (js2-node-parent node)))
7514 (or
7515 ;; function(){...}();
7516 (and (js2-call-node-p parent)
7517 (eq node (js2-call-node-target parent)))
7518 (and (js2-paren-node-p parent)
7519 ;; (function(){...})();
7520 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7521 ;; (function(){...}).call(this);
7522 (and (js2-prop-get-node-p parent)
7523 (member (js2-name-node-name (js2-prop-get-node-right parent))
7524 '("call" "apply"))
7525 (js2-call-node-p (js2-node-parent parent))))))))
7526
7527 (defun js2-browse-postprocess-chains ()
7528 "Modify function-declaration name chains after parsing finishes.
7529 Some of the information is only available after the parse tree is complete.
7530 For instance, processing a nested scope requires a parent function node."
7531 (let (result fn parent-qname p elem)
7532 (dolist (entry js2-imenu-recorder)
7533 ;; function node goes first
7534 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7535 ;; Examine head's defining scope:
7536 ;; Pre-processed chain, or top-level/external, keep as-is.
7537 (if (or (stringp head) (js2-node-top-level-decl-p head))
7538 (push chain result)
7539 (when (js2-this-or-super-node-p head)
7540 (setq chain (cdr chain))) ; discard this-node
7541 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7542 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7543 (when (eq parent-qname 'not-found)
7544 ;; anonymous function expressions are not recorded
7545 ;; during the parse, so we need to handle this case here
7546 (setq parent-qname
7547 (if (js2-wrapper-function-p fn)
7548 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7549 (if (js2-ast-root-p grandparent)
7550 nil
7551 (gethash grandparent js2-imenu-function-map 'skip)))
7552 'skip))
7553 (puthash fn parent-qname js2-imenu-function-map))
7554 (if (eq parent-qname 'skip)
7555 ;; We don't show it, let's record that fact.
7556 (remhash current-fn js2-imenu-function-map)
7557 ;; Prepend parent fn qname to this chain.
7558 (let ((qname (append parent-qname chain)))
7559 (puthash current-fn (butlast qname) js2-imenu-function-map)
7560 (push qname result)))))))
7561 ;; Collect chains obtained by third-party code.
7562 (let (js2-imenu-recorder)
7563 (run-hooks 'js2-build-imenu-callbacks)
7564 (dolist (entry js2-imenu-recorder)
7565 (push (cdr entry) result)))
7566 ;; Finally replace each node in each chain with its name.
7567 (dolist (chain result)
7568 (setq p chain)
7569 (while p
7570 (if (js2-node-p (setq elem (car p)))
7571 (setcar p (js2-node-qname-component elem)))
7572 (setq p (cdr p))))
7573 result))
7574
7575 ;; Merge name chains into a trie-like tree structure of nested lists.
7576 ;; To simplify construction of the trie, we first build it out using the rule
7577 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7578 ;; [key, num-or-list]. The second element can be a number; if so, this key
7579 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7580 ;; associated with the key at this level.) Otherwise the second element is
7581 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7582 ;; a simple recursive formulation.
7583 ;;
7584 ;; js2-mode is building the data structure for imenu. The imenu documentation
7585 ;; claims that it's the structure above, but in practice it wants the children
7586 ;; at the same list level as the key for that level, which is how I've drawn
7587 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7588 ;; list wrapper around the children at each level.
7589 ;;
7590 ;; A completed nested imenu-alist entry looks like this:
7591 ;; '(("foo"
7592 ;; ("<definition>" . 7)
7593 ;; ("bar"
7594 ;; ("a" . 40)
7595 ;; ("b" . 60))))
7596 ;;
7597 ;; In particular, the documentation for `imenu--index-alist' says that
7598 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7599 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7600
7601 (defun js2-treeify (lst)
7602 "Convert (a b c d) to (a ((b ((c d)))))."
7603 (if (null (cddr lst)) ; list length <= 2
7604 lst
7605 (list (car lst) (list (js2-treeify (cdr lst))))))
7606
7607 (defun js2-build-alist-trie (chains trie)
7608 "Merge declaration name chains into a trie-like alist structure for imenu.
7609 CHAINS is the qname chain list produced during parsing. TRIE is a
7610 list of elements built up so far."
7611 (let (head tail pos branch kids)
7612 (dolist (chain chains)
7613 (setq head (car chain)
7614 tail (cdr chain)
7615 pos (if (numberp (car tail)) (car tail))
7616 branch (js2-find-if (lambda (n)
7617 (string= (car n) head))
7618 trie)
7619 kids (cl-second branch))
7620 (cond
7621 ;; case 1: this key isn't in the trie yet
7622 ((null branch)
7623 (if trie
7624 (setcdr (last trie) (list (js2-treeify chain)))
7625 (setq trie (list (js2-treeify chain)))))
7626 ;; case 2: key is present with a single number entry: replace w/ list
7627 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7628 ;; ("<definition>" 20)))
7629 ((numberp kids)
7630 (setcar (cdr branch)
7631 (list (list "<definition-1>" kids)
7632 (if pos
7633 (list "<definition-2>" pos)
7634 (js2-treeify tail)))))
7635 ;; case 3: key is there (with kids), and we're a number entry
7636 (pos
7637 (setcdr (last kids)
7638 (list
7639 (list (format "<definition-%d>"
7640 (1+ (cl-loop for kid in kids
7641 count (eq ?< (aref (car kid) 0)))))
7642 pos))))
7643 ;; case 4: key is there with kids, need to merge in our chain
7644 (t
7645 (js2-build-alist-trie (list tail) kids))))
7646 trie))
7647
7648 (defun js2-flatten-trie (trie)
7649 "Convert TRIE to imenu-format.
7650 Recurses through nodes, and for each one whose second element is a list,
7651 appends the list's flattened elements to the current element. Also
7652 changes the tails into conses. For instance, this pre-flattened trie
7653
7654 '(a ((b 20)
7655 (c ((d 30)
7656 (e 40)))))
7657
7658 becomes
7659
7660 '(a (b . 20)
7661 (c (d . 30)
7662 (e . 40)))
7663
7664 Note that the root of the trie has no key, just a list of chains.
7665 This is also true for the value of any key with multiple children,
7666 e.g. key 'c' in the example above."
7667 (cond
7668 ((listp (car trie))
7669 (mapcar #'js2-flatten-trie trie))
7670 (t
7671 (if (numberp (cl-second trie))
7672 (cons (car trie) (cl-second trie))
7673 ;; else pop list and append its kids
7674 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7675
7676 (defun js2-build-imenu-index ()
7677 "Turn `js2-imenu-recorder' into an imenu data structure."
7678 (when (eq js2-imenu-recorder 'empty)
7679 (setq js2-imenu-recorder nil))
7680 (let* ((chains (js2-browse-postprocess-chains))
7681 (result (js2-build-alist-trie chains nil)))
7682 (js2-flatten-trie result)))
7683
7684 (defun js2-test-print-chains (chains)
7685 "Print a list of qname chains.
7686 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7687 i.e. one or more nodes, and an integer position as the list tail."
7688 (mapconcat (lambda (chain)
7689 (concat "("
7690 (mapconcat (lambda (elem)
7691 (if (js2-node-p elem)
7692 (or (js2-node-qname-component elem)
7693 "nil")
7694 (number-to-string elem)))
7695 chain
7696 " ")
7697 ")"))
7698 chains
7699 "\n"))
7700
7701 ;;; Parser
7702
7703 (defconst js2-version "1.8.5"
7704 "Version of JavaScript supported.")
7705
7706 (defun js2-record-face (face &optional token)
7707 "Record a style run of FACE for TOKEN or the current token."
7708 (unless token (setq token (js2-current-token)))
7709 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7710
7711 (defsubst js2-node-end (n)
7712 "Computes the absolute end of node N.
7713 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7714 is only true until the node is added to its parent; i.e., while parsing."
7715 (+ (js2-node-pos n)
7716 (js2-node-len n)))
7717
7718 (defun js2-record-comment (token)
7719 "Record a comment in `js2-scanned-comments'."
7720 (let ((ct (js2-token-comment-type token))
7721 (beg (js2-token-beg token))
7722 (end (js2-token-end token)))
7723 (push (make-js2-comment-node :len (- end beg)
7724 :format ct)
7725 js2-scanned-comments)
7726 (when js2-parse-ide-mode
7727 (js2-record-face (if (eq ct 'jsdoc)
7728 'font-lock-doc-face
7729 'font-lock-comment-face)
7730 token)
7731 (when (memq ct '(html preprocessor))
7732 ;; Tell cc-engine the bounds of the comment.
7733 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7734
7735 (defun js2-peek-token ()
7736 "Return the next token type without consuming it.
7737 If `js2-ti-lookahead' is positive, return the type of next token
7738 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7739 (if (not (zerop js2-ti-lookahead))
7740 (js2-token-type
7741 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7742 (let ((tt (js2-get-token-internal nil)))
7743 (js2-unget-token)
7744 tt)))
7745
7746 (defalias 'js2-next-token 'js2-get-token)
7747
7748 (defun js2-match-token (match &optional dont-unget)
7749 "Get next token and return t if it matches MATCH, a bytecode.
7750 Returns nil and consumes nothing if MATCH is not the next token."
7751 (if (/= (js2-get-token) match)
7752 (ignore (unless dont-unget (js2-unget-token)))
7753 t))
7754
7755 (defun js2-match-contextual-kwd (name)
7756 "Consume and return t if next token is `js2-NAME', and its
7757 string is NAME. Returns nil and keeps current token otherwise."
7758 (if (or (/= (js2-get-token) js2-NAME)
7759 (not (string= (js2-current-token-string) name)))
7760 (progn
7761 (js2-unget-token)
7762 nil)
7763 (js2-record-face 'font-lock-keyword-face)
7764 t))
7765
7766 (defun js2-get-prop-name-token ()
7767 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7768
7769 (defun js2-match-prop-name ()
7770 "Consume token and return t if next token is a valid property name.
7771 If `js2-language-version' is >= 180, a keyword or reserved word
7772 is considered valid name as well."
7773 (if (eq js2-NAME (js2-get-prop-name-token))
7774 t
7775 (js2-unget-token)
7776 nil))
7777
7778 (defun js2-must-match-prop-name (msg-id &optional pos len)
7779 (if (js2-match-prop-name)
7780 t
7781 (js2-report-error msg-id nil pos len)
7782 nil))
7783
7784 (defun js2-peek-token-or-eol ()
7785 "Return js2-EOL if the next token immediately follows a newline.
7786 Else returns the next token. Used in situations where we don't
7787 consider certain token types valid if they are preceded by a newline.
7788 One example is the postfix ++ or -- operator, which has to be on the
7789 same line as its operand."
7790 (let ((tt (js2-get-token))
7791 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7792 (js2-unget-token)
7793 (if follows-eol
7794 js2-EOL
7795 tt)))
7796
7797 (defun js2-must-match (token msg-id &optional pos len)
7798 "Match next token to token code TOKEN, or record a syntax error.
7799 MSG-ID is the error message to report if the match fails.
7800 Returns t on match, nil if no match."
7801 (if (js2-match-token token t)
7802 t
7803 (js2-report-error msg-id nil pos len)
7804 (js2-unget-token)
7805 nil))
7806
7807 (defun js2-must-match-name (msg-id)
7808 (if (js2-match-token js2-NAME t)
7809 t
7810 (if (eq (js2-current-token-type) js2-RESERVED)
7811 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7812 (js2-report-error msg-id)
7813 (js2-unget-token))
7814 nil))
7815
7816 (defsubst js2-inside-function ()
7817 (cl-plusp js2-nesting-of-function))
7818
7819 (defun js2-set-requires-activation ()
7820 (if (js2-function-node-p js2-current-script-or-fn)
7821 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7822
7823 (defun js2-check-activation-name (name _token)
7824 (when (js2-inside-function)
7825 ;; skip language-version 1.2 check from Rhino
7826 (if (or (string= "arguments" name)
7827 (and js2-compiler-activation-names ; only used in codegen
7828 (gethash name js2-compiler-activation-names)))
7829 (js2-set-requires-activation))))
7830
7831 (defun js2-set-is-generator ()
7832 (let ((fn-node js2-current-script-or-fn))
7833 (when (and (js2-function-node-p fn-node)
7834 (not (js2-function-node-generator-type fn-node)))
7835 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7836
7837 (defun js2-must-have-xml ()
7838 (unless js2-compiler-xml-available
7839 (js2-report-error "msg.XML.not.available")))
7840
7841 (defun js2-push-scope (scope)
7842 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7843 (cl-assert (js2-scope-p scope))
7844 (cl-assert (null (js2-scope-parent-scope scope)))
7845 (cl-assert (not (eq js2-current-scope scope)))
7846 (setf (js2-scope-parent-scope scope) js2-current-scope
7847 js2-current-scope scope))
7848
7849 (defsubst js2-pop-scope ()
7850 (setq js2-current-scope
7851 (js2-scope-parent-scope js2-current-scope)))
7852
7853 (defun js2-enter-loop (loop-node)
7854 (push loop-node js2-loop-set)
7855 (push loop-node js2-loop-and-switch-set)
7856 (js2-push-scope loop-node)
7857 ;; Tell the current labeled statement (if any) its statement,
7858 ;; and set the jump target of the first label to the loop.
7859 ;; These are used in `js2-parse-continue' to verify that the
7860 ;; continue target is an actual labeled loop. (And for codegen.)
7861 (when js2-labeled-stmt
7862 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7863 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7864 js2-labeled-stmt))) loop-node)))
7865
7866 (defun js2-exit-loop ()
7867 (pop js2-loop-set)
7868 (pop js2-loop-and-switch-set)
7869 (js2-pop-scope))
7870
7871 (defsubst js2-enter-switch (switch-node)
7872 (push switch-node js2-loop-and-switch-set))
7873
7874 (defsubst js2-exit-switch ()
7875 (pop js2-loop-and-switch-set))
7876
7877 (defsubst js2-get-directive (node)
7878 "Return NODE's value if it is a directive, nil otherwise.
7879
7880 A directive is an otherwise-meaningless expression statement
7881 consisting of a string literal, such as \"use strict\"."
7882 (and (js2-expr-stmt-node-p node)
7883 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7884 (js2-string-node-value node)))
7885
7886 (defun js2-parse (&optional buf cb)
7887 "Tell the js2 parser to parse a region of JavaScript.
7888
7889 BUF is a buffer or buffer name containing the code to parse.
7890 Call `narrow-to-region' first to parse only part of the buffer.
7891
7892 The returned AST root node is given some additional properties:
7893 `node-count' - total number of nodes in the AST
7894 `buffer' - BUF. The buffer it refers to may change or be killed,
7895 so the value is not necessarily reliable.
7896
7897 An optional callback CB can be specified to report parsing
7898 progress. If `(functionp CB)' returns t, it will be called with
7899 the current line number once before parsing begins, then again
7900 each time the lexer reaches a new line number.
7901
7902 CB can also be a list of the form `(symbol cb ...)' to specify
7903 multiple callbacks with different criteria. Each symbol is a
7904 criterion keyword, and the following element is the callback to
7905 call
7906
7907 :line - called whenever the line number changes
7908 :token - called for each new token consumed
7909
7910 The list of criteria could be extended to include entering or
7911 leaving a statement, an expression, or a function definition."
7912 (if (and cb (not (functionp cb)))
7913 (error "criteria callbacks not yet implemented"))
7914 (let ((inhibit-point-motion-hooks t)
7915 (js2-compiler-xml-available (>= js2-language-version 160))
7916 ;; This is a recursive-descent parser, so give it a big stack.
7917 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7918 (max-specpdl-size (max max-specpdl-size 3000))
7919 (case-fold-search nil)
7920 ast)
7921 (with-current-buffer (or buf (current-buffer))
7922 (setq js2-scanned-comments nil
7923 js2-parsed-errors nil
7924 js2-parsed-warnings nil
7925 js2-imenu-recorder nil
7926 js2-imenu-function-map nil
7927 js2-label-set nil)
7928 (js2-init-scanner)
7929 (setq ast (js2-do-parse))
7930 (unless js2-ts-hit-eof
7931 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7932 (setf (js2-ast-root-errors ast) js2-parsed-errors
7933 (js2-ast-root-warnings ast) js2-parsed-warnings)
7934 ;; if we didn't find any declarations, put a dummy in this list so we
7935 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7936 (unless js2-imenu-recorder
7937 (setq js2-imenu-recorder 'empty))
7938 (run-hooks 'js2-parse-finished-hook)
7939 ast)))
7940
7941 ;; Corresponds to Rhino's Parser.parse() method.
7942 (defun js2-do-parse ()
7943 "Parse current buffer starting from current point.
7944 Scanner should be initialized."
7945 (let ((pos js2-ts-cursor)
7946 (end js2-ts-cursor) ; in case file is empty
7947 root n tt
7948 (in-directive-prologue t)
7949 (js2-in-use-strict-directive js2-in-use-strict-directive)
7950 directive)
7951 ;; initialize buffer-local parsing vars
7952 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7953 js2-current-script-or-fn root
7954 js2-current-scope root
7955 js2-nesting-of-function 0
7956 js2-labeled-stmt nil
7957 js2-recorded-identifiers nil ; for js2-highlight
7958 js2-in-use-strict-directive nil)
7959 (while (/= (setq tt (js2-get-token)) js2-EOF)
7960 (if (= tt js2-FUNCTION)
7961 (progn
7962 (setq n (if js2-called-by-compile-function
7963 (js2-parse-function-expr)
7964 (js2-parse-function-stmt))))
7965 ;; not a function - parse a statement
7966 (js2-unget-token)
7967 (setq n (js2-parse-statement))
7968 (when in-directive-prologue
7969 (setq directive (js2-get-directive n))
7970 (cond
7971 ((null directive)
7972 (setq in-directive-prologue nil))
7973 ((string= directive "use strict")
7974 (setq js2-in-use-strict-directive t)))))
7975 ;; add function or statement to script
7976 (setq end (js2-node-end n))
7977 (js2-block-node-push root n))
7978 ;; add comments to root in lexical order
7979 (when js2-scanned-comments
7980 ;; if we find a comment beyond end of normal kids, use its end
7981 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7982 (dolist (comment js2-scanned-comments)
7983 (push comment (js2-ast-root-comments root))
7984 (js2-node-add-children root comment)))
7985 (setf (js2-node-len root) (- end pos))
7986 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7987 ;; Give extensions a chance to muck with things before highlighting starts.
7988 (let ((js2-additional-externs js2-additional-externs))
7989 (save-excursion
7990 (run-hooks 'js2-post-parse-callbacks))
7991 (js2-highlight-undeclared-vars))
7992 root))
7993
7994 (defun js2-parse-function-closure-body (fn-node)
7995 "Parse a JavaScript 1.8 function closure body."
7996 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7997 (if js2-ts-hit-eof
7998 (js2-report-error "msg.no.brace.body" nil
7999 (js2-node-pos fn-node)
8000 (- js2-ts-cursor (js2-node-pos fn-node)))
8001 (js2-node-add-children fn-node
8002 (setf (js2-function-node-body fn-node)
8003 (js2-parse-expr t))))))
8004
8005 (defun js2-parse-function-body (fn-node)
8006 (js2-must-match js2-LC "msg.no.brace.body"
8007 (js2-node-pos fn-node)
8008 (- js2-ts-cursor (js2-node-pos fn-node)))
8009 (let ((pos (js2-current-token-beg)) ; LC position
8010 (pn (make-js2-block-node)) ; starts at LC position
8011 tt
8012 end
8013 not-in-directive-prologue
8014 node
8015 directive)
8016 (cl-incf js2-nesting-of-function)
8017 (unwind-protect
8018 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
8019 (= tt js2-EOF)
8020 (= tt js2-RC)))
8021 (js2-block-node-push
8022 pn
8023 (if (/= tt js2-FUNCTION)
8024 (if not-in-directive-prologue
8025 (js2-parse-statement)
8026 (setq node (js2-parse-statement)
8027 directive (js2-get-directive node))
8028 (cond
8029 ((null directive)
8030 (setq not-in-directive-prologue t))
8031 ((string= directive "use strict")
8032 ;; Back up and reparse the function, because new rules apply
8033 ;; to the function name and parameters.
8034 (when (not js2-in-use-strict-directive)
8035 (setq js2-in-use-strict-directive t)
8036 (throw 'reparse t))))
8037 node)
8038 (js2-get-token)
8039 (js2-parse-function-stmt))))
8040 (cl-decf js2-nesting-of-function))
8041 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
8042 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
8043 (setq end (js2-current-token-end)))
8044 (setf (js2-node-pos pn) pos
8045 (js2-node-len pn) (- end pos))
8046 (setf (js2-function-node-body fn-node) pn)
8047 (js2-node-add-children fn-node pn)
8048 pn))
8049
8050 (defun js2-define-destruct-symbols-internal
8051 (node decl-type face &optional ignore-not-in-block name-nodes)
8052 "Internal version of `js2-define-destruct-symbols'. The only
8053 difference is that NAME-NODES is passed down recursively."
8054 (cond
8055 ((js2-name-node-p node)
8056 (let (leftpos)
8057 (js2-define-symbol decl-type (js2-name-node-name node)
8058 node ignore-not-in-block)
8059 (when face
8060 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8061 (+ leftpos (js2-node-len node))
8062 face 'record))
8063 (setq name-nodes (append name-nodes (list node)))))
8064 ((js2-object-node-p node)
8065 (dolist (elem (js2-object-node-elems node))
8066 (setq name-nodes
8067 (append name-nodes
8068 (js2-define-destruct-symbols-internal
8069 ;; In abbreviated destructuring {a, b}, right == left.
8070 (js2-object-prop-node-right elem)
8071 decl-type face ignore-not-in-block name-nodes)))))
8072 ((js2-array-node-p node)
8073 (dolist (elem (js2-array-node-elems node))
8074 (when elem
8075 (setq name-nodes
8076 (append name-nodes
8077 (js2-define-destruct-symbols-internal
8078 elem decl-type face ignore-not-in-block name-nodes))))))
8079 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8080 (js2-node-len node))))
8081 name-nodes)
8082
8083 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8084 "Declare and fontify destructuring parameters inside NODE.
8085 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8086
8087 Return a list of `js2-name-node' nodes representing the symbols
8088 declared; probably to check them for errors."
8089 (js2-define-destruct-symbols-internal node decl-type face ignore-not-in-block))
8090
8091 (defvar js2-illegal-strict-identifiers
8092 '("eval" "arguments")
8093 "Identifiers not allowed as variables in strict mode.")
8094
8095 (defun js2-check-strict-identifier (name-node)
8096 "Check that NAME-NODE makes a legal strict mode identifier."
8097 (when js2-in-use-strict-directive
8098 (let ((param-name (js2-name-node-name name-node)))
8099 (when (member param-name js2-illegal-strict-identifiers)
8100 (js2-report-error "msg.bad.id.strict" param-name
8101 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8102
8103 (defun js2-check-strict-function-params (preceding-params params)
8104 "Given PRECEDING-PARAMS in a function's parameter list, check
8105 for strict mode errors caused by PARAMS."
8106 (when js2-in-use-strict-directive
8107 (dolist (param params)
8108 (let ((param-name (js2-name-node-name param)))
8109 (js2-check-strict-identifier param)
8110 (when (cl-some (lambda (param)
8111 (string= (js2-name-node-name param) param-name))
8112 preceding-params)
8113 (js2-report-error "msg.dup.param.strict" param-name
8114 (js2-node-abs-pos param) (js2-node-len param)))))))
8115
8116 (defun js2-parse-function-params (function-type fn-node pos)
8117 "Parse the parameters of a function of FUNCTION-TYPE
8118 represented by FN-NODE at POS."
8119 (if (js2-match-token js2-RP)
8120 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8121 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8122 (eq (js2-current-token-type) js2-NAME)))
8123 params param
8124 param-name-nodes new-param-name-nodes
8125 default-found rest-param-at)
8126 (when paren-free-arrow
8127 (js2-unget-token))
8128 (cl-loop for tt = (js2-peek-token)
8129 do
8130 (cond
8131 ;; destructuring param
8132 ((and (not paren-free-arrow)
8133 (or (= tt js2-LB) (= tt js2-LC)))
8134 (js2-get-token)
8135 (when default-found
8136 (js2-report-error "msg.no.default.after.default.param"))
8137 (setq param (js2-parse-destruct-primary-expr)
8138 new-param-name-nodes (js2-define-destruct-symbols
8139 param js2-LP 'js2-function-param))
8140 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8141 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8142 (push param params))
8143 ;; variable name
8144 (t
8145 (when (and (>= js2-language-version 200)
8146 (not paren-free-arrow)
8147 (js2-match-token js2-TRIPLEDOT)
8148 (not rest-param-at))
8149 ;; to report errors if there are more parameters
8150 (setq rest-param-at (length params)))
8151 (js2-must-match-name "msg.no.parm")
8152 (js2-record-face 'js2-function-param)
8153 (setq param (js2-create-name-node))
8154 (js2-define-symbol js2-LP (js2-current-token-string) param)
8155 (js2-check-strict-function-params param-name-nodes (list param))
8156 (setq param-name-nodes (append param-name-nodes (list param)))
8157 ;; default parameter value
8158 (when (or (and default-found
8159 (not rest-param-at)
8160 (js2-must-match js2-ASSIGN
8161 "msg.no.default.after.default.param"
8162 (js2-node-pos param)
8163 (js2-node-len param)))
8164 (and (>= js2-language-version 200)
8165 (js2-match-token js2-ASSIGN)))
8166 (cl-assert (not paren-free-arrow))
8167 (let* ((pos (js2-node-pos param))
8168 (tt (js2-current-token-type))
8169 (op-pos (- (js2-current-token-beg) pos))
8170 (left param)
8171 (right (js2-parse-assign-expr))
8172 (len (- (js2-node-end right) pos)))
8173 (setq param (make-js2-assign-node
8174 :type tt :pos pos :len len :op-pos op-pos
8175 :left left :right right)
8176 default-found t)
8177 (js2-node-add-children param left right)))
8178 (push param params)))
8179 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8180 (js2-report-error "msg.param.after.rest" nil
8181 (js2-node-pos param) (js2-node-len param)))
8182 while
8183 (js2-match-token js2-COMMA))
8184 (when (and (not paren-free-arrow)
8185 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8186 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8187 (when rest-param-at
8188 (setf (js2-function-node-rest-p fn-node) t))
8189 (dolist (p params)
8190 (js2-node-add-children fn-node p)
8191 (push p (js2-function-node-params fn-node))))))
8192
8193 (defun js2-check-inconsistent-return-warning (fn-node name)
8194 "Possibly show inconsistent-return warning.
8195 Last token scanned is the close-curly for the function body."
8196 (when (and js2-mode-show-strict-warnings
8197 js2-strict-inconsistent-return-warning
8198 (not (js2-has-consistent-return-usage
8199 (js2-function-node-body fn-node))))
8200 ;; Have it extend from close-curly to bol or beginning of block.
8201 (let ((pos (save-excursion
8202 (goto-char (js2-current-token-end))
8203 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8204 (point-at-bol))))
8205 (end (js2-current-token-end)))
8206 (if (cl-plusp (js2-name-node-length name))
8207 (js2-add-strict-warning "msg.no.return.value"
8208 (js2-name-node-name name) pos end)
8209 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8210
8211 (defun js2-parse-function-stmt ()
8212 (let ((pos (js2-current-token-beg))
8213 (star-p (js2-match-token js2-MUL)))
8214 (js2-must-match-name "msg.unnamed.function.stmt")
8215 (let ((name (js2-create-name-node t))
8216 pn member-expr)
8217 (cond
8218 ((js2-match-token js2-LP)
8219 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8220 (js2-allow-member-expr-as-function-name
8221 (setq member-expr (js2-parse-member-expr-tail nil name))
8222 (js2-parse-highlight-member-expr-fn-name member-expr)
8223 (js2-must-match js2-LP "msg.no.paren.parms")
8224 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8225 (js2-function-node-member-expr pn) member-expr)
8226 pn)
8227 (t
8228 (js2-report-error "msg.no.paren.parms")
8229 (make-js2-error-node))))))
8230
8231 (defun js2-parse-function-expr ()
8232 (let ((pos (js2-current-token-beg))
8233 (star-p (js2-match-token js2-MUL))
8234 name)
8235 (when (js2-match-token js2-NAME)
8236 (setq name (js2-create-name-node t)))
8237 (js2-must-match js2-LP "msg.no.paren.parms")
8238 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8239
8240 (defun js2-parse-function-internal (function-type pos star-p &optional name)
8241 (let (fn-node lp)
8242 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8243 (setq lp (js2-current-token-beg)))
8244 (setf fn-node (make-js2-function-node :pos pos
8245 :name name
8246 :form function-type
8247 :lp (if lp (- lp pos))
8248 :generator-type (and star-p 'STAR)))
8249 (when name
8250 (js2-set-face (js2-node-pos name) (js2-node-end name)
8251 'font-lock-function-name-face 'record)
8252 (when (and (eq function-type 'FUNCTION_STATEMENT)
8253 (cl-plusp (js2-name-node-length name)))
8254 ;; Function statements define a symbol in the enclosing scope
8255 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8256 (when js2-in-use-strict-directive
8257 (js2-check-strict-identifier name)))
8258 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8259 ;; 1. Nested functions are not affected by the dynamic scope flag
8260 ;; as dynamic scope is already a parent of their scope.
8261 ;; 2. Functions defined under the with statement also immune to
8262 ;; this setup, in which case dynamic scope is ignored in favor
8263 ;; of the with object.
8264 (setf (js2-function-node-ignore-dynamic fn-node) t))
8265 ;; dynamically bind all the per-function variables
8266 (let ((js2-current-script-or-fn fn-node)
8267 (js2-current-scope fn-node)
8268 (js2-nesting-of-with 0)
8269 (js2-end-flags 0)
8270 js2-label-set
8271 js2-loop-set
8272 js2-loop-and-switch-set)
8273 (js2-parse-function-params function-type fn-node pos)
8274 (when (eq function-type 'FUNCTION_ARROW)
8275 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8276 (if (and (>= js2-language-version 180)
8277 (/= (js2-peek-token) js2-LC))
8278 (js2-parse-function-closure-body fn-node)
8279 (js2-parse-function-body fn-node))
8280 (js2-check-inconsistent-return-warning fn-node name)
8281
8282 (when name
8283 (js2-node-add-children fn-node name)
8284 ;; Function expressions define a name only in the body of the
8285 ;; function, and only if not hidden by a parameter name
8286 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8287 (null (js2-scope-get-symbol js2-current-scope
8288 (js2-name-node-name name))))
8289 (js2-define-symbol js2-FUNCTION
8290 (js2-name-node-name name)
8291 fn-node))
8292 (when (eq function-type 'FUNCTION_STATEMENT)
8293 (js2-record-imenu-functions fn-node))))
8294
8295 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8296 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8297 ;; We wait until after parsing the function to set its parent scope,
8298 ;; since `js2-define-symbol' needs the defining-scope check to stop
8299 ;; at the function boundary when checking for redeclarations.
8300 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8301 fn-node))
8302
8303 (defun js2-parse-function (function-type pos star-p &optional name)
8304 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8305 beginning of the first token (function keyword, unless it's an
8306 arrow function), NAME is js2-name-node."
8307 (let ((continue t)
8308 ts-state
8309 fn-node
8310 ;; Preserve strict state outside this function.
8311 (js2-in-use-strict-directive js2-in-use-strict-directive))
8312 ;; Parse multiple times if a new strict mode directive is discovered in the
8313 ;; function body, as new rules will be retroactively applied to the legality
8314 ;; of function names and parameters.
8315 (while continue
8316 (setq ts-state (make-js2-ts-state))
8317 (setq continue (catch 'reparse
8318 (setq fn-node (js2-parse-function-internal
8319 function-type pos star-p name))
8320 ;; Don't continue.
8321 nil))
8322 (when continue
8323 (js2-ts-seek ts-state)))
8324 fn-node))
8325
8326 (defun js2-parse-statements (&optional parent)
8327 "Parse a statement list. Last token consumed must be js2-LC.
8328
8329 PARENT can be a `js2-block-node', in which case the statements are
8330 appended to PARENT. Otherwise a new `js2-block-node' is created
8331 and returned.
8332
8333 This function does not match the closing js2-RC: the caller
8334 matches the RC so it can provide a suitable error message if not
8335 matched. This means it's up to the caller to set the length of
8336 the node to include the closing RC. The node start pos is set to
8337 the absolute buffer start position, and the caller should fix it
8338 up to be relative to the parent node. All children of this block
8339 node are given relative start positions and correct lengths."
8340 (let ((pn (or parent (make-js2-block-node)))
8341 tt)
8342 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8343 (/= tt js2-RC))
8344 (js2-block-node-push pn (js2-parse-statement)))
8345 pn))
8346
8347 (defun js2-parse-statement ()
8348 (let (pn beg end)
8349 ;; coarse-grained user-interrupt check - needs work
8350 (and js2-parse-interruptable-p
8351 (zerop (% (cl-incf js2-parse-stmt-count)
8352 js2-statements-per-pause))
8353 (input-pending-p)
8354 (throw 'interrupted t))
8355 (setq pn (js2-statement-helper))
8356 ;; no-side-effects warning check
8357 (unless (js2-node-has-side-effects pn)
8358 (setq end (js2-node-end pn))
8359 (save-excursion
8360 (goto-char end)
8361 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8362 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8363 pn))
8364
8365 ;; These correspond to the switch cases in Parser.statementHelper
8366 (defconst js2-parsers
8367 (let ((parsers (make-vector js2-num-tokens
8368 #'js2-parse-expr-stmt)))
8369 (aset parsers js2-BREAK #'js2-parse-break)
8370 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8371 (aset parsers js2-CONST #'js2-parse-const-var)
8372 (aset parsers js2-CONTINUE #'js2-parse-continue)
8373 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8374 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8375 (aset parsers js2-DO #'js2-parse-do)
8376 (aset parsers js2-EXPORT #'js2-parse-export)
8377 (aset parsers js2-FOR #'js2-parse-for)
8378 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8379 (aset parsers js2-IF #'js2-parse-if)
8380 (aset parsers js2-IMPORT #'js2-parse-import)
8381 (aset parsers js2-LC #'js2-parse-block)
8382 (aset parsers js2-LET #'js2-parse-let-stmt)
8383 (aset parsers js2-NAME #'js2-parse-name-or-label)
8384 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8385 (aset parsers js2-SEMI #'js2-parse-semi)
8386 (aset parsers js2-SWITCH #'js2-parse-switch)
8387 (aset parsers js2-THROW #'js2-parse-throw)
8388 (aset parsers js2-TRY #'js2-parse-try)
8389 (aset parsers js2-VAR #'js2-parse-const-var)
8390 (aset parsers js2-WHILE #'js2-parse-while)
8391 (aset parsers js2-WITH #'js2-parse-with)
8392 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8393 parsers)
8394 "A vector mapping token types to parser functions.")
8395
8396 (defun js2-parse-warn-missing-semi (beg end)
8397 (and js2-mode-show-strict-warnings
8398 js2-strict-missing-semi-warning
8399 (js2-add-strict-warning
8400 "msg.missing.semi" nil
8401 ;; back up to beginning of statement or line
8402 (max beg (save-excursion
8403 (goto-char end)
8404 (point-at-bol)))
8405 end)))
8406
8407 (defconst js2-no-semi-insertion
8408 (list js2-IF
8409 js2-SWITCH
8410 js2-WHILE
8411 js2-DO
8412 js2-FOR
8413 js2-TRY
8414 js2-WITH
8415 js2-LC
8416 js2-ERROR
8417 js2-SEMI
8418 js2-CLASS
8419 js2-FUNCTION
8420 js2-EXPORT)
8421 "List of tokens that don't do automatic semicolon insertion.")
8422
8423 (defconst js2-autoinsert-semi-and-warn
8424 (list js2-ERROR js2-EOF js2-RC))
8425
8426 (defun js2-statement-helper ()
8427 (let* ((tt (js2-get-token))
8428 (first-tt tt)
8429 (parser (if (= tt js2-ERROR)
8430 #'js2-parse-semi
8431 (aref js2-parsers tt)))
8432 pn)
8433 ;; If the statement is set, then it's been told its label by now.
8434 (and js2-labeled-stmt
8435 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8436 (setq js2-labeled-stmt nil))
8437 (setq pn (funcall parser))
8438 ;; Don't do auto semi insertion for certain statement types.
8439 (unless (or (memq first-tt js2-no-semi-insertion)
8440 (js2-labeled-stmt-node-p pn))
8441 (js2-auto-insert-semicolon pn))
8442 pn))
8443
8444 (defun js2-auto-insert-semicolon (pn)
8445 (let* ((tt (js2-get-token))
8446 (pos (js2-node-pos pn)))
8447 (cond
8448 ((= tt js2-SEMI)
8449 ;; extend the node bounds to include the semicolon.
8450 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8451 ((memq tt js2-autoinsert-semi-and-warn)
8452 (js2-unget-token) ; Not ';', do not consume.
8453 ;; Autoinsert ;
8454 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8455 (t
8456 (if (not (js2-token-follows-eol-p (js2-current-token)))
8457 ;; Report error if no EOL or autoinsert ';' otherwise
8458 (js2-report-error "msg.no.semi.stmt")
8459 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8460 (js2-unget-token) ; Not ';', do not consume.
8461 ))))
8462
8463 (defun js2-parse-condition ()
8464 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8465 The parens are discarded and the expression node is returned.
8466 The `pos' field of the return value is set to an absolute position
8467 that must be fixed up by the caller.
8468 Return value is a list (EXPR LP RP), with absolute paren positions."
8469 (let (pn lp rp)
8470 (if (js2-must-match js2-LP "msg.no.paren.cond")
8471 (setq lp (js2-current-token-beg)))
8472 (setq pn (js2-parse-expr))
8473 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8474 (setq rp (js2-current-token-beg)))
8475 ;; Report strict warning on code like "if (a = 7) ..."
8476 (if (and js2-strict-cond-assign-warning
8477 (js2-assign-node-p pn))
8478 (js2-add-strict-warning "msg.equal.as.assign" nil
8479 (js2-node-pos pn)
8480 (+ (js2-node-pos pn)
8481 (js2-node-len pn))))
8482 (list pn lp rp)))
8483
8484 (defun js2-parse-if ()
8485 "Parser for if-statement. Last matched token must be js2-IF."
8486 (let ((pos (js2-current-token-beg))
8487 cond if-true if-false else-pos end pn)
8488 (setq cond (js2-parse-condition)
8489 if-true (js2-parse-statement)
8490 if-false (if (js2-match-token js2-ELSE)
8491 (progn
8492 (setq else-pos (- (js2-current-token-beg) pos))
8493 (js2-parse-statement)))
8494 end (js2-node-end (or if-false if-true))
8495 pn (make-js2-if-node :pos pos
8496 :len (- end pos)
8497 :condition (car cond)
8498 :then-part if-true
8499 :else-part if-false
8500 :else-pos else-pos
8501 :lp (js2-relpos (cl-second cond) pos)
8502 :rp (js2-relpos (cl-third cond) pos)))
8503 (js2-node-add-children pn (car cond) if-true if-false)
8504 pn))
8505
8506 (defun js2-parse-import ()
8507 "Parse import statement. The current token must be js2-IMPORT."
8508 (unless (js2-ast-root-p js2-current-scope)
8509 (js2-report-error "msg.mod.import.decl.at.top.level"))
8510 (let ((beg (js2-current-token-beg)))
8511 (cond ((js2-match-token js2-STRING)
8512 (make-js2-import-node
8513 :pos beg
8514 :len (- (js2-current-token-end) beg)
8515 :module-id (js2-current-token-string)))
8516 (t
8517 (let* ((import-clause (js2-parse-import-clause))
8518 (from-clause (and import-clause (js2-parse-from-clause)))
8519 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8520 (node (make-js2-import-node
8521 :pos beg
8522 :len (- (js2-current-token-end) beg)
8523 :import import-clause
8524 :from from-clause
8525 :module-id module-id)))
8526 (when import-clause
8527 (js2-node-add-children node import-clause))
8528 (when from-clause
8529 (js2-node-add-children node from-clause))
8530 node)))))
8531
8532 (defun js2-parse-import-clause ()
8533 "Parse the bindings in an import statement.
8534 This can take many forms:
8535
8536 ImportedDefaultBinding -> 'foo'
8537 NameSpaceImport -> '* as lib'
8538 NamedImports -> '{foo as bar, bang}'
8539 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8540 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8541
8542 Try to match namespace imports and named imports first because nothing can
8543 come after them. If it is an imported default binding, then it could have named
8544 imports or a namespace import that follows it.
8545 "
8546 (let* ((beg (js2-current-token-beg))
8547 (clause (make-js2-import-clause-node
8548 :pos beg))
8549 (children (list)))
8550 (cond
8551 ((js2-match-token js2-MUL)
8552 (let ((ns-import (js2-parse-namespace-import)))
8553 (when ns-import
8554 (let ((name-node (js2-namespace-import-node-name ns-import)))
8555 (js2-define-symbol
8556 js2-LET (js2-name-node-name name-node) name-node t)))
8557 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8558 (push ns-import children)))
8559 ((js2-match-token js2-LC)
8560 (let ((imports (js2-parse-export-bindings t)))
8561 (setf (js2-import-clause-node-named-imports clause) imports)
8562 (dolist (import imports)
8563 (push import children)
8564 (let ((name-node (js2-export-binding-node-local-name import)))
8565 (when name-node
8566 (js2-define-symbol
8567 js2-LET (js2-name-node-name name-node) name-node t))))))
8568 ((= (js2-peek-token) js2-NAME)
8569 (let ((binding (js2-maybe-parse-export-binding)))
8570 (let ((node-name (js2-export-binding-node-local-name binding)))
8571 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8572 (setf (js2-import-clause-node-default-binding clause) binding)
8573 (push binding children))
8574 (when (js2-match-token js2-COMMA)
8575 (cond
8576 ((js2-match-token js2-MUL)
8577 (let ((ns-import (js2-parse-namespace-import)))
8578 (let ((name-node (js2-namespace-import-node-name ns-import)))
8579 (js2-define-symbol
8580 js2-LET (js2-name-node-name name-node) name-node t))
8581 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8582 (push ns-import children)))
8583 ((js2-match-token js2-LC)
8584 (let ((imports (js2-parse-export-bindings t)))
8585 (setf (js2-import-clause-node-named-imports clause) imports)
8586 (dolist (import imports)
8587 (push import children)
8588 (let ((name-node (js2-export-binding-node-local-name import)))
8589 (when name-node
8590 (js2-define-symbol
8591 js2-LET (js2-name-node-name name-node) name-node t))))))
8592 (t (js2-report-error "msg.syntax")))))
8593 (t (js2-report-error "msg.mod.declaration.after.import")))
8594 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8595 (apply #'js2-node-add-children clause children)
8596 clause))
8597
8598 (defun js2-parse-namespace-import ()
8599 "Parse a namespace import expression such as '* as bar'.
8600 The current token must be js2-MUL."
8601 (let ((beg (js2-current-token-beg)))
8602 (when (js2-must-match js2-NAME "msg.syntax")
8603 (if (equal "as" (js2-current-token-string))
8604 (when (js2-must-match-prop-name "msg.syntax")
8605 (let ((node (make-js2-namespace-import-node
8606 :pos beg
8607 :len (- (js2-current-token-end) beg)
8608 :name (make-js2-name-node
8609 :pos (js2-current-token-beg)
8610 :len (js2-current-token-end)
8611 :name (js2-current-token-string)))))
8612 (js2-node-add-children node (js2-namespace-import-node-name node))
8613 node))
8614 (js2-unget-token)
8615 (js2-report-error "msg.syntax")))))
8616
8617
8618 (defun js2-parse-from-clause ()
8619 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8620 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8621 (let ((beg (js2-current-token-beg)))
8622 (if (equal "from" (js2-current-token-string))
8623 (cond
8624 ((js2-match-token js2-STRING)
8625 (make-js2-from-clause-node
8626 :pos beg
8627 :len (- (js2-current-token-end) beg)
8628 :module-id (js2-current-token-string)
8629 :metadata-p nil))
8630 ((js2-match-token js2-THIS)
8631 (when (js2-must-match-name "msg.mod.spec.after.from")
8632 (if (equal "module" (js2-current-token-string))
8633 (make-js2-from-clause-node
8634 :pos beg
8635 :len (- (js2-current-token-end) beg)
8636 :module-id "this"
8637 :metadata-p t)
8638 (js2-unget-token)
8639 (js2-unget-token)
8640 (js2-report-error "msg.mod.spec.after.from")
8641 nil)))
8642 (t (js2-report-error "msg.mod.spec.after.from") nil))
8643 (js2-unget-token)
8644 (js2-report-error "msg.mod.from.after.import.spec.set")
8645 nil))))
8646
8647 (defun js2-parse-export-bindings (&optional import-p)
8648 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8649 {foo as bar, baz as bang}. The current token must be
8650 js2-LC. Return a lisp list of js2-export-binding-node"
8651 (let ((bindings (list)))
8652 (while
8653 (let ((binding (js2-maybe-parse-export-binding)))
8654 (when binding
8655 (push binding bindings))
8656 (js2-match-token js2-COMMA)))
8657 (when (js2-must-match js2-RC (if import-p
8658 "msg.mod.rc.after.import.spec.list"
8659 "msg.mod.rc.after.export.spec.list"))
8660 (reverse bindings))))
8661
8662 (defun js2-maybe-parse-export-binding ()
8663 "Attempt to parse a binding expression found inside an import/export statement.
8664 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8665 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8666 js2-export-binding-node and consume all the tokens. If it does not match, it
8667 consumes no tokens."
8668 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8669 (beg (js2-current-token-beg))
8670 (extern-name-len (js2-current-token-len))
8671 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8672 (aref js2-kwd-tokens (js2-current-token-type)))))
8673 (if extern-name
8674 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8675 (if (and as (equal "as" (js2-current-token-string)))
8676 (let ((name
8677 (or
8678 (and (js2-match-token js2-DEFAULT) "default")
8679 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8680 (if name
8681 (let ((node (make-js2-export-binding-node
8682 :pos beg
8683 :len (- (js2-current-token-end) beg)
8684 :local-name (make-js2-name-node
8685 :name name
8686 :pos (js2-current-token-beg)
8687 :len (js2-current-token-len))
8688 :extern-name (make-js2-name-node
8689 :name extern-name
8690 :pos beg
8691 :len extern-name-len))))
8692 (js2-node-add-children
8693 node
8694 (js2-export-binding-node-local-name node)
8695 (js2-export-binding-node-extern-name node))
8696 node)
8697 (js2-unget-token)
8698 nil))
8699 (when as (js2-unget-token))
8700 (let* ((name-node (make-js2-name-node
8701 :name (js2-current-token-string)
8702 :pos (js2-current-token-beg)
8703 :len (js2-current-token-len)))
8704 (node (make-js2-export-binding-node
8705 :pos (js2-current-token-beg)
8706 :len (js2-current-token-len)
8707 :local-name name-node
8708 :extern-name name-node)))
8709 (when is-reserved-name
8710 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8711 (js2-node-add-children node name-node)
8712 node)))
8713 nil)))
8714
8715 (defun js2-parse-switch ()
8716 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8717 (let ((pos (js2-current-token-beg))
8718 tt pn discriminant has-default case-expr case-node
8719 case-pos cases stmt lp)
8720 (if (js2-must-match js2-LP "msg.no.paren.switch")
8721 (setq lp (js2-current-token-beg)))
8722 (setq discriminant (js2-parse-expr)
8723 pn (make-js2-switch-node :discriminant discriminant
8724 :pos pos
8725 :lp (js2-relpos lp pos)))
8726 (js2-node-add-children pn discriminant)
8727 (js2-enter-switch pn)
8728 (unwind-protect
8729 (progn
8730 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8731 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8732 (js2-must-match js2-LC "msg.no.brace.switch")
8733 (catch 'break
8734 (while t
8735 (setq tt (js2-next-token)
8736 case-pos (js2-current-token-beg))
8737 (cond
8738 ((= tt js2-RC)
8739 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8740 (throw 'break nil)) ; done
8741 ((= tt js2-CASE)
8742 (setq case-expr (js2-parse-expr))
8743 (js2-must-match js2-COLON "msg.no.colon.case"))
8744 ((= tt js2-DEFAULT)
8745 (if has-default
8746 (js2-report-error "msg.double.switch.default"))
8747 (setq has-default t
8748 case-expr nil)
8749 (js2-must-match js2-COLON "msg.no.colon.case"))
8750 (t
8751 (js2-report-error "msg.bad.switch")
8752 (throw 'break nil)))
8753 (setq case-node (make-js2-case-node :pos case-pos
8754 :len (- (js2-current-token-end) case-pos)
8755 :expr case-expr))
8756 (js2-node-add-children case-node case-expr)
8757 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8758 (/= tt js2-CASE)
8759 (/= tt js2-DEFAULT)
8760 (/= tt js2-EOF))
8761 (setf stmt (js2-parse-statement)
8762 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8763 (js2-block-node-push case-node stmt))
8764 (push case-node cases)))
8765 ;; add cases last, as pushing reverses the order to be correct
8766 (dolist (kid cases)
8767 (js2-node-add-children pn kid)
8768 (push kid (js2-switch-node-cases pn)))
8769 pn) ; return value
8770 (js2-exit-switch))))
8771
8772 (defun js2-parse-while ()
8773 "Parser for while-statement. Last matched token must be js2-WHILE."
8774 (let ((pos (js2-current-token-beg))
8775 (pn (make-js2-while-node))
8776 cond body)
8777 (js2-enter-loop pn)
8778 (unwind-protect
8779 (progn
8780 (setf cond (js2-parse-condition)
8781 (js2-while-node-condition pn) (car cond)
8782 body (js2-parse-statement)
8783 (js2-while-node-body pn) body
8784 (js2-node-len pn) (- (js2-node-end body) pos)
8785 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8786 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8787 (js2-node-add-children pn body (car cond)))
8788 (js2-exit-loop))
8789 pn))
8790
8791 (defun js2-parse-do ()
8792 "Parser for do-statement. Last matched token must be js2-DO."
8793 (let ((pos (js2-current-token-beg))
8794 (pn (make-js2-do-node))
8795 cond body end)
8796 (js2-enter-loop pn)
8797 (unwind-protect
8798 (progn
8799 (setq body (js2-parse-statement))
8800 (js2-must-match js2-WHILE "msg.no.while.do")
8801 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8802 cond (js2-parse-condition)
8803 (js2-do-node-condition pn) (car cond)
8804 (js2-do-node-body pn) body
8805 end js2-ts-cursor
8806 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8807 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8808 (js2-node-add-children pn (car cond) body))
8809 (js2-exit-loop))
8810 ;; Always auto-insert semicolon to follow SpiderMonkey:
8811 ;; It is required by ECMAScript but is ignored by the rest of
8812 ;; world; see bug 238945
8813 (if (js2-match-token js2-SEMI)
8814 (setq end js2-ts-cursor))
8815 (setf (js2-node-len pn) (- end pos))
8816 pn))
8817
8818 (defun js2-parse-export ()
8819 "Parse an export statement.
8820 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8821 expressions should only be either hoistable expressions (function or generator)
8822 or assignment expressions, but there is no checking to enforce that and so it
8823 will parse without error a small subset of
8824 invalid export statements."
8825 (unless (js2-ast-root-p js2-current-scope)
8826 (js2-report-error "msg.mod.export.decl.at.top.level"))
8827 (let ((beg (js2-current-token-beg))
8828 (children (list))
8829 exports-list from-clause declaration default)
8830 (cond
8831 ((js2-match-token js2-MUL)
8832 (setq from-clause (js2-parse-from-clause))
8833 (when from-clause
8834 (push from-clause children)))
8835 ((js2-match-token js2-LC)
8836 (setq exports-list (js2-parse-export-bindings))
8837 (when exports-list
8838 (dolist (export exports-list)
8839 (push export children)))
8840 (when (js2-match-token js2-NAME)
8841 (if (equal "from" (js2-current-token-string))
8842 (progn
8843 (js2-unget-token)
8844 (setq from-clause (js2-parse-from-clause)))
8845 (js2-unget-token))))
8846 ((js2-match-token js2-DEFAULT)
8847 (setq default (js2-parse-expr)))
8848 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8849 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8850 (t
8851 (setq declaration (js2-parse-expr))))
8852 (when from-clause
8853 (push from-clause children))
8854 (when declaration
8855 (push declaration children)
8856 (when (not (js2-function-node-p declaration))
8857 (js2-auto-insert-semicolon declaration)))
8858 (when default
8859 (push default children)
8860 (when (not (js2-function-node-p default))
8861 (js2-auto-insert-semicolon default)))
8862 (let ((node (make-js2-export-node
8863 :pos beg
8864 :len (- (js2-current-token-end) beg)
8865 :exports-list exports-list
8866 :from-clause from-clause
8867 :declaration declaration
8868 :default default)))
8869 (apply #'js2-node-add-children node children)
8870 node)))
8871
8872 (defun js2-parse-for ()
8873 "Parse a for, for-in or for each-in statement.
8874 Last matched token must be js2-FOR."
8875 (let ((for-pos (js2-current-token-beg))
8876 (tmp-scope (make-js2-scope))
8877 pn is-for-each is-for-in-or-of is-for-of
8878 in-pos each-pos tmp-pos
8879 init ; Node init is also foo in 'foo in object'.
8880 cond ; Node cond is also object in 'foo in object'.
8881 incr ; 3rd section of for-loop initializer.
8882 body tt lp rp)
8883 ;; See if this is a for each () instead of just a for ()
8884 (when (js2-match-token js2-NAME)
8885 (if (string= "each" (js2-current-token-string))
8886 (progn
8887 (setq is-for-each t
8888 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8889 (js2-record-face 'font-lock-keyword-face))
8890 (js2-report-error "msg.no.paren.for")))
8891 (if (js2-must-match js2-LP "msg.no.paren.for")
8892 (setq lp (- (js2-current-token-beg) for-pos)))
8893 (setq tt (js2-get-token))
8894 ;; Capture identifiers inside parens. We can't create the node
8895 ;; (and use it as the current scope) until we know its type.
8896 (js2-push-scope tmp-scope)
8897 (unwind-protect
8898 (progn
8899 ;; parse init clause
8900 (let ((js2-in-for-init t)) ; set as dynamic variable
8901 (cond
8902 ((= tt js2-SEMI)
8903 (js2-unget-token)
8904 (setq init (make-js2-empty-expr-node)))
8905 ((or (= tt js2-VAR) (= tt js2-LET))
8906 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8907 (t
8908 (js2-unget-token)
8909 (setq init (js2-parse-expr)))))
8910 (if (or (js2-match-token js2-IN)
8911 (and (>= js2-language-version 200)
8912 (js2-match-contextual-kwd "of")
8913 (setq is-for-of t)))
8914 (setq is-for-in-or-of t
8915 in-pos (- (js2-current-token-beg) for-pos)
8916 ;; scope of iteration target object is not the scope we've created above.
8917 ;; stash current scope temporary.
8918 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8919 (js2-parse-expr))) ; object over which we're iterating
8920 ;; else ordinary for loop - parse cond and incr
8921 (js2-must-match js2-SEMI "msg.no.semi.for")
8922 (setq cond (if (= (js2-peek-token) js2-SEMI)
8923 (make-js2-empty-expr-node) ; no loop condition
8924 (js2-parse-expr)))
8925 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8926 (setq tmp-pos (js2-current-token-end)
8927 incr (if (= (js2-peek-token) js2-RP)
8928 (make-js2-empty-expr-node :pos tmp-pos)
8929 (js2-parse-expr)))))
8930 (js2-pop-scope))
8931 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8932 (setq rp (- (js2-current-token-beg) for-pos)))
8933 (if (not is-for-in-or-of)
8934 (setq pn (make-js2-for-node :init init
8935 :condition cond
8936 :update incr
8937 :lp lp
8938 :rp rp))
8939 ;; cond could be null if 'in obj' got eaten by the init node.
8940 (if (js2-infix-node-p init)
8941 ;; it was (foo in bar) instead of (var foo in bar)
8942 (setq cond (js2-infix-node-right init)
8943 init (js2-infix-node-left init))
8944 (if (and (js2-var-decl-node-p init)
8945 (> (length (js2-var-decl-node-kids init)) 1))
8946 (js2-report-error "msg.mult.index")))
8947 (setq pn (make-js2-for-in-node :iterator init
8948 :object cond
8949 :in-pos in-pos
8950 :foreach-p is-for-each
8951 :each-pos each-pos
8952 :forof-p is-for-of
8953 :lp lp
8954 :rp rp)))
8955 ;; Transplant the declarations.
8956 (setf (js2-scope-symbol-table pn)
8957 (js2-scope-symbol-table tmp-scope))
8958 (unwind-protect
8959 (progn
8960 (js2-enter-loop pn)
8961 ;; We have to parse the body -after- creating the loop node,
8962 ;; so that the loop node appears in the js2-loop-set, allowing
8963 ;; break/continue statements to find the enclosing loop.
8964 (setf body (js2-parse-statement)
8965 (js2-loop-node-body pn) body
8966 (js2-node-pos pn) for-pos
8967 (js2-node-len pn) (- (js2-node-end body) for-pos))
8968 (js2-node-add-children pn init cond incr body))
8969 ;; finally
8970 (js2-exit-loop))
8971 pn))
8972
8973 (defun js2-parse-try ()
8974 "Parse a try statement. Last matched token must be js2-TRY."
8975 (let ((try-pos (js2-current-token-beg))
8976 try-end
8977 try-block
8978 catch-blocks
8979 finally-block
8980 saw-default-catch
8981 peek)
8982 (if (/= (js2-peek-token) js2-LC)
8983 (js2-report-error "msg.no.brace.try"))
8984 (setq try-block (js2-parse-statement)
8985 try-end (js2-node-end try-block)
8986 peek (js2-peek-token))
8987 (cond
8988 ((= peek js2-CATCH)
8989 (while (js2-match-token js2-CATCH)
8990 (let* ((catch-pos (js2-current-token-beg))
8991 (catch-node (make-js2-catch-node :pos catch-pos))
8992 param
8993 guard-kwd
8994 catch-cond
8995 lp rp)
8996 (if saw-default-catch
8997 (js2-report-error "msg.catch.unreachable"))
8998 (if (js2-must-match js2-LP "msg.no.paren.catch")
8999 (setq lp (- (js2-current-token-beg) catch-pos)))
9000 (js2-push-scope catch-node)
9001 (let ((tt (js2-peek-token)))
9002 (cond
9003 ;; Destructuring pattern:
9004 ;; catch ({ message, file }) { ... }
9005 ((or (= tt js2-LB) (= tt js2-LC))
9006 (js2-get-token)
9007 (setq param (js2-parse-destruct-primary-expr))
9008 (js2-define-destruct-symbols param js2-LET nil))
9009 ;; Simple name.
9010 (t
9011 (js2-must-match-name "msg.bad.catchcond")
9012 (setq param (js2-create-name-node))
9013 (js2-define-symbol js2-LET (js2-current-token-string) param)
9014 (js2-check-strict-identifier param))))
9015 ;; Catch condition.
9016 (if (js2-match-token js2-IF)
9017 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
9018 catch-cond (js2-parse-expr))
9019 (setq saw-default-catch t))
9020 (if (js2-must-match js2-RP "msg.bad.catchcond")
9021 (setq rp (- (js2-current-token-beg) catch-pos)))
9022 (js2-must-match js2-LC "msg.no.brace.catchblock")
9023 (js2-parse-statements catch-node)
9024 (if (js2-must-match js2-RC "msg.no.brace.after.body")
9025 (setq try-end (js2-current-token-end)))
9026 (js2-pop-scope)
9027 (setf (js2-node-len catch-node) (- try-end catch-pos)
9028 (js2-catch-node-param catch-node) param
9029 (js2-catch-node-guard-expr catch-node) catch-cond
9030 (js2-catch-node-guard-kwd catch-node) guard-kwd
9031 (js2-catch-node-lp catch-node) lp
9032 (js2-catch-node-rp catch-node) rp)
9033 (js2-node-add-children catch-node param catch-cond)
9034 (push catch-node catch-blocks))))
9035 ((/= peek js2-FINALLY)
9036 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
9037 (js2-node-pos try-block)
9038 (- (setq try-end (js2-node-end try-block))
9039 (js2-node-pos try-block)))))
9040 (when (js2-match-token js2-FINALLY)
9041 (let ((finally-pos (js2-current-token-beg))
9042 (block (js2-parse-statement)))
9043 (setq try-end (js2-node-end block)
9044 finally-block (make-js2-finally-node :pos finally-pos
9045 :len (- try-end finally-pos)
9046 :body block))
9047 (js2-node-add-children finally-block block)))
9048 (let ((pn (make-js2-try-node :pos try-pos
9049 :len (- try-end try-pos)
9050 :try-block try-block
9051 :finally-block finally-block)))
9052 (js2-node-add-children pn try-block finally-block)
9053 ;; Push them onto the try-node, which reverses and corrects their order.
9054 (dolist (cb catch-blocks)
9055 (js2-node-add-children pn cb)
9056 (push cb (js2-try-node-catch-clauses pn)))
9057 pn)))
9058
9059 (defun js2-parse-throw ()
9060 "Parser for throw-statement. Last matched token must be js2-THROW."
9061 (let ((pos (js2-current-token-beg))
9062 expr pn)
9063 (if (= (js2-peek-token-or-eol) js2-EOL)
9064 ;; ECMAScript does not allow new lines before throw expression,
9065 ;; see bug 256617
9066 (js2-report-error "msg.bad.throw.eol"))
9067 (setq expr (js2-parse-expr)
9068 pn (make-js2-throw-node :pos pos
9069 :len (- (js2-node-end expr) pos)
9070 :expr expr))
9071 (js2-node-add-children pn expr)
9072 pn))
9073
9074 (defun js2-match-jump-label-name (label-name)
9075 "If break/continue specified a label, return that label's labeled stmt.
9076 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9077 does not match an existing label, reports an error and returns nil."
9078 (let ((bundle (cdr (assoc label-name js2-label-set))))
9079 (if (null bundle)
9080 (js2-report-error "msg.undef.label"))
9081 bundle))
9082
9083 (defun js2-parse-break ()
9084 "Parser for break-statement. Last matched token must be js2-BREAK."
9085 (let ((pos (js2-current-token-beg))
9086 (end (js2-current-token-end))
9087 break-target ; statement to break from
9088 break-label ; in "break foo", name-node representing the foo
9089 labels ; matching labeled statement to break to
9090 pn)
9091 (when (eq (js2-peek-token-or-eol) js2-NAME)
9092 (js2-get-token)
9093 (setq break-label (js2-create-name-node)
9094 end (js2-node-end break-label)
9095 ;; matchJumpLabelName only matches if there is one
9096 labels (js2-match-jump-label-name (js2-current-token-string))
9097 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9098 (unless (or break-target break-label)
9099 ;; no break target specified - try for innermost enclosing loop/switch
9100 (if (null js2-loop-and-switch-set)
9101 (unless break-label
9102 (js2-report-error "msg.bad.break" nil pos (length "break")))
9103 (setq break-target (car js2-loop-and-switch-set))))
9104 (setq pn (make-js2-break-node :pos pos
9105 :len (- end pos)
9106 :label break-label
9107 :target break-target))
9108 (js2-node-add-children pn break-label) ; but not break-target
9109 pn))
9110
9111 (defun js2-parse-continue ()
9112 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9113 (let ((pos (js2-current-token-beg))
9114 (end (js2-current-token-end))
9115 label ; optional user-specified label, a `js2-name-node'
9116 labels ; current matching labeled stmt, if any
9117 target ; the `js2-loop-node' target of this continue stmt
9118 pn)
9119 (when (= (js2-peek-token-or-eol) js2-NAME)
9120 (js2-get-token)
9121 (setq label (js2-create-name-node)
9122 end (js2-node-end label)
9123 ;; matchJumpLabelName only matches if there is one
9124 labels (js2-match-jump-label-name (js2-current-token-string))))
9125 (cond
9126 ((null labels) ; no current label to go to
9127 (if (null js2-loop-set) ; no loop to continue to
9128 (js2-report-error "msg.continue.outside" nil pos
9129 (length "continue"))
9130 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9131 (t
9132 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9133 (setq target (js2-labeled-stmt-node-stmt labels))
9134 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9135 (setq pn (make-js2-continue-node :pos pos
9136 :len (- end pos)
9137 :label label
9138 :target target))
9139 (js2-node-add-children pn label) ; but not target - it's not our child
9140 pn))
9141
9142 (defun js2-parse-with ()
9143 "Parser for with-statement. Last matched token must be js2-WITH."
9144 (when js2-in-use-strict-directive
9145 (js2-report-error "msg.no.with.strict"))
9146 (let ((pos (js2-current-token-beg))
9147 obj body pn lp rp)
9148 (if (js2-must-match js2-LP "msg.no.paren.with")
9149 (setq lp (js2-current-token-beg)))
9150 (setq obj (js2-parse-expr))
9151 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9152 (setq rp (js2-current-token-beg)))
9153 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9154 (setq body (js2-parse-statement)))
9155 (setq pn (make-js2-with-node :pos pos
9156 :len (- (js2-node-end body) pos)
9157 :object obj
9158 :body body
9159 :lp (js2-relpos lp pos)
9160 :rp (js2-relpos rp pos)))
9161 (js2-node-add-children pn obj body)
9162 pn))
9163
9164 (defun js2-parse-const-var ()
9165 "Parser for var- or const-statement.
9166 Last matched token must be js2-CONST or js2-VAR."
9167 (let ((tt (js2-current-token-type))
9168 (pos (js2-current-token-beg))
9169 expr pn)
9170 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9171 pn (make-js2-expr-stmt-node :pos pos
9172 :len (- (js2-node-end expr) pos)
9173 :expr expr))
9174 (js2-node-add-children pn expr)
9175 pn))
9176
9177 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9178 (let ((pn (make-js2-expr-stmt-node :pos pos
9179 :len (js2-node-len expr)
9180 :type (if (js2-inside-function)
9181 js2-EXPR_VOID
9182 js2-EXPR_RESULT)
9183 :expr expr)))
9184 (if add-child
9185 (js2-node-add-children pn expr))
9186 pn))
9187
9188 (defun js2-parse-let-stmt ()
9189 "Parser for let-statement. Last matched token must be js2-LET."
9190 (let ((pos (js2-current-token-beg))
9191 expr pn)
9192 (if (= (js2-peek-token) js2-LP)
9193 ;; let expression in statement context
9194 (setq expr (js2-parse-let pos 'statement)
9195 pn (js2-wrap-with-expr-stmt pos expr t))
9196 ;; else we're looking at a statement like let x=6, y=7;
9197 (setf expr (js2-parse-variables js2-LET pos)
9198 pn (js2-wrap-with-expr-stmt pos expr t)
9199 (js2-node-type pn) js2-EXPR_RESULT))
9200 pn))
9201
9202 (defun js2-parse-ret-yield ()
9203 (js2-parse-return-or-yield (js2-current-token-type) nil))
9204
9205 (defconst js2-parse-return-stmt-enders
9206 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9207
9208 (defsubst js2-now-all-set (before after mask)
9209 "Return whether or not the bits in the mask have changed to all set.
9210 BEFORE is bits before change, AFTER is bits after change, and MASK is
9211 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9212 but not BEFORE."
9213 (and (/= (logand before mask) mask)
9214 (= (logand after mask) mask)))
9215
9216 (defun js2-parse-return-or-yield (tt expr-context)
9217 (let* ((pos (js2-current-token-beg))
9218 (end (js2-current-token-end))
9219 (before js2-end-flags)
9220 (inside-function (js2-inside-function))
9221 (gen-type (and inside-function (js2-function-node-generator-type
9222 js2-current-script-or-fn)))
9223 e ret name yield-star-p)
9224 (unless inside-function
9225 (js2-report-error (if (eq tt js2-RETURN)
9226 "msg.bad.return"
9227 "msg.bad.yield")))
9228 (when (and inside-function
9229 (eq gen-type 'STAR)
9230 (js2-match-token js2-MUL))
9231 (setq yield-star-p t))
9232 ;; This is ugly, but we don't want to require a semicolon.
9233 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9234 (setq e (js2-parse-expr)
9235 end (js2-node-end e)))
9236 (cond
9237 ((eq tt js2-RETURN)
9238 (js2-set-flag js2-end-flags (if (null e)
9239 js2-end-returns
9240 js2-end-returns-value))
9241 (setq ret (make-js2-return-node :pos pos
9242 :len (- end pos)
9243 :retval e))
9244 (js2-node-add-children ret e)
9245 ;; See if we need a strict mode warning.
9246 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9247 ;; more thorough and accurate than this before/after flag check.
9248 ;; E.g. if there's a finally-block that always returns, we shouldn't
9249 ;; show a warning generated by inconsistent returns in the catch blocks.
9250 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9251 ;; so we know which returns/yields to highlight, and we should get rid of
9252 ;; all the checking in `js2-parse-return-or-yield'.
9253 (if (and js2-strict-inconsistent-return-warning
9254 (js2-now-all-set before js2-end-flags
9255 (logior js2-end-returns js2-end-returns-value)))
9256 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9257 ((eq gen-type 'COMPREHENSION)
9258 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9259 ;; like SpiderMonkey does.
9260 (js2-report-error "msg.syntax" nil pos 5))
9261 (t
9262 (setq ret (make-js2-yield-node :pos pos
9263 :len (- end pos)
9264 :value e
9265 :star-p yield-star-p))
9266 (js2-node-add-children ret e)
9267 (unless expr-context
9268 (setq e ret
9269 ret (js2-wrap-with-expr-stmt pos e t))
9270 (js2-set-requires-activation)
9271 (js2-set-is-generator))))
9272 ;; see if we are mixing yields and value returns.
9273 (when (and inside-function
9274 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9275 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9276 'LEGACY))
9277 (setq name (js2-function-name js2-current-script-or-fn))
9278 (if (zerop (length name))
9279 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9280 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9281 ret))
9282
9283 (defun js2-parse-debugger ()
9284 (make-js2-keyword-node :type js2-DEBUGGER))
9285
9286 (defun js2-parse-block ()
9287 "Parser for a curly-delimited statement block.
9288 Last token matched must be `js2-LC'."
9289 (let ((pos (js2-current-token-beg))
9290 (pn (make-js2-scope)))
9291 (js2-push-scope pn)
9292 (unwind-protect
9293 (progn
9294 (js2-parse-statements pn)
9295 (js2-must-match js2-RC "msg.no.brace.block")
9296 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9297 (js2-pop-scope))
9298 pn))
9299
9300 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9301 (defun js2-parse-semi ()
9302 "Parse a statement or handle an error.
9303 Current token type is `js2-SEMI' or `js2-ERROR'."
9304 (let ((tt (js2-current-token-type)) pos len)
9305 (if (eq tt js2-SEMI)
9306 (make-js2-empty-expr-node :len 1)
9307 (setq pos (js2-current-token-beg)
9308 len (- (js2-current-token-end) pos))
9309 (js2-report-error "msg.syntax" nil pos len)
9310 (make-js2-error-node :pos pos :len len))))
9311
9312 (defun js2-parse-default-xml-namespace ()
9313 "Parse a `default xml namespace = <expr>' e4x statement."
9314 (let ((pos (js2-current-token-beg))
9315 end len expr unary)
9316 (js2-must-have-xml)
9317 (js2-set-requires-activation)
9318 (setq len (- js2-ts-cursor pos))
9319 (unless (and (js2-match-token js2-NAME)
9320 (string= (js2-current-token-string) "xml"))
9321 (js2-report-error "msg.bad.namespace" nil pos len))
9322 (unless (and (js2-match-token js2-NAME)
9323 (string= (js2-current-token-string) "namespace"))
9324 (js2-report-error "msg.bad.namespace" nil pos len))
9325 (unless (js2-match-token js2-ASSIGN)
9326 (js2-report-error "msg.bad.namespace" nil pos len))
9327 (setq expr (js2-parse-expr)
9328 end (js2-node-end expr)
9329 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9330 :pos pos
9331 :len (- end pos)
9332 :operand expr))
9333 (js2-node-add-children unary expr)
9334 (make-js2-expr-stmt-node :pos pos
9335 :len (- end pos)
9336 :expr unary)))
9337
9338 (defun js2-record-label (label bundle)
9339 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9340 (js2-get-token)
9341 (let ((name (js2-label-node-name label))
9342 labeled-stmt
9343 dup)
9344 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9345 ;; flag both labels if possible when used in editing mode
9346 (if (and js2-parse-ide-mode
9347 (setq dup (js2-get-label-by-name labeled-stmt name)))
9348 (js2-report-error "msg.dup.label" nil
9349 (js2-node-abs-pos dup) (js2-node-len dup)))
9350 (js2-report-error "msg.dup.label" nil
9351 (js2-node-pos label) (js2-node-len label)))
9352 (js2-labeled-stmt-node-add-label bundle label)
9353 (js2-node-add-children bundle label)
9354 ;; Add one reference to the bundle per label in `js2-label-set'
9355 (push (cons name bundle) js2-label-set)))
9356
9357 (defun js2-parse-name-or-label ()
9358 "Parser for identifier or label. Last token matched must be js2-NAME.
9359 Called when we found a name in a statement context. If it's a label, we gather
9360 up any following labels and the next non-label statement into a
9361 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9362 expression and return it wrapped in a `js2-expr-stmt-node'."
9363 (let ((pos (js2-current-token-beg))
9364 expr stmt bundle
9365 (continue t))
9366 ;; set check for label and call down to `js2-parse-primary-expr'
9367 (setq expr (js2-maybe-parse-label))
9368 (if (null expr)
9369 ;; Parse the non-label expression and wrap with expression stmt.
9370 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9371 ;; else parsed a label
9372 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9373 (js2-record-label expr bundle)
9374 ;; look for more labels
9375 (while (and continue (= (js2-get-token) js2-NAME))
9376 (if (setq expr (js2-maybe-parse-label))
9377 (js2-record-label expr bundle)
9378 (setq expr (js2-parse-expr)
9379 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9380 continue nil)
9381 (js2-auto-insert-semicolon stmt)))
9382 ;; no more labels; now parse the labeled statement
9383 (unwind-protect
9384 (unless stmt
9385 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9386 (js2-unget-token)
9387 (setq stmt (js2-statement-helper))))
9388 ;; remove the labels for this statement from the global set
9389 (dolist (label (js2-labeled-stmt-node-labels bundle))
9390 (setq js2-label-set (remove label js2-label-set))))
9391 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9392 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9393 (js2-node-add-children bundle stmt)
9394 bundle)))
9395
9396 (defun js2-maybe-parse-label ()
9397 (cl-assert (= (js2-current-token-type) js2-NAME))
9398 (let (label-pos
9399 (next-tt (js2-get-token))
9400 (label-end (js2-current-token-end)))
9401 ;; Do not consume colon, it is used as unwind indicator
9402 ;; to return to statementHelper.
9403 (js2-unget-token)
9404 (if (= next-tt js2-COLON)
9405 (prog2
9406 (setq label-pos (js2-current-token-beg))
9407 (make-js2-label-node :pos label-pos
9408 :len (- label-end label-pos)
9409 :name (js2-current-token-string))
9410 (js2-set-face label-pos
9411 label-end
9412 'font-lock-variable-name-face 'record))
9413 ;; Backtrack from the name token, too.
9414 (js2-unget-token)
9415 nil)))
9416
9417 (defun js2-parse-expr-stmt ()
9418 "Default parser in statement context, if no recognized statement found."
9419 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9420 (progn
9421 (js2-unget-token)
9422 (js2-parse-expr)) t))
9423
9424 (defun js2-parse-variables (decl-type pos)
9425 "Parse a comma-separated list of variable declarations.
9426 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9427
9428 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9429 For 'var' or 'const', the keyword should be the token last scanned.
9430
9431 POS is the position where the node should start. It's sometimes the
9432 var/const/let keyword, and other times the beginning of the first token
9433 in the first variable declaration.
9434
9435 Returns the parsed `js2-var-decl-node' expression node."
9436 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9437 :pos pos))
9438 destructuring kid-pos tt init name end nbeg nend vi
9439 (continue t))
9440 ;; Example:
9441 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9442 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9443 ;; var {a, b} = baz;
9444 (while continue
9445 (setq destructuring nil
9446 name nil
9447 tt (js2-get-token)
9448 kid-pos (js2-current-token-beg)
9449 end (js2-current-token-end)
9450 init nil)
9451 (if (or (= tt js2-LB) (= tt js2-LC))
9452 ;; Destructuring assignment, e.g., var [a, b] = ...
9453 (setq destructuring (js2-parse-destruct-primary-expr)
9454 end (js2-node-end destructuring))
9455 ;; Simple variable name
9456 (js2-unget-token)
9457 (when (js2-must-match-name "msg.bad.var")
9458 (setq name (js2-create-name-node)
9459 nbeg (js2-current-token-beg)
9460 nend (js2-current-token-end)
9461 end nend)
9462 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9463 (js2-check-strict-identifier name)))
9464 (when (js2-match-token js2-ASSIGN)
9465 (setq init (js2-parse-assign-expr)
9466 end (js2-node-end init))
9467 (js2-record-imenu-functions init name))
9468 (when name
9469 (js2-set-face nbeg nend (if (js2-function-node-p init)
9470 'font-lock-function-name-face
9471 'font-lock-variable-name-face)
9472 'record))
9473 (setq vi (make-js2-var-init-node :pos kid-pos
9474 :len (- end kid-pos)
9475 :type decl-type))
9476 (if destructuring
9477 (progn
9478 (if (and (null init) (not js2-in-for-init))
9479 (js2-report-error "msg.destruct.assign.no.init"))
9480 (js2-define-destruct-symbols destructuring
9481 decl-type
9482 'font-lock-variable-name-face)
9483 (setf (js2-var-init-node-target vi) destructuring))
9484 (setf (js2-var-init-node-target vi) name))
9485 (setf (js2-var-init-node-initializer vi) init)
9486 (js2-node-add-children vi name destructuring init)
9487 (js2-block-node-push result vi)
9488 (unless (js2-match-token js2-COMMA)
9489 (setq continue nil)))
9490 (setf (js2-node-len result) (- end pos))
9491 result))
9492
9493 (defun js2-parse-let (pos &optional stmt-p)
9494 "Parse a let expression or statement.
9495 A let-expression is of the form `let (vars) expr'.
9496 A let-statement is of the form `let (vars) {statements}'.
9497 The third form of let is a variable declaration list, handled
9498 by `js2-parse-variables'."
9499 (let ((pn (make-js2-let-node :pos pos))
9500 beg vars body)
9501 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9502 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9503 (js2-push-scope pn)
9504 (unwind-protect
9505 (progn
9506 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9507 (if (js2-must-match js2-RP "msg.no.paren.let")
9508 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9509 (if (and stmt-p (js2-match-token js2-LC))
9510 ;; let statement
9511 (progn
9512 (setf beg (js2-current-token-beg) ; position stmt at LC
9513 body (js2-parse-statements))
9514 (js2-must-match js2-RC "msg.no.curly.let")
9515 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9516 (js2-node-len pn) (- (js2-current-token-end) pos)
9517 (js2-let-node-body pn) body
9518 (js2-node-type pn) js2-LET))
9519 ;; let expression
9520 (setf body (js2-parse-expr)
9521 (js2-node-len pn) (- (js2-node-end body) pos)
9522 (js2-let-node-body pn) body))
9523 (setf (js2-let-node-vars pn) vars)
9524 (js2-node-add-children pn vars body))
9525 (js2-pop-scope))
9526 pn))
9527
9528 (defun js2-define-new-symbol (decl-type name node &optional scope)
9529 (js2-scope-put-symbol (or scope js2-current-scope)
9530 name
9531 (make-js2-symbol decl-type name node)))
9532
9533 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9534 "Define a symbol in the current scope.
9535 If NODE is non-nil, it is the AST node associated with the symbol."
9536 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9537 (symbol (if defining-scope
9538 (js2-scope-get-symbol defining-scope name)))
9539 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9540 (pos (if node (js2-node-abs-pos node)))
9541 (len (if node (js2-node-len node))))
9542 (cond
9543 ((and symbol ; already defined
9544 (or (if js2-in-use-strict-directive
9545 ;; two const-bound vars in this block have same name
9546 (and (= sdt js2-CONST)
9547 (eq defining-scope js2-current-scope))
9548 (or (= sdt js2-CONST) ; old version is const
9549 (= decl-type js2-CONST))) ; new version is const
9550 ;; two let-bound vars in this block have same name
9551 (and (= sdt js2-LET)
9552 (eq defining-scope js2-current-scope))))
9553 (js2-report-error
9554 (cond
9555 ((= sdt js2-CONST) "msg.const.redecl")
9556 ((= sdt js2-LET) "msg.let.redecl")
9557 ((= sdt js2-VAR) "msg.var.redecl")
9558 ((= sdt js2-FUNCTION) "msg.function.redecl")
9559 (t "msg.parm.redecl"))
9560 name pos len))
9561 ((or (= decl-type js2-LET)
9562 ;; strict mode const is scoped to the current LexicalEnvironment
9563 (and js2-in-use-strict-directive
9564 (= decl-type js2-CONST)))
9565 (if (and (= decl-type js2-LET)
9566 (not ignore-not-in-block)
9567 (or (= (js2-node-type js2-current-scope) js2-IF)
9568 (js2-loop-node-p js2-current-scope)))
9569 (js2-report-error "msg.let.decl.not.in.block")
9570 (js2-define-new-symbol decl-type name node)))
9571 ((or (= decl-type js2-VAR)
9572 (= decl-type js2-FUNCTION)
9573 ;; sloppy mode const is scoped to the current VariableEnvironment
9574 (and (not js2-in-use-strict-directive)
9575 (= decl-type js2-CONST)))
9576 (if symbol
9577 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9578 (js2-add-strict-warning "msg.var.redecl" name)
9579 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9580 (js2-add-strict-warning "msg.var.hides.arg" name)))
9581 (js2-define-new-symbol decl-type name node
9582 js2-current-script-or-fn)))
9583 ((= decl-type js2-LP)
9584 (if symbol
9585 ;; must be duplicate parameter. Second parameter hides the
9586 ;; first, so go ahead and add the second pararameter
9587 (js2-report-warning "msg.dup.parms" name))
9588 (js2-define-new-symbol decl-type name node))
9589 (t (js2-code-bug)))))
9590
9591 (defun js2-parse-paren-expr-or-generator-comp ()
9592 (let ((px-pos (js2-current-token-beg)))
9593 (cond
9594 ((and (>= js2-language-version 200)
9595 (js2-match-token js2-FOR))
9596 (js2-parse-generator-comp px-pos))
9597 ((and (>= js2-language-version 200)
9598 (js2-match-token js2-RP))
9599 ;; Not valid expression syntax, but this is valid in an arrow
9600 ;; function with no params: () => body.
9601 (if (eq (js2-peek-token) js2-ARROW)
9602 ;; Return whatever, it will hopefully be rewinded and
9603 ;; reparsed when we reach the =>.
9604 (make-js2-keyword-node :type js2-NULL)
9605 (js2-report-error "msg.syntax")
9606 (make-js2-error-node)))
9607 (t
9608 (let* ((js2-in-for-init nil)
9609 (expr (js2-parse-expr))
9610 (pn (make-js2-paren-node :pos px-pos
9611 :expr expr)))
9612 (js2-node-add-children pn (js2-paren-node-expr pn))
9613 (js2-must-match js2-RP "msg.no.paren")
9614 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9615 pn)))))
9616
9617 (defun js2-parse-expr (&optional oneshot)
9618 (let* ((pn (js2-parse-assign-expr))
9619 (pos (js2-node-pos pn))
9620 left
9621 right
9622 op-pos)
9623 (while (and (not oneshot)
9624 (js2-match-token js2-COMMA))
9625 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9626 (if (= (js2-peek-token) js2-YIELD)
9627 (js2-report-error "msg.yield.parenthesized"))
9628 (setq right (js2-parse-assign-expr)
9629 left pn
9630 pn (make-js2-infix-node :type js2-COMMA
9631 :pos pos
9632 :len (- js2-ts-cursor pos)
9633 :op-pos op-pos
9634 :left left
9635 :right right))
9636 (js2-node-add-children pn left right))
9637 pn))
9638
9639 (defun js2-parse-assign-expr ()
9640 (let ((tt (js2-get-token))
9641 (pos (js2-current-token-beg))
9642 pn left right op-pos
9643 ts-state recorded-identifiers parsed-errors)
9644 (if (= tt js2-YIELD)
9645 (js2-parse-return-or-yield tt t)
9646 ;; Save the tokenizer state in case we find an arrow function
9647 ;; and have to rewind.
9648 (setq ts-state (make-js2-ts-state)
9649 recorded-identifiers js2-recorded-identifiers
9650 parsed-errors js2-parsed-errors)
9651 ;; not yield - parse assignment expression
9652 (setq pn (js2-parse-cond-expr)
9653 tt (js2-get-token))
9654 (cond
9655 ((and (<= js2-first-assign tt)
9656 (<= tt js2-last-assign))
9657 ;; tt express assignment (=, |=, ^=, ..., %=)
9658 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9659 left pn)
9660 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9661 ;; care about assignment to strict variable names.
9662 (when (js2-name-node-p left)
9663 (js2-check-strict-identifier left))
9664 (setq right (js2-parse-assign-expr)
9665 pn (make-js2-assign-node :type tt
9666 :pos pos
9667 :len (- (js2-node-end right) pos)
9668 :op-pos op-pos
9669 :left left
9670 :right right))
9671 (when js2-parse-ide-mode
9672 (js2-highlight-assign-targets pn left right)
9673 (js2-record-imenu-functions right left))
9674 ;; do this last so ide checks above can use absolute positions
9675 (js2-node-add-children pn left right))
9676 ((and (= tt js2-ARROW)
9677 (>= js2-language-version 200))
9678 (js2-ts-seek ts-state)
9679 (setq js2-recorded-identifiers recorded-identifiers
9680 js2-parsed-errors parsed-errors)
9681 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9682 (t
9683 (js2-unget-token)))
9684 pn)))
9685
9686 (defun js2-parse-cond-expr ()
9687 (let ((pos (js2-current-token-beg))
9688 (pn (js2-parse-or-expr))
9689 test-expr
9690 if-true
9691 if-false
9692 q-pos
9693 c-pos)
9694 (when (js2-match-token js2-HOOK)
9695 (setq q-pos (- (js2-current-token-beg) pos)
9696 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9697 (js2-must-match js2-COLON "msg.no.colon.cond")
9698 (setq c-pos (- (js2-current-token-beg) pos)
9699 if-false (js2-parse-assign-expr)
9700 test-expr pn
9701 pn (make-js2-cond-node :pos pos
9702 :len (- (js2-node-end if-false) pos)
9703 :test-expr test-expr
9704 :true-expr if-true
9705 :false-expr if-false
9706 :q-pos q-pos
9707 :c-pos c-pos))
9708 (js2-node-add-children pn test-expr if-true if-false))
9709 pn))
9710
9711 (defun js2-make-binary (type left parser)
9712 "Helper for constructing a binary-operator AST node.
9713 LEFT is the left-side-expression, already parsed, and the
9714 binary operator should have just been matched.
9715 PARSER is a function to call to parse the right operand,
9716 or a `js2-node' struct if it has already been parsed.
9717 FIXME: The latter option is unused?"
9718 (let* ((pos (js2-node-pos left))
9719 (op-pos (- (js2-current-token-beg) pos))
9720 (right (if (js2-node-p parser)
9721 parser
9722 (js2-get-token)
9723 (funcall parser)))
9724 (pn (make-js2-infix-node :type type
9725 :pos pos
9726 :len (- (js2-node-end right) pos)
9727 :op-pos op-pos
9728 :left left
9729 :right right)))
9730 (js2-node-add-children pn left right)
9731 pn))
9732
9733 (defun js2-parse-or-expr ()
9734 (let ((pn (js2-parse-and-expr)))
9735 (when (js2-match-token js2-OR)
9736 (setq pn (js2-make-binary js2-OR
9737 pn
9738 'js2-parse-or-expr)))
9739 pn))
9740
9741 (defun js2-parse-and-expr ()
9742 (let ((pn (js2-parse-bit-or-expr)))
9743 (when (js2-match-token js2-AND)
9744 (setq pn (js2-make-binary js2-AND
9745 pn
9746 'js2-parse-and-expr)))
9747 pn))
9748
9749 (defun js2-parse-bit-or-expr ()
9750 (let ((pn (js2-parse-bit-xor-expr)))
9751 (while (js2-match-token js2-BITOR)
9752 (setq pn (js2-make-binary js2-BITOR
9753 pn
9754 'js2-parse-bit-xor-expr)))
9755 pn))
9756
9757 (defun js2-parse-bit-xor-expr ()
9758 (let ((pn (js2-parse-bit-and-expr)))
9759 (while (js2-match-token js2-BITXOR)
9760 (setq pn (js2-make-binary js2-BITXOR
9761 pn
9762 'js2-parse-bit-and-expr)))
9763 pn))
9764
9765 (defun js2-parse-bit-and-expr ()
9766 (let ((pn (js2-parse-eq-expr)))
9767 (while (js2-match-token js2-BITAND)
9768 (setq pn (js2-make-binary js2-BITAND
9769 pn
9770 'js2-parse-eq-expr)))
9771 pn))
9772
9773 (defconst js2-parse-eq-ops
9774 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9775
9776 (defun js2-parse-eq-expr ()
9777 (let ((pn (js2-parse-rel-expr))
9778 tt)
9779 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9780 (setq pn (js2-make-binary tt
9781 pn
9782 'js2-parse-rel-expr)))
9783 (js2-unget-token)
9784 pn))
9785
9786 (defconst js2-parse-rel-ops
9787 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9788
9789 (defun js2-parse-rel-expr ()
9790 (let ((pn (js2-parse-shift-expr))
9791 (continue t)
9792 tt)
9793 (while continue
9794 (setq tt (js2-get-token))
9795 (cond
9796 ((and js2-in-for-init (= tt js2-IN))
9797 (js2-unget-token)
9798 (setq continue nil))
9799 ((memq tt js2-parse-rel-ops)
9800 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9801 (t
9802 (js2-unget-token)
9803 (setq continue nil))))
9804 pn))
9805
9806 (defconst js2-parse-shift-ops
9807 (list js2-LSH js2-URSH js2-RSH))
9808
9809 (defun js2-parse-shift-expr ()
9810 (let ((pn (js2-parse-add-expr))
9811 tt
9812 (continue t))
9813 (while continue
9814 (setq tt (js2-get-token))
9815 (if (memq tt js2-parse-shift-ops)
9816 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9817 (js2-unget-token)
9818 (setq continue nil)))
9819 pn))
9820
9821 (defun js2-parse-add-expr ()
9822 (let ((pn (js2-parse-mul-expr))
9823 tt
9824 (continue t))
9825 (while continue
9826 (setq tt (js2-get-token))
9827 (if (or (= tt js2-ADD) (= tt js2-SUB))
9828 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9829 (js2-unget-token)
9830 (setq continue nil)))
9831 pn))
9832
9833 (defconst js2-parse-mul-ops
9834 (list js2-MUL js2-DIV js2-MOD))
9835
9836 (defun js2-parse-mul-expr ()
9837 (let ((pn (js2-parse-unary-expr))
9838 tt
9839 (continue t))
9840 (while continue
9841 (setq tt (js2-get-token))
9842 (if (memq tt js2-parse-mul-ops)
9843 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9844 (js2-unget-token)
9845 (setq continue nil)))
9846 pn))
9847
9848 (defun js2-make-unary (type parser &rest args)
9849 "Make a unary node of type TYPE.
9850 PARSER is either a node (for postfix operators) or a function to call
9851 to parse the operand (for prefix operators)."
9852 (let* ((pos (js2-current-token-beg))
9853 (postfix (js2-node-p parser))
9854 (expr (if postfix
9855 parser
9856 (apply parser args)))
9857 end
9858 pn)
9859 (if postfix ; e.g. i++
9860 (setq pos (js2-node-pos expr)
9861 end (js2-current-token-end))
9862 (setq end (js2-node-end expr)))
9863 (setq pn (make-js2-unary-node :type type
9864 :pos pos
9865 :len (- end pos)
9866 :operand expr))
9867 (js2-node-add-children pn expr)
9868 pn))
9869
9870 (defconst js2-incrementable-node-types
9871 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9872 "Node types that can be the operand of a ++ or -- operator.")
9873
9874 (defun js2-check-bad-inc-dec (tt beg end unary)
9875 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9876 js2-incrementable-node-types)
9877 (js2-report-error (if (= tt js2-INC)
9878 "msg.bad.incr"
9879 "msg.bad.decr")
9880 nil beg (- end beg))))
9881
9882 (defun js2-parse-unary-expr ()
9883 (let ((tt (js2-current-token-type))
9884 pn expr beg end)
9885 (cond
9886 ((or (= tt js2-VOID)
9887 (= tt js2-NOT)
9888 (= tt js2-BITNOT)
9889 (= tt js2-TYPEOF))
9890 (js2-get-token)
9891 (js2-make-unary tt 'js2-parse-unary-expr))
9892 ((= tt js2-ADD)
9893 (js2-get-token)
9894 ;; Convert to special POS token in decompiler and parse tree
9895 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9896 ((= tt js2-SUB)
9897 (js2-get-token)
9898 ;; Convert to special NEG token in decompiler and parse tree
9899 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9900 ((or (= tt js2-INC)
9901 (= tt js2-DEC))
9902 (js2-get-token)
9903 (prog1
9904 (setq beg (js2-current-token-beg)
9905 end (js2-current-token-end)
9906 expr (js2-make-unary tt 'js2-parse-member-expr t))
9907 (js2-check-bad-inc-dec tt beg end expr)))
9908 ((= tt js2-DELPROP)
9909 (js2-get-token)
9910 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9911 ((= tt js2-ERROR)
9912 (js2-get-token)
9913 (make-js2-error-node)) ; try to continue
9914 ((and (= tt js2-LT)
9915 js2-compiler-xml-available)
9916 ;; XML stream encountered in expression.
9917 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9918 (t
9919 (setq pn (js2-parse-member-expr t)
9920 ;; Don't look across a newline boundary for a postfix incop.
9921 tt (js2-peek-token-or-eol))
9922 (when (or (= tt js2-INC) (= tt js2-DEC))
9923 (js2-get-token)
9924 (setf expr pn
9925 pn (js2-make-unary tt expr))
9926 (js2-node-set-prop pn 'postfix t)
9927 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9928 pn))))
9929
9930 (defun js2-parse-xml-initializer ()
9931 "Parse an E4X XML initializer.
9932 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9933 Then I'll postprocess the result, depending on whether we're in IDE
9934 mode or codegen mode, and generate the appropriate rewritten AST.
9935 IDE mode uses a rich AST that models the XML structure. Codegen mode
9936 just concatenates everything and makes a new XML or XMLList out of it."
9937 (let ((tt (js2-get-first-xml-token))
9938 pn-xml pn expr kids expr-pos
9939 (continue t)
9940 (first-token t))
9941 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9942 (js2-report-error "msg.syntax"))
9943 (setq pn-xml (make-js2-xml-node))
9944 (while continue
9945 (if first-token
9946 (setq first-token nil)
9947 (setq tt (js2-get-next-xml-token)))
9948 (cond
9949 ;; js2-XML means we found a {expr} in the XML stream.
9950 ;; The token string is the XML up to the left-curly.
9951 ((= tt js2-XML)
9952 (push (make-js2-string-node :pos (js2-current-token-beg)
9953 :len (- js2-ts-cursor (js2-current-token-beg)))
9954 kids)
9955 (js2-must-match js2-LC "msg.syntax")
9956 (setq expr-pos js2-ts-cursor
9957 expr (if (eq (js2-peek-token) js2-RC)
9958 (make-js2-empty-expr-node :pos expr-pos)
9959 (js2-parse-expr)))
9960 (js2-must-match js2-RC "msg.syntax")
9961 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9962 :len (js2-node-len expr)
9963 :expr expr))
9964 (js2-node-add-children pn expr)
9965 (push pn kids))
9966 ;; a js2-XMLEND token means we hit the final close-tag.
9967 ((= tt js2-XMLEND)
9968 (push (make-js2-string-node :pos (js2-current-token-beg)
9969 :len (- js2-ts-cursor (js2-current-token-beg)))
9970 kids)
9971 (dolist (kid (nreverse kids))
9972 (js2-block-node-push pn-xml kid))
9973 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9974 (js2-node-pos pn-xml))
9975 continue nil))
9976 (t
9977 (js2-report-error "msg.syntax")
9978 (setq continue nil))))
9979 pn-xml))
9980
9981
9982 (defun js2-parse-argument-list ()
9983 "Parse an argument list and return it as a Lisp list of nodes.
9984 Returns the list in reverse order. Consumes the right-paren token."
9985 (let (result)
9986 (unless (js2-match-token js2-RP)
9987 (cl-loop do
9988 (let ((tt (js2-get-token)))
9989 (if (= tt js2-YIELD)
9990 (js2-report-error "msg.yield.parenthesized"))
9991 (if (and (= tt js2-TRIPLEDOT)
9992 (>= js2-language-version 200))
9993 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9994 (js2-unget-token)
9995 (push (js2-parse-assign-expr) result)))
9996 while
9997 (js2-match-token js2-COMMA))
9998 (js2-must-match js2-RP "msg.no.paren.arg")
9999 result)))
10000
10001 (defun js2-parse-member-expr (&optional allow-call-syntax)
10002 (let ((tt (js2-current-token-type))
10003 pn pos target args beg end init)
10004 (if (/= tt js2-NEW)
10005 (setq pn (js2-parse-primary-expr))
10006 ;; parse a 'new' expression
10007 (js2-get-token)
10008 (setq pos (js2-current-token-beg)
10009 beg pos
10010 target (js2-parse-member-expr)
10011 end (js2-node-end target)
10012 pn (make-js2-new-node :pos pos
10013 :target target
10014 :len (- end pos)))
10015 (js2-highlight-function-call (js2-current-token))
10016 (js2-node-add-children pn target)
10017 (when (js2-match-token js2-LP)
10018 ;; Add the arguments to pn, if any are supplied.
10019 (setf beg pos ; start of "new" keyword
10020 pos (js2-current-token-beg)
10021 args (nreverse (js2-parse-argument-list))
10022 (js2-new-node-args pn) args
10023 end (js2-current-token-end)
10024 (js2-new-node-lp pn) (- pos beg)
10025 (js2-new-node-rp pn) (- end 1 beg))
10026 (apply #'js2-node-add-children pn args))
10027 (when (and js2-allow-rhino-new-expr-initializer
10028 (js2-match-token js2-LC))
10029 (setf init (js2-parse-object-literal)
10030 end (js2-node-end init)
10031 (js2-new-node-initializer pn) init)
10032 (js2-node-add-children pn init))
10033 (setf (js2-node-len pn) (- end beg))) ; end outer if
10034 (js2-parse-member-expr-tail allow-call-syntax pn)))
10035
10036 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
10037 "Parse a chain of property/array accesses or function calls.
10038 Includes parsing for E4X operators like `..' and `.@'.
10039 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
10040 Returns an expression tree that includes PN, the parent node."
10041 (let (tt
10042 (continue t))
10043 (while continue
10044 (setq tt (js2-get-token))
10045 (cond
10046 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
10047 (setq pn (js2-parse-property-access tt pn)))
10048 ((= tt js2-DOTQUERY)
10049 (setq pn (js2-parse-dot-query pn)))
10050 ((= tt js2-LB)
10051 (setq pn (js2-parse-element-get pn)))
10052 ((= tt js2-LP)
10053 (js2-unget-token)
10054 (if allow-call-syntax
10055 (setq pn (js2-parse-function-call pn))
10056 (setq continue nil)))
10057 ((= tt js2-TEMPLATE_HEAD)
10058 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
10059 ((= tt js2-NO_SUBS_TEMPLATE)
10060 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
10061 (t
10062 (js2-unget-token)
10063 (setq continue nil))))
10064 (if (>= js2-highlight-level 2)
10065 (js2-parse-highlight-member-expr-node pn))
10066 pn))
10067
10068 (defun js2-parse-tagged-template (tag-node tpl-node)
10069 "Parse tagged template expression."
10070 (let* ((beg (js2-node-pos tag-node))
10071 (pn (make-js2-tagged-template-node :beg beg
10072 :len (- (js2-current-token-end) beg)
10073 :tag tag-node
10074 :template tpl-node)))
10075 (js2-node-add-children pn tag-node tpl-node)
10076 pn))
10077
10078 (defun js2-parse-dot-query (pn)
10079 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10080 Last token parsed must be `js2-DOTQUERY'."
10081 (let ((pos (js2-node-pos pn))
10082 op-pos expr end)
10083 (js2-must-have-xml)
10084 (js2-set-requires-activation)
10085 (setq op-pos (js2-current-token-beg)
10086 expr (js2-parse-expr)
10087 end (js2-node-end expr)
10088 pn (make-js2-xml-dot-query-node :left pn
10089 :pos pos
10090 :op-pos op-pos
10091 :right expr))
10092 (js2-node-add-children pn
10093 (js2-xml-dot-query-node-left pn)
10094 (js2-xml-dot-query-node-right pn))
10095 (if (js2-must-match js2-RP "msg.no.paren")
10096 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10097 end (js2-current-token-end)))
10098 (setf (js2-node-len pn) (- end pos))
10099 pn))
10100
10101 (defun js2-parse-element-get (pn)
10102 "Parse an element-get expression, e.g. foo[bar].
10103 Last token parsed must be `js2-RB'."
10104 (let ((lb (js2-current-token-beg))
10105 (pos (js2-node-pos pn))
10106 rb expr)
10107 (setq expr (js2-parse-expr))
10108 (if (js2-must-match js2-RB "msg.no.bracket.index")
10109 (setq rb (js2-current-token-beg)))
10110 (setq pn (make-js2-elem-get-node :target pn
10111 :pos pos
10112 :element expr
10113 :lb (js2-relpos lb pos)
10114 :rb (js2-relpos rb pos)
10115 :len (- (js2-current-token-end) pos)))
10116 (js2-node-add-children pn
10117 (js2-elem-get-node-target pn)
10118 (js2-elem-get-node-element pn))
10119 pn))
10120
10121 (defun js2-highlight-function-call (token)
10122 (when (eq (js2-token-type token) js2-NAME)
10123 (js2-record-face 'js2-function-call token)))
10124
10125 (defun js2-parse-function-call (pn)
10126 (js2-highlight-function-call (js2-current-token))
10127 (js2-get-token)
10128 (let (args
10129 (pos (js2-node-pos pn)))
10130 (setq pn (make-js2-call-node :pos pos
10131 :target pn
10132 :lp (- (js2-current-token-beg) pos)))
10133 (js2-node-add-children pn (js2-call-node-target pn))
10134 ;; Add the arguments to pn, if any are supplied.
10135 (setf args (nreverse (js2-parse-argument-list))
10136 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10137 (js2-call-node-args pn) args)
10138 (apply #'js2-node-add-children pn args)
10139 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10140 pn))
10141
10142 (defun js2-parse-property-access (tt pn)
10143 "Parse a property access, XML descendants access, or XML attr access."
10144 (let ((member-type-flags 0)
10145 (dot-pos (js2-current-token-beg))
10146 (dot-len (if (= tt js2-DOTDOT) 2 1))
10147 name
10148 ref ; right side of . or .. operator
10149 result)
10150 (when (= tt js2-DOTDOT)
10151 (js2-must-have-xml)
10152 (setq member-type-flags js2-descendants-flag))
10153 (if (not js2-compiler-xml-available)
10154 (progn
10155 (js2-must-match-prop-name "msg.no.name.after.dot")
10156 (setq name (js2-create-name-node t js2-GETPROP)
10157 result (make-js2-prop-get-node :left pn
10158 :pos (js2-current-token-beg)
10159 :right name
10160 :len (js2-current-token-len)))
10161 (js2-node-add-children result pn name)
10162 result)
10163 ;; otherwise look for XML operators
10164 (setf result (if (= tt js2-DOT)
10165 (make-js2-prop-get-node)
10166 (make-js2-infix-node :type js2-DOTDOT))
10167 (js2-node-pos result) (js2-node-pos pn)
10168 (js2-infix-node-op-pos result) dot-pos
10169 (js2-infix-node-left result) pn ; do this after setting position
10170 tt (js2-get-prop-name-token))
10171 (cond
10172 ;; handles: name, ns::name, ns::*, ns::[expr]
10173 ((= tt js2-NAME)
10174 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10175 ;; handles: *, *::name, *::*, *::[expr]
10176 ((= tt js2-MUL)
10177 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10178 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10179 ((= tt js2-XMLATTR)
10180 (setq result (js2-parse-attribute-access)))
10181 (t
10182 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10183 (if ref
10184 (setf (js2-node-len result) (- (js2-node-end ref)
10185 (js2-node-pos result))
10186 (js2-infix-node-right result) ref))
10187 (if (js2-infix-node-p result)
10188 (js2-node-add-children result
10189 (js2-infix-node-left result)
10190 (js2-infix-node-right result)))
10191 result)))
10192
10193 (defun js2-parse-attribute-access ()
10194 "Parse an E4X XML attribute expression.
10195 This includes expressions of the forms:
10196
10197 @attr @ns::attr @ns::*
10198 @* @*::attr @*::*
10199 @[expr] @*::[expr] @ns::[expr]
10200
10201 Called if we peeked an '@' token."
10202 (let ((tt (js2-get-prop-name-token))
10203 (at-pos (js2-current-token-beg)))
10204 (cond
10205 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10206 ((= tt js2-NAME)
10207 (js2-parse-property-name at-pos nil 0))
10208 ;; handles: @*, @*::name, @*::*, @*::[expr]
10209 ((= tt js2-MUL)
10210 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10211 ;; handles @[expr]
10212 ((= tt js2-LB)
10213 (js2-parse-xml-elem-ref at-pos))
10214 (t
10215 (js2-report-error "msg.no.name.after.xmlAttr")
10216 ;; Avoid cascaded errors that happen if we make an error node here.
10217 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10218
10219 (defun js2-parse-property-name (at-pos s member-type-flags)
10220 "Check if :: follows name in which case it becomes qualified name.
10221
10222 AT-POS is a natural number if we just read an '@' token, else nil.
10223 S is the name or string that was matched: an identifier, 'throw' or '*'.
10224 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10225
10226 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10227 operator, or the name is followed by ::. For a plain name, returns a
10228 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10229 (let ((pos (or at-pos (js2-current-token-beg)))
10230 colon-pos
10231 (name (js2-create-name-node t (js2-current-token-type) s))
10232 ns tt pn)
10233 (catch 'return
10234 (when (js2-match-token js2-COLONCOLON)
10235 (setq ns name
10236 colon-pos (js2-current-token-beg)
10237 tt (js2-get-prop-name-token))
10238 (cond
10239 ;; handles name::name
10240 ((= tt js2-NAME)
10241 (setq name (js2-create-name-node)))
10242 ;; handles name::*
10243 ((= tt js2-MUL)
10244 (setq name (js2-create-name-node nil nil "*")))
10245 ;; handles name::[expr]
10246 ((= tt js2-LB)
10247 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10248 (t
10249 (js2-report-error "msg.no.name.after.coloncolon"))))
10250 (if (and (null ns) (zerop member-type-flags))
10251 name
10252 (prog1
10253 (setq pn
10254 (make-js2-xml-prop-ref-node :pos pos
10255 :len (- (js2-node-end name) pos)
10256 :at-pos at-pos
10257 :colon-pos colon-pos
10258 :propname name))
10259 (js2-node-add-children pn name))))))
10260
10261 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10262 "Parse the [expr] portion of an xml element reference.
10263 For instance, @[expr], @*::[expr], or ns::[expr]."
10264 (let* ((lb (js2-current-token-beg))
10265 (pos (or at-pos lb))
10266 rb
10267 (expr (js2-parse-expr))
10268 (end (js2-node-end expr))
10269 pn)
10270 (if (js2-must-match js2-RB "msg.no.bracket.index")
10271 (setq rb (js2-current-token-beg)
10272 end (js2-current-token-end)))
10273 (prog1
10274 (setq pn
10275 (make-js2-xml-elem-ref-node :pos pos
10276 :len (- end pos)
10277 :namespace namespace
10278 :colon-pos colon-pos
10279 :at-pos at-pos
10280 :expr expr
10281 :lb (js2-relpos lb pos)
10282 :rb (js2-relpos rb pos)))
10283 (js2-node-add-children pn namespace expr))))
10284
10285 (defun js2-parse-destruct-primary-expr ()
10286 (let ((js2-is-in-destructuring t))
10287 (js2-parse-primary-expr)))
10288
10289 (defun js2-parse-primary-expr ()
10290 "Parse a literal (leaf) expression of some sort.
10291 Includes complex literals such as functions, object-literals,
10292 array-literals, array comprehensions and regular expressions."
10293 (let (tt node)
10294 (setq tt (js2-current-token-type))
10295 (cond
10296 ((= tt js2-CLASS)
10297 (js2-parse-class-expr))
10298 ((= tt js2-FUNCTION)
10299 (js2-parse-function-expr))
10300 ((= tt js2-LB)
10301 (js2-parse-array-comp-or-literal))
10302 ((= tt js2-LC)
10303 (js2-parse-object-literal))
10304 ((= tt js2-LET)
10305 (js2-parse-let (js2-current-token-beg)))
10306 ((= tt js2-LP)
10307 (js2-parse-paren-expr-or-generator-comp))
10308 ((= tt js2-XMLATTR)
10309 (js2-must-have-xml)
10310 (js2-parse-attribute-access))
10311 ((= tt js2-NAME)
10312 (js2-parse-name tt))
10313 ((= tt js2-NUMBER)
10314 (setq node (make-js2-number-node))
10315 (when (and js2-in-use-strict-directive
10316 (= (js2-number-node-num-base node) 8))
10317 (js2-report-error "msg.no.octal.strict"))
10318 node)
10319 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10320 (make-js2-string-node :type tt))
10321 ((= tt js2-TEMPLATE_HEAD)
10322 (js2-parse-template-literal))
10323 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10324 ;; Got / or /= which in this context means a regexp literal
10325 (let ((px-pos (js2-current-token-beg))
10326 (flags (js2-read-regexp tt))
10327 (end (js2-current-token-end)))
10328 (prog1
10329 (make-js2-regexp-node :pos px-pos
10330 :len (- end px-pos)
10331 :value (js2-current-token-string)
10332 :flags flags)
10333 (js2-set-face px-pos end 'font-lock-string-face 'record)
10334 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10335 ((or (= tt js2-NULL)
10336 (= tt js2-THIS)
10337 (= tt js2-SUPER)
10338 (= tt js2-FALSE)
10339 (= tt js2-TRUE))
10340 (make-js2-keyword-node :type tt))
10341 ((= tt js2-TRIPLEDOT)
10342 ;; Likewise, only valid in an arrow function with a rest param.
10343 (if (and (js2-match-token js2-NAME)
10344 (js2-match-token js2-RP)
10345 (eq (js2-peek-token) js2-ARROW))
10346 (progn
10347 (js2-unget-token) ; Put back the right paren.
10348 ;; See the previous case.
10349 (make-js2-keyword-node :type js2-NULL))
10350 (js2-report-error "msg.syntax")
10351 (make-js2-error-node)))
10352 ((= tt js2-RESERVED)
10353 (js2-report-error "msg.reserved.id")
10354 (make-js2-name-node))
10355 ((= tt js2-ERROR)
10356 ;; the scanner or one of its subroutines reported the error.
10357 (make-js2-error-node))
10358 ((= tt js2-EOF)
10359 (let* ((px-pos (point-at-bol))
10360 (len (- js2-ts-cursor px-pos)))
10361 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10362 (make-js2-error-node :pos (1- js2-ts-cursor)))
10363 (t
10364 (js2-report-error "msg.syntax")
10365 (make-js2-error-node)))))
10366
10367 (defun js2-parse-template-literal ()
10368 (let ((beg (js2-current-token-beg))
10369 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10370 (tt js2-TEMPLATE_HEAD))
10371 (while (eq tt js2-TEMPLATE_HEAD)
10372 (push (js2-parse-expr) kids)
10373 (js2-must-match js2-RC "msg.syntax")
10374 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10375 (push (make-js2-string-node :type tt) kids))
10376 (setq kids (nreverse kids))
10377 (let ((tpl (make-js2-template-node :beg beg
10378 :len (- (js2-current-token-end) beg)
10379 :kids kids)))
10380 (apply #'js2-node-add-children tpl kids)
10381 tpl)))
10382
10383 (defun js2-parse-name (_tt)
10384 (let ((name (js2-current-token-string))
10385 node)
10386 (setq node (if js2-compiler-xml-available
10387 (js2-parse-property-name nil name 0)
10388 (js2-create-name-node 'check-activation nil name)))
10389 (if js2-highlight-external-variables
10390 (js2-record-name-node node))
10391 node))
10392
10393 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10394 (js2-add-strict-warning
10395 msg nil
10396 ;; back up from comma to beginning of line or array/objlit
10397 (max (if elems
10398 (js2-node-pos (car elems))
10399 pos)
10400 (save-excursion
10401 (goto-char comma-pos)
10402 (back-to-indentation)
10403 (point)))
10404 comma-pos))
10405
10406 (defun js2-parse-array-comp-or-literal ()
10407 (let ((pos (js2-current-token-beg)))
10408 (if (and (>= js2-language-version 200)
10409 (js2-match-token js2-FOR))
10410 (js2-parse-array-comp pos)
10411 (js2-parse-array-literal pos))))
10412
10413 (defun js2-parse-array-literal (pos)
10414 (let ((after-lb-or-comma t)
10415 after-comma tt elems pn
10416 (continue t))
10417 (unless js2-is-in-destructuring
10418 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10419 (while continue
10420 (setq tt (js2-get-token))
10421 (cond
10422 ;; comma
10423 ((= tt js2-COMMA)
10424 (setq after-comma (js2-current-token-end))
10425 (if (not after-lb-or-comma)
10426 (setq after-lb-or-comma t)
10427 (push nil elems)))
10428 ;; end of array
10429 ((or (= tt js2-RB)
10430 (= tt js2-EOF)) ; prevent infinite loop
10431 (if (= tt js2-EOF)
10432 (js2-report-error "msg.no.bracket.arg" nil pos))
10433 (when (and after-comma (< js2-language-version 170))
10434 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10435 pos (remove nil elems) after-comma))
10436 (setq continue nil
10437 pn (make-js2-array-node :pos pos
10438 :len (- js2-ts-cursor pos)
10439 :elems (nreverse elems)))
10440 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10441 ;; destructuring binding
10442 (js2-is-in-destructuring
10443 (push (if (or (= tt js2-LC)
10444 (= tt js2-LB)
10445 (= tt js2-NAME))
10446 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10447 (js2-parse-destruct-primary-expr)
10448 ;; invalid pattern
10449 (js2-report-error "msg.bad.var")
10450 (make-js2-error-node))
10451 elems)
10452 (setq after-lb-or-comma nil
10453 after-comma nil))
10454 ;; array comp
10455 ((and (>= js2-language-version 170)
10456 (= tt js2-FOR) ; check for array comprehension
10457 (not after-lb-or-comma) ; "for" can't follow a comma
10458 elems ; must have at least 1 element
10459 (not (cdr elems))) ; but no 2nd element
10460 (js2-unget-token)
10461 (setf continue nil
10462 pn (js2-parse-legacy-array-comp (car elems) pos)))
10463 ;; another element
10464 (t
10465 (unless after-lb-or-comma
10466 (js2-report-error "msg.no.bracket.arg"))
10467 (if (and (= tt js2-TRIPLEDOT)
10468 (>= js2-language-version 200))
10469 ;; spread operator
10470 (push (js2-make-unary tt 'js2-parse-assign-expr)
10471 elems)
10472 (js2-unget-token)
10473 (push (js2-parse-assign-expr) elems))
10474 (setq after-lb-or-comma nil
10475 after-comma nil))))
10476 (unless js2-is-in-destructuring
10477 (js2-pop-scope))
10478 pn))
10479
10480 (defun js2-parse-legacy-array-comp (expr pos)
10481 "Parse a legacy array comprehension (JavaScript 1.7).
10482 EXPR is the first expression after the opening left-bracket.
10483 POS is the beginning of the LB token preceding EXPR.
10484 We should have just parsed the 'for' keyword before calling this function."
10485 (let ((current-scope js2-current-scope)
10486 loops first filter result)
10487 (unwind-protect
10488 (progn
10489 (while (js2-match-token js2-FOR)
10490 (let ((loop (make-js2-comp-loop-node)))
10491 (js2-push-scope loop)
10492 (push loop loops)
10493 (js2-parse-comp-loop loop)))
10494 ;; First loop takes expr scope's parent.
10495 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10496 (js2-scope-parent-scope current-scope))
10497 ;; Set expr scope's parent to the last loop.
10498 (setf (js2-scope-parent-scope current-scope) (car loops))
10499 (if (/= (js2-get-token) js2-IF)
10500 (js2-unget-token)
10501 (setq filter (js2-parse-condition))))
10502 (dotimes (_ (1- (length loops)))
10503 (js2-pop-scope)))
10504 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10505 (setq result (make-js2-comp-node :pos pos
10506 :len (- js2-ts-cursor pos)
10507 :result expr
10508 :loops (nreverse loops)
10509 :filters (and filter (list (car filter)))
10510 :form 'LEGACY_ARRAY))
10511 ;; Set comp loop's parent to the last loop.
10512 ;; TODO: Get rid of the bogus expr scope.
10513 (setf (js2-scope-parent-scope result) first)
10514 (apply #'js2-node-add-children result expr (car filter)
10515 (js2-comp-node-loops result))
10516 result))
10517
10518 (defun js2-parse-array-comp (pos)
10519 "Parse an ES6 array comprehension.
10520 POS is the beginning of the LB token.
10521 We should have just parsed the 'for' keyword before calling this function."
10522 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10523 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10524 pn))
10525
10526 (defun js2-parse-generator-comp (pos)
10527 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10528 (js2-current-script-or-fn
10529 (make-js2-function-node :generator-type 'COMPREHENSION))
10530 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10531 (js2-must-match js2-RP "msg.no.paren" pos)
10532 pn))
10533
10534 (defun js2-parse-comprehension (pos form)
10535 (let (loops filters expr result last)
10536 (unwind-protect
10537 (progn
10538 (js2-unget-token)
10539 (while (js2-match-token js2-FOR)
10540 (let ((loop (make-js2-comp-loop-node)))
10541 (js2-push-scope loop)
10542 (push loop loops)
10543 (js2-parse-comp-loop loop)))
10544 (while (js2-match-token js2-IF)
10545 (push (car (js2-parse-condition)) filters))
10546 (setq expr (js2-parse-assign-expr))
10547 (setq last (car loops)))
10548 (dolist (_ loops)
10549 (js2-pop-scope)))
10550 (setq result (make-js2-comp-node :pos pos
10551 :len (- js2-ts-cursor pos)
10552 :result expr
10553 :loops (nreverse loops)
10554 :filters (nreverse filters)
10555 :form form))
10556 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10557 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10558 (setf (js2-scope-parent-scope result) last)
10559 result))
10560
10561 (defun js2-parse-comp-loop (pn &optional only-of-p)
10562 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10563 The current token should be the initial FOR.
10564 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10565 (let ((pos (js2-comp-loop-node-pos pn))
10566 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10567 (when (and (not only-of-p) (js2-match-token js2-NAME))
10568 (if (string= (js2-current-token-string) "each")
10569 (progn
10570 (setq foreach-p t
10571 each-pos (- (js2-current-token-beg) pos)) ; relative
10572 (js2-record-face 'font-lock-keyword-face))
10573 (js2-report-error "msg.no.paren.for")))
10574 (if (js2-must-match js2-LP "msg.no.paren.for")
10575 (setq lp (- (js2-current-token-beg) pos)))
10576 (setq tt (js2-peek-token))
10577 (cond
10578 ((or (= tt js2-LB)
10579 (= tt js2-LC))
10580 (js2-get-token)
10581 (setq iter (js2-parse-destruct-primary-expr))
10582 (js2-define-destruct-symbols iter js2-LET
10583 'font-lock-variable-name-face t))
10584 ((js2-match-token js2-NAME)
10585 (setq iter (js2-create-name-node)))
10586 (t
10587 (js2-report-error "msg.bad.var")))
10588 ;; Define as a let since we want the scope of the variable to
10589 ;; be restricted to the array comprehension
10590 (if (js2-name-node-p iter)
10591 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10592 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10593 (and (>= js2-language-version 200)
10594 (js2-match-contextual-kwd "of")
10595 (setq forof-p t)))
10596 (setq in-pos (- (js2-current-token-beg) pos))
10597 (js2-report-error "msg.in.after.for.name"))
10598 (setq obj (js2-parse-expr))
10599 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10600 (setq rp (- (js2-current-token-beg) pos)))
10601 (setf (js2-node-pos pn) pos
10602 (js2-node-len pn) (- js2-ts-cursor pos)
10603 (js2-comp-loop-node-iterator pn) iter
10604 (js2-comp-loop-node-object pn) obj
10605 (js2-comp-loop-node-in-pos pn) in-pos
10606 (js2-comp-loop-node-each-pos pn) each-pos
10607 (js2-comp-loop-node-foreach-p pn) foreach-p
10608 (js2-comp-loop-node-forof-p pn) forof-p
10609 (js2-comp-loop-node-lp pn) lp
10610 (js2-comp-loop-node-rp pn) rp)
10611 (js2-node-add-children pn iter obj)
10612 pn))
10613
10614 (defun js2-parse-class-stmt ()
10615 (let ((pos (js2-current-token-beg))
10616 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10617 (name (js2-create-name-node t)))
10618 (js2-set-face (js2-node-pos name) (js2-node-end name)
10619 'font-lock-function-name-face 'record)
10620 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10621 (js2-define-symbol js2-FUNCTION
10622 (js2-name-node-name name)
10623 node)
10624 node)))
10625
10626 (defun js2-parse-class-expr ()
10627 (let ((pos (js2-current-token-beg))
10628 name)
10629 (when (js2-match-token js2-NAME)
10630 (setq name (js2-create-name-node t)))
10631 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10632
10633 (defun js2-parse-class (pos form name)
10634 ;; class X [extends ...] {
10635 (let (pn elems extends)
10636 (if (js2-match-token js2-EXTENDS)
10637 (if (= (js2-peek-token) js2-LC)
10638 (js2-report-error "msg.missing.extends")
10639 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10640 (setq extends (js2-parse-assign-expr))
10641 (if (not extends)
10642 (js2-report-error "msg.bad.extends"))))
10643 (js2-must-match js2-LC "msg.no.brace.class")
10644 (setq elems (js2-parse-object-literal-elems t)
10645 pn (make-js2-class-node :pos pos
10646 :len (- js2-ts-cursor pos)
10647 :form form
10648 :name name
10649 :extends extends
10650 :elems elems))
10651 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10652 pn))
10653
10654 (defun js2-parse-object-literal ()
10655 (let* ((pos (js2-current-token-beg))
10656 (elems (js2-parse-object-literal-elems))
10657 (result (make-js2-object-node :pos pos
10658 :len (- js2-ts-cursor pos)
10659 :elems elems)))
10660 (apply #'js2-node-add-children result (js2-object-node-elems result))
10661 result))
10662
10663 (defun js2-property-key-string (property-node)
10664 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10665 `js2-getter-setter-node') as a string, or nil if it can't be
10666 represented as a string (e.g., the key is computed by an
10667 expression)."
10668 (let ((key (js2-infix-node-left property-node)))
10669 (cond
10670 ((js2-name-node-p key)
10671 (js2-name-node-name key))
10672 ((js2-string-node-p key)
10673 (js2-string-node-value key))
10674 ((js2-number-node-p key)
10675 (js2-number-node-value key)))))
10676
10677 (defun js2-parse-object-literal-elems (&optional class-p)
10678 (let ((pos (js2-current-token-beg))
10679 (static nil)
10680 (continue t)
10681 tt elems elem
10682 elem-key-string previous-elem-key-string
10683 after-comma previous-token)
10684 (while continue
10685 (setq tt (js2-get-prop-name-token)
10686 static nil
10687 elem nil
10688 previous-token nil)
10689 ;; Handle 'static' keyword only if we're in a class
10690 (when (and class-p (= js2-NAME tt)
10691 (string= "static" (js2-current-token-string)))
10692 (js2-record-face 'font-lock-keyword-face)
10693 (setq static t
10694 tt (js2-get-prop-name-token)))
10695 ;; Handle generator * before the property name for in-line functions
10696 (when (and (>= js2-language-version 200)
10697 (= js2-MUL tt))
10698 (setq previous-token (js2-current-token)
10699 tt (js2-get-prop-name-token)))
10700 ;; Handle 'get' or 'set' keywords
10701 (let ((prop (js2-current-token-string)))
10702 (when (and (>= js2-language-version 200)
10703 (= js2-NAME tt)
10704 (or (string= prop "get")
10705 (string= prop "set"))
10706 (member (js2-peek-token)
10707 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10708 (setq previous-token (js2-current-token)
10709 tt (js2-get-prop-name-token))))
10710 (cond
10711 ;; Found a property (of any sort)
10712 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10713 (setq after-comma nil
10714 elem (js2-parse-named-prop tt pos previous-token))
10715 (if (and (null elem)
10716 (not js2-recover-from-parse-errors))
10717 (setq continue nil)))
10718 ;; Break out of loop, and handle trailing commas.
10719 ((or (= tt js2-RC)
10720 (= tt js2-EOF))
10721 (js2-unget-token)
10722 (setq continue nil)
10723 (if after-comma
10724 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10725 pos elems after-comma)))
10726 (t
10727 (js2-report-error "msg.bad.prop")
10728 (unless js2-recover-from-parse-errors
10729 (setq continue nil)))) ; end switch
10730 ;; Handle static for classes' codegen.
10731 (if static
10732 (if elem (js2-node-set-prop elem 'STATIC t)
10733 (js2-report-error "msg.unexpected.static")))
10734 ;; Handle commas, depending on class-p.
10735 (let ((tok (js2-get-prop-name-token)))
10736 (if (eq tok js2-COMMA)
10737 (if class-p
10738 (js2-report-error "msg.class.unexpected.comma")
10739 (setq after-comma (js2-current-token-end)))
10740 (js2-unget-token)
10741 (unless class-p (setq continue nil))))
10742 (when elem
10743 (when (and js2-in-use-strict-directive
10744 (setq elem-key-string (js2-property-key-string elem))
10745 (cl-some
10746 (lambda (previous-elem)
10747 (and (setq previous-elem-key-string
10748 (js2-property-key-string previous-elem))
10749 (string= previous-elem-key-string elem-key-string)))
10750 elems))
10751 (js2-report-error "msg.dup.obj.lit.prop.strict"
10752 elem-key-string
10753 (js2-node-abs-pos (js2-infix-node-left elem))
10754 (js2-node-len (js2-infix-node-left elem))))
10755 ;; Append any parsed element.
10756 (push elem elems))) ; end loop
10757 (js2-must-match js2-RC "msg.no.brace.prop")
10758 (nreverse elems)))
10759
10760 (defun js2-parse-named-prop (tt pos previous-token)
10761 "Parse a name, string, or getter/setter object property.
10762 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10763 (let ((key (cond
10764 ;; Literal string keys: {'foo': 'bar'}
10765 ((= tt js2-STRING)
10766 (make-js2-string-node))
10767 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10768 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10769 ((and (= tt js2-LB)
10770 (>= js2-language-version 200))
10771 (prog1 (js2-parse-expr)
10772 (js2-must-match js2-RB "msg.missing.computed.rb")))
10773 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10774 ((= tt js2-NUMBER)
10775 (make-js2-number-node))
10776 ;; Unquoted names: {foo: 12}
10777 ((= tt js2-NAME)
10778 (js2-create-name-node))
10779 ;; Anything else is an error
10780 (t (js2-report-error "msg.bad.prop"))))
10781 (prop (and previous-token (js2-token-string previous-token)))
10782 (property-type (when previous-token
10783 (if (= (js2-token-type previous-token) js2-MUL)
10784 "*"
10785 (js2-token-string previous-token)))))
10786 (when (or (string= prop "get")
10787 (string= prop "set"))
10788 (js2-set-face (js2-token-beg previous-token)
10789 (js2-token-end previous-token)
10790 'font-lock-keyword-face 'record)) ; get/set
10791 (cond
10792 ;; method definition: {f() {...}}
10793 ((and (= (js2-peek-token) js2-LP)
10794 (>= js2-language-version 200))
10795 (when (js2-name-node-p key) ; highlight function name properties
10796 (js2-record-face 'font-lock-function-name-face))
10797 (js2-parse-getter-setter-prop pos key property-type))
10798 ;; regular prop
10799 (t
10800 (let ((beg (js2-current-token-beg))
10801 (end (js2-current-token-end))
10802 (expr (js2-parse-plain-property key)))
10803 (when (and (= tt js2-NAME)
10804 (not js2-is-in-destructuring)
10805 js2-highlight-external-variables
10806 (js2-node-get-prop expr 'SHORTHAND))
10807 (js2-record-name-node key))
10808 (js2-set-face beg end
10809 (if (js2-function-node-p
10810 (js2-object-prop-node-right expr))
10811 'font-lock-function-name-face
10812 'font-lock-variable-name-face)
10813 'record)
10814 expr)))))
10815
10816 (defun js2-parse-plain-property (prop)
10817 "Parse a non-getter/setter property in an object literal.
10818 PROP is the node representing the property: a number, name,
10819 string or expression."
10820 (let* ((tt (js2-get-token))
10821 (pos (js2-node-pos prop))
10822 colon expr result)
10823 (cond
10824 ;; Abbreviated property, as in {foo, bar}
10825 ((and (>= js2-language-version 200)
10826 (or (= tt js2-COMMA)
10827 (= tt js2-RC))
10828 (not (js2-number-node-p prop)))
10829 (js2-unget-token)
10830 (setq result (make-js2-object-prop-node
10831 :pos pos
10832 :left prop
10833 :right prop
10834 :op-pos (js2-current-token-len)))
10835 (js2-node-add-children result prop)
10836 (js2-node-set-prop result 'SHORTHAND t)
10837 result)
10838 ;; Normal property
10839 (t
10840 (if (= tt js2-COLON)
10841 (setq colon (- (js2-current-token-beg) pos)
10842 expr (js2-parse-assign-expr))
10843 (js2-report-error "msg.no.colon.prop")
10844 (setq expr (make-js2-error-node)))
10845 (setq result (make-js2-object-prop-node
10846 :pos pos
10847 ;; don't include last consumed token in length
10848 :len (- (+ (js2-node-pos expr)
10849 (js2-node-len expr))
10850 pos)
10851 :left prop
10852 :right expr
10853 :op-pos colon))
10854 (js2-node-add-children result prop expr)
10855 result))))
10856
10857 (defun js2-parse-getter-setter-prop (pos prop type-string)
10858 "Parse getter or setter property in an object literal.
10859 JavaScript syntax is:
10860
10861 { get foo() {...}, set foo(x) {...} }
10862
10863 and expression closure style is also supported
10864
10865 { get foo() x, set foo(x) _x = x }
10866
10867 POS is the start position of the `get' or `set' keyword.
10868 PROP is the `js2-name-node' representing the property name.
10869 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10870 (let ((type (cond
10871 ((string= "get" type-string) js2-GET)
10872 ((string= "set" type-string) js2-SET)
10873 (t js2-FUNCTION)))
10874 result end
10875 (fn (js2-parse-function-expr)))
10876 ;; it has to be an anonymous function, as we already parsed the name
10877 (if (/= (js2-node-type fn) js2-FUNCTION)
10878 (js2-report-error "msg.bad.prop")
10879 (if (cl-plusp (length (js2-function-name fn)))
10880 (js2-report-error "msg.bad.prop")))
10881 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10882 (when (string= type-string "*")
10883 (setf (js2-function-node-generator-type fn) 'STAR))
10884 (setq end (js2-node-end fn)
10885 result (make-js2-getter-setter-node :type type
10886 :pos pos
10887 :len (- end pos)
10888 :left prop
10889 :right fn))
10890 (js2-node-add-children result prop fn)
10891 result))
10892
10893 (defun js2-create-name-node (&optional check-activation-p token string)
10894 "Create a name node using the current token and, optionally, STRING.
10895 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10896 (let* ((beg (js2-current-token-beg))
10897 (tt (js2-current-token-type))
10898 (s (or string
10899 (if (= js2-NAME tt)
10900 (js2-current-token-string)
10901 (js2-tt-name tt))))
10902 name)
10903 (setq name (make-js2-name-node :pos beg
10904 :name s
10905 :len (length s)))
10906 (if check-activation-p
10907 (js2-check-activation-name s (or token js2-NAME)))
10908 name))
10909
10910 ;;; Indentation support
10911
10912 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10913 ;; Karl cleverly deduces that the desired indentation level is often a
10914 ;; function of paren/bracket/brace nesting depth, which can be determined
10915 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10916 ;; then does some equally clever checks to see if we're in the context of a
10917 ;; substatement of a possibly braceless statement keyword such as if, while,
10918 ;; or finally. This approach yields pretty good results.
10919
10920 ;; The indenter is often "wrong", however, and needs to be overridden.
10921 ;; The right long-term solution is probably to emulate (or integrate
10922 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10923 ;; parse tree from `js2-parse' is present, which is not true at the
10924 ;; moment the user is typing, computing indentation is still thousands
10925 ;; of lines of code to handle every possible syntactic edge case.
10926
10927 ;; In the meantime, the compromise solution is that we offer a "bounce
10928 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10929 ;; current line indent among various likely guess points. This approach
10930 ;; is far from perfect, but should at least make it slightly easier to
10931 ;; move the line towards its desired indentation when manually
10932 ;; overriding Karl's heuristic nesting guesser.
10933
10934 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10935 ;; extensions such as `let' and Array comprehensions. Major kudos to
10936 ;; Karl for coming up with the initial approach, which packs a lot of
10937 ;; punch for so little code.
10938
10939 (defconst js2-possibly-braceless-keywords-re
10940 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10941 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10942 "try" "while" "with" "let")))
10943 "Regular expression matching keywords that are optionally
10944 followed by an opening brace.")
10945
10946 (defconst js2-indent-operator-re
10947 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10948 (regexp-opt '("in" "instanceof") 'words))
10949 "Regular expression matching operators that affect indentation
10950 of continued expressions.")
10951
10952 (defconst js2-declaration-keyword-re
10953 (regexp-opt '("var" "let" "const") 'words)
10954 "Regular expression matching variable declaration keywords.")
10955
10956 (defun js2-re-search-forward-inner (regexp &optional bound count)
10957 "Auxiliary function for `js2-re-search-forward'."
10958 (let (parse saved-point)
10959 (while (> count 0)
10960 (re-search-forward regexp bound)
10961 (setq parse (if saved-point
10962 (parse-partial-sexp saved-point (point))
10963 (syntax-ppss (point))))
10964 (cond ((nth 3 parse)
10965 (re-search-forward
10966 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10967 (save-excursion (end-of-line) (point)) t))
10968 ((nth 7 parse)
10969 (forward-line))
10970 ((or (nth 4 parse)
10971 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10972 (re-search-forward "\\*/"))
10973 (t
10974 (setq count (1- count))))
10975 (setq saved-point (point))))
10976 (point))
10977
10978 (defun js2-re-search-forward (regexp &optional bound noerror count)
10979 "Search forward but ignore strings and comments.
10980 Invokes `re-search-forward' but treats the buffer as if strings
10981 and comments have been removed."
10982 (let ((saved-point (point)))
10983 (condition-case err
10984 (cond ((null count)
10985 (js2-re-search-forward-inner regexp bound 1))
10986 ((< count 0)
10987 (js2-re-search-backward-inner regexp bound (- count)))
10988 ((> count 0)
10989 (js2-re-search-forward-inner regexp bound count)))
10990 (search-failed
10991 (goto-char saved-point)
10992 (unless noerror
10993 (error (error-message-string err)))))))
10994
10995 (defun js2-re-search-backward-inner (regexp &optional bound count)
10996 "Auxiliary function for `js2-re-search-backward'."
10997 (let (parse)
10998 (while (> count 0)
10999 (re-search-backward regexp bound)
11000 (setq parse (syntax-ppss (point)))
11001 (cond ((nth 3 parse)
11002 (re-search-backward
11003 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
11004 (line-beginning-position) t))
11005 ((nth 7 parse)
11006 (goto-char (nth 8 parse)))
11007 ((or (nth 4 parse)
11008 (and (eq (char-before) ?/) (eq (char-after) ?*)))
11009 (re-search-backward "/\\*"))
11010 (t
11011 (setq count (1- count))))))
11012 (point))
11013
11014 (defun js2-re-search-backward (regexp &optional bound noerror count)
11015 "Search backward but ignore strings and comments.
11016 Invokes `re-search-backward' but treats the buffer as if strings
11017 and comments have been removed."
11018 (let ((saved-point (point)))
11019 (condition-case err
11020 (cond ((null count)
11021 (js2-re-search-backward-inner regexp bound 1))
11022 ((< count 0)
11023 (js2-re-search-forward-inner regexp bound (- count)))
11024 ((> count 0)
11025 (js2-re-search-backward-inner regexp bound count)))
11026 (search-failed
11027 (goto-char saved-point)
11028 (unless noerror
11029 (error (error-message-string err)))))))
11030
11031 (defun js2-looking-at-operator-p ()
11032 "Return non-nil if text after point is a non-comma operator."
11033 (and (looking-at js2-indent-operator-re)
11034 (or (not (looking-at ":"))
11035 (save-excursion
11036 (and (js2-re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
11037 (looking-at "?"))))))
11038
11039 (defun js2-continued-expression-p ()
11040 "Return non-nil if the current line continues an expression."
11041 (save-excursion
11042 (back-to-indentation)
11043 (or (js2-looking-at-operator-p)
11044 (when (catch 'found
11045 (while (and (re-search-backward "\n" nil t)
11046 (let ((state (syntax-ppss)))
11047 (when (nth 4 state)
11048 (goto-char (nth 8 state))) ;; skip comments
11049 (skip-chars-backward " \t")
11050 (if (bolp)
11051 t
11052 (throw 'found t))))))
11053 (backward-char)
11054 (when (js2-looking-at-operator-p)
11055 (backward-char)
11056 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
11057
11058 (defun js2-end-of-do-while-loop-p ()
11059 "Return non-nil if word after point is `while' of a do-while
11060 statement, else returns nil. A braceless do-while statement
11061 spanning several lines requires that the start of the loop is
11062 indented to the same column as the current line."
11063 (interactive)
11064 (save-excursion
11065 (when (looking-at "\\s-*\\_<while\\_>")
11066 (if (save-excursion
11067 (skip-chars-backward "[ \t\n]*}")
11068 (looking-at "[ \t\n]*}"))
11069 (save-excursion
11070 (backward-list) (backward-word 1) (looking-at "\\_<do\\_>"))
11071 (js2-re-search-backward "\\_<do\\_>" (point-at-bol) t)
11072 (or (looking-at "\\_<do\\_>")
11073 (let ((saved-indent (current-indentation)))
11074 (while (and (js2-re-search-backward "^[ \t]*\\_<" nil t)
11075 (/= (current-indentation) saved-indent)))
11076 (and (looking-at "[ \t]*\\_<do\\_>")
11077 (not (js2-re-search-forward
11078 "\\_<while\\_>" (point-at-eol) t))
11079 (= (current-indentation) saved-indent))))))))
11080
11081 (defun js2-multiline-decl-indentation ()
11082 "Return the declaration indentation column if the current line belongs
11083 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
11084 (let (forward-sexp-function ; use Lisp version
11085 at-opening-bracket)
11086 (save-excursion
11087 (back-to-indentation)
11088 (when (not (looking-at js2-declaration-keyword-re))
11089 (when (looking-at js2-indent-operator-re)
11090 (goto-char (match-end 0))) ; continued expressions are ok
11091 (while (and (not at-opening-bracket)
11092 (not (bobp))
11093 (let ((pos (point)))
11094 (save-excursion
11095 (js2-backward-sws)
11096 (or (eq (char-before) ?,)
11097 (and (not (eq (char-before) ?\;))
11098 (prog2 (skip-syntax-backward ".")
11099 (looking-at js2-indent-operator-re)
11100 (js2-backward-sws))
11101 (not (eq (char-before) ?\;)))
11102 (js2-same-line pos)))))
11103 (condition-case _
11104 (backward-sexp)
11105 (scan-error (setq at-opening-bracket t))))
11106 (when (looking-at js2-declaration-keyword-re)
11107 (goto-char (match-end 0))
11108 (1+ (current-column)))))))
11109
11110 (defun js2-ctrl-statement-indentation ()
11111 "Return the proper indentation of current line if it is a control statement.
11112 Returns an indentation if this line starts the body of a control
11113 statement without braces, else returns nil."
11114 (let (forward-sexp-function)
11115 (save-excursion
11116 (back-to-indentation)
11117 (when (and (not (js2-same-line (point-min)))
11118 (not (looking-at "{"))
11119 (js2-re-search-backward "[[:graph:]]" nil t)
11120 (not (looking-at "[{([]"))
11121 (progn
11122 (forward-char)
11123 (when (= (char-before) ?\))
11124 ;; scan-sexps sometimes throws an error
11125 (ignore-errors (backward-sexp))
11126 (skip-chars-backward " \t" (point-at-bol)))
11127 (let ((pt (point)))
11128 (back-to-indentation)
11129 (when (looking-at "}[ \t]*")
11130 (goto-char (match-end 0)))
11131 (and (looking-at js2-possibly-braceless-keywords-re)
11132 (= (match-end 0) pt)
11133 (not (js2-end-of-do-while-loop-p))))))
11134 (+ (current-indentation) js2-basic-offset)))))
11135
11136 (defun js2-indent-in-array-comp (parse-status)
11137 "Return non-nil if we think we're in an array comprehension.
11138 In particular, return the buffer position of the first `for' kwd."
11139 (let ((bracket (nth 1 parse-status))
11140 (end (point)))
11141 (when bracket
11142 (save-excursion
11143 (goto-char bracket)
11144 (when (looking-at "\\[")
11145 (forward-char 1)
11146 (js2-forward-sws)
11147 (if (looking-at "[[{]")
11148 (let (forward-sexp-function) ; use Lisp version
11149 (forward-sexp) ; skip destructuring form
11150 (js2-forward-sws)
11151 (if (and (/= (char-after) ?,) ; regular array
11152 (looking-at "for"))
11153 (match-beginning 0)))
11154 ;; to skip arbitrary expressions we need the parser,
11155 ;; so we'll just guess at it.
11156 (if (and (> end (point)) ; not empty literal
11157 (re-search-forward "[^,]]* \\(for\\) " end t)
11158 ;; not inside comment or string literal
11159 (let ((state (parse-partial-sexp bracket (point))))
11160 (not (or (nth 3 state) (nth 4 state)))))
11161 (match-beginning 1))))))))
11162
11163 (defun js2-array-comp-indentation (parse-status for-kwd)
11164 (if (js2-same-line for-kwd)
11165 ;; first continuation line
11166 (save-excursion
11167 (goto-char (nth 1 parse-status))
11168 (forward-char 1)
11169 (skip-chars-forward " \t")
11170 (current-column))
11171 (save-excursion
11172 (goto-char for-kwd)
11173 (current-column))))
11174
11175 (defun js2-maybe-goto-declaration-keyword-end (bracket)
11176 "Helper function for `js2-proper-indentation'.
11177 Depending on the value of `js2-pretty-multiline-declarations',
11178 move point to the end of a variable declaration keyword so that
11179 indentation is aligned to that column."
11180 (cond
11181 ((eq js2-pretty-multiline-declarations 'all)
11182 (when (looking-at js2-declaration-keyword-re)
11183 (goto-char (1+ (match-end 0)))))
11184 ((eq js2-pretty-multiline-declarations 'dynamic)
11185 (let (declaration-keyword-end
11186 at-closing-bracket-p
11187 comma-p)
11188 (when (looking-at js2-declaration-keyword-re)
11189 ;; Preserve the match data lest it somehow be overridden.
11190 (setq declaration-keyword-end (match-end 0))
11191 (save-excursion
11192 (goto-char bracket)
11193 (setq at-closing-bracket-p
11194 ;; Handle scan errors gracefully.
11195 (condition-case nil
11196 (progn
11197 ;; Use the regular `forward-sexp-function' because the
11198 ;; normal one for this mode uses the AST.
11199 (let (forward-sexp-function)
11200 (forward-sexp))
11201 t)
11202 (error nil)))
11203 (when at-closing-bracket-p
11204 (js2-forward-sws)
11205 (setq comma-p (looking-at-p ","))))
11206 (when comma-p
11207 (goto-char (1+ declaration-keyword-end))))))))
11208
11209 (defun js2-proper-indentation (parse-status)
11210 "Return the proper indentation for the current line."
11211 (save-excursion
11212 (back-to-indentation)
11213 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
11214 (at-closing-bracket (looking-at "[]})]"))
11215 (same-indent-p (or at-closing-bracket
11216 (looking-at "\\_<case\\_>[^:]")
11217 (and (looking-at "\\_<default:")
11218 (save-excursion
11219 (js2-backward-sws)
11220 (not (memq (char-before) '(?, ?{)))))))
11221 (continued-expr-p (js2-continued-expression-p))
11222 (declaration-indent (and js2-pretty-multiline-declarations
11223 (js2-multiline-decl-indentation)))
11224 (bracket (nth 1 parse-status))
11225 beg indent)
11226 (cond
11227 ;; indent array comprehension continuation lines specially
11228 ((and bracket
11229 (>= js2-language-version 170)
11230 (not (js2-same-line bracket))
11231 (setq beg (js2-indent-in-array-comp parse-status))
11232 (>= (point) (save-excursion
11233 (goto-char beg)
11234 (point-at-bol)))) ; at or after first loop?
11235 (js2-array-comp-indentation parse-status beg))
11236
11237 (ctrl-stmt-indent)
11238
11239 ((and declaration-indent continued-expr-p)
11240 (+ declaration-indent js2-basic-offset))
11241
11242 (declaration-indent)
11243
11244 (bracket
11245 (goto-char bracket)
11246 (cond
11247 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
11248 (when (save-excursion (skip-chars-backward " \t)")
11249 (looking-at ")"))
11250 (backward-list))
11251 (back-to-indentation)
11252 (js2-maybe-goto-declaration-keyword-end bracket)
11253 (setq indent
11254 (cond (same-indent-p
11255 (current-column))
11256 (continued-expr-p
11257 (+ (current-column) (* 2 js2-basic-offset)))
11258 (t
11259 (+ (current-column) js2-basic-offset))))
11260 (if (and js2-indent-switch-body
11261 (not at-closing-bracket)
11262 (looking-at "\\_<switch\\_>"))
11263 (+ indent js2-basic-offset)
11264 indent))
11265 (t
11266 (unless same-indent-p
11267 (forward-char)
11268 (skip-chars-forward " \t"))
11269 (current-column))))
11270
11271 (continued-expr-p js2-basic-offset)
11272
11273 (t 0)))))
11274
11275 (defun js2-lineup-comment (parse-status)
11276 "Indent a multi-line block comment continuation line."
11277 (let* ((beg (nth 8 parse-status))
11278 (first-line (js2-same-line beg))
11279 (offset (save-excursion
11280 (goto-char beg)
11281 (if (looking-at "/\\*")
11282 (+ 1 (current-column))
11283 0))))
11284 (unless first-line
11285 (indent-line-to offset))))
11286
11287 (defun js2-backward-sws ()
11288 "Move backward through whitespace and comments."
11289 (interactive)
11290 (while (forward-comment -1)))
11291
11292 (defun js2-forward-sws ()
11293 "Move forward through whitespace and comments."
11294 (interactive)
11295 (while (forward-comment 1)))
11296
11297 (defun js2-arglist-close ()
11298 "Return non-nil if we're on a line beginning with a close-paren/brace."
11299 (save-excursion
11300 (goto-char (point-at-bol))
11301 (js2-forward-sws)
11302 (looking-at "[])}]")))
11303
11304 (defun js2-indent-looks-like-label-p ()
11305 (goto-char (point-at-bol))
11306 (js2-forward-sws)
11307 (looking-at (concat js2-mode-identifier-re ":")))
11308
11309 (defun js2-indent-in-objlit-p (parse-status)
11310 "Return non-nil if this looks like an object-literal entry."
11311 (let ((start (nth 1 parse-status)))
11312 (and
11313 start
11314 (save-excursion
11315 (and (zerop (forward-line -1))
11316 (not (< (point) start)) ; crossed a {} boundary
11317 (js2-indent-looks-like-label-p)))
11318 (save-excursion
11319 (js2-indent-looks-like-label-p)))))
11320
11321 ;; If prev line looks like foobar({ then we're passing an object
11322 ;; literal to a function call, and people pretty much always want to
11323 ;; de-dent back to the previous line, so move the 'basic-offset'
11324 ;; position to the front.
11325 (defun js2-indent-objlit-arg-p (parse-status)
11326 (save-excursion
11327 (back-to-indentation)
11328 (js2-backward-sws)
11329 (and (eq (1- (point)) (nth 1 parse-status))
11330 (eq (char-before) ?{)
11331 (progn
11332 (forward-char -1)
11333 (skip-chars-backward " \t")
11334 (eq (char-before) ?\()))))
11335
11336 (defun js2-indent-case-block-p ()
11337 (save-excursion
11338 (back-to-indentation)
11339 (js2-backward-sws)
11340 (goto-char (point-at-bol))
11341 (skip-chars-forward " \t")
11342 (looking-at "case\\s-.+:")))
11343
11344 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
11345 "Cycle among alternate computed indentation positions.
11346 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11347 of the buffer to the current point. NORMAL-COL is the indentation
11348 column computed by the heuristic guesser based on current paren,
11349 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11350 in reverse."
11351 (let ((cur-indent (current-indentation))
11352 (old-buffer-undo-list buffer-undo-list)
11353 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11354 (current-line (save-excursion
11355 (forward-line 0) ; move to bol
11356 (1+ (count-lines (point-min) (point)))))
11357 positions pos main-pos anchor arglist-cont same-indent
11358 basic-offset computed-pos)
11359 ;; temporarily don't record undo info, if user requested this
11360 (when js2-mode-indent-inhibit-undo
11361 (setq buffer-undo-list t))
11362 (unwind-protect
11363 (progn
11364 ;; First likely point: indent from beginning of previous code line
11365 (push (setq basic-offset
11366 (+ (save-excursion
11367 (back-to-indentation)
11368 (js2-backward-sws)
11369 (back-to-indentation)
11370 (current-column))
11371 js2-basic-offset))
11372 positions)
11373
11374 ;; (First + epsilon) likely point: indent 2x from beginning of
11375 ;; previous code line. Google does it this way.
11376 (push (setq basic-offset
11377 (+ (save-excursion
11378 (back-to-indentation)
11379 (js2-backward-sws)
11380 (back-to-indentation)
11381 (current-column))
11382 (* 2 js2-basic-offset)))
11383 positions)
11384
11385 ;; Second likely point: indent from assign-expr RHS. This
11386 ;; is just a crude guess based on finding " = " on the previous
11387 ;; line containing actual code.
11388 (setq pos (save-excursion
11389 (forward-line -1)
11390 (goto-char (point-at-bol))
11391 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11392 (point-at-eol) t)
11393 (goto-char (match-end 1))
11394 (skip-chars-forward " \t\r\n")
11395 (current-column))))
11396 (when pos
11397 (cl-incf pos js2-basic-offset)
11398 (push pos positions))
11399
11400 ;; Third likely point: same indent as previous line of code.
11401 ;; Make it the first likely point if we're not on an
11402 ;; arglist-close line and previous line ends in a comma, or
11403 ;; both this line and prev line look like object-literal
11404 ;; elements.
11405 (setq pos (save-excursion
11406 (goto-char (point-at-bol))
11407 (js2-backward-sws)
11408 (back-to-indentation)
11409 (prog1
11410 (current-column)
11411 ;; while we're here, look for trailing comma
11412 (if (save-excursion
11413 (goto-char (point-at-eol))
11414 (js2-backward-sws)
11415 (eq (char-before) ?,))
11416 (setq arglist-cont (1- (point)))))))
11417 (when pos
11418 (if (and (or arglist-cont
11419 (js2-indent-in-objlit-p parse-status))
11420 (not (js2-arglist-close)))
11421 (setq same-indent pos))
11422 (push pos positions))
11423
11424 ;; Fourth likely point: first preceding code with less indentation.
11425 ;; than the immediately preceding code line.
11426 (setq pos (save-excursion
11427 (back-to-indentation)
11428 (js2-backward-sws)
11429 (back-to-indentation)
11430 (setq anchor (current-column))
11431 (while (and (zerop (forward-line -1))
11432 (>= (progn
11433 (back-to-indentation)
11434 (current-column))
11435 anchor)))
11436 (setq pos (current-column))))
11437 (push pos positions)
11438
11439 ;; nesting-heuristic position, main by default
11440 (push (setq main-pos normal-col) positions)
11441
11442 ;; delete duplicates and sort positions list
11443 (setq positions (sort (delete-dups positions) '<))
11444
11445 ;; comma-list continuation lines: prev line indent takes precedence
11446 (if same-indent
11447 (setq main-pos same-indent))
11448
11449 ;; common special cases where we want to indent in from previous line
11450 (if (or (js2-indent-case-block-p)
11451 (js2-indent-objlit-arg-p parse-status))
11452 (setq main-pos basic-offset))
11453
11454 ;; if bouncing backwards, reverse positions list
11455 (if backwards
11456 (setq positions (reverse positions)))
11457
11458 ;; record whether we're already sitting on one of the alternatives
11459 (setq pos (member cur-indent positions))
11460
11461 (cond
11462 ;; case 0: we're one one of the alternatives and this is the
11463 ;; first time they've pressed TAB on this line (best-guess).
11464 ((and js2-mode-indent-ignore-first-tab
11465 pos
11466 ;; first time pressing TAB on this line?
11467 (not (eq js2-mode-last-indented-line current-line)))
11468 ;; do nothing
11469 (setq computed-pos nil))
11470 ;; case 1: only one computed position => use it
11471 ((null (cdr positions))
11472 (setq computed-pos 0))
11473 ;; case 2: not on any of the computed spots => use main spot
11474 ((not pos)
11475 (setq computed-pos (js2-position main-pos positions)))
11476 ;; case 3: on last position: cycle to first position
11477 ((null (cdr pos))
11478 (setq computed-pos 0))
11479 ;; case 4: on intermediate position: cycle to next position
11480 (t
11481 (setq computed-pos (js2-position (cl-second pos) positions))))
11482
11483 ;; see if any hooks want to indent; otherwise we do it
11484 (cl-loop with result = nil
11485 for hook in js2-indent-hook
11486 while (null result)
11487 do
11488 (setq result (funcall hook positions computed-pos))
11489 finally do
11490 (unless (or result (null computed-pos))
11491 (indent-line-to (nth computed-pos positions)))))
11492
11493 ;; finally
11494 (if js2-mode-indent-inhibit-undo
11495 (setq buffer-undo-list old-buffer-undo-list))
11496 ;; see commentary for `js2-mode-last-indented-line'
11497 (setq js2-mode-last-indented-line current-line))))
11498
11499 (defun js2-indent-bounce-backwards ()
11500 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11501 cycles between the computed indentation positions in reverse order."
11502 (interactive)
11503 (js2-indent-line t))
11504
11505 (defun js2-1-line-comment-continuation-p ()
11506 "Return t if we're in a 1-line comment continuation.
11507 If so, we don't ever want to use bounce-indent."
11508 (save-excursion
11509 (and (progn
11510 (forward-line 0)
11511 (looking-at "\\s-*//"))
11512 (progn
11513 (forward-line -1)
11514 (forward-line 0)
11515 (when (looking-at "\\s-*$")
11516 (js2-backward-sws)
11517 (forward-line 0))
11518 (looking-at "\\s-*//")))))
11519
11520 (defun js2-indent-line (&optional bounce-backwards)
11521 "Indent the current line as JavaScript source text."
11522 (interactive)
11523 (let (parse-status offset indent-col
11524 ;; Don't whine about errors/warnings when we're indenting.
11525 ;; This has to be set before calling parse-partial-sexp below.
11526 (inhibit-point-motion-hooks t))
11527 (setq parse-status (save-excursion
11528 (syntax-ppss (point-at-bol)))
11529 offset (- (point) (save-excursion
11530 (back-to-indentation)
11531 (point))))
11532 ;; Don't touch multiline strings.
11533 (unless (nth 3 parse-status)
11534 (if (nth 4 parse-status)
11535 (js2-lineup-comment parse-status)
11536 (setq indent-col (js2-proper-indentation parse-status))
11537 ;; See comments below about `js2-mode-last-indented-line'.
11538 (cond
11539 ;; bounce-indenting is disabled during electric-key indent.
11540 ;; It doesn't work well on first line of buffer.
11541 ((and js2-bounce-indent-p
11542 (not (js2-same-line (point-min)))
11543 (not (js2-1-line-comment-continuation-p)))
11544 (js2-bounce-indent indent-col parse-status bounce-backwards))
11545 ;; just indent to the guesser's likely spot
11546 (t (indent-line-to indent-col))))
11547 (when (cl-plusp offset)
11548 (forward-char offset)))))
11549
11550 (defun js2-indent-region (start end)
11551 "Indent the region, but don't use bounce indenting."
11552 (let ((js2-bounce-indent-p nil)
11553 (indent-region-function nil)
11554 (after-change-functions (remq 'js2-mode-edit
11555 after-change-functions)))
11556 (indent-region start end nil) ; nil for byte-compiler
11557 (js2-mode-edit start end (- end start))))
11558
11559 (defvar js2-minor-mode-map
11560 (let ((map (make-sparse-keymap)))
11561 (define-key map (kbd "C-c C-`") #'js2-next-error)
11562 (define-key map [mouse-1] #'js2-mode-show-node)
11563 map)
11564 "Keymap used when `js2-minor-mode' is active.")
11565
11566 ;;;###autoload
11567 (define-minor-mode js2-minor-mode
11568 "Minor mode for running js2 as a background linter.
11569 This allows you to use a different major mode for JavaScript editing,
11570 such as `js-mode', while retaining the asynchronous error/warning
11571 highlighting features of `js2-mode'."
11572 :group 'js2-mode
11573 :lighter " js-lint"
11574 (if js2-minor-mode
11575 (js2-minor-mode-enter)
11576 (js2-minor-mode-exit)))
11577
11578 (defun js2-minor-mode-enter ()
11579 "Initialization for `js2-minor-mode'."
11580 (set (make-local-variable 'max-lisp-eval-depth)
11581 (max max-lisp-eval-depth 3000))
11582 (setq next-error-function #'js2-next-error)
11583 (js2-set-default-externs)
11584 ;; Experiment: make reparse-delay longer for longer files.
11585 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11586 (setq js2-idle-timer-delay
11587 (* js2-idle-timer-delay
11588 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11589 (setq js2-mode-buffer-dirty-p t
11590 js2-mode-parsing nil)
11591 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11592 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11593 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11594 (when js2-include-jslint-globals
11595 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11596 (run-hooks 'js2-init-hook)
11597 (js2-reparse))
11598
11599 (defun js2-minor-mode-exit ()
11600 "Turn off `js2-minor-mode'."
11601 (setq next-error-function nil)
11602 (remove-hook 'after-change-functions #'js2-mode-edit t)
11603 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11604 (when js2-mode-node-overlay
11605 (delete-overlay js2-mode-node-overlay)
11606 (setq js2-mode-node-overlay nil))
11607 (js2-remove-overlays)
11608 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11609 (setq js2-mode-ast nil))
11610
11611 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11612 (make-variable-buffer-local 'js2-source-buffer)
11613
11614 (cl-defun js2-display-error-list ()
11615 "Display a navigable buffer listing parse errors/warnings."
11616 (interactive)
11617 (unless (js2-have-errors-p)
11618 (message "No errors")
11619 (cl-return-from js2-display-error-list))
11620 (cl-labels ((annotate-list
11621 (lst type)
11622 "Add diagnostic TYPE and line number to errs list"
11623 (mapcar (lambda (err)
11624 (list err type (line-number-at-pos (nth 1 err))))
11625 lst)))
11626 (let* ((srcbuf (current-buffer))
11627 (errbuf (get-buffer-create "*js-lint*"))
11628 (errors (annotate-list
11629 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11630 'js2-error)) ; must be a valid face name
11631 (warnings (annotate-list
11632 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11633 'js2-warning)) ; must be a valid face name
11634 (all-errs (sort (append errors warnings)
11635 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11636 (with-current-buffer errbuf
11637 (let ((inhibit-read-only t))
11638 (erase-buffer)
11639 (dolist (err all-errs)
11640 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11641 (insert-text-button
11642 (format "line %d: %s" line (js2-get-msg msg-key))
11643 'face type
11644 'follow-link "\C-m"
11645 'action 'js2-error-buffer-jump
11646 'js2-msg (js2-get-msg msg-key)
11647 'js2-pos beg)
11648 (insert "\n"))))
11649 (js2-error-buffer-mode)
11650 (setq js2-source-buffer srcbuf)
11651 (pop-to-buffer errbuf)
11652 (goto-char (point-min))
11653 (unless (eobp)
11654 (js2-error-buffer-view))))))
11655
11656 (defvar js2-error-buffer-mode-map
11657 (let ((map (make-sparse-keymap)))
11658 (define-key map "n" #'js2-error-buffer-next)
11659 (define-key map "p" #'js2-error-buffer-prev)
11660 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11661 (define-key map "o" #'js2-error-buffer-view)
11662 (define-key map "q" #'js2-error-buffer-quit)
11663 map)
11664 "Keymap used for js2 diagnostics buffers.")
11665
11666 (defun js2-error-buffer-mode ()
11667 "Major mode for js2 diagnostics buffers.
11668 Selecting an error will jump it to the corresponding source-buffer error.
11669 \\{js2-error-buffer-mode-map}"
11670 (interactive)
11671 (setq major-mode 'js2-error-buffer-mode
11672 mode-name "JS Lint Diagnostics")
11673 (use-local-map js2-error-buffer-mode-map)
11674 (setq truncate-lines t)
11675 (set-buffer-modified-p nil)
11676 (setq buffer-read-only t)
11677 (run-hooks 'js2-error-buffer-mode-hook))
11678
11679 (defun js2-error-buffer-next ()
11680 "Move to next error and view it."
11681 (interactive)
11682 (when (zerop (forward-line 1))
11683 (js2-error-buffer-view)))
11684
11685 (defun js2-error-buffer-prev ()
11686 "Move to previous error and view it."
11687 (interactive)
11688 (when (zerop (forward-line -1))
11689 (js2-error-buffer-view)))
11690
11691 (defun js2-error-buffer-quit ()
11692 "Kill the current buffer."
11693 (interactive)
11694 (kill-buffer))
11695
11696 (defun js2-error-buffer-jump (&rest ignored)
11697 "Jump cursor to current error in source buffer."
11698 (interactive)
11699 (when (js2-error-buffer-view)
11700 (pop-to-buffer js2-source-buffer)))
11701
11702 (defun js2-error-buffer-view ()
11703 "Scroll source buffer to show error at current line."
11704 (interactive)
11705 (cond
11706 ((not (eq major-mode 'js2-error-buffer-mode))
11707 (message "Not in a js2 errors buffer"))
11708 ((not (buffer-live-p js2-source-buffer))
11709 (message "Source buffer has been killed"))
11710 ((not (wholenump (get-text-property (point) 'js2-pos)))
11711 (message "There does not seem to be an error here"))
11712 (t
11713 (let ((pos (get-text-property (point) 'js2-pos))
11714 (msg (get-text-property (point) 'js2-msg)))
11715 (save-selected-window
11716 (pop-to-buffer js2-source-buffer)
11717 (goto-char pos)
11718 (message msg))))))
11719
11720 ;;;###autoload
11721 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11722 ;; FIXME: Should derive from js-mode.
11723 "Major mode for editing JavaScript code."
11724 ;; Used by comment-region; don't change it.
11725 (set (make-local-variable 'comment-start) "//")
11726 (set (make-local-variable 'comment-end) "")
11727 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11728 (set (make-local-variable 'max-lisp-eval-depth)
11729 (max max-lisp-eval-depth 3000))
11730 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11731 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11732 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11733 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11734 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11735 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11736 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11737 ;; for characters inside regexp literals.
11738 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11739 ;; this is necessary to make `show-paren-function' work properly
11740 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11741 ;; needed for M-x rgrep, among other things
11742 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11743
11744 (set (make-local-variable 'electric-indent-chars)
11745 (append "{}()[]:;,*." electric-indent-chars))
11746 (set (make-local-variable 'electric-layout-rules)
11747 '((?\; . after) (?\{ . after) (?\} . before)))
11748
11749 ;; some variables needed by cc-engine for paragraph-fill, etc.
11750 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11751 c-comment-start-regexp "/[*/]\\|\\s|"
11752 c-line-comment-starter "//"
11753 c-paragraph-start js2-paragraph-start
11754 c-paragraph-separate "$"
11755 c-syntactic-ws-start js2-syntactic-ws-start
11756 c-syntactic-ws-end js2-syntactic-ws-end
11757 c-syntactic-eol js2-syntactic-eol)
11758
11759 (let ((c-buffer-is-cc-mode t))
11760 ;; Copied from `js-mode'. Also see Bug#6071.
11761 (make-local-variable 'paragraph-start)
11762 (make-local-variable 'paragraph-separate)
11763 (make-local-variable 'paragraph-ignore-fill-prefix)
11764 (make-local-variable 'adaptive-fill-mode)
11765 (make-local-variable 'adaptive-fill-regexp)
11766 (c-setup-paragraph-variables))
11767
11768 (setq font-lock-defaults '(nil t))
11769
11770 ;; Experiment: make reparse-delay longer for longer files.
11771 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11772 (setq js2-idle-timer-delay
11773 (* js2-idle-timer-delay
11774 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11775
11776 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11777 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11778 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11779 (setq next-error-function #'js2-next-error)
11780 (imenu-add-to-menubar (concat "IM-" mode-name))
11781 (add-to-invisibility-spec '(js2-outline . t))
11782 (set (make-local-variable 'line-move-ignore-invisible) t)
11783 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11784 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11785
11786 (setq js2-mode-functions-hidden nil
11787 js2-mode-comments-hidden nil
11788 js2-mode-buffer-dirty-p t
11789 js2-mode-parsing nil)
11790
11791 (js2-set-default-externs)
11792
11793 (when js2-include-jslint-globals
11794 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11795
11796 (run-hooks 'js2-init-hook)
11797
11798 (js2-reparse))
11799
11800 (defun js2-mode-exit ()
11801 "Exit `js2-mode' and clean up."
11802 (interactive)
11803 (when js2-mode-node-overlay
11804 (delete-overlay js2-mode-node-overlay)
11805 (setq js2-mode-node-overlay nil))
11806 (js2-remove-overlays)
11807 (setq js2-mode-ast nil)
11808 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11809 (remove-from-invisibility-spec '(js2-outline . t))
11810 (js2-mode-show-all)
11811 (with-silent-modifications
11812 (js2-clear-face (point-min) (point-max))))
11813
11814 (defun js2-mode-reset-timer ()
11815 "Cancel any existing parse timer and schedule a new one."
11816 (if js2-mode-parse-timer
11817 (cancel-timer js2-mode-parse-timer))
11818 (setq js2-mode-parsing nil)
11819 (let ((timer (timer-create)))
11820 (setq js2-mode-parse-timer timer)
11821 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11822 (timer-set-idle-time timer js2-idle-timer-delay)
11823 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11824 (timer-activate-when-idle timer nil)))
11825
11826 (defun js2-mode-idle-reparse (buffer)
11827 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11828 it to be reparsed when the buffer is selected."
11829 (cond ((eq buffer (current-buffer))
11830 (js2-reparse))
11831 ((buffer-live-p buffer)
11832 ;; reparse when the buffer is selected again
11833 (with-current-buffer buffer
11834 (add-hook 'window-configuration-change-hook
11835 #'js2-mode-idle-reparse-inner
11836 nil t)))))
11837
11838 (defun js2-mode-idle-reparse-inner ()
11839 (remove-hook 'window-configuration-change-hook
11840 #'js2-mode-idle-reparse-inner
11841 t)
11842 (js2-reparse))
11843
11844 (defun js2-mode-edit (_beg _end _len)
11845 "Schedule a new parse after buffer is edited.
11846 Buffer edit spans from BEG to END and is of length LEN."
11847 (setq js2-mode-buffer-dirty-p t)
11848 (js2-mode-hide-overlay)
11849 (js2-mode-reset-timer))
11850
11851 (defun js2-minor-mode-edit (_beg _end _len)
11852 "Callback for buffer edits in `js2-mode'.
11853 Schedules a new parse after buffer is edited.
11854 Buffer edit spans from BEG to END and is of length LEN."
11855 (setq js2-mode-buffer-dirty-p t)
11856 (js2-mode-hide-overlay)
11857 (js2-mode-reset-timer))
11858
11859 (defun js2-reparse (&optional force)
11860 "Re-parse current buffer after user finishes some data entry.
11861 If we get any user input while parsing, including cursor motion,
11862 we discard the parse and reschedule it. If FORCE is nil, then the
11863 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11864 (let (time
11865 interrupted-p
11866 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11867 (unless js2-mode-parsing
11868 (setq js2-mode-parsing t)
11869 (unwind-protect
11870 (when (or js2-mode-buffer-dirty-p force)
11871 (js2-remove-overlays)
11872 (setq js2-mode-buffer-dirty-p nil
11873 js2-mode-fontifications nil
11874 js2-mode-deferred-properties nil)
11875 (if js2-mode-verbose-parse-p
11876 (message "parsing..."))
11877 (setq time
11878 (js2-time
11879 (setq interrupted-p
11880 (catch 'interrupted
11881 (js2-parse)
11882 (with-silent-modifications
11883 ;; if parsing is interrupted, comments and regex
11884 ;; literals stay ignored by `parse-partial-sexp'
11885 (remove-text-properties (point-min) (point-max)
11886 '(syntax-table))
11887 (js2-mode-apply-deferred-properties)
11888 (js2-mode-remove-suppressed-warnings)
11889 (js2-mode-show-warnings)
11890 (js2-mode-show-errors)
11891 (if (>= js2-highlight-level 1)
11892 (js2-highlight-jsdoc js2-mode-ast)))
11893 nil))))
11894 (if interrupted-p
11895 (progn
11896 ;; unfinished parse => try again
11897 (setq js2-mode-buffer-dirty-p t)
11898 (js2-mode-reset-timer))
11899 (if js2-mode-verbose-parse-p
11900 (message "Parse time: %s" time))))
11901 (setq js2-mode-parsing nil)
11902 (unless interrupted-p
11903 (setq js2-mode-parse-timer nil))))))
11904
11905 (defun js2-mode-show-node (event)
11906 "Debugging aid: highlight selected AST node on mouse click."
11907 (interactive "e")
11908 (mouse-set-point event)
11909 (setq deactivate-mark t)
11910 (when js2-mode-show-overlay
11911 (let ((node (js2-node-at-point))
11912 beg end)
11913 (if (null node)
11914 (message "No node found at location %s" (point))
11915 (setq beg (js2-node-abs-pos node)
11916 end (+ beg (js2-node-len node)))
11917 (if js2-mode-node-overlay
11918 (move-overlay js2-mode-node-overlay beg end)
11919 (setq js2-mode-node-overlay (make-overlay beg end))
11920 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11921 (with-silent-modifications
11922 (if (fboundp 'cursor-sensor-mode)
11923 (put-text-property beg end 'cursor-sensor-functions
11924 '(js2-mode-hide-overlay))
11925 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11926 (message "%s, parent: %s"
11927 (js2-node-short-name node)
11928 (if (js2-node-parent node)
11929 (js2-node-short-name (js2-node-parent node))
11930 "nil"))))))
11931
11932 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11933 "Remove the debugging overlay when point moves.
11934 ARG1, ARG2 and ARG3 have different values depending on whether this function
11935 was found on `point-left' or in `cursor-sensor-functions'."
11936 (when js2-mode-node-overlay
11937 (let ((beg (overlay-start js2-mode-node-overlay))
11938 (end (overlay-end js2-mode-node-overlay))
11939 (p2 (if (windowp arg1)
11940 ;; Called from cursor-sensor-functions.
11941 (window-point arg1)
11942 ;; Called from point-left.
11943 arg2)))
11944 ;; Sometimes we're called spuriously.
11945 (unless (and p2
11946 (>= p2 beg)
11947 (<= p2 end))
11948 (with-silent-modifications
11949 (remove-text-properties beg end
11950 '(point-left nil cursor-sensor-functions)))
11951 (delete-overlay js2-mode-node-overlay)
11952 (setq js2-mode-node-overlay nil)))))
11953
11954 (defun js2-mode-reset ()
11955 "Debugging helper: reset everything."
11956 (interactive)
11957 (js2-mode-exit)
11958 (js2-mode))
11959
11960 (defun js2-mode-show-warn-or-err (e face)
11961 "Highlight a warning or error E with FACE.
11962 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11963 The last element is optional. When present, use instead of FACE."
11964 (let* ((key (cl-first e))
11965 (beg (cl-second e))
11966 (end (+ beg (cl-third e)))
11967 ;; Don't inadvertently go out of bounds.
11968 (beg (max (point-min) (min beg (point-max))))
11969 (end (max (point-min) (min end (point-max))))
11970 (ovl (make-overlay beg end)))
11971 ;; FIXME: Why a mix of overlays and text-properties?
11972 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11973 (overlay-put ovl 'js2-error t)
11974 (put-text-property beg end 'help-echo (js2-get-msg key))
11975 (if (fboundp 'cursor-sensor-mode)
11976 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11977 (put-text-property beg end 'point-entered #'js2-echo-error))))
11978
11979 (defun js2-remove-overlays ()
11980 "Remove overlays from buffer that have a `js2-error' property."
11981 (let ((beg (point-min))
11982 (end (point-max)))
11983 (save-excursion
11984 (dolist (o (overlays-in beg end))
11985 (when (overlay-get o 'js2-error)
11986 (delete-overlay o))))))
11987
11988 (defun js2-mode-apply-deferred-properties ()
11989 "Apply fontifications and other text properties recorded during parsing."
11990 (when (cl-plusp js2-highlight-level)
11991 ;; We defer clearing faces as long as possible to eliminate flashing.
11992 (js2-clear-face (point-min) (point-max))
11993 ;; Have to reverse the recorded fontifications list so that errors
11994 ;; and warnings overwrite the normal fontifications.
11995 (dolist (f (nreverse js2-mode-fontifications))
11996 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11997 (setq js2-mode-fontifications nil))
11998 (dolist (p js2-mode-deferred-properties)
11999 (apply #'put-text-property p))
12000 (setq js2-mode-deferred-properties nil))
12001
12002 (defun js2-mode-show-errors ()
12003 "Highlight syntax errors."
12004 (when js2-mode-show-parse-errors
12005 (dolist (e (js2-ast-root-errors js2-mode-ast))
12006 (js2-mode-show-warn-or-err e 'js2-error))))
12007
12008 (defun js2-mode-remove-suppressed-warnings ()
12009 "Take suppressed warnings out of the AST warnings list.
12010 This ensures that the counts and `next-error' are correct."
12011 (setf (js2-ast-root-warnings js2-mode-ast)
12012 (js2-delete-if
12013 (lambda (e)
12014 (let ((key (caar e)))
12015 (or
12016 (and (not js2-strict-trailing-comma-warning)
12017 (string-match "trailing\\.comma" key))
12018 (and (not js2-strict-cond-assign-warning)
12019 (string= key "msg.equal.as.assign"))
12020 (and js2-missing-semi-one-line-override
12021 (string= key "msg.missing.semi")
12022 (let* ((beg (cl-second e))
12023 (node (js2-node-at-point beg))
12024 (fn (js2-mode-find-parent-fn node))
12025 (body (and fn (js2-function-node-body fn)))
12026 (lc (and body (js2-node-abs-pos body)))
12027 (rc (and lc (+ lc (js2-node-len body)))))
12028 (and fn
12029 (or (null body)
12030 (save-excursion
12031 (goto-char beg)
12032 (and (js2-same-line lc)
12033 (js2-same-line rc))))))))))
12034 (js2-ast-root-warnings js2-mode-ast))))
12035
12036 (defun js2-mode-show-warnings ()
12037 "Highlight strict-mode warnings."
12038 (when js2-mode-show-strict-warnings
12039 (dolist (e (js2-ast-root-warnings js2-mode-ast))
12040 (js2-mode-show-warn-or-err e 'js2-warning))))
12041
12042 (defun js2-echo-error (arg1 arg2 &optional _arg3)
12043 "Called by point-motion hooks.
12044 ARG1, ARG2 and ARG3 have different values depending on whether this function
12045 was found on `point-entered' or in `cursor-sensor-functions'."
12046 (let* ((new-point (if (windowp arg1)
12047 ;; Called from cursor-sensor-functions.
12048 (window-point arg1)
12049 ;; Called from point-left.
12050 arg2))
12051 (msg (get-text-property new-point 'help-echo)))
12052 (when (and (stringp msg)
12053 (not (active-minibuffer-window))
12054 (not (current-message)))
12055 (message msg))))
12056
12057 (defun js2-line-break (&optional _soft)
12058 "Break line at point and indent, continuing comment if within one.
12059 If inside a string, and `js2-concat-multiline-strings' is not
12060 nil, turn it into concatenation."
12061 (interactive)
12062 (let ((parse-status (syntax-ppss)))
12063 (cond
12064 ;; Check if we're inside a string.
12065 ((nth 3 parse-status)
12066 (if js2-concat-multiline-strings
12067 (js2-mode-split-string parse-status)
12068 (insert "\n")))
12069 ;; Check if inside a block comment.
12070 ((nth 4 parse-status)
12071 (js2-mode-extend-comment (nth 8 parse-status)))
12072 (t
12073 (newline-and-indent)))))
12074
12075 (defun js2-mode-split-string (parse-status)
12076 "Turn a newline in mid-string into a string concatenation.
12077 PARSE-STATUS is as documented in `parse-partial-sexp'."
12078 (let* ((quote-char (nth 3 parse-status))
12079 (at-eol (eq js2-concat-multiline-strings 'eol)))
12080 (insert quote-char)
12081 (insert (if at-eol " +\n" "\n"))
12082 (unless at-eol
12083 (insert "+ "))
12084 (js2-indent-line)
12085 (insert quote-char)
12086 (when (eolp)
12087 (insert quote-char)
12088 (backward-char 1))))
12089
12090 (defun js2-mode-extend-comment (start-pos)
12091 "Indent the line and, when inside a comment block, add comment prefix."
12092 (let (star single col first-line needs-close)
12093 (save-excursion
12094 (back-to-indentation)
12095 (when (< (point) start-pos)
12096 (goto-char start-pos))
12097 (cond
12098 ((looking-at "\\*[^/]")
12099 (setq star t
12100 col (current-column)))
12101 ((looking-at "/\\*")
12102 (setq star t
12103 first-line t
12104 col (1+ (current-column))))
12105 ((looking-at "//")
12106 (setq single t
12107 col (current-column)))))
12108 ;; Heuristic for whether we need to close the comment:
12109 ;; if we've got a parse error here, assume it's an unterminated
12110 ;; comment.
12111 (setq needs-close
12112 (or
12113 (get-char-property (1- (point)) 'js2-error)
12114 ;; The heuristic above doesn't work well when we're
12115 ;; creating a comment and there's another one downstream,
12116 ;; as our parser thinks this one ends at the end of the
12117 ;; next one. (You can have a /* inside a js block comment.)
12118 ;; So just close it if the next non-ws char isn't a *.
12119 (and first-line
12120 (eolp)
12121 (save-excursion
12122 (skip-chars-forward " \t\r\n")
12123 (not (eq (char-after) ?*))))))
12124 (delete-horizontal-space)
12125 (insert "\n")
12126 (cond
12127 (star
12128 (indent-to col)
12129 (insert "* ")
12130 (if (and first-line needs-close)
12131 (save-excursion
12132 (insert "\n")
12133 (indent-to col)
12134 (insert "*/"))))
12135 ((and single
12136 (save-excursion
12137 (and (zerop (forward-line 1))
12138 (looking-at "\\s-*//"))))
12139 (indent-to col)
12140 (insert "// ")))
12141 ;; Don't need to extend the comment after all.
12142 (js2-indent-line)))
12143
12144 (defun js2-beginning-of-line ()
12145 "Toggle point between bol and first non-whitespace char in line.
12146 Also moves past comment delimiters when inside comments."
12147 (interactive)
12148 (let (node)
12149 (cond
12150 ((bolp)
12151 (back-to-indentation))
12152 ((looking-at "//")
12153 (skip-chars-forward "/ \t"))
12154 ((and (eq (char-after) ?*)
12155 (setq node (js2-comment-at-point))
12156 (memq (js2-comment-node-format node) '(jsdoc block))
12157 (save-excursion
12158 (skip-chars-backward " \t")
12159 (bolp)))
12160 (skip-chars-forward "\* \t"))
12161 (t
12162 (goto-char (point-at-bol))))))
12163
12164 (defun js2-end-of-line ()
12165 "Toggle point between eol and last non-whitespace char in line."
12166 (interactive)
12167 (if (eolp)
12168 (skip-chars-backward " \t")
12169 (goto-char (point-at-eol))))
12170
12171 (defun js2-mode-wait-for-parse (callback)
12172 "Invoke CALLBACK when parsing is finished.
12173 If parsing is already finished, calls CALLBACK immediately."
12174 (if (not js2-mode-buffer-dirty-p)
12175 (funcall callback)
12176 (push callback js2-mode-pending-parse-callbacks)
12177 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
12178
12179 (defun js2-mode-parse-finished ()
12180 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
12181 ;; We can't let errors propagate up, since it prevents the
12182 ;; `js2-parse' method from completing normally and returning
12183 ;; the ast, which makes things mysteriously not work right.
12184 (unwind-protect
12185 (dolist (cb js2-mode-pending-parse-callbacks)
12186 (condition-case err
12187 (funcall cb)
12188 (error (message "%s" err))))
12189 (setq js2-mode-pending-parse-callbacks nil)))
12190
12191 (defun js2-mode-flag-region (from to flag)
12192 "Hide or show text from FROM to TO, according to FLAG.
12193 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
12194 Returns the created overlay if FLAG is non-nil."
12195 (remove-overlays from to 'invisible 'js2-outline)
12196 (when flag
12197 (let ((o (make-overlay from to)))
12198 (overlay-put o 'invisible 'js2-outline)
12199 (overlay-put o 'isearch-open-invisible
12200 'js2-isearch-open-invisible)
12201 o)))
12202
12203 ;; Function to be set as an outline-isearch-open-invisible' property
12204 ;; to the overlay that makes the outline invisible (see
12205 ;; `js2-mode-flag-region').
12206 (defun js2-isearch-open-invisible (_overlay)
12207 ;; We rely on the fact that isearch places point on the matched text.
12208 (js2-mode-show-element))
12209
12210 (defun js2-mode-invisible-overlay-bounds (&optional pos)
12211 "Return cons cell of bounds of folding overlay at POS.
12212 Returns nil if not found."
12213 (let ((overlays (overlays-at (or pos (point))))
12214 o)
12215 (while (and overlays
12216 (not o))
12217 (if (overlay-get (car overlays) 'invisible)
12218 (setq o (car overlays))
12219 (setq overlays (cdr overlays))))
12220 (if o
12221 (cons (overlay-start o) (overlay-end o)))))
12222
12223 (defun js2-mode-function-at-point (&optional pos)
12224 "Return the innermost function node enclosing current point.
12225 Returns nil if point is not in a function."
12226 (let ((node (js2-node-at-point pos)))
12227 (while (and node (not (js2-function-node-p node)))
12228 (setq node (js2-node-parent node)))
12229 (if (js2-function-node-p node)
12230 node)))
12231
12232 (defun js2-mode-toggle-element ()
12233 "Hide or show the foldable element at the point."
12234 (interactive)
12235 (let (comment fn pos)
12236 (save-excursion
12237 (cond
12238 ;; /* ... */ comment?
12239 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
12240 (if (js2-mode-invisible-overlay-bounds
12241 (setq pos (+ 3 (js2-node-abs-pos comment))))
12242 (progn
12243 (goto-char pos)
12244 (js2-mode-show-element))
12245 (js2-mode-hide-element)))
12246 ;; //-comment?
12247 ((save-excursion
12248 (back-to-indentation)
12249 (looking-at js2-mode-//-comment-re))
12250 (js2-mode-toggle-//-comment))
12251 ;; function?
12252 ((setq fn (js2-mode-function-at-point))
12253 (setq pos (and (js2-function-node-body fn)
12254 (js2-node-abs-pos (js2-function-node-body fn))))
12255 (goto-char (1+ pos))
12256 (if (js2-mode-invisible-overlay-bounds)
12257 (js2-mode-show-element)
12258 (js2-mode-hide-element)))
12259 (t
12260 (message "Nothing at point to hide or show"))))))
12261
12262 (defun js2-mode-hide-element ()
12263 "Fold/hide contents of a block, showing ellipses.
12264 Show the hidden text with \\[js2-mode-show-element]."
12265 (interactive)
12266 (if js2-mode-buffer-dirty-p
12267 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12268 (let (node body beg end)
12269 (cond
12270 ((js2-mode-invisible-overlay-bounds)
12271 (message "already hidden"))
12272 (t
12273 (setq node (js2-node-at-point))
12274 (cond
12275 ((js2-block-comment-p node)
12276 (js2-mode-hide-comment node))
12277 (t
12278 (while (and node (not (js2-function-node-p node)))
12279 (setq node (js2-node-parent node)))
12280 (if (and node
12281 (setq body (js2-function-node-body node)))
12282 (progn
12283 (setq beg (js2-node-abs-pos body)
12284 end (+ beg (js2-node-len body)))
12285 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12286 (message "No collapsable element found at point"))))))))
12287
12288 (defun js2-mode-show-element ()
12289 "Show the hidden element at current point."
12290 (interactive)
12291 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12292 (if bounds
12293 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12294 (message "Nothing to un-hide"))))
12295
12296 (defun js2-mode-show-all ()
12297 "Show all of the text in the buffer."
12298 (interactive)
12299 (js2-mode-flag-region (point-min) (point-max) nil))
12300
12301 (defun js2-mode-toggle-hide-functions ()
12302 (interactive)
12303 (if js2-mode-functions-hidden
12304 (js2-mode-show-functions)
12305 (js2-mode-hide-functions)))
12306
12307 (defun js2-mode-hide-functions ()
12308 "Hides all non-nested function bodies in the buffer.
12309 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12310 to open an individual entry."
12311 (interactive)
12312 (if js2-mode-buffer-dirty-p
12313 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12314 (if (null js2-mode-ast)
12315 (message "Oops - parsing failed")
12316 (setq js2-mode-functions-hidden t)
12317 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12318
12319 (defun js2-mode-function-hider (n endp)
12320 (when (not endp)
12321 (let ((tt (js2-node-type n))
12322 body beg end)
12323 (cond
12324 ((and (= tt js2-FUNCTION)
12325 (setq body (js2-function-node-body n)))
12326 (setq beg (js2-node-abs-pos body)
12327 end (+ beg (js2-node-len body)))
12328 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12329 nil) ; don't process children of function
12330 (t
12331 t))))) ; keep processing other AST nodes
12332
12333 (defun js2-mode-show-functions ()
12334 "Un-hide any folded function bodies in the buffer."
12335 (interactive)
12336 (setq js2-mode-functions-hidden nil)
12337 (save-excursion
12338 (goto-char (point-min))
12339 (while (/= (goto-char (next-overlay-change (point)))
12340 (point-max))
12341 (dolist (o (overlays-at (point)))
12342 (when (and (overlay-get o 'invisible)
12343 (not (overlay-get o 'comment)))
12344 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12345
12346 (defun js2-mode-hide-comment (n)
12347 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12348 3 ; /**
12349 2)) ; /*
12350 (beg (+ (js2-node-abs-pos n) head))
12351 (end (- (+ beg (js2-node-len n)) head 2))
12352 (o (js2-mode-flag-region beg end 'hide)))
12353 (overlay-put o 'comment t)))
12354
12355 (defun js2-mode-toggle-hide-comments ()
12356 "Folds all block comments in the buffer.
12357 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12358 to open an individual entry."
12359 (interactive)
12360 (if js2-mode-comments-hidden
12361 (js2-mode-show-comments)
12362 (js2-mode-hide-comments)))
12363
12364 (defun js2-mode-hide-comments ()
12365 (interactive)
12366 (if js2-mode-buffer-dirty-p
12367 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12368 (if (null js2-mode-ast)
12369 (message "Oops - parsing failed")
12370 (setq js2-mode-comments-hidden t)
12371 (dolist (n (js2-ast-root-comments js2-mode-ast))
12372 (when (js2-block-comment-p n)
12373 (js2-mode-hide-comment n)))
12374 (js2-mode-hide-//-comments)))
12375
12376 (defun js2-mode-extend-//-comment (direction)
12377 "Find start or end of a block of similar //-comment lines.
12378 DIRECTION is -1 to look back, 1 to look forward.
12379 INDENT is the indentation level to match.
12380 Returns the end-of-line position of the furthest adjacent
12381 //-comment line with the same indentation as the current line.
12382 If there is no such matching line, returns current end of line."
12383 (let ((pos (point-at-eol))
12384 (indent (current-indentation)))
12385 (save-excursion
12386 (while (and (zerop (forward-line direction))
12387 (looking-at js2-mode-//-comment-re)
12388 (eq indent (length (match-string 1))))
12389 (setq pos (point-at-eol)))
12390 pos)))
12391
12392 (defun js2-mode-hide-//-comments ()
12393 "Fold adjacent 1-line comments, showing only snippet of first one."
12394 (let (beg end)
12395 (save-excursion
12396 (goto-char (point-min))
12397 (while (re-search-forward js2-mode-//-comment-re nil t)
12398 (setq beg (point)
12399 end (js2-mode-extend-//-comment 1))
12400 (unless (eq beg end)
12401 (overlay-put (js2-mode-flag-region beg end 'hide)
12402 'comment t))
12403 (goto-char end)
12404 (forward-char 1)))))
12405
12406 (defun js2-mode-toggle-//-comment ()
12407 "Fold or un-fold any multi-line //-comment at point.
12408 Caller should have determined that this line starts with a //-comment."
12409 (let* ((beg (point-at-eol))
12410 (end beg))
12411 (save-excursion
12412 (goto-char end)
12413 (if (js2-mode-invisible-overlay-bounds)
12414 (js2-mode-show-element)
12415 ;; else hide the comment
12416 (setq beg (js2-mode-extend-//-comment -1)
12417 end (js2-mode-extend-//-comment 1))
12418 (unless (eq beg end)
12419 (overlay-put (js2-mode-flag-region beg end 'hide)
12420 'comment t))))))
12421
12422 (defun js2-mode-show-comments ()
12423 "Un-hide any hidden comments, leaving other hidden elements alone."
12424 (interactive)
12425 (setq js2-mode-comments-hidden nil)
12426 (save-excursion
12427 (goto-char (point-min))
12428 (while (/= (goto-char (next-overlay-change (point)))
12429 (point-max))
12430 (dolist (o (overlays-at (point)))
12431 (when (overlay-get o 'comment)
12432 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12433
12434 (defun js2-mode-display-warnings-and-errors ()
12435 "Turn on display of warnings and errors."
12436 (interactive)
12437 (setq js2-mode-show-parse-errors t
12438 js2-mode-show-strict-warnings t)
12439 (js2-reparse 'force))
12440
12441 (defun js2-mode-hide-warnings-and-errors ()
12442 "Turn off display of warnings and errors."
12443 (interactive)
12444 (setq js2-mode-show-parse-errors nil
12445 js2-mode-show-strict-warnings nil)
12446 (js2-reparse 'force))
12447
12448 (defun js2-mode-toggle-warnings-and-errors ()
12449 "Toggle the display of warnings and errors.
12450 Some users don't like having warnings/errors reported while they type."
12451 (interactive)
12452 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12453 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12454 (if (called-interactively-p 'any)
12455 (message "warnings and errors %s"
12456 (if js2-mode-show-parse-errors
12457 "enabled"
12458 "disabled")))
12459 (js2-reparse 'force))
12460
12461 (defun js2-mode-customize ()
12462 (interactive)
12463 (customize-group 'js2-mode))
12464
12465 (defun js2-mode-forward-sexp (&optional arg)
12466 "Move forward across one statement or balanced expression.
12467 With ARG, do it that many times. Negative arg -N means
12468 move backward across N balanced expressions."
12469 (interactive "p")
12470 (setq arg (or arg 1))
12471 (save-restriction
12472 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12473 (js2-reparse)
12474 (let (forward-sexp-function
12475 node (start (point)) pos lp rp child)
12476 (cond
12477 ;; backward-sexp
12478 ;; could probably make this better for some cases:
12479 ;; - if in statement block (e.g. function body), go to parent
12480 ;; - infix exprs like (foo in bar) - maybe go to beginning
12481 ;; of infix expr if in the right-side expression?
12482 ((and arg (cl-minusp arg))
12483 (dotimes (_ (- arg))
12484 (js2-backward-sws)
12485 (forward-char -1) ; Enter the node we backed up to.
12486 (when (setq node (js2-node-at-point (point) t))
12487 (setq pos (js2-node-abs-pos node))
12488 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12489 (setq lp (car parens)
12490 rp (cdr parens)))
12491 (when (and lp (> start lp))
12492 (if (and rp (<= start rp))
12493 ;; Between parens, check if there's a child node we can jump.
12494 (when (setq child (js2-node-closest-child node (point) lp t))
12495 (setq pos (js2-node-abs-pos child)))
12496 ;; Before both parens.
12497 (setq pos lp)))
12498 (let ((state (parse-partial-sexp start pos)))
12499 (goto-char (if (not (zerop (car state)))
12500 ;; Stumble at the unbalanced paren if < 0, or
12501 ;; jump a bit further if > 0.
12502 (scan-sexps start -1)
12503 pos))))
12504 (unless pos (goto-char (point-min)))))
12505 (t
12506 ;; forward-sexp
12507 (dotimes (_ arg)
12508 (js2-forward-sws)
12509 (when (setq node (js2-node-at-point (point) t))
12510 (setq pos (js2-node-abs-pos node))
12511 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12512 (setq lp (car parens)
12513 rp (cdr parens)))
12514 (or
12515 (when (and rp (<= start rp))
12516 (if (> start lp)
12517 (when (setq child (js2-node-closest-child node (point) rp))
12518 (setq pos (js2-node-abs-end child)))
12519 (setq pos (1+ rp))))
12520 ;; No parens or child nodes, looks for the end of the current node.
12521 (cl-incf pos (js2-node-len
12522 (if (js2-expr-stmt-node-p (js2-node-parent node))
12523 ;; Stop after the semicolon.
12524 (js2-node-parent node)
12525 node))))
12526 (let ((state (save-excursion (parse-partial-sexp start pos))))
12527 (goto-char (if (not (zerop (car state)))
12528 (scan-sexps start 1)
12529 pos))))
12530 (unless pos (goto-char (point-max)))))))))
12531
12532 (defun js2-mode-forward-sexp-parens (node abs-pos)
12533 "Return a cons cell with positions of main parens in NODE."
12534 (cond
12535 ((or (js2-array-node-p node)
12536 (js2-object-node-p node)
12537 (js2-comp-node-p node)
12538 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12539 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12540 ((js2-paren-expr-node-p node)
12541 (let ((lp (js2-node-lp node))
12542 (rp (js2-node-rp node)))
12543 (cons (when lp (+ abs-pos lp))
12544 (when rp (+ abs-pos rp)))))))
12545
12546 (defun js2-node-closest-child (parent point limit &optional before)
12547 (let* ((parent-pos (js2-node-abs-pos parent))
12548 (rpoint (- point parent-pos))
12549 (rlimit (- limit parent-pos))
12550 (min (min rpoint rlimit))
12551 (max (max rpoint rlimit))
12552 found)
12553 (catch 'done
12554 (js2-visit-ast
12555 parent
12556 (lambda (node _end-p)
12557 (if (eq node parent)
12558 t
12559 (let ((pos (js2-node-pos node)) ;; Both relative values.
12560 (end (+ (js2-node-pos node) (js2-node-len node))))
12561 (when (and (>= pos min) (<= end max)
12562 (if before (< pos rpoint) (> end rpoint)))
12563 (setq found node))
12564 (when (> end rpoint)
12565 (throw 'done nil)))
12566 nil))))
12567 found))
12568
12569 (defun js2-errors ()
12570 "Return a list of errors found."
12571 (and js2-mode-ast
12572 (js2-ast-root-errors js2-mode-ast)))
12573
12574 (defun js2-warnings ()
12575 "Return a list of warnings found."
12576 (and js2-mode-ast
12577 (js2-ast-root-warnings js2-mode-ast)))
12578
12579 (defun js2-have-errors-p ()
12580 "Return non-nil if any parse errors or warnings were found."
12581 (or (js2-errors) (js2-warnings)))
12582
12583 (defun js2-errors-and-warnings ()
12584 "Return a copy of the concatenated errors and warnings lists.
12585 They are appended: first the errors, then the warnings.
12586 Entries are of the form (MSG BEG END)."
12587 (when js2-mode-ast
12588 (append (js2-ast-root-errors js2-mode-ast)
12589 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12590
12591 (defun js2-next-error (&optional arg reset)
12592 "Move to next parse error.
12593 Typically invoked via \\[next-error].
12594 ARG is the number of errors, forward or backward, to move.
12595 RESET means start over from the beginning."
12596 (interactive "p")
12597 (if (not (or (js2-errors) (js2-warnings)))
12598 (message "No errors")
12599 (when reset
12600 (goto-char (point-min)))
12601 (let* ((errs (js2-errors-and-warnings))
12602 (continue t)
12603 (start (point))
12604 (count (or arg 1))
12605 (backward (cl-minusp count))
12606 (sorter (if backward '> '<))
12607 (stopper (if backward '< '>))
12608 (count (abs count))
12609 all-errs err)
12610 ;; Sort by start position.
12611 (setq errs (sort errs (lambda (e1 e2)
12612 (funcall sorter (cl-second e1) (cl-second e2))))
12613 all-errs errs)
12614 ;; Find nth error with pos > start.
12615 (while (and errs continue)
12616 (when (funcall stopper (cl-cadar errs) start)
12617 (setq err (car errs))
12618 (if (zerop (cl-decf count))
12619 (setq continue nil)))
12620 (setq errs (cdr errs)))
12621 ;; Clear for `js2-echo-error'.
12622 (message nil)
12623 (if err
12624 (goto-char (cl-second err))
12625 ;; Wrap around to first error.
12626 (goto-char (cl-second (car all-errs)))
12627 ;; If we were already on it, echo msg again.
12628 (if (= (point) start)
12629 (js2-echo-error (point) (point)))))))
12630
12631 (defun js2-down-mouse-3 ()
12632 "Make right-click move the point to the click location.
12633 This makes right-click context menu operations a bit more intuitive.
12634 The point will not move if the region is active, however, to avoid
12635 destroying the region selection."
12636 (interactive)
12637 (when (and js2-move-point-on-right-click
12638 (not mark-active))
12639 (let ((e last-input-event))
12640 (ignore-errors
12641 (goto-char (cl-cadadr e))))))
12642
12643 (defun js2-mode-create-imenu-index ()
12644 "Return an alist for `imenu--index-alist'."
12645 ;; This is built up in `js2-parse-record-imenu' during parsing.
12646 (when js2-mode-ast
12647 ;; if we have an ast but no recorder, they're requesting a rescan
12648 (unless js2-imenu-recorder
12649 (js2-reparse 'force))
12650 (prog1
12651 (js2-build-imenu-index)
12652 (setq js2-imenu-recorder nil
12653 js2-imenu-function-map nil))))
12654
12655 (defun js2-mode-find-tag ()
12656 "Replacement for `find-tag-default'.
12657 `find-tag-default' returns a ridiculous answer inside comments."
12658 (let (beg end)
12659 (save-excursion
12660 (if (looking-at "\\_>")
12661 (setq beg (progn (forward-symbol -1) (point))
12662 end (progn (forward-symbol 1) (point)))
12663 (setq beg (progn (forward-symbol 1) (point))
12664 end (progn (forward-symbol -1) (point))))
12665 (replace-regexp-in-string
12666 "[\"']" ""
12667 (buffer-substring-no-properties beg end)))))
12668
12669 (defun js2-mode-forward-sibling ()
12670 "Move to the end of the sibling following point in parent.
12671 Returns non-nil if successful, or nil if there was no following sibling."
12672 (let* ((node (js2-node-at-point))
12673 (parent (js2-mode-find-enclosing-fn node))
12674 sib)
12675 (when (setq sib (js2-node-find-child-after (point) parent))
12676 (goto-char (+ (js2-node-abs-pos sib)
12677 (js2-node-len sib))))))
12678
12679 (defun js2-mode-backward-sibling ()
12680 "Move to the beginning of the sibling node preceding point in parent.
12681 Parent is defined as the enclosing script or function."
12682 (let* ((node (js2-node-at-point))
12683 (parent (js2-mode-find-enclosing-fn node))
12684 sib)
12685 (when (setq sib (js2-node-find-child-before (point) parent))
12686 (goto-char (js2-node-abs-pos sib)))))
12687
12688 (defun js2-beginning-of-defun (&optional arg)
12689 "Go to line on which current function starts, and return t on success.
12690 If we're not in a function or already at the beginning of one, go
12691 to beginning of previous script-level element.
12692 With ARG N, do that N times. If N is negative, move forward."
12693 (setq arg (or arg 1))
12694 (if (cl-plusp arg)
12695 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12696 (when (cond
12697 ((js2-function-node-p parent)
12698 (goto-char (js2-node-abs-pos parent)))
12699 (t
12700 (js2-mode-backward-sibling)))
12701 (if (> arg 1)
12702 (js2-beginning-of-defun (1- arg))
12703 t)))
12704 (when (js2-end-of-defun)
12705 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12706
12707 (defun js2-end-of-defun ()
12708 "Go to the char after the last position of the current function
12709 or script-level element."
12710 (let* ((node (js2-node-at-point))
12711 (parent (or (and (js2-function-node-p node) node)
12712 (js2-node-parent-script-or-fn node)))
12713 script)
12714 (unless (js2-function-node-p parent)
12715 ;; Use current script-level node, or, if none, the next one.
12716 (setq script (or parent node)
12717 parent (js2-node-find-child-before (point) script))
12718 (when (or (null parent)
12719 (>= (point) (+ (js2-node-abs-pos parent)
12720 (js2-node-len parent))))
12721 (setq parent (js2-node-find-child-after (point) script))))
12722 (when parent
12723 (goto-char (+ (js2-node-abs-pos parent)
12724 (js2-node-len parent))))))
12725
12726 (defun js2-mark-defun (&optional allow-extend)
12727 "Put mark at end of this function, point at beginning.
12728 The function marked is the one that contains point.
12729
12730 Interactively, if this command is repeated,
12731 or (in Transient Mark mode) if the mark is active,
12732 it marks the next defun after the ones already marked."
12733 (interactive "p")
12734 (let (extended)
12735 (when (and allow-extend
12736 (or (and (eq last-command this-command) (mark t))
12737 (and transient-mark-mode mark-active)))
12738 (let ((sib (save-excursion
12739 (goto-char (mark))
12740 (if (js2-mode-forward-sibling)
12741 (point)))))
12742 (if sib
12743 (progn
12744 (set-mark sib)
12745 (setq extended t))
12746 ;; no more siblings - try extending to enclosing node
12747 (goto-char (mark t)))))
12748 (when (not extended)
12749 (let ((node (js2-node-at-point (point) t)) ; skip comments
12750 ast fn stmt parent beg end)
12751 (when (js2-ast-root-p node)
12752 (setq ast node
12753 node (or (js2-node-find-child-after (point) node)
12754 (js2-node-find-child-before (point) node))))
12755 ;; only mark whole buffer if we can't find any children
12756 (if (null node)
12757 (setq node ast))
12758 (if (js2-function-node-p node)
12759 (setq parent node)
12760 (setq fn (js2-mode-find-enclosing-fn node)
12761 stmt (if (or (null fn)
12762 (js2-ast-root-p fn))
12763 (js2-mode-find-first-stmt node))
12764 parent (or stmt fn)))
12765 (setq beg (js2-node-abs-pos parent)
12766 end (+ beg (js2-node-len parent)))
12767 (push-mark beg)
12768 (goto-char end)
12769 (exchange-point-and-mark)))))
12770
12771 (defun js2-narrow-to-defun ()
12772 "Narrow to the function enclosing point."
12773 (interactive)
12774 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12775 (fn (if (js2-script-node-p node)
12776 node
12777 (js2-mode-find-enclosing-fn node)))
12778 (beg (js2-node-abs-pos fn)))
12779 (unless (js2-ast-root-p fn)
12780 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12781
12782 (provide 'js2-mode)
12783
12784 ;;; js2-mode.el ends here