]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Generalize object literal parsing to support short-hand function/generator/getter...
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2015 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20150202
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (require 'cl-lib)
89 (require 'imenu)
90 (require 'cc-cmds) ; for `c-fill-paragraph'
91
92 (eval-and-compile
93 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
94 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
95
96 (defvar electric-layout-rules)
97
98 ;;; Externs (variables presumed to be defined by the host system)
99
100 (defvar js2-ecma-262-externs
101 (mapcar 'symbol-name
102 '(Array Boolean Date Error EvalError Function Infinity JSON
103 Math NaN Number Object RangeError ReferenceError RegExp
104 String SyntaxError TypeError URIError
105 decodeURI decodeURIComponent encodeURI
106 encodeURIComponent escape eval isFinite isNaN
107 parseFloat parseInt undefined unescape))
108 "Ecma-262 externs. Included in `js2-externs' by default.")
109
110 (defvar js2-browser-externs
111 (mapcar 'symbol-name
112 '(;; DOM level 1
113 Attr CDATASection CharacterData Comment DOMException
114 DOMImplementation Document DocumentFragment
115 DocumentType Element Entity EntityReference
116 ExceptionCode NamedNodeMap Node NodeList Notation
117 ProcessingInstruction Text
118
119 ;; DOM level 2
120 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
121 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
122 HTMLBodyElement HTMLButtonElement HTMLCollection
123 HTMLDListElement HTMLDirectoryElement HTMLDivElement
124 HTMLDocument HTMLElement HTMLFieldSetElement
125 HTMLFontElement HTMLFormElement HTMLFrameElement
126 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
127 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
128 HTMLImageElement HTMLInputElement HTMLIsIndexElement
129 HTMLLIElement HTMLLabelElement HTMLLegendElement
130 HTMLLinkElement HTMLMapElement HTMLMenuElement
131 HTMLMetaElement HTMLModElement HTMLOListElement
132 HTMLObjectElement HTMLOptGroupElement
133 HTMLOptionElement HTMLOptionsCollection
134 HTMLParagraphElement HTMLParamElement HTMLPreElement
135 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
136 HTMLStyleElement HTMLTableCaptionElement
137 HTMLTableCellElement HTMLTableColElement
138 HTMLTableElement HTMLTableRowElement
139 HTMLTableSectionElement HTMLTextAreaElement
140 HTMLTitleElement HTMLUListElement
141
142 ;; DOM level 3
143 DOMConfiguration DOMError DOMException
144 DOMImplementationList DOMImplementationSource
145 DOMLocator DOMStringList NameList TypeInfo
146 UserDataHandler
147
148 ;; Window
149 window alert confirm document java navigator prompt screen
150 self top requestAnimationFrame cancelAnimationFrame
151
152 ;; W3C CSS
153 CSSCharsetRule CSSFontFace CSSFontFaceRule
154 CSSImportRule CSSMediaRule CSSPageRule
155 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
156 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
157 CSSValue CSSValueList Counter DOMImplementationCSS
158 DocumentCSS DocumentStyle ElementCSSInlineStyle
159 LinkStyle MediaList RGBColor Rect StyleSheet
160 StyleSheetList ViewCSS
161
162 ;; W3C Event
163 EventListener EventTarget Event DocumentEvent UIEvent
164 MouseEvent MutationEvent KeyboardEvent
165
166 ;; W3C Range
167 DocumentRange Range RangeException
168
169 ;; W3C XML
170 XPathResult XMLHttpRequest
171
172 ;; console object. Provided by at least Chrome and Firefox.
173 console))
174 "Browser externs.
175 You can cause these to be included or excluded with the custom
176 variable `js2-include-browser-externs'.")
177
178 (defvar js2-rhino-externs
179 (mapcar 'symbol-name
180 '(Packages importClass importPackage com org java
181 ;; Global object (shell) externs.
182 defineClass deserialize doctest gc help load
183 loadClass print quit readFile readUrl runCommand seal
184 serialize spawn sync toint32 version))
185 "Mozilla Rhino externs.
186 Set `js2-include-rhino-externs' to t to include them.")
187
188 (defvar js2-node-externs
189 (mapcar 'symbol-name
190 '(__dirname __filename Buffer clearInterval clearTimeout require
191 console exports global module process setInterval setTimeout))
192 "Node.js externs.
193 Set `js2-include-node-externs' to t to include them.")
194
195 (defvar js2-typed-array-externs
196 (mapcar 'symbol-name
197 '(ArrayBuffer Uint8ClampedArray DataView
198 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
199 Float32Array Float64Array))
200 "Khronos typed array externs. Available in most modern browsers and
201 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
202 are enabled, these will also be included.")
203
204 (defvar js2-harmony-externs
205 (mapcar 'symbol-name
206 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
207 "ES6 externs. If `js2-include-browser-externs' is enabled and
208 `js2-language-version' is sufficiently high, these will be included.")
209
210 ;;; Variables
211
212 (defun js2-mark-safe-local (name pred)
213 "Make the variable NAME buffer-local and mark it as safe file-local
214 variable with predicate PRED."
215 (make-variable-buffer-local name)
216 (put name 'safe-local-variable pred))
217
218 (defcustom js2-highlight-level 2
219 "Amount of syntax highlighting to perform.
220 0 or a negative value means none.
221 1 adds basic syntax highlighting.
222 2 adds highlighting of some Ecma built-in properties.
223 3 adds highlighting of many Ecma built-in functions."
224 :group 'js2-mode
225 :type '(choice (const :tag "None" 0)
226 (const :tag "Basic" 1)
227 (const :tag "Include Properties" 2)
228 (const :tag "Include Functions" 3)))
229
230 (defvar js2-mode-dev-mode-p nil
231 "Non-nil if running in development mode. Normally nil.")
232
233 (defgroup js2-mode nil
234 "An improved JavaScript mode."
235 :group 'languages)
236
237 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
238 (numberp c-basic-offset))
239 c-basic-offset
240 4)
241 "Number of spaces to indent nested statements.
242 Similar to `c-basic-offset'."
243 :group 'js2-mode
244 :type 'integer)
245 (js2-mark-safe-local 'js2-basic-offset 'integerp)
246
247 (defcustom js2-bounce-indent-p nil
248 "Non-nil to have indent-line function choose among alternatives.
249 If nil, the indent-line function will indent to a predetermined column
250 based on heuristic guessing. If non-nil, then if the current line is
251 already indented to that predetermined column, indenting will choose
252 another likely column and indent to that spot. Repeated invocation of
253 the indent-line function will cycle among the computed alternatives.
254 See the function `js2-bounce-indent' for details. When it is non-nil,
255 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
256 :type 'boolean
257 :group 'js2-mode)
258
259 (defcustom js2-pretty-multiline-declarations t
260 "Non-nil to line up multiline declarations vertically:
261
262 var a = 10,
263 b = 20,
264 c = 30;
265
266 If the value is t, and the first assigned value in the
267 declaration is a function/array/object literal spanning several
268 lines, it won't be indented additionally:
269
270 var o = { var bar = 2,
271 foo: 3 vs. o = {
272 }, foo: 3
273 bar = 2; };
274
275 If the value is `all', it will always be indented additionally:
276
277 var o = {
278 foo: 3
279 };
280
281 var o = {
282 foo: 3
283 },
284 bar = 2;
285
286 If the value is `dynamic', it will be indented additionally only
287 if the declaration contains more than one variable:
288
289 var o = {
290 foo: 3
291 };
292
293 var o = {
294 foo: 3
295 },
296 bar = 2;"
297 :group 'js2-mode
298 :type 'symbol)
299 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
300
301 (defcustom js2-indent-switch-body nil
302 "When nil, case labels are indented on the same level as the
303 containing switch statement. Otherwise, all lines inside
304 switch statement body are indented one additional level."
305 :type 'boolean
306 :group 'js2-mode)
307 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
308
309 (defcustom js2-idle-timer-delay 0.2
310 "Delay in secs before re-parsing after user makes changes.
311 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
312 :type 'number
313 :group 'js2-mode)
314 (make-variable-buffer-local 'js2-idle-timer-delay)
315
316 (defcustom js2-dynamic-idle-timer-adjust 0
317 "Positive to adjust `js2-idle-timer-delay' based on file size.
318 The idea is that for short files, parsing is faster so we can be
319 more responsive to user edits without interfering with editing.
320 The buffer length in characters (typically bytes) is divided by
321 this value and used to multiply `js2-idle-timer-delay' for the
322 buffer. For example, a 21k file and 10k adjust yields 21k/10k
323 == 2, so js2-idle-timer-delay is multiplied by 2.
324 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
325 `js2-idle-timer-delay' is not dependent on the file size."
326 :type 'number
327 :group 'js2-mode)
328
329 (defcustom js2-concat-multiline-strings t
330 "When non-nil, `js2-line-break' in mid-string will make it a
331 string concatenation. When `eol', the '+' will be inserted at the
332 end of the line, otherwise, at the beginning of the next line."
333 :type '(choice (const t) (const eol) (const nil))
334 :group 'js2-mode)
335
336 (defcustom js2-mode-show-parse-errors t
337 "True to highlight parse errors."
338 :type 'boolean
339 :group 'js2-mode)
340
341 (defcustom js2-mode-show-strict-warnings t
342 "Non-nil to emit Ecma strict-mode warnings.
343 Some of the warnings can be individually disabled by other flags,
344 even if this flag is non-nil."
345 :type 'boolean
346 :group 'js2-mode)
347
348 (defcustom js2-strict-trailing-comma-warning t
349 "Non-nil to warn about trailing commas in array literals.
350 Ecma-262-5.1 allows them, but older versions of IE raise an error."
351 :type 'boolean
352 :group 'js2-mode)
353
354 (defcustom js2-strict-missing-semi-warning t
355 "Non-nil to warn about semicolon auto-insertion after statement.
356 Technically this is legal per Ecma-262, but some style guides disallow
357 depending on it."
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-missing-semi-one-line-override nil
362 "Non-nil to permit missing semicolons in one-line functions.
363 In one-liner functions such as `function identity(x) {return x}'
364 people often omit the semicolon for a cleaner look. If you are
365 such a person, you can suppress the missing-semicolon warning
366 by setting this variable to t."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-strict-inconsistent-return-warning t
371 "Non-nil to warn about mixing returns with value-returns.
372 It's perfectly legal to have a `return' and a `return foo' in the
373 same function, but it's often an indicator of a bug, and it also
374 interferes with type inference (in systems that support it.)"
375 :type 'boolean
376 :group 'js2-mode)
377
378 (defcustom js2-strict-cond-assign-warning t
379 "Non-nil to warn about expressions like if (a = b).
380 This often should have been '==' instead of '='. If the warning
381 is enabled, you can suppress it on a per-expression basis by
382 parenthesizing the expression, e.g. if ((a = b)) ..."
383 :type 'boolean
384 :group 'js2-mode)
385
386 (defcustom js2-strict-var-redeclaration-warning t
387 "Non-nil to warn about redeclaring variables in a script or function."
388 :type 'boolean
389 :group 'js2-mode)
390
391 (defcustom js2-strict-var-hides-function-arg-warning t
392 "Non-nil to warn about a var decl hiding a function argument."
393 :type 'boolean
394 :group 'js2-mode)
395
396 (defcustom js2-skip-preprocessor-directives nil
397 "Non-nil to treat lines beginning with # as comments.
398 Useful for viewing Mozilla JavaScript source code."
399 :type 'boolean
400 :group 'js2-mode)
401
402 (defcustom js2-language-version 200
403 "Configures what JavaScript language version to recognize.
404 Currently versions 150, 160, 170, 180 and 200 are supported,
405 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
406 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
407 yield, and Array comprehensions, and 1.8 adds function closures."
408 :type 'integer
409 :group 'js2-mode)
410
411 (defcustom js2-instanceof-has-side-effects nil
412 "If non-nil, treats the instanceof operator as having side effects.
413 This is useful for xulrunner apps."
414 :type 'boolean
415 :group 'js2-mode)
416
417 (defcustom js2-move-point-on-right-click t
418 "Non-nil to move insertion point when you right-click.
419 This makes right-click context menu behavior a bit more intuitive,
420 since menu operations generally apply to the point. The exception
421 is if there is a region selection, in which case the point does -not-
422 move, so cut/copy/paste can work properly.
423
424 Note that IntelliJ moves the point, and Eclipse leaves it alone,
425 so this behavior is customizable."
426 :group 'js2-mode
427 :type 'boolean)
428
429 (defcustom js2-allow-rhino-new-expr-initializer t
430 "Non-nil to support a Rhino's experimental syntactic construct.
431
432 Rhino supports the ability to follow a `new' expression with an object
433 literal, which is used to set additional properties on the new object
434 after calling its constructor. Syntax:
435
436 new <expr> [ ( arglist ) ] [initializer]
437
438 Hence, this expression:
439
440 new Object {a: 1, b: 2}
441
442 results in an Object with properties a=1 and b=2. This syntax is
443 apparently not configurable in Rhino - it's currently always enabled,
444 as of Rhino version 1.7R2."
445 :type 'boolean
446 :group 'js2-mode)
447
448 (defcustom js2-allow-member-expr-as-function-name nil
449 "Non-nil to support experimental Rhino syntax for function names.
450
451 Rhino supports an experimental syntax configured via the Rhino Context
452 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
453
454 function <member-expr> ( [ arg-list ] ) { <body> }
455
456 Where member-expr is a non-parenthesized 'member expression', which
457 is anything at the grammar level of a new-expression or lower, meaning
458 any expression that does not involve infix or unary operators.
459
460 When <member-expr> is not a simple identifier, then it is syntactic
461 sugar for assigning the anonymous function to the <member-expr>. Hence,
462 this code:
463
464 function a.b().c[2] (x, y) { ... }
465
466 is rewritten as:
467
468 a.b().c[2] = function(x, y) {...}
469
470 which doesn't seem particularly useful, but Rhino permits it."
471 :type 'boolean
472 :group 'js2-mode)
473
474 ;; scanner variables
475
476 (defmacro js2-deflocal (name value &optional comment)
477 "Define a buffer-local variable NAME with VALUE and COMMENT."
478 (declare (debug defvar) (doc-string 3))
479 `(progn
480 (defvar ,name ,value ,comment)
481 (make-variable-buffer-local ',name)))
482
483 (defvar js2-EOF_CHAR -1
484 "Represents end of stream. Distinct from js2-EOF token type.")
485
486 ;; I originally used symbols to represent tokens, but Rhino uses
487 ;; ints and then sets various flag bits in them, so ints it is.
488 ;; The upshot is that we need a `js2-' prefix in front of each name.
489 (defvar js2-ERROR -1)
490 (defvar js2-EOF 0)
491 (defvar js2-EOL 1)
492 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
493 (defvar js2-LEAVEWITH 3)
494 (defvar js2-RETURN 4)
495 (defvar js2-GOTO 5)
496 (defvar js2-IFEQ 6)
497 (defvar js2-IFNE 7)
498 (defvar js2-SETNAME 8)
499 (defvar js2-BITOR 9)
500 (defvar js2-BITXOR 10)
501 (defvar js2-BITAND 11)
502 (defvar js2-EQ 12)
503 (defvar js2-NE 13)
504 (defvar js2-LT 14)
505 (defvar js2-LE 15)
506 (defvar js2-GT 16)
507 (defvar js2-GE 17)
508 (defvar js2-LSH 18)
509 (defvar js2-RSH 19)
510 (defvar js2-URSH 20)
511 (defvar js2-ADD 21) ; infix plus
512 (defvar js2-SUB 22) ; infix minus
513 (defvar js2-MUL 23)
514 (defvar js2-DIV 24)
515 (defvar js2-MOD 25)
516 (defvar js2-NOT 26)
517 (defvar js2-BITNOT 27)
518 (defvar js2-POS 28) ; unary plus
519 (defvar js2-NEG 29) ; unary minus
520 (defvar js2-NEW 30)
521 (defvar js2-DELPROP 31)
522 (defvar js2-TYPEOF 32)
523 (defvar js2-GETPROP 33)
524 (defvar js2-GETPROPNOWARN 34)
525 (defvar js2-SETPROP 35)
526 (defvar js2-GETELEM 36)
527 (defvar js2-SETELEM 37)
528 (defvar js2-CALL 38)
529 (defvar js2-NAME 39) ; an identifier
530 (defvar js2-NUMBER 40)
531 (defvar js2-STRING 41)
532 (defvar js2-NULL 42)
533 (defvar js2-THIS 43)
534 (defvar js2-FALSE 44)
535 (defvar js2-TRUE 45)
536 (defvar js2-SHEQ 46) ; shallow equality (===)
537 (defvar js2-SHNE 47) ; shallow inequality (!==)
538 (defvar js2-REGEXP 48)
539 (defvar js2-BINDNAME 49)
540 (defvar js2-THROW 50)
541 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
542 (defvar js2-IN 52)
543 (defvar js2-INSTANCEOF 53)
544 (defvar js2-LOCAL_LOAD 54)
545 (defvar js2-GETVAR 55)
546 (defvar js2-SETVAR 56)
547 (defvar js2-CATCH_SCOPE 57)
548 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
549 (defvar js2-ENUM_INIT_VALUES 59)
550 (defvar js2-ENUM_INIT_ARRAY 60)
551 (defvar js2-ENUM_NEXT 61)
552 (defvar js2-ENUM_ID 62)
553 (defvar js2-THISFN 63)
554 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
555 (defvar js2-ARRAYLIT 65) ; array literal
556 (defvar js2-OBJECTLIT 66) ; object literal
557 (defvar js2-GET_REF 67) ; *reference
558 (defvar js2-SET_REF 68) ; *reference = something
559 (defvar js2-DEL_REF 69) ; delete reference
560 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
561 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
562 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
563
564 ;; XML support
565 (defvar js2-DEFAULTNAMESPACE 73)
566 (defvar js2-ESCXMLATTR 74)
567 (defvar js2-ESCXMLTEXT 75)
568 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
569 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
570 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
571 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
572
573 (defvar js2-first-bytecode js2-ENTERWITH)
574 (defvar js2-last-bytecode js2-REF_NS_NAME)
575
576 (defvar js2-TRY 80)
577 (defvar js2-SEMI 81) ; semicolon
578 (defvar js2-LB 82) ; left and right brackets
579 (defvar js2-RB 83)
580 (defvar js2-LC 84) ; left and right curly-braces
581 (defvar js2-RC 85)
582 (defvar js2-LP 86) ; left and right parens
583 (defvar js2-RP 87)
584 (defvar js2-COMMA 88) ; comma operator
585
586 (defvar js2-ASSIGN 89) ; simple assignment (=)
587 (defvar js2-ASSIGN_BITOR 90) ; |=
588 (defvar js2-ASSIGN_BITXOR 91) ; ^=
589 (defvar js2-ASSIGN_BITAND 92) ; &=
590 (defvar js2-ASSIGN_LSH 93) ; <<=
591 (defvar js2-ASSIGN_RSH 94) ; >>=
592 (defvar js2-ASSIGN_URSH 95) ; >>>=
593 (defvar js2-ASSIGN_ADD 96) ; +=
594 (defvar js2-ASSIGN_SUB 97) ; -=
595 (defvar js2-ASSIGN_MUL 98) ; *=
596 (defvar js2-ASSIGN_DIV 99) ; /=
597 (defvar js2-ASSIGN_MOD 100) ; %=
598
599 (defvar js2-first-assign js2-ASSIGN)
600 (defvar js2-last-assign js2-ASSIGN_MOD)
601
602 (defvar js2-HOOK 101) ; conditional (?:)
603 (defvar js2-COLON 102)
604 (defvar js2-OR 103) ; logical or (||)
605 (defvar js2-AND 104) ; logical and (&&)
606 (defvar js2-INC 105) ; increment/decrement (++ --)
607 (defvar js2-DEC 106)
608 (defvar js2-DOT 107) ; member operator (.)
609 (defvar js2-FUNCTION 108) ; function keyword
610 (defvar js2-EXPORT 109) ; export keyword
611 (defvar js2-IMPORT 110) ; import keyword
612 (defvar js2-IF 111) ; if keyword
613 (defvar js2-ELSE 112) ; else keyword
614 (defvar js2-SWITCH 113) ; switch keyword
615 (defvar js2-CASE 114) ; case keyword
616 (defvar js2-DEFAULT 115) ; default keyword
617 (defvar js2-WHILE 116) ; while keyword
618 (defvar js2-DO 117) ; do keyword
619 (defvar js2-FOR 118) ; for keyword
620 (defvar js2-BREAK 119) ; break keyword
621 (defvar js2-CONTINUE 120) ; continue keyword
622 (defvar js2-VAR 121) ; var keyword
623 (defvar js2-WITH 122) ; with keyword
624 (defvar js2-CATCH 123) ; catch keyword
625 (defvar js2-FINALLY 124) ; finally keyword
626 (defvar js2-VOID 125) ; void keyword
627 (defvar js2-RESERVED 126) ; reserved keywords
628
629 (defvar js2-EMPTY 127)
630
631 ;; Types used for the parse tree - never returned by scanner.
632
633 (defvar js2-BLOCK 128) ; statement block
634 (defvar js2-LABEL 129) ; label
635 (defvar js2-TARGET 130)
636 (defvar js2-LOOP 131)
637 (defvar js2-EXPR_VOID 132) ; expression statement in functions
638 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
639 (defvar js2-JSR 134)
640 (defvar js2-SCRIPT 135) ; top-level node for entire script
641 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
642 (defvar js2-USE_STACK 137)
643 (defvar js2-SETPROP_OP 138) ; x.y op= something
644 (defvar js2-SETELEM_OP 139) ; x[y] op= something
645 (defvar js2-LOCAL_BLOCK 140)
646 (defvar js2-SET_REF_OP 141) ; *reference op= something
647
648 ;; For XML support:
649 (defvar js2-DOTDOT 142) ; member operator (..)
650 (defvar js2-COLONCOLON 143) ; namespace::name
651 (defvar js2-XML 144) ; XML type
652 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
653 (defvar js2-XMLATTR 146) ; @
654 (defvar js2-XMLEND 147)
655
656 ;; Optimizer-only tokens
657 (defvar js2-TO_OBJECT 148)
658 (defvar js2-TO_DOUBLE 149)
659
660 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
661 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
662 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
663 (defvar js2-CONST 153)
664 (defvar js2-SETCONST 154)
665 (defvar js2-SETCONSTVAR 155)
666 (defvar js2-ARRAYCOMP 156)
667 (defvar js2-LETEXPR 157)
668 (defvar js2-WITHEXPR 158)
669 (defvar js2-DEBUGGER 159)
670
671 (defvar js2-COMMENT 160)
672 (defvar js2-TRIPLEDOT 161) ; for rest parameter
673 (defvar js2-ARROW 162) ; function arrow (=>)
674 (defvar js2-CLASS 163)
675 (defvar js2-EXTENDS 164)
676 (defvar js2-SUPER 165)
677 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
678 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
679 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
680
681 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
682
683 (defconst js2-debug-print-trees nil)
684
685 ;; Rhino accepts any string or stream as input. Emacs character
686 ;; processing works best in buffers, so we'll assume the input is a
687 ;; buffer. JavaScript strings can be copied into temp buffers before
688 ;; scanning them.
689
690 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
691 ;; They're the Emacs equivalent of instance variables, more or less.
692
693 (js2-deflocal js2-ts-dirty-line nil
694 "Token stream buffer-local variable.
695 Indicates stuff other than whitespace since start of line.")
696
697 (js2-deflocal js2-ts-hit-eof nil
698 "Token stream buffer-local variable.")
699
700 ;; FIXME: Unused.
701 (js2-deflocal js2-ts-line-start 0
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-lineno 1
705 "Token stream buffer-local variable.")
706
707 ;; FIXME: Unused.
708 (js2-deflocal js2-ts-line-end-char -1
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
712 "Token stream buffer-local variable.
713 Current scan position.")
714
715 ;; FIXME: Unused.
716 (js2-deflocal js2-ts-is-xml-attribute nil
717 "Token stream buffer-local variable.")
718
719 (js2-deflocal js2-ts-xml-is-tag-content nil
720 "Token stream buffer-local variable.")
721
722 (js2-deflocal js2-ts-xml-open-tags-count 0
723 "Token stream buffer-local variable.")
724
725 (js2-deflocal js2-ts-string-buffer nil
726 "Token stream buffer-local variable.
727 List of chars built up while scanning various tokens.")
728
729 (cl-defstruct (js2-token
730 (:constructor nil)
731 (:constructor make-js2-token (beg)))
732 "Value returned from the token stream."
733 (type js2-EOF)
734 (beg 1)
735 (end -1)
736 (string "")
737 number
738 regexp-flags
739 comment-type
740 follows-eol-p)
741
742 ;; Have to call `js2-init-scanner' to initialize the values.
743 (js2-deflocal js2-ti-tokens nil)
744 (js2-deflocal js2-ti-tokens-cursor nil)
745 (js2-deflocal js2-ti-lookahead nil)
746
747 (cl-defstruct (js2-ts-state
748 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
749 (cursor js2-ts-cursor)
750 (tokens (copy-sequence js2-ti-tokens))
751 (tokens-cursor js2-ti-tokens-cursor)
752 (lookahead js2-ti-lookahead))))
753 lineno
754 cursor
755 tokens
756 tokens-cursor
757 lookahead)
758
759 ;;; Parser variables
760
761 (js2-deflocal js2-parsed-errors nil
762 "List of errors produced during scanning/parsing.")
763
764 (js2-deflocal js2-parsed-warnings nil
765 "List of warnings produced during scanning/parsing.")
766
767 (js2-deflocal js2-recover-from-parse-errors t
768 "Non-nil to continue parsing after a syntax error.
769
770 In recovery mode, the AST will be built in full, and any error
771 nodes will be flagged with appropriate error information. If
772 this flag is nil, a syntax error will result in an error being
773 signaled.
774
775 The variable is automatically buffer-local, because different
776 modes that use the parser will need different settings.")
777
778 (js2-deflocal js2-parse-hook nil
779 "List of callbacks for receiving parsing progress.")
780
781 (defvar js2-parse-finished-hook nil
782 "List of callbacks to notify when parsing finishes.
783 Not called if parsing was interrupted.")
784
785 (js2-deflocal js2-is-eval-code nil
786 "True if we're evaluating code in a string.
787 If non-nil, the tokenizer will record the token text, and the AST nodes
788 will record their source text. Off by default for IDE modes, since the
789 text is available in the buffer.")
790
791 (defvar js2-parse-ide-mode t
792 "Non-nil if the parser is being used for `js2-mode'.
793 If non-nil, the parser will set text properties for fontification
794 and the syntax table. The value should be nil when using the
795 parser as a frontend to an interpreter or byte compiler.")
796
797 ;;; Parser instance variables (buffer-local vars for js2-parse)
798
799 (defconst js2-ti-after-eol (lsh 1 16)
800 "Flag: first token of the source line.")
801
802 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
803
804 (js2-deflocal js2-compiler-generate-debug-info t)
805 (js2-deflocal js2-compiler-use-dynamic-scope nil)
806 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
807 (js2-deflocal js2-compiler-xml-available t)
808 (js2-deflocal js2-compiler-optimization-level 0)
809 (js2-deflocal js2-compiler-generating-source t)
810 (js2-deflocal js2-compiler-strict-mode nil)
811 (js2-deflocal js2-compiler-report-warning-as-error nil)
812 (js2-deflocal js2-compiler-generate-observer-count nil)
813 (js2-deflocal js2-compiler-activation-names nil)
814
815 ;; SKIP: sourceURI
816
817 ;; There's a compileFunction method in Context.java - may need it.
818 (js2-deflocal js2-called-by-compile-function nil
819 "True if `js2-parse' was called by `js2-compile-function'.
820 Will only be used when we finish implementing the interpreter.")
821
822 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
823
824 ;; SKIP: node factory - we're going to just call functions directly,
825 ;; and eventually go to a unified AST format.
826
827 (js2-deflocal js2-nesting-of-function 0)
828
829 (js2-deflocal js2-recorded-identifiers nil
830 "Tracks identifiers found during parsing.")
831
832 (js2-deflocal js2-is-in-destructuring nil
833 "True while parsing destructuring expression.")
834
835 (defcustom js2-global-externs nil
836 "A list of any extern names you'd like to consider always declared.
837 This list is global and is used by all `js2-mode' files.
838 You can create buffer-local externs list using `js2-additional-externs'.
839
840 There is also a buffer-local variable `js2-default-externs',
841 which is initialized by default to include the Ecma-262 externs
842 and the standard browser externs. The three lists are all
843 checked during highlighting."
844 :type 'list
845 :group 'js2-mode)
846
847 (js2-deflocal js2-default-externs nil
848 "Default external declarations.
849
850 These are currently only used for highlighting undeclared variables,
851 which only worries about top-level (unqualified) references.
852 As js2-mode's processing improves, we will flesh out this list.
853
854 The initial value is set to `js2-ecma-262-externs', unless some
855 of the `js2-include-?-externs' variables are set to t, in which
856 case the browser, Rhino and/or Node.js externs are also included.
857
858 See `js2-additional-externs' for more information.")
859
860 (defcustom js2-include-browser-externs t
861 "Non-nil to include browser externs in the master externs list.
862 If you work on JavaScript files that are not intended for browsers,
863 such as Mozilla Rhino server-side JavaScript, set this to nil.
864 See `js2-additional-externs' for more information about externs."
865 :type 'boolean
866 :group 'js2-mode)
867
868 (defcustom js2-include-rhino-externs nil
869 "Non-nil to include Mozilla Rhino externs in the master externs list.
870 See `js2-additional-externs' for more information about externs."
871 :type 'boolean
872 :group 'js2-mode)
873
874 (defcustom js2-include-node-externs nil
875 "Non-nil to include Node.js externs in the master externs list.
876 See `js2-additional-externs' for more information about externs."
877 :type 'boolean
878 :group 'js2-mode)
879
880 (js2-deflocal js2-additional-externs nil
881 "A buffer-local list of additional external declarations.
882 It is used to decide whether variables are considered undeclared
883 for purposes of highlighting.
884
885 Each entry is a Lisp string. The string should be the fully qualified
886 name of an external entity. All externs should be added to this list,
887 so that as js2-mode's processing improves it can take advantage of them.
888
889 You may want to declare your externs in three ways.
890 First, you can add externs that are valid for all your JavaScript files.
891 You should probably do this by adding them to `js2-global-externs', which
892 is a global list used for all js2-mode files.
893
894 Next, you can add a function to `js2-init-hook' that adds additional
895 externs appropriate for the specific file, perhaps based on its path.
896 These should go in `js2-additional-externs', which is buffer-local.
897
898 Third, you can use JSLint's global declaration, as long as
899 `js2-include-jslint-globals' is non-nil, which see.
900
901 Finally, you can add a function to `js2-post-parse-callbacks',
902 which is called after parsing completes, and `js2-mode-ast' is bound to
903 the root of the parse tree. At this stage you can set up an AST
904 node visitor using `js2-visit-ast' and examine the parse tree
905 for specific import patterns that may imply the existence of
906 other externs, possibly tied to your build system. These should also
907 be added to `js2-additional-externs'.
908
909 Your post-parse callback may of course also use the simpler and
910 faster (but perhaps less robust) approach of simply scanning the
911 buffer text for your imports, using regular expressions.")
912
913 ;; SKIP: decompiler
914 ;; SKIP: encoded-source
915
916 ;;; The following variables are per-function and should be saved/restored
917 ;;; during function parsing...
918
919 (js2-deflocal js2-current-script-or-fn nil)
920 (js2-deflocal js2-current-scope nil)
921 (js2-deflocal js2-nesting-of-with 0)
922 (js2-deflocal js2-label-set nil
923 "An alist mapping label names to nodes.")
924
925 (js2-deflocal js2-loop-set nil)
926 (js2-deflocal js2-loop-and-switch-set nil)
927 (js2-deflocal js2-has-return-value nil)
928 (js2-deflocal js2-end-flags 0)
929
930 ;;; ...end of per function variables
931
932 ;; These flags enumerate the possible ways a statement/function can
933 ;; terminate. These flags are used by endCheck() and by the Parser to
934 ;; detect inconsistent return usage.
935 ;;
936 ;; END_UNREACHED is reserved for code paths that are assumed to always be
937 ;; able to execute (example: throw, continue)
938 ;;
939 ;; END_DROPS_OFF indicates if the statement can transfer control to the
940 ;; next one. Statement such as return dont. A compound statement may have
941 ;; some branch that drops off control to the next statement.
942 ;;
943 ;; END_RETURNS indicates that the statement can return (without arguments)
944 ;; END_RETURNS_VALUE indicates that the statement can return a value.
945 ;;
946 ;; A compound statement such as
947 ;; if (condition) {
948 ;; return value;
949 ;; }
950 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
951
952 (defconst js2-end-unreached #x0)
953 (defconst js2-end-drops-off #x1)
954 (defconst js2-end-returns #x2)
955 (defconst js2-end-returns-value #x4)
956
957 ;; Rhino awkwardly passes a statementLabel parameter to the
958 ;; statementHelper() function, the main statement parser, which
959 ;; is then used by quite a few of the sub-parsers. We just make
960 ;; it a buffer-local variable and make sure it's cleaned up properly.
961 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
962
963 ;; Similarly, Rhino passes an inForInit boolean through about half
964 ;; the expression parsers. We use a dynamically-scoped variable,
965 ;; which makes it easier to funcall the parsers individually without
966 ;; worrying about whether they take the parameter or not.
967 (js2-deflocal js2-in-for-init nil)
968 (js2-deflocal js2-temp-name-counter 0)
969 (js2-deflocal js2-parse-stmt-count 0)
970
971 (defsubst js2-get-next-temp-name ()
972 (format "$%d" (cl-incf js2-temp-name-counter)))
973
974 (defvar js2-parse-interruptable-p t
975 "Set this to nil to force parse to continue until finished.
976 This will mostly be useful for interpreters.")
977
978 (defvar js2-statements-per-pause 50
979 "Pause after this many statements to check for user input.
980 If user input is pending, stop the parse and discard the tree.
981 This makes for a smoother user experience for large files.
982 You may have to wait a second or two before the highlighting
983 and error-reporting appear, but you can always type ahead if
984 you wish. This appears to be more or less how Eclipse, IntelliJ
985 and other editors work.")
986
987 (js2-deflocal js2-record-comments t
988 "Instructs the scanner to record comments in `js2-scanned-comments'.")
989
990 (js2-deflocal js2-scanned-comments nil
991 "List of all comments from the current parse.")
992
993 (defcustom js2-mode-indent-inhibit-undo nil
994 "Non-nil to disable collection of Undo information when indenting lines.
995 Some users have requested this behavior. It's nil by default because
996 other Emacs modes don't work this way."
997 :type 'boolean
998 :group 'js2-mode)
999
1000 (defcustom js2-mode-indent-ignore-first-tab nil
1001 "If non-nil, ignore first TAB keypress if we look indented properly.
1002 It's fairly common for users to navigate to an already-indented line
1003 and press TAB for reassurance that it's been indented. For this class
1004 of users, we want the first TAB press on a line to be ignored if the
1005 line is already indented to one of the precomputed alternatives.
1006
1007 This behavior is only partly implemented. If you TAB-indent a line,
1008 navigate to another line, and then navigate back, it fails to clear
1009 the last-indented variable, so it thinks you've already hit TAB once,
1010 and performs the indent. A full solution would involve getting on the
1011 point-motion hooks for the entire buffer. If we come across another
1012 use cases that requires watching point motion, I'll consider doing it.
1013
1014 If you set this variable to nil, then the TAB key will always change
1015 the indentation of the current line, if more than one alternative
1016 indentation spot exists."
1017 :type 'boolean
1018 :group 'js2-mode)
1019
1020 (defvar js2-indent-hook nil
1021 "A hook for user-defined indentation rules.
1022
1023 Functions on this hook should expect two arguments: (LIST INDEX)
1024 The LIST argument is the list of computed indentation points for
1025 the current line. INDEX is the list index of the indentation point
1026 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1027 indent function is not going to change the current line indentation.
1028
1029 If a hook function on this list returns a non-nil value, then
1030 `js2-bounce-indent' assumes the hook function has performed its own
1031 indentation, and will do nothing. If all hook functions on the list
1032 return nil, then `js2-bounce-indent' will use its computed indentation
1033 and reindent the line.
1034
1035 When hook functions on this hook list are called, the variable
1036 `js2-mode-ast' may or may not be set, depending on whether the
1037 parse tree is available. If the variable is nil, you can pass a
1038 callback to `js2-mode-wait-for-parse', and your callback will be
1039 called after the new parse tree is built. This can take some time
1040 in large files.")
1041
1042 (defface js2-warning
1043 `((((class color) (background light))
1044 (:underline "orange"))
1045 (((class color) (background dark))
1046 (:underline "orange"))
1047 (t (:underline t)))
1048 "Face for JavaScript warnings."
1049 :group 'js2-mode)
1050
1051 (defface js2-error
1052 `((((class color) (background light))
1053 (:foreground "red"))
1054 (((class color) (background dark))
1055 (:foreground "red"))
1056 (t (:foreground "red")))
1057 "Face for JavaScript errors."
1058 :group 'js2-mode)
1059
1060 (defface js2-jsdoc-tag
1061 '((t :foreground "SlateGray"))
1062 "Face used to highlight @whatever tags in jsdoc comments."
1063 :group 'js2-mode)
1064
1065 (defface js2-jsdoc-type
1066 '((t :foreground "SteelBlue"))
1067 "Face used to highlight {FooBar} types in jsdoc comments."
1068 :group 'js2-mode)
1069
1070 (defface js2-jsdoc-value
1071 '((t :foreground "PeachPuff3"))
1072 "Face used to highlight tag values in jsdoc comments."
1073 :group 'js2-mode)
1074
1075 (defface js2-function-param
1076 '((t :foreground "SeaGreen"))
1077 "Face used to highlight function parameters in javascript."
1078 :group 'js2-mode)
1079
1080 (defface js2-function-call
1081 '((t :inherit default))
1082 "Face used to highlight function name in calls."
1083 :group 'js2-mode)
1084
1085 (defface js2-instance-member
1086 '((t :foreground "DarkOrchid"))
1087 "Face used to highlight instance variables in javascript.
1088 Not currently used."
1089 :group 'js2-mode)
1090
1091 (defface js2-private-member
1092 '((t :foreground "PeachPuff3"))
1093 "Face used to highlight calls to private methods in javascript.
1094 Not currently used."
1095 :group 'js2-mode)
1096
1097 (defface js2-private-function-call
1098 '((t :foreground "goldenrod"))
1099 "Face used to highlight calls to private functions in javascript.
1100 Not currently used."
1101 :group 'js2-mode)
1102
1103 (defface js2-jsdoc-html-tag-name
1104 '((((class color) (min-colors 88) (background light))
1105 (:foreground "rosybrown"))
1106 (((class color) (min-colors 8) (background dark))
1107 (:foreground "yellow"))
1108 (((class color) (min-colors 8) (background light))
1109 (:foreground "magenta")))
1110 "Face used to highlight jsdoc html tag names"
1111 :group 'js2-mode)
1112
1113 (defface js2-jsdoc-html-tag-delimiter
1114 '((((class color) (min-colors 88) (background light))
1115 (:foreground "dark khaki"))
1116 (((class color) (min-colors 8) (background dark))
1117 (:foreground "green"))
1118 (((class color) (min-colors 8) (background light))
1119 (:foreground "green")))
1120 "Face used to highlight brackets in jsdoc html tags."
1121 :group 'js2-mode)
1122
1123 (defface js2-external-variable
1124 '((t :foreground "orange"))
1125 "Face used to highlight undeclared variable identifiers.")
1126
1127 (defcustom js2-init-hook nil
1128 "List of functions to be called after `js2-mode' or
1129 `js2-minor-mode' has initialized all variables, before parsing
1130 the buffer for the first time."
1131 :type 'hook
1132 :group 'js2-mode
1133 :version "20130608")
1134
1135 (defcustom js2-post-parse-callbacks nil
1136 "List of callback functions invoked after parsing finishes.
1137 Currently, the main use for this function is to add synthetic
1138 declarations to `js2-recorded-identifiers', which see."
1139 :type 'hook
1140 :group 'js2-mode)
1141
1142 (defcustom js2-build-imenu-callbacks nil
1143 "List of functions called during Imenu index generation.
1144 It's a good place to add additional entries to it, using
1145 `js2-record-imenu-entry'."
1146 :type 'hook
1147 :group 'js2-mode)
1148
1149 (defcustom js2-highlight-external-variables t
1150 "Non-nil to highlight undeclared variable identifiers.
1151 An undeclared variable is any variable not declared with var or let
1152 in the current scope or any lexically enclosing scope. If you use
1153 such a variable, then you are either expecting it to originate from
1154 another file, or you've got a potential bug."
1155 :type 'boolean
1156 :group 'js2-mode)
1157
1158 (defcustom js2-include-jslint-globals t
1159 "Non-nil to include the identifiers from JSLint global
1160 declaration (see http://www.jslint.com/lint.html#global) in the
1161 buffer-local externs list. See `js2-additional-externs' for more
1162 information."
1163 :type 'boolean
1164 :group 'js2-mode)
1165
1166 (defvar js2-mode-map
1167 (let ((map (make-sparse-keymap)))
1168 (define-key map [mouse-1] #'js2-mode-show-node)
1169 (define-key map (kbd "M-j") #'js2-line-break)
1170 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1171 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1172 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1173 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1174 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1175 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1176 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1177 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1178 (when js2-bounce-indent-p
1179 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1180
1181 (define-key map [menu-bar javascript]
1182 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1183
1184 (define-key map [menu-bar javascript customize-js2-mode]
1185 '(menu-item "Customize js2-mode" js2-mode-customize
1186 :help "Customize the behavior of this mode"))
1187
1188 (define-key map [menu-bar javascript js2-force-refresh]
1189 '(menu-item "Force buffer refresh" js2-mode-reset
1190 :help "Re-parse the buffer from scratch"))
1191
1192 (define-key map [menu-bar javascript separator-2]
1193 '("--"))
1194
1195 (define-key map [menu-bar javascript next-error]
1196 '(menu-item "Next warning or error" next-error
1197 :enabled (and js2-mode-ast
1198 (or (js2-ast-root-errors js2-mode-ast)
1199 (js2-ast-root-warnings js2-mode-ast)))
1200 :help "Move to next warning or error"))
1201
1202 (define-key map [menu-bar javascript display-errors]
1203 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1204 :visible (not js2-mode-show-parse-errors)
1205 :help "Turn on display of warnings and errors"))
1206
1207 (define-key map [menu-bar javascript hide-errors]
1208 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1209 :visible js2-mode-show-parse-errors
1210 :help "Turn off display of warnings and errors"))
1211
1212 (define-key map [menu-bar javascript separator-1]
1213 '("--"))
1214
1215 (define-key map [menu-bar javascript js2-toggle-function]
1216 '(menu-item "Show/collapse element" js2-mode-toggle-element
1217 :help "Hide or show function body or comment"))
1218
1219 (define-key map [menu-bar javascript show-comments]
1220 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1221 :visible js2-mode-comments-hidden
1222 :help "Expand all hidden block comments"))
1223
1224 (define-key map [menu-bar javascript hide-comments]
1225 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1226 :visible (not js2-mode-comments-hidden)
1227 :help "Show block comments as /*...*/"))
1228
1229 (define-key map [menu-bar javascript show-all-functions]
1230 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1231 :visible js2-mode-functions-hidden
1232 :help "Expand all hidden function bodies"))
1233
1234 (define-key map [menu-bar javascript hide-all-functions]
1235 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1236 :visible (not js2-mode-functions-hidden)
1237 :help "Show {...} for all top-level function bodies"))
1238
1239 map)
1240 "Keymap used in `js2-mode' buffers.")
1241
1242 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1243
1244 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1245 "Matches a //-comment line. Must be first non-whitespace on line.
1246 First match-group is the leading whitespace.")
1247
1248 (defvar js2-mode-hook nil)
1249
1250 (js2-deflocal js2-mode-ast nil "Private variable.")
1251 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1252 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1253 (js2-deflocal js2-mode-parsing nil "Private variable.")
1254 (js2-deflocal js2-mode-node-overlay nil)
1255
1256 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1257 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1258
1259 (js2-deflocal js2-mode-fontifications nil "Private variable")
1260 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1261 (js2-deflocal js2-imenu-recorder nil "Private variable")
1262 (js2-deflocal js2-imenu-function-map nil "Private variable")
1263
1264 (defvar js2-paragraph-start
1265 "\\(@[[:alpha:]]+\\>\\|$\\)")
1266
1267 ;; Note that we also set a 'c-in-sws text property in html comments,
1268 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1269 (defvar js2-syntactic-ws-start
1270 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1271
1272 (defvar js2-syntactic-ws-end
1273 "\\s \\|[\n\r/]\\|\\s!")
1274
1275 (defvar js2-syntactic-eol
1276 (concat "\\s *\\(/\\*[^*\n\r]*"
1277 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1278 "\\*+/\\s *\\)*"
1279 "\\(//\\|/\\*[^*\n\r]*"
1280 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1281 "\\|\\\\$\\|$\\)")
1282 "Copied from `java-mode'. Needed for some cc-engine functions.")
1283
1284 (defvar js2-comment-prefix-regexp
1285 "//+\\|\\**")
1286
1287 (defvar js2-comment-start-skip
1288 "\\(//+\\|/\\*+\\)\\s *")
1289
1290 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1291 "Non-nil to emit status messages during parsing.")
1292
1293 (defvar js2-mode-functions-hidden nil "Private variable.")
1294 (defvar js2-mode-comments-hidden nil "Private variable.")
1295
1296 (defvar js2-mode-syntax-table
1297 (let ((table (make-syntax-table)))
1298 (c-populate-syntax-table table)
1299 (modify-syntax-entry ?` "\"" table)
1300 table)
1301 "Syntax table used in `js2-mode' buffers.")
1302
1303 (defvar js2-mode-abbrev-table nil
1304 "Abbrev table in use in `js2-mode' buffers.")
1305 (define-abbrev-table 'js2-mode-abbrev-table ())
1306
1307 (defvar js2-mode-pending-parse-callbacks nil
1308 "List of functions waiting to be notified that parse is finished.")
1309
1310 (defvar js2-mode-last-indented-line -1)
1311
1312 ;;; Localizable error and warning messages
1313
1314 ;; Messages are copied from Rhino's Messages.properties.
1315 ;; Many of the Java-specific messages have been elided.
1316 ;; Add any js2-specific ones at the end, so we can keep
1317 ;; this file synced with changes to Rhino's.
1318
1319 (defvar js2-message-table
1320 (make-hash-table :test 'equal :size 250)
1321 "Contains localized messages for `js2-mode'.")
1322
1323 ;; TODO(stevey): construct this table at compile-time.
1324 (defmacro js2-msg (key &rest strings)
1325 `(puthash ,key (concat ,@strings)
1326 js2-message-table))
1327
1328 (defun js2-get-msg (msg-key)
1329 "Look up a localized message.
1330 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1331 the correct number of ARGS must be provided."
1332 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1333 (args (if (listp msg-key) (cdr msg-key)))
1334 (msg (gethash key js2-message-table)))
1335 (if msg
1336 (apply #'format msg args)
1337 key))) ; default to showing the key
1338
1339 (js2-msg "msg.dup.parms"
1340 "Duplicate parameter name '%s'.")
1341
1342 (js2-msg "msg.too.big.jump"
1343 "Program too complex: jump offset too big.")
1344
1345 (js2-msg "msg.too.big.index"
1346 "Program too complex: internal index exceeds 64K limit.")
1347
1348 (js2-msg "msg.while.compiling.fn"
1349 "Encountered code generation error while compiling function '%s': %s")
1350
1351 (js2-msg "msg.while.compiling.script"
1352 "Encountered code generation error while compiling script: %s")
1353
1354 ;; Context
1355 (js2-msg "msg.ctor.not.found"
1356 "Constructor for '%s' not found.")
1357
1358 (js2-msg "msg.not.ctor"
1359 "'%s' is not a constructor.")
1360
1361 ;; FunctionObject
1362 (js2-msg "msg.varargs.ctor"
1363 "Method or constructor '%s' must be static "
1364 "with the signature (Context cx, Object[] args, "
1365 "Function ctorObj, boolean inNewExpr) "
1366 "to define a variable arguments constructor.")
1367
1368 (js2-msg "msg.varargs.fun"
1369 "Method '%s' must be static with the signature "
1370 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1371 "to define a variable arguments function.")
1372
1373 (js2-msg "msg.incompat.call"
1374 "Method '%s' called on incompatible object.")
1375
1376 (js2-msg "msg.bad.parms"
1377 "Unsupported parameter type '%s' in method '%s'.")
1378
1379 (js2-msg "msg.bad.method.return"
1380 "Unsupported return type '%s' in method '%s'.")
1381
1382 (js2-msg "msg.bad.ctor.return"
1383 "Construction of objects of type '%s' is not supported.")
1384
1385 (js2-msg "msg.no.overload"
1386 "Method '%s' occurs multiple times in class '%s'.")
1387
1388 (js2-msg "msg.method.not.found"
1389 "Method '%s' not found in '%s'.")
1390
1391 ;; IRFactory
1392
1393 (js2-msg "msg.bad.for.in.lhs"
1394 "Invalid left-hand side of for..in loop.")
1395
1396 (js2-msg "msg.mult.index"
1397 "Only one variable allowed in for..in loop.")
1398
1399 (js2-msg "msg.bad.for.in.destruct"
1400 "Left hand side of for..in loop must be an array of "
1401 "length 2 to accept key/value pair.")
1402
1403 (js2-msg "msg.cant.convert"
1404 "Can't convert to type '%s'.")
1405
1406 (js2-msg "msg.bad.assign.left"
1407 "Invalid assignment left-hand side.")
1408
1409 (js2-msg "msg.bad.decr"
1410 "Invalid decrement operand.")
1411
1412 (js2-msg "msg.bad.incr"
1413 "Invalid increment operand.")
1414
1415 (js2-msg "msg.bad.yield"
1416 "yield must be in a function.")
1417
1418 (js2-msg "msg.yield.parenthesized"
1419 "yield expression must be parenthesized.")
1420
1421 ;; NativeGlobal
1422 (js2-msg "msg.cant.call.indirect"
1423 "Function '%s' must be called directly, and not by way of a "
1424 "function of another name.")
1425
1426 (js2-msg "msg.eval.nonstring"
1427 "Calling eval() with anything other than a primitive "
1428 "string value will simply return the value. "
1429 "Is this what you intended?")
1430
1431 (js2-msg "msg.eval.nonstring.strict"
1432 "Calling eval() with anything other than a primitive "
1433 "string value is not allowed in strict mode.")
1434
1435 (js2-msg "msg.bad.destruct.op"
1436 "Invalid destructuring assignment operator")
1437
1438 ;; NativeCall
1439 (js2-msg "msg.only.from.new"
1440 "'%s' may only be invoked from a `new' expression.")
1441
1442 (js2-msg "msg.deprec.ctor"
1443 "The '%s' constructor is deprecated.")
1444
1445 ;; NativeFunction
1446 (js2-msg "msg.no.function.ref.found"
1447 "no source found to decompile function reference %s")
1448
1449 (js2-msg "msg.arg.isnt.array"
1450 "second argument to Function.prototype.apply must be an array")
1451
1452 ;; NativeGlobal
1453 (js2-msg "msg.bad.esc.mask"
1454 "invalid string escape mask")
1455
1456 ;; NativeRegExp
1457 (js2-msg "msg.bad.quant"
1458 "Invalid quantifier %s")
1459
1460 (js2-msg "msg.overlarge.backref"
1461 "Overly large back reference %s")
1462
1463 (js2-msg "msg.overlarge.min"
1464 "Overly large minimum %s")
1465
1466 (js2-msg "msg.overlarge.max"
1467 "Overly large maximum %s")
1468
1469 (js2-msg "msg.zero.quant"
1470 "Zero quantifier %s")
1471
1472 (js2-msg "msg.max.lt.min"
1473 "Maximum %s less than minimum")
1474
1475 (js2-msg "msg.unterm.quant"
1476 "Unterminated quantifier %s")
1477
1478 (js2-msg "msg.unterm.paren"
1479 "Unterminated parenthetical %s")
1480
1481 (js2-msg "msg.unterm.class"
1482 "Unterminated character class %s")
1483
1484 (js2-msg "msg.bad.range"
1485 "Invalid range in character class.")
1486
1487 (js2-msg "msg.trail.backslash"
1488 "Trailing \\ in regular expression.")
1489
1490 (js2-msg "msg.re.unmatched.right.paren"
1491 "unmatched ) in regular expression.")
1492
1493 (js2-msg "msg.no.regexp"
1494 "Regular expressions are not available.")
1495
1496 (js2-msg "msg.bad.backref"
1497 "back-reference exceeds number of capturing parentheses.")
1498
1499 (js2-msg "msg.bad.regexp.compile"
1500 "Only one argument may be specified if the first "
1501 "argument to RegExp.prototype.compile is a RegExp object.")
1502
1503 ;; Parser
1504 (js2-msg "msg.got.syntax.errors"
1505 "Compilation produced %s syntax errors.")
1506
1507 (js2-msg "msg.var.redecl"
1508 "TypeError: redeclaration of var %s.")
1509
1510 (js2-msg "msg.const.redecl"
1511 "TypeError: redeclaration of const %s.")
1512
1513 (js2-msg "msg.let.redecl"
1514 "TypeError: redeclaration of variable %s.")
1515
1516 (js2-msg "msg.parm.redecl"
1517 "TypeError: redeclaration of formal parameter %s.")
1518
1519 (js2-msg "msg.fn.redecl"
1520 "TypeError: redeclaration of function %s.")
1521
1522 (js2-msg "msg.let.decl.not.in.block"
1523 "SyntaxError: let declaration not directly within block")
1524
1525 (js2-msg "msg.mod.import.decl.at.top.level"
1526 "SyntaxError: import declarations may only appear at the top level")
1527
1528 (js2-msg "msg.mod.as.after.reserved.word"
1529 "SyntaxError: missing keyword 'as' after reserved word %s")
1530
1531 (js2-msg "msg.mod.rc.after.import.spec.list"
1532 "SyntaxError: missing '}' after module specifier list")
1533
1534 (js2-msg "msg.mod.from.after.import.spec.set"
1535 "SyntaxError: missing keyword 'from' after import specifier set")
1536
1537 (js2-msg "msg.mod.declaration.after.import"
1538 "SyntaxError: missing declaration after 'import' keyword")
1539
1540 (js2-msg "msg.mod.spec.after.from"
1541 "SyntaxError: missing module specifier after 'from' keyword")
1542
1543 (js2-msg "msg.mod.export.decl.at.top.level"
1544 "SyntaxError: export declarations may only appear at top level")
1545
1546 (js2-msg "msg.mod.rc.after.export.spec.list"
1547 "SyntaxError: missing '}' after export specifier list")
1548
1549 ;; NodeTransformer
1550 (js2-msg "msg.dup.label"
1551 "duplicated label")
1552
1553 (js2-msg "msg.undef.label"
1554 "undefined label")
1555
1556 (js2-msg "msg.bad.break"
1557 "unlabelled break must be inside loop or switch")
1558
1559 (js2-msg "msg.continue.outside"
1560 "continue must be inside loop")
1561
1562 (js2-msg "msg.continue.nonloop"
1563 "continue can only use labels of iteration statements")
1564
1565 (js2-msg "msg.bad.throw.eol"
1566 "Line terminator is not allowed between the throw "
1567 "keyword and throw expression.")
1568
1569 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1570 "function statement requires a name")
1571
1572 (js2-msg "msg.no.paren.parms"
1573 "missing ( before function parameters.")
1574
1575 (js2-msg "msg.no.parm"
1576 "missing formal parameter")
1577
1578 (js2-msg "msg.no.paren.after.parms"
1579 "missing ) after formal parameters")
1580
1581 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1582 "parameter without default follows parameter with default")
1583
1584 (js2-msg "msg.param.after.rest" ; added by js2-mode
1585 "parameter after rest parameter")
1586
1587 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1588 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1589
1590 (js2-msg "msg.no.brace.body"
1591 "missing '{' before function body")
1592
1593 (js2-msg "msg.no.brace.after.body"
1594 "missing } after function body")
1595
1596 (js2-msg "msg.no.paren.cond"
1597 "missing ( before condition")
1598
1599 (js2-msg "msg.no.paren.after.cond"
1600 "missing ) after condition")
1601
1602 (js2-msg "msg.no.semi.stmt"
1603 "missing ; before statement")
1604
1605 (js2-msg "msg.missing.semi"
1606 "missing ; after statement")
1607
1608 (js2-msg "msg.no.name.after.dot"
1609 "missing name after . operator")
1610
1611 (js2-msg "msg.no.name.after.coloncolon"
1612 "missing name after :: operator")
1613
1614 (js2-msg "msg.no.name.after.dotdot"
1615 "missing name after .. operator")
1616
1617 (js2-msg "msg.no.name.after.xmlAttr"
1618 "missing name after .@")
1619
1620 (js2-msg "msg.no.bracket.index"
1621 "missing ] in index expression")
1622
1623 (js2-msg "msg.no.paren.switch"
1624 "missing ( before switch expression")
1625
1626 (js2-msg "msg.no.paren.after.switch"
1627 "missing ) after switch expression")
1628
1629 (js2-msg "msg.no.brace.switch"
1630 "missing '{' before switch body")
1631
1632 (js2-msg "msg.bad.switch"
1633 "invalid switch statement")
1634
1635 (js2-msg "msg.no.colon.case"
1636 "missing : after case expression")
1637
1638 (js2-msg "msg.double.switch.default"
1639 "double default label in the switch statement")
1640
1641 (js2-msg "msg.no.while.do"
1642 "missing while after do-loop body")
1643
1644 (js2-msg "msg.no.paren.for"
1645 "missing ( after for")
1646
1647 (js2-msg "msg.no.semi.for"
1648 "missing ; after for-loop initializer")
1649
1650 (js2-msg "msg.no.semi.for.cond"
1651 "missing ; after for-loop condition")
1652
1653 (js2-msg "msg.in.after.for.name"
1654 "missing in or of after for")
1655
1656 (js2-msg "msg.no.paren.for.ctrl"
1657 "missing ) after for-loop control")
1658
1659 (js2-msg "msg.no.paren.with"
1660 "missing ( before with-statement object")
1661
1662 (js2-msg "msg.no.paren.after.with"
1663 "missing ) after with-statement object")
1664
1665 (js2-msg "msg.no.paren.after.let"
1666 "missing ( after let")
1667
1668 (js2-msg "msg.no.paren.let"
1669 "missing ) after variable list")
1670
1671 (js2-msg "msg.no.curly.let"
1672 "missing } after let statement")
1673
1674 (js2-msg "msg.bad.return"
1675 "invalid return")
1676
1677 (js2-msg "msg.no.brace.block"
1678 "missing } in compound statement")
1679
1680 (js2-msg "msg.bad.label"
1681 "invalid label")
1682
1683 (js2-msg "msg.bad.var"
1684 "missing variable name")
1685
1686 (js2-msg "msg.bad.var.init"
1687 "invalid variable initialization")
1688
1689 (js2-msg "msg.no.colon.cond"
1690 "missing : in conditional expression")
1691
1692 (js2-msg "msg.no.paren.arg"
1693 "missing ) after argument list")
1694
1695 (js2-msg "msg.no.bracket.arg"
1696 "missing ] after element list")
1697
1698 (js2-msg "msg.bad.prop"
1699 "invalid property id")
1700
1701 (js2-msg "msg.no.colon.prop"
1702 "missing : after property id")
1703
1704 (js2-msg "msg.no.brace.prop"
1705 "missing } after property list")
1706
1707 (js2-msg "msg.no.paren"
1708 "missing ) in parenthetical")
1709
1710 (js2-msg "msg.reserved.id"
1711 "'%s' is a reserved identifier")
1712
1713 (js2-msg "msg.no.paren.catch"
1714 "missing ( before catch-block condition")
1715
1716 (js2-msg "msg.bad.catchcond"
1717 "invalid catch block condition")
1718
1719 (js2-msg "msg.catch.unreachable"
1720 "any catch clauses following an unqualified catch are unreachable")
1721
1722 (js2-msg "msg.no.brace.try"
1723 "missing '{' before try block")
1724
1725 (js2-msg "msg.no.brace.catchblock"
1726 "missing '{' before catch-block body")
1727
1728 (js2-msg "msg.try.no.catchfinally"
1729 "'try' without 'catch' or 'finally'")
1730
1731 (js2-msg "msg.no.return.value"
1732 "function %s does not always return a value")
1733
1734 (js2-msg "msg.anon.no.return.value"
1735 "anonymous function does not always return a value")
1736
1737 (js2-msg "msg.return.inconsistent"
1738 "return statement is inconsistent with previous usage")
1739
1740 (js2-msg "msg.generator.returns"
1741 "TypeError: legacy generator function '%s' returns a value")
1742
1743 (js2-msg "msg.anon.generator.returns"
1744 "TypeError: anonymous legacy generator function returns a value")
1745
1746 (js2-msg "msg.syntax"
1747 "syntax error")
1748
1749 (js2-msg "msg.unexpected.eof"
1750 "Unexpected end of file")
1751
1752 (js2-msg "msg.XML.bad.form"
1753 "illegally formed XML syntax")
1754
1755 (js2-msg "msg.XML.not.available"
1756 "XML runtime not available")
1757
1758 (js2-msg "msg.too.deep.parser.recursion"
1759 "Too deep recursion while parsing")
1760
1761 (js2-msg "msg.no.side.effects"
1762 "Code has no side effects")
1763
1764 (js2-msg "msg.extra.trailing.comma"
1765 "Trailing comma is not supported in some browsers")
1766
1767 (js2-msg "msg.array.trailing.comma"
1768 "Trailing comma yields different behavior across browsers")
1769
1770 (js2-msg "msg.equal.as.assign"
1771 (concat "Test for equality (==) mistyped as assignment (=)?"
1772 " (parenthesize to suppress warning)"))
1773
1774 (js2-msg "msg.var.hides.arg"
1775 "Variable %s hides argument")
1776
1777 (js2-msg "msg.destruct.assign.no.init"
1778 "Missing = in destructuring declaration")
1779
1780 ;; ScriptRuntime
1781 (js2-msg "msg.no.properties"
1782 "%s has no properties.")
1783
1784 (js2-msg "msg.invalid.iterator"
1785 "Invalid iterator value")
1786
1787 (js2-msg "msg.iterator.primitive"
1788 "__iterator__ returned a primitive value")
1789
1790 (js2-msg "msg.assn.create.strict"
1791 "Assignment to undeclared variable %s")
1792
1793 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1794 "Undeclared variable or function '%s'")
1795
1796 (js2-msg "msg.ref.undefined.prop"
1797 "Reference to undefined property '%s'")
1798
1799 (js2-msg "msg.prop.not.found"
1800 "Property %s not found.")
1801
1802 (js2-msg "msg.invalid.type"
1803 "Invalid JavaScript value of type %s")
1804
1805 (js2-msg "msg.primitive.expected"
1806 "Primitive type expected (had %s instead)")
1807
1808 (js2-msg "msg.namespace.expected"
1809 "Namespace object expected to left of :: (found %s instead)")
1810
1811 (js2-msg "msg.null.to.object"
1812 "Cannot convert null to an object.")
1813
1814 (js2-msg "msg.undef.to.object"
1815 "Cannot convert undefined to an object.")
1816
1817 (js2-msg "msg.cyclic.value"
1818 "Cyclic %s value not allowed.")
1819
1820 (js2-msg "msg.is.not.defined"
1821 "'%s' is not defined.")
1822
1823 (js2-msg "msg.undef.prop.read"
1824 "Cannot read property '%s' from %s")
1825
1826 (js2-msg "msg.undef.prop.write"
1827 "Cannot set property '%s' of %s to '%s'")
1828
1829 (js2-msg "msg.undef.prop.delete"
1830 "Cannot delete property '%s' of %s")
1831
1832 (js2-msg "msg.undef.method.call"
1833 "Cannot call method '%s' of %s")
1834
1835 (js2-msg "msg.undef.with"
1836 "Cannot apply 'with' to %s")
1837
1838 (js2-msg "msg.isnt.function"
1839 "%s is not a function, it is %s.")
1840
1841 (js2-msg "msg.isnt.function.in"
1842 "Cannot call property %s in object %s. "
1843 "It is not a function, it is '%s'.")
1844
1845 (js2-msg "msg.function.not.found"
1846 "Cannot find function %s.")
1847
1848 (js2-msg "msg.function.not.found.in"
1849 "Cannot find function %s in object %s.")
1850
1851 (js2-msg "msg.isnt.xml.object"
1852 "%s is not an xml object.")
1853
1854 (js2-msg "msg.no.ref.to.get"
1855 "%s is not a reference to read reference value.")
1856
1857 (js2-msg "msg.no.ref.to.set"
1858 "%s is not a reference to set reference value to %s.")
1859
1860 (js2-msg "msg.no.ref.from.function"
1861 "Function %s can not be used as the left-hand "
1862 "side of assignment or as an operand of ++ or -- operator.")
1863
1864 (js2-msg "msg.bad.default.value"
1865 "Object's getDefaultValue() method returned an object.")
1866
1867 (js2-msg "msg.instanceof.not.object"
1868 "Can't use instanceof on a non-object.")
1869
1870 (js2-msg "msg.instanceof.bad.prototype"
1871 "'prototype' property of %s is not an object.")
1872
1873 (js2-msg "msg.bad.radix"
1874 "illegal radix %s.")
1875
1876 ;; ScriptableObject
1877 (js2-msg "msg.default.value"
1878 "Cannot find default value for object.")
1879
1880 (js2-msg "msg.zero.arg.ctor"
1881 "Cannot load class '%s' which has no zero-parameter constructor.")
1882
1883 (js2-msg "msg.ctor.multiple.parms"
1884 "Can't define constructor or class %s since more than "
1885 "one constructor has multiple parameters.")
1886
1887 (js2-msg "msg.extend.scriptable"
1888 "%s must extend ScriptableObject in order to define property %s.")
1889
1890 (js2-msg "msg.bad.getter.parms"
1891 "In order to define a property, getter %s must have zero "
1892 "parameters or a single ScriptableObject parameter.")
1893
1894 (js2-msg "msg.obj.getter.parms"
1895 "Expected static or delegated getter %s to take "
1896 "a ScriptableObject parameter.")
1897
1898 (js2-msg "msg.getter.static"
1899 "Getter and setter must both be static or neither be static.")
1900
1901 (js2-msg "msg.setter.return"
1902 "Setter must have void return type: %s")
1903
1904 (js2-msg "msg.setter2.parms"
1905 "Two-parameter setter must take a ScriptableObject as "
1906 "its first parameter.")
1907
1908 (js2-msg "msg.setter1.parms"
1909 "Expected single parameter setter for %s")
1910
1911 (js2-msg "msg.setter2.expected"
1912 "Expected static or delegated setter %s to take two parameters.")
1913
1914 (js2-msg "msg.setter.parms"
1915 "Expected either one or two parameters for setter.")
1916
1917 (js2-msg "msg.setter.bad.type"
1918 "Unsupported parameter type '%s' in setter '%s'.")
1919
1920 (js2-msg "msg.add.sealed"
1921 "Cannot add a property to a sealed object: %s.")
1922
1923 (js2-msg "msg.remove.sealed"
1924 "Cannot remove a property from a sealed object: %s.")
1925
1926 (js2-msg "msg.modify.sealed"
1927 "Cannot modify a property of a sealed object: %s.")
1928
1929 (js2-msg "msg.modify.readonly"
1930 "Cannot modify readonly property: %s.")
1931
1932 ;; TokenStream
1933 (js2-msg "msg.missing.exponent"
1934 "missing exponent")
1935
1936 (js2-msg "msg.caught.nfe"
1937 "number format error")
1938
1939 (js2-msg "msg.unterminated.string.lit"
1940 "unterminated string literal")
1941
1942 (js2-msg "msg.unterminated.comment"
1943 "unterminated comment")
1944
1945 (js2-msg "msg.unterminated.re.lit"
1946 "unterminated regular expression literal")
1947
1948 (js2-msg "msg.invalid.re.flag"
1949 "invalid flag after regular expression")
1950
1951 (js2-msg "msg.no.re.input.for"
1952 "no input for %s")
1953
1954 (js2-msg "msg.illegal.character"
1955 "illegal character")
1956
1957 (js2-msg "msg.invalid.escape"
1958 "invalid Unicode escape sequence")
1959
1960 (js2-msg "msg.bad.namespace"
1961 "not a valid default namespace statement. "
1962 "Syntax is: default xml namespace = EXPRESSION;")
1963
1964 ;; TokensStream warnings
1965 (js2-msg "msg.bad.octal.literal"
1966 "illegal octal literal digit %s; "
1967 "interpreting it as a decimal digit")
1968
1969 (js2-msg "msg.missing.hex.digits"
1970 "missing hexadecimal digits after '0x'")
1971
1972 (js2-msg "msg.missing.binary.digits"
1973 "missing binary digits after '0b'")
1974
1975 (js2-msg "msg.missing.octal.digits"
1976 "missing octal digits after '0o'")
1977
1978 (js2-msg "msg.script.is.not.constructor"
1979 "Script objects are not constructors.")
1980
1981 ;; Arrays
1982 (js2-msg "msg.arraylength.bad"
1983 "Inappropriate array length.")
1984
1985 ;; Arrays
1986 (js2-msg "msg.arraylength.too.big"
1987 "Array length %s exceeds supported capacity limit.")
1988
1989 ;; URI
1990 (js2-msg "msg.bad.uri"
1991 "Malformed URI sequence.")
1992
1993 ;; Number
1994 (js2-msg "msg.bad.precision"
1995 "Precision %s out of range.")
1996
1997 ;; NativeGenerator
1998 (js2-msg "msg.send.newborn"
1999 "Attempt to send value to newborn generator")
2000
2001 (js2-msg "msg.already.exec.gen"
2002 "Already executing generator")
2003
2004 (js2-msg "msg.StopIteration.invalid"
2005 "StopIteration may not be changed to an arbitrary object.")
2006
2007 ;; Interpreter
2008 (js2-msg "msg.yield.closing"
2009 "Yield from closing generator")
2010
2011 ;; Classes
2012 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
2013 "class statement requires a name")
2014
2015 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
2016 "unexpected ',' between class properties")
2017
2018 (js2-msg "msg.unexpected.static" ; added by js2-mode
2019 "unexpected 'static'")
2020
2021 (js2-msg "msg.missing.extends" ; added by js2-mode
2022 "name is required after extends")
2023
2024 (js2-msg "msg.no.brace.class" ; added by js2-mode
2025 "missing '{' before class body")
2026
2027 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2028 "missing ']' after computed property expression")
2029
2030 ;;; Tokens Buffer
2031
2032 (defconst js2-ti-max-lookahead 2)
2033 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2034
2035 (defun js2-new-token (offset)
2036 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2037 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2038 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2039 token))
2040
2041 (defsubst js2-current-token ()
2042 (aref js2-ti-tokens js2-ti-tokens-cursor))
2043
2044 (defsubst js2-current-token-string ()
2045 (js2-token-string (js2-current-token)))
2046
2047 (defsubst js2-current-token-type ()
2048 (js2-token-type (js2-current-token)))
2049
2050 (defsubst js2-current-token-beg ()
2051 (js2-token-beg (js2-current-token)))
2052
2053 (defsubst js2-current-token-end ()
2054 (js2-token-end (js2-current-token)))
2055
2056 (defun js2-current-token-len ()
2057 (let ((token (js2-current-token)))
2058 (- (js2-token-end token)
2059 (js2-token-beg token))))
2060
2061 (defun js2-ts-seek (state)
2062 (setq js2-ts-lineno (js2-ts-state-lineno state)
2063 js2-ts-cursor (js2-ts-state-cursor state)
2064 js2-ti-tokens (js2-ts-state-tokens state)
2065 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2066 js2-ti-lookahead (js2-ts-state-lookahead state)))
2067
2068 ;;; Utilities
2069
2070 (defun js2-delete-if (predicate list)
2071 "Remove all items satisfying PREDICATE in LIST."
2072 (cl-loop for item in list
2073 if (not (funcall predicate item))
2074 collect item))
2075
2076 (defun js2-position (element list)
2077 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2078 Returns nil if element is not found in the list."
2079 (let ((count 0)
2080 found)
2081 (while (and list (not found))
2082 (if (eq element (car list))
2083 (setq found t)
2084 (setq count (1+ count)
2085 list (cdr list))))
2086 (if found count)))
2087
2088 (defun js2-find-if (predicate list)
2089 "Find first item satisfying PREDICATE in LIST."
2090 (let (result)
2091 (while (and list (not result))
2092 (if (funcall predicate (car list))
2093 (setq result (car list)))
2094 (setq list (cdr list)))
2095 result))
2096
2097 (defmacro js2-time (form)
2098 "Evaluate FORM, discard result, and return elapsed time in sec."
2099 (declare (debug t))
2100 (let ((beg (make-symbol "--js2-time-beg--")))
2101 `(let ((,beg (current-time)))
2102 ,form
2103 (/ (truncate (* (- (float-time (current-time))
2104 (float-time ,beg))
2105 10000))
2106 10000.0))))
2107
2108 (defsubst js2-same-line (pos)
2109 "Return t if POS is on the same line as current point."
2110 (and (>= pos (point-at-bol))
2111 (<= pos (point-at-eol))))
2112
2113 (defun js2-code-bug ()
2114 "Signal an error when we encounter an unexpected code path."
2115 (error "failed assertion"))
2116
2117 (defsubst js2-record-text-property (beg end prop value)
2118 "Record a text property to set when parsing finishes."
2119 (push (list beg end prop value) js2-mode-deferred-properties))
2120
2121 ;; I'd like to associate errors with nodes, but for now the
2122 ;; easiest thing to do is get the context info from the last token.
2123 (defun js2-record-parse-error (msg &optional arg pos len)
2124 (push (list (list msg arg)
2125 (or pos (js2-current-token-beg))
2126 (or len (js2-current-token-len)))
2127 js2-parsed-errors))
2128
2129 (defun js2-report-error (msg &optional msg-arg pos len)
2130 "Signal a syntax error or record a parse error."
2131 (if js2-recover-from-parse-errors
2132 (js2-record-parse-error msg msg-arg pos len)
2133 (signal 'js2-syntax-error
2134 (list msg
2135 js2-ts-lineno
2136 (save-excursion
2137 (goto-char js2-ts-cursor)
2138 (current-column))
2139 js2-ts-hit-eof))))
2140
2141 (defun js2-report-warning (msg &optional msg-arg pos len face)
2142 (if js2-compiler-report-warning-as-error
2143 (js2-report-error msg msg-arg pos len)
2144 (push (list (list msg msg-arg)
2145 (or pos (js2-current-token-beg))
2146 (or len (js2-current-token-len))
2147 face)
2148 js2-parsed-warnings)))
2149
2150 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2151 (if js2-compiler-strict-mode
2152 (js2-report-warning msg-id msg-arg beg
2153 (and beg end (- end beg)))))
2154
2155 (put 'js2-syntax-error 'error-conditions
2156 '(error syntax-error js2-syntax-error))
2157 (put 'js2-syntax-error 'error-message "Syntax error")
2158
2159 (put 'js2-parse-error 'error-conditions
2160 '(error parse-error js2-parse-error))
2161 (put 'js2-parse-error 'error-message "Parse error")
2162
2163 (defmacro js2-clear-flag (flags flag)
2164 `(setq ,flags (logand ,flags (lognot ,flag))))
2165
2166 (defmacro js2-set-flag (flags flag)
2167 "Logical-or FLAG into FLAGS."
2168 `(setq ,flags (logior ,flags ,flag)))
2169
2170 (defsubst js2-flag-set-p (flags flag)
2171 (/= 0 (logand flags flag)))
2172
2173 (defsubst js2-flag-not-set-p (flags flag)
2174 (zerop (logand flags flag)))
2175
2176 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2177 "Evaluate BODY with the _ character set to be word-syntax."
2178 (declare (indent 0) (debug t))
2179 (let ((old-syntax (make-symbol "old-syntax")))
2180 `(let ((,old-syntax (string (char-syntax ?_))))
2181 (unwind-protect
2182 (progn
2183 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2184 ,@body)
2185 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2186
2187 ;;; AST struct and function definitions
2188
2189 ;; flags for ast node property 'member-type (used for e4x operators)
2190 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2191 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2192 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2193
2194 (defsubst js2-relpos (pos anchor)
2195 "Convert POS to be relative to ANCHOR.
2196 If POS is nil, returns nil."
2197 (and pos (- pos anchor)))
2198
2199 (defun js2-make-pad (indent)
2200 (if (zerop indent)
2201 ""
2202 (make-string (* indent js2-basic-offset) ? )))
2203
2204 (defun js2-visit-ast (node callback)
2205 "Visit every node in ast NODE with visitor CALLBACK.
2206
2207 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2208 called twice: once to visit the node, and again after all the node's
2209 children have been processed. The END-P argument is nil on the first
2210 call and non-nil on the second call. The return value of the callback
2211 affects the traversal: if non-nil, the children of NODE are processed.
2212 If the callback returns nil, or if the node has no children, then the
2213 callback is called immediately with a non-nil END-P argument.
2214
2215 The node traversal is approximately lexical-order, although there
2216 are currently no guarantees around this."
2217 (when node
2218 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2219 ;; visit the node
2220 (when (funcall callback node nil)
2221 ;; visit the kids
2222 (cond
2223 ((eq vfunc 'js2-visit-none)
2224 nil) ; don't even bother calling it
2225 ;; Each AST node type has to define a `js2-visitor' function
2226 ;; that takes a node and a callback, and calls `js2-visit-ast'
2227 ;; on each child of the node.
2228 (vfunc
2229 (funcall vfunc node callback))
2230 (t
2231 (error "%s does not define a visitor-traversal function"
2232 (aref node 0)))))
2233 ;; call the end-visit
2234 (funcall callback node t))))
2235
2236 (cl-defstruct (js2-node
2237 (:constructor nil)) ; abstract
2238 "Base AST node type."
2239 (type -1) ; token type
2240 (pos -1) ; start position of this AST node in parsed input
2241 (len 1) ; num characters spanned by the node
2242 props ; optional node property list (an alist)
2243 parent) ; link to parent node; null for root
2244
2245 (defsubst js2-node-get-prop (node prop &optional default)
2246 (or (cadr (assoc prop (js2-node-props node))) default))
2247
2248 (defsubst js2-node-set-prop (node prop value)
2249 (setf (js2-node-props node)
2250 (cons (list prop value) (js2-node-props node))))
2251
2252 (defun js2-fixup-starts (n nodes)
2253 "Adjust the start positions of NODES to be relative to N.
2254 Any node in the list may be nil, for convenience."
2255 (dolist (node nodes)
2256 (when node
2257 (setf (js2-node-pos node) (- (js2-node-pos node)
2258 (js2-node-pos n))))))
2259
2260 (defun js2-node-add-children (parent &rest nodes)
2261 "Set parent node of NODES to PARENT, and return PARENT.
2262 Does nothing if we're not recording parent links.
2263 If any given node in NODES is nil, doesn't record that link."
2264 (js2-fixup-starts parent nodes)
2265 (dolist (node nodes)
2266 (and node
2267 (setf (js2-node-parent node) parent))))
2268
2269 ;; Non-recursive since it's called a frightening number of times.
2270 (defun js2-node-abs-pos (n)
2271 (let ((pos (js2-node-pos n)))
2272 (while (setq n (js2-node-parent n))
2273 (setq pos (+ pos (js2-node-pos n))))
2274 pos))
2275
2276 (defsubst js2-node-abs-end (n)
2277 "Return absolute buffer position of end of N."
2278 (+ (js2-node-abs-pos n) (js2-node-len n)))
2279
2280 ;; It's important to make sure block nodes have a Lisp list for the
2281 ;; child nodes, to limit printing recursion depth in an AST that
2282 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2283 ;; a sufficiently large vector tree.
2284
2285 (cl-defstruct (js2-block-node
2286 (:include js2-node)
2287 (:constructor nil)
2288 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2289 (pos (js2-current-token-beg))
2290 len
2291 props
2292 kids)))
2293 "A block of statements."
2294 kids) ; a Lisp list of the child statement nodes
2295
2296 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2297 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2298
2299 (defun js2-visit-block (ast callback)
2300 "Visit the `js2-block-node' children of AST."
2301 (dolist (kid (js2-block-node-kids ast))
2302 (js2-visit-ast kid callback)))
2303
2304 (defun js2-print-block (n i)
2305 (let ((pad (js2-make-pad i)))
2306 (insert pad "{\n")
2307 (dolist (kid (js2-block-node-kids n))
2308 (js2-print-ast kid (1+ i)))
2309 (insert pad "}")))
2310
2311 (cl-defstruct (js2-scope
2312 (:include js2-block-node)
2313 (:constructor nil)
2314 (:constructor make-js2-scope (&key (type js2-BLOCK)
2315 (pos (js2-current-token-beg))
2316 len
2317 kids)))
2318 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2319 ;; I don't have one of those handy, so I'll use an alist for now.
2320 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2321 ;; and is much lighter-weight to construct (both CPU and mem).
2322 ;; The keys are interned strings (symbols) for faster lookup.
2323 ;; Should switch to hybrid alist/hashtable eventually.
2324 symbol-table ; an alist of (symbol . js2-symbol)
2325 parent-scope ; a `js2-scope'
2326 top) ; top-level `js2-scope' (script/function)
2327
2328 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2329 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2330
2331 (defun js2-node-get-enclosing-scope (node)
2332 "Return the innermost `js2-scope' node surrounding NODE.
2333 Returns nil if there is no enclosing scope node."
2334 (while (and (setq node (js2-node-parent node))
2335 (not (js2-scope-p node))))
2336 node)
2337
2338 (defun js2-get-defining-scope (scope name &optional point)
2339 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2340 Returns `js2-scope' in which NAME is defined, or nil if not found.
2341
2342 If POINT is non-nil, and if the found declaration type is
2343 `js2-LET', also check that the declaration node is before POINT."
2344 (let ((sym (if (symbolp name)
2345 name
2346 (intern name)))
2347 result
2348 (continue t))
2349 (while (and scope continue)
2350 (if (or
2351 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2352 (and entry
2353 (or (not point)
2354 (not (eq js2-LET (js2-symbol-decl-type entry)))
2355 (>= point
2356 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2357 (and (eq sym 'arguments)
2358 (js2-function-node-p scope)))
2359 (setq continue nil
2360 result scope)
2361 (setq scope (js2-scope-parent-scope scope))))
2362 result))
2363
2364 (defun js2-scope-get-symbol (scope name)
2365 "Return symbol table entry for NAME in SCOPE.
2366 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2367 (and (js2-scope-symbol-table scope)
2368 (cdr (assq (if (symbolp name)
2369 name
2370 (intern name))
2371 (js2-scope-symbol-table scope)))))
2372
2373 (defun js2-scope-put-symbol (scope name symbol)
2374 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2375 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2376 (let* ((table (js2-scope-symbol-table scope))
2377 (sym (if (symbolp name) name (intern name)))
2378 (entry (assq sym table)))
2379 (if entry
2380 (setcdr entry symbol)
2381 (push (cons sym symbol)
2382 (js2-scope-symbol-table scope)))))
2383
2384 (cl-defstruct (js2-symbol
2385 (:constructor nil)
2386 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2387 "A symbol table entry."
2388 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2389 ;; js2-LET, or js2-CONST
2390 decl-type
2391 name ; string
2392 ast-node) ; a `js2-node'
2393
2394 (cl-defstruct (js2-error-node
2395 (:include js2-node)
2396 (:constructor nil) ; silence emacs21 byte-compiler
2397 (:constructor make-js2-error-node (&key (type js2-ERROR)
2398 (pos (js2-current-token-beg))
2399 len)))
2400 "AST node representing a parse error.")
2401
2402 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2403 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2404
2405 (cl-defstruct (js2-script-node
2406 (:include js2-scope)
2407 (:constructor nil)
2408 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2409 (pos (js2-current-token-beg))
2410 len
2411 ;; FIXME: What are those?
2412 var-decls
2413 fun-decls)))
2414 functions ; Lisp list of nested functions
2415 regexps ; Lisp list of (string . flags)
2416 symbols ; alist (every symbol gets unique index)
2417 (param-count 0)
2418 var-names ; vector of string names
2419 consts ; bool-vector matching var-decls
2420 (temp-number 0)) ; for generating temp variables
2421
2422 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2423 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2424
2425 (defun js2-print-script (node indent)
2426 (dolist (kid (js2-block-node-kids node))
2427 (js2-print-ast kid indent)))
2428
2429 (cl-defstruct (js2-ast-root
2430 (:include js2-script-node)
2431 (:constructor nil)
2432 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2433 (pos (js2-current-token-beg))
2434 len
2435 buffer)))
2436 "The root node of a js2 AST."
2437 buffer ; the source buffer from which the code was parsed
2438 comments ; a Lisp list of comments, ordered by start position
2439 errors ; a Lisp list of errors found during parsing
2440 warnings ; a Lisp list of warnings found during parsing
2441 node-count) ; number of nodes in the tree, including the root
2442
2443 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2444 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2445
2446 (defun js2-visit-ast-root (ast callback)
2447 (dolist (kid (js2-ast-root-kids ast))
2448 (js2-visit-ast kid callback))
2449 (dolist (comment (js2-ast-root-comments ast))
2450 (js2-visit-ast comment callback)))
2451
2452 (cl-defstruct (js2-comment-node
2453 (:include js2-node)
2454 (:constructor nil)
2455 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2456 (pos (js2-current-token-beg))
2457 len
2458 format)))
2459 format) ; 'line, 'block, 'jsdoc or 'html
2460
2461 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2462 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2463
2464 (defun js2-print-comment (n i)
2465 ;; We really ought to link end-of-line comments to their nodes.
2466 ;; Or maybe we could add a new comment type, 'endline.
2467 (insert (js2-make-pad i)
2468 (js2-node-string n)))
2469
2470 (cl-defstruct (js2-expr-stmt-node
2471 (:include js2-node)
2472 (:constructor nil)
2473 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2474 (pos js2-ts-cursor)
2475 len
2476 expr)))
2477 "An expression statement."
2478 expr)
2479
2480 (defsubst js2-expr-stmt-node-set-has-result (node)
2481 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2482 (setf (js2-node-type node) js2-EXPR_RESULT))
2483
2484 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2485 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2486
2487 (defun js2-visit-expr-stmt-node (n v)
2488 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2489
2490 (defun js2-print-expr-stmt-node (n indent)
2491 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2492 (insert ";\n"))
2493
2494 (cl-defstruct (js2-loop-node
2495 (:include js2-scope)
2496 (:constructor nil))
2497 "Abstract supertype of loop nodes."
2498 body ; a `js2-block-node'
2499 lp ; position of left-paren, nil if omitted
2500 rp) ; position of right-paren, nil if omitted
2501
2502 (cl-defstruct (js2-do-node
2503 (:include js2-loop-node)
2504 (:constructor nil)
2505 (:constructor make-js2-do-node (&key (type js2-DO)
2506 (pos (js2-current-token-beg))
2507 len
2508 body
2509 condition
2510 while-pos
2511 lp
2512 rp)))
2513 "AST node for do-loop."
2514 condition ; while (expression)
2515 while-pos) ; buffer position of 'while' keyword
2516
2517 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2518 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2519
2520 (defun js2-visit-do-node (n v)
2521 (js2-visit-ast (js2-do-node-body n) v)
2522 (js2-visit-ast (js2-do-node-condition n) v))
2523
2524 (defun js2-print-do-node (n i)
2525 (let ((pad (js2-make-pad i)))
2526 (insert pad "do {\n")
2527 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2528 (js2-print-ast kid (1+ i)))
2529 (insert pad "} while (")
2530 (js2-print-ast (js2-do-node-condition n) 0)
2531 (insert ");\n")))
2532
2533 (cl-defstruct (js2-export-node
2534 (:include js2-node)
2535 (:constructor nil)
2536 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2537 (pos (js2-current-token-beg))
2538 len
2539 exports-list
2540 from-clause
2541 declaration
2542 default)))
2543 "AST node for an export statement. There are many things that can be exported,
2544 so many of its properties will be nil.
2545 "
2546 exports-list ; lisp list of js2-export-binding-node to export
2547 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2548 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2549 default) ; js2-function-node or js2-assign-node
2550
2551 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2552 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2553
2554 (defun js2-visit-export-node (n v)
2555 (let ((exports-list (js2-export-node-exports-list n))
2556 (from (js2-export-node-from-clause n))
2557 (declaration (js2-export-node-declaration n))
2558 (default (js2-export-node-default n)))
2559 (when exports-list
2560 (dolist (export exports-list)
2561 (js2-visit-ast export v)))
2562 (when from
2563 (js2-visit-ast from v))
2564 (when declaration
2565 (js2-visit-ast declaration v))
2566 (when default
2567 (js2-visit-ast default v))))
2568
2569 (defun js2-print-export-node (n i)
2570 (let ((pad (js2-make-pad i))
2571 (exports-list (js2-export-node-exports-list n))
2572 (from (js2-export-node-from-clause n))
2573 (declaration (js2-export-node-declaration n))
2574 (default (js2-export-node-default n)))
2575 (insert pad "export ")
2576 (cond
2577 (default
2578 (insert "default ")
2579 (js2-print-ast default i))
2580 (declaration
2581 (js2-print-ast declaration i))
2582 ((and exports-list from)
2583 (js2-print-named-imports exports-list)
2584 (insert " ")
2585 (js2-print-from-clause from))
2586 (from
2587 (insert "* ")
2588 (js2-print-from-clause from))
2589 (exports-list
2590 (js2-print-named-imports exports-list)))
2591 (insert ";\n")))
2592
2593 (cl-defstruct (js2-while-node
2594 (:include js2-loop-node)
2595 (:constructor nil)
2596 (:constructor make-js2-while-node (&key (type js2-WHILE)
2597 (pos (js2-current-token-beg))
2598 len body
2599 condition lp
2600 rp)))
2601 "AST node for while-loop."
2602 condition) ; while-condition
2603
2604 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2605 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2606
2607 (defun js2-visit-while-node (n v)
2608 (js2-visit-ast (js2-while-node-condition n) v)
2609 (js2-visit-ast (js2-while-node-body n) v))
2610
2611 (defun js2-print-while-node (n i)
2612 (let ((pad (js2-make-pad i)))
2613 (insert pad "while (")
2614 (js2-print-ast (js2-while-node-condition n) 0)
2615 (insert ") {\n")
2616 (js2-print-body (js2-while-node-body n) (1+ i))
2617 (insert pad "}\n")))
2618
2619 (cl-defstruct (js2-for-node
2620 (:include js2-loop-node)
2621 (:constructor nil)
2622 (:constructor make-js2-for-node (&key (type js2-FOR)
2623 (pos js2-ts-cursor)
2624 len body init
2625 condition
2626 update lp rp)))
2627 "AST node for a C-style for-loop."
2628 init ; initialization expression
2629 condition ; loop condition
2630 update) ; update clause
2631
2632 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2633 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2634
2635 (defun js2-visit-for-node (n v)
2636 (js2-visit-ast (js2-for-node-init n) v)
2637 (js2-visit-ast (js2-for-node-condition n) v)
2638 (js2-visit-ast (js2-for-node-update n) v)
2639 (js2-visit-ast (js2-for-node-body n) v))
2640
2641 (defun js2-print-for-node (n i)
2642 (let ((pad (js2-make-pad i)))
2643 (insert pad "for (")
2644 (js2-print-ast (js2-for-node-init n) 0)
2645 (insert "; ")
2646 (js2-print-ast (js2-for-node-condition n) 0)
2647 (insert "; ")
2648 (js2-print-ast (js2-for-node-update n) 0)
2649 (insert ") {\n")
2650 (js2-print-body (js2-for-node-body n) (1+ i))
2651 (insert pad "}\n")))
2652
2653 (cl-defstruct (js2-for-in-node
2654 (:include js2-loop-node)
2655 (:constructor nil)
2656 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2657 (pos js2-ts-cursor)
2658 len body
2659 iterator
2660 object
2661 in-pos
2662 each-pos
2663 foreach-p forof-p
2664 lp rp)))
2665 "AST node for a for..in loop."
2666 iterator ; [var] foo in ...
2667 object ; object over which we're iterating
2668 in-pos ; buffer position of 'in' keyword
2669 each-pos ; buffer position of 'each' keyword, if foreach-p
2670 foreach-p ; t if it's a for-each loop
2671 forof-p) ; t if it's a for-of loop
2672
2673 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2674 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2675
2676 (defun js2-visit-for-in-node (n v)
2677 (js2-visit-ast (js2-for-in-node-iterator n) v)
2678 (js2-visit-ast (js2-for-in-node-object n) v)
2679 (js2-visit-ast (js2-for-in-node-body n) v))
2680
2681 (defun js2-print-for-in-node (n i)
2682 (let ((pad (js2-make-pad i))
2683 (foreach (js2-for-in-node-foreach-p n))
2684 (forof (js2-for-in-node-forof-p n)))
2685 (insert pad "for ")
2686 (if foreach
2687 (insert "each "))
2688 (insert "(")
2689 (js2-print-ast (js2-for-in-node-iterator n) 0)
2690 (insert (if forof " of " " in "))
2691 (js2-print-ast (js2-for-in-node-object n) 0)
2692 (insert ") {\n")
2693 (js2-print-body (js2-for-in-node-body n) (1+ i))
2694 (insert pad "}\n")))
2695
2696 (cl-defstruct (js2-return-node
2697 (:include js2-node)
2698 (:constructor nil)
2699 (:constructor make-js2-return-node (&key (type js2-RETURN)
2700 (pos js2-ts-cursor)
2701 len
2702 retval)))
2703 "AST node for a return statement."
2704 retval) ; expression to return, or 'undefined
2705
2706 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2707 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2708
2709 (defun js2-visit-return-node (n v)
2710 (js2-visit-ast (js2-return-node-retval n) v))
2711
2712 (defun js2-print-return-node (n i)
2713 (insert (js2-make-pad i) "return")
2714 (when (js2-return-node-retval n)
2715 (insert " ")
2716 (js2-print-ast (js2-return-node-retval n) 0))
2717 (insert ";\n"))
2718
2719 (cl-defstruct (js2-if-node
2720 (:include js2-node)
2721 (:constructor nil)
2722 (:constructor make-js2-if-node (&key (type js2-IF)
2723 (pos js2-ts-cursor)
2724 len condition
2725 then-part
2726 else-pos
2727 else-part lp
2728 rp)))
2729 "AST node for an if-statement."
2730 condition ; expression
2731 then-part ; statement or block
2732 else-pos ; optional buffer position of 'else' keyword
2733 else-part ; optional statement or block
2734 lp ; position of left-paren, nil if omitted
2735 rp) ; position of right-paren, nil if omitted
2736
2737 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2738 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2739
2740 (defun js2-visit-if-node (n v)
2741 (js2-visit-ast (js2-if-node-condition n) v)
2742 (js2-visit-ast (js2-if-node-then-part n) v)
2743 (js2-visit-ast (js2-if-node-else-part n) v))
2744
2745 (defun js2-print-if-node (n i)
2746 (let ((pad (js2-make-pad i))
2747 (then-part (js2-if-node-then-part n))
2748 (else-part (js2-if-node-else-part n)))
2749 (insert pad "if (")
2750 (js2-print-ast (js2-if-node-condition n) 0)
2751 (insert ") {\n")
2752 (js2-print-body then-part (1+ i))
2753 (insert pad "}")
2754 (cond
2755 ((not else-part)
2756 (insert "\n"))
2757 ((js2-if-node-p else-part)
2758 (insert " else ")
2759 (js2-print-body else-part i))
2760 (t
2761 (insert " else {\n")
2762 (js2-print-body else-part (1+ i))
2763 (insert pad "}\n")))))
2764
2765 (cl-defstruct (js2-export-binding-node
2766 (:include js2-node)
2767 (:constructor nil)
2768 (:constructor make-js2-export-binding-node (&key (type -1)
2769 pos
2770 len
2771 local-name
2772 extern-name)))
2773 "AST node for an external symbol binding.
2774 It contains a local-name node which is the name of the value in the
2775 current scope, and extern-name which is the name of the value in the
2776 imported or exported scope. By default these are the same, but if the
2777 name is aliased as in {foo as bar}, it would have an extern-name node
2778 containing 'foo' and a local-name node containing 'bar'."
2779 local-name ; js2-name-node with the variable name in this scope
2780 extern-name) ; js2-name-node with the value name in the exporting module
2781
2782 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2783 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2784
2785 (defun js2-visit-extern-binding (n v)
2786 "Visit an extern binding node. First visit the local-name, and, if
2787 different, visit the extern-name."
2788 (let ((local-name (js2-export-binding-node-local-name n))
2789 (extern-name (js2-export-binding-node-extern-name n)))
2790 (when local-name
2791 (js2-visit-ast local-name v))
2792 (when (not (equal local-name extern-name))
2793 (js2-visit-ast extern-name v))))
2794
2795 (defun js2-print-extern-binding (n _i)
2796 "Print a representation of a single extern binding. E.g. 'foo' or
2797 'foo as bar'."
2798 (let ((local-name (js2-export-binding-node-local-name n))
2799 (extern-name (js2-export-binding-node-extern-name n)))
2800 (insert (js2-name-node-name extern-name))
2801 (when (not (equal local-name extern-name))
2802 (insert " as ")
2803 (insert (js2-name-node-name local-name)))))
2804
2805
2806 (cl-defstruct (js2-import-node
2807 (:include js2-node)
2808 (:constructor nil)
2809 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2810 (pos (js2-current-token-beg))
2811 len
2812 import
2813 from
2814 module-id)))
2815 "AST node for an import statement. It follows the form
2816
2817 import ModuleSpecifier;
2818 import ImportClause FromClause;"
2819 import ; js2-import-clause-node specifying which names are to imported.
2820 from ; js2-from-clause-node indicating the module from which to import.
2821 module-id) ; module-id of the import. E.g. 'src/mylib'.
2822
2823 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2824 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2825
2826 (defun js2-visit-import (n v)
2827 (let ((import-clause (js2-import-node-import n))
2828 (from-clause (js2-import-node-from n)))
2829 (when import-clause
2830 (js2-visit-ast import-clause v))
2831 (when from-clause
2832 (js2-visit-ast from-clause v))))
2833
2834 (defun js2-print-import (n i)
2835 "Prints a representation of the import node"
2836 (let ((pad (js2-make-pad i))
2837 (import-clause (js2-import-node-import n))
2838 (from-clause (js2-import-node-from n))
2839 (module-id (js2-import-node-module-id n)))
2840 (insert pad "import ")
2841 (if import-clause
2842 (progn
2843 (js2-print-import-clause import-clause)
2844 (insert " ")
2845 (js2-print-from-clause from-clause))
2846 (insert "'")
2847 (insert module-id)
2848 (insert "'"))
2849 (insert ";\n")))
2850
2851 (cl-defstruct (js2-import-clause-node
2852 (:include js2-node)
2853 (:constructor nil)
2854 (:constructor make-js2-import-clause-node (&key (type -1)
2855 pos
2856 len
2857 namespace-import
2858 named-imports
2859 default-binding)))
2860 "AST node corresponding to the import clause of an import statement. This is
2861 the portion of the import that bindings names from the external context to the
2862 local context."
2863 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2864 named-imports ; lisp list of js2-export-binding-node for all named imports.
2865 default-binding) ; js2-export-binding-node for the default import binding
2866
2867 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2868 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2869
2870 (defun js2-visit-import-clause (n v)
2871 (let ((ns-import (js2-import-clause-node-namespace-import n))
2872 (named-imports (js2-import-clause-node-named-imports n))
2873 (default (js2-import-clause-node-default-binding n)))
2874 (when ns-import
2875 (js2-visit-ast ns-import v))
2876 (when named-imports
2877 (dolist (import named-imports)
2878 (js2-visit-ast import v)))
2879 (when default
2880 (js2-visit-ast default v))))
2881
2882 (defun js2-print-import-clause (n)
2883 (let ((ns-import (js2-import-clause-node-namespace-import n))
2884 (named-imports (js2-import-clause-node-named-imports n))
2885 (default (js2-import-clause-node-default-binding n)))
2886 (cond
2887 ((and default ns-import)
2888 (js2-print-ast default)
2889 (insert ", ")
2890 (js2-print-namespace-import ns-import))
2891 ((and default named-imports)
2892 (js2-print-ast default)
2893 (insert ", ")
2894 (js2-print-named-imports named-imports))
2895 (default
2896 (js2-print-ast default))
2897 (ns-import
2898 (js2-print-namespace-import ns-import))
2899 (named-imports
2900 (js2-print-named-imports named-imports)))))
2901
2902 (defun js2-print-namespace-import (node)
2903 (insert "* as ")
2904 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2905
2906 (defun js2-print-named-imports (imports)
2907 (insert "{")
2908 (let ((len (length imports))
2909 (n 0))
2910 (while (< n len)
2911 (js2-print-extern-binding (nth n imports) 0)
2912 (unless (= n (- len 1))
2913 (insert ", "))
2914 (setq n (+ n 1))))
2915 (insert "}"))
2916
2917 (cl-defstruct (js2-namespace-import-node
2918 (:include js2-node)
2919 (:constructor nil)
2920 (:constructor make-js2-namespace-import-node (&key (type -1)
2921 pos
2922 len
2923 name)))
2924 "AST node for a complete namespace import.
2925 E.g. the '* as lib' expression in:
2926
2927 import * as lib from 'src/lib'
2928
2929 It contains a single name node referring to the bound name."
2930 name) ; js2-name-node of the bound name.
2931
2932 (defun js2-visit-namespace-import (n v)
2933 (js2-visit-ast (js2-namespace-import-node-name n) v))
2934
2935 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2936 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2937
2938 (cl-defstruct (js2-from-clause-node
2939 (:include js2-node)
2940 (:constructor nil)
2941 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2942 pos
2943 len
2944 module-id
2945 metadata-p)))
2946 "AST node for the from clause in an import or export statement.
2947 E.g. from 'my/module'. It can refere to either an external module, or to the
2948 modules metadata itself."
2949 module-id ; string containing the module specifier.
2950 metadata-p) ; true if this clause refers to the module's metadata
2951
2952 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2953 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2954
2955 (defun js2-print-from-clause (n)
2956 (insert "from ")
2957 (if (js2-from-clause-node-metadata-p n)
2958 (insert "this module")
2959 (insert "'")
2960 (insert (js2-from-clause-node-module-id n))
2961 (insert "'")))
2962
2963 (cl-defstruct (js2-try-node
2964 (:include js2-node)
2965 (:constructor nil)
2966 (:constructor make-js2-try-node (&key (type js2-TRY)
2967 (pos js2-ts-cursor)
2968 len
2969 try-block
2970 catch-clauses
2971 finally-block)))
2972 "AST node for a try-statement."
2973 try-block
2974 catch-clauses ; a Lisp list of `js2-catch-node'
2975 finally-block) ; a `js2-finally-node'
2976
2977 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2978 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2979
2980 (defun js2-visit-try-node (n v)
2981 (js2-visit-ast (js2-try-node-try-block n) v)
2982 (dolist (clause (js2-try-node-catch-clauses n))
2983 (js2-visit-ast clause v))
2984 (js2-visit-ast (js2-try-node-finally-block n) v))
2985
2986 (defun js2-print-try-node (n i)
2987 (let ((pad (js2-make-pad i))
2988 (catches (js2-try-node-catch-clauses n))
2989 (finally (js2-try-node-finally-block n)))
2990 (insert pad "try {\n")
2991 (js2-print-body (js2-try-node-try-block n) (1+ i))
2992 (insert pad "}")
2993 (when catches
2994 (dolist (catch catches)
2995 (js2-print-ast catch i)))
2996 (if finally
2997 (js2-print-ast finally i)
2998 (insert "\n"))))
2999
3000 (cl-defstruct (js2-catch-node
3001 (:include js2-scope)
3002 (:constructor nil)
3003 (:constructor make-js2-catch-node (&key (type js2-CATCH)
3004 (pos js2-ts-cursor)
3005 len
3006 param
3007 guard-kwd
3008 guard-expr
3009 lp rp)))
3010 "AST node for a catch clause."
3011 param ; destructuring form or simple name node
3012 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
3013 guard-expr ; catch condition, a `js2-node'
3014 lp ; buffer position of left-paren, nil if omitted
3015 rp) ; buffer position of right-paren, nil if omitted
3016
3017 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
3018 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
3019
3020 (defun js2-visit-catch-node (n v)
3021 (js2-visit-ast (js2-catch-node-param n) v)
3022 (when (js2-catch-node-guard-kwd n)
3023 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3024 (js2-visit-block n v))
3025
3026 (defun js2-print-catch-node (n i)
3027 (let ((pad (js2-make-pad i))
3028 (guard-kwd (js2-catch-node-guard-kwd n))
3029 (guard-expr (js2-catch-node-guard-expr n)))
3030 (insert " catch (")
3031 (js2-print-ast (js2-catch-node-param n) 0)
3032 (when guard-kwd
3033 (insert " if ")
3034 (js2-print-ast guard-expr 0))
3035 (insert ") {\n")
3036 (js2-print-body n (1+ i))
3037 (insert pad "}")))
3038
3039 (cl-defstruct (js2-finally-node
3040 (:include js2-node)
3041 (:constructor nil)
3042 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3043 (pos js2-ts-cursor)
3044 len body)))
3045 "AST node for a finally clause."
3046 body) ; a `js2-node', often but not always a block node
3047
3048 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3049 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3050
3051 (defun js2-visit-finally-node (n v)
3052 (js2-visit-ast (js2-finally-node-body n) v))
3053
3054 (defun js2-print-finally-node (n i)
3055 (let ((pad (js2-make-pad i)))
3056 (insert " finally {\n")
3057 (js2-print-body (js2-finally-node-body n) (1+ i))
3058 (insert pad "}\n")))
3059
3060 (cl-defstruct (js2-switch-node
3061 (:include js2-node)
3062 (:constructor nil)
3063 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3064 (pos js2-ts-cursor)
3065 len
3066 discriminant
3067 cases lp
3068 rp)))
3069 "AST node for a switch statement."
3070 discriminant ; a `js2-node' (switch expression)
3071 cases ; a Lisp list of `js2-case-node'
3072 lp ; position of open-paren for discriminant, nil if omitted
3073 rp) ; position of close-paren for discriminant, nil if omitted
3074
3075 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3076 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3077
3078 (defun js2-visit-switch-node (n v)
3079 (js2-visit-ast (js2-switch-node-discriminant n) v)
3080 (dolist (c (js2-switch-node-cases n))
3081 (js2-visit-ast c v)))
3082
3083 (defun js2-print-switch-node (n i)
3084 (let ((pad (js2-make-pad i))
3085 (cases (js2-switch-node-cases n)))
3086 (insert pad "switch (")
3087 (js2-print-ast (js2-switch-node-discriminant n) 0)
3088 (insert ") {\n")
3089 (dolist (case cases)
3090 (js2-print-ast case i))
3091 (insert pad "}\n")))
3092
3093 (cl-defstruct (js2-case-node
3094 (:include js2-block-node)
3095 (:constructor nil)
3096 (:constructor make-js2-case-node (&key (type js2-CASE)
3097 (pos js2-ts-cursor)
3098 len kids expr)))
3099 "AST node for a case clause of a switch statement."
3100 expr) ; the case expression (nil for default)
3101
3102 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3103 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3104
3105 (defun js2-visit-case-node (n v)
3106 (js2-visit-ast (js2-case-node-expr n) v)
3107 (js2-visit-block n v))
3108
3109 (defun js2-print-case-node (n i)
3110 (let ((pad (js2-make-pad i))
3111 (expr (js2-case-node-expr n)))
3112 (insert pad)
3113 (if (null expr)
3114 (insert "default:\n")
3115 (insert "case ")
3116 (js2-print-ast expr 0)
3117 (insert ":\n"))
3118 (dolist (kid (js2-case-node-kids n))
3119 (js2-print-ast kid (1+ i)))))
3120
3121 (cl-defstruct (js2-throw-node
3122 (:include js2-node)
3123 (:constructor nil)
3124 (:constructor make-js2-throw-node (&key (type js2-THROW)
3125 (pos js2-ts-cursor)
3126 len expr)))
3127 "AST node for a throw statement."
3128 expr) ; the expression to throw
3129
3130 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3131 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3132
3133 (defun js2-visit-throw-node (n v)
3134 (js2-visit-ast (js2-throw-node-expr n) v))
3135
3136 (defun js2-print-throw-node (n i)
3137 (insert (js2-make-pad i) "throw ")
3138 (js2-print-ast (js2-throw-node-expr n) 0)
3139 (insert ";\n"))
3140
3141 (cl-defstruct (js2-with-node
3142 (:include js2-node)
3143 (:constructor nil)
3144 (:constructor make-js2-with-node (&key (type js2-WITH)
3145 (pos js2-ts-cursor)
3146 len object
3147 body lp rp)))
3148 "AST node for a with-statement."
3149 object
3150 body
3151 lp ; buffer position of left-paren around object, nil if omitted
3152 rp) ; buffer position of right-paren around object, nil if omitted
3153
3154 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3155 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3156
3157 (defun js2-visit-with-node (n v)
3158 (js2-visit-ast (js2-with-node-object n) v)
3159 (js2-visit-ast (js2-with-node-body n) v))
3160
3161 (defun js2-print-with-node (n i)
3162 (let ((pad (js2-make-pad i)))
3163 (insert pad "with (")
3164 (js2-print-ast (js2-with-node-object n) 0)
3165 (insert ") {\n")
3166 (js2-print-body (js2-with-node-body n) (1+ i))
3167 (insert pad "}\n")))
3168
3169 (cl-defstruct (js2-label-node
3170 (:include js2-node)
3171 (:constructor nil)
3172 (:constructor make-js2-label-node (&key (type js2-LABEL)
3173 (pos js2-ts-cursor)
3174 len name)))
3175 "AST node for a statement label or case label."
3176 name ; a string
3177 loop) ; for validating and code-generating continue-to-label
3178
3179 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3180 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3181
3182 (defun js2-print-label (n i)
3183 (insert (js2-make-pad i)
3184 (js2-label-node-name n)
3185 ":\n"))
3186
3187 (cl-defstruct (js2-labeled-stmt-node
3188 (:include js2-node)
3189 (:constructor nil)
3190 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3191 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3192 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3193 (pos js2-ts-cursor)
3194 len labels stmt)))
3195 "AST node for a statement with one or more labels.
3196 Multiple labels for a statement are collapsed into the labels field."
3197 labels ; Lisp list of `js2-label-node'
3198 stmt) ; the statement these labels are for
3199
3200 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3201 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3202
3203 (defun js2-get-label-by-name (lbl-stmt name)
3204 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3205 Returns nil if no such label is in the list."
3206 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3207 result)
3208 (while (and label-list (not result))
3209 (if (string= (js2-label-node-name (car label-list)) name)
3210 (setq result (car label-list))
3211 (setq label-list (cdr label-list))))
3212 result))
3213
3214 (defun js2-visit-labeled-stmt (n v)
3215 (dolist (label (js2-labeled-stmt-node-labels n))
3216 (js2-visit-ast label v))
3217 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3218
3219 (defun js2-print-labeled-stmt (n i)
3220 (dolist (label (js2-labeled-stmt-node-labels n))
3221 (js2-print-ast label i))
3222 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3223
3224 (defun js2-labeled-stmt-node-contains (node label)
3225 "Return t if NODE contains LABEL in its label set.
3226 NODE is a `js2-labels-node'. LABEL is an identifier."
3227 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3228 if (string= label (js2-label-node-name nl))
3229 return t
3230 finally return nil))
3231
3232 (defsubst js2-labeled-stmt-node-add-label (node label)
3233 "Add a `js2-label-node' to the label set for this statement."
3234 (setf (js2-labeled-stmt-node-labels node)
3235 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3236
3237 (cl-defstruct (js2-jump-node
3238 (:include js2-node)
3239 (:constructor nil))
3240 "Abstract supertype of break and continue nodes."
3241 label ; `js2-name-node' for location of label identifier, if present
3242 target) ; target js2-labels-node or loop/switch statement
3243
3244 (defun js2-visit-jump-node (n v)
3245 ;; We don't visit the target, since it's a back-link.
3246 (js2-visit-ast (js2-jump-node-label n) v))
3247
3248 (cl-defstruct (js2-break-node
3249 (:include js2-jump-node)
3250 (:constructor nil)
3251 (:constructor make-js2-break-node (&key (type js2-BREAK)
3252 (pos js2-ts-cursor)
3253 len label target)))
3254 "AST node for a break statement.
3255 The label field is a `js2-name-node', possibly nil, for the named label
3256 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3257 is the target of the break - a label node or enclosing loop/switch statement.")
3258
3259 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3260 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3261
3262 (defun js2-print-break-node (n i)
3263 (insert (js2-make-pad i) "break")
3264 (when (js2-break-node-label n)
3265 (insert " ")
3266 (js2-print-ast (js2-break-node-label n) 0))
3267 (insert ";\n"))
3268
3269 (cl-defstruct (js2-continue-node
3270 (:include js2-jump-node)
3271 (:constructor nil)
3272 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3273 (pos js2-ts-cursor)
3274 len label target)))
3275 "AST node for a continue statement.
3276 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3277 It is nil if continue specifies no label. The target field is the jump target:
3278 a `js2-label-node' or the innermost enclosing loop.")
3279
3280 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3281 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3282
3283 (defun js2-print-continue-node (n i)
3284 (insert (js2-make-pad i) "continue")
3285 (when (js2-continue-node-label n)
3286 (insert " ")
3287 (js2-print-ast (js2-continue-node-label n) 0))
3288 (insert ";\n"))
3289
3290 (cl-defstruct (js2-function-node
3291 (:include js2-script-node)
3292 (:constructor nil)
3293 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3294 (pos js2-ts-cursor)
3295 len
3296 (ftype 'FUNCTION)
3297 (form 'FUNCTION_STATEMENT)
3298 (name "")
3299 params rest-p
3300 body
3301 generator-type
3302 lp rp)))
3303 "AST node for a function declaration.
3304 The `params' field is a Lisp list of nodes. Each node is either a simple
3305 `js2-name-node', or if it's a destructuring-assignment parameter, a
3306 `js2-array-node' or `js2-object-node'."
3307 ftype ; FUNCTION, GETTER or SETTER
3308 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3309 name ; function name (a `js2-name-node', or nil if anonymous)
3310 params ; a Lisp list of destructuring forms or simple name nodes
3311 rest-p ; if t, the last parameter is rest parameter
3312 body ; a `js2-block-node' or expression node (1.8 only)
3313 lp ; position of arg-list open-paren, or nil if omitted
3314 rp ; position of arg-list close-paren, or nil if omitted
3315 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3316 needs-activation ; t if we need an activation object for this frame
3317 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3318 member-expr) ; nonstandard Ecma extension from Rhino
3319
3320 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3321 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3322
3323 (defun js2-visit-function-node (n v)
3324 (js2-visit-ast (js2-function-node-name n) v)
3325 (dolist (p (js2-function-node-params n))
3326 (js2-visit-ast p v))
3327 (js2-visit-ast (js2-function-node-body n) v))
3328
3329 (defun js2-print-function-node (n i)
3330 (let* ((pad (js2-make-pad i))
3331 (getter (js2-node-get-prop n 'GETTER_SETTER))
3332 (name (or (js2-function-node-name n)
3333 (js2-function-node-member-expr n)))
3334 (params (js2-function-node-params n))
3335 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3336 (rest-p (js2-function-node-rest-p n))
3337 (body (js2-function-node-body n))
3338 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3339 (unless (or getter arrow)
3340 (insert pad "function")
3341 (when (eq (js2-function-node-generator-type n) 'STAR)
3342 (insert "*")))
3343 (when name
3344 (insert " ")
3345 (js2-print-ast name 0))
3346 (insert "(")
3347 (cl-loop with len = (length params)
3348 for param in params
3349 for count from 1
3350 do
3351 (when (and rest-p (= count len))
3352 (insert "..."))
3353 (js2-print-ast param 0)
3354 (when (< count len)
3355 (insert ", ")))
3356 (insert ") ")
3357 (when arrow
3358 (insert "=> "))
3359 (insert "{")
3360 ;; TODO: fix this to be smarter about indenting, etc.
3361 (unless expr
3362 (insert "\n"))
3363 (if (js2-block-node-p body)
3364 (js2-print-body body (1+ i))
3365 (js2-print-ast body 0))
3366 (insert pad "}")
3367 (unless expr
3368 (insert "\n"))))
3369
3370 (defun js2-function-name (node)
3371 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3372 (and (js2-function-node-name node)
3373 (js2-name-node-name (js2-function-node-name node))))
3374
3375 ;; Having this be an expression node makes it more flexible.
3376 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3377 ;; that work better if you assume it's an expression. Whenever we have
3378 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3379 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3380 (cl-defstruct (js2-var-decl-node
3381 (:include js2-node)
3382 (:constructor nil)
3383 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3384 (pos (js2-current-token-beg))
3385 len kids
3386 decl-type)))
3387 "AST node for a variable declaration list (VAR, CONST or LET).
3388 The node bounds differ depending on the declaration type. For VAR or
3389 CONST declarations, the bounds include the var/const keyword. For LET
3390 declarations, the node begins at the position of the first child."
3391 kids ; a Lisp list of `js2-var-init-node' structs.
3392 decl-type) ; js2-VAR, js2-CONST or js2-LET
3393
3394 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3395 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3396
3397 (defun js2-visit-var-decl (n v)
3398 (dolist (kid (js2-var-decl-node-kids n))
3399 (js2-visit-ast kid v)))
3400
3401 (defun js2-print-var-decl (n i)
3402 (let ((pad (js2-make-pad i))
3403 (tt (js2-var-decl-node-decl-type n)))
3404 (insert pad)
3405 (insert (cond
3406 ((= tt js2-VAR) "var ")
3407 ((= tt js2-LET) "let ")
3408 ((= tt js2-CONST) "const ")
3409 (t
3410 (error "malformed var-decl node"))))
3411 (cl-loop with kids = (js2-var-decl-node-kids n)
3412 with len = (length kids)
3413 for kid in kids
3414 for count from 1
3415 do
3416 (js2-print-ast kid 0)
3417 (if (< count len)
3418 (insert ", ")))))
3419
3420 (cl-defstruct (js2-var-init-node
3421 (:include js2-node)
3422 (:constructor nil)
3423 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3424 (pos js2-ts-cursor)
3425 len target
3426 initializer)))
3427 "AST node for a variable declaration.
3428 The type field will be js2-CONST for a const decl."
3429 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3430 initializer) ; initializer expression, a `js2-node'
3431
3432 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3433 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3434
3435 (defun js2-visit-var-init-node (n v)
3436 (js2-visit-ast (js2-var-init-node-target n) v)
3437 (js2-visit-ast (js2-var-init-node-initializer n) v))
3438
3439 (defun js2-print-var-init-node (n i)
3440 (let ((pad (js2-make-pad i))
3441 (name (js2-var-init-node-target n))
3442 (init (js2-var-init-node-initializer n)))
3443 (insert pad)
3444 (js2-print-ast name 0)
3445 (when init
3446 (insert " = ")
3447 (js2-print-ast init 0))))
3448
3449 (cl-defstruct (js2-cond-node
3450 (:include js2-node)
3451 (:constructor nil)
3452 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3453 (pos js2-ts-cursor)
3454 len
3455 test-expr
3456 true-expr
3457 false-expr
3458 q-pos c-pos)))
3459 "AST node for the ternary operator"
3460 test-expr
3461 true-expr
3462 false-expr
3463 q-pos ; buffer position of ?
3464 c-pos) ; buffer position of :
3465
3466 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3467 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3468
3469 (defun js2-visit-cond-node (n v)
3470 (js2-visit-ast (js2-cond-node-test-expr n) v)
3471 (js2-visit-ast (js2-cond-node-true-expr n) v)
3472 (js2-visit-ast (js2-cond-node-false-expr n) v))
3473
3474 (defun js2-print-cond-node (n i)
3475 (let ((pad (js2-make-pad i)))
3476 (insert pad)
3477 (js2-print-ast (js2-cond-node-test-expr n) 0)
3478 (insert " ? ")
3479 (js2-print-ast (js2-cond-node-true-expr n) 0)
3480 (insert " : ")
3481 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3482
3483 (cl-defstruct (js2-infix-node
3484 (:include js2-node)
3485 (:constructor nil)
3486 (:constructor make-js2-infix-node (&key type
3487 (pos js2-ts-cursor)
3488 len op-pos
3489 left right)))
3490 "Represents infix expressions.
3491 Includes assignment ops like `|=', and the comma operator.
3492 The type field inherited from `js2-node' holds the operator."
3493 op-pos ; buffer position where operator begins
3494 left ; any `js2-node'
3495 right) ; any `js2-node'
3496
3497 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3498 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3499
3500 (defun js2-visit-infix-node (n v)
3501 (js2-visit-ast (js2-infix-node-left n) v)
3502 (js2-visit-ast (js2-infix-node-right n) v))
3503
3504 (defconst js2-operator-tokens
3505 (let ((table (make-hash-table :test 'eq))
3506 (tokens
3507 (list (cons js2-IN "in")
3508 (cons js2-TYPEOF "typeof")
3509 (cons js2-INSTANCEOF "instanceof")
3510 (cons js2-DELPROP "delete")
3511 (cons js2-COMMA ",")
3512 (cons js2-COLON ":")
3513 (cons js2-OR "||")
3514 (cons js2-AND "&&")
3515 (cons js2-INC "++")
3516 (cons js2-DEC "--")
3517 (cons js2-BITOR "|")
3518 (cons js2-BITXOR "^")
3519 (cons js2-BITAND "&")
3520 (cons js2-EQ "==")
3521 (cons js2-NE "!=")
3522 (cons js2-LT "<")
3523 (cons js2-LE "<=")
3524 (cons js2-GT ">")
3525 (cons js2-GE ">=")
3526 (cons js2-LSH "<<")
3527 (cons js2-RSH ">>")
3528 (cons js2-URSH ">>>")
3529 (cons js2-ADD "+") ; infix plus
3530 (cons js2-SUB "-") ; infix minus
3531 (cons js2-MUL "*")
3532 (cons js2-DIV "/")
3533 (cons js2-MOD "%")
3534 (cons js2-NOT "!")
3535 (cons js2-BITNOT "~")
3536 (cons js2-POS "+") ; unary plus
3537 (cons js2-NEG "-") ; unary minus
3538 (cons js2-TRIPLEDOT "...")
3539 (cons js2-SHEQ "===") ; shallow equality
3540 (cons js2-SHNE "!==") ; shallow inequality
3541 (cons js2-ASSIGN "=")
3542 (cons js2-ASSIGN_BITOR "|=")
3543 (cons js2-ASSIGN_BITXOR "^=")
3544 (cons js2-ASSIGN_BITAND "&=")
3545 (cons js2-ASSIGN_LSH "<<=")
3546 (cons js2-ASSIGN_RSH ">>=")
3547 (cons js2-ASSIGN_URSH ">>>=")
3548 (cons js2-ASSIGN_ADD "+=")
3549 (cons js2-ASSIGN_SUB "-=")
3550 (cons js2-ASSIGN_MUL "*=")
3551 (cons js2-ASSIGN_DIV "/=")
3552 (cons js2-ASSIGN_MOD "%="))))
3553 (cl-loop for (k . v) in tokens do
3554 (puthash k v table))
3555 table))
3556
3557 (defun js2-print-infix-node (n i)
3558 (let* ((tt (js2-node-type n))
3559 (op (gethash tt js2-operator-tokens)))
3560 (unless op
3561 (error "unrecognized infix operator %s" (js2-node-type n)))
3562 (insert (js2-make-pad i))
3563 (js2-print-ast (js2-infix-node-left n) 0)
3564 (unless (= tt js2-COMMA)
3565 (insert " "))
3566 (insert op)
3567 (insert " ")
3568 (js2-print-ast (js2-infix-node-right n) 0)))
3569
3570 (cl-defstruct (js2-assign-node
3571 (:include js2-infix-node)
3572 (:constructor nil)
3573 (:constructor make-js2-assign-node (&key type
3574 (pos js2-ts-cursor)
3575 len op-pos
3576 left right)))
3577 "Represents any assignment.
3578 The type field holds the actual assignment operator.")
3579
3580 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3581 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3582
3583 (cl-defstruct (js2-unary-node
3584 (:include js2-node)
3585 (:constructor nil)
3586 (:constructor make-js2-unary-node (&key type ; required
3587 (pos js2-ts-cursor)
3588 len operand)))
3589 "AST node type for unary operator nodes.
3590 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3591 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3592 property is added if the operator follows the operand."
3593 operand) ; a `js2-node' expression
3594
3595 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3596 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3597
3598 (defun js2-visit-unary-node (n v)
3599 (js2-visit-ast (js2-unary-node-operand n) v))
3600
3601 (defun js2-print-unary-node (n i)
3602 (let* ((tt (js2-node-type n))
3603 (op (gethash tt js2-operator-tokens))
3604 (postfix (js2-node-get-prop n 'postfix)))
3605 (unless op
3606 (error "unrecognized unary operator %s" tt))
3607 (insert (js2-make-pad i))
3608 (unless postfix
3609 (insert op))
3610 (if (or (= tt js2-TYPEOF)
3611 (= tt js2-DELPROP))
3612 (insert " "))
3613 (js2-print-ast (js2-unary-node-operand n) 0)
3614 (when postfix
3615 (insert op))))
3616
3617 (cl-defstruct (js2-let-node
3618 (:include js2-scope)
3619 (:constructor nil)
3620 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3621 (pos (js2-current-token-beg))
3622 len vars body
3623 lp rp)))
3624 "AST node for a let expression or a let statement.
3625 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3626 vars ; a `js2-var-decl-node'
3627 body ; a `js2-node' representing the expression or body block
3628 lp
3629 rp)
3630
3631 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3632 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3633
3634 (defun js2-visit-let-node (n v)
3635 (js2-visit-ast (js2-let-node-vars n) v)
3636 (js2-visit-ast (js2-let-node-body n) v))
3637
3638 (defun js2-print-let-node (n i)
3639 (insert (js2-make-pad i) "let (")
3640 (let ((p (point)))
3641 (js2-print-ast (js2-let-node-vars n) 0)
3642 (delete-region p (+ p 4)))
3643 (insert ") ")
3644 (js2-print-ast (js2-let-node-body n) i))
3645
3646 (cl-defstruct (js2-keyword-node
3647 (:include js2-node)
3648 (:constructor nil)
3649 (:constructor make-js2-keyword-node (&key type
3650 (pos (js2-current-token-beg))
3651 (len (- js2-ts-cursor pos)))))
3652 "AST node representing a literal keyword such as `null'.
3653 Used for `null', `this', `true', `false' and `debugger'.
3654 The node type is set to js2-NULL, js2-THIS, etc.")
3655
3656 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3657 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3658
3659 (defun js2-print-keyword-node (n i)
3660 (insert (js2-make-pad i)
3661 (let ((tt (js2-node-type n)))
3662 (cond
3663 ((= tt js2-THIS) "this")
3664 ((= tt js2-SUPER) "super")
3665 ((= tt js2-NULL) "null")
3666 ((= tt js2-TRUE) "true")
3667 ((= tt js2-FALSE) "false")
3668 ((= tt js2-DEBUGGER) "debugger")
3669 (t (error "Invalid keyword literal type: %d" tt))))))
3670
3671 (defsubst js2-this-or-super-node-p (node)
3672 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3673 (let ((type (js2-node-type node)))
3674 (or (eq type js2-THIS) (eq type js2-SUPER))))
3675
3676 (cl-defstruct (js2-new-node
3677 (:include js2-node)
3678 (:constructor nil)
3679 (:constructor make-js2-new-node (&key (type js2-NEW)
3680 (pos (js2-current-token-beg))
3681 len target
3682 args initializer
3683 lp rp)))
3684 "AST node for new-expression such as new Foo()."
3685 target ; an identifier or reference
3686 args ; a Lisp list of argument nodes
3687 lp ; position of left-paren, nil if omitted
3688 rp ; position of right-paren, nil if omitted
3689 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3690
3691 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3692 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3693
3694 (defun js2-visit-new-node (n v)
3695 (js2-visit-ast (js2-new-node-target n) v)
3696 (dolist (arg (js2-new-node-args n))
3697 (js2-visit-ast arg v))
3698 (js2-visit-ast (js2-new-node-initializer n) v))
3699
3700 (defun js2-print-new-node (n i)
3701 (insert (js2-make-pad i) "new ")
3702 (js2-print-ast (js2-new-node-target n))
3703 (insert "(")
3704 (js2-print-list (js2-new-node-args n))
3705 (insert ")")
3706 (when (js2-new-node-initializer n)
3707 (insert " ")
3708 (js2-print-ast (js2-new-node-initializer n))))
3709
3710 (cl-defstruct (js2-name-node
3711 (:include js2-node)
3712 (:constructor nil)
3713 (:constructor make-js2-name-node (&key (type js2-NAME)
3714 (pos (js2-current-token-beg))
3715 (len (- js2-ts-cursor
3716 (js2-current-token-beg)))
3717 (name (js2-current-token-string)))))
3718 "AST node for a JavaScript identifier"
3719 name ; a string
3720 scope) ; a `js2-scope' (optional, used for codegen)
3721
3722 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3723 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3724
3725 (defun js2-print-name-node (n i)
3726 (insert (js2-make-pad i)
3727 (js2-name-node-name n)))
3728
3729 (defsubst js2-name-node-length (node)
3730 "Return identifier length of NODE, a `js2-name-node'.
3731 Returns 0 if NODE is nil or its identifier field is nil."
3732 (if node
3733 (length (js2-name-node-name node))
3734 0))
3735
3736 (cl-defstruct (js2-number-node
3737 (:include js2-node)
3738 (:constructor nil)
3739 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3740 (pos (js2-current-token-beg))
3741 (len (- js2-ts-cursor
3742 (js2-current-token-beg)))
3743 (value (js2-current-token-string))
3744 (num-value (js2-token-number
3745 (js2-current-token))))))
3746 "AST node for a number literal."
3747 value ; the original string, e.g. "6.02e23"
3748 num-value) ; the parsed number value
3749
3750 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3751 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3752
3753 (defun js2-print-number-node (n i)
3754 (insert (js2-make-pad i)
3755 (number-to-string (js2-number-node-num-value n))))
3756
3757 (cl-defstruct (js2-regexp-node
3758 (:include js2-node)
3759 (:constructor nil)
3760 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3761 (pos (js2-current-token-beg))
3762 (len (- js2-ts-cursor
3763 (js2-current-token-beg)))
3764 value flags)))
3765 "AST node for a regular expression literal."
3766 value ; the regexp string, without // delimiters
3767 flags) ; a string of flags, e.g. `mi'.
3768
3769 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3770 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3771
3772 (defun js2-print-regexp (n i)
3773 (insert (js2-make-pad i)
3774 "/"
3775 (js2-regexp-node-value n)
3776 "/")
3777 (if (js2-regexp-node-flags n)
3778 (insert (js2-regexp-node-flags n))))
3779
3780 (cl-defstruct (js2-string-node
3781 (:include js2-node)
3782 (:constructor nil)
3783 (:constructor make-js2-string-node (&key (type js2-STRING)
3784 (pos (js2-current-token-beg))
3785 (len (- js2-ts-cursor
3786 (js2-current-token-beg)))
3787 (value (js2-current-token-string)))))
3788 "String literal.
3789 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3790 You can tell the quote type by looking at the first character."
3791 value) ; the characters of the string, including the quotes
3792
3793 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3794 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3795
3796 (defun js2-print-string-node (n i)
3797 (insert (js2-make-pad i)
3798 (js2-node-string n)))
3799
3800 (cl-defstruct (js2-template-node
3801 (:include js2-node)
3802 (:constructor nil)
3803 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3804 beg len kids)))
3805 "Template literal."
3806 kids) ; `js2-string-node' is used for string segments, other nodes
3807 ; for substitutions inside.
3808
3809 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3810 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3811
3812 (defun js2-visit-template (n callback)
3813 (dolist (kid (js2-template-node-kids n))
3814 (js2-visit-ast kid callback)))
3815
3816 (defun js2-print-template (n i)
3817 (insert (js2-make-pad i))
3818 (dolist (kid (js2-template-node-kids n))
3819 (if (js2-string-node-p kid)
3820 (insert (js2-node-string kid))
3821 (js2-print-ast kid))))
3822
3823 (cl-defstruct (js2-tagged-template-node
3824 (:include js2-node)
3825 (:constructor nil)
3826 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3827 beg len tag template)))
3828 "Tagged template literal."
3829 tag ; `js2-node' with the tag expression.
3830 template) ; `js2-template-node' with the template.
3831
3832 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3833 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3834
3835 (defun js2-visit-tagged-template (n callback)
3836 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3837 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3838
3839 (defun js2-print-tagged-template (n i)
3840 (insert (js2-make-pad i))
3841 (js2-print-ast (js2-tagged-template-node-tag n))
3842 (js2-print-ast (js2-tagged-template-node-template n)))
3843
3844 (cl-defstruct (js2-array-node
3845 (:include js2-node)
3846 (:constructor nil)
3847 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3848 (pos js2-ts-cursor)
3849 len elems)))
3850 "AST node for an array literal."
3851 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3852
3853 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3854 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3855
3856 (defun js2-visit-array-node (n v)
3857 (dolist (e (js2-array-node-elems n))
3858 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3859
3860 (defun js2-print-array-node (n i)
3861 (insert (js2-make-pad i) "[")
3862 (let ((elems (js2-array-node-elems n)))
3863 (js2-print-list elems)
3864 (when (and elems (null (car (last elems))))
3865 (insert ",")))
3866 (insert "]"))
3867
3868 (cl-defstruct (js2-class-node
3869 (:include js2-node)
3870 (:constructor nil)
3871 (:constructor make-js2-class-node (&key (type js2-CLASS)
3872 (pos js2-ts-cursor)
3873 (form 'CLASS_STATEMENT)
3874 (name "")
3875 extends len elems)))
3876 "AST node for an class expression.
3877 `elems' is a list of `js2-object-prop-node', and `extends' is an
3878 optional `js2-expr-node'"
3879 form ; CLASS_{STATEMENT|EXPRESSION}
3880 name ; class name (a `js2-node-name', or nil if anonymous)
3881 extends ; class heritage (a `js2-expr-node', or nil if none)
3882 elems)
3883
3884 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3885 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3886
3887 (defun js2-visit-class-node (n v)
3888 (js2-visit-ast (js2-class-node-name n) v)
3889 (js2-visit-ast (js2-class-node-extends n) v)
3890 (dolist (e (js2-class-node-elems n))
3891 (js2-visit-ast e v)))
3892
3893 (defun js2-print-class-node (n i)
3894 (let* ((pad (js2-make-pad i))
3895 (name (js2-class-node-name n))
3896 (extends (js2-class-node-extends n))
3897 (elems (js2-class-node-elems n)))
3898 (insert pad "class")
3899 (when name
3900 (insert " ")
3901 (js2-print-ast name 0))
3902 (when extends
3903 (insert " extends ")
3904 (js2-print-ast extends))
3905 (insert " {")
3906 (dolist (elem elems)
3907 (insert "\n")
3908 (if (js2-node-get-prop elem 'STATIC)
3909 (progn (insert (js2-make-pad (1+ i)) "static ")
3910 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3911 (js2-print-ast elem (1+ i))))
3912 (insert "\n" pad "}")))
3913
3914 (cl-defstruct (js2-object-node
3915 (:include js2-node)
3916 (:constructor nil)
3917 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3918 (pos js2-ts-cursor)
3919 len
3920 elems)))
3921 "AST node for an object literal expression.
3922 `elems' is a list of `js2-object-prop-node'."
3923 elems)
3924
3925 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3926 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3927
3928 (defun js2-visit-object-node (n v)
3929 (dolist (e (js2-object-node-elems n))
3930 (js2-visit-ast e v)))
3931
3932 (defun js2-print-object-node (n i)
3933 (insert (js2-make-pad i) "{")
3934 (js2-print-list (js2-object-node-elems n))
3935 (insert "}"))
3936
3937 (cl-defstruct (js2-object-prop-node
3938 (:include js2-infix-node)
3939 (:constructor nil)
3940 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3941 (pos js2-ts-cursor)
3942 len left
3943 right op-pos)))
3944 "AST node for an object literal prop:value entry.
3945 The `left' field is the property: a name node, string node or number node.
3946 The `right' field is a `js2-node' representing the initializer value.
3947 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3948 and both fields have the same value.")
3949
3950 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3951 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3952
3953 (defun js2-print-object-prop-node (n i)
3954 (let* ((left (js2-object-prop-node-left n))
3955 (right (js2-object-prop-node-right n))
3956 (computed (not (or (js2-string-node-p left)
3957 (js2-number-node-p left)
3958 (js2-name-node-p left)))))
3959 (insert (js2-make-pad i))
3960 (if computed
3961 (insert "["))
3962 (js2-print-ast left 0)
3963 (if computed
3964 (insert "]"))
3965 (if (not (js2-node-get-prop n 'SHORTHAND))
3966 (progn
3967 (insert ": ")
3968 (js2-print-ast right 0)))))
3969
3970 (cl-defstruct (js2-getter-setter-node
3971 (:include js2-infix-node)
3972 (:constructor nil)
3973 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3974 (pos js2-ts-cursor)
3975 len left right)))
3976 "AST node for a getter/setter property in an object literal.
3977 The `left' field is the `js2-name-node' naming the getter/setter prop.
3978 The `right' field is always an anonymous `js2-function-node' with a node
3979 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3980
3981 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3982 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3983
3984 (defun js2-print-getter-setter (n i)
3985 (let* ((pad (js2-make-pad i))
3986 (left (js2-getter-setter-node-left n))
3987 (right (js2-getter-setter-node-right n))
3988 (computed (not (or (js2-string-node-p left)
3989 (js2-number-node-p left)
3990 (js2-name-node-p left)))))
3991 (insert pad)
3992 (if (/= (js2-node-type n) js2-FUNCTION)
3993 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3994 (when (and (js2-function-node-p right)
3995 (eq 'STAR (js2-function-node-generator-type right)))
3996 (insert "*"))
3997 (when computed
3998 (insert "["))
3999 (js2-print-ast left 0)
4000 (when computed
4001 (insert "]"))
4002 (js2-print-ast right 0)))
4003
4004 (cl-defstruct (js2-prop-get-node
4005 (:include js2-infix-node)
4006 (:constructor nil)
4007 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
4008 (pos js2-ts-cursor)
4009 len left right)))
4010 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
4011
4012 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4013 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4014
4015 (defun js2-visit-prop-get-node (n v)
4016 (js2-visit-ast (js2-prop-get-node-left n) v)
4017 (js2-visit-ast (js2-prop-get-node-right n) v))
4018
4019 (defun js2-print-prop-get-node (n i)
4020 (insert (js2-make-pad i))
4021 (js2-print-ast (js2-prop-get-node-left n) 0)
4022 (insert ".")
4023 (js2-print-ast (js2-prop-get-node-right n) 0))
4024
4025 (cl-defstruct (js2-elem-get-node
4026 (:include js2-node)
4027 (:constructor nil)
4028 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4029 (pos js2-ts-cursor)
4030 len target element
4031 lb rb)))
4032 "AST node for an array index expression such as foo[bar]."
4033 target ; a `js2-node' - the expression preceding the "."
4034 element ; a `js2-node' - the expression in brackets
4035 lb ; position of left-bracket, nil if omitted
4036 rb) ; position of right-bracket, nil if omitted
4037
4038 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4039 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4040
4041 (defun js2-visit-elem-get-node (n v)
4042 (js2-visit-ast (js2-elem-get-node-target n) v)
4043 (js2-visit-ast (js2-elem-get-node-element n) v))
4044
4045 (defun js2-print-elem-get-node (n i)
4046 (insert (js2-make-pad i))
4047 (js2-print-ast (js2-elem-get-node-target n) 0)
4048 (insert "[")
4049 (js2-print-ast (js2-elem-get-node-element n) 0)
4050 (insert "]"))
4051
4052 (cl-defstruct (js2-call-node
4053 (:include js2-node)
4054 (:constructor nil)
4055 (:constructor make-js2-call-node (&key (type js2-CALL)
4056 (pos js2-ts-cursor)
4057 len target args
4058 lp rp)))
4059 "AST node for a JavaScript function call."
4060 target ; a `js2-node' evaluating to the function to call
4061 args ; a Lisp list of `js2-node' arguments
4062 lp ; position of open-paren, or nil if missing
4063 rp) ; position of close-paren, or nil if missing
4064
4065 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4066 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4067
4068 (defun js2-visit-call-node (n v)
4069 (js2-visit-ast (js2-call-node-target n) v)
4070 (dolist (arg (js2-call-node-args n))
4071 (js2-visit-ast arg v)))
4072
4073 (defun js2-print-call-node (n i)
4074 (insert (js2-make-pad i))
4075 (js2-print-ast (js2-call-node-target n) 0)
4076 (insert "(")
4077 (js2-print-list (js2-call-node-args n))
4078 (insert ")"))
4079
4080 (cl-defstruct (js2-yield-node
4081 (:include js2-node)
4082 (:constructor nil)
4083 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4084 (pos js2-ts-cursor)
4085 len value star-p)))
4086 "AST node for yield statement or expression."
4087 star-p ; whether it's yield*
4088 value) ; optional: value to be yielded
4089
4090 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4091 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4092
4093 (defun js2-visit-yield-node (n v)
4094 (js2-visit-ast (js2-yield-node-value n) v))
4095
4096 (defun js2-print-yield-node (n i)
4097 (insert (js2-make-pad i))
4098 (insert "yield")
4099 (when (js2-yield-node-star-p n)
4100 (insert "*"))
4101 (when (js2-yield-node-value n)
4102 (insert " ")
4103 (js2-print-ast (js2-yield-node-value n) 0)))
4104
4105 (cl-defstruct (js2-paren-node
4106 (:include js2-node)
4107 (:constructor nil)
4108 (:constructor make-js2-paren-node (&key (type js2-LP)
4109 (pos js2-ts-cursor)
4110 len expr)))
4111 "AST node for a parenthesized expression.
4112 In particular, used when the parens are syntactically optional,
4113 as opposed to required parens such as those enclosing an if-conditional."
4114 expr) ; `js2-node'
4115
4116 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4117 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4118
4119 (defun js2-visit-paren-node (n v)
4120 (js2-visit-ast (js2-paren-node-expr n) v))
4121
4122 (defun js2-print-paren-node (n i)
4123 (insert (js2-make-pad i))
4124 (insert "(")
4125 (js2-print-ast (js2-paren-node-expr n) 0)
4126 (insert ")"))
4127
4128 (cl-defstruct (js2-comp-node
4129 (:include js2-scope)
4130 (:constructor nil)
4131 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4132 (pos js2-ts-cursor)
4133 len result
4134 loops filters
4135 form)))
4136 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4137 result ; result expression (just after left-bracket)
4138 loops ; a Lisp list of `js2-comp-loop-node'
4139 filters ; a Lisp list of guard/filter expressions
4140 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4141 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4142 )
4143
4144 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4145 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4146
4147 (defun js2-visit-comp-node (n v)
4148 (js2-visit-ast (js2-comp-node-result n) v)
4149 (dolist (l (js2-comp-node-loops n))
4150 (js2-visit-ast l v))
4151 (dolist (f (js2-comp-node-filters n))
4152 (js2-visit-ast f v)))
4153
4154 (defun js2-print-comp-node (n i)
4155 (let ((pad (js2-make-pad i))
4156 (result (js2-comp-node-result n))
4157 (loops (js2-comp-node-loops n))
4158 (filters (js2-comp-node-filters n))
4159 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4160 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4161 (insert pad (if gen-p "(" "["))
4162 (when legacy-p
4163 (js2-print-ast result 0))
4164 (dolist (l loops)
4165 (when legacy-p
4166 (insert " "))
4167 (js2-print-ast l 0)
4168 (unless legacy-p
4169 (insert " ")))
4170 (dolist (f filters)
4171 (when legacy-p
4172 (insert " "))
4173 (insert "if (")
4174 (js2-print-ast f 0)
4175 (insert ")")
4176 (unless legacy-p
4177 (insert " ")))
4178 (unless legacy-p
4179 (js2-print-ast result 0))
4180 (insert (if gen-p ")" "]"))))
4181
4182 (cl-defstruct (js2-comp-loop-node
4183 (:include js2-for-in-node)
4184 (:constructor nil)
4185 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4186 (pos js2-ts-cursor)
4187 len iterator
4188 object in-pos
4189 foreach-p
4190 each-pos
4191 forof-p
4192 lp rp)))
4193 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4194
4195 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4196 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4197
4198 (defun js2-visit-comp-loop (n v)
4199 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4200 (js2-visit-ast (js2-comp-loop-node-object n) v))
4201
4202 (defun js2-print-comp-loop (n _i)
4203 (insert "for ")
4204 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4205 (insert "(")
4206 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4207 (insert (if (js2-comp-loop-node-forof-p n)
4208 " of " " in "))
4209 (js2-print-ast (js2-comp-loop-node-object n) 0)
4210 (insert ")"))
4211
4212 (cl-defstruct (js2-empty-expr-node
4213 (:include js2-node)
4214 (:constructor nil)
4215 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4216 (pos (js2-current-token-beg))
4217 len)))
4218 "AST node for an empty expression.")
4219
4220 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4221 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4222
4223 (cl-defstruct (js2-xml-node
4224 (:include js2-block-node)
4225 (:constructor nil)
4226 (:constructor make-js2-xml-node (&key (type js2-XML)
4227 (pos (js2-current-token-beg))
4228 len kids)))
4229 "AST node for initial parse of E4X literals.
4230 The kids field is a list of XML fragments, each a `js2-string-node' or
4231 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4232
4233 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4234 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4235
4236 (defun js2-print-xml-node (n i)
4237 (dolist (kid (js2-xml-node-kids n))
4238 (js2-print-ast kid i)))
4239
4240 (cl-defstruct (js2-xml-js-expr-node
4241 (:include js2-xml-node)
4242 (:constructor nil)
4243 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4244 (pos js2-ts-cursor)
4245 len expr)))
4246 "AST node for an embedded JavaScript {expression} in an E4X literal.
4247 The start and end fields correspond to the curly-braces."
4248 expr) ; a `js2-expr-node' of some sort
4249
4250 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4251 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4252
4253 (defun js2-visit-xml-js-expr (n v)
4254 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4255
4256 (defun js2-print-xml-js-expr (n i)
4257 (insert (js2-make-pad i))
4258 (insert "{")
4259 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4260 (insert "}"))
4261
4262 (cl-defstruct (js2-xml-dot-query-node
4263 (:include js2-infix-node)
4264 (:constructor nil)
4265 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4266 (pos js2-ts-cursor)
4267 op-pos len left
4268 right rp)))
4269 "AST node for an E4X foo.(bar) filter expression.
4270 Note that the left-paren is automatically the character immediately
4271 following the dot (.) in the operator. No whitespace is permitted
4272 between the dot and the lp by the scanner."
4273 rp)
4274
4275 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4276 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4277
4278 (defun js2-print-xml-dot-query (n i)
4279 (insert (js2-make-pad i))
4280 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4281 (insert ".(")
4282 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4283 (insert ")"))
4284
4285 (cl-defstruct (js2-xml-ref-node
4286 (:include js2-node)
4287 (:constructor nil)) ; abstract
4288 "Base type for E4X XML attribute-access or property-get expressions.
4289 Such expressions can take a variety of forms. The general syntax has
4290 three parts:
4291
4292 - (optional) an @ (specifying an attribute access)
4293 - (optional) a namespace (a `js2-name-node') and double-colon
4294 - (required) either a `js2-name-node' or a bracketed [expression]
4295
4296 The property-name expressions (examples: ns::name, @name) are
4297 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4298 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4299
4300 This node type (or more specifically, its subclasses) will sometimes
4301 be the right-hand child of a `js2-prop-get-node' or a
4302 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4303 The `js2-xml-ref-node' may also be a standalone primary expression with
4304 no explicit target, which is valid in certain expression contexts such as
4305
4306 company..employee.(@id < 100)
4307
4308 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4309 expression whose parent is a `js2-xml-dot-query-node'."
4310 namespace
4311 at-pos
4312 colon-pos)
4313
4314 (defsubst js2-xml-ref-node-attr-access-p (node)
4315 "Return non-nil if this expression began with an @-token."
4316 (and (numberp (js2-xml-ref-node-at-pos node))
4317 (cl-plusp (js2-xml-ref-node-at-pos node))))
4318
4319 (cl-defstruct (js2-xml-prop-ref-node
4320 (:include js2-xml-ref-node)
4321 (:constructor nil)
4322 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4323 (pos (js2-current-token-beg))
4324 len propname
4325 namespace at-pos
4326 colon-pos)))
4327 "AST node for an E4X XML [expr] property-ref expression.
4328 The JavaScript syntax is an optional @, an optional ns::, and a name.
4329
4330 [ '@' ] [ name '::' ] name
4331
4332 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4333 @ns::*, @*::attr, @*::*, and @*.
4334
4335 The node starts at the @ token, if present. Otherwise it starts at the
4336 namespace name. The node bounds extend through the closing right-bracket,
4337 or if it is missing due to a syntax error, through the end of the index
4338 expression."
4339 propname)
4340
4341 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4342 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4343
4344 (defun js2-visit-xml-prop-ref-node (n v)
4345 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4346 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4347
4348 (defun js2-print-xml-prop-ref-node (n i)
4349 (insert (js2-make-pad i))
4350 (if (js2-xml-ref-node-attr-access-p n)
4351 (insert "@"))
4352 (when (js2-xml-prop-ref-node-namespace n)
4353 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4354 (insert "::"))
4355 (if (js2-xml-prop-ref-node-propname n)
4356 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4357
4358 (cl-defstruct (js2-xml-elem-ref-node
4359 (:include js2-xml-ref-node)
4360 (:constructor nil)
4361 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4362 (pos (js2-current-token-beg))
4363 len expr lb rb
4364 namespace at-pos
4365 colon-pos)))
4366 "AST node for an E4X XML [expr] member-ref expression.
4367 Syntax:
4368
4369 [ '@' ] [ name '::' ] '[' expr ']'
4370
4371 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4372
4373 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4374 is not a legal E4X XML element-ref expression, since it's already used
4375 for standard JavaScript element-get array indexing. Hence, a
4376 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4377 non-nil namespace node, or both.
4378
4379 The node starts at the @ token, if present. Otherwise it starts
4380 at the namespace name. The node bounds extend through the closing
4381 right-bracket, or if it is missing due to a syntax error, through the
4382 end of the index expression."
4383 expr ; the bracketed index expression
4384 lb
4385 rb)
4386
4387 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4388 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4389
4390 (defun js2-visit-xml-elem-ref-node (n v)
4391 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4392 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4393
4394 (defun js2-print-xml-elem-ref-node (n i)
4395 (insert (js2-make-pad i))
4396 (if (js2-xml-ref-node-attr-access-p n)
4397 (insert "@"))
4398 (when (js2-xml-elem-ref-node-namespace n)
4399 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4400 (insert "::"))
4401 (insert "[")
4402 (if (js2-xml-elem-ref-node-expr n)
4403 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4404 (insert "]"))
4405
4406 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4407
4408 (cl-defstruct (js2-xml-start-tag-node
4409 (:include js2-xml-node)
4410 (:constructor nil)
4411 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4412 (pos js2-ts-cursor)
4413 len name attrs kids
4414 empty-p)))
4415 "AST node for an XML start-tag. Not currently used.
4416 The `kids' field is a Lisp list of child content nodes."
4417 name ; a `js2-xml-name-node'
4418 attrs ; a Lisp list of `js2-xml-attr-node'
4419 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4420
4421 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4422 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4423
4424 (defun js2-visit-xml-start-tag (n v)
4425 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4426 (dolist (attr (js2-xml-start-tag-node-attrs n))
4427 (js2-visit-ast attr v))
4428 (js2-visit-block n v))
4429
4430 (defun js2-print-xml-start-tag (n i)
4431 (insert (js2-make-pad i) "<")
4432 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4433 (when (js2-xml-start-tag-node-attrs n)
4434 (insert " ")
4435 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4436 (insert ">"))
4437
4438 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4439 ;; and add the end-tag to the kids list of the parent as well.
4440 (cl-defstruct (js2-xml-end-tag-node
4441 (:include js2-xml-node)
4442 (:constructor nil)
4443 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4444 (pos js2-ts-cursor)
4445 len name)))
4446 "AST node for an XML end-tag. Not currently used."
4447 name) ; a `js2-xml-name-node'
4448
4449 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4450 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4451
4452 (defun js2-visit-xml-end-tag (n v)
4453 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4454
4455 (defun js2-print-xml-end-tag (n i)
4456 (insert (js2-make-pad i))
4457 (insert "</")
4458 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4459 (insert ">"))
4460
4461 (cl-defstruct (js2-xml-name-node
4462 (:include js2-xml-node)
4463 (:constructor nil)
4464 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4465 (pos js2-ts-cursor)
4466 len namespace kids)))
4467 "AST node for an E4X XML name. Not currently used.
4468 Any XML name can be qualified with a namespace, hence the namespace field.
4469 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4470 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4471 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4472 namespace) ; a `js2-string-node'
4473
4474 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4475 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4476
4477 (defun js2-visit-xml-name-node (n v)
4478 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4479
4480 (defun js2-print-xml-name-node (n i)
4481 (insert (js2-make-pad i))
4482 (when (js2-xml-name-node-namespace n)
4483 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4484 (insert "::"))
4485 (dolist (kid (js2-xml-name-node-kids n))
4486 (js2-print-ast kid 0)))
4487
4488 (cl-defstruct (js2-xml-pi-node
4489 (:include js2-xml-node)
4490 (:constructor nil)
4491 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4492 (pos js2-ts-cursor)
4493 len name attrs)))
4494 "AST node for an E4X XML processing instruction. Not currently used."
4495 name ; a `js2-xml-name-node'
4496 attrs) ; a list of `js2-xml-attr-node'
4497
4498 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4499 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4500
4501 (defun js2-visit-xml-pi-node (n v)
4502 (js2-visit-ast (js2-xml-pi-node-name n) v)
4503 (dolist (attr (js2-xml-pi-node-attrs n))
4504 (js2-visit-ast attr v)))
4505
4506 (defun js2-print-xml-pi-node (n i)
4507 (insert (js2-make-pad i) "<?")
4508 (js2-print-ast (js2-xml-pi-node-name n))
4509 (when (js2-xml-pi-node-attrs n)
4510 (insert " ")
4511 (js2-print-list (js2-xml-pi-node-attrs n)))
4512 (insert "?>"))
4513
4514 (cl-defstruct (js2-xml-cdata-node
4515 (:include js2-xml-node)
4516 (:constructor nil)
4517 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4518 (pos js2-ts-cursor)
4519 len content)))
4520 "AST node for a CDATA escape section. Not currently used."
4521 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4522
4523 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4524 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4525
4526 (defun js2-visit-xml-cdata-node (n v)
4527 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4528
4529 (defun js2-print-xml-cdata-node (n i)
4530 (insert (js2-make-pad i))
4531 (js2-print-ast (js2-xml-cdata-node-content n)))
4532
4533 (cl-defstruct (js2-xml-attr-node
4534 (:include js2-xml-node)
4535 (:constructor nil)
4536 (:constructor make-js2-attr-node (&key (type js2-XML)
4537 (pos js2-ts-cursor)
4538 len name value
4539 eq-pos quote-type)))
4540 "AST node representing a foo='bar' XML attribute value. Not yet used."
4541 name ; a `js2-xml-name-node'
4542 value ; a `js2-xml-name-node'
4543 eq-pos ; buffer position of "=" sign
4544 quote-type) ; 'single or 'double
4545
4546 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4547 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4548
4549 (defun js2-visit-xml-attr-node (n v)
4550 (js2-visit-ast (js2-xml-attr-node-name n) v)
4551 (js2-visit-ast (js2-xml-attr-node-value n) v))
4552
4553 (defun js2-print-xml-attr-node (n i)
4554 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4555 "'"
4556 "\"")))
4557 (insert (js2-make-pad i))
4558 (js2-print-ast (js2-xml-attr-node-name n) 0)
4559 (insert "=" quote)
4560 (js2-print-ast (js2-xml-attr-node-value n) 0)
4561 (insert quote)))
4562
4563 (cl-defstruct (js2-xml-text-node
4564 (:include js2-xml-node)
4565 (:constructor nil)
4566 (:constructor make-js2-text-node (&key (type js2-XML)
4567 (pos js2-ts-cursor)
4568 len content)))
4569 "AST node for an E4X XML text node. Not currently used."
4570 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4571
4572 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4573 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4574
4575 (defun js2-visit-xml-text-node (n v)
4576 (js2-visit-ast (js2-xml-text-node-content n) v))
4577
4578 (defun js2-print-xml-text-node (n i)
4579 (insert (js2-make-pad i))
4580 (dolist (kid (js2-xml-text-node-content n))
4581 (js2-print-ast kid)))
4582
4583 (cl-defstruct (js2-xml-comment-node
4584 (:include js2-xml-node)
4585 (:constructor nil)
4586 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4587 (pos js2-ts-cursor)
4588 len)))
4589 "AST node for E4X XML comment. Not currently used.")
4590
4591 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4592 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4593
4594 (defun js2-print-xml-comment (n i)
4595 (insert (js2-make-pad i)
4596 (js2-node-string n)))
4597
4598 ;;; Node utilities
4599
4600 (defsubst js2-node-line (n)
4601 "Fetch the source line number at the start of node N.
4602 This is O(n) in the length of the source buffer; use prudently."
4603 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4604
4605 (defsubst js2-block-node-kid (n i)
4606 "Return child I of node N, or nil if there aren't that many."
4607 (nth i (js2-block-node-kids n)))
4608
4609 (defsubst js2-block-node-first (n)
4610 "Return first child of block node N, or nil if there is none."
4611 (cl-first (js2-block-node-kids n)))
4612
4613 (defun js2-node-root (n)
4614 "Return the root of the AST containing N.
4615 If N has no parent pointer, returns N."
4616 (let ((parent (js2-node-parent n)))
4617 (if parent
4618 (js2-node-root parent)
4619 n)))
4620
4621 (defsubst js2-node-short-name (n)
4622 "Return the short name of node N as a string, e.g. `js2-if-node'."
4623 (substring (symbol-name (aref n 0))
4624 (length "cl-struct-")))
4625
4626 (defun js2-node-child-list (node)
4627 "Return the child list for NODE, a Lisp list of nodes.
4628 Works for block nodes, array nodes, obj literals, funarg lists,
4629 var decls and try nodes (for catch clauses). Note that you should call
4630 `js2-block-node-kids' on the function body for the body statements.
4631 Returns nil for zero-length child lists or unsupported nodes."
4632 (cond
4633 ((js2-function-node-p node)
4634 (js2-function-node-params node))
4635 ((js2-block-node-p node)
4636 (js2-block-node-kids node))
4637 ((js2-try-node-p node)
4638 (js2-try-node-catch-clauses node))
4639 ((js2-array-node-p node)
4640 (js2-array-node-elems node))
4641 ((js2-object-node-p node)
4642 (js2-object-node-elems node))
4643 ((js2-call-node-p node)
4644 (js2-call-node-args node))
4645 ((js2-new-node-p node)
4646 (js2-new-node-args node))
4647 ((js2-var-decl-node-p node)
4648 (js2-var-decl-node-kids node))
4649 (t
4650 nil)))
4651
4652 (defun js2-node-set-child-list (node kids)
4653 "Set the child list for NODE to KIDS."
4654 (cond
4655 ((js2-function-node-p node)
4656 (setf (js2-function-node-params node) kids))
4657 ((js2-block-node-p node)
4658 (setf (js2-block-node-kids node) kids))
4659 ((js2-try-node-p node)
4660 (setf (js2-try-node-catch-clauses node) kids))
4661 ((js2-array-node-p node)
4662 (setf (js2-array-node-elems node) kids))
4663 ((js2-object-node-p node)
4664 (setf (js2-object-node-elems node) kids))
4665 ((js2-call-node-p node)
4666 (setf (js2-call-node-args node) kids))
4667 ((js2-new-node-p node)
4668 (setf (js2-new-node-args node) kids))
4669 ((js2-var-decl-node-p node)
4670 (setf (js2-var-decl-node-kids node) kids))
4671 (t
4672 (error "Unsupported node type: %s" (js2-node-short-name node))))
4673 kids)
4674
4675 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4676 (defconst js2-paren-expr-nodes
4677 '(cl-struct-js2-comp-loop-node
4678 cl-struct-js2-comp-node
4679 cl-struct-js2-call-node
4680 cl-struct-js2-catch-node
4681 cl-struct-js2-do-node
4682 cl-struct-js2-elem-get-node
4683 cl-struct-js2-for-in-node
4684 cl-struct-js2-for-node
4685 cl-struct-js2-function-node
4686 cl-struct-js2-if-node
4687 cl-struct-js2-let-node
4688 cl-struct-js2-new-node
4689 cl-struct-js2-paren-node
4690 cl-struct-js2-switch-node
4691 cl-struct-js2-while-node
4692 cl-struct-js2-with-node
4693 cl-struct-js2-xml-dot-query-node)
4694 "Node types that can have a parenthesized child expression.
4695 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4696
4697 (defsubst js2-paren-expr-node-p (node)
4698 "Return t for nodes that typically have a parenthesized child expression.
4699 Useful for computing the indentation anchors for arg-lists and conditions.
4700 Note that it may return a false positive, for instance when NODE is
4701 a `js2-new-node' and there are no arguments or parentheses."
4702 (memq (aref node 0) js2-paren-expr-nodes))
4703
4704 ;; Fake polymorphism... yech.
4705 (defun js2-node-lp (node)
4706 "Return relative left-paren position for NODE, if applicable.
4707 For `js2-elem-get-node' structs, returns left-bracket position.
4708 Note that the position may be nil in the case of a parse error."
4709 (cond
4710 ((js2-elem-get-node-p node)
4711 (js2-elem-get-node-lb node))
4712 ((js2-loop-node-p node)
4713 (js2-loop-node-lp node))
4714 ((js2-function-node-p node)
4715 (js2-function-node-lp node))
4716 ((js2-if-node-p node)
4717 (js2-if-node-lp node))
4718 ((js2-new-node-p node)
4719 (js2-new-node-lp node))
4720 ((js2-call-node-p node)
4721 (js2-call-node-lp node))
4722 ((js2-paren-node-p node)
4723 0)
4724 ((js2-switch-node-p node)
4725 (js2-switch-node-lp node))
4726 ((js2-catch-node-p node)
4727 (js2-catch-node-lp node))
4728 ((js2-let-node-p node)
4729 (js2-let-node-lp node))
4730 ((js2-comp-node-p node)
4731 0)
4732 ((js2-with-node-p node)
4733 (js2-with-node-lp node))
4734 ((js2-xml-dot-query-node-p node)
4735 (1+ (js2-infix-node-op-pos node)))
4736 (t
4737 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4738
4739 ;; Fake polymorphism... blech.
4740 (defun js2-node-rp (node)
4741 "Return relative right-paren position for NODE, if applicable.
4742 For `js2-elem-get-node' structs, returns right-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-rb node))
4747 ((js2-loop-node-p node)
4748 (js2-loop-node-rp node))
4749 ((js2-function-node-p node)
4750 (js2-function-node-rp node))
4751 ((js2-if-node-p node)
4752 (js2-if-node-rp node))
4753 ((js2-new-node-p node)
4754 (js2-new-node-rp node))
4755 ((js2-call-node-p node)
4756 (js2-call-node-rp node))
4757 ((js2-paren-node-p node)
4758 (1- (js2-node-len node)))
4759 ((js2-switch-node-p node)
4760 (js2-switch-node-rp node))
4761 ((js2-catch-node-p node)
4762 (js2-catch-node-rp node))
4763 ((js2-let-node-p node)
4764 (js2-let-node-rp node))
4765 ((js2-comp-node-p node)
4766 (1- (js2-node-len node)))
4767 ((js2-with-node-p node)
4768 (js2-with-node-rp node))
4769 ((js2-xml-dot-query-node-p node)
4770 (1+ (js2-xml-dot-query-node-rp node)))
4771 (t
4772 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4773
4774 (defsubst js2-node-first-child (node)
4775 "Return the first element of `js2-node-child-list' for NODE."
4776 (car (js2-node-child-list node)))
4777
4778 (defsubst js2-node-last-child (node)
4779 "Return the last element of `js2-node-last-child' for NODE."
4780 (car (last (js2-node-child-list node))))
4781
4782 (defun js2-node-prev-sibling (node)
4783 "Return the previous statement in parent.
4784 Works for parents supported by `js2-node-child-list'.
4785 Returns nil if NODE is not in the parent, or PARENT is
4786 not a supported node, or if NODE is the first child."
4787 (let* ((p (js2-node-parent node))
4788 (kids (js2-node-child-list p))
4789 (sib (car kids)))
4790 (while (and kids
4791 (not (eq node (cadr kids))))
4792 (setq kids (cdr kids)
4793 sib (car kids)))
4794 sib))
4795
4796 (defun js2-node-next-sibling (node)
4797 "Return the next statement in parent block.
4798 Returns nil if NODE is not in the block, or PARENT is not
4799 a block node, or if NODE is the last statement."
4800 (let* ((p (js2-node-parent node))
4801 (kids (js2-node-child-list p)))
4802 (while (and kids
4803 (not (eq node (car kids))))
4804 (setq kids (cdr kids)))
4805 (cadr kids)))
4806
4807 (defun js2-node-find-child-before (pos parent &optional after)
4808 "Find the last child that starts before POS in parent.
4809 If AFTER is non-nil, returns first child starting after POS.
4810 POS is an absolute buffer position. PARENT is any node
4811 supported by `js2-node-child-list'.
4812 Returns nil if no applicable child is found."
4813 (let ((kids (if (js2-function-node-p parent)
4814 (js2-block-node-kids (js2-function-node-body parent))
4815 (js2-node-child-list parent)))
4816 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4817 (js2-function-node-body parent)
4818 parent)))
4819 kid result fn
4820 (continue t))
4821 (setq fn (if after '>= '<))
4822 (while (and kids continue)
4823 (setq kid (car kids))
4824 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4825 (setq result kid
4826 continue (not after))
4827 (setq continue after))
4828 (setq kids (cdr kids)))
4829 result))
4830
4831 (defun js2-node-find-child-after (pos parent)
4832 "Find first child that starts after POS in parent.
4833 POS is an absolute buffer position. PARENT is any node
4834 supported by `js2-node-child-list'.
4835 Returns nil if no applicable child is found."
4836 (js2-node-find-child-before pos parent 'after))
4837
4838 (defun js2-node-replace-child (pos parent new-node)
4839 "Replace node at index POS in PARENT with NEW-NODE.
4840 Only works for parents supported by `js2-node-child-list'."
4841 (let ((kids (js2-node-child-list parent))
4842 (i 0))
4843 (while (< i pos)
4844 (setq kids (cdr kids)
4845 i (1+ i)))
4846 (setcar kids new-node)
4847 (js2-node-add-children parent new-node)))
4848
4849 (defun js2-node-buffer (n)
4850 "Return the buffer associated with AST N.
4851 Returns nil if the buffer is not set as a property on the root
4852 node, or if parent links were not recorded during parsing."
4853 (let ((root (js2-node-root n)))
4854 (and root
4855 (js2-ast-root-p root)
4856 (js2-ast-root-buffer root))))
4857
4858 (defun js2-block-node-push (n kid)
4859 "Push js2-node KID onto the end of js2-block-node N's child list.
4860 KID is always added to the -end- of the kids list.
4861 Function also calls `js2-node-add-children' to add the parent link."
4862 (let ((kids (js2-node-child-list n)))
4863 (if kids
4864 (setcdr kids (nconc (cdr kids) (list kid)))
4865 (js2-node-set-child-list n (list kid)))
4866 (js2-node-add-children n kid)))
4867
4868 (defun js2-node-string (node)
4869 (with-current-buffer (or (js2-node-buffer node)
4870 (error "No buffer available for node %s" node))
4871 (let ((pos (js2-node-abs-pos node)))
4872 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4873
4874 ;; Container for storing the node we're looking for in a traversal.
4875 (js2-deflocal js2-discovered-node nil)
4876
4877 ;; Keep track of absolute node position during traversals.
4878 (js2-deflocal js2-visitor-offset nil)
4879
4880 (js2-deflocal js2-node-search-point nil)
4881
4882 (when js2-mode-dev-mode-p
4883 (defun js2-find-node-at-point ()
4884 (interactive)
4885 (let ((node (js2-node-at-point)))
4886 (message "%s" (or node "No node found at point"))))
4887 (defun js2-node-name-at-point ()
4888 (interactive)
4889 (let ((node (js2-node-at-point)))
4890 (message "%s" (if node
4891 (js2-node-short-name node)
4892 "No node found at point.")))))
4893
4894 (defun js2-node-at-point (&optional pos skip-comments)
4895 "Return AST node at POS, a buffer position, defaulting to current point.
4896 The `js2-mode-ast' variable must be set to the current parse tree.
4897 Signals an error if the AST (`js2-mode-ast') is nil.
4898 Always returns a node - if it can't find one, it returns the root.
4899 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4900 (let ((ast js2-mode-ast)
4901 result)
4902 (unless ast
4903 (error "No JavaScript AST available"))
4904 ;; Look through comments first, since they may be inside nodes that
4905 ;; would otherwise report a match.
4906 (setq pos (or pos (point))
4907 result (if (> pos (js2-node-abs-end ast))
4908 ast
4909 (if (not skip-comments)
4910 (js2-comment-at-point pos))))
4911 (unless result
4912 (setq js2-discovered-node nil
4913 js2-visitor-offset 0
4914 js2-node-search-point pos)
4915 (unwind-protect
4916 (catch 'js2-visit-done
4917 (js2-visit-ast ast #'js2-node-at-point-visitor))
4918 (setq js2-visitor-offset nil
4919 js2-node-search-point nil))
4920 (setq result js2-discovered-node))
4921 ;; may have found a comment beyond end of last child node,
4922 ;; since visiting the ast-root looks at the comment-list last.
4923 (if (and skip-comments
4924 (js2-comment-node-p result))
4925 (setq result nil))
4926 (or result js2-mode-ast)))
4927
4928 (defun js2-node-at-point-visitor (node end-p)
4929 (let ((rel-pos (js2-node-pos node))
4930 abs-pos
4931 abs-end
4932 (point js2-node-search-point))
4933 (cond
4934 (end-p
4935 ;; this evaluates to a non-nil return value, even if it's zero
4936 (cl-decf js2-visitor-offset rel-pos))
4937 ;; we already looked for comments before visiting, and don't want them now
4938 ((js2-comment-node-p node)
4939 nil)
4940 (t
4941 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4942 ;; we only want to use the node if the point is before
4943 ;; the last character position in the node, so we decrement
4944 ;; the absolute end by 1.
4945 abs-end (+ abs-pos (js2-node-len node) -1))
4946 (cond
4947 ;; If this node starts after search-point, stop the search.
4948 ((> abs-pos point)
4949 (throw 'js2-visit-done nil))
4950 ;; If this node ends before the search-point, don't check kids.
4951 ((> point abs-end)
4952 nil)
4953 (t
4954 ;; Otherwise point is within this node, possibly in a child.
4955 (setq js2-discovered-node node)
4956 t)))))) ; keep processing kids to look for more specific match
4957
4958 (defsubst js2-block-comment-p (node)
4959 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4960 (and (js2-comment-node-p node)
4961 (memq (js2-comment-node-format node) '(jsdoc block))))
4962
4963 ;; TODO: put the comments in a vector and binary-search them instead
4964 (defun js2-comment-at-point (&optional pos)
4965 "Look through scanned comment nodes for one containing POS.
4966 POS is a buffer position that defaults to current point.
4967 Function returns nil if POS was not in any comment node."
4968 (let ((ast js2-mode-ast)
4969 (x (or pos (point)))
4970 beg end)
4971 (unless ast
4972 (error "No JavaScript AST available"))
4973 (catch 'done
4974 ;; Comments are stored in lexical order.
4975 (dolist (comment (js2-ast-root-comments ast) nil)
4976 (setq beg (js2-node-abs-pos comment)
4977 end (+ beg (js2-node-len comment)))
4978 (if (and (>= x beg)
4979 (<= x end))
4980 (throw 'done comment))))))
4981
4982 (defun js2-mode-find-parent-fn (node)
4983 "Find function enclosing NODE.
4984 Returns nil if NODE is not inside a function."
4985 (setq node (js2-node-parent node))
4986 (while (and node (not (js2-function-node-p node)))
4987 (setq node (js2-node-parent node)))
4988 (and (js2-function-node-p node) node))
4989
4990 (defun js2-mode-find-enclosing-fn (node)
4991 "Find function or root enclosing NODE."
4992 (if (js2-ast-root-p node)
4993 node
4994 (setq node (js2-node-parent node))
4995 (while (not (or (js2-ast-root-p node)
4996 (js2-function-node-p node)))
4997 (setq node (js2-node-parent node)))
4998 node))
4999
5000 (defun js2-mode-find-enclosing-node (beg end)
5001 "Find node fully enclosing BEG and END."
5002 (let ((node (js2-node-at-point beg))
5003 pos
5004 (continue t))
5005 (while continue
5006 (if (or (js2-ast-root-p node)
5007 (and
5008 (<= (setq pos (js2-node-abs-pos node)) beg)
5009 (>= (+ pos (js2-node-len node)) end)))
5010 (setq continue nil)
5011 (setq node (js2-node-parent node))))
5012 node))
5013
5014 (defun js2-node-parent-script-or-fn (node)
5015 "Find script or function immediately enclosing NODE.
5016 If NODE is the ast-root, returns nil."
5017 (if (js2-ast-root-p node)
5018 nil
5019 (setq node (js2-node-parent node))
5020 (while (and node (not (or (js2-function-node-p node)
5021 (js2-script-node-p node))))
5022 (setq node (js2-node-parent node)))
5023 node))
5024
5025 (defun js2-node-is-descendant (node ancestor)
5026 "Return t if NODE is a descendant of ANCESTOR."
5027 (while (and node
5028 (not (eq node ancestor)))
5029 (setq node (js2-node-parent node)))
5030 node)
5031
5032 ;;; visitor infrastructure
5033
5034 (defun js2-visit-none (_node _callback)
5035 "Visitor for AST node that have no node children."
5036 nil)
5037
5038 (defun js2-print-none (_node _indent)
5039 "Visitor for AST node with no printed representation.")
5040
5041 (defun js2-print-body (node indent)
5042 "Print a statement, or a block without braces."
5043 (if (js2-block-node-p node)
5044 (dolist (kid (js2-block-node-kids node))
5045 (js2-print-ast kid indent))
5046 (js2-print-ast node indent)))
5047
5048 (defun js2-print-list (args &optional delimiter)
5049 (cl-loop with len = (length args)
5050 for arg in args
5051 for count from 1
5052 do
5053 (when arg (js2-print-ast arg 0))
5054 (if (< count len)
5055 (insert (or delimiter ", ")))))
5056
5057 (defun js2-print-tree (ast)
5058 "Prints an AST to the current buffer.
5059 Makes `js2-ast-parent-nodes' available to the printer functions."
5060 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5061 (js2-print-ast ast)))
5062
5063 (defun js2-print-ast (node &optional indent)
5064 "Helper function for printing AST nodes.
5065 Requires `js2-ast-parent-nodes' to be non-nil.
5066 You should use `js2-print-tree' instead of this function."
5067 (let ((printer (get (aref node 0) 'js2-printer))
5068 (i (or indent 0)))
5069 ;; TODO: wedge comments in here somewhere
5070 (if printer
5071 (funcall printer node i))))
5072
5073 (defconst js2-side-effecting-tokens
5074 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5075 (dolist (tt (list js2-ASSIGN
5076 js2-ASSIGN_ADD
5077 js2-ASSIGN_BITAND
5078 js2-ASSIGN_BITOR
5079 js2-ASSIGN_BITXOR
5080 js2-ASSIGN_DIV
5081 js2-ASSIGN_LSH
5082 js2-ASSIGN_MOD
5083 js2-ASSIGN_MUL
5084 js2-ASSIGN_RSH
5085 js2-ASSIGN_SUB
5086 js2-ASSIGN_URSH
5087 js2-BLOCK
5088 js2-BREAK
5089 js2-CALL
5090 js2-CATCH
5091 js2-CATCH_SCOPE
5092 js2-CLASS
5093 js2-CONST
5094 js2-CONTINUE
5095 js2-DEBUGGER
5096 js2-DEC
5097 js2-DELPROP
5098 js2-DEL_REF
5099 js2-DO
5100 js2-ELSE
5101 js2-EMPTY
5102 js2-ENTERWITH
5103 js2-EXPORT
5104 js2-EXPR_RESULT
5105 js2-FINALLY
5106 js2-FOR
5107 js2-FUNCTION
5108 js2-GOTO
5109 js2-IF
5110 js2-IFEQ
5111 js2-IFNE
5112 js2-IMPORT
5113 js2-INC
5114 js2-JSR
5115 js2-LABEL
5116 js2-LEAVEWITH
5117 js2-LET
5118 js2-LETEXPR
5119 js2-LOCAL_BLOCK
5120 js2-LOOP
5121 js2-NEW
5122 js2-REF_CALL
5123 js2-RETHROW
5124 js2-RETURN
5125 js2-RETURN_RESULT
5126 js2-SEMI
5127 js2-SETELEM
5128 js2-SETELEM_OP
5129 js2-SETNAME
5130 js2-SETPROP
5131 js2-SETPROP_OP
5132 js2-SETVAR
5133 js2-SET_REF
5134 js2-SET_REF_OP
5135 js2-SWITCH
5136 js2-TARGET
5137 js2-THROW
5138 js2-TRY
5139 js2-VAR
5140 js2-WHILE
5141 js2-WITH
5142 js2-WITHEXPR
5143 js2-YIELD))
5144 (aset tokens tt t))
5145 (if js2-instanceof-has-side-effects
5146 (aset tokens js2-INSTANCEOF t))
5147 tokens))
5148
5149 (defun js2-node-has-side-effects (node)
5150 "Return t if NODE has side effects."
5151 (when node ; makes it easier to handle malformed expressions
5152 (let ((tt (js2-node-type node)))
5153 (cond
5154 ;; This doubtless needs some work, since EXPR_VOID is used
5155 ;; in several ways in Rhino and I may not have caught them all.
5156 ;; I'll wait for people to notice incorrect warnings.
5157 ((and (= tt js2-EXPR_VOID)
5158 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5159 (let ((expr (js2-expr-stmt-node-expr node)))
5160 (or (js2-node-has-side-effects expr)
5161 (when (js2-string-node-p expr)
5162 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5163 ((= tt js2-COMMA)
5164 (js2-node-has-side-effects (js2-infix-node-right node)))
5165 ((or (= tt js2-AND)
5166 (= tt js2-OR))
5167 (or (js2-node-has-side-effects (js2-infix-node-right node))
5168 (js2-node-has-side-effects (js2-infix-node-left node))))
5169 ((= tt js2-HOOK)
5170 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5171 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5172 ((js2-paren-node-p node)
5173 (js2-node-has-side-effects (js2-paren-node-expr node)))
5174 ((= tt js2-ERROR) ; avoid cascaded error messages
5175 nil)
5176 (t
5177 (aref js2-side-effecting-tokens tt))))))
5178
5179 (defconst js2-stmt-node-types
5180 (list js2-BLOCK
5181 js2-BREAK
5182 js2-CONTINUE
5183 js2-DEFAULT ; e4x "default xml namespace" statement
5184 js2-DO
5185 js2-EXPORT
5186 js2-EXPR_RESULT
5187 js2-EXPR_VOID
5188 js2-FOR
5189 js2-IF
5190 js2-IMPORT
5191 js2-RETURN
5192 js2-SWITCH
5193 js2-THROW
5194 js2-TRY
5195 js2-WHILE
5196 js2-WITH)
5197 "Node types that only appear in statement contexts.
5198 The list does not include nodes that always appear as the child
5199 of another specific statement type, such as switch-cases,
5200 catch and finally blocks, and else-clauses. The list also excludes
5201 nodes like yield, let and var, which may appear in either expression
5202 or statement context, and in the latter context always have a
5203 `js2-expr-stmt-node' parent. Finally, the list does not include
5204 functions or scripts, which are treated separately from statements
5205 by the JavaScript parser and runtime.")
5206
5207 (defun js2-stmt-node-p (node)
5208 "Heuristic for figuring out if NODE is a statement.
5209 Some node types can appear in either an expression context or a
5210 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5211 For these node types in a statement context, the parent will be a
5212 `js2-expr-stmt-node'.
5213 Functions aren't included in the check."
5214 (memq (js2-node-type node) js2-stmt-node-types))
5215
5216 (defun js2-mode-find-first-stmt (node)
5217 "Search upward starting from NODE looking for a statement.
5218 For purposes of this function, a `js2-function-node' counts."
5219 (while (not (or (js2-stmt-node-p node)
5220 (js2-function-node-p node)))
5221 (setq node (js2-node-parent node)))
5222 node)
5223
5224 (defun js2-node-parent-stmt (node)
5225 "Return the node's first ancestor that is a statement.
5226 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5227 appearing in a statement context will have a parent that is a
5228 `js2-expr-stmt-node' that will be returned by this function."
5229 (let ((parent (js2-node-parent node)))
5230 (if (or (null parent)
5231 (js2-stmt-node-p parent)
5232 (and (js2-function-node-p parent)
5233 (not (eq (js2-function-node-form parent)
5234 'FUNCTION_EXPRESSION))))
5235 parent
5236 (js2-node-parent-stmt parent))))
5237
5238 ;; In the Mozilla Rhino sources, Roshan James writes:
5239 ;; Does consistent-return analysis on the function body when strict mode is
5240 ;; enabled.
5241 ;;
5242 ;; function (x) { return (x+1) }
5243 ;;
5244 ;; is ok, but
5245 ;;
5246 ;; function (x) { if (x < 0) return (x+1); }
5247 ;;
5248 ;; is not because the function can potentially return a value when the
5249 ;; condition is satisfied and if not, the function does not explicitly
5250 ;; return a value.
5251 ;;
5252 ;; This extends to checking mismatches such as "return" and "return <value>"
5253 ;; used in the same function. Warnings are not emitted if inconsistent
5254 ;; returns exist in code that can be statically shown to be unreachable.
5255 ;; Ex.
5256 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5257 ;;
5258 ;; emits no warning. However if the loop had a break statement, then a
5259 ;; warning would be emitted.
5260 ;;
5261 ;; The consistency analysis looks at control structures such as loops, ifs,
5262 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5263 ;; warns the user about an inconsistent set of termination possibilities.
5264 ;;
5265 ;; These flags enumerate the possible ways a statement/function can
5266 ;; terminate. These flags are used by endCheck() and by the Parser to
5267 ;; detect inconsistent return usage.
5268 ;;
5269 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5270 ;; able to execute (example: throw, continue)
5271 ;;
5272 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5273 ;; next one. Statement such as return dont. A compound statement may have
5274 ;; some branch that drops off control to the next statement.
5275 ;;
5276 ;; END_RETURNS indicates that the statement can return with no value.
5277 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5278 ;;
5279 ;; A compound statement such as
5280 ;; if (condition) {
5281 ;; return value;
5282 ;; }
5283 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5284
5285 (defconst js2-END_UNREACHED 0)
5286 (defconst js2-END_DROPS_OFF 1)
5287 (defconst js2-END_RETURNS 2)
5288 (defconst js2-END_RETURNS_VALUE 4)
5289 (defconst js2-END_YIELDS 8)
5290
5291 (defun js2-has-consistent-return-usage (node)
5292 "Check that every return usage in a function body is consistent.
5293 Returns t if the function satisfies strict mode requirement."
5294 (let ((n (js2-end-check node)))
5295 ;; either it doesn't return a value in any branch...
5296 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5297 ;; or it returns a value (or is unreached) at every branch
5298 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5299 js2-END_RETURNS
5300 js2-END_YIELDS)))))
5301
5302 (defun js2-end-check-if (node)
5303 "Ensure that return usage in then/else blocks is consistent.
5304 If there is no else block, then the return statement can fall through.
5305 Returns logical OR of END_* flags"
5306 (let ((th (js2-if-node-then-part node))
5307 (el (js2-if-node-else-part node)))
5308 (if (null th)
5309 js2-END_UNREACHED
5310 (logior (js2-end-check th) (if el
5311 (js2-end-check el)
5312 js2-END_DROPS_OFF)))))
5313
5314 (defun js2-end-check-switch (node)
5315 "Consistency of return statements is checked between the case statements.
5316 If there is no default, then the switch can fall through. If there is a
5317 default, we check to see if all code paths in the default return or if
5318 there is a code path that can fall through.
5319 Returns logical OR of END_* flags."
5320 (let ((rv js2-END_UNREACHED)
5321 default-case)
5322 ;; examine the cases
5323 (catch 'break
5324 (dolist (c (js2-switch-node-cases node))
5325 (if (js2-case-node-expr c)
5326 (js2-set-flag rv (js2-end-check-block c))
5327 (setq default-case c)
5328 (throw 'break nil))))
5329 ;; we don't care how the cases drop into each other
5330 (js2-clear-flag rv js2-END_DROPS_OFF)
5331 ;; examine the default
5332 (js2-set-flag rv (if default-case
5333 (js2-end-check default-case)
5334 js2-END_DROPS_OFF))
5335 rv))
5336
5337 (defun js2-end-check-try (node)
5338 "If the block has a finally, return consistency is checked in the
5339 finally block. If all code paths in the finally return, then the
5340 returns in the try-catch blocks don't matter. If there is a code path
5341 that does not return or if there is no finally block, the returns
5342 of the try and catch blocks are checked for mismatch.
5343 Returns logical OR of END_* flags."
5344 (let ((finally (js2-try-node-finally-block node))
5345 rv)
5346 ;; check the finally if it exists
5347 (setq rv (if finally
5348 (js2-end-check (js2-finally-node-body finally))
5349 js2-END_DROPS_OFF))
5350 ;; If the finally block always returns, then none of the returns
5351 ;; in the try or catch blocks matter.
5352 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5353 (js2-clear-flag rv js2-END_DROPS_OFF)
5354 ;; examine the try block
5355 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5356 ;; check each catch block
5357 (dolist (cb (js2-try-node-catch-clauses node))
5358 (js2-set-flag rv (js2-end-check cb))))
5359 rv))
5360
5361 (defun js2-end-check-loop (node)
5362 "Return statement in the loop body must be consistent.
5363 The default assumption for any kind of a loop is that it will eventually
5364 terminate. The only exception is a loop with a constant true condition.
5365 Code that follows such a loop is examined only if one can determine
5366 statically that there is a break out of the loop.
5367
5368 for(... ; ... ; ...) {}
5369 for(... in ... ) {}
5370 while(...) { }
5371 do { } while(...)
5372
5373 Returns logical OR of END_* flags."
5374 (let ((rv (js2-end-check (js2-loop-node-body node)))
5375 (condition (cond
5376 ((js2-while-node-p node)
5377 (js2-while-node-condition node))
5378 ((js2-do-node-p node)
5379 (js2-do-node-condition node))
5380 ((js2-for-node-p node)
5381 (js2-for-node-condition node)))))
5382
5383 ;; check to see if the loop condition is always true
5384 (if (and condition
5385 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5386 (js2-clear-flag rv js2-END_DROPS_OFF))
5387
5388 ;; look for effect of breaks
5389 (js2-set-flag rv (js2-node-get-prop node
5390 'CONTROL_BLOCK_PROP
5391 js2-END_UNREACHED))
5392 rv))
5393
5394 (defun js2-end-check-block (node)
5395 "A general block of code is examined statement by statement.
5396 If any statement (even a compound one) returns in all branches, then
5397 subsequent statements are not examined.
5398 Returns logical OR of END_* flags."
5399 (let* ((rv js2-END_DROPS_OFF)
5400 (kids (js2-block-node-kids node))
5401 (n (car kids)))
5402 ;; Check each statement. If the statement can continue onto the next
5403 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5404 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5405 (js2-clear-flag rv js2-END_DROPS_OFF)
5406 (js2-set-flag rv (js2-end-check n))
5407 (setq kids (cdr kids)
5408 n (car kids)))
5409 rv))
5410
5411 (defun js2-end-check-label (node)
5412 "A labeled statement implies that there may be a break to the label.
5413 The function processes the labeled statement and then checks the
5414 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5415 particular label.
5416 Returns logical OR of END_* flags."
5417 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5418 (logior rv (js2-node-get-prop node
5419 'CONTROL_BLOCK_PROP
5420 js2-END_UNREACHED))))
5421
5422 (defun js2-end-check-break (node)
5423 "When a break is encountered annotate the statement being broken
5424 out of by setting its CONTROL_BLOCK_PROP property.
5425 Returns logical OR of END_* flags."
5426 (and (js2-break-node-target node)
5427 (js2-node-set-prop (js2-break-node-target node)
5428 'CONTROL_BLOCK_PROP
5429 js2-END_DROPS_OFF))
5430 js2-END_UNREACHED)
5431
5432 (defun js2-end-check (node)
5433 "Examine the body of a function, doing a basic reachability analysis.
5434 Returns a combination of flags END_* flags that indicate
5435 how the function execution can terminate. These constitute only the
5436 pessimistic set of termination conditions. It is possible that at
5437 runtime certain code paths will never be actually taken. Hence this
5438 analysis will flag errors in cases where there may not be errors.
5439 Returns logical OR of END_* flags"
5440 (let (kid)
5441 (cond
5442 ((js2-break-node-p node)
5443 (js2-end-check-break node))
5444 ((js2-expr-stmt-node-p node)
5445 (if (setq kid (js2-expr-stmt-node-expr node))
5446 (js2-end-check kid)
5447 js2-END_DROPS_OFF))
5448 ((or (js2-continue-node-p node)
5449 (js2-throw-node-p node))
5450 js2-END_UNREACHED)
5451 ((js2-return-node-p node)
5452 (if (setq kid (js2-return-node-retval node))
5453 js2-END_RETURNS_VALUE
5454 js2-END_RETURNS))
5455 ((js2-loop-node-p node)
5456 (js2-end-check-loop node))
5457 ((js2-switch-node-p node)
5458 (js2-end-check-switch node))
5459 ((js2-labeled-stmt-node-p node)
5460 (js2-end-check-label node))
5461 ((js2-if-node-p node)
5462 (js2-end-check-if node))
5463 ((js2-try-node-p node)
5464 (js2-end-check-try node))
5465 ((js2-block-node-p node)
5466 (if (null (js2-block-node-kids node))
5467 js2-END_DROPS_OFF
5468 (js2-end-check-block node)))
5469 ((js2-yield-node-p node)
5470 js2-END_YIELDS)
5471 (t
5472 js2-END_DROPS_OFF))))
5473
5474 (defun js2-always-defined-boolean-p (node)
5475 "Check if NODE always evaluates to true or false in boolean context.
5476 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5477 nor always false."
5478 (let ((tt (js2-node-type node))
5479 num)
5480 (cond
5481 ((or (= tt js2-FALSE) (= tt js2-NULL))
5482 'ALWAYS_FALSE)
5483 ((= tt js2-TRUE)
5484 'ALWAYS_TRUE)
5485 ((= tt js2-NUMBER)
5486 (setq num (js2-number-node-num-value node))
5487 (if (and (not (eq num 0.0e+NaN))
5488 (not (zerop num)))
5489 'ALWAYS_TRUE
5490 'ALWAYS_FALSE))
5491 (t
5492 nil))))
5493
5494 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5495 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5496
5497 (defvar js2-tokens nil
5498 "List of all defined token names.") ; initialized in `js2-token-names'
5499
5500 (defconst js2-token-names
5501 (let* ((names (make-vector js2-num-tokens -1))
5502 (case-fold-search nil) ; only match js2-UPPER_CASE
5503 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5504 (cl-loop for sym in syms
5505 for i from 0
5506 do
5507 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5508 (not (boundp sym)))
5509 (aset names (symbol-value sym) ; code, e.g. 152
5510 (downcase
5511 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5512 (push sym js2-tokens)))
5513 names)
5514 "Vector mapping int values to token string names, sans `js2-' prefix.")
5515
5516 (defun js2-tt-name (tok)
5517 "Return a string name for TOK, a token symbol or code.
5518 Signals an error if it's not a recognized token."
5519 (let ((code tok))
5520 (if (symbolp tok)
5521 (setq code (symbol-value tok)))
5522 (if (eq code -1)
5523 "ERROR"
5524 (if (and (numberp code)
5525 (not (cl-minusp code))
5526 (< code js2-num-tokens))
5527 (aref js2-token-names code)
5528 (error "Invalid token: %s" code)))))
5529
5530 (defsubst js2-tt-sym (tok)
5531 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5532 (intern (js2-tt-name tok)))
5533
5534 (defconst js2-token-codes
5535 (let ((table (make-hash-table :test 'eq :size 256)))
5536 (cl-loop for name across js2-token-names
5537 for sym = (intern (concat "js2-" (upcase name)))
5538 do
5539 (puthash sym (symbol-value sym) table))
5540 ;; clean up a few that are "wrong" in Rhino's token codes
5541 (puthash 'js2-DELETE js2-DELPROP table)
5542 table)
5543 "Hashtable mapping token type symbols to their bytecodes.")
5544
5545 (defsubst js2-tt-code (sym)
5546 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5547 (or (gethash sym js2-token-codes)
5548 (error "Invalid token symbol: %s " sym))) ; signal code bug
5549
5550 (defun js2-report-scan-error (msg &optional no-throw beg len)
5551 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5552 (js2-report-error msg nil
5553 (or beg (js2-current-token-beg))
5554 (or len (js2-current-token-len)))
5555 (unless no-throw
5556 (throw 'return js2-ERROR)))
5557
5558 (defun js2-set-string-from-buffer (token)
5559 "Set `string' and `end' slots for TOKEN, return the string."
5560 (setf (js2-token-end token) js2-ts-cursor
5561 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5562
5563 ;; TODO: could potentially avoid a lot of consing by allocating a
5564 ;; char buffer the way Rhino does.
5565 (defsubst js2-add-to-string (c)
5566 (push c js2-ts-string-buffer))
5567
5568 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5569 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5570 ;; any other character: when it's not part of the current token, we
5571 ;; unget it, allowing it to be read again by the following call.
5572 (defsubst js2-unget-char ()
5573 (cl-decf js2-ts-cursor))
5574
5575 ;; Rhino distinguishes \r and \n line endings. We don't need to
5576 ;; because we only scan from Emacs buffers, which always use \n.
5577 (defun js2-get-char ()
5578 "Read and return the next character from the input buffer.
5579 Increments `js2-ts-lineno' if the return value is a newline char.
5580 Updates `js2-ts-cursor' to the point after the returned char.
5581 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5582 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5583 (let (c)
5584 ;; check for end of buffer
5585 (if (>= js2-ts-cursor (point-max))
5586 (setq js2-ts-hit-eof t
5587 js2-ts-cursor (1+ js2-ts-cursor)
5588 c js2-EOF_CHAR) ; return value
5589 ;; otherwise read next char
5590 (setq c (char-before (cl-incf js2-ts-cursor)))
5591 ;; if we read a newline, update counters
5592 (if (= c ?\n)
5593 (setq js2-ts-line-start js2-ts-cursor
5594 js2-ts-lineno (1+ js2-ts-lineno)))
5595 ;; TODO: skip over format characters
5596 c)))
5597
5598 (defun js2-read-unicode-escape ()
5599 "Read a \\uNNNN sequence from the input.
5600 Assumes the ?\ and ?u have already been read.
5601 Returns the unicode character, or nil if it wasn't a valid character.
5602 Doesn't change the values of any scanner variables."
5603 ;; I really wish I knew a better way to do this, but I can't
5604 ;; find the Emacs function that takes a 16-bit int and converts
5605 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5606 ;; Have to first check that it's 4 hex characters or it may stop
5607 ;; the read early.
5608 (ignore-errors
5609 (let ((s (buffer-substring-no-properties js2-ts-cursor
5610 (+ 4 js2-ts-cursor))))
5611 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5612 (read (concat "?\\u" s))))))
5613
5614 (defun js2-match-char (test)
5615 "Consume and return next character if it matches TEST, a character.
5616 Returns nil and consumes nothing if TEST is not the next character."
5617 (let ((c (js2-get-char)))
5618 (if (eq c test)
5619 t
5620 (js2-unget-char)
5621 nil)))
5622
5623 (defun js2-peek-char ()
5624 (prog1
5625 (js2-get-char)
5626 (js2-unget-char)))
5627
5628 (defun js2-identifier-start-p (c)
5629 "Is C a valid start to an ES5 Identifier?
5630 See http://es5.github.io/#x7.6"
5631 (or
5632 (memq c '(?$ ?_))
5633 (memq (get-char-code-property c 'general-category)
5634 ;; Letters
5635 '(Lu Ll Lt Lm Lo Nl))))
5636
5637 (defun js2-identifier-part-p (c)
5638 "Is C a valid part of an ES5 Identifier?
5639 See http://es5.github.io/#x7.6"
5640 (or
5641 (memq c '(?$ ?_ ?\u200c ?\u200d))
5642 (memq (get-char-code-property c 'general-category)
5643 '(;; Letters
5644 Lu Ll Lt Lm Lo Nl
5645 ;; Combining Marks
5646 Mn Mc
5647 ;; Digits
5648 Nd
5649 ;; Connector Punctuation
5650 Pc))))
5651
5652 (defun js2-alpha-p (c)
5653 (cond ((and (<= ?A c) (<= c ?Z)) t)
5654 ((and (<= ?a c) (<= c ?z)) t)
5655 (t nil)))
5656
5657 (defsubst js2-digit-p (c)
5658 (and (<= ?0 c) (<= c ?9)))
5659
5660 (defun js2-js-space-p (c)
5661 (if (<= c 127)
5662 (memq c '(#x20 #x9 #xB #xC #xD))
5663 (or
5664 (eq c #xA0)
5665 ;; TODO: change this nil to check for Unicode space character
5666 nil)))
5667
5668 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5669
5670 (defun js2-skip-line ()
5671 "Skip to end of line."
5672 (while (not (memq (js2-get-char) js2-eol-chars)))
5673 (js2-unget-char)
5674 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5675
5676 (defun js2-init-scanner (&optional buf line)
5677 "Create token stream for BUF starting on LINE.
5678 BUF defaults to `current-buffer' and LINE defaults to 1.
5679
5680 A buffer can only have one scanner active at a time, which yields
5681 dramatically simpler code than using a defstruct. If you need to
5682 have simultaneous scanners in a buffer, copy the regions to scan
5683 into temp buffers."
5684 (with-current-buffer (or buf (current-buffer))
5685 (setq js2-ts-dirty-line nil
5686 js2-ts-hit-eof nil
5687 js2-ts-line-start 0
5688 js2-ts-lineno (or line 1)
5689 js2-ts-line-end-char -1
5690 js2-ts-cursor (point-min)
5691 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5692 js2-ti-tokens-cursor 0
5693 js2-ti-lookahead 0
5694 js2-ts-is-xml-attribute nil
5695 js2-ts-xml-is-tag-content nil
5696 js2-ts-xml-open-tags-count 0
5697 js2-ts-string-buffer nil)))
5698
5699 ;; This function uses the cached op, string and number fields in
5700 ;; TokenStream; if getToken has been called since the passed token
5701 ;; was scanned, the op or string printed may be incorrect.
5702 (defun js2-token-to-string (token)
5703 ;; Not sure where this function is used in Rhino. Not tested.
5704 (if (not js2-debug-print-trees)
5705 ""
5706 (let ((name (js2-tt-name token)))
5707 (cond
5708 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5709 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5710 (concat name " `" (js2-current-token-string) "'"))
5711 ((eq token js2-NUMBER)
5712 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5713 (t
5714 name)))))
5715
5716 (defconst js2-keywords
5717 '(break
5718 case catch class const continue
5719 debugger default delete do
5720 else extends export
5721 false finally for function
5722 if in instanceof import
5723 let
5724 new null
5725 return
5726 super switch
5727 this throw true try typeof
5728 var void
5729 while with
5730 yield))
5731
5732 ;; Token names aren't exactly the same as the keywords, unfortunately.
5733 ;; E.g. delete is js2-DELPROP.
5734 (defconst js2-kwd-tokens
5735 (let ((table (make-vector js2-num-tokens nil))
5736 (tokens
5737 (list js2-BREAK
5738 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5739 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5740 js2-ELSE js2-EXPORT
5741 js2-ELSE js2-EXTENDS js2-EXPORT
5742 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5743 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5744 js2-LET
5745 js2-NEW js2-NULL
5746 js2-RETURN
5747 js2-SUPER js2-SWITCH
5748 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5749 js2-VAR
5750 js2-WHILE js2-WITH
5751 js2-YIELD)))
5752 (dolist (i tokens)
5753 (aset table i 'font-lock-keyword-face))
5754 (aset table js2-STRING 'font-lock-string-face)
5755 (aset table js2-REGEXP 'font-lock-string-face)
5756 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5757 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5758 (aset table js2-COMMENT 'font-lock-comment-face)
5759 (aset table js2-THIS 'font-lock-builtin-face)
5760 (aset table js2-SUPER 'font-lock-builtin-face)
5761 (aset table js2-VOID 'font-lock-constant-face)
5762 (aset table js2-NULL 'font-lock-constant-face)
5763 (aset table js2-TRUE 'font-lock-constant-face)
5764 (aset table js2-FALSE 'font-lock-constant-face)
5765 (aset table js2-NOT 'font-lock-negation-char-face)
5766 table)
5767 "Vector whose values are non-nil for tokens that are keywords.
5768 The values are default faces to use for highlighting the keywords.")
5769
5770 ;; FIXME: Support strict mode-only future reserved words, after we know
5771 ;; which parts scopes are in strict mode, and which are not.
5772 (defconst js2-reserved-words '(class enum export extends import static super)
5773 "Future reserved keywords in ECMAScript 5.1.")
5774
5775 (defconst js2-keyword-names
5776 (let ((table (make-hash-table :test 'equal)))
5777 (cl-loop for k in js2-keywords
5778 do (puthash
5779 (symbol-name k) ; instanceof
5780 (intern (concat "js2-"
5781 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5782 table))
5783 table)
5784 "JavaScript keywords by name, mapped to their symbols.")
5785
5786 (defconst js2-reserved-word-names
5787 (let ((table (make-hash-table :test 'equal)))
5788 (cl-loop for k in js2-reserved-words
5789 do
5790 (puthash (symbol-name k) 'js2-RESERVED table))
5791 table)
5792 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5793
5794 (defun js2-collect-string (buf)
5795 "Convert BUF, a list of chars, to a string.
5796 Reverses BUF before converting."
5797 (if buf
5798 (apply #'string (nreverse buf))
5799 ""))
5800
5801 (defun js2-string-to-keyword (s)
5802 "Return token for S, a string, if S is a keyword or reserved word.
5803 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5804 (or (gethash s js2-keyword-names)
5805 (gethash s js2-reserved-word-names)))
5806
5807 (defsubst js2-ts-set-char-token-bounds (token)
5808 "Used when next token is one character."
5809 (setf (js2-token-beg token) (1- js2-ts-cursor)
5810 (js2-token-end token) js2-ts-cursor))
5811
5812 (defsubst js2-ts-return (token type)
5813 "Update the `end' and `type' slots of TOKEN,
5814 then throw `return' with value TYPE."
5815 (setf (js2-token-end token) js2-ts-cursor
5816 (js2-token-type token) type)
5817 (throw 'return type))
5818
5819 (defun js2-x-digit-to-int (c accumulator)
5820 "Build up a hex number.
5821 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5822 corresponding number. Otherwise return -1."
5823 (catch 'return
5824 (catch 'check
5825 ;; Use 0..9 < A..Z < a..z
5826 (cond
5827 ((<= c ?9)
5828 (cl-decf c ?0)
5829 (if (<= 0 c)
5830 (throw 'check nil)))
5831 ((<= c ?F)
5832 (when (<= ?A c)
5833 (cl-decf c (- ?A 10))
5834 (throw 'check nil)))
5835 ((<= c ?f)
5836 (when (<= ?a c)
5837 (cl-decf c (- ?a 10))
5838 (throw 'check nil))))
5839 (throw 'return -1))
5840 (logior c (lsh accumulator 4))))
5841
5842 (defun js2-get-token (&optional modifier)
5843 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5844 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5845 next saved token.
5846
5847 This function will not return a newline (js2-EOL) - instead, it
5848 gobbles newlines until it finds a non-newline token. Call
5849 `js2-peek-token-or-eol' when you care about newlines.
5850
5851 This function will also not return a js2-COMMENT. Instead, it
5852 records comments found in `js2-scanned-comments'. If the token
5853 returned by this function immediately follows a jsdoc comment,
5854 the token is flagged as such."
5855 (if (zerop js2-ti-lookahead)
5856 (js2-get-token-internal modifier)
5857 (cl-decf js2-ti-lookahead)
5858 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5859 (let ((tt (js2-current-token-type)))
5860 (cl-assert (not (= tt js2-EOL)))
5861 tt)))
5862
5863 (defun js2-unget-token ()
5864 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5865 (cl-incf js2-ti-lookahead)
5866 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5867
5868 (defun js2-get-token-internal (modifier)
5869 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5870 (tt (js2-token-type token))
5871 saw-eol
5872 face)
5873 ;; process comments
5874 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5875 (if (= tt js2-EOL)
5876 (setq saw-eol t)
5877 (setq saw-eol nil)
5878 (when js2-record-comments
5879 (js2-record-comment token)))
5880 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5881 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5882 tt (js2-token-type token)))
5883
5884 (when saw-eol
5885 (setf (js2-token-follows-eol-p token) t))
5886
5887 ;; perform lexical fontification as soon as token is scanned
5888 (when js2-parse-ide-mode
5889 (cond
5890 ((cl-minusp tt)
5891 (js2-record-face 'js2-error token))
5892 ((setq face (aref js2-kwd-tokens tt))
5893 (js2-record-face face token))
5894 ((and (= tt js2-NAME)
5895 (equal (js2-token-string token) "undefined"))
5896 (js2-record-face 'font-lock-constant-face token))))
5897 tt))
5898
5899 (defsubst js2-string-to-number (str base)
5900 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5901 (condition-case nil
5902 (string-to-number str base)
5903 (overflow-error -1)))
5904
5905 (defun js2-get-token-internal-1 (modifier)
5906 "Return next JavaScript token type, an int such as js2-RETURN.
5907 During operation, creates an instance of `js2-token' struct, sets
5908 its relevant fields and puts it into `js2-ti-tokens'."
5909 (let (identifier-start
5910 is-unicode-escape-start c
5911 contains-escape escape-val str result base
5912 look-for-slash continue tt
5913 (token (js2-new-token 0)))
5914 (setq
5915 tt
5916 (catch 'return
5917 (when (eq modifier 'TEMPLATE_TAIL)
5918 (setf (js2-token-beg token) (1- js2-ts-cursor))
5919 (throw 'return (js2-get-string-or-template-token ?` token)))
5920 (while t
5921 ;; Eat whitespace, possibly sensitive to newlines.
5922 (setq continue t)
5923 (while continue
5924 (setq c (js2-get-char))
5925 (cond
5926 ((eq c js2-EOF_CHAR)
5927 (js2-unget-char)
5928 (js2-ts-set-char-token-bounds token)
5929 (throw 'return js2-EOF))
5930 ((eq c ?\n)
5931 (js2-ts-set-char-token-bounds token)
5932 (setq js2-ts-dirty-line nil)
5933 (throw 'return js2-EOL))
5934 ((not (js2-js-space-p c))
5935 (if (/= c ?-) ; in case end of HTML comment
5936 (setq js2-ts-dirty-line t))
5937 (setq continue nil))))
5938 ;; Assume the token will be 1 char - fixed up below.
5939 (js2-ts-set-char-token-bounds token)
5940 (when (eq c ?@)
5941 (throw 'return js2-XMLATTR))
5942 ;; identifier/keyword/instanceof?
5943 ;; watch out for starting with a <backslash>
5944 (cond
5945 ((eq c ?\\)
5946 (setq c (js2-get-char))
5947 (if (eq c ?u)
5948 (setq identifier-start t
5949 is-unicode-escape-start t
5950 js2-ts-string-buffer nil)
5951 (setq identifier-start nil)
5952 (js2-unget-char)
5953 (setq c ?\\)))
5954 (t
5955 (when (setq identifier-start (js2-identifier-start-p c))
5956 (setq js2-ts-string-buffer nil)
5957 (js2-add-to-string c))))
5958 (when identifier-start
5959 (setq contains-escape is-unicode-escape-start)
5960 (catch 'break
5961 (while t
5962 (if is-unicode-escape-start
5963 ;; strictly speaking we should probably push-back
5964 ;; all the bad characters if the <backslash>uXXXX
5965 ;; sequence is malformed. But since there isn't a
5966 ;; correct context(is there?) for a bad Unicode
5967 ;; escape sequence in an identifier, we can report
5968 ;; an error here.
5969 (progn
5970 (setq escape-val 0)
5971 (dotimes (_ 4)
5972 (setq c (js2-get-char)
5973 escape-val (js2-x-digit-to-int c escape-val))
5974 ;; Next check takes care of c < 0 and bad escape
5975 (if (cl-minusp escape-val)
5976 (throw 'break nil)))
5977 (if (cl-minusp escape-val)
5978 (js2-report-scan-error "msg.invalid.escape" t))
5979 (js2-add-to-string escape-val)
5980 (setq is-unicode-escape-start nil))
5981 (setq c (js2-get-char))
5982 (cond
5983 ((eq c ?\\)
5984 (setq c (js2-get-char))
5985 (if (eq c ?u)
5986 (setq is-unicode-escape-start t
5987 contains-escape t)
5988 (js2-report-scan-error "msg.illegal.character" t)))
5989 (t
5990 (if (or (eq c js2-EOF_CHAR)
5991 (not (js2-identifier-part-p c)))
5992 (throw 'break nil))
5993 (js2-add-to-string c))))))
5994 (js2-unget-char)
5995 (setf str (js2-collect-string js2-ts-string-buffer)
5996 (js2-token-end token) js2-ts-cursor)
5997 ;; FIXME: Invalid in ES5 and ES6, see
5998 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5999 ;; Probably should just drop this conditional.
6000 (unless contains-escape
6001 ;; OPT we shouldn't have to make a string (object!) to
6002 ;; check if it's a keyword.
6003 ;; Return the corresponding token if it's a keyword
6004 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
6005 (setq result (js2-string-to-keyword str)))
6006 (if (and (< js2-language-version 170)
6007 (memq result '(js2-LET js2-YIELD)))
6008 ;; LET and YIELD are tokens only in 1.7 and later
6009 (setq result 'js2-NAME))
6010 (when (eq result 'js2-RESERVED)
6011 (setf (js2-token-string token) str))
6012 (throw 'return (js2-tt-code result))))
6013 ;; If we want to intern these as Rhino does, just use (intern str)
6014 (setf (js2-token-string token) str)
6015 (throw 'return js2-NAME)) ; end identifier/kwd check
6016 ;; is it a number?
6017 (when (or (js2-digit-p c)
6018 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6019 (setq js2-ts-string-buffer nil
6020 base 10)
6021 (when (eq c ?0)
6022 (setq c (js2-get-char))
6023 (cond
6024 ((or (eq c ?x) (eq c ?X))
6025 (setq base 16)
6026 (setq c (js2-get-char)))
6027 ((and (or (eq c ?b) (eq c ?B))
6028 (>= js2-language-version 200))
6029 (setq base 2)
6030 (setq c (js2-get-char)))
6031 ((and (or (eq c ?o) (eq c ?O))
6032 (>= js2-language-version 200))
6033 (setq base 8)
6034 (setq c (js2-get-char)))
6035 ((js2-digit-p c)
6036 (setq base 'maybe-8))
6037 (t
6038 (js2-add-to-string ?0))))
6039 (cond
6040 ((eq base 16)
6041 (if (> 0 (js2-x-digit-to-int c 0))
6042 (js2-report-scan-error "msg.missing.hex.digits")
6043 (while (<= 0 (js2-x-digit-to-int c 0))
6044 (js2-add-to-string c)
6045 (setq c (js2-get-char)))))
6046 ((eq base 2)
6047 (if (not (memq c '(?0 ?1)))
6048 (js2-report-scan-error "msg.missing.binary.digits")
6049 (while (memq c '(?0 ?1))
6050 (js2-add-to-string c)
6051 (setq c (js2-get-char)))))
6052 ((eq base 8)
6053 (if (or (> ?0 c) (< ?7 c))
6054 (js2-report-scan-error "msg.missing.octal.digits")
6055 (while (and (<= ?0 c) (>= ?7 c))
6056 (js2-add-to-string c)
6057 (setq c (js2-get-char)))))
6058 (t
6059 (while (and (<= ?0 c) (<= c ?9))
6060 ;; We permit 08 and 09 as decimal numbers, which
6061 ;; makes our behavior a superset of the ECMA
6062 ;; numeric grammar. We might not always be so
6063 ;; permissive, so we warn about it.
6064 (when (and (eq base 'maybe-8) (>= c ?8))
6065 (js2-report-warning "msg.bad.octal.literal"
6066 (if (eq c ?8) "8" "9"))
6067 (setq base 10))
6068 (js2-add-to-string c)
6069 (setq c (js2-get-char)))
6070 (when (eq base 'maybe-8)
6071 (setq base 8))))
6072 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6073 (when (eq c ?.)
6074 (cl-loop do
6075 (js2-add-to-string c)
6076 (setq c (js2-get-char))
6077 while (js2-digit-p c)))
6078 (when (memq c '(?e ?E))
6079 (js2-add-to-string c)
6080 (setq c (js2-get-char))
6081 (when (memq c '(?+ ?-))
6082 (js2-add-to-string c)
6083 (setq c (js2-get-char)))
6084 (unless (js2-digit-p c)
6085 (js2-report-scan-error "msg.missing.exponent" t))
6086 (cl-loop do
6087 (js2-add-to-string c)
6088 (setq c (js2-get-char))
6089 while (js2-digit-p c))))
6090 (js2-unget-char)
6091 (let ((str (js2-set-string-from-buffer token)))
6092 (setf (js2-token-number token)
6093 (js2-string-to-number str base)))
6094 (throw 'return js2-NUMBER))
6095 ;; is it a string?
6096 (when (or (memq c '(?\" ?\'))
6097 (and (>= js2-language-version 200)
6098 (= c ?`)))
6099 (throw 'return
6100 (js2-get-string-or-template-token c token)))
6101 (js2-ts-return token
6102 (cl-case c
6103 (?\;
6104 (throw 'return js2-SEMI))
6105 (?\[
6106 (throw 'return js2-LB))
6107 (?\]
6108 (throw 'return js2-RB))
6109 (?{
6110 (throw 'return js2-LC))
6111 (?}
6112 (throw 'return js2-RC))
6113 (?\(
6114 (throw 'return js2-LP))
6115 (?\)
6116 (throw 'return js2-RP))
6117 (?,
6118 (throw 'return js2-COMMA))
6119 (??
6120 (throw 'return js2-HOOK))
6121 (?:
6122 (if (js2-match-char ?:)
6123 js2-COLONCOLON
6124 (throw 'return js2-COLON)))
6125 (?.
6126 (if (js2-match-char ?.)
6127 (if (js2-match-char ?.)
6128 js2-TRIPLEDOT js2-DOTDOT)
6129 (if (js2-match-char ?\()
6130 js2-DOTQUERY
6131 (throw 'return js2-DOT))))
6132 (?|
6133 (if (js2-match-char ?|)
6134 (throw 'return js2-OR)
6135 (if (js2-match-char ?=)
6136 js2-ASSIGN_BITOR
6137 (throw 'return js2-BITOR))))
6138 (?^
6139 (if (js2-match-char ?=)
6140 js2-ASSIGN_BITOR
6141 (throw 'return js2-BITXOR)))
6142 (?&
6143 (if (js2-match-char ?&)
6144 (throw 'return js2-AND)
6145 (if (js2-match-char ?=)
6146 js2-ASSIGN_BITAND
6147 (throw 'return js2-BITAND))))
6148 (?=
6149 (if (js2-match-char ?=)
6150 (if (js2-match-char ?=)
6151 js2-SHEQ
6152 (throw 'return js2-EQ))
6153 (if (js2-match-char ?>)
6154 (js2-ts-return token js2-ARROW)
6155 (throw 'return js2-ASSIGN))))
6156 (?!
6157 (if (js2-match-char ?=)
6158 (if (js2-match-char ?=)
6159 js2-SHNE
6160 js2-NE)
6161 (throw 'return js2-NOT)))
6162 (?<
6163 ;; NB:treat HTML begin-comment as comment-till-eol
6164 (when (js2-match-char ?!)
6165 (when (js2-match-char ?-)
6166 (when (js2-match-char ?-)
6167 (js2-skip-line)
6168 (setf (js2-token-comment-type (js2-current-token)) 'html)
6169 (throw 'return js2-COMMENT)))
6170 (js2-unget-char))
6171 (if (js2-match-char ?<)
6172 (if (js2-match-char ?=)
6173 js2-ASSIGN_LSH
6174 js2-LSH)
6175 (if (js2-match-char ?=)
6176 js2-LE
6177 (throw 'return js2-LT))))
6178 (?>
6179 (if (js2-match-char ?>)
6180 (if (js2-match-char ?>)
6181 (if (js2-match-char ?=)
6182 js2-ASSIGN_URSH
6183 js2-URSH)
6184 (if (js2-match-char ?=)
6185 js2-ASSIGN_RSH
6186 js2-RSH))
6187 (if (js2-match-char ?=)
6188 js2-GE
6189 (throw 'return js2-GT))))
6190 (?*
6191 (if (js2-match-char ?=)
6192 js2-ASSIGN_MUL
6193 (throw 'return js2-MUL)))
6194 (?/
6195 ;; is it a // comment?
6196 (when (js2-match-char ?/)
6197 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6198 (js2-skip-line)
6199 (setf (js2-token-comment-type token) 'line)
6200 ;; include newline so highlighting goes to end of
6201 ;; window, if there actually is a newline; if we
6202 ;; hit eof, then implicitly there isn't
6203 (unless js2-ts-hit-eof
6204 (cl-incf (js2-token-end token)))
6205 (throw 'return js2-COMMENT))
6206 ;; is it a /* comment?
6207 (when (js2-match-char ?*)
6208 (setf look-for-slash nil
6209 (js2-token-beg token) (- js2-ts-cursor 2)
6210 (js2-token-comment-type token)
6211 (if (js2-match-char ?*)
6212 (progn
6213 (setq look-for-slash t)
6214 'jsdoc)
6215 'block))
6216 (while t
6217 (setq c (js2-get-char))
6218 (cond
6219 ((eq c js2-EOF_CHAR)
6220 (setf (js2-token-end token) (1- js2-ts-cursor))
6221 (js2-report-error "msg.unterminated.comment")
6222 (throw 'return js2-COMMENT))
6223 ((eq c ?*)
6224 (setq look-for-slash t))
6225 ((eq c ?/)
6226 (if look-for-slash
6227 (js2-ts-return token js2-COMMENT)))
6228 (t
6229 (setf look-for-slash nil
6230 (js2-token-end token) js2-ts-cursor)))))
6231 (if (js2-match-char ?=)
6232 js2-ASSIGN_DIV
6233 (throw 'return js2-DIV)))
6234 (?#
6235 (when js2-skip-preprocessor-directives
6236 (js2-skip-line)
6237 (setf (js2-token-comment-type token) 'preprocessor
6238 (js2-token-end token) js2-ts-cursor)
6239 (throw 'return js2-COMMENT))
6240 (throw 'return js2-ERROR))
6241 (?%
6242 (if (js2-match-char ?=)
6243 js2-ASSIGN_MOD
6244 (throw 'return js2-MOD)))
6245 (?~
6246 (throw 'return js2-BITNOT))
6247 (?+
6248 (if (js2-match-char ?=)
6249 js2-ASSIGN_ADD
6250 (if (js2-match-char ?+)
6251 js2-INC
6252 (throw 'return js2-ADD))))
6253 (?-
6254 (cond
6255 ((js2-match-char ?=)
6256 (setq c js2-ASSIGN_SUB))
6257 ((js2-match-char ?-)
6258 (unless js2-ts-dirty-line
6259 ;; treat HTML end-comment after possible whitespace
6260 ;; after line start as comment-until-eol
6261 (when (js2-match-char ?>)
6262 (js2-skip-line)
6263 (setf (js2-token-comment-type (js2-current-token)) 'html)
6264 (throw 'return js2-COMMENT)))
6265 (setq c js2-DEC))
6266 (t
6267 (setq c js2-SUB)))
6268 (setq js2-ts-dirty-line t)
6269 c)
6270 (otherwise
6271 (js2-report-scan-error "msg.illegal.character")))))))
6272 (setf (js2-token-type token) tt)
6273 token))
6274
6275 (defun js2-get-string-or-template-token (quote-char token)
6276 ;; We attempt to accumulate a string the fast way, by
6277 ;; building it directly out of the reader. But if there
6278 ;; are any escaped characters in the string, we revert to
6279 ;; building it out of a string buffer.
6280 (let ((c (js2-get-char))
6281 js2-ts-string-buffer
6282 nc c1 val escape-val)
6283 (catch 'break
6284 (while (/= c quote-char)
6285 (catch 'continue
6286 (when (eq c js2-EOF_CHAR)
6287 (js2-unget-char)
6288 (js2-report-error "msg.unterminated.string.lit")
6289 (throw 'break nil))
6290 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6291 (js2-unget-char)
6292 (js2-report-error "msg.unterminated.string.lit")
6293 (throw 'break nil))
6294 (when (eq c ?\\)
6295 ;; We've hit an escaped character
6296 (setq c (js2-get-char))
6297 (cl-case c
6298 (?b (setq c ?\b))
6299 (?f (setq c ?\f))
6300 (?n (setq c ?\n))
6301 (?r (setq c ?\r))
6302 (?t (setq c ?\t))
6303 (?v (setq c ?\v))
6304 (?u
6305 (setq c1 (js2-read-unicode-escape))
6306 (if js2-parse-ide-mode
6307 (if c1
6308 (progn
6309 ;; just copy the string in IDE-mode
6310 (js2-add-to-string ?\\)
6311 (js2-add-to-string ?u)
6312 (dotimes (_ 3)
6313 (js2-add-to-string (js2-get-char)))
6314 (setq c (js2-get-char))) ; added at end of loop
6315 ;; flag it as an invalid escape
6316 (js2-report-warning "msg.invalid.escape"
6317 nil (- js2-ts-cursor 2) 6))
6318 ;; Get 4 hex digits; if the u escape is not
6319 ;; followed by 4 hex digits, use 'u' + the
6320 ;; literal character sequence that follows.
6321 (js2-add-to-string ?u)
6322 (setq escape-val 0)
6323 (dotimes (_ 4)
6324 (setq c (js2-get-char)
6325 escape-val (js2-x-digit-to-int c escape-val))
6326 (if (cl-minusp escape-val)
6327 (throw 'continue nil))
6328 (js2-add-to-string c))
6329 ;; prepare for replace of stored 'u' sequence by escape value
6330 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6331 c escape-val)))
6332 (?x
6333 ;; Get 2 hex digits, defaulting to 'x'+literal
6334 ;; sequence, as above.
6335 (setq c (js2-get-char)
6336 escape-val (js2-x-digit-to-int c 0))
6337 (if (cl-minusp escape-val)
6338 (progn
6339 (js2-add-to-string ?x)
6340 (throw 'continue nil))
6341 (setq c1 c
6342 c (js2-get-char)
6343 escape-val (js2-x-digit-to-int c escape-val))
6344 (if (cl-minusp escape-val)
6345 (progn
6346 (js2-add-to-string ?x)
6347 (js2-add-to-string c1)
6348 (throw 'continue nil))
6349 ;; got 2 hex digits
6350 (setq c escape-val))))
6351 (?\n
6352 ;; Remove line terminator after escape to follow
6353 ;; SpiderMonkey and C/C++
6354 (setq c (js2-get-char))
6355 (throw 'continue nil))
6356 (t
6357 (when (and (<= ?0 c) (< c ?8))
6358 (setq val (- c ?0)
6359 c (js2-get-char))
6360 (when (and (<= ?0 c) (< c ?8))
6361 (setq val (- (+ (* 8 val) c) ?0)
6362 c (js2-get-char))
6363 (when (and (<= ?0 c)
6364 (< c ?8)
6365 (< val #o37))
6366 ;; c is 3rd char of octal sequence only
6367 ;; if the resulting val <= 0377
6368 (setq val (- (+ (* 8 val) c) ?0)
6369 c (js2-get-char))))
6370 (js2-unget-char)
6371 (setq c val)))))
6372 (when (and (eq quote-char ?`) (eq c ?$))
6373 (when (eq (setq nc (js2-get-char)) ?\{)
6374 (throw 'break nil))
6375 (js2-unget-char))
6376 (js2-add-to-string c)
6377 (setq c (js2-get-char)))))
6378 (js2-set-string-from-buffer token)
6379 (if (not (eq quote-char ?`))
6380 js2-STRING
6381 (if (and (eq c ?$) (eq nc ?\{))
6382 js2-TEMPLATE_HEAD
6383 js2-NO_SUBS_TEMPLATE))))
6384
6385 (defun js2-read-regexp (start-tt)
6386 "Called by parser when it gets / or /= in literal context."
6387 (let (c err
6388 in-class ; inside a '[' .. ']' character-class
6389 flags
6390 (continue t)
6391 (token (js2-new-token 0)))
6392 (setq js2-ts-string-buffer nil)
6393 (if (eq start-tt js2-ASSIGN_DIV)
6394 ;; mis-scanned /=
6395 (js2-add-to-string ?=)
6396 (if (not (eq start-tt js2-DIV))
6397 (error "failed assertion")))
6398 (while (and (not err)
6399 (or (/= (setq c (js2-get-char)) ?/)
6400 in-class))
6401 (cond
6402 ((or (= c ?\n)
6403 (= c js2-EOF_CHAR))
6404 (setf (js2-token-end token) (1- js2-ts-cursor)
6405 err t
6406 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6407 (js2-report-error "msg.unterminated.re.lit"))
6408 (t (cond
6409 ((= c ?\\)
6410 (js2-add-to-string c)
6411 (setq c (js2-get-char)))
6412 ((= c ?\[)
6413 (setq in-class t))
6414 ((= c ?\])
6415 (setq in-class nil)))
6416 (js2-add-to-string c))))
6417 (unless err
6418 (while continue
6419 (cond
6420 ((js2-match-char ?g)
6421 (push ?g flags))
6422 ((js2-match-char ?i)
6423 (push ?i flags))
6424 ((js2-match-char ?m)
6425 (push ?m flags))
6426 ((and (js2-match-char ?u)
6427 (>= js2-language-version 200))
6428 (push ?u flags))
6429 ((and (js2-match-char ?y)
6430 (>= js2-language-version 200))
6431 (push ?y flags))
6432 (t
6433 (setq continue nil))))
6434 (if (js2-alpha-p (js2-peek-char))
6435 (js2-report-scan-error "msg.invalid.re.flag" t
6436 js2-ts-cursor 1))
6437 (js2-set-string-from-buffer token))
6438 (js2-collect-string flags)))
6439
6440 (defun js2-get-first-xml-token ()
6441 (setq js2-ts-xml-open-tags-count 0
6442 js2-ts-is-xml-attribute nil
6443 js2-ts-xml-is-tag-content nil)
6444 (js2-unget-char)
6445 (js2-get-next-xml-token))
6446
6447 (defun js2-xml-discard-string (token)
6448 "Throw away the string in progress and flag an XML parse error."
6449 (setf js2-ts-string-buffer nil
6450 (js2-token-string token) nil)
6451 (js2-report-scan-error "msg.XML.bad.form" t))
6452
6453 (defun js2-get-next-xml-token ()
6454 (setq js2-ts-string-buffer nil) ; for recording the XML
6455 (let ((token (js2-new-token 0))
6456 c result)
6457 (setq result
6458 (catch 'return
6459 (while t
6460 (setq c (js2-get-char))
6461 (cond
6462 ((= c js2-EOF_CHAR)
6463 (throw 'return js2-ERROR))
6464 (js2-ts-xml-is-tag-content
6465 (cl-case c
6466 (?>
6467 (js2-add-to-string c)
6468 (setq js2-ts-xml-is-tag-content nil
6469 js2-ts-is-xml-attribute nil))
6470 (?/
6471 (js2-add-to-string c)
6472 (when (eq ?> (js2-peek-char))
6473 (setq c (js2-get-char))
6474 (js2-add-to-string c)
6475 (setq js2-ts-xml-is-tag-content nil)
6476 (cl-decf js2-ts-xml-open-tags-count)))
6477 (?{
6478 (js2-unget-char)
6479 (js2-set-string-from-buffer token)
6480 (throw 'return js2-XML))
6481 ((?\' ?\")
6482 (js2-add-to-string c)
6483 (unless (js2-read-quoted-string c token)
6484 (throw 'return js2-ERROR)))
6485 (?=
6486 (js2-add-to-string c)
6487 (setq js2-ts-is-xml-attribute t))
6488 ((? ?\t ?\r ?\n)
6489 (js2-add-to-string c))
6490 (t
6491 (js2-add-to-string c)
6492 (setq js2-ts-is-xml-attribute nil)))
6493 (when (and (not js2-ts-xml-is-tag-content)
6494 (zerop js2-ts-xml-open-tags-count))
6495 (js2-set-string-from-buffer token)
6496 (throw 'return js2-XMLEND)))
6497 (t
6498 ;; else not tag content
6499 (cl-case c
6500 (?<
6501 (js2-add-to-string c)
6502 (setq c (js2-peek-char))
6503 (cl-case c
6504 (?!
6505 (setq c (js2-get-char)) ;; skip !
6506 (js2-add-to-string c)
6507 (setq c (js2-peek-char))
6508 (cl-case c
6509 (?-
6510 (setq c (js2-get-char)) ;; skip -
6511 (js2-add-to-string c)
6512 (if (eq c ?-)
6513 (progn
6514 (js2-add-to-string c)
6515 (unless (js2-read-xml-comment token)
6516 (throw 'return js2-ERROR)))
6517 (js2-xml-discard-string token)
6518 (throw 'return js2-ERROR)))
6519 (?\[
6520 (setq c (js2-get-char)) ;; skip [
6521 (js2-add-to-string c)
6522 (if (and (= (js2-get-char) ?C)
6523 (= (js2-get-char) ?D)
6524 (= (js2-get-char) ?A)
6525 (= (js2-get-char) ?T)
6526 (= (js2-get-char) ?A)
6527 (= (js2-get-char) ?\[))
6528 (progn
6529 (js2-add-to-string ?C)
6530 (js2-add-to-string ?D)
6531 (js2-add-to-string ?A)
6532 (js2-add-to-string ?T)
6533 (js2-add-to-string ?A)
6534 (js2-add-to-string ?\[)
6535 (unless (js2-read-cdata token)
6536 (throw 'return js2-ERROR)))
6537 (js2-xml-discard-string token)
6538 (throw 'return js2-ERROR)))
6539 (t
6540 (unless (js2-read-entity token)
6541 (throw 'return js2-ERROR))))
6542 ;; Allow bare CDATA section, e.g.:
6543 ;; let xml = <![CDATA[ foo bar baz ]]>;
6544 (when (zerop js2-ts-xml-open-tags-count)
6545 (throw 'return js2-XMLEND)))
6546 (??
6547 (setq c (js2-get-char)) ;; skip ?
6548 (js2-add-to-string c)
6549 (unless (js2-read-PI token)
6550 (throw 'return js2-ERROR)))
6551 (?/
6552 ;; end tag
6553 (setq c (js2-get-char)) ;; skip /
6554 (js2-add-to-string c)
6555 (when (zerop js2-ts-xml-open-tags-count)
6556 (js2-xml-discard-string token)
6557 (throw 'return js2-ERROR))
6558 (setq js2-ts-xml-is-tag-content t)
6559 (cl-decf js2-ts-xml-open-tags-count))
6560 (t
6561 ;; start tag
6562 (setq js2-ts-xml-is-tag-content t)
6563 (cl-incf js2-ts-xml-open-tags-count))))
6564 (?{
6565 (js2-unget-char)
6566 (js2-set-string-from-buffer token)
6567 (throw 'return js2-XML))
6568 (t
6569 (js2-add-to-string c))))))))
6570 (setf (js2-token-end token) js2-ts-cursor)
6571 (setf (js2-token-type token) result)
6572 result))
6573
6574 (defun js2-read-quoted-string (quote token)
6575 (let (c)
6576 (catch 'return
6577 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6578 (js2-add-to-string c)
6579 (if (eq c quote)
6580 (throw 'return t)))
6581 (js2-xml-discard-string token) ;; throw away string in progress
6582 nil)))
6583
6584 (defun js2-read-xml-comment (token)
6585 (let ((c (js2-get-char)))
6586 (catch 'return
6587 (while (/= c js2-EOF_CHAR)
6588 (catch 'continue
6589 (js2-add-to-string c)
6590 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6591 (setq c (js2-get-char))
6592 (js2-add-to-string c)
6593 (if (eq (js2-peek-char) ?>)
6594 (progn
6595 (setq c (js2-get-char)) ;; skip >
6596 (js2-add-to-string c)
6597 (throw 'return t))
6598 (throw 'continue nil)))
6599 (setq c (js2-get-char))))
6600 (js2-xml-discard-string token)
6601 nil)))
6602
6603 (defun js2-read-cdata (token)
6604 (let ((c (js2-get-char)))
6605 (catch 'return
6606 (while (/= c js2-EOF_CHAR)
6607 (catch 'continue
6608 (js2-add-to-string c)
6609 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6610 (setq c (js2-get-char))
6611 (js2-add-to-string c)
6612 (if (eq (js2-peek-char) ?>)
6613 (progn
6614 (setq c (js2-get-char)) ;; Skip >
6615 (js2-add-to-string c)
6616 (throw 'return t))
6617 (throw 'continue nil)))
6618 (setq c (js2-get-char))))
6619 (js2-xml-discard-string token)
6620 nil)))
6621
6622 (defun js2-read-entity (token)
6623 (let ((decl-tags 1)
6624 c)
6625 (catch 'return
6626 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6627 (js2-add-to-string c)
6628 (cl-case c
6629 (?<
6630 (cl-incf decl-tags))
6631 (?>
6632 (cl-decf decl-tags)
6633 (if (zerop decl-tags)
6634 (throw 'return t)))))
6635 (js2-xml-discard-string token)
6636 nil)))
6637
6638 (defun js2-read-PI (token)
6639 "Scan an XML processing instruction."
6640 (let (c)
6641 (catch 'return
6642 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6643 (js2-add-to-string c)
6644 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6645 (setq c (js2-get-char)) ;; Skip >
6646 (js2-add-to-string c)
6647 (throw 'return t)))
6648 (js2-xml-discard-string token)
6649 nil)))
6650
6651 ;;; Highlighting
6652
6653 (defun js2-set-face (beg end face &optional record)
6654 "Fontify a region. If RECORD is non-nil, record for later."
6655 (when (cl-plusp js2-highlight-level)
6656 (setq beg (min (point-max) beg)
6657 beg (max (point-min) beg)
6658 end (min (point-max) end)
6659 end (max (point-min) end))
6660 (if record
6661 (push (list beg end face) js2-mode-fontifications)
6662 (put-text-property beg end 'font-lock-face face))))
6663
6664 (defsubst js2-clear-face (beg end)
6665 (remove-text-properties beg end '(font-lock-face nil
6666 help-echo nil
6667 point-entered nil
6668 cursor-sensor-functions nil
6669 c-in-sws nil)))
6670
6671 (defconst js2-ecma-global-props
6672 (concat "^"
6673 (regexp-opt
6674 '("Infinity" "NaN" "undefined" "arguments") t)
6675 "$")
6676 "Value properties of the Ecma-262 Global Object.
6677 Shown at or above `js2-highlight-level' 2.")
6678
6679 ;; might want to add the name "arguments" to this list?
6680 (defconst js2-ecma-object-props
6681 (concat "^"
6682 (regexp-opt
6683 '("prototype" "__proto__" "__parent__") t)
6684 "$")
6685 "Value properties of the Ecma-262 Object constructor.
6686 Shown at or above `js2-highlight-level' 2.")
6687
6688 (defconst js2-ecma-global-funcs
6689 (concat
6690 "^"
6691 (regexp-opt
6692 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6693 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6694 "$")
6695 "Function properties of the Ecma-262 Global object.
6696 Shown at or above `js2-highlight-level' 2.")
6697
6698 (defconst js2-ecma-number-props
6699 (concat "^"
6700 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6701 "NEGATIVE_INFINITY"
6702 "POSITIVE_INFINITY") t)
6703 "$")
6704 "Properties of the Ecma-262 Number constructor.
6705 Shown at or above `js2-highlight-level' 2.")
6706
6707 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6708 "Properties of the Ecma-262 Date constructor.
6709 Shown at or above `js2-highlight-level' 2.")
6710
6711 (defconst js2-ecma-math-props
6712 (concat "^"
6713 (regexp-opt
6714 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6715 t)
6716 "$")
6717 "Properties of the Ecma-262 Math object.
6718 Shown at or above `js2-highlight-level' 2.")
6719
6720 (defconst js2-ecma-math-funcs
6721 (concat "^"
6722 (regexp-opt
6723 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6724 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6725 "$")
6726 "Function properties of the Ecma-262 Math object.
6727 Shown at or above `js2-highlight-level' 2.")
6728
6729 (defconst js2-ecma-function-props
6730 (concat
6731 "^"
6732 (regexp-opt
6733 '(;; properties of the Object prototype object
6734 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6735 "toLocaleString" "toString" "valueOf"
6736 ;; properties of the Function prototype object
6737 "apply" "call"
6738 ;; properties of the Array prototype object
6739 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6740 "splice" "unshift"
6741 ;; properties of the String prototype object
6742 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6743 "localeCompare" "match" "replace" "search" "split" "substring"
6744 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6745 "toUpperCase"
6746 ;; properties of the Number prototype object
6747 "toExponential" "toFixed" "toPrecision"
6748 ;; properties of the Date prototype object
6749 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6750 "getMinutes" "getMonth" "getSeconds" "getTime"
6751 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6752 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6753 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6754 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6755 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6756 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6757 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6758 "toTimeString" "toUTCString"
6759 ;; properties of the RegExp prototype object
6760 "exec" "test"
6761 ;; properties of the JSON prototype object
6762 "parse" "stringify"
6763 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6764 "toSource" "__defineGetter__" "__defineSetter__"
6765 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6766 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6767 t)
6768 "$")
6769 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6770 Shown at or above `js2-highlight-level' 3.")
6771
6772 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6773 (let ((target-name (and target
6774 (js2-name-node-p target)
6775 (js2-name-node-name target)))
6776 (prop-name (if prop (js2-name-node-name prop)))
6777 (level2 (>= js2-highlight-level 2))
6778 (level3 (>= js2-highlight-level 3)))
6779 (when level2
6780 (let ((face
6781 (if call-p
6782 (cond
6783 ((and target prop)
6784 (cond
6785 ((and level3 (string-match js2-ecma-function-props prop-name))
6786 'font-lock-builtin-face)
6787 ((and target-name prop)
6788 (cond
6789 ((string= target-name "Date")
6790 (if (string-match js2-ecma-date-props prop-name)
6791 'font-lock-builtin-face))
6792 ((string= target-name "Math")
6793 (if (string-match js2-ecma-math-funcs prop-name)
6794 'font-lock-builtin-face))))))
6795 (prop
6796 (if (string-match js2-ecma-global-funcs prop-name)
6797 'font-lock-builtin-face)))
6798 (cond
6799 ((and target prop)
6800 (cond
6801 ((string= target-name "Number")
6802 (if (string-match js2-ecma-number-props prop-name)
6803 'font-lock-constant-face))
6804 ((string= target-name "Math")
6805 (if (string-match js2-ecma-math-props prop-name)
6806 'font-lock-constant-face))))
6807 (prop
6808 (if (string-match js2-ecma-object-props prop-name)
6809 'font-lock-constant-face))))))
6810 (when face
6811 (let ((pos (+ (js2-node-pos parent) ; absolute
6812 (js2-node-pos prop)))) ; relative
6813 (js2-set-face pos
6814 (+ pos (js2-node-len prop))
6815 face 'record)))))))
6816
6817 (defun js2-parse-highlight-member-expr-node (node)
6818 "Perform syntax highlighting of EcmaScript built-in properties.
6819 The variable `js2-highlight-level' governs this highlighting."
6820 (let (face target prop name pos end parent call-p callee)
6821 (cond
6822 ;; case 1: simple name, e.g. foo
6823 ((js2-name-node-p node)
6824 (setq name (js2-name-node-name node))
6825 ;; possible for name to be nil in rare cases - saw it when
6826 ;; running js2-mode on an elisp buffer. Might as well try to
6827 ;; make it so js2-mode never barfs.
6828 (when name
6829 (setq face (if (string-match js2-ecma-global-props name)
6830 'font-lock-constant-face))
6831 (when face
6832 (setq pos (js2-node-pos node)
6833 end (+ pos (js2-node-len node)))
6834 (js2-set-face pos end face 'record))))
6835 ;; case 2: property access or function call
6836 ((or (js2-prop-get-node-p node)
6837 ;; highlight function call if expr is a prop-get node
6838 ;; or a plain name (i.e. unqualified function call)
6839 (and (setq call-p (js2-call-node-p node))
6840 (setq callee (js2-call-node-target node)) ; separate setq!
6841 (or (js2-prop-get-node-p callee)
6842 (js2-name-node-p callee))))
6843 (setq parent node
6844 node (if call-p callee node))
6845 (if (and call-p (js2-name-node-p callee))
6846 (setq prop callee)
6847 (setq target (js2-prop-get-node-left node)
6848 prop (js2-prop-get-node-right node)))
6849 (cond
6850 ((js2-name-node-p prop)
6851 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6852 (js2-parse-highlight-prop-get parent target prop call-p))
6853 ((js2-name-node-p target)
6854 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6855 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6856
6857 (defun js2-parse-highlight-member-expr-fn-name (expr)
6858 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6859 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6860 We currently only handle the case where the last component is a prop-get
6861 of a simple name. Called before EXPR has a parent node."
6862 (let (pos
6863 (name (and (js2-prop-get-node-p expr)
6864 (js2-prop-get-node-right expr))))
6865 (when (js2-name-node-p name)
6866 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6867 (js2-node-pos name)))
6868 (+ pos (js2-node-len name))
6869 'font-lock-function-name-face
6870 'record))))
6871
6872 ;; source: http://jsdoc.sourceforge.net/
6873 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6874 ;; allows type specifications, and needs work before entering the wild.
6875
6876 (defconst js2-jsdoc-param-tag-regexp
6877 (concat "^\\s-*\\*+\\s-*\\(@"
6878 "\\(?:param\\|argument\\)"
6879 "\\)"
6880 "\\s-*\\({[^}]+}\\)?" ; optional type
6881 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6882 "\\>")
6883 "Matches jsdoc tags with optional type and optional param name.")
6884
6885 (defconst js2-jsdoc-typed-tag-regexp
6886 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6887 (regexp-opt
6888 '("enum"
6889 "extends"
6890 "field"
6891 "id"
6892 "implements"
6893 "lends"
6894 "mods"
6895 "requires"
6896 "return"
6897 "returns"
6898 "throw"
6899 "throws"))
6900 "\\)\\)\\s-*\\({[^}]+}\\)?")
6901 "Matches jsdoc tags with optional type.")
6902
6903 (defconst js2-jsdoc-arg-tag-regexp
6904 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6905 (regexp-opt
6906 '("alias"
6907 "augments"
6908 "borrows"
6909 "bug"
6910 "base"
6911 "config"
6912 "default"
6913 "define"
6914 "exception"
6915 "function"
6916 "member"
6917 "memberOf"
6918 "name"
6919 "namespace"
6920 "property"
6921 "since"
6922 "suppress"
6923 "this"
6924 "throws"
6925 "type"
6926 "version"))
6927 "\\)\\)\\s-+\\([^ \t]+\\)")
6928 "Matches jsdoc tags with a single argument.")
6929
6930 (defconst js2-jsdoc-empty-tag-regexp
6931 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6932 (regexp-opt
6933 '("addon"
6934 "author"
6935 "class"
6936 "const"
6937 "constant"
6938 "constructor"
6939 "constructs"
6940 "deprecated"
6941 "desc"
6942 "description"
6943 "event"
6944 "example"
6945 "exec"
6946 "export"
6947 "fileoverview"
6948 "final"
6949 "function"
6950 "hidden"
6951 "ignore"
6952 "implicitCast"
6953 "inheritDoc"
6954 "inner"
6955 "interface"
6956 "license"
6957 "noalias"
6958 "noshadow"
6959 "notypecheck"
6960 "override"
6961 "owner"
6962 "preserve"
6963 "preserveTry"
6964 "private"
6965 "protected"
6966 "public"
6967 "static"
6968 "supported"
6969 ))
6970 "\\)\\)\\s-*")
6971 "Matches empty jsdoc tags.")
6972
6973 (defconst js2-jsdoc-link-tag-regexp
6974 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6975 "Matches a jsdoc link or code tag.")
6976
6977 (defconst js2-jsdoc-see-tag-regexp
6978 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6979 "Matches a jsdoc @see tag.")
6980
6981 (defconst js2-jsdoc-html-tag-regexp
6982 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6983 "Matches a simple (no attributes) html start- or end-tag.")
6984
6985 (defun js2-jsdoc-highlight-helper ()
6986 (js2-set-face (match-beginning 1)
6987 (match-end 1)
6988 'js2-jsdoc-tag)
6989 (if (match-beginning 2)
6990 (if (save-excursion
6991 (goto-char (match-beginning 2))
6992 (= (char-after) ?{))
6993 (js2-set-face (1+ (match-beginning 2))
6994 (1- (match-end 2))
6995 'js2-jsdoc-type)
6996 (js2-set-face (match-beginning 2)
6997 (match-end 2)
6998 'js2-jsdoc-value)))
6999 (if (match-beginning 3)
7000 (js2-set-face (match-beginning 3)
7001 (match-end 3)
7002 'js2-jsdoc-value)))
7003
7004 (defun js2-highlight-jsdoc (ast)
7005 "Highlight doc comment tags."
7006 (let ((comments (js2-ast-root-comments ast))
7007 beg end)
7008 (save-excursion
7009 (dolist (node comments)
7010 (when (eq (js2-comment-node-format node) 'jsdoc)
7011 (setq beg (js2-node-abs-pos node)
7012 end (+ beg (js2-node-len node)))
7013 (save-restriction
7014 (narrow-to-region beg end)
7015 (dolist (re (list js2-jsdoc-param-tag-regexp
7016 js2-jsdoc-typed-tag-regexp
7017 js2-jsdoc-arg-tag-regexp
7018 js2-jsdoc-link-tag-regexp
7019 js2-jsdoc-see-tag-regexp
7020 js2-jsdoc-empty-tag-regexp))
7021 (goto-char beg)
7022 (while (re-search-forward re nil t)
7023 (js2-jsdoc-highlight-helper)))
7024 ;; simple highlighting for html tags
7025 (goto-char beg)
7026 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7027 (js2-set-face (match-beginning 1)
7028 (match-end 1)
7029 'js2-jsdoc-html-tag-delimiter)
7030 (js2-set-face (match-beginning 2)
7031 (match-end 2)
7032 'js2-jsdoc-html-tag-name)
7033 (js2-set-face (match-beginning 3)
7034 (match-end 3)
7035 'js2-jsdoc-html-tag-delimiter))))))))
7036
7037 (defun js2-highlight-assign-targets (_node left right)
7038 "Highlight function properties and external variables."
7039 (let (leftpos name)
7040 ;; highlight vars and props assigned function values
7041 (when (or (js2-function-node-p right)
7042 (js2-class-node-p right))
7043 (cond
7044 ;; var foo = function() {...}
7045 ((js2-name-node-p left)
7046 (setq name left))
7047 ;; foo.bar.baz = function() {...}
7048 ((and (js2-prop-get-node-p left)
7049 (js2-name-node-p (js2-prop-get-node-right left)))
7050 (setq name (js2-prop-get-node-right left))))
7051 (when name
7052 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7053 (+ leftpos (js2-node-len name))
7054 'font-lock-function-name-face
7055 'record)))))
7056
7057 (defun js2-record-name-node (node)
7058 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7059 later. NODE must be a name node."
7060 (let ((leftpos (js2-node-abs-pos node)))
7061 (push (list node js2-current-scope
7062 leftpos
7063 (+ leftpos (js2-node-len node)))
7064 js2-recorded-identifiers)))
7065
7066 (defun js2-highlight-undeclared-vars ()
7067 "After entire parse is finished, look for undeclared variable references.
7068 We have to wait until entire buffer is parsed, since JavaScript permits var
7069 decls to occur after they're used.
7070
7071 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7072 it is considered declared."
7073 (let (name)
7074 (dolist (entry js2-recorded-identifiers)
7075 (cl-destructuring-bind (name-node scope pos end) entry
7076 (setq name (js2-name-node-name name-node))
7077 (unless (or (member name js2-global-externs)
7078 (member name js2-default-externs)
7079 (member name js2-additional-externs)
7080 (js2-get-defining-scope scope name pos))
7081 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7082 'js2-external-variable))))
7083 (setq js2-recorded-identifiers nil)))
7084
7085 (defun js2-set-default-externs ()
7086 "Set the value of `js2-default-externs' based on the various
7087 `js2-include-?-externs' variables."
7088 (setq js2-default-externs
7089 (append js2-ecma-262-externs
7090 (if js2-include-browser-externs js2-browser-externs)
7091 (if (and js2-include-browser-externs
7092 (>= js2-language-version 200)) js2-harmony-externs)
7093 (if js2-include-rhino-externs js2-rhino-externs)
7094 (if js2-include-node-externs js2-node-externs)
7095 (if (or js2-include-browser-externs js2-include-node-externs)
7096 js2-typed-array-externs))))
7097
7098 (defun js2-apply-jslint-globals ()
7099 (setq js2-additional-externs
7100 (nconc (js2-get-jslint-globals)
7101 js2-additional-externs)))
7102
7103 (defun js2-get-jslint-globals ()
7104 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7105 when (and (eq 'block (js2-comment-node-format node))
7106 (save-excursion
7107 (goto-char (js2-node-abs-pos node))
7108 (looking-at "/\\*global ")))
7109 append (js2-get-jslint-globals-in
7110 (match-end 0)
7111 (js2-node-abs-end node))))
7112
7113 (defun js2-get-jslint-globals-in (beg end)
7114 (let (res)
7115 (save-excursion
7116 (goto-char beg)
7117 (while (re-search-forward js2-mode-identifier-re end t)
7118 (let ((match (match-string 0)))
7119 (unless (member match '("true" "false"))
7120 (push match res)))))
7121 (nreverse res)))
7122
7123 ;;; IMenu support
7124
7125 ;; We currently only support imenu, but eventually should support speedbar and
7126 ;; possibly other browsing mechanisms.
7127
7128 ;; The basic strategy is to identify function assignment targets of the form
7129 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7130 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7131 ;; for imenu after parsing is finished.
7132
7133 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7134 ;; JavaScript, and the general problem is undecidable. However, several forms
7135 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7136 ;; include:
7137
7138 ;; function foo() -- function declaration
7139 ;; foo = function() -- function expression assigned to variable
7140 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7141 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7142 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7143 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7144 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7145 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7146 ;; function foo() {function bar() {...}} -- nested function
7147 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7148
7149 ;; This list boils down to a few forms that can be combined recursively.
7150 ;; Top-level named function declarations include both the left-hand (name)
7151 ;; and the right-hand (function value) expressions needed to produce an imenu
7152 ;; entry. The other "right-hand" forms we need to look for are:
7153 ;; - functions declared as props/getters/setters in object literals
7154 ;; - nested named function declarations
7155 ;; The "left-hand" expressions that functions can be assigned to include:
7156 ;; - local/global variables
7157 ;; - nested property-get expressions like a.b.c.d
7158 ;; - element gets like foo[10] or foo['bar'] where the index
7159 ;; expression can be trivially converted to a property name. They
7160 ;; effectively then become property gets.
7161
7162 ;; All the different definition types are canonicalized into the form
7163 ;; foo.bar.baz = position-of-function-keyword
7164
7165 ;; We need to build a trie-like structure for imenu. As an example,
7166 ;; consider the following JavaScript code:
7167
7168 ;; a = function() {...} // function at position 5
7169 ;; b = function() {...} // function at position 25
7170 ;; foo = function() {...} // function at position 100
7171 ;; foo.bar = function() {...} // function at position 200
7172 ;; foo.bar.baz = function() {...} // function at position 300
7173 ;; foo.bar.zab = function() {...} // function at position 400
7174
7175 ;; During parsing we accumulate an entry for each definition in
7176 ;; the variable `js2-imenu-recorder', like so:
7177
7178 ;; '((fn a 5)
7179 ;; (fn b 25)
7180 ;; (fn foo 100)
7181 ;; (fn foo bar 200)
7182 ;; (fn foo bar baz 300)
7183 ;; (fn foo bar zab 400))
7184
7185 ;; Where 'fn' is the respective function node.
7186 ;; After parsing these entries are merged into this alist-trie:
7187
7188 ;; '((a . 1)
7189 ;; (b . 2)
7190 ;; (foo (<definition> . 3)
7191 ;; (bar (<definition> . 6)
7192 ;; (baz . 100)
7193 ;; (zab . 200))))
7194
7195 ;; Note the wacky need for a <definition> name. The token can be anything
7196 ;; that isn't a valid JavaScript identifier, because you might make foo
7197 ;; a function and then start setting properties on it that are also functions.
7198
7199 (defun js2-prop-node-name (node)
7200 "Return the name of a node that may be a property-get/property-name.
7201 If NODE is not a valid name-node, string-node or integral number-node,
7202 returns nil. Otherwise returns the string name/value of the node."
7203 (cond
7204 ((js2-name-node-p node)
7205 (js2-name-node-name node))
7206 ((js2-string-node-p node)
7207 (js2-string-node-value node))
7208 ((and (js2-number-node-p node)
7209 (string-match "^[0-9]+$" (js2-number-node-value node)))
7210 (js2-number-node-value node))
7211 ((eq (js2-node-type node) js2-THIS)
7212 "this")
7213 ((eq (js2-node-type node) js2-SUPER)
7214 "super")))
7215
7216 (defun js2-node-qname-component (node)
7217 "Return the name of this node, if it contributes to a qname.
7218 Returns nil if the node doesn't contribute."
7219 (copy-sequence
7220 (or (js2-prop-node-name node)
7221 (if (and (js2-function-node-p node)
7222 (js2-function-node-name node))
7223 (js2-name-node-name (js2-function-node-name node))))))
7224
7225 (defun js2-record-imenu-entry (fn-node qname pos)
7226 "Add an entry to `js2-imenu-recorder'.
7227 FN-NODE should be the current item's function node.
7228
7229 Associate FN-NODE with its QNAME for later lookup.
7230 This is used in postprocessing the chain list. For each chain, we find
7231 the parent function, look up its qname, then prepend a copy of it to the chain."
7232 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7233 (unless js2-imenu-function-map
7234 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7235 (puthash fn-node qname js2-imenu-function-map))
7236
7237 (defun js2-record-imenu-functions (node &optional var)
7238 "Record function definitions for imenu.
7239 NODE is a function node or an object literal.
7240 VAR, if non-nil, is the expression that NODE is being assigned to.
7241 When passed arguments of wrong type, does nothing."
7242 (when js2-parse-ide-mode
7243 (let ((fun-p (js2-function-node-p node))
7244 qname fname-node)
7245 (cond
7246 ;; non-anonymous function declaration?
7247 ((and fun-p
7248 (not var)
7249 (setq fname-node (js2-function-node-name node)))
7250 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7251 ;; for remaining forms, compute left-side tree branch first
7252 ((and var (setq qname (js2-compute-nested-prop-get var)))
7253 (cond
7254 ;; foo.bar.baz = function
7255 (fun-p
7256 (js2-record-imenu-entry node qname (js2-node-pos node)))
7257 ;; foo.bar.baz = object-literal
7258 ;; look for nested functions: {a: {b: function() {...} }}
7259 ((js2-object-node-p node)
7260 ;; Node position here is still absolute, since the parser
7261 ;; passes the assignment target and value expressions
7262 ;; to us before they are added as children of the assignment node.
7263 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7264
7265 (defun js2-compute-nested-prop-get (node)
7266 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7267 component nodes as a list. Otherwise return nil. Element-gets are treated
7268 as property-gets if the index expression is a string, or a positive integer."
7269 (let (left right head)
7270 (cond
7271 ((or (js2-name-node-p node)
7272 (js2-this-or-super-node-p node))
7273 (list node))
7274 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7275 ((js2-prop-get-node-p node) ; foo.bar
7276 (setq left (js2-prop-get-node-left node)
7277 right (js2-prop-get-node-right node))
7278 (if (setq head (js2-compute-nested-prop-get left))
7279 (nconc head (list right))))
7280 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7281 (setq left (js2-elem-get-node-target node)
7282 right (js2-elem-get-node-element node))
7283 (if (or (js2-string-node-p right) ; ['bar']
7284 (and (js2-number-node-p right) ; [10]
7285 (string-match "^[0-9]+$"
7286 (js2-number-node-value right))))
7287 (if (setq head (js2-compute-nested-prop-get left))
7288 (nconc head (list right))))))))
7289
7290 (defun js2-record-object-literal (node qname pos)
7291 "Recursively process an object literal looking for functions.
7292 NODE is an object literal that is the right-hand child of an assignment
7293 expression. QNAME is a list of nodes representing the assignment target,
7294 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7295 POS is the absolute position of the node.
7296 We do a depth-first traversal of NODE. For any functions we find,
7297 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7298 (let (right)
7299 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7300 (let ((left (js2-infix-node-left e))
7301 ;; Element positions are relative to the parent position.
7302 (pos (+ pos (js2-node-pos e))))
7303 (cond
7304 ;; foo: function() {...}
7305 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7306 (when (js2-prop-node-name left)
7307 ;; As a policy decision, we record the position of the property,
7308 ;; not the position of the `function' keyword, since the property
7309 ;; is effectively the name of the function.
7310 (js2-record-imenu-entry right (append qname (list left)) pos)))
7311 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7312 ((js2-object-node-p right)
7313 (js2-record-object-literal right
7314 (append qname (list (js2-infix-node-left e)))
7315 (+ pos (js2-node-pos right)))))))))
7316
7317 (defun js2-node-top-level-decl-p (node)
7318 "Return t if NODE's name is defined in the top-level scope.
7319 Also returns t if NODE's name is not defined in any scope, since it implies
7320 that it's an external variable, which must also be in the top-level scope."
7321 (let* ((name (js2-prop-node-name node))
7322 (this-scope (js2-node-get-enclosing-scope node))
7323 defining-scope)
7324 (cond
7325 ((js2-this-or-super-node-p node)
7326 nil)
7327 ((null this-scope)
7328 t)
7329 ((setq defining-scope (js2-get-defining-scope this-scope name))
7330 (js2-ast-root-p defining-scope))
7331 (t t))))
7332
7333 (defun js2-wrapper-function-p (node)
7334 "Return t if NODE is a function expression that's immediately invoked.
7335 NODE must be `js2-function-node'."
7336 (let ((parent (js2-node-parent node)))
7337 (or
7338 ;; function(){...}();
7339 (and (js2-call-node-p parent)
7340 (eq node (js2-call-node-target parent)))
7341 (and (js2-paren-node-p parent)
7342 ;; (function(){...})();
7343 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7344 ;; (function(){...}).call(this);
7345 (and (js2-prop-get-node-p parent)
7346 (member (js2-name-node-name (js2-prop-get-node-right parent))
7347 '("call" "apply"))
7348 (js2-call-node-p (js2-node-parent parent))))))))
7349
7350 (defun js2-browse-postprocess-chains ()
7351 "Modify function-declaration name chains after parsing finishes.
7352 Some of the information is only available after the parse tree is complete.
7353 For instance, processing a nested scope requires a parent function node."
7354 (let (result fn parent-qname p elem)
7355 (dolist (entry js2-imenu-recorder)
7356 ;; function node goes first
7357 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7358 ;; Examine head's defining scope:
7359 ;; Pre-processed chain, or top-level/external, keep as-is.
7360 (if (or (stringp head) (js2-node-top-level-decl-p head))
7361 (push chain result)
7362 (when (js2-this-or-super-node-p head)
7363 (setq chain (cdr chain))) ; discard this-node
7364 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7365 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7366 (when (eq parent-qname 'not-found)
7367 ;; anonymous function expressions are not recorded
7368 ;; during the parse, so we need to handle this case here
7369 (setq parent-qname
7370 (if (js2-wrapper-function-p fn)
7371 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7372 (if (js2-ast-root-p grandparent)
7373 nil
7374 (gethash grandparent js2-imenu-function-map 'skip)))
7375 'skip))
7376 (puthash fn parent-qname js2-imenu-function-map))
7377 (if (eq parent-qname 'skip)
7378 ;; We don't show it, let's record that fact.
7379 (remhash current-fn js2-imenu-function-map)
7380 ;; Prepend parent fn qname to this chain.
7381 (let ((qname (append parent-qname chain)))
7382 (puthash current-fn (butlast qname) js2-imenu-function-map)
7383 (push qname result)))))))
7384 ;; Collect chains obtained by third-party code.
7385 (let (js2-imenu-recorder)
7386 (run-hooks 'js2-build-imenu-callbacks)
7387 (dolist (entry js2-imenu-recorder)
7388 (push (cdr entry) result)))
7389 ;; Finally replace each node in each chain with its name.
7390 (dolist (chain result)
7391 (setq p chain)
7392 (while p
7393 (if (js2-node-p (setq elem (car p)))
7394 (setcar p (js2-node-qname-component elem)))
7395 (setq p (cdr p))))
7396 result))
7397
7398 ;; Merge name chains into a trie-like tree structure of nested lists.
7399 ;; To simplify construction of the trie, we first build it out using the rule
7400 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7401 ;; [key, num-or-list]. The second element can be a number; if so, this key
7402 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7403 ;; associated with the key at this level.) Otherwise the second element is
7404 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7405 ;; a simple recursive formulation.
7406 ;;
7407 ;; js2-mode is building the data structure for imenu. The imenu documentation
7408 ;; claims that it's the structure above, but in practice it wants the children
7409 ;; at the same list level as the key for that level, which is how I've drawn
7410 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7411 ;; list wrapper around the children at each level.
7412 ;;
7413 ;; A completed nested imenu-alist entry looks like this:
7414 ;; '(("foo"
7415 ;; ("<definition>" . 7)
7416 ;; ("bar"
7417 ;; ("a" . 40)
7418 ;; ("b" . 60))))
7419 ;;
7420 ;; In particular, the documentation for `imenu--index-alist' says that
7421 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7422 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7423
7424 (defun js2-treeify (lst)
7425 "Convert (a b c d) to (a ((b ((c d)))))."
7426 (if (null (cddr lst)) ; list length <= 2
7427 lst
7428 (list (car lst) (list (js2-treeify (cdr lst))))))
7429
7430 (defun js2-build-alist-trie (chains trie)
7431 "Merge declaration name chains into a trie-like alist structure for imenu.
7432 CHAINS is the qname chain list produced during parsing. TRIE is a
7433 list of elements built up so far."
7434 (let (head tail pos branch kids)
7435 (dolist (chain chains)
7436 (setq head (car chain)
7437 tail (cdr chain)
7438 pos (if (numberp (car tail)) (car tail))
7439 branch (js2-find-if (lambda (n)
7440 (string= (car n) head))
7441 trie)
7442 kids (cl-second branch))
7443 (cond
7444 ;; case 1: this key isn't in the trie yet
7445 ((null branch)
7446 (if trie
7447 (setcdr (last trie) (list (js2-treeify chain)))
7448 (setq trie (list (js2-treeify chain)))))
7449 ;; case 2: key is present with a single number entry: replace w/ list
7450 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7451 ;; ("<definition>" 20)))
7452 ((numberp kids)
7453 (setcar (cdr branch)
7454 (list (list "<definition-1>" kids)
7455 (if pos
7456 (list "<definition-2>" pos)
7457 (js2-treeify tail)))))
7458 ;; case 3: key is there (with kids), and we're a number entry
7459 (pos
7460 (setcdr (last kids)
7461 (list
7462 (list (format "<definition-%d>"
7463 (1+ (cl-loop for kid in kids
7464 count (eq ?< (aref (car kid) 0)))))
7465 pos))))
7466 ;; case 4: key is there with kids, need to merge in our chain
7467 (t
7468 (js2-build-alist-trie (list tail) kids))))
7469 trie))
7470
7471 (defun js2-flatten-trie (trie)
7472 "Convert TRIE to imenu-format.
7473 Recurses through nodes, and for each one whose second element is a list,
7474 appends the list's flattened elements to the current element. Also
7475 changes the tails into conses. For instance, this pre-flattened trie
7476
7477 '(a ((b 20)
7478 (c ((d 30)
7479 (e 40)))))
7480
7481 becomes
7482
7483 '(a (b . 20)
7484 (c (d . 30)
7485 (e . 40)))
7486
7487 Note that the root of the trie has no key, just a list of chains.
7488 This is also true for the value of any key with multiple children,
7489 e.g. key 'c' in the example above."
7490 (cond
7491 ((listp (car trie))
7492 (mapcar #'js2-flatten-trie trie))
7493 (t
7494 (if (numberp (cl-second trie))
7495 (cons (car trie) (cl-second trie))
7496 ;; else pop list and append its kids
7497 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7498
7499 (defun js2-build-imenu-index ()
7500 "Turn `js2-imenu-recorder' into an imenu data structure."
7501 (when (eq js2-imenu-recorder 'empty)
7502 (setq js2-imenu-recorder nil))
7503 (let* ((chains (js2-browse-postprocess-chains))
7504 (result (js2-build-alist-trie chains nil)))
7505 (js2-flatten-trie result)))
7506
7507 (defun js2-test-print-chains (chains)
7508 "Print a list of qname chains.
7509 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7510 i.e. one or more nodes, and an integer position as the list tail."
7511 (mapconcat (lambda (chain)
7512 (concat "("
7513 (mapconcat (lambda (elem)
7514 (if (js2-node-p elem)
7515 (or (js2-node-qname-component elem)
7516 "nil")
7517 (number-to-string elem)))
7518 chain
7519 " ")
7520 ")"))
7521 chains
7522 "\n"))
7523
7524 ;;; Parser
7525
7526 (defconst js2-version "1.8.5"
7527 "Version of JavaScript supported.")
7528
7529 (defun js2-record-face (face &optional token)
7530 "Record a style run of FACE for TOKEN or the current token."
7531 (unless token (setq token (js2-current-token)))
7532 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7533
7534 (defsubst js2-node-end (n)
7535 "Computes the absolute end of node N.
7536 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7537 is only true until the node is added to its parent; i.e., while parsing."
7538 (+ (js2-node-pos n)
7539 (js2-node-len n)))
7540
7541 (defun js2-record-comment (token)
7542 "Record a comment in `js2-scanned-comments'."
7543 (let ((ct (js2-token-comment-type token))
7544 (beg (js2-token-beg token))
7545 (end (js2-token-end token)))
7546 (push (make-js2-comment-node :len (- end beg)
7547 :format ct)
7548 js2-scanned-comments)
7549 (when js2-parse-ide-mode
7550 (js2-record-face (if (eq ct 'jsdoc)
7551 'font-lock-doc-face
7552 'font-lock-comment-face)
7553 token)
7554 (when (memq ct '(html preprocessor))
7555 ;; Tell cc-engine the bounds of the comment.
7556 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7557
7558 (defun js2-peek-token ()
7559 "Return the next token type without consuming it.
7560 If `js2-ti-lookahead' is positive, return the type of next token
7561 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7562 (if (not (zerop js2-ti-lookahead))
7563 (js2-token-type
7564 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7565 (let ((tt (js2-get-token-internal nil)))
7566 (js2-unget-token)
7567 tt)))
7568
7569 (defalias 'js2-next-token 'js2-get-token)
7570
7571 (defun js2-match-token (match &optional dont-unget)
7572 "Get next token and return t if it matches MATCH, a bytecode.
7573 Returns nil and consumes nothing if MATCH is not the next token."
7574 (if (/= (js2-get-token) match)
7575 (ignore (unless dont-unget (js2-unget-token)))
7576 t))
7577
7578 (defun js2-match-contextual-kwd (name)
7579 "Consume and return t if next token is `js2-NAME', and its
7580 string is NAME. Returns nil and keeps current token otherwise."
7581 (if (or (/= (js2-get-token) js2-NAME)
7582 (not (string= (js2-current-token-string) name)))
7583 (progn
7584 (js2-unget-token)
7585 nil)
7586 (js2-record-face 'font-lock-keyword-face)
7587 t))
7588
7589 (defun js2-get-prop-name-token ()
7590 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7591
7592 (defun js2-match-prop-name ()
7593 "Consume token and return t if next token is a valid property name.
7594 If `js2-language-version' is >= 180, a keyword or reserved word
7595 is considered valid name as well."
7596 (if (eq js2-NAME (js2-get-prop-name-token))
7597 t
7598 (js2-unget-token)
7599 nil))
7600
7601 (defun js2-must-match-prop-name (msg-id &optional pos len)
7602 (if (js2-match-prop-name)
7603 t
7604 (js2-report-error msg-id nil pos len)
7605 nil))
7606
7607 (defun js2-peek-token-or-eol ()
7608 "Return js2-EOL if the next token immediately follows a newline.
7609 Else returns the next token. Used in situations where we don't
7610 consider certain token types valid if they are preceded by a newline.
7611 One example is the postfix ++ or -- operator, which has to be on the
7612 same line as its operand."
7613 (let ((tt (js2-get-token))
7614 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7615 (js2-unget-token)
7616 (if follows-eol
7617 js2-EOL
7618 tt)))
7619
7620 (defun js2-must-match (token msg-id &optional pos len)
7621 "Match next token to token code TOKEN, or record a syntax error.
7622 MSG-ID is the error message to report if the match fails.
7623 Returns t on match, nil if no match."
7624 (if (js2-match-token token t)
7625 t
7626 (js2-report-error msg-id nil pos len)
7627 (js2-unget-token)
7628 nil))
7629
7630 (defun js2-must-match-name (msg-id)
7631 (if (js2-match-token js2-NAME t)
7632 t
7633 (if (eq (js2-current-token-type) js2-RESERVED)
7634 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7635 (js2-report-error msg-id)
7636 (js2-unget-token))
7637 nil))
7638
7639 (defsubst js2-inside-function ()
7640 (cl-plusp js2-nesting-of-function))
7641
7642 (defun js2-set-requires-activation ()
7643 (if (js2-function-node-p js2-current-script-or-fn)
7644 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7645
7646 (defun js2-check-activation-name (name _token)
7647 (when (js2-inside-function)
7648 ;; skip language-version 1.2 check from Rhino
7649 (if (or (string= "arguments" name)
7650 (and js2-compiler-activation-names ; only used in codegen
7651 (gethash name js2-compiler-activation-names)))
7652 (js2-set-requires-activation))))
7653
7654 (defun js2-set-is-generator ()
7655 (let ((fn-node js2-current-script-or-fn))
7656 (when (and (js2-function-node-p fn-node)
7657 (not (js2-function-node-generator-type fn-node)))
7658 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7659
7660 (defun js2-must-have-xml ()
7661 (unless js2-compiler-xml-available
7662 (js2-report-error "msg.XML.not.available")))
7663
7664 (defun js2-push-scope (scope)
7665 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7666 (cl-assert (js2-scope-p scope))
7667 (cl-assert (null (js2-scope-parent-scope scope)))
7668 (cl-assert (not (eq js2-current-scope scope)))
7669 (setf (js2-scope-parent-scope scope) js2-current-scope
7670 js2-current-scope scope))
7671
7672 (defsubst js2-pop-scope ()
7673 (setq js2-current-scope
7674 (js2-scope-parent-scope js2-current-scope)))
7675
7676 (defun js2-enter-loop (loop-node)
7677 (push loop-node js2-loop-set)
7678 (push loop-node js2-loop-and-switch-set)
7679 (js2-push-scope loop-node)
7680 ;; Tell the current labeled statement (if any) its statement,
7681 ;; and set the jump target of the first label to the loop.
7682 ;; These are used in `js2-parse-continue' to verify that the
7683 ;; continue target is an actual labeled loop. (And for codegen.)
7684 (when js2-labeled-stmt
7685 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7686 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7687 js2-labeled-stmt))) loop-node)))
7688
7689 (defun js2-exit-loop ()
7690 (pop js2-loop-set)
7691 (pop js2-loop-and-switch-set)
7692 (js2-pop-scope))
7693
7694 (defsubst js2-enter-switch (switch-node)
7695 (push switch-node js2-loop-and-switch-set))
7696
7697 (defsubst js2-exit-switch ()
7698 (pop js2-loop-and-switch-set))
7699
7700 (defun js2-parse (&optional buf cb)
7701 "Tell the js2 parser to parse a region of JavaScript.
7702
7703 BUF is a buffer or buffer name containing the code to parse.
7704 Call `narrow-to-region' first to parse only part of the buffer.
7705
7706 The returned AST root node is given some additional properties:
7707 `node-count' - total number of nodes in the AST
7708 `buffer' - BUF. The buffer it refers to may change or be killed,
7709 so the value is not necessarily reliable.
7710
7711 An optional callback CB can be specified to report parsing
7712 progress. If `(functionp CB)' returns t, it will be called with
7713 the current line number once before parsing begins, then again
7714 each time the lexer reaches a new line number.
7715
7716 CB can also be a list of the form `(symbol cb ...)' to specify
7717 multiple callbacks with different criteria. Each symbol is a
7718 criterion keyword, and the following element is the callback to
7719 call
7720
7721 :line - called whenever the line number changes
7722 :token - called for each new token consumed
7723
7724 The list of criteria could be extended to include entering or
7725 leaving a statement, an expression, or a function definition."
7726 (if (and cb (not (functionp cb)))
7727 (error "criteria callbacks not yet implemented"))
7728 (let ((inhibit-point-motion-hooks t)
7729 (js2-compiler-xml-available (>= js2-language-version 160))
7730 ;; This is a recursive-descent parser, so give it a big stack.
7731 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7732 (max-specpdl-size (max max-specpdl-size 3000))
7733 (case-fold-search nil)
7734 ast)
7735 (with-current-buffer (or buf (current-buffer))
7736 (setq js2-scanned-comments nil
7737 js2-parsed-errors nil
7738 js2-parsed-warnings nil
7739 js2-imenu-recorder nil
7740 js2-imenu-function-map nil
7741 js2-label-set nil)
7742 (js2-init-scanner)
7743 (setq ast (js2-do-parse))
7744 (unless js2-ts-hit-eof
7745 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7746 (setf (js2-ast-root-errors ast) js2-parsed-errors
7747 (js2-ast-root-warnings ast) js2-parsed-warnings)
7748 ;; if we didn't find any declarations, put a dummy in this list so we
7749 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7750 (unless js2-imenu-recorder
7751 (setq js2-imenu-recorder 'empty))
7752 (run-hooks 'js2-parse-finished-hook)
7753 ast)))
7754
7755 ;; Corresponds to Rhino's Parser.parse() method.
7756 (defun js2-do-parse ()
7757 "Parse current buffer starting from current point.
7758 Scanner should be initialized."
7759 (let ((pos js2-ts-cursor)
7760 (end js2-ts-cursor) ; in case file is empty
7761 root n tt)
7762 ;; initialize buffer-local parsing vars
7763 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7764 js2-current-script-or-fn root
7765 js2-current-scope root
7766 js2-nesting-of-function 0
7767 js2-labeled-stmt nil
7768 js2-recorded-identifiers nil) ; for js2-highlight
7769 (while (/= (setq tt (js2-get-token)) js2-EOF)
7770 (if (= tt js2-FUNCTION)
7771 (progn
7772 (setq n (if js2-called-by-compile-function
7773 (js2-parse-function-expr)
7774 (js2-parse-function-stmt))))
7775 ;; not a function - parse a statement
7776 (js2-unget-token)
7777 (setq n (js2-parse-statement)))
7778 ;; add function or statement to script
7779 (setq end (js2-node-end n))
7780 (js2-block-node-push root n))
7781 ;; add comments to root in lexical order
7782 (when js2-scanned-comments
7783 ;; if we find a comment beyond end of normal kids, use its end
7784 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7785 (dolist (comment js2-scanned-comments)
7786 (push comment (js2-ast-root-comments root))
7787 (js2-node-add-children root comment)))
7788 (setf (js2-node-len root) (- end pos))
7789 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7790 ;; Give extensions a chance to muck with things before highlighting starts.
7791 (let ((js2-additional-externs js2-additional-externs))
7792 (save-excursion
7793 (run-hooks 'js2-post-parse-callbacks))
7794 (js2-highlight-undeclared-vars))
7795 root))
7796
7797 (defun js2-parse-function-closure-body (fn-node)
7798 "Parse a JavaScript 1.8 function closure body."
7799 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7800 (if js2-ts-hit-eof
7801 (js2-report-error "msg.no.brace.body" nil
7802 (js2-node-pos fn-node)
7803 (- js2-ts-cursor (js2-node-pos fn-node)))
7804 (js2-node-add-children fn-node
7805 (setf (js2-function-node-body fn-node)
7806 (js2-parse-expr t))))))
7807
7808 (defun js2-parse-function-body (fn-node)
7809 (js2-must-match js2-LC "msg.no.brace.body"
7810 (js2-node-pos fn-node)
7811 (- js2-ts-cursor (js2-node-pos fn-node)))
7812 (let ((pos (js2-current-token-beg)) ; LC position
7813 (pn (make-js2-block-node)) ; starts at LC position
7814 tt
7815 end)
7816 (cl-incf js2-nesting-of-function)
7817 (unwind-protect
7818 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7819 (= tt js2-EOF)
7820 (= tt js2-RC)))
7821 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7822 (js2-parse-statement)
7823 (js2-get-token)
7824 (js2-parse-function-stmt))))
7825 (cl-decf js2-nesting-of-function))
7826 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7827 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7828 (setq end (js2-current-token-end)))
7829 (setf (js2-node-pos pn) pos
7830 (js2-node-len pn) (- end pos))
7831 (setf (js2-function-node-body fn-node) pn)
7832 (js2-node-add-children fn-node pn)
7833 pn))
7834
7835 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7836 "Declare and fontify destructuring parameters inside NODE.
7837 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7838 (cond
7839 ((js2-name-node-p node)
7840 (let (leftpos)
7841 (js2-define-symbol decl-type (js2-name-node-name node)
7842 node ignore-not-in-block)
7843 (when face
7844 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7845 (+ leftpos (js2-node-len node))
7846 face 'record))))
7847 ((js2-object-node-p node)
7848 (dolist (elem (js2-object-node-elems node))
7849 (js2-define-destruct-symbols
7850 ;; In abbreviated destructuring {a, b}, right == left.
7851 (js2-object-prop-node-right elem)
7852 decl-type face ignore-not-in-block)))
7853 ((js2-array-node-p node)
7854 (dolist (elem (js2-array-node-elems node))
7855 (when elem
7856 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7857 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7858 (js2-node-len node)))))
7859
7860 (defun js2-parse-function-params (function-type fn-node pos)
7861 (if (js2-match-token js2-RP)
7862 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7863 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7864 (eq (js2-current-token-type) js2-NAME)))
7865 params param default-found rest-param-at)
7866 (when paren-free-arrow
7867 (js2-unget-token))
7868 (cl-loop for tt = (js2-peek-token)
7869 do
7870 (cond
7871 ;; destructuring param
7872 ((and (not paren-free-arrow)
7873 (or (= tt js2-LB) (= tt js2-LC)))
7874 (js2-get-token)
7875 (when default-found
7876 (js2-report-error "msg.no.default.after.default.param"))
7877 (setq param (js2-parse-destruct-primary-expr))
7878 (js2-define-destruct-symbols param
7879 js2-LP
7880 'js2-function-param)
7881 (push param params))
7882 ;; variable name
7883 (t
7884 (when (and (>= js2-language-version 200)
7885 (not paren-free-arrow)
7886 (js2-match-token js2-TRIPLEDOT)
7887 (not rest-param-at))
7888 ;; to report errors if there are more parameters
7889 (setq rest-param-at (length params)))
7890 (js2-must-match-name "msg.no.parm")
7891 (js2-record-face 'js2-function-param)
7892 (setq param (js2-create-name-node))
7893 (js2-define-symbol js2-LP (js2-current-token-string) param)
7894 ;; default parameter value
7895 (when (or (and default-found
7896 (not rest-param-at)
7897 (js2-must-match js2-ASSIGN
7898 "msg.no.default.after.default.param"
7899 (js2-node-pos param)
7900 (js2-node-len param)))
7901 (and (>= js2-language-version 200)
7902 (js2-match-token js2-ASSIGN)))
7903 (cl-assert (not paren-free-arrow))
7904 (let* ((pos (js2-node-pos param))
7905 (tt (js2-current-token-type))
7906 (op-pos (- (js2-current-token-beg) pos))
7907 (left param)
7908 (right (js2-parse-assign-expr))
7909 (len (- (js2-node-end right) pos)))
7910 (setq param (make-js2-assign-node
7911 :type tt :pos pos :len len :op-pos op-pos
7912 :left left :right right)
7913 default-found t)
7914 (js2-node-add-children param left right)))
7915 (push param params)))
7916 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7917 (js2-report-error "msg.param.after.rest" nil
7918 (js2-node-pos param) (js2-node-len param)))
7919 while
7920 (js2-match-token js2-COMMA))
7921 (when (and (not paren-free-arrow)
7922 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7923 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7924 (when rest-param-at
7925 (setf (js2-function-node-rest-p fn-node) t))
7926 (dolist (p params)
7927 (js2-node-add-children fn-node p)
7928 (push p (js2-function-node-params fn-node))))))
7929
7930 (defun js2-check-inconsistent-return-warning (fn-node name)
7931 "Possibly show inconsistent-return warning.
7932 Last token scanned is the close-curly for the function body."
7933 (when (and js2-mode-show-strict-warnings
7934 js2-strict-inconsistent-return-warning
7935 (not (js2-has-consistent-return-usage
7936 (js2-function-node-body fn-node))))
7937 ;; Have it extend from close-curly to bol or beginning of block.
7938 (let ((pos (save-excursion
7939 (goto-char (js2-current-token-end))
7940 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7941 (point-at-bol))))
7942 (end (js2-current-token-end)))
7943 (if (cl-plusp (js2-name-node-length name))
7944 (js2-add-strict-warning "msg.no.return.value"
7945 (js2-name-node-name name) pos end)
7946 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7947
7948 (defun js2-parse-function-stmt ()
7949 (let ((pos (js2-current-token-beg))
7950 (star-p (js2-match-token js2-MUL)))
7951 (js2-must-match-name "msg.unnamed.function.stmt")
7952 (let ((name (js2-create-name-node t))
7953 pn member-expr)
7954 (cond
7955 ((js2-match-token js2-LP)
7956 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7957 (js2-allow-member-expr-as-function-name
7958 (setq member-expr (js2-parse-member-expr-tail nil name))
7959 (js2-parse-highlight-member-expr-fn-name member-expr)
7960 (js2-must-match js2-LP "msg.no.paren.parms")
7961 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7962 (js2-function-node-member-expr pn) member-expr)
7963 pn)
7964 (t
7965 (js2-report-error "msg.no.paren.parms")
7966 (make-js2-error-node))))))
7967
7968 (defun js2-parse-function-expr ()
7969 (let ((pos (js2-current-token-beg))
7970 (star-p (js2-match-token js2-MUL))
7971 name)
7972 (when (js2-match-token js2-NAME)
7973 (setq name (js2-create-name-node t)))
7974 (js2-must-match js2-LP "msg.no.paren.parms")
7975 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7976
7977 (defun js2-parse-function (function-type pos star-p &optional name)
7978 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7979 beginning of the first token (function keyword, unless it's an
7980 arrow function), NAME is js2-name-node."
7981 (let (fn-node lp)
7982 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7983 (setq lp (js2-current-token-beg)))
7984 (setf fn-node (make-js2-function-node :pos pos
7985 :name name
7986 :form function-type
7987 :lp (if lp (- lp pos))
7988 :generator-type (and star-p 'STAR)))
7989 (when name
7990 (js2-set-face (js2-node-pos name) (js2-node-end name)
7991 'font-lock-function-name-face 'record)
7992 (when (and (eq function-type 'FUNCTION_STATEMENT)
7993 (cl-plusp (js2-name-node-length name)))
7994 ;; Function statements define a symbol in the enclosing scope
7995 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7996 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
7997 ;; 1. Nested functions are not affected by the dynamic scope flag
7998 ;; as dynamic scope is already a parent of their scope.
7999 ;; 2. Functions defined under the with statement also immune to
8000 ;; this setup, in which case dynamic scope is ignored in favor
8001 ;; of the with object.
8002 (setf (js2-function-node-ignore-dynamic fn-node) t))
8003 ;; dynamically bind all the per-function variables
8004 (let ((js2-current-script-or-fn fn-node)
8005 (js2-current-scope fn-node)
8006 (js2-nesting-of-with 0)
8007 (js2-end-flags 0)
8008 js2-label-set
8009 js2-loop-set
8010 js2-loop-and-switch-set)
8011 (js2-parse-function-params function-type fn-node pos)
8012 (when (eq function-type 'FUNCTION_ARROW)
8013 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8014 (if (and (>= js2-language-version 180)
8015 (/= (js2-peek-token) js2-LC))
8016 (js2-parse-function-closure-body fn-node)
8017 (js2-parse-function-body fn-node))
8018 (js2-check-inconsistent-return-warning fn-node name)
8019
8020 (when name
8021 (js2-node-add-children fn-node name)
8022 ;; Function expressions define a name only in the body of the
8023 ;; function, and only if not hidden by a parameter name
8024 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8025 (null (js2-scope-get-symbol js2-current-scope
8026 (js2-name-node-name name))))
8027 (js2-define-symbol js2-FUNCTION
8028 (js2-name-node-name name)
8029 fn-node))
8030 (when (eq function-type 'FUNCTION_STATEMENT)
8031 (js2-record-imenu-functions fn-node))))
8032
8033 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8034 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8035 ;; We wait until after parsing the function to set its parent scope,
8036 ;; since `js2-define-symbol' needs the defining-scope check to stop
8037 ;; at the function boundary when checking for redeclarations.
8038 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8039 fn-node))
8040
8041 (defun js2-parse-statements (&optional parent)
8042 "Parse a statement list. Last token consumed must be js2-LC.
8043
8044 PARENT can be a `js2-block-node', in which case the statements are
8045 appended to PARENT. Otherwise a new `js2-block-node' is created
8046 and returned.
8047
8048 This function does not match the closing js2-RC: the caller
8049 matches the RC so it can provide a suitable error message if not
8050 matched. This means it's up to the caller to set the length of
8051 the node to include the closing RC. The node start pos is set to
8052 the absolute buffer start position, and the caller should fix it
8053 up to be relative to the parent node. All children of this block
8054 node are given relative start positions and correct lengths."
8055 (let ((pn (or parent (make-js2-block-node)))
8056 tt)
8057 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8058 (/= tt js2-RC))
8059 (js2-block-node-push pn (js2-parse-statement)))
8060 pn))
8061
8062 (defun js2-parse-statement ()
8063 (let (pn beg end)
8064 ;; coarse-grained user-interrupt check - needs work
8065 (and js2-parse-interruptable-p
8066 (zerop (% (cl-incf js2-parse-stmt-count)
8067 js2-statements-per-pause))
8068 (input-pending-p)
8069 (throw 'interrupted t))
8070 (setq pn (js2-statement-helper))
8071 ;; no-side-effects warning check
8072 (unless (js2-node-has-side-effects pn)
8073 (setq end (js2-node-end pn))
8074 (save-excursion
8075 (goto-char end)
8076 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8077 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8078 pn))
8079
8080 ;; These correspond to the switch cases in Parser.statementHelper
8081 (defconst js2-parsers
8082 (let ((parsers (make-vector js2-num-tokens
8083 #'js2-parse-expr-stmt)))
8084 (aset parsers js2-BREAK #'js2-parse-break)
8085 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8086 (aset parsers js2-CONST #'js2-parse-const-var)
8087 (aset parsers js2-CONTINUE #'js2-parse-continue)
8088 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8089 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8090 (aset parsers js2-DO #'js2-parse-do)
8091 (aset parsers js2-EXPORT #'js2-parse-export)
8092 (aset parsers js2-FOR #'js2-parse-for)
8093 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8094 (aset parsers js2-IF #'js2-parse-if)
8095 (aset parsers js2-IMPORT #'js2-parse-import)
8096 (aset parsers js2-LC #'js2-parse-block)
8097 (aset parsers js2-LET #'js2-parse-let-stmt)
8098 (aset parsers js2-NAME #'js2-parse-name-or-label)
8099 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8100 (aset parsers js2-SEMI #'js2-parse-semi)
8101 (aset parsers js2-SWITCH #'js2-parse-switch)
8102 (aset parsers js2-THROW #'js2-parse-throw)
8103 (aset parsers js2-TRY #'js2-parse-try)
8104 (aset parsers js2-VAR #'js2-parse-const-var)
8105 (aset parsers js2-WHILE #'js2-parse-while)
8106 (aset parsers js2-WITH #'js2-parse-with)
8107 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8108 parsers)
8109 "A vector mapping token types to parser functions.")
8110
8111 (defun js2-parse-warn-missing-semi (beg end)
8112 (and js2-mode-show-strict-warnings
8113 js2-strict-missing-semi-warning
8114 (js2-add-strict-warning
8115 "msg.missing.semi" nil
8116 ;; back up to beginning of statement or line
8117 (max beg (save-excursion
8118 (goto-char end)
8119 (point-at-bol)))
8120 end)))
8121
8122 (defconst js2-no-semi-insertion
8123 (list js2-IF
8124 js2-SWITCH
8125 js2-WHILE
8126 js2-DO
8127 js2-FOR
8128 js2-TRY
8129 js2-WITH
8130 js2-LC
8131 js2-ERROR
8132 js2-SEMI
8133 js2-CLASS
8134 js2-FUNCTION
8135 js2-EXPORT)
8136 "List of tokens that don't do automatic semicolon insertion.")
8137
8138 (defconst js2-autoinsert-semi-and-warn
8139 (list js2-ERROR js2-EOF js2-RC))
8140
8141 (defun js2-statement-helper ()
8142 (let* ((tt (js2-get-token))
8143 (first-tt tt)
8144 (parser (if (= tt js2-ERROR)
8145 #'js2-parse-semi
8146 (aref js2-parsers tt)))
8147 pn)
8148 ;; If the statement is set, then it's been told its label by now.
8149 (and js2-labeled-stmt
8150 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8151 (setq js2-labeled-stmt nil))
8152 (setq pn (funcall parser))
8153 ;; Don't do auto semi insertion for certain statement types.
8154 (unless (or (memq first-tt js2-no-semi-insertion)
8155 (js2-labeled-stmt-node-p pn))
8156 (js2-auto-insert-semicolon pn))
8157 pn))
8158
8159 (defun js2-auto-insert-semicolon (pn)
8160 (let* ((tt (js2-get-token))
8161 (pos (js2-node-pos pn)))
8162 (cond
8163 ((= tt js2-SEMI)
8164 ;; extend the node bounds to include the semicolon.
8165 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8166 ((memq tt js2-autoinsert-semi-and-warn)
8167 (js2-unget-token) ; Not ';', do not consume.
8168 ;; Autoinsert ;
8169 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8170 (t
8171 (if (not (js2-token-follows-eol-p (js2-current-token)))
8172 ;; Report error if no EOL or autoinsert ';' otherwise
8173 (js2-report-error "msg.no.semi.stmt")
8174 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8175 (js2-unget-token) ; Not ';', do not consume.
8176 ))))
8177
8178 (defun js2-parse-condition ()
8179 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8180 The parens are discarded and the expression node is returned.
8181 The `pos' field of the return value is set to an absolute position
8182 that must be fixed up by the caller.
8183 Return value is a list (EXPR LP RP), with absolute paren positions."
8184 (let (pn lp rp)
8185 (if (js2-must-match js2-LP "msg.no.paren.cond")
8186 (setq lp (js2-current-token-beg)))
8187 (setq pn (js2-parse-expr))
8188 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8189 (setq rp (js2-current-token-beg)))
8190 ;; Report strict warning on code like "if (a = 7) ..."
8191 (if (and js2-strict-cond-assign-warning
8192 (js2-assign-node-p pn))
8193 (js2-add-strict-warning "msg.equal.as.assign" nil
8194 (js2-node-pos pn)
8195 (+ (js2-node-pos pn)
8196 (js2-node-len pn))))
8197 (list pn lp rp)))
8198
8199 (defun js2-parse-if ()
8200 "Parser for if-statement. Last matched token must be js2-IF."
8201 (let ((pos (js2-current-token-beg))
8202 cond if-true if-false else-pos end pn)
8203 (setq cond (js2-parse-condition)
8204 if-true (js2-parse-statement)
8205 if-false (if (js2-match-token js2-ELSE)
8206 (progn
8207 (setq else-pos (- (js2-current-token-beg) pos))
8208 (js2-parse-statement)))
8209 end (js2-node-end (or if-false if-true))
8210 pn (make-js2-if-node :pos pos
8211 :len (- end pos)
8212 :condition (car cond)
8213 :then-part if-true
8214 :else-part if-false
8215 :else-pos else-pos
8216 :lp (js2-relpos (cl-second cond) pos)
8217 :rp (js2-relpos (cl-third cond) pos)))
8218 (js2-node-add-children pn (car cond) if-true if-false)
8219 pn))
8220
8221 (defun js2-parse-import ()
8222 "Parse import statement. The current token must be js2-IMPORT."
8223 (unless (js2-ast-root-p js2-current-scope)
8224 (js2-report-error "msg.mod.import.decl.at.top.level"))
8225 (let ((beg (js2-current-token-beg)))
8226 (cond ((js2-match-token js2-STRING)
8227 (make-js2-import-node
8228 :pos beg
8229 :len (- (js2-current-token-end) beg)
8230 :module-id (js2-current-token-string)))
8231 (t
8232 (let* ((import-clause (js2-parse-import-clause))
8233 (from-clause (and import-clause (js2-parse-from-clause)))
8234 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8235 (node (make-js2-import-node
8236 :pos beg
8237 :len (- (js2-current-token-end) beg)
8238 :import import-clause
8239 :from from-clause
8240 :module-id module-id)))
8241 (when import-clause
8242 (js2-node-add-children node import-clause))
8243 (when from-clause
8244 (js2-node-add-children node from-clause))
8245 node)))))
8246
8247 (defun js2-parse-import-clause ()
8248 "Parse the bindings in an import statement.
8249 This can take many forms:
8250
8251 ImportedDefaultBinding -> 'foo'
8252 NameSpaceImport -> '* as lib'
8253 NamedImports -> '{foo as bar, bang}'
8254 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8255 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8256
8257 Try to match namespace imports and named imports first because nothing can
8258 come after them. If it is an imported default binding, then it could have named
8259 imports or a namespace import that follows it.
8260 "
8261 (let* ((beg (js2-current-token-beg))
8262 (clause (make-js2-import-clause-node
8263 :pos beg))
8264 (children (list)))
8265 (cond
8266 ((js2-match-token js2-MUL)
8267 (let ((ns-import (js2-parse-namespace-import)))
8268 (when ns-import
8269 (let ((name-node (js2-namespace-import-node-name ns-import)))
8270 (js2-define-symbol
8271 js2-LET (js2-name-node-name name-node) name-node t)))
8272 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8273 (push ns-import children)))
8274 ((js2-match-token js2-LC)
8275 (let ((imports (js2-parse-export-bindings t)))
8276 (setf (js2-import-clause-node-named-imports clause) imports)
8277 (dolist (import imports)
8278 (push import children)
8279 (let ((name-node (js2-export-binding-node-local-name import)))
8280 (when name-node
8281 (js2-define-symbol
8282 js2-LET (js2-name-node-name name-node) name-node t))))))
8283 ((= (js2-peek-token) js2-NAME)
8284 (let ((binding (js2-maybe-parse-export-binding)))
8285 (let ((node-name (js2-export-binding-node-local-name binding)))
8286 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8287 (setf (js2-import-clause-node-default-binding clause) binding)
8288 (push binding children))
8289 (when (js2-match-token js2-COMMA)
8290 (cond
8291 ((js2-match-token js2-MUL)
8292 (let ((ns-import (js2-parse-namespace-import)))
8293 (let ((name-node (js2-namespace-import-node-name ns-import)))
8294 (js2-define-symbol
8295 js2-LET (js2-name-node-name name-node) name-node t))
8296 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8297 (push ns-import children)))
8298 ((js2-match-token js2-LC)
8299 (let ((imports (js2-parse-export-bindings t)))
8300 (setf (js2-import-clause-node-named-imports clause) imports)
8301 (dolist (import imports)
8302 (push import children)
8303 (let ((name-node (js2-export-binding-node-local-name import)))
8304 (when name-node
8305 (js2-define-symbol
8306 js2-LET (js2-name-node-name name-node) name-node t))))))
8307 (t (js2-report-error "msg.syntax")))))
8308 (t (js2-report-error "msg.mod.declaration.after.import")))
8309 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8310 (apply #'js2-node-add-children clause children)
8311 clause))
8312
8313 (defun js2-parse-namespace-import ()
8314 "Parse a namespace import expression such as '* as bar'.
8315 The current token must be js2-MUL."
8316 (let ((beg (js2-current-token-beg)))
8317 (when (js2-must-match js2-NAME "msg.syntax")
8318 (if (equal "as" (js2-current-token-string))
8319 (when (js2-must-match-prop-name "msg.syntax")
8320 (let ((node (make-js2-namespace-import-node
8321 :pos beg
8322 :len (- (js2-current-token-end) beg)
8323 :name (make-js2-name-node
8324 :pos (js2-current-token-beg)
8325 :len (js2-current-token-end)
8326 :name (js2-current-token-string)))))
8327 (js2-node-add-children node (js2-namespace-import-node-name node))
8328 node))
8329 (js2-unget-token)
8330 (js2-report-error "msg.syntax")))))
8331
8332
8333 (defun js2-parse-from-clause ()
8334 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8335 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8336 (let ((beg (js2-current-token-beg)))
8337 (if (equal "from" (js2-current-token-string))
8338 (cond
8339 ((js2-match-token js2-STRING)
8340 (make-js2-from-clause-node
8341 :pos beg
8342 :len (- (js2-current-token-end) beg)
8343 :module-id (js2-current-token-string)
8344 :metadata-p nil))
8345 ((js2-match-token js2-THIS)
8346 (when (js2-must-match-name "msg.mod.spec.after.from")
8347 (if (equal "module" (js2-current-token-string))
8348 (make-js2-from-clause-node
8349 :pos beg
8350 :len (- (js2-current-token-end) beg)
8351 :module-id "this"
8352 :metadata-p t)
8353 (js2-unget-token)
8354 (js2-unget-token)
8355 (js2-report-error "msg.mod.spec.after.from")
8356 nil)))
8357 (t (js2-report-error "msg.mod.spec.after.from") nil))
8358 (js2-unget-token)
8359 (js2-report-error "msg.mod.from.after.import.spec.set")
8360 nil))))
8361
8362 (defun js2-parse-export-bindings (&optional import-p)
8363 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8364 {foo as bar, baz as bang}. The current token must be
8365 js2-LC. Return a lisp list of js2-export-binding-node"
8366 (let ((bindings (list)))
8367 (while
8368 (let ((binding (js2-maybe-parse-export-binding)))
8369 (when binding
8370 (push binding bindings))
8371 (js2-match-token js2-COMMA)))
8372 (when (js2-must-match js2-RC (if import-p
8373 "msg.mod.rc.after.import.spec.list"
8374 "msg.mod.rc.after.export.spec.list"))
8375 (reverse bindings))))
8376
8377 (defun js2-maybe-parse-export-binding ()
8378 "Attempt to parse a binding expression found inside an import/export statement.
8379 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8380 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8381 js2-export-binding-node and consume all the tokens. If it does not match, it
8382 consumes no tokens."
8383 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8384 (beg (js2-current-token-beg))
8385 (extern-name-len (js2-current-token-len))
8386 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8387 (aref js2-kwd-tokens (js2-current-token-type)))))
8388 (if extern-name
8389 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8390 (if (and as (equal "as" (js2-current-token-string)))
8391 (let ((name
8392 (or
8393 (and (js2-match-token js2-DEFAULT) "default")
8394 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8395 (if name
8396 (let ((node (make-js2-export-binding-node
8397 :pos beg
8398 :len (- (js2-current-token-end) beg)
8399 :local-name (make-js2-name-node
8400 :name name
8401 :pos (js2-current-token-beg)
8402 :len (js2-current-token-len))
8403 :extern-name (make-js2-name-node
8404 :name extern-name
8405 :pos beg
8406 :len extern-name-len))))
8407 (js2-node-add-children
8408 node
8409 (js2-export-binding-node-local-name node)
8410 (js2-export-binding-node-extern-name node))
8411 node)
8412 (js2-unget-token)
8413 nil))
8414 (when as (js2-unget-token))
8415 (let* ((name-node (make-js2-name-node
8416 :name (js2-current-token-string)
8417 :pos (js2-current-token-beg)
8418 :len (js2-current-token-len)))
8419 (node (make-js2-export-binding-node
8420 :pos (js2-current-token-beg)
8421 :len (js2-current-token-len)
8422 :local-name name-node
8423 :extern-name name-node)))
8424 (when is-reserved-name
8425 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8426 (js2-node-add-children node name-node)
8427 node)))
8428 nil)))
8429
8430 (defun js2-parse-switch ()
8431 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8432 (let ((pos (js2-current-token-beg))
8433 tt pn discriminant has-default case-expr case-node
8434 case-pos cases stmt lp)
8435 (if (js2-must-match js2-LP "msg.no.paren.switch")
8436 (setq lp (js2-current-token-beg)))
8437 (setq discriminant (js2-parse-expr)
8438 pn (make-js2-switch-node :discriminant discriminant
8439 :pos pos
8440 :lp (js2-relpos lp pos)))
8441 (js2-node-add-children pn discriminant)
8442 (js2-enter-switch pn)
8443 (unwind-protect
8444 (progn
8445 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8446 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8447 (js2-must-match js2-LC "msg.no.brace.switch")
8448 (catch 'break
8449 (while t
8450 (setq tt (js2-next-token)
8451 case-pos (js2-current-token-beg))
8452 (cond
8453 ((= tt js2-RC)
8454 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8455 (throw 'break nil)) ; done
8456 ((= tt js2-CASE)
8457 (setq case-expr (js2-parse-expr))
8458 (js2-must-match js2-COLON "msg.no.colon.case"))
8459 ((= tt js2-DEFAULT)
8460 (if has-default
8461 (js2-report-error "msg.double.switch.default"))
8462 (setq has-default t
8463 case-expr nil)
8464 (js2-must-match js2-COLON "msg.no.colon.case"))
8465 (t
8466 (js2-report-error "msg.bad.switch")
8467 (throw 'break nil)))
8468 (setq case-node (make-js2-case-node :pos case-pos
8469 :len (- (js2-current-token-end) case-pos)
8470 :expr case-expr))
8471 (js2-node-add-children case-node case-expr)
8472 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8473 (/= tt js2-CASE)
8474 (/= tt js2-DEFAULT)
8475 (/= tt js2-EOF))
8476 (setf stmt (js2-parse-statement)
8477 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8478 (js2-block-node-push case-node stmt))
8479 (push case-node cases)))
8480 ;; add cases last, as pushing reverses the order to be correct
8481 (dolist (kid cases)
8482 (js2-node-add-children pn kid)
8483 (push kid (js2-switch-node-cases pn)))
8484 pn) ; return value
8485 (js2-exit-switch))))
8486
8487 (defun js2-parse-while ()
8488 "Parser for while-statement. Last matched token must be js2-WHILE."
8489 (let ((pos (js2-current-token-beg))
8490 (pn (make-js2-while-node))
8491 cond body)
8492 (js2-enter-loop pn)
8493 (unwind-protect
8494 (progn
8495 (setf cond (js2-parse-condition)
8496 (js2-while-node-condition pn) (car cond)
8497 body (js2-parse-statement)
8498 (js2-while-node-body pn) body
8499 (js2-node-len pn) (- (js2-node-end body) pos)
8500 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8501 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8502 (js2-node-add-children pn body (car cond)))
8503 (js2-exit-loop))
8504 pn))
8505
8506 (defun js2-parse-do ()
8507 "Parser for do-statement. Last matched token must be js2-DO."
8508 (let ((pos (js2-current-token-beg))
8509 (pn (make-js2-do-node))
8510 cond body end)
8511 (js2-enter-loop pn)
8512 (unwind-protect
8513 (progn
8514 (setq body (js2-parse-statement))
8515 (js2-must-match js2-WHILE "msg.no.while.do")
8516 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8517 cond (js2-parse-condition)
8518 (js2-do-node-condition pn) (car cond)
8519 (js2-do-node-body pn) body
8520 end js2-ts-cursor
8521 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8522 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8523 (js2-node-add-children pn (car cond) body))
8524 (js2-exit-loop))
8525 ;; Always auto-insert semicolon to follow SpiderMonkey:
8526 ;; It is required by ECMAScript but is ignored by the rest of
8527 ;; world; see bug 238945
8528 (if (js2-match-token js2-SEMI)
8529 (setq end js2-ts-cursor))
8530 (setf (js2-node-len pn) (- end pos))
8531 pn))
8532
8533 (defun js2-parse-export ()
8534 "Parse an export statement.
8535 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8536 expressions should only be either hoistable expressions (function or generator)
8537 or assignment expressions, but there is no checking to enforce that and so it
8538 will parse without error a small subset of
8539 invalid export statements."
8540 (unless (js2-ast-root-p js2-current-scope)
8541 (js2-report-error "msg.mod.export.decl.at.top.level"))
8542 (let ((beg (js2-current-token-beg))
8543 (children (list))
8544 exports-list from-clause declaration default)
8545 (cond
8546 ((js2-match-token js2-MUL)
8547 (setq from-clause (js2-parse-from-clause))
8548 (when from-clause
8549 (push from-clause children)))
8550 ((js2-match-token js2-LC)
8551 (setq exports-list (js2-parse-export-bindings))
8552 (when exports-list
8553 (dolist (export exports-list)
8554 (push export children)))
8555 (when (js2-match-token js2-NAME)
8556 (if (equal "from" (js2-current-token-string))
8557 (progn
8558 (js2-unget-token)
8559 (setq from-clause (js2-parse-from-clause)))
8560 (js2-unget-token))))
8561 ((js2-match-token js2-DEFAULT)
8562 (setq default (js2-parse-expr)))
8563 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8564 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8565 (t
8566 (setq declaration (js2-parse-expr))))
8567 (when from-clause
8568 (push from-clause children))
8569 (when declaration
8570 (push declaration children)
8571 (when (not (js2-function-node-p declaration))
8572 (js2-auto-insert-semicolon declaration)))
8573 (when default
8574 (push default children)
8575 (when (not (js2-function-node-p default))
8576 (js2-auto-insert-semicolon default)))
8577 (let ((node (make-js2-export-node
8578 :pos beg
8579 :len (- (js2-current-token-end) beg)
8580 :exports-list exports-list
8581 :from-clause from-clause
8582 :declaration declaration
8583 :default default)))
8584 (apply #'js2-node-add-children node children)
8585 node)))
8586
8587 (defun js2-parse-for ()
8588 "Parse a for, for-in or for each-in statement.
8589 Last matched token must be js2-FOR."
8590 (let ((for-pos (js2-current-token-beg))
8591 (tmp-scope (make-js2-scope))
8592 pn is-for-each is-for-in-or-of is-for-of
8593 in-pos each-pos tmp-pos
8594 init ; Node init is also foo in 'foo in object'.
8595 cond ; Node cond is also object in 'foo in object'.
8596 incr ; 3rd section of for-loop initializer.
8597 body tt lp rp)
8598 ;; See if this is a for each () instead of just a for ()
8599 (when (js2-match-token js2-NAME)
8600 (if (string= "each" (js2-current-token-string))
8601 (progn
8602 (setq is-for-each t
8603 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8604 (js2-record-face 'font-lock-keyword-face))
8605 (js2-report-error "msg.no.paren.for")))
8606 (if (js2-must-match js2-LP "msg.no.paren.for")
8607 (setq lp (- (js2-current-token-beg) for-pos)))
8608 (setq tt (js2-get-token))
8609 ;; Capture identifiers inside parens. We can't create the node
8610 ;; (and use it as the current scope) until we know its type.
8611 (js2-push-scope tmp-scope)
8612 (unwind-protect
8613 (progn
8614 ;; parse init clause
8615 (let ((js2-in-for-init t)) ; set as dynamic variable
8616 (cond
8617 ((= tt js2-SEMI)
8618 (js2-unget-token)
8619 (setq init (make-js2-empty-expr-node)))
8620 ((or (= tt js2-VAR) (= tt js2-LET))
8621 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8622 (t
8623 (js2-unget-token)
8624 (setq init (js2-parse-expr)))))
8625 (if (or (js2-match-token js2-IN)
8626 (and (>= js2-language-version 200)
8627 (js2-match-contextual-kwd "of")
8628 (setq is-for-of t)))
8629 (setq is-for-in-or-of t
8630 in-pos (- (js2-current-token-beg) for-pos)
8631 ;; scope of iteration target object is not the scope we've created above.
8632 ;; stash current scope temporary.
8633 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8634 (js2-parse-expr))) ; object over which we're iterating
8635 ;; else ordinary for loop - parse cond and incr
8636 (js2-must-match js2-SEMI "msg.no.semi.for")
8637 (setq cond (if (= (js2-peek-token) js2-SEMI)
8638 (make-js2-empty-expr-node) ; no loop condition
8639 (js2-parse-expr)))
8640 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8641 (setq tmp-pos (js2-current-token-end)
8642 incr (if (= (js2-peek-token) js2-RP)
8643 (make-js2-empty-expr-node :pos tmp-pos)
8644 (js2-parse-expr)))))
8645 (js2-pop-scope))
8646 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8647 (setq rp (- (js2-current-token-beg) for-pos)))
8648 (if (not is-for-in-or-of)
8649 (setq pn (make-js2-for-node :init init
8650 :condition cond
8651 :update incr
8652 :lp lp
8653 :rp rp))
8654 ;; cond could be null if 'in obj' got eaten by the init node.
8655 (if (js2-infix-node-p init)
8656 ;; it was (foo in bar) instead of (var foo in bar)
8657 (setq cond (js2-infix-node-right init)
8658 init (js2-infix-node-left init))
8659 (if (and (js2-var-decl-node-p init)
8660 (> (length (js2-var-decl-node-kids init)) 1))
8661 (js2-report-error "msg.mult.index")))
8662 (setq pn (make-js2-for-in-node :iterator init
8663 :object cond
8664 :in-pos in-pos
8665 :foreach-p is-for-each
8666 :each-pos each-pos
8667 :forof-p is-for-of
8668 :lp lp
8669 :rp rp)))
8670 ;; Transplant the declarations.
8671 (setf (js2-scope-symbol-table pn)
8672 (js2-scope-symbol-table tmp-scope))
8673 (unwind-protect
8674 (progn
8675 (js2-enter-loop pn)
8676 ;; We have to parse the body -after- creating the loop node,
8677 ;; so that the loop node appears in the js2-loop-set, allowing
8678 ;; break/continue statements to find the enclosing loop.
8679 (setf body (js2-parse-statement)
8680 (js2-loop-node-body pn) body
8681 (js2-node-pos pn) for-pos
8682 (js2-node-len pn) (- (js2-node-end body) for-pos))
8683 (js2-node-add-children pn init cond incr body))
8684 ;; finally
8685 (js2-exit-loop))
8686 pn))
8687
8688 (defun js2-parse-try ()
8689 "Parse a try statement. Last matched token must be js2-TRY."
8690 (let ((try-pos (js2-current-token-beg))
8691 try-end
8692 try-block
8693 catch-blocks
8694 finally-block
8695 saw-default-catch
8696 peek)
8697 (if (/= (js2-peek-token) js2-LC)
8698 (js2-report-error "msg.no.brace.try"))
8699 (setq try-block (js2-parse-statement)
8700 try-end (js2-node-end try-block)
8701 peek (js2-peek-token))
8702 (cond
8703 ((= peek js2-CATCH)
8704 (while (js2-match-token js2-CATCH)
8705 (let* ((catch-pos (js2-current-token-beg))
8706 (catch-node (make-js2-catch-node :pos catch-pos))
8707 param
8708 guard-kwd
8709 catch-cond
8710 lp rp)
8711 (if saw-default-catch
8712 (js2-report-error "msg.catch.unreachable"))
8713 (if (js2-must-match js2-LP "msg.no.paren.catch")
8714 (setq lp (- (js2-current-token-beg) catch-pos)))
8715 (js2-push-scope catch-node)
8716 (let ((tt (js2-peek-token)))
8717 (cond
8718 ;; Destructuring pattern:
8719 ;; catch ({ message, file }) { ... }
8720 ((or (= tt js2-LB) (= tt js2-LC))
8721 (js2-get-token)
8722 (setq param (js2-parse-destruct-primary-expr))
8723 (js2-define-destruct-symbols param js2-LET nil))
8724 ;; Simple name.
8725 (t
8726 (js2-must-match-name "msg.bad.catchcond")
8727 (setq param (js2-create-name-node))
8728 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8729 ;; Catch condition.
8730 (if (js2-match-token js2-IF)
8731 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8732 catch-cond (js2-parse-expr))
8733 (setq saw-default-catch t))
8734 (if (js2-must-match js2-RP "msg.bad.catchcond")
8735 (setq rp (- (js2-current-token-beg) catch-pos)))
8736 (js2-must-match js2-LC "msg.no.brace.catchblock")
8737 (js2-parse-statements catch-node)
8738 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8739 (setq try-end (js2-current-token-end)))
8740 (js2-pop-scope)
8741 (setf (js2-node-len catch-node) (- try-end catch-pos)
8742 (js2-catch-node-param catch-node) param
8743 (js2-catch-node-guard-expr catch-node) catch-cond
8744 (js2-catch-node-guard-kwd catch-node) guard-kwd
8745 (js2-catch-node-lp catch-node) lp
8746 (js2-catch-node-rp catch-node) rp)
8747 (js2-node-add-children catch-node param catch-cond)
8748 (push catch-node catch-blocks))))
8749 ((/= peek js2-FINALLY)
8750 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8751 (js2-node-pos try-block)
8752 (- (setq try-end (js2-node-end try-block))
8753 (js2-node-pos try-block)))))
8754 (when (js2-match-token js2-FINALLY)
8755 (let ((finally-pos (js2-current-token-beg))
8756 (block (js2-parse-statement)))
8757 (setq try-end (js2-node-end block)
8758 finally-block (make-js2-finally-node :pos finally-pos
8759 :len (- try-end finally-pos)
8760 :body block))
8761 (js2-node-add-children finally-block block)))
8762 (let ((pn (make-js2-try-node :pos try-pos
8763 :len (- try-end try-pos)
8764 :try-block try-block
8765 :finally-block finally-block)))
8766 (js2-node-add-children pn try-block finally-block)
8767 ;; Push them onto the try-node, which reverses and corrects their order.
8768 (dolist (cb catch-blocks)
8769 (js2-node-add-children pn cb)
8770 (push cb (js2-try-node-catch-clauses pn)))
8771 pn)))
8772
8773 (defun js2-parse-throw ()
8774 "Parser for throw-statement. Last matched token must be js2-THROW."
8775 (let ((pos (js2-current-token-beg))
8776 expr pn)
8777 (if (= (js2-peek-token-or-eol) js2-EOL)
8778 ;; ECMAScript does not allow new lines before throw expression,
8779 ;; see bug 256617
8780 (js2-report-error "msg.bad.throw.eol"))
8781 (setq expr (js2-parse-expr)
8782 pn (make-js2-throw-node :pos pos
8783 :len (- (js2-node-end expr) pos)
8784 :expr expr))
8785 (js2-node-add-children pn expr)
8786 pn))
8787
8788 (defun js2-match-jump-label-name (label-name)
8789 "If break/continue specified a label, return that label's labeled stmt.
8790 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8791 does not match an existing label, reports an error and returns nil."
8792 (let ((bundle (cdr (assoc label-name js2-label-set))))
8793 (if (null bundle)
8794 (js2-report-error "msg.undef.label"))
8795 bundle))
8796
8797 (defun js2-parse-break ()
8798 "Parser for break-statement. Last matched token must be js2-BREAK."
8799 (let ((pos (js2-current-token-beg))
8800 (end (js2-current-token-end))
8801 break-target ; statement to break from
8802 break-label ; in "break foo", name-node representing the foo
8803 labels ; matching labeled statement to break to
8804 pn)
8805 (when (eq (js2-peek-token-or-eol) js2-NAME)
8806 (js2-get-token)
8807 (setq break-label (js2-create-name-node)
8808 end (js2-node-end break-label)
8809 ;; matchJumpLabelName only matches if there is one
8810 labels (js2-match-jump-label-name (js2-current-token-string))
8811 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8812 (unless (or break-target break-label)
8813 ;; no break target specified - try for innermost enclosing loop/switch
8814 (if (null js2-loop-and-switch-set)
8815 (unless break-label
8816 (js2-report-error "msg.bad.break" nil pos (length "break")))
8817 (setq break-target (car js2-loop-and-switch-set))))
8818 (setq pn (make-js2-break-node :pos pos
8819 :len (- end pos)
8820 :label break-label
8821 :target break-target))
8822 (js2-node-add-children pn break-label) ; but not break-target
8823 pn))
8824
8825 (defun js2-parse-continue ()
8826 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8827 (let ((pos (js2-current-token-beg))
8828 (end (js2-current-token-end))
8829 label ; optional user-specified label, a `js2-name-node'
8830 labels ; current matching labeled stmt, if any
8831 target ; the `js2-loop-node' target of this continue stmt
8832 pn)
8833 (when (= (js2-peek-token-or-eol) js2-NAME)
8834 (js2-get-token)
8835 (setq label (js2-create-name-node)
8836 end (js2-node-end label)
8837 ;; matchJumpLabelName only matches if there is one
8838 labels (js2-match-jump-label-name (js2-current-token-string))))
8839 (cond
8840 ((null labels) ; no current label to go to
8841 (if (null js2-loop-set) ; no loop to continue to
8842 (js2-report-error "msg.continue.outside" nil pos
8843 (length "continue"))
8844 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8845 (t
8846 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8847 (setq target (js2-labeled-stmt-node-stmt labels))
8848 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8849 (setq pn (make-js2-continue-node :pos pos
8850 :len (- end pos)
8851 :label label
8852 :target target))
8853 (js2-node-add-children pn label) ; but not target - it's not our child
8854 pn))
8855
8856 (defun js2-parse-with ()
8857 "Parser for with-statement. Last matched token must be js2-WITH."
8858 (let ((pos (js2-current-token-beg))
8859 obj body pn lp rp)
8860 (if (js2-must-match js2-LP "msg.no.paren.with")
8861 (setq lp (js2-current-token-beg)))
8862 (setq obj (js2-parse-expr))
8863 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8864 (setq rp (js2-current-token-beg)))
8865 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8866 (setq body (js2-parse-statement)))
8867 (setq pn (make-js2-with-node :pos pos
8868 :len (- (js2-node-end body) pos)
8869 :object obj
8870 :body body
8871 :lp (js2-relpos lp pos)
8872 :rp (js2-relpos rp pos)))
8873 (js2-node-add-children pn obj body)
8874 pn))
8875
8876 (defun js2-parse-const-var ()
8877 "Parser for var- or const-statement.
8878 Last matched token must be js2-CONST or js2-VAR."
8879 (let ((tt (js2-current-token-type))
8880 (pos (js2-current-token-beg))
8881 expr pn)
8882 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8883 pn (make-js2-expr-stmt-node :pos pos
8884 :len (- (js2-node-end expr) pos)
8885 :expr expr))
8886 (js2-node-add-children pn expr)
8887 pn))
8888
8889 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8890 (let ((pn (make-js2-expr-stmt-node :pos pos
8891 :len (js2-node-len expr)
8892 :type (if (js2-inside-function)
8893 js2-EXPR_VOID
8894 js2-EXPR_RESULT)
8895 :expr expr)))
8896 (if add-child
8897 (js2-node-add-children pn expr))
8898 pn))
8899
8900 (defun js2-parse-let-stmt ()
8901 "Parser for let-statement. Last matched token must be js2-LET."
8902 (let ((pos (js2-current-token-beg))
8903 expr pn)
8904 (if (= (js2-peek-token) js2-LP)
8905 ;; let expression in statement context
8906 (setq expr (js2-parse-let pos 'statement)
8907 pn (js2-wrap-with-expr-stmt pos expr t))
8908 ;; else we're looking at a statement like let x=6, y=7;
8909 (setf expr (js2-parse-variables js2-LET pos)
8910 pn (js2-wrap-with-expr-stmt pos expr t)
8911 (js2-node-type pn) js2-EXPR_RESULT))
8912 pn))
8913
8914 (defun js2-parse-ret-yield ()
8915 (js2-parse-return-or-yield (js2-current-token-type) nil))
8916
8917 (defconst js2-parse-return-stmt-enders
8918 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8919
8920 (defsubst js2-now-all-set (before after mask)
8921 "Return whether or not the bits in the mask have changed to all set.
8922 BEFORE is bits before change, AFTER is bits after change, and MASK is
8923 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8924 but not BEFORE."
8925 (and (/= (logand before mask) mask)
8926 (= (logand after mask) mask)))
8927
8928 (defun js2-parse-return-or-yield (tt expr-context)
8929 (let* ((pos (js2-current-token-beg))
8930 (end (js2-current-token-end))
8931 (before js2-end-flags)
8932 (inside-function (js2-inside-function))
8933 (gen-type (and inside-function (js2-function-node-generator-type
8934 js2-current-script-or-fn)))
8935 e ret name yield-star-p)
8936 (unless inside-function
8937 (js2-report-error (if (eq tt js2-RETURN)
8938 "msg.bad.return"
8939 "msg.bad.yield")))
8940 (when (and inside-function
8941 (eq gen-type 'STAR)
8942 (js2-match-token js2-MUL))
8943 (setq yield-star-p t))
8944 ;; This is ugly, but we don't want to require a semicolon.
8945 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8946 (setq e (js2-parse-expr)
8947 end (js2-node-end e)))
8948 (cond
8949 ((eq tt js2-RETURN)
8950 (js2-set-flag js2-end-flags (if (null e)
8951 js2-end-returns
8952 js2-end-returns-value))
8953 (setq ret (make-js2-return-node :pos pos
8954 :len (- end pos)
8955 :retval e))
8956 (js2-node-add-children ret e)
8957 ;; See if we need a strict mode warning.
8958 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8959 ;; more thorough and accurate than this before/after flag check.
8960 ;; E.g. if there's a finally-block that always returns, we shouldn't
8961 ;; show a warning generated by inconsistent returns in the catch blocks.
8962 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8963 ;; so we know which returns/yields to highlight, and we should get rid of
8964 ;; all the checking in `js2-parse-return-or-yield'.
8965 (if (and js2-strict-inconsistent-return-warning
8966 (js2-now-all-set before js2-end-flags
8967 (logior js2-end-returns js2-end-returns-value)))
8968 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8969 ((eq gen-type 'COMPREHENSION)
8970 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8971 ;; like SpiderMonkey does.
8972 (js2-report-error "msg.syntax" nil pos 5))
8973 (t
8974 (setq ret (make-js2-yield-node :pos pos
8975 :len (- end pos)
8976 :value e
8977 :star-p yield-star-p))
8978 (js2-node-add-children ret e)
8979 (unless expr-context
8980 (setq e ret
8981 ret (js2-wrap-with-expr-stmt pos e t))
8982 (js2-set-requires-activation)
8983 (js2-set-is-generator))))
8984 ;; see if we are mixing yields and value returns.
8985 (when (and inside-function
8986 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8987 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8988 'LEGACY))
8989 (setq name (js2-function-name js2-current-script-or-fn))
8990 (if (zerop (length name))
8991 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8992 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8993 ret))
8994
8995 (defun js2-parse-debugger ()
8996 (make-js2-keyword-node :type js2-DEBUGGER))
8997
8998 (defun js2-parse-block ()
8999 "Parser for a curly-delimited statement block.
9000 Last token matched must be `js2-LC'."
9001 (let ((pos (js2-current-token-beg))
9002 (pn (make-js2-scope)))
9003 (js2-push-scope pn)
9004 (unwind-protect
9005 (progn
9006 (js2-parse-statements pn)
9007 (js2-must-match js2-RC "msg.no.brace.block")
9008 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9009 (js2-pop-scope))
9010 pn))
9011
9012 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9013 (defun js2-parse-semi ()
9014 "Parse a statement or handle an error.
9015 Current token type is `js2-SEMI' or `js2-ERROR'."
9016 (let ((tt (js2-current-token-type)) pos len)
9017 (if (eq tt js2-SEMI)
9018 (make-js2-empty-expr-node :len 1)
9019 (setq pos (js2-current-token-beg)
9020 len (- (js2-current-token-end) pos))
9021 (js2-report-error "msg.syntax" nil pos len)
9022 (make-js2-error-node :pos pos :len len))))
9023
9024 (defun js2-parse-default-xml-namespace ()
9025 "Parse a `default xml namespace = <expr>' e4x statement."
9026 (let ((pos (js2-current-token-beg))
9027 end len expr unary)
9028 (js2-must-have-xml)
9029 (js2-set-requires-activation)
9030 (setq len (- js2-ts-cursor pos))
9031 (unless (and (js2-match-token js2-NAME)
9032 (string= (js2-current-token-string) "xml"))
9033 (js2-report-error "msg.bad.namespace" nil pos len))
9034 (unless (and (js2-match-token js2-NAME)
9035 (string= (js2-current-token-string) "namespace"))
9036 (js2-report-error "msg.bad.namespace" nil pos len))
9037 (unless (js2-match-token js2-ASSIGN)
9038 (js2-report-error "msg.bad.namespace" nil pos len))
9039 (setq expr (js2-parse-expr)
9040 end (js2-node-end expr)
9041 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9042 :pos pos
9043 :len (- end pos)
9044 :operand expr))
9045 (js2-node-add-children unary expr)
9046 (make-js2-expr-stmt-node :pos pos
9047 :len (- end pos)
9048 :expr unary)))
9049
9050 (defun js2-record-label (label bundle)
9051 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9052 (js2-get-token)
9053 (let ((name (js2-label-node-name label))
9054 labeled-stmt
9055 dup)
9056 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9057 ;; flag both labels if possible when used in editing mode
9058 (if (and js2-parse-ide-mode
9059 (setq dup (js2-get-label-by-name labeled-stmt name)))
9060 (js2-report-error "msg.dup.label" nil
9061 (js2-node-abs-pos dup) (js2-node-len dup)))
9062 (js2-report-error "msg.dup.label" nil
9063 (js2-node-pos label) (js2-node-len label)))
9064 (js2-labeled-stmt-node-add-label bundle label)
9065 (js2-node-add-children bundle label)
9066 ;; Add one reference to the bundle per label in `js2-label-set'
9067 (push (cons name bundle) js2-label-set)))
9068
9069 (defun js2-parse-name-or-label ()
9070 "Parser for identifier or label. Last token matched must be js2-NAME.
9071 Called when we found a name in a statement context. If it's a label, we gather
9072 up any following labels and the next non-label statement into a
9073 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9074 expression and return it wrapped in a `js2-expr-stmt-node'."
9075 (let ((pos (js2-current-token-beg))
9076 expr stmt bundle
9077 (continue t))
9078 ;; set check for label and call down to `js2-parse-primary-expr'
9079 (setq expr (js2-maybe-parse-label))
9080 (if (null expr)
9081 ;; Parse the non-label expression and wrap with expression stmt.
9082 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9083 ;; else parsed a label
9084 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9085 (js2-record-label expr bundle)
9086 ;; look for more labels
9087 (while (and continue (= (js2-get-token) js2-NAME))
9088 (if (setq expr (js2-maybe-parse-label))
9089 (js2-record-label expr bundle)
9090 (setq expr (js2-parse-expr)
9091 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9092 continue nil)
9093 (js2-auto-insert-semicolon stmt)))
9094 ;; no more labels; now parse the labeled statement
9095 (unwind-protect
9096 (unless stmt
9097 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9098 (js2-unget-token)
9099 (setq stmt (js2-statement-helper))))
9100 ;; remove the labels for this statement from the global set
9101 (dolist (label (js2-labeled-stmt-node-labels bundle))
9102 (setq js2-label-set (remove label js2-label-set))))
9103 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9104 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9105 (js2-node-add-children bundle stmt)
9106 bundle)))
9107
9108 (defun js2-maybe-parse-label ()
9109 (cl-assert (= (js2-current-token-type) js2-NAME))
9110 (let (label-pos
9111 (next-tt (js2-get-token))
9112 (label-end (js2-current-token-end)))
9113 ;; Do not consume colon, it is used as unwind indicator
9114 ;; to return to statementHelper.
9115 (js2-unget-token)
9116 (if (= next-tt js2-COLON)
9117 (prog2
9118 (setq label-pos (js2-current-token-beg))
9119 (make-js2-label-node :pos label-pos
9120 :len (- label-end label-pos)
9121 :name (js2-current-token-string))
9122 (js2-set-face label-pos
9123 label-end
9124 'font-lock-variable-name-face 'record))
9125 ;; Backtrack from the name token, too.
9126 (js2-unget-token)
9127 nil)))
9128
9129 (defun js2-parse-expr-stmt ()
9130 "Default parser in statement context, if no recognized statement found."
9131 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9132 (progn
9133 (js2-unget-token)
9134 (js2-parse-expr)) t))
9135
9136 (defun js2-parse-variables (decl-type pos)
9137 "Parse a comma-separated list of variable declarations.
9138 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9139
9140 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9141 For 'var' or 'const', the keyword should be the token last scanned.
9142
9143 POS is the position where the node should start. It's sometimes the
9144 var/const/let keyword, and other times the beginning of the first token
9145 in the first variable declaration.
9146
9147 Returns the parsed `js2-var-decl-node' expression node."
9148 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9149 :pos pos))
9150 destructuring kid-pos tt init name end nbeg nend vi
9151 (continue t))
9152 ;; Example:
9153 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9154 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9155 ;; var {a, b} = baz;
9156 (while continue
9157 (setq destructuring nil
9158 name nil
9159 tt (js2-get-token)
9160 kid-pos (js2-current-token-beg)
9161 end (js2-current-token-end)
9162 init nil)
9163 (if (or (= tt js2-LB) (= tt js2-LC))
9164 ;; Destructuring assignment, e.g., var [a, b] = ...
9165 (setq destructuring (js2-parse-destruct-primary-expr)
9166 end (js2-node-end destructuring))
9167 ;; Simple variable name
9168 (js2-unget-token)
9169 (when (js2-must-match-name "msg.bad.var")
9170 (setq name (js2-create-name-node)
9171 nbeg (js2-current-token-beg)
9172 nend (js2-current-token-end)
9173 end nend)
9174 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9175 (when (js2-match-token js2-ASSIGN)
9176 (setq init (js2-parse-assign-expr)
9177 end (js2-node-end init))
9178 (js2-record-imenu-functions init name))
9179 (when name
9180 (js2-set-face nbeg nend (if (js2-function-node-p init)
9181 'font-lock-function-name-face
9182 'font-lock-variable-name-face)
9183 'record))
9184 (setq vi (make-js2-var-init-node :pos kid-pos
9185 :len (- end kid-pos)
9186 :type decl-type))
9187 (if destructuring
9188 (progn
9189 (if (and (null init) (not js2-in-for-init))
9190 (js2-report-error "msg.destruct.assign.no.init"))
9191 (js2-define-destruct-symbols destructuring
9192 decl-type
9193 'font-lock-variable-name-face)
9194 (setf (js2-var-init-node-target vi) destructuring))
9195 (setf (js2-var-init-node-target vi) name))
9196 (setf (js2-var-init-node-initializer vi) init)
9197 (js2-node-add-children vi name destructuring init)
9198 (js2-block-node-push result vi)
9199 (unless (js2-match-token js2-COMMA)
9200 (setq continue nil)))
9201 (setf (js2-node-len result) (- end pos))
9202 result))
9203
9204 (defun js2-parse-let (pos &optional stmt-p)
9205 "Parse a let expression or statement.
9206 A let-expression is of the form `let (vars) expr'.
9207 A let-statement is of the form `let (vars) {statements}'.
9208 The third form of let is a variable declaration list, handled
9209 by `js2-parse-variables'."
9210 (let ((pn (make-js2-let-node :pos pos))
9211 beg vars body)
9212 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9213 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9214 (js2-push-scope pn)
9215 (unwind-protect
9216 (progn
9217 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9218 (if (js2-must-match js2-RP "msg.no.paren.let")
9219 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9220 (if (and stmt-p (js2-match-token js2-LC))
9221 ;; let statement
9222 (progn
9223 (setf beg (js2-current-token-beg) ; position stmt at LC
9224 body (js2-parse-statements))
9225 (js2-must-match js2-RC "msg.no.curly.let")
9226 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9227 (js2-node-len pn) (- (js2-current-token-end) pos)
9228 (js2-let-node-body pn) body
9229 (js2-node-type pn) js2-LET))
9230 ;; let expression
9231 (setf body (js2-parse-expr)
9232 (js2-node-len pn) (- (js2-node-end body) pos)
9233 (js2-let-node-body pn) body))
9234 (setf (js2-let-node-vars pn) vars)
9235 (js2-node-add-children pn vars body))
9236 (js2-pop-scope))
9237 pn))
9238
9239 (defun js2-define-new-symbol (decl-type name node &optional scope)
9240 (js2-scope-put-symbol (or scope js2-current-scope)
9241 name
9242 (make-js2-symbol decl-type name node)))
9243
9244 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9245 "Define a symbol in the current scope.
9246 If NODE is non-nil, it is the AST node associated with the symbol."
9247 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9248 (symbol (if defining-scope
9249 (js2-scope-get-symbol defining-scope name)))
9250 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9251 (pos (if node (js2-node-abs-pos node)))
9252 (len (if node (js2-node-len node))))
9253 (cond
9254 ((and symbol ; already defined
9255 (or (= sdt js2-CONST) ; old version is const
9256 (= decl-type js2-CONST) ; new version is const
9257 ;; two let-bound vars in this block have same name
9258 (and (= sdt js2-LET)
9259 (eq defining-scope js2-current-scope))))
9260 (js2-report-error
9261 (cond
9262 ((= sdt js2-CONST) "msg.const.redecl")
9263 ((= sdt js2-LET) "msg.let.redecl")
9264 ((= sdt js2-VAR) "msg.var.redecl")
9265 ((= sdt js2-FUNCTION) "msg.function.redecl")
9266 (t "msg.parm.redecl"))
9267 name pos len))
9268 ((= decl-type js2-LET)
9269 (if (and (not ignore-not-in-block)
9270 (or (= (js2-node-type js2-current-scope) js2-IF)
9271 (js2-loop-node-p js2-current-scope)))
9272 (js2-report-error "msg.let.decl.not.in.block")
9273 (js2-define-new-symbol decl-type name node)))
9274 ((or (= decl-type js2-VAR)
9275 (= decl-type js2-CONST)
9276 (= decl-type js2-FUNCTION))
9277 (if symbol
9278 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9279 (js2-add-strict-warning "msg.var.redecl" name)
9280 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9281 (js2-add-strict-warning "msg.var.hides.arg" name)))
9282 (js2-define-new-symbol decl-type name node
9283 js2-current-script-or-fn)))
9284 ((= decl-type js2-LP)
9285 (if symbol
9286 ;; must be duplicate parameter. Second parameter hides the
9287 ;; first, so go ahead and add the second pararameter
9288 (js2-report-warning "msg.dup.parms" name))
9289 (js2-define-new-symbol decl-type name node))
9290 (t (js2-code-bug)))))
9291
9292 (defun js2-parse-paren-expr-or-generator-comp ()
9293 (let ((px-pos (js2-current-token-beg)))
9294 (cond
9295 ((and (>= js2-language-version 200)
9296 (js2-match-token js2-FOR))
9297 (js2-parse-generator-comp px-pos))
9298 ((and (>= js2-language-version 200)
9299 (js2-match-token js2-RP))
9300 ;; Not valid expression syntax, but this is valid in an arrow
9301 ;; function with no params: () => body.
9302 (if (eq (js2-peek-token) js2-ARROW)
9303 ;; Return whatever, it will hopefully be rewinded and
9304 ;; reparsed when we reach the =>.
9305 (make-js2-keyword-node :type js2-NULL)
9306 (js2-report-error "msg.syntax")
9307 (make-js2-error-node)))
9308 (t
9309 (let* ((js2-in-for-init nil)
9310 (expr (js2-parse-expr))
9311 (pn (make-js2-paren-node :pos px-pos
9312 :expr expr)))
9313 (js2-node-add-children pn (js2-paren-node-expr pn))
9314 (js2-must-match js2-RP "msg.no.paren")
9315 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9316 pn)))))
9317
9318 (defun js2-parse-expr (&optional oneshot)
9319 (let* ((pn (js2-parse-assign-expr))
9320 (pos (js2-node-pos pn))
9321 left
9322 right
9323 op-pos)
9324 (while (and (not oneshot)
9325 (js2-match-token js2-COMMA))
9326 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9327 (if (= (js2-peek-token) js2-YIELD)
9328 (js2-report-error "msg.yield.parenthesized"))
9329 (setq right (js2-parse-assign-expr)
9330 left pn
9331 pn (make-js2-infix-node :type js2-COMMA
9332 :pos pos
9333 :len (- js2-ts-cursor pos)
9334 :op-pos op-pos
9335 :left left
9336 :right right))
9337 (js2-node-add-children pn left right))
9338 pn))
9339
9340 (defun js2-parse-assign-expr ()
9341 (let ((tt (js2-get-token))
9342 (pos (js2-current-token-beg))
9343 pn left right op-pos
9344 ts-state recorded-identifiers parsed-errors)
9345 (if (= tt js2-YIELD)
9346 (js2-parse-return-or-yield tt t)
9347 ;; Save the tokenizer state in case we find an arrow function
9348 ;; and have to rewind.
9349 (setq ts-state (make-js2-ts-state)
9350 recorded-identifiers js2-recorded-identifiers
9351 parsed-errors js2-parsed-errors)
9352 ;; not yield - parse assignment expression
9353 (setq pn (js2-parse-cond-expr)
9354 tt (js2-get-token))
9355 (cond
9356 ((and (<= js2-first-assign tt)
9357 (<= tt js2-last-assign))
9358 ;; tt express assignment (=, |=, ^=, ..., %=)
9359 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9360 left pn)
9361 (setq right (js2-parse-assign-expr)
9362 pn (make-js2-assign-node :type tt
9363 :pos pos
9364 :len (- (js2-node-end right) pos)
9365 :op-pos op-pos
9366 :left left
9367 :right right))
9368 (when js2-parse-ide-mode
9369 (js2-highlight-assign-targets pn left right)
9370 (js2-record-imenu-functions right left))
9371 ;; do this last so ide checks above can use absolute positions
9372 (js2-node-add-children pn left right))
9373 ((and (= tt js2-ARROW)
9374 (>= js2-language-version 200))
9375 (js2-ts-seek ts-state)
9376 (setq js2-recorded-identifiers recorded-identifiers
9377 js2-parsed-errors parsed-errors)
9378 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9379 (t
9380 (js2-unget-token)))
9381 pn)))
9382
9383 (defun js2-parse-cond-expr ()
9384 (let ((pos (js2-current-token-beg))
9385 (pn (js2-parse-or-expr))
9386 test-expr
9387 if-true
9388 if-false
9389 q-pos
9390 c-pos)
9391 (when (js2-match-token js2-HOOK)
9392 (setq q-pos (- (js2-current-token-beg) pos)
9393 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9394 (js2-must-match js2-COLON "msg.no.colon.cond")
9395 (setq c-pos (- (js2-current-token-beg) pos)
9396 if-false (js2-parse-assign-expr)
9397 test-expr pn
9398 pn (make-js2-cond-node :pos pos
9399 :len (- (js2-node-end if-false) pos)
9400 :test-expr test-expr
9401 :true-expr if-true
9402 :false-expr if-false
9403 :q-pos q-pos
9404 :c-pos c-pos))
9405 (js2-node-add-children pn test-expr if-true if-false))
9406 pn))
9407
9408 (defun js2-make-binary (type left parser)
9409 "Helper for constructing a binary-operator AST node.
9410 LEFT is the left-side-expression, already parsed, and the
9411 binary operator should have just been matched.
9412 PARSER is a function to call to parse the right operand,
9413 or a `js2-node' struct if it has already been parsed.
9414 FIXME: The latter option is unused?"
9415 (let* ((pos (js2-node-pos left))
9416 (op-pos (- (js2-current-token-beg) pos))
9417 (right (if (js2-node-p parser)
9418 parser
9419 (js2-get-token)
9420 (funcall parser)))
9421 (pn (make-js2-infix-node :type type
9422 :pos pos
9423 :len (- (js2-node-end right) pos)
9424 :op-pos op-pos
9425 :left left
9426 :right right)))
9427 (js2-node-add-children pn left right)
9428 pn))
9429
9430 (defun js2-parse-or-expr ()
9431 (let ((pn (js2-parse-and-expr)))
9432 (when (js2-match-token js2-OR)
9433 (setq pn (js2-make-binary js2-OR
9434 pn
9435 'js2-parse-or-expr)))
9436 pn))
9437
9438 (defun js2-parse-and-expr ()
9439 (let ((pn (js2-parse-bit-or-expr)))
9440 (when (js2-match-token js2-AND)
9441 (setq pn (js2-make-binary js2-AND
9442 pn
9443 'js2-parse-and-expr)))
9444 pn))
9445
9446 (defun js2-parse-bit-or-expr ()
9447 (let ((pn (js2-parse-bit-xor-expr)))
9448 (while (js2-match-token js2-BITOR)
9449 (setq pn (js2-make-binary js2-BITOR
9450 pn
9451 'js2-parse-bit-xor-expr)))
9452 pn))
9453
9454 (defun js2-parse-bit-xor-expr ()
9455 (let ((pn (js2-parse-bit-and-expr)))
9456 (while (js2-match-token js2-BITXOR)
9457 (setq pn (js2-make-binary js2-BITXOR
9458 pn
9459 'js2-parse-bit-and-expr)))
9460 pn))
9461
9462 (defun js2-parse-bit-and-expr ()
9463 (let ((pn (js2-parse-eq-expr)))
9464 (while (js2-match-token js2-BITAND)
9465 (setq pn (js2-make-binary js2-BITAND
9466 pn
9467 'js2-parse-eq-expr)))
9468 pn))
9469
9470 (defconst js2-parse-eq-ops
9471 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9472
9473 (defun js2-parse-eq-expr ()
9474 (let ((pn (js2-parse-rel-expr))
9475 tt)
9476 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9477 (setq pn (js2-make-binary tt
9478 pn
9479 'js2-parse-rel-expr)))
9480 (js2-unget-token)
9481 pn))
9482
9483 (defconst js2-parse-rel-ops
9484 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9485
9486 (defun js2-parse-rel-expr ()
9487 (let ((pn (js2-parse-shift-expr))
9488 (continue t)
9489 tt)
9490 (while continue
9491 (setq tt (js2-get-token))
9492 (cond
9493 ((and js2-in-for-init (= tt js2-IN))
9494 (js2-unget-token)
9495 (setq continue nil))
9496 ((memq tt js2-parse-rel-ops)
9497 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9498 (t
9499 (js2-unget-token)
9500 (setq continue nil))))
9501 pn))
9502
9503 (defconst js2-parse-shift-ops
9504 (list js2-LSH js2-URSH js2-RSH))
9505
9506 (defun js2-parse-shift-expr ()
9507 (let ((pn (js2-parse-add-expr))
9508 tt
9509 (continue t))
9510 (while continue
9511 (setq tt (js2-get-token))
9512 (if (memq tt js2-parse-shift-ops)
9513 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9514 (js2-unget-token)
9515 (setq continue nil)))
9516 pn))
9517
9518 (defun js2-parse-add-expr ()
9519 (let ((pn (js2-parse-mul-expr))
9520 tt
9521 (continue t))
9522 (while continue
9523 (setq tt (js2-get-token))
9524 (if (or (= tt js2-ADD) (= tt js2-SUB))
9525 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9526 (js2-unget-token)
9527 (setq continue nil)))
9528 pn))
9529
9530 (defconst js2-parse-mul-ops
9531 (list js2-MUL js2-DIV js2-MOD))
9532
9533 (defun js2-parse-mul-expr ()
9534 (let ((pn (js2-parse-unary-expr))
9535 tt
9536 (continue t))
9537 (while continue
9538 (setq tt (js2-get-token))
9539 (if (memq tt js2-parse-mul-ops)
9540 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9541 (js2-unget-token)
9542 (setq continue nil)))
9543 pn))
9544
9545 (defun js2-make-unary (type parser &rest args)
9546 "Make a unary node of type TYPE.
9547 PARSER is either a node (for postfix operators) or a function to call
9548 to parse the operand (for prefix operators)."
9549 (let* ((pos (js2-current-token-beg))
9550 (postfix (js2-node-p parser))
9551 (expr (if postfix
9552 parser
9553 (apply parser args)))
9554 end
9555 pn)
9556 (if postfix ; e.g. i++
9557 (setq pos (js2-node-pos expr)
9558 end (js2-current-token-end))
9559 (setq end (js2-node-end expr)))
9560 (setq pn (make-js2-unary-node :type type
9561 :pos pos
9562 :len (- end pos)
9563 :operand expr))
9564 (js2-node-add-children pn expr)
9565 pn))
9566
9567 (defconst js2-incrementable-node-types
9568 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9569 "Node types that can be the operand of a ++ or -- operator.")
9570
9571 (defun js2-check-bad-inc-dec (tt beg end unary)
9572 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9573 js2-incrementable-node-types)
9574 (js2-report-error (if (= tt js2-INC)
9575 "msg.bad.incr"
9576 "msg.bad.decr")
9577 nil beg (- end beg))))
9578
9579 (defun js2-parse-unary-expr ()
9580 (let ((tt (js2-current-token-type))
9581 pn expr beg end)
9582 (cond
9583 ((or (= tt js2-VOID)
9584 (= tt js2-NOT)
9585 (= tt js2-BITNOT)
9586 (= tt js2-TYPEOF))
9587 (js2-get-token)
9588 (js2-make-unary tt 'js2-parse-unary-expr))
9589 ((= tt js2-ADD)
9590 (js2-get-token)
9591 ;; Convert to special POS token in decompiler and parse tree
9592 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9593 ((= tt js2-SUB)
9594 (js2-get-token)
9595 ;; Convert to special NEG token in decompiler and parse tree
9596 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9597 ((or (= tt js2-INC)
9598 (= tt js2-DEC))
9599 (js2-get-token)
9600 (prog1
9601 (setq beg (js2-current-token-beg)
9602 end (js2-current-token-end)
9603 expr (js2-make-unary tt 'js2-parse-member-expr t))
9604 (js2-check-bad-inc-dec tt beg end expr)))
9605 ((= tt js2-DELPROP)
9606 (js2-get-token)
9607 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9608 ((= tt js2-ERROR)
9609 (js2-get-token)
9610 (make-js2-error-node)) ; try to continue
9611 ((and (= tt js2-LT)
9612 js2-compiler-xml-available)
9613 ;; XML stream encountered in expression.
9614 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9615 (t
9616 (setq pn (js2-parse-member-expr t)
9617 ;; Don't look across a newline boundary for a postfix incop.
9618 tt (js2-peek-token-or-eol))
9619 (when (or (= tt js2-INC) (= tt js2-DEC))
9620 (js2-get-token)
9621 (setf expr pn
9622 pn (js2-make-unary tt expr))
9623 (js2-node-set-prop pn 'postfix t)
9624 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9625 pn))))
9626
9627 (defun js2-parse-xml-initializer ()
9628 "Parse an E4X XML initializer.
9629 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9630 Then I'll postprocess the result, depending on whether we're in IDE
9631 mode or codegen mode, and generate the appropriate rewritten AST.
9632 IDE mode uses a rich AST that models the XML structure. Codegen mode
9633 just concatenates everything and makes a new XML or XMLList out of it."
9634 (let ((tt (js2-get-first-xml-token))
9635 pn-xml pn expr kids expr-pos
9636 (continue t)
9637 (first-token t))
9638 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9639 (js2-report-error "msg.syntax"))
9640 (setq pn-xml (make-js2-xml-node))
9641 (while continue
9642 (if first-token
9643 (setq first-token nil)
9644 (setq tt (js2-get-next-xml-token)))
9645 (cond
9646 ;; js2-XML means we found a {expr} in the XML stream.
9647 ;; The token string is the XML up to the left-curly.
9648 ((= tt js2-XML)
9649 (push (make-js2-string-node :pos (js2-current-token-beg)
9650 :len (- js2-ts-cursor (js2-current-token-beg)))
9651 kids)
9652 (js2-must-match js2-LC "msg.syntax")
9653 (setq expr-pos js2-ts-cursor
9654 expr (if (eq (js2-peek-token) js2-RC)
9655 (make-js2-empty-expr-node :pos expr-pos)
9656 (js2-parse-expr)))
9657 (js2-must-match js2-RC "msg.syntax")
9658 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9659 :len (js2-node-len expr)
9660 :expr expr))
9661 (js2-node-add-children pn expr)
9662 (push pn kids))
9663 ;; a js2-XMLEND token means we hit the final close-tag.
9664 ((= tt js2-XMLEND)
9665 (push (make-js2-string-node :pos (js2-current-token-beg)
9666 :len (- js2-ts-cursor (js2-current-token-beg)))
9667 kids)
9668 (dolist (kid (nreverse kids))
9669 (js2-block-node-push pn-xml kid))
9670 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9671 (js2-node-pos pn-xml))
9672 continue nil))
9673 (t
9674 (js2-report-error "msg.syntax")
9675 (setq continue nil))))
9676 pn-xml))
9677
9678
9679 (defun js2-parse-argument-list ()
9680 "Parse an argument list and return it as a Lisp list of nodes.
9681 Returns the list in reverse order. Consumes the right-paren token."
9682 (let (result)
9683 (unless (js2-match-token js2-RP)
9684 (cl-loop do
9685 (let ((tt (js2-get-token)))
9686 (if (= tt js2-YIELD)
9687 (js2-report-error "msg.yield.parenthesized"))
9688 (if (and (= tt js2-TRIPLEDOT)
9689 (>= js2-language-version 200))
9690 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9691 (js2-unget-token)
9692 (push (js2-parse-assign-expr) result)))
9693 while
9694 (js2-match-token js2-COMMA))
9695 (js2-must-match js2-RP "msg.no.paren.arg")
9696 result)))
9697
9698 (defun js2-parse-member-expr (&optional allow-call-syntax)
9699 (let ((tt (js2-current-token-type))
9700 pn pos target args beg end init)
9701 (if (/= tt js2-NEW)
9702 (setq pn (js2-parse-primary-expr))
9703 ;; parse a 'new' expression
9704 (js2-get-token)
9705 (setq pos (js2-current-token-beg)
9706 beg pos
9707 target (js2-parse-member-expr)
9708 end (js2-node-end target)
9709 pn (make-js2-new-node :pos pos
9710 :target target
9711 :len (- end pos)))
9712 (js2-highlight-function-call (js2-current-token))
9713 (js2-node-add-children pn target)
9714 (when (js2-match-token js2-LP)
9715 ;; Add the arguments to pn, if any are supplied.
9716 (setf beg pos ; start of "new" keyword
9717 pos (js2-current-token-beg)
9718 args (nreverse (js2-parse-argument-list))
9719 (js2-new-node-args pn) args
9720 end (js2-current-token-end)
9721 (js2-new-node-lp pn) (- pos beg)
9722 (js2-new-node-rp pn) (- end 1 beg))
9723 (apply #'js2-node-add-children pn args))
9724 (when (and js2-allow-rhino-new-expr-initializer
9725 (js2-match-token js2-LC))
9726 (setf init (js2-parse-object-literal)
9727 end (js2-node-end init)
9728 (js2-new-node-initializer pn) init)
9729 (js2-node-add-children pn init))
9730 (setf (js2-node-len pn) (- end beg))) ; end outer if
9731 (js2-parse-member-expr-tail allow-call-syntax pn)))
9732
9733 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9734 "Parse a chain of property/array accesses or function calls.
9735 Includes parsing for E4X operators like `..' and `.@'.
9736 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9737 Returns an expression tree that includes PN, the parent node."
9738 (let (tt
9739 (continue t))
9740 (while continue
9741 (setq tt (js2-get-token))
9742 (cond
9743 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9744 (setq pn (js2-parse-property-access tt pn)))
9745 ((= tt js2-DOTQUERY)
9746 (setq pn (js2-parse-dot-query pn)))
9747 ((= tt js2-LB)
9748 (setq pn (js2-parse-element-get pn)))
9749 ((= tt js2-LP)
9750 (js2-unget-token)
9751 (if allow-call-syntax
9752 (setq pn (js2-parse-function-call pn))
9753 (setq continue nil)))
9754 ((= tt js2-TEMPLATE_HEAD)
9755 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9756 ((= tt js2-NO_SUBS_TEMPLATE)
9757 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9758 (t
9759 (js2-unget-token)
9760 (setq continue nil))))
9761 (if (>= js2-highlight-level 2)
9762 (js2-parse-highlight-member-expr-node pn))
9763 pn))
9764
9765 (defun js2-parse-tagged-template (tag-node tpl-node)
9766 "Parse tagged template expression."
9767 (let* ((beg (js2-node-pos tag-node))
9768 (pn (make-js2-tagged-template-node :beg beg
9769 :len (- (js2-current-token-end) beg)
9770 :tag tag-node
9771 :template tpl-node)))
9772 (js2-node-add-children pn tag-node tpl-node)
9773 pn))
9774
9775 (defun js2-parse-dot-query (pn)
9776 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9777 Last token parsed must be `js2-DOTQUERY'."
9778 (let ((pos (js2-node-pos pn))
9779 op-pos expr end)
9780 (js2-must-have-xml)
9781 (js2-set-requires-activation)
9782 (setq op-pos (js2-current-token-beg)
9783 expr (js2-parse-expr)
9784 end (js2-node-end expr)
9785 pn (make-js2-xml-dot-query-node :left pn
9786 :pos pos
9787 :op-pos op-pos
9788 :right expr))
9789 (js2-node-add-children pn
9790 (js2-xml-dot-query-node-left pn)
9791 (js2-xml-dot-query-node-right pn))
9792 (if (js2-must-match js2-RP "msg.no.paren")
9793 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9794 end (js2-current-token-end)))
9795 (setf (js2-node-len pn) (- end pos))
9796 pn))
9797
9798 (defun js2-parse-element-get (pn)
9799 "Parse an element-get expression, e.g. foo[bar].
9800 Last token parsed must be `js2-RB'."
9801 (let ((lb (js2-current-token-beg))
9802 (pos (js2-node-pos pn))
9803 rb expr)
9804 (setq expr (js2-parse-expr))
9805 (if (js2-must-match js2-RB "msg.no.bracket.index")
9806 (setq rb (js2-current-token-beg)))
9807 (setq pn (make-js2-elem-get-node :target pn
9808 :pos pos
9809 :element expr
9810 :lb (js2-relpos lb pos)
9811 :rb (js2-relpos rb pos)
9812 :len (- (js2-current-token-end) pos)))
9813 (js2-node-add-children pn
9814 (js2-elem-get-node-target pn)
9815 (js2-elem-get-node-element pn))
9816 pn))
9817
9818 (defun js2-highlight-function-call (token)
9819 (when (eq (js2-token-type token) js2-NAME)
9820 (js2-record-face 'js2-function-call token)))
9821
9822 (defun js2-parse-function-call (pn)
9823 (js2-highlight-function-call (js2-current-token))
9824 (js2-get-token)
9825 (let (args
9826 (pos (js2-node-pos pn)))
9827 (setq pn (make-js2-call-node :pos pos
9828 :target pn
9829 :lp (- (js2-current-token-beg) pos)))
9830 (js2-node-add-children pn (js2-call-node-target pn))
9831 ;; Add the arguments to pn, if any are supplied.
9832 (setf args (nreverse (js2-parse-argument-list))
9833 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9834 (js2-call-node-args pn) args)
9835 (apply #'js2-node-add-children pn args)
9836 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9837 pn))
9838
9839 (defun js2-parse-property-access (tt pn)
9840 "Parse a property access, XML descendants access, or XML attr access."
9841 (let ((member-type-flags 0)
9842 (dot-pos (js2-current-token-beg))
9843 (dot-len (if (= tt js2-DOTDOT) 2 1))
9844 name
9845 ref ; right side of . or .. operator
9846 result)
9847 (when (= tt js2-DOTDOT)
9848 (js2-must-have-xml)
9849 (setq member-type-flags js2-descendants-flag))
9850 (if (not js2-compiler-xml-available)
9851 (progn
9852 (js2-must-match-prop-name "msg.no.name.after.dot")
9853 (setq name (js2-create-name-node t js2-GETPROP)
9854 result (make-js2-prop-get-node :left pn
9855 :pos (js2-current-token-beg)
9856 :right name
9857 :len (js2-current-token-len)))
9858 (js2-node-add-children result pn name)
9859 result)
9860 ;; otherwise look for XML operators
9861 (setf result (if (= tt js2-DOT)
9862 (make-js2-prop-get-node)
9863 (make-js2-infix-node :type js2-DOTDOT))
9864 (js2-node-pos result) (js2-node-pos pn)
9865 (js2-infix-node-op-pos result) dot-pos
9866 (js2-infix-node-left result) pn ; do this after setting position
9867 tt (js2-get-prop-name-token))
9868 (cond
9869 ;; handles: name, ns::name, ns::*, ns::[expr]
9870 ((= tt js2-NAME)
9871 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9872 ;; handles: *, *::name, *::*, *::[expr]
9873 ((= tt js2-MUL)
9874 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9875 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9876 ((= tt js2-XMLATTR)
9877 (setq result (js2-parse-attribute-access)))
9878 (t
9879 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9880 (if ref
9881 (setf (js2-node-len result) (- (js2-node-end ref)
9882 (js2-node-pos result))
9883 (js2-infix-node-right result) ref))
9884 (if (js2-infix-node-p result)
9885 (js2-node-add-children result
9886 (js2-infix-node-left result)
9887 (js2-infix-node-right result)))
9888 result)))
9889
9890 (defun js2-parse-attribute-access ()
9891 "Parse an E4X XML attribute expression.
9892 This includes expressions of the forms:
9893
9894 @attr @ns::attr @ns::*
9895 @* @*::attr @*::*
9896 @[expr] @*::[expr] @ns::[expr]
9897
9898 Called if we peeked an '@' token."
9899 (let ((tt (js2-get-prop-name-token))
9900 (at-pos (js2-current-token-beg)))
9901 (cond
9902 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9903 ((= tt js2-NAME)
9904 (js2-parse-property-name at-pos nil 0))
9905 ;; handles: @*, @*::name, @*::*, @*::[expr]
9906 ((= tt js2-MUL)
9907 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9908 ;; handles @[expr]
9909 ((= tt js2-LB)
9910 (js2-parse-xml-elem-ref at-pos))
9911 (t
9912 (js2-report-error "msg.no.name.after.xmlAttr")
9913 ;; Avoid cascaded errors that happen if we make an error node here.
9914 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9915
9916 (defun js2-parse-property-name (at-pos s member-type-flags)
9917 "Check if :: follows name in which case it becomes qualified name.
9918
9919 AT-POS is a natural number if we just read an '@' token, else nil.
9920 S is the name or string that was matched: an identifier, 'throw' or '*'.
9921 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9922
9923 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9924 operator, or the name is followed by ::. For a plain name, returns a
9925 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9926 (let ((pos (or at-pos (js2-current-token-beg)))
9927 colon-pos
9928 (name (js2-create-name-node t (js2-current-token-type) s))
9929 ns tt pn)
9930 (catch 'return
9931 (when (js2-match-token js2-COLONCOLON)
9932 (setq ns name
9933 colon-pos (js2-current-token-beg)
9934 tt (js2-get-prop-name-token))
9935 (cond
9936 ;; handles name::name
9937 ((= tt js2-NAME)
9938 (setq name (js2-create-name-node)))
9939 ;; handles name::*
9940 ((= tt js2-MUL)
9941 (setq name (js2-create-name-node nil nil "*")))
9942 ;; handles name::[expr]
9943 ((= tt js2-LB)
9944 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9945 (t
9946 (js2-report-error "msg.no.name.after.coloncolon"))))
9947 (if (and (null ns) (zerop member-type-flags))
9948 name
9949 (prog1
9950 (setq pn
9951 (make-js2-xml-prop-ref-node :pos pos
9952 :len (- (js2-node-end name) pos)
9953 :at-pos at-pos
9954 :colon-pos colon-pos
9955 :propname name))
9956 (js2-node-add-children pn name))))))
9957
9958 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9959 "Parse the [expr] portion of an xml element reference.
9960 For instance, @[expr], @*::[expr], or ns::[expr]."
9961 (let* ((lb (js2-current-token-beg))
9962 (pos (or at-pos lb))
9963 rb
9964 (expr (js2-parse-expr))
9965 (end (js2-node-end expr))
9966 pn)
9967 (if (js2-must-match js2-RB "msg.no.bracket.index")
9968 (setq rb (js2-current-token-beg)
9969 end (js2-current-token-end)))
9970 (prog1
9971 (setq pn
9972 (make-js2-xml-elem-ref-node :pos pos
9973 :len (- end pos)
9974 :namespace namespace
9975 :colon-pos colon-pos
9976 :at-pos at-pos
9977 :expr expr
9978 :lb (js2-relpos lb pos)
9979 :rb (js2-relpos rb pos)))
9980 (js2-node-add-children pn namespace expr))))
9981
9982 (defun js2-parse-destruct-primary-expr ()
9983 (let ((js2-is-in-destructuring t))
9984 (js2-parse-primary-expr)))
9985
9986 (defun js2-parse-primary-expr ()
9987 "Parse a literal (leaf) expression of some sort.
9988 Includes complex literals such as functions, object-literals,
9989 array-literals, array comprehensions and regular expressions."
9990 (let (tt)
9991 (setq tt (js2-current-token-type))
9992 (cond
9993 ((= tt js2-CLASS)
9994 (js2-parse-class-expr))
9995 ((= tt js2-FUNCTION)
9996 (js2-parse-function-expr))
9997 ((= tt js2-LB)
9998 (js2-parse-array-comp-or-literal))
9999 ((= tt js2-LC)
10000 (js2-parse-object-literal))
10001 ((= tt js2-LET)
10002 (js2-parse-let (js2-current-token-beg)))
10003 ((= tt js2-LP)
10004 (js2-parse-paren-expr-or-generator-comp))
10005 ((= tt js2-XMLATTR)
10006 (js2-must-have-xml)
10007 (js2-parse-attribute-access))
10008 ((= tt js2-NAME)
10009 (js2-parse-name tt))
10010 ((= tt js2-NUMBER)
10011 (make-js2-number-node))
10012 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10013 (make-js2-string-node :type tt))
10014 ((= tt js2-TEMPLATE_HEAD)
10015 (js2-parse-template-literal))
10016 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10017 ;; Got / or /= which in this context means a regexp literal
10018 (let ((px-pos (js2-current-token-beg))
10019 (flags (js2-read-regexp tt))
10020 (end (js2-current-token-end)))
10021 (prog1
10022 (make-js2-regexp-node :pos px-pos
10023 :len (- end px-pos)
10024 :value (js2-current-token-string)
10025 :flags flags)
10026 (js2-set-face px-pos end 'font-lock-string-face 'record)
10027 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10028 ((or (= tt js2-NULL)
10029 (= tt js2-THIS)
10030 (= tt js2-SUPER)
10031 (= tt js2-FALSE)
10032 (= tt js2-TRUE))
10033 (make-js2-keyword-node :type tt))
10034 ((= tt js2-TRIPLEDOT)
10035 ;; Likewise, only valid in an arrow function with a rest param.
10036 (if (and (js2-match-token js2-NAME)
10037 (js2-match-token js2-RP)
10038 (eq (js2-peek-token) js2-ARROW))
10039 (progn
10040 (js2-unget-token) ; Put back the right paren.
10041 ;; See the previous case.
10042 (make-js2-keyword-node :type js2-NULL))
10043 (js2-report-error "msg.syntax")
10044 (make-js2-error-node)))
10045 ((= tt js2-RESERVED)
10046 (js2-report-error "msg.reserved.id")
10047 (make-js2-name-node))
10048 ((= tt js2-ERROR)
10049 ;; the scanner or one of its subroutines reported the error.
10050 (make-js2-error-node))
10051 ((= tt js2-EOF)
10052 (let* ((px-pos (point-at-bol))
10053 (len (- js2-ts-cursor px-pos)))
10054 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10055 (make-js2-error-node :pos (1- js2-ts-cursor)))
10056 (t
10057 (js2-report-error "msg.syntax")
10058 (make-js2-error-node)))))
10059
10060 (defun js2-parse-template-literal ()
10061 (let ((beg (js2-current-token-beg))
10062 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10063 (tt js2-TEMPLATE_HEAD))
10064 (while (eq tt js2-TEMPLATE_HEAD)
10065 (push (js2-parse-expr) kids)
10066 (js2-must-match js2-RC "msg.syntax")
10067 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10068 (push (make-js2-string-node :type tt) kids))
10069 (setq kids (nreverse kids))
10070 (let ((tpl (make-js2-template-node :beg beg
10071 :len (- (js2-current-token-end) beg)
10072 :kids kids)))
10073 (apply #'js2-node-add-children tpl kids)
10074 tpl)))
10075
10076 (defun js2-parse-name (_tt)
10077 (let ((name (js2-current-token-string))
10078 node)
10079 (setq node (if js2-compiler-xml-available
10080 (js2-parse-property-name nil name 0)
10081 (js2-create-name-node 'check-activation nil name)))
10082 (if js2-highlight-external-variables
10083 (js2-record-name-node node))
10084 node))
10085
10086 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10087 (js2-add-strict-warning
10088 msg nil
10089 ;; back up from comma to beginning of line or array/objlit
10090 (max (if elems
10091 (js2-node-pos (car elems))
10092 pos)
10093 (save-excursion
10094 (goto-char comma-pos)
10095 (back-to-indentation)
10096 (point)))
10097 comma-pos))
10098
10099 (defun js2-parse-array-comp-or-literal ()
10100 (let ((pos (js2-current-token-beg)))
10101 (if (and (>= js2-language-version 200)
10102 (js2-match-token js2-FOR))
10103 (js2-parse-array-comp pos)
10104 (js2-parse-array-literal pos))))
10105
10106 (defun js2-parse-array-literal (pos)
10107 (let ((after-lb-or-comma t)
10108 after-comma tt elems pn
10109 (continue t))
10110 (unless js2-is-in-destructuring
10111 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10112 (while continue
10113 (setq tt (js2-get-token))
10114 (cond
10115 ;; comma
10116 ((= tt js2-COMMA)
10117 (setq after-comma (js2-current-token-end))
10118 (if (not after-lb-or-comma)
10119 (setq after-lb-or-comma t)
10120 (push nil elems)))
10121 ;; end of array
10122 ((or (= tt js2-RB)
10123 (= tt js2-EOF)) ; prevent infinite loop
10124 (if (= tt js2-EOF)
10125 (js2-report-error "msg.no.bracket.arg" nil pos))
10126 (when (and after-comma (< js2-language-version 170))
10127 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10128 pos (remove nil elems) after-comma))
10129 (setq continue nil
10130 pn (make-js2-array-node :pos pos
10131 :len (- js2-ts-cursor pos)
10132 :elems (nreverse elems)))
10133 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10134 ;; destructuring binding
10135 (js2-is-in-destructuring
10136 (push (if (or (= tt js2-LC)
10137 (= tt js2-LB)
10138 (= tt js2-NAME))
10139 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10140 (js2-parse-destruct-primary-expr)
10141 ;; invalid pattern
10142 (js2-report-error "msg.bad.var")
10143 (make-js2-error-node))
10144 elems)
10145 (setq after-lb-or-comma nil
10146 after-comma nil))
10147 ;; array comp
10148 ((and (>= js2-language-version 170)
10149 (= tt js2-FOR) ; check for array comprehension
10150 (not after-lb-or-comma) ; "for" can't follow a comma
10151 elems ; must have at least 1 element
10152 (not (cdr elems))) ; but no 2nd element
10153 (js2-unget-token)
10154 (setf continue nil
10155 pn (js2-parse-legacy-array-comp (car elems) pos)))
10156 ;; another element
10157 (t
10158 (unless after-lb-or-comma
10159 (js2-report-error "msg.no.bracket.arg"))
10160 (if (and (= tt js2-TRIPLEDOT)
10161 (>= js2-language-version 200))
10162 ;; spread operator
10163 (push (js2-make-unary tt 'js2-parse-assign-expr)
10164 elems)
10165 (js2-unget-token)
10166 (push (js2-parse-assign-expr) elems))
10167 (setq after-lb-or-comma nil
10168 after-comma nil))))
10169 (unless js2-is-in-destructuring
10170 (js2-pop-scope))
10171 pn))
10172
10173 (defun js2-parse-legacy-array-comp (expr pos)
10174 "Parse a legacy array comprehension (JavaScript 1.7).
10175 EXPR is the first expression after the opening left-bracket.
10176 POS is the beginning of the LB token preceding EXPR.
10177 We should have just parsed the 'for' keyword before calling this function."
10178 (let ((current-scope js2-current-scope)
10179 loops first filter result)
10180 (unwind-protect
10181 (progn
10182 (while (js2-match-token js2-FOR)
10183 (let ((loop (make-js2-comp-loop-node)))
10184 (js2-push-scope loop)
10185 (push loop loops)
10186 (js2-parse-comp-loop loop)))
10187 ;; First loop takes expr scope's parent.
10188 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10189 (js2-scope-parent-scope current-scope))
10190 ;; Set expr scope's parent to the last loop.
10191 (setf (js2-scope-parent-scope current-scope) (car loops))
10192 (if (/= (js2-get-token) js2-IF)
10193 (js2-unget-token)
10194 (setq filter (js2-parse-condition))))
10195 (dotimes (_ (1- (length loops)))
10196 (js2-pop-scope)))
10197 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10198 (setq result (make-js2-comp-node :pos pos
10199 :len (- js2-ts-cursor pos)
10200 :result expr
10201 :loops (nreverse loops)
10202 :filters (and filter (list (car filter)))
10203 :form 'LEGACY_ARRAY))
10204 ;; Set comp loop's parent to the last loop.
10205 ;; TODO: Get rid of the bogus expr scope.
10206 (setf (js2-scope-parent-scope result) first)
10207 (apply #'js2-node-add-children result expr (car filter)
10208 (js2-comp-node-loops result))
10209 result))
10210
10211 (defun js2-parse-array-comp (pos)
10212 "Parse an ES6 array comprehension.
10213 POS is the beginning of the LB token.
10214 We should have just parsed the 'for' keyword before calling this function."
10215 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10216 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10217 pn))
10218
10219 (defun js2-parse-generator-comp (pos)
10220 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10221 (js2-current-script-or-fn
10222 (make-js2-function-node :generator-type 'COMPREHENSION))
10223 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10224 (js2-must-match js2-RP "msg.no.paren" pos)
10225 pn))
10226
10227 (defun js2-parse-comprehension (pos form)
10228 (let (loops filters expr result)
10229 (unwind-protect
10230 (progn
10231 (js2-unget-token)
10232 (while (js2-match-token js2-FOR)
10233 (let ((loop (make-js2-comp-loop-node)))
10234 (js2-push-scope loop)
10235 (push loop loops)
10236 (js2-parse-comp-loop loop)))
10237 (while (js2-match-token js2-IF)
10238 (push (car (js2-parse-condition)) filters))
10239 (setq expr (js2-parse-assign-expr)))
10240 (dolist (_ loops)
10241 (js2-pop-scope)))
10242 (setq result (make-js2-comp-node :pos pos
10243 :len (- js2-ts-cursor pos)
10244 :result expr
10245 :loops (nreverse loops)
10246 :filters (nreverse filters)
10247 :form form))
10248 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10249 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10250 result))
10251
10252 (defun js2-parse-comp-loop (pn &optional only-of-p)
10253 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10254 The current token should be the initial FOR.
10255 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10256 (let ((pos (js2-comp-loop-node-pos pn))
10257 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10258 (when (and (not only-of-p) (js2-match-token js2-NAME))
10259 (if (string= (js2-current-token-string) "each")
10260 (progn
10261 (setq foreach-p t
10262 each-pos (- (js2-current-token-beg) pos)) ; relative
10263 (js2-record-face 'font-lock-keyword-face))
10264 (js2-report-error "msg.no.paren.for")))
10265 (if (js2-must-match js2-LP "msg.no.paren.for")
10266 (setq lp (- (js2-current-token-beg) pos)))
10267 (setq tt (js2-peek-token))
10268 (cond
10269 ((or (= tt js2-LB)
10270 (= tt js2-LC))
10271 (js2-get-token)
10272 (setq iter (js2-parse-destruct-primary-expr))
10273 (js2-define-destruct-symbols iter js2-LET
10274 'font-lock-variable-name-face t))
10275 ((js2-match-token js2-NAME)
10276 (setq iter (js2-create-name-node)))
10277 (t
10278 (js2-report-error "msg.bad.var")))
10279 ;; Define as a let since we want the scope of the variable to
10280 ;; be restricted to the array comprehension
10281 (if (js2-name-node-p iter)
10282 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10283 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10284 (and (>= js2-language-version 200)
10285 (js2-match-contextual-kwd "of")
10286 (setq forof-p t)))
10287 (setq in-pos (- (js2-current-token-beg) pos))
10288 (js2-report-error "msg.in.after.for.name"))
10289 (setq obj (js2-parse-expr))
10290 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10291 (setq rp (- (js2-current-token-beg) pos)))
10292 (setf (js2-node-pos pn) pos
10293 (js2-node-len pn) (- js2-ts-cursor pos)
10294 (js2-comp-loop-node-iterator pn) iter
10295 (js2-comp-loop-node-object pn) obj
10296 (js2-comp-loop-node-in-pos pn) in-pos
10297 (js2-comp-loop-node-each-pos pn) each-pos
10298 (js2-comp-loop-node-foreach-p pn) foreach-p
10299 (js2-comp-loop-node-forof-p pn) forof-p
10300 (js2-comp-loop-node-lp pn) lp
10301 (js2-comp-loop-node-rp pn) rp)
10302 (js2-node-add-children pn iter obj)
10303 pn))
10304
10305 (defun js2-parse-class-stmt ()
10306 (let ((pos (js2-current-token-beg))
10307 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10308 (name (js2-create-name-node t)))
10309 (js2-set-face (js2-node-pos name) (js2-node-end name)
10310 'font-lock-function-name-face 'record)
10311 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10312 (js2-define-symbol js2-FUNCTION
10313 (js2-name-node-name name)
10314 node)
10315 node)))
10316
10317 (defun js2-parse-class-expr ()
10318 (let ((pos (js2-current-token-beg))
10319 name)
10320 (when (js2-match-token js2-NAME)
10321 (setq name (js2-create-name-node t)))
10322 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10323
10324 (defun js2-parse-class (pos form name)
10325 ;; class X [extends ...] {
10326 (let (pn elems extends)
10327 (if (js2-match-token js2-EXTENDS)
10328 (if (= (js2-peek-token) js2-LC)
10329 (js2-report-error "msg.missing.extends")
10330 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10331 (setq extends (js2-parse-assign-expr))
10332 (if (not extends)
10333 (js2-report-error "msg.bad.extends"))))
10334 (js2-must-match js2-LC "msg.no.brace.class")
10335 (setq elems (js2-parse-object-literal-elems t)
10336 pn (make-js2-class-node :pos pos
10337 :len (- js2-ts-cursor pos)
10338 :form form
10339 :name name
10340 :extends extends
10341 :elems elems))
10342 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10343 pn))
10344
10345 (defun js2-parse-object-literal ()
10346 (let* ((pos (js2-current-token-beg))
10347 (elems (js2-parse-object-literal-elems))
10348 (result (make-js2-object-node :pos pos
10349 :len (- js2-ts-cursor pos)
10350 :elems elems)))
10351 (apply #'js2-node-add-children result (js2-object-node-elems result))
10352 result))
10353
10354 (defun js2-parse-object-literal-elems (&optional class-p)
10355 (let ((pos (js2-current-token-beg))
10356 (static nil)
10357 (continue t)
10358 tt elems elem after-comma previous-token)
10359 (while continue
10360 (setq tt (js2-get-prop-name-token)
10361 static nil
10362 elem nil
10363 previous-token nil)
10364 ;; Handle 'static' keyword only if we're in a class
10365 (when (and class-p (= js2-NAME tt)
10366 (string= "static" (js2-current-token-string)))
10367 (js2-record-face 'font-lock-keyword-face)
10368 (setq static t
10369 tt (js2-get-prop-name-token)))
10370 ;; Handle generator * before the property name for in-line functions
10371 (when (and (>= js2-language-version 200)
10372 (= js2-MUL tt))
10373 (setq previous-token (js2-current-token)
10374 tt (js2-get-prop-name-token)))
10375 ;; Handle 'get' or 'set' keywords
10376 (let ((prop (js2-current-token-string)))
10377 (when (and (>= js2-language-version 200)
10378 (= js2-NAME tt)
10379 (or (string= prop "get")
10380 (string= prop "set"))
10381 (member (js2-peek-token)
10382 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10383 (setq previous-token (js2-current-token)
10384 tt (js2-get-prop-name-token))))
10385 (cond
10386 ;; Found a property (of any sort)
10387 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10388 (setq after-comma nil
10389 elem (js2-parse-named-prop tt pos previous-token))
10390 (if (and (null elem)
10391 (not js2-recover-from-parse-errors))
10392 (setq continue nil)))
10393 ;; Break out of loop, and handle trailing commas.
10394 ((or (= tt js2-RC)
10395 (= tt js2-EOF))
10396 (js2-unget-token)
10397 (setq continue nil)
10398 (if after-comma
10399 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10400 pos elems after-comma)))
10401 (t
10402 (js2-report-error "msg.bad.prop")
10403 (unless js2-recover-from-parse-errors
10404 (setq continue nil)))) ; end switch
10405 ;; Handle static for classes' codegen.
10406 (if static
10407 (if elem (js2-node-set-prop elem 'STATIC t)
10408 (js2-report-error "msg.unexpected.static")))
10409 ;; Handle commas, depending on class-p.
10410 (let ((tok (js2-get-prop-name-token)))
10411 (if (eq tok js2-COMMA)
10412 (if class-p
10413 (js2-report-error "msg.class.unexpected.comma")
10414 (setq after-comma (js2-current-token-end)))
10415 (js2-unget-token)
10416 (unless class-p (setq continue nil))))
10417 ;; Append any parsed element.
10418 (if elem (push elem elems))) ; end loop
10419 (js2-must-match js2-RC "msg.no.brace.prop")
10420 (nreverse elems)))
10421
10422 (defun js2-parse-named-prop (tt pos previous-token)
10423 "Parse a name, string, or getter/setter object property.
10424 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10425 (let ((key (cond
10426 ;; Literal string keys: {'foo': 'bar'}
10427 ((= tt js2-STRING)
10428 (make-js2-string-node))
10429 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10430 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10431 ((and (= tt js2-LB)
10432 (>= js2-language-version 200))
10433 (prog1 (js2-parse-expr)
10434 (js2-must-match js2-RB "msg.missing.computed.rb")))
10435 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10436 ((= tt js2-NUMBER)
10437 (make-js2-number-node))
10438 ;; Unquoted names: {foo: 12}
10439 ((= tt js2-NAME)
10440 (js2-create-name-node))
10441 ;; Anything else is an error
10442 (t (js2-report-error "msg.bad.prop"))))
10443 expr
10444 (prop (and previous-token (js2-token-string previous-token)))
10445 (property-type (when previous-token
10446 (if (= (js2-token-type previous-token) js2-MUL)
10447 "*"
10448 (js2-token-string previous-token)))))
10449 (when (or (string= prop "get")
10450 (string= prop "set"))
10451 (js2-set-face (js2-token-beg previous-token)
10452 (js2-token-end previous-token)
10453 'font-lock-keyword-face 'record)) ; get/set
10454 (cond
10455 ;; method definition: {f() {...}}
10456 ((and (= (js2-peek-token) js2-LP)
10457 (>= js2-language-version 200))
10458 (when (js2-name-node-p key) ; highlight function name properties
10459 (js2-record-face 'font-lock-function-name-face))
10460 (js2-parse-getter-setter-prop pos key property-type))
10461 ;; regular prop
10462 (t
10463 (prog1
10464 (setq expr (js2-parse-plain-property key))
10465 (when (and (= tt js2-NAME)
10466 (not js2-is-in-destructuring)
10467 js2-highlight-external-variables
10468 (js2-node-get-prop expr 'SHORTHAND))
10469 (js2-record-name-node key))
10470 (js2-set-face (js2-current-token-beg) (js2-current-token-end)
10471 (if (js2-function-node-p
10472 (js2-object-prop-node-right expr))
10473 'font-lock-function-name-face
10474 'font-lock-variable-name-face)
10475 'record))))))
10476
10477 (defun js2-parse-plain-property (prop)
10478 "Parse a non-getter/setter property in an object literal.
10479 PROP is the node representing the property: a number, name or string."
10480 (let* ((tt (js2-get-token))
10481 (pos (js2-node-pos prop))
10482 colon expr result)
10483 (cond
10484 ;; Abbreviated property, as in {foo, bar}
10485 ((and (>= js2-language-version 200)
10486 (or (= tt js2-COMMA)
10487 (= tt js2-RC))
10488 (not (js2-number-node-p prop)))
10489 (js2-unget-token)
10490 (setq result (make-js2-object-prop-node
10491 :pos pos
10492 :left prop
10493 :right prop
10494 :op-pos (js2-current-token-len)))
10495 (js2-node-add-children result prop)
10496 (js2-node-set-prop result 'SHORTHAND t)
10497 result)
10498 ;; Normal property
10499 (t
10500 (if (= tt js2-COLON)
10501 (setq colon (- (js2-current-token-beg) pos)
10502 expr (js2-parse-assign-expr))
10503 (js2-report-error "msg.no.colon.prop")
10504 (setq expr (make-js2-error-node)))
10505 (setq result (make-js2-object-prop-node
10506 :pos pos
10507 ;; don't include last consumed token in length
10508 :len (- (+ (js2-node-pos expr)
10509 (js2-node-len expr))
10510 pos)
10511 :left prop
10512 :right expr
10513 :op-pos colon))
10514 (js2-node-add-children result prop expr)
10515 result))))
10516
10517 (defun js2-parse-getter-setter-prop (pos prop type-string)
10518 "Parse getter or setter property in an object literal.
10519 JavaScript syntax is:
10520
10521 { get foo() {...}, set foo(x) {...} }
10522
10523 and expression closure style is also supported
10524
10525 { get foo() x, set foo(x) _x = x }
10526
10527 POS is the start position of the `get' or `set' keyword.
10528 PROP is the `js2-name-node' representing the property name.
10529 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10530 (let ((type (cond
10531 ((string= "get" type-string) js2-GET)
10532 ((string= "set" type-string) js2-SET)
10533 (t js2-FUNCTION)))
10534 result end
10535 (fn (js2-parse-function-expr)))
10536 ;; it has to be an anonymous function, as we already parsed the name
10537 (if (/= (js2-node-type fn) js2-FUNCTION)
10538 (js2-report-error "msg.bad.prop")
10539 (if (cl-plusp (length (js2-function-name fn)))
10540 (js2-report-error "msg.bad.prop")))
10541 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10542 (when (string= type-string "*")
10543 (setf (js2-function-node-generator-type fn) 'STAR))
10544 (setq end (js2-node-end fn)
10545 result (make-js2-getter-setter-node :type type
10546 :pos pos
10547 :len (- end pos)
10548 :left prop
10549 :right fn))
10550 (js2-node-add-children result prop fn)
10551 result))
10552
10553 (defun js2-create-name-node (&optional check-activation-p token string)
10554 "Create a name node using the current token and, optionally, STRING.
10555 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10556 (let* ((beg (js2-current-token-beg))
10557 (tt (js2-current-token-type))
10558 (s (or string
10559 (if (= js2-NAME tt)
10560 (js2-current-token-string)
10561 (js2-tt-name tt))))
10562 name)
10563 (setq name (make-js2-name-node :pos beg
10564 :name s
10565 :len (length s)))
10566 (if check-activation-p
10567 (js2-check-activation-name s (or token js2-NAME)))
10568 name))
10569
10570 ;;; Indentation support
10571
10572 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10573 ;; Karl cleverly deduces that the desired indentation level is often a
10574 ;; function of paren/bracket/brace nesting depth, which can be determined
10575 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10576 ;; then does some equally clever checks to see if we're in the context of a
10577 ;; substatement of a possibly braceless statement keyword such as if, while,
10578 ;; or finally. This approach yields pretty good results.
10579
10580 ;; The indenter is often "wrong", however, and needs to be overridden.
10581 ;; The right long-term solution is probably to emulate (or integrate
10582 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10583 ;; parse tree from `js2-parse' is present, which is not true at the
10584 ;; moment the user is typing, computing indentation is still thousands
10585 ;; of lines of code to handle every possible syntactic edge case.
10586
10587 ;; In the meantime, the compromise solution is that we offer a "bounce
10588 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10589 ;; current line indent among various likely guess points. This approach
10590 ;; is far from perfect, but should at least make it slightly easier to
10591 ;; move the line towards its desired indentation when manually
10592 ;; overriding Karl's heuristic nesting guesser.
10593
10594 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10595 ;; extensions such as `let' and Array comprehensions. Major kudos to
10596 ;; Karl for coming up with the initial approach, which packs a lot of
10597 ;; punch for so little code.
10598
10599 (defconst js2-possibly-braceless-keywords-re
10600 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10601 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10602 "try" "while" "with" "let")))
10603 "Regular expression matching keywords that are optionally
10604 followed by an opening brace.")
10605
10606 (defconst js2-indent-operator-re
10607 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10608 (regexp-opt '("in" "instanceof") 'words))
10609 "Regular expression matching operators that affect indentation
10610 of continued expressions.")
10611
10612 (defconst js2-declaration-keyword-re
10613 (regexp-opt '("var" "let" "const") 'words)
10614 "Regular expression matching variable declaration keywords.")
10615
10616 (defun js2-re-search-forward-inner (regexp &optional bound count)
10617 "Auxiliary function for `js2-re-search-forward'."
10618 (let (parse saved-point)
10619 (while (> count 0)
10620 (re-search-forward regexp bound)
10621 (setq parse (if saved-point
10622 (parse-partial-sexp saved-point (point))
10623 (syntax-ppss (point))))
10624 (cond ((nth 3 parse)
10625 (re-search-forward
10626 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10627 (save-excursion (end-of-line) (point)) t))
10628 ((nth 7 parse)
10629 (forward-line))
10630 ((or (nth 4 parse)
10631 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10632 (re-search-forward "\\*/"))
10633 (t
10634 (setq count (1- count))))
10635 (setq saved-point (point))))
10636 (point))
10637
10638 (defun js2-re-search-forward (regexp &optional bound noerror count)
10639 "Search forward but ignore strings and comments.
10640 Invokes `re-search-forward' but treats the buffer as if strings
10641 and comments have been removed."
10642 (let ((saved-point (point)))
10643 (condition-case err
10644 (cond ((null count)
10645 (js2-re-search-forward-inner regexp bound 1))
10646 ((< count 0)
10647 (js2-re-search-backward-inner regexp bound (- count)))
10648 ((> count 0)
10649 (js2-re-search-forward-inner regexp bound count)))
10650 (search-failed
10651 (goto-char saved-point)
10652 (unless noerror
10653 (error (error-message-string err)))))))
10654
10655 (defun js2-re-search-backward-inner (regexp &optional bound count)
10656 "Auxiliary function for `js2-re-search-backward'."
10657 (let (parse)
10658 (while (> count 0)
10659 (re-search-backward regexp bound)
10660 (setq parse (syntax-ppss (point)))
10661 (cond ((nth 3 parse)
10662 (re-search-backward
10663 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10664 (line-beginning-position) t))
10665 ((nth 7 parse)
10666 (goto-char (nth 8 parse)))
10667 ((or (nth 4 parse)
10668 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10669 (re-search-backward "/\\*"))
10670 (t
10671 (setq count (1- count))))))
10672 (point))
10673
10674 (defun js2-re-search-backward (regexp &optional bound noerror count)
10675 "Search backward but ignore strings and comments.
10676 Invokes `re-search-backward' but treats the buffer as if strings
10677 and comments have been removed."
10678 (let ((saved-point (point)))
10679 (condition-case err
10680 (cond ((null count)
10681 (js2-re-search-backward-inner regexp bound 1))
10682 ((< count 0)
10683 (js2-re-search-forward-inner regexp bound (- count)))
10684 ((> count 0)
10685 (js2-re-search-backward-inner regexp bound count)))
10686 (search-failed
10687 (goto-char saved-point)
10688 (unless noerror
10689 (error (error-message-string err)))))))
10690
10691 (defun js2-looking-at-operator-p ()
10692 "Return non-nil if text after point is a non-comma operator."
10693 (and (looking-at js2-indent-operator-re)
10694 (or (not (looking-at ":"))
10695 (save-excursion
10696 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10697 (looking-at "?"))))))
10698
10699 (defun js2-continued-expression-p ()
10700 "Return non-nil if the current line continues an expression."
10701 (save-excursion
10702 (back-to-indentation)
10703 (or (js2-looking-at-operator-p)
10704 (when (catch 'found
10705 (while (and (re-search-backward "\n" nil t)
10706 (let ((state (syntax-ppss)))
10707 (when (nth 4 state)
10708 (goto-char (nth 8 state))) ;; skip comments
10709 (skip-chars-backward " \t")
10710 (if (bolp)
10711 t
10712 (throw 'found t))))))
10713 (backward-char)
10714 (when (js2-looking-at-operator-p)
10715 (backward-char)
10716 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10717
10718 (defun js2-end-of-do-while-loop-p ()
10719 "Return non-nil if word after point is `while' of a do-while
10720 statement, else returns nil. A braceless do-while statement
10721 spanning several lines requires that the start of the loop is
10722 indented to the same column as the current line."
10723 (interactive)
10724 (save-excursion
10725 (when (looking-at "\\s-*\\<while\\>")
10726 (if (save-excursion
10727 (skip-chars-backward "[ \t\n]*}")
10728 (looking-at "[ \t\n]*}"))
10729 (save-excursion
10730 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10731 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10732 (or (looking-at "\\<do\\>")
10733 (let ((saved-indent (current-indentation)))
10734 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10735 (/= (current-indentation) saved-indent)))
10736 (and (looking-at "[ \t]*\\<do\\>")
10737 (not (js2-re-search-forward
10738 "\\<while\\>" (point-at-eol) t))
10739 (= (current-indentation) saved-indent))))))))
10740
10741 (defun js2-multiline-decl-indentation ()
10742 "Return the declaration indentation column if the current line belongs
10743 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10744 (let (forward-sexp-function ; use Lisp version
10745 at-opening-bracket)
10746 (save-excursion
10747 (back-to-indentation)
10748 (when (not (looking-at js2-declaration-keyword-re))
10749 (when (looking-at js2-indent-operator-re)
10750 (goto-char (match-end 0))) ; continued expressions are ok
10751 (while (and (not at-opening-bracket)
10752 (not (bobp))
10753 (let ((pos (point)))
10754 (save-excursion
10755 (js2-backward-sws)
10756 (or (eq (char-before) ?,)
10757 (and (not (eq (char-before) ?\;))
10758 (prog2 (skip-syntax-backward ".")
10759 (looking-at js2-indent-operator-re)
10760 (js2-backward-sws))
10761 (not (eq (char-before) ?\;)))
10762 (js2-same-line pos)))))
10763 (condition-case _
10764 (backward-sexp)
10765 (scan-error (setq at-opening-bracket t))))
10766 (when (looking-at js2-declaration-keyword-re)
10767 (goto-char (match-end 0))
10768 (1+ (current-column)))))))
10769
10770 (defun js2-ctrl-statement-indentation ()
10771 "Return the proper indentation of current line if it is a control statement.
10772 Returns an indentation if this line starts the body of a control
10773 statement without braces, else returns nil."
10774 (let (forward-sexp-function)
10775 (save-excursion
10776 (back-to-indentation)
10777 (when (and (not (js2-same-line (point-min)))
10778 (not (looking-at "{"))
10779 (js2-re-search-backward "[[:graph:]]" nil t)
10780 (not (looking-at "[{([]"))
10781 (progn
10782 (forward-char)
10783 (when (= (char-before) ?\))
10784 ;; scan-sexps sometimes throws an error
10785 (ignore-errors (backward-sexp))
10786 (skip-chars-backward " \t" (point-at-bol)))
10787 (let ((pt (point)))
10788 (back-to-indentation)
10789 (when (looking-at "}[ \t]*")
10790 (goto-char (match-end 0)))
10791 (and (looking-at js2-possibly-braceless-keywords-re)
10792 (= (match-end 0) pt)
10793 (not (js2-end-of-do-while-loop-p))))))
10794 (+ (current-indentation) js2-basic-offset)))))
10795
10796 (defun js2-indent-in-array-comp (parse-status)
10797 "Return non-nil if we think we're in an array comprehension.
10798 In particular, return the buffer position of the first `for' kwd."
10799 (let ((bracket (nth 1 parse-status))
10800 (end (point)))
10801 (when bracket
10802 (save-excursion
10803 (goto-char bracket)
10804 (when (looking-at "\\[")
10805 (forward-char 1)
10806 (js2-forward-sws)
10807 (if (looking-at "[[{]")
10808 (let (forward-sexp-function) ; use Lisp version
10809 (forward-sexp) ; skip destructuring form
10810 (js2-forward-sws)
10811 (if (and (/= (char-after) ?,) ; regular array
10812 (looking-at "for"))
10813 (match-beginning 0)))
10814 ;; to skip arbitrary expressions we need the parser,
10815 ;; so we'll just guess at it.
10816 (if (and (> end (point)) ; not empty literal
10817 (re-search-forward "[^,]]* \\(for\\) " end t)
10818 ;; not inside comment or string literal
10819 (let ((state (parse-partial-sexp bracket (point))))
10820 (not (or (nth 3 state) (nth 4 state)))))
10821 (match-beginning 1))))))))
10822
10823 (defun js2-array-comp-indentation (parse-status for-kwd)
10824 (if (js2-same-line for-kwd)
10825 ;; first continuation line
10826 (save-excursion
10827 (goto-char (nth 1 parse-status))
10828 (forward-char 1)
10829 (skip-chars-forward " \t")
10830 (current-column))
10831 (save-excursion
10832 (goto-char for-kwd)
10833 (current-column))))
10834
10835 (defun js2-maybe-goto-declaration-keyword-end (bracket)
10836 "Helper function for `js2-proper-indentation'.
10837 Depending on the value of `js2-pretty-multiline-declarations',
10838 move point to the end of a variable declaration keyword so that
10839 indentation is aligned to that column."
10840 (cond
10841 ((eq js2-pretty-multiline-declarations 'all)
10842 (when (looking-at js2-declaration-keyword-re)
10843 (goto-char (1+ (match-end 0)))))
10844 ((eq js2-pretty-multiline-declarations 'dynamic)
10845 (let (declaration-keyword-end
10846 at-closing-bracket-p
10847 comma-p)
10848 (when (looking-at js2-declaration-keyword-re)
10849 ;; Preserve the match data lest it somehow be overridden.
10850 (setq declaration-keyword-end (match-end 0))
10851 (save-excursion
10852 (goto-char bracket)
10853 (setq at-closing-bracket-p
10854 ;; Handle scan errors gracefully.
10855 (condition-case nil
10856 (progn
10857 ;; Use the regular `forward-sexp-function' because the
10858 ;; normal one for this mode uses the AST.
10859 (let (forward-sexp-function)
10860 (forward-sexp))
10861 t)
10862 (error nil)))
10863 (when at-closing-bracket-p
10864 (js2-forward-sws)
10865 (setq comma-p (looking-at-p ","))))
10866 (when comma-p
10867 (goto-char (1+ declaration-keyword-end))))))))
10868
10869 (defun js2-proper-indentation (parse-status)
10870 "Return the proper indentation for the current line."
10871 (save-excursion
10872 (back-to-indentation)
10873 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10874 (at-closing-bracket (looking-at "[]})]"))
10875 (same-indent-p (or at-closing-bracket
10876 (looking-at "\\<case\\>[^:]")
10877 (and (looking-at "\\<default:")
10878 (save-excursion
10879 (js2-backward-sws)
10880 (not (memq (char-before) '(?, ?{)))))))
10881 (continued-expr-p (js2-continued-expression-p))
10882 (declaration-indent (and js2-pretty-multiline-declarations
10883 (js2-multiline-decl-indentation)))
10884 (bracket (nth 1 parse-status))
10885 beg indent)
10886 (cond
10887 ;; indent array comprehension continuation lines specially
10888 ((and bracket
10889 (>= js2-language-version 170)
10890 (not (js2-same-line bracket))
10891 (setq beg (js2-indent-in-array-comp parse-status))
10892 (>= (point) (save-excursion
10893 (goto-char beg)
10894 (point-at-bol)))) ; at or after first loop?
10895 (js2-array-comp-indentation parse-status beg))
10896
10897 (ctrl-stmt-indent)
10898
10899 ((and declaration-indent continued-expr-p)
10900 (+ declaration-indent js2-basic-offset))
10901
10902 (declaration-indent)
10903
10904 (bracket
10905 (goto-char bracket)
10906 (cond
10907 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10908 (when (save-excursion (skip-chars-backward " \t)")
10909 (looking-at ")"))
10910 (backward-list))
10911 (back-to-indentation)
10912 (js2-maybe-goto-declaration-keyword-end bracket)
10913 (setq indent
10914 (cond (same-indent-p
10915 (current-column))
10916 (continued-expr-p
10917 (+ (current-column) (* 2 js2-basic-offset)))
10918 (t
10919 (+ (current-column) js2-basic-offset))))
10920 (if (and js2-indent-switch-body
10921 (not at-closing-bracket)
10922 (looking-at "\\_<switch\\_>"))
10923 (+ indent js2-basic-offset)
10924 indent))
10925 (t
10926 (unless same-indent-p
10927 (forward-char)
10928 (skip-chars-forward " \t"))
10929 (current-column))))
10930
10931 (continued-expr-p js2-basic-offset)
10932
10933 (t 0)))))
10934
10935 (defun js2-lineup-comment (parse-status)
10936 "Indent a multi-line block comment continuation line."
10937 (let* ((beg (nth 8 parse-status))
10938 (first-line (js2-same-line beg))
10939 (offset (save-excursion
10940 (goto-char beg)
10941 (if (looking-at "/\\*")
10942 (+ 1 (current-column))
10943 0))))
10944 (unless first-line
10945 (indent-line-to offset))))
10946
10947 (defun js2-backward-sws ()
10948 "Move backward through whitespace and comments."
10949 (interactive)
10950 (while (forward-comment -1)))
10951
10952 (defun js2-forward-sws ()
10953 "Move forward through whitespace and comments."
10954 (interactive)
10955 (while (forward-comment 1)))
10956
10957 (defun js2-current-indent (&optional pos)
10958 "Return column of indentation on current line.
10959 If POS is non-nil, go to that point and return indentation for that line."
10960 (save-excursion
10961 (if pos
10962 (goto-char pos))
10963 (back-to-indentation)
10964 (current-column)))
10965
10966 (defun js2-arglist-close ()
10967 "Return non-nil if we're on a line beginning with a close-paren/brace."
10968 (save-excursion
10969 (goto-char (point-at-bol))
10970 (js2-forward-sws)
10971 (looking-at "[])}]")))
10972
10973 (defun js2-indent-looks-like-label-p ()
10974 (goto-char (point-at-bol))
10975 (js2-forward-sws)
10976 (looking-at (concat js2-mode-identifier-re ":")))
10977
10978 (defun js2-indent-in-objlit-p (parse-status)
10979 "Return non-nil if this looks like an object-literal entry."
10980 (let ((start (nth 1 parse-status)))
10981 (and
10982 start
10983 (save-excursion
10984 (and (zerop (forward-line -1))
10985 (not (< (point) start)) ; crossed a {} boundary
10986 (js2-indent-looks-like-label-p)))
10987 (save-excursion
10988 (js2-indent-looks-like-label-p)))))
10989
10990 ;; If prev line looks like foobar({ then we're passing an object
10991 ;; literal to a function call, and people pretty much always want to
10992 ;; de-dent back to the previous line, so move the 'basic-offset'
10993 ;; position to the front.
10994 (defun js2-indent-objlit-arg-p (parse-status)
10995 (save-excursion
10996 (back-to-indentation)
10997 (js2-backward-sws)
10998 (and (eq (1- (point)) (nth 1 parse-status))
10999 (eq (char-before) ?{)
11000 (progn
11001 (forward-char -1)
11002 (skip-chars-backward " \t")
11003 (eq (char-before) ?\()))))
11004
11005 (defun js2-indent-case-block-p ()
11006 (save-excursion
11007 (back-to-indentation)
11008 (js2-backward-sws)
11009 (goto-char (point-at-bol))
11010 (skip-chars-forward " \t")
11011 (looking-at "case\\s-.+:")))
11012
11013 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
11014 "Cycle among alternate computed indentation positions.
11015 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11016 of the buffer to the current point. NORMAL-COL is the indentation
11017 column computed by the heuristic guesser based on current paren,
11018 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11019 in reverse."
11020 (let ((cur-indent (js2-current-indent))
11021 (old-buffer-undo-list buffer-undo-list)
11022 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11023 (current-line (save-excursion
11024 (forward-line 0) ; move to bol
11025 (1+ (count-lines (point-min) (point)))))
11026 positions pos main-pos anchor arglist-cont same-indent
11027 basic-offset computed-pos)
11028 ;; temporarily don't record undo info, if user requested this
11029 (when js2-mode-indent-inhibit-undo
11030 (setq buffer-undo-list t))
11031 (unwind-protect
11032 (progn
11033 ;; First likely point: indent from beginning of previous code line
11034 (push (setq basic-offset
11035 (+ (save-excursion
11036 (back-to-indentation)
11037 (js2-backward-sws)
11038 (back-to-indentation)
11039 (current-column))
11040 js2-basic-offset))
11041 positions)
11042
11043 ;; (First + epsilon) likely point: indent 2x from beginning of
11044 ;; previous code line. Google does it this way.
11045 (push (setq basic-offset
11046 (+ (save-excursion
11047 (back-to-indentation)
11048 (js2-backward-sws)
11049 (back-to-indentation)
11050 (current-column))
11051 (* 2 js2-basic-offset)))
11052 positions)
11053
11054 ;; Second likely point: indent from assign-expr RHS. This
11055 ;; is just a crude guess based on finding " = " on the previous
11056 ;; line containing actual code.
11057 (setq pos (save-excursion
11058 (forward-line -1)
11059 (goto-char (point-at-bol))
11060 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11061 (point-at-eol) t)
11062 (goto-char (match-end 1))
11063 (skip-chars-forward " \t\r\n")
11064 (current-column))))
11065 (when pos
11066 (cl-incf pos js2-basic-offset)
11067 (push pos positions))
11068
11069 ;; Third likely point: same indent as previous line of code.
11070 ;; Make it the first likely point if we're not on an
11071 ;; arglist-close line and previous line ends in a comma, or
11072 ;; both this line and prev line look like object-literal
11073 ;; elements.
11074 (setq pos (save-excursion
11075 (goto-char (point-at-bol))
11076 (js2-backward-sws)
11077 (back-to-indentation)
11078 (prog1
11079 (current-column)
11080 ;; while we're here, look for trailing comma
11081 (if (save-excursion
11082 (goto-char (point-at-eol))
11083 (js2-backward-sws)
11084 (eq (char-before) ?,))
11085 (setq arglist-cont (1- (point)))))))
11086 (when pos
11087 (if (and (or arglist-cont
11088 (js2-indent-in-objlit-p parse-status))
11089 (not (js2-arglist-close)))
11090 (setq same-indent pos))
11091 (push pos positions))
11092
11093 ;; Fourth likely point: first preceding code with less indentation.
11094 ;; than the immediately preceding code line.
11095 (setq pos (save-excursion
11096 (back-to-indentation)
11097 (js2-backward-sws)
11098 (back-to-indentation)
11099 (setq anchor (current-column))
11100 (while (and (zerop (forward-line -1))
11101 (>= (progn
11102 (back-to-indentation)
11103 (current-column))
11104 anchor)))
11105 (setq pos (current-column))))
11106 (push pos positions)
11107
11108 ;; nesting-heuristic position, main by default
11109 (push (setq main-pos normal-col) positions)
11110
11111 ;; delete duplicates and sort positions list
11112 (setq positions (sort (delete-dups positions) '<))
11113
11114 ;; comma-list continuation lines: prev line indent takes precedence
11115 (if same-indent
11116 (setq main-pos same-indent))
11117
11118 ;; common special cases where we want to indent in from previous line
11119 (if (or (js2-indent-case-block-p)
11120 (js2-indent-objlit-arg-p parse-status))
11121 (setq main-pos basic-offset))
11122
11123 ;; if bouncing backwards, reverse positions list
11124 (if backwards
11125 (setq positions (reverse positions)))
11126
11127 ;; record whether we're already sitting on one of the alternatives
11128 (setq pos (member cur-indent positions))
11129
11130 (cond
11131 ;; case 0: we're one one of the alternatives and this is the
11132 ;; first time they've pressed TAB on this line (best-guess).
11133 ((and js2-mode-indent-ignore-first-tab
11134 pos
11135 ;; first time pressing TAB on this line?
11136 (not (eq js2-mode-last-indented-line current-line)))
11137 ;; do nothing
11138 (setq computed-pos nil))
11139 ;; case 1: only one computed position => use it
11140 ((null (cdr positions))
11141 (setq computed-pos 0))
11142 ;; case 2: not on any of the computed spots => use main spot
11143 ((not pos)
11144 (setq computed-pos (js2-position main-pos positions)))
11145 ;; case 3: on last position: cycle to first position
11146 ((null (cdr pos))
11147 (setq computed-pos 0))
11148 ;; case 4: on intermediate position: cycle to next position
11149 (t
11150 (setq computed-pos (js2-position (cl-second pos) positions))))
11151
11152 ;; see if any hooks want to indent; otherwise we do it
11153 (cl-loop with result = nil
11154 for hook in js2-indent-hook
11155 while (null result)
11156 do
11157 (setq result (funcall hook positions computed-pos))
11158 finally do
11159 (unless (or result (null computed-pos))
11160 (indent-line-to (nth computed-pos positions)))))
11161
11162 ;; finally
11163 (if js2-mode-indent-inhibit-undo
11164 (setq buffer-undo-list old-buffer-undo-list))
11165 ;; see commentary for `js2-mode-last-indented-line'
11166 (setq js2-mode-last-indented-line current-line))))
11167
11168 (defun js2-indent-bounce-backwards ()
11169 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11170 cycles between the computed indentation positions in reverse order."
11171 (interactive)
11172 (js2-indent-line t))
11173
11174 (defun js2-1-line-comment-continuation-p ()
11175 "Return t if we're in a 1-line comment continuation.
11176 If so, we don't ever want to use bounce-indent."
11177 (save-excursion
11178 (and (progn
11179 (forward-line 0)
11180 (looking-at "\\s-*//"))
11181 (progn
11182 (forward-line -1)
11183 (forward-line 0)
11184 (when (looking-at "\\s-*$")
11185 (js2-backward-sws)
11186 (forward-line 0))
11187 (looking-at "\\s-*//")))))
11188
11189 (defun js2-indent-line (&optional bounce-backwards)
11190 "Indent the current line as JavaScript source text."
11191 (interactive)
11192 (let (parse-status offset indent-col
11193 ;; Don't whine about errors/warnings when we're indenting.
11194 ;; This has to be set before calling parse-partial-sexp below.
11195 (inhibit-point-motion-hooks t))
11196 (setq parse-status (save-excursion
11197 (syntax-ppss (point-at-bol)))
11198 offset (- (point) (save-excursion
11199 (back-to-indentation)
11200 (point))))
11201 ;; Don't touch multiline strings.
11202 (unless (nth 3 parse-status)
11203 (js2-with-underscore-as-word-syntax
11204 (if (nth 4 parse-status)
11205 (js2-lineup-comment parse-status)
11206 (setq indent-col (js2-proper-indentation parse-status))
11207 ;; See comments below about `js2-mode-last-indented-line'.
11208 (cond
11209 ;; bounce-indenting is disabled during electric-key indent.
11210 ;; It doesn't work well on first line of buffer.
11211 ((and js2-bounce-indent-p
11212 (not (js2-same-line (point-min)))
11213 (not (js2-1-line-comment-continuation-p)))
11214 (js2-bounce-indent indent-col parse-status bounce-backwards))
11215 ;; just indent to the guesser's likely spot
11216 (t (indent-line-to indent-col))))
11217 (when (cl-plusp offset)
11218 (forward-char offset))))))
11219
11220 (defun js2-indent-region (start end)
11221 "Indent the region, but don't use bounce indenting."
11222 (let ((js2-bounce-indent-p nil)
11223 (indent-region-function nil)
11224 (after-change-functions (remq 'js2-mode-edit
11225 after-change-functions)))
11226 (indent-region start end nil) ; nil for byte-compiler
11227 (js2-mode-edit start end (- end start))))
11228
11229 (defvar js2-minor-mode-map
11230 (let ((map (make-sparse-keymap)))
11231 (define-key map (kbd "C-c C-`") #'js2-next-error)
11232 (define-key map [mouse-1] #'js2-mode-show-node)
11233 map)
11234 "Keymap used when `js2-minor-mode' is active.")
11235
11236 ;;;###autoload
11237 (define-minor-mode js2-minor-mode
11238 "Minor mode for running js2 as a background linter.
11239 This allows you to use a different major mode for JavaScript editing,
11240 such as `js-mode', while retaining the asynchronous error/warning
11241 highlighting features of `js2-mode'."
11242 :group 'js2-mode
11243 :lighter " js-lint"
11244 (if js2-minor-mode
11245 (js2-minor-mode-enter)
11246 (js2-minor-mode-exit)))
11247
11248 (defun js2-minor-mode-enter ()
11249 "Initialization for `js2-minor-mode'."
11250 (set (make-local-variable 'max-lisp-eval-depth)
11251 (max max-lisp-eval-depth 3000))
11252 (setq next-error-function #'js2-next-error)
11253 (js2-set-default-externs)
11254 ;; Experiment: make reparse-delay longer for longer files.
11255 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11256 (setq js2-idle-timer-delay
11257 (* js2-idle-timer-delay
11258 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11259 (setq js2-mode-buffer-dirty-p t
11260 js2-mode-parsing nil)
11261 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11262 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11263 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11264 (when js2-include-jslint-globals
11265 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11266 (run-hooks 'js2-init-hook)
11267 (js2-reparse))
11268
11269 (defun js2-minor-mode-exit ()
11270 "Turn off `js2-minor-mode'."
11271 (setq next-error-function nil)
11272 (remove-hook 'after-change-functions #'js2-mode-edit t)
11273 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11274 (when js2-mode-node-overlay
11275 (delete-overlay js2-mode-node-overlay)
11276 (setq js2-mode-node-overlay nil))
11277 (js2-remove-overlays)
11278 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11279 (setq js2-mode-ast nil))
11280
11281 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11282 (make-variable-buffer-local 'js2-source-buffer)
11283
11284 (cl-defun js2-display-error-list ()
11285 "Display a navigable buffer listing parse errors/warnings."
11286 (interactive)
11287 (unless (js2-have-errors-p)
11288 (message "No errors")
11289 (cl-return-from js2-display-error-list))
11290 (cl-labels ((annotate-list
11291 (lst type)
11292 "Add diagnostic TYPE and line number to errs list"
11293 (mapcar (lambda (err)
11294 (list err type (line-number-at-pos (nth 1 err))))
11295 lst)))
11296 (let* ((srcbuf (current-buffer))
11297 (errbuf (get-buffer-create "*js-lint*"))
11298 (errors (annotate-list
11299 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11300 'js2-error)) ; must be a valid face name
11301 (warnings (annotate-list
11302 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11303 'js2-warning)) ; must be a valid face name
11304 (all-errs (sort (append errors warnings)
11305 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11306 (with-current-buffer errbuf
11307 (let ((inhibit-read-only t))
11308 (erase-buffer)
11309 (dolist (err all-errs)
11310 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11311 (insert-text-button
11312 (format "line %d: %s" line (js2-get-msg msg-key))
11313 'face type
11314 'follow-link "\C-m"
11315 'action 'js2-error-buffer-jump
11316 'js2-msg (js2-get-msg msg-key)
11317 'js2-pos beg)
11318 (insert "\n"))))
11319 (js2-error-buffer-mode)
11320 (setq js2-source-buffer srcbuf)
11321 (pop-to-buffer errbuf)
11322 (goto-char (point-min))
11323 (unless (eobp)
11324 (js2-error-buffer-view))))))
11325
11326 (defvar js2-error-buffer-mode-map
11327 (let ((map (make-sparse-keymap)))
11328 (define-key map "n" #'js2-error-buffer-next)
11329 (define-key map "p" #'js2-error-buffer-prev)
11330 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11331 (define-key map "o" #'js2-error-buffer-view)
11332 (define-key map "q" #'js2-error-buffer-quit)
11333 map)
11334 "Keymap used for js2 diagnostics buffers.")
11335
11336 (defun js2-error-buffer-mode ()
11337 "Major mode for js2 diagnostics buffers.
11338 Selecting an error will jump it to the corresponding source-buffer error.
11339 \\{js2-error-buffer-mode-map}"
11340 (interactive)
11341 (setq major-mode 'js2-error-buffer-mode
11342 mode-name "JS Lint Diagnostics")
11343 (use-local-map js2-error-buffer-mode-map)
11344 (setq truncate-lines t)
11345 (set-buffer-modified-p nil)
11346 (setq buffer-read-only t)
11347 (run-hooks 'js2-error-buffer-mode-hook))
11348
11349 (defun js2-error-buffer-next ()
11350 "Move to next error and view it."
11351 (interactive)
11352 (when (zerop (forward-line 1))
11353 (js2-error-buffer-view)))
11354
11355 (defun js2-error-buffer-prev ()
11356 "Move to previous error and view it."
11357 (interactive)
11358 (when (zerop (forward-line -1))
11359 (js2-error-buffer-view)))
11360
11361 (defun js2-error-buffer-quit ()
11362 "Kill the current buffer."
11363 (interactive)
11364 (kill-buffer))
11365
11366 (defun js2-error-buffer-jump (&rest ignored)
11367 "Jump cursor to current error in source buffer."
11368 (interactive)
11369 (when (js2-error-buffer-view)
11370 (pop-to-buffer js2-source-buffer)))
11371
11372 (defun js2-error-buffer-view ()
11373 "Scroll source buffer to show error at current line."
11374 (interactive)
11375 (cond
11376 ((not (eq major-mode 'js2-error-buffer-mode))
11377 (message "Not in a js2 errors buffer"))
11378 ((not (buffer-live-p js2-source-buffer))
11379 (message "Source buffer has been killed"))
11380 ((not (wholenump (get-text-property (point) 'js2-pos)))
11381 (message "There does not seem to be an error here"))
11382 (t
11383 (let ((pos (get-text-property (point) 'js2-pos))
11384 (msg (get-text-property (point) 'js2-msg)))
11385 (save-selected-window
11386 (pop-to-buffer js2-source-buffer)
11387 (goto-char pos)
11388 (message msg))))))
11389
11390 ;;;###autoload
11391 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11392 ;; FIXME: Should derive from js-mode.
11393 "Major mode for editing JavaScript code."
11394 ;; Used by comment-region; don't change it.
11395 (set (make-local-variable 'comment-start) "//")
11396 (set (make-local-variable 'comment-end) "")
11397 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11398 (set (make-local-variable 'max-lisp-eval-depth)
11399 (max max-lisp-eval-depth 3000))
11400 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11401 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11402 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11403 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11404 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11405 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11406 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11407 ;; for characters inside regexp literals.
11408 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11409 ;; this is necessary to make `show-paren-function' work properly
11410 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11411 ;; needed for M-x rgrep, among other things
11412 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11413
11414 (set (make-local-variable 'electric-indent-chars)
11415 (append "{}()[]:;,*." electric-indent-chars))
11416 (set (make-local-variable 'electric-layout-rules)
11417 '((?\; . after) (?\{ . after) (?\} . before)))
11418
11419 ;; some variables needed by cc-engine for paragraph-fill, etc.
11420 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11421 c-comment-start-regexp "/[*/]\\|\\s|"
11422 c-line-comment-starter "//"
11423 c-paragraph-start js2-paragraph-start
11424 c-paragraph-separate "$"
11425 c-syntactic-ws-start js2-syntactic-ws-start
11426 c-syntactic-ws-end js2-syntactic-ws-end
11427 c-syntactic-eol js2-syntactic-eol)
11428
11429 (let ((c-buffer-is-cc-mode t))
11430 ;; Copied from `js-mode'. Also see Bug#6071.
11431 (make-local-variable 'paragraph-start)
11432 (make-local-variable 'paragraph-separate)
11433 (make-local-variable 'paragraph-ignore-fill-prefix)
11434 (make-local-variable 'adaptive-fill-mode)
11435 (make-local-variable 'adaptive-fill-regexp)
11436 (c-setup-paragraph-variables))
11437
11438 (setq font-lock-defaults '(nil t))
11439
11440 ;; Experiment: make reparse-delay longer for longer files.
11441 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11442 (setq js2-idle-timer-delay
11443 (* js2-idle-timer-delay
11444 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11445
11446 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11447 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11448 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11449 (setq next-error-function #'js2-next-error)
11450 (imenu-add-to-menubar (concat "IM-" mode-name))
11451 (add-to-invisibility-spec '(js2-outline . t))
11452 (set (make-local-variable 'line-move-ignore-invisible) t)
11453 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11454 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11455
11456 (setq js2-mode-functions-hidden nil
11457 js2-mode-comments-hidden nil
11458 js2-mode-buffer-dirty-p t
11459 js2-mode-parsing nil)
11460
11461 (js2-set-default-externs)
11462
11463 (when js2-include-jslint-globals
11464 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11465
11466 (run-hooks 'js2-init-hook)
11467
11468 (js2-reparse))
11469
11470 (defun js2-mode-exit ()
11471 "Exit `js2-mode' and clean up."
11472 (interactive)
11473 (when js2-mode-node-overlay
11474 (delete-overlay js2-mode-node-overlay)
11475 (setq js2-mode-node-overlay nil))
11476 (js2-remove-overlays)
11477 (setq js2-mode-ast nil)
11478 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11479 (remove-from-invisibility-spec '(js2-outline . t))
11480 (js2-mode-show-all)
11481 (with-silent-modifications
11482 (js2-clear-face (point-min) (point-max))))
11483
11484 (defun js2-mode-reset-timer ()
11485 "Cancel any existing parse timer and schedule a new one."
11486 (if js2-mode-parse-timer
11487 (cancel-timer js2-mode-parse-timer))
11488 (setq js2-mode-parsing nil)
11489 (let ((timer (timer-create)))
11490 (setq js2-mode-parse-timer timer)
11491 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11492 (timer-set-idle-time timer js2-idle-timer-delay)
11493 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11494 (timer-activate-when-idle timer nil)))
11495
11496 (defun js2-mode-idle-reparse (buffer)
11497 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11498 it to be reparsed when the buffer is selected."
11499 (cond ((eq buffer (current-buffer))
11500 (js2-reparse))
11501 ((buffer-live-p buffer)
11502 ;; reparse when the buffer is selected again
11503 (with-current-buffer buffer
11504 (add-hook 'window-configuration-change-hook
11505 #'js2-mode-idle-reparse-inner
11506 nil t)))))
11507
11508 (defun js2-mode-idle-reparse-inner ()
11509 (remove-hook 'window-configuration-change-hook
11510 #'js2-mode-idle-reparse-inner
11511 t)
11512 (js2-reparse))
11513
11514 (defun js2-mode-edit (_beg _end _len)
11515 "Schedule a new parse after buffer is edited.
11516 Buffer edit spans from BEG to END and is of length LEN."
11517 (setq js2-mode-buffer-dirty-p t)
11518 (js2-mode-hide-overlay)
11519 (js2-mode-reset-timer))
11520
11521 (defun js2-minor-mode-edit (_beg _end _len)
11522 "Callback for buffer edits in `js2-mode'.
11523 Schedules a new parse after buffer is edited.
11524 Buffer edit spans from BEG to END and is of length LEN."
11525 (setq js2-mode-buffer-dirty-p t)
11526 (js2-mode-hide-overlay)
11527 (js2-mode-reset-timer))
11528
11529 (defun js2-reparse (&optional force)
11530 "Re-parse current buffer after user finishes some data entry.
11531 If we get any user input while parsing, including cursor motion,
11532 we discard the parse and reschedule it. If FORCE is nil, then the
11533 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11534 (let (time
11535 interrupted-p
11536 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11537 (unless js2-mode-parsing
11538 (setq js2-mode-parsing t)
11539 (unwind-protect
11540 (when (or js2-mode-buffer-dirty-p force)
11541 (js2-remove-overlays)
11542 (setq js2-mode-buffer-dirty-p nil
11543 js2-mode-fontifications nil
11544 js2-mode-deferred-properties nil)
11545 (if js2-mode-verbose-parse-p
11546 (message "parsing..."))
11547 (setq time
11548 (js2-time
11549 (setq interrupted-p
11550 (catch 'interrupted
11551 (js2-parse)
11552 (with-silent-modifications
11553 ;; if parsing is interrupted, comments and regex
11554 ;; literals stay ignored by `parse-partial-sexp'
11555 (remove-text-properties (point-min) (point-max)
11556 '(syntax-table))
11557 (js2-mode-apply-deferred-properties)
11558 (js2-mode-remove-suppressed-warnings)
11559 (js2-mode-show-warnings)
11560 (js2-mode-show-errors)
11561 (if (>= js2-highlight-level 1)
11562 (js2-highlight-jsdoc js2-mode-ast)))
11563 nil))))
11564 (if interrupted-p
11565 (progn
11566 ;; unfinished parse => try again
11567 (setq js2-mode-buffer-dirty-p t)
11568 (js2-mode-reset-timer))
11569 (if js2-mode-verbose-parse-p
11570 (message "Parse time: %s" time))))
11571 (setq js2-mode-parsing nil)
11572 (unless interrupted-p
11573 (setq js2-mode-parse-timer nil))))))
11574
11575 (defun js2-mode-show-node (event)
11576 "Debugging aid: highlight selected AST node on mouse click."
11577 (interactive "e")
11578 (mouse-set-point event)
11579 (setq deactivate-mark t)
11580 (when js2-mode-show-overlay
11581 (let ((node (js2-node-at-point))
11582 beg end)
11583 (if (null node)
11584 (message "No node found at location %s" (point))
11585 (setq beg (js2-node-abs-pos node)
11586 end (+ beg (js2-node-len node)))
11587 (if js2-mode-node-overlay
11588 (move-overlay js2-mode-node-overlay beg end)
11589 (setq js2-mode-node-overlay (make-overlay beg end))
11590 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11591 (with-silent-modifications
11592 (if (fboundp 'cursor-sensor-mode)
11593 (put-text-property beg end 'cursor-sensor-functions
11594 '(js2-mode-hide-overlay))
11595 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11596 (message "%s, parent: %s"
11597 (js2-node-short-name node)
11598 (if (js2-node-parent node)
11599 (js2-node-short-name (js2-node-parent node))
11600 "nil"))))))
11601
11602 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11603 "Remove the debugging overlay when point moves.
11604 ARG1, ARG2 and ARG3 have different values depending on whether this function
11605 was found on `point-left' or in `cursor-sensor-functions'."
11606 (when js2-mode-node-overlay
11607 (let ((beg (overlay-start js2-mode-node-overlay))
11608 (end (overlay-end js2-mode-node-overlay))
11609 (p2 (if (windowp arg1)
11610 ;; Called from cursor-sensor-functions.
11611 (window-point arg1)
11612 ;; Called from point-left.
11613 arg2)))
11614 ;; Sometimes we're called spuriously.
11615 (unless (and p2
11616 (>= p2 beg)
11617 (<= p2 end))
11618 (with-silent-modifications
11619 (remove-text-properties beg end
11620 '(point-left nil cursor-sensor-functions)))
11621 (delete-overlay js2-mode-node-overlay)
11622 (setq js2-mode-node-overlay nil)))))
11623
11624 (defun js2-mode-reset ()
11625 "Debugging helper: reset everything."
11626 (interactive)
11627 (js2-mode-exit)
11628 (js2-mode))
11629
11630 (defun js2-mode-show-warn-or-err (e face)
11631 "Highlight a warning or error E with FACE.
11632 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11633 The last element is optional. When present, use instead of FACE."
11634 (let* ((key (cl-first e))
11635 (beg (cl-second e))
11636 (end (+ beg (cl-third e)))
11637 ;; Don't inadvertently go out of bounds.
11638 (beg (max (point-min) (min beg (point-max))))
11639 (end (max (point-min) (min end (point-max))))
11640 (ovl (make-overlay beg end)))
11641 ;; FIXME: Why a mix of overlays and text-properties?
11642 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11643 (overlay-put ovl 'js2-error t)
11644 (put-text-property beg end 'help-echo (js2-get-msg key))
11645 (if (fboundp 'cursor-sensor-mode)
11646 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11647 (put-text-property beg end 'point-entered #'js2-echo-error))))
11648
11649 (defun js2-remove-overlays ()
11650 "Remove overlays from buffer that have a `js2-error' property."
11651 (let ((beg (point-min))
11652 (end (point-max)))
11653 (save-excursion
11654 (dolist (o (overlays-in beg end))
11655 (when (overlay-get o 'js2-error)
11656 (delete-overlay o))))))
11657
11658 (defun js2-mode-apply-deferred-properties ()
11659 "Apply fontifications and other text properties recorded during parsing."
11660 (when (cl-plusp js2-highlight-level)
11661 ;; We defer clearing faces as long as possible to eliminate flashing.
11662 (js2-clear-face (point-min) (point-max))
11663 ;; Have to reverse the recorded fontifications list so that errors
11664 ;; and warnings overwrite the normal fontifications.
11665 (dolist (f (nreverse js2-mode-fontifications))
11666 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11667 (setq js2-mode-fontifications nil))
11668 (dolist (p js2-mode-deferred-properties)
11669 (apply #'put-text-property p))
11670 (setq js2-mode-deferred-properties nil))
11671
11672 (defun js2-mode-show-errors ()
11673 "Highlight syntax errors."
11674 (when js2-mode-show-parse-errors
11675 (dolist (e (js2-ast-root-errors js2-mode-ast))
11676 (js2-mode-show-warn-or-err e 'js2-error))))
11677
11678 (defun js2-mode-remove-suppressed-warnings ()
11679 "Take suppressed warnings out of the AST warnings list.
11680 This ensures that the counts and `next-error' are correct."
11681 (setf (js2-ast-root-warnings js2-mode-ast)
11682 (js2-delete-if
11683 (lambda (e)
11684 (let ((key (caar e)))
11685 (or
11686 (and (not js2-strict-trailing-comma-warning)
11687 (string-match "trailing\\.comma" key))
11688 (and (not js2-strict-cond-assign-warning)
11689 (string= key "msg.equal.as.assign"))
11690 (and js2-missing-semi-one-line-override
11691 (string= key "msg.missing.semi")
11692 (let* ((beg (cl-second e))
11693 (node (js2-node-at-point beg))
11694 (fn (js2-mode-find-parent-fn node))
11695 (body (and fn (js2-function-node-body fn)))
11696 (lc (and body (js2-node-abs-pos body)))
11697 (rc (and lc (+ lc (js2-node-len body)))))
11698 (and fn
11699 (or (null body)
11700 (save-excursion
11701 (goto-char beg)
11702 (and (js2-same-line lc)
11703 (js2-same-line rc))))))))))
11704 (js2-ast-root-warnings js2-mode-ast))))
11705
11706 (defun js2-mode-show-warnings ()
11707 "Highlight strict-mode warnings."
11708 (when js2-mode-show-strict-warnings
11709 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11710 (js2-mode-show-warn-or-err e 'js2-warning))))
11711
11712 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11713 "Called by point-motion hooks.
11714 ARG1, ARG2 and ARG3 have different values depending on whether this function
11715 was found on `point-entered' or in `cursor-sensor-functions'."
11716 (let* ((new-point (if (windowp arg1)
11717 ;; Called from cursor-sensor-functions.
11718 (window-point arg1)
11719 ;; Called from point-left.
11720 arg2))
11721 (msg (get-text-property new-point 'help-echo)))
11722 (when (and (stringp msg)
11723 (not (active-minibuffer-window))
11724 (not (current-message)))
11725 (message msg))))
11726
11727 (defun js2-line-break (&optional _soft)
11728 "Break line at point and indent, continuing comment if within one.
11729 If inside a string, and `js2-concat-multiline-strings' is not
11730 nil, turn it into concatenation."
11731 (interactive)
11732 (let ((parse-status (syntax-ppss)))
11733 (cond
11734 ;; Check if we're inside a string.
11735 ((nth 3 parse-status)
11736 (if js2-concat-multiline-strings
11737 (js2-mode-split-string parse-status)
11738 (insert "\n")))
11739 ;; Check if inside a block comment.
11740 ((nth 4 parse-status)
11741 (js2-mode-extend-comment (nth 8 parse-status)))
11742 (t
11743 (newline-and-indent)))))
11744
11745 (defun js2-mode-split-string (parse-status)
11746 "Turn a newline in mid-string into a string concatenation.
11747 PARSE-STATUS is as documented in `parse-partial-sexp'."
11748 (let* ((quote-char (nth 3 parse-status))
11749 (at-eol (eq js2-concat-multiline-strings 'eol)))
11750 (insert quote-char)
11751 (insert (if at-eol " +\n" "\n"))
11752 (unless at-eol
11753 (insert "+ "))
11754 (js2-indent-line)
11755 (insert quote-char)
11756 (when (eolp)
11757 (insert quote-char)
11758 (backward-char 1))))
11759
11760 (defun js2-mode-extend-comment (start-pos)
11761 "Indent the line and, when inside a comment block, add comment prefix."
11762 (let (star single col first-line needs-close)
11763 (save-excursion
11764 (back-to-indentation)
11765 (when (< (point) start-pos)
11766 (goto-char start-pos))
11767 (cond
11768 ((looking-at "\\*[^/]")
11769 (setq star t
11770 col (current-column)))
11771 ((looking-at "/\\*")
11772 (setq star t
11773 first-line t
11774 col (1+ (current-column))))
11775 ((looking-at "//")
11776 (setq single t
11777 col (current-column)))))
11778 ;; Heuristic for whether we need to close the comment:
11779 ;; if we've got a parse error here, assume it's an unterminated
11780 ;; comment.
11781 (setq needs-close
11782 (or
11783 (get-char-property (1- (point)) 'js2-error)
11784 ;; The heuristic above doesn't work well when we're
11785 ;; creating a comment and there's another one downstream,
11786 ;; as our parser thinks this one ends at the end of the
11787 ;; next one. (You can have a /* inside a js block comment.)
11788 ;; So just close it if the next non-ws char isn't a *.
11789 (and first-line
11790 (eolp)
11791 (save-excursion
11792 (skip-chars-forward " \t\r\n")
11793 (not (eq (char-after) ?*))))))
11794 (delete-horizontal-space)
11795 (insert "\n")
11796 (cond
11797 (star
11798 (indent-to col)
11799 (insert "* ")
11800 (if (and first-line needs-close)
11801 (save-excursion
11802 (insert "\n")
11803 (indent-to col)
11804 (insert "*/"))))
11805 ((and single
11806 (save-excursion
11807 (and (zerop (forward-line 1))
11808 (looking-at "\\s-*//"))))
11809 (indent-to col)
11810 (insert "// ")))
11811 ;; Don't need to extend the comment after all.
11812 (js2-indent-line)))
11813
11814 (defun js2-beginning-of-line ()
11815 "Toggle point between bol and first non-whitespace char in line.
11816 Also moves past comment delimiters when inside comments."
11817 (interactive)
11818 (let (node)
11819 (cond
11820 ((bolp)
11821 (back-to-indentation))
11822 ((looking-at "//")
11823 (skip-chars-forward "/ \t"))
11824 ((and (eq (char-after) ?*)
11825 (setq node (js2-comment-at-point))
11826 (memq (js2-comment-node-format node) '(jsdoc block))
11827 (save-excursion
11828 (skip-chars-backward " \t")
11829 (bolp)))
11830 (skip-chars-forward "\* \t"))
11831 (t
11832 (goto-char (point-at-bol))))))
11833
11834 (defun js2-end-of-line ()
11835 "Toggle point between eol and last non-whitespace char in line."
11836 (interactive)
11837 (if (eolp)
11838 (skip-chars-backward " \t")
11839 (goto-char (point-at-eol))))
11840
11841 (defun js2-mode-wait-for-parse (callback)
11842 "Invoke CALLBACK when parsing is finished.
11843 If parsing is already finished, calls CALLBACK immediately."
11844 (if (not js2-mode-buffer-dirty-p)
11845 (funcall callback)
11846 (push callback js2-mode-pending-parse-callbacks)
11847 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11848
11849 (defun js2-mode-parse-finished ()
11850 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11851 ;; We can't let errors propagate up, since it prevents the
11852 ;; `js2-parse' method from completing normally and returning
11853 ;; the ast, which makes things mysteriously not work right.
11854 (unwind-protect
11855 (dolist (cb js2-mode-pending-parse-callbacks)
11856 (condition-case err
11857 (funcall cb)
11858 (error (message "%s" err))))
11859 (setq js2-mode-pending-parse-callbacks nil)))
11860
11861 (defun js2-mode-flag-region (from to flag)
11862 "Hide or show text from FROM to TO, according to FLAG.
11863 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11864 Returns the created overlay if FLAG is non-nil."
11865 (remove-overlays from to 'invisible 'js2-outline)
11866 (when flag
11867 (let ((o (make-overlay from to)))
11868 (overlay-put o 'invisible 'js2-outline)
11869 (overlay-put o 'isearch-open-invisible
11870 'js2-isearch-open-invisible)
11871 o)))
11872
11873 ;; Function to be set as an outline-isearch-open-invisible' property
11874 ;; to the overlay that makes the outline invisible (see
11875 ;; `js2-mode-flag-region').
11876 (defun js2-isearch-open-invisible (_overlay)
11877 ;; We rely on the fact that isearch places point on the matched text.
11878 (js2-mode-show-element))
11879
11880 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11881 "Return cons cell of bounds of folding overlay at POS.
11882 Returns nil if not found."
11883 (let ((overlays (overlays-at (or pos (point))))
11884 o)
11885 (while (and overlays
11886 (not o))
11887 (if (overlay-get (car overlays) 'invisible)
11888 (setq o (car overlays))
11889 (setq overlays (cdr overlays))))
11890 (if o
11891 (cons (overlay-start o) (overlay-end o)))))
11892
11893 (defun js2-mode-function-at-point (&optional pos)
11894 "Return the innermost function node enclosing current point.
11895 Returns nil if point is not in a function."
11896 (let ((node (js2-node-at-point pos)))
11897 (while (and node (not (js2-function-node-p node)))
11898 (setq node (js2-node-parent node)))
11899 (if (js2-function-node-p node)
11900 node)))
11901
11902 (defun js2-mode-toggle-element ()
11903 "Hide or show the foldable element at the point."
11904 (interactive)
11905 (let (comment fn pos)
11906 (save-excursion
11907 (cond
11908 ;; /* ... */ comment?
11909 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11910 (if (js2-mode-invisible-overlay-bounds
11911 (setq pos (+ 3 (js2-node-abs-pos comment))))
11912 (progn
11913 (goto-char pos)
11914 (js2-mode-show-element))
11915 (js2-mode-hide-element)))
11916 ;; //-comment?
11917 ((save-excursion
11918 (back-to-indentation)
11919 (looking-at js2-mode-//-comment-re))
11920 (js2-mode-toggle-//-comment))
11921 ;; function?
11922 ((setq fn (js2-mode-function-at-point))
11923 (setq pos (and (js2-function-node-body fn)
11924 (js2-node-abs-pos (js2-function-node-body fn))))
11925 (goto-char (1+ pos))
11926 (if (js2-mode-invisible-overlay-bounds)
11927 (js2-mode-show-element)
11928 (js2-mode-hide-element)))
11929 (t
11930 (message "Nothing at point to hide or show"))))))
11931
11932 (defun js2-mode-hide-element ()
11933 "Fold/hide contents of a block, showing ellipses.
11934 Show the hidden text with \\[js2-mode-show-element]."
11935 (interactive)
11936 (if js2-mode-buffer-dirty-p
11937 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11938 (let (node body beg end)
11939 (cond
11940 ((js2-mode-invisible-overlay-bounds)
11941 (message "already hidden"))
11942 (t
11943 (setq node (js2-node-at-point))
11944 (cond
11945 ((js2-block-comment-p node)
11946 (js2-mode-hide-comment node))
11947 (t
11948 (while (and node (not (js2-function-node-p node)))
11949 (setq node (js2-node-parent node)))
11950 (if (and node
11951 (setq body (js2-function-node-body node)))
11952 (progn
11953 (setq beg (js2-node-abs-pos body)
11954 end (+ beg (js2-node-len body)))
11955 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11956 (message "No collapsable element found at point"))))))))
11957
11958 (defun js2-mode-show-element ()
11959 "Show the hidden element at current point."
11960 (interactive)
11961 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11962 (if bounds
11963 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11964 (message "Nothing to un-hide"))))
11965
11966 (defun js2-mode-show-all ()
11967 "Show all of the text in the buffer."
11968 (interactive)
11969 (js2-mode-flag-region (point-min) (point-max) nil))
11970
11971 (defun js2-mode-toggle-hide-functions ()
11972 (interactive)
11973 (if js2-mode-functions-hidden
11974 (js2-mode-show-functions)
11975 (js2-mode-hide-functions)))
11976
11977 (defun js2-mode-hide-functions ()
11978 "Hides all non-nested function bodies in the buffer.
11979 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11980 to open an individual entry."
11981 (interactive)
11982 (if js2-mode-buffer-dirty-p
11983 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11984 (if (null js2-mode-ast)
11985 (message "Oops - parsing failed")
11986 (setq js2-mode-functions-hidden t)
11987 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11988
11989 (defun js2-mode-function-hider (n endp)
11990 (when (not endp)
11991 (let ((tt (js2-node-type n))
11992 body beg end)
11993 (cond
11994 ((and (= tt js2-FUNCTION)
11995 (setq body (js2-function-node-body n)))
11996 (setq beg (js2-node-abs-pos body)
11997 end (+ beg (js2-node-len body)))
11998 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11999 nil) ; don't process children of function
12000 (t
12001 t))))) ; keep processing other AST nodes
12002
12003 (defun js2-mode-show-functions ()
12004 "Un-hide any folded function bodies in the buffer."
12005 (interactive)
12006 (setq js2-mode-functions-hidden nil)
12007 (save-excursion
12008 (goto-char (point-min))
12009 (while (/= (goto-char (next-overlay-change (point)))
12010 (point-max))
12011 (dolist (o (overlays-at (point)))
12012 (when (and (overlay-get o 'invisible)
12013 (not (overlay-get o 'comment)))
12014 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12015
12016 (defun js2-mode-hide-comment (n)
12017 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12018 3 ; /**
12019 2)) ; /*
12020 (beg (+ (js2-node-abs-pos n) head))
12021 (end (- (+ beg (js2-node-len n)) head 2))
12022 (o (js2-mode-flag-region beg end 'hide)))
12023 (overlay-put o 'comment t)))
12024
12025 (defun js2-mode-toggle-hide-comments ()
12026 "Folds all block comments in the buffer.
12027 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12028 to open an individual entry."
12029 (interactive)
12030 (if js2-mode-comments-hidden
12031 (js2-mode-show-comments)
12032 (js2-mode-hide-comments)))
12033
12034 (defun js2-mode-hide-comments ()
12035 (interactive)
12036 (if js2-mode-buffer-dirty-p
12037 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12038 (if (null js2-mode-ast)
12039 (message "Oops - parsing failed")
12040 (setq js2-mode-comments-hidden t)
12041 (dolist (n (js2-ast-root-comments js2-mode-ast))
12042 (when (js2-block-comment-p n)
12043 (js2-mode-hide-comment n)))
12044 (js2-mode-hide-//-comments)))
12045
12046 (defun js2-mode-extend-//-comment (direction)
12047 "Find start or end of a block of similar //-comment lines.
12048 DIRECTION is -1 to look back, 1 to look forward.
12049 INDENT is the indentation level to match.
12050 Returns the end-of-line position of the furthest adjacent
12051 //-comment line with the same indentation as the current line.
12052 If there is no such matching line, returns current end of line."
12053 (let ((pos (point-at-eol))
12054 (indent (current-indentation)))
12055 (save-excursion
12056 (while (and (zerop (forward-line direction))
12057 (looking-at js2-mode-//-comment-re)
12058 (eq indent (length (match-string 1))))
12059 (setq pos (point-at-eol)))
12060 pos)))
12061
12062 (defun js2-mode-hide-//-comments ()
12063 "Fold adjacent 1-line comments, showing only snippet of first one."
12064 (let (beg end)
12065 (save-excursion
12066 (goto-char (point-min))
12067 (while (re-search-forward js2-mode-//-comment-re nil t)
12068 (setq beg (point)
12069 end (js2-mode-extend-//-comment 1))
12070 (unless (eq beg end)
12071 (overlay-put (js2-mode-flag-region beg end 'hide)
12072 'comment t))
12073 (goto-char end)
12074 (forward-char 1)))))
12075
12076 (defun js2-mode-toggle-//-comment ()
12077 "Fold or un-fold any multi-line //-comment at point.
12078 Caller should have determined that this line starts with a //-comment."
12079 (let* ((beg (point-at-eol))
12080 (end beg))
12081 (save-excursion
12082 (goto-char end)
12083 (if (js2-mode-invisible-overlay-bounds)
12084 (js2-mode-show-element)
12085 ;; else hide the comment
12086 (setq beg (js2-mode-extend-//-comment -1)
12087 end (js2-mode-extend-//-comment 1))
12088 (unless (eq beg end)
12089 (overlay-put (js2-mode-flag-region beg end 'hide)
12090 'comment t))))))
12091
12092 (defun js2-mode-show-comments ()
12093 "Un-hide any hidden comments, leaving other hidden elements alone."
12094 (interactive)
12095 (setq js2-mode-comments-hidden nil)
12096 (save-excursion
12097 (goto-char (point-min))
12098 (while (/= (goto-char (next-overlay-change (point)))
12099 (point-max))
12100 (dolist (o (overlays-at (point)))
12101 (when (overlay-get o 'comment)
12102 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12103
12104 (defun js2-mode-display-warnings-and-errors ()
12105 "Turn on display of warnings and errors."
12106 (interactive)
12107 (setq js2-mode-show-parse-errors t
12108 js2-mode-show-strict-warnings t)
12109 (js2-reparse 'force))
12110
12111 (defun js2-mode-hide-warnings-and-errors ()
12112 "Turn off display of warnings and errors."
12113 (interactive)
12114 (setq js2-mode-show-parse-errors nil
12115 js2-mode-show-strict-warnings nil)
12116 (js2-reparse 'force))
12117
12118 (defun js2-mode-toggle-warnings-and-errors ()
12119 "Toggle the display of warnings and errors.
12120 Some users don't like having warnings/errors reported while they type."
12121 (interactive)
12122 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12123 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12124 (if (called-interactively-p 'any)
12125 (message "warnings and errors %s"
12126 (if js2-mode-show-parse-errors
12127 "enabled"
12128 "disabled")))
12129 (js2-reparse 'force))
12130
12131 (defun js2-mode-customize ()
12132 (interactive)
12133 (customize-group 'js2-mode))
12134
12135 (defun js2-mode-forward-sexp (&optional arg)
12136 "Move forward across one statement or balanced expression.
12137 With ARG, do it that many times. Negative arg -N means
12138 move backward across N balanced expressions."
12139 (interactive "p")
12140 (setq arg (or arg 1))
12141 (save-restriction
12142 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12143 (js2-reparse)
12144 (let (forward-sexp-function
12145 node (start (point)) pos lp rp child)
12146 (cond
12147 ;; backward-sexp
12148 ;; could probably make this better for some cases:
12149 ;; - if in statement block (e.g. function body), go to parent
12150 ;; - infix exprs like (foo in bar) - maybe go to beginning
12151 ;; of infix expr if in the right-side expression?
12152 ((and arg (cl-minusp arg))
12153 (dotimes (_ (- arg))
12154 (js2-backward-sws)
12155 (forward-char -1) ; Enter the node we backed up to.
12156 (when (setq node (js2-node-at-point (point) t))
12157 (setq pos (js2-node-abs-pos node))
12158 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12159 (setq lp (car parens)
12160 rp (cdr parens)))
12161 (when (and lp (> start lp))
12162 (if (and rp (<= start rp))
12163 ;; Between parens, check if there's a child node we can jump.
12164 (when (setq child (js2-node-closest-child node (point) lp t))
12165 (setq pos (js2-node-abs-pos child)))
12166 ;; Before both parens.
12167 (setq pos lp)))
12168 (let ((state (parse-partial-sexp start pos)))
12169 (goto-char (if (not (zerop (car state)))
12170 ;; Stumble at the unbalanced paren if < 0, or
12171 ;; jump a bit further if > 0.
12172 (scan-sexps start -1)
12173 pos))))
12174 (unless pos (goto-char (point-min)))))
12175 (t
12176 ;; forward-sexp
12177 (dotimes (_ arg)
12178 (js2-forward-sws)
12179 (when (setq node (js2-node-at-point (point) t))
12180 (setq pos (js2-node-abs-pos node))
12181 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12182 (setq lp (car parens)
12183 rp (cdr parens)))
12184 (or
12185 (when (and rp (<= start rp))
12186 (if (> start lp)
12187 (when (setq child (js2-node-closest-child node (point) rp))
12188 (setq pos (js2-node-abs-end child)))
12189 (setq pos (1+ rp))))
12190 ;; No parens or child nodes, looks for the end of the current node.
12191 (cl-incf pos (js2-node-len
12192 (if (js2-expr-stmt-node-p (js2-node-parent node))
12193 ;; Stop after the semicolon.
12194 (js2-node-parent node)
12195 node))))
12196 (let ((state (save-excursion (parse-partial-sexp start pos))))
12197 (goto-char (if (not (zerop (car state)))
12198 (scan-sexps start 1)
12199 pos))))
12200 (unless pos (goto-char (point-max)))))))))
12201
12202 (defun js2-mode-forward-sexp-parens (node abs-pos)
12203 "Return a cons cell with positions of main parens in NODE."
12204 (cond
12205 ((or (js2-array-node-p node)
12206 (js2-object-node-p node)
12207 (js2-comp-node-p node)
12208 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12209 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12210 ((js2-paren-expr-node-p node)
12211 (let ((lp (js2-node-lp node))
12212 (rp (js2-node-rp node)))
12213 (cons (when lp (+ abs-pos lp))
12214 (when rp (+ abs-pos rp)))))))
12215
12216 (defun js2-node-closest-child (parent point limit &optional before)
12217 (let* ((parent-pos (js2-node-abs-pos parent))
12218 (rpoint (- point parent-pos))
12219 (rlimit (- limit parent-pos))
12220 (min (min rpoint rlimit))
12221 (max (max rpoint rlimit))
12222 found)
12223 (catch 'done
12224 (js2-visit-ast
12225 parent
12226 (lambda (node _end-p)
12227 (if (eq node parent)
12228 t
12229 (let ((pos (js2-node-pos node)) ;; Both relative values.
12230 (end (+ (js2-node-pos node) (js2-node-len node))))
12231 (when (and (>= pos min) (<= end max)
12232 (if before (< pos rpoint) (> end rpoint)))
12233 (setq found node))
12234 (when (> end rpoint)
12235 (throw 'done nil)))
12236 nil))))
12237 found))
12238
12239 (defun js2-errors ()
12240 "Return a list of errors found."
12241 (and js2-mode-ast
12242 (js2-ast-root-errors js2-mode-ast)))
12243
12244 (defun js2-warnings ()
12245 "Return a list of warnings found."
12246 (and js2-mode-ast
12247 (js2-ast-root-warnings js2-mode-ast)))
12248
12249 (defun js2-have-errors-p ()
12250 "Return non-nil if any parse errors or warnings were found."
12251 (or (js2-errors) (js2-warnings)))
12252
12253 (defun js2-errors-and-warnings ()
12254 "Return a copy of the concatenated errors and warnings lists.
12255 They are appended: first the errors, then the warnings.
12256 Entries are of the form (MSG BEG END)."
12257 (when js2-mode-ast
12258 (append (js2-ast-root-errors js2-mode-ast)
12259 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12260
12261 (defun js2-next-error (&optional arg reset)
12262 "Move to next parse error.
12263 Typically invoked via \\[next-error].
12264 ARG is the number of errors, forward or backward, to move.
12265 RESET means start over from the beginning."
12266 (interactive "p")
12267 (if (not (or (js2-errors) (js2-warnings)))
12268 (message "No errors")
12269 (when reset
12270 (goto-char (point-min)))
12271 (let* ((errs (js2-errors-and-warnings))
12272 (continue t)
12273 (start (point))
12274 (count (or arg 1))
12275 (backward (cl-minusp count))
12276 (sorter (if backward '> '<))
12277 (stopper (if backward '< '>))
12278 (count (abs count))
12279 all-errs err)
12280 ;; Sort by start position.
12281 (setq errs (sort errs (lambda (e1 e2)
12282 (funcall sorter (cl-second e1) (cl-second e2))))
12283 all-errs errs)
12284 ;; Find nth error with pos > start.
12285 (while (and errs continue)
12286 (when (funcall stopper (cl-cadar errs) start)
12287 (setq err (car errs))
12288 (if (zerop (cl-decf count))
12289 (setq continue nil)))
12290 (setq errs (cdr errs)))
12291 ;; Clear for `js2-echo-error'.
12292 (message nil)
12293 (if err
12294 (goto-char (cl-second err))
12295 ;; Wrap around to first error.
12296 (goto-char (cl-second (car all-errs)))
12297 ;; If we were already on it, echo msg again.
12298 (if (= (point) start)
12299 (js2-echo-error (point) (point)))))))
12300
12301 (defun js2-down-mouse-3 ()
12302 "Make right-click move the point to the click location.
12303 This makes right-click context menu operations a bit more intuitive.
12304 The point will not move if the region is active, however, to avoid
12305 destroying the region selection."
12306 (interactive)
12307 (when (and js2-move-point-on-right-click
12308 (not mark-active))
12309 (let ((e last-input-event))
12310 (ignore-errors
12311 (goto-char (cl-cadadr e))))))
12312
12313 (defun js2-mode-create-imenu-index ()
12314 "Return an alist for `imenu--index-alist'."
12315 ;; This is built up in `js2-parse-record-imenu' during parsing.
12316 (when js2-mode-ast
12317 ;; if we have an ast but no recorder, they're requesting a rescan
12318 (unless js2-imenu-recorder
12319 (js2-reparse 'force))
12320 (prog1
12321 (js2-build-imenu-index)
12322 (setq js2-imenu-recorder nil
12323 js2-imenu-function-map nil))))
12324
12325 (defun js2-mode-find-tag ()
12326 "Replacement for `find-tag-default'.
12327 `find-tag-default' returns a ridiculous answer inside comments."
12328 (let (beg end)
12329 (js2-with-underscore-as-word-syntax
12330 (save-excursion
12331 (if (and (not (looking-at "[[:alnum:]_$]"))
12332 (looking-back "[[:alnum:]_$]"))
12333 (setq beg (progn (forward-word -1) (point))
12334 end (progn (forward-word 1) (point)))
12335 (setq beg (progn (forward-word 1) (point))
12336 end (progn (forward-word -1) (point))))
12337 (replace-regexp-in-string
12338 "[\"']" ""
12339 (buffer-substring-no-properties beg end))))))
12340
12341 (defun js2-mode-forward-sibling ()
12342 "Move to the end of the sibling following point in parent.
12343 Returns non-nil if successful, or nil if there was no following sibling."
12344 (let* ((node (js2-node-at-point))
12345 (parent (js2-mode-find-enclosing-fn node))
12346 sib)
12347 (when (setq sib (js2-node-find-child-after (point) parent))
12348 (goto-char (+ (js2-node-abs-pos sib)
12349 (js2-node-len sib))))))
12350
12351 (defun js2-mode-backward-sibling ()
12352 "Move to the beginning of the sibling node preceding point in parent.
12353 Parent is defined as the enclosing script or function."
12354 (let* ((node (js2-node-at-point))
12355 (parent (js2-mode-find-enclosing-fn node))
12356 sib)
12357 (when (setq sib (js2-node-find-child-before (point) parent))
12358 (goto-char (js2-node-abs-pos sib)))))
12359
12360 (defun js2-beginning-of-defun (&optional arg)
12361 "Go to line on which current function starts, and return t on success.
12362 If we're not in a function or already at the beginning of one, go
12363 to beginning of previous script-level element.
12364 With ARG N, do that N times. If N is negative, move forward."
12365 (setq arg (or arg 1))
12366 (if (cl-plusp arg)
12367 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12368 (when (cond
12369 ((js2-function-node-p parent)
12370 (goto-char (js2-node-abs-pos parent)))
12371 (t
12372 (js2-mode-backward-sibling)))
12373 (if (> arg 1)
12374 (js2-beginning-of-defun (1- arg))
12375 t)))
12376 (when (js2-end-of-defun)
12377 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12378
12379 (defun js2-end-of-defun ()
12380 "Go to the char after the last position of the current function
12381 or script-level element."
12382 (let* ((node (js2-node-at-point))
12383 (parent (or (and (js2-function-node-p node) node)
12384 (js2-node-parent-script-or-fn node)))
12385 script)
12386 (unless (js2-function-node-p parent)
12387 ;; Use current script-level node, or, if none, the next one.
12388 (setq script (or parent node)
12389 parent (js2-node-find-child-before (point) script))
12390 (when (or (null parent)
12391 (>= (point) (+ (js2-node-abs-pos parent)
12392 (js2-node-len parent))))
12393 (setq parent (js2-node-find-child-after (point) script))))
12394 (when parent
12395 (goto-char (+ (js2-node-abs-pos parent)
12396 (js2-node-len parent))))))
12397
12398 (defun js2-mark-defun (&optional allow-extend)
12399 "Put mark at end of this function, point at beginning.
12400 The function marked is the one that contains point.
12401
12402 Interactively, if this command is repeated,
12403 or (in Transient Mark mode) if the mark is active,
12404 it marks the next defun after the ones already marked."
12405 (interactive "p")
12406 (let (extended)
12407 (when (and allow-extend
12408 (or (and (eq last-command this-command) (mark t))
12409 (and transient-mark-mode mark-active)))
12410 (let ((sib (save-excursion
12411 (goto-char (mark))
12412 (if (js2-mode-forward-sibling)
12413 (point)))))
12414 (if sib
12415 (progn
12416 (set-mark sib)
12417 (setq extended t))
12418 ;; no more siblings - try extending to enclosing node
12419 (goto-char (mark t)))))
12420 (when (not extended)
12421 (let ((node (js2-node-at-point (point) t)) ; skip comments
12422 ast fn stmt parent beg end)
12423 (when (js2-ast-root-p node)
12424 (setq ast node
12425 node (or (js2-node-find-child-after (point) node)
12426 (js2-node-find-child-before (point) node))))
12427 ;; only mark whole buffer if we can't find any children
12428 (if (null node)
12429 (setq node ast))
12430 (if (js2-function-node-p node)
12431 (setq parent node)
12432 (setq fn (js2-mode-find-enclosing-fn node)
12433 stmt (if (or (null fn)
12434 (js2-ast-root-p fn))
12435 (js2-mode-find-first-stmt node))
12436 parent (or stmt fn)))
12437 (setq beg (js2-node-abs-pos parent)
12438 end (+ beg (js2-node-len parent)))
12439 (push-mark beg)
12440 (goto-char end)
12441 (exchange-point-and-mark)))))
12442
12443 (defun js2-narrow-to-defun ()
12444 "Narrow to the function enclosing point."
12445 (interactive)
12446 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12447 (fn (if (js2-script-node-p node)
12448 node
12449 (js2-mode-find-enclosing-fn node)))
12450 (beg (js2-node-abs-pos fn)))
12451 (unless (js2-ast-root-p fn)
12452 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12453
12454 (provide 'js2-mode)
12455
12456 ;;; js2-mode.el ends here