]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Add NEWS entry and bump version
[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 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2208 "Evaluate BODY with the _ character set to be word-syntax."
2209 (declare (indent 0) (debug t))
2210 (let ((old-syntax (make-symbol "old-syntax")))
2211 `(let ((,old-syntax (string (char-syntax ?_))))
2212 (unwind-protect
2213 (progn
2214 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2215 ,@body)
2216 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2217
2218 ;;; AST struct and function definitions
2219
2220 ;; flags for ast node property 'member-type (used for e4x operators)
2221 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2222 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2223 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2224
2225 (defsubst js2-relpos (pos anchor)
2226 "Convert POS to be relative to ANCHOR.
2227 If POS is nil, returns nil."
2228 (and pos (- pos anchor)))
2229
2230 (defun js2-make-pad (indent)
2231 (if (zerop indent)
2232 ""
2233 (make-string (* indent js2-basic-offset) ? )))
2234
2235 (defun js2-visit-ast (node callback)
2236 "Visit every node in ast NODE with visitor CALLBACK.
2237
2238 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2239 called twice: once to visit the node, and again after all the node's
2240 children have been processed. The END-P argument is nil on the first
2241 call and non-nil on the second call. The return value of the callback
2242 affects the traversal: if non-nil, the children of NODE are processed.
2243 If the callback returns nil, or if the node has no children, then the
2244 callback is called immediately with a non-nil END-P argument.
2245
2246 The node traversal is approximately lexical-order, although there
2247 are currently no guarantees around this."
2248 (when node
2249 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2250 ;; visit the node
2251 (when (funcall callback node nil)
2252 ;; visit the kids
2253 (cond
2254 ((eq vfunc 'js2-visit-none)
2255 nil) ; don't even bother calling it
2256 ;; Each AST node type has to define a `js2-visitor' function
2257 ;; that takes a node and a callback, and calls `js2-visit-ast'
2258 ;; on each child of the node.
2259 (vfunc
2260 (funcall vfunc node callback))
2261 (t
2262 (error "%s does not define a visitor-traversal function"
2263 (aref node 0)))))
2264 ;; call the end-visit
2265 (funcall callback node t))))
2266
2267 (cl-defstruct (js2-node
2268 (:constructor nil)) ; abstract
2269 "Base AST node type."
2270 (type -1) ; token type
2271 (pos -1) ; start position of this AST node in parsed input
2272 (len 1) ; num characters spanned by the node
2273 props ; optional node property list (an alist)
2274 parent) ; link to parent node; null for root
2275
2276 (defsubst js2-node-get-prop (node prop &optional default)
2277 (or (cadr (assoc prop (js2-node-props node))) default))
2278
2279 (defsubst js2-node-set-prop (node prop value)
2280 (setf (js2-node-props node)
2281 (cons (list prop value) (js2-node-props node))))
2282
2283 (defun js2-fixup-starts (n nodes)
2284 "Adjust the start positions of NODES to be relative to N.
2285 Any node in the list may be nil, for convenience."
2286 (dolist (node nodes)
2287 (when node
2288 (setf (js2-node-pos node) (- (js2-node-pos node)
2289 (js2-node-pos n))))))
2290
2291 (defun js2-node-add-children (parent &rest nodes)
2292 "Set parent node of NODES to PARENT, and return PARENT.
2293 Does nothing if we're not recording parent links.
2294 If any given node in NODES is nil, doesn't record that link."
2295 (js2-fixup-starts parent nodes)
2296 (dolist (node nodes)
2297 (and node
2298 (setf (js2-node-parent node) parent))))
2299
2300 ;; Non-recursive since it's called a frightening number of times.
2301 (defun js2-node-abs-pos (n)
2302 (let ((pos (js2-node-pos n)))
2303 (while (setq n (js2-node-parent n))
2304 (setq pos (+ pos (js2-node-pos n))))
2305 pos))
2306
2307 (defsubst js2-node-abs-end (n)
2308 "Return absolute buffer position of end of N."
2309 (+ (js2-node-abs-pos n) (js2-node-len n)))
2310
2311 ;; It's important to make sure block nodes have a Lisp list for the
2312 ;; child nodes, to limit printing recursion depth in an AST that
2313 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2314 ;; a sufficiently large vector tree.
2315
2316 (cl-defstruct (js2-block-node
2317 (:include js2-node)
2318 (:constructor nil)
2319 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2320 (pos (js2-current-token-beg))
2321 len
2322 props
2323 kids)))
2324 "A block of statements."
2325 kids) ; a Lisp list of the child statement nodes
2326
2327 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2328 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2329
2330 (defun js2-visit-block (ast callback)
2331 "Visit the `js2-block-node' children of AST."
2332 (dolist (kid (js2-block-node-kids ast))
2333 (js2-visit-ast kid callback)))
2334
2335 (defun js2-print-block (n i)
2336 (let ((pad (js2-make-pad i)))
2337 (insert pad "{\n")
2338 (dolist (kid (js2-block-node-kids n))
2339 (js2-print-ast kid (1+ i)))
2340 (insert pad "}")))
2341
2342 (cl-defstruct (js2-scope
2343 (:include js2-block-node)
2344 (:constructor nil)
2345 (:constructor make-js2-scope (&key (type js2-BLOCK)
2346 (pos (js2-current-token-beg))
2347 len
2348 kids)))
2349 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2350 ;; I don't have one of those handy, so I'll use an alist for now.
2351 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2352 ;; and is much lighter-weight to construct (both CPU and mem).
2353 ;; The keys are interned strings (symbols) for faster lookup.
2354 ;; Should switch to hybrid alist/hashtable eventually.
2355 symbol-table ; an alist of (symbol . js2-symbol)
2356 parent-scope ; a `js2-scope'
2357 top) ; top-level `js2-scope' (script/function)
2358
2359 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2360 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2361
2362 (defun js2-node-get-enclosing-scope (node)
2363 "Return the innermost `js2-scope' node surrounding NODE.
2364 Returns nil if there is no enclosing scope node."
2365 (while (and (setq node (js2-node-parent node))
2366 (not (js2-scope-p node))))
2367 node)
2368
2369 (defun js2-get-defining-scope (scope name &optional point)
2370 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2371 Returns `js2-scope' in which NAME is defined, or nil if not found.
2372
2373 If POINT is non-nil, and if the found declaration type is
2374 `js2-LET', also check that the declaration node is before POINT."
2375 (let ((sym (if (symbolp name)
2376 name
2377 (intern name)))
2378 result
2379 (continue t))
2380 (while (and scope continue)
2381 (if (or
2382 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2383 (and entry
2384 (or (not point)
2385 (not (eq js2-LET (js2-symbol-decl-type entry)))
2386 (>= point
2387 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2388 (and (eq sym 'arguments)
2389 (js2-function-node-p scope)))
2390 (setq continue nil
2391 result scope)
2392 (setq scope (js2-scope-parent-scope scope))))
2393 result))
2394
2395 (defun js2-scope-get-symbol (scope name)
2396 "Return symbol table entry for NAME in SCOPE.
2397 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2398 (and (js2-scope-symbol-table scope)
2399 (cdr (assq (if (symbolp name)
2400 name
2401 (intern name))
2402 (js2-scope-symbol-table scope)))))
2403
2404 (defun js2-scope-put-symbol (scope name symbol)
2405 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2406 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2407 (let* ((table (js2-scope-symbol-table scope))
2408 (sym (if (symbolp name) name (intern name)))
2409 (entry (assq sym table)))
2410 (if entry
2411 (setcdr entry symbol)
2412 (push (cons sym symbol)
2413 (js2-scope-symbol-table scope)))))
2414
2415 (cl-defstruct (js2-symbol
2416 (:constructor nil)
2417 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2418 "A symbol table entry."
2419 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2420 ;; js2-LET, or js2-CONST
2421 decl-type
2422 name ; string
2423 ast-node) ; a `js2-node'
2424
2425 (cl-defstruct (js2-error-node
2426 (:include js2-node)
2427 (:constructor nil) ; silence emacs21 byte-compiler
2428 (:constructor make-js2-error-node (&key (type js2-ERROR)
2429 (pos (js2-current-token-beg))
2430 len)))
2431 "AST node representing a parse error.")
2432
2433 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2434 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2435
2436 (cl-defstruct (js2-script-node
2437 (:include js2-scope)
2438 (:constructor nil)
2439 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2440 (pos (js2-current-token-beg))
2441 len
2442 ;; FIXME: What are those?
2443 var-decls
2444 fun-decls)))
2445 functions ; Lisp list of nested functions
2446 regexps ; Lisp list of (string . flags)
2447 symbols ; alist (every symbol gets unique index)
2448 (param-count 0)
2449 var-names ; vector of string names
2450 consts ; bool-vector matching var-decls
2451 (temp-number 0)) ; for generating temp variables
2452
2453 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2454 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2455
2456 (defun js2-print-script (node indent)
2457 (dolist (kid (js2-block-node-kids node))
2458 (js2-print-ast kid indent)))
2459
2460 (cl-defstruct (js2-ast-root
2461 (:include js2-script-node)
2462 (:constructor nil)
2463 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2464 (pos (js2-current-token-beg))
2465 len
2466 buffer)))
2467 "The root node of a js2 AST."
2468 buffer ; the source buffer from which the code was parsed
2469 comments ; a Lisp list of comments, ordered by start position
2470 errors ; a Lisp list of errors found during parsing
2471 warnings ; a Lisp list of warnings found during parsing
2472 node-count) ; number of nodes in the tree, including the root
2473
2474 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2475 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2476
2477 (defun js2-visit-ast-root (ast callback)
2478 (dolist (kid (js2-ast-root-kids ast))
2479 (js2-visit-ast kid callback))
2480 (dolist (comment (js2-ast-root-comments ast))
2481 (js2-visit-ast comment callback)))
2482
2483 (cl-defstruct (js2-comment-node
2484 (:include js2-node)
2485 (:constructor nil)
2486 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2487 (pos (js2-current-token-beg))
2488 len
2489 format)))
2490 format) ; 'line, 'block, 'jsdoc or 'html
2491
2492 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2493 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2494
2495 (defun js2-print-comment (n i)
2496 ;; We really ought to link end-of-line comments to their nodes.
2497 ;; Or maybe we could add a new comment type, 'endline.
2498 (insert (js2-make-pad i)
2499 (js2-node-string n)))
2500
2501 (cl-defstruct (js2-expr-stmt-node
2502 (:include js2-node)
2503 (:constructor nil)
2504 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2505 (pos js2-ts-cursor)
2506 len
2507 expr)))
2508 "An expression statement."
2509 expr)
2510
2511 (defsubst js2-expr-stmt-node-set-has-result (node)
2512 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2513 (setf (js2-node-type node) js2-EXPR_RESULT))
2514
2515 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2516 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2517
2518 (defun js2-visit-expr-stmt-node (n v)
2519 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2520
2521 (defun js2-print-expr-stmt-node (n indent)
2522 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2523 (insert ";\n"))
2524
2525 (cl-defstruct (js2-loop-node
2526 (:include js2-scope)
2527 (:constructor nil))
2528 "Abstract supertype of loop nodes."
2529 body ; a `js2-block-node'
2530 lp ; position of left-paren, nil if omitted
2531 rp) ; position of right-paren, nil if omitted
2532
2533 (cl-defstruct (js2-do-node
2534 (:include js2-loop-node)
2535 (:constructor nil)
2536 (:constructor make-js2-do-node (&key (type js2-DO)
2537 (pos (js2-current-token-beg))
2538 len
2539 body
2540 condition
2541 while-pos
2542 lp
2543 rp)))
2544 "AST node for do-loop."
2545 condition ; while (expression)
2546 while-pos) ; buffer position of 'while' keyword
2547
2548 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2549 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2550
2551 (defun js2-visit-do-node (n v)
2552 (js2-visit-ast (js2-do-node-body n) v)
2553 (js2-visit-ast (js2-do-node-condition n) v))
2554
2555 (defun js2-print-do-node (n i)
2556 (let ((pad (js2-make-pad i)))
2557 (insert pad "do {\n")
2558 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2559 (js2-print-ast kid (1+ i)))
2560 (insert pad "} while (")
2561 (js2-print-ast (js2-do-node-condition n) 0)
2562 (insert ");\n")))
2563
2564 (cl-defstruct (js2-export-node
2565 (:include js2-node)
2566 (:constructor nil)
2567 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2568 (pos (js2-current-token-beg))
2569 len
2570 exports-list
2571 from-clause
2572 declaration
2573 default)))
2574 "AST node for an export statement. There are many things that can be exported,
2575 so many of its properties will be nil.
2576 "
2577 exports-list ; lisp list of js2-export-binding-node to export
2578 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2579 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2580 default) ; js2-function-node or js2-assign-node
2581
2582 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2583 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2584
2585 (defun js2-visit-export-node (n v)
2586 (let ((exports-list (js2-export-node-exports-list n))
2587 (from (js2-export-node-from-clause n))
2588 (declaration (js2-export-node-declaration n))
2589 (default (js2-export-node-default n)))
2590 (when exports-list
2591 (dolist (export exports-list)
2592 (js2-visit-ast export v)))
2593 (when from
2594 (js2-visit-ast from v))
2595 (when declaration
2596 (js2-visit-ast declaration v))
2597 (when default
2598 (js2-visit-ast default v))))
2599
2600 (defun js2-print-export-node (n i)
2601 (let ((pad (js2-make-pad i))
2602 (exports-list (js2-export-node-exports-list n))
2603 (from (js2-export-node-from-clause n))
2604 (declaration (js2-export-node-declaration n))
2605 (default (js2-export-node-default n)))
2606 (insert pad "export ")
2607 (cond
2608 (default
2609 (insert "default ")
2610 (js2-print-ast default i))
2611 (declaration
2612 (js2-print-ast declaration i))
2613 ((and exports-list from)
2614 (js2-print-named-imports exports-list)
2615 (insert " ")
2616 (js2-print-from-clause from))
2617 (from
2618 (insert "* ")
2619 (js2-print-from-clause from))
2620 (exports-list
2621 (js2-print-named-imports exports-list)))
2622 (insert ";\n")))
2623
2624 (cl-defstruct (js2-while-node
2625 (:include js2-loop-node)
2626 (:constructor nil)
2627 (:constructor make-js2-while-node (&key (type js2-WHILE)
2628 (pos (js2-current-token-beg))
2629 len body
2630 condition lp
2631 rp)))
2632 "AST node for while-loop."
2633 condition) ; while-condition
2634
2635 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2636 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2637
2638 (defun js2-visit-while-node (n v)
2639 (js2-visit-ast (js2-while-node-condition n) v)
2640 (js2-visit-ast (js2-while-node-body n) v))
2641
2642 (defun js2-print-while-node (n i)
2643 (let ((pad (js2-make-pad i)))
2644 (insert pad "while (")
2645 (js2-print-ast (js2-while-node-condition n) 0)
2646 (insert ") {\n")
2647 (js2-print-body (js2-while-node-body n) (1+ i))
2648 (insert pad "}\n")))
2649
2650 (cl-defstruct (js2-for-node
2651 (:include js2-loop-node)
2652 (:constructor nil)
2653 (:constructor make-js2-for-node (&key (type js2-FOR)
2654 (pos js2-ts-cursor)
2655 len body init
2656 condition
2657 update lp rp)))
2658 "AST node for a C-style for-loop."
2659 init ; initialization expression
2660 condition ; loop condition
2661 update) ; update clause
2662
2663 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2664 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2665
2666 (defun js2-visit-for-node (n v)
2667 (js2-visit-ast (js2-for-node-init n) v)
2668 (js2-visit-ast (js2-for-node-condition n) v)
2669 (js2-visit-ast (js2-for-node-update n) v)
2670 (js2-visit-ast (js2-for-node-body n) v))
2671
2672 (defun js2-print-for-node (n i)
2673 (let ((pad (js2-make-pad i)))
2674 (insert pad "for (")
2675 (js2-print-ast (js2-for-node-init n) 0)
2676 (insert "; ")
2677 (js2-print-ast (js2-for-node-condition n) 0)
2678 (insert "; ")
2679 (js2-print-ast (js2-for-node-update n) 0)
2680 (insert ") {\n")
2681 (js2-print-body (js2-for-node-body n) (1+ i))
2682 (insert pad "}\n")))
2683
2684 (cl-defstruct (js2-for-in-node
2685 (:include js2-loop-node)
2686 (:constructor nil)
2687 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2688 (pos js2-ts-cursor)
2689 len body
2690 iterator
2691 object
2692 in-pos
2693 each-pos
2694 foreach-p forof-p
2695 lp rp)))
2696 "AST node for a for..in loop."
2697 iterator ; [var] foo in ...
2698 object ; object over which we're iterating
2699 in-pos ; buffer position of 'in' keyword
2700 each-pos ; buffer position of 'each' keyword, if foreach-p
2701 foreach-p ; t if it's a for-each loop
2702 forof-p) ; t if it's a for-of loop
2703
2704 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2705 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2706
2707 (defun js2-visit-for-in-node (n v)
2708 (js2-visit-ast (js2-for-in-node-iterator n) v)
2709 (js2-visit-ast (js2-for-in-node-object n) v)
2710 (js2-visit-ast (js2-for-in-node-body n) v))
2711
2712 (defun js2-print-for-in-node (n i)
2713 (let ((pad (js2-make-pad i))
2714 (foreach (js2-for-in-node-foreach-p n))
2715 (forof (js2-for-in-node-forof-p n)))
2716 (insert pad "for ")
2717 (if foreach
2718 (insert "each "))
2719 (insert "(")
2720 (js2-print-ast (js2-for-in-node-iterator n) 0)
2721 (insert (if forof " of " " in "))
2722 (js2-print-ast (js2-for-in-node-object n) 0)
2723 (insert ") {\n")
2724 (js2-print-body (js2-for-in-node-body n) (1+ i))
2725 (insert pad "}\n")))
2726
2727 (cl-defstruct (js2-return-node
2728 (:include js2-node)
2729 (:constructor nil)
2730 (:constructor make-js2-return-node (&key (type js2-RETURN)
2731 (pos js2-ts-cursor)
2732 len
2733 retval)))
2734 "AST node for a return statement."
2735 retval) ; expression to return, or 'undefined
2736
2737 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2738 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2739
2740 (defun js2-visit-return-node (n v)
2741 (js2-visit-ast (js2-return-node-retval n) v))
2742
2743 (defun js2-print-return-node (n i)
2744 (insert (js2-make-pad i) "return")
2745 (when (js2-return-node-retval n)
2746 (insert " ")
2747 (js2-print-ast (js2-return-node-retval n) 0))
2748 (insert ";\n"))
2749
2750 (cl-defstruct (js2-if-node
2751 (:include js2-node)
2752 (:constructor nil)
2753 (:constructor make-js2-if-node (&key (type js2-IF)
2754 (pos js2-ts-cursor)
2755 len condition
2756 then-part
2757 else-pos
2758 else-part lp
2759 rp)))
2760 "AST node for an if-statement."
2761 condition ; expression
2762 then-part ; statement or block
2763 else-pos ; optional buffer position of 'else' keyword
2764 else-part ; optional statement or block
2765 lp ; position of left-paren, nil if omitted
2766 rp) ; position of right-paren, nil if omitted
2767
2768 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2769 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2770
2771 (defun js2-visit-if-node (n v)
2772 (js2-visit-ast (js2-if-node-condition n) v)
2773 (js2-visit-ast (js2-if-node-then-part n) v)
2774 (js2-visit-ast (js2-if-node-else-part n) v))
2775
2776 (defun js2-print-if-node (n i)
2777 (let ((pad (js2-make-pad i))
2778 (then-part (js2-if-node-then-part n))
2779 (else-part (js2-if-node-else-part n)))
2780 (insert pad "if (")
2781 (js2-print-ast (js2-if-node-condition n) 0)
2782 (insert ") {\n")
2783 (js2-print-body then-part (1+ i))
2784 (insert pad "}")
2785 (cond
2786 ((not else-part)
2787 (insert "\n"))
2788 ((js2-if-node-p else-part)
2789 (insert " else ")
2790 (js2-print-body else-part i))
2791 (t
2792 (insert " else {\n")
2793 (js2-print-body else-part (1+ i))
2794 (insert pad "}\n")))))
2795
2796 (cl-defstruct (js2-export-binding-node
2797 (:include js2-node)
2798 (:constructor nil)
2799 (:constructor make-js2-export-binding-node (&key (type -1)
2800 pos
2801 len
2802 local-name
2803 extern-name)))
2804 "AST node for an external symbol binding.
2805 It contains a local-name node which is the name of the value in the
2806 current scope, and extern-name which is the name of the value in the
2807 imported or exported scope. By default these are the same, but if the
2808 name is aliased as in {foo as bar}, it would have an extern-name node
2809 containing 'foo' and a local-name node containing 'bar'."
2810 local-name ; js2-name-node with the variable name in this scope
2811 extern-name) ; js2-name-node with the value name in the exporting module
2812
2813 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2814 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2815
2816 (defun js2-visit-extern-binding (n v)
2817 "Visit an extern binding node. First visit the local-name, and, if
2818 different, visit the extern-name."
2819 (let ((local-name (js2-export-binding-node-local-name n))
2820 (extern-name (js2-export-binding-node-extern-name n)))
2821 (when local-name
2822 (js2-visit-ast local-name v))
2823 (when (not (equal local-name extern-name))
2824 (js2-visit-ast extern-name v))))
2825
2826 (defun js2-print-extern-binding (n _i)
2827 "Print a representation of a single extern binding. E.g. 'foo' or
2828 'foo as bar'."
2829 (let ((local-name (js2-export-binding-node-local-name n))
2830 (extern-name (js2-export-binding-node-extern-name n)))
2831 (insert (js2-name-node-name extern-name))
2832 (when (not (equal local-name extern-name))
2833 (insert " as ")
2834 (insert (js2-name-node-name local-name)))))
2835
2836
2837 (cl-defstruct (js2-import-node
2838 (:include js2-node)
2839 (:constructor nil)
2840 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2841 (pos (js2-current-token-beg))
2842 len
2843 import
2844 from
2845 module-id)))
2846 "AST node for an import statement. It follows the form
2847
2848 import ModuleSpecifier;
2849 import ImportClause FromClause;"
2850 import ; js2-import-clause-node specifying which names are to imported.
2851 from ; js2-from-clause-node indicating the module from which to import.
2852 module-id) ; module-id of the import. E.g. 'src/mylib'.
2853
2854 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2855 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2856
2857 (defun js2-visit-import (n v)
2858 (let ((import-clause (js2-import-node-import n))
2859 (from-clause (js2-import-node-from n)))
2860 (when import-clause
2861 (js2-visit-ast import-clause v))
2862 (when from-clause
2863 (js2-visit-ast from-clause v))))
2864
2865 (defun js2-print-import (n i)
2866 "Prints a representation of the import node"
2867 (let ((pad (js2-make-pad i))
2868 (import-clause (js2-import-node-import n))
2869 (from-clause (js2-import-node-from n))
2870 (module-id (js2-import-node-module-id n)))
2871 (insert pad "import ")
2872 (if import-clause
2873 (progn
2874 (js2-print-import-clause import-clause)
2875 (insert " ")
2876 (js2-print-from-clause from-clause))
2877 (insert "'")
2878 (insert module-id)
2879 (insert "'"))
2880 (insert ";\n")))
2881
2882 (cl-defstruct (js2-import-clause-node
2883 (:include js2-node)
2884 (:constructor nil)
2885 (:constructor make-js2-import-clause-node (&key (type -1)
2886 pos
2887 len
2888 namespace-import
2889 named-imports
2890 default-binding)))
2891 "AST node corresponding to the import clause of an import statement. This is
2892 the portion of the import that bindings names from the external context to the
2893 local context."
2894 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2895 named-imports ; lisp list of js2-export-binding-node for all named imports.
2896 default-binding) ; js2-export-binding-node for the default import binding
2897
2898 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2899 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2900
2901 (defun js2-visit-import-clause (n v)
2902 (let ((ns-import (js2-import-clause-node-namespace-import n))
2903 (named-imports (js2-import-clause-node-named-imports n))
2904 (default (js2-import-clause-node-default-binding n)))
2905 (when ns-import
2906 (js2-visit-ast ns-import v))
2907 (when named-imports
2908 (dolist (import named-imports)
2909 (js2-visit-ast import v)))
2910 (when default
2911 (js2-visit-ast default v))))
2912
2913 (defun js2-print-import-clause (n)
2914 (let ((ns-import (js2-import-clause-node-namespace-import n))
2915 (named-imports (js2-import-clause-node-named-imports n))
2916 (default (js2-import-clause-node-default-binding n)))
2917 (cond
2918 ((and default ns-import)
2919 (js2-print-ast default)
2920 (insert ", ")
2921 (js2-print-namespace-import ns-import))
2922 ((and default named-imports)
2923 (js2-print-ast default)
2924 (insert ", ")
2925 (js2-print-named-imports named-imports))
2926 (default
2927 (js2-print-ast default))
2928 (ns-import
2929 (js2-print-namespace-import ns-import))
2930 (named-imports
2931 (js2-print-named-imports named-imports)))))
2932
2933 (defun js2-print-namespace-import (node)
2934 (insert "* as ")
2935 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2936
2937 (defun js2-print-named-imports (imports)
2938 (insert "{")
2939 (let ((len (length imports))
2940 (n 0))
2941 (while (< n len)
2942 (js2-print-extern-binding (nth n imports) 0)
2943 (unless (= n (- len 1))
2944 (insert ", "))
2945 (setq n (+ n 1))))
2946 (insert "}"))
2947
2948 (cl-defstruct (js2-namespace-import-node
2949 (:include js2-node)
2950 (:constructor nil)
2951 (:constructor make-js2-namespace-import-node (&key (type -1)
2952 pos
2953 len
2954 name)))
2955 "AST node for a complete namespace import.
2956 E.g. the '* as lib' expression in:
2957
2958 import * as lib from 'src/lib'
2959
2960 It contains a single name node referring to the bound name."
2961 name) ; js2-name-node of the bound name.
2962
2963 (defun js2-visit-namespace-import (n v)
2964 (js2-visit-ast (js2-namespace-import-node-name n) v))
2965
2966 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2967 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2968
2969 (cl-defstruct (js2-from-clause-node
2970 (:include js2-node)
2971 (:constructor nil)
2972 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2973 pos
2974 len
2975 module-id
2976 metadata-p)))
2977 "AST node for the from clause in an import or export statement.
2978 E.g. from 'my/module'. It can refere to either an external module, or to the
2979 modules metadata itself."
2980 module-id ; string containing the module specifier.
2981 metadata-p) ; true if this clause refers to the module's metadata
2982
2983 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2984 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2985
2986 (defun js2-print-from-clause (n)
2987 (insert "from ")
2988 (if (js2-from-clause-node-metadata-p n)
2989 (insert "this module")
2990 (insert "'")
2991 (insert (js2-from-clause-node-module-id n))
2992 (insert "'")))
2993
2994 (cl-defstruct (js2-try-node
2995 (:include js2-node)
2996 (:constructor nil)
2997 (:constructor make-js2-try-node (&key (type js2-TRY)
2998 (pos js2-ts-cursor)
2999 len
3000 try-block
3001 catch-clauses
3002 finally-block)))
3003 "AST node for a try-statement."
3004 try-block
3005 catch-clauses ; a Lisp list of `js2-catch-node'
3006 finally-block) ; a `js2-finally-node'
3007
3008 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
3009 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
3010
3011 (defun js2-visit-try-node (n v)
3012 (js2-visit-ast (js2-try-node-try-block n) v)
3013 (dolist (clause (js2-try-node-catch-clauses n))
3014 (js2-visit-ast clause v))
3015 (js2-visit-ast (js2-try-node-finally-block n) v))
3016
3017 (defun js2-print-try-node (n i)
3018 (let ((pad (js2-make-pad i))
3019 (catches (js2-try-node-catch-clauses n))
3020 (finally (js2-try-node-finally-block n)))
3021 (insert pad "try {\n")
3022 (js2-print-body (js2-try-node-try-block n) (1+ i))
3023 (insert pad "}")
3024 (when catches
3025 (dolist (catch catches)
3026 (js2-print-ast catch i)))
3027 (if finally
3028 (js2-print-ast finally i)
3029 (insert "\n"))))
3030
3031 (cl-defstruct (js2-catch-node
3032 (:include js2-scope)
3033 (:constructor nil)
3034 (:constructor make-js2-catch-node (&key (type js2-CATCH)
3035 (pos js2-ts-cursor)
3036 len
3037 param
3038 guard-kwd
3039 guard-expr
3040 lp rp)))
3041 "AST node for a catch clause."
3042 param ; destructuring form or simple name node
3043 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
3044 guard-expr ; catch condition, a `js2-node'
3045 lp ; buffer position of left-paren, nil if omitted
3046 rp) ; buffer position of right-paren, nil if omitted
3047
3048 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
3049 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
3050
3051 (defun js2-visit-catch-node (n v)
3052 (js2-visit-ast (js2-catch-node-param n) v)
3053 (when (js2-catch-node-guard-kwd n)
3054 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3055 (js2-visit-block n v))
3056
3057 (defun js2-print-catch-node (n i)
3058 (let ((pad (js2-make-pad i))
3059 (guard-kwd (js2-catch-node-guard-kwd n))
3060 (guard-expr (js2-catch-node-guard-expr n)))
3061 (insert " catch (")
3062 (js2-print-ast (js2-catch-node-param n) 0)
3063 (when guard-kwd
3064 (insert " if ")
3065 (js2-print-ast guard-expr 0))
3066 (insert ") {\n")
3067 (js2-print-body n (1+ i))
3068 (insert pad "}")))
3069
3070 (cl-defstruct (js2-finally-node
3071 (:include js2-node)
3072 (:constructor nil)
3073 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3074 (pos js2-ts-cursor)
3075 len body)))
3076 "AST node for a finally clause."
3077 body) ; a `js2-node', often but not always a block node
3078
3079 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3080 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3081
3082 (defun js2-visit-finally-node (n v)
3083 (js2-visit-ast (js2-finally-node-body n) v))
3084
3085 (defun js2-print-finally-node (n i)
3086 (let ((pad (js2-make-pad i)))
3087 (insert " finally {\n")
3088 (js2-print-body (js2-finally-node-body n) (1+ i))
3089 (insert pad "}\n")))
3090
3091 (cl-defstruct (js2-switch-node
3092 (:include js2-node)
3093 (:constructor nil)
3094 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3095 (pos js2-ts-cursor)
3096 len
3097 discriminant
3098 cases lp
3099 rp)))
3100 "AST node for a switch statement."
3101 discriminant ; a `js2-node' (switch expression)
3102 cases ; a Lisp list of `js2-case-node'
3103 lp ; position of open-paren for discriminant, nil if omitted
3104 rp) ; position of close-paren for discriminant, nil if omitted
3105
3106 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3107 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3108
3109 (defun js2-visit-switch-node (n v)
3110 (js2-visit-ast (js2-switch-node-discriminant n) v)
3111 (dolist (c (js2-switch-node-cases n))
3112 (js2-visit-ast c v)))
3113
3114 (defun js2-print-switch-node (n i)
3115 (let ((pad (js2-make-pad i))
3116 (cases (js2-switch-node-cases n)))
3117 (insert pad "switch (")
3118 (js2-print-ast (js2-switch-node-discriminant n) 0)
3119 (insert ") {\n")
3120 (dolist (case cases)
3121 (js2-print-ast case i))
3122 (insert pad "}\n")))
3123
3124 (cl-defstruct (js2-case-node
3125 (:include js2-block-node)
3126 (:constructor nil)
3127 (:constructor make-js2-case-node (&key (type js2-CASE)
3128 (pos js2-ts-cursor)
3129 len kids expr)))
3130 "AST node for a case clause of a switch statement."
3131 expr) ; the case expression (nil for default)
3132
3133 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3134 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3135
3136 (defun js2-visit-case-node (n v)
3137 (js2-visit-ast (js2-case-node-expr n) v)
3138 (js2-visit-block n v))
3139
3140 (defun js2-print-case-node (n i)
3141 (let ((pad (js2-make-pad i))
3142 (expr (js2-case-node-expr n)))
3143 (insert pad)
3144 (if (null expr)
3145 (insert "default:\n")
3146 (insert "case ")
3147 (js2-print-ast expr 0)
3148 (insert ":\n"))
3149 (dolist (kid (js2-case-node-kids n))
3150 (js2-print-ast kid (1+ i)))))
3151
3152 (cl-defstruct (js2-throw-node
3153 (:include js2-node)
3154 (:constructor nil)
3155 (:constructor make-js2-throw-node (&key (type js2-THROW)
3156 (pos js2-ts-cursor)
3157 len expr)))
3158 "AST node for a throw statement."
3159 expr) ; the expression to throw
3160
3161 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3162 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3163
3164 (defun js2-visit-throw-node (n v)
3165 (js2-visit-ast (js2-throw-node-expr n) v))
3166
3167 (defun js2-print-throw-node (n i)
3168 (insert (js2-make-pad i) "throw ")
3169 (js2-print-ast (js2-throw-node-expr n) 0)
3170 (insert ";\n"))
3171
3172 (cl-defstruct (js2-with-node
3173 (:include js2-node)
3174 (:constructor nil)
3175 (:constructor make-js2-with-node (&key (type js2-WITH)
3176 (pos js2-ts-cursor)
3177 len object
3178 body lp rp)))
3179 "AST node for a with-statement."
3180 object
3181 body
3182 lp ; buffer position of left-paren around object, nil if omitted
3183 rp) ; buffer position of right-paren around object, nil if omitted
3184
3185 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3186 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3187
3188 (defun js2-visit-with-node (n v)
3189 (js2-visit-ast (js2-with-node-object n) v)
3190 (js2-visit-ast (js2-with-node-body n) v))
3191
3192 (defun js2-print-with-node (n i)
3193 (let ((pad (js2-make-pad i)))
3194 (insert pad "with (")
3195 (js2-print-ast (js2-with-node-object n) 0)
3196 (insert ") {\n")
3197 (js2-print-body (js2-with-node-body n) (1+ i))
3198 (insert pad "}\n")))
3199
3200 (cl-defstruct (js2-label-node
3201 (:include js2-node)
3202 (:constructor nil)
3203 (:constructor make-js2-label-node (&key (type js2-LABEL)
3204 (pos js2-ts-cursor)
3205 len name)))
3206 "AST node for a statement label or case label."
3207 name ; a string
3208 loop) ; for validating and code-generating continue-to-label
3209
3210 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3211 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3212
3213 (defun js2-print-label (n i)
3214 (insert (js2-make-pad i)
3215 (js2-label-node-name n)
3216 ":\n"))
3217
3218 (cl-defstruct (js2-labeled-stmt-node
3219 (:include js2-node)
3220 (:constructor nil)
3221 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3222 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3223 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3224 (pos js2-ts-cursor)
3225 len labels stmt)))
3226 "AST node for a statement with one or more labels.
3227 Multiple labels for a statement are collapsed into the labels field."
3228 labels ; Lisp list of `js2-label-node'
3229 stmt) ; the statement these labels are for
3230
3231 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3232 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3233
3234 (defun js2-get-label-by-name (lbl-stmt name)
3235 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3236 Returns nil if no such label is in the list."
3237 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3238 result)
3239 (while (and label-list (not result))
3240 (if (string= (js2-label-node-name (car label-list)) name)
3241 (setq result (car label-list))
3242 (setq label-list (cdr label-list))))
3243 result))
3244
3245 (defun js2-visit-labeled-stmt (n v)
3246 (dolist (label (js2-labeled-stmt-node-labels n))
3247 (js2-visit-ast label v))
3248 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3249
3250 (defun js2-print-labeled-stmt (n i)
3251 (dolist (label (js2-labeled-stmt-node-labels n))
3252 (js2-print-ast label i))
3253 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3254
3255 (defun js2-labeled-stmt-node-contains (node label)
3256 "Return t if NODE contains LABEL in its label set.
3257 NODE is a `js2-labels-node'. LABEL is an identifier."
3258 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3259 if (string= label (js2-label-node-name nl))
3260 return t
3261 finally return nil))
3262
3263 (defsubst js2-labeled-stmt-node-add-label (node label)
3264 "Add a `js2-label-node' to the label set for this statement."
3265 (setf (js2-labeled-stmt-node-labels node)
3266 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3267
3268 (cl-defstruct (js2-jump-node
3269 (:include js2-node)
3270 (:constructor nil))
3271 "Abstract supertype of break and continue nodes."
3272 label ; `js2-name-node' for location of label identifier, if present
3273 target) ; target js2-labels-node or loop/switch statement
3274
3275 (defun js2-visit-jump-node (n v)
3276 ;; We don't visit the target, since it's a back-link.
3277 (js2-visit-ast (js2-jump-node-label n) v))
3278
3279 (cl-defstruct (js2-break-node
3280 (:include js2-jump-node)
3281 (:constructor nil)
3282 (:constructor make-js2-break-node (&key (type js2-BREAK)
3283 (pos js2-ts-cursor)
3284 len label target)))
3285 "AST node for a break statement.
3286 The label field is a `js2-name-node', possibly nil, for the named label
3287 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3288 is the target of the break - a label node or enclosing loop/switch statement.")
3289
3290 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3291 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3292
3293 (defun js2-print-break-node (n i)
3294 (insert (js2-make-pad i) "break")
3295 (when (js2-break-node-label n)
3296 (insert " ")
3297 (js2-print-ast (js2-break-node-label n) 0))
3298 (insert ";\n"))
3299
3300 (cl-defstruct (js2-continue-node
3301 (:include js2-jump-node)
3302 (:constructor nil)
3303 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3304 (pos js2-ts-cursor)
3305 len label target)))
3306 "AST node for a continue statement.
3307 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3308 It is nil if continue specifies no label. The target field is the jump target:
3309 a `js2-label-node' or the innermost enclosing loop.")
3310
3311 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3312 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3313
3314 (defun js2-print-continue-node (n i)
3315 (insert (js2-make-pad i) "continue")
3316 (when (js2-continue-node-label n)
3317 (insert " ")
3318 (js2-print-ast (js2-continue-node-label n) 0))
3319 (insert ";\n"))
3320
3321 (cl-defstruct (js2-function-node
3322 (:include js2-script-node)
3323 (:constructor nil)
3324 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3325 (pos js2-ts-cursor)
3326 len
3327 (ftype 'FUNCTION)
3328 (form 'FUNCTION_STATEMENT)
3329 (name "")
3330 params rest-p
3331 body
3332 generator-type
3333 lp rp)))
3334 "AST node for a function declaration.
3335 The `params' field is a Lisp list of nodes. Each node is either a simple
3336 `js2-name-node', or if it's a destructuring-assignment parameter, a
3337 `js2-array-node' or `js2-object-node'."
3338 ftype ; FUNCTION, GETTER or SETTER
3339 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3340 name ; function name (a `js2-name-node', or nil if anonymous)
3341 params ; a Lisp list of destructuring forms or simple name nodes
3342 rest-p ; if t, the last parameter is rest parameter
3343 body ; a `js2-block-node' or expression node (1.8 only)
3344 lp ; position of arg-list open-paren, or nil if omitted
3345 rp ; position of arg-list close-paren, or nil if omitted
3346 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3347 needs-activation ; t if we need an activation object for this frame
3348 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3349 member-expr) ; nonstandard Ecma extension from Rhino
3350
3351 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3352 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3353
3354 (defun js2-visit-function-node (n v)
3355 (js2-visit-ast (js2-function-node-name n) v)
3356 (dolist (p (js2-function-node-params n))
3357 (js2-visit-ast p v))
3358 (js2-visit-ast (js2-function-node-body n) v))
3359
3360 (defun js2-print-function-node (n i)
3361 (let* ((pad (js2-make-pad i))
3362 (getter (js2-node-get-prop n 'GETTER_SETTER))
3363 (name (or (js2-function-node-name n)
3364 (js2-function-node-member-expr n)))
3365 (params (js2-function-node-params n))
3366 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3367 (rest-p (js2-function-node-rest-p n))
3368 (body (js2-function-node-body n))
3369 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3370 (unless (or getter arrow)
3371 (insert pad "function")
3372 (when (eq (js2-function-node-generator-type n) 'STAR)
3373 (insert "*")))
3374 (when name
3375 (insert " ")
3376 (js2-print-ast name 0))
3377 (insert "(")
3378 (cl-loop with len = (length params)
3379 for param in params
3380 for count from 1
3381 do
3382 (when (and rest-p (= count len))
3383 (insert "..."))
3384 (js2-print-ast param 0)
3385 (when (< count len)
3386 (insert ", ")))
3387 (insert ") ")
3388 (when arrow
3389 (insert "=> "))
3390 (insert "{")
3391 ;; TODO: fix this to be smarter about indenting, etc.
3392 (unless expr
3393 (insert "\n"))
3394 (if (js2-block-node-p body)
3395 (js2-print-body body (1+ i))
3396 (js2-print-ast body 0))
3397 (insert pad "}")
3398 (unless expr
3399 (insert "\n"))))
3400
3401 (defun js2-function-name (node)
3402 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3403 (and (js2-function-node-name node)
3404 (js2-name-node-name (js2-function-node-name node))))
3405
3406 ;; Having this be an expression node makes it more flexible.
3407 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3408 ;; that work better if you assume it's an expression. Whenever we have
3409 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3410 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3411 (cl-defstruct (js2-var-decl-node
3412 (:include js2-node)
3413 (:constructor nil)
3414 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3415 (pos (js2-current-token-beg))
3416 len kids
3417 decl-type)))
3418 "AST node for a variable declaration list (VAR, CONST or LET).
3419 The node bounds differ depending on the declaration type. For VAR or
3420 CONST declarations, the bounds include the var/const keyword. For LET
3421 declarations, the node begins at the position of the first child."
3422 kids ; a Lisp list of `js2-var-init-node' structs.
3423 decl-type) ; js2-VAR, js2-CONST or js2-LET
3424
3425 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3426 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3427
3428 (defun js2-visit-var-decl (n v)
3429 (dolist (kid (js2-var-decl-node-kids n))
3430 (js2-visit-ast kid v)))
3431
3432 (defun js2-print-var-decl (n i)
3433 (let ((pad (js2-make-pad i))
3434 (tt (js2-var-decl-node-decl-type n)))
3435 (insert pad)
3436 (insert (cond
3437 ((= tt js2-VAR) "var ")
3438 ((= tt js2-LET) "let ")
3439 ((= tt js2-CONST) "const ")
3440 (t
3441 (error "malformed var-decl node"))))
3442 (cl-loop with kids = (js2-var-decl-node-kids n)
3443 with len = (length kids)
3444 for kid in kids
3445 for count from 1
3446 do
3447 (js2-print-ast kid 0)
3448 (if (< count len)
3449 (insert ", ")))))
3450
3451 (cl-defstruct (js2-var-init-node
3452 (:include js2-node)
3453 (:constructor nil)
3454 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3455 (pos js2-ts-cursor)
3456 len target
3457 initializer)))
3458 "AST node for a variable declaration.
3459 The type field will be js2-CONST for a const decl."
3460 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3461 initializer) ; initializer expression, a `js2-node'
3462
3463 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3464 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3465
3466 (defun js2-visit-var-init-node (n v)
3467 (js2-visit-ast (js2-var-init-node-target n) v)
3468 (js2-visit-ast (js2-var-init-node-initializer n) v))
3469
3470 (defun js2-print-var-init-node (n i)
3471 (let ((pad (js2-make-pad i))
3472 (name (js2-var-init-node-target n))
3473 (init (js2-var-init-node-initializer n)))
3474 (insert pad)
3475 (js2-print-ast name 0)
3476 (when init
3477 (insert " = ")
3478 (js2-print-ast init 0))))
3479
3480 (cl-defstruct (js2-cond-node
3481 (:include js2-node)
3482 (:constructor nil)
3483 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3484 (pos js2-ts-cursor)
3485 len
3486 test-expr
3487 true-expr
3488 false-expr
3489 q-pos c-pos)))
3490 "AST node for the ternary operator"
3491 test-expr
3492 true-expr
3493 false-expr
3494 q-pos ; buffer position of ?
3495 c-pos) ; buffer position of :
3496
3497 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3498 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3499
3500 (defun js2-visit-cond-node (n v)
3501 (js2-visit-ast (js2-cond-node-test-expr n) v)
3502 (js2-visit-ast (js2-cond-node-true-expr n) v)
3503 (js2-visit-ast (js2-cond-node-false-expr n) v))
3504
3505 (defun js2-print-cond-node (n i)
3506 (let ((pad (js2-make-pad i)))
3507 (insert pad)
3508 (js2-print-ast (js2-cond-node-test-expr n) 0)
3509 (insert " ? ")
3510 (js2-print-ast (js2-cond-node-true-expr n) 0)
3511 (insert " : ")
3512 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3513
3514 (cl-defstruct (js2-infix-node
3515 (:include js2-node)
3516 (:constructor nil)
3517 (:constructor make-js2-infix-node (&key type
3518 (pos js2-ts-cursor)
3519 len op-pos
3520 left right)))
3521 "Represents infix expressions.
3522 Includes assignment ops like `|=', and the comma operator.
3523 The type field inherited from `js2-node' holds the operator."
3524 op-pos ; buffer position where operator begins
3525 left ; any `js2-node'
3526 right) ; any `js2-node'
3527
3528 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3529 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3530
3531 (defun js2-visit-infix-node (n v)
3532 (js2-visit-ast (js2-infix-node-left n) v)
3533 (js2-visit-ast (js2-infix-node-right n) v))
3534
3535 (defconst js2-operator-tokens
3536 (let ((table (make-hash-table :test 'eq))
3537 (tokens
3538 (list (cons js2-IN "in")
3539 (cons js2-TYPEOF "typeof")
3540 (cons js2-INSTANCEOF "instanceof")
3541 (cons js2-DELPROP "delete")
3542 (cons js2-COMMA ",")
3543 (cons js2-COLON ":")
3544 (cons js2-OR "||")
3545 (cons js2-AND "&&")
3546 (cons js2-INC "++")
3547 (cons js2-DEC "--")
3548 (cons js2-BITOR "|")
3549 (cons js2-BITXOR "^")
3550 (cons js2-BITAND "&")
3551 (cons js2-EQ "==")
3552 (cons js2-NE "!=")
3553 (cons js2-LT "<")
3554 (cons js2-LE "<=")
3555 (cons js2-GT ">")
3556 (cons js2-GE ">=")
3557 (cons js2-LSH "<<")
3558 (cons js2-RSH ">>")
3559 (cons js2-URSH ">>>")
3560 (cons js2-ADD "+") ; infix plus
3561 (cons js2-SUB "-") ; infix minus
3562 (cons js2-MUL "*")
3563 (cons js2-DIV "/")
3564 (cons js2-MOD "%")
3565 (cons js2-NOT "!")
3566 (cons js2-BITNOT "~")
3567 (cons js2-POS "+") ; unary plus
3568 (cons js2-NEG "-") ; unary minus
3569 (cons js2-TRIPLEDOT "...")
3570 (cons js2-SHEQ "===") ; shallow equality
3571 (cons js2-SHNE "!==") ; shallow inequality
3572 (cons js2-ASSIGN "=")
3573 (cons js2-ASSIGN_BITOR "|=")
3574 (cons js2-ASSIGN_BITXOR "^=")
3575 (cons js2-ASSIGN_BITAND "&=")
3576 (cons js2-ASSIGN_LSH "<<=")
3577 (cons js2-ASSIGN_RSH ">>=")
3578 (cons js2-ASSIGN_URSH ">>>=")
3579 (cons js2-ASSIGN_ADD "+=")
3580 (cons js2-ASSIGN_SUB "-=")
3581 (cons js2-ASSIGN_MUL "*=")
3582 (cons js2-ASSIGN_DIV "/=")
3583 (cons js2-ASSIGN_MOD "%="))))
3584 (cl-loop for (k . v) in tokens do
3585 (puthash k v table))
3586 table))
3587
3588 (defun js2-print-infix-node (n i)
3589 (let* ((tt (js2-node-type n))
3590 (op (gethash tt js2-operator-tokens)))
3591 (unless op
3592 (error "unrecognized infix operator %s" (js2-node-type n)))
3593 (insert (js2-make-pad i))
3594 (js2-print-ast (js2-infix-node-left n) 0)
3595 (unless (= tt js2-COMMA)
3596 (insert " "))
3597 (insert op)
3598 (insert " ")
3599 (js2-print-ast (js2-infix-node-right n) 0)))
3600
3601 (cl-defstruct (js2-assign-node
3602 (:include js2-infix-node)
3603 (:constructor nil)
3604 (:constructor make-js2-assign-node (&key type
3605 (pos js2-ts-cursor)
3606 len op-pos
3607 left right)))
3608 "Represents any assignment.
3609 The type field holds the actual assignment operator.")
3610
3611 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3612 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3613
3614 (cl-defstruct (js2-unary-node
3615 (:include js2-node)
3616 (:constructor nil)
3617 (:constructor make-js2-unary-node (&key type ; required
3618 (pos js2-ts-cursor)
3619 len operand)))
3620 "AST node type for unary operator nodes.
3621 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3622 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3623 property is added if the operator follows the operand."
3624 operand) ; a `js2-node' expression
3625
3626 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3627 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3628
3629 (defun js2-visit-unary-node (n v)
3630 (js2-visit-ast (js2-unary-node-operand n) v))
3631
3632 (defun js2-print-unary-node (n i)
3633 (let* ((tt (js2-node-type n))
3634 (op (gethash tt js2-operator-tokens))
3635 (postfix (js2-node-get-prop n 'postfix)))
3636 (unless op
3637 (error "unrecognized unary operator %s" tt))
3638 (insert (js2-make-pad i))
3639 (unless postfix
3640 (insert op))
3641 (if (or (= tt js2-TYPEOF)
3642 (= tt js2-DELPROP))
3643 (insert " "))
3644 (js2-print-ast (js2-unary-node-operand n) 0)
3645 (when postfix
3646 (insert op))))
3647
3648 (cl-defstruct (js2-let-node
3649 (:include js2-scope)
3650 (:constructor nil)
3651 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3652 (pos (js2-current-token-beg))
3653 len vars body
3654 lp rp)))
3655 "AST node for a let expression or a let statement.
3656 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3657 vars ; a `js2-var-decl-node'
3658 body ; a `js2-node' representing the expression or body block
3659 lp
3660 rp)
3661
3662 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3663 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3664
3665 (defun js2-visit-let-node (n v)
3666 (js2-visit-ast (js2-let-node-vars n) v)
3667 (js2-visit-ast (js2-let-node-body n) v))
3668
3669 (defun js2-print-let-node (n i)
3670 (insert (js2-make-pad i) "let (")
3671 (let ((p (point)))
3672 (js2-print-ast (js2-let-node-vars n) 0)
3673 (delete-region p (+ p 4)))
3674 (insert ") ")
3675 (js2-print-ast (js2-let-node-body n) i))
3676
3677 (cl-defstruct (js2-keyword-node
3678 (:include js2-node)
3679 (:constructor nil)
3680 (:constructor make-js2-keyword-node (&key type
3681 (pos (js2-current-token-beg))
3682 (len (- js2-ts-cursor pos)))))
3683 "AST node representing a literal keyword such as `null'.
3684 Used for `null', `this', `true', `false' and `debugger'.
3685 The node type is set to js2-NULL, js2-THIS, etc.")
3686
3687 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3688 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3689
3690 (defun js2-print-keyword-node (n i)
3691 (insert (js2-make-pad i)
3692 (let ((tt (js2-node-type n)))
3693 (cond
3694 ((= tt js2-THIS) "this")
3695 ((= tt js2-SUPER) "super")
3696 ((= tt js2-NULL) "null")
3697 ((= tt js2-TRUE) "true")
3698 ((= tt js2-FALSE) "false")
3699 ((= tt js2-DEBUGGER) "debugger")
3700 (t (error "Invalid keyword literal type: %d" tt))))))
3701
3702 (defsubst js2-this-or-super-node-p (node)
3703 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3704 (let ((type (js2-node-type node)))
3705 (or (eq type js2-THIS) (eq type js2-SUPER))))
3706
3707 (cl-defstruct (js2-new-node
3708 (:include js2-node)
3709 (:constructor nil)
3710 (:constructor make-js2-new-node (&key (type js2-NEW)
3711 (pos (js2-current-token-beg))
3712 len target
3713 args initializer
3714 lp rp)))
3715 "AST node for new-expression such as new Foo()."
3716 target ; an identifier or reference
3717 args ; a Lisp list of argument nodes
3718 lp ; position of left-paren, nil if omitted
3719 rp ; position of right-paren, nil if omitted
3720 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3721
3722 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3723 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3724
3725 (defun js2-visit-new-node (n v)
3726 (js2-visit-ast (js2-new-node-target n) v)
3727 (dolist (arg (js2-new-node-args n))
3728 (js2-visit-ast arg v))
3729 (js2-visit-ast (js2-new-node-initializer n) v))
3730
3731 (defun js2-print-new-node (n i)
3732 (insert (js2-make-pad i) "new ")
3733 (js2-print-ast (js2-new-node-target n))
3734 (insert "(")
3735 (js2-print-list (js2-new-node-args n))
3736 (insert ")")
3737 (when (js2-new-node-initializer n)
3738 (insert " ")
3739 (js2-print-ast (js2-new-node-initializer n))))
3740
3741 (cl-defstruct (js2-name-node
3742 (:include js2-node)
3743 (:constructor nil)
3744 (:constructor make-js2-name-node (&key (type js2-NAME)
3745 (pos (js2-current-token-beg))
3746 (len (- js2-ts-cursor
3747 (js2-current-token-beg)))
3748 (name (js2-current-token-string)))))
3749 "AST node for a JavaScript identifier"
3750 name ; a string
3751 scope) ; a `js2-scope' (optional, used for codegen)
3752
3753 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3754 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3755
3756 (defun js2-print-name-node (n i)
3757 (insert (js2-make-pad i)
3758 (js2-name-node-name n)))
3759
3760 (defsubst js2-name-node-length (node)
3761 "Return identifier length of NODE, a `js2-name-node'.
3762 Returns 0 if NODE is nil or its identifier field is nil."
3763 (if node
3764 (length (js2-name-node-name node))
3765 0))
3766
3767 (cl-defstruct (js2-number-node
3768 (:include js2-node)
3769 (:constructor nil)
3770 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3771 (pos (js2-current-token-beg))
3772 (len (- js2-ts-cursor
3773 (js2-current-token-beg)))
3774 (value (js2-current-token-string))
3775 (num-value (js2-token-number
3776 (js2-current-token)))
3777 (num-base (js2-token-number-base
3778 (js2-current-token))))))
3779 "AST node for a number literal."
3780 value ; the original string, e.g. "6.02e23"
3781 num-value ; the parsed number value
3782 num-base) ; the number's base
3783
3784 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3785 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3786
3787 (defun js2-print-number-node (n i)
3788 (insert (js2-make-pad i)
3789 (number-to-string (js2-number-node-num-value n))))
3790
3791 (cl-defstruct (js2-regexp-node
3792 (:include js2-node)
3793 (:constructor nil)
3794 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3795 (pos (js2-current-token-beg))
3796 (len (- js2-ts-cursor
3797 (js2-current-token-beg)))
3798 value flags)))
3799 "AST node for a regular expression literal."
3800 value ; the regexp string, without // delimiters
3801 flags) ; a string of flags, e.g. `mi'.
3802
3803 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3804 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3805
3806 (defun js2-print-regexp (n i)
3807 (insert (js2-make-pad i)
3808 "/"
3809 (js2-regexp-node-value n)
3810 "/")
3811 (if (js2-regexp-node-flags n)
3812 (insert (js2-regexp-node-flags n))))
3813
3814 (cl-defstruct (js2-string-node
3815 (:include js2-node)
3816 (:constructor nil)
3817 (:constructor make-js2-string-node (&key (type js2-STRING)
3818 (pos (js2-current-token-beg))
3819 (len (- js2-ts-cursor
3820 (js2-current-token-beg)))
3821 (value (js2-current-token-string)))))
3822 "String literal.
3823 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3824 You can tell the quote type by looking at the first character."
3825 value) ; the characters of the string, including the quotes
3826
3827 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3828 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3829
3830 (defun js2-print-string-node (n i)
3831 (insert (js2-make-pad i)
3832 (js2-node-string n)))
3833
3834 (cl-defstruct (js2-template-node
3835 (:include js2-node)
3836 (:constructor nil)
3837 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3838 beg len kids)))
3839 "Template literal."
3840 kids) ; `js2-string-node' is used for string segments, other nodes
3841 ; for substitutions inside.
3842
3843 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3844 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3845
3846 (defun js2-visit-template (n callback)
3847 (dolist (kid (js2-template-node-kids n))
3848 (js2-visit-ast kid callback)))
3849
3850 (defun js2-print-template (n i)
3851 (insert (js2-make-pad i))
3852 (dolist (kid (js2-template-node-kids n))
3853 (if (js2-string-node-p kid)
3854 (insert (js2-node-string kid))
3855 (js2-print-ast kid))))
3856
3857 (cl-defstruct (js2-tagged-template-node
3858 (:include js2-node)
3859 (:constructor nil)
3860 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3861 beg len tag template)))
3862 "Tagged template literal."
3863 tag ; `js2-node' with the tag expression.
3864 template) ; `js2-template-node' with the template.
3865
3866 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3867 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3868
3869 (defun js2-visit-tagged-template (n callback)
3870 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3871 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3872
3873 (defun js2-print-tagged-template (n i)
3874 (insert (js2-make-pad i))
3875 (js2-print-ast (js2-tagged-template-node-tag n))
3876 (js2-print-ast (js2-tagged-template-node-template n)))
3877
3878 (cl-defstruct (js2-array-node
3879 (:include js2-node)
3880 (:constructor nil)
3881 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3882 (pos js2-ts-cursor)
3883 len elems)))
3884 "AST node for an array literal."
3885 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3886
3887 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3888 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3889
3890 (defun js2-visit-array-node (n v)
3891 (dolist (e (js2-array-node-elems n))
3892 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3893
3894 (defun js2-print-array-node (n i)
3895 (insert (js2-make-pad i) "[")
3896 (let ((elems (js2-array-node-elems n)))
3897 (js2-print-list elems)
3898 (when (and elems (null (car (last elems))))
3899 (insert ",")))
3900 (insert "]"))
3901
3902 (cl-defstruct (js2-class-node
3903 (:include js2-node)
3904 (:constructor nil)
3905 (:constructor make-js2-class-node (&key (type js2-CLASS)
3906 (pos js2-ts-cursor)
3907 (form 'CLASS_STATEMENT)
3908 (name "")
3909 extends len elems)))
3910 "AST node for an class expression.
3911 `elems' is a list of `js2-object-prop-node', and `extends' is an
3912 optional `js2-expr-node'"
3913 form ; CLASS_{STATEMENT|EXPRESSION}
3914 name ; class name (a `js2-node-name', or nil if anonymous)
3915 extends ; class heritage (a `js2-expr-node', or nil if none)
3916 elems)
3917
3918 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3919 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3920
3921 (defun js2-visit-class-node (n v)
3922 (js2-visit-ast (js2-class-node-name n) v)
3923 (js2-visit-ast (js2-class-node-extends n) v)
3924 (dolist (e (js2-class-node-elems n))
3925 (js2-visit-ast e v)))
3926
3927 (defun js2-print-class-node (n i)
3928 (let* ((pad (js2-make-pad i))
3929 (name (js2-class-node-name n))
3930 (extends (js2-class-node-extends n))
3931 (elems (js2-class-node-elems n)))
3932 (insert pad "class")
3933 (when name
3934 (insert " ")
3935 (js2-print-ast name 0))
3936 (when extends
3937 (insert " extends ")
3938 (js2-print-ast extends))
3939 (insert " {")
3940 (dolist (elem elems)
3941 (insert "\n")
3942 (if (js2-node-get-prop elem 'STATIC)
3943 (progn (insert (js2-make-pad (1+ i)) "static ")
3944 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3945 (js2-print-ast elem (1+ i))))
3946 (insert "\n" pad "}")))
3947
3948 (cl-defstruct (js2-object-node
3949 (:include js2-node)
3950 (:constructor nil)
3951 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3952 (pos js2-ts-cursor)
3953 len
3954 elems)))
3955 "AST node for an object literal expression.
3956 `elems' is a list of `js2-object-prop-node'."
3957 elems)
3958
3959 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3960 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3961
3962 (defun js2-visit-object-node (n v)
3963 (dolist (e (js2-object-node-elems n))
3964 (js2-visit-ast e v)))
3965
3966 (defun js2-print-object-node (n i)
3967 (insert (js2-make-pad i) "{")
3968 (js2-print-list (js2-object-node-elems n))
3969 (insert "}"))
3970
3971 (cl-defstruct (js2-object-prop-node
3972 (:include js2-infix-node)
3973 (:constructor nil)
3974 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3975 (pos js2-ts-cursor)
3976 len left
3977 right op-pos)))
3978 "AST node for an object literal prop:value entry.
3979 The `left' field is the property: a name node, string node,
3980 number node or expression node. The `right' field is a
3981 `js2-node' representing the initializer value. If the property
3982 is abbreviated, the node's `SHORTHAND' property is non-nil and
3983 both fields have the same value.")
3984
3985 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3986 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3987
3988 (defun js2-print-object-prop-node (n i)
3989 (let* ((left (js2-object-prop-node-left n))
3990 (right (js2-object-prop-node-right n))
3991 (computed (not (or (js2-string-node-p left)
3992 (js2-number-node-p left)
3993 (js2-name-node-p left)))))
3994 (insert (js2-make-pad i))
3995 (if computed
3996 (insert "["))
3997 (js2-print-ast left 0)
3998 (if computed
3999 (insert "]"))
4000 (if (not (js2-node-get-prop n 'SHORTHAND))
4001 (progn
4002 (insert ": ")
4003 (js2-print-ast right 0)))))
4004
4005 (cl-defstruct (js2-getter-setter-node
4006 (:include js2-infix-node)
4007 (:constructor nil)
4008 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
4009 (pos js2-ts-cursor)
4010 len left right)))
4011 "AST node for a getter/setter property in an object literal.
4012 The `left' field is the `js2-name-node' naming the getter/setter prop.
4013 The `right' field is always an anonymous `js2-function-node' with a node
4014 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
4015
4016 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
4017 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
4018
4019 (defun js2-print-getter-setter (n i)
4020 (let* ((pad (js2-make-pad i))
4021 (left (js2-getter-setter-node-left n))
4022 (right (js2-getter-setter-node-right n))
4023 (computed (not (or (js2-string-node-p left)
4024 (js2-number-node-p left)
4025 (js2-name-node-p left)))))
4026 (insert pad)
4027 (if (/= (js2-node-type n) js2-FUNCTION)
4028 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
4029 (when (and (js2-function-node-p right)
4030 (eq 'STAR (js2-function-node-generator-type right)))
4031 (insert "*"))
4032 (when computed
4033 (insert "["))
4034 (js2-print-ast left 0)
4035 (when computed
4036 (insert "]"))
4037 (js2-print-ast right 0)))
4038
4039 (cl-defstruct (js2-prop-get-node
4040 (:include js2-infix-node)
4041 (:constructor nil)
4042 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
4043 (pos js2-ts-cursor)
4044 len left right)))
4045 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
4046
4047 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4048 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4049
4050 (defun js2-visit-prop-get-node (n v)
4051 (js2-visit-ast (js2-prop-get-node-left n) v)
4052 (js2-visit-ast (js2-prop-get-node-right n) v))
4053
4054 (defun js2-print-prop-get-node (n i)
4055 (insert (js2-make-pad i))
4056 (js2-print-ast (js2-prop-get-node-left n) 0)
4057 (insert ".")
4058 (js2-print-ast (js2-prop-get-node-right n) 0))
4059
4060 (cl-defstruct (js2-elem-get-node
4061 (:include js2-node)
4062 (:constructor nil)
4063 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4064 (pos js2-ts-cursor)
4065 len target element
4066 lb rb)))
4067 "AST node for an array index expression such as foo[bar]."
4068 target ; a `js2-node' - the expression preceding the "."
4069 element ; a `js2-node' - the expression in brackets
4070 lb ; position of left-bracket, nil if omitted
4071 rb) ; position of right-bracket, nil if omitted
4072
4073 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4074 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4075
4076 (defun js2-visit-elem-get-node (n v)
4077 (js2-visit-ast (js2-elem-get-node-target n) v)
4078 (js2-visit-ast (js2-elem-get-node-element n) v))
4079
4080 (defun js2-print-elem-get-node (n i)
4081 (insert (js2-make-pad i))
4082 (js2-print-ast (js2-elem-get-node-target n) 0)
4083 (insert "[")
4084 (js2-print-ast (js2-elem-get-node-element n) 0)
4085 (insert "]"))
4086
4087 (cl-defstruct (js2-call-node
4088 (:include js2-node)
4089 (:constructor nil)
4090 (:constructor make-js2-call-node (&key (type js2-CALL)
4091 (pos js2-ts-cursor)
4092 len target args
4093 lp rp)))
4094 "AST node for a JavaScript function call."
4095 target ; a `js2-node' evaluating to the function to call
4096 args ; a Lisp list of `js2-node' arguments
4097 lp ; position of open-paren, or nil if missing
4098 rp) ; position of close-paren, or nil if missing
4099
4100 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4101 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4102
4103 (defun js2-visit-call-node (n v)
4104 (js2-visit-ast (js2-call-node-target n) v)
4105 (dolist (arg (js2-call-node-args n))
4106 (js2-visit-ast arg v)))
4107
4108 (defun js2-print-call-node (n i)
4109 (insert (js2-make-pad i))
4110 (js2-print-ast (js2-call-node-target n) 0)
4111 (insert "(")
4112 (js2-print-list (js2-call-node-args n))
4113 (insert ")"))
4114
4115 (cl-defstruct (js2-yield-node
4116 (:include js2-node)
4117 (:constructor nil)
4118 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4119 (pos js2-ts-cursor)
4120 len value star-p)))
4121 "AST node for yield statement or expression."
4122 star-p ; whether it's yield*
4123 value) ; optional: value to be yielded
4124
4125 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4126 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4127
4128 (defun js2-visit-yield-node (n v)
4129 (js2-visit-ast (js2-yield-node-value n) v))
4130
4131 (defun js2-print-yield-node (n i)
4132 (insert (js2-make-pad i))
4133 (insert "yield")
4134 (when (js2-yield-node-star-p n)
4135 (insert "*"))
4136 (when (js2-yield-node-value n)
4137 (insert " ")
4138 (js2-print-ast (js2-yield-node-value n) 0)))
4139
4140 (cl-defstruct (js2-paren-node
4141 (:include js2-node)
4142 (:constructor nil)
4143 (:constructor make-js2-paren-node (&key (type js2-LP)
4144 (pos js2-ts-cursor)
4145 len expr)))
4146 "AST node for a parenthesized expression.
4147 In particular, used when the parens are syntactically optional,
4148 as opposed to required parens such as those enclosing an if-conditional."
4149 expr) ; `js2-node'
4150
4151 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4152 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4153
4154 (defun js2-visit-paren-node (n v)
4155 (js2-visit-ast (js2-paren-node-expr n) v))
4156
4157 (defun js2-print-paren-node (n i)
4158 (insert (js2-make-pad i))
4159 (insert "(")
4160 (js2-print-ast (js2-paren-node-expr n) 0)
4161 (insert ")"))
4162
4163 (cl-defstruct (js2-comp-node
4164 (:include js2-scope)
4165 (:constructor nil)
4166 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4167 (pos js2-ts-cursor)
4168 len result
4169 loops filters
4170 form)))
4171 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4172 result ; result expression (just after left-bracket)
4173 loops ; a Lisp list of `js2-comp-loop-node'
4174 filters ; a Lisp list of guard/filter expressions
4175 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4176 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4177 )
4178
4179 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4180 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4181
4182 (defun js2-visit-comp-node (n v)
4183 (js2-visit-ast (js2-comp-node-result n) v)
4184 (dolist (l (js2-comp-node-loops n))
4185 (js2-visit-ast l v))
4186 (dolist (f (js2-comp-node-filters n))
4187 (js2-visit-ast f v)))
4188
4189 (defun js2-print-comp-node (n i)
4190 (let ((pad (js2-make-pad i))
4191 (result (js2-comp-node-result n))
4192 (loops (js2-comp-node-loops n))
4193 (filters (js2-comp-node-filters n))
4194 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4195 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4196 (insert pad (if gen-p "(" "["))
4197 (when legacy-p
4198 (js2-print-ast result 0))
4199 (dolist (l loops)
4200 (when legacy-p
4201 (insert " "))
4202 (js2-print-ast l 0)
4203 (unless legacy-p
4204 (insert " ")))
4205 (dolist (f filters)
4206 (when legacy-p
4207 (insert " "))
4208 (insert "if (")
4209 (js2-print-ast f 0)
4210 (insert ")")
4211 (unless legacy-p
4212 (insert " ")))
4213 (unless legacy-p
4214 (js2-print-ast result 0))
4215 (insert (if gen-p ")" "]"))))
4216
4217 (cl-defstruct (js2-comp-loop-node
4218 (:include js2-for-in-node)
4219 (:constructor nil)
4220 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4221 (pos js2-ts-cursor)
4222 len iterator
4223 object in-pos
4224 foreach-p
4225 each-pos
4226 forof-p
4227 lp rp)))
4228 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4229
4230 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4231 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4232
4233 (defun js2-visit-comp-loop (n v)
4234 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4235 (js2-visit-ast (js2-comp-loop-node-object n) v))
4236
4237 (defun js2-print-comp-loop (n _i)
4238 (insert "for ")
4239 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4240 (insert "(")
4241 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4242 (insert (if (js2-comp-loop-node-forof-p n)
4243 " of " " in "))
4244 (js2-print-ast (js2-comp-loop-node-object n) 0)
4245 (insert ")"))
4246
4247 (cl-defstruct (js2-empty-expr-node
4248 (:include js2-node)
4249 (:constructor nil)
4250 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4251 (pos (js2-current-token-beg))
4252 len)))
4253 "AST node for an empty expression.")
4254
4255 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4256 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4257
4258 (cl-defstruct (js2-xml-node
4259 (:include js2-block-node)
4260 (:constructor nil)
4261 (:constructor make-js2-xml-node (&key (type js2-XML)
4262 (pos (js2-current-token-beg))
4263 len kids)))
4264 "AST node for initial parse of E4X literals.
4265 The kids field is a list of XML fragments, each a `js2-string-node' or
4266 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4267
4268 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4269 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4270
4271 (defun js2-print-xml-node (n i)
4272 (dolist (kid (js2-xml-node-kids n))
4273 (js2-print-ast kid i)))
4274
4275 (cl-defstruct (js2-xml-js-expr-node
4276 (:include js2-xml-node)
4277 (:constructor nil)
4278 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4279 (pos js2-ts-cursor)
4280 len expr)))
4281 "AST node for an embedded JavaScript {expression} in an E4X literal.
4282 The start and end fields correspond to the curly-braces."
4283 expr) ; a `js2-expr-node' of some sort
4284
4285 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4286 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4287
4288 (defun js2-visit-xml-js-expr (n v)
4289 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4290
4291 (defun js2-print-xml-js-expr (n i)
4292 (insert (js2-make-pad i))
4293 (insert "{")
4294 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4295 (insert "}"))
4296
4297 (cl-defstruct (js2-xml-dot-query-node
4298 (:include js2-infix-node)
4299 (:constructor nil)
4300 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4301 (pos js2-ts-cursor)
4302 op-pos len left
4303 right rp)))
4304 "AST node for an E4X foo.(bar) filter expression.
4305 Note that the left-paren is automatically the character immediately
4306 following the dot (.) in the operator. No whitespace is permitted
4307 between the dot and the lp by the scanner."
4308 rp)
4309
4310 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4311 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4312
4313 (defun js2-print-xml-dot-query (n i)
4314 (insert (js2-make-pad i))
4315 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4316 (insert ".(")
4317 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4318 (insert ")"))
4319
4320 (cl-defstruct (js2-xml-ref-node
4321 (:include js2-node)
4322 (:constructor nil)) ; abstract
4323 "Base type for E4X XML attribute-access or property-get expressions.
4324 Such expressions can take a variety of forms. The general syntax has
4325 three parts:
4326
4327 - (optional) an @ (specifying an attribute access)
4328 - (optional) a namespace (a `js2-name-node') and double-colon
4329 - (required) either a `js2-name-node' or a bracketed [expression]
4330
4331 The property-name expressions (examples: ns::name, @name) are
4332 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4333 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4334
4335 This node type (or more specifically, its subclasses) will sometimes
4336 be the right-hand child of a `js2-prop-get-node' or a
4337 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4338 The `js2-xml-ref-node' may also be a standalone primary expression with
4339 no explicit target, which is valid in certain expression contexts such as
4340
4341 company..employee.(@id < 100)
4342
4343 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4344 expression whose parent is a `js2-xml-dot-query-node'."
4345 namespace
4346 at-pos
4347 colon-pos)
4348
4349 (defsubst js2-xml-ref-node-attr-access-p (node)
4350 "Return non-nil if this expression began with an @-token."
4351 (and (numberp (js2-xml-ref-node-at-pos node))
4352 (cl-plusp (js2-xml-ref-node-at-pos node))))
4353
4354 (cl-defstruct (js2-xml-prop-ref-node
4355 (:include js2-xml-ref-node)
4356 (:constructor nil)
4357 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4358 (pos (js2-current-token-beg))
4359 len propname
4360 namespace at-pos
4361 colon-pos)))
4362 "AST node for an E4X XML [expr] property-ref expression.
4363 The JavaScript syntax is an optional @, an optional ns::, and a name.
4364
4365 [ '@' ] [ name '::' ] name
4366
4367 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4368 @ns::*, @*::attr, @*::*, and @*.
4369
4370 The node starts at the @ token, if present. Otherwise it starts at the
4371 namespace name. The node bounds extend through the closing right-bracket,
4372 or if it is missing due to a syntax error, through the end of the index
4373 expression."
4374 propname)
4375
4376 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4377 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4378
4379 (defun js2-visit-xml-prop-ref-node (n v)
4380 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4381 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4382
4383 (defun js2-print-xml-prop-ref-node (n i)
4384 (insert (js2-make-pad i))
4385 (if (js2-xml-ref-node-attr-access-p n)
4386 (insert "@"))
4387 (when (js2-xml-prop-ref-node-namespace n)
4388 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4389 (insert "::"))
4390 (if (js2-xml-prop-ref-node-propname n)
4391 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4392
4393 (cl-defstruct (js2-xml-elem-ref-node
4394 (:include js2-xml-ref-node)
4395 (:constructor nil)
4396 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4397 (pos (js2-current-token-beg))
4398 len expr lb rb
4399 namespace at-pos
4400 colon-pos)))
4401 "AST node for an E4X XML [expr] member-ref expression.
4402 Syntax:
4403
4404 [ '@' ] [ name '::' ] '[' expr ']'
4405
4406 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4407
4408 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4409 is not a legal E4X XML element-ref expression, since it's already used
4410 for standard JavaScript element-get array indexing. Hence, a
4411 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4412 non-nil namespace node, or both.
4413
4414 The node starts at the @ token, if present. Otherwise it starts
4415 at the namespace name. The node bounds extend through the closing
4416 right-bracket, or if it is missing due to a syntax error, through the
4417 end of the index expression."
4418 expr ; the bracketed index expression
4419 lb
4420 rb)
4421
4422 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4423 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4424
4425 (defun js2-visit-xml-elem-ref-node (n v)
4426 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4427 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4428
4429 (defun js2-print-xml-elem-ref-node (n i)
4430 (insert (js2-make-pad i))
4431 (if (js2-xml-ref-node-attr-access-p n)
4432 (insert "@"))
4433 (when (js2-xml-elem-ref-node-namespace n)
4434 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4435 (insert "::"))
4436 (insert "[")
4437 (if (js2-xml-elem-ref-node-expr n)
4438 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4439 (insert "]"))
4440
4441 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4442
4443 (cl-defstruct (js2-xml-start-tag-node
4444 (:include js2-xml-node)
4445 (:constructor nil)
4446 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4447 (pos js2-ts-cursor)
4448 len name attrs kids
4449 empty-p)))
4450 "AST node for an XML start-tag. Not currently used.
4451 The `kids' field is a Lisp list of child content nodes."
4452 name ; a `js2-xml-name-node'
4453 attrs ; a Lisp list of `js2-xml-attr-node'
4454 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4455
4456 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4457 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4458
4459 (defun js2-visit-xml-start-tag (n v)
4460 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4461 (dolist (attr (js2-xml-start-tag-node-attrs n))
4462 (js2-visit-ast attr v))
4463 (js2-visit-block n v))
4464
4465 (defun js2-print-xml-start-tag (n i)
4466 (insert (js2-make-pad i) "<")
4467 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4468 (when (js2-xml-start-tag-node-attrs n)
4469 (insert " ")
4470 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4471 (insert ">"))
4472
4473 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4474 ;; and add the end-tag to the kids list of the parent as well.
4475 (cl-defstruct (js2-xml-end-tag-node
4476 (:include js2-xml-node)
4477 (:constructor nil)
4478 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4479 (pos js2-ts-cursor)
4480 len name)))
4481 "AST node for an XML end-tag. Not currently used."
4482 name) ; a `js2-xml-name-node'
4483
4484 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4485 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4486
4487 (defun js2-visit-xml-end-tag (n v)
4488 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4489
4490 (defun js2-print-xml-end-tag (n i)
4491 (insert (js2-make-pad i))
4492 (insert "</")
4493 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4494 (insert ">"))
4495
4496 (cl-defstruct (js2-xml-name-node
4497 (:include js2-xml-node)
4498 (:constructor nil)
4499 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4500 (pos js2-ts-cursor)
4501 len namespace kids)))
4502 "AST node for an E4X XML name. Not currently used.
4503 Any XML name can be qualified with a namespace, hence the namespace field.
4504 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4505 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4506 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4507 namespace) ; a `js2-string-node'
4508
4509 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4510 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4511
4512 (defun js2-visit-xml-name-node (n v)
4513 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4514
4515 (defun js2-print-xml-name-node (n i)
4516 (insert (js2-make-pad i))
4517 (when (js2-xml-name-node-namespace n)
4518 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4519 (insert "::"))
4520 (dolist (kid (js2-xml-name-node-kids n))
4521 (js2-print-ast kid 0)))
4522
4523 (cl-defstruct (js2-xml-pi-node
4524 (:include js2-xml-node)
4525 (:constructor nil)
4526 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4527 (pos js2-ts-cursor)
4528 len name attrs)))
4529 "AST node for an E4X XML processing instruction. Not currently used."
4530 name ; a `js2-xml-name-node'
4531 attrs) ; a list of `js2-xml-attr-node'
4532
4533 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4534 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4535
4536 (defun js2-visit-xml-pi-node (n v)
4537 (js2-visit-ast (js2-xml-pi-node-name n) v)
4538 (dolist (attr (js2-xml-pi-node-attrs n))
4539 (js2-visit-ast attr v)))
4540
4541 (defun js2-print-xml-pi-node (n i)
4542 (insert (js2-make-pad i) "<?")
4543 (js2-print-ast (js2-xml-pi-node-name n))
4544 (when (js2-xml-pi-node-attrs n)
4545 (insert " ")
4546 (js2-print-list (js2-xml-pi-node-attrs n)))
4547 (insert "?>"))
4548
4549 (cl-defstruct (js2-xml-cdata-node
4550 (:include js2-xml-node)
4551 (:constructor nil)
4552 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4553 (pos js2-ts-cursor)
4554 len content)))
4555 "AST node for a CDATA escape section. Not currently used."
4556 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4557
4558 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4559 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4560
4561 (defun js2-visit-xml-cdata-node (n v)
4562 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4563
4564 (defun js2-print-xml-cdata-node (n i)
4565 (insert (js2-make-pad i))
4566 (js2-print-ast (js2-xml-cdata-node-content n)))
4567
4568 (cl-defstruct (js2-xml-attr-node
4569 (:include js2-xml-node)
4570 (:constructor nil)
4571 (:constructor make-js2-attr-node (&key (type js2-XML)
4572 (pos js2-ts-cursor)
4573 len name value
4574 eq-pos quote-type)))
4575 "AST node representing a foo='bar' XML attribute value. Not yet used."
4576 name ; a `js2-xml-name-node'
4577 value ; a `js2-xml-name-node'
4578 eq-pos ; buffer position of "=" sign
4579 quote-type) ; 'single or 'double
4580
4581 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4582 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4583
4584 (defun js2-visit-xml-attr-node (n v)
4585 (js2-visit-ast (js2-xml-attr-node-name n) v)
4586 (js2-visit-ast (js2-xml-attr-node-value n) v))
4587
4588 (defun js2-print-xml-attr-node (n i)
4589 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4590 "'"
4591 "\"")))
4592 (insert (js2-make-pad i))
4593 (js2-print-ast (js2-xml-attr-node-name n) 0)
4594 (insert "=" quote)
4595 (js2-print-ast (js2-xml-attr-node-value n) 0)
4596 (insert quote)))
4597
4598 (cl-defstruct (js2-xml-text-node
4599 (:include js2-xml-node)
4600 (:constructor nil)
4601 (:constructor make-js2-text-node (&key (type js2-XML)
4602 (pos js2-ts-cursor)
4603 len content)))
4604 "AST node for an E4X XML text node. Not currently used."
4605 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4606
4607 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4608 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4609
4610 (defun js2-visit-xml-text-node (n v)
4611 (js2-visit-ast (js2-xml-text-node-content n) v))
4612
4613 (defun js2-print-xml-text-node (n i)
4614 (insert (js2-make-pad i))
4615 (dolist (kid (js2-xml-text-node-content n))
4616 (js2-print-ast kid)))
4617
4618 (cl-defstruct (js2-xml-comment-node
4619 (:include js2-xml-node)
4620 (:constructor nil)
4621 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4622 (pos js2-ts-cursor)
4623 len)))
4624 "AST node for E4X XML comment. Not currently used.")
4625
4626 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4627 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4628
4629 (defun js2-print-xml-comment (n i)
4630 (insert (js2-make-pad i)
4631 (js2-node-string n)))
4632
4633 ;;; Node utilities
4634
4635 (defsubst js2-node-line (n)
4636 "Fetch the source line number at the start of node N.
4637 This is O(n) in the length of the source buffer; use prudently."
4638 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4639
4640 (defsubst js2-block-node-kid (n i)
4641 "Return child I of node N, or nil if there aren't that many."
4642 (nth i (js2-block-node-kids n)))
4643
4644 (defsubst js2-block-node-first (n)
4645 "Return first child of block node N, or nil if there is none."
4646 (cl-first (js2-block-node-kids n)))
4647
4648 (defun js2-node-root (n)
4649 "Return the root of the AST containing N.
4650 If N has no parent pointer, returns N."
4651 (let ((parent (js2-node-parent n)))
4652 (if parent
4653 (js2-node-root parent)
4654 n)))
4655
4656 (defsubst js2-node-short-name (n)
4657 "Return the short name of node N as a string, e.g. `js2-if-node'."
4658 (substring (symbol-name (aref n 0))
4659 (length "cl-struct-")))
4660
4661 (defun js2-node-child-list (node)
4662 "Return the child list for NODE, a Lisp list of nodes.
4663 Works for block nodes, array nodes, obj literals, funarg lists,
4664 var decls and try nodes (for catch clauses). Note that you should call
4665 `js2-block-node-kids' on the function body for the body statements.
4666 Returns nil for zero-length child lists or unsupported nodes."
4667 (cond
4668 ((js2-function-node-p node)
4669 (js2-function-node-params node))
4670 ((js2-block-node-p node)
4671 (js2-block-node-kids node))
4672 ((js2-try-node-p node)
4673 (js2-try-node-catch-clauses node))
4674 ((js2-array-node-p node)
4675 (js2-array-node-elems node))
4676 ((js2-object-node-p node)
4677 (js2-object-node-elems node))
4678 ((js2-call-node-p node)
4679 (js2-call-node-args node))
4680 ((js2-new-node-p node)
4681 (js2-new-node-args node))
4682 ((js2-var-decl-node-p node)
4683 (js2-var-decl-node-kids node))
4684 (t
4685 nil)))
4686
4687 (defun js2-node-set-child-list (node kids)
4688 "Set the child list for NODE to KIDS."
4689 (cond
4690 ((js2-function-node-p node)
4691 (setf (js2-function-node-params node) kids))
4692 ((js2-block-node-p node)
4693 (setf (js2-block-node-kids node) kids))
4694 ((js2-try-node-p node)
4695 (setf (js2-try-node-catch-clauses node) kids))
4696 ((js2-array-node-p node)
4697 (setf (js2-array-node-elems node) kids))
4698 ((js2-object-node-p node)
4699 (setf (js2-object-node-elems node) kids))
4700 ((js2-call-node-p node)
4701 (setf (js2-call-node-args node) kids))
4702 ((js2-new-node-p node)
4703 (setf (js2-new-node-args node) kids))
4704 ((js2-var-decl-node-p node)
4705 (setf (js2-var-decl-node-kids node) kids))
4706 (t
4707 (error "Unsupported node type: %s" (js2-node-short-name node))))
4708 kids)
4709
4710 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4711 (defconst js2-paren-expr-nodes
4712 '(cl-struct-js2-comp-loop-node
4713 cl-struct-js2-comp-node
4714 cl-struct-js2-call-node
4715 cl-struct-js2-catch-node
4716 cl-struct-js2-do-node
4717 cl-struct-js2-elem-get-node
4718 cl-struct-js2-for-in-node
4719 cl-struct-js2-for-node
4720 cl-struct-js2-function-node
4721 cl-struct-js2-if-node
4722 cl-struct-js2-let-node
4723 cl-struct-js2-new-node
4724 cl-struct-js2-paren-node
4725 cl-struct-js2-switch-node
4726 cl-struct-js2-while-node
4727 cl-struct-js2-with-node
4728 cl-struct-js2-xml-dot-query-node)
4729 "Node types that can have a parenthesized child expression.
4730 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4731
4732 (defsubst js2-paren-expr-node-p (node)
4733 "Return t for nodes that typically have a parenthesized child expression.
4734 Useful for computing the indentation anchors for arg-lists and conditions.
4735 Note that it may return a false positive, for instance when NODE is
4736 a `js2-new-node' and there are no arguments or parentheses."
4737 (memq (aref node 0) js2-paren-expr-nodes))
4738
4739 ;; Fake polymorphism... yech.
4740 (defun js2-node-lp (node)
4741 "Return relative left-paren position for NODE, if applicable.
4742 For `js2-elem-get-node' structs, returns left-bracket position.
4743 Note that the position may be nil in the case of a parse error."
4744 (cond
4745 ((js2-elem-get-node-p node)
4746 (js2-elem-get-node-lb node))
4747 ((js2-loop-node-p node)
4748 (js2-loop-node-lp node))
4749 ((js2-function-node-p node)
4750 (js2-function-node-lp node))
4751 ((js2-if-node-p node)
4752 (js2-if-node-lp node))
4753 ((js2-new-node-p node)
4754 (js2-new-node-lp node))
4755 ((js2-call-node-p node)
4756 (js2-call-node-lp node))
4757 ((js2-paren-node-p node)
4758 0)
4759 ((js2-switch-node-p node)
4760 (js2-switch-node-lp node))
4761 ((js2-catch-node-p node)
4762 (js2-catch-node-lp node))
4763 ((js2-let-node-p node)
4764 (js2-let-node-lp node))
4765 ((js2-comp-node-p node)
4766 0)
4767 ((js2-with-node-p node)
4768 (js2-with-node-lp node))
4769 ((js2-xml-dot-query-node-p node)
4770 (1+ (js2-infix-node-op-pos node)))
4771 (t
4772 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4773
4774 ;; Fake polymorphism... blech.
4775 (defun js2-node-rp (node)
4776 "Return relative right-paren position for NODE, if applicable.
4777 For `js2-elem-get-node' structs, returns right-bracket position.
4778 Note that the position may be nil in the case of a parse error."
4779 (cond
4780 ((js2-elem-get-node-p node)
4781 (js2-elem-get-node-rb node))
4782 ((js2-loop-node-p node)
4783 (js2-loop-node-rp node))
4784 ((js2-function-node-p node)
4785 (js2-function-node-rp node))
4786 ((js2-if-node-p node)
4787 (js2-if-node-rp node))
4788 ((js2-new-node-p node)
4789 (js2-new-node-rp node))
4790 ((js2-call-node-p node)
4791 (js2-call-node-rp node))
4792 ((js2-paren-node-p node)
4793 (1- (js2-node-len node)))
4794 ((js2-switch-node-p node)
4795 (js2-switch-node-rp node))
4796 ((js2-catch-node-p node)
4797 (js2-catch-node-rp node))
4798 ((js2-let-node-p node)
4799 (js2-let-node-rp node))
4800 ((js2-comp-node-p node)
4801 (1- (js2-node-len node)))
4802 ((js2-with-node-p node)
4803 (js2-with-node-rp node))
4804 ((js2-xml-dot-query-node-p node)
4805 (1+ (js2-xml-dot-query-node-rp node)))
4806 (t
4807 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4808
4809 (defsubst js2-node-first-child (node)
4810 "Return the first element of `js2-node-child-list' for NODE."
4811 (car (js2-node-child-list node)))
4812
4813 (defsubst js2-node-last-child (node)
4814 "Return the last element of `js2-node-last-child' for NODE."
4815 (car (last (js2-node-child-list node))))
4816
4817 (defun js2-node-prev-sibling (node)
4818 "Return the previous statement in parent.
4819 Works for parents supported by `js2-node-child-list'.
4820 Returns nil if NODE is not in the parent, or PARENT is
4821 not a supported node, or if NODE is the first child."
4822 (let* ((p (js2-node-parent node))
4823 (kids (js2-node-child-list p))
4824 (sib (car kids)))
4825 (while (and kids
4826 (not (eq node (cadr kids))))
4827 (setq kids (cdr kids)
4828 sib (car kids)))
4829 sib))
4830
4831 (defun js2-node-next-sibling (node)
4832 "Return the next statement in parent block.
4833 Returns nil if NODE is not in the block, or PARENT is not
4834 a block node, or if NODE is the last statement."
4835 (let* ((p (js2-node-parent node))
4836 (kids (js2-node-child-list p)))
4837 (while (and kids
4838 (not (eq node (car kids))))
4839 (setq kids (cdr kids)))
4840 (cadr kids)))
4841
4842 (defun js2-node-find-child-before (pos parent &optional after)
4843 "Find the last child that starts before POS in parent.
4844 If AFTER is non-nil, returns first child starting after POS.
4845 POS is an absolute buffer position. PARENT is any node
4846 supported by `js2-node-child-list'.
4847 Returns nil if no applicable child is found."
4848 (let ((kids (if (js2-function-node-p parent)
4849 (js2-block-node-kids (js2-function-node-body parent))
4850 (js2-node-child-list parent)))
4851 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4852 (js2-function-node-body parent)
4853 parent)))
4854 kid result fn
4855 (continue t))
4856 (setq fn (if after '>= '<))
4857 (while (and kids continue)
4858 (setq kid (car kids))
4859 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4860 (setq result kid
4861 continue (not after))
4862 (setq continue after))
4863 (setq kids (cdr kids)))
4864 result))
4865
4866 (defun js2-node-find-child-after (pos parent)
4867 "Find first child that starts after POS in parent.
4868 POS is an absolute buffer position. PARENT is any node
4869 supported by `js2-node-child-list'.
4870 Returns nil if no applicable child is found."
4871 (js2-node-find-child-before pos parent 'after))
4872
4873 (defun js2-node-replace-child (pos parent new-node)
4874 "Replace node at index POS in PARENT with NEW-NODE.
4875 Only works for parents supported by `js2-node-child-list'."
4876 (let ((kids (js2-node-child-list parent))
4877 (i 0))
4878 (while (< i pos)
4879 (setq kids (cdr kids)
4880 i (1+ i)))
4881 (setcar kids new-node)
4882 (js2-node-add-children parent new-node)))
4883
4884 (defun js2-node-buffer (n)
4885 "Return the buffer associated with AST N.
4886 Returns nil if the buffer is not set as a property on the root
4887 node, or if parent links were not recorded during parsing."
4888 (let ((root (js2-node-root n)))
4889 (and root
4890 (js2-ast-root-p root)
4891 (js2-ast-root-buffer root))))
4892
4893 (defun js2-block-node-push (n kid)
4894 "Push js2-node KID onto the end of js2-block-node N's child list.
4895 KID is always added to the -end- of the kids list.
4896 Function also calls `js2-node-add-children' to add the parent link."
4897 (let ((kids (js2-node-child-list n)))
4898 (if kids
4899 (setcdr kids (nconc (cdr kids) (list kid)))
4900 (js2-node-set-child-list n (list kid)))
4901 (js2-node-add-children n kid)))
4902
4903 (defun js2-node-string (node)
4904 (with-current-buffer (or (js2-node-buffer node)
4905 (error "No buffer available for node %s" node))
4906 (let ((pos (js2-node-abs-pos node)))
4907 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4908
4909 ;; Container for storing the node we're looking for in a traversal.
4910 (js2-deflocal js2-discovered-node nil)
4911
4912 ;; Keep track of absolute node position during traversals.
4913 (js2-deflocal js2-visitor-offset nil)
4914
4915 (js2-deflocal js2-node-search-point nil)
4916
4917 (when js2-mode-dev-mode-p
4918 (defun js2-find-node-at-point ()
4919 (interactive)
4920 (let ((node (js2-node-at-point)))
4921 (message "%s" (or node "No node found at point"))))
4922 (defun js2-node-name-at-point ()
4923 (interactive)
4924 (let ((node (js2-node-at-point)))
4925 (message "%s" (if node
4926 (js2-node-short-name node)
4927 "No node found at point.")))))
4928
4929 (defun js2-node-at-point (&optional pos skip-comments)
4930 "Return AST node at POS, a buffer position, defaulting to current point.
4931 The `js2-mode-ast' variable must be set to the current parse tree.
4932 Signals an error if the AST (`js2-mode-ast') is nil.
4933 Always returns a node - if it can't find one, it returns the root.
4934 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4935 (let ((ast js2-mode-ast)
4936 result)
4937 (unless ast
4938 (error "No JavaScript AST available"))
4939 ;; Look through comments first, since they may be inside nodes that
4940 ;; would otherwise report a match.
4941 (setq pos (or pos (point))
4942 result (if (> pos (js2-node-abs-end ast))
4943 ast
4944 (if (not skip-comments)
4945 (js2-comment-at-point pos))))
4946 (unless result
4947 (setq js2-discovered-node nil
4948 js2-visitor-offset 0
4949 js2-node-search-point pos)
4950 (unwind-protect
4951 (catch 'js2-visit-done
4952 (js2-visit-ast ast #'js2-node-at-point-visitor))
4953 (setq js2-visitor-offset nil
4954 js2-node-search-point nil))
4955 (setq result js2-discovered-node))
4956 ;; may have found a comment beyond end of last child node,
4957 ;; since visiting the ast-root looks at the comment-list last.
4958 (if (and skip-comments
4959 (js2-comment-node-p result))
4960 (setq result nil))
4961 (or result js2-mode-ast)))
4962
4963 (defun js2-node-at-point-visitor (node end-p)
4964 (let ((rel-pos (js2-node-pos node))
4965 abs-pos
4966 abs-end
4967 (point js2-node-search-point))
4968 (cond
4969 (end-p
4970 ;; this evaluates to a non-nil return value, even if it's zero
4971 (cl-decf js2-visitor-offset rel-pos))
4972 ;; we already looked for comments before visiting, and don't want them now
4973 ((js2-comment-node-p node)
4974 nil)
4975 (t
4976 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4977 ;; we only want to use the node if the point is before
4978 ;; the last character position in the node, so we decrement
4979 ;; the absolute end by 1.
4980 abs-end (+ abs-pos (js2-node-len node) -1))
4981 (cond
4982 ;; If this node starts after search-point, stop the search.
4983 ((> abs-pos point)
4984 (throw 'js2-visit-done nil))
4985 ;; If this node ends before the search-point, don't check kids.
4986 ((> point abs-end)
4987 nil)
4988 (t
4989 ;; Otherwise point is within this node, possibly in a child.
4990 (setq js2-discovered-node node)
4991 t)))))) ; keep processing kids to look for more specific match
4992
4993 (defsubst js2-block-comment-p (node)
4994 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4995 (and (js2-comment-node-p node)
4996 (memq (js2-comment-node-format node) '(jsdoc block))))
4997
4998 ;; TODO: put the comments in a vector and binary-search them instead
4999 (defun js2-comment-at-point (&optional pos)
5000 "Look through scanned comment nodes for one containing POS.
5001 POS is a buffer position that defaults to current point.
5002 Function returns nil if POS was not in any comment node."
5003 (let ((ast js2-mode-ast)
5004 (x (or pos (point)))
5005 beg end)
5006 (unless ast
5007 (error "No JavaScript AST available"))
5008 (catch 'done
5009 ;; Comments are stored in lexical order.
5010 (dolist (comment (js2-ast-root-comments ast) nil)
5011 (setq beg (js2-node-abs-pos comment)
5012 end (+ beg (js2-node-len comment)))
5013 (if (and (>= x beg)
5014 (<= x end))
5015 (throw 'done comment))))))
5016
5017 (defun js2-mode-find-parent-fn (node)
5018 "Find function enclosing NODE.
5019 Returns nil if NODE is not inside a function."
5020 (setq node (js2-node-parent node))
5021 (while (and node (not (js2-function-node-p node)))
5022 (setq node (js2-node-parent node)))
5023 (and (js2-function-node-p node) node))
5024
5025 (defun js2-mode-find-enclosing-fn (node)
5026 "Find function or root enclosing NODE."
5027 (if (js2-ast-root-p node)
5028 node
5029 (setq node (js2-node-parent node))
5030 (while (not (or (js2-ast-root-p node)
5031 (js2-function-node-p node)))
5032 (setq node (js2-node-parent node)))
5033 node))
5034
5035 (defun js2-mode-find-enclosing-node (beg end)
5036 "Find node fully enclosing BEG and END."
5037 (let ((node (js2-node-at-point beg))
5038 pos
5039 (continue t))
5040 (while continue
5041 (if (or (js2-ast-root-p node)
5042 (and
5043 (<= (setq pos (js2-node-abs-pos node)) beg)
5044 (>= (+ pos (js2-node-len node)) end)))
5045 (setq continue nil)
5046 (setq node (js2-node-parent node))))
5047 node))
5048
5049 (defun js2-node-parent-script-or-fn (node)
5050 "Find script or function immediately enclosing NODE.
5051 If NODE is the ast-root, returns nil."
5052 (if (js2-ast-root-p node)
5053 nil
5054 (setq node (js2-node-parent node))
5055 (while (and node (not (or (js2-function-node-p node)
5056 (js2-script-node-p node))))
5057 (setq node (js2-node-parent node)))
5058 node))
5059
5060 (defun js2-node-is-descendant (node ancestor)
5061 "Return t if NODE is a descendant of ANCESTOR."
5062 (while (and node
5063 (not (eq node ancestor)))
5064 (setq node (js2-node-parent node)))
5065 node)
5066
5067 ;;; visitor infrastructure
5068
5069 (defun js2-visit-none (_node _callback)
5070 "Visitor for AST node that have no node children."
5071 nil)
5072
5073 (defun js2-print-none (_node _indent)
5074 "Visitor for AST node with no printed representation.")
5075
5076 (defun js2-print-body (node indent)
5077 "Print a statement, or a block without braces."
5078 (if (js2-block-node-p node)
5079 (dolist (kid (js2-block-node-kids node))
5080 (js2-print-ast kid indent))
5081 (js2-print-ast node indent)))
5082
5083 (defun js2-print-list (args &optional delimiter)
5084 (cl-loop with len = (length args)
5085 for arg in args
5086 for count from 1
5087 do
5088 (when arg (js2-print-ast arg 0))
5089 (if (< count len)
5090 (insert (or delimiter ", ")))))
5091
5092 (defun js2-print-tree (ast)
5093 "Prints an AST to the current buffer.
5094 Makes `js2-ast-parent-nodes' available to the printer functions."
5095 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5096 (js2-print-ast ast)))
5097
5098 (defun js2-print-ast (node &optional indent)
5099 "Helper function for printing AST nodes.
5100 Requires `js2-ast-parent-nodes' to be non-nil.
5101 You should use `js2-print-tree' instead of this function."
5102 (let ((printer (get (aref node 0) 'js2-printer))
5103 (i (or indent 0)))
5104 ;; TODO: wedge comments in here somewhere
5105 (if printer
5106 (funcall printer node i))))
5107
5108 (defconst js2-side-effecting-tokens
5109 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5110 (dolist (tt (list js2-ASSIGN
5111 js2-ASSIGN_ADD
5112 js2-ASSIGN_BITAND
5113 js2-ASSIGN_BITOR
5114 js2-ASSIGN_BITXOR
5115 js2-ASSIGN_DIV
5116 js2-ASSIGN_LSH
5117 js2-ASSIGN_MOD
5118 js2-ASSIGN_MUL
5119 js2-ASSIGN_RSH
5120 js2-ASSIGN_SUB
5121 js2-ASSIGN_URSH
5122 js2-BLOCK
5123 js2-BREAK
5124 js2-CALL
5125 js2-CATCH
5126 js2-CATCH_SCOPE
5127 js2-CLASS
5128 js2-CONST
5129 js2-CONTINUE
5130 js2-DEBUGGER
5131 js2-DEC
5132 js2-DELPROP
5133 js2-DEL_REF
5134 js2-DO
5135 js2-ELSE
5136 js2-EMPTY
5137 js2-ENTERWITH
5138 js2-EXPORT
5139 js2-EXPR_RESULT
5140 js2-FINALLY
5141 js2-FOR
5142 js2-FUNCTION
5143 js2-GOTO
5144 js2-IF
5145 js2-IFEQ
5146 js2-IFNE
5147 js2-IMPORT
5148 js2-INC
5149 js2-JSR
5150 js2-LABEL
5151 js2-LEAVEWITH
5152 js2-LET
5153 js2-LETEXPR
5154 js2-LOCAL_BLOCK
5155 js2-LOOP
5156 js2-NEW
5157 js2-REF_CALL
5158 js2-RETHROW
5159 js2-RETURN
5160 js2-RETURN_RESULT
5161 js2-SEMI
5162 js2-SETELEM
5163 js2-SETELEM_OP
5164 js2-SETNAME
5165 js2-SETPROP
5166 js2-SETPROP_OP
5167 js2-SETVAR
5168 js2-SET_REF
5169 js2-SET_REF_OP
5170 js2-SWITCH
5171 js2-TARGET
5172 js2-THROW
5173 js2-TRY
5174 js2-VAR
5175 js2-WHILE
5176 js2-WITH
5177 js2-WITHEXPR
5178 js2-YIELD))
5179 (aset tokens tt t))
5180 (if js2-instanceof-has-side-effects
5181 (aset tokens js2-INSTANCEOF t))
5182 tokens))
5183
5184 (defun js2-node-has-side-effects (node)
5185 "Return t if NODE has side effects."
5186 (when node ; makes it easier to handle malformed expressions
5187 (let ((tt (js2-node-type node)))
5188 (cond
5189 ;; This doubtless needs some work, since EXPR_VOID is used
5190 ;; in several ways in Rhino and I may not have caught them all.
5191 ;; I'll wait for people to notice incorrect warnings.
5192 ((and (= tt js2-EXPR_VOID)
5193 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5194 (let ((expr (js2-expr-stmt-node-expr node)))
5195 (or (js2-node-has-side-effects expr)
5196 (when (js2-string-node-p expr)
5197 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5198 ((= tt js2-COMMA)
5199 (js2-node-has-side-effects (js2-infix-node-right node)))
5200 ((or (= tt js2-AND)
5201 (= tt js2-OR))
5202 (or (js2-node-has-side-effects (js2-infix-node-right node))
5203 (js2-node-has-side-effects (js2-infix-node-left node))))
5204 ((= tt js2-HOOK)
5205 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5206 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5207 ((js2-paren-node-p node)
5208 (js2-node-has-side-effects (js2-paren-node-expr node)))
5209 ((= tt js2-ERROR) ; avoid cascaded error messages
5210 nil)
5211 (t
5212 (aref js2-side-effecting-tokens tt))))))
5213
5214 (defconst js2-stmt-node-types
5215 (list js2-BLOCK
5216 js2-BREAK
5217 js2-CONTINUE
5218 js2-DEFAULT ; e4x "default xml namespace" statement
5219 js2-DO
5220 js2-EXPORT
5221 js2-EXPR_RESULT
5222 js2-EXPR_VOID
5223 js2-FOR
5224 js2-IF
5225 js2-IMPORT
5226 js2-RETURN
5227 js2-SWITCH
5228 js2-THROW
5229 js2-TRY
5230 js2-WHILE
5231 js2-WITH)
5232 "Node types that only appear in statement contexts.
5233 The list does not include nodes that always appear as the child
5234 of another specific statement type, such as switch-cases,
5235 catch and finally blocks, and else-clauses. The list also excludes
5236 nodes like yield, let and var, which may appear in either expression
5237 or statement context, and in the latter context always have a
5238 `js2-expr-stmt-node' parent. Finally, the list does not include
5239 functions or scripts, which are treated separately from statements
5240 by the JavaScript parser and runtime.")
5241
5242 (defun js2-stmt-node-p (node)
5243 "Heuristic for figuring out if NODE is a statement.
5244 Some node types can appear in either an expression context or a
5245 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5246 For these node types in a statement context, the parent will be a
5247 `js2-expr-stmt-node'.
5248 Functions aren't included in the check."
5249 (memq (js2-node-type node) js2-stmt-node-types))
5250
5251 (defun js2-mode-find-first-stmt (node)
5252 "Search upward starting from NODE looking for a statement.
5253 For purposes of this function, a `js2-function-node' counts."
5254 (while (not (or (js2-stmt-node-p node)
5255 (js2-function-node-p node)))
5256 (setq node (js2-node-parent node)))
5257 node)
5258
5259 (defun js2-node-parent-stmt (node)
5260 "Return the node's first ancestor that is a statement.
5261 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5262 appearing in a statement context will have a parent that is a
5263 `js2-expr-stmt-node' that will be returned by this function."
5264 (let ((parent (js2-node-parent node)))
5265 (if (or (null parent)
5266 (js2-stmt-node-p parent)
5267 (and (js2-function-node-p parent)
5268 (not (eq (js2-function-node-form parent)
5269 'FUNCTION_EXPRESSION))))
5270 parent
5271 (js2-node-parent-stmt parent))))
5272
5273 ;; In the Mozilla Rhino sources, Roshan James writes:
5274 ;; Does consistent-return analysis on the function body when strict mode is
5275 ;; enabled.
5276 ;;
5277 ;; function (x) { return (x+1) }
5278 ;;
5279 ;; is ok, but
5280 ;;
5281 ;; function (x) { if (x < 0) return (x+1); }
5282 ;;
5283 ;; is not because the function can potentially return a value when the
5284 ;; condition is satisfied and if not, the function does not explicitly
5285 ;; return a value.
5286 ;;
5287 ;; This extends to checking mismatches such as "return" and "return <value>"
5288 ;; used in the same function. Warnings are not emitted if inconsistent
5289 ;; returns exist in code that can be statically shown to be unreachable.
5290 ;; Ex.
5291 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5292 ;;
5293 ;; emits no warning. However if the loop had a break statement, then a
5294 ;; warning would be emitted.
5295 ;;
5296 ;; The consistency analysis looks at control structures such as loops, ifs,
5297 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5298 ;; warns the user about an inconsistent set of termination possibilities.
5299 ;;
5300 ;; These flags enumerate the possible ways a statement/function can
5301 ;; terminate. These flags are used by endCheck() and by the Parser to
5302 ;; detect inconsistent return usage.
5303 ;;
5304 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5305 ;; able to execute (example: throw, continue)
5306 ;;
5307 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5308 ;; next one. Statement such as return dont. A compound statement may have
5309 ;; some branch that drops off control to the next statement.
5310 ;;
5311 ;; END_RETURNS indicates that the statement can return with no value.
5312 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5313 ;;
5314 ;; A compound statement such as
5315 ;; if (condition) {
5316 ;; return value;
5317 ;; }
5318 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5319
5320 (defconst js2-END_UNREACHED 0)
5321 (defconst js2-END_DROPS_OFF 1)
5322 (defconst js2-END_RETURNS 2)
5323 (defconst js2-END_RETURNS_VALUE 4)
5324 (defconst js2-END_YIELDS 8)
5325
5326 (defun js2-has-consistent-return-usage (node)
5327 "Check that every return usage in a function body is consistent.
5328 Returns t if the function satisfies strict mode requirement."
5329 (let ((n (js2-end-check node)))
5330 ;; either it doesn't return a value in any branch...
5331 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5332 ;; or it returns a value (or is unreached) at every branch
5333 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5334 js2-END_RETURNS
5335 js2-END_YIELDS)))))
5336
5337 (defun js2-end-check-if (node)
5338 "Ensure that return usage in then/else blocks is consistent.
5339 If there is no else block, then the return statement can fall through.
5340 Returns logical OR of END_* flags"
5341 (let ((th (js2-if-node-then-part node))
5342 (el (js2-if-node-else-part node)))
5343 (if (null th)
5344 js2-END_UNREACHED
5345 (logior (js2-end-check th) (if el
5346 (js2-end-check el)
5347 js2-END_DROPS_OFF)))))
5348
5349 (defun js2-end-check-switch (node)
5350 "Consistency of return statements is checked between the case statements.
5351 If there is no default, then the switch can fall through. If there is a
5352 default, we check to see if all code paths in the default return or if
5353 there is a code path that can fall through.
5354 Returns logical OR of END_* flags."
5355 (let ((rv js2-END_UNREACHED)
5356 default-case)
5357 ;; examine the cases
5358 (catch 'break
5359 (dolist (c (js2-switch-node-cases node))
5360 (if (js2-case-node-expr c)
5361 (js2-set-flag rv (js2-end-check-block c))
5362 (setq default-case c)
5363 (throw 'break nil))))
5364 ;; we don't care how the cases drop into each other
5365 (js2-clear-flag rv js2-END_DROPS_OFF)
5366 ;; examine the default
5367 (js2-set-flag rv (if default-case
5368 (js2-end-check default-case)
5369 js2-END_DROPS_OFF))
5370 rv))
5371
5372 (defun js2-end-check-try (node)
5373 "If the block has a finally, return consistency is checked in the
5374 finally block. If all code paths in the finally return, then the
5375 returns in the try-catch blocks don't matter. If there is a code path
5376 that does not return or if there is no finally block, the returns
5377 of the try and catch blocks are checked for mismatch.
5378 Returns logical OR of END_* flags."
5379 (let ((finally (js2-try-node-finally-block node))
5380 rv)
5381 ;; check the finally if it exists
5382 (setq rv (if finally
5383 (js2-end-check (js2-finally-node-body finally))
5384 js2-END_DROPS_OFF))
5385 ;; If the finally block always returns, then none of the returns
5386 ;; in the try or catch blocks matter.
5387 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5388 (js2-clear-flag rv js2-END_DROPS_OFF)
5389 ;; examine the try block
5390 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5391 ;; check each catch block
5392 (dolist (cb (js2-try-node-catch-clauses node))
5393 (js2-set-flag rv (js2-end-check cb))))
5394 rv))
5395
5396 (defun js2-end-check-loop (node)
5397 "Return statement in the loop body must be consistent.
5398 The default assumption for any kind of a loop is that it will eventually
5399 terminate. The only exception is a loop with a constant true condition.
5400 Code that follows such a loop is examined only if one can determine
5401 statically that there is a break out of the loop.
5402
5403 for(... ; ... ; ...) {}
5404 for(... in ... ) {}
5405 while(...) { }
5406 do { } while(...)
5407
5408 Returns logical OR of END_* flags."
5409 (let ((rv (js2-end-check (js2-loop-node-body node)))
5410 (condition (cond
5411 ((js2-while-node-p node)
5412 (js2-while-node-condition node))
5413 ((js2-do-node-p node)
5414 (js2-do-node-condition node))
5415 ((js2-for-node-p node)
5416 (js2-for-node-condition node)))))
5417
5418 ;; check to see if the loop condition is always true
5419 (if (and condition
5420 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5421 (js2-clear-flag rv js2-END_DROPS_OFF))
5422
5423 ;; look for effect of breaks
5424 (js2-set-flag rv (js2-node-get-prop node
5425 'CONTROL_BLOCK_PROP
5426 js2-END_UNREACHED))
5427 rv))
5428
5429 (defun js2-end-check-block (node)
5430 "A general block of code is examined statement by statement.
5431 If any statement (even a compound one) returns in all branches, then
5432 subsequent statements are not examined.
5433 Returns logical OR of END_* flags."
5434 (let* ((rv js2-END_DROPS_OFF)
5435 (kids (js2-block-node-kids node))
5436 (n (car kids)))
5437 ;; Check each statement. If the statement can continue onto the next
5438 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5439 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5440 (js2-clear-flag rv js2-END_DROPS_OFF)
5441 (js2-set-flag rv (js2-end-check n))
5442 (setq kids (cdr kids)
5443 n (car kids)))
5444 rv))
5445
5446 (defun js2-end-check-label (node)
5447 "A labeled statement implies that there may be a break to the label.
5448 The function processes the labeled statement and then checks the
5449 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5450 particular label.
5451 Returns logical OR of END_* flags."
5452 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5453 (logior rv (js2-node-get-prop node
5454 'CONTROL_BLOCK_PROP
5455 js2-END_UNREACHED))))
5456
5457 (defun js2-end-check-break (node)
5458 "When a break is encountered annotate the statement being broken
5459 out of by setting its CONTROL_BLOCK_PROP property.
5460 Returns logical OR of END_* flags."
5461 (and (js2-break-node-target node)
5462 (js2-node-set-prop (js2-break-node-target node)
5463 'CONTROL_BLOCK_PROP
5464 js2-END_DROPS_OFF))
5465 js2-END_UNREACHED)
5466
5467 (defun js2-end-check (node)
5468 "Examine the body of a function, doing a basic reachability analysis.
5469 Returns a combination of flags END_* flags that indicate
5470 how the function execution can terminate. These constitute only the
5471 pessimistic set of termination conditions. It is possible that at
5472 runtime certain code paths will never be actually taken. Hence this
5473 analysis will flag errors in cases where there may not be errors.
5474 Returns logical OR of END_* flags"
5475 (let (kid)
5476 (cond
5477 ((js2-break-node-p node)
5478 (js2-end-check-break node))
5479 ((js2-expr-stmt-node-p node)
5480 (if (setq kid (js2-expr-stmt-node-expr node))
5481 (js2-end-check kid)
5482 js2-END_DROPS_OFF))
5483 ((or (js2-continue-node-p node)
5484 (js2-throw-node-p node))
5485 js2-END_UNREACHED)
5486 ((js2-return-node-p node)
5487 (if (setq kid (js2-return-node-retval node))
5488 js2-END_RETURNS_VALUE
5489 js2-END_RETURNS))
5490 ((js2-loop-node-p node)
5491 (js2-end-check-loop node))
5492 ((js2-switch-node-p node)
5493 (js2-end-check-switch node))
5494 ((js2-labeled-stmt-node-p node)
5495 (js2-end-check-label node))
5496 ((js2-if-node-p node)
5497 (js2-end-check-if node))
5498 ((js2-try-node-p node)
5499 (js2-end-check-try node))
5500 ((js2-block-node-p node)
5501 (if (null (js2-block-node-kids node))
5502 js2-END_DROPS_OFF
5503 (js2-end-check-block node)))
5504 ((js2-yield-node-p node)
5505 js2-END_YIELDS)
5506 (t
5507 js2-END_DROPS_OFF))))
5508
5509 (defun js2-always-defined-boolean-p (node)
5510 "Check if NODE always evaluates to true or false in boolean context.
5511 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5512 nor always false."
5513 (let ((tt (js2-node-type node))
5514 num)
5515 (cond
5516 ((or (= tt js2-FALSE) (= tt js2-NULL))
5517 'ALWAYS_FALSE)
5518 ((= tt js2-TRUE)
5519 'ALWAYS_TRUE)
5520 ((= tt js2-NUMBER)
5521 (setq num (js2-number-node-num-value node))
5522 (if (and (not (eq num 0.0e+NaN))
5523 (not (zerop num)))
5524 'ALWAYS_TRUE
5525 'ALWAYS_FALSE))
5526 (t
5527 nil))))
5528
5529 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5530 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5531
5532 (defvar js2-tokens nil
5533 "List of all defined token names.") ; initialized in `js2-token-names'
5534
5535 (defconst js2-token-names
5536 (let* ((names (make-vector js2-num-tokens -1))
5537 (case-fold-search nil) ; only match js2-UPPER_CASE
5538 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5539 (cl-loop for sym in syms
5540 for i from 0
5541 do
5542 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5543 (not (boundp sym)))
5544 (aset names (symbol-value sym) ; code, e.g. 152
5545 (downcase
5546 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5547 (push sym js2-tokens)))
5548 names)
5549 "Vector mapping int values to token string names, sans `js2-' prefix.")
5550
5551 (defun js2-tt-name (tok)
5552 "Return a string name for TOK, a token symbol or code.
5553 Signals an error if it's not a recognized token."
5554 (let ((code tok))
5555 (if (symbolp tok)
5556 (setq code (symbol-value tok)))
5557 (if (eq code -1)
5558 "ERROR"
5559 (if (and (numberp code)
5560 (not (cl-minusp code))
5561 (< code js2-num-tokens))
5562 (aref js2-token-names code)
5563 (error "Invalid token: %s" code)))))
5564
5565 (defsubst js2-tt-sym (tok)
5566 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5567 (intern (js2-tt-name tok)))
5568
5569 (defconst js2-token-codes
5570 (let ((table (make-hash-table :test 'eq :size 256)))
5571 (cl-loop for name across js2-token-names
5572 for sym = (intern (concat "js2-" (upcase name)))
5573 do
5574 (puthash sym (symbol-value sym) table))
5575 ;; clean up a few that are "wrong" in Rhino's token codes
5576 (puthash 'js2-DELETE js2-DELPROP table)
5577 table)
5578 "Hashtable mapping token type symbols to their bytecodes.")
5579
5580 (defsubst js2-tt-code (sym)
5581 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5582 (or (gethash sym js2-token-codes)
5583 (error "Invalid token symbol: %s " sym))) ; signal code bug
5584
5585 (defun js2-report-scan-error (msg &optional no-throw beg len)
5586 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5587 (js2-report-error msg nil
5588 (or beg (js2-current-token-beg))
5589 (or len (js2-current-token-len)))
5590 (unless no-throw
5591 (throw 'return js2-ERROR)))
5592
5593 (defun js2-set-string-from-buffer (token)
5594 "Set `string' and `end' slots for TOKEN, return the string."
5595 (setf (js2-token-end token) js2-ts-cursor
5596 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5597
5598 ;; TODO: could potentially avoid a lot of consing by allocating a
5599 ;; char buffer the way Rhino does.
5600 (defsubst js2-add-to-string (c)
5601 (push c js2-ts-string-buffer))
5602
5603 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5604 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5605 ;; any other character: when it's not part of the current token, we
5606 ;; unget it, allowing it to be read again by the following call.
5607 (defsubst js2-unget-char ()
5608 (cl-decf js2-ts-cursor))
5609
5610 ;; Rhino distinguishes \r and \n line endings. We don't need to
5611 ;; because we only scan from Emacs buffers, which always use \n.
5612 (defun js2-get-char ()
5613 "Read and return the next character from the input buffer.
5614 Increments `js2-ts-lineno' if the return value is a newline char.
5615 Updates `js2-ts-cursor' to the point after the returned char.
5616 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5617 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5618 (let (c)
5619 ;; check for end of buffer
5620 (if (>= js2-ts-cursor (point-max))
5621 (setq js2-ts-hit-eof t
5622 js2-ts-cursor (1+ js2-ts-cursor)
5623 c js2-EOF_CHAR) ; return value
5624 ;; otherwise read next char
5625 (setq c (char-before (cl-incf js2-ts-cursor)))
5626 ;; if we read a newline, update counters
5627 (if (= c ?\n)
5628 (setq js2-ts-line-start js2-ts-cursor
5629 js2-ts-lineno (1+ js2-ts-lineno)))
5630 ;; TODO: skip over format characters
5631 c)))
5632
5633 (defun js2-read-unicode-escape ()
5634 "Read a \\uNNNN sequence from the input.
5635 Assumes the ?\ and ?u have already been read.
5636 Returns the unicode character, or nil if it wasn't a valid character.
5637 Doesn't change the values of any scanner variables."
5638 ;; I really wish I knew a better way to do this, but I can't
5639 ;; find the Emacs function that takes a 16-bit int and converts
5640 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5641 ;; Have to first check that it's 4 hex characters or it may stop
5642 ;; the read early.
5643 (ignore-errors
5644 (let ((s (buffer-substring-no-properties js2-ts-cursor
5645 (+ 4 js2-ts-cursor))))
5646 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5647 (read (concat "?\\u" s))))))
5648
5649 (defun js2-match-char (test)
5650 "Consume and return next character if it matches TEST, a character.
5651 Returns nil and consumes nothing if TEST is not the next character."
5652 (let ((c (js2-get-char)))
5653 (if (eq c test)
5654 t
5655 (js2-unget-char)
5656 nil)))
5657
5658 (defun js2-peek-char ()
5659 (prog1
5660 (js2-get-char)
5661 (js2-unget-char)))
5662
5663 (defun js2-identifier-start-p (c)
5664 "Is C a valid start to an ES5 Identifier?
5665 See http://es5.github.io/#x7.6"
5666 (or
5667 (memq c '(?$ ?_))
5668 (memq (get-char-code-property c 'general-category)
5669 ;; Letters
5670 '(Lu Ll Lt Lm Lo Nl))))
5671
5672 (defun js2-identifier-part-p (c)
5673 "Is C a valid part of an ES5 Identifier?
5674 See http://es5.github.io/#x7.6"
5675 (or
5676 (memq c '(?$ ?_ ?\u200c ?\u200d))
5677 (memq (get-char-code-property c 'general-category)
5678 '(;; Letters
5679 Lu Ll Lt Lm Lo Nl
5680 ;; Combining Marks
5681 Mn Mc
5682 ;; Digits
5683 Nd
5684 ;; Connector Punctuation
5685 Pc))))
5686
5687 (defun js2-alpha-p (c)
5688 (cond ((and (<= ?A c) (<= c ?Z)) t)
5689 ((and (<= ?a c) (<= c ?z)) t)
5690 (t nil)))
5691
5692 (defsubst js2-digit-p (c)
5693 (and (<= ?0 c) (<= c ?9)))
5694
5695 (defun js2-js-space-p (c)
5696 (if (<= c 127)
5697 (memq c '(#x20 #x9 #xB #xC #xD))
5698 (or
5699 (eq c #xA0)
5700 ;; TODO: change this nil to check for Unicode space character
5701 nil)))
5702
5703 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5704
5705 (defun js2-skip-line ()
5706 "Skip to end of line."
5707 (while (not (memq (js2-get-char) js2-eol-chars)))
5708 (js2-unget-char)
5709 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5710
5711 (defun js2-init-scanner (&optional buf line)
5712 "Create token stream for BUF starting on LINE.
5713 BUF defaults to `current-buffer' and LINE defaults to 1.
5714
5715 A buffer can only have one scanner active at a time, which yields
5716 dramatically simpler code than using a defstruct. If you need to
5717 have simultaneous scanners in a buffer, copy the regions to scan
5718 into temp buffers."
5719 (with-current-buffer (or buf (current-buffer))
5720 (setq js2-ts-dirty-line nil
5721 js2-ts-hit-eof nil
5722 js2-ts-line-start 0
5723 js2-ts-lineno (or line 1)
5724 js2-ts-line-end-char -1
5725 js2-ts-cursor (point-min)
5726 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5727 js2-ti-tokens-cursor 0
5728 js2-ti-lookahead 0
5729 js2-ts-is-xml-attribute nil
5730 js2-ts-xml-is-tag-content nil
5731 js2-ts-xml-open-tags-count 0
5732 js2-ts-string-buffer nil)))
5733
5734 ;; This function uses the cached op, string and number fields in
5735 ;; TokenStream; if getToken has been called since the passed token
5736 ;; was scanned, the op or string printed may be incorrect.
5737 (defun js2-token-to-string (token)
5738 ;; Not sure where this function is used in Rhino. Not tested.
5739 (if (not js2-debug-print-trees)
5740 ""
5741 (let ((name (js2-tt-name token)))
5742 (cond
5743 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5744 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5745 (concat name " `" (js2-current-token-string) "'"))
5746 ((eq token js2-NUMBER)
5747 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5748 (t
5749 name)))))
5750
5751 (defconst js2-keywords
5752 '(break
5753 case catch class const continue
5754 debugger default delete do
5755 else extends export
5756 false finally for function
5757 if in instanceof import
5758 let
5759 new null
5760 return
5761 super switch
5762 this throw true try typeof
5763 var void
5764 while with
5765 yield))
5766
5767 ;; Token names aren't exactly the same as the keywords, unfortunately.
5768 ;; E.g. delete is js2-DELPROP.
5769 (defconst js2-kwd-tokens
5770 (let ((table (make-vector js2-num-tokens nil))
5771 (tokens
5772 (list js2-BREAK
5773 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5774 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5775 js2-ELSE js2-EXPORT
5776 js2-ELSE js2-EXTENDS js2-EXPORT
5777 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5778 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5779 js2-LET
5780 js2-NEW js2-NULL
5781 js2-RETURN
5782 js2-SUPER js2-SWITCH
5783 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5784 js2-VAR
5785 js2-WHILE js2-WITH
5786 js2-YIELD)))
5787 (dolist (i tokens)
5788 (aset table i 'font-lock-keyword-face))
5789 (aset table js2-STRING 'font-lock-string-face)
5790 (aset table js2-REGEXP 'font-lock-string-face)
5791 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5792 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5793 (aset table js2-COMMENT 'font-lock-comment-face)
5794 (aset table js2-THIS 'font-lock-builtin-face)
5795 (aset table js2-SUPER 'font-lock-builtin-face)
5796 (aset table js2-VOID 'font-lock-constant-face)
5797 (aset table js2-NULL 'font-lock-constant-face)
5798 (aset table js2-TRUE 'font-lock-constant-face)
5799 (aset table js2-FALSE 'font-lock-constant-face)
5800 (aset table js2-NOT 'font-lock-negation-char-face)
5801 table)
5802 "Vector whose values are non-nil for tokens that are keywords.
5803 The values are default faces to use for highlighting the keywords.")
5804
5805 ;; FIXME: Support strict mode-only future reserved words, after we know
5806 ;; which parts scopes are in strict mode, and which are not.
5807 (defconst js2-reserved-words '(class enum export extends import static super)
5808 "Future reserved keywords in ECMAScript 5.1.")
5809
5810 (defconst js2-keyword-names
5811 (let ((table (make-hash-table :test 'equal)))
5812 (cl-loop for k in js2-keywords
5813 do (puthash
5814 (symbol-name k) ; instanceof
5815 (intern (concat "js2-"
5816 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5817 table))
5818 table)
5819 "JavaScript keywords by name, mapped to their symbols.")
5820
5821 (defconst js2-reserved-word-names
5822 (let ((table (make-hash-table :test 'equal)))
5823 (cl-loop for k in js2-reserved-words
5824 do
5825 (puthash (symbol-name k) 'js2-RESERVED table))
5826 table)
5827 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5828
5829 (defun js2-collect-string (buf)
5830 "Convert BUF, a list of chars, to a string.
5831 Reverses BUF before converting."
5832 (if buf
5833 (apply #'string (nreverse buf))
5834 ""))
5835
5836 (defun js2-string-to-keyword (s)
5837 "Return token for S, a string, if S is a keyword or reserved word.
5838 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5839 (or (gethash s js2-keyword-names)
5840 (gethash s js2-reserved-word-names)))
5841
5842 (defsubst js2-ts-set-char-token-bounds (token)
5843 "Used when next token is one character."
5844 (setf (js2-token-beg token) (1- js2-ts-cursor)
5845 (js2-token-end token) js2-ts-cursor))
5846
5847 (defsubst js2-ts-return (token type)
5848 "Update the `end' and `type' slots of TOKEN,
5849 then throw `return' with value TYPE."
5850 (setf (js2-token-end token) js2-ts-cursor
5851 (js2-token-type token) type)
5852 (throw 'return type))
5853
5854 (defun js2-x-digit-to-int (c accumulator)
5855 "Build up a hex number.
5856 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5857 corresponding number. Otherwise return -1."
5858 (catch 'return
5859 (catch 'check
5860 ;; Use 0..9 < A..Z < a..z
5861 (cond
5862 ((<= c ?9)
5863 (cl-decf c ?0)
5864 (if (<= 0 c)
5865 (throw 'check nil)))
5866 ((<= c ?F)
5867 (when (<= ?A c)
5868 (cl-decf c (- ?A 10))
5869 (throw 'check nil)))
5870 ((<= c ?f)
5871 (when (<= ?a c)
5872 (cl-decf c (- ?a 10))
5873 (throw 'check nil))))
5874 (throw 'return -1))
5875 (logior c (lsh accumulator 4))))
5876
5877 (defun js2-get-token (&optional modifier)
5878 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5879 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5880 next saved token.
5881
5882 This function will not return a newline (js2-EOL) - instead, it
5883 gobbles newlines until it finds a non-newline token. Call
5884 `js2-peek-token-or-eol' when you care about newlines.
5885
5886 This function will also not return a js2-COMMENT. Instead, it
5887 records comments found in `js2-scanned-comments'. If the token
5888 returned by this function immediately follows a jsdoc comment,
5889 the token is flagged as such."
5890 (if (zerop js2-ti-lookahead)
5891 (js2-get-token-internal modifier)
5892 (cl-decf js2-ti-lookahead)
5893 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5894 (let ((tt (js2-current-token-type)))
5895 (cl-assert (not (= tt js2-EOL)))
5896 tt)))
5897
5898 (defun js2-unget-token ()
5899 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5900 (cl-incf js2-ti-lookahead)
5901 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5902
5903 (defun js2-get-token-internal (modifier)
5904 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5905 (tt (js2-token-type token))
5906 saw-eol
5907 face)
5908 ;; process comments
5909 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5910 (if (= tt js2-EOL)
5911 (setq saw-eol t)
5912 (setq saw-eol nil)
5913 (when js2-record-comments
5914 (js2-record-comment token)))
5915 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5916 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5917 tt (js2-token-type token)))
5918
5919 (when saw-eol
5920 (setf (js2-token-follows-eol-p token) t))
5921
5922 ;; perform lexical fontification as soon as token is scanned
5923 (when js2-parse-ide-mode
5924 (cond
5925 ((cl-minusp tt)
5926 (js2-record-face 'js2-error token))
5927 ((setq face (aref js2-kwd-tokens tt))
5928 (js2-record-face face token))
5929 ((and (= tt js2-NAME)
5930 (equal (js2-token-string token) "undefined"))
5931 (js2-record-face 'font-lock-constant-face token))))
5932 tt))
5933
5934 (defsubst js2-string-to-number (str base)
5935 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5936 (condition-case nil
5937 (string-to-number str base)
5938 (overflow-error -1)))
5939
5940 (defun js2-get-token-internal-1 (modifier)
5941 "Return next JavaScript token type, an int such as js2-RETURN.
5942 During operation, creates an instance of `js2-token' struct, sets
5943 its relevant fields and puts it into `js2-ti-tokens'."
5944 (let (identifier-start
5945 is-unicode-escape-start c
5946 contains-escape escape-val str result base
5947 look-for-slash continue tt
5948 (token (js2-new-token 0)))
5949 (setq
5950 tt
5951 (catch 'return
5952 (when (eq modifier 'TEMPLATE_TAIL)
5953 (setf (js2-token-beg token) (1- js2-ts-cursor))
5954 (throw 'return (js2-get-string-or-template-token ?` token)))
5955 (while t
5956 ;; Eat whitespace, possibly sensitive to newlines.
5957 (setq continue t)
5958 (while continue
5959 (setq c (js2-get-char))
5960 (cond
5961 ((eq c js2-EOF_CHAR)
5962 (js2-unget-char)
5963 (js2-ts-set-char-token-bounds token)
5964 (throw 'return js2-EOF))
5965 ((eq c ?\n)
5966 (js2-ts-set-char-token-bounds token)
5967 (setq js2-ts-dirty-line nil)
5968 (throw 'return js2-EOL))
5969 ((not (js2-js-space-p c))
5970 (if (/= c ?-) ; in case end of HTML comment
5971 (setq js2-ts-dirty-line t))
5972 (setq continue nil))))
5973 ;; Assume the token will be 1 char - fixed up below.
5974 (js2-ts-set-char-token-bounds token)
5975 (when (eq c ?@)
5976 (throw 'return js2-XMLATTR))
5977 ;; identifier/keyword/instanceof?
5978 ;; watch out for starting with a <backslash>
5979 (cond
5980 ((eq c ?\\)
5981 (setq c (js2-get-char))
5982 (if (eq c ?u)
5983 (setq identifier-start t
5984 is-unicode-escape-start t
5985 js2-ts-string-buffer nil)
5986 (setq identifier-start nil)
5987 (js2-unget-char)
5988 (setq c ?\\)))
5989 (t
5990 (when (setq identifier-start (js2-identifier-start-p c))
5991 (setq js2-ts-string-buffer nil)
5992 (js2-add-to-string c))))
5993 (when identifier-start
5994 (setq contains-escape is-unicode-escape-start)
5995 (catch 'break
5996 (while t
5997 (if is-unicode-escape-start
5998 ;; strictly speaking we should probably push-back
5999 ;; all the bad characters if the <backslash>uXXXX
6000 ;; sequence is malformed. But since there isn't a
6001 ;; correct context(is there?) for a bad Unicode
6002 ;; escape sequence in an identifier, we can report
6003 ;; an error here.
6004 (progn
6005 (setq escape-val 0)
6006 (dotimes (_ 4)
6007 (setq c (js2-get-char)
6008 escape-val (js2-x-digit-to-int c escape-val))
6009 ;; Next check takes care of c < 0 and bad escape
6010 (if (cl-minusp escape-val)
6011 (throw 'break nil)))
6012 (if (cl-minusp escape-val)
6013 (js2-report-scan-error "msg.invalid.escape" t))
6014 (js2-add-to-string escape-val)
6015 (setq is-unicode-escape-start nil))
6016 (setq c (js2-get-char))
6017 (cond
6018 ((eq c ?\\)
6019 (setq c (js2-get-char))
6020 (if (eq c ?u)
6021 (setq is-unicode-escape-start t
6022 contains-escape t)
6023 (js2-report-scan-error "msg.illegal.character" t)))
6024 (t
6025 (if (or (eq c js2-EOF_CHAR)
6026 (not (js2-identifier-part-p c)))
6027 (throw 'break nil))
6028 (js2-add-to-string c))))))
6029 (js2-unget-char)
6030 (setf str (js2-collect-string js2-ts-string-buffer)
6031 (js2-token-end token) js2-ts-cursor)
6032 ;; FIXME: Invalid in ES5 and ES6, see
6033 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
6034 ;; Probably should just drop this conditional.
6035 (unless contains-escape
6036 ;; OPT we shouldn't have to make a string (object!) to
6037 ;; check if it's a keyword.
6038 ;; Return the corresponding token if it's a keyword
6039 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
6040 (setq result (js2-string-to-keyword str)))
6041 (if (and (< js2-language-version 170)
6042 (memq result '(js2-LET js2-YIELD)))
6043 ;; LET and YIELD are tokens only in 1.7 and later
6044 (setq result 'js2-NAME))
6045 (when (eq result 'js2-RESERVED)
6046 (setf (js2-token-string token) str))
6047 (throw 'return (js2-tt-code result))))
6048 ;; If we want to intern these as Rhino does, just use (intern str)
6049 (setf (js2-token-string token) str)
6050 (throw 'return js2-NAME)) ; end identifier/kwd check
6051 ;; is it a number?
6052 (when (or (js2-digit-p c)
6053 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6054 (setq js2-ts-string-buffer nil
6055 base 10)
6056 (when (eq c ?0)
6057 (setq c (js2-get-char))
6058 (cond
6059 ((or (eq c ?x) (eq c ?X))
6060 (setq base 16)
6061 (setq c (js2-get-char)))
6062 ((and (or (eq c ?b) (eq c ?B))
6063 (>= js2-language-version 200))
6064 (setq base 2)
6065 (setq c (js2-get-char)))
6066 ((and (or (eq c ?o) (eq c ?O))
6067 (>= js2-language-version 200))
6068 (setq base 8)
6069 (setq c (js2-get-char)))
6070 ((js2-digit-p c)
6071 (setq base 'maybe-8))
6072 (t
6073 (js2-add-to-string ?0))))
6074 (cond
6075 ((eq base 16)
6076 (if (> 0 (js2-x-digit-to-int c 0))
6077 (js2-report-scan-error "msg.missing.hex.digits")
6078 (while (<= 0 (js2-x-digit-to-int c 0))
6079 (js2-add-to-string c)
6080 (setq c (js2-get-char)))))
6081 ((eq base 2)
6082 (if (not (memq c '(?0 ?1)))
6083 (js2-report-scan-error "msg.missing.binary.digits")
6084 (while (memq c '(?0 ?1))
6085 (js2-add-to-string c)
6086 (setq c (js2-get-char)))))
6087 ((eq base 8)
6088 (if (or (> ?0 c) (< ?7 c))
6089 (js2-report-scan-error "msg.missing.octal.digits")
6090 (while (and (<= ?0 c) (>= ?7 c))
6091 (js2-add-to-string c)
6092 (setq c (js2-get-char)))))
6093 (t
6094 (while (and (<= ?0 c) (<= c ?9))
6095 ;; We permit 08 and 09 as decimal numbers, which
6096 ;; makes our behavior a superset of the ECMA
6097 ;; numeric grammar. We might not always be so
6098 ;; permissive, so we warn about it.
6099 (when (and (eq base 'maybe-8) (>= c ?8))
6100 (js2-report-warning "msg.bad.octal.literal"
6101 (if (eq c ?8) "8" "9"))
6102 (setq base 10))
6103 (js2-add-to-string c)
6104 (setq c (js2-get-char)))
6105 (when (eq base 'maybe-8)
6106 (setq base 8))))
6107 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6108 (when (eq c ?.)
6109 (cl-loop do
6110 (js2-add-to-string c)
6111 (setq c (js2-get-char))
6112 while (js2-digit-p c)))
6113 (when (memq c '(?e ?E))
6114 (js2-add-to-string c)
6115 (setq c (js2-get-char))
6116 (when (memq c '(?+ ?-))
6117 (js2-add-to-string c)
6118 (setq c (js2-get-char)))
6119 (unless (js2-digit-p c)
6120 (js2-report-scan-error "msg.missing.exponent" t))
6121 (cl-loop do
6122 (js2-add-to-string c)
6123 (setq c (js2-get-char))
6124 while (js2-digit-p c))))
6125 (js2-unget-char)
6126 (let ((str (js2-set-string-from-buffer token)))
6127 (setf (js2-token-number token) (js2-string-to-number str base)
6128 (js2-token-number-base token) base))
6129 (throw 'return js2-NUMBER))
6130 ;; is it a string?
6131 (when (or (memq c '(?\" ?\'))
6132 (and (>= js2-language-version 200)
6133 (= c ?`)))
6134 (throw 'return
6135 (js2-get-string-or-template-token c token)))
6136 (js2-ts-return token
6137 (cl-case c
6138 (?\;
6139 (throw 'return js2-SEMI))
6140 (?\[
6141 (throw 'return js2-LB))
6142 (?\]
6143 (throw 'return js2-RB))
6144 (?{
6145 (throw 'return js2-LC))
6146 (?}
6147 (throw 'return js2-RC))
6148 (?\(
6149 (throw 'return js2-LP))
6150 (?\)
6151 (throw 'return js2-RP))
6152 (?,
6153 (throw 'return js2-COMMA))
6154 (??
6155 (throw 'return js2-HOOK))
6156 (?:
6157 (if (js2-match-char ?:)
6158 js2-COLONCOLON
6159 (throw 'return js2-COLON)))
6160 (?.
6161 (if (js2-match-char ?.)
6162 (if (js2-match-char ?.)
6163 js2-TRIPLEDOT js2-DOTDOT)
6164 (if (js2-match-char ?\()
6165 js2-DOTQUERY
6166 (throw 'return js2-DOT))))
6167 (?|
6168 (if (js2-match-char ?|)
6169 (throw 'return js2-OR)
6170 (if (js2-match-char ?=)
6171 js2-ASSIGN_BITOR
6172 (throw 'return js2-BITOR))))
6173 (?^
6174 (if (js2-match-char ?=)
6175 js2-ASSIGN_BITOR
6176 (throw 'return js2-BITXOR)))
6177 (?&
6178 (if (js2-match-char ?&)
6179 (throw 'return js2-AND)
6180 (if (js2-match-char ?=)
6181 js2-ASSIGN_BITAND
6182 (throw 'return js2-BITAND))))
6183 (?=
6184 (if (js2-match-char ?=)
6185 (if (js2-match-char ?=)
6186 js2-SHEQ
6187 (throw 'return js2-EQ))
6188 (if (js2-match-char ?>)
6189 (js2-ts-return token js2-ARROW)
6190 (throw 'return js2-ASSIGN))))
6191 (?!
6192 (if (js2-match-char ?=)
6193 (if (js2-match-char ?=)
6194 js2-SHNE
6195 js2-NE)
6196 (throw 'return js2-NOT)))
6197 (?<
6198 ;; NB:treat HTML begin-comment as comment-till-eol
6199 (when (js2-match-char ?!)
6200 (when (js2-match-char ?-)
6201 (when (js2-match-char ?-)
6202 (js2-skip-line)
6203 (setf (js2-token-comment-type (js2-current-token)) 'html)
6204 (throw 'return js2-COMMENT)))
6205 (js2-unget-char))
6206 (if (js2-match-char ?<)
6207 (if (js2-match-char ?=)
6208 js2-ASSIGN_LSH
6209 js2-LSH)
6210 (if (js2-match-char ?=)
6211 js2-LE
6212 (throw 'return js2-LT))))
6213 (?>
6214 (if (js2-match-char ?>)
6215 (if (js2-match-char ?>)
6216 (if (js2-match-char ?=)
6217 js2-ASSIGN_URSH
6218 js2-URSH)
6219 (if (js2-match-char ?=)
6220 js2-ASSIGN_RSH
6221 js2-RSH))
6222 (if (js2-match-char ?=)
6223 js2-GE
6224 (throw 'return js2-GT))))
6225 (?*
6226 (if (js2-match-char ?=)
6227 js2-ASSIGN_MUL
6228 (throw 'return js2-MUL)))
6229 (?/
6230 ;; is it a // comment?
6231 (when (js2-match-char ?/)
6232 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6233 (js2-skip-line)
6234 (setf (js2-token-comment-type token) 'line)
6235 ;; include newline so highlighting goes to end of
6236 ;; window, if there actually is a newline; if we
6237 ;; hit eof, then implicitly there isn't
6238 (unless js2-ts-hit-eof
6239 (cl-incf (js2-token-end token)))
6240 (throw 'return js2-COMMENT))
6241 ;; is it a /* comment?
6242 (when (js2-match-char ?*)
6243 (setf look-for-slash nil
6244 (js2-token-beg token) (- js2-ts-cursor 2)
6245 (js2-token-comment-type token)
6246 (if (js2-match-char ?*)
6247 (progn
6248 (setq look-for-slash t)
6249 'jsdoc)
6250 'block))
6251 (while t
6252 (setq c (js2-get-char))
6253 (cond
6254 ((eq c js2-EOF_CHAR)
6255 (setf (js2-token-end token) (1- js2-ts-cursor))
6256 (js2-report-error "msg.unterminated.comment")
6257 (throw 'return js2-COMMENT))
6258 ((eq c ?*)
6259 (setq look-for-slash t))
6260 ((eq c ?/)
6261 (if look-for-slash
6262 (js2-ts-return token js2-COMMENT)))
6263 (t
6264 (setf look-for-slash nil
6265 (js2-token-end token) js2-ts-cursor)))))
6266 (if (js2-match-char ?=)
6267 js2-ASSIGN_DIV
6268 (throw 'return js2-DIV)))
6269 (?#
6270 (when js2-skip-preprocessor-directives
6271 (js2-skip-line)
6272 (setf (js2-token-comment-type token) 'preprocessor
6273 (js2-token-end token) js2-ts-cursor)
6274 (throw 'return js2-COMMENT))
6275 (throw 'return js2-ERROR))
6276 (?%
6277 (if (js2-match-char ?=)
6278 js2-ASSIGN_MOD
6279 (throw 'return js2-MOD)))
6280 (?~
6281 (throw 'return js2-BITNOT))
6282 (?+
6283 (if (js2-match-char ?=)
6284 js2-ASSIGN_ADD
6285 (if (js2-match-char ?+)
6286 js2-INC
6287 (throw 'return js2-ADD))))
6288 (?-
6289 (cond
6290 ((js2-match-char ?=)
6291 (setq c js2-ASSIGN_SUB))
6292 ((js2-match-char ?-)
6293 (unless js2-ts-dirty-line
6294 ;; treat HTML end-comment after possible whitespace
6295 ;; after line start as comment-until-eol
6296 (when (js2-match-char ?>)
6297 (js2-skip-line)
6298 (setf (js2-token-comment-type (js2-current-token)) 'html)
6299 (throw 'return js2-COMMENT)))
6300 (setq c js2-DEC))
6301 (t
6302 (setq c js2-SUB)))
6303 (setq js2-ts-dirty-line t)
6304 c)
6305 (otherwise
6306 (js2-report-scan-error "msg.illegal.character")))))))
6307 (setf (js2-token-type token) tt)
6308 token))
6309
6310 (defun js2-get-string-or-template-token (quote-char token)
6311 ;; We attempt to accumulate a string the fast way, by
6312 ;; building it directly out of the reader. But if there
6313 ;; are any escaped characters in the string, we revert to
6314 ;; building it out of a string buffer.
6315 (let ((c (js2-get-char))
6316 js2-ts-string-buffer
6317 nc c1 val escape-val)
6318 (catch 'break
6319 (while (/= c quote-char)
6320 (catch 'continue
6321 (when (eq c js2-EOF_CHAR)
6322 (js2-unget-char)
6323 (js2-report-error "msg.unterminated.string.lit")
6324 (throw 'break nil))
6325 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6326 (js2-unget-char)
6327 (js2-report-error "msg.unterminated.string.lit")
6328 (throw 'break nil))
6329 (when (eq c ?\\)
6330 ;; We've hit an escaped character
6331 (setq c (js2-get-char))
6332 (cl-case c
6333 (?b (setq c ?\b))
6334 (?f (setq c ?\f))
6335 (?n (setq c ?\n))
6336 (?r (setq c ?\r))
6337 (?t (setq c ?\t))
6338 (?v (setq c ?\v))
6339 (?u
6340 (setq c1 (js2-read-unicode-escape))
6341 (if js2-parse-ide-mode
6342 (if c1
6343 (progn
6344 ;; just copy the string in IDE-mode
6345 (js2-add-to-string ?\\)
6346 (js2-add-to-string ?u)
6347 (dotimes (_ 3)
6348 (js2-add-to-string (js2-get-char)))
6349 (setq c (js2-get-char))) ; added at end of loop
6350 ;; flag it as an invalid escape
6351 (js2-report-warning "msg.invalid.escape"
6352 nil (- js2-ts-cursor 2) 6))
6353 ;; Get 4 hex digits; if the u escape is not
6354 ;; followed by 4 hex digits, use 'u' + the
6355 ;; literal character sequence that follows.
6356 (js2-add-to-string ?u)
6357 (setq escape-val 0)
6358 (dotimes (_ 4)
6359 (setq c (js2-get-char)
6360 escape-val (js2-x-digit-to-int c escape-val))
6361 (if (cl-minusp escape-val)
6362 (throw 'continue nil))
6363 (js2-add-to-string c))
6364 ;; prepare for replace of stored 'u' sequence by escape value
6365 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6366 c escape-val)))
6367 (?x
6368 ;; Get 2 hex digits, defaulting to 'x'+literal
6369 ;; sequence, as above.
6370 (setq c (js2-get-char)
6371 escape-val (js2-x-digit-to-int c 0))
6372 (if (cl-minusp escape-val)
6373 (progn
6374 (js2-add-to-string ?x)
6375 (throw 'continue nil))
6376 (setq c1 c
6377 c (js2-get-char)
6378 escape-val (js2-x-digit-to-int c escape-val))
6379 (if (cl-minusp escape-val)
6380 (progn
6381 (js2-add-to-string ?x)
6382 (js2-add-to-string c1)
6383 (throw 'continue nil))
6384 ;; got 2 hex digits
6385 (setq c escape-val))))
6386 (?\n
6387 ;; Remove line terminator after escape to follow
6388 ;; SpiderMonkey and C/C++
6389 (setq c (js2-get-char))
6390 (throw 'continue nil))
6391 (t
6392 (when (and (<= ?0 c) (< c ?8))
6393 (setq val (- c ?0)
6394 c (js2-get-char))
6395 (when (and (<= ?0 c) (< c ?8))
6396 (setq val (- (+ (* 8 val) c) ?0)
6397 c (js2-get-char))
6398 (when (and (<= ?0 c)
6399 (< c ?8)
6400 (< val #o37))
6401 ;; c is 3rd char of octal sequence only
6402 ;; if the resulting val <= 0377
6403 (setq val (- (+ (* 8 val) c) ?0)
6404 c (js2-get-char))))
6405 (js2-unget-char)
6406 (setq c val)))))
6407 (when (and (eq quote-char ?`) (eq c ?$))
6408 (when (eq (setq nc (js2-get-char)) ?\{)
6409 (throw 'break nil))
6410 (js2-unget-char))
6411 (js2-add-to-string c)
6412 (setq c (js2-get-char)))))
6413 (js2-set-string-from-buffer token)
6414 (if (not (eq quote-char ?`))
6415 js2-STRING
6416 (if (and (eq c ?$) (eq nc ?\{))
6417 js2-TEMPLATE_HEAD
6418 js2-NO_SUBS_TEMPLATE))))
6419
6420 (defun js2-read-regexp (start-tt)
6421 "Called by parser when it gets / or /= in literal context."
6422 (let (c err
6423 in-class ; inside a '[' .. ']' character-class
6424 flags
6425 (continue t)
6426 (token (js2-new-token 0)))
6427 (setq js2-ts-string-buffer nil)
6428 (if (eq start-tt js2-ASSIGN_DIV)
6429 ;; mis-scanned /=
6430 (js2-add-to-string ?=)
6431 (if (not (eq start-tt js2-DIV))
6432 (error "failed assertion")))
6433 (while (and (not err)
6434 (or (/= (setq c (js2-get-char)) ?/)
6435 in-class))
6436 (cond
6437 ((or (= c ?\n)
6438 (= c js2-EOF_CHAR))
6439 (setf (js2-token-end token) (1- js2-ts-cursor)
6440 err t
6441 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6442 (js2-report-error "msg.unterminated.re.lit"))
6443 (t (cond
6444 ((= c ?\\)
6445 (js2-add-to-string c)
6446 (setq c (js2-get-char)))
6447 ((= c ?\[)
6448 (setq in-class t))
6449 ((= c ?\])
6450 (setq in-class nil)))
6451 (js2-add-to-string c))))
6452 (unless err
6453 (while continue
6454 (cond
6455 ((js2-match-char ?g)
6456 (push ?g flags))
6457 ((js2-match-char ?i)
6458 (push ?i flags))
6459 ((js2-match-char ?m)
6460 (push ?m flags))
6461 ((and (js2-match-char ?u)
6462 (>= js2-language-version 200))
6463 (push ?u flags))
6464 ((and (js2-match-char ?y)
6465 (>= js2-language-version 200))
6466 (push ?y flags))
6467 (t
6468 (setq continue nil))))
6469 (if (js2-alpha-p (js2-peek-char))
6470 (js2-report-scan-error "msg.invalid.re.flag" t
6471 js2-ts-cursor 1))
6472 (js2-set-string-from-buffer token))
6473 (js2-collect-string flags)))
6474
6475 (defun js2-get-first-xml-token ()
6476 (setq js2-ts-xml-open-tags-count 0
6477 js2-ts-is-xml-attribute nil
6478 js2-ts-xml-is-tag-content nil)
6479 (js2-unget-char)
6480 (js2-get-next-xml-token))
6481
6482 (defun js2-xml-discard-string (token)
6483 "Throw away the string in progress and flag an XML parse error."
6484 (setf js2-ts-string-buffer nil
6485 (js2-token-string token) nil)
6486 (js2-report-scan-error "msg.XML.bad.form" t))
6487
6488 (defun js2-get-next-xml-token ()
6489 (setq js2-ts-string-buffer nil) ; for recording the XML
6490 (let ((token (js2-new-token 0))
6491 c result)
6492 (setq result
6493 (catch 'return
6494 (while t
6495 (setq c (js2-get-char))
6496 (cond
6497 ((= c js2-EOF_CHAR)
6498 (throw 'return js2-ERROR))
6499 (js2-ts-xml-is-tag-content
6500 (cl-case c
6501 (?>
6502 (js2-add-to-string c)
6503 (setq js2-ts-xml-is-tag-content nil
6504 js2-ts-is-xml-attribute nil))
6505 (?/
6506 (js2-add-to-string c)
6507 (when (eq ?> (js2-peek-char))
6508 (setq c (js2-get-char))
6509 (js2-add-to-string c)
6510 (setq js2-ts-xml-is-tag-content nil)
6511 (cl-decf js2-ts-xml-open-tags-count)))
6512 (?{
6513 (js2-unget-char)
6514 (js2-set-string-from-buffer token)
6515 (throw 'return js2-XML))
6516 ((?\' ?\")
6517 (js2-add-to-string c)
6518 (unless (js2-read-quoted-string c token)
6519 (throw 'return js2-ERROR)))
6520 (?=
6521 (js2-add-to-string c)
6522 (setq js2-ts-is-xml-attribute t))
6523 ((? ?\t ?\r ?\n)
6524 (js2-add-to-string c))
6525 (t
6526 (js2-add-to-string c)
6527 (setq js2-ts-is-xml-attribute nil)))
6528 (when (and (not js2-ts-xml-is-tag-content)
6529 (zerop js2-ts-xml-open-tags-count))
6530 (js2-set-string-from-buffer token)
6531 (throw 'return js2-XMLEND)))
6532 (t
6533 ;; else not tag content
6534 (cl-case c
6535 (?<
6536 (js2-add-to-string c)
6537 (setq c (js2-peek-char))
6538 (cl-case c
6539 (?!
6540 (setq c (js2-get-char)) ;; skip !
6541 (js2-add-to-string c)
6542 (setq c (js2-peek-char))
6543 (cl-case c
6544 (?-
6545 (setq c (js2-get-char)) ;; skip -
6546 (js2-add-to-string c)
6547 (if (eq c ?-)
6548 (progn
6549 (js2-add-to-string c)
6550 (unless (js2-read-xml-comment token)
6551 (throw 'return js2-ERROR)))
6552 (js2-xml-discard-string token)
6553 (throw 'return js2-ERROR)))
6554 (?\[
6555 (setq c (js2-get-char)) ;; skip [
6556 (js2-add-to-string c)
6557 (if (and (= (js2-get-char) ?C)
6558 (= (js2-get-char) ?D)
6559 (= (js2-get-char) ?A)
6560 (= (js2-get-char) ?T)
6561 (= (js2-get-char) ?A)
6562 (= (js2-get-char) ?\[))
6563 (progn
6564 (js2-add-to-string ?C)
6565 (js2-add-to-string ?D)
6566 (js2-add-to-string ?A)
6567 (js2-add-to-string ?T)
6568 (js2-add-to-string ?A)
6569 (js2-add-to-string ?\[)
6570 (unless (js2-read-cdata token)
6571 (throw 'return js2-ERROR)))
6572 (js2-xml-discard-string token)
6573 (throw 'return js2-ERROR)))
6574 (t
6575 (unless (js2-read-entity token)
6576 (throw 'return js2-ERROR))))
6577 ;; Allow bare CDATA section, e.g.:
6578 ;; let xml = <![CDATA[ foo bar baz ]]>;
6579 (when (zerop js2-ts-xml-open-tags-count)
6580 (throw 'return js2-XMLEND)))
6581 (??
6582 (setq c (js2-get-char)) ;; skip ?
6583 (js2-add-to-string c)
6584 (unless (js2-read-PI token)
6585 (throw 'return js2-ERROR)))
6586 (?/
6587 ;; end tag
6588 (setq c (js2-get-char)) ;; skip /
6589 (js2-add-to-string c)
6590 (when (zerop js2-ts-xml-open-tags-count)
6591 (js2-xml-discard-string token)
6592 (throw 'return js2-ERROR))
6593 (setq js2-ts-xml-is-tag-content t)
6594 (cl-decf js2-ts-xml-open-tags-count))
6595 (t
6596 ;; start tag
6597 (setq js2-ts-xml-is-tag-content t)
6598 (cl-incf js2-ts-xml-open-tags-count))))
6599 (?{
6600 (js2-unget-char)
6601 (js2-set-string-from-buffer token)
6602 (throw 'return js2-XML))
6603 (t
6604 (js2-add-to-string c))))))))
6605 (setf (js2-token-end token) js2-ts-cursor)
6606 (setf (js2-token-type token) result)
6607 result))
6608
6609 (defun js2-read-quoted-string (quote token)
6610 (let (c)
6611 (catch 'return
6612 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6613 (js2-add-to-string c)
6614 (if (eq c quote)
6615 (throw 'return t)))
6616 (js2-xml-discard-string token) ;; throw away string in progress
6617 nil)))
6618
6619 (defun js2-read-xml-comment (token)
6620 (let ((c (js2-get-char)))
6621 (catch 'return
6622 (while (/= c js2-EOF_CHAR)
6623 (catch 'continue
6624 (js2-add-to-string c)
6625 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6626 (setq c (js2-get-char))
6627 (js2-add-to-string c)
6628 (if (eq (js2-peek-char) ?>)
6629 (progn
6630 (setq c (js2-get-char)) ;; skip >
6631 (js2-add-to-string c)
6632 (throw 'return t))
6633 (throw 'continue nil)))
6634 (setq c (js2-get-char))))
6635 (js2-xml-discard-string token)
6636 nil)))
6637
6638 (defun js2-read-cdata (token)
6639 (let ((c (js2-get-char)))
6640 (catch 'return
6641 (while (/= c js2-EOF_CHAR)
6642 (catch 'continue
6643 (js2-add-to-string c)
6644 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6645 (setq c (js2-get-char))
6646 (js2-add-to-string c)
6647 (if (eq (js2-peek-char) ?>)
6648 (progn
6649 (setq c (js2-get-char)) ;; Skip >
6650 (js2-add-to-string c)
6651 (throw 'return t))
6652 (throw 'continue nil)))
6653 (setq c (js2-get-char))))
6654 (js2-xml-discard-string token)
6655 nil)))
6656
6657 (defun js2-read-entity (token)
6658 (let ((decl-tags 1)
6659 c)
6660 (catch 'return
6661 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6662 (js2-add-to-string c)
6663 (cl-case c
6664 (?<
6665 (cl-incf decl-tags))
6666 (?>
6667 (cl-decf decl-tags)
6668 (if (zerop decl-tags)
6669 (throw 'return t)))))
6670 (js2-xml-discard-string token)
6671 nil)))
6672
6673 (defun js2-read-PI (token)
6674 "Scan an XML processing instruction."
6675 (let (c)
6676 (catch 'return
6677 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6678 (js2-add-to-string c)
6679 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6680 (setq c (js2-get-char)) ;; Skip >
6681 (js2-add-to-string c)
6682 (throw 'return t)))
6683 (js2-xml-discard-string token)
6684 nil)))
6685
6686 ;;; Highlighting
6687
6688 (defun js2-set-face (beg end face &optional record)
6689 "Fontify a region. If RECORD is non-nil, record for later."
6690 (when (cl-plusp js2-highlight-level)
6691 (setq beg (min (point-max) beg)
6692 beg (max (point-min) beg)
6693 end (min (point-max) end)
6694 end (max (point-min) end))
6695 (if record
6696 (push (list beg end face) js2-mode-fontifications)
6697 (put-text-property beg end 'font-lock-face face))))
6698
6699 (defsubst js2-clear-face (beg end)
6700 (remove-text-properties beg end '(font-lock-face nil
6701 help-echo nil
6702 point-entered nil
6703 cursor-sensor-functions nil
6704 c-in-sws nil)))
6705
6706 (defconst js2-ecma-global-props
6707 (concat "^"
6708 (regexp-opt
6709 '("Infinity" "NaN" "undefined" "arguments") t)
6710 "$")
6711 "Value properties of the Ecma-262 Global Object.
6712 Shown at or above `js2-highlight-level' 2.")
6713
6714 ;; might want to add the name "arguments" to this list?
6715 (defconst js2-ecma-object-props
6716 (concat "^"
6717 (regexp-opt
6718 '("prototype" "__proto__" "__parent__") t)
6719 "$")
6720 "Value properties of the Ecma-262 Object constructor.
6721 Shown at or above `js2-highlight-level' 2.")
6722
6723 (defconst js2-ecma-global-funcs
6724 (concat
6725 "^"
6726 (regexp-opt
6727 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6728 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6729 "$")
6730 "Function properties of the Ecma-262 Global object.
6731 Shown at or above `js2-highlight-level' 2.")
6732
6733 (defconst js2-ecma-number-props
6734 (concat "^"
6735 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6736 "NEGATIVE_INFINITY"
6737 "POSITIVE_INFINITY") t)
6738 "$")
6739 "Properties of the Ecma-262 Number constructor.
6740 Shown at or above `js2-highlight-level' 2.")
6741
6742 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6743 "Properties of the Ecma-262 Date constructor.
6744 Shown at or above `js2-highlight-level' 2.")
6745
6746 (defconst js2-ecma-math-props
6747 (concat "^"
6748 (regexp-opt
6749 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6750 t)
6751 "$")
6752 "Properties of the Ecma-262 Math object.
6753 Shown at or above `js2-highlight-level' 2.")
6754
6755 (defconst js2-ecma-math-funcs
6756 (concat "^"
6757 (regexp-opt
6758 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6759 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6760 "$")
6761 "Function properties of the Ecma-262 Math object.
6762 Shown at or above `js2-highlight-level' 2.")
6763
6764 (defconst js2-ecma-function-props
6765 (concat
6766 "^"
6767 (regexp-opt
6768 '(;; properties of the Object prototype object
6769 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6770 "toLocaleString" "toString" "valueOf"
6771 ;; properties of the Function prototype object
6772 "apply" "call"
6773 ;; properties of the Array prototype object
6774 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6775 "splice" "unshift"
6776 ;; properties of the String prototype object
6777 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6778 "localeCompare" "match" "replace" "search" "split" "substring"
6779 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6780 "toUpperCase"
6781 ;; properties of the Number prototype object
6782 "toExponential" "toFixed" "toPrecision"
6783 ;; properties of the Date prototype object
6784 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6785 "getMinutes" "getMonth" "getSeconds" "getTime"
6786 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6787 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6788 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6789 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6790 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6791 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6792 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6793 "toTimeString" "toUTCString"
6794 ;; properties of the RegExp prototype object
6795 "exec" "test"
6796 ;; properties of the JSON prototype object
6797 "parse" "stringify"
6798 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6799 "toSource" "__defineGetter__" "__defineSetter__"
6800 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6801 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6802 t)
6803 "$")
6804 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6805 Shown at or above `js2-highlight-level' 3.")
6806
6807 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6808 (let ((target-name (and target
6809 (js2-name-node-p target)
6810 (js2-name-node-name target)))
6811 (prop-name (if prop (js2-name-node-name prop)))
6812 (level2 (>= js2-highlight-level 2))
6813 (level3 (>= js2-highlight-level 3)))
6814 (when level2
6815 (let ((face
6816 (if call-p
6817 (cond
6818 ((and target prop)
6819 (cond
6820 ((and level3 (string-match js2-ecma-function-props prop-name))
6821 'font-lock-builtin-face)
6822 ((and target-name prop)
6823 (cond
6824 ((string= target-name "Date")
6825 (if (string-match js2-ecma-date-props prop-name)
6826 'font-lock-builtin-face))
6827 ((string= target-name "Math")
6828 (if (string-match js2-ecma-math-funcs prop-name)
6829 'font-lock-builtin-face))))))
6830 (prop
6831 (if (string-match js2-ecma-global-funcs prop-name)
6832 'font-lock-builtin-face)))
6833 (cond
6834 ((and target prop)
6835 (cond
6836 ((string= target-name "Number")
6837 (if (string-match js2-ecma-number-props prop-name)
6838 'font-lock-constant-face))
6839 ((string= target-name "Math")
6840 (if (string-match js2-ecma-math-props prop-name)
6841 'font-lock-constant-face))))
6842 (prop
6843 (if (string-match js2-ecma-object-props prop-name)
6844 'font-lock-constant-face))))))
6845 (when face
6846 (let ((pos (+ (js2-node-pos parent) ; absolute
6847 (js2-node-pos prop)))) ; relative
6848 (js2-set-face pos
6849 (+ pos (js2-node-len prop))
6850 face 'record)))))))
6851
6852 (defun js2-parse-highlight-member-expr-node (node)
6853 "Perform syntax highlighting of EcmaScript built-in properties.
6854 The variable `js2-highlight-level' governs this highlighting."
6855 (let (face target prop name pos end parent call-p callee)
6856 (cond
6857 ;; case 1: simple name, e.g. foo
6858 ((js2-name-node-p node)
6859 (setq name (js2-name-node-name node))
6860 ;; possible for name to be nil in rare cases - saw it when
6861 ;; running js2-mode on an elisp buffer. Might as well try to
6862 ;; make it so js2-mode never barfs.
6863 (when name
6864 (setq face (if (string-match js2-ecma-global-props name)
6865 'font-lock-constant-face))
6866 (when face
6867 (setq pos (js2-node-pos node)
6868 end (+ pos (js2-node-len node)))
6869 (js2-set-face pos end face 'record))))
6870 ;; case 2: property access or function call
6871 ((or (js2-prop-get-node-p node)
6872 ;; highlight function call if expr is a prop-get node
6873 ;; or a plain name (i.e. unqualified function call)
6874 (and (setq call-p (js2-call-node-p node))
6875 (setq callee (js2-call-node-target node)) ; separate setq!
6876 (or (js2-prop-get-node-p callee)
6877 (js2-name-node-p callee))))
6878 (setq parent node
6879 node (if call-p callee node))
6880 (if (and call-p (js2-name-node-p callee))
6881 (setq prop callee)
6882 (setq target (js2-prop-get-node-left node)
6883 prop (js2-prop-get-node-right node)))
6884 (cond
6885 ((js2-name-node-p prop)
6886 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6887 (js2-parse-highlight-prop-get parent target prop call-p))
6888 ((js2-name-node-p target)
6889 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6890 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6891
6892 (defun js2-parse-highlight-member-expr-fn-name (expr)
6893 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6894 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6895 We currently only handle the case where the last component is a prop-get
6896 of a simple name. Called before EXPR has a parent node."
6897 (let (pos
6898 (name (and (js2-prop-get-node-p expr)
6899 (js2-prop-get-node-right expr))))
6900 (when (js2-name-node-p name)
6901 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6902 (js2-node-pos name)))
6903 (+ pos (js2-node-len name))
6904 'font-lock-function-name-face
6905 'record))))
6906
6907 ;; source: http://jsdoc.sourceforge.net/
6908 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6909 ;; allows type specifications, and needs work before entering the wild.
6910
6911 (defconst js2-jsdoc-param-tag-regexp
6912 (concat "^\\s-*\\*+\\s-*\\(@"
6913 "\\(?:param\\|argument\\)"
6914 "\\)"
6915 "\\s-*\\({[^}]+}\\)?" ; optional type
6916 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6917 "\\_>")
6918 "Matches jsdoc tags with optional type and optional param name.")
6919
6920 (defconst js2-jsdoc-typed-tag-regexp
6921 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6922 (regexp-opt
6923 '("enum"
6924 "extends"
6925 "field"
6926 "id"
6927 "implements"
6928 "lends"
6929 "mods"
6930 "requires"
6931 "return"
6932 "returns"
6933 "throw"
6934 "throws"))
6935 "\\)\\)\\s-*\\({[^}]+}\\)?")
6936 "Matches jsdoc tags with optional type.")
6937
6938 (defconst js2-jsdoc-arg-tag-regexp
6939 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6940 (regexp-opt
6941 '("alias"
6942 "augments"
6943 "borrows"
6944 "bug"
6945 "base"
6946 "config"
6947 "default"
6948 "define"
6949 "exception"
6950 "function"
6951 "member"
6952 "memberOf"
6953 "name"
6954 "namespace"
6955 "property"
6956 "since"
6957 "suppress"
6958 "this"
6959 "throws"
6960 "type"
6961 "version"))
6962 "\\)\\)\\s-+\\([^ \t]+\\)")
6963 "Matches jsdoc tags with a single argument.")
6964
6965 (defconst js2-jsdoc-empty-tag-regexp
6966 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6967 (regexp-opt
6968 '("addon"
6969 "author"
6970 "class"
6971 "const"
6972 "constant"
6973 "constructor"
6974 "constructs"
6975 "deprecated"
6976 "desc"
6977 "description"
6978 "event"
6979 "example"
6980 "exec"
6981 "export"
6982 "fileoverview"
6983 "final"
6984 "function"
6985 "hidden"
6986 "ignore"
6987 "implicitCast"
6988 "inheritDoc"
6989 "inner"
6990 "interface"
6991 "license"
6992 "noalias"
6993 "noshadow"
6994 "notypecheck"
6995 "override"
6996 "owner"
6997 "preserve"
6998 "preserveTry"
6999 "private"
7000 "protected"
7001 "public"
7002 "static"
7003 "supported"
7004 ))
7005 "\\)\\)\\s-*")
7006 "Matches empty jsdoc tags.")
7007
7008 (defconst js2-jsdoc-link-tag-regexp
7009 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
7010 "Matches a jsdoc link or code tag.")
7011
7012 (defconst js2-jsdoc-see-tag-regexp
7013 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
7014 "Matches a jsdoc @see tag.")
7015
7016 (defconst js2-jsdoc-html-tag-regexp
7017 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
7018 "Matches a simple (no attributes) html start- or end-tag.")
7019
7020 (defun js2-jsdoc-highlight-helper ()
7021 (js2-set-face (match-beginning 1)
7022 (match-end 1)
7023 'js2-jsdoc-tag)
7024 (if (match-beginning 2)
7025 (if (save-excursion
7026 (goto-char (match-beginning 2))
7027 (= (char-after) ?{))
7028 (js2-set-face (1+ (match-beginning 2))
7029 (1- (match-end 2))
7030 'js2-jsdoc-type)
7031 (js2-set-face (match-beginning 2)
7032 (match-end 2)
7033 'js2-jsdoc-value)))
7034 (if (match-beginning 3)
7035 (js2-set-face (match-beginning 3)
7036 (match-end 3)
7037 'js2-jsdoc-value)))
7038
7039 (defun js2-highlight-jsdoc (ast)
7040 "Highlight doc comment tags."
7041 (let ((comments (js2-ast-root-comments ast))
7042 beg end)
7043 (save-excursion
7044 (dolist (node comments)
7045 (when (eq (js2-comment-node-format node) 'jsdoc)
7046 (setq beg (js2-node-abs-pos node)
7047 end (+ beg (js2-node-len node)))
7048 (save-restriction
7049 (narrow-to-region beg end)
7050 (dolist (re (list js2-jsdoc-param-tag-regexp
7051 js2-jsdoc-typed-tag-regexp
7052 js2-jsdoc-arg-tag-regexp
7053 js2-jsdoc-link-tag-regexp
7054 js2-jsdoc-see-tag-regexp
7055 js2-jsdoc-empty-tag-regexp))
7056 (goto-char beg)
7057 (while (re-search-forward re nil t)
7058 (js2-jsdoc-highlight-helper)))
7059 ;; simple highlighting for html tags
7060 (goto-char beg)
7061 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7062 (js2-set-face (match-beginning 1)
7063 (match-end 1)
7064 'js2-jsdoc-html-tag-delimiter)
7065 (js2-set-face (match-beginning 2)
7066 (match-end 2)
7067 'js2-jsdoc-html-tag-name)
7068 (js2-set-face (match-beginning 3)
7069 (match-end 3)
7070 'js2-jsdoc-html-tag-delimiter))))))))
7071
7072 (defun js2-highlight-assign-targets (_node left right)
7073 "Highlight function properties and external variables."
7074 (let (leftpos name)
7075 ;; highlight vars and props assigned function values
7076 (when (or (js2-function-node-p right)
7077 (js2-class-node-p right))
7078 (cond
7079 ;; var foo = function() {...}
7080 ((js2-name-node-p left)
7081 (setq name left))
7082 ;; foo.bar.baz = function() {...}
7083 ((and (js2-prop-get-node-p left)
7084 (js2-name-node-p (js2-prop-get-node-right left)))
7085 (setq name (js2-prop-get-node-right left))))
7086 (when name
7087 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7088 (+ leftpos (js2-node-len name))
7089 'font-lock-function-name-face
7090 'record)))))
7091
7092 (defun js2-record-name-node (node)
7093 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7094 later. NODE must be a name node."
7095 (let ((leftpos (js2-node-abs-pos node)))
7096 (push (list node js2-current-scope
7097 leftpos
7098 (+ leftpos (js2-node-len node)))
7099 js2-recorded-identifiers)))
7100
7101 (defun js2-highlight-undeclared-vars ()
7102 "After entire parse is finished, look for undeclared variable references.
7103 We have to wait until entire buffer is parsed, since JavaScript permits var
7104 decls to occur after they're used.
7105
7106 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7107 it is considered declared."
7108 (let (name)
7109 (dolist (entry js2-recorded-identifiers)
7110 (cl-destructuring-bind (name-node scope pos end) entry
7111 (setq name (js2-name-node-name name-node))
7112 (unless (or (member name js2-global-externs)
7113 (member name js2-default-externs)
7114 (member name js2-additional-externs)
7115 (js2-get-defining-scope scope name pos))
7116 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7117 'js2-external-variable))))))
7118
7119 (defun js2--add-or-update-symbol (symbol inition used vars)
7120 "Add or update SYMBOL entry in VARS, an hash table.
7121 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7122 respectively meaning that SYMBOL is a mere declaration, an
7123 assignment or a function parameter; when USED is t, the symbol
7124 node is assumed to be an usage and thus added to the list stored
7125 in the cdr of the entry.
7126 "
7127 (let* ((nm (js2-name-node-name symbol))
7128 (es (js2-node-get-enclosing-scope symbol))
7129 (ds (js2-get-defining-scope es nm)))
7130 (when (and ds (not (equal nm "arguments")))
7131 (let* ((sym (js2-scope-get-symbol ds nm))
7132 (var (gethash sym vars))
7133 (err-var-p (js2-catch-node-p ds)))
7134 (unless inition
7135 (setq inition err-var-p))
7136 (if var
7137 (progn
7138 (when (and inition (not (equal (car var) ?P)))
7139 (setcar var inition))
7140 (when used
7141 (push symbol (cdr var))))
7142 ;; do not consider the declaration of catch parameter as an usage
7143 (when (and err-var-p used)
7144 (setq used nil))
7145 (puthash sym (cons inition (if used (list symbol))) vars))))))
7146
7147 (defun js2--classify-variables ()
7148 "Collect and classify variables declared or used within js2-mode-ast.
7149 Traverse the whole ast tree returning a summary of the variables
7150 usage as an hash-table, keyed by their corresponding symbol table
7151 entry.
7152 Each variable is described by a tuple where the car is a flag
7153 indicating whether the variable has been initialized and the cdr
7154 is a possibly empty list of name nodes where it is used. External
7155 symbols, i.e. those not present in the whole scopes hierarchy,
7156 are ignored."
7157 (let ((vars (make-hash-table :test #'eq :size 100)))
7158 (js2-visit-ast
7159 js2-mode-ast
7160 (lambda (node end-p)
7161 (when (null end-p)
7162 (cond
7163 ((js2-var-init-node-p node)
7164 ;; take note about possibly initialized declarations
7165 (let ((target (js2-var-init-node-target node))
7166 (initializer (js2-var-init-node-initializer node)))
7167 (when target
7168 (let* ((parent (js2-node-parent node))
7169 (grandparent (if parent (js2-node-parent parent)))
7170 (inited (not (null initializer))))
7171 (unless inited
7172 (setq inited
7173 (and grandparent
7174 (js2-for-in-node-p grandparent)
7175 (memq target
7176 (mapcar #'js2-var-init-node-target
7177 (js2-var-decl-node-kids
7178 (js2-for-in-node-iterator grandparent)))))))
7179 (js2--add-or-update-symbol target inited nil vars)))))
7180
7181 ((js2-assign-node-p node)
7182 ;; take note about assignments
7183 (let ((left (js2-assign-node-left node)))
7184 (when (js2-name-node-p left)
7185 (js2--add-or-update-symbol left t nil vars))))
7186
7187 ((js2-prop-get-node-p node)
7188 ;; handle x.y.z nodes, considering only x
7189 (let ((left (js2-prop-get-node-left node)))
7190 (when (js2-name-node-p left)
7191 (js2--add-or-update-symbol left nil t vars))))
7192
7193 ((js2-name-node-p node)
7194 ;; take note about used variables
7195 (let ((parent (js2-node-parent node)))
7196 (when parent
7197 (unless (or (and (js2-var-init-node-p parent) ; handled above
7198 (eq node (js2-var-init-node-target parent)))
7199 (and (js2-assign-node-p parent)
7200 (eq node (js2-assign-node-left parent)))
7201 (js2-prop-get-node-p parent))
7202 (let ((used t) inited)
7203 (cond
7204 ((and (js2-function-node-p parent)
7205 (js2-wrapper-function-p parent))
7206 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7207
7208 ((js2-for-in-node-p parent)
7209 (if (eq node (js2-for-in-node-iterator parent))
7210 (setq inited t used nil)))
7211
7212 ((js2-function-node-p parent)
7213 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7214 used nil)))
7215
7216 (unless used
7217 (let ((grandparent (js2-node-parent parent)))
7218 (when grandparent
7219 (setq used (js2-return-node-p grandparent)))))
7220
7221 (js2--add-or-update-symbol node inited used vars))))))))
7222 t))
7223 vars))
7224
7225 (defun js2--get-name-node (node)
7226 (cond
7227 ((js2-name-node-p node) node)
7228 ((js2-function-node-p node)
7229 (js2-function-node-name node))
7230 ((js2-class-node-p node)
7231 (js2-class-node-name node))
7232 ((js2-comp-loop-node-p node)
7233 (js2-comp-loop-node-iterator node))
7234 (t node)))
7235
7236 (defun js2--highlight-unused-variable (symbol info)
7237 (let ((name (js2-symbol-name symbol))
7238 (inited (car info))
7239 (refs (cdr info))
7240 pos len)
7241 (unless (and inited refs)
7242 (if refs
7243 (dolist (ref refs)
7244 (setq pos (js2-node-abs-pos ref))
7245 (setq len (js2-name-node-len ref))
7246 (js2-report-warning "msg.uninitialized.variable" name pos len
7247 'js2-warning))
7248 (when (or js2-warn-about-unused-function-arguments
7249 (not (eq inited ?P)))
7250 (let* ((symn (js2-symbol-ast-node symbol))
7251 (namen (js2--get-name-node symn)))
7252 (unless (js2-node-top-level-decl-p namen)
7253 (setq pos (js2-node-abs-pos namen))
7254 (setq len (js2-name-node-len namen))
7255 (js2-report-warning "msg.unused.variable" name pos len
7256 'js2-warning))))))))
7257
7258 (defun js2-highlight-unused-variables ()
7259 "Highlight unused variables."
7260 (let ((vars (js2--classify-variables)))
7261 (maphash #'js2--highlight-unused-variable vars)))
7262
7263 ;;;###autoload
7264 (define-minor-mode js2-highlight-unused-variables-mode
7265 "Toggle highlight of unused variables."
7266 :lighter ""
7267 (if js2-highlight-unused-variables-mode
7268 (add-hook 'js2-post-parse-callbacks
7269 #'js2-highlight-unused-variables nil t)
7270 (remove-hook 'js2-post-parse-callbacks
7271 #'js2-highlight-unused-variables t)))
7272
7273 (defun js2-set-default-externs ()
7274 "Set the value of `js2-default-externs' based on the various
7275 `js2-include-?-externs' variables."
7276 (setq js2-default-externs
7277 (append js2-ecma-262-externs
7278 (if js2-include-browser-externs js2-browser-externs)
7279 (if (and js2-include-browser-externs
7280 (>= js2-language-version 200)) js2-harmony-externs)
7281 (if js2-include-rhino-externs js2-rhino-externs)
7282 (if js2-include-node-externs js2-node-externs)
7283 (if (or js2-include-browser-externs js2-include-node-externs)
7284 js2-typed-array-externs))))
7285
7286 (defun js2-apply-jslint-globals ()
7287 (setq js2-additional-externs
7288 (nconc (js2-get-jslint-globals)
7289 js2-additional-externs)))
7290
7291 (defun js2-get-jslint-globals ()
7292 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7293 when (and (eq 'block (js2-comment-node-format node))
7294 (save-excursion
7295 (goto-char (js2-node-abs-pos node))
7296 (looking-at "/\\*global ")))
7297 append (js2-get-jslint-globals-in
7298 (match-end 0)
7299 (js2-node-abs-end node))))
7300
7301 (defun js2-get-jslint-globals-in (beg end)
7302 (let (res)
7303 (save-excursion
7304 (goto-char beg)
7305 (while (re-search-forward js2-mode-identifier-re end t)
7306 (let ((match (match-string 0)))
7307 (unless (member match '("true" "false"))
7308 (push match res)))))
7309 (nreverse res)))
7310
7311 ;;; IMenu support
7312
7313 ;; We currently only support imenu, but eventually should support speedbar and
7314 ;; possibly other browsing mechanisms.
7315
7316 ;; The basic strategy is to identify function assignment targets of the form
7317 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7318 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7319 ;; for imenu after parsing is finished.
7320
7321 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7322 ;; JavaScript, and the general problem is undecidable. However, several forms
7323 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7324 ;; include:
7325
7326 ;; function foo() -- function declaration
7327 ;; foo = function() -- function expression assigned to variable
7328 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7329 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7330 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7331 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7332 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7333 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7334 ;; function foo() {function bar() {...}} -- nested function
7335 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7336
7337 ;; This list boils down to a few forms that can be combined recursively.
7338 ;; Top-level named function declarations include both the left-hand (name)
7339 ;; and the right-hand (function value) expressions needed to produce an imenu
7340 ;; entry. The other "right-hand" forms we need to look for are:
7341 ;; - functions declared as props/getters/setters in object literals
7342 ;; - nested named function declarations
7343 ;; The "left-hand" expressions that functions can be assigned to include:
7344 ;; - local/global variables
7345 ;; - nested property-get expressions like a.b.c.d
7346 ;; - element gets like foo[10] or foo['bar'] where the index
7347 ;; expression can be trivially converted to a property name. They
7348 ;; effectively then become property gets.
7349
7350 ;; All the different definition types are canonicalized into the form
7351 ;; foo.bar.baz = position-of-function-keyword
7352
7353 ;; We need to build a trie-like structure for imenu. As an example,
7354 ;; consider the following JavaScript code:
7355
7356 ;; a = function() {...} // function at position 5
7357 ;; b = function() {...} // function at position 25
7358 ;; foo = function() {...} // function at position 100
7359 ;; foo.bar = function() {...} // function at position 200
7360 ;; foo.bar.baz = function() {...} // function at position 300
7361 ;; foo.bar.zab = function() {...} // function at position 400
7362
7363 ;; During parsing we accumulate an entry for each definition in
7364 ;; the variable `js2-imenu-recorder', like so:
7365
7366 ;; '((fn a 5)
7367 ;; (fn b 25)
7368 ;; (fn foo 100)
7369 ;; (fn foo bar 200)
7370 ;; (fn foo bar baz 300)
7371 ;; (fn foo bar zab 400))
7372
7373 ;; Where 'fn' is the respective function node.
7374 ;; After parsing these entries are merged into this alist-trie:
7375
7376 ;; '((a . 1)
7377 ;; (b . 2)
7378 ;; (foo (<definition> . 3)
7379 ;; (bar (<definition> . 6)
7380 ;; (baz . 100)
7381 ;; (zab . 200))))
7382
7383 ;; Note the wacky need for a <definition> name. The token can be anything
7384 ;; that isn't a valid JavaScript identifier, because you might make foo
7385 ;; a function and then start setting properties on it that are also functions.
7386
7387 (defun js2-prop-node-name (node)
7388 "Return the name of a node that may be a property-get/property-name.
7389 If NODE is not a valid name-node, string-node or integral number-node,
7390 returns nil. Otherwise returns the string name/value of the node."
7391 (cond
7392 ((js2-name-node-p node)
7393 (js2-name-node-name node))
7394 ((js2-string-node-p node)
7395 (js2-string-node-value node))
7396 ((and (js2-number-node-p node)
7397 (string-match "^[0-9]+$" (js2-number-node-value node)))
7398 (js2-number-node-value node))
7399 ((eq (js2-node-type node) js2-THIS)
7400 "this")
7401 ((eq (js2-node-type node) js2-SUPER)
7402 "super")))
7403
7404 (defun js2-node-qname-component (node)
7405 "Return the name of this node, if it contributes to a qname.
7406 Returns nil if the node doesn't contribute."
7407 (copy-sequence
7408 (or (js2-prop-node-name node)
7409 (if (and (js2-function-node-p node)
7410 (js2-function-node-name node))
7411 (js2-name-node-name (js2-function-node-name node))))))
7412
7413 (defun js2-record-imenu-entry (fn-node qname pos)
7414 "Add an entry to `js2-imenu-recorder'.
7415 FN-NODE should be the current item's function node.
7416
7417 Associate FN-NODE with its QNAME for later lookup.
7418 This is used in postprocessing the chain list. For each chain, we find
7419 the parent function, look up its qname, then prepend a copy of it to the chain."
7420 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7421 (unless js2-imenu-function-map
7422 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7423 (puthash fn-node qname js2-imenu-function-map))
7424
7425 (defun js2-record-imenu-functions (node &optional var)
7426 "Record function definitions for imenu.
7427 NODE is a function node or an object literal.
7428 VAR, if non-nil, is the expression that NODE is being assigned to.
7429 When passed arguments of wrong type, does nothing."
7430 (when js2-parse-ide-mode
7431 (let ((fun-p (js2-function-node-p node))
7432 qname fname-node)
7433 (cond
7434 ;; non-anonymous function declaration?
7435 ((and fun-p
7436 (not var)
7437 (setq fname-node (js2-function-node-name node)))
7438 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7439 ;; for remaining forms, compute left-side tree branch first
7440 ((and var (setq qname (js2-compute-nested-prop-get var)))
7441 (cond
7442 ;; foo.bar.baz = function
7443 (fun-p
7444 (js2-record-imenu-entry node qname (js2-node-pos node)))
7445 ;; foo.bar.baz = object-literal
7446 ;; look for nested functions: {a: {b: function() {...} }}
7447 ((js2-object-node-p node)
7448 ;; Node position here is still absolute, since the parser
7449 ;; passes the assignment target and value expressions
7450 ;; to us before they are added as children of the assignment node.
7451 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7452
7453 (defun js2-compute-nested-prop-get (node)
7454 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7455 component nodes as a list. Otherwise return nil. Element-gets are treated
7456 as property-gets if the index expression is a string, or a positive integer."
7457 (let (left right head)
7458 (cond
7459 ((or (js2-name-node-p node)
7460 (js2-this-or-super-node-p node))
7461 (list node))
7462 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7463 ((js2-prop-get-node-p node) ; foo.bar
7464 (setq left (js2-prop-get-node-left node)
7465 right (js2-prop-get-node-right node))
7466 (if (setq head (js2-compute-nested-prop-get left))
7467 (nconc head (list right))))
7468 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7469 (setq left (js2-elem-get-node-target node)
7470 right (js2-elem-get-node-element node))
7471 (if (or (js2-string-node-p right) ; ['bar']
7472 (and (js2-number-node-p right) ; [10]
7473 (string-match "^[0-9]+$"
7474 (js2-number-node-value right))))
7475 (if (setq head (js2-compute-nested-prop-get left))
7476 (nconc head (list right))))))))
7477
7478 (defun js2-record-object-literal (node qname pos)
7479 "Recursively process an object literal looking for functions.
7480 NODE is an object literal that is the right-hand child of an assignment
7481 expression. QNAME is a list of nodes representing the assignment target,
7482 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7483 POS is the absolute position of the node.
7484 We do a depth-first traversal of NODE. For any functions we find,
7485 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7486 (let (right)
7487 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7488 (let ((left (js2-infix-node-left e))
7489 ;; Element positions are relative to the parent position.
7490 (pos (+ pos (js2-node-pos e))))
7491 (cond
7492 ;; foo: function() {...}
7493 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7494 (when (js2-prop-node-name left)
7495 ;; As a policy decision, we record the position of the property,
7496 ;; not the position of the `function' keyword, since the property
7497 ;; is effectively the name of the function.
7498 (js2-record-imenu-entry right (append qname (list left)) pos)))
7499 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7500 ((js2-object-node-p right)
7501 (js2-record-object-literal right
7502 (append qname (list (js2-infix-node-left e)))
7503 (+ pos (js2-node-pos right)))))))))
7504
7505 (defun js2-node-top-level-decl-p (node)
7506 "Return t if NODE's name is defined in the top-level scope.
7507 Also returns t if NODE's name is not defined in any scope, since it implies
7508 that it's an external variable, which must also be in the top-level scope."
7509 (let* ((name (js2-prop-node-name node))
7510 (this-scope (js2-node-get-enclosing-scope node))
7511 defining-scope)
7512 (cond
7513 ((js2-this-or-super-node-p node)
7514 nil)
7515 ((null this-scope)
7516 t)
7517 ((setq defining-scope (js2-get-defining-scope this-scope name))
7518 (js2-ast-root-p defining-scope))
7519 (t t))))
7520
7521 (defun js2-wrapper-function-p (node)
7522 "Return t if NODE is a function expression that's immediately invoked.
7523 NODE must be `js2-function-node'."
7524 (let ((parent (js2-node-parent node)))
7525 (or
7526 ;; function(){...}();
7527 (and (js2-call-node-p parent)
7528 (eq node (js2-call-node-target parent)))
7529 (and (js2-paren-node-p parent)
7530 ;; (function(){...})();
7531 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7532 ;; (function(){...}).call(this);
7533 (and (js2-prop-get-node-p parent)
7534 (member (js2-name-node-name (js2-prop-get-node-right parent))
7535 '("call" "apply"))
7536 (js2-call-node-p (js2-node-parent parent))))))))
7537
7538 (defun js2-browse-postprocess-chains ()
7539 "Modify function-declaration name chains after parsing finishes.
7540 Some of the information is only available after the parse tree is complete.
7541 For instance, processing a nested scope requires a parent function node."
7542 (let (result fn parent-qname p elem)
7543 (dolist (entry js2-imenu-recorder)
7544 ;; function node goes first
7545 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7546 ;; Examine head's defining scope:
7547 ;; Pre-processed chain, or top-level/external, keep as-is.
7548 (if (or (stringp head) (js2-node-top-level-decl-p head))
7549 (push chain result)
7550 (when (js2-this-or-super-node-p head)
7551 (setq chain (cdr chain))) ; discard this-node
7552 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7553 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7554 (when (eq parent-qname 'not-found)
7555 ;; anonymous function expressions are not recorded
7556 ;; during the parse, so we need to handle this case here
7557 (setq parent-qname
7558 (if (js2-wrapper-function-p fn)
7559 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7560 (if (js2-ast-root-p grandparent)
7561 nil
7562 (gethash grandparent js2-imenu-function-map 'skip)))
7563 'skip))
7564 (puthash fn parent-qname js2-imenu-function-map))
7565 (if (eq parent-qname 'skip)
7566 ;; We don't show it, let's record that fact.
7567 (remhash current-fn js2-imenu-function-map)
7568 ;; Prepend parent fn qname to this chain.
7569 (let ((qname (append parent-qname chain)))
7570 (puthash current-fn (butlast qname) js2-imenu-function-map)
7571 (push qname result)))))))
7572 ;; Collect chains obtained by third-party code.
7573 (let (js2-imenu-recorder)
7574 (run-hooks 'js2-build-imenu-callbacks)
7575 (dolist (entry js2-imenu-recorder)
7576 (push (cdr entry) result)))
7577 ;; Finally replace each node in each chain with its name.
7578 (dolist (chain result)
7579 (setq p chain)
7580 (while p
7581 (if (js2-node-p (setq elem (car p)))
7582 (setcar p (js2-node-qname-component elem)))
7583 (setq p (cdr p))))
7584 result))
7585
7586 ;; Merge name chains into a trie-like tree structure of nested lists.
7587 ;; To simplify construction of the trie, we first build it out using the rule
7588 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7589 ;; [key, num-or-list]. The second element can be a number; if so, this key
7590 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7591 ;; associated with the key at this level.) Otherwise the second element is
7592 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7593 ;; a simple recursive formulation.
7594 ;;
7595 ;; js2-mode is building the data structure for imenu. The imenu documentation
7596 ;; claims that it's the structure above, but in practice it wants the children
7597 ;; at the same list level as the key for that level, which is how I've drawn
7598 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7599 ;; list wrapper around the children at each level.
7600 ;;
7601 ;; A completed nested imenu-alist entry looks like this:
7602 ;; '(("foo"
7603 ;; ("<definition>" . 7)
7604 ;; ("bar"
7605 ;; ("a" . 40)
7606 ;; ("b" . 60))))
7607 ;;
7608 ;; In particular, the documentation for `imenu--index-alist' says that
7609 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7610 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7611
7612 (defun js2-treeify (lst)
7613 "Convert (a b c d) to (a ((b ((c d)))))."
7614 (if (null (cddr lst)) ; list length <= 2
7615 lst
7616 (list (car lst) (list (js2-treeify (cdr lst))))))
7617
7618 (defun js2-build-alist-trie (chains trie)
7619 "Merge declaration name chains into a trie-like alist structure for imenu.
7620 CHAINS is the qname chain list produced during parsing. TRIE is a
7621 list of elements built up so far."
7622 (let (head tail pos branch kids)
7623 (dolist (chain chains)
7624 (setq head (car chain)
7625 tail (cdr chain)
7626 pos (if (numberp (car tail)) (car tail))
7627 branch (js2-find-if (lambda (n)
7628 (string= (car n) head))
7629 trie)
7630 kids (cl-second branch))
7631 (cond
7632 ;; case 1: this key isn't in the trie yet
7633 ((null branch)
7634 (if trie
7635 (setcdr (last trie) (list (js2-treeify chain)))
7636 (setq trie (list (js2-treeify chain)))))
7637 ;; case 2: key is present with a single number entry: replace w/ list
7638 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7639 ;; ("<definition>" 20)))
7640 ((numberp kids)
7641 (setcar (cdr branch)
7642 (list (list "<definition-1>" kids)
7643 (if pos
7644 (list "<definition-2>" pos)
7645 (js2-treeify tail)))))
7646 ;; case 3: key is there (with kids), and we're a number entry
7647 (pos
7648 (setcdr (last kids)
7649 (list
7650 (list (format "<definition-%d>"
7651 (1+ (cl-loop for kid in kids
7652 count (eq ?< (aref (car kid) 0)))))
7653 pos))))
7654 ;; case 4: key is there with kids, need to merge in our chain
7655 (t
7656 (js2-build-alist-trie (list tail) kids))))
7657 trie))
7658
7659 (defun js2-flatten-trie (trie)
7660 "Convert TRIE to imenu-format.
7661 Recurses through nodes, and for each one whose second element is a list,
7662 appends the list's flattened elements to the current element. Also
7663 changes the tails into conses. For instance, this pre-flattened trie
7664
7665 '(a ((b 20)
7666 (c ((d 30)
7667 (e 40)))))
7668
7669 becomes
7670
7671 '(a (b . 20)
7672 (c (d . 30)
7673 (e . 40)))
7674
7675 Note that the root of the trie has no key, just a list of chains.
7676 This is also true for the value of any key with multiple children,
7677 e.g. key 'c' in the example above."
7678 (cond
7679 ((listp (car trie))
7680 (mapcar #'js2-flatten-trie trie))
7681 (t
7682 (if (numberp (cl-second trie))
7683 (cons (car trie) (cl-second trie))
7684 ;; else pop list and append its kids
7685 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7686
7687 (defun js2-build-imenu-index ()
7688 "Turn `js2-imenu-recorder' into an imenu data structure."
7689 (when (eq js2-imenu-recorder 'empty)
7690 (setq js2-imenu-recorder nil))
7691 (let* ((chains (js2-browse-postprocess-chains))
7692 (result (js2-build-alist-trie chains nil)))
7693 (js2-flatten-trie result)))
7694
7695 (defun js2-test-print-chains (chains)
7696 "Print a list of qname chains.
7697 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7698 i.e. one or more nodes, and an integer position as the list tail."
7699 (mapconcat (lambda (chain)
7700 (concat "("
7701 (mapconcat (lambda (elem)
7702 (if (js2-node-p elem)
7703 (or (js2-node-qname-component elem)
7704 "nil")
7705 (number-to-string elem)))
7706 chain
7707 " ")
7708 ")"))
7709 chains
7710 "\n"))
7711
7712 ;;; Parser
7713
7714 (defconst js2-version "1.8.5"
7715 "Version of JavaScript supported.")
7716
7717 (defun js2-record-face (face &optional token)
7718 "Record a style run of FACE for TOKEN or the current token."
7719 (unless token (setq token (js2-current-token)))
7720 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7721
7722 (defsubst js2-node-end (n)
7723 "Computes the absolute end of node N.
7724 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7725 is only true until the node is added to its parent; i.e., while parsing."
7726 (+ (js2-node-pos n)
7727 (js2-node-len n)))
7728
7729 (defun js2-record-comment (token)
7730 "Record a comment in `js2-scanned-comments'."
7731 (let ((ct (js2-token-comment-type token))
7732 (beg (js2-token-beg token))
7733 (end (js2-token-end token)))
7734 (push (make-js2-comment-node :len (- end beg)
7735 :format ct)
7736 js2-scanned-comments)
7737 (when js2-parse-ide-mode
7738 (js2-record-face (if (eq ct 'jsdoc)
7739 'font-lock-doc-face
7740 'font-lock-comment-face)
7741 token)
7742 (when (memq ct '(html preprocessor))
7743 ;; Tell cc-engine the bounds of the comment.
7744 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7745
7746 (defun js2-peek-token ()
7747 "Return the next token type without consuming it.
7748 If `js2-ti-lookahead' is positive, return the type of next token
7749 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7750 (if (not (zerop js2-ti-lookahead))
7751 (js2-token-type
7752 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7753 (let ((tt (js2-get-token-internal nil)))
7754 (js2-unget-token)
7755 tt)))
7756
7757 (defalias 'js2-next-token 'js2-get-token)
7758
7759 (defun js2-match-token (match &optional dont-unget)
7760 "Get next token and return t if it matches MATCH, a bytecode.
7761 Returns nil and consumes nothing if MATCH is not the next token."
7762 (if (/= (js2-get-token) match)
7763 (ignore (unless dont-unget (js2-unget-token)))
7764 t))
7765
7766 (defun js2-match-contextual-kwd (name)
7767 "Consume and return t if next token is `js2-NAME', and its
7768 string is NAME. Returns nil and keeps current token otherwise."
7769 (if (or (/= (js2-get-token) js2-NAME)
7770 (not (string= (js2-current-token-string) name)))
7771 (progn
7772 (js2-unget-token)
7773 nil)
7774 (js2-record-face 'font-lock-keyword-face)
7775 t))
7776
7777 (defun js2-get-prop-name-token ()
7778 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7779
7780 (defun js2-match-prop-name ()
7781 "Consume token and return t if next token is a valid property name.
7782 If `js2-language-version' is >= 180, a keyword or reserved word
7783 is considered valid name as well."
7784 (if (eq js2-NAME (js2-get-prop-name-token))
7785 t
7786 (js2-unget-token)
7787 nil))
7788
7789 (defun js2-must-match-prop-name (msg-id &optional pos len)
7790 (if (js2-match-prop-name)
7791 t
7792 (js2-report-error msg-id nil pos len)
7793 nil))
7794
7795 (defun js2-peek-token-or-eol ()
7796 "Return js2-EOL if the next token immediately follows a newline.
7797 Else returns the next token. Used in situations where we don't
7798 consider certain token types valid if they are preceded by a newline.
7799 One example is the postfix ++ or -- operator, which has to be on the
7800 same line as its operand."
7801 (let ((tt (js2-get-token))
7802 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7803 (js2-unget-token)
7804 (if follows-eol
7805 js2-EOL
7806 tt)))
7807
7808 (defun js2-must-match (token msg-id &optional pos len)
7809 "Match next token to token code TOKEN, or record a syntax error.
7810 MSG-ID is the error message to report if the match fails.
7811 Returns t on match, nil if no match."
7812 (if (js2-match-token token t)
7813 t
7814 (js2-report-error msg-id nil pos len)
7815 (js2-unget-token)
7816 nil))
7817
7818 (defun js2-must-match-name (msg-id)
7819 (if (js2-match-token js2-NAME t)
7820 t
7821 (if (eq (js2-current-token-type) js2-RESERVED)
7822 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7823 (js2-report-error msg-id)
7824 (js2-unget-token))
7825 nil))
7826
7827 (defsubst js2-inside-function ()
7828 (cl-plusp js2-nesting-of-function))
7829
7830 (defun js2-set-requires-activation ()
7831 (if (js2-function-node-p js2-current-script-or-fn)
7832 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7833
7834 (defun js2-check-activation-name (name _token)
7835 (when (js2-inside-function)
7836 ;; skip language-version 1.2 check from Rhino
7837 (if (or (string= "arguments" name)
7838 (and js2-compiler-activation-names ; only used in codegen
7839 (gethash name js2-compiler-activation-names)))
7840 (js2-set-requires-activation))))
7841
7842 (defun js2-set-is-generator ()
7843 (let ((fn-node js2-current-script-or-fn))
7844 (when (and (js2-function-node-p fn-node)
7845 (not (js2-function-node-generator-type fn-node)))
7846 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7847
7848 (defun js2-must-have-xml ()
7849 (unless js2-compiler-xml-available
7850 (js2-report-error "msg.XML.not.available")))
7851
7852 (defun js2-push-scope (scope)
7853 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7854 (cl-assert (js2-scope-p scope))
7855 (cl-assert (null (js2-scope-parent-scope scope)))
7856 (cl-assert (not (eq js2-current-scope scope)))
7857 (setf (js2-scope-parent-scope scope) js2-current-scope
7858 js2-current-scope scope))
7859
7860 (defsubst js2-pop-scope ()
7861 (setq js2-current-scope
7862 (js2-scope-parent-scope js2-current-scope)))
7863
7864 (defun js2-enter-loop (loop-node)
7865 (push loop-node js2-loop-set)
7866 (push loop-node js2-loop-and-switch-set)
7867 (js2-push-scope loop-node)
7868 ;; Tell the current labeled statement (if any) its statement,
7869 ;; and set the jump target of the first label to the loop.
7870 ;; These are used in `js2-parse-continue' to verify that the
7871 ;; continue target is an actual labeled loop. (And for codegen.)
7872 (when js2-labeled-stmt
7873 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7874 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7875 js2-labeled-stmt))) loop-node)))
7876
7877 (defun js2-exit-loop ()
7878 (pop js2-loop-set)
7879 (pop js2-loop-and-switch-set)
7880 (js2-pop-scope))
7881
7882 (defsubst js2-enter-switch (switch-node)
7883 (push switch-node js2-loop-and-switch-set))
7884
7885 (defsubst js2-exit-switch ()
7886 (pop js2-loop-and-switch-set))
7887
7888 (defsubst js2-get-directive (node)
7889 "Return NODE's value if it is a directive, nil otherwise.
7890
7891 A directive is an otherwise-meaningless expression statement
7892 consisting of a string literal, such as \"use strict\"."
7893 (and (js2-expr-stmt-node-p node)
7894 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7895 (js2-string-node-value node)))
7896
7897 (defun js2-parse (&optional buf cb)
7898 "Tell the js2 parser to parse a region of JavaScript.
7899
7900 BUF is a buffer or buffer name containing the code to parse.
7901 Call `narrow-to-region' first to parse only part of the buffer.
7902
7903 The returned AST root node is given some additional properties:
7904 `node-count' - total number of nodes in the AST
7905 `buffer' - BUF. The buffer it refers to may change or be killed,
7906 so the value is not necessarily reliable.
7907
7908 An optional callback CB can be specified to report parsing
7909 progress. If `(functionp CB)' returns t, it will be called with
7910 the current line number once before parsing begins, then again
7911 each time the lexer reaches a new line number.
7912
7913 CB can also be a list of the form `(symbol cb ...)' to specify
7914 multiple callbacks with different criteria. Each symbol is a
7915 criterion keyword, and the following element is the callback to
7916 call
7917
7918 :line - called whenever the line number changes
7919 :token - called for each new token consumed
7920
7921 The list of criteria could be extended to include entering or
7922 leaving a statement, an expression, or a function definition."
7923 (if (and cb (not (functionp cb)))
7924 (error "criteria callbacks not yet implemented"))
7925 (let ((inhibit-point-motion-hooks t)
7926 (js2-compiler-xml-available (>= js2-language-version 160))
7927 ;; This is a recursive-descent parser, so give it a big stack.
7928 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7929 (max-specpdl-size (max max-specpdl-size 3000))
7930 (case-fold-search nil)
7931 ast)
7932 (with-current-buffer (or buf (current-buffer))
7933 (setq js2-scanned-comments nil
7934 js2-parsed-errors nil
7935 js2-parsed-warnings nil
7936 js2-imenu-recorder nil
7937 js2-imenu-function-map nil
7938 js2-label-set nil)
7939 (js2-init-scanner)
7940 (setq ast (js2-do-parse))
7941 (unless js2-ts-hit-eof
7942 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7943 (setf (js2-ast-root-errors ast) js2-parsed-errors
7944 (js2-ast-root-warnings ast) js2-parsed-warnings)
7945 ;; if we didn't find any declarations, put a dummy in this list so we
7946 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7947 (unless js2-imenu-recorder
7948 (setq js2-imenu-recorder 'empty))
7949 (run-hooks 'js2-parse-finished-hook)
7950 ast)))
7951
7952 ;; Corresponds to Rhino's Parser.parse() method.
7953 (defun js2-do-parse ()
7954 "Parse current buffer starting from current point.
7955 Scanner should be initialized."
7956 (let ((pos js2-ts-cursor)
7957 (end js2-ts-cursor) ; in case file is empty
7958 root n tt
7959 (in-directive-prologue t)
7960 (js2-in-use-strict-directive js2-in-use-strict-directive)
7961 directive)
7962 ;; initialize buffer-local parsing vars
7963 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7964 js2-current-script-or-fn root
7965 js2-current-scope root
7966 js2-nesting-of-function 0
7967 js2-labeled-stmt nil
7968 js2-recorded-identifiers nil ; for js2-highlight
7969 js2-in-use-strict-directive nil)
7970 (while (/= (setq tt (js2-get-token)) js2-EOF)
7971 (if (= tt js2-FUNCTION)
7972 (progn
7973 (setq n (if js2-called-by-compile-function
7974 (js2-parse-function-expr)
7975 (js2-parse-function-stmt))))
7976 ;; not a function - parse a statement
7977 (js2-unget-token)
7978 (setq n (js2-parse-statement))
7979 (when in-directive-prologue
7980 (setq directive (js2-get-directive n))
7981 (cond
7982 ((null directive)
7983 (setq in-directive-prologue nil))
7984 ((string= directive "use strict")
7985 (setq js2-in-use-strict-directive t)))))
7986 ;; add function or statement to script
7987 (setq end (js2-node-end n))
7988 (js2-block-node-push root n))
7989 ;; add comments to root in lexical order
7990 (when js2-scanned-comments
7991 ;; if we find a comment beyond end of normal kids, use its end
7992 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7993 (dolist (comment js2-scanned-comments)
7994 (push comment (js2-ast-root-comments root))
7995 (js2-node-add-children root comment)))
7996 (setf (js2-node-len root) (- end pos))
7997 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7998 ;; Give extensions a chance to muck with things before highlighting starts.
7999 (let ((js2-additional-externs js2-additional-externs))
8000 (save-excursion
8001 (run-hooks 'js2-post-parse-callbacks))
8002 (js2-highlight-undeclared-vars))
8003 root))
8004
8005 (defun js2-parse-function-closure-body (fn-node)
8006 "Parse a JavaScript 1.8 function closure body."
8007 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
8008 (if js2-ts-hit-eof
8009 (js2-report-error "msg.no.brace.body" nil
8010 (js2-node-pos fn-node)
8011 (- js2-ts-cursor (js2-node-pos fn-node)))
8012 (js2-node-add-children fn-node
8013 (setf (js2-function-node-body fn-node)
8014 (js2-parse-expr t))))))
8015
8016 (defun js2-parse-function-body (fn-node)
8017 (js2-must-match js2-LC "msg.no.brace.body"
8018 (js2-node-pos fn-node)
8019 (- js2-ts-cursor (js2-node-pos fn-node)))
8020 (let ((pos (js2-current-token-beg)) ; LC position
8021 (pn (make-js2-block-node)) ; starts at LC position
8022 tt
8023 end
8024 not-in-directive-prologue
8025 node
8026 directive)
8027 (cl-incf js2-nesting-of-function)
8028 (unwind-protect
8029 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
8030 (= tt js2-EOF)
8031 (= tt js2-RC)))
8032 (js2-block-node-push
8033 pn
8034 (if (/= tt js2-FUNCTION)
8035 (if not-in-directive-prologue
8036 (js2-parse-statement)
8037 (setq node (js2-parse-statement)
8038 directive (js2-get-directive node))
8039 (cond
8040 ((null directive)
8041 (setq not-in-directive-prologue t))
8042 ((string= directive "use strict")
8043 ;; Back up and reparse the function, because new rules apply
8044 ;; to the function name and parameters.
8045 (when (not js2-in-use-strict-directive)
8046 (setq js2-in-use-strict-directive t)
8047 (throw 'reparse t))))
8048 node)
8049 (js2-get-token)
8050 (js2-parse-function-stmt))))
8051 (cl-decf js2-nesting-of-function))
8052 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
8053 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
8054 (setq end (js2-current-token-end)))
8055 (setf (js2-node-pos pn) pos
8056 (js2-node-len pn) (- end pos))
8057 (setf (js2-function-node-body fn-node) pn)
8058 (js2-node-add-children fn-node pn)
8059 pn))
8060
8061 (defun js2-define-destruct-symbols-internal
8062 (node decl-type face &optional ignore-not-in-block name-nodes)
8063 "Internal version of `js2-define-destruct-symbols'. The only
8064 difference is that NAME-NODES is passed down recursively."
8065 (cond
8066 ((js2-name-node-p node)
8067 (let (leftpos)
8068 (js2-define-symbol decl-type (js2-name-node-name node)
8069 node ignore-not-in-block)
8070 (when face
8071 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8072 (+ leftpos (js2-node-len node))
8073 face 'record))
8074 (setq name-nodes (append name-nodes (list node)))))
8075 ((js2-object-node-p node)
8076 (dolist (elem (js2-object-node-elems node))
8077 (setq name-nodes
8078 (append name-nodes
8079 (js2-define-destruct-symbols-internal
8080 ;; In abbreviated destructuring {a, b}, right == left.
8081 (js2-object-prop-node-right elem)
8082 decl-type face ignore-not-in-block name-nodes)))))
8083 ((js2-array-node-p node)
8084 (dolist (elem (js2-array-node-elems node))
8085 (when elem
8086 (setq name-nodes
8087 (append name-nodes
8088 (js2-define-destruct-symbols-internal
8089 elem decl-type face ignore-not-in-block name-nodes))))))
8090 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8091 (js2-node-len node))))
8092 name-nodes)
8093
8094 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8095 "Declare and fontify destructuring parameters inside NODE.
8096 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8097
8098 Return a list of `js2-name-node' nodes representing the symbols
8099 declared; probably to check them for errors."
8100 (js2-define-destruct-symbols-internal node decl-type face ignore-not-in-block))
8101
8102 (defvar js2-illegal-strict-identifiers
8103 '("eval" "arguments")
8104 "Identifiers not allowed as variables in strict mode.")
8105
8106 (defun js2-check-strict-identifier (name-node)
8107 "Check that NAME-NODE makes a legal strict mode identifier."
8108 (when js2-in-use-strict-directive
8109 (let ((param-name (js2-name-node-name name-node)))
8110 (when (member param-name js2-illegal-strict-identifiers)
8111 (js2-report-error "msg.bad.id.strict" param-name
8112 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8113
8114 (defun js2-check-strict-function-params (preceding-params params)
8115 "Given PRECEDING-PARAMS in a function's parameter list, check
8116 for strict mode errors caused by PARAMS."
8117 (when js2-in-use-strict-directive
8118 (dolist (param params)
8119 (let ((param-name (js2-name-node-name param)))
8120 (js2-check-strict-identifier param)
8121 (when (cl-some (lambda (param)
8122 (string= (js2-name-node-name param) param-name))
8123 preceding-params)
8124 (js2-report-error "msg.dup.param.strict" param-name
8125 (js2-node-abs-pos param) (js2-node-len param)))))))
8126
8127 (defun js2-parse-function-params (function-type fn-node pos)
8128 "Parse the parameters of a function of FUNCTION-TYPE
8129 represented by FN-NODE at POS."
8130 (if (js2-match-token js2-RP)
8131 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8132 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8133 (eq (js2-current-token-type) js2-NAME)))
8134 params param
8135 param-name-nodes new-param-name-nodes
8136 default-found rest-param-at)
8137 (when paren-free-arrow
8138 (js2-unget-token))
8139 (cl-loop for tt = (js2-peek-token)
8140 do
8141 (cond
8142 ;; destructuring param
8143 ((and (not paren-free-arrow)
8144 (or (= tt js2-LB) (= tt js2-LC)))
8145 (js2-get-token)
8146 (when default-found
8147 (js2-report-error "msg.no.default.after.default.param"))
8148 (setq param (js2-parse-destruct-primary-expr)
8149 new-param-name-nodes (js2-define-destruct-symbols
8150 param js2-LP 'js2-function-param))
8151 (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
8152 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8153 (push param params))
8154 ;; variable name
8155 (t
8156 (when (and (>= js2-language-version 200)
8157 (not paren-free-arrow)
8158 (js2-match-token js2-TRIPLEDOT)
8159 (not rest-param-at))
8160 ;; to report errors if there are more parameters
8161 (setq rest-param-at (length params)))
8162 (js2-must-match-name "msg.no.parm")
8163 (js2-record-face 'js2-function-param)
8164 (setq param (js2-create-name-node))
8165 (js2-define-symbol js2-LP (js2-current-token-string) param)
8166 (js2-check-strict-function-params param-name-nodes (list param))
8167 (setq param-name-nodes (append param-name-nodes (list param)))
8168 ;; default parameter value
8169 (when (or (and default-found
8170 (not rest-param-at)
8171 (js2-must-match js2-ASSIGN
8172 "msg.no.default.after.default.param"
8173 (js2-node-pos param)
8174 (js2-node-len param)))
8175 (and (>= js2-language-version 200)
8176 (js2-match-token js2-ASSIGN)))
8177 (cl-assert (not paren-free-arrow))
8178 (let* ((pos (js2-node-pos param))
8179 (tt (js2-current-token-type))
8180 (op-pos (- (js2-current-token-beg) pos))
8181 (left param)
8182 (right (js2-parse-assign-expr))
8183 (len (- (js2-node-end right) pos)))
8184 (setq param (make-js2-assign-node
8185 :type tt :pos pos :len len :op-pos op-pos
8186 :left left :right right)
8187 default-found t)
8188 (js2-node-add-children param left right)))
8189 (push param params)))
8190 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8191 (js2-report-error "msg.param.after.rest" nil
8192 (js2-node-pos param) (js2-node-len param)))
8193 while
8194 (js2-match-token js2-COMMA))
8195 (when (and (not paren-free-arrow)
8196 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8197 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8198 (when rest-param-at
8199 (setf (js2-function-node-rest-p fn-node) t))
8200 (dolist (p params)
8201 (js2-node-add-children fn-node p)
8202 (push p (js2-function-node-params fn-node))))))
8203
8204 (defun js2-check-inconsistent-return-warning (fn-node name)
8205 "Possibly show inconsistent-return warning.
8206 Last token scanned is the close-curly for the function body."
8207 (when (and js2-mode-show-strict-warnings
8208 js2-strict-inconsistent-return-warning
8209 (not (js2-has-consistent-return-usage
8210 (js2-function-node-body fn-node))))
8211 ;; Have it extend from close-curly to bol or beginning of block.
8212 (let ((pos (save-excursion
8213 (goto-char (js2-current-token-end))
8214 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8215 (point-at-bol))))
8216 (end (js2-current-token-end)))
8217 (if (cl-plusp (js2-name-node-length name))
8218 (js2-add-strict-warning "msg.no.return.value"
8219 (js2-name-node-name name) pos end)
8220 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8221
8222 (defun js2-parse-function-stmt ()
8223 (let ((pos (js2-current-token-beg))
8224 (star-p (js2-match-token js2-MUL)))
8225 (js2-must-match-name "msg.unnamed.function.stmt")
8226 (let ((name (js2-create-name-node t))
8227 pn member-expr)
8228 (cond
8229 ((js2-match-token js2-LP)
8230 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8231 (js2-allow-member-expr-as-function-name
8232 (setq member-expr (js2-parse-member-expr-tail nil name))
8233 (js2-parse-highlight-member-expr-fn-name member-expr)
8234 (js2-must-match js2-LP "msg.no.paren.parms")
8235 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8236 (js2-function-node-member-expr pn) member-expr)
8237 pn)
8238 (t
8239 (js2-report-error "msg.no.paren.parms")
8240 (make-js2-error-node))))))
8241
8242 (defun js2-parse-function-expr ()
8243 (let ((pos (js2-current-token-beg))
8244 (star-p (js2-match-token js2-MUL))
8245 name)
8246 (when (js2-match-token js2-NAME)
8247 (setq name (js2-create-name-node t)))
8248 (js2-must-match js2-LP "msg.no.paren.parms")
8249 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8250
8251 (defun js2-parse-function-internal (function-type pos star-p &optional name)
8252 (let (fn-node lp)
8253 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8254 (setq lp (js2-current-token-beg)))
8255 (setf fn-node (make-js2-function-node :pos pos
8256 :name name
8257 :form function-type
8258 :lp (if lp (- lp pos))
8259 :generator-type (and star-p 'STAR)))
8260 (when name
8261 (js2-set-face (js2-node-pos name) (js2-node-end name)
8262 'font-lock-function-name-face 'record)
8263 (when (and (eq function-type 'FUNCTION_STATEMENT)
8264 (cl-plusp (js2-name-node-length name)))
8265 ;; Function statements define a symbol in the enclosing scope
8266 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
8267 (when js2-in-use-strict-directive
8268 (js2-check-strict-identifier name)))
8269 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8270 ;; 1. Nested functions are not affected by the dynamic scope flag
8271 ;; as dynamic scope is already a parent of their scope.
8272 ;; 2. Functions defined under the with statement also immune to
8273 ;; this setup, in which case dynamic scope is ignored in favor
8274 ;; of the with object.
8275 (setf (js2-function-node-ignore-dynamic fn-node) t))
8276 ;; dynamically bind all the per-function variables
8277 (let ((js2-current-script-or-fn fn-node)
8278 (js2-current-scope fn-node)
8279 (js2-nesting-of-with 0)
8280 (js2-end-flags 0)
8281 js2-label-set
8282 js2-loop-set
8283 js2-loop-and-switch-set)
8284 (js2-parse-function-params function-type fn-node pos)
8285 (when (eq function-type 'FUNCTION_ARROW)
8286 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8287 (if (and (>= js2-language-version 180)
8288 (/= (js2-peek-token) js2-LC))
8289 (js2-parse-function-closure-body fn-node)
8290 (js2-parse-function-body fn-node))
8291 (js2-check-inconsistent-return-warning fn-node name)
8292
8293 (when name
8294 (js2-node-add-children fn-node name)
8295 ;; Function expressions define a name only in the body of the
8296 ;; function, and only if not hidden by a parameter name
8297 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8298 (null (js2-scope-get-symbol js2-current-scope
8299 (js2-name-node-name name))))
8300 (js2-define-symbol js2-FUNCTION
8301 (js2-name-node-name name)
8302 fn-node))
8303 (when (eq function-type 'FUNCTION_STATEMENT)
8304 (js2-record-imenu-functions fn-node))))
8305
8306 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8307 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8308 ;; We wait until after parsing the function to set its parent scope,
8309 ;; since `js2-define-symbol' needs the defining-scope check to stop
8310 ;; at the function boundary when checking for redeclarations.
8311 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8312 fn-node))
8313
8314 (defun js2-parse-function (function-type pos star-p &optional name)
8315 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8316 beginning of the first token (function keyword, unless it's an
8317 arrow function), NAME is js2-name-node."
8318 (let ((continue t)
8319 ts-state
8320 fn-node
8321 ;; Preserve strict state outside this function.
8322 (js2-in-use-strict-directive js2-in-use-strict-directive))
8323 ;; Parse multiple times if a new strict mode directive is discovered in the
8324 ;; function body, as new rules will be retroactively applied to the legality
8325 ;; of function names and parameters.
8326 (while continue
8327 (setq ts-state (make-js2-ts-state))
8328 (setq continue (catch 'reparse
8329 (setq fn-node (js2-parse-function-internal
8330 function-type pos star-p name))
8331 ;; Don't continue.
8332 nil))
8333 (when continue
8334 (js2-ts-seek ts-state)))
8335 fn-node))
8336
8337 (defun js2-parse-statements (&optional parent)
8338 "Parse a statement list. Last token consumed must be js2-LC.
8339
8340 PARENT can be a `js2-block-node', in which case the statements are
8341 appended to PARENT. Otherwise a new `js2-block-node' is created
8342 and returned.
8343
8344 This function does not match the closing js2-RC: the caller
8345 matches the RC so it can provide a suitable error message if not
8346 matched. This means it's up to the caller to set the length of
8347 the node to include the closing RC. The node start pos is set to
8348 the absolute buffer start position, and the caller should fix it
8349 up to be relative to the parent node. All children of this block
8350 node are given relative start positions and correct lengths."
8351 (let ((pn (or parent (make-js2-block-node)))
8352 tt)
8353 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8354 (/= tt js2-RC))
8355 (js2-block-node-push pn (js2-parse-statement)))
8356 pn))
8357
8358 (defun js2-parse-statement ()
8359 (let (pn beg end)
8360 ;; coarse-grained user-interrupt check - needs work
8361 (and js2-parse-interruptable-p
8362 (zerop (% (cl-incf js2-parse-stmt-count)
8363 js2-statements-per-pause))
8364 (input-pending-p)
8365 (throw 'interrupted t))
8366 (setq pn (js2-statement-helper))
8367 ;; no-side-effects warning check
8368 (unless (js2-node-has-side-effects pn)
8369 (setq end (js2-node-end pn))
8370 (save-excursion
8371 (goto-char end)
8372 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8373 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8374 pn))
8375
8376 ;; These correspond to the switch cases in Parser.statementHelper
8377 (defconst js2-parsers
8378 (let ((parsers (make-vector js2-num-tokens
8379 #'js2-parse-expr-stmt)))
8380 (aset parsers js2-BREAK #'js2-parse-break)
8381 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8382 (aset parsers js2-CONST #'js2-parse-const-var)
8383 (aset parsers js2-CONTINUE #'js2-parse-continue)
8384 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8385 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8386 (aset parsers js2-DO #'js2-parse-do)
8387 (aset parsers js2-EXPORT #'js2-parse-export)
8388 (aset parsers js2-FOR #'js2-parse-for)
8389 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8390 (aset parsers js2-IF #'js2-parse-if)
8391 (aset parsers js2-IMPORT #'js2-parse-import)
8392 (aset parsers js2-LC #'js2-parse-block)
8393 (aset parsers js2-LET #'js2-parse-let-stmt)
8394 (aset parsers js2-NAME #'js2-parse-name-or-label)
8395 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8396 (aset parsers js2-SEMI #'js2-parse-semi)
8397 (aset parsers js2-SWITCH #'js2-parse-switch)
8398 (aset parsers js2-THROW #'js2-parse-throw)
8399 (aset parsers js2-TRY #'js2-parse-try)
8400 (aset parsers js2-VAR #'js2-parse-const-var)
8401 (aset parsers js2-WHILE #'js2-parse-while)
8402 (aset parsers js2-WITH #'js2-parse-with)
8403 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8404 parsers)
8405 "A vector mapping token types to parser functions.")
8406
8407 (defun js2-parse-warn-missing-semi (beg end)
8408 (and js2-mode-show-strict-warnings
8409 js2-strict-missing-semi-warning
8410 (js2-add-strict-warning
8411 "msg.missing.semi" nil
8412 ;; back up to beginning of statement or line
8413 (max beg (save-excursion
8414 (goto-char end)
8415 (point-at-bol)))
8416 end)))
8417
8418 (defconst js2-no-semi-insertion
8419 (list js2-IF
8420 js2-SWITCH
8421 js2-WHILE
8422 js2-DO
8423 js2-FOR
8424 js2-TRY
8425 js2-WITH
8426 js2-LC
8427 js2-ERROR
8428 js2-SEMI
8429 js2-CLASS
8430 js2-FUNCTION
8431 js2-EXPORT)
8432 "List of tokens that don't do automatic semicolon insertion.")
8433
8434 (defconst js2-autoinsert-semi-and-warn
8435 (list js2-ERROR js2-EOF js2-RC))
8436
8437 (defun js2-statement-helper ()
8438 (let* ((tt (js2-get-token))
8439 (first-tt tt)
8440 (parser (if (= tt js2-ERROR)
8441 #'js2-parse-semi
8442 (aref js2-parsers tt)))
8443 pn)
8444 ;; If the statement is set, then it's been told its label by now.
8445 (and js2-labeled-stmt
8446 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8447 (setq js2-labeled-stmt nil))
8448 (setq pn (funcall parser))
8449 ;; Don't do auto semi insertion for certain statement types.
8450 (unless (or (memq first-tt js2-no-semi-insertion)
8451 (js2-labeled-stmt-node-p pn))
8452 (js2-auto-insert-semicolon pn))
8453 pn))
8454
8455 (defun js2-auto-insert-semicolon (pn)
8456 (let* ((tt (js2-get-token))
8457 (pos (js2-node-pos pn)))
8458 (cond
8459 ((= tt js2-SEMI)
8460 ;; extend the node bounds to include the semicolon.
8461 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8462 ((memq tt js2-autoinsert-semi-and-warn)
8463 (js2-unget-token) ; Not ';', do not consume.
8464 ;; Autoinsert ;
8465 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8466 (t
8467 (if (not (js2-token-follows-eol-p (js2-current-token)))
8468 ;; Report error if no EOL or autoinsert ';' otherwise
8469 (js2-report-error "msg.no.semi.stmt")
8470 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8471 (js2-unget-token) ; Not ';', do not consume.
8472 ))))
8473
8474 (defun js2-parse-condition ()
8475 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8476 The parens are discarded and the expression node is returned.
8477 The `pos' field of the return value is set to an absolute position
8478 that must be fixed up by the caller.
8479 Return value is a list (EXPR LP RP), with absolute paren positions."
8480 (let (pn lp rp)
8481 (if (js2-must-match js2-LP "msg.no.paren.cond")
8482 (setq lp (js2-current-token-beg)))
8483 (setq pn (js2-parse-expr))
8484 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8485 (setq rp (js2-current-token-beg)))
8486 ;; Report strict warning on code like "if (a = 7) ..."
8487 (if (and js2-strict-cond-assign-warning
8488 (js2-assign-node-p pn))
8489 (js2-add-strict-warning "msg.equal.as.assign" nil
8490 (js2-node-pos pn)
8491 (+ (js2-node-pos pn)
8492 (js2-node-len pn))))
8493 (list pn lp rp)))
8494
8495 (defun js2-parse-if ()
8496 "Parser for if-statement. Last matched token must be js2-IF."
8497 (let ((pos (js2-current-token-beg))
8498 cond if-true if-false else-pos end pn)
8499 (setq cond (js2-parse-condition)
8500 if-true (js2-parse-statement)
8501 if-false (if (js2-match-token js2-ELSE)
8502 (progn
8503 (setq else-pos (- (js2-current-token-beg) pos))
8504 (js2-parse-statement)))
8505 end (js2-node-end (or if-false if-true))
8506 pn (make-js2-if-node :pos pos
8507 :len (- end pos)
8508 :condition (car cond)
8509 :then-part if-true
8510 :else-part if-false
8511 :else-pos else-pos
8512 :lp (js2-relpos (cl-second cond) pos)
8513 :rp (js2-relpos (cl-third cond) pos)))
8514 (js2-node-add-children pn (car cond) if-true if-false)
8515 pn))
8516
8517 (defun js2-parse-import ()
8518 "Parse import statement. The current token must be js2-IMPORT."
8519 (unless (js2-ast-root-p js2-current-scope)
8520 (js2-report-error "msg.mod.import.decl.at.top.level"))
8521 (let ((beg (js2-current-token-beg)))
8522 (cond ((js2-match-token js2-STRING)
8523 (make-js2-import-node
8524 :pos beg
8525 :len (- (js2-current-token-end) beg)
8526 :module-id (js2-current-token-string)))
8527 (t
8528 (let* ((import-clause (js2-parse-import-clause))
8529 (from-clause (and import-clause (js2-parse-from-clause)))
8530 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8531 (node (make-js2-import-node
8532 :pos beg
8533 :len (- (js2-current-token-end) beg)
8534 :import import-clause
8535 :from from-clause
8536 :module-id module-id)))
8537 (when import-clause
8538 (js2-node-add-children node import-clause))
8539 (when from-clause
8540 (js2-node-add-children node from-clause))
8541 node)))))
8542
8543 (defun js2-parse-import-clause ()
8544 "Parse the bindings in an import statement.
8545 This can take many forms:
8546
8547 ImportedDefaultBinding -> 'foo'
8548 NameSpaceImport -> '* as lib'
8549 NamedImports -> '{foo as bar, bang}'
8550 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8551 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8552
8553 Try to match namespace imports and named imports first because nothing can
8554 come after them. If it is an imported default binding, then it could have named
8555 imports or a namespace import that follows it.
8556 "
8557 (let* ((beg (js2-current-token-beg))
8558 (clause (make-js2-import-clause-node
8559 :pos beg))
8560 (children (list)))
8561 (cond
8562 ((js2-match-token js2-MUL)
8563 (let ((ns-import (js2-parse-namespace-import)))
8564 (when ns-import
8565 (let ((name-node (js2-namespace-import-node-name ns-import)))
8566 (js2-define-symbol
8567 js2-LET (js2-name-node-name name-node) name-node t)))
8568 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8569 (push ns-import children)))
8570 ((js2-match-token js2-LC)
8571 (let ((imports (js2-parse-export-bindings t)))
8572 (setf (js2-import-clause-node-named-imports clause) imports)
8573 (dolist (import imports)
8574 (push import children)
8575 (let ((name-node (js2-export-binding-node-local-name import)))
8576 (when name-node
8577 (js2-define-symbol
8578 js2-LET (js2-name-node-name name-node) name-node t))))))
8579 ((= (js2-peek-token) js2-NAME)
8580 (let ((binding (js2-maybe-parse-export-binding)))
8581 (let ((node-name (js2-export-binding-node-local-name binding)))
8582 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8583 (setf (js2-import-clause-node-default-binding clause) binding)
8584 (push binding children))
8585 (when (js2-match-token js2-COMMA)
8586 (cond
8587 ((js2-match-token js2-MUL)
8588 (let ((ns-import (js2-parse-namespace-import)))
8589 (let ((name-node (js2-namespace-import-node-name ns-import)))
8590 (js2-define-symbol
8591 js2-LET (js2-name-node-name name-node) name-node t))
8592 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8593 (push ns-import children)))
8594 ((js2-match-token js2-LC)
8595 (let ((imports (js2-parse-export-bindings t)))
8596 (setf (js2-import-clause-node-named-imports clause) imports)
8597 (dolist (import imports)
8598 (push import children)
8599 (let ((name-node (js2-export-binding-node-local-name import)))
8600 (when name-node
8601 (js2-define-symbol
8602 js2-LET (js2-name-node-name name-node) name-node t))))))
8603 (t (js2-report-error "msg.syntax")))))
8604 (t (js2-report-error "msg.mod.declaration.after.import")))
8605 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8606 (apply #'js2-node-add-children clause children)
8607 clause))
8608
8609 (defun js2-parse-namespace-import ()
8610 "Parse a namespace import expression such as '* as bar'.
8611 The current token must be js2-MUL."
8612 (let ((beg (js2-current-token-beg)))
8613 (when (js2-must-match js2-NAME "msg.syntax")
8614 (if (equal "as" (js2-current-token-string))
8615 (when (js2-must-match-prop-name "msg.syntax")
8616 (let ((node (make-js2-namespace-import-node
8617 :pos beg
8618 :len (- (js2-current-token-end) beg)
8619 :name (make-js2-name-node
8620 :pos (js2-current-token-beg)
8621 :len (js2-current-token-end)
8622 :name (js2-current-token-string)))))
8623 (js2-node-add-children node (js2-namespace-import-node-name node))
8624 node))
8625 (js2-unget-token)
8626 (js2-report-error "msg.syntax")))))
8627
8628
8629 (defun js2-parse-from-clause ()
8630 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8631 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8632 (let ((beg (js2-current-token-beg)))
8633 (if (equal "from" (js2-current-token-string))
8634 (cond
8635 ((js2-match-token js2-STRING)
8636 (make-js2-from-clause-node
8637 :pos beg
8638 :len (- (js2-current-token-end) beg)
8639 :module-id (js2-current-token-string)
8640 :metadata-p nil))
8641 ((js2-match-token js2-THIS)
8642 (when (js2-must-match-name "msg.mod.spec.after.from")
8643 (if (equal "module" (js2-current-token-string))
8644 (make-js2-from-clause-node
8645 :pos beg
8646 :len (- (js2-current-token-end) beg)
8647 :module-id "this"
8648 :metadata-p t)
8649 (js2-unget-token)
8650 (js2-unget-token)
8651 (js2-report-error "msg.mod.spec.after.from")
8652 nil)))
8653 (t (js2-report-error "msg.mod.spec.after.from") nil))
8654 (js2-unget-token)
8655 (js2-report-error "msg.mod.from.after.import.spec.set")
8656 nil))))
8657
8658 (defun js2-parse-export-bindings (&optional import-p)
8659 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8660 {foo as bar, baz as bang}. The current token must be
8661 js2-LC. Return a lisp list of js2-export-binding-node"
8662 (let ((bindings (list)))
8663 (while
8664 (let ((binding (js2-maybe-parse-export-binding)))
8665 (when binding
8666 (push binding bindings))
8667 (js2-match-token js2-COMMA)))
8668 (when (js2-must-match js2-RC (if import-p
8669 "msg.mod.rc.after.import.spec.list"
8670 "msg.mod.rc.after.export.spec.list"))
8671 (reverse bindings))))
8672
8673 (defun js2-maybe-parse-export-binding ()
8674 "Attempt to parse a binding expression found inside an import/export statement.
8675 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8676 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8677 js2-export-binding-node and consume all the tokens. If it does not match, it
8678 consumes no tokens."
8679 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8680 (beg (js2-current-token-beg))
8681 (extern-name-len (js2-current-token-len))
8682 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8683 (aref js2-kwd-tokens (js2-current-token-type)))))
8684 (if extern-name
8685 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8686 (if (and as (equal "as" (js2-current-token-string)))
8687 (let ((name
8688 (or
8689 (and (js2-match-token js2-DEFAULT) "default")
8690 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8691 (if name
8692 (let ((node (make-js2-export-binding-node
8693 :pos beg
8694 :len (- (js2-current-token-end) beg)
8695 :local-name (make-js2-name-node
8696 :name name
8697 :pos (js2-current-token-beg)
8698 :len (js2-current-token-len))
8699 :extern-name (make-js2-name-node
8700 :name extern-name
8701 :pos beg
8702 :len extern-name-len))))
8703 (js2-node-add-children
8704 node
8705 (js2-export-binding-node-local-name node)
8706 (js2-export-binding-node-extern-name node))
8707 node)
8708 (js2-unget-token)
8709 nil))
8710 (when as (js2-unget-token))
8711 (let* ((name-node (make-js2-name-node
8712 :name (js2-current-token-string)
8713 :pos (js2-current-token-beg)
8714 :len (js2-current-token-len)))
8715 (node (make-js2-export-binding-node
8716 :pos (js2-current-token-beg)
8717 :len (js2-current-token-len)
8718 :local-name name-node
8719 :extern-name name-node)))
8720 (when is-reserved-name
8721 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8722 (js2-node-add-children node name-node)
8723 node)))
8724 nil)))
8725
8726 (defun js2-parse-switch ()
8727 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8728 (let ((pos (js2-current-token-beg))
8729 tt pn discriminant has-default case-expr case-node
8730 case-pos cases stmt lp)
8731 (if (js2-must-match js2-LP "msg.no.paren.switch")
8732 (setq lp (js2-current-token-beg)))
8733 (setq discriminant (js2-parse-expr)
8734 pn (make-js2-switch-node :discriminant discriminant
8735 :pos pos
8736 :lp (js2-relpos lp pos)))
8737 (js2-node-add-children pn discriminant)
8738 (js2-enter-switch pn)
8739 (unwind-protect
8740 (progn
8741 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8742 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8743 (js2-must-match js2-LC "msg.no.brace.switch")
8744 (catch 'break
8745 (while t
8746 (setq tt (js2-next-token)
8747 case-pos (js2-current-token-beg))
8748 (cond
8749 ((= tt js2-RC)
8750 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8751 (throw 'break nil)) ; done
8752 ((= tt js2-CASE)
8753 (setq case-expr (js2-parse-expr))
8754 (js2-must-match js2-COLON "msg.no.colon.case"))
8755 ((= tt js2-DEFAULT)
8756 (if has-default
8757 (js2-report-error "msg.double.switch.default"))
8758 (setq has-default t
8759 case-expr nil)
8760 (js2-must-match js2-COLON "msg.no.colon.case"))
8761 (t
8762 (js2-report-error "msg.bad.switch")
8763 (throw 'break nil)))
8764 (setq case-node (make-js2-case-node :pos case-pos
8765 :len (- (js2-current-token-end) case-pos)
8766 :expr case-expr))
8767 (js2-node-add-children case-node case-expr)
8768 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8769 (/= tt js2-CASE)
8770 (/= tt js2-DEFAULT)
8771 (/= tt js2-EOF))
8772 (setf stmt (js2-parse-statement)
8773 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8774 (js2-block-node-push case-node stmt))
8775 (push case-node cases)))
8776 ;; add cases last, as pushing reverses the order to be correct
8777 (dolist (kid cases)
8778 (js2-node-add-children pn kid)
8779 (push kid (js2-switch-node-cases pn)))
8780 pn) ; return value
8781 (js2-exit-switch))))
8782
8783 (defun js2-parse-while ()
8784 "Parser for while-statement. Last matched token must be js2-WHILE."
8785 (let ((pos (js2-current-token-beg))
8786 (pn (make-js2-while-node))
8787 cond body)
8788 (js2-enter-loop pn)
8789 (unwind-protect
8790 (progn
8791 (setf cond (js2-parse-condition)
8792 (js2-while-node-condition pn) (car cond)
8793 body (js2-parse-statement)
8794 (js2-while-node-body pn) body
8795 (js2-node-len pn) (- (js2-node-end body) pos)
8796 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8797 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8798 (js2-node-add-children pn body (car cond)))
8799 (js2-exit-loop))
8800 pn))
8801
8802 (defun js2-parse-do ()
8803 "Parser for do-statement. Last matched token must be js2-DO."
8804 (let ((pos (js2-current-token-beg))
8805 (pn (make-js2-do-node))
8806 cond body end)
8807 (js2-enter-loop pn)
8808 (unwind-protect
8809 (progn
8810 (setq body (js2-parse-statement))
8811 (js2-must-match js2-WHILE "msg.no.while.do")
8812 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8813 cond (js2-parse-condition)
8814 (js2-do-node-condition pn) (car cond)
8815 (js2-do-node-body pn) body
8816 end js2-ts-cursor
8817 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8818 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8819 (js2-node-add-children pn (car cond) body))
8820 (js2-exit-loop))
8821 ;; Always auto-insert semicolon to follow SpiderMonkey:
8822 ;; It is required by ECMAScript but is ignored by the rest of
8823 ;; world; see bug 238945
8824 (if (js2-match-token js2-SEMI)
8825 (setq end js2-ts-cursor))
8826 (setf (js2-node-len pn) (- end pos))
8827 pn))
8828
8829 (defun js2-parse-export ()
8830 "Parse an export statement.
8831 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8832 expressions should only be either hoistable expressions (function or generator)
8833 or assignment expressions, but there is no checking to enforce that and so it
8834 will parse without error a small subset of
8835 invalid export statements."
8836 (unless (js2-ast-root-p js2-current-scope)
8837 (js2-report-error "msg.mod.export.decl.at.top.level"))
8838 (let ((beg (js2-current-token-beg))
8839 (children (list))
8840 exports-list from-clause declaration default)
8841 (cond
8842 ((js2-match-token js2-MUL)
8843 (setq from-clause (js2-parse-from-clause))
8844 (when from-clause
8845 (push from-clause children)))
8846 ((js2-match-token js2-LC)
8847 (setq exports-list (js2-parse-export-bindings))
8848 (when exports-list
8849 (dolist (export exports-list)
8850 (push export children)))
8851 (when (js2-match-token js2-NAME)
8852 (if (equal "from" (js2-current-token-string))
8853 (progn
8854 (js2-unget-token)
8855 (setq from-clause (js2-parse-from-clause)))
8856 (js2-unget-token))))
8857 ((js2-match-token js2-DEFAULT)
8858 (setq default (js2-parse-expr)))
8859 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8860 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8861 (t
8862 (setq declaration (js2-parse-expr))))
8863 (when from-clause
8864 (push from-clause children))
8865 (when declaration
8866 (push declaration children)
8867 (when (not (js2-function-node-p declaration))
8868 (js2-auto-insert-semicolon declaration)))
8869 (when default
8870 (push default children)
8871 (when (not (js2-function-node-p default))
8872 (js2-auto-insert-semicolon default)))
8873 (let ((node (make-js2-export-node
8874 :pos beg
8875 :len (- (js2-current-token-end) beg)
8876 :exports-list exports-list
8877 :from-clause from-clause
8878 :declaration declaration
8879 :default default)))
8880 (apply #'js2-node-add-children node children)
8881 node)))
8882
8883 (defun js2-parse-for ()
8884 "Parse a for, for-in or for each-in statement.
8885 Last matched token must be js2-FOR."
8886 (let ((for-pos (js2-current-token-beg))
8887 (tmp-scope (make-js2-scope))
8888 pn is-for-each is-for-in-or-of is-for-of
8889 in-pos each-pos tmp-pos
8890 init ; Node init is also foo in 'foo in object'.
8891 cond ; Node cond is also object in 'foo in object'.
8892 incr ; 3rd section of for-loop initializer.
8893 body tt lp rp)
8894 ;; See if this is a for each () instead of just a for ()
8895 (when (js2-match-token js2-NAME)
8896 (if (string= "each" (js2-current-token-string))
8897 (progn
8898 (setq is-for-each t
8899 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8900 (js2-record-face 'font-lock-keyword-face))
8901 (js2-report-error "msg.no.paren.for")))
8902 (if (js2-must-match js2-LP "msg.no.paren.for")
8903 (setq lp (- (js2-current-token-beg) for-pos)))
8904 (setq tt (js2-get-token))
8905 ;; Capture identifiers inside parens. We can't create the node
8906 ;; (and use it as the current scope) until we know its type.
8907 (js2-push-scope tmp-scope)
8908 (unwind-protect
8909 (progn
8910 ;; parse init clause
8911 (let ((js2-in-for-init t)) ; set as dynamic variable
8912 (cond
8913 ((= tt js2-SEMI)
8914 (js2-unget-token)
8915 (setq init (make-js2-empty-expr-node)))
8916 ((or (= tt js2-VAR) (= tt js2-LET))
8917 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8918 (t
8919 (js2-unget-token)
8920 (setq init (js2-parse-expr)))))
8921 (if (or (js2-match-token js2-IN)
8922 (and (>= js2-language-version 200)
8923 (js2-match-contextual-kwd "of")
8924 (setq is-for-of t)))
8925 (setq is-for-in-or-of t
8926 in-pos (- (js2-current-token-beg) for-pos)
8927 ;; scope of iteration target object is not the scope we've created above.
8928 ;; stash current scope temporary.
8929 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8930 (js2-parse-expr))) ; object over which we're iterating
8931 ;; else ordinary for loop - parse cond and incr
8932 (js2-must-match js2-SEMI "msg.no.semi.for")
8933 (setq cond (if (= (js2-peek-token) js2-SEMI)
8934 (make-js2-empty-expr-node) ; no loop condition
8935 (js2-parse-expr)))
8936 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8937 (setq tmp-pos (js2-current-token-end)
8938 incr (if (= (js2-peek-token) js2-RP)
8939 (make-js2-empty-expr-node :pos tmp-pos)
8940 (js2-parse-expr)))))
8941 (js2-pop-scope))
8942 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8943 (setq rp (- (js2-current-token-beg) for-pos)))
8944 (if (not is-for-in-or-of)
8945 (setq pn (make-js2-for-node :init init
8946 :condition cond
8947 :update incr
8948 :lp lp
8949 :rp rp))
8950 ;; cond could be null if 'in obj' got eaten by the init node.
8951 (if (js2-infix-node-p init)
8952 ;; it was (foo in bar) instead of (var foo in bar)
8953 (setq cond (js2-infix-node-right init)
8954 init (js2-infix-node-left init))
8955 (if (and (js2-var-decl-node-p init)
8956 (> (length (js2-var-decl-node-kids init)) 1))
8957 (js2-report-error "msg.mult.index")))
8958 (setq pn (make-js2-for-in-node :iterator init
8959 :object cond
8960 :in-pos in-pos
8961 :foreach-p is-for-each
8962 :each-pos each-pos
8963 :forof-p is-for-of
8964 :lp lp
8965 :rp rp)))
8966 ;; Transplant the declarations.
8967 (setf (js2-scope-symbol-table pn)
8968 (js2-scope-symbol-table tmp-scope))
8969 (unwind-protect
8970 (progn
8971 (js2-enter-loop pn)
8972 ;; We have to parse the body -after- creating the loop node,
8973 ;; so that the loop node appears in the js2-loop-set, allowing
8974 ;; break/continue statements to find the enclosing loop.
8975 (setf body (js2-parse-statement)
8976 (js2-loop-node-body pn) body
8977 (js2-node-pos pn) for-pos
8978 (js2-node-len pn) (- (js2-node-end body) for-pos))
8979 (js2-node-add-children pn init cond incr body))
8980 ;; finally
8981 (js2-exit-loop))
8982 pn))
8983
8984 (defun js2-parse-try ()
8985 "Parse a try statement. Last matched token must be js2-TRY."
8986 (let ((try-pos (js2-current-token-beg))
8987 try-end
8988 try-block
8989 catch-blocks
8990 finally-block
8991 saw-default-catch
8992 peek)
8993 (if (/= (js2-peek-token) js2-LC)
8994 (js2-report-error "msg.no.brace.try"))
8995 (setq try-block (js2-parse-statement)
8996 try-end (js2-node-end try-block)
8997 peek (js2-peek-token))
8998 (cond
8999 ((= peek js2-CATCH)
9000 (while (js2-match-token js2-CATCH)
9001 (let* ((catch-pos (js2-current-token-beg))
9002 (catch-node (make-js2-catch-node :pos catch-pos))
9003 param
9004 guard-kwd
9005 catch-cond
9006 lp rp)
9007 (if saw-default-catch
9008 (js2-report-error "msg.catch.unreachable"))
9009 (if (js2-must-match js2-LP "msg.no.paren.catch")
9010 (setq lp (- (js2-current-token-beg) catch-pos)))
9011 (js2-push-scope catch-node)
9012 (let ((tt (js2-peek-token)))
9013 (cond
9014 ;; Destructuring pattern:
9015 ;; catch ({ message, file }) { ... }
9016 ((or (= tt js2-LB) (= tt js2-LC))
9017 (js2-get-token)
9018 (setq param (js2-parse-destruct-primary-expr))
9019 (js2-define-destruct-symbols param js2-LET nil))
9020 ;; Simple name.
9021 (t
9022 (js2-must-match-name "msg.bad.catchcond")
9023 (setq param (js2-create-name-node))
9024 (js2-define-symbol js2-LET (js2-current-token-string) param)
9025 (js2-check-strict-identifier param))))
9026 ;; Catch condition.
9027 (if (js2-match-token js2-IF)
9028 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
9029 catch-cond (js2-parse-expr))
9030 (setq saw-default-catch t))
9031 (if (js2-must-match js2-RP "msg.bad.catchcond")
9032 (setq rp (- (js2-current-token-beg) catch-pos)))
9033 (js2-must-match js2-LC "msg.no.brace.catchblock")
9034 (js2-parse-statements catch-node)
9035 (if (js2-must-match js2-RC "msg.no.brace.after.body")
9036 (setq try-end (js2-current-token-end)))
9037 (js2-pop-scope)
9038 (setf (js2-node-len catch-node) (- try-end catch-pos)
9039 (js2-catch-node-param catch-node) param
9040 (js2-catch-node-guard-expr catch-node) catch-cond
9041 (js2-catch-node-guard-kwd catch-node) guard-kwd
9042 (js2-catch-node-lp catch-node) lp
9043 (js2-catch-node-rp catch-node) rp)
9044 (js2-node-add-children catch-node param catch-cond)
9045 (push catch-node catch-blocks))))
9046 ((/= peek js2-FINALLY)
9047 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
9048 (js2-node-pos try-block)
9049 (- (setq try-end (js2-node-end try-block))
9050 (js2-node-pos try-block)))))
9051 (when (js2-match-token js2-FINALLY)
9052 (let ((finally-pos (js2-current-token-beg))
9053 (block (js2-parse-statement)))
9054 (setq try-end (js2-node-end block)
9055 finally-block (make-js2-finally-node :pos finally-pos
9056 :len (- try-end finally-pos)
9057 :body block))
9058 (js2-node-add-children finally-block block)))
9059 (let ((pn (make-js2-try-node :pos try-pos
9060 :len (- try-end try-pos)
9061 :try-block try-block
9062 :finally-block finally-block)))
9063 (js2-node-add-children pn try-block finally-block)
9064 ;; Push them onto the try-node, which reverses and corrects their order.
9065 (dolist (cb catch-blocks)
9066 (js2-node-add-children pn cb)
9067 (push cb (js2-try-node-catch-clauses pn)))
9068 pn)))
9069
9070 (defun js2-parse-throw ()
9071 "Parser for throw-statement. Last matched token must be js2-THROW."
9072 (let ((pos (js2-current-token-beg))
9073 expr pn)
9074 (if (= (js2-peek-token-or-eol) js2-EOL)
9075 ;; ECMAScript does not allow new lines before throw expression,
9076 ;; see bug 256617
9077 (js2-report-error "msg.bad.throw.eol"))
9078 (setq expr (js2-parse-expr)
9079 pn (make-js2-throw-node :pos pos
9080 :len (- (js2-node-end expr) pos)
9081 :expr expr))
9082 (js2-node-add-children pn expr)
9083 pn))
9084
9085 (defun js2-match-jump-label-name (label-name)
9086 "If break/continue specified a label, return that label's labeled stmt.
9087 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9088 does not match an existing label, reports an error and returns nil."
9089 (let ((bundle (cdr (assoc label-name js2-label-set))))
9090 (if (null bundle)
9091 (js2-report-error "msg.undef.label"))
9092 bundle))
9093
9094 (defun js2-parse-break ()
9095 "Parser for break-statement. Last matched token must be js2-BREAK."
9096 (let ((pos (js2-current-token-beg))
9097 (end (js2-current-token-end))
9098 break-target ; statement to break from
9099 break-label ; in "break foo", name-node representing the foo
9100 labels ; matching labeled statement to break to
9101 pn)
9102 (when (eq (js2-peek-token-or-eol) js2-NAME)
9103 (js2-get-token)
9104 (setq break-label (js2-create-name-node)
9105 end (js2-node-end break-label)
9106 ;; matchJumpLabelName only matches if there is one
9107 labels (js2-match-jump-label-name (js2-current-token-string))
9108 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9109 (unless (or break-target break-label)
9110 ;; no break target specified - try for innermost enclosing loop/switch
9111 (if (null js2-loop-and-switch-set)
9112 (unless break-label
9113 (js2-report-error "msg.bad.break" nil pos (length "break")))
9114 (setq break-target (car js2-loop-and-switch-set))))
9115 (setq pn (make-js2-break-node :pos pos
9116 :len (- end pos)
9117 :label break-label
9118 :target break-target))
9119 (js2-node-add-children pn break-label) ; but not break-target
9120 pn))
9121
9122 (defun js2-parse-continue ()
9123 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9124 (let ((pos (js2-current-token-beg))
9125 (end (js2-current-token-end))
9126 label ; optional user-specified label, a `js2-name-node'
9127 labels ; current matching labeled stmt, if any
9128 target ; the `js2-loop-node' target of this continue stmt
9129 pn)
9130 (when (= (js2-peek-token-or-eol) js2-NAME)
9131 (js2-get-token)
9132 (setq label (js2-create-name-node)
9133 end (js2-node-end label)
9134 ;; matchJumpLabelName only matches if there is one
9135 labels (js2-match-jump-label-name (js2-current-token-string))))
9136 (cond
9137 ((null labels) ; no current label to go to
9138 (if (null js2-loop-set) ; no loop to continue to
9139 (js2-report-error "msg.continue.outside" nil pos
9140 (length "continue"))
9141 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9142 (t
9143 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9144 (setq target (js2-labeled-stmt-node-stmt labels))
9145 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9146 (setq pn (make-js2-continue-node :pos pos
9147 :len (- end pos)
9148 :label label
9149 :target target))
9150 (js2-node-add-children pn label) ; but not target - it's not our child
9151 pn))
9152
9153 (defun js2-parse-with ()
9154 "Parser for with-statement. Last matched token must be js2-WITH."
9155 (when js2-in-use-strict-directive
9156 (js2-report-error "msg.no.with.strict"))
9157 (let ((pos (js2-current-token-beg))
9158 obj body pn lp rp)
9159 (if (js2-must-match js2-LP "msg.no.paren.with")
9160 (setq lp (js2-current-token-beg)))
9161 (setq obj (js2-parse-expr))
9162 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9163 (setq rp (js2-current-token-beg)))
9164 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9165 (setq body (js2-parse-statement)))
9166 (setq pn (make-js2-with-node :pos pos
9167 :len (- (js2-node-end body) pos)
9168 :object obj
9169 :body body
9170 :lp (js2-relpos lp pos)
9171 :rp (js2-relpos rp pos)))
9172 (js2-node-add-children pn obj body)
9173 pn))
9174
9175 (defun js2-parse-const-var ()
9176 "Parser for var- or const-statement.
9177 Last matched token must be js2-CONST or js2-VAR."
9178 (let ((tt (js2-current-token-type))
9179 (pos (js2-current-token-beg))
9180 expr pn)
9181 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9182 pn (make-js2-expr-stmt-node :pos pos
9183 :len (- (js2-node-end expr) pos)
9184 :expr expr))
9185 (js2-node-add-children pn expr)
9186 pn))
9187
9188 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9189 (let ((pn (make-js2-expr-stmt-node :pos pos
9190 :len (js2-node-len expr)
9191 :type (if (js2-inside-function)
9192 js2-EXPR_VOID
9193 js2-EXPR_RESULT)
9194 :expr expr)))
9195 (if add-child
9196 (js2-node-add-children pn expr))
9197 pn))
9198
9199 (defun js2-parse-let-stmt ()
9200 "Parser for let-statement. Last matched token must be js2-LET."
9201 (let ((pos (js2-current-token-beg))
9202 expr pn)
9203 (if (= (js2-peek-token) js2-LP)
9204 ;; let expression in statement context
9205 (setq expr (js2-parse-let pos 'statement)
9206 pn (js2-wrap-with-expr-stmt pos expr t))
9207 ;; else we're looking at a statement like let x=6, y=7;
9208 (setf expr (js2-parse-variables js2-LET pos)
9209 pn (js2-wrap-with-expr-stmt pos expr t)
9210 (js2-node-type pn) js2-EXPR_RESULT))
9211 pn))
9212
9213 (defun js2-parse-ret-yield ()
9214 (js2-parse-return-or-yield (js2-current-token-type) nil))
9215
9216 (defconst js2-parse-return-stmt-enders
9217 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9218
9219 (defsubst js2-now-all-set (before after mask)
9220 "Return whether or not the bits in the mask have changed to all set.
9221 BEFORE is bits before change, AFTER is bits after change, and MASK is
9222 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9223 but not BEFORE."
9224 (and (/= (logand before mask) mask)
9225 (= (logand after mask) mask)))
9226
9227 (defun js2-parse-return-or-yield (tt expr-context)
9228 (let* ((pos (js2-current-token-beg))
9229 (end (js2-current-token-end))
9230 (before js2-end-flags)
9231 (inside-function (js2-inside-function))
9232 (gen-type (and inside-function (js2-function-node-generator-type
9233 js2-current-script-or-fn)))
9234 e ret name yield-star-p)
9235 (unless inside-function
9236 (js2-report-error (if (eq tt js2-RETURN)
9237 "msg.bad.return"
9238 "msg.bad.yield")))
9239 (when (and inside-function
9240 (eq gen-type 'STAR)
9241 (js2-match-token js2-MUL))
9242 (setq yield-star-p t))
9243 ;; This is ugly, but we don't want to require a semicolon.
9244 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9245 (setq e (js2-parse-expr)
9246 end (js2-node-end e)))
9247 (cond
9248 ((eq tt js2-RETURN)
9249 (js2-set-flag js2-end-flags (if (null e)
9250 js2-end-returns
9251 js2-end-returns-value))
9252 (setq ret (make-js2-return-node :pos pos
9253 :len (- end pos)
9254 :retval e))
9255 (js2-node-add-children ret e)
9256 ;; See if we need a strict mode warning.
9257 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9258 ;; more thorough and accurate than this before/after flag check.
9259 ;; E.g. if there's a finally-block that always returns, we shouldn't
9260 ;; show a warning generated by inconsistent returns in the catch blocks.
9261 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9262 ;; so we know which returns/yields to highlight, and we should get rid of
9263 ;; all the checking in `js2-parse-return-or-yield'.
9264 (if (and js2-strict-inconsistent-return-warning
9265 (js2-now-all-set before js2-end-flags
9266 (logior js2-end-returns js2-end-returns-value)))
9267 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9268 ((eq gen-type 'COMPREHENSION)
9269 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9270 ;; like SpiderMonkey does.
9271 (js2-report-error "msg.syntax" nil pos 5))
9272 (t
9273 (setq ret (make-js2-yield-node :pos pos
9274 :len (- end pos)
9275 :value e
9276 :star-p yield-star-p))
9277 (js2-node-add-children ret e)
9278 (unless expr-context
9279 (setq e ret
9280 ret (js2-wrap-with-expr-stmt pos e t))
9281 (js2-set-requires-activation)
9282 (js2-set-is-generator))))
9283 ;; see if we are mixing yields and value returns.
9284 (when (and inside-function
9285 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9286 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9287 'LEGACY))
9288 (setq name (js2-function-name js2-current-script-or-fn))
9289 (if (zerop (length name))
9290 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9291 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9292 ret))
9293
9294 (defun js2-parse-debugger ()
9295 (make-js2-keyword-node :type js2-DEBUGGER))
9296
9297 (defun js2-parse-block ()
9298 "Parser for a curly-delimited statement block.
9299 Last token matched must be `js2-LC'."
9300 (let ((pos (js2-current-token-beg))
9301 (pn (make-js2-scope)))
9302 (js2-push-scope pn)
9303 (unwind-protect
9304 (progn
9305 (js2-parse-statements pn)
9306 (js2-must-match js2-RC "msg.no.brace.block")
9307 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9308 (js2-pop-scope))
9309 pn))
9310
9311 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9312 (defun js2-parse-semi ()
9313 "Parse a statement or handle an error.
9314 Current token type is `js2-SEMI' or `js2-ERROR'."
9315 (let ((tt (js2-current-token-type)) pos len)
9316 (if (eq tt js2-SEMI)
9317 (make-js2-empty-expr-node :len 1)
9318 (setq pos (js2-current-token-beg)
9319 len (- (js2-current-token-end) pos))
9320 (js2-report-error "msg.syntax" nil pos len)
9321 (make-js2-error-node :pos pos :len len))))
9322
9323 (defun js2-parse-default-xml-namespace ()
9324 "Parse a `default xml namespace = <expr>' e4x statement."
9325 (let ((pos (js2-current-token-beg))
9326 end len expr unary)
9327 (js2-must-have-xml)
9328 (js2-set-requires-activation)
9329 (setq len (- js2-ts-cursor pos))
9330 (unless (and (js2-match-token js2-NAME)
9331 (string= (js2-current-token-string) "xml"))
9332 (js2-report-error "msg.bad.namespace" nil pos len))
9333 (unless (and (js2-match-token js2-NAME)
9334 (string= (js2-current-token-string) "namespace"))
9335 (js2-report-error "msg.bad.namespace" nil pos len))
9336 (unless (js2-match-token js2-ASSIGN)
9337 (js2-report-error "msg.bad.namespace" nil pos len))
9338 (setq expr (js2-parse-expr)
9339 end (js2-node-end expr)
9340 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9341 :pos pos
9342 :len (- end pos)
9343 :operand expr))
9344 (js2-node-add-children unary expr)
9345 (make-js2-expr-stmt-node :pos pos
9346 :len (- end pos)
9347 :expr unary)))
9348
9349 (defun js2-record-label (label bundle)
9350 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9351 (js2-get-token)
9352 (let ((name (js2-label-node-name label))
9353 labeled-stmt
9354 dup)
9355 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9356 ;; flag both labels if possible when used in editing mode
9357 (if (and js2-parse-ide-mode
9358 (setq dup (js2-get-label-by-name labeled-stmt name)))
9359 (js2-report-error "msg.dup.label" nil
9360 (js2-node-abs-pos dup) (js2-node-len dup)))
9361 (js2-report-error "msg.dup.label" nil
9362 (js2-node-pos label) (js2-node-len label)))
9363 (js2-labeled-stmt-node-add-label bundle label)
9364 (js2-node-add-children bundle label)
9365 ;; Add one reference to the bundle per label in `js2-label-set'
9366 (push (cons name bundle) js2-label-set)))
9367
9368 (defun js2-parse-name-or-label ()
9369 "Parser for identifier or label. Last token matched must be js2-NAME.
9370 Called when we found a name in a statement context. If it's a label, we gather
9371 up any following labels and the next non-label statement into a
9372 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9373 expression and return it wrapped in a `js2-expr-stmt-node'."
9374 (let ((pos (js2-current-token-beg))
9375 expr stmt bundle
9376 (continue t))
9377 ;; set check for label and call down to `js2-parse-primary-expr'
9378 (setq expr (js2-maybe-parse-label))
9379 (if (null expr)
9380 ;; Parse the non-label expression and wrap with expression stmt.
9381 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9382 ;; else parsed a label
9383 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9384 (js2-record-label expr bundle)
9385 ;; look for more labels
9386 (while (and continue (= (js2-get-token) js2-NAME))
9387 (if (setq expr (js2-maybe-parse-label))
9388 (js2-record-label expr bundle)
9389 (setq expr (js2-parse-expr)
9390 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9391 continue nil)
9392 (js2-auto-insert-semicolon stmt)))
9393 ;; no more labels; now parse the labeled statement
9394 (unwind-protect
9395 (unless stmt
9396 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9397 (js2-unget-token)
9398 (setq stmt (js2-statement-helper))))
9399 ;; remove the labels for this statement from the global set
9400 (dolist (label (js2-labeled-stmt-node-labels bundle))
9401 (setq js2-label-set (remove label js2-label-set))))
9402 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9403 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9404 (js2-node-add-children bundle stmt)
9405 bundle)))
9406
9407 (defun js2-maybe-parse-label ()
9408 (cl-assert (= (js2-current-token-type) js2-NAME))
9409 (let (label-pos
9410 (next-tt (js2-get-token))
9411 (label-end (js2-current-token-end)))
9412 ;; Do not consume colon, it is used as unwind indicator
9413 ;; to return to statementHelper.
9414 (js2-unget-token)
9415 (if (= next-tt js2-COLON)
9416 (prog2
9417 (setq label-pos (js2-current-token-beg))
9418 (make-js2-label-node :pos label-pos
9419 :len (- label-end label-pos)
9420 :name (js2-current-token-string))
9421 (js2-set-face label-pos
9422 label-end
9423 'font-lock-variable-name-face 'record))
9424 ;; Backtrack from the name token, too.
9425 (js2-unget-token)
9426 nil)))
9427
9428 (defun js2-parse-expr-stmt ()
9429 "Default parser in statement context, if no recognized statement found."
9430 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9431 (progn
9432 (js2-unget-token)
9433 (js2-parse-expr)) t))
9434
9435 (defun js2-parse-variables (decl-type pos)
9436 "Parse a comma-separated list of variable declarations.
9437 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9438
9439 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9440 For 'var' or 'const', the keyword should be the token last scanned.
9441
9442 POS is the position where the node should start. It's sometimes the
9443 var/const/let keyword, and other times the beginning of the first token
9444 in the first variable declaration.
9445
9446 Returns the parsed `js2-var-decl-node' expression node."
9447 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9448 :pos pos))
9449 destructuring kid-pos tt init name end nbeg nend vi
9450 (continue t))
9451 ;; Example:
9452 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9453 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9454 ;; var {a, b} = baz;
9455 (while continue
9456 (setq destructuring nil
9457 name nil
9458 tt (js2-get-token)
9459 kid-pos (js2-current-token-beg)
9460 end (js2-current-token-end)
9461 init nil)
9462 (if (or (= tt js2-LB) (= tt js2-LC))
9463 ;; Destructuring assignment, e.g., var [a, b] = ...
9464 (setq destructuring (js2-parse-destruct-primary-expr)
9465 end (js2-node-end destructuring))
9466 ;; Simple variable name
9467 (js2-unget-token)
9468 (when (js2-must-match-name "msg.bad.var")
9469 (setq name (js2-create-name-node)
9470 nbeg (js2-current-token-beg)
9471 nend (js2-current-token-end)
9472 end nend)
9473 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9474 (js2-check-strict-identifier name)))
9475 (when (js2-match-token js2-ASSIGN)
9476 (setq init (js2-parse-assign-expr)
9477 end (js2-node-end init))
9478 (js2-record-imenu-functions init name))
9479 (when name
9480 (js2-set-face nbeg nend (if (js2-function-node-p init)
9481 'font-lock-function-name-face
9482 'font-lock-variable-name-face)
9483 'record))
9484 (setq vi (make-js2-var-init-node :pos kid-pos
9485 :len (- end kid-pos)
9486 :type decl-type))
9487 (if destructuring
9488 (progn
9489 (if (and (null init) (not js2-in-for-init))
9490 (js2-report-error "msg.destruct.assign.no.init"))
9491 (js2-define-destruct-symbols destructuring
9492 decl-type
9493 'font-lock-variable-name-face)
9494 (setf (js2-var-init-node-target vi) destructuring))
9495 (setf (js2-var-init-node-target vi) name))
9496 (setf (js2-var-init-node-initializer vi) init)
9497 (js2-node-add-children vi name destructuring init)
9498 (js2-block-node-push result vi)
9499 (unless (js2-match-token js2-COMMA)
9500 (setq continue nil)))
9501 (setf (js2-node-len result) (- end pos))
9502 result))
9503
9504 (defun js2-parse-let (pos &optional stmt-p)
9505 "Parse a let expression or statement.
9506 A let-expression is of the form `let (vars) expr'.
9507 A let-statement is of the form `let (vars) {statements}'.
9508 The third form of let is a variable declaration list, handled
9509 by `js2-parse-variables'."
9510 (let ((pn (make-js2-let-node :pos pos))
9511 beg vars body)
9512 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9513 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9514 (js2-push-scope pn)
9515 (unwind-protect
9516 (progn
9517 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9518 (if (js2-must-match js2-RP "msg.no.paren.let")
9519 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9520 (if (and stmt-p (js2-match-token js2-LC))
9521 ;; let statement
9522 (progn
9523 (setf beg (js2-current-token-beg) ; position stmt at LC
9524 body (js2-parse-statements))
9525 (js2-must-match js2-RC "msg.no.curly.let")
9526 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9527 (js2-node-len pn) (- (js2-current-token-end) pos)
9528 (js2-let-node-body pn) body
9529 (js2-node-type pn) js2-LET))
9530 ;; let expression
9531 (setf body (js2-parse-expr)
9532 (js2-node-len pn) (- (js2-node-end body) pos)
9533 (js2-let-node-body pn) body))
9534 (setf (js2-let-node-vars pn) vars)
9535 (js2-node-add-children pn vars body))
9536 (js2-pop-scope))
9537 pn))
9538
9539 (defun js2-define-new-symbol (decl-type name node &optional scope)
9540 (js2-scope-put-symbol (or scope js2-current-scope)
9541 name
9542 (make-js2-symbol decl-type name node)))
9543
9544 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9545 "Define a symbol in the current scope.
9546 If NODE is non-nil, it is the AST node associated with the symbol."
9547 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9548 (symbol (if defining-scope
9549 (js2-scope-get-symbol defining-scope name)))
9550 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9551 (pos (if node (js2-node-abs-pos node)))
9552 (len (if node (js2-node-len node))))
9553 (cond
9554 ((and symbol ; already defined
9555 (or (if js2-in-use-strict-directive
9556 ;; two const-bound vars in this block have same name
9557 (and (= sdt js2-CONST)
9558 (eq defining-scope js2-current-scope))
9559 (or (= sdt js2-CONST) ; old version is const
9560 (= decl-type js2-CONST))) ; new version is const
9561 ;; two let-bound vars in this block have same name
9562 (and (= sdt js2-LET)
9563 (eq defining-scope js2-current-scope))))
9564 (js2-report-error
9565 (cond
9566 ((= sdt js2-CONST) "msg.const.redecl")
9567 ((= sdt js2-LET) "msg.let.redecl")
9568 ((= sdt js2-VAR) "msg.var.redecl")
9569 ((= sdt js2-FUNCTION) "msg.function.redecl")
9570 (t "msg.parm.redecl"))
9571 name pos len))
9572 ((or (= decl-type js2-LET)
9573 ;; strict mode const is scoped to the current LexicalEnvironment
9574 (and js2-in-use-strict-directive
9575 (= decl-type js2-CONST)))
9576 (if (and (= decl-type js2-LET)
9577 (not ignore-not-in-block)
9578 (or (= (js2-node-type js2-current-scope) js2-IF)
9579 (js2-loop-node-p js2-current-scope)))
9580 (js2-report-error "msg.let.decl.not.in.block")
9581 (js2-define-new-symbol decl-type name node)))
9582 ((or (= decl-type js2-VAR)
9583 (= decl-type js2-FUNCTION)
9584 ;; sloppy mode const is scoped to the current VariableEnvironment
9585 (and (not js2-in-use-strict-directive)
9586 (= decl-type js2-CONST)))
9587 (if symbol
9588 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9589 (js2-add-strict-warning "msg.var.redecl" name)
9590 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9591 (js2-add-strict-warning "msg.var.hides.arg" name)))
9592 (js2-define-new-symbol decl-type name node
9593 js2-current-script-or-fn)))
9594 ((= decl-type js2-LP)
9595 (if symbol
9596 ;; must be duplicate parameter. Second parameter hides the
9597 ;; first, so go ahead and add the second pararameter
9598 (js2-report-warning "msg.dup.parms" name))
9599 (js2-define-new-symbol decl-type name node))
9600 (t (js2-code-bug)))))
9601
9602 (defun js2-parse-paren-expr-or-generator-comp ()
9603 (let ((px-pos (js2-current-token-beg)))
9604 (cond
9605 ((and (>= js2-language-version 200)
9606 (js2-match-token js2-FOR))
9607 (js2-parse-generator-comp px-pos))
9608 ((and (>= js2-language-version 200)
9609 (js2-match-token js2-RP))
9610 ;; Not valid expression syntax, but this is valid in an arrow
9611 ;; function with no params: () => body.
9612 (if (eq (js2-peek-token) js2-ARROW)
9613 ;; Return whatever, it will hopefully be rewinded and
9614 ;; reparsed when we reach the =>.
9615 (make-js2-keyword-node :type js2-NULL)
9616 (js2-report-error "msg.syntax")
9617 (make-js2-error-node)))
9618 (t
9619 (let* ((js2-in-for-init nil)
9620 (expr (js2-parse-expr))
9621 (pn (make-js2-paren-node :pos px-pos
9622 :expr expr)))
9623 (js2-node-add-children pn (js2-paren-node-expr pn))
9624 (js2-must-match js2-RP "msg.no.paren")
9625 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9626 pn)))))
9627
9628 (defun js2-parse-expr (&optional oneshot)
9629 (let* ((pn (js2-parse-assign-expr))
9630 (pos (js2-node-pos pn))
9631 left
9632 right
9633 op-pos)
9634 (while (and (not oneshot)
9635 (js2-match-token js2-COMMA))
9636 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9637 (if (= (js2-peek-token) js2-YIELD)
9638 (js2-report-error "msg.yield.parenthesized"))
9639 (setq right (js2-parse-assign-expr)
9640 left pn
9641 pn (make-js2-infix-node :type js2-COMMA
9642 :pos pos
9643 :len (- js2-ts-cursor pos)
9644 :op-pos op-pos
9645 :left left
9646 :right right))
9647 (js2-node-add-children pn left right))
9648 pn))
9649
9650 (defun js2-parse-assign-expr ()
9651 (let ((tt (js2-get-token))
9652 (pos (js2-current-token-beg))
9653 pn left right op-pos
9654 ts-state recorded-identifiers parsed-errors)
9655 (if (= tt js2-YIELD)
9656 (js2-parse-return-or-yield tt t)
9657 ;; Save the tokenizer state in case we find an arrow function
9658 ;; and have to rewind.
9659 (setq ts-state (make-js2-ts-state)
9660 recorded-identifiers js2-recorded-identifiers
9661 parsed-errors js2-parsed-errors)
9662 ;; not yield - parse assignment expression
9663 (setq pn (js2-parse-cond-expr)
9664 tt (js2-get-token))
9665 (cond
9666 ((and (<= js2-first-assign tt)
9667 (<= tt js2-last-assign))
9668 ;; tt express assignment (=, |=, ^=, ..., %=)
9669 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9670 left pn)
9671 ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
9672 ;; care about assignment to strict variable names.
9673 (when (js2-name-node-p left)
9674 (js2-check-strict-identifier left))
9675 (setq right (js2-parse-assign-expr)
9676 pn (make-js2-assign-node :type tt
9677 :pos pos
9678 :len (- (js2-node-end right) pos)
9679 :op-pos op-pos
9680 :left left
9681 :right right))
9682 (when js2-parse-ide-mode
9683 (js2-highlight-assign-targets pn left right)
9684 (js2-record-imenu-functions right left))
9685 ;; do this last so ide checks above can use absolute positions
9686 (js2-node-add-children pn left right))
9687 ((and (= tt js2-ARROW)
9688 (>= js2-language-version 200))
9689 (js2-ts-seek ts-state)
9690 (setq js2-recorded-identifiers recorded-identifiers
9691 js2-parsed-errors parsed-errors)
9692 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9693 (t
9694 (js2-unget-token)))
9695 pn)))
9696
9697 (defun js2-parse-cond-expr ()
9698 (let ((pos (js2-current-token-beg))
9699 (pn (js2-parse-or-expr))
9700 test-expr
9701 if-true
9702 if-false
9703 q-pos
9704 c-pos)
9705 (when (js2-match-token js2-HOOK)
9706 (setq q-pos (- (js2-current-token-beg) pos)
9707 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9708 (js2-must-match js2-COLON "msg.no.colon.cond")
9709 (setq c-pos (- (js2-current-token-beg) pos)
9710 if-false (js2-parse-assign-expr)
9711 test-expr pn
9712 pn (make-js2-cond-node :pos pos
9713 :len (- (js2-node-end if-false) pos)
9714 :test-expr test-expr
9715 :true-expr if-true
9716 :false-expr if-false
9717 :q-pos q-pos
9718 :c-pos c-pos))
9719 (js2-node-add-children pn test-expr if-true if-false))
9720 pn))
9721
9722 (defun js2-make-binary (type left parser)
9723 "Helper for constructing a binary-operator AST node.
9724 LEFT is the left-side-expression, already parsed, and the
9725 binary operator should have just been matched.
9726 PARSER is a function to call to parse the right operand,
9727 or a `js2-node' struct if it has already been parsed.
9728 FIXME: The latter option is unused?"
9729 (let* ((pos (js2-node-pos left))
9730 (op-pos (- (js2-current-token-beg) pos))
9731 (right (if (js2-node-p parser)
9732 parser
9733 (js2-get-token)
9734 (funcall parser)))
9735 (pn (make-js2-infix-node :type type
9736 :pos pos
9737 :len (- (js2-node-end right) pos)
9738 :op-pos op-pos
9739 :left left
9740 :right right)))
9741 (js2-node-add-children pn left right)
9742 pn))
9743
9744 (defun js2-parse-or-expr ()
9745 (let ((pn (js2-parse-and-expr)))
9746 (when (js2-match-token js2-OR)
9747 (setq pn (js2-make-binary js2-OR
9748 pn
9749 'js2-parse-or-expr)))
9750 pn))
9751
9752 (defun js2-parse-and-expr ()
9753 (let ((pn (js2-parse-bit-or-expr)))
9754 (when (js2-match-token js2-AND)
9755 (setq pn (js2-make-binary js2-AND
9756 pn
9757 'js2-parse-and-expr)))
9758 pn))
9759
9760 (defun js2-parse-bit-or-expr ()
9761 (let ((pn (js2-parse-bit-xor-expr)))
9762 (while (js2-match-token js2-BITOR)
9763 (setq pn (js2-make-binary js2-BITOR
9764 pn
9765 'js2-parse-bit-xor-expr)))
9766 pn))
9767
9768 (defun js2-parse-bit-xor-expr ()
9769 (let ((pn (js2-parse-bit-and-expr)))
9770 (while (js2-match-token js2-BITXOR)
9771 (setq pn (js2-make-binary js2-BITXOR
9772 pn
9773 'js2-parse-bit-and-expr)))
9774 pn))
9775
9776 (defun js2-parse-bit-and-expr ()
9777 (let ((pn (js2-parse-eq-expr)))
9778 (while (js2-match-token js2-BITAND)
9779 (setq pn (js2-make-binary js2-BITAND
9780 pn
9781 'js2-parse-eq-expr)))
9782 pn))
9783
9784 (defconst js2-parse-eq-ops
9785 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9786
9787 (defun js2-parse-eq-expr ()
9788 (let ((pn (js2-parse-rel-expr))
9789 tt)
9790 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9791 (setq pn (js2-make-binary tt
9792 pn
9793 'js2-parse-rel-expr)))
9794 (js2-unget-token)
9795 pn))
9796
9797 (defconst js2-parse-rel-ops
9798 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9799
9800 (defun js2-parse-rel-expr ()
9801 (let ((pn (js2-parse-shift-expr))
9802 (continue t)
9803 tt)
9804 (while continue
9805 (setq tt (js2-get-token))
9806 (cond
9807 ((and js2-in-for-init (= tt js2-IN))
9808 (js2-unget-token)
9809 (setq continue nil))
9810 ((memq tt js2-parse-rel-ops)
9811 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9812 (t
9813 (js2-unget-token)
9814 (setq continue nil))))
9815 pn))
9816
9817 (defconst js2-parse-shift-ops
9818 (list js2-LSH js2-URSH js2-RSH))
9819
9820 (defun js2-parse-shift-expr ()
9821 (let ((pn (js2-parse-add-expr))
9822 tt
9823 (continue t))
9824 (while continue
9825 (setq tt (js2-get-token))
9826 (if (memq tt js2-parse-shift-ops)
9827 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9828 (js2-unget-token)
9829 (setq continue nil)))
9830 pn))
9831
9832 (defun js2-parse-add-expr ()
9833 (let ((pn (js2-parse-mul-expr))
9834 tt
9835 (continue t))
9836 (while continue
9837 (setq tt (js2-get-token))
9838 (if (or (= tt js2-ADD) (= tt js2-SUB))
9839 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9840 (js2-unget-token)
9841 (setq continue nil)))
9842 pn))
9843
9844 (defconst js2-parse-mul-ops
9845 (list js2-MUL js2-DIV js2-MOD))
9846
9847 (defun js2-parse-mul-expr ()
9848 (let ((pn (js2-parse-unary-expr))
9849 tt
9850 (continue t))
9851 (while continue
9852 (setq tt (js2-get-token))
9853 (if (memq tt js2-parse-mul-ops)
9854 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9855 (js2-unget-token)
9856 (setq continue nil)))
9857 pn))
9858
9859 (defun js2-make-unary (type parser &rest args)
9860 "Make a unary node of type TYPE.
9861 PARSER is either a node (for postfix operators) or a function to call
9862 to parse the operand (for prefix operators)."
9863 (let* ((pos (js2-current-token-beg))
9864 (postfix (js2-node-p parser))
9865 (expr (if postfix
9866 parser
9867 (apply parser args)))
9868 end
9869 pn)
9870 (if postfix ; e.g. i++
9871 (setq pos (js2-node-pos expr)
9872 end (js2-current-token-end))
9873 (setq end (js2-node-end expr)))
9874 (setq pn (make-js2-unary-node :type type
9875 :pos pos
9876 :len (- end pos)
9877 :operand expr))
9878 (js2-node-add-children pn expr)
9879 pn))
9880
9881 (defconst js2-incrementable-node-types
9882 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9883 "Node types that can be the operand of a ++ or -- operator.")
9884
9885 (defun js2-check-bad-inc-dec (tt beg end unary)
9886 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9887 js2-incrementable-node-types)
9888 (js2-report-error (if (= tt js2-INC)
9889 "msg.bad.incr"
9890 "msg.bad.decr")
9891 nil beg (- end beg))))
9892
9893 (defun js2-parse-unary-expr ()
9894 (let ((tt (js2-current-token-type))
9895 pn expr beg end)
9896 (cond
9897 ((or (= tt js2-VOID)
9898 (= tt js2-NOT)
9899 (= tt js2-BITNOT)
9900 (= tt js2-TYPEOF))
9901 (js2-get-token)
9902 (js2-make-unary tt 'js2-parse-unary-expr))
9903 ((= tt js2-ADD)
9904 (js2-get-token)
9905 ;; Convert to special POS token in decompiler and parse tree
9906 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9907 ((= tt js2-SUB)
9908 (js2-get-token)
9909 ;; Convert to special NEG token in decompiler and parse tree
9910 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9911 ((or (= tt js2-INC)
9912 (= tt js2-DEC))
9913 (js2-get-token)
9914 (prog1
9915 (setq beg (js2-current-token-beg)
9916 end (js2-current-token-end)
9917 expr (js2-make-unary tt 'js2-parse-member-expr t))
9918 (js2-check-bad-inc-dec tt beg end expr)))
9919 ((= tt js2-DELPROP)
9920 (js2-get-token)
9921 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9922 ((= tt js2-ERROR)
9923 (js2-get-token)
9924 (make-js2-error-node)) ; try to continue
9925 ((and (= tt js2-LT)
9926 js2-compiler-xml-available)
9927 ;; XML stream encountered in expression.
9928 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9929 (t
9930 (setq pn (js2-parse-member-expr t)
9931 ;; Don't look across a newline boundary for a postfix incop.
9932 tt (js2-peek-token-or-eol))
9933 (when (or (= tt js2-INC) (= tt js2-DEC))
9934 (js2-get-token)
9935 (setf expr pn
9936 pn (js2-make-unary tt expr))
9937 (js2-node-set-prop pn 'postfix t)
9938 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9939 pn))))
9940
9941 (defun js2-parse-xml-initializer ()
9942 "Parse an E4X XML initializer.
9943 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9944 Then I'll postprocess the result, depending on whether we're in IDE
9945 mode or codegen mode, and generate the appropriate rewritten AST.
9946 IDE mode uses a rich AST that models the XML structure. Codegen mode
9947 just concatenates everything and makes a new XML or XMLList out of it."
9948 (let ((tt (js2-get-first-xml-token))
9949 pn-xml pn expr kids expr-pos
9950 (continue t)
9951 (first-token t))
9952 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9953 (js2-report-error "msg.syntax"))
9954 (setq pn-xml (make-js2-xml-node))
9955 (while continue
9956 (if first-token
9957 (setq first-token nil)
9958 (setq tt (js2-get-next-xml-token)))
9959 (cond
9960 ;; js2-XML means we found a {expr} in the XML stream.
9961 ;; The token string is the XML up to the left-curly.
9962 ((= tt js2-XML)
9963 (push (make-js2-string-node :pos (js2-current-token-beg)
9964 :len (- js2-ts-cursor (js2-current-token-beg)))
9965 kids)
9966 (js2-must-match js2-LC "msg.syntax")
9967 (setq expr-pos js2-ts-cursor
9968 expr (if (eq (js2-peek-token) js2-RC)
9969 (make-js2-empty-expr-node :pos expr-pos)
9970 (js2-parse-expr)))
9971 (js2-must-match js2-RC "msg.syntax")
9972 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9973 :len (js2-node-len expr)
9974 :expr expr))
9975 (js2-node-add-children pn expr)
9976 (push pn kids))
9977 ;; a js2-XMLEND token means we hit the final close-tag.
9978 ((= tt js2-XMLEND)
9979 (push (make-js2-string-node :pos (js2-current-token-beg)
9980 :len (- js2-ts-cursor (js2-current-token-beg)))
9981 kids)
9982 (dolist (kid (nreverse kids))
9983 (js2-block-node-push pn-xml kid))
9984 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9985 (js2-node-pos pn-xml))
9986 continue nil))
9987 (t
9988 (js2-report-error "msg.syntax")
9989 (setq continue nil))))
9990 pn-xml))
9991
9992
9993 (defun js2-parse-argument-list ()
9994 "Parse an argument list and return it as a Lisp list of nodes.
9995 Returns the list in reverse order. Consumes the right-paren token."
9996 (let (result)
9997 (unless (js2-match-token js2-RP)
9998 (cl-loop do
9999 (let ((tt (js2-get-token)))
10000 (if (= tt js2-YIELD)
10001 (js2-report-error "msg.yield.parenthesized"))
10002 (if (and (= tt js2-TRIPLEDOT)
10003 (>= js2-language-version 200))
10004 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
10005 (js2-unget-token)
10006 (push (js2-parse-assign-expr) result)))
10007 while
10008 (js2-match-token js2-COMMA))
10009 (js2-must-match js2-RP "msg.no.paren.arg")
10010 result)))
10011
10012 (defun js2-parse-member-expr (&optional allow-call-syntax)
10013 (let ((tt (js2-current-token-type))
10014 pn pos target args beg end init)
10015 (if (/= tt js2-NEW)
10016 (setq pn (js2-parse-primary-expr))
10017 ;; parse a 'new' expression
10018 (js2-get-token)
10019 (setq pos (js2-current-token-beg)
10020 beg pos
10021 target (js2-parse-member-expr)
10022 end (js2-node-end target)
10023 pn (make-js2-new-node :pos pos
10024 :target target
10025 :len (- end pos)))
10026 (js2-highlight-function-call (js2-current-token))
10027 (js2-node-add-children pn target)
10028 (when (js2-match-token js2-LP)
10029 ;; Add the arguments to pn, if any are supplied.
10030 (setf beg pos ; start of "new" keyword
10031 pos (js2-current-token-beg)
10032 args (nreverse (js2-parse-argument-list))
10033 (js2-new-node-args pn) args
10034 end (js2-current-token-end)
10035 (js2-new-node-lp pn) (- pos beg)
10036 (js2-new-node-rp pn) (- end 1 beg))
10037 (apply #'js2-node-add-children pn args))
10038 (when (and js2-allow-rhino-new-expr-initializer
10039 (js2-match-token js2-LC))
10040 (setf init (js2-parse-object-literal)
10041 end (js2-node-end init)
10042 (js2-new-node-initializer pn) init)
10043 (js2-node-add-children pn init))
10044 (setf (js2-node-len pn) (- end beg))) ; end outer if
10045 (js2-parse-member-expr-tail allow-call-syntax pn)))
10046
10047 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
10048 "Parse a chain of property/array accesses or function calls.
10049 Includes parsing for E4X operators like `..' and `.@'.
10050 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
10051 Returns an expression tree that includes PN, the parent node."
10052 (let (tt
10053 (continue t))
10054 (while continue
10055 (setq tt (js2-get-token))
10056 (cond
10057 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
10058 (setq pn (js2-parse-property-access tt pn)))
10059 ((= tt js2-DOTQUERY)
10060 (setq pn (js2-parse-dot-query pn)))
10061 ((= tt js2-LB)
10062 (setq pn (js2-parse-element-get pn)))
10063 ((= tt js2-LP)
10064 (js2-unget-token)
10065 (if allow-call-syntax
10066 (setq pn (js2-parse-function-call pn))
10067 (setq continue nil)))
10068 ((= tt js2-TEMPLATE_HEAD)
10069 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
10070 ((= tt js2-NO_SUBS_TEMPLATE)
10071 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
10072 (t
10073 (js2-unget-token)
10074 (setq continue nil))))
10075 (if (>= js2-highlight-level 2)
10076 (js2-parse-highlight-member-expr-node pn))
10077 pn))
10078
10079 (defun js2-parse-tagged-template (tag-node tpl-node)
10080 "Parse tagged template expression."
10081 (let* ((beg (js2-node-pos tag-node))
10082 (pn (make-js2-tagged-template-node :beg beg
10083 :len (- (js2-current-token-end) beg)
10084 :tag tag-node
10085 :template tpl-node)))
10086 (js2-node-add-children pn tag-node tpl-node)
10087 pn))
10088
10089 (defun js2-parse-dot-query (pn)
10090 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10091 Last token parsed must be `js2-DOTQUERY'."
10092 (let ((pos (js2-node-pos pn))
10093 op-pos expr end)
10094 (js2-must-have-xml)
10095 (js2-set-requires-activation)
10096 (setq op-pos (js2-current-token-beg)
10097 expr (js2-parse-expr)
10098 end (js2-node-end expr)
10099 pn (make-js2-xml-dot-query-node :left pn
10100 :pos pos
10101 :op-pos op-pos
10102 :right expr))
10103 (js2-node-add-children pn
10104 (js2-xml-dot-query-node-left pn)
10105 (js2-xml-dot-query-node-right pn))
10106 (if (js2-must-match js2-RP "msg.no.paren")
10107 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10108 end (js2-current-token-end)))
10109 (setf (js2-node-len pn) (- end pos))
10110 pn))
10111
10112 (defun js2-parse-element-get (pn)
10113 "Parse an element-get expression, e.g. foo[bar].
10114 Last token parsed must be `js2-RB'."
10115 (let ((lb (js2-current-token-beg))
10116 (pos (js2-node-pos pn))
10117 rb expr)
10118 (setq expr (js2-parse-expr))
10119 (if (js2-must-match js2-RB "msg.no.bracket.index")
10120 (setq rb (js2-current-token-beg)))
10121 (setq pn (make-js2-elem-get-node :target pn
10122 :pos pos
10123 :element expr
10124 :lb (js2-relpos lb pos)
10125 :rb (js2-relpos rb pos)
10126 :len (- (js2-current-token-end) pos)))
10127 (js2-node-add-children pn
10128 (js2-elem-get-node-target pn)
10129 (js2-elem-get-node-element pn))
10130 pn))
10131
10132 (defun js2-highlight-function-call (token)
10133 (when (eq (js2-token-type token) js2-NAME)
10134 (js2-record-face 'js2-function-call token)))
10135
10136 (defun js2-parse-function-call (pn)
10137 (js2-highlight-function-call (js2-current-token))
10138 (js2-get-token)
10139 (let (args
10140 (pos (js2-node-pos pn)))
10141 (setq pn (make-js2-call-node :pos pos
10142 :target pn
10143 :lp (- (js2-current-token-beg) pos)))
10144 (js2-node-add-children pn (js2-call-node-target pn))
10145 ;; Add the arguments to pn, if any are supplied.
10146 (setf args (nreverse (js2-parse-argument-list))
10147 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10148 (js2-call-node-args pn) args)
10149 (apply #'js2-node-add-children pn args)
10150 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10151 pn))
10152
10153 (defun js2-parse-property-access (tt pn)
10154 "Parse a property access, XML descendants access, or XML attr access."
10155 (let ((member-type-flags 0)
10156 (dot-pos (js2-current-token-beg))
10157 (dot-len (if (= tt js2-DOTDOT) 2 1))
10158 name
10159 ref ; right side of . or .. operator
10160 result)
10161 (when (= tt js2-DOTDOT)
10162 (js2-must-have-xml)
10163 (setq member-type-flags js2-descendants-flag))
10164 (if (not js2-compiler-xml-available)
10165 (progn
10166 (js2-must-match-prop-name "msg.no.name.after.dot")
10167 (setq name (js2-create-name-node t js2-GETPROP)
10168 result (make-js2-prop-get-node :left pn
10169 :pos (js2-current-token-beg)
10170 :right name
10171 :len (js2-current-token-len)))
10172 (js2-node-add-children result pn name)
10173 result)
10174 ;; otherwise look for XML operators
10175 (setf result (if (= tt js2-DOT)
10176 (make-js2-prop-get-node)
10177 (make-js2-infix-node :type js2-DOTDOT))
10178 (js2-node-pos result) (js2-node-pos pn)
10179 (js2-infix-node-op-pos result) dot-pos
10180 (js2-infix-node-left result) pn ; do this after setting position
10181 tt (js2-get-prop-name-token))
10182 (cond
10183 ;; handles: name, ns::name, ns::*, ns::[expr]
10184 ((= tt js2-NAME)
10185 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10186 ;; handles: *, *::name, *::*, *::[expr]
10187 ((= tt js2-MUL)
10188 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10189 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10190 ((= tt js2-XMLATTR)
10191 (setq result (js2-parse-attribute-access)))
10192 (t
10193 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10194 (if ref
10195 (setf (js2-node-len result) (- (js2-node-end ref)
10196 (js2-node-pos result))
10197 (js2-infix-node-right result) ref))
10198 (if (js2-infix-node-p result)
10199 (js2-node-add-children result
10200 (js2-infix-node-left result)
10201 (js2-infix-node-right result)))
10202 result)))
10203
10204 (defun js2-parse-attribute-access ()
10205 "Parse an E4X XML attribute expression.
10206 This includes expressions of the forms:
10207
10208 @attr @ns::attr @ns::*
10209 @* @*::attr @*::*
10210 @[expr] @*::[expr] @ns::[expr]
10211
10212 Called if we peeked an '@' token."
10213 (let ((tt (js2-get-prop-name-token))
10214 (at-pos (js2-current-token-beg)))
10215 (cond
10216 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10217 ((= tt js2-NAME)
10218 (js2-parse-property-name at-pos nil 0))
10219 ;; handles: @*, @*::name, @*::*, @*::[expr]
10220 ((= tt js2-MUL)
10221 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10222 ;; handles @[expr]
10223 ((= tt js2-LB)
10224 (js2-parse-xml-elem-ref at-pos))
10225 (t
10226 (js2-report-error "msg.no.name.after.xmlAttr")
10227 ;; Avoid cascaded errors that happen if we make an error node here.
10228 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10229
10230 (defun js2-parse-property-name (at-pos s member-type-flags)
10231 "Check if :: follows name in which case it becomes qualified name.
10232
10233 AT-POS is a natural number if we just read an '@' token, else nil.
10234 S is the name or string that was matched: an identifier, 'throw' or '*'.
10235 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10236
10237 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10238 operator, or the name is followed by ::. For a plain name, returns a
10239 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10240 (let ((pos (or at-pos (js2-current-token-beg)))
10241 colon-pos
10242 (name (js2-create-name-node t (js2-current-token-type) s))
10243 ns tt pn)
10244 (catch 'return
10245 (when (js2-match-token js2-COLONCOLON)
10246 (setq ns name
10247 colon-pos (js2-current-token-beg)
10248 tt (js2-get-prop-name-token))
10249 (cond
10250 ;; handles name::name
10251 ((= tt js2-NAME)
10252 (setq name (js2-create-name-node)))
10253 ;; handles name::*
10254 ((= tt js2-MUL)
10255 (setq name (js2-create-name-node nil nil "*")))
10256 ;; handles name::[expr]
10257 ((= tt js2-LB)
10258 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10259 (t
10260 (js2-report-error "msg.no.name.after.coloncolon"))))
10261 (if (and (null ns) (zerop member-type-flags))
10262 name
10263 (prog1
10264 (setq pn
10265 (make-js2-xml-prop-ref-node :pos pos
10266 :len (- (js2-node-end name) pos)
10267 :at-pos at-pos
10268 :colon-pos colon-pos
10269 :propname name))
10270 (js2-node-add-children pn name))))))
10271
10272 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10273 "Parse the [expr] portion of an xml element reference.
10274 For instance, @[expr], @*::[expr], or ns::[expr]."
10275 (let* ((lb (js2-current-token-beg))
10276 (pos (or at-pos lb))
10277 rb
10278 (expr (js2-parse-expr))
10279 (end (js2-node-end expr))
10280 pn)
10281 (if (js2-must-match js2-RB "msg.no.bracket.index")
10282 (setq rb (js2-current-token-beg)
10283 end (js2-current-token-end)))
10284 (prog1
10285 (setq pn
10286 (make-js2-xml-elem-ref-node :pos pos
10287 :len (- end pos)
10288 :namespace namespace
10289 :colon-pos colon-pos
10290 :at-pos at-pos
10291 :expr expr
10292 :lb (js2-relpos lb pos)
10293 :rb (js2-relpos rb pos)))
10294 (js2-node-add-children pn namespace expr))))
10295
10296 (defun js2-parse-destruct-primary-expr ()
10297 (let ((js2-is-in-destructuring t))
10298 (js2-parse-primary-expr)))
10299
10300 (defun js2-parse-primary-expr ()
10301 "Parse a literal (leaf) expression of some sort.
10302 Includes complex literals such as functions, object-literals,
10303 array-literals, array comprehensions and regular expressions."
10304 (let (tt node)
10305 (setq tt (js2-current-token-type))
10306 (cond
10307 ((= tt js2-CLASS)
10308 (js2-parse-class-expr))
10309 ((= tt js2-FUNCTION)
10310 (js2-parse-function-expr))
10311 ((= tt js2-LB)
10312 (js2-parse-array-comp-or-literal))
10313 ((= tt js2-LC)
10314 (js2-parse-object-literal))
10315 ((= tt js2-LET)
10316 (js2-parse-let (js2-current-token-beg)))
10317 ((= tt js2-LP)
10318 (js2-parse-paren-expr-or-generator-comp))
10319 ((= tt js2-XMLATTR)
10320 (js2-must-have-xml)
10321 (js2-parse-attribute-access))
10322 ((= tt js2-NAME)
10323 (js2-parse-name tt))
10324 ((= tt js2-NUMBER)
10325 (setq node (make-js2-number-node))
10326 (when (and js2-in-use-strict-directive
10327 (= (js2-number-node-num-base node) 8))
10328 (js2-report-error "msg.no.octal.strict"))
10329 node)
10330 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10331 (make-js2-string-node :type tt))
10332 ((= tt js2-TEMPLATE_HEAD)
10333 (js2-parse-template-literal))
10334 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10335 ;; Got / or /= which in this context means a regexp literal
10336 (let ((px-pos (js2-current-token-beg))
10337 (flags (js2-read-regexp tt))
10338 (end (js2-current-token-end)))
10339 (prog1
10340 (make-js2-regexp-node :pos px-pos
10341 :len (- end px-pos)
10342 :value (js2-current-token-string)
10343 :flags flags)
10344 (js2-set-face px-pos end 'font-lock-string-face 'record)
10345 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10346 ((or (= tt js2-NULL)
10347 (= tt js2-THIS)
10348 (= tt js2-SUPER)
10349 (= tt js2-FALSE)
10350 (= tt js2-TRUE))
10351 (make-js2-keyword-node :type tt))
10352 ((= tt js2-TRIPLEDOT)
10353 ;; Likewise, only valid in an arrow function with a rest param.
10354 (if (and (js2-match-token js2-NAME)
10355 (js2-match-token js2-RP)
10356 (eq (js2-peek-token) js2-ARROW))
10357 (progn
10358 (js2-unget-token) ; Put back the right paren.
10359 ;; See the previous case.
10360 (make-js2-keyword-node :type js2-NULL))
10361 (js2-report-error "msg.syntax")
10362 (make-js2-error-node)))
10363 ((= tt js2-RESERVED)
10364 (js2-report-error "msg.reserved.id")
10365 (make-js2-name-node))
10366 ((= tt js2-ERROR)
10367 ;; the scanner or one of its subroutines reported the error.
10368 (make-js2-error-node))
10369 ((= tt js2-EOF)
10370 (let* ((px-pos (point-at-bol))
10371 (len (- js2-ts-cursor px-pos)))
10372 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10373 (make-js2-error-node :pos (1- js2-ts-cursor)))
10374 (t
10375 (js2-report-error "msg.syntax")
10376 (make-js2-error-node)))))
10377
10378 (defun js2-parse-template-literal ()
10379 (let ((beg (js2-current-token-beg))
10380 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10381 (tt js2-TEMPLATE_HEAD))
10382 (while (eq tt js2-TEMPLATE_HEAD)
10383 (push (js2-parse-expr) kids)
10384 (js2-must-match js2-RC "msg.syntax")
10385 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10386 (push (make-js2-string-node :type tt) kids))
10387 (setq kids (nreverse kids))
10388 (let ((tpl (make-js2-template-node :beg beg
10389 :len (- (js2-current-token-end) beg)
10390 :kids kids)))
10391 (apply #'js2-node-add-children tpl kids)
10392 tpl)))
10393
10394 (defun js2-parse-name (_tt)
10395 (let ((name (js2-current-token-string))
10396 node)
10397 (setq node (if js2-compiler-xml-available
10398 (js2-parse-property-name nil name 0)
10399 (js2-create-name-node 'check-activation nil name)))
10400 (if js2-highlight-external-variables
10401 (js2-record-name-node node))
10402 node))
10403
10404 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10405 (js2-add-strict-warning
10406 msg nil
10407 ;; back up from comma to beginning of line or array/objlit
10408 (max (if elems
10409 (js2-node-pos (car elems))
10410 pos)
10411 (save-excursion
10412 (goto-char comma-pos)
10413 (back-to-indentation)
10414 (point)))
10415 comma-pos))
10416
10417 (defun js2-parse-array-comp-or-literal ()
10418 (let ((pos (js2-current-token-beg)))
10419 (if (and (>= js2-language-version 200)
10420 (js2-match-token js2-FOR))
10421 (js2-parse-array-comp pos)
10422 (js2-parse-array-literal pos))))
10423
10424 (defun js2-parse-array-literal (pos)
10425 (let ((after-lb-or-comma t)
10426 after-comma tt elems pn
10427 (continue t))
10428 (unless js2-is-in-destructuring
10429 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10430 (while continue
10431 (setq tt (js2-get-token))
10432 (cond
10433 ;; comma
10434 ((= tt js2-COMMA)
10435 (setq after-comma (js2-current-token-end))
10436 (if (not after-lb-or-comma)
10437 (setq after-lb-or-comma t)
10438 (push nil elems)))
10439 ;; end of array
10440 ((or (= tt js2-RB)
10441 (= tt js2-EOF)) ; prevent infinite loop
10442 (if (= tt js2-EOF)
10443 (js2-report-error "msg.no.bracket.arg" nil pos))
10444 (when (and after-comma (< js2-language-version 170))
10445 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10446 pos (remove nil elems) after-comma))
10447 (setq continue nil
10448 pn (make-js2-array-node :pos pos
10449 :len (- js2-ts-cursor pos)
10450 :elems (nreverse elems)))
10451 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10452 ;; destructuring binding
10453 (js2-is-in-destructuring
10454 (push (if (or (= tt js2-LC)
10455 (= tt js2-LB)
10456 (= tt js2-NAME))
10457 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10458 (js2-parse-destruct-primary-expr)
10459 ;; invalid pattern
10460 (js2-report-error "msg.bad.var")
10461 (make-js2-error-node))
10462 elems)
10463 (setq after-lb-or-comma nil
10464 after-comma nil))
10465 ;; array comp
10466 ((and (>= js2-language-version 170)
10467 (= tt js2-FOR) ; check for array comprehension
10468 (not after-lb-or-comma) ; "for" can't follow a comma
10469 elems ; must have at least 1 element
10470 (not (cdr elems))) ; but no 2nd element
10471 (js2-unget-token)
10472 (setf continue nil
10473 pn (js2-parse-legacy-array-comp (car elems) pos)))
10474 ;; another element
10475 (t
10476 (unless after-lb-or-comma
10477 (js2-report-error "msg.no.bracket.arg"))
10478 (if (and (= tt js2-TRIPLEDOT)
10479 (>= js2-language-version 200))
10480 ;; spread operator
10481 (push (js2-make-unary tt 'js2-parse-assign-expr)
10482 elems)
10483 (js2-unget-token)
10484 (push (js2-parse-assign-expr) elems))
10485 (setq after-lb-or-comma nil
10486 after-comma nil))))
10487 (unless js2-is-in-destructuring
10488 (js2-pop-scope))
10489 pn))
10490
10491 (defun js2-parse-legacy-array-comp (expr pos)
10492 "Parse a legacy array comprehension (JavaScript 1.7).
10493 EXPR is the first expression after the opening left-bracket.
10494 POS is the beginning of the LB token preceding EXPR.
10495 We should have just parsed the 'for' keyword before calling this function."
10496 (let ((current-scope js2-current-scope)
10497 loops first filter result)
10498 (unwind-protect
10499 (progn
10500 (while (js2-match-token js2-FOR)
10501 (let ((loop (make-js2-comp-loop-node)))
10502 (js2-push-scope loop)
10503 (push loop loops)
10504 (js2-parse-comp-loop loop)))
10505 ;; First loop takes expr scope's parent.
10506 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10507 (js2-scope-parent-scope current-scope))
10508 ;; Set expr scope's parent to the last loop.
10509 (setf (js2-scope-parent-scope current-scope) (car loops))
10510 (if (/= (js2-get-token) js2-IF)
10511 (js2-unget-token)
10512 (setq filter (js2-parse-condition))))
10513 (dotimes (_ (1- (length loops)))
10514 (js2-pop-scope)))
10515 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10516 (setq result (make-js2-comp-node :pos pos
10517 :len (- js2-ts-cursor pos)
10518 :result expr
10519 :loops (nreverse loops)
10520 :filters (and filter (list (car filter)))
10521 :form 'LEGACY_ARRAY))
10522 ;; Set comp loop's parent to the last loop.
10523 ;; TODO: Get rid of the bogus expr scope.
10524 (setf (js2-scope-parent-scope result) first)
10525 (apply #'js2-node-add-children result expr (car filter)
10526 (js2-comp-node-loops result))
10527 result))
10528
10529 (defun js2-parse-array-comp (pos)
10530 "Parse an ES6 array comprehension.
10531 POS is the beginning of the LB token.
10532 We should have just parsed the 'for' keyword before calling this function."
10533 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10534 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10535 pn))
10536
10537 (defun js2-parse-generator-comp (pos)
10538 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10539 (js2-current-script-or-fn
10540 (make-js2-function-node :generator-type 'COMPREHENSION))
10541 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10542 (js2-must-match js2-RP "msg.no.paren" pos)
10543 pn))
10544
10545 (defun js2-parse-comprehension (pos form)
10546 (let (loops filters expr result last)
10547 (unwind-protect
10548 (progn
10549 (js2-unget-token)
10550 (while (js2-match-token js2-FOR)
10551 (let ((loop (make-js2-comp-loop-node)))
10552 (js2-push-scope loop)
10553 (push loop loops)
10554 (js2-parse-comp-loop loop)))
10555 (while (js2-match-token js2-IF)
10556 (push (car (js2-parse-condition)) filters))
10557 (setq expr (js2-parse-assign-expr))
10558 (setq last (car loops)))
10559 (dolist (_ loops)
10560 (js2-pop-scope)))
10561 (setq result (make-js2-comp-node :pos pos
10562 :len (- js2-ts-cursor pos)
10563 :result expr
10564 :loops (nreverse loops)
10565 :filters (nreverse filters)
10566 :form form))
10567 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10568 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10569 (setf (js2-scope-parent-scope result) last)
10570 result))
10571
10572 (defun js2-parse-comp-loop (pn &optional only-of-p)
10573 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10574 The current token should be the initial FOR.
10575 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10576 (let ((pos (js2-comp-loop-node-pos pn))
10577 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10578 (when (and (not only-of-p) (js2-match-token js2-NAME))
10579 (if (string= (js2-current-token-string) "each")
10580 (progn
10581 (setq foreach-p t
10582 each-pos (- (js2-current-token-beg) pos)) ; relative
10583 (js2-record-face 'font-lock-keyword-face))
10584 (js2-report-error "msg.no.paren.for")))
10585 (if (js2-must-match js2-LP "msg.no.paren.for")
10586 (setq lp (- (js2-current-token-beg) pos)))
10587 (setq tt (js2-peek-token))
10588 (cond
10589 ((or (= tt js2-LB)
10590 (= tt js2-LC))
10591 (js2-get-token)
10592 (setq iter (js2-parse-destruct-primary-expr))
10593 (js2-define-destruct-symbols iter js2-LET
10594 'font-lock-variable-name-face t))
10595 ((js2-match-token js2-NAME)
10596 (setq iter (js2-create-name-node)))
10597 (t
10598 (js2-report-error "msg.bad.var")))
10599 ;; Define as a let since we want the scope of the variable to
10600 ;; be restricted to the array comprehension
10601 (if (js2-name-node-p iter)
10602 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10603 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10604 (and (>= js2-language-version 200)
10605 (js2-match-contextual-kwd "of")
10606 (setq forof-p t)))
10607 (setq in-pos (- (js2-current-token-beg) pos))
10608 (js2-report-error "msg.in.after.for.name"))
10609 (setq obj (js2-parse-expr))
10610 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10611 (setq rp (- (js2-current-token-beg) pos)))
10612 (setf (js2-node-pos pn) pos
10613 (js2-node-len pn) (- js2-ts-cursor pos)
10614 (js2-comp-loop-node-iterator pn) iter
10615 (js2-comp-loop-node-object pn) obj
10616 (js2-comp-loop-node-in-pos pn) in-pos
10617 (js2-comp-loop-node-each-pos pn) each-pos
10618 (js2-comp-loop-node-foreach-p pn) foreach-p
10619 (js2-comp-loop-node-forof-p pn) forof-p
10620 (js2-comp-loop-node-lp pn) lp
10621 (js2-comp-loop-node-rp pn) rp)
10622 (js2-node-add-children pn iter obj)
10623 pn))
10624
10625 (defun js2-parse-class-stmt ()
10626 (let ((pos (js2-current-token-beg))
10627 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10628 (name (js2-create-name-node t)))
10629 (js2-set-face (js2-node-pos name) (js2-node-end name)
10630 'font-lock-function-name-face 'record)
10631 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10632 (js2-define-symbol js2-FUNCTION
10633 (js2-name-node-name name)
10634 node)
10635 node)))
10636
10637 (defun js2-parse-class-expr ()
10638 (let ((pos (js2-current-token-beg))
10639 name)
10640 (when (js2-match-token js2-NAME)
10641 (setq name (js2-create-name-node t)))
10642 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10643
10644 (defun js2-parse-class (pos form name)
10645 ;; class X [extends ...] {
10646 (let (pn elems extends)
10647 (if (js2-match-token js2-EXTENDS)
10648 (if (= (js2-peek-token) js2-LC)
10649 (js2-report-error "msg.missing.extends")
10650 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10651 (setq extends (js2-parse-assign-expr))
10652 (if (not extends)
10653 (js2-report-error "msg.bad.extends"))))
10654 (js2-must-match js2-LC "msg.no.brace.class")
10655 (setq elems (js2-parse-object-literal-elems t)
10656 pn (make-js2-class-node :pos pos
10657 :len (- js2-ts-cursor pos)
10658 :form form
10659 :name name
10660 :extends extends
10661 :elems elems))
10662 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10663 pn))
10664
10665 (defun js2-parse-object-literal ()
10666 (let* ((pos (js2-current-token-beg))
10667 (elems (js2-parse-object-literal-elems))
10668 (result (make-js2-object-node :pos pos
10669 :len (- js2-ts-cursor pos)
10670 :elems elems)))
10671 (apply #'js2-node-add-children result (js2-object-node-elems result))
10672 result))
10673
10674 (defun js2-property-key-string (property-node)
10675 "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
10676 `js2-getter-setter-node') as a string, or nil if it can't be
10677 represented as a string (e.g., the key is computed by an
10678 expression)."
10679 (let ((key (js2-infix-node-left property-node)))
10680 (cond
10681 ((js2-name-node-p key)
10682 (js2-name-node-name key))
10683 ((js2-string-node-p key)
10684 (js2-string-node-value key))
10685 ((js2-number-node-p key)
10686 (js2-number-node-value key)))))
10687
10688 (defun js2-parse-object-literal-elems (&optional class-p)
10689 (let ((pos (js2-current-token-beg))
10690 (static nil)
10691 (continue t)
10692 tt elems elem
10693 elem-key-string previous-elem-key-string
10694 after-comma previous-token)
10695 (while continue
10696 (setq tt (js2-get-prop-name-token)
10697 static nil
10698 elem nil
10699 previous-token nil)
10700 ;; Handle 'static' keyword only if we're in a class
10701 (when (and class-p (= js2-NAME tt)
10702 (string= "static" (js2-current-token-string)))
10703 (js2-record-face 'font-lock-keyword-face)
10704 (setq static t
10705 tt (js2-get-prop-name-token)))
10706 ;; Handle generator * before the property name for in-line functions
10707 (when (and (>= js2-language-version 200)
10708 (= js2-MUL tt))
10709 (setq previous-token (js2-current-token)
10710 tt (js2-get-prop-name-token)))
10711 ;; Handle 'get' or 'set' keywords
10712 (let ((prop (js2-current-token-string)))
10713 (when (and (>= js2-language-version 200)
10714 (= js2-NAME tt)
10715 (or (string= prop "get")
10716 (string= prop "set"))
10717 (member (js2-peek-token)
10718 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10719 (setq previous-token (js2-current-token)
10720 tt (js2-get-prop-name-token))))
10721 (cond
10722 ;; Found a property (of any sort)
10723 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10724 (setq after-comma nil
10725 elem (js2-parse-named-prop tt pos previous-token))
10726 (if (and (null elem)
10727 (not js2-recover-from-parse-errors))
10728 (setq continue nil)))
10729 ;; Break out of loop, and handle trailing commas.
10730 ((or (= tt js2-RC)
10731 (= tt js2-EOF))
10732 (js2-unget-token)
10733 (setq continue nil)
10734 (if after-comma
10735 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10736 pos elems after-comma)))
10737 (t
10738 (js2-report-error "msg.bad.prop")
10739 (unless js2-recover-from-parse-errors
10740 (setq continue nil)))) ; end switch
10741 ;; Handle static for classes' codegen.
10742 (if static
10743 (if elem (js2-node-set-prop elem 'STATIC t)
10744 (js2-report-error "msg.unexpected.static")))
10745 ;; Handle commas, depending on class-p.
10746 (let ((tok (js2-get-prop-name-token)))
10747 (if (eq tok js2-COMMA)
10748 (if class-p
10749 (js2-report-error "msg.class.unexpected.comma")
10750 (setq after-comma (js2-current-token-end)))
10751 (js2-unget-token)
10752 (unless class-p (setq continue nil))))
10753 (when elem
10754 (when (and js2-in-use-strict-directive
10755 (setq elem-key-string (js2-property-key-string elem))
10756 (cl-some
10757 (lambda (previous-elem)
10758 (and (setq previous-elem-key-string
10759 (js2-property-key-string previous-elem))
10760 (string= previous-elem-key-string elem-key-string)))
10761 elems))
10762 (js2-report-error "msg.dup.obj.lit.prop.strict"
10763 elem-key-string
10764 (js2-node-abs-pos (js2-infix-node-left elem))
10765 (js2-node-len (js2-infix-node-left elem))))
10766 ;; Append any parsed element.
10767 (push elem elems))) ; end loop
10768 (js2-must-match js2-RC "msg.no.brace.prop")
10769 (nreverse elems)))
10770
10771 (defun js2-parse-named-prop (tt pos previous-token)
10772 "Parse a name, string, or getter/setter object property.
10773 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10774 (let ((key (cond
10775 ;; Literal string keys: {'foo': 'bar'}
10776 ((= tt js2-STRING)
10777 (make-js2-string-node))
10778 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10779 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10780 ((and (= tt js2-LB)
10781 (>= js2-language-version 200))
10782 (prog1 (js2-parse-expr)
10783 (js2-must-match js2-RB "msg.missing.computed.rb")))
10784 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10785 ((= tt js2-NUMBER)
10786 (make-js2-number-node))
10787 ;; Unquoted names: {foo: 12}
10788 ((= tt js2-NAME)
10789 (js2-create-name-node))
10790 ;; Anything else is an error
10791 (t (js2-report-error "msg.bad.prop"))))
10792 (prop (and previous-token (js2-token-string previous-token)))
10793 (property-type (when previous-token
10794 (if (= (js2-token-type previous-token) js2-MUL)
10795 "*"
10796 (js2-token-string previous-token)))))
10797 (when (or (string= prop "get")
10798 (string= prop "set"))
10799 (js2-set-face (js2-token-beg previous-token)
10800 (js2-token-end previous-token)
10801 'font-lock-keyword-face 'record)) ; get/set
10802 (cond
10803 ;; method definition: {f() {...}}
10804 ((and (= (js2-peek-token) js2-LP)
10805 (>= js2-language-version 200))
10806 (when (js2-name-node-p key) ; highlight function name properties
10807 (js2-record-face 'font-lock-function-name-face))
10808 (js2-parse-getter-setter-prop pos key property-type))
10809 ;; regular prop
10810 (t
10811 (let ((beg (js2-current-token-beg))
10812 (end (js2-current-token-end))
10813 (expr (js2-parse-plain-property key)))
10814 (when (and (= tt js2-NAME)
10815 (not js2-is-in-destructuring)
10816 js2-highlight-external-variables
10817 (js2-node-get-prop expr 'SHORTHAND))
10818 (js2-record-name-node key))
10819 (js2-set-face beg end
10820 (if (js2-function-node-p
10821 (js2-object-prop-node-right expr))
10822 'font-lock-function-name-face
10823 'font-lock-variable-name-face)
10824 'record)
10825 expr)))))
10826
10827 (defun js2-parse-plain-property (prop)
10828 "Parse a non-getter/setter property in an object literal.
10829 PROP is the node representing the property: a number, name,
10830 string or expression."
10831 (let* ((tt (js2-get-token))
10832 (pos (js2-node-pos prop))
10833 colon expr result)
10834 (cond
10835 ;; Abbreviated property, as in {foo, bar}
10836 ((and (>= js2-language-version 200)
10837 (or (= tt js2-COMMA)
10838 (= tt js2-RC))
10839 (not (js2-number-node-p prop)))
10840 (js2-unget-token)
10841 (setq result (make-js2-object-prop-node
10842 :pos pos
10843 :left prop
10844 :right prop
10845 :op-pos (js2-current-token-len)))
10846 (js2-node-add-children result prop)
10847 (js2-node-set-prop result 'SHORTHAND t)
10848 result)
10849 ;; Normal property
10850 (t
10851 (if (= tt js2-COLON)
10852 (setq colon (- (js2-current-token-beg) pos)
10853 expr (js2-parse-assign-expr))
10854 (js2-report-error "msg.no.colon.prop")
10855 (setq expr (make-js2-error-node)))
10856 (setq result (make-js2-object-prop-node
10857 :pos pos
10858 ;; don't include last consumed token in length
10859 :len (- (+ (js2-node-pos expr)
10860 (js2-node-len expr))
10861 pos)
10862 :left prop
10863 :right expr
10864 :op-pos colon))
10865 (js2-node-add-children result prop expr)
10866 result))))
10867
10868 (defun js2-parse-getter-setter-prop (pos prop type-string)
10869 "Parse getter or setter property in an object literal.
10870 JavaScript syntax is:
10871
10872 { get foo() {...}, set foo(x) {...} }
10873
10874 and expression closure style is also supported
10875
10876 { get foo() x, set foo(x) _x = x }
10877
10878 POS is the start position of the `get' or `set' keyword.
10879 PROP is the `js2-name-node' representing the property name.
10880 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10881 (let ((type (cond
10882 ((string= "get" type-string) js2-GET)
10883 ((string= "set" type-string) js2-SET)
10884 (t js2-FUNCTION)))
10885 result end
10886 (fn (js2-parse-function-expr)))
10887 ;; it has to be an anonymous function, as we already parsed the name
10888 (if (/= (js2-node-type fn) js2-FUNCTION)
10889 (js2-report-error "msg.bad.prop")
10890 (if (cl-plusp (length (js2-function-name fn)))
10891 (js2-report-error "msg.bad.prop")))
10892 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10893 (when (string= type-string "*")
10894 (setf (js2-function-node-generator-type fn) 'STAR))
10895 (setq end (js2-node-end fn)
10896 result (make-js2-getter-setter-node :type type
10897 :pos pos
10898 :len (- end pos)
10899 :left prop
10900 :right fn))
10901 (js2-node-add-children result prop fn)
10902 result))
10903
10904 (defun js2-create-name-node (&optional check-activation-p token string)
10905 "Create a name node using the current token and, optionally, STRING.
10906 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10907 (let* ((beg (js2-current-token-beg))
10908 (tt (js2-current-token-type))
10909 (s (or string
10910 (if (= js2-NAME tt)
10911 (js2-current-token-string)
10912 (js2-tt-name tt))))
10913 name)
10914 (setq name (make-js2-name-node :pos beg
10915 :name s
10916 :len (length s)))
10917 (if check-activation-p
10918 (js2-check-activation-name s (or token js2-NAME)))
10919 name))
10920
10921 ;;; Indentation support
10922
10923 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10924 ;; Karl cleverly deduces that the desired indentation level is often a
10925 ;; function of paren/bracket/brace nesting depth, which can be determined
10926 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10927 ;; then does some equally clever checks to see if we're in the context of a
10928 ;; substatement of a possibly braceless statement keyword such as if, while,
10929 ;; or finally. This approach yields pretty good results.
10930
10931 ;; The indenter is often "wrong", however, and needs to be overridden.
10932 ;; The right long-term solution is probably to emulate (or integrate
10933 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10934 ;; parse tree from `js2-parse' is present, which is not true at the
10935 ;; moment the user is typing, computing indentation is still thousands
10936 ;; of lines of code to handle every possible syntactic edge case.
10937
10938 ;; In the meantime, the compromise solution is that we offer a "bounce
10939 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10940 ;; current line indent among various likely guess points. This approach
10941 ;; is far from perfect, but should at least make it slightly easier to
10942 ;; move the line towards its desired indentation when manually
10943 ;; overriding Karl's heuristic nesting guesser.
10944
10945 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10946 ;; extensions such as `let' and Array comprehensions. Major kudos to
10947 ;; Karl for coming up with the initial approach, which packs a lot of
10948 ;; punch for so little code.
10949
10950 (defconst js2-possibly-braceless-keywords-re
10951 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10952 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10953 "try" "while" "with" "let")))
10954 "Regular expression matching keywords that are optionally
10955 followed by an opening brace.")
10956
10957 (defconst js2-indent-operator-re
10958 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10959 (regexp-opt '("in" "instanceof") 'words))
10960 "Regular expression matching operators that affect indentation
10961 of continued expressions.")
10962
10963 (defconst js2-declaration-keyword-re
10964 (regexp-opt '("var" "let" "const") 'words)
10965 "Regular expression matching variable declaration keywords.")
10966
10967 (defun js2-re-search-forward-inner (regexp &optional bound count)
10968 "Auxiliary function for `js2-re-search-forward'."
10969 (let (parse saved-point)
10970 (while (> count 0)
10971 (re-search-forward regexp bound)
10972 (setq parse (if saved-point
10973 (parse-partial-sexp saved-point (point))
10974 (syntax-ppss (point))))
10975 (cond ((nth 3 parse)
10976 (re-search-forward
10977 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10978 (save-excursion (end-of-line) (point)) t))
10979 ((nth 7 parse)
10980 (forward-line))
10981 ((or (nth 4 parse)
10982 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10983 (re-search-forward "\\*/"))
10984 (t
10985 (setq count (1- count))))
10986 (setq saved-point (point))))
10987 (point))
10988
10989 (defun js2-re-search-forward (regexp &optional bound noerror count)
10990 "Search forward but ignore strings and comments.
10991 Invokes `re-search-forward' but treats the buffer as if strings
10992 and comments have been removed."
10993 (let ((saved-point (point)))
10994 (condition-case err
10995 (cond ((null count)
10996 (js2-re-search-forward-inner regexp bound 1))
10997 ((< count 0)
10998 (js2-re-search-backward-inner regexp bound (- count)))
10999 ((> count 0)
11000 (js2-re-search-forward-inner regexp bound count)))
11001 (search-failed
11002 (goto-char saved-point)
11003 (unless noerror
11004 (error (error-message-string err)))))))
11005
11006 (defun js2-re-search-backward-inner (regexp &optional bound count)
11007 "Auxiliary function for `js2-re-search-backward'."
11008 (let (parse)
11009 (while (> count 0)
11010 (re-search-backward regexp bound)
11011 (setq parse (syntax-ppss (point)))
11012 (cond ((nth 3 parse)
11013 (re-search-backward
11014 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
11015 (line-beginning-position) t))
11016 ((nth 7 parse)
11017 (goto-char (nth 8 parse)))
11018 ((or (nth 4 parse)
11019 (and (eq (char-before) ?/) (eq (char-after) ?*)))
11020 (re-search-backward "/\\*"))
11021 (t
11022 (setq count (1- count))))))
11023 (point))
11024
11025 (defun js2-re-search-backward (regexp &optional bound noerror count)
11026 "Search backward but ignore strings and comments.
11027 Invokes `re-search-backward' but treats the buffer as if strings
11028 and comments have been removed."
11029 (let ((saved-point (point)))
11030 (condition-case err
11031 (cond ((null count)
11032 (js2-re-search-backward-inner regexp bound 1))
11033 ((< count 0)
11034 (js2-re-search-forward-inner regexp bound (- count)))
11035 ((> count 0)
11036 (js2-re-search-backward-inner regexp bound count)))
11037 (search-failed
11038 (goto-char saved-point)
11039 (unless noerror
11040 (error (error-message-string err)))))))
11041
11042 (defun js2-looking-at-operator-p ()
11043 "Return non-nil if text after point is a non-comma operator."
11044 (and (looking-at js2-indent-operator-re)
11045 (or (not (looking-at ":"))
11046 (save-excursion
11047 (and (js2-re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
11048 (looking-at "?"))))))
11049
11050 (defun js2-continued-expression-p ()
11051 "Return non-nil if the current line continues an expression."
11052 (save-excursion
11053 (back-to-indentation)
11054 (or (js2-looking-at-operator-p)
11055 (when (catch 'found
11056 (while (and (re-search-backward "\n" nil t)
11057 (let ((state (syntax-ppss)))
11058 (when (nth 4 state)
11059 (goto-char (nth 8 state))) ;; skip comments
11060 (skip-chars-backward " \t")
11061 (if (bolp)
11062 t
11063 (throw 'found t))))))
11064 (backward-char)
11065 (when (js2-looking-at-operator-p)
11066 (backward-char)
11067 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
11068
11069 (defun js2-end-of-do-while-loop-p ()
11070 "Return non-nil if word after point is `while' of a do-while
11071 statement, else returns nil. A braceless do-while statement
11072 spanning several lines requires that the start of the loop is
11073 indented to the same column as the current line."
11074 (interactive)
11075 (save-excursion
11076 (when (looking-at "\\s-*\\_<while\\_>")
11077 (if (save-excursion
11078 (skip-chars-backward "[ \t\n]*}")
11079 (looking-at "[ \t\n]*}"))
11080 (save-excursion
11081 (backward-list) (backward-word 1) (looking-at "\\_<do\\_>"))
11082 (js2-re-search-backward "\\_<do\\_>" (point-at-bol) t)
11083 (or (looking-at "\\_<do\\_>")
11084 (let ((saved-indent (current-indentation)))
11085 (while (and (js2-re-search-backward "^[ \t]*\\_<" nil t)
11086 (/= (current-indentation) saved-indent)))
11087 (and (looking-at "[ \t]*\\_<do\\_>")
11088 (not (js2-re-search-forward
11089 "\\_<while\\_>" (point-at-eol) t))
11090 (= (current-indentation) saved-indent))))))))
11091
11092 (defun js2-multiline-decl-indentation ()
11093 "Return the declaration indentation column if the current line belongs
11094 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
11095 (let (forward-sexp-function ; use Lisp version
11096 at-opening-bracket)
11097 (save-excursion
11098 (back-to-indentation)
11099 (when (not (looking-at js2-declaration-keyword-re))
11100 (when (looking-at js2-indent-operator-re)
11101 (goto-char (match-end 0))) ; continued expressions are ok
11102 (while (and (not at-opening-bracket)
11103 (not (bobp))
11104 (let ((pos (point)))
11105 (save-excursion
11106 (js2-backward-sws)
11107 (or (eq (char-before) ?,)
11108 (and (not (eq (char-before) ?\;))
11109 (prog2 (skip-syntax-backward ".")
11110 (looking-at js2-indent-operator-re)
11111 (js2-backward-sws))
11112 (not (eq (char-before) ?\;)))
11113 (js2-same-line pos)))))
11114 (condition-case _
11115 (backward-sexp)
11116 (scan-error (setq at-opening-bracket t))))
11117 (when (looking-at js2-declaration-keyword-re)
11118 (goto-char (match-end 0))
11119 (1+ (current-column)))))))
11120
11121 (defun js2-ctrl-statement-indentation ()
11122 "Return the proper indentation of current line if it is a control statement.
11123 Returns an indentation if this line starts the body of a control
11124 statement without braces, else returns nil."
11125 (let (forward-sexp-function)
11126 (save-excursion
11127 (back-to-indentation)
11128 (when (and (not (js2-same-line (point-min)))
11129 (not (looking-at "{"))
11130 (js2-re-search-backward "[[:graph:]]" nil t)
11131 (not (looking-at "[{([]"))
11132 (progn
11133 (forward-char)
11134 (when (= (char-before) ?\))
11135 ;; scan-sexps sometimes throws an error
11136 (ignore-errors (backward-sexp))
11137 (skip-chars-backward " \t" (point-at-bol)))
11138 (let ((pt (point)))
11139 (back-to-indentation)
11140 (when (looking-at "}[ \t]*")
11141 (goto-char (match-end 0)))
11142 (and (looking-at js2-possibly-braceless-keywords-re)
11143 (= (match-end 0) pt)
11144 (not (js2-end-of-do-while-loop-p))))))
11145 (+ (current-indentation) js2-basic-offset)))))
11146
11147 (defun js2-indent-in-array-comp (parse-status)
11148 "Return non-nil if we think we're in an array comprehension.
11149 In particular, return the buffer position of the first `for' kwd."
11150 (let ((bracket (nth 1 parse-status))
11151 (end (point)))
11152 (when bracket
11153 (save-excursion
11154 (goto-char bracket)
11155 (when (looking-at "\\[")
11156 (forward-char 1)
11157 (js2-forward-sws)
11158 (if (looking-at "[[{]")
11159 (let (forward-sexp-function) ; use Lisp version
11160 (forward-sexp) ; skip destructuring form
11161 (js2-forward-sws)
11162 (if (and (/= (char-after) ?,) ; regular array
11163 (looking-at "for"))
11164 (match-beginning 0)))
11165 ;; to skip arbitrary expressions we need the parser,
11166 ;; so we'll just guess at it.
11167 (if (and (> end (point)) ; not empty literal
11168 (re-search-forward "[^,]]* \\(for\\) " end t)
11169 ;; not inside comment or string literal
11170 (let ((state (parse-partial-sexp bracket (point))))
11171 (not (or (nth 3 state) (nth 4 state)))))
11172 (match-beginning 1))))))))
11173
11174 (defun js2-array-comp-indentation (parse-status for-kwd)
11175 (if (js2-same-line for-kwd)
11176 ;; first continuation line
11177 (save-excursion
11178 (goto-char (nth 1 parse-status))
11179 (forward-char 1)
11180 (skip-chars-forward " \t")
11181 (current-column))
11182 (save-excursion
11183 (goto-char for-kwd)
11184 (current-column))))
11185
11186 (defun js2-maybe-goto-declaration-keyword-end (bracket)
11187 "Helper function for `js2-proper-indentation'.
11188 Depending on the value of `js2-pretty-multiline-declarations',
11189 move point to the end of a variable declaration keyword so that
11190 indentation is aligned to that column."
11191 (cond
11192 ((eq js2-pretty-multiline-declarations 'all)
11193 (when (looking-at js2-declaration-keyword-re)
11194 (goto-char (1+ (match-end 0)))))
11195 ((eq js2-pretty-multiline-declarations 'dynamic)
11196 (let (declaration-keyword-end
11197 at-closing-bracket-p
11198 comma-p)
11199 (when (looking-at js2-declaration-keyword-re)
11200 ;; Preserve the match data lest it somehow be overridden.
11201 (setq declaration-keyword-end (match-end 0))
11202 (save-excursion
11203 (goto-char bracket)
11204 (setq at-closing-bracket-p
11205 ;; Handle scan errors gracefully.
11206 (condition-case nil
11207 (progn
11208 ;; Use the regular `forward-sexp-function' because the
11209 ;; normal one for this mode uses the AST.
11210 (let (forward-sexp-function)
11211 (forward-sexp))
11212 t)
11213 (error nil)))
11214 (when at-closing-bracket-p
11215 (js2-forward-sws)
11216 (setq comma-p (looking-at-p ","))))
11217 (when comma-p
11218 (goto-char (1+ declaration-keyword-end))))))))
11219
11220 (defun js2-proper-indentation (parse-status)
11221 "Return the proper indentation for the current line."
11222 (save-excursion
11223 (back-to-indentation)
11224 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
11225 (at-closing-bracket (looking-at "[]})]"))
11226 (same-indent-p (or at-closing-bracket
11227 (looking-at "\\_<case\\_>[^:]")
11228 (and (looking-at "\\_<default:")
11229 (save-excursion
11230 (js2-backward-sws)
11231 (not (memq (char-before) '(?, ?{)))))))
11232 (continued-expr-p (js2-continued-expression-p))
11233 (declaration-indent (and js2-pretty-multiline-declarations
11234 (js2-multiline-decl-indentation)))
11235 (bracket (nth 1 parse-status))
11236 beg indent)
11237 (cond
11238 ;; indent array comprehension continuation lines specially
11239 ((and bracket
11240 (>= js2-language-version 170)
11241 (not (js2-same-line bracket))
11242 (setq beg (js2-indent-in-array-comp parse-status))
11243 (>= (point) (save-excursion
11244 (goto-char beg)
11245 (point-at-bol)))) ; at or after first loop?
11246 (js2-array-comp-indentation parse-status beg))
11247
11248 (ctrl-stmt-indent)
11249
11250 ((and declaration-indent continued-expr-p)
11251 (+ declaration-indent js2-basic-offset))
11252
11253 (declaration-indent)
11254
11255 (bracket
11256 (goto-char bracket)
11257 (cond
11258 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
11259 (when (save-excursion (skip-chars-backward " \t)")
11260 (looking-at ")"))
11261 (backward-list))
11262 (back-to-indentation)
11263 (js2-maybe-goto-declaration-keyword-end bracket)
11264 (setq indent
11265 (cond (same-indent-p
11266 (current-column))
11267 (continued-expr-p
11268 (+ (current-column) (* 2 js2-basic-offset)))
11269 (t
11270 (+ (current-column) js2-basic-offset))))
11271 (if (and js2-indent-switch-body
11272 (not at-closing-bracket)
11273 (looking-at "\\_<switch\\_>"))
11274 (+ indent js2-basic-offset)
11275 indent))
11276 (t
11277 (unless same-indent-p
11278 (forward-char)
11279 (skip-chars-forward " \t"))
11280 (current-column))))
11281
11282 (continued-expr-p js2-basic-offset)
11283
11284 (t 0)))))
11285
11286 (defun js2-lineup-comment (parse-status)
11287 "Indent a multi-line block comment continuation line."
11288 (let* ((beg (nth 8 parse-status))
11289 (first-line (js2-same-line beg))
11290 (offset (save-excursion
11291 (goto-char beg)
11292 (if (looking-at "/\\*")
11293 (+ 1 (current-column))
11294 0))))
11295 (unless first-line
11296 (indent-line-to offset))))
11297
11298 (defun js2-backward-sws ()
11299 "Move backward through whitespace and comments."
11300 (interactive)
11301 (while (forward-comment -1)))
11302
11303 (defun js2-forward-sws ()
11304 "Move forward through whitespace and comments."
11305 (interactive)
11306 (while (forward-comment 1)))
11307
11308 (defun js2-arglist-close ()
11309 "Return non-nil if we're on a line beginning with a close-paren/brace."
11310 (save-excursion
11311 (goto-char (point-at-bol))
11312 (js2-forward-sws)
11313 (looking-at "[])}]")))
11314
11315 (defun js2-indent-looks-like-label-p ()
11316 (goto-char (point-at-bol))
11317 (js2-forward-sws)
11318 (looking-at (concat js2-mode-identifier-re ":")))
11319
11320 (defun js2-indent-in-objlit-p (parse-status)
11321 "Return non-nil if this looks like an object-literal entry."
11322 (let ((start (nth 1 parse-status)))
11323 (and
11324 start
11325 (save-excursion
11326 (and (zerop (forward-line -1))
11327 (not (< (point) start)) ; crossed a {} boundary
11328 (js2-indent-looks-like-label-p)))
11329 (save-excursion
11330 (js2-indent-looks-like-label-p)))))
11331
11332 ;; If prev line looks like foobar({ then we're passing an object
11333 ;; literal to a function call, and people pretty much always want to
11334 ;; de-dent back to the previous line, so move the 'basic-offset'
11335 ;; position to the front.
11336 (defun js2-indent-objlit-arg-p (parse-status)
11337 (save-excursion
11338 (back-to-indentation)
11339 (js2-backward-sws)
11340 (and (eq (1- (point)) (nth 1 parse-status))
11341 (eq (char-before) ?{)
11342 (progn
11343 (forward-char -1)
11344 (skip-chars-backward " \t")
11345 (eq (char-before) ?\()))))
11346
11347 (defun js2-indent-case-block-p ()
11348 (save-excursion
11349 (back-to-indentation)
11350 (js2-backward-sws)
11351 (goto-char (point-at-bol))
11352 (skip-chars-forward " \t")
11353 (looking-at "case\\s-.+:")))
11354
11355 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
11356 "Cycle among alternate computed indentation positions.
11357 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11358 of the buffer to the current point. NORMAL-COL is the indentation
11359 column computed by the heuristic guesser based on current paren,
11360 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11361 in reverse."
11362 (let ((cur-indent (current-indentation))
11363 (old-buffer-undo-list buffer-undo-list)
11364 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11365 (current-line (save-excursion
11366 (forward-line 0) ; move to bol
11367 (1+ (count-lines (point-min) (point)))))
11368 positions pos main-pos anchor arglist-cont same-indent
11369 basic-offset computed-pos)
11370 ;; temporarily don't record undo info, if user requested this
11371 (when js2-mode-indent-inhibit-undo
11372 (setq buffer-undo-list t))
11373 (unwind-protect
11374 (progn
11375 ;; First likely point: indent from beginning of previous code line
11376 (push (setq basic-offset
11377 (+ (save-excursion
11378 (back-to-indentation)
11379 (js2-backward-sws)
11380 (back-to-indentation)
11381 (current-column))
11382 js2-basic-offset))
11383 positions)
11384
11385 ;; (First + epsilon) likely point: indent 2x from beginning of
11386 ;; previous code line. Google does it this way.
11387 (push (setq basic-offset
11388 (+ (save-excursion
11389 (back-to-indentation)
11390 (js2-backward-sws)
11391 (back-to-indentation)
11392 (current-column))
11393 (* 2 js2-basic-offset)))
11394 positions)
11395
11396 ;; Second likely point: indent from assign-expr RHS. This
11397 ;; is just a crude guess based on finding " = " on the previous
11398 ;; line containing actual code.
11399 (setq pos (save-excursion
11400 (forward-line -1)
11401 (goto-char (point-at-bol))
11402 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11403 (point-at-eol) t)
11404 (goto-char (match-end 1))
11405 (skip-chars-forward " \t\r\n")
11406 (current-column))))
11407 (when pos
11408 (cl-incf pos js2-basic-offset)
11409 (push pos positions))
11410
11411 ;; Third likely point: same indent as previous line of code.
11412 ;; Make it the first likely point if we're not on an
11413 ;; arglist-close line and previous line ends in a comma, or
11414 ;; both this line and prev line look like object-literal
11415 ;; elements.
11416 (setq pos (save-excursion
11417 (goto-char (point-at-bol))
11418 (js2-backward-sws)
11419 (back-to-indentation)
11420 (prog1
11421 (current-column)
11422 ;; while we're here, look for trailing comma
11423 (if (save-excursion
11424 (goto-char (point-at-eol))
11425 (js2-backward-sws)
11426 (eq (char-before) ?,))
11427 (setq arglist-cont (1- (point)))))))
11428 (when pos
11429 (if (and (or arglist-cont
11430 (js2-indent-in-objlit-p parse-status))
11431 (not (js2-arglist-close)))
11432 (setq same-indent pos))
11433 (push pos positions))
11434
11435 ;; Fourth likely point: first preceding code with less indentation.
11436 ;; than the immediately preceding code line.
11437 (setq pos (save-excursion
11438 (back-to-indentation)
11439 (js2-backward-sws)
11440 (back-to-indentation)
11441 (setq anchor (current-column))
11442 (while (and (zerop (forward-line -1))
11443 (>= (progn
11444 (back-to-indentation)
11445 (current-column))
11446 anchor)))
11447 (setq pos (current-column))))
11448 (push pos positions)
11449
11450 ;; nesting-heuristic position, main by default
11451 (push (setq main-pos normal-col) positions)
11452
11453 ;; delete duplicates and sort positions list
11454 (setq positions (sort (delete-dups positions) '<))
11455
11456 ;; comma-list continuation lines: prev line indent takes precedence
11457 (if same-indent
11458 (setq main-pos same-indent))
11459
11460 ;; common special cases where we want to indent in from previous line
11461 (if (or (js2-indent-case-block-p)
11462 (js2-indent-objlit-arg-p parse-status))
11463 (setq main-pos basic-offset))
11464
11465 ;; if bouncing backwards, reverse positions list
11466 (if backwards
11467 (setq positions (reverse positions)))
11468
11469 ;; record whether we're already sitting on one of the alternatives
11470 (setq pos (member cur-indent positions))
11471
11472 (cond
11473 ;; case 0: we're one one of the alternatives and this is the
11474 ;; first time they've pressed TAB on this line (best-guess).
11475 ((and js2-mode-indent-ignore-first-tab
11476 pos
11477 ;; first time pressing TAB on this line?
11478 (not (eq js2-mode-last-indented-line current-line)))
11479 ;; do nothing
11480 (setq computed-pos nil))
11481 ;; case 1: only one computed position => use it
11482 ((null (cdr positions))
11483 (setq computed-pos 0))
11484 ;; case 2: not on any of the computed spots => use main spot
11485 ((not pos)
11486 (setq computed-pos (js2-position main-pos positions)))
11487 ;; case 3: on last position: cycle to first position
11488 ((null (cdr pos))
11489 (setq computed-pos 0))
11490 ;; case 4: on intermediate position: cycle to next position
11491 (t
11492 (setq computed-pos (js2-position (cl-second pos) positions))))
11493
11494 ;; see if any hooks want to indent; otherwise we do it
11495 (cl-loop with result = nil
11496 for hook in js2-indent-hook
11497 while (null result)
11498 do
11499 (setq result (funcall hook positions computed-pos))
11500 finally do
11501 (unless (or result (null computed-pos))
11502 (indent-line-to (nth computed-pos positions)))))
11503
11504 ;; finally
11505 (if js2-mode-indent-inhibit-undo
11506 (setq buffer-undo-list old-buffer-undo-list))
11507 ;; see commentary for `js2-mode-last-indented-line'
11508 (setq js2-mode-last-indented-line current-line))))
11509
11510 (defun js2-indent-bounce-backwards ()
11511 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11512 cycles between the computed indentation positions in reverse order."
11513 (interactive)
11514 (js2-indent-line t))
11515
11516 (defun js2-1-line-comment-continuation-p ()
11517 "Return t if we're in a 1-line comment continuation.
11518 If so, we don't ever want to use bounce-indent."
11519 (save-excursion
11520 (and (progn
11521 (forward-line 0)
11522 (looking-at "\\s-*//"))
11523 (progn
11524 (forward-line -1)
11525 (forward-line 0)
11526 (when (looking-at "\\s-*$")
11527 (js2-backward-sws)
11528 (forward-line 0))
11529 (looking-at "\\s-*//")))))
11530
11531 (defun js2-indent-line (&optional bounce-backwards)
11532 "Indent the current line as JavaScript source text."
11533 (interactive)
11534 (let (parse-status offset indent-col
11535 ;; Don't whine about errors/warnings when we're indenting.
11536 ;; This has to be set before calling parse-partial-sexp below.
11537 (inhibit-point-motion-hooks t))
11538 (setq parse-status (save-excursion
11539 (syntax-ppss (point-at-bol)))
11540 offset (- (point) (save-excursion
11541 (back-to-indentation)
11542 (point))))
11543 ;; Don't touch multiline strings.
11544 (unless (nth 3 parse-status)
11545 (if (nth 4 parse-status)
11546 (js2-lineup-comment parse-status)
11547 (setq indent-col (js2-proper-indentation parse-status))
11548 ;; See comments below about `js2-mode-last-indented-line'.
11549 (cond
11550 ;; bounce-indenting is disabled during electric-key indent.
11551 ;; It doesn't work well on first line of buffer.
11552 ((and js2-bounce-indent-p
11553 (not (js2-same-line (point-min)))
11554 (not (js2-1-line-comment-continuation-p)))
11555 (js2-bounce-indent indent-col parse-status bounce-backwards))
11556 ;; just indent to the guesser's likely spot
11557 (t (indent-line-to indent-col))))
11558 (when (cl-plusp offset)
11559 (forward-char offset)))))
11560
11561 (defun js2-indent-region (start end)
11562 "Indent the region, but don't use bounce indenting."
11563 (let ((js2-bounce-indent-p nil)
11564 (indent-region-function nil)
11565 (after-change-functions (remq 'js2-mode-edit
11566 after-change-functions)))
11567 (indent-region start end nil) ; nil for byte-compiler
11568 (js2-mode-edit start end (- end start))))
11569
11570 (defvar js2-minor-mode-map
11571 (let ((map (make-sparse-keymap)))
11572 (define-key map (kbd "C-c C-`") #'js2-next-error)
11573 (define-key map [mouse-1] #'js2-mode-show-node)
11574 map)
11575 "Keymap used when `js2-minor-mode' is active.")
11576
11577 ;;;###autoload
11578 (define-minor-mode js2-minor-mode
11579 "Minor mode for running js2 as a background linter.
11580 This allows you to use a different major mode for JavaScript editing,
11581 such as `js-mode', while retaining the asynchronous error/warning
11582 highlighting features of `js2-mode'."
11583 :group 'js2-mode
11584 :lighter " js-lint"
11585 (if js2-minor-mode
11586 (js2-minor-mode-enter)
11587 (js2-minor-mode-exit)))
11588
11589 (defun js2-minor-mode-enter ()
11590 "Initialization for `js2-minor-mode'."
11591 (set (make-local-variable 'max-lisp-eval-depth)
11592 (max max-lisp-eval-depth 3000))
11593 (setq next-error-function #'js2-next-error)
11594 (js2-set-default-externs)
11595 ;; Experiment: make reparse-delay longer for longer files.
11596 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11597 (setq js2-idle-timer-delay
11598 (* js2-idle-timer-delay
11599 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11600 (setq js2-mode-buffer-dirty-p t
11601 js2-mode-parsing nil)
11602 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11603 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11604 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11605 (when js2-include-jslint-globals
11606 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11607 (run-hooks 'js2-init-hook)
11608 (js2-reparse))
11609
11610 (defun js2-minor-mode-exit ()
11611 "Turn off `js2-minor-mode'."
11612 (setq next-error-function nil)
11613 (remove-hook 'after-change-functions #'js2-mode-edit t)
11614 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11615 (when js2-mode-node-overlay
11616 (delete-overlay js2-mode-node-overlay)
11617 (setq js2-mode-node-overlay nil))
11618 (js2-remove-overlays)
11619 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11620 (setq js2-mode-ast nil))
11621
11622 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11623 (make-variable-buffer-local 'js2-source-buffer)
11624
11625 (cl-defun js2-display-error-list ()
11626 "Display a navigable buffer listing parse errors/warnings."
11627 (interactive)
11628 (unless (js2-have-errors-p)
11629 (message "No errors")
11630 (cl-return-from js2-display-error-list))
11631 (cl-labels ((annotate-list
11632 (lst type)
11633 "Add diagnostic TYPE and line number to errs list"
11634 (mapcar (lambda (err)
11635 (list err type (line-number-at-pos (nth 1 err))))
11636 lst)))
11637 (let* ((srcbuf (current-buffer))
11638 (errbuf (get-buffer-create "*js-lint*"))
11639 (errors (annotate-list
11640 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11641 'js2-error)) ; must be a valid face name
11642 (warnings (annotate-list
11643 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11644 'js2-warning)) ; must be a valid face name
11645 (all-errs (sort (append errors warnings)
11646 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11647 (with-current-buffer errbuf
11648 (let ((inhibit-read-only t))
11649 (erase-buffer)
11650 (dolist (err all-errs)
11651 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11652 (insert-text-button
11653 (format "line %d: %s" line (js2-get-msg msg-key))
11654 'face type
11655 'follow-link "\C-m"
11656 'action 'js2-error-buffer-jump
11657 'js2-msg (js2-get-msg msg-key)
11658 'js2-pos beg)
11659 (insert "\n"))))
11660 (js2-error-buffer-mode)
11661 (setq js2-source-buffer srcbuf)
11662 (pop-to-buffer errbuf)
11663 (goto-char (point-min))
11664 (unless (eobp)
11665 (js2-error-buffer-view))))))
11666
11667 (defvar js2-error-buffer-mode-map
11668 (let ((map (make-sparse-keymap)))
11669 (define-key map "n" #'js2-error-buffer-next)
11670 (define-key map "p" #'js2-error-buffer-prev)
11671 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11672 (define-key map "o" #'js2-error-buffer-view)
11673 (define-key map "q" #'js2-error-buffer-quit)
11674 map)
11675 "Keymap used for js2 diagnostics buffers.")
11676
11677 (defun js2-error-buffer-mode ()
11678 "Major mode for js2 diagnostics buffers.
11679 Selecting an error will jump it to the corresponding source-buffer error.
11680 \\{js2-error-buffer-mode-map}"
11681 (interactive)
11682 (setq major-mode 'js2-error-buffer-mode
11683 mode-name "JS Lint Diagnostics")
11684 (use-local-map js2-error-buffer-mode-map)
11685 (setq truncate-lines t)
11686 (set-buffer-modified-p nil)
11687 (setq buffer-read-only t)
11688 (run-hooks 'js2-error-buffer-mode-hook))
11689
11690 (defun js2-error-buffer-next ()
11691 "Move to next error and view it."
11692 (interactive)
11693 (when (zerop (forward-line 1))
11694 (js2-error-buffer-view)))
11695
11696 (defun js2-error-buffer-prev ()
11697 "Move to previous error and view it."
11698 (interactive)
11699 (when (zerop (forward-line -1))
11700 (js2-error-buffer-view)))
11701
11702 (defun js2-error-buffer-quit ()
11703 "Kill the current buffer."
11704 (interactive)
11705 (kill-buffer))
11706
11707 (defun js2-error-buffer-jump (&rest ignored)
11708 "Jump cursor to current error in source buffer."
11709 (interactive)
11710 (when (js2-error-buffer-view)
11711 (pop-to-buffer js2-source-buffer)))
11712
11713 (defun js2-error-buffer-view ()
11714 "Scroll source buffer to show error at current line."
11715 (interactive)
11716 (cond
11717 ((not (eq major-mode 'js2-error-buffer-mode))
11718 (message "Not in a js2 errors buffer"))
11719 ((not (buffer-live-p js2-source-buffer))
11720 (message "Source buffer has been killed"))
11721 ((not (wholenump (get-text-property (point) 'js2-pos)))
11722 (message "There does not seem to be an error here"))
11723 (t
11724 (let ((pos (get-text-property (point) 'js2-pos))
11725 (msg (get-text-property (point) 'js2-msg)))
11726 (save-selected-window
11727 (pop-to-buffer js2-source-buffer)
11728 (goto-char pos)
11729 (message msg))))))
11730
11731 ;;;###autoload
11732 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11733 ;; FIXME: Should derive from js-mode.
11734 "Major mode for editing JavaScript code."
11735 ;; Used by comment-region; don't change it.
11736 (set (make-local-variable 'comment-start) "//")
11737 (set (make-local-variable 'comment-end) "")
11738 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11739 (set (make-local-variable 'max-lisp-eval-depth)
11740 (max max-lisp-eval-depth 3000))
11741 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11742 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11743 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11744 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11745 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11746 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11747 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11748 ;; for characters inside regexp literals.
11749 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11750 ;; this is necessary to make `show-paren-function' work properly
11751 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11752 ;; needed for M-x rgrep, among other things
11753 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11754
11755 (set (make-local-variable 'electric-indent-chars)
11756 (append "{}()[]:;,*." electric-indent-chars))
11757 (set (make-local-variable 'electric-layout-rules)
11758 '((?\; . after) (?\{ . after) (?\} . before)))
11759
11760 ;; some variables needed by cc-engine for paragraph-fill, etc.
11761 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11762 c-comment-start-regexp "/[*/]\\|\\s|"
11763 c-line-comment-starter "//"
11764 c-paragraph-start js2-paragraph-start
11765 c-paragraph-separate "$"
11766 c-syntactic-ws-start js2-syntactic-ws-start
11767 c-syntactic-ws-end js2-syntactic-ws-end
11768 c-syntactic-eol js2-syntactic-eol)
11769
11770 (let ((c-buffer-is-cc-mode t))
11771 ;; Copied from `js-mode'. Also see Bug#6071.
11772 (make-local-variable 'paragraph-start)
11773 (make-local-variable 'paragraph-separate)
11774 (make-local-variable 'paragraph-ignore-fill-prefix)
11775 (make-local-variable 'adaptive-fill-mode)
11776 (make-local-variable 'adaptive-fill-regexp)
11777 (c-setup-paragraph-variables))
11778
11779 (setq font-lock-defaults '(nil t))
11780
11781 ;; Experiment: make reparse-delay longer for longer files.
11782 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11783 (setq js2-idle-timer-delay
11784 (* js2-idle-timer-delay
11785 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11786
11787 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11788 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11789 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11790 (setq next-error-function #'js2-next-error)
11791 (imenu-add-to-menubar (concat "IM-" mode-name))
11792 (add-to-invisibility-spec '(js2-outline . t))
11793 (set (make-local-variable 'line-move-ignore-invisible) t)
11794 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11795 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11796
11797 (setq js2-mode-functions-hidden nil
11798 js2-mode-comments-hidden nil
11799 js2-mode-buffer-dirty-p t
11800 js2-mode-parsing nil)
11801
11802 (js2-set-default-externs)
11803
11804 (when js2-include-jslint-globals
11805 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11806
11807 (run-hooks 'js2-init-hook)
11808
11809 (js2-reparse))
11810
11811 (defun js2-mode-exit ()
11812 "Exit `js2-mode' and clean up."
11813 (interactive)
11814 (when js2-mode-node-overlay
11815 (delete-overlay js2-mode-node-overlay)
11816 (setq js2-mode-node-overlay nil))
11817 (js2-remove-overlays)
11818 (setq js2-mode-ast nil)
11819 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11820 (remove-from-invisibility-spec '(js2-outline . t))
11821 (js2-mode-show-all)
11822 (with-silent-modifications
11823 (js2-clear-face (point-min) (point-max))))
11824
11825 (defun js2-mode-reset-timer ()
11826 "Cancel any existing parse timer and schedule a new one."
11827 (if js2-mode-parse-timer
11828 (cancel-timer js2-mode-parse-timer))
11829 (setq js2-mode-parsing nil)
11830 (let ((timer (timer-create)))
11831 (setq js2-mode-parse-timer timer)
11832 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11833 (timer-set-idle-time timer js2-idle-timer-delay)
11834 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11835 (timer-activate-when-idle timer nil)))
11836
11837 (defun js2-mode-idle-reparse (buffer)
11838 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11839 it to be reparsed when the buffer is selected."
11840 (cond ((eq buffer (current-buffer))
11841 (js2-reparse))
11842 ((buffer-live-p buffer)
11843 ;; reparse when the buffer is selected again
11844 (with-current-buffer buffer
11845 (add-hook 'window-configuration-change-hook
11846 #'js2-mode-idle-reparse-inner
11847 nil t)))))
11848
11849 (defun js2-mode-idle-reparse-inner ()
11850 (remove-hook 'window-configuration-change-hook
11851 #'js2-mode-idle-reparse-inner
11852 t)
11853 (js2-reparse))
11854
11855 (defun js2-mode-edit (_beg _end _len)
11856 "Schedule a new parse after buffer is edited.
11857 Buffer edit spans from BEG to END and is of length LEN."
11858 (setq js2-mode-buffer-dirty-p t)
11859 (js2-mode-hide-overlay)
11860 (js2-mode-reset-timer))
11861
11862 (defun js2-minor-mode-edit (_beg _end _len)
11863 "Callback for buffer edits in `js2-mode'.
11864 Schedules a new parse after buffer is edited.
11865 Buffer edit spans from BEG to END and is of length LEN."
11866 (setq js2-mode-buffer-dirty-p t)
11867 (js2-mode-hide-overlay)
11868 (js2-mode-reset-timer))
11869
11870 (defun js2-reparse (&optional force)
11871 "Re-parse current buffer after user finishes some data entry.
11872 If we get any user input while parsing, including cursor motion,
11873 we discard the parse and reschedule it. If FORCE is nil, then the
11874 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11875 (let (time
11876 interrupted-p
11877 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11878 (unless js2-mode-parsing
11879 (setq js2-mode-parsing t)
11880 (unwind-protect
11881 (when (or js2-mode-buffer-dirty-p force)
11882 (js2-remove-overlays)
11883 (setq js2-mode-buffer-dirty-p nil
11884 js2-mode-fontifications nil
11885 js2-mode-deferred-properties nil)
11886 (if js2-mode-verbose-parse-p
11887 (message "parsing..."))
11888 (setq time
11889 (js2-time
11890 (setq interrupted-p
11891 (catch 'interrupted
11892 (js2-parse)
11893 (with-silent-modifications
11894 ;; if parsing is interrupted, comments and regex
11895 ;; literals stay ignored by `parse-partial-sexp'
11896 (remove-text-properties (point-min) (point-max)
11897 '(syntax-table))
11898 (js2-mode-apply-deferred-properties)
11899 (js2-mode-remove-suppressed-warnings)
11900 (js2-mode-show-warnings)
11901 (js2-mode-show-errors)
11902 (if (>= js2-highlight-level 1)
11903 (js2-highlight-jsdoc js2-mode-ast)))
11904 nil))))
11905 (if interrupted-p
11906 (progn
11907 ;; unfinished parse => try again
11908 (setq js2-mode-buffer-dirty-p t)
11909 (js2-mode-reset-timer))
11910 (if js2-mode-verbose-parse-p
11911 (message "Parse time: %s" time))))
11912 (setq js2-mode-parsing nil)
11913 (unless interrupted-p
11914 (setq js2-mode-parse-timer nil))))))
11915
11916 (defun js2-mode-show-node (event)
11917 "Debugging aid: highlight selected AST node on mouse click."
11918 (interactive "e")
11919 (mouse-set-point event)
11920 (setq deactivate-mark t)
11921 (when js2-mode-show-overlay
11922 (let ((node (js2-node-at-point))
11923 beg end)
11924 (if (null node)
11925 (message "No node found at location %s" (point))
11926 (setq beg (js2-node-abs-pos node)
11927 end (+ beg (js2-node-len node)))
11928 (if js2-mode-node-overlay
11929 (move-overlay js2-mode-node-overlay beg end)
11930 (setq js2-mode-node-overlay (make-overlay beg end))
11931 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11932 (with-silent-modifications
11933 (if (fboundp 'cursor-sensor-mode)
11934 (put-text-property beg end 'cursor-sensor-functions
11935 '(js2-mode-hide-overlay))
11936 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11937 (message "%s, parent: %s"
11938 (js2-node-short-name node)
11939 (if (js2-node-parent node)
11940 (js2-node-short-name (js2-node-parent node))
11941 "nil"))))))
11942
11943 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11944 "Remove the debugging overlay when point moves.
11945 ARG1, ARG2 and ARG3 have different values depending on whether this function
11946 was found on `point-left' or in `cursor-sensor-functions'."
11947 (when js2-mode-node-overlay
11948 (let ((beg (overlay-start js2-mode-node-overlay))
11949 (end (overlay-end js2-mode-node-overlay))
11950 (p2 (if (windowp arg1)
11951 ;; Called from cursor-sensor-functions.
11952 (window-point arg1)
11953 ;; Called from point-left.
11954 arg2)))
11955 ;; Sometimes we're called spuriously.
11956 (unless (and p2
11957 (>= p2 beg)
11958 (<= p2 end))
11959 (with-silent-modifications
11960 (remove-text-properties beg end
11961 '(point-left nil cursor-sensor-functions)))
11962 (delete-overlay js2-mode-node-overlay)
11963 (setq js2-mode-node-overlay nil)))))
11964
11965 (defun js2-mode-reset ()
11966 "Debugging helper: reset everything."
11967 (interactive)
11968 (js2-mode-exit)
11969 (js2-mode))
11970
11971 (defun js2-mode-show-warn-or-err (e face)
11972 "Highlight a warning or error E with FACE.
11973 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11974 The last element is optional. When present, use instead of FACE."
11975 (let* ((key (cl-first e))
11976 (beg (cl-second e))
11977 (end (+ beg (cl-third e)))
11978 ;; Don't inadvertently go out of bounds.
11979 (beg (max (point-min) (min beg (point-max))))
11980 (end (max (point-min) (min end (point-max))))
11981 (ovl (make-overlay beg end)))
11982 ;; FIXME: Why a mix of overlays and text-properties?
11983 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11984 (overlay-put ovl 'js2-error t)
11985 (put-text-property beg end 'help-echo (js2-get-msg key))
11986 (if (fboundp 'cursor-sensor-mode)
11987 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11988 (put-text-property beg end 'point-entered #'js2-echo-error))))
11989
11990 (defun js2-remove-overlays ()
11991 "Remove overlays from buffer that have a `js2-error' property."
11992 (let ((beg (point-min))
11993 (end (point-max)))
11994 (save-excursion
11995 (dolist (o (overlays-in beg end))
11996 (when (overlay-get o 'js2-error)
11997 (delete-overlay o))))))
11998
11999 (defun js2-mode-apply-deferred-properties ()
12000 "Apply fontifications and other text properties recorded during parsing."
12001 (when (cl-plusp js2-highlight-level)
12002 ;; We defer clearing faces as long as possible to eliminate flashing.
12003 (js2-clear-face (point-min) (point-max))
12004 ;; Have to reverse the recorded fontifications list so that errors
12005 ;; and warnings overwrite the normal fontifications.
12006 (dolist (f (nreverse js2-mode-fontifications))
12007 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
12008 (setq js2-mode-fontifications nil))
12009 (dolist (p js2-mode-deferred-properties)
12010 (apply #'put-text-property p))
12011 (setq js2-mode-deferred-properties nil))
12012
12013 (defun js2-mode-show-errors ()
12014 "Highlight syntax errors."
12015 (when js2-mode-show-parse-errors
12016 (dolist (e (js2-ast-root-errors js2-mode-ast))
12017 (js2-mode-show-warn-or-err e 'js2-error))))
12018
12019 (defun js2-mode-remove-suppressed-warnings ()
12020 "Take suppressed warnings out of the AST warnings list.
12021 This ensures that the counts and `next-error' are correct."
12022 (setf (js2-ast-root-warnings js2-mode-ast)
12023 (js2-delete-if
12024 (lambda (e)
12025 (let ((key (caar e)))
12026 (or
12027 (and (not js2-strict-trailing-comma-warning)
12028 (string-match "trailing\\.comma" key))
12029 (and (not js2-strict-cond-assign-warning)
12030 (string= key "msg.equal.as.assign"))
12031 (and js2-missing-semi-one-line-override
12032 (string= key "msg.missing.semi")
12033 (let* ((beg (cl-second e))
12034 (node (js2-node-at-point beg))
12035 (fn (js2-mode-find-parent-fn node))
12036 (body (and fn (js2-function-node-body fn)))
12037 (lc (and body (js2-node-abs-pos body)))
12038 (rc (and lc (+ lc (js2-node-len body)))))
12039 (and fn
12040 (or (null body)
12041 (save-excursion
12042 (goto-char beg)
12043 (and (js2-same-line lc)
12044 (js2-same-line rc))))))))))
12045 (js2-ast-root-warnings js2-mode-ast))))
12046
12047 (defun js2-mode-show-warnings ()
12048 "Highlight strict-mode warnings."
12049 (when js2-mode-show-strict-warnings
12050 (dolist (e (js2-ast-root-warnings js2-mode-ast))
12051 (js2-mode-show-warn-or-err e 'js2-warning))))
12052
12053 (defun js2-echo-error (arg1 arg2 &optional _arg3)
12054 "Called by point-motion hooks.
12055 ARG1, ARG2 and ARG3 have different values depending on whether this function
12056 was found on `point-entered' or in `cursor-sensor-functions'."
12057 (let* ((new-point (if (windowp arg1)
12058 ;; Called from cursor-sensor-functions.
12059 (window-point arg1)
12060 ;; Called from point-left.
12061 arg2))
12062 (msg (get-text-property new-point 'help-echo)))
12063 (when (and (stringp msg)
12064 (not (active-minibuffer-window))
12065 (not (current-message)))
12066 (message msg))))
12067
12068 (defun js2-line-break (&optional _soft)
12069 "Break line at point and indent, continuing comment if within one.
12070 If inside a string, and `js2-concat-multiline-strings' is not
12071 nil, turn it into concatenation."
12072 (interactive)
12073 (let ((parse-status (syntax-ppss)))
12074 (cond
12075 ;; Check if we're inside a string.
12076 ((nth 3 parse-status)
12077 (if js2-concat-multiline-strings
12078 (js2-mode-split-string parse-status)
12079 (insert "\n")))
12080 ;; Check if inside a block comment.
12081 ((nth 4 parse-status)
12082 (js2-mode-extend-comment (nth 8 parse-status)))
12083 (t
12084 (newline-and-indent)))))
12085
12086 (defun js2-mode-split-string (parse-status)
12087 "Turn a newline in mid-string into a string concatenation.
12088 PARSE-STATUS is as documented in `parse-partial-sexp'."
12089 (let* ((quote-char (nth 3 parse-status))
12090 (at-eol (eq js2-concat-multiline-strings 'eol)))
12091 (insert quote-char)
12092 (insert (if at-eol " +\n" "\n"))
12093 (unless at-eol
12094 (insert "+ "))
12095 (js2-indent-line)
12096 (insert quote-char)
12097 (when (eolp)
12098 (insert quote-char)
12099 (backward-char 1))))
12100
12101 (defun js2-mode-extend-comment (start-pos)
12102 "Indent the line and, when inside a comment block, add comment prefix."
12103 (let (star single col first-line needs-close)
12104 (save-excursion
12105 (back-to-indentation)
12106 (when (< (point) start-pos)
12107 (goto-char start-pos))
12108 (cond
12109 ((looking-at "\\*[^/]")
12110 (setq star t
12111 col (current-column)))
12112 ((looking-at "/\\*")
12113 (setq star t
12114 first-line t
12115 col (1+ (current-column))))
12116 ((looking-at "//")
12117 (setq single t
12118 col (current-column)))))
12119 ;; Heuristic for whether we need to close the comment:
12120 ;; if we've got a parse error here, assume it's an unterminated
12121 ;; comment.
12122 (setq needs-close
12123 (or
12124 (get-char-property (1- (point)) 'js2-error)
12125 ;; The heuristic above doesn't work well when we're
12126 ;; creating a comment and there's another one downstream,
12127 ;; as our parser thinks this one ends at the end of the
12128 ;; next one. (You can have a /* inside a js block comment.)
12129 ;; So just close it if the next non-ws char isn't a *.
12130 (and first-line
12131 (eolp)
12132 (save-excursion
12133 (skip-chars-forward " \t\r\n")
12134 (not (eq (char-after) ?*))))))
12135 (delete-horizontal-space)
12136 (insert "\n")
12137 (cond
12138 (star
12139 (indent-to col)
12140 (insert "* ")
12141 (if (and first-line needs-close)
12142 (save-excursion
12143 (insert "\n")
12144 (indent-to col)
12145 (insert "*/"))))
12146 ((and single
12147 (save-excursion
12148 (and (zerop (forward-line 1))
12149 (looking-at "\\s-*//"))))
12150 (indent-to col)
12151 (insert "// ")))
12152 ;; Don't need to extend the comment after all.
12153 (js2-indent-line)))
12154
12155 (defun js2-beginning-of-line ()
12156 "Toggle point between bol and first non-whitespace char in line.
12157 Also moves past comment delimiters when inside comments."
12158 (interactive)
12159 (let (node)
12160 (cond
12161 ((bolp)
12162 (back-to-indentation))
12163 ((looking-at "//")
12164 (skip-chars-forward "/ \t"))
12165 ((and (eq (char-after) ?*)
12166 (setq node (js2-comment-at-point))
12167 (memq (js2-comment-node-format node) '(jsdoc block))
12168 (save-excursion
12169 (skip-chars-backward " \t")
12170 (bolp)))
12171 (skip-chars-forward "\* \t"))
12172 (t
12173 (goto-char (point-at-bol))))))
12174
12175 (defun js2-end-of-line ()
12176 "Toggle point between eol and last non-whitespace char in line."
12177 (interactive)
12178 (if (eolp)
12179 (skip-chars-backward " \t")
12180 (goto-char (point-at-eol))))
12181
12182 (defun js2-mode-wait-for-parse (callback)
12183 "Invoke CALLBACK when parsing is finished.
12184 If parsing is already finished, calls CALLBACK immediately."
12185 (if (not js2-mode-buffer-dirty-p)
12186 (funcall callback)
12187 (push callback js2-mode-pending-parse-callbacks)
12188 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
12189
12190 (defun js2-mode-parse-finished ()
12191 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
12192 ;; We can't let errors propagate up, since it prevents the
12193 ;; `js2-parse' method from completing normally and returning
12194 ;; the ast, which makes things mysteriously not work right.
12195 (unwind-protect
12196 (dolist (cb js2-mode-pending-parse-callbacks)
12197 (condition-case err
12198 (funcall cb)
12199 (error (message "%s" err))))
12200 (setq js2-mode-pending-parse-callbacks nil)))
12201
12202 (defun js2-mode-flag-region (from to flag)
12203 "Hide or show text from FROM to TO, according to FLAG.
12204 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
12205 Returns the created overlay if FLAG is non-nil."
12206 (remove-overlays from to 'invisible 'js2-outline)
12207 (when flag
12208 (let ((o (make-overlay from to)))
12209 (overlay-put o 'invisible 'js2-outline)
12210 (overlay-put o 'isearch-open-invisible
12211 'js2-isearch-open-invisible)
12212 o)))
12213
12214 ;; Function to be set as an outline-isearch-open-invisible' property
12215 ;; to the overlay that makes the outline invisible (see
12216 ;; `js2-mode-flag-region').
12217 (defun js2-isearch-open-invisible (_overlay)
12218 ;; We rely on the fact that isearch places point on the matched text.
12219 (js2-mode-show-element))
12220
12221 (defun js2-mode-invisible-overlay-bounds (&optional pos)
12222 "Return cons cell of bounds of folding overlay at POS.
12223 Returns nil if not found."
12224 (let ((overlays (overlays-at (or pos (point))))
12225 o)
12226 (while (and overlays
12227 (not o))
12228 (if (overlay-get (car overlays) 'invisible)
12229 (setq o (car overlays))
12230 (setq overlays (cdr overlays))))
12231 (if o
12232 (cons (overlay-start o) (overlay-end o)))))
12233
12234 (defun js2-mode-function-at-point (&optional pos)
12235 "Return the innermost function node enclosing current point.
12236 Returns nil if point is not in a function."
12237 (let ((node (js2-node-at-point pos)))
12238 (while (and node (not (js2-function-node-p node)))
12239 (setq node (js2-node-parent node)))
12240 (if (js2-function-node-p node)
12241 node)))
12242
12243 (defun js2-mode-toggle-element ()
12244 "Hide or show the foldable element at the point."
12245 (interactive)
12246 (let (comment fn pos)
12247 (save-excursion
12248 (cond
12249 ;; /* ... */ comment?
12250 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
12251 (if (js2-mode-invisible-overlay-bounds
12252 (setq pos (+ 3 (js2-node-abs-pos comment))))
12253 (progn
12254 (goto-char pos)
12255 (js2-mode-show-element))
12256 (js2-mode-hide-element)))
12257 ;; //-comment?
12258 ((save-excursion
12259 (back-to-indentation)
12260 (looking-at js2-mode-//-comment-re))
12261 (js2-mode-toggle-//-comment))
12262 ;; function?
12263 ((setq fn (js2-mode-function-at-point))
12264 (setq pos (and (js2-function-node-body fn)
12265 (js2-node-abs-pos (js2-function-node-body fn))))
12266 (goto-char (1+ pos))
12267 (if (js2-mode-invisible-overlay-bounds)
12268 (js2-mode-show-element)
12269 (js2-mode-hide-element)))
12270 (t
12271 (message "Nothing at point to hide or show"))))))
12272
12273 (defun js2-mode-hide-element ()
12274 "Fold/hide contents of a block, showing ellipses.
12275 Show the hidden text with \\[js2-mode-show-element]."
12276 (interactive)
12277 (if js2-mode-buffer-dirty-p
12278 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12279 (let (node body beg end)
12280 (cond
12281 ((js2-mode-invisible-overlay-bounds)
12282 (message "already hidden"))
12283 (t
12284 (setq node (js2-node-at-point))
12285 (cond
12286 ((js2-block-comment-p node)
12287 (js2-mode-hide-comment node))
12288 (t
12289 (while (and node (not (js2-function-node-p node)))
12290 (setq node (js2-node-parent node)))
12291 (if (and node
12292 (setq body (js2-function-node-body node)))
12293 (progn
12294 (setq beg (js2-node-abs-pos body)
12295 end (+ beg (js2-node-len body)))
12296 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12297 (message "No collapsable element found at point"))))))))
12298
12299 (defun js2-mode-show-element ()
12300 "Show the hidden element at current point."
12301 (interactive)
12302 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12303 (if bounds
12304 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12305 (message "Nothing to un-hide"))))
12306
12307 (defun js2-mode-show-all ()
12308 "Show all of the text in the buffer."
12309 (interactive)
12310 (js2-mode-flag-region (point-min) (point-max) nil))
12311
12312 (defun js2-mode-toggle-hide-functions ()
12313 (interactive)
12314 (if js2-mode-functions-hidden
12315 (js2-mode-show-functions)
12316 (js2-mode-hide-functions)))
12317
12318 (defun js2-mode-hide-functions ()
12319 "Hides all non-nested function bodies in the buffer.
12320 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12321 to open an individual entry."
12322 (interactive)
12323 (if js2-mode-buffer-dirty-p
12324 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12325 (if (null js2-mode-ast)
12326 (message "Oops - parsing failed")
12327 (setq js2-mode-functions-hidden t)
12328 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12329
12330 (defun js2-mode-function-hider (n endp)
12331 (when (not endp)
12332 (let ((tt (js2-node-type n))
12333 body beg end)
12334 (cond
12335 ((and (= tt js2-FUNCTION)
12336 (setq body (js2-function-node-body n)))
12337 (setq beg (js2-node-abs-pos body)
12338 end (+ beg (js2-node-len body)))
12339 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12340 nil) ; don't process children of function
12341 (t
12342 t))))) ; keep processing other AST nodes
12343
12344 (defun js2-mode-show-functions ()
12345 "Un-hide any folded function bodies in the buffer."
12346 (interactive)
12347 (setq js2-mode-functions-hidden nil)
12348 (save-excursion
12349 (goto-char (point-min))
12350 (while (/= (goto-char (next-overlay-change (point)))
12351 (point-max))
12352 (dolist (o (overlays-at (point)))
12353 (when (and (overlay-get o 'invisible)
12354 (not (overlay-get o 'comment)))
12355 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12356
12357 (defun js2-mode-hide-comment (n)
12358 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12359 3 ; /**
12360 2)) ; /*
12361 (beg (+ (js2-node-abs-pos n) head))
12362 (end (- (+ beg (js2-node-len n)) head 2))
12363 (o (js2-mode-flag-region beg end 'hide)))
12364 (overlay-put o 'comment t)))
12365
12366 (defun js2-mode-toggle-hide-comments ()
12367 "Folds all block comments in the buffer.
12368 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12369 to open an individual entry."
12370 (interactive)
12371 (if js2-mode-comments-hidden
12372 (js2-mode-show-comments)
12373 (js2-mode-hide-comments)))
12374
12375 (defun js2-mode-hide-comments ()
12376 (interactive)
12377 (if js2-mode-buffer-dirty-p
12378 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12379 (if (null js2-mode-ast)
12380 (message "Oops - parsing failed")
12381 (setq js2-mode-comments-hidden t)
12382 (dolist (n (js2-ast-root-comments js2-mode-ast))
12383 (when (js2-block-comment-p n)
12384 (js2-mode-hide-comment n)))
12385 (js2-mode-hide-//-comments)))
12386
12387 (defun js2-mode-extend-//-comment (direction)
12388 "Find start or end of a block of similar //-comment lines.
12389 DIRECTION is -1 to look back, 1 to look forward.
12390 INDENT is the indentation level to match.
12391 Returns the end-of-line position of the furthest adjacent
12392 //-comment line with the same indentation as the current line.
12393 If there is no such matching line, returns current end of line."
12394 (let ((pos (point-at-eol))
12395 (indent (current-indentation)))
12396 (save-excursion
12397 (while (and (zerop (forward-line direction))
12398 (looking-at js2-mode-//-comment-re)
12399 (eq indent (length (match-string 1))))
12400 (setq pos (point-at-eol)))
12401 pos)))
12402
12403 (defun js2-mode-hide-//-comments ()
12404 "Fold adjacent 1-line comments, showing only snippet of first one."
12405 (let (beg end)
12406 (save-excursion
12407 (goto-char (point-min))
12408 (while (re-search-forward js2-mode-//-comment-re nil t)
12409 (setq beg (point)
12410 end (js2-mode-extend-//-comment 1))
12411 (unless (eq beg end)
12412 (overlay-put (js2-mode-flag-region beg end 'hide)
12413 'comment t))
12414 (goto-char end)
12415 (forward-char 1)))))
12416
12417 (defun js2-mode-toggle-//-comment ()
12418 "Fold or un-fold any multi-line //-comment at point.
12419 Caller should have determined that this line starts with a //-comment."
12420 (let* ((beg (point-at-eol))
12421 (end beg))
12422 (save-excursion
12423 (goto-char end)
12424 (if (js2-mode-invisible-overlay-bounds)
12425 (js2-mode-show-element)
12426 ;; else hide the comment
12427 (setq beg (js2-mode-extend-//-comment -1)
12428 end (js2-mode-extend-//-comment 1))
12429 (unless (eq beg end)
12430 (overlay-put (js2-mode-flag-region beg end 'hide)
12431 'comment t))))))
12432
12433 (defun js2-mode-show-comments ()
12434 "Un-hide any hidden comments, leaving other hidden elements alone."
12435 (interactive)
12436 (setq js2-mode-comments-hidden nil)
12437 (save-excursion
12438 (goto-char (point-min))
12439 (while (/= (goto-char (next-overlay-change (point)))
12440 (point-max))
12441 (dolist (o (overlays-at (point)))
12442 (when (overlay-get o 'comment)
12443 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12444
12445 (defun js2-mode-display-warnings-and-errors ()
12446 "Turn on display of warnings and errors."
12447 (interactive)
12448 (setq js2-mode-show-parse-errors t
12449 js2-mode-show-strict-warnings t)
12450 (js2-reparse 'force))
12451
12452 (defun js2-mode-hide-warnings-and-errors ()
12453 "Turn off display of warnings and errors."
12454 (interactive)
12455 (setq js2-mode-show-parse-errors nil
12456 js2-mode-show-strict-warnings nil)
12457 (js2-reparse 'force))
12458
12459 (defun js2-mode-toggle-warnings-and-errors ()
12460 "Toggle the display of warnings and errors.
12461 Some users don't like having warnings/errors reported while they type."
12462 (interactive)
12463 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12464 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12465 (if (called-interactively-p 'any)
12466 (message "warnings and errors %s"
12467 (if js2-mode-show-parse-errors
12468 "enabled"
12469 "disabled")))
12470 (js2-reparse 'force))
12471
12472 (defun js2-mode-customize ()
12473 (interactive)
12474 (customize-group 'js2-mode))
12475
12476 (defun js2-mode-forward-sexp (&optional arg)
12477 "Move forward across one statement or balanced expression.
12478 With ARG, do it that many times. Negative arg -N means
12479 move backward across N balanced expressions."
12480 (interactive "p")
12481 (setq arg (or arg 1))
12482 (save-restriction
12483 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12484 (js2-reparse)
12485 (let (forward-sexp-function
12486 node (start (point)) pos lp rp child)
12487 (cond
12488 ;; backward-sexp
12489 ;; could probably make this better for some cases:
12490 ;; - if in statement block (e.g. function body), go to parent
12491 ;; - infix exprs like (foo in bar) - maybe go to beginning
12492 ;; of infix expr if in the right-side expression?
12493 ((and arg (cl-minusp arg))
12494 (dotimes (_ (- arg))
12495 (js2-backward-sws)
12496 (forward-char -1) ; Enter the node we backed up to.
12497 (when (setq node (js2-node-at-point (point) t))
12498 (setq pos (js2-node-abs-pos node))
12499 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12500 (setq lp (car parens)
12501 rp (cdr parens)))
12502 (when (and lp (> start lp))
12503 (if (and rp (<= start rp))
12504 ;; Between parens, check if there's a child node we can jump.
12505 (when (setq child (js2-node-closest-child node (point) lp t))
12506 (setq pos (js2-node-abs-pos child)))
12507 ;; Before both parens.
12508 (setq pos lp)))
12509 (let ((state (parse-partial-sexp start pos)))
12510 (goto-char (if (not (zerop (car state)))
12511 ;; Stumble at the unbalanced paren if < 0, or
12512 ;; jump a bit further if > 0.
12513 (scan-sexps start -1)
12514 pos))))
12515 (unless pos (goto-char (point-min)))))
12516 (t
12517 ;; forward-sexp
12518 (dotimes (_ arg)
12519 (js2-forward-sws)
12520 (when (setq node (js2-node-at-point (point) t))
12521 (setq pos (js2-node-abs-pos node))
12522 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12523 (setq lp (car parens)
12524 rp (cdr parens)))
12525 (or
12526 (when (and rp (<= start rp))
12527 (if (> start lp)
12528 (when (setq child (js2-node-closest-child node (point) rp))
12529 (setq pos (js2-node-abs-end child)))
12530 (setq pos (1+ rp))))
12531 ;; No parens or child nodes, looks for the end of the current node.
12532 (cl-incf pos (js2-node-len
12533 (if (js2-expr-stmt-node-p (js2-node-parent node))
12534 ;; Stop after the semicolon.
12535 (js2-node-parent node)
12536 node))))
12537 (let ((state (save-excursion (parse-partial-sexp start pos))))
12538 (goto-char (if (not (zerop (car state)))
12539 (scan-sexps start 1)
12540 pos))))
12541 (unless pos (goto-char (point-max)))))))))
12542
12543 (defun js2-mode-forward-sexp-parens (node abs-pos)
12544 "Return a cons cell with positions of main parens in NODE."
12545 (cond
12546 ((or (js2-array-node-p node)
12547 (js2-object-node-p node)
12548 (js2-comp-node-p node)
12549 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12550 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12551 ((js2-paren-expr-node-p node)
12552 (let ((lp (js2-node-lp node))
12553 (rp (js2-node-rp node)))
12554 (cons (when lp (+ abs-pos lp))
12555 (when rp (+ abs-pos rp)))))))
12556
12557 (defun js2-node-closest-child (parent point limit &optional before)
12558 (let* ((parent-pos (js2-node-abs-pos parent))
12559 (rpoint (- point parent-pos))
12560 (rlimit (- limit parent-pos))
12561 (min (min rpoint rlimit))
12562 (max (max rpoint rlimit))
12563 found)
12564 (catch 'done
12565 (js2-visit-ast
12566 parent
12567 (lambda (node _end-p)
12568 (if (eq node parent)
12569 t
12570 (let ((pos (js2-node-pos node)) ;; Both relative values.
12571 (end (+ (js2-node-pos node) (js2-node-len node))))
12572 (when (and (>= pos min) (<= end max)
12573 (if before (< pos rpoint) (> end rpoint)))
12574 (setq found node))
12575 (when (> end rpoint)
12576 (throw 'done nil)))
12577 nil))))
12578 found))
12579
12580 (defun js2-errors ()
12581 "Return a list of errors found."
12582 (and js2-mode-ast
12583 (js2-ast-root-errors js2-mode-ast)))
12584
12585 (defun js2-warnings ()
12586 "Return a list of warnings found."
12587 (and js2-mode-ast
12588 (js2-ast-root-warnings js2-mode-ast)))
12589
12590 (defun js2-have-errors-p ()
12591 "Return non-nil if any parse errors or warnings were found."
12592 (or (js2-errors) (js2-warnings)))
12593
12594 (defun js2-errors-and-warnings ()
12595 "Return a copy of the concatenated errors and warnings lists.
12596 They are appended: first the errors, then the warnings.
12597 Entries are of the form (MSG BEG END)."
12598 (when js2-mode-ast
12599 (append (js2-ast-root-errors js2-mode-ast)
12600 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12601
12602 (defun js2-next-error (&optional arg reset)
12603 "Move to next parse error.
12604 Typically invoked via \\[next-error].
12605 ARG is the number of errors, forward or backward, to move.
12606 RESET means start over from the beginning."
12607 (interactive "p")
12608 (if (not (or (js2-errors) (js2-warnings)))
12609 (message "No errors")
12610 (when reset
12611 (goto-char (point-min)))
12612 (let* ((errs (js2-errors-and-warnings))
12613 (continue t)
12614 (start (point))
12615 (count (or arg 1))
12616 (backward (cl-minusp count))
12617 (sorter (if backward '> '<))
12618 (stopper (if backward '< '>))
12619 (count (abs count))
12620 all-errs err)
12621 ;; Sort by start position.
12622 (setq errs (sort errs (lambda (e1 e2)
12623 (funcall sorter (cl-second e1) (cl-second e2))))
12624 all-errs errs)
12625 ;; Find nth error with pos > start.
12626 (while (and errs continue)
12627 (when (funcall stopper (cl-cadar errs) start)
12628 (setq err (car errs))
12629 (if (zerop (cl-decf count))
12630 (setq continue nil)))
12631 (setq errs (cdr errs)))
12632 ;; Clear for `js2-echo-error'.
12633 (message nil)
12634 (if err
12635 (goto-char (cl-second err))
12636 ;; Wrap around to first error.
12637 (goto-char (cl-second (car all-errs)))
12638 ;; If we were already on it, echo msg again.
12639 (if (= (point) start)
12640 (js2-echo-error (point) (point)))))))
12641
12642 (defun js2-down-mouse-3 ()
12643 "Make right-click move the point to the click location.
12644 This makes right-click context menu operations a bit more intuitive.
12645 The point will not move if the region is active, however, to avoid
12646 destroying the region selection."
12647 (interactive)
12648 (when (and js2-move-point-on-right-click
12649 (not mark-active))
12650 (let ((e last-input-event))
12651 (ignore-errors
12652 (goto-char (cl-cadadr e))))))
12653
12654 (defun js2-mode-create-imenu-index ()
12655 "Return an alist for `imenu--index-alist'."
12656 ;; This is built up in `js2-parse-record-imenu' during parsing.
12657 (when js2-mode-ast
12658 ;; if we have an ast but no recorder, they're requesting a rescan
12659 (unless js2-imenu-recorder
12660 (js2-reparse 'force))
12661 (prog1
12662 (js2-build-imenu-index)
12663 (setq js2-imenu-recorder nil
12664 js2-imenu-function-map nil))))
12665
12666 (defun js2-mode-find-tag ()
12667 "Replacement for `find-tag-default'.
12668 `find-tag-default' returns a ridiculous answer inside comments."
12669 (let (beg end)
12670 (save-excursion
12671 (if (looking-at "\\_>")
12672 (setq beg (progn (forward-symbol -1) (point))
12673 end (progn (forward-symbol 1) (point)))
12674 (setq beg (progn (forward-symbol 1) (point))
12675 end (progn (forward-symbol -1) (point))))
12676 (replace-regexp-in-string
12677 "[\"']" ""
12678 (buffer-substring-no-properties beg end)))))
12679
12680 (defun js2-mode-forward-sibling ()
12681 "Move to the end of the sibling following point in parent.
12682 Returns non-nil if successful, or nil if there was no following sibling."
12683 (let* ((node (js2-node-at-point))
12684 (parent (js2-mode-find-enclosing-fn node))
12685 sib)
12686 (when (setq sib (js2-node-find-child-after (point) parent))
12687 (goto-char (+ (js2-node-abs-pos sib)
12688 (js2-node-len sib))))))
12689
12690 (defun js2-mode-backward-sibling ()
12691 "Move to the beginning of the sibling node preceding point in parent.
12692 Parent is defined as the enclosing script or function."
12693 (let* ((node (js2-node-at-point))
12694 (parent (js2-mode-find-enclosing-fn node))
12695 sib)
12696 (when (setq sib (js2-node-find-child-before (point) parent))
12697 (goto-char (js2-node-abs-pos sib)))))
12698
12699 (defun js2-beginning-of-defun (&optional arg)
12700 "Go to line on which current function starts, and return t on success.
12701 If we're not in a function or already at the beginning of one, go
12702 to beginning of previous script-level element.
12703 With ARG N, do that N times. If N is negative, move forward."
12704 (setq arg (or arg 1))
12705 (if (cl-plusp arg)
12706 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12707 (when (cond
12708 ((js2-function-node-p parent)
12709 (goto-char (js2-node-abs-pos parent)))
12710 (t
12711 (js2-mode-backward-sibling)))
12712 (if (> arg 1)
12713 (js2-beginning-of-defun (1- arg))
12714 t)))
12715 (when (js2-end-of-defun)
12716 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12717
12718 (defun js2-end-of-defun ()
12719 "Go to the char after the last position of the current function
12720 or script-level element."
12721 (let* ((node (js2-node-at-point))
12722 (parent (or (and (js2-function-node-p node) node)
12723 (js2-node-parent-script-or-fn node)))
12724 script)
12725 (unless (js2-function-node-p parent)
12726 ;; Use current script-level node, or, if none, the next one.
12727 (setq script (or parent node)
12728 parent (js2-node-find-child-before (point) script))
12729 (when (or (null parent)
12730 (>= (point) (+ (js2-node-abs-pos parent)
12731 (js2-node-len parent))))
12732 (setq parent (js2-node-find-child-after (point) script))))
12733 (when parent
12734 (goto-char (+ (js2-node-abs-pos parent)
12735 (js2-node-len parent))))))
12736
12737 (defun js2-mark-defun (&optional allow-extend)
12738 "Put mark at end of this function, point at beginning.
12739 The function marked is the one that contains point.
12740
12741 Interactively, if this command is repeated,
12742 or (in Transient Mark mode) if the mark is active,
12743 it marks the next defun after the ones already marked."
12744 (interactive "p")
12745 (let (extended)
12746 (when (and allow-extend
12747 (or (and (eq last-command this-command) (mark t))
12748 (and transient-mark-mode mark-active)))
12749 (let ((sib (save-excursion
12750 (goto-char (mark))
12751 (if (js2-mode-forward-sibling)
12752 (point)))))
12753 (if sib
12754 (progn
12755 (set-mark sib)
12756 (setq extended t))
12757 ;; no more siblings - try extending to enclosing node
12758 (goto-char (mark t)))))
12759 (when (not extended)
12760 (let ((node (js2-node-at-point (point) t)) ; skip comments
12761 ast fn stmt parent beg end)
12762 (when (js2-ast-root-p node)
12763 (setq ast node
12764 node (or (js2-node-find-child-after (point) node)
12765 (js2-node-find-child-before (point) node))))
12766 ;; only mark whole buffer if we can't find any children
12767 (if (null node)
12768 (setq node ast))
12769 (if (js2-function-node-p node)
12770 (setq parent node)
12771 (setq fn (js2-mode-find-enclosing-fn node)
12772 stmt (if (or (null fn)
12773 (js2-ast-root-p fn))
12774 (js2-mode-find-first-stmt node))
12775 parent (or stmt fn)))
12776 (setq beg (js2-node-abs-pos parent)
12777 end (+ beg (js2-node-len parent)))
12778 (push-mark beg)
12779 (goto-char end)
12780 (exchange-point-and-mark)))))
12781
12782 (defun js2-narrow-to-defun ()
12783 "Narrow to the function enclosing point."
12784 (interactive)
12785 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12786 (fn (if (js2-script-node-p node)
12787 node
12788 (js2-mode-find-enclosing-fn node)))
12789 (beg (js2-node-abs-pos fn)))
12790 (unless (js2-ast-root-p fn)
12791 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12792
12793 (provide 'js2-mode)
12794
12795 ;;; js2-mode.el ends here