]> code.delx.au - gnu-emacs-elpa/blob - packages/js2-mode/js2-mode.el
Merge commit 'ac93b9eef9b6ac44d187b9688d68a7a5f205b3fe' from js2-mode
[gnu-emacs-elpa] / packages / js2-mode / 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 (computed (not (or (js2-string-node-p left)
3956 (js2-number-node-p left)
3957 (js2-name-node-p left)))))
3958 (insert (js2-make-pad i))
3959 (if computed
3960 (insert "["))
3961 (js2-print-ast left 0)
3962 (if computed
3963 (insert "]"))
3964 (if (not (js2-node-get-prop n 'SHORTHAND))
3965 (progn
3966 (insert ": ")
3967 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3968
3969 (cl-defstruct (js2-getter-setter-node
3970 (:include js2-infix-node)
3971 (:constructor nil)
3972 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3973 (pos js2-ts-cursor)
3974 len left right)))
3975 "AST node for a getter/setter property in an object literal.
3976 The `left' field is the `js2-name-node' naming the getter/setter prop.
3977 The `right' field is always an anonymous `js2-function-node' with a node
3978 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3979
3980 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3981 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3982
3983 (defun js2-print-getter-setter (n i)
3984 (let ((pad (js2-make-pad i))
3985 (left (js2-getter-setter-node-left n))
3986 (right (js2-getter-setter-node-right n)))
3987 (insert pad)
3988 (if (/= (js2-node-type n) js2-FUNCTION)
3989 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3990 (js2-print-ast left 0)
3991 (js2-print-ast right 0)))
3992
3993 (cl-defstruct (js2-prop-get-node
3994 (:include js2-infix-node)
3995 (:constructor nil)
3996 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3997 (pos js2-ts-cursor)
3998 len left right)))
3999 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
4000
4001 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4002 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4003
4004 (defun js2-visit-prop-get-node (n v)
4005 (js2-visit-ast (js2-prop-get-node-left n) v)
4006 (js2-visit-ast (js2-prop-get-node-right n) v))
4007
4008 (defun js2-print-prop-get-node (n i)
4009 (insert (js2-make-pad i))
4010 (js2-print-ast (js2-prop-get-node-left n) 0)
4011 (insert ".")
4012 (js2-print-ast (js2-prop-get-node-right n) 0))
4013
4014 (cl-defstruct (js2-elem-get-node
4015 (:include js2-node)
4016 (:constructor nil)
4017 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4018 (pos js2-ts-cursor)
4019 len target element
4020 lb rb)))
4021 "AST node for an array index expression such as foo[bar]."
4022 target ; a `js2-node' - the expression preceding the "."
4023 element ; a `js2-node' - the expression in brackets
4024 lb ; position of left-bracket, nil if omitted
4025 rb) ; position of right-bracket, nil if omitted
4026
4027 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4028 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4029
4030 (defun js2-visit-elem-get-node (n v)
4031 (js2-visit-ast (js2-elem-get-node-target n) v)
4032 (js2-visit-ast (js2-elem-get-node-element n) v))
4033
4034 (defun js2-print-elem-get-node (n i)
4035 (insert (js2-make-pad i))
4036 (js2-print-ast (js2-elem-get-node-target n) 0)
4037 (insert "[")
4038 (js2-print-ast (js2-elem-get-node-element n) 0)
4039 (insert "]"))
4040
4041 (cl-defstruct (js2-call-node
4042 (:include js2-node)
4043 (:constructor nil)
4044 (:constructor make-js2-call-node (&key (type js2-CALL)
4045 (pos js2-ts-cursor)
4046 len target args
4047 lp rp)))
4048 "AST node for a JavaScript function call."
4049 target ; a `js2-node' evaluating to the function to call
4050 args ; a Lisp list of `js2-node' arguments
4051 lp ; position of open-paren, or nil if missing
4052 rp) ; position of close-paren, or nil if missing
4053
4054 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4055 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4056
4057 (defun js2-visit-call-node (n v)
4058 (js2-visit-ast (js2-call-node-target n) v)
4059 (dolist (arg (js2-call-node-args n))
4060 (js2-visit-ast arg v)))
4061
4062 (defun js2-print-call-node (n i)
4063 (insert (js2-make-pad i))
4064 (js2-print-ast (js2-call-node-target n) 0)
4065 (insert "(")
4066 (js2-print-list (js2-call-node-args n))
4067 (insert ")"))
4068
4069 (cl-defstruct (js2-yield-node
4070 (:include js2-node)
4071 (:constructor nil)
4072 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4073 (pos js2-ts-cursor)
4074 len value star-p)))
4075 "AST node for yield statement or expression."
4076 star-p ; whether it's yield*
4077 value) ; optional: value to be yielded
4078
4079 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4080 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4081
4082 (defun js2-visit-yield-node (n v)
4083 (js2-visit-ast (js2-yield-node-value n) v))
4084
4085 (defun js2-print-yield-node (n i)
4086 (insert (js2-make-pad i))
4087 (insert "yield")
4088 (when (js2-yield-node-star-p n)
4089 (insert "*"))
4090 (when (js2-yield-node-value n)
4091 (insert " ")
4092 (js2-print-ast (js2-yield-node-value n) 0)))
4093
4094 (cl-defstruct (js2-paren-node
4095 (:include js2-node)
4096 (:constructor nil)
4097 (:constructor make-js2-paren-node (&key (type js2-LP)
4098 (pos js2-ts-cursor)
4099 len expr)))
4100 "AST node for a parenthesized expression.
4101 In particular, used when the parens are syntactically optional,
4102 as opposed to required parens such as those enclosing an if-conditional."
4103 expr) ; `js2-node'
4104
4105 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4106 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4107
4108 (defun js2-visit-paren-node (n v)
4109 (js2-visit-ast (js2-paren-node-expr n) v))
4110
4111 (defun js2-print-paren-node (n i)
4112 (insert (js2-make-pad i))
4113 (insert "(")
4114 (js2-print-ast (js2-paren-node-expr n) 0)
4115 (insert ")"))
4116
4117 (cl-defstruct (js2-comp-node
4118 (:include js2-scope)
4119 (:constructor nil)
4120 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4121 (pos js2-ts-cursor)
4122 len result
4123 loops filters
4124 form)))
4125 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4126 result ; result expression (just after left-bracket)
4127 loops ; a Lisp list of `js2-comp-loop-node'
4128 filters ; a Lisp list of guard/filter expressions
4129 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4130 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4131 )
4132
4133 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4134 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4135
4136 (defun js2-visit-comp-node (n v)
4137 (js2-visit-ast (js2-comp-node-result n) v)
4138 (dolist (l (js2-comp-node-loops n))
4139 (js2-visit-ast l v))
4140 (dolist (f (js2-comp-node-filters n))
4141 (js2-visit-ast f v)))
4142
4143 (defun js2-print-comp-node (n i)
4144 (let ((pad (js2-make-pad i))
4145 (result (js2-comp-node-result n))
4146 (loops (js2-comp-node-loops n))
4147 (filters (js2-comp-node-filters n))
4148 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4149 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4150 (insert pad (if gen-p "(" "["))
4151 (when legacy-p
4152 (js2-print-ast result 0))
4153 (dolist (l loops)
4154 (when legacy-p
4155 (insert " "))
4156 (js2-print-ast l 0)
4157 (unless legacy-p
4158 (insert " ")))
4159 (dolist (f filters)
4160 (when legacy-p
4161 (insert " "))
4162 (insert "if (")
4163 (js2-print-ast f 0)
4164 (insert ")")
4165 (unless legacy-p
4166 (insert " ")))
4167 (unless legacy-p
4168 (js2-print-ast result 0))
4169 (insert (if gen-p ")" "]"))))
4170
4171 (cl-defstruct (js2-comp-loop-node
4172 (:include js2-for-in-node)
4173 (:constructor nil)
4174 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4175 (pos js2-ts-cursor)
4176 len iterator
4177 object in-pos
4178 foreach-p
4179 each-pos
4180 forof-p
4181 lp rp)))
4182 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4183
4184 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4185 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4186
4187 (defun js2-visit-comp-loop (n v)
4188 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4189 (js2-visit-ast (js2-comp-loop-node-object n) v))
4190
4191 (defun js2-print-comp-loop (n _i)
4192 (insert "for ")
4193 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4194 (insert "(")
4195 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4196 (insert (if (js2-comp-loop-node-forof-p n)
4197 " of " " in "))
4198 (js2-print-ast (js2-comp-loop-node-object n) 0)
4199 (insert ")"))
4200
4201 (cl-defstruct (js2-empty-expr-node
4202 (:include js2-node)
4203 (:constructor nil)
4204 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4205 (pos (js2-current-token-beg))
4206 len)))
4207 "AST node for an empty expression.")
4208
4209 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4210 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4211
4212 (cl-defstruct (js2-xml-node
4213 (:include js2-block-node)
4214 (:constructor nil)
4215 (:constructor make-js2-xml-node (&key (type js2-XML)
4216 (pos (js2-current-token-beg))
4217 len kids)))
4218 "AST node for initial parse of E4X literals.
4219 The kids field is a list of XML fragments, each a `js2-string-node' or
4220 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4221
4222 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4223 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4224
4225 (defun js2-print-xml-node (n i)
4226 (dolist (kid (js2-xml-node-kids n))
4227 (js2-print-ast kid i)))
4228
4229 (cl-defstruct (js2-xml-js-expr-node
4230 (:include js2-xml-node)
4231 (:constructor nil)
4232 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4233 (pos js2-ts-cursor)
4234 len expr)))
4235 "AST node for an embedded JavaScript {expression} in an E4X literal.
4236 The start and end fields correspond to the curly-braces."
4237 expr) ; a `js2-expr-node' of some sort
4238
4239 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4240 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4241
4242 (defun js2-visit-xml-js-expr (n v)
4243 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4244
4245 (defun js2-print-xml-js-expr (n i)
4246 (insert (js2-make-pad i))
4247 (insert "{")
4248 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4249 (insert "}"))
4250
4251 (cl-defstruct (js2-xml-dot-query-node
4252 (:include js2-infix-node)
4253 (:constructor nil)
4254 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4255 (pos js2-ts-cursor)
4256 op-pos len left
4257 right rp)))
4258 "AST node for an E4X foo.(bar) filter expression.
4259 Note that the left-paren is automatically the character immediately
4260 following the dot (.) in the operator. No whitespace is permitted
4261 between the dot and the lp by the scanner."
4262 rp)
4263
4264 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4265 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4266
4267 (defun js2-print-xml-dot-query (n i)
4268 (insert (js2-make-pad i))
4269 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4270 (insert ".(")
4271 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4272 (insert ")"))
4273
4274 (cl-defstruct (js2-xml-ref-node
4275 (:include js2-node)
4276 (:constructor nil)) ; abstract
4277 "Base type for E4X XML attribute-access or property-get expressions.
4278 Such expressions can take a variety of forms. The general syntax has
4279 three parts:
4280
4281 - (optional) an @ (specifying an attribute access)
4282 - (optional) a namespace (a `js2-name-node') and double-colon
4283 - (required) either a `js2-name-node' or a bracketed [expression]
4284
4285 The property-name expressions (examples: ns::name, @name) are
4286 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4287 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4288
4289 This node type (or more specifically, its subclasses) will sometimes
4290 be the right-hand child of a `js2-prop-get-node' or a
4291 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4292 The `js2-xml-ref-node' may also be a standalone primary expression with
4293 no explicit target, which is valid in certain expression contexts such as
4294
4295 company..employee.(@id < 100)
4296
4297 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4298 expression whose parent is a `js2-xml-dot-query-node'."
4299 namespace
4300 at-pos
4301 colon-pos)
4302
4303 (defsubst js2-xml-ref-node-attr-access-p (node)
4304 "Return non-nil if this expression began with an @-token."
4305 (and (numberp (js2-xml-ref-node-at-pos node))
4306 (cl-plusp (js2-xml-ref-node-at-pos node))))
4307
4308 (cl-defstruct (js2-xml-prop-ref-node
4309 (:include js2-xml-ref-node)
4310 (:constructor nil)
4311 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4312 (pos (js2-current-token-beg))
4313 len propname
4314 namespace at-pos
4315 colon-pos)))
4316 "AST node for an E4X XML [expr] property-ref expression.
4317 The JavaScript syntax is an optional @, an optional ns::, and a name.
4318
4319 [ '@' ] [ name '::' ] name
4320
4321 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4322 @ns::*, @*::attr, @*::*, and @*.
4323
4324 The node starts at the @ token, if present. Otherwise it starts at the
4325 namespace name. The node bounds extend through the closing right-bracket,
4326 or if it is missing due to a syntax error, through the end of the index
4327 expression."
4328 propname)
4329
4330 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4331 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4332
4333 (defun js2-visit-xml-prop-ref-node (n v)
4334 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4335 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4336
4337 (defun js2-print-xml-prop-ref-node (n i)
4338 (insert (js2-make-pad i))
4339 (if (js2-xml-ref-node-attr-access-p n)
4340 (insert "@"))
4341 (when (js2-xml-prop-ref-node-namespace n)
4342 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4343 (insert "::"))
4344 (if (js2-xml-prop-ref-node-propname n)
4345 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4346
4347 (cl-defstruct (js2-xml-elem-ref-node
4348 (:include js2-xml-ref-node)
4349 (:constructor nil)
4350 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4351 (pos (js2-current-token-beg))
4352 len expr lb rb
4353 namespace at-pos
4354 colon-pos)))
4355 "AST node for an E4X XML [expr] member-ref expression.
4356 Syntax:
4357
4358 [ '@' ] [ name '::' ] '[' expr ']'
4359
4360 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4361
4362 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4363 is not a legal E4X XML element-ref expression, since it's already used
4364 for standard JavaScript element-get array indexing. Hence, a
4365 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4366 non-nil namespace node, or both.
4367
4368 The node starts at the @ token, if present. Otherwise it starts
4369 at the namespace name. The node bounds extend through the closing
4370 right-bracket, or if it is missing due to a syntax error, through the
4371 end of the index expression."
4372 expr ; the bracketed index expression
4373 lb
4374 rb)
4375
4376 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4377 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4378
4379 (defun js2-visit-xml-elem-ref-node (n v)
4380 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4381 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4382
4383 (defun js2-print-xml-elem-ref-node (n i)
4384 (insert (js2-make-pad i))
4385 (if (js2-xml-ref-node-attr-access-p n)
4386 (insert "@"))
4387 (when (js2-xml-elem-ref-node-namespace n)
4388 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4389 (insert "::"))
4390 (insert "[")
4391 (if (js2-xml-elem-ref-node-expr n)
4392 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4393 (insert "]"))
4394
4395 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4396
4397 (cl-defstruct (js2-xml-start-tag-node
4398 (:include js2-xml-node)
4399 (:constructor nil)
4400 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4401 (pos js2-ts-cursor)
4402 len name attrs kids
4403 empty-p)))
4404 "AST node for an XML start-tag. Not currently used.
4405 The `kids' field is a Lisp list of child content nodes."
4406 name ; a `js2-xml-name-node'
4407 attrs ; a Lisp list of `js2-xml-attr-node'
4408 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4409
4410 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4411 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4412
4413 (defun js2-visit-xml-start-tag (n v)
4414 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4415 (dolist (attr (js2-xml-start-tag-node-attrs n))
4416 (js2-visit-ast attr v))
4417 (js2-visit-block n v))
4418
4419 (defun js2-print-xml-start-tag (n i)
4420 (insert (js2-make-pad i) "<")
4421 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4422 (when (js2-xml-start-tag-node-attrs n)
4423 (insert " ")
4424 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4425 (insert ">"))
4426
4427 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4428 ;; and add the end-tag to the kids list of the parent as well.
4429 (cl-defstruct (js2-xml-end-tag-node
4430 (:include js2-xml-node)
4431 (:constructor nil)
4432 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4433 (pos js2-ts-cursor)
4434 len name)))
4435 "AST node for an XML end-tag. Not currently used."
4436 name) ; a `js2-xml-name-node'
4437
4438 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4439 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4440
4441 (defun js2-visit-xml-end-tag (n v)
4442 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4443
4444 (defun js2-print-xml-end-tag (n i)
4445 (insert (js2-make-pad i))
4446 (insert "</")
4447 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4448 (insert ">"))
4449
4450 (cl-defstruct (js2-xml-name-node
4451 (:include js2-xml-node)
4452 (:constructor nil)
4453 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4454 (pos js2-ts-cursor)
4455 len namespace kids)))
4456 "AST node for an E4X XML name. Not currently used.
4457 Any XML name can be qualified with a namespace, hence the namespace field.
4458 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4459 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4460 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4461 namespace) ; a `js2-string-node'
4462
4463 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4464 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4465
4466 (defun js2-visit-xml-name-node (n v)
4467 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4468
4469 (defun js2-print-xml-name-node (n i)
4470 (insert (js2-make-pad i))
4471 (when (js2-xml-name-node-namespace n)
4472 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4473 (insert "::"))
4474 (dolist (kid (js2-xml-name-node-kids n))
4475 (js2-print-ast kid 0)))
4476
4477 (cl-defstruct (js2-xml-pi-node
4478 (:include js2-xml-node)
4479 (:constructor nil)
4480 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4481 (pos js2-ts-cursor)
4482 len name attrs)))
4483 "AST node for an E4X XML processing instruction. Not currently used."
4484 name ; a `js2-xml-name-node'
4485 attrs) ; a list of `js2-xml-attr-node'
4486
4487 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4488 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4489
4490 (defun js2-visit-xml-pi-node (n v)
4491 (js2-visit-ast (js2-xml-pi-node-name n) v)
4492 (dolist (attr (js2-xml-pi-node-attrs n))
4493 (js2-visit-ast attr v)))
4494
4495 (defun js2-print-xml-pi-node (n i)
4496 (insert (js2-make-pad i) "<?")
4497 (js2-print-ast (js2-xml-pi-node-name n))
4498 (when (js2-xml-pi-node-attrs n)
4499 (insert " ")
4500 (js2-print-list (js2-xml-pi-node-attrs n)))
4501 (insert "?>"))
4502
4503 (cl-defstruct (js2-xml-cdata-node
4504 (:include js2-xml-node)
4505 (:constructor nil)
4506 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4507 (pos js2-ts-cursor)
4508 len content)))
4509 "AST node for a CDATA escape section. Not currently used."
4510 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4511
4512 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4513 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4514
4515 (defun js2-visit-xml-cdata-node (n v)
4516 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4517
4518 (defun js2-print-xml-cdata-node (n i)
4519 (insert (js2-make-pad i))
4520 (js2-print-ast (js2-xml-cdata-node-content n)))
4521
4522 (cl-defstruct (js2-xml-attr-node
4523 (:include js2-xml-node)
4524 (:constructor nil)
4525 (:constructor make-js2-attr-node (&key (type js2-XML)
4526 (pos js2-ts-cursor)
4527 len name value
4528 eq-pos quote-type)))
4529 "AST node representing a foo='bar' XML attribute value. Not yet used."
4530 name ; a `js2-xml-name-node'
4531 value ; a `js2-xml-name-node'
4532 eq-pos ; buffer position of "=" sign
4533 quote-type) ; 'single or 'double
4534
4535 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4536 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4537
4538 (defun js2-visit-xml-attr-node (n v)
4539 (js2-visit-ast (js2-xml-attr-node-name n) v)
4540 (js2-visit-ast (js2-xml-attr-node-value n) v))
4541
4542 (defun js2-print-xml-attr-node (n i)
4543 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4544 "'"
4545 "\"")))
4546 (insert (js2-make-pad i))
4547 (js2-print-ast (js2-xml-attr-node-name n) 0)
4548 (insert "=" quote)
4549 (js2-print-ast (js2-xml-attr-node-value n) 0)
4550 (insert quote)))
4551
4552 (cl-defstruct (js2-xml-text-node
4553 (:include js2-xml-node)
4554 (:constructor nil)
4555 (:constructor make-js2-text-node (&key (type js2-XML)
4556 (pos js2-ts-cursor)
4557 len content)))
4558 "AST node for an E4X XML text node. Not currently used."
4559 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4560
4561 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4562 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4563
4564 (defun js2-visit-xml-text-node (n v)
4565 (js2-visit-ast (js2-xml-text-node-content n) v))
4566
4567 (defun js2-print-xml-text-node (n i)
4568 (insert (js2-make-pad i))
4569 (dolist (kid (js2-xml-text-node-content n))
4570 (js2-print-ast kid)))
4571
4572 (cl-defstruct (js2-xml-comment-node
4573 (:include js2-xml-node)
4574 (:constructor nil)
4575 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4576 (pos js2-ts-cursor)
4577 len)))
4578 "AST node for E4X XML comment. Not currently used.")
4579
4580 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4581 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4582
4583 (defun js2-print-xml-comment (n i)
4584 (insert (js2-make-pad i)
4585 (js2-node-string n)))
4586
4587 ;;; Node utilities
4588
4589 (defsubst js2-node-line (n)
4590 "Fetch the source line number at the start of node N.
4591 This is O(n) in the length of the source buffer; use prudently."
4592 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4593
4594 (defsubst js2-block-node-kid (n i)
4595 "Return child I of node N, or nil if there aren't that many."
4596 (nth i (js2-block-node-kids n)))
4597
4598 (defsubst js2-block-node-first (n)
4599 "Return first child of block node N, or nil if there is none."
4600 (cl-first (js2-block-node-kids n)))
4601
4602 (defun js2-node-root (n)
4603 "Return the root of the AST containing N.
4604 If N has no parent pointer, returns N."
4605 (let ((parent (js2-node-parent n)))
4606 (if parent
4607 (js2-node-root parent)
4608 n)))
4609
4610 (defsubst js2-node-short-name (n)
4611 "Return the short name of node N as a string, e.g. `js2-if-node'."
4612 (substring (symbol-name (aref n 0))
4613 (length "cl-struct-")))
4614
4615 (defun js2-node-child-list (node)
4616 "Return the child list for NODE, a Lisp list of nodes.
4617 Works for block nodes, array nodes, obj literals, funarg lists,
4618 var decls and try nodes (for catch clauses). Note that you should call
4619 `js2-block-node-kids' on the function body for the body statements.
4620 Returns nil for zero-length child lists or unsupported nodes."
4621 (cond
4622 ((js2-function-node-p node)
4623 (js2-function-node-params node))
4624 ((js2-block-node-p node)
4625 (js2-block-node-kids node))
4626 ((js2-try-node-p node)
4627 (js2-try-node-catch-clauses node))
4628 ((js2-array-node-p node)
4629 (js2-array-node-elems node))
4630 ((js2-object-node-p node)
4631 (js2-object-node-elems node))
4632 ((js2-call-node-p node)
4633 (js2-call-node-args node))
4634 ((js2-new-node-p node)
4635 (js2-new-node-args node))
4636 ((js2-var-decl-node-p node)
4637 (js2-var-decl-node-kids node))
4638 (t
4639 nil)))
4640
4641 (defun js2-node-set-child-list (node kids)
4642 "Set the child list for NODE to KIDS."
4643 (cond
4644 ((js2-function-node-p node)
4645 (setf (js2-function-node-params node) kids))
4646 ((js2-block-node-p node)
4647 (setf (js2-block-node-kids node) kids))
4648 ((js2-try-node-p node)
4649 (setf (js2-try-node-catch-clauses node) kids))
4650 ((js2-array-node-p node)
4651 (setf (js2-array-node-elems node) kids))
4652 ((js2-object-node-p node)
4653 (setf (js2-object-node-elems node) kids))
4654 ((js2-call-node-p node)
4655 (setf (js2-call-node-args node) kids))
4656 ((js2-new-node-p node)
4657 (setf (js2-new-node-args node) kids))
4658 ((js2-var-decl-node-p node)
4659 (setf (js2-var-decl-node-kids node) kids))
4660 (t
4661 (error "Unsupported node type: %s" (js2-node-short-name node))))
4662 kids)
4663
4664 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4665 (defconst js2-paren-expr-nodes
4666 '(cl-struct-js2-comp-loop-node
4667 cl-struct-js2-comp-node
4668 cl-struct-js2-call-node
4669 cl-struct-js2-catch-node
4670 cl-struct-js2-do-node
4671 cl-struct-js2-elem-get-node
4672 cl-struct-js2-for-in-node
4673 cl-struct-js2-for-node
4674 cl-struct-js2-function-node
4675 cl-struct-js2-if-node
4676 cl-struct-js2-let-node
4677 cl-struct-js2-new-node
4678 cl-struct-js2-paren-node
4679 cl-struct-js2-switch-node
4680 cl-struct-js2-while-node
4681 cl-struct-js2-with-node
4682 cl-struct-js2-xml-dot-query-node)
4683 "Node types that can have a parenthesized child expression.
4684 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4685
4686 (defsubst js2-paren-expr-node-p (node)
4687 "Return t for nodes that typically have a parenthesized child expression.
4688 Useful for computing the indentation anchors for arg-lists and conditions.
4689 Note that it may return a false positive, for instance when NODE is
4690 a `js2-new-node' and there are no arguments or parentheses."
4691 (memq (aref node 0) js2-paren-expr-nodes))
4692
4693 ;; Fake polymorphism... yech.
4694 (defun js2-node-lp (node)
4695 "Return relative left-paren position for NODE, if applicable.
4696 For `js2-elem-get-node' structs, returns left-bracket position.
4697 Note that the position may be nil in the case of a parse error."
4698 (cond
4699 ((js2-elem-get-node-p node)
4700 (js2-elem-get-node-lb node))
4701 ((js2-loop-node-p node)
4702 (js2-loop-node-lp node))
4703 ((js2-function-node-p node)
4704 (js2-function-node-lp node))
4705 ((js2-if-node-p node)
4706 (js2-if-node-lp node))
4707 ((js2-new-node-p node)
4708 (js2-new-node-lp node))
4709 ((js2-call-node-p node)
4710 (js2-call-node-lp node))
4711 ((js2-paren-node-p node)
4712 0)
4713 ((js2-switch-node-p node)
4714 (js2-switch-node-lp node))
4715 ((js2-catch-node-p node)
4716 (js2-catch-node-lp node))
4717 ((js2-let-node-p node)
4718 (js2-let-node-lp node))
4719 ((js2-comp-node-p node)
4720 0)
4721 ((js2-with-node-p node)
4722 (js2-with-node-lp node))
4723 ((js2-xml-dot-query-node-p node)
4724 (1+ (js2-infix-node-op-pos node)))
4725 (t
4726 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4727
4728 ;; Fake polymorphism... blech.
4729 (defun js2-node-rp (node)
4730 "Return relative right-paren position for NODE, if applicable.
4731 For `js2-elem-get-node' structs, returns right-bracket position.
4732 Note that the position may be nil in the case of a parse error."
4733 (cond
4734 ((js2-elem-get-node-p node)
4735 (js2-elem-get-node-rb node))
4736 ((js2-loop-node-p node)
4737 (js2-loop-node-rp node))
4738 ((js2-function-node-p node)
4739 (js2-function-node-rp node))
4740 ((js2-if-node-p node)
4741 (js2-if-node-rp node))
4742 ((js2-new-node-p node)
4743 (js2-new-node-rp node))
4744 ((js2-call-node-p node)
4745 (js2-call-node-rp node))
4746 ((js2-paren-node-p node)
4747 (1- (js2-node-len node)))
4748 ((js2-switch-node-p node)
4749 (js2-switch-node-rp node))
4750 ((js2-catch-node-p node)
4751 (js2-catch-node-rp node))
4752 ((js2-let-node-p node)
4753 (js2-let-node-rp node))
4754 ((js2-comp-node-p node)
4755 (1- (js2-node-len node)))
4756 ((js2-with-node-p node)
4757 (js2-with-node-rp node))
4758 ((js2-xml-dot-query-node-p node)
4759 (1+ (js2-xml-dot-query-node-rp node)))
4760 (t
4761 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4762
4763 (defsubst js2-node-first-child (node)
4764 "Return the first element of `js2-node-child-list' for NODE."
4765 (car (js2-node-child-list node)))
4766
4767 (defsubst js2-node-last-child (node)
4768 "Return the last element of `js2-node-last-child' for NODE."
4769 (car (last (js2-node-child-list node))))
4770
4771 (defun js2-node-prev-sibling (node)
4772 "Return the previous statement in parent.
4773 Works for parents supported by `js2-node-child-list'.
4774 Returns nil if NODE is not in the parent, or PARENT is
4775 not a supported node, or if NODE is the first child."
4776 (let* ((p (js2-node-parent node))
4777 (kids (js2-node-child-list p))
4778 (sib (car kids)))
4779 (while (and kids
4780 (not (eq node (cadr kids))))
4781 (setq kids (cdr kids)
4782 sib (car kids)))
4783 sib))
4784
4785 (defun js2-node-next-sibling (node)
4786 "Return the next statement in parent block.
4787 Returns nil if NODE is not in the block, or PARENT is not
4788 a block node, or if NODE is the last statement."
4789 (let* ((p (js2-node-parent node))
4790 (kids (js2-node-child-list p)))
4791 (while (and kids
4792 (not (eq node (car kids))))
4793 (setq kids (cdr kids)))
4794 (cadr kids)))
4795
4796 (defun js2-node-find-child-before (pos parent &optional after)
4797 "Find the last child that starts before POS in parent.
4798 If AFTER is non-nil, returns first child starting after POS.
4799 POS is an absolute buffer position. PARENT is any node
4800 supported by `js2-node-child-list'.
4801 Returns nil if no applicable child is found."
4802 (let ((kids (if (js2-function-node-p parent)
4803 (js2-block-node-kids (js2-function-node-body parent))
4804 (js2-node-child-list parent)))
4805 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4806 (js2-function-node-body parent)
4807 parent)))
4808 kid result fn
4809 (continue t))
4810 (setq fn (if after '>= '<))
4811 (while (and kids continue)
4812 (setq kid (car kids))
4813 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4814 (setq result kid
4815 continue (not after))
4816 (setq continue after))
4817 (setq kids (cdr kids)))
4818 result))
4819
4820 (defun js2-node-find-child-after (pos parent)
4821 "Find first child that starts after POS in parent.
4822 POS is an absolute buffer position. PARENT is any node
4823 supported by `js2-node-child-list'.
4824 Returns nil if no applicable child is found."
4825 (js2-node-find-child-before pos parent 'after))
4826
4827 (defun js2-node-replace-child (pos parent new-node)
4828 "Replace node at index POS in PARENT with NEW-NODE.
4829 Only works for parents supported by `js2-node-child-list'."
4830 (let ((kids (js2-node-child-list parent))
4831 (i 0))
4832 (while (< i pos)
4833 (setq kids (cdr kids)
4834 i (1+ i)))
4835 (setcar kids new-node)
4836 (js2-node-add-children parent new-node)))
4837
4838 (defun js2-node-buffer (n)
4839 "Return the buffer associated with AST N.
4840 Returns nil if the buffer is not set as a property on the root
4841 node, or if parent links were not recorded during parsing."
4842 (let ((root (js2-node-root n)))
4843 (and root
4844 (js2-ast-root-p root)
4845 (js2-ast-root-buffer root))))
4846
4847 (defun js2-block-node-push (n kid)
4848 "Push js2-node KID onto the end of js2-block-node N's child list.
4849 KID is always added to the -end- of the kids list.
4850 Function also calls `js2-node-add-children' to add the parent link."
4851 (let ((kids (js2-node-child-list n)))
4852 (if kids
4853 (setcdr kids (nconc (cdr kids) (list kid)))
4854 (js2-node-set-child-list n (list kid)))
4855 (js2-node-add-children n kid)))
4856
4857 (defun js2-node-string (node)
4858 (with-current-buffer (or (js2-node-buffer node)
4859 (error "No buffer available for node %s" node))
4860 (let ((pos (js2-node-abs-pos node)))
4861 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4862
4863 ;; Container for storing the node we're looking for in a traversal.
4864 (js2-deflocal js2-discovered-node nil)
4865
4866 ;; Keep track of absolute node position during traversals.
4867 (js2-deflocal js2-visitor-offset nil)
4868
4869 (js2-deflocal js2-node-search-point nil)
4870
4871 (when js2-mode-dev-mode-p
4872 (defun js2-find-node-at-point ()
4873 (interactive)
4874 (let ((node (js2-node-at-point)))
4875 (message "%s" (or node "No node found at point"))))
4876 (defun js2-node-name-at-point ()
4877 (interactive)
4878 (let ((node (js2-node-at-point)))
4879 (message "%s" (if node
4880 (js2-node-short-name node)
4881 "No node found at point.")))))
4882
4883 (defun js2-node-at-point (&optional pos skip-comments)
4884 "Return AST node at POS, a buffer position, defaulting to current point.
4885 The `js2-mode-ast' variable must be set to the current parse tree.
4886 Signals an error if the AST (`js2-mode-ast') is nil.
4887 Always returns a node - if it can't find one, it returns the root.
4888 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4889 (let ((ast js2-mode-ast)
4890 result)
4891 (unless ast
4892 (error "No JavaScript AST available"))
4893 ;; Look through comments first, since they may be inside nodes that
4894 ;; would otherwise report a match.
4895 (setq pos (or pos (point))
4896 result (if (> pos (js2-node-abs-end ast))
4897 ast
4898 (if (not skip-comments)
4899 (js2-comment-at-point pos))))
4900 (unless result
4901 (setq js2-discovered-node nil
4902 js2-visitor-offset 0
4903 js2-node-search-point pos)
4904 (unwind-protect
4905 (catch 'js2-visit-done
4906 (js2-visit-ast ast #'js2-node-at-point-visitor))
4907 (setq js2-visitor-offset nil
4908 js2-node-search-point nil))
4909 (setq result js2-discovered-node))
4910 ;; may have found a comment beyond end of last child node,
4911 ;; since visiting the ast-root looks at the comment-list last.
4912 (if (and skip-comments
4913 (js2-comment-node-p result))
4914 (setq result nil))
4915 (or result js2-mode-ast)))
4916
4917 (defun js2-node-at-point-visitor (node end-p)
4918 (let ((rel-pos (js2-node-pos node))
4919 abs-pos
4920 abs-end
4921 (point js2-node-search-point))
4922 (cond
4923 (end-p
4924 ;; this evaluates to a non-nil return value, even if it's zero
4925 (cl-decf js2-visitor-offset rel-pos))
4926 ;; we already looked for comments before visiting, and don't want them now
4927 ((js2-comment-node-p node)
4928 nil)
4929 (t
4930 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4931 ;; we only want to use the node if the point is before
4932 ;; the last character position in the node, so we decrement
4933 ;; the absolute end by 1.
4934 abs-end (+ abs-pos (js2-node-len node) -1))
4935 (cond
4936 ;; If this node starts after search-point, stop the search.
4937 ((> abs-pos point)
4938 (throw 'js2-visit-done nil))
4939 ;; If this node ends before the search-point, don't check kids.
4940 ((> point abs-end)
4941 nil)
4942 (t
4943 ;; Otherwise point is within this node, possibly in a child.
4944 (setq js2-discovered-node node)
4945 t)))))) ; keep processing kids to look for more specific match
4946
4947 (defsubst js2-block-comment-p (node)
4948 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4949 (and (js2-comment-node-p node)
4950 (memq (js2-comment-node-format node) '(jsdoc block))))
4951
4952 ;; TODO: put the comments in a vector and binary-search them instead
4953 (defun js2-comment-at-point (&optional pos)
4954 "Look through scanned comment nodes for one containing POS.
4955 POS is a buffer position that defaults to current point.
4956 Function returns nil if POS was not in any comment node."
4957 (let ((ast js2-mode-ast)
4958 (x (or pos (point)))
4959 beg end)
4960 (unless ast
4961 (error "No JavaScript AST available"))
4962 (catch 'done
4963 ;; Comments are stored in lexical order.
4964 (dolist (comment (js2-ast-root-comments ast) nil)
4965 (setq beg (js2-node-abs-pos comment)
4966 end (+ beg (js2-node-len comment)))
4967 (if (and (>= x beg)
4968 (<= x end))
4969 (throw 'done comment))))))
4970
4971 (defun js2-mode-find-parent-fn (node)
4972 "Find function enclosing NODE.
4973 Returns nil if NODE is not inside a function."
4974 (setq node (js2-node-parent node))
4975 (while (and node (not (js2-function-node-p node)))
4976 (setq node (js2-node-parent node)))
4977 (and (js2-function-node-p node) node))
4978
4979 (defun js2-mode-find-enclosing-fn (node)
4980 "Find function or root enclosing NODE."
4981 (if (js2-ast-root-p node)
4982 node
4983 (setq node (js2-node-parent node))
4984 (while (not (or (js2-ast-root-p node)
4985 (js2-function-node-p node)))
4986 (setq node (js2-node-parent node)))
4987 node))
4988
4989 (defun js2-mode-find-enclosing-node (beg end)
4990 "Find node fully enclosing BEG and END."
4991 (let ((node (js2-node-at-point beg))
4992 pos
4993 (continue t))
4994 (while continue
4995 (if (or (js2-ast-root-p node)
4996 (and
4997 (<= (setq pos (js2-node-abs-pos node)) beg)
4998 (>= (+ pos (js2-node-len node)) end)))
4999 (setq continue nil)
5000 (setq node (js2-node-parent node))))
5001 node))
5002
5003 (defun js2-node-parent-script-or-fn (node)
5004 "Find script or function immediately enclosing NODE.
5005 If NODE is the ast-root, returns nil."
5006 (if (js2-ast-root-p node)
5007 nil
5008 (setq node (js2-node-parent node))
5009 (while (and node (not (or (js2-function-node-p node)
5010 (js2-script-node-p node))))
5011 (setq node (js2-node-parent node)))
5012 node))
5013
5014 (defun js2-node-is-descendant (node ancestor)
5015 "Return t if NODE is a descendant of ANCESTOR."
5016 (while (and node
5017 (not (eq node ancestor)))
5018 (setq node (js2-node-parent node)))
5019 node)
5020
5021 ;;; visitor infrastructure
5022
5023 (defun js2-visit-none (_node _callback)
5024 "Visitor for AST node that have no node children."
5025 nil)
5026
5027 (defun js2-print-none (_node _indent)
5028 "Visitor for AST node with no printed representation.")
5029
5030 (defun js2-print-body (node indent)
5031 "Print a statement, or a block without braces."
5032 (if (js2-block-node-p node)
5033 (dolist (kid (js2-block-node-kids node))
5034 (js2-print-ast kid indent))
5035 (js2-print-ast node indent)))
5036
5037 (defun js2-print-list (args &optional delimiter)
5038 (cl-loop with len = (length args)
5039 for arg in args
5040 for count from 1
5041 do
5042 (when arg (js2-print-ast arg 0))
5043 (if (< count len)
5044 (insert (or delimiter ", ")))))
5045
5046 (defun js2-print-tree (ast)
5047 "Prints an AST to the current buffer.
5048 Makes `js2-ast-parent-nodes' available to the printer functions."
5049 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5050 (js2-print-ast ast)))
5051
5052 (defun js2-print-ast (node &optional indent)
5053 "Helper function for printing AST nodes.
5054 Requires `js2-ast-parent-nodes' to be non-nil.
5055 You should use `js2-print-tree' instead of this function."
5056 (let ((printer (get (aref node 0) 'js2-printer))
5057 (i (or indent 0)))
5058 ;; TODO: wedge comments in here somewhere
5059 (if printer
5060 (funcall printer node i))))
5061
5062 (defconst js2-side-effecting-tokens
5063 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5064 (dolist (tt (list js2-ASSIGN
5065 js2-ASSIGN_ADD
5066 js2-ASSIGN_BITAND
5067 js2-ASSIGN_BITOR
5068 js2-ASSIGN_BITXOR
5069 js2-ASSIGN_DIV
5070 js2-ASSIGN_LSH
5071 js2-ASSIGN_MOD
5072 js2-ASSIGN_MUL
5073 js2-ASSIGN_RSH
5074 js2-ASSIGN_SUB
5075 js2-ASSIGN_URSH
5076 js2-BLOCK
5077 js2-BREAK
5078 js2-CALL
5079 js2-CATCH
5080 js2-CATCH_SCOPE
5081 js2-CLASS
5082 js2-CONST
5083 js2-CONTINUE
5084 js2-DEBUGGER
5085 js2-DEC
5086 js2-DELPROP
5087 js2-DEL_REF
5088 js2-DO
5089 js2-ELSE
5090 js2-EMPTY
5091 js2-ENTERWITH
5092 js2-EXPORT
5093 js2-EXPR_RESULT
5094 js2-FINALLY
5095 js2-FOR
5096 js2-FUNCTION
5097 js2-GOTO
5098 js2-IF
5099 js2-IFEQ
5100 js2-IFNE
5101 js2-IMPORT
5102 js2-INC
5103 js2-JSR
5104 js2-LABEL
5105 js2-LEAVEWITH
5106 js2-LET
5107 js2-LETEXPR
5108 js2-LOCAL_BLOCK
5109 js2-LOOP
5110 js2-NEW
5111 js2-REF_CALL
5112 js2-RETHROW
5113 js2-RETURN
5114 js2-RETURN_RESULT
5115 js2-SEMI
5116 js2-SETELEM
5117 js2-SETELEM_OP
5118 js2-SETNAME
5119 js2-SETPROP
5120 js2-SETPROP_OP
5121 js2-SETVAR
5122 js2-SET_REF
5123 js2-SET_REF_OP
5124 js2-SWITCH
5125 js2-TARGET
5126 js2-THROW
5127 js2-TRY
5128 js2-VAR
5129 js2-WHILE
5130 js2-WITH
5131 js2-WITHEXPR
5132 js2-YIELD))
5133 (aset tokens tt t))
5134 (if js2-instanceof-has-side-effects
5135 (aset tokens js2-INSTANCEOF t))
5136 tokens))
5137
5138 (defun js2-node-has-side-effects (node)
5139 "Return t if NODE has side effects."
5140 (when node ; makes it easier to handle malformed expressions
5141 (let ((tt (js2-node-type node)))
5142 (cond
5143 ;; This doubtless needs some work, since EXPR_VOID is used
5144 ;; in several ways in Rhino and I may not have caught them all.
5145 ;; I'll wait for people to notice incorrect warnings.
5146 ((and (= tt js2-EXPR_VOID)
5147 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5148 (let ((expr (js2-expr-stmt-node-expr node)))
5149 (or (js2-node-has-side-effects expr)
5150 (when (js2-string-node-p expr)
5151 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5152 ((= tt js2-COMMA)
5153 (js2-node-has-side-effects (js2-infix-node-right node)))
5154 ((or (= tt js2-AND)
5155 (= tt js2-OR))
5156 (or (js2-node-has-side-effects (js2-infix-node-right node))
5157 (js2-node-has-side-effects (js2-infix-node-left node))))
5158 ((= tt js2-HOOK)
5159 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5160 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5161 ((js2-paren-node-p node)
5162 (js2-node-has-side-effects (js2-paren-node-expr node)))
5163 ((= tt js2-ERROR) ; avoid cascaded error messages
5164 nil)
5165 (t
5166 (aref js2-side-effecting-tokens tt))))))
5167
5168 (defconst js2-stmt-node-types
5169 (list js2-BLOCK
5170 js2-BREAK
5171 js2-CONTINUE
5172 js2-DEFAULT ; e4x "default xml namespace" statement
5173 js2-DO
5174 js2-EXPORT
5175 js2-EXPR_RESULT
5176 js2-EXPR_VOID
5177 js2-FOR
5178 js2-IF
5179 js2-IMPORT
5180 js2-RETURN
5181 js2-SWITCH
5182 js2-THROW
5183 js2-TRY
5184 js2-WHILE
5185 js2-WITH)
5186 "Node types that only appear in statement contexts.
5187 The list does not include nodes that always appear as the child
5188 of another specific statement type, such as switch-cases,
5189 catch and finally blocks, and else-clauses. The list also excludes
5190 nodes like yield, let and var, which may appear in either expression
5191 or statement context, and in the latter context always have a
5192 `js2-expr-stmt-node' parent. Finally, the list does not include
5193 functions or scripts, which are treated separately from statements
5194 by the JavaScript parser and runtime.")
5195
5196 (defun js2-stmt-node-p (node)
5197 "Heuristic for figuring out if NODE is a statement.
5198 Some node types can appear in either an expression context or a
5199 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5200 For these node types in a statement context, the parent will be a
5201 `js2-expr-stmt-node'.
5202 Functions aren't included in the check."
5203 (memq (js2-node-type node) js2-stmt-node-types))
5204
5205 (defun js2-mode-find-first-stmt (node)
5206 "Search upward starting from NODE looking for a statement.
5207 For purposes of this function, a `js2-function-node' counts."
5208 (while (not (or (js2-stmt-node-p node)
5209 (js2-function-node-p node)))
5210 (setq node (js2-node-parent node)))
5211 node)
5212
5213 (defun js2-node-parent-stmt (node)
5214 "Return the node's first ancestor that is a statement.
5215 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5216 appearing in a statement context will have a parent that is a
5217 `js2-expr-stmt-node' that will be returned by this function."
5218 (let ((parent (js2-node-parent node)))
5219 (if (or (null parent)
5220 (js2-stmt-node-p parent)
5221 (and (js2-function-node-p parent)
5222 (not (eq (js2-function-node-form parent)
5223 'FUNCTION_EXPRESSION))))
5224 parent
5225 (js2-node-parent-stmt parent))))
5226
5227 ;; In the Mozilla Rhino sources, Roshan James writes:
5228 ;; Does consistent-return analysis on the function body when strict mode is
5229 ;; enabled.
5230 ;;
5231 ;; function (x) { return (x+1) }
5232 ;;
5233 ;; is ok, but
5234 ;;
5235 ;; function (x) { if (x < 0) return (x+1); }
5236 ;;
5237 ;; is not because the function can potentially return a value when the
5238 ;; condition is satisfied and if not, the function does not explicitly
5239 ;; return a value.
5240 ;;
5241 ;; This extends to checking mismatches such as "return" and "return <value>"
5242 ;; used in the same function. Warnings are not emitted if inconsistent
5243 ;; returns exist in code that can be statically shown to be unreachable.
5244 ;; Ex.
5245 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5246 ;;
5247 ;; emits no warning. However if the loop had a break statement, then a
5248 ;; warning would be emitted.
5249 ;;
5250 ;; The consistency analysis looks at control structures such as loops, ifs,
5251 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5252 ;; warns the user about an inconsistent set of termination possibilities.
5253 ;;
5254 ;; These flags enumerate the possible ways a statement/function can
5255 ;; terminate. These flags are used by endCheck() and by the Parser to
5256 ;; detect inconsistent return usage.
5257 ;;
5258 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5259 ;; able to execute (example: throw, continue)
5260 ;;
5261 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5262 ;; next one. Statement such as return dont. A compound statement may have
5263 ;; some branch that drops off control to the next statement.
5264 ;;
5265 ;; END_RETURNS indicates that the statement can return with no value.
5266 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5267 ;;
5268 ;; A compound statement such as
5269 ;; if (condition) {
5270 ;; return value;
5271 ;; }
5272 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5273
5274 (defconst js2-END_UNREACHED 0)
5275 (defconst js2-END_DROPS_OFF 1)
5276 (defconst js2-END_RETURNS 2)
5277 (defconst js2-END_RETURNS_VALUE 4)
5278 (defconst js2-END_YIELDS 8)
5279
5280 (defun js2-has-consistent-return-usage (node)
5281 "Check that every return usage in a function body is consistent.
5282 Returns t if the function satisfies strict mode requirement."
5283 (let ((n (js2-end-check node)))
5284 ;; either it doesn't return a value in any branch...
5285 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5286 ;; or it returns a value (or is unreached) at every branch
5287 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5288 js2-END_RETURNS
5289 js2-END_YIELDS)))))
5290
5291 (defun js2-end-check-if (node)
5292 "Ensure that return usage in then/else blocks is consistent.
5293 If there is no else block, then the return statement can fall through.
5294 Returns logical OR of END_* flags"
5295 (let ((th (js2-if-node-then-part node))
5296 (el (js2-if-node-else-part node)))
5297 (if (null th)
5298 js2-END_UNREACHED
5299 (logior (js2-end-check th) (if el
5300 (js2-end-check el)
5301 js2-END_DROPS_OFF)))))
5302
5303 (defun js2-end-check-switch (node)
5304 "Consistency of return statements is checked between the case statements.
5305 If there is no default, then the switch can fall through. If there is a
5306 default, we check to see if all code paths in the default return or if
5307 there is a code path that can fall through.
5308 Returns logical OR of END_* flags."
5309 (let ((rv js2-END_UNREACHED)
5310 default-case)
5311 ;; examine the cases
5312 (catch 'break
5313 (dolist (c (js2-switch-node-cases node))
5314 (if (js2-case-node-expr c)
5315 (js2-set-flag rv (js2-end-check-block c))
5316 (setq default-case c)
5317 (throw 'break nil))))
5318 ;; we don't care how the cases drop into each other
5319 (js2-clear-flag rv js2-END_DROPS_OFF)
5320 ;; examine the default
5321 (js2-set-flag rv (if default-case
5322 (js2-end-check default-case)
5323 js2-END_DROPS_OFF))
5324 rv))
5325
5326 (defun js2-end-check-try (node)
5327 "If the block has a finally, return consistency is checked in the
5328 finally block. If all code paths in the finally return, then the
5329 returns in the try-catch blocks don't matter. If there is a code path
5330 that does not return or if there is no finally block, the returns
5331 of the try and catch blocks are checked for mismatch.
5332 Returns logical OR of END_* flags."
5333 (let ((finally (js2-try-node-finally-block node))
5334 rv)
5335 ;; check the finally if it exists
5336 (setq rv (if finally
5337 (js2-end-check (js2-finally-node-body finally))
5338 js2-END_DROPS_OFF))
5339 ;; If the finally block always returns, then none of the returns
5340 ;; in the try or catch blocks matter.
5341 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5342 (js2-clear-flag rv js2-END_DROPS_OFF)
5343 ;; examine the try block
5344 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5345 ;; check each catch block
5346 (dolist (cb (js2-try-node-catch-clauses node))
5347 (js2-set-flag rv (js2-end-check cb))))
5348 rv))
5349
5350 (defun js2-end-check-loop (node)
5351 "Return statement in the loop body must be consistent.
5352 The default assumption for any kind of a loop is that it will eventually
5353 terminate. The only exception is a loop with a constant true condition.
5354 Code that follows such a loop is examined only if one can determine
5355 statically that there is a break out of the loop.
5356
5357 for(... ; ... ; ...) {}
5358 for(... in ... ) {}
5359 while(...) { }
5360 do { } while(...)
5361
5362 Returns logical OR of END_* flags."
5363 (let ((rv (js2-end-check (js2-loop-node-body node)))
5364 (condition (cond
5365 ((js2-while-node-p node)
5366 (js2-while-node-condition node))
5367 ((js2-do-node-p node)
5368 (js2-do-node-condition node))
5369 ((js2-for-node-p node)
5370 (js2-for-node-condition node)))))
5371
5372 ;; check to see if the loop condition is always true
5373 (if (and condition
5374 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5375 (js2-clear-flag rv js2-END_DROPS_OFF))
5376
5377 ;; look for effect of breaks
5378 (js2-set-flag rv (js2-node-get-prop node
5379 'CONTROL_BLOCK_PROP
5380 js2-END_UNREACHED))
5381 rv))
5382
5383 (defun js2-end-check-block (node)
5384 "A general block of code is examined statement by statement.
5385 If any statement (even a compound one) returns in all branches, then
5386 subsequent statements are not examined.
5387 Returns logical OR of END_* flags."
5388 (let* ((rv js2-END_DROPS_OFF)
5389 (kids (js2-block-node-kids node))
5390 (n (car kids)))
5391 ;; Check each statement. If the statement can continue onto the next
5392 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5393 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5394 (js2-clear-flag rv js2-END_DROPS_OFF)
5395 (js2-set-flag rv (js2-end-check n))
5396 (setq kids (cdr kids)
5397 n (car kids)))
5398 rv))
5399
5400 (defun js2-end-check-label (node)
5401 "A labeled statement implies that there may be a break to the label.
5402 The function processes the labeled statement and then checks the
5403 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5404 particular label.
5405 Returns logical OR of END_* flags."
5406 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5407 (logior rv (js2-node-get-prop node
5408 'CONTROL_BLOCK_PROP
5409 js2-END_UNREACHED))))
5410
5411 (defun js2-end-check-break (node)
5412 "When a break is encountered annotate the statement being broken
5413 out of by setting its CONTROL_BLOCK_PROP property.
5414 Returns logical OR of END_* flags."
5415 (and (js2-break-node-target node)
5416 (js2-node-set-prop (js2-break-node-target node)
5417 'CONTROL_BLOCK_PROP
5418 js2-END_DROPS_OFF))
5419 js2-END_UNREACHED)
5420
5421 (defun js2-end-check (node)
5422 "Examine the body of a function, doing a basic reachability analysis.
5423 Returns a combination of flags END_* flags that indicate
5424 how the function execution can terminate. These constitute only the
5425 pessimistic set of termination conditions. It is possible that at
5426 runtime certain code paths will never be actually taken. Hence this
5427 analysis will flag errors in cases where there may not be errors.
5428 Returns logical OR of END_* flags"
5429 (let (kid)
5430 (cond
5431 ((js2-break-node-p node)
5432 (js2-end-check-break node))
5433 ((js2-expr-stmt-node-p node)
5434 (if (setq kid (js2-expr-stmt-node-expr node))
5435 (js2-end-check kid)
5436 js2-END_DROPS_OFF))
5437 ((or (js2-continue-node-p node)
5438 (js2-throw-node-p node))
5439 js2-END_UNREACHED)
5440 ((js2-return-node-p node)
5441 (if (setq kid (js2-return-node-retval node))
5442 js2-END_RETURNS_VALUE
5443 js2-END_RETURNS))
5444 ((js2-loop-node-p node)
5445 (js2-end-check-loop node))
5446 ((js2-switch-node-p node)
5447 (js2-end-check-switch node))
5448 ((js2-labeled-stmt-node-p node)
5449 (js2-end-check-label node))
5450 ((js2-if-node-p node)
5451 (js2-end-check-if node))
5452 ((js2-try-node-p node)
5453 (js2-end-check-try node))
5454 ((js2-block-node-p node)
5455 (if (null (js2-block-node-kids node))
5456 js2-END_DROPS_OFF
5457 (js2-end-check-block node)))
5458 ((js2-yield-node-p node)
5459 js2-END_YIELDS)
5460 (t
5461 js2-END_DROPS_OFF))))
5462
5463 (defun js2-always-defined-boolean-p (node)
5464 "Check if NODE always evaluates to true or false in boolean context.
5465 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5466 nor always false."
5467 (let ((tt (js2-node-type node))
5468 num)
5469 (cond
5470 ((or (= tt js2-FALSE) (= tt js2-NULL))
5471 'ALWAYS_FALSE)
5472 ((= tt js2-TRUE)
5473 'ALWAYS_TRUE)
5474 ((= tt js2-NUMBER)
5475 (setq num (js2-number-node-num-value node))
5476 (if (and (not (eq num 0.0e+NaN))
5477 (not (zerop num)))
5478 'ALWAYS_TRUE
5479 'ALWAYS_FALSE))
5480 (t
5481 nil))))
5482
5483 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5484 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5485
5486 (defvar js2-tokens nil
5487 "List of all defined token names.") ; initialized in `js2-token-names'
5488
5489 (defconst js2-token-names
5490 (let* ((names (make-vector js2-num-tokens -1))
5491 (case-fold-search nil) ; only match js2-UPPER_CASE
5492 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5493 (cl-loop for sym in syms
5494 for i from 0
5495 do
5496 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5497 (not (boundp sym)))
5498 (aset names (symbol-value sym) ; code, e.g. 152
5499 (downcase
5500 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5501 (push sym js2-tokens)))
5502 names)
5503 "Vector mapping int values to token string names, sans `js2-' prefix.")
5504
5505 (defun js2-tt-name (tok)
5506 "Return a string name for TOK, a token symbol or code.
5507 Signals an error if it's not a recognized token."
5508 (let ((code tok))
5509 (if (symbolp tok)
5510 (setq code (symbol-value tok)))
5511 (if (eq code -1)
5512 "ERROR"
5513 (if (and (numberp code)
5514 (not (cl-minusp code))
5515 (< code js2-num-tokens))
5516 (aref js2-token-names code)
5517 (error "Invalid token: %s" code)))))
5518
5519 (defsubst js2-tt-sym (tok)
5520 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5521 (intern (js2-tt-name tok)))
5522
5523 (defconst js2-token-codes
5524 (let ((table (make-hash-table :test 'eq :size 256)))
5525 (cl-loop for name across js2-token-names
5526 for sym = (intern (concat "js2-" (upcase name)))
5527 do
5528 (puthash sym (symbol-value sym) table))
5529 ;; clean up a few that are "wrong" in Rhino's token codes
5530 (puthash 'js2-DELETE js2-DELPROP table)
5531 table)
5532 "Hashtable mapping token type symbols to their bytecodes.")
5533
5534 (defsubst js2-tt-code (sym)
5535 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5536 (or (gethash sym js2-token-codes)
5537 (error "Invalid token symbol: %s " sym))) ; signal code bug
5538
5539 (defun js2-report-scan-error (msg &optional no-throw beg len)
5540 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5541 (js2-report-error msg nil
5542 (or beg (js2-current-token-beg))
5543 (or len (js2-current-token-len)))
5544 (unless no-throw
5545 (throw 'return js2-ERROR)))
5546
5547 (defun js2-set-string-from-buffer (token)
5548 "Set `string' and `end' slots for TOKEN, return the string."
5549 (setf (js2-token-end token) js2-ts-cursor
5550 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5551
5552 ;; TODO: could potentially avoid a lot of consing by allocating a
5553 ;; char buffer the way Rhino does.
5554 (defsubst js2-add-to-string (c)
5555 (push c js2-ts-string-buffer))
5556
5557 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5558 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5559 ;; any other character: when it's not part of the current token, we
5560 ;; unget it, allowing it to be read again by the following call.
5561 (defsubst js2-unget-char ()
5562 (cl-decf js2-ts-cursor))
5563
5564 ;; Rhino distinguishes \r and \n line endings. We don't need to
5565 ;; because we only scan from Emacs buffers, which always use \n.
5566 (defun js2-get-char ()
5567 "Read and return the next character from the input buffer.
5568 Increments `js2-ts-lineno' if the return value is a newline char.
5569 Updates `js2-ts-cursor' to the point after the returned char.
5570 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5571 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5572 (let (c)
5573 ;; check for end of buffer
5574 (if (>= js2-ts-cursor (point-max))
5575 (setq js2-ts-hit-eof t
5576 js2-ts-cursor (1+ js2-ts-cursor)
5577 c js2-EOF_CHAR) ; return value
5578 ;; otherwise read next char
5579 (setq c (char-before (cl-incf js2-ts-cursor)))
5580 ;; if we read a newline, update counters
5581 (if (= c ?\n)
5582 (setq js2-ts-line-start js2-ts-cursor
5583 js2-ts-lineno (1+ js2-ts-lineno)))
5584 ;; TODO: skip over format characters
5585 c)))
5586
5587 (defun js2-read-unicode-escape ()
5588 "Read a \\uNNNN sequence from the input.
5589 Assumes the ?\ and ?u have already been read.
5590 Returns the unicode character, or nil if it wasn't a valid character.
5591 Doesn't change the values of any scanner variables."
5592 ;; I really wish I knew a better way to do this, but I can't
5593 ;; find the Emacs function that takes a 16-bit int and converts
5594 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5595 ;; Have to first check that it's 4 hex characters or it may stop
5596 ;; the read early.
5597 (ignore-errors
5598 (let ((s (buffer-substring-no-properties js2-ts-cursor
5599 (+ 4 js2-ts-cursor))))
5600 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5601 (read (concat "?\\u" s))))))
5602
5603 (defun js2-match-char (test)
5604 "Consume and return next character if it matches TEST, a character.
5605 Returns nil and consumes nothing if TEST is not the next character."
5606 (let ((c (js2-get-char)))
5607 (if (eq c test)
5608 t
5609 (js2-unget-char)
5610 nil)))
5611
5612 (defun js2-peek-char ()
5613 (prog1
5614 (js2-get-char)
5615 (js2-unget-char)))
5616
5617 (defun js2-identifier-start-p (c)
5618 "Is C a valid start to an ES5 Identifier?
5619 See http://es5.github.io/#x7.6"
5620 (or
5621 (memq c '(?$ ?_))
5622 (memq (get-char-code-property c 'general-category)
5623 ;; Letters
5624 '(Lu Ll Lt Lm Lo Nl))))
5625
5626 (defun js2-identifier-part-p (c)
5627 "Is C a valid part of an ES5 Identifier?
5628 See http://es5.github.io/#x7.6"
5629 (or
5630 (memq c '(?$ ?_ ?\u200c ?\u200d))
5631 (memq (get-char-code-property c 'general-category)
5632 '(;; Letters
5633 Lu Ll Lt Lm Lo Nl
5634 ;; Combining Marks
5635 Mn Mc
5636 ;; Digits
5637 Nd
5638 ;; Connector Punctuation
5639 Pc))))
5640
5641 (defun js2-alpha-p (c)
5642 (cond ((and (<= ?A c) (<= c ?Z)) t)
5643 ((and (<= ?a c) (<= c ?z)) t)
5644 (t nil)))
5645
5646 (defsubst js2-digit-p (c)
5647 (and (<= ?0 c) (<= c ?9)))
5648
5649 (defun js2-js-space-p (c)
5650 (if (<= c 127)
5651 (memq c '(#x20 #x9 #xB #xC #xD))
5652 (or
5653 (eq c #xA0)
5654 ;; TODO: change this nil to check for Unicode space character
5655 nil)))
5656
5657 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5658
5659 (defun js2-skip-line ()
5660 "Skip to end of line."
5661 (while (not (memq (js2-get-char) js2-eol-chars)))
5662 (js2-unget-char)
5663 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5664
5665 (defun js2-init-scanner (&optional buf line)
5666 "Create token stream for BUF starting on LINE.
5667 BUF defaults to `current-buffer' and LINE defaults to 1.
5668
5669 A buffer can only have one scanner active at a time, which yields
5670 dramatically simpler code than using a defstruct. If you need to
5671 have simultaneous scanners in a buffer, copy the regions to scan
5672 into temp buffers."
5673 (with-current-buffer (or buf (current-buffer))
5674 (setq js2-ts-dirty-line nil
5675 js2-ts-hit-eof nil
5676 js2-ts-line-start 0
5677 js2-ts-lineno (or line 1)
5678 js2-ts-line-end-char -1
5679 js2-ts-cursor (point-min)
5680 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5681 js2-ti-tokens-cursor 0
5682 js2-ti-lookahead 0
5683 js2-ts-is-xml-attribute nil
5684 js2-ts-xml-is-tag-content nil
5685 js2-ts-xml-open-tags-count 0
5686 js2-ts-string-buffer nil)))
5687
5688 ;; This function uses the cached op, string and number fields in
5689 ;; TokenStream; if getToken has been called since the passed token
5690 ;; was scanned, the op or string printed may be incorrect.
5691 (defun js2-token-to-string (token)
5692 ;; Not sure where this function is used in Rhino. Not tested.
5693 (if (not js2-debug-print-trees)
5694 ""
5695 (let ((name (js2-tt-name token)))
5696 (cond
5697 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5698 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5699 (concat name " `" (js2-current-token-string) "'"))
5700 ((eq token js2-NUMBER)
5701 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5702 (t
5703 name)))))
5704
5705 (defconst js2-keywords
5706 '(break
5707 case catch class const continue
5708 debugger default delete do
5709 else extends export
5710 false finally for function
5711 if in instanceof import
5712 let
5713 new null
5714 return
5715 super switch
5716 this throw true try typeof
5717 var void
5718 while with
5719 yield))
5720
5721 ;; Token names aren't exactly the same as the keywords, unfortunately.
5722 ;; E.g. delete is js2-DELPROP.
5723 (defconst js2-kwd-tokens
5724 (let ((table (make-vector js2-num-tokens nil))
5725 (tokens
5726 (list js2-BREAK
5727 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5728 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5729 js2-ELSE js2-EXPORT
5730 js2-ELSE js2-EXTENDS js2-EXPORT
5731 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5732 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5733 js2-LET
5734 js2-NEW js2-NULL
5735 js2-RETURN
5736 js2-SUPER js2-SWITCH
5737 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5738 js2-VAR
5739 js2-WHILE js2-WITH
5740 js2-YIELD)))
5741 (dolist (i tokens)
5742 (aset table i 'font-lock-keyword-face))
5743 (aset table js2-STRING 'font-lock-string-face)
5744 (aset table js2-REGEXP 'font-lock-string-face)
5745 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5746 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5747 (aset table js2-COMMENT 'font-lock-comment-face)
5748 (aset table js2-THIS 'font-lock-builtin-face)
5749 (aset table js2-SUPER 'font-lock-builtin-face)
5750 (aset table js2-VOID 'font-lock-constant-face)
5751 (aset table js2-NULL 'font-lock-constant-face)
5752 (aset table js2-TRUE 'font-lock-constant-face)
5753 (aset table js2-FALSE 'font-lock-constant-face)
5754 (aset table js2-NOT 'font-lock-negation-char-face)
5755 table)
5756 "Vector whose values are non-nil for tokens that are keywords.
5757 The values are default faces to use for highlighting the keywords.")
5758
5759 ;; FIXME: Support strict mode-only future reserved words, after we know
5760 ;; which parts scopes are in strict mode, and which are not.
5761 (defconst js2-reserved-words '(class enum export extends import static super)
5762 "Future reserved keywords in ECMAScript 5.1.")
5763
5764 (defconst js2-keyword-names
5765 (let ((table (make-hash-table :test 'equal)))
5766 (cl-loop for k in js2-keywords
5767 do (puthash
5768 (symbol-name k) ; instanceof
5769 (intern (concat "js2-"
5770 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5771 table))
5772 table)
5773 "JavaScript keywords by name, mapped to their symbols.")
5774
5775 (defconst js2-reserved-word-names
5776 (let ((table (make-hash-table :test 'equal)))
5777 (cl-loop for k in js2-reserved-words
5778 do
5779 (puthash (symbol-name k) 'js2-RESERVED table))
5780 table)
5781 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5782
5783 (defun js2-collect-string (buf)
5784 "Convert BUF, a list of chars, to a string.
5785 Reverses BUF before converting."
5786 (if buf
5787 (apply #'string (nreverse buf))
5788 ""))
5789
5790 (defun js2-string-to-keyword (s)
5791 "Return token for S, a string, if S is a keyword or reserved word.
5792 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5793 (or (gethash s js2-keyword-names)
5794 (gethash s js2-reserved-word-names)))
5795
5796 (defsubst js2-ts-set-char-token-bounds (token)
5797 "Used when next token is one character."
5798 (setf (js2-token-beg token) (1- js2-ts-cursor)
5799 (js2-token-end token) js2-ts-cursor))
5800
5801 (defsubst js2-ts-return (token type)
5802 "Update the `end' and `type' slots of TOKEN,
5803 then throw `return' with value TYPE."
5804 (setf (js2-token-end token) js2-ts-cursor
5805 (js2-token-type token) type)
5806 (throw 'return type))
5807
5808 (defun js2-x-digit-to-int (c accumulator)
5809 "Build up a hex number.
5810 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5811 corresponding number. Otherwise return -1."
5812 (catch 'return
5813 (catch 'check
5814 ;; Use 0..9 < A..Z < a..z
5815 (cond
5816 ((<= c ?9)
5817 (cl-decf c ?0)
5818 (if (<= 0 c)
5819 (throw 'check nil)))
5820 ((<= c ?F)
5821 (when (<= ?A c)
5822 (cl-decf c (- ?A 10))
5823 (throw 'check nil)))
5824 ((<= c ?f)
5825 (when (<= ?a c)
5826 (cl-decf c (- ?a 10))
5827 (throw 'check nil))))
5828 (throw 'return -1))
5829 (logior c (lsh accumulator 4))))
5830
5831 (defun js2-get-token (&optional modifier)
5832 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5833 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5834 next saved token.
5835
5836 This function will not return a newline (js2-EOL) - instead, it
5837 gobbles newlines until it finds a non-newline token. Call
5838 `js2-peek-token-or-eol' when you care about newlines.
5839
5840 This function will also not return a js2-COMMENT. Instead, it
5841 records comments found in `js2-scanned-comments'. If the token
5842 returned by this function immediately follows a jsdoc comment,
5843 the token is flagged as such."
5844 (if (zerop js2-ti-lookahead)
5845 (js2-get-token-internal modifier)
5846 (cl-decf js2-ti-lookahead)
5847 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5848 (let ((tt (js2-current-token-type)))
5849 (cl-assert (not (= tt js2-EOL)))
5850 tt)))
5851
5852 (defun js2-unget-token ()
5853 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5854 (cl-incf js2-ti-lookahead)
5855 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5856
5857 (defun js2-get-token-internal (modifier)
5858 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5859 (tt (js2-token-type token))
5860 saw-eol
5861 face)
5862 ;; process comments
5863 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5864 (if (= tt js2-EOL)
5865 (setq saw-eol t)
5866 (setq saw-eol nil)
5867 (when js2-record-comments
5868 (js2-record-comment token)))
5869 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5870 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5871 tt (js2-token-type token)))
5872
5873 (when saw-eol
5874 (setf (js2-token-follows-eol-p token) t))
5875
5876 ;; perform lexical fontification as soon as token is scanned
5877 (when js2-parse-ide-mode
5878 (cond
5879 ((cl-minusp tt)
5880 (js2-record-face 'js2-error token))
5881 ((setq face (aref js2-kwd-tokens tt))
5882 (js2-record-face face token))
5883 ((and (= tt js2-NAME)
5884 (equal (js2-token-string token) "undefined"))
5885 (js2-record-face 'font-lock-constant-face token))))
5886 tt))
5887
5888 (defsubst js2-string-to-number (str base)
5889 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5890 (condition-case nil
5891 (string-to-number str base)
5892 (overflow-error -1)))
5893
5894 (defun js2-get-token-internal-1 (modifier)
5895 "Return next JavaScript token type, an int such as js2-RETURN.
5896 During operation, creates an instance of `js2-token' struct, sets
5897 its relevant fields and puts it into `js2-ti-tokens'."
5898 (let (identifier-start
5899 is-unicode-escape-start c
5900 contains-escape escape-val str result base
5901 look-for-slash continue tt
5902 (token (js2-new-token 0)))
5903 (setq
5904 tt
5905 (catch 'return
5906 (when (eq modifier 'TEMPLATE_TAIL)
5907 (setf (js2-token-beg token) (1- js2-ts-cursor))
5908 (throw 'return (js2-get-string-or-template-token ?` token)))
5909 (while t
5910 ;; Eat whitespace, possibly sensitive to newlines.
5911 (setq continue t)
5912 (while continue
5913 (setq c (js2-get-char))
5914 (cond
5915 ((eq c js2-EOF_CHAR)
5916 (js2-unget-char)
5917 (js2-ts-set-char-token-bounds token)
5918 (throw 'return js2-EOF))
5919 ((eq c ?\n)
5920 (js2-ts-set-char-token-bounds token)
5921 (setq js2-ts-dirty-line nil)
5922 (throw 'return js2-EOL))
5923 ((not (js2-js-space-p c))
5924 (if (/= c ?-) ; in case end of HTML comment
5925 (setq js2-ts-dirty-line t))
5926 (setq continue nil))))
5927 ;; Assume the token will be 1 char - fixed up below.
5928 (js2-ts-set-char-token-bounds token)
5929 (when (eq c ?@)
5930 (throw 'return js2-XMLATTR))
5931 ;; identifier/keyword/instanceof?
5932 ;; watch out for starting with a <backslash>
5933 (cond
5934 ((eq c ?\\)
5935 (setq c (js2-get-char))
5936 (if (eq c ?u)
5937 (setq identifier-start t
5938 is-unicode-escape-start t
5939 js2-ts-string-buffer nil)
5940 (setq identifier-start nil)
5941 (js2-unget-char)
5942 (setq c ?\\)))
5943 (t
5944 (when (setq identifier-start (js2-identifier-start-p c))
5945 (setq js2-ts-string-buffer nil)
5946 (js2-add-to-string c))))
5947 (when identifier-start
5948 (setq contains-escape is-unicode-escape-start)
5949 (catch 'break
5950 (while t
5951 (if is-unicode-escape-start
5952 ;; strictly speaking we should probably push-back
5953 ;; all the bad characters if the <backslash>uXXXX
5954 ;; sequence is malformed. But since there isn't a
5955 ;; correct context(is there?) for a bad Unicode
5956 ;; escape sequence in an identifier, we can report
5957 ;; an error here.
5958 (progn
5959 (setq escape-val 0)
5960 (dotimes (_ 4)
5961 (setq c (js2-get-char)
5962 escape-val (js2-x-digit-to-int c escape-val))
5963 ;; Next check takes care of c < 0 and bad escape
5964 (if (cl-minusp escape-val)
5965 (throw 'break nil)))
5966 (if (cl-minusp escape-val)
5967 (js2-report-scan-error "msg.invalid.escape" t))
5968 (js2-add-to-string escape-val)
5969 (setq is-unicode-escape-start nil))
5970 (setq c (js2-get-char))
5971 (cond
5972 ((eq c ?\\)
5973 (setq c (js2-get-char))
5974 (if (eq c ?u)
5975 (setq is-unicode-escape-start t
5976 contains-escape t)
5977 (js2-report-scan-error "msg.illegal.character" t)))
5978 (t
5979 (if (or (eq c js2-EOF_CHAR)
5980 (not (js2-identifier-part-p c)))
5981 (throw 'break nil))
5982 (js2-add-to-string c))))))
5983 (js2-unget-char)
5984 (setf str (js2-collect-string js2-ts-string-buffer)
5985 (js2-token-end token) js2-ts-cursor)
5986 ;; FIXME: Invalid in ES5 and ES6, see
5987 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5988 ;; Probably should just drop this conditional.
5989 (unless contains-escape
5990 ;; OPT we shouldn't have to make a string (object!) to
5991 ;; check if it's a keyword.
5992 ;; Return the corresponding token if it's a keyword
5993 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5994 (setq result (js2-string-to-keyword str)))
5995 (if (and (< js2-language-version 170)
5996 (memq result '(js2-LET js2-YIELD)))
5997 ;; LET and YIELD are tokens only in 1.7 and later
5998 (setq result 'js2-NAME))
5999 (when (eq result 'js2-RESERVED)
6000 (setf (js2-token-string token) str))
6001 (throw 'return (js2-tt-code result))))
6002 ;; If we want to intern these as Rhino does, just use (intern str)
6003 (setf (js2-token-string token) str)
6004 (throw 'return js2-NAME)) ; end identifier/kwd check
6005 ;; is it a number?
6006 (when (or (js2-digit-p c)
6007 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6008 (setq js2-ts-string-buffer nil
6009 base 10)
6010 (when (eq c ?0)
6011 (setq c (js2-get-char))
6012 (cond
6013 ((or (eq c ?x) (eq c ?X))
6014 (setq base 16)
6015 (setq c (js2-get-char)))
6016 ((and (or (eq c ?b) (eq c ?B))
6017 (>= js2-language-version 200))
6018 (setq base 2)
6019 (setq c (js2-get-char)))
6020 ((and (or (eq c ?o) (eq c ?O))
6021 (>= js2-language-version 200))
6022 (setq base 8)
6023 (setq c (js2-get-char)))
6024 ((js2-digit-p c)
6025 (setq base 'maybe-8))
6026 (t
6027 (js2-add-to-string ?0))))
6028 (cond
6029 ((eq base 16)
6030 (if (> 0 (js2-x-digit-to-int c 0))
6031 (js2-report-scan-error "msg.missing.hex.digits")
6032 (while (<= 0 (js2-x-digit-to-int c 0))
6033 (js2-add-to-string c)
6034 (setq c (js2-get-char)))))
6035 ((eq base 2)
6036 (if (not (memq c '(?0 ?1)))
6037 (js2-report-scan-error "msg.missing.binary.digits")
6038 (while (memq c '(?0 ?1))
6039 (js2-add-to-string c)
6040 (setq c (js2-get-char)))))
6041 ((eq base 8)
6042 (if (or (> ?0 c) (< ?7 c))
6043 (js2-report-scan-error "msg.missing.octal.digits")
6044 (while (and (<= ?0 c) (>= ?7 c))
6045 (js2-add-to-string c)
6046 (setq c (js2-get-char)))))
6047 (t
6048 (while (and (<= ?0 c) (<= c ?9))
6049 ;; We permit 08 and 09 as decimal numbers, which
6050 ;; makes our behavior a superset of the ECMA
6051 ;; numeric grammar. We might not always be so
6052 ;; permissive, so we warn about it.
6053 (when (and (eq base 'maybe-8) (>= c ?8))
6054 (js2-report-warning "msg.bad.octal.literal"
6055 (if (eq c ?8) "8" "9"))
6056 (setq base 10))
6057 (js2-add-to-string c)
6058 (setq c (js2-get-char)))
6059 (when (eq base 'maybe-8)
6060 (setq base 8))))
6061 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6062 (when (eq c ?.)
6063 (cl-loop do
6064 (js2-add-to-string c)
6065 (setq c (js2-get-char))
6066 while (js2-digit-p c)))
6067 (when (memq c '(?e ?E))
6068 (js2-add-to-string c)
6069 (setq c (js2-get-char))
6070 (when (memq c '(?+ ?-))
6071 (js2-add-to-string c)
6072 (setq c (js2-get-char)))
6073 (unless (js2-digit-p c)
6074 (js2-report-scan-error "msg.missing.exponent" t))
6075 (cl-loop do
6076 (js2-add-to-string c)
6077 (setq c (js2-get-char))
6078 while (js2-digit-p c))))
6079 (js2-unget-char)
6080 (let ((str (js2-set-string-from-buffer token)))
6081 (setf (js2-token-number token)
6082 (js2-string-to-number str base)))
6083 (throw 'return js2-NUMBER))
6084 ;; is it a string?
6085 (when (or (memq c '(?\" ?\'))
6086 (and (>= js2-language-version 200)
6087 (= c ?`)))
6088 (throw 'return
6089 (js2-get-string-or-template-token c token)))
6090 (js2-ts-return token
6091 (cl-case c
6092 (?\;
6093 (throw 'return js2-SEMI))
6094 (?\[
6095 (throw 'return js2-LB))
6096 (?\]
6097 (throw 'return js2-RB))
6098 (?{
6099 (throw 'return js2-LC))
6100 (?}
6101 (throw 'return js2-RC))
6102 (?\(
6103 (throw 'return js2-LP))
6104 (?\)
6105 (throw 'return js2-RP))
6106 (?,
6107 (throw 'return js2-COMMA))
6108 (??
6109 (throw 'return js2-HOOK))
6110 (?:
6111 (if (js2-match-char ?:)
6112 js2-COLONCOLON
6113 (throw 'return js2-COLON)))
6114 (?.
6115 (if (js2-match-char ?.)
6116 (if (js2-match-char ?.)
6117 js2-TRIPLEDOT js2-DOTDOT)
6118 (if (js2-match-char ?\()
6119 js2-DOTQUERY
6120 (throw 'return js2-DOT))))
6121 (?|
6122 (if (js2-match-char ?|)
6123 (throw 'return js2-OR)
6124 (if (js2-match-char ?=)
6125 js2-ASSIGN_BITOR
6126 (throw 'return js2-BITOR))))
6127 (?^
6128 (if (js2-match-char ?=)
6129 js2-ASSIGN_BITOR
6130 (throw 'return js2-BITXOR)))
6131 (?&
6132 (if (js2-match-char ?&)
6133 (throw 'return js2-AND)
6134 (if (js2-match-char ?=)
6135 js2-ASSIGN_BITAND
6136 (throw 'return js2-BITAND))))
6137 (?=
6138 (if (js2-match-char ?=)
6139 (if (js2-match-char ?=)
6140 js2-SHEQ
6141 (throw 'return js2-EQ))
6142 (if (js2-match-char ?>)
6143 (js2-ts-return token js2-ARROW)
6144 (throw 'return js2-ASSIGN))))
6145 (?!
6146 (if (js2-match-char ?=)
6147 (if (js2-match-char ?=)
6148 js2-SHNE
6149 js2-NE)
6150 (throw 'return js2-NOT)))
6151 (?<
6152 ;; NB:treat HTML begin-comment as comment-till-eol
6153 (when (js2-match-char ?!)
6154 (when (js2-match-char ?-)
6155 (when (js2-match-char ?-)
6156 (js2-skip-line)
6157 (setf (js2-token-comment-type (js2-current-token)) 'html)
6158 (throw 'return js2-COMMENT)))
6159 (js2-unget-char))
6160 (if (js2-match-char ?<)
6161 (if (js2-match-char ?=)
6162 js2-ASSIGN_LSH
6163 js2-LSH)
6164 (if (js2-match-char ?=)
6165 js2-LE
6166 (throw 'return js2-LT))))
6167 (?>
6168 (if (js2-match-char ?>)
6169 (if (js2-match-char ?>)
6170 (if (js2-match-char ?=)
6171 js2-ASSIGN_URSH
6172 js2-URSH)
6173 (if (js2-match-char ?=)
6174 js2-ASSIGN_RSH
6175 js2-RSH))
6176 (if (js2-match-char ?=)
6177 js2-GE
6178 (throw 'return js2-GT))))
6179 (?*
6180 (if (js2-match-char ?=)
6181 js2-ASSIGN_MUL
6182 (throw 'return js2-MUL)))
6183 (?/
6184 ;; is it a // comment?
6185 (when (js2-match-char ?/)
6186 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6187 (js2-skip-line)
6188 (setf (js2-token-comment-type token) 'line)
6189 ;; include newline so highlighting goes to end of
6190 ;; window, if there actually is a newline; if we
6191 ;; hit eof, then implicitly there isn't
6192 (unless js2-ts-hit-eof
6193 (cl-incf (js2-token-end token)))
6194 (throw 'return js2-COMMENT))
6195 ;; is it a /* comment?
6196 (when (js2-match-char ?*)
6197 (setf look-for-slash nil
6198 (js2-token-beg token) (- js2-ts-cursor 2)
6199 (js2-token-comment-type token)
6200 (if (js2-match-char ?*)
6201 (progn
6202 (setq look-for-slash t)
6203 'jsdoc)
6204 'block))
6205 (while t
6206 (setq c (js2-get-char))
6207 (cond
6208 ((eq c js2-EOF_CHAR)
6209 (setf (js2-token-end token) (1- js2-ts-cursor))
6210 (js2-report-error "msg.unterminated.comment")
6211 (throw 'return js2-COMMENT))
6212 ((eq c ?*)
6213 (setq look-for-slash t))
6214 ((eq c ?/)
6215 (if look-for-slash
6216 (js2-ts-return token js2-COMMENT)))
6217 (t
6218 (setf look-for-slash nil
6219 (js2-token-end token) js2-ts-cursor)))))
6220 (if (js2-match-char ?=)
6221 js2-ASSIGN_DIV
6222 (throw 'return js2-DIV)))
6223 (?#
6224 (when js2-skip-preprocessor-directives
6225 (js2-skip-line)
6226 (setf (js2-token-comment-type token) 'preprocessor
6227 (js2-token-end token) js2-ts-cursor)
6228 (throw 'return js2-COMMENT))
6229 (throw 'return js2-ERROR))
6230 (?%
6231 (if (js2-match-char ?=)
6232 js2-ASSIGN_MOD
6233 (throw 'return js2-MOD)))
6234 (?~
6235 (throw 'return js2-BITNOT))
6236 (?+
6237 (if (js2-match-char ?=)
6238 js2-ASSIGN_ADD
6239 (if (js2-match-char ?+)
6240 js2-INC
6241 (throw 'return js2-ADD))))
6242 (?-
6243 (cond
6244 ((js2-match-char ?=)
6245 (setq c js2-ASSIGN_SUB))
6246 ((js2-match-char ?-)
6247 (unless js2-ts-dirty-line
6248 ;; treat HTML end-comment after possible whitespace
6249 ;; after line start as comment-until-eol
6250 (when (js2-match-char ?>)
6251 (js2-skip-line)
6252 (setf (js2-token-comment-type (js2-current-token)) 'html)
6253 (throw 'return js2-COMMENT)))
6254 (setq c js2-DEC))
6255 (t
6256 (setq c js2-SUB)))
6257 (setq js2-ts-dirty-line t)
6258 c)
6259 (otherwise
6260 (js2-report-scan-error "msg.illegal.character")))))))
6261 (setf (js2-token-type token) tt)
6262 token))
6263
6264 (defun js2-get-string-or-template-token (quote-char token)
6265 ;; We attempt to accumulate a string the fast way, by
6266 ;; building it directly out of the reader. But if there
6267 ;; are any escaped characters in the string, we revert to
6268 ;; building it out of a string buffer.
6269 (let ((c (js2-get-char))
6270 js2-ts-string-buffer
6271 nc c1 val escape-val)
6272 (catch 'break
6273 (while (/= c quote-char)
6274 (catch 'continue
6275 (when (eq c js2-EOF_CHAR)
6276 (js2-unget-char)
6277 (js2-report-error "msg.unterminated.string.lit")
6278 (throw 'break nil))
6279 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6280 (js2-unget-char)
6281 (js2-report-error "msg.unterminated.string.lit")
6282 (throw 'break nil))
6283 (when (eq c ?\\)
6284 ;; We've hit an escaped character
6285 (setq c (js2-get-char))
6286 (cl-case c
6287 (?b (setq c ?\b))
6288 (?f (setq c ?\f))
6289 (?n (setq c ?\n))
6290 (?r (setq c ?\r))
6291 (?t (setq c ?\t))
6292 (?v (setq c ?\v))
6293 (?u
6294 (setq c1 (js2-read-unicode-escape))
6295 (if js2-parse-ide-mode
6296 (if c1
6297 (progn
6298 ;; just copy the string in IDE-mode
6299 (js2-add-to-string ?\\)
6300 (js2-add-to-string ?u)
6301 (dotimes (_ 3)
6302 (js2-add-to-string (js2-get-char)))
6303 (setq c (js2-get-char))) ; added at end of loop
6304 ;; flag it as an invalid escape
6305 (js2-report-warning "msg.invalid.escape"
6306 nil (- js2-ts-cursor 2) 6))
6307 ;; Get 4 hex digits; if the u escape is not
6308 ;; followed by 4 hex digits, use 'u' + the
6309 ;; literal character sequence that follows.
6310 (js2-add-to-string ?u)
6311 (setq escape-val 0)
6312 (dotimes (_ 4)
6313 (setq c (js2-get-char)
6314 escape-val (js2-x-digit-to-int c escape-val))
6315 (if (cl-minusp escape-val)
6316 (throw 'continue nil))
6317 (js2-add-to-string c))
6318 ;; prepare for replace of stored 'u' sequence by escape value
6319 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6320 c escape-val)))
6321 (?x
6322 ;; Get 2 hex digits, defaulting to 'x'+literal
6323 ;; sequence, as above.
6324 (setq c (js2-get-char)
6325 escape-val (js2-x-digit-to-int c 0))
6326 (if (cl-minusp escape-val)
6327 (progn
6328 (js2-add-to-string ?x)
6329 (throw 'continue nil))
6330 (setq c1 c
6331 c (js2-get-char)
6332 escape-val (js2-x-digit-to-int c escape-val))
6333 (if (cl-minusp escape-val)
6334 (progn
6335 (js2-add-to-string ?x)
6336 (js2-add-to-string c1)
6337 (throw 'continue nil))
6338 ;; got 2 hex digits
6339 (setq c escape-val))))
6340 (?\n
6341 ;; Remove line terminator after escape to follow
6342 ;; SpiderMonkey and C/C++
6343 (setq c (js2-get-char))
6344 (throw 'continue nil))
6345 (t
6346 (when (and (<= ?0 c) (< c ?8))
6347 (setq val (- c ?0)
6348 c (js2-get-char))
6349 (when (and (<= ?0 c) (< c ?8))
6350 (setq val (- (+ (* 8 val) c) ?0)
6351 c (js2-get-char))
6352 (when (and (<= ?0 c)
6353 (< c ?8)
6354 (< val #o37))
6355 ;; c is 3rd char of octal sequence only
6356 ;; if the resulting val <= 0377
6357 (setq val (- (+ (* 8 val) c) ?0)
6358 c (js2-get-char))))
6359 (js2-unget-char)
6360 (setq c val)))))
6361 (when (and (eq quote-char ?`) (eq c ?$))
6362 (when (eq (setq nc (js2-get-char)) ?\{)
6363 (throw 'break nil))
6364 (js2-unget-char))
6365 (js2-add-to-string c)
6366 (setq c (js2-get-char)))))
6367 (js2-set-string-from-buffer token)
6368 (if (not (eq quote-char ?`))
6369 js2-STRING
6370 (if (and (eq c ?$) (eq nc ?\{))
6371 js2-TEMPLATE_HEAD
6372 js2-NO_SUBS_TEMPLATE))))
6373
6374 (defun js2-read-regexp (start-tt)
6375 "Called by parser when it gets / or /= in literal context."
6376 (let (c err
6377 in-class ; inside a '[' .. ']' character-class
6378 flags
6379 (continue t)
6380 (token (js2-new-token 0)))
6381 (setq js2-ts-string-buffer nil)
6382 (if (eq start-tt js2-ASSIGN_DIV)
6383 ;; mis-scanned /=
6384 (js2-add-to-string ?=)
6385 (if (not (eq start-tt js2-DIV))
6386 (error "failed assertion")))
6387 (while (and (not err)
6388 (or (/= (setq c (js2-get-char)) ?/)
6389 in-class))
6390 (cond
6391 ((or (= c ?\n)
6392 (= c js2-EOF_CHAR))
6393 (setf (js2-token-end token) (1- js2-ts-cursor)
6394 err t
6395 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6396 (js2-report-error "msg.unterminated.re.lit"))
6397 (t (cond
6398 ((= c ?\\)
6399 (js2-add-to-string c)
6400 (setq c (js2-get-char)))
6401 ((= c ?\[)
6402 (setq in-class t))
6403 ((= c ?\])
6404 (setq in-class nil)))
6405 (js2-add-to-string c))))
6406 (unless err
6407 (while continue
6408 (cond
6409 ((js2-match-char ?g)
6410 (push ?g flags))
6411 ((js2-match-char ?i)
6412 (push ?i flags))
6413 ((js2-match-char ?m)
6414 (push ?m flags))
6415 ((and (js2-match-char ?u)
6416 (>= js2-language-version 200))
6417 (push ?u flags))
6418 ((and (js2-match-char ?y)
6419 (>= js2-language-version 200))
6420 (push ?y flags))
6421 (t
6422 (setq continue nil))))
6423 (if (js2-alpha-p (js2-peek-char))
6424 (js2-report-scan-error "msg.invalid.re.flag" t
6425 js2-ts-cursor 1))
6426 (js2-set-string-from-buffer token))
6427 (js2-collect-string flags)))
6428
6429 (defun js2-get-first-xml-token ()
6430 (setq js2-ts-xml-open-tags-count 0
6431 js2-ts-is-xml-attribute nil
6432 js2-ts-xml-is-tag-content nil)
6433 (js2-unget-char)
6434 (js2-get-next-xml-token))
6435
6436 (defun js2-xml-discard-string (token)
6437 "Throw away the string in progress and flag an XML parse error."
6438 (setf js2-ts-string-buffer nil
6439 (js2-token-string token) nil)
6440 (js2-report-scan-error "msg.XML.bad.form" t))
6441
6442 (defun js2-get-next-xml-token ()
6443 (setq js2-ts-string-buffer nil) ; for recording the XML
6444 (let ((token (js2-new-token 0))
6445 c result)
6446 (setq result
6447 (catch 'return
6448 (while t
6449 (setq c (js2-get-char))
6450 (cond
6451 ((= c js2-EOF_CHAR)
6452 (throw 'return js2-ERROR))
6453 (js2-ts-xml-is-tag-content
6454 (cl-case c
6455 (?>
6456 (js2-add-to-string c)
6457 (setq js2-ts-xml-is-tag-content nil
6458 js2-ts-is-xml-attribute nil))
6459 (?/
6460 (js2-add-to-string c)
6461 (when (eq ?> (js2-peek-char))
6462 (setq c (js2-get-char))
6463 (js2-add-to-string c)
6464 (setq js2-ts-xml-is-tag-content nil)
6465 (cl-decf js2-ts-xml-open-tags-count)))
6466 (?{
6467 (js2-unget-char)
6468 (js2-set-string-from-buffer token)
6469 (throw 'return js2-XML))
6470 ((?\' ?\")
6471 (js2-add-to-string c)
6472 (unless (js2-read-quoted-string c token)
6473 (throw 'return js2-ERROR)))
6474 (?=
6475 (js2-add-to-string c)
6476 (setq js2-ts-is-xml-attribute t))
6477 ((? ?\t ?\r ?\n)
6478 (js2-add-to-string c))
6479 (t
6480 (js2-add-to-string c)
6481 (setq js2-ts-is-xml-attribute nil)))
6482 (when (and (not js2-ts-xml-is-tag-content)
6483 (zerop js2-ts-xml-open-tags-count))
6484 (js2-set-string-from-buffer token)
6485 (throw 'return js2-XMLEND)))
6486 (t
6487 ;; else not tag content
6488 (cl-case c
6489 (?<
6490 (js2-add-to-string c)
6491 (setq c (js2-peek-char))
6492 (cl-case c
6493 (?!
6494 (setq c (js2-get-char)) ;; skip !
6495 (js2-add-to-string c)
6496 (setq c (js2-peek-char))
6497 (cl-case c
6498 (?-
6499 (setq c (js2-get-char)) ;; skip -
6500 (js2-add-to-string c)
6501 (if (eq c ?-)
6502 (progn
6503 (js2-add-to-string c)
6504 (unless (js2-read-xml-comment token)
6505 (throw 'return js2-ERROR)))
6506 (js2-xml-discard-string token)
6507 (throw 'return js2-ERROR)))
6508 (?\[
6509 (setq c (js2-get-char)) ;; skip [
6510 (js2-add-to-string c)
6511 (if (and (= (js2-get-char) ?C)
6512 (= (js2-get-char) ?D)
6513 (= (js2-get-char) ?A)
6514 (= (js2-get-char) ?T)
6515 (= (js2-get-char) ?A)
6516 (= (js2-get-char) ?\[))
6517 (progn
6518 (js2-add-to-string ?C)
6519 (js2-add-to-string ?D)
6520 (js2-add-to-string ?A)
6521 (js2-add-to-string ?T)
6522 (js2-add-to-string ?A)
6523 (js2-add-to-string ?\[)
6524 (unless (js2-read-cdata token)
6525 (throw 'return js2-ERROR)))
6526 (js2-xml-discard-string token)
6527 (throw 'return js2-ERROR)))
6528 (t
6529 (unless (js2-read-entity token)
6530 (throw 'return js2-ERROR))))
6531 ;; Allow bare CDATA section, e.g.:
6532 ;; let xml = <![CDATA[ foo bar baz ]]>;
6533 (when (zerop js2-ts-xml-open-tags-count)
6534 (throw 'return js2-XMLEND)))
6535 (??
6536 (setq c (js2-get-char)) ;; skip ?
6537 (js2-add-to-string c)
6538 (unless (js2-read-PI token)
6539 (throw 'return js2-ERROR)))
6540 (?/
6541 ;; end tag
6542 (setq c (js2-get-char)) ;; skip /
6543 (js2-add-to-string c)
6544 (when (zerop js2-ts-xml-open-tags-count)
6545 (js2-xml-discard-string token)
6546 (throw 'return js2-ERROR))
6547 (setq js2-ts-xml-is-tag-content t)
6548 (cl-decf js2-ts-xml-open-tags-count))
6549 (t
6550 ;; start tag
6551 (setq js2-ts-xml-is-tag-content t)
6552 (cl-incf js2-ts-xml-open-tags-count))))
6553 (?{
6554 (js2-unget-char)
6555 (js2-set-string-from-buffer token)
6556 (throw 'return js2-XML))
6557 (t
6558 (js2-add-to-string c))))))))
6559 (setf (js2-token-end token) js2-ts-cursor)
6560 (setf (js2-token-type token) result)
6561 result))
6562
6563 (defun js2-read-quoted-string (quote token)
6564 (let (c)
6565 (catch 'return
6566 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6567 (js2-add-to-string c)
6568 (if (eq c quote)
6569 (throw 'return t)))
6570 (js2-xml-discard-string token) ;; throw away string in progress
6571 nil)))
6572
6573 (defun js2-read-xml-comment (token)
6574 (let ((c (js2-get-char)))
6575 (catch 'return
6576 (while (/= c js2-EOF_CHAR)
6577 (catch 'continue
6578 (js2-add-to-string c)
6579 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6580 (setq c (js2-get-char))
6581 (js2-add-to-string c)
6582 (if (eq (js2-peek-char) ?>)
6583 (progn
6584 (setq c (js2-get-char)) ;; skip >
6585 (js2-add-to-string c)
6586 (throw 'return t))
6587 (throw 'continue nil)))
6588 (setq c (js2-get-char))))
6589 (js2-xml-discard-string token)
6590 nil)))
6591
6592 (defun js2-read-cdata (token)
6593 (let ((c (js2-get-char)))
6594 (catch 'return
6595 (while (/= c js2-EOF_CHAR)
6596 (catch 'continue
6597 (js2-add-to-string c)
6598 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6599 (setq c (js2-get-char))
6600 (js2-add-to-string c)
6601 (if (eq (js2-peek-char) ?>)
6602 (progn
6603 (setq c (js2-get-char)) ;; Skip >
6604 (js2-add-to-string c)
6605 (throw 'return t))
6606 (throw 'continue nil)))
6607 (setq c (js2-get-char))))
6608 (js2-xml-discard-string token)
6609 nil)))
6610
6611 (defun js2-read-entity (token)
6612 (let ((decl-tags 1)
6613 c)
6614 (catch 'return
6615 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6616 (js2-add-to-string c)
6617 (cl-case c
6618 (?<
6619 (cl-incf decl-tags))
6620 (?>
6621 (cl-decf decl-tags)
6622 (if (zerop decl-tags)
6623 (throw 'return t)))))
6624 (js2-xml-discard-string token)
6625 nil)))
6626
6627 (defun js2-read-PI (token)
6628 "Scan an XML processing instruction."
6629 (let (c)
6630 (catch 'return
6631 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6632 (js2-add-to-string c)
6633 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6634 (setq c (js2-get-char)) ;; Skip >
6635 (js2-add-to-string c)
6636 (throw 'return t)))
6637 (js2-xml-discard-string token)
6638 nil)))
6639
6640 ;;; Highlighting
6641
6642 (defun js2-set-face (beg end face &optional record)
6643 "Fontify a region. If RECORD is non-nil, record for later."
6644 (when (cl-plusp js2-highlight-level)
6645 (setq beg (min (point-max) beg)
6646 beg (max (point-min) beg)
6647 end (min (point-max) end)
6648 end (max (point-min) end))
6649 (if record
6650 (push (list beg end face) js2-mode-fontifications)
6651 (put-text-property beg end 'font-lock-face face))))
6652
6653 (defsubst js2-clear-face (beg end)
6654 (remove-text-properties beg end '(font-lock-face nil
6655 help-echo nil
6656 point-entered nil
6657 cursor-sensor-functions nil
6658 c-in-sws nil)))
6659
6660 (defconst js2-ecma-global-props
6661 (concat "^"
6662 (regexp-opt
6663 '("Infinity" "NaN" "undefined" "arguments") t)
6664 "$")
6665 "Value properties of the Ecma-262 Global Object.
6666 Shown at or above `js2-highlight-level' 2.")
6667
6668 ;; might want to add the name "arguments" to this list?
6669 (defconst js2-ecma-object-props
6670 (concat "^"
6671 (regexp-opt
6672 '("prototype" "__proto__" "__parent__") t)
6673 "$")
6674 "Value properties of the Ecma-262 Object constructor.
6675 Shown at or above `js2-highlight-level' 2.")
6676
6677 (defconst js2-ecma-global-funcs
6678 (concat
6679 "^"
6680 (regexp-opt
6681 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6682 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6683 "$")
6684 "Function properties of the Ecma-262 Global object.
6685 Shown at or above `js2-highlight-level' 2.")
6686
6687 (defconst js2-ecma-number-props
6688 (concat "^"
6689 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6690 "NEGATIVE_INFINITY"
6691 "POSITIVE_INFINITY") t)
6692 "$")
6693 "Properties of the Ecma-262 Number constructor.
6694 Shown at or above `js2-highlight-level' 2.")
6695
6696 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6697 "Properties of the Ecma-262 Date constructor.
6698 Shown at or above `js2-highlight-level' 2.")
6699
6700 (defconst js2-ecma-math-props
6701 (concat "^"
6702 (regexp-opt
6703 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6704 t)
6705 "$")
6706 "Properties of the Ecma-262 Math object.
6707 Shown at or above `js2-highlight-level' 2.")
6708
6709 (defconst js2-ecma-math-funcs
6710 (concat "^"
6711 (regexp-opt
6712 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6713 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6714 "$")
6715 "Function properties of the Ecma-262 Math object.
6716 Shown at or above `js2-highlight-level' 2.")
6717
6718 (defconst js2-ecma-function-props
6719 (concat
6720 "^"
6721 (regexp-opt
6722 '(;; properties of the Object prototype object
6723 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6724 "toLocaleString" "toString" "valueOf"
6725 ;; properties of the Function prototype object
6726 "apply" "call"
6727 ;; properties of the Array prototype object
6728 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6729 "splice" "unshift"
6730 ;; properties of the String prototype object
6731 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6732 "localeCompare" "match" "replace" "search" "split" "substring"
6733 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6734 "toUpperCase"
6735 ;; properties of the Number prototype object
6736 "toExponential" "toFixed" "toPrecision"
6737 ;; properties of the Date prototype object
6738 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6739 "getMinutes" "getMonth" "getSeconds" "getTime"
6740 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6741 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6742 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6743 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6744 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6745 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6746 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6747 "toTimeString" "toUTCString"
6748 ;; properties of the RegExp prototype object
6749 "exec" "test"
6750 ;; properties of the JSON prototype object
6751 "parse" "stringify"
6752 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6753 "toSource" "__defineGetter__" "__defineSetter__"
6754 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6755 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6756 t)
6757 "$")
6758 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6759 Shown at or above `js2-highlight-level' 3.")
6760
6761 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6762 (let ((target-name (and target
6763 (js2-name-node-p target)
6764 (js2-name-node-name target)))
6765 (prop-name (if prop (js2-name-node-name prop)))
6766 (level2 (>= js2-highlight-level 2))
6767 (level3 (>= js2-highlight-level 3)))
6768 (when level2
6769 (let ((face
6770 (if call-p
6771 (cond
6772 ((and target prop)
6773 (cond
6774 ((and level3 (string-match js2-ecma-function-props prop-name))
6775 'font-lock-builtin-face)
6776 ((and target-name prop)
6777 (cond
6778 ((string= target-name "Date")
6779 (if (string-match js2-ecma-date-props prop-name)
6780 'font-lock-builtin-face))
6781 ((string= target-name "Math")
6782 (if (string-match js2-ecma-math-funcs prop-name)
6783 'font-lock-builtin-face))))))
6784 (prop
6785 (if (string-match js2-ecma-global-funcs prop-name)
6786 'font-lock-builtin-face)))
6787 (cond
6788 ((and target prop)
6789 (cond
6790 ((string= target-name "Number")
6791 (if (string-match js2-ecma-number-props prop-name)
6792 'font-lock-constant-face))
6793 ((string= target-name "Math")
6794 (if (string-match js2-ecma-math-props prop-name)
6795 'font-lock-constant-face))))
6796 (prop
6797 (if (string-match js2-ecma-object-props prop-name)
6798 'font-lock-constant-face))))))
6799 (when face
6800 (let ((pos (+ (js2-node-pos parent) ; absolute
6801 (js2-node-pos prop)))) ; relative
6802 (js2-set-face pos
6803 (+ pos (js2-node-len prop))
6804 face 'record)))))))
6805
6806 (defun js2-parse-highlight-member-expr-node (node)
6807 "Perform syntax highlighting of EcmaScript built-in properties.
6808 The variable `js2-highlight-level' governs this highlighting."
6809 (let (face target prop name pos end parent call-p callee)
6810 (cond
6811 ;; case 1: simple name, e.g. foo
6812 ((js2-name-node-p node)
6813 (setq name (js2-name-node-name node))
6814 ;; possible for name to be nil in rare cases - saw it when
6815 ;; running js2-mode on an elisp buffer. Might as well try to
6816 ;; make it so js2-mode never barfs.
6817 (when name
6818 (setq face (if (string-match js2-ecma-global-props name)
6819 'font-lock-constant-face))
6820 (when face
6821 (setq pos (js2-node-pos node)
6822 end (+ pos (js2-node-len node)))
6823 (js2-set-face pos end face 'record))))
6824 ;; case 2: property access or function call
6825 ((or (js2-prop-get-node-p node)
6826 ;; highlight function call if expr is a prop-get node
6827 ;; or a plain name (i.e. unqualified function call)
6828 (and (setq call-p (js2-call-node-p node))
6829 (setq callee (js2-call-node-target node)) ; separate setq!
6830 (or (js2-prop-get-node-p callee)
6831 (js2-name-node-p callee))))
6832 (setq parent node
6833 node (if call-p callee node))
6834 (if (and call-p (js2-name-node-p callee))
6835 (setq prop callee)
6836 (setq target (js2-prop-get-node-left node)
6837 prop (js2-prop-get-node-right node)))
6838 (cond
6839 ((js2-name-node-p prop)
6840 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6841 (js2-parse-highlight-prop-get parent target prop call-p))
6842 ((js2-name-node-p target)
6843 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6844 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6845
6846 (defun js2-parse-highlight-member-expr-fn-name (expr)
6847 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6848 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6849 We currently only handle the case where the last component is a prop-get
6850 of a simple name. Called before EXPR has a parent node."
6851 (let (pos
6852 (name (and (js2-prop-get-node-p expr)
6853 (js2-prop-get-node-right expr))))
6854 (when (js2-name-node-p name)
6855 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6856 (js2-node-pos name)))
6857 (+ pos (js2-node-len name))
6858 'font-lock-function-name-face
6859 'record))))
6860
6861 ;; source: http://jsdoc.sourceforge.net/
6862 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6863 ;; allows type specifications, and needs work before entering the wild.
6864
6865 (defconst js2-jsdoc-param-tag-regexp
6866 (concat "^\\s-*\\*+\\s-*\\(@"
6867 "\\(?:param\\|argument\\)"
6868 "\\)"
6869 "\\s-*\\({[^}]+}\\)?" ; optional type
6870 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6871 "\\>")
6872 "Matches jsdoc tags with optional type and optional param name.")
6873
6874 (defconst js2-jsdoc-typed-tag-regexp
6875 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6876 (regexp-opt
6877 '("enum"
6878 "extends"
6879 "field"
6880 "id"
6881 "implements"
6882 "lends"
6883 "mods"
6884 "requires"
6885 "return"
6886 "returns"
6887 "throw"
6888 "throws"))
6889 "\\)\\)\\s-*\\({[^}]+}\\)?")
6890 "Matches jsdoc tags with optional type.")
6891
6892 (defconst js2-jsdoc-arg-tag-regexp
6893 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6894 (regexp-opt
6895 '("alias"
6896 "augments"
6897 "borrows"
6898 "bug"
6899 "base"
6900 "config"
6901 "default"
6902 "define"
6903 "exception"
6904 "function"
6905 "member"
6906 "memberOf"
6907 "name"
6908 "namespace"
6909 "property"
6910 "since"
6911 "suppress"
6912 "this"
6913 "throws"
6914 "type"
6915 "version"))
6916 "\\)\\)\\s-+\\([^ \t]+\\)")
6917 "Matches jsdoc tags with a single argument.")
6918
6919 (defconst js2-jsdoc-empty-tag-regexp
6920 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6921 (regexp-opt
6922 '("addon"
6923 "author"
6924 "class"
6925 "const"
6926 "constant"
6927 "constructor"
6928 "constructs"
6929 "deprecated"
6930 "desc"
6931 "description"
6932 "event"
6933 "example"
6934 "exec"
6935 "export"
6936 "fileoverview"
6937 "final"
6938 "function"
6939 "hidden"
6940 "ignore"
6941 "implicitCast"
6942 "inheritDoc"
6943 "inner"
6944 "interface"
6945 "license"
6946 "noalias"
6947 "noshadow"
6948 "notypecheck"
6949 "override"
6950 "owner"
6951 "preserve"
6952 "preserveTry"
6953 "private"
6954 "protected"
6955 "public"
6956 "static"
6957 "supported"
6958 ))
6959 "\\)\\)\\s-*")
6960 "Matches empty jsdoc tags.")
6961
6962 (defconst js2-jsdoc-link-tag-regexp
6963 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6964 "Matches a jsdoc link or code tag.")
6965
6966 (defconst js2-jsdoc-see-tag-regexp
6967 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6968 "Matches a jsdoc @see tag.")
6969
6970 (defconst js2-jsdoc-html-tag-regexp
6971 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6972 "Matches a simple (no attributes) html start- or end-tag.")
6973
6974 (defun js2-jsdoc-highlight-helper ()
6975 (js2-set-face (match-beginning 1)
6976 (match-end 1)
6977 'js2-jsdoc-tag)
6978 (if (match-beginning 2)
6979 (if (save-excursion
6980 (goto-char (match-beginning 2))
6981 (= (char-after) ?{))
6982 (js2-set-face (1+ (match-beginning 2))
6983 (1- (match-end 2))
6984 'js2-jsdoc-type)
6985 (js2-set-face (match-beginning 2)
6986 (match-end 2)
6987 'js2-jsdoc-value)))
6988 (if (match-beginning 3)
6989 (js2-set-face (match-beginning 3)
6990 (match-end 3)
6991 'js2-jsdoc-value)))
6992
6993 (defun js2-highlight-jsdoc (ast)
6994 "Highlight doc comment tags."
6995 (let ((comments (js2-ast-root-comments ast))
6996 beg end)
6997 (save-excursion
6998 (dolist (node comments)
6999 (when (eq (js2-comment-node-format node) 'jsdoc)
7000 (setq beg (js2-node-abs-pos node)
7001 end (+ beg (js2-node-len node)))
7002 (save-restriction
7003 (narrow-to-region beg end)
7004 (dolist (re (list js2-jsdoc-param-tag-regexp
7005 js2-jsdoc-typed-tag-regexp
7006 js2-jsdoc-arg-tag-regexp
7007 js2-jsdoc-link-tag-regexp
7008 js2-jsdoc-see-tag-regexp
7009 js2-jsdoc-empty-tag-regexp))
7010 (goto-char beg)
7011 (while (re-search-forward re nil t)
7012 (js2-jsdoc-highlight-helper)))
7013 ;; simple highlighting for html tags
7014 (goto-char beg)
7015 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7016 (js2-set-face (match-beginning 1)
7017 (match-end 1)
7018 'js2-jsdoc-html-tag-delimiter)
7019 (js2-set-face (match-beginning 2)
7020 (match-end 2)
7021 'js2-jsdoc-html-tag-name)
7022 (js2-set-face (match-beginning 3)
7023 (match-end 3)
7024 'js2-jsdoc-html-tag-delimiter))))))))
7025
7026 (defun js2-highlight-assign-targets (_node left right)
7027 "Highlight function properties and external variables."
7028 (let (leftpos name)
7029 ;; highlight vars and props assigned function values
7030 (when (or (js2-function-node-p right)
7031 (js2-class-node-p right))
7032 (cond
7033 ;; var foo = function() {...}
7034 ((js2-name-node-p left)
7035 (setq name left))
7036 ;; foo.bar.baz = function() {...}
7037 ((and (js2-prop-get-node-p left)
7038 (js2-name-node-p (js2-prop-get-node-right left)))
7039 (setq name (js2-prop-get-node-right left))))
7040 (when name
7041 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7042 (+ leftpos (js2-node-len name))
7043 'font-lock-function-name-face
7044 'record)))))
7045
7046 (defun js2-record-name-node (node)
7047 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7048 later. NODE must be a name node."
7049 (let ((leftpos (js2-node-abs-pos node)))
7050 (push (list node js2-current-scope
7051 leftpos
7052 (+ leftpos (js2-node-len node)))
7053 js2-recorded-identifiers)))
7054
7055 (defun js2-highlight-undeclared-vars ()
7056 "After entire parse is finished, look for undeclared variable references.
7057 We have to wait until entire buffer is parsed, since JavaScript permits var
7058 decls to occur after they're used.
7059
7060 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7061 it is considered declared."
7062 (let (name)
7063 (dolist (entry js2-recorded-identifiers)
7064 (cl-destructuring-bind (name-node scope pos end) entry
7065 (setq name (js2-name-node-name name-node))
7066 (unless (or (member name js2-global-externs)
7067 (member name js2-default-externs)
7068 (member name js2-additional-externs)
7069 (js2-get-defining-scope scope name pos))
7070 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7071 'js2-external-variable))))
7072 (setq js2-recorded-identifiers nil)))
7073
7074 (defun js2-set-default-externs ()
7075 "Set the value of `js2-default-externs' based on the various
7076 `js2-include-?-externs' variables."
7077 (setq js2-default-externs
7078 (append js2-ecma-262-externs
7079 (if js2-include-browser-externs js2-browser-externs)
7080 (if (and js2-include-browser-externs
7081 (>= js2-language-version 200)) js2-harmony-externs)
7082 (if js2-include-rhino-externs js2-rhino-externs)
7083 (if js2-include-node-externs js2-node-externs)
7084 (if (or js2-include-browser-externs js2-include-node-externs)
7085 js2-typed-array-externs))))
7086
7087 (defun js2-apply-jslint-globals ()
7088 (setq js2-additional-externs
7089 (nconc (js2-get-jslint-globals)
7090 js2-additional-externs)))
7091
7092 (defun js2-get-jslint-globals ()
7093 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7094 when (and (eq 'block (js2-comment-node-format node))
7095 (save-excursion
7096 (goto-char (js2-node-abs-pos node))
7097 (looking-at "/\\*global ")))
7098 append (js2-get-jslint-globals-in
7099 (match-end 0)
7100 (js2-node-abs-end node))))
7101
7102 (defun js2-get-jslint-globals-in (beg end)
7103 (let (res)
7104 (save-excursion
7105 (goto-char beg)
7106 (while (re-search-forward js2-mode-identifier-re end t)
7107 (let ((match (match-string 0)))
7108 (unless (member match '("true" "false"))
7109 (push match res)))))
7110 (nreverse res)))
7111
7112 ;;; IMenu support
7113
7114 ;; We currently only support imenu, but eventually should support speedbar and
7115 ;; possibly other browsing mechanisms.
7116
7117 ;; The basic strategy is to identify function assignment targets of the form
7118 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7119 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7120 ;; for imenu after parsing is finished.
7121
7122 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7123 ;; JavaScript, and the general problem is undecidable. However, several forms
7124 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7125 ;; include:
7126
7127 ;; function foo() -- function declaration
7128 ;; foo = function() -- function expression assigned to variable
7129 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7130 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7131 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7132 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7133 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7134 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7135 ;; function foo() {function bar() {...}} -- nested function
7136 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7137
7138 ;; This list boils down to a few forms that can be combined recursively.
7139 ;; Top-level named function declarations include both the left-hand (name)
7140 ;; and the right-hand (function value) expressions needed to produce an imenu
7141 ;; entry. The other "right-hand" forms we need to look for are:
7142 ;; - functions declared as props/getters/setters in object literals
7143 ;; - nested named function declarations
7144 ;; The "left-hand" expressions that functions can be assigned to include:
7145 ;; - local/global variables
7146 ;; - nested property-get expressions like a.b.c.d
7147 ;; - element gets like foo[10] or foo['bar'] where the index
7148 ;; expression can be trivially converted to a property name. They
7149 ;; effectively then become property gets.
7150
7151 ;; All the different definition types are canonicalized into the form
7152 ;; foo.bar.baz = position-of-function-keyword
7153
7154 ;; We need to build a trie-like structure for imenu. As an example,
7155 ;; consider the following JavaScript code:
7156
7157 ;; a = function() {...} // function at position 5
7158 ;; b = function() {...} // function at position 25
7159 ;; foo = function() {...} // function at position 100
7160 ;; foo.bar = function() {...} // function at position 200
7161 ;; foo.bar.baz = function() {...} // function at position 300
7162 ;; foo.bar.zab = function() {...} // function at position 400
7163
7164 ;; During parsing we accumulate an entry for each definition in
7165 ;; the variable `js2-imenu-recorder', like so:
7166
7167 ;; '((fn a 5)
7168 ;; (fn b 25)
7169 ;; (fn foo 100)
7170 ;; (fn foo bar 200)
7171 ;; (fn foo bar baz 300)
7172 ;; (fn foo bar zab 400))
7173
7174 ;; Where 'fn' is the respective function node.
7175 ;; After parsing these entries are merged into this alist-trie:
7176
7177 ;; '((a . 1)
7178 ;; (b . 2)
7179 ;; (foo (<definition> . 3)
7180 ;; (bar (<definition> . 6)
7181 ;; (baz . 100)
7182 ;; (zab . 200))))
7183
7184 ;; Note the wacky need for a <definition> name. The token can be anything
7185 ;; that isn't a valid JavaScript identifier, because you might make foo
7186 ;; a function and then start setting properties on it that are also functions.
7187
7188 (defun js2-prop-node-name (node)
7189 "Return the name of a node that may be a property-get/property-name.
7190 If NODE is not a valid name-node, string-node or integral number-node,
7191 returns nil. Otherwise returns the string name/value of the node."
7192 (cond
7193 ((js2-name-node-p node)
7194 (js2-name-node-name node))
7195 ((js2-string-node-p node)
7196 (js2-string-node-value node))
7197 ((and (js2-number-node-p node)
7198 (string-match "^[0-9]+$" (js2-number-node-value node)))
7199 (js2-number-node-value node))
7200 ((eq (js2-node-type node) js2-THIS)
7201 "this")
7202 ((eq (js2-node-type node) js2-SUPER)
7203 "super")))
7204
7205 (defun js2-node-qname-component (node)
7206 "Return the name of this node, if it contributes to a qname.
7207 Returns nil if the node doesn't contribute."
7208 (copy-sequence
7209 (or (js2-prop-node-name node)
7210 (if (and (js2-function-node-p node)
7211 (js2-function-node-name node))
7212 (js2-name-node-name (js2-function-node-name node))))))
7213
7214 (defun js2-record-imenu-entry (fn-node qname pos)
7215 "Add an entry to `js2-imenu-recorder'.
7216 FN-NODE should be the current item's function node.
7217
7218 Associate FN-NODE with its QNAME for later lookup.
7219 This is used in postprocessing the chain list. For each chain, we find
7220 the parent function, look up its qname, then prepend a copy of it to the chain."
7221 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7222 (unless js2-imenu-function-map
7223 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7224 (puthash fn-node qname js2-imenu-function-map))
7225
7226 (defun js2-record-imenu-functions (node &optional var)
7227 "Record function definitions for imenu.
7228 NODE is a function node or an object literal.
7229 VAR, if non-nil, is the expression that NODE is being assigned to.
7230 When passed arguments of wrong type, does nothing."
7231 (when js2-parse-ide-mode
7232 (let ((fun-p (js2-function-node-p node))
7233 qname fname-node)
7234 (cond
7235 ;; non-anonymous function declaration?
7236 ((and fun-p
7237 (not var)
7238 (setq fname-node (js2-function-node-name node)))
7239 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7240 ;; for remaining forms, compute left-side tree branch first
7241 ((and var (setq qname (js2-compute-nested-prop-get var)))
7242 (cond
7243 ;; foo.bar.baz = function
7244 (fun-p
7245 (js2-record-imenu-entry node qname (js2-node-pos node)))
7246 ;; foo.bar.baz = object-literal
7247 ;; look for nested functions: {a: {b: function() {...} }}
7248 ((js2-object-node-p node)
7249 ;; Node position here is still absolute, since the parser
7250 ;; passes the assignment target and value expressions
7251 ;; to us before they are added as children of the assignment node.
7252 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7253
7254 (defun js2-compute-nested-prop-get (node)
7255 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7256 component nodes as a list. Otherwise return nil. Element-gets are treated
7257 as property-gets if the index expression is a string, or a positive integer."
7258 (let (left right head)
7259 (cond
7260 ((or (js2-name-node-p node)
7261 (js2-this-or-super-node-p node))
7262 (list node))
7263 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7264 ((js2-prop-get-node-p node) ; foo.bar
7265 (setq left (js2-prop-get-node-left node)
7266 right (js2-prop-get-node-right node))
7267 (if (setq head (js2-compute-nested-prop-get left))
7268 (nconc head (list right))))
7269 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7270 (setq left (js2-elem-get-node-target node)
7271 right (js2-elem-get-node-element node))
7272 (if (or (js2-string-node-p right) ; ['bar']
7273 (and (js2-number-node-p right) ; [10]
7274 (string-match "^[0-9]+$"
7275 (js2-number-node-value right))))
7276 (if (setq head (js2-compute-nested-prop-get left))
7277 (nconc head (list right))))))))
7278
7279 (defun js2-record-object-literal (node qname pos)
7280 "Recursively process an object literal looking for functions.
7281 NODE is an object literal that is the right-hand child of an assignment
7282 expression. QNAME is a list of nodes representing the assignment target,
7283 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7284 POS is the absolute position of the node.
7285 We do a depth-first traversal of NODE. For any functions we find,
7286 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7287 (let (right)
7288 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7289 (let ((left (js2-infix-node-left e))
7290 ;; Element positions are relative to the parent position.
7291 (pos (+ pos (js2-node-pos e))))
7292 (cond
7293 ;; foo: function() {...}
7294 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7295 (when (js2-prop-node-name left)
7296 ;; As a policy decision, we record the position of the property,
7297 ;; not the position of the `function' keyword, since the property
7298 ;; is effectively the name of the function.
7299 (js2-record-imenu-entry right (append qname (list left)) pos)))
7300 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7301 ((js2-object-node-p right)
7302 (js2-record-object-literal right
7303 (append qname (list (js2-infix-node-left e)))
7304 (+ pos (js2-node-pos right)))))))))
7305
7306 (defun js2-node-top-level-decl-p (node)
7307 "Return t if NODE's name is defined in the top-level scope.
7308 Also returns t if NODE's name is not defined in any scope, since it implies
7309 that it's an external variable, which must also be in the top-level scope."
7310 (let* ((name (js2-prop-node-name node))
7311 (this-scope (js2-node-get-enclosing-scope node))
7312 defining-scope)
7313 (cond
7314 ((js2-this-or-super-node-p node)
7315 nil)
7316 ((null this-scope)
7317 t)
7318 ((setq defining-scope (js2-get-defining-scope this-scope name))
7319 (js2-ast-root-p defining-scope))
7320 (t t))))
7321
7322 (defun js2-wrapper-function-p (node)
7323 "Return t if NODE is a function expression that's immediately invoked.
7324 NODE must be `js2-function-node'."
7325 (let ((parent (js2-node-parent node)))
7326 (or
7327 ;; function(){...}();
7328 (and (js2-call-node-p parent)
7329 (eq node (js2-call-node-target parent)))
7330 (and (js2-paren-node-p parent)
7331 ;; (function(){...})();
7332 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7333 ;; (function(){...}).call(this);
7334 (and (js2-prop-get-node-p parent)
7335 (member (js2-name-node-name (js2-prop-get-node-right parent))
7336 '("call" "apply"))
7337 (js2-call-node-p (js2-node-parent parent))))))))
7338
7339 (defun js2-browse-postprocess-chains ()
7340 "Modify function-declaration name chains after parsing finishes.
7341 Some of the information is only available after the parse tree is complete.
7342 For instance, processing a nested scope requires a parent function node."
7343 (let (result fn parent-qname p elem)
7344 (dolist (entry js2-imenu-recorder)
7345 ;; function node goes first
7346 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7347 ;; Examine head's defining scope:
7348 ;; Pre-processed chain, or top-level/external, keep as-is.
7349 (if (or (stringp head) (js2-node-top-level-decl-p head))
7350 (push chain result)
7351 (when (js2-this-or-super-node-p head)
7352 (setq chain (cdr chain))) ; discard this-node
7353 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7354 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7355 (when (eq parent-qname 'not-found)
7356 ;; anonymous function expressions are not recorded
7357 ;; during the parse, so we need to handle this case here
7358 (setq parent-qname
7359 (if (js2-wrapper-function-p fn)
7360 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7361 (if (js2-ast-root-p grandparent)
7362 nil
7363 (gethash grandparent js2-imenu-function-map 'skip)))
7364 'skip))
7365 (puthash fn parent-qname js2-imenu-function-map))
7366 (if (eq parent-qname 'skip)
7367 ;; We don't show it, let's record that fact.
7368 (remhash current-fn js2-imenu-function-map)
7369 ;; Prepend parent fn qname to this chain.
7370 (let ((qname (append parent-qname chain)))
7371 (puthash current-fn (butlast qname) js2-imenu-function-map)
7372 (push qname result)))))))
7373 ;; Collect chains obtained by third-party code.
7374 (let (js2-imenu-recorder)
7375 (run-hooks 'js2-build-imenu-callbacks)
7376 (dolist (entry js2-imenu-recorder)
7377 (push (cdr entry) result)))
7378 ;; Finally replace each node in each chain with its name.
7379 (dolist (chain result)
7380 (setq p chain)
7381 (while p
7382 (if (js2-node-p (setq elem (car p)))
7383 (setcar p (js2-node-qname-component elem)))
7384 (setq p (cdr p))))
7385 result))
7386
7387 ;; Merge name chains into a trie-like tree structure of nested lists.
7388 ;; To simplify construction of the trie, we first build it out using the rule
7389 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7390 ;; [key, num-or-list]. The second element can be a number; if so, this key
7391 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7392 ;; associated with the key at this level.) Otherwise the second element is
7393 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7394 ;; a simple recursive formulation.
7395 ;;
7396 ;; js2-mode is building the data structure for imenu. The imenu documentation
7397 ;; claims that it's the structure above, but in practice it wants the children
7398 ;; at the same list level as the key for that level, which is how I've drawn
7399 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7400 ;; list wrapper around the children at each level.
7401 ;;
7402 ;; A completed nested imenu-alist entry looks like this:
7403 ;; '(("foo"
7404 ;; ("<definition>" . 7)
7405 ;; ("bar"
7406 ;; ("a" . 40)
7407 ;; ("b" . 60))))
7408 ;;
7409 ;; In particular, the documentation for `imenu--index-alist' says that
7410 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7411 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7412
7413 (defun js2-treeify (lst)
7414 "Convert (a b c d) to (a ((b ((c d)))))."
7415 (if (null (cddr lst)) ; list length <= 2
7416 lst
7417 (list (car lst) (list (js2-treeify (cdr lst))))))
7418
7419 (defun js2-build-alist-trie (chains trie)
7420 "Merge declaration name chains into a trie-like alist structure for imenu.
7421 CHAINS is the qname chain list produced during parsing. TRIE is a
7422 list of elements built up so far."
7423 (let (head tail pos branch kids)
7424 (dolist (chain chains)
7425 (setq head (car chain)
7426 tail (cdr chain)
7427 pos (if (numberp (car tail)) (car tail))
7428 branch (js2-find-if (lambda (n)
7429 (string= (car n) head))
7430 trie)
7431 kids (cl-second branch))
7432 (cond
7433 ;; case 1: this key isn't in the trie yet
7434 ((null branch)
7435 (if trie
7436 (setcdr (last trie) (list (js2-treeify chain)))
7437 (setq trie (list (js2-treeify chain)))))
7438 ;; case 2: key is present with a single number entry: replace w/ list
7439 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7440 ;; ("<definition>" 20)))
7441 ((numberp kids)
7442 (setcar (cdr branch)
7443 (list (list "<definition-1>" kids)
7444 (if pos
7445 (list "<definition-2>" pos)
7446 (js2-treeify tail)))))
7447 ;; case 3: key is there (with kids), and we're a number entry
7448 (pos
7449 (setcdr (last kids)
7450 (list
7451 (list (format "<definition-%d>"
7452 (1+ (cl-loop for kid in kids
7453 count (eq ?< (aref (car kid) 0)))))
7454 pos))))
7455 ;; case 4: key is there with kids, need to merge in our chain
7456 (t
7457 (js2-build-alist-trie (list tail) kids))))
7458 trie))
7459
7460 (defun js2-flatten-trie (trie)
7461 "Convert TRIE to imenu-format.
7462 Recurses through nodes, and for each one whose second element is a list,
7463 appends the list's flattened elements to the current element. Also
7464 changes the tails into conses. For instance, this pre-flattened trie
7465
7466 '(a ((b 20)
7467 (c ((d 30)
7468 (e 40)))))
7469
7470 becomes
7471
7472 '(a (b . 20)
7473 (c (d . 30)
7474 (e . 40)))
7475
7476 Note that the root of the trie has no key, just a list of chains.
7477 This is also true for the value of any key with multiple children,
7478 e.g. key 'c' in the example above."
7479 (cond
7480 ((listp (car trie))
7481 (mapcar #'js2-flatten-trie trie))
7482 (t
7483 (if (numberp (cl-second trie))
7484 (cons (car trie) (cl-second trie))
7485 ;; else pop list and append its kids
7486 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7487
7488 (defun js2-build-imenu-index ()
7489 "Turn `js2-imenu-recorder' into an imenu data structure."
7490 (when (eq js2-imenu-recorder 'empty)
7491 (setq js2-imenu-recorder nil))
7492 (let* ((chains (js2-browse-postprocess-chains))
7493 (result (js2-build-alist-trie chains nil)))
7494 (js2-flatten-trie result)))
7495
7496 (defun js2-test-print-chains (chains)
7497 "Print a list of qname chains.
7498 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7499 i.e. one or more nodes, and an integer position as the list tail."
7500 (mapconcat (lambda (chain)
7501 (concat "("
7502 (mapconcat (lambda (elem)
7503 (if (js2-node-p elem)
7504 (or (js2-node-qname-component elem)
7505 "nil")
7506 (number-to-string elem)))
7507 chain
7508 " ")
7509 ")"))
7510 chains
7511 "\n"))
7512
7513 ;;; Parser
7514
7515 (defconst js2-version "1.8.5"
7516 "Version of JavaScript supported.")
7517
7518 (defun js2-record-face (face &optional token)
7519 "Record a style run of FACE for TOKEN or the current token."
7520 (unless token (setq token (js2-current-token)))
7521 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7522
7523 (defsubst js2-node-end (n)
7524 "Computes the absolute end of node N.
7525 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7526 is only true until the node is added to its parent; i.e., while parsing."
7527 (+ (js2-node-pos n)
7528 (js2-node-len n)))
7529
7530 (defun js2-record-comment (token)
7531 "Record a comment in `js2-scanned-comments'."
7532 (let ((ct (js2-token-comment-type token))
7533 (beg (js2-token-beg token))
7534 (end (js2-token-end token)))
7535 (push (make-js2-comment-node :len (- end beg)
7536 :format ct)
7537 js2-scanned-comments)
7538 (when js2-parse-ide-mode
7539 (js2-record-face (if (eq ct 'jsdoc)
7540 'font-lock-doc-face
7541 'font-lock-comment-face)
7542 token)
7543 (when (memq ct '(html preprocessor))
7544 ;; Tell cc-engine the bounds of the comment.
7545 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7546
7547 (defun js2-peek-token ()
7548 "Return the next token type without consuming it.
7549 If `js2-ti-lookahead' is positive, return the type of next token
7550 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7551 (if (not (zerop js2-ti-lookahead))
7552 (js2-token-type
7553 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7554 (let ((tt (js2-get-token-internal nil)))
7555 (js2-unget-token)
7556 tt)))
7557
7558 (defalias 'js2-next-token 'js2-get-token)
7559
7560 (defun js2-match-token (match &optional dont-unget)
7561 "Get next token and return t if it matches MATCH, a bytecode.
7562 Returns nil and consumes nothing if MATCH is not the next token."
7563 (if (/= (js2-get-token) match)
7564 (ignore (unless dont-unget (js2-unget-token)))
7565 t))
7566
7567 (defun js2-match-contextual-kwd (name)
7568 "Consume and return t if next token is `js2-NAME', and its
7569 string is NAME. Returns nil and keeps current token otherwise."
7570 (if (or (/= (js2-get-token) js2-NAME)
7571 (not (string= (js2-current-token-string) name)))
7572 (progn
7573 (js2-unget-token)
7574 nil)
7575 (js2-record-face 'font-lock-keyword-face)
7576 t))
7577
7578 (defun js2-get-prop-name-token ()
7579 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7580
7581 (defun js2-match-prop-name ()
7582 "Consume token and return t if next token is a valid property name.
7583 If `js2-language-version' is >= 180, a keyword or reserved word
7584 is considered valid name as well."
7585 (if (eq js2-NAME (js2-get-prop-name-token))
7586 t
7587 (js2-unget-token)
7588 nil))
7589
7590 (defun js2-must-match-prop-name (msg-id &optional pos len)
7591 (if (js2-match-prop-name)
7592 t
7593 (js2-report-error msg-id nil pos len)
7594 nil))
7595
7596 (defun js2-peek-token-or-eol ()
7597 "Return js2-EOL if the next token immediately follows a newline.
7598 Else returns the next token. Used in situations where we don't
7599 consider certain token types valid if they are preceded by a newline.
7600 One example is the postfix ++ or -- operator, which has to be on the
7601 same line as its operand."
7602 (let ((tt (js2-get-token))
7603 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7604 (js2-unget-token)
7605 (if follows-eol
7606 js2-EOL
7607 tt)))
7608
7609 (defun js2-must-match (token msg-id &optional pos len)
7610 "Match next token to token code TOKEN, or record a syntax error.
7611 MSG-ID is the error message to report if the match fails.
7612 Returns t on match, nil if no match."
7613 (if (js2-match-token token t)
7614 t
7615 (js2-report-error msg-id nil pos len)
7616 (js2-unget-token)
7617 nil))
7618
7619 (defun js2-must-match-name (msg-id)
7620 (if (js2-match-token js2-NAME t)
7621 t
7622 (if (eq (js2-current-token-type) js2-RESERVED)
7623 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7624 (js2-report-error msg-id)
7625 (js2-unget-token))
7626 nil))
7627
7628 (defsubst js2-inside-function ()
7629 (cl-plusp js2-nesting-of-function))
7630
7631 (defun js2-set-requires-activation ()
7632 (if (js2-function-node-p js2-current-script-or-fn)
7633 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7634
7635 (defun js2-check-activation-name (name _token)
7636 (when (js2-inside-function)
7637 ;; skip language-version 1.2 check from Rhino
7638 (if (or (string= "arguments" name)
7639 (and js2-compiler-activation-names ; only used in codegen
7640 (gethash name js2-compiler-activation-names)))
7641 (js2-set-requires-activation))))
7642
7643 (defun js2-set-is-generator ()
7644 (let ((fn-node js2-current-script-or-fn))
7645 (when (and (js2-function-node-p fn-node)
7646 (not (js2-function-node-generator-type fn-node)))
7647 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7648
7649 (defun js2-must-have-xml ()
7650 (unless js2-compiler-xml-available
7651 (js2-report-error "msg.XML.not.available")))
7652
7653 (defun js2-push-scope (scope)
7654 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7655 (cl-assert (js2-scope-p scope))
7656 (cl-assert (null (js2-scope-parent-scope scope)))
7657 (cl-assert (not (eq js2-current-scope scope)))
7658 (setf (js2-scope-parent-scope scope) js2-current-scope
7659 js2-current-scope scope))
7660
7661 (defsubst js2-pop-scope ()
7662 (setq js2-current-scope
7663 (js2-scope-parent-scope js2-current-scope)))
7664
7665 (defun js2-enter-loop (loop-node)
7666 (push loop-node js2-loop-set)
7667 (push loop-node js2-loop-and-switch-set)
7668 (js2-push-scope loop-node)
7669 ;; Tell the current labeled statement (if any) its statement,
7670 ;; and set the jump target of the first label to the loop.
7671 ;; These are used in `js2-parse-continue' to verify that the
7672 ;; continue target is an actual labeled loop. (And for codegen.)
7673 (when js2-labeled-stmt
7674 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7675 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7676 js2-labeled-stmt))) loop-node)))
7677
7678 (defun js2-exit-loop ()
7679 (pop js2-loop-set)
7680 (pop js2-loop-and-switch-set)
7681 (js2-pop-scope))
7682
7683 (defsubst js2-enter-switch (switch-node)
7684 (push switch-node js2-loop-and-switch-set))
7685
7686 (defsubst js2-exit-switch ()
7687 (pop js2-loop-and-switch-set))
7688
7689 (defun js2-parse (&optional buf cb)
7690 "Tell the js2 parser to parse a region of JavaScript.
7691
7692 BUF is a buffer or buffer name containing the code to parse.
7693 Call `narrow-to-region' first to parse only part of the buffer.
7694
7695 The returned AST root node is given some additional properties:
7696 `node-count' - total number of nodes in the AST
7697 `buffer' - BUF. The buffer it refers to may change or be killed,
7698 so the value is not necessarily reliable.
7699
7700 An optional callback CB can be specified to report parsing
7701 progress. If `(functionp CB)' returns t, it will be called with
7702 the current line number once before parsing begins, then again
7703 each time the lexer reaches a new line number.
7704
7705 CB can also be a list of the form `(symbol cb ...)' to specify
7706 multiple callbacks with different criteria. Each symbol is a
7707 criterion keyword, and the following element is the callback to
7708 call
7709
7710 :line - called whenever the line number changes
7711 :token - called for each new token consumed
7712
7713 The list of criteria could be extended to include entering or
7714 leaving a statement, an expression, or a function definition."
7715 (if (and cb (not (functionp cb)))
7716 (error "criteria callbacks not yet implemented"))
7717 (let ((inhibit-point-motion-hooks t)
7718 (js2-compiler-xml-available (>= js2-language-version 160))
7719 ;; This is a recursive-descent parser, so give it a big stack.
7720 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7721 (max-specpdl-size (max max-specpdl-size 3000))
7722 (case-fold-search nil)
7723 ast)
7724 (with-current-buffer (or buf (current-buffer))
7725 (setq js2-scanned-comments nil
7726 js2-parsed-errors nil
7727 js2-parsed-warnings nil
7728 js2-imenu-recorder nil
7729 js2-imenu-function-map nil
7730 js2-label-set nil)
7731 (js2-init-scanner)
7732 (setq ast (js2-do-parse))
7733 (unless js2-ts-hit-eof
7734 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7735 (setf (js2-ast-root-errors ast) js2-parsed-errors
7736 (js2-ast-root-warnings ast) js2-parsed-warnings)
7737 ;; if we didn't find any declarations, put a dummy in this list so we
7738 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7739 (unless js2-imenu-recorder
7740 (setq js2-imenu-recorder 'empty))
7741 (run-hooks 'js2-parse-finished-hook)
7742 ast)))
7743
7744 ;; Corresponds to Rhino's Parser.parse() method.
7745 (defun js2-do-parse ()
7746 "Parse current buffer starting from current point.
7747 Scanner should be initialized."
7748 (let ((pos js2-ts-cursor)
7749 (end js2-ts-cursor) ; in case file is empty
7750 root n tt)
7751 ;; initialize buffer-local parsing vars
7752 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7753 js2-current-script-or-fn root
7754 js2-current-scope root
7755 js2-nesting-of-function 0
7756 js2-labeled-stmt nil
7757 js2-recorded-identifiers nil) ; for js2-highlight
7758 (while (/= (setq tt (js2-get-token)) js2-EOF)
7759 (if (= tt js2-FUNCTION)
7760 (progn
7761 (setq n (if js2-called-by-compile-function
7762 (js2-parse-function-expr)
7763 (js2-parse-function-stmt))))
7764 ;; not a function - parse a statement
7765 (js2-unget-token)
7766 (setq n (js2-parse-statement)))
7767 ;; add function or statement to script
7768 (setq end (js2-node-end n))
7769 (js2-block-node-push root n))
7770 ;; add comments to root in lexical order
7771 (when js2-scanned-comments
7772 ;; if we find a comment beyond end of normal kids, use its end
7773 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7774 (dolist (comment js2-scanned-comments)
7775 (push comment (js2-ast-root-comments root))
7776 (js2-node-add-children root comment)))
7777 (setf (js2-node-len root) (- end pos))
7778 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7779 ;; Give extensions a chance to muck with things before highlighting starts.
7780 (let ((js2-additional-externs js2-additional-externs))
7781 (save-excursion
7782 (run-hooks 'js2-post-parse-callbacks))
7783 (js2-highlight-undeclared-vars))
7784 root))
7785
7786 (defun js2-parse-function-closure-body (fn-node)
7787 "Parse a JavaScript 1.8 function closure body."
7788 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7789 (if js2-ts-hit-eof
7790 (js2-report-error "msg.no.brace.body" nil
7791 (js2-node-pos fn-node)
7792 (- js2-ts-cursor (js2-node-pos fn-node)))
7793 (js2-node-add-children fn-node
7794 (setf (js2-function-node-body fn-node)
7795 (js2-parse-expr t))))))
7796
7797 (defun js2-parse-function-body (fn-node)
7798 (js2-must-match js2-LC "msg.no.brace.body"
7799 (js2-node-pos fn-node)
7800 (- js2-ts-cursor (js2-node-pos fn-node)))
7801 (let ((pos (js2-current-token-beg)) ; LC position
7802 (pn (make-js2-block-node)) ; starts at LC position
7803 tt
7804 end)
7805 (cl-incf js2-nesting-of-function)
7806 (unwind-protect
7807 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7808 (= tt js2-EOF)
7809 (= tt js2-RC)))
7810 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7811 (js2-parse-statement)
7812 (js2-get-token)
7813 (js2-parse-function-stmt))))
7814 (cl-decf js2-nesting-of-function))
7815 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7816 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7817 (setq end (js2-current-token-end)))
7818 (setf (js2-node-pos pn) pos
7819 (js2-node-len pn) (- end pos))
7820 (setf (js2-function-node-body fn-node) pn)
7821 (js2-node-add-children fn-node pn)
7822 pn))
7823
7824 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7825 "Declare and fontify destructuring parameters inside NODE.
7826 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7827 (cond
7828 ((js2-name-node-p node)
7829 (let (leftpos)
7830 (js2-define-symbol decl-type (js2-name-node-name node)
7831 node ignore-not-in-block)
7832 (when face
7833 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7834 (+ leftpos (js2-node-len node))
7835 face 'record))))
7836 ((js2-object-node-p node)
7837 (dolist (elem (js2-object-node-elems node))
7838 (js2-define-destruct-symbols
7839 ;; In abbreviated destructuring {a, b}, right == left.
7840 (js2-object-prop-node-right elem)
7841 decl-type face ignore-not-in-block)))
7842 ((js2-array-node-p node)
7843 (dolist (elem (js2-array-node-elems node))
7844 (when elem
7845 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7846 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7847 (js2-node-len node)))))
7848
7849 (defun js2-parse-function-params (function-type fn-node pos)
7850 (if (js2-match-token js2-RP)
7851 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7852 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7853 (eq (js2-current-token-type) js2-NAME)))
7854 params param default-found rest-param-at)
7855 (when paren-free-arrow
7856 (js2-unget-token))
7857 (cl-loop for tt = (js2-peek-token)
7858 do
7859 (cond
7860 ;; destructuring param
7861 ((and (not paren-free-arrow)
7862 (or (= tt js2-LB) (= tt js2-LC)))
7863 (js2-get-token)
7864 (when default-found
7865 (js2-report-error "msg.no.default.after.default.param"))
7866 (setq param (js2-parse-destruct-primary-expr))
7867 (js2-define-destruct-symbols param
7868 js2-LP
7869 'js2-function-param)
7870 (push param params))
7871 ;; variable name
7872 (t
7873 (when (and (>= js2-language-version 200)
7874 (not paren-free-arrow)
7875 (js2-match-token js2-TRIPLEDOT)
7876 (not rest-param-at))
7877 ;; to report errors if there are more parameters
7878 (setq rest-param-at (length params)))
7879 (js2-must-match-name "msg.no.parm")
7880 (js2-record-face 'js2-function-param)
7881 (setq param (js2-create-name-node))
7882 (js2-define-symbol js2-LP (js2-current-token-string) param)
7883 ;; default parameter value
7884 (when (or (and default-found
7885 (not rest-param-at)
7886 (js2-must-match js2-ASSIGN
7887 "msg.no.default.after.default.param"
7888 (js2-node-pos param)
7889 (js2-node-len param)))
7890 (and (>= js2-language-version 200)
7891 (js2-match-token js2-ASSIGN)))
7892 (cl-assert (not paren-free-arrow))
7893 (let* ((pos (js2-node-pos param))
7894 (tt (js2-current-token-type))
7895 (op-pos (- (js2-current-token-beg) pos))
7896 (left param)
7897 (right (js2-parse-assign-expr))
7898 (len (- (js2-node-end right) pos)))
7899 (setq param (make-js2-assign-node
7900 :type tt :pos pos :len len :op-pos op-pos
7901 :left left :right right)
7902 default-found t)
7903 (js2-node-add-children param left right)))
7904 (push param params)))
7905 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7906 (js2-report-error "msg.param.after.rest" nil
7907 (js2-node-pos param) (js2-node-len param)))
7908 while
7909 (js2-match-token js2-COMMA))
7910 (when (and (not paren-free-arrow)
7911 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7912 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7913 (when rest-param-at
7914 (setf (js2-function-node-rest-p fn-node) t))
7915 (dolist (p params)
7916 (js2-node-add-children fn-node p)
7917 (push p (js2-function-node-params fn-node))))))
7918
7919 (defun js2-check-inconsistent-return-warning (fn-node name)
7920 "Possibly show inconsistent-return warning.
7921 Last token scanned is the close-curly for the function body."
7922 (when (and js2-mode-show-strict-warnings
7923 js2-strict-inconsistent-return-warning
7924 (not (js2-has-consistent-return-usage
7925 (js2-function-node-body fn-node))))
7926 ;; Have it extend from close-curly to bol or beginning of block.
7927 (let ((pos (save-excursion
7928 (goto-char (js2-current-token-end))
7929 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7930 (point-at-bol))))
7931 (end (js2-current-token-end)))
7932 (if (cl-plusp (js2-name-node-length name))
7933 (js2-add-strict-warning "msg.no.return.value"
7934 (js2-name-node-name name) pos end)
7935 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7936
7937 (defun js2-parse-function-stmt ()
7938 (let ((pos (js2-current-token-beg))
7939 (star-p (js2-match-token js2-MUL)))
7940 (js2-must-match-name "msg.unnamed.function.stmt")
7941 (let ((name (js2-create-name-node t))
7942 pn member-expr)
7943 (cond
7944 ((js2-match-token js2-LP)
7945 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7946 (js2-allow-member-expr-as-function-name
7947 (setq member-expr (js2-parse-member-expr-tail nil name))
7948 (js2-parse-highlight-member-expr-fn-name member-expr)
7949 (js2-must-match js2-LP "msg.no.paren.parms")
7950 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7951 (js2-function-node-member-expr pn) member-expr)
7952 pn)
7953 (t
7954 (js2-report-error "msg.no.paren.parms")
7955 (make-js2-error-node))))))
7956
7957 (defun js2-parse-function-expr ()
7958 (let ((pos (js2-current-token-beg))
7959 (star-p (js2-match-token js2-MUL))
7960 name)
7961 (when (js2-match-token js2-NAME)
7962 (setq name (js2-create-name-node t)))
7963 (js2-must-match js2-LP "msg.no.paren.parms")
7964 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7965
7966 (defun js2-parse-function (function-type pos star-p &optional name)
7967 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7968 beginning of the first token (function keyword, unless it's an
7969 arrow function), NAME is js2-name-node."
7970 (let (fn-node lp)
7971 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7972 (setq lp (js2-current-token-beg)))
7973 (setf fn-node (make-js2-function-node :pos pos
7974 :name name
7975 :form function-type
7976 :lp (if lp (- lp pos))
7977 :generator-type (and star-p 'STAR)))
7978 (when name
7979 (js2-set-face (js2-node-pos name) (js2-node-end name)
7980 'font-lock-function-name-face 'record)
7981 (when (and (eq function-type 'FUNCTION_STATEMENT)
7982 (cl-plusp (js2-name-node-length name)))
7983 ;; Function statements define a symbol in the enclosing scope
7984 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7985 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
7986 ;; 1. Nested functions are not affected by the dynamic scope flag
7987 ;; as dynamic scope is already a parent of their scope.
7988 ;; 2. Functions defined under the with statement also immune to
7989 ;; this setup, in which case dynamic scope is ignored in favor
7990 ;; of the with object.
7991 (setf (js2-function-node-ignore-dynamic fn-node) t))
7992 ;; dynamically bind all the per-function variables
7993 (let ((js2-current-script-or-fn fn-node)
7994 (js2-current-scope fn-node)
7995 (js2-nesting-of-with 0)
7996 (js2-end-flags 0)
7997 js2-label-set
7998 js2-loop-set
7999 js2-loop-and-switch-set)
8000 (js2-parse-function-params function-type fn-node pos)
8001 (when (eq function-type 'FUNCTION_ARROW)
8002 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8003 (if (and (>= js2-language-version 180)
8004 (/= (js2-peek-token) js2-LC))
8005 (js2-parse-function-closure-body fn-node)
8006 (js2-parse-function-body fn-node))
8007 (js2-check-inconsistent-return-warning fn-node name)
8008
8009 (when name
8010 (js2-node-add-children fn-node name)
8011 ;; Function expressions define a name only in the body of the
8012 ;; function, and only if not hidden by a parameter name
8013 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8014 (null (js2-scope-get-symbol js2-current-scope
8015 (js2-name-node-name name))))
8016 (js2-define-symbol js2-FUNCTION
8017 (js2-name-node-name name)
8018 fn-node))
8019 (when (eq function-type 'FUNCTION_STATEMENT)
8020 (js2-record-imenu-functions fn-node))))
8021
8022 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8023 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8024 ;; We wait until after parsing the function to set its parent scope,
8025 ;; since `js2-define-symbol' needs the defining-scope check to stop
8026 ;; at the function boundary when checking for redeclarations.
8027 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8028 fn-node))
8029
8030 (defun js2-parse-statements (&optional parent)
8031 "Parse a statement list. Last token consumed must be js2-LC.
8032
8033 PARENT can be a `js2-block-node', in which case the statements are
8034 appended to PARENT. Otherwise a new `js2-block-node' is created
8035 and returned.
8036
8037 This function does not match the closing js2-RC: the caller
8038 matches the RC so it can provide a suitable error message if not
8039 matched. This means it's up to the caller to set the length of
8040 the node to include the closing RC. The node start pos is set to
8041 the absolute buffer start position, and the caller should fix it
8042 up to be relative to the parent node. All children of this block
8043 node are given relative start positions and correct lengths."
8044 (let ((pn (or parent (make-js2-block-node)))
8045 tt)
8046 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8047 (/= tt js2-RC))
8048 (js2-block-node-push pn (js2-parse-statement)))
8049 pn))
8050
8051 (defun js2-parse-statement ()
8052 (let (pn beg end)
8053 ;; coarse-grained user-interrupt check - needs work
8054 (and js2-parse-interruptable-p
8055 (zerop (% (cl-incf js2-parse-stmt-count)
8056 js2-statements-per-pause))
8057 (input-pending-p)
8058 (throw 'interrupted t))
8059 (setq pn (js2-statement-helper))
8060 ;; no-side-effects warning check
8061 (unless (js2-node-has-side-effects pn)
8062 (setq end (js2-node-end pn))
8063 (save-excursion
8064 (goto-char end)
8065 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8066 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8067 pn))
8068
8069 ;; These correspond to the switch cases in Parser.statementHelper
8070 (defconst js2-parsers
8071 (let ((parsers (make-vector js2-num-tokens
8072 #'js2-parse-expr-stmt)))
8073 (aset parsers js2-BREAK #'js2-parse-break)
8074 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8075 (aset parsers js2-CONST #'js2-parse-const-var)
8076 (aset parsers js2-CONTINUE #'js2-parse-continue)
8077 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8078 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8079 (aset parsers js2-DO #'js2-parse-do)
8080 (aset parsers js2-EXPORT #'js2-parse-export)
8081 (aset parsers js2-FOR #'js2-parse-for)
8082 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8083 (aset parsers js2-IF #'js2-parse-if)
8084 (aset parsers js2-IMPORT #'js2-parse-import)
8085 (aset parsers js2-LC #'js2-parse-block)
8086 (aset parsers js2-LET #'js2-parse-let-stmt)
8087 (aset parsers js2-NAME #'js2-parse-name-or-label)
8088 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8089 (aset parsers js2-SEMI #'js2-parse-semi)
8090 (aset parsers js2-SWITCH #'js2-parse-switch)
8091 (aset parsers js2-THROW #'js2-parse-throw)
8092 (aset parsers js2-TRY #'js2-parse-try)
8093 (aset parsers js2-VAR #'js2-parse-const-var)
8094 (aset parsers js2-WHILE #'js2-parse-while)
8095 (aset parsers js2-WITH #'js2-parse-with)
8096 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8097 parsers)
8098 "A vector mapping token types to parser functions.")
8099
8100 (defun js2-parse-warn-missing-semi (beg end)
8101 (and js2-mode-show-strict-warnings
8102 js2-strict-missing-semi-warning
8103 (js2-add-strict-warning
8104 "msg.missing.semi" nil
8105 ;; back up to beginning of statement or line
8106 (max beg (save-excursion
8107 (goto-char end)
8108 (point-at-bol)))
8109 end)))
8110
8111 (defconst js2-no-semi-insertion
8112 (list js2-IF
8113 js2-SWITCH
8114 js2-WHILE
8115 js2-DO
8116 js2-FOR
8117 js2-TRY
8118 js2-WITH
8119 js2-LC
8120 js2-ERROR
8121 js2-SEMI
8122 js2-CLASS
8123 js2-FUNCTION
8124 js2-EXPORT)
8125 "List of tokens that don't do automatic semicolon insertion.")
8126
8127 (defconst js2-autoinsert-semi-and-warn
8128 (list js2-ERROR js2-EOF js2-RC))
8129
8130 (defun js2-statement-helper ()
8131 (let* ((tt (js2-get-token))
8132 (first-tt tt)
8133 (parser (if (= tt js2-ERROR)
8134 #'js2-parse-semi
8135 (aref js2-parsers tt)))
8136 pn)
8137 ;; If the statement is set, then it's been told its label by now.
8138 (and js2-labeled-stmt
8139 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8140 (setq js2-labeled-stmt nil))
8141 (setq pn (funcall parser))
8142 ;; Don't do auto semi insertion for certain statement types.
8143 (unless (or (memq first-tt js2-no-semi-insertion)
8144 (js2-labeled-stmt-node-p pn))
8145 (js2-auto-insert-semicolon pn))
8146 pn))
8147
8148 (defun js2-auto-insert-semicolon (pn)
8149 (let* ((tt (js2-get-token))
8150 (pos (js2-node-pos pn)))
8151 (cond
8152 ((= tt js2-SEMI)
8153 ;; extend the node bounds to include the semicolon.
8154 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8155 ((memq tt js2-autoinsert-semi-and-warn)
8156 (js2-unget-token) ; Not ';', do not consume.
8157 ;; Autoinsert ;
8158 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8159 (t
8160 (if (not (js2-token-follows-eol-p (js2-current-token)))
8161 ;; Report error if no EOL or autoinsert ';' otherwise
8162 (js2-report-error "msg.no.semi.stmt")
8163 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8164 (js2-unget-token) ; Not ';', do not consume.
8165 ))))
8166
8167 (defun js2-parse-condition ()
8168 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8169 The parens are discarded and the expression node is returned.
8170 The `pos' field of the return value is set to an absolute position
8171 that must be fixed up by the caller.
8172 Return value is a list (EXPR LP RP), with absolute paren positions."
8173 (let (pn lp rp)
8174 (if (js2-must-match js2-LP "msg.no.paren.cond")
8175 (setq lp (js2-current-token-beg)))
8176 (setq pn (js2-parse-expr))
8177 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8178 (setq rp (js2-current-token-beg)))
8179 ;; Report strict warning on code like "if (a = 7) ..."
8180 (if (and js2-strict-cond-assign-warning
8181 (js2-assign-node-p pn))
8182 (js2-add-strict-warning "msg.equal.as.assign" nil
8183 (js2-node-pos pn)
8184 (+ (js2-node-pos pn)
8185 (js2-node-len pn))))
8186 (list pn lp rp)))
8187
8188 (defun js2-parse-if ()
8189 "Parser for if-statement. Last matched token must be js2-IF."
8190 (let ((pos (js2-current-token-beg))
8191 cond if-true if-false else-pos end pn)
8192 (setq cond (js2-parse-condition)
8193 if-true (js2-parse-statement)
8194 if-false (if (js2-match-token js2-ELSE)
8195 (progn
8196 (setq else-pos (- (js2-current-token-beg) pos))
8197 (js2-parse-statement)))
8198 end (js2-node-end (or if-false if-true))
8199 pn (make-js2-if-node :pos pos
8200 :len (- end pos)
8201 :condition (car cond)
8202 :then-part if-true
8203 :else-part if-false
8204 :else-pos else-pos
8205 :lp (js2-relpos (cl-second cond) pos)
8206 :rp (js2-relpos (cl-third cond) pos)))
8207 (js2-node-add-children pn (car cond) if-true if-false)
8208 pn))
8209
8210 (defun js2-parse-import ()
8211 "Parse import statement. The current token must be js2-IMPORT."
8212 (unless (js2-ast-root-p js2-current-scope)
8213 (js2-report-error "msg.mod.import.decl.at.top.level"))
8214 (let ((beg (js2-current-token-beg)))
8215 (cond ((js2-match-token js2-STRING)
8216 (make-js2-import-node
8217 :pos beg
8218 :len (- (js2-current-token-end) beg)
8219 :module-id (js2-current-token-string)))
8220 (t
8221 (let* ((import-clause (js2-parse-import-clause))
8222 (from-clause (and import-clause (js2-parse-from-clause)))
8223 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8224 (node (make-js2-import-node
8225 :pos beg
8226 :len (- (js2-current-token-end) beg)
8227 :import import-clause
8228 :from from-clause
8229 :module-id module-id)))
8230 (when import-clause
8231 (js2-node-add-children node import-clause))
8232 (when from-clause
8233 (js2-node-add-children node from-clause))
8234 node)))))
8235
8236 (defun js2-parse-import-clause ()
8237 "Parse the bindings in an import statement.
8238 This can take many forms:
8239
8240 ImportedDefaultBinding -> 'foo'
8241 NameSpaceImport -> '* as lib'
8242 NamedImports -> '{foo as bar, bang}'
8243 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8244 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8245
8246 Try to match namespace imports and named imports first because nothing can
8247 come after them. If it is an imported default binding, then it could have named
8248 imports or a namespace import that follows it.
8249 "
8250 (let* ((beg (js2-current-token-beg))
8251 (clause (make-js2-import-clause-node
8252 :pos beg))
8253 (children (list)))
8254 (cond
8255 ((js2-match-token js2-MUL)
8256 (let ((ns-import (js2-parse-namespace-import)))
8257 (when ns-import
8258 (let ((name-node (js2-namespace-import-node-name ns-import)))
8259 (js2-define-symbol
8260 js2-LET (js2-name-node-name name-node) name-node t)))
8261 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8262 (push ns-import children)))
8263 ((js2-match-token js2-LC)
8264 (let ((imports (js2-parse-export-bindings t)))
8265 (setf (js2-import-clause-node-named-imports clause) imports)
8266 (dolist (import imports)
8267 (push import children)
8268 (let ((name-node (js2-export-binding-node-local-name import)))
8269 (when name-node
8270 (js2-define-symbol
8271 js2-LET (js2-name-node-name name-node) name-node t))))))
8272 ((= (js2-peek-token) js2-NAME)
8273 (let ((binding (js2-maybe-parse-export-binding)))
8274 (let ((node-name (js2-export-binding-node-local-name binding)))
8275 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8276 (setf (js2-import-clause-node-default-binding clause) binding)
8277 (push binding children))
8278 (when (js2-match-token js2-COMMA)
8279 (cond
8280 ((js2-match-token js2-MUL)
8281 (let ((ns-import (js2-parse-namespace-import)))
8282 (let ((name-node (js2-namespace-import-node-name ns-import)))
8283 (js2-define-symbol
8284 js2-LET (js2-name-node-name name-node) name-node t))
8285 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8286 (push ns-import children)))
8287 ((js2-match-token js2-LC)
8288 (let ((imports (js2-parse-export-bindings t)))
8289 (setf (js2-import-clause-node-named-imports clause) imports)
8290 (dolist (import imports)
8291 (push import children)
8292 (let ((name-node (js2-export-binding-node-local-name import)))
8293 (when name-node
8294 (js2-define-symbol
8295 js2-LET (js2-name-node-name name-node) name-node t))))))
8296 (t (js2-report-error "msg.syntax")))))
8297 (t (js2-report-error "msg.mod.declaration.after.import")))
8298 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8299 (apply #'js2-node-add-children clause children)
8300 clause))
8301
8302 (defun js2-parse-namespace-import ()
8303 "Parse a namespace import expression such as '* as bar'.
8304 The current token must be js2-MUL."
8305 (let ((beg (js2-current-token-beg)))
8306 (when (js2-must-match js2-NAME "msg.syntax")
8307 (if (equal "as" (js2-current-token-string))
8308 (when (js2-must-match-prop-name "msg.syntax")
8309 (let ((node (make-js2-namespace-import-node
8310 :pos beg
8311 :len (- (js2-current-token-end) beg)
8312 :name (make-js2-name-node
8313 :pos (js2-current-token-beg)
8314 :len (js2-current-token-end)
8315 :name (js2-current-token-string)))))
8316 (js2-node-add-children node (js2-namespace-import-node-name node))
8317 node))
8318 (js2-unget-token)
8319 (js2-report-error "msg.syntax")))))
8320
8321
8322 (defun js2-parse-from-clause ()
8323 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8324 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8325 (let ((beg (js2-current-token-beg)))
8326 (if (equal "from" (js2-current-token-string))
8327 (cond
8328 ((js2-match-token js2-STRING)
8329 (make-js2-from-clause-node
8330 :pos beg
8331 :len (- (js2-current-token-end) beg)
8332 :module-id (js2-current-token-string)
8333 :metadata-p nil))
8334 ((js2-match-token js2-THIS)
8335 (when (js2-must-match-name "msg.mod.spec.after.from")
8336 (if (equal "module" (js2-current-token-string))
8337 (make-js2-from-clause-node
8338 :pos beg
8339 :len (- (js2-current-token-end) beg)
8340 :module-id "this"
8341 :metadata-p t)
8342 (js2-unget-token)
8343 (js2-unget-token)
8344 (js2-report-error "msg.mod.spec.after.from")
8345 nil)))
8346 (t (js2-report-error "msg.mod.spec.after.from") nil))
8347 (js2-unget-token)
8348 (js2-report-error "msg.mod.from.after.import.spec.set")
8349 nil))))
8350
8351 (defun js2-parse-export-bindings (&optional import-p)
8352 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8353 {foo as bar, baz as bang}. The current token must be
8354 js2-LC. Return a lisp list of js2-export-binding-node"
8355 (let ((bindings (list)))
8356 (while
8357 (let ((binding (js2-maybe-parse-export-binding)))
8358 (when binding
8359 (push binding bindings))
8360 (js2-match-token js2-COMMA)))
8361 (when (js2-must-match js2-RC (if import-p
8362 "msg.mod.rc.after.import.spec.list"
8363 "msg.mod.rc.after.export.spec.list"))
8364 (reverse bindings))))
8365
8366 (defun js2-maybe-parse-export-binding ()
8367 "Attempt to parse a binding expression found inside an import/export statement.
8368 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8369 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8370 js2-export-binding-node and consume all the tokens. If it does not match, it
8371 consumes no tokens."
8372 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8373 (beg (js2-current-token-beg))
8374 (extern-name-len (js2-current-token-len))
8375 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8376 (aref js2-kwd-tokens (js2-current-token-type)))))
8377 (if extern-name
8378 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8379 (if (and as (equal "as" (js2-current-token-string)))
8380 (let ((name
8381 (or
8382 (and (js2-match-token js2-DEFAULT) "default")
8383 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8384 (if name
8385 (let ((node (make-js2-export-binding-node
8386 :pos beg
8387 :len (- (js2-current-token-end) beg)
8388 :local-name (make-js2-name-node
8389 :name name
8390 :pos (js2-current-token-beg)
8391 :len (js2-current-token-len))
8392 :extern-name (make-js2-name-node
8393 :name extern-name
8394 :pos beg
8395 :len extern-name-len))))
8396 (js2-node-add-children
8397 node
8398 (js2-export-binding-node-local-name node)
8399 (js2-export-binding-node-extern-name node))
8400 node)
8401 (js2-unget-token)
8402 nil))
8403 (when as (js2-unget-token))
8404 (let* ((name-node (make-js2-name-node
8405 :name (js2-current-token-string)
8406 :pos (js2-current-token-beg)
8407 :len (js2-current-token-len)))
8408 (node (make-js2-export-binding-node
8409 :pos (js2-current-token-beg)
8410 :len (js2-current-token-len)
8411 :local-name name-node
8412 :extern-name name-node)))
8413 (when is-reserved-name
8414 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8415 (js2-node-add-children node name-node)
8416 node)))
8417 nil)))
8418
8419 (defun js2-parse-switch ()
8420 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8421 (let ((pos (js2-current-token-beg))
8422 tt pn discriminant has-default case-expr case-node
8423 case-pos cases stmt lp)
8424 (if (js2-must-match js2-LP "msg.no.paren.switch")
8425 (setq lp (js2-current-token-beg)))
8426 (setq discriminant (js2-parse-expr)
8427 pn (make-js2-switch-node :discriminant discriminant
8428 :pos pos
8429 :lp (js2-relpos lp pos)))
8430 (js2-node-add-children pn discriminant)
8431 (js2-enter-switch pn)
8432 (unwind-protect
8433 (progn
8434 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8435 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8436 (js2-must-match js2-LC "msg.no.brace.switch")
8437 (catch 'break
8438 (while t
8439 (setq tt (js2-next-token)
8440 case-pos (js2-current-token-beg))
8441 (cond
8442 ((= tt js2-RC)
8443 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8444 (throw 'break nil)) ; done
8445 ((= tt js2-CASE)
8446 (setq case-expr (js2-parse-expr))
8447 (js2-must-match js2-COLON "msg.no.colon.case"))
8448 ((= tt js2-DEFAULT)
8449 (if has-default
8450 (js2-report-error "msg.double.switch.default"))
8451 (setq has-default t
8452 case-expr nil)
8453 (js2-must-match js2-COLON "msg.no.colon.case"))
8454 (t
8455 (js2-report-error "msg.bad.switch")
8456 (throw 'break nil)))
8457 (setq case-node (make-js2-case-node :pos case-pos
8458 :len (- (js2-current-token-end) case-pos)
8459 :expr case-expr))
8460 (js2-node-add-children case-node case-expr)
8461 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8462 (/= tt js2-CASE)
8463 (/= tt js2-DEFAULT)
8464 (/= tt js2-EOF))
8465 (setf stmt (js2-parse-statement)
8466 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8467 (js2-block-node-push case-node stmt))
8468 (push case-node cases)))
8469 ;; add cases last, as pushing reverses the order to be correct
8470 (dolist (kid cases)
8471 (js2-node-add-children pn kid)
8472 (push kid (js2-switch-node-cases pn)))
8473 pn) ; return value
8474 (js2-exit-switch))))
8475
8476 (defun js2-parse-while ()
8477 "Parser for while-statement. Last matched token must be js2-WHILE."
8478 (let ((pos (js2-current-token-beg))
8479 (pn (make-js2-while-node))
8480 cond body)
8481 (js2-enter-loop pn)
8482 (unwind-protect
8483 (progn
8484 (setf cond (js2-parse-condition)
8485 (js2-while-node-condition pn) (car cond)
8486 body (js2-parse-statement)
8487 (js2-while-node-body pn) body
8488 (js2-node-len pn) (- (js2-node-end body) pos)
8489 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8490 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8491 (js2-node-add-children pn body (car cond)))
8492 (js2-exit-loop))
8493 pn))
8494
8495 (defun js2-parse-do ()
8496 "Parser for do-statement. Last matched token must be js2-DO."
8497 (let ((pos (js2-current-token-beg))
8498 (pn (make-js2-do-node))
8499 cond body end)
8500 (js2-enter-loop pn)
8501 (unwind-protect
8502 (progn
8503 (setq body (js2-parse-statement))
8504 (js2-must-match js2-WHILE "msg.no.while.do")
8505 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8506 cond (js2-parse-condition)
8507 (js2-do-node-condition pn) (car cond)
8508 (js2-do-node-body pn) body
8509 end js2-ts-cursor
8510 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8511 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8512 (js2-node-add-children pn (car cond) body))
8513 (js2-exit-loop))
8514 ;; Always auto-insert semicolon to follow SpiderMonkey:
8515 ;; It is required by ECMAScript but is ignored by the rest of
8516 ;; world; see bug 238945
8517 (if (js2-match-token js2-SEMI)
8518 (setq end js2-ts-cursor))
8519 (setf (js2-node-len pn) (- end pos))
8520 pn))
8521
8522 (defun js2-parse-export ()
8523 "Parse an export statement.
8524 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8525 expressions should only be either hoistable expressions (function or generator)
8526 or assignment expressions, but there is no checking to enforce that and so it
8527 will parse without error a small subset of
8528 invalid export statements."
8529 (unless (js2-ast-root-p js2-current-scope)
8530 (js2-report-error "msg.mod.export.decl.at.top.level"))
8531 (let ((beg (js2-current-token-beg))
8532 (children (list))
8533 exports-list from-clause declaration default)
8534 (cond
8535 ((js2-match-token js2-MUL)
8536 (setq from-clause (js2-parse-from-clause))
8537 (when from-clause
8538 (push from-clause children)))
8539 ((js2-match-token js2-LC)
8540 (setq exports-list (js2-parse-export-bindings))
8541 (when exports-list
8542 (dolist (export exports-list)
8543 (push export children)))
8544 (when (js2-match-token js2-NAME)
8545 (if (equal "from" (js2-current-token-string))
8546 (progn
8547 (js2-unget-token)
8548 (setq from-clause (js2-parse-from-clause)))
8549 (js2-unget-token))))
8550 ((js2-match-token js2-DEFAULT)
8551 (setq default (js2-parse-expr)))
8552 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8553 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8554 (t
8555 (setq declaration (js2-parse-expr))))
8556 (when from-clause
8557 (push from-clause children))
8558 (when declaration
8559 (push declaration children)
8560 (when (not (js2-function-node-p declaration))
8561 (js2-auto-insert-semicolon declaration)))
8562 (when default
8563 (push default children)
8564 (when (not (js2-function-node-p default))
8565 (js2-auto-insert-semicolon default)))
8566 (let ((node (make-js2-export-node
8567 :pos beg
8568 :len (- (js2-current-token-end) beg)
8569 :exports-list exports-list
8570 :from-clause from-clause
8571 :declaration declaration
8572 :default default)))
8573 (apply #'js2-node-add-children node children)
8574 node)))
8575
8576 (defun js2-parse-for ()
8577 "Parse a for, for-in or for each-in statement.
8578 Last matched token must be js2-FOR."
8579 (let ((for-pos (js2-current-token-beg))
8580 (tmp-scope (make-js2-scope))
8581 pn is-for-each is-for-in-or-of is-for-of
8582 in-pos each-pos tmp-pos
8583 init ; Node init is also foo in 'foo in object'.
8584 cond ; Node cond is also object in 'foo in object'.
8585 incr ; 3rd section of for-loop initializer.
8586 body tt lp rp)
8587 ;; See if this is a for each () instead of just a for ()
8588 (when (js2-match-token js2-NAME)
8589 (if (string= "each" (js2-current-token-string))
8590 (progn
8591 (setq is-for-each t
8592 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8593 (js2-record-face 'font-lock-keyword-face))
8594 (js2-report-error "msg.no.paren.for")))
8595 (if (js2-must-match js2-LP "msg.no.paren.for")
8596 (setq lp (- (js2-current-token-beg) for-pos)))
8597 (setq tt (js2-get-token))
8598 ;; Capture identifiers inside parens. We can't create the node
8599 ;; (and use it as the current scope) until we know its type.
8600 (js2-push-scope tmp-scope)
8601 (unwind-protect
8602 (progn
8603 ;; parse init clause
8604 (let ((js2-in-for-init t)) ; set as dynamic variable
8605 (cond
8606 ((= tt js2-SEMI)
8607 (js2-unget-token)
8608 (setq init (make-js2-empty-expr-node)))
8609 ((or (= tt js2-VAR) (= tt js2-LET))
8610 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8611 (t
8612 (js2-unget-token)
8613 (setq init (js2-parse-expr)))))
8614 (if (or (js2-match-token js2-IN)
8615 (and (>= js2-language-version 200)
8616 (js2-match-contextual-kwd "of")
8617 (setq is-for-of t)))
8618 (setq is-for-in-or-of t
8619 in-pos (- (js2-current-token-beg) for-pos)
8620 ;; scope of iteration target object is not the scope we've created above.
8621 ;; stash current scope temporary.
8622 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8623 (js2-parse-expr))) ; object over which we're iterating
8624 ;; else ordinary for loop - parse cond and incr
8625 (js2-must-match js2-SEMI "msg.no.semi.for")
8626 (setq cond (if (= (js2-peek-token) js2-SEMI)
8627 (make-js2-empty-expr-node) ; no loop condition
8628 (js2-parse-expr)))
8629 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8630 (setq tmp-pos (js2-current-token-end)
8631 incr (if (= (js2-peek-token) js2-RP)
8632 (make-js2-empty-expr-node :pos tmp-pos)
8633 (js2-parse-expr)))))
8634 (js2-pop-scope))
8635 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8636 (setq rp (- (js2-current-token-beg) for-pos)))
8637 (if (not is-for-in-or-of)
8638 (setq pn (make-js2-for-node :init init
8639 :condition cond
8640 :update incr
8641 :lp lp
8642 :rp rp))
8643 ;; cond could be null if 'in obj' got eaten by the init node.
8644 (if (js2-infix-node-p init)
8645 ;; it was (foo in bar) instead of (var foo in bar)
8646 (setq cond (js2-infix-node-right init)
8647 init (js2-infix-node-left init))
8648 (if (and (js2-var-decl-node-p init)
8649 (> (length (js2-var-decl-node-kids init)) 1))
8650 (js2-report-error "msg.mult.index")))
8651 (setq pn (make-js2-for-in-node :iterator init
8652 :object cond
8653 :in-pos in-pos
8654 :foreach-p is-for-each
8655 :each-pos each-pos
8656 :forof-p is-for-of
8657 :lp lp
8658 :rp rp)))
8659 ;; Transplant the declarations.
8660 (setf (js2-scope-symbol-table pn)
8661 (js2-scope-symbol-table tmp-scope))
8662 (unwind-protect
8663 (progn
8664 (js2-enter-loop pn)
8665 ;; We have to parse the body -after- creating the loop node,
8666 ;; so that the loop node appears in the js2-loop-set, allowing
8667 ;; break/continue statements to find the enclosing loop.
8668 (setf body (js2-parse-statement)
8669 (js2-loop-node-body pn) body
8670 (js2-node-pos pn) for-pos
8671 (js2-node-len pn) (- (js2-node-end body) for-pos))
8672 (js2-node-add-children pn init cond incr body))
8673 ;; finally
8674 (js2-exit-loop))
8675 pn))
8676
8677 (defun js2-parse-try ()
8678 "Parse a try statement. Last matched token must be js2-TRY."
8679 (let ((try-pos (js2-current-token-beg))
8680 try-end
8681 try-block
8682 catch-blocks
8683 finally-block
8684 saw-default-catch
8685 peek)
8686 (if (/= (js2-peek-token) js2-LC)
8687 (js2-report-error "msg.no.brace.try"))
8688 (setq try-block (js2-parse-statement)
8689 try-end (js2-node-end try-block)
8690 peek (js2-peek-token))
8691 (cond
8692 ((= peek js2-CATCH)
8693 (while (js2-match-token js2-CATCH)
8694 (let* ((catch-pos (js2-current-token-beg))
8695 (catch-node (make-js2-catch-node :pos catch-pos))
8696 param
8697 guard-kwd
8698 catch-cond
8699 lp rp)
8700 (if saw-default-catch
8701 (js2-report-error "msg.catch.unreachable"))
8702 (if (js2-must-match js2-LP "msg.no.paren.catch")
8703 (setq lp (- (js2-current-token-beg) catch-pos)))
8704 (js2-push-scope catch-node)
8705 (let ((tt (js2-peek-token)))
8706 (cond
8707 ;; Destructuring pattern:
8708 ;; catch ({ message, file }) { ... }
8709 ((or (= tt js2-LB) (= tt js2-LC))
8710 (js2-get-token)
8711 (setq param (js2-parse-destruct-primary-expr))
8712 (js2-define-destruct-symbols param js2-LET nil))
8713 ;; Simple name.
8714 (t
8715 (js2-must-match-name "msg.bad.catchcond")
8716 (setq param (js2-create-name-node))
8717 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8718 ;; Catch condition.
8719 (if (js2-match-token js2-IF)
8720 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8721 catch-cond (js2-parse-expr))
8722 (setq saw-default-catch t))
8723 (if (js2-must-match js2-RP "msg.bad.catchcond")
8724 (setq rp (- (js2-current-token-beg) catch-pos)))
8725 (js2-must-match js2-LC "msg.no.brace.catchblock")
8726 (js2-parse-statements catch-node)
8727 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8728 (setq try-end (js2-current-token-end)))
8729 (js2-pop-scope)
8730 (setf (js2-node-len catch-node) (- try-end catch-pos)
8731 (js2-catch-node-param catch-node) param
8732 (js2-catch-node-guard-expr catch-node) catch-cond
8733 (js2-catch-node-guard-kwd catch-node) guard-kwd
8734 (js2-catch-node-lp catch-node) lp
8735 (js2-catch-node-rp catch-node) rp)
8736 (js2-node-add-children catch-node param catch-cond)
8737 (push catch-node catch-blocks))))
8738 ((/= peek js2-FINALLY)
8739 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8740 (js2-node-pos try-block)
8741 (- (setq try-end (js2-node-end try-block))
8742 (js2-node-pos try-block)))))
8743 (when (js2-match-token js2-FINALLY)
8744 (let ((finally-pos (js2-current-token-beg))
8745 (block (js2-parse-statement)))
8746 (setq try-end (js2-node-end block)
8747 finally-block (make-js2-finally-node :pos finally-pos
8748 :len (- try-end finally-pos)
8749 :body block))
8750 (js2-node-add-children finally-block block)))
8751 (let ((pn (make-js2-try-node :pos try-pos
8752 :len (- try-end try-pos)
8753 :try-block try-block
8754 :finally-block finally-block)))
8755 (js2-node-add-children pn try-block finally-block)
8756 ;; Push them onto the try-node, which reverses and corrects their order.
8757 (dolist (cb catch-blocks)
8758 (js2-node-add-children pn cb)
8759 (push cb (js2-try-node-catch-clauses pn)))
8760 pn)))
8761
8762 (defun js2-parse-throw ()
8763 "Parser for throw-statement. Last matched token must be js2-THROW."
8764 (let ((pos (js2-current-token-beg))
8765 expr pn)
8766 (if (= (js2-peek-token-or-eol) js2-EOL)
8767 ;; ECMAScript does not allow new lines before throw expression,
8768 ;; see bug 256617
8769 (js2-report-error "msg.bad.throw.eol"))
8770 (setq expr (js2-parse-expr)
8771 pn (make-js2-throw-node :pos pos
8772 :len (- (js2-node-end expr) pos)
8773 :expr expr))
8774 (js2-node-add-children pn expr)
8775 pn))
8776
8777 (defun js2-match-jump-label-name (label-name)
8778 "If break/continue specified a label, return that label's labeled stmt.
8779 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8780 does not match an existing label, reports an error and returns nil."
8781 (let ((bundle (cdr (assoc label-name js2-label-set))))
8782 (if (null bundle)
8783 (js2-report-error "msg.undef.label"))
8784 bundle))
8785
8786 (defun js2-parse-break ()
8787 "Parser for break-statement. Last matched token must be js2-BREAK."
8788 (let ((pos (js2-current-token-beg))
8789 (end (js2-current-token-end))
8790 break-target ; statement to break from
8791 break-label ; in "break foo", name-node representing the foo
8792 labels ; matching labeled statement to break to
8793 pn)
8794 (when (eq (js2-peek-token-or-eol) js2-NAME)
8795 (js2-get-token)
8796 (setq break-label (js2-create-name-node)
8797 end (js2-node-end break-label)
8798 ;; matchJumpLabelName only matches if there is one
8799 labels (js2-match-jump-label-name (js2-current-token-string))
8800 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8801 (unless (or break-target break-label)
8802 ;; no break target specified - try for innermost enclosing loop/switch
8803 (if (null js2-loop-and-switch-set)
8804 (unless break-label
8805 (js2-report-error "msg.bad.break" nil pos (length "break")))
8806 (setq break-target (car js2-loop-and-switch-set))))
8807 (setq pn (make-js2-break-node :pos pos
8808 :len (- end pos)
8809 :label break-label
8810 :target break-target))
8811 (js2-node-add-children pn break-label) ; but not break-target
8812 pn))
8813
8814 (defun js2-parse-continue ()
8815 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8816 (let ((pos (js2-current-token-beg))
8817 (end (js2-current-token-end))
8818 label ; optional user-specified label, a `js2-name-node'
8819 labels ; current matching labeled stmt, if any
8820 target ; the `js2-loop-node' target of this continue stmt
8821 pn)
8822 (when (= (js2-peek-token-or-eol) js2-NAME)
8823 (js2-get-token)
8824 (setq label (js2-create-name-node)
8825 end (js2-node-end label)
8826 ;; matchJumpLabelName only matches if there is one
8827 labels (js2-match-jump-label-name (js2-current-token-string))))
8828 (cond
8829 ((null labels) ; no current label to go to
8830 (if (null js2-loop-set) ; no loop to continue to
8831 (js2-report-error "msg.continue.outside" nil pos
8832 (length "continue"))
8833 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8834 (t
8835 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8836 (setq target (js2-labeled-stmt-node-stmt labels))
8837 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8838 (setq pn (make-js2-continue-node :pos pos
8839 :len (- end pos)
8840 :label label
8841 :target target))
8842 (js2-node-add-children pn label) ; but not target - it's not our child
8843 pn))
8844
8845 (defun js2-parse-with ()
8846 "Parser for with-statement. Last matched token must be js2-WITH."
8847 (let ((pos (js2-current-token-beg))
8848 obj body pn lp rp)
8849 (if (js2-must-match js2-LP "msg.no.paren.with")
8850 (setq lp (js2-current-token-beg)))
8851 (setq obj (js2-parse-expr))
8852 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8853 (setq rp (js2-current-token-beg)))
8854 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8855 (setq body (js2-parse-statement)))
8856 (setq pn (make-js2-with-node :pos pos
8857 :len (- (js2-node-end body) pos)
8858 :object obj
8859 :body body
8860 :lp (js2-relpos lp pos)
8861 :rp (js2-relpos rp pos)))
8862 (js2-node-add-children pn obj body)
8863 pn))
8864
8865 (defun js2-parse-const-var ()
8866 "Parser for var- or const-statement.
8867 Last matched token must be js2-CONST or js2-VAR."
8868 (let ((tt (js2-current-token-type))
8869 (pos (js2-current-token-beg))
8870 expr pn)
8871 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8872 pn (make-js2-expr-stmt-node :pos pos
8873 :len (- (js2-node-end expr) pos)
8874 :expr expr))
8875 (js2-node-add-children pn expr)
8876 pn))
8877
8878 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8879 (let ((pn (make-js2-expr-stmt-node :pos pos
8880 :len (js2-node-len expr)
8881 :type (if (js2-inside-function)
8882 js2-EXPR_VOID
8883 js2-EXPR_RESULT)
8884 :expr expr)))
8885 (if add-child
8886 (js2-node-add-children pn expr))
8887 pn))
8888
8889 (defun js2-parse-let-stmt ()
8890 "Parser for let-statement. Last matched token must be js2-LET."
8891 (let ((pos (js2-current-token-beg))
8892 expr pn)
8893 (if (= (js2-peek-token) js2-LP)
8894 ;; let expression in statement context
8895 (setq expr (js2-parse-let pos 'statement)
8896 pn (js2-wrap-with-expr-stmt pos expr t))
8897 ;; else we're looking at a statement like let x=6, y=7;
8898 (setf expr (js2-parse-variables js2-LET pos)
8899 pn (js2-wrap-with-expr-stmt pos expr t)
8900 (js2-node-type pn) js2-EXPR_RESULT))
8901 pn))
8902
8903 (defun js2-parse-ret-yield ()
8904 (js2-parse-return-or-yield (js2-current-token-type) nil))
8905
8906 (defconst js2-parse-return-stmt-enders
8907 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8908
8909 (defsubst js2-now-all-set (before after mask)
8910 "Return whether or not the bits in the mask have changed to all set.
8911 BEFORE is bits before change, AFTER is bits after change, and MASK is
8912 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8913 but not BEFORE."
8914 (and (/= (logand before mask) mask)
8915 (= (logand after mask) mask)))
8916
8917 (defun js2-parse-return-or-yield (tt expr-context)
8918 (let* ((pos (js2-current-token-beg))
8919 (end (js2-current-token-end))
8920 (before js2-end-flags)
8921 (inside-function (js2-inside-function))
8922 (gen-type (and inside-function (js2-function-node-generator-type
8923 js2-current-script-or-fn)))
8924 e ret name yield-star-p)
8925 (unless inside-function
8926 (js2-report-error (if (eq tt js2-RETURN)
8927 "msg.bad.return"
8928 "msg.bad.yield")))
8929 (when (and inside-function
8930 (eq gen-type 'STAR)
8931 (js2-match-token js2-MUL))
8932 (setq yield-star-p t))
8933 ;; This is ugly, but we don't want to require a semicolon.
8934 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8935 (setq e (js2-parse-expr)
8936 end (js2-node-end e)))
8937 (cond
8938 ((eq tt js2-RETURN)
8939 (js2-set-flag js2-end-flags (if (null e)
8940 js2-end-returns
8941 js2-end-returns-value))
8942 (setq ret (make-js2-return-node :pos pos
8943 :len (- end pos)
8944 :retval e))
8945 (js2-node-add-children ret e)
8946 ;; See if we need a strict mode warning.
8947 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8948 ;; more thorough and accurate than this before/after flag check.
8949 ;; E.g. if there's a finally-block that always returns, we shouldn't
8950 ;; show a warning generated by inconsistent returns in the catch blocks.
8951 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8952 ;; so we know which returns/yields to highlight, and we should get rid of
8953 ;; all the checking in `js2-parse-return-or-yield'.
8954 (if (and js2-strict-inconsistent-return-warning
8955 (js2-now-all-set before js2-end-flags
8956 (logior js2-end-returns js2-end-returns-value)))
8957 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8958 ((eq gen-type 'COMPREHENSION)
8959 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8960 ;; like SpiderMonkey does.
8961 (js2-report-error "msg.syntax" nil pos 5))
8962 (t
8963 (setq ret (make-js2-yield-node :pos pos
8964 :len (- end pos)
8965 :value e
8966 :star-p yield-star-p))
8967 (js2-node-add-children ret e)
8968 (unless expr-context
8969 (setq e ret
8970 ret (js2-wrap-with-expr-stmt pos e t))
8971 (js2-set-requires-activation)
8972 (js2-set-is-generator))))
8973 ;; see if we are mixing yields and value returns.
8974 (when (and inside-function
8975 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8976 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8977 'LEGACY))
8978 (setq name (js2-function-name js2-current-script-or-fn))
8979 (if (zerop (length name))
8980 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8981 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8982 ret))
8983
8984 (defun js2-parse-debugger ()
8985 (make-js2-keyword-node :type js2-DEBUGGER))
8986
8987 (defun js2-parse-block ()
8988 "Parser for a curly-delimited statement block.
8989 Last token matched must be `js2-LC'."
8990 (let ((pos (js2-current-token-beg))
8991 (pn (make-js2-scope)))
8992 (js2-push-scope pn)
8993 (unwind-protect
8994 (progn
8995 (js2-parse-statements pn)
8996 (js2-must-match js2-RC "msg.no.brace.block")
8997 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8998 (js2-pop-scope))
8999 pn))
9000
9001 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9002 (defun js2-parse-semi ()
9003 "Parse a statement or handle an error.
9004 Current token type is `js2-SEMI' or `js2-ERROR'."
9005 (let ((tt (js2-current-token-type)) pos len)
9006 (if (eq tt js2-SEMI)
9007 (make-js2-empty-expr-node :len 1)
9008 (setq pos (js2-current-token-beg)
9009 len (- (js2-current-token-end) pos))
9010 (js2-report-error "msg.syntax" nil pos len)
9011 (make-js2-error-node :pos pos :len len))))
9012
9013 (defun js2-parse-default-xml-namespace ()
9014 "Parse a `default xml namespace = <expr>' e4x statement."
9015 (let ((pos (js2-current-token-beg))
9016 end len expr unary)
9017 (js2-must-have-xml)
9018 (js2-set-requires-activation)
9019 (setq len (- js2-ts-cursor pos))
9020 (unless (and (js2-match-token js2-NAME)
9021 (string= (js2-current-token-string) "xml"))
9022 (js2-report-error "msg.bad.namespace" nil pos len))
9023 (unless (and (js2-match-token js2-NAME)
9024 (string= (js2-current-token-string) "namespace"))
9025 (js2-report-error "msg.bad.namespace" nil pos len))
9026 (unless (js2-match-token js2-ASSIGN)
9027 (js2-report-error "msg.bad.namespace" nil pos len))
9028 (setq expr (js2-parse-expr)
9029 end (js2-node-end expr)
9030 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9031 :pos pos
9032 :len (- end pos)
9033 :operand expr))
9034 (js2-node-add-children unary expr)
9035 (make-js2-expr-stmt-node :pos pos
9036 :len (- end pos)
9037 :expr unary)))
9038
9039 (defun js2-record-label (label bundle)
9040 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9041 (js2-get-token)
9042 (let ((name (js2-label-node-name label))
9043 labeled-stmt
9044 dup)
9045 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9046 ;; flag both labels if possible when used in editing mode
9047 (if (and js2-parse-ide-mode
9048 (setq dup (js2-get-label-by-name labeled-stmt name)))
9049 (js2-report-error "msg.dup.label" nil
9050 (js2-node-abs-pos dup) (js2-node-len dup)))
9051 (js2-report-error "msg.dup.label" nil
9052 (js2-node-pos label) (js2-node-len label)))
9053 (js2-labeled-stmt-node-add-label bundle label)
9054 (js2-node-add-children bundle label)
9055 ;; Add one reference to the bundle per label in `js2-label-set'
9056 (push (cons name bundle) js2-label-set)))
9057
9058 (defun js2-parse-name-or-label ()
9059 "Parser for identifier or label. Last token matched must be js2-NAME.
9060 Called when we found a name in a statement context. If it's a label, we gather
9061 up any following labels and the next non-label statement into a
9062 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9063 expression and return it wrapped in a `js2-expr-stmt-node'."
9064 (let ((pos (js2-current-token-beg))
9065 expr stmt bundle
9066 (continue t))
9067 ;; set check for label and call down to `js2-parse-primary-expr'
9068 (setq expr (js2-maybe-parse-label))
9069 (if (null expr)
9070 ;; Parse the non-label expression and wrap with expression stmt.
9071 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9072 ;; else parsed a label
9073 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9074 (js2-record-label expr bundle)
9075 ;; look for more labels
9076 (while (and continue (= (js2-get-token) js2-NAME))
9077 (if (setq expr (js2-maybe-parse-label))
9078 (js2-record-label expr bundle)
9079 (setq expr (js2-parse-expr)
9080 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9081 continue nil)
9082 (js2-auto-insert-semicolon stmt)))
9083 ;; no more labels; now parse the labeled statement
9084 (unwind-protect
9085 (unless stmt
9086 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9087 (js2-unget-token)
9088 (setq stmt (js2-statement-helper))))
9089 ;; remove the labels for this statement from the global set
9090 (dolist (label (js2-labeled-stmt-node-labels bundle))
9091 (setq js2-label-set (remove label js2-label-set))))
9092 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9093 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9094 (js2-node-add-children bundle stmt)
9095 bundle)))
9096
9097 (defun js2-maybe-parse-label ()
9098 (cl-assert (= (js2-current-token-type) js2-NAME))
9099 (let (label-pos
9100 (next-tt (js2-get-token))
9101 (label-end (js2-current-token-end)))
9102 ;; Do not consume colon, it is used as unwind indicator
9103 ;; to return to statementHelper.
9104 (js2-unget-token)
9105 (if (= next-tt js2-COLON)
9106 (prog2
9107 (setq label-pos (js2-current-token-beg))
9108 (make-js2-label-node :pos label-pos
9109 :len (- label-end label-pos)
9110 :name (js2-current-token-string))
9111 (js2-set-face label-pos
9112 label-end
9113 'font-lock-variable-name-face 'record))
9114 ;; Backtrack from the name token, too.
9115 (js2-unget-token)
9116 nil)))
9117
9118 (defun js2-parse-expr-stmt ()
9119 "Default parser in statement context, if no recognized statement found."
9120 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9121 (progn
9122 (js2-unget-token)
9123 (js2-parse-expr)) t))
9124
9125 (defun js2-parse-variables (decl-type pos)
9126 "Parse a comma-separated list of variable declarations.
9127 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9128
9129 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9130 For 'var' or 'const', the keyword should be the token last scanned.
9131
9132 POS is the position where the node should start. It's sometimes the
9133 var/const/let keyword, and other times the beginning of the first token
9134 in the first variable declaration.
9135
9136 Returns the parsed `js2-var-decl-node' expression node."
9137 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9138 :pos pos))
9139 destructuring kid-pos tt init name end nbeg nend vi
9140 (continue t))
9141 ;; Example:
9142 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9143 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9144 ;; var {a, b} = baz;
9145 (while continue
9146 (setq destructuring nil
9147 name nil
9148 tt (js2-get-token)
9149 kid-pos (js2-current-token-beg)
9150 end (js2-current-token-end)
9151 init nil)
9152 (if (or (= tt js2-LB) (= tt js2-LC))
9153 ;; Destructuring assignment, e.g., var [a, b] = ...
9154 (setq destructuring (js2-parse-destruct-primary-expr)
9155 end (js2-node-end destructuring))
9156 ;; Simple variable name
9157 (js2-unget-token)
9158 (when (js2-must-match-name "msg.bad.var")
9159 (setq name (js2-create-name-node)
9160 nbeg (js2-current-token-beg)
9161 nend (js2-current-token-end)
9162 end nend)
9163 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9164 (when (js2-match-token js2-ASSIGN)
9165 (setq init (js2-parse-assign-expr)
9166 end (js2-node-end init))
9167 (js2-record-imenu-functions init name))
9168 (when name
9169 (js2-set-face nbeg nend (if (js2-function-node-p init)
9170 'font-lock-function-name-face
9171 'font-lock-variable-name-face)
9172 'record))
9173 (setq vi (make-js2-var-init-node :pos kid-pos
9174 :len (- end kid-pos)
9175 :type decl-type))
9176 (if destructuring
9177 (progn
9178 (if (and (null init) (not js2-in-for-init))
9179 (js2-report-error "msg.destruct.assign.no.init"))
9180 (js2-define-destruct-symbols destructuring
9181 decl-type
9182 'font-lock-variable-name-face)
9183 (setf (js2-var-init-node-target vi) destructuring))
9184 (setf (js2-var-init-node-target vi) name))
9185 (setf (js2-var-init-node-initializer vi) init)
9186 (js2-node-add-children vi name destructuring init)
9187 (js2-block-node-push result vi)
9188 (unless (js2-match-token js2-COMMA)
9189 (setq continue nil)))
9190 (setf (js2-node-len result) (- end pos))
9191 result))
9192
9193 (defun js2-parse-let (pos &optional stmt-p)
9194 "Parse a let expression or statement.
9195 A let-expression is of the form `let (vars) expr'.
9196 A let-statement is of the form `let (vars) {statements}'.
9197 The third form of let is a variable declaration list, handled
9198 by `js2-parse-variables'."
9199 (let ((pn (make-js2-let-node :pos pos))
9200 beg vars body)
9201 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9202 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9203 (js2-push-scope pn)
9204 (unwind-protect
9205 (progn
9206 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9207 (if (js2-must-match js2-RP "msg.no.paren.let")
9208 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9209 (if (and stmt-p (js2-match-token js2-LC))
9210 ;; let statement
9211 (progn
9212 (setf beg (js2-current-token-beg) ; position stmt at LC
9213 body (js2-parse-statements))
9214 (js2-must-match js2-RC "msg.no.curly.let")
9215 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9216 (js2-node-len pn) (- (js2-current-token-end) pos)
9217 (js2-let-node-body pn) body
9218 (js2-node-type pn) js2-LET))
9219 ;; let expression
9220 (setf body (js2-parse-expr)
9221 (js2-node-len pn) (- (js2-node-end body) pos)
9222 (js2-let-node-body pn) body))
9223 (setf (js2-let-node-vars pn) vars)
9224 (js2-node-add-children pn vars body))
9225 (js2-pop-scope))
9226 pn))
9227
9228 (defun js2-define-new-symbol (decl-type name node &optional scope)
9229 (js2-scope-put-symbol (or scope js2-current-scope)
9230 name
9231 (make-js2-symbol decl-type name node)))
9232
9233 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9234 "Define a symbol in the current scope.
9235 If NODE is non-nil, it is the AST node associated with the symbol."
9236 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9237 (symbol (if defining-scope
9238 (js2-scope-get-symbol defining-scope name)))
9239 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9240 (pos (if node (js2-node-abs-pos node)))
9241 (len (if node (js2-node-len node))))
9242 (cond
9243 ((and symbol ; already defined
9244 (or (= sdt js2-CONST) ; old version is const
9245 (= decl-type js2-CONST) ; new version is const
9246 ;; two let-bound vars in this block have same name
9247 (and (= sdt js2-LET)
9248 (eq defining-scope js2-current-scope))))
9249 (js2-report-error
9250 (cond
9251 ((= sdt js2-CONST) "msg.const.redecl")
9252 ((= sdt js2-LET) "msg.let.redecl")
9253 ((= sdt js2-VAR) "msg.var.redecl")
9254 ((= sdt js2-FUNCTION) "msg.function.redecl")
9255 (t "msg.parm.redecl"))
9256 name pos len))
9257 ((= decl-type js2-LET)
9258 (if (and (not ignore-not-in-block)
9259 (or (= (js2-node-type js2-current-scope) js2-IF)
9260 (js2-loop-node-p js2-current-scope)))
9261 (js2-report-error "msg.let.decl.not.in.block")
9262 (js2-define-new-symbol decl-type name node)))
9263 ((or (= decl-type js2-VAR)
9264 (= decl-type js2-CONST)
9265 (= decl-type js2-FUNCTION))
9266 (if symbol
9267 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9268 (js2-add-strict-warning "msg.var.redecl" name)
9269 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9270 (js2-add-strict-warning "msg.var.hides.arg" name)))
9271 (js2-define-new-symbol decl-type name node
9272 js2-current-script-or-fn)))
9273 ((= decl-type js2-LP)
9274 (if symbol
9275 ;; must be duplicate parameter. Second parameter hides the
9276 ;; first, so go ahead and add the second pararameter
9277 (js2-report-warning "msg.dup.parms" name))
9278 (js2-define-new-symbol decl-type name node))
9279 (t (js2-code-bug)))))
9280
9281 (defun js2-parse-paren-expr-or-generator-comp ()
9282 (let ((px-pos (js2-current-token-beg)))
9283 (cond
9284 ((and (>= js2-language-version 200)
9285 (js2-match-token js2-FOR))
9286 (js2-parse-generator-comp px-pos))
9287 ((and (>= js2-language-version 200)
9288 (js2-match-token js2-RP))
9289 ;; Not valid expression syntax, but this is valid in an arrow
9290 ;; function with no params: () => body.
9291 (if (eq (js2-peek-token) js2-ARROW)
9292 ;; Return whatever, it will hopefully be rewinded and
9293 ;; reparsed when we reach the =>.
9294 (make-js2-keyword-node :type js2-NULL)
9295 (js2-report-error "msg.syntax")
9296 (make-js2-error-node)))
9297 (t
9298 (let* ((js2-in-for-init nil)
9299 (expr (js2-parse-expr))
9300 (pn (make-js2-paren-node :pos px-pos
9301 :expr expr)))
9302 (js2-node-add-children pn (js2-paren-node-expr pn))
9303 (js2-must-match js2-RP "msg.no.paren")
9304 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9305 pn)))))
9306
9307 (defun js2-parse-expr (&optional oneshot)
9308 (let* ((pn (js2-parse-assign-expr))
9309 (pos (js2-node-pos pn))
9310 left
9311 right
9312 op-pos)
9313 (while (and (not oneshot)
9314 (js2-match-token js2-COMMA))
9315 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9316 (if (= (js2-peek-token) js2-YIELD)
9317 (js2-report-error "msg.yield.parenthesized"))
9318 (setq right (js2-parse-assign-expr)
9319 left pn
9320 pn (make-js2-infix-node :type js2-COMMA
9321 :pos pos
9322 :len (- js2-ts-cursor pos)
9323 :op-pos op-pos
9324 :left left
9325 :right right))
9326 (js2-node-add-children pn left right))
9327 pn))
9328
9329 (defun js2-parse-assign-expr ()
9330 (let ((tt (js2-get-token))
9331 (pos (js2-current-token-beg))
9332 pn left right op-pos
9333 ts-state recorded-identifiers parsed-errors)
9334 (if (= tt js2-YIELD)
9335 (js2-parse-return-or-yield tt t)
9336 ;; Save the tokenizer state in case we find an arrow function
9337 ;; and have to rewind.
9338 (setq ts-state (make-js2-ts-state)
9339 recorded-identifiers js2-recorded-identifiers
9340 parsed-errors js2-parsed-errors)
9341 ;; not yield - parse assignment expression
9342 (setq pn (js2-parse-cond-expr)
9343 tt (js2-get-token))
9344 (cond
9345 ((and (<= js2-first-assign tt)
9346 (<= tt js2-last-assign))
9347 ;; tt express assignment (=, |=, ^=, ..., %=)
9348 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9349 left pn)
9350 (setq right (js2-parse-assign-expr)
9351 pn (make-js2-assign-node :type tt
9352 :pos pos
9353 :len (- (js2-node-end right) pos)
9354 :op-pos op-pos
9355 :left left
9356 :right right))
9357 (when js2-parse-ide-mode
9358 (js2-highlight-assign-targets pn left right)
9359 (js2-record-imenu-functions right left))
9360 ;; do this last so ide checks above can use absolute positions
9361 (js2-node-add-children pn left right))
9362 ((and (= tt js2-ARROW)
9363 (>= js2-language-version 200))
9364 (js2-ts-seek ts-state)
9365 (setq js2-recorded-identifiers recorded-identifiers
9366 js2-parsed-errors parsed-errors)
9367 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9368 (t
9369 (js2-unget-token)))
9370 pn)))
9371
9372 (defun js2-parse-cond-expr ()
9373 (let ((pos (js2-current-token-beg))
9374 (pn (js2-parse-or-expr))
9375 test-expr
9376 if-true
9377 if-false
9378 q-pos
9379 c-pos)
9380 (when (js2-match-token js2-HOOK)
9381 (setq q-pos (- (js2-current-token-beg) pos)
9382 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9383 (js2-must-match js2-COLON "msg.no.colon.cond")
9384 (setq c-pos (- (js2-current-token-beg) pos)
9385 if-false (js2-parse-assign-expr)
9386 test-expr pn
9387 pn (make-js2-cond-node :pos pos
9388 :len (- (js2-node-end if-false) pos)
9389 :test-expr test-expr
9390 :true-expr if-true
9391 :false-expr if-false
9392 :q-pos q-pos
9393 :c-pos c-pos))
9394 (js2-node-add-children pn test-expr if-true if-false))
9395 pn))
9396
9397 (defun js2-make-binary (type left parser)
9398 "Helper for constructing a binary-operator AST node.
9399 LEFT is the left-side-expression, already parsed, and the
9400 binary operator should have just been matched.
9401 PARSER is a function to call to parse the right operand,
9402 or a `js2-node' struct if it has already been parsed.
9403 FIXME: The latter option is unused?"
9404 (let* ((pos (js2-node-pos left))
9405 (op-pos (- (js2-current-token-beg) pos))
9406 (right (if (js2-node-p parser)
9407 parser
9408 (js2-get-token)
9409 (funcall parser)))
9410 (pn (make-js2-infix-node :type type
9411 :pos pos
9412 :len (- (js2-node-end right) pos)
9413 :op-pos op-pos
9414 :left left
9415 :right right)))
9416 (js2-node-add-children pn left right)
9417 pn))
9418
9419 (defun js2-parse-or-expr ()
9420 (let ((pn (js2-parse-and-expr)))
9421 (when (js2-match-token js2-OR)
9422 (setq pn (js2-make-binary js2-OR
9423 pn
9424 'js2-parse-or-expr)))
9425 pn))
9426
9427 (defun js2-parse-and-expr ()
9428 (let ((pn (js2-parse-bit-or-expr)))
9429 (when (js2-match-token js2-AND)
9430 (setq pn (js2-make-binary js2-AND
9431 pn
9432 'js2-parse-and-expr)))
9433 pn))
9434
9435 (defun js2-parse-bit-or-expr ()
9436 (let ((pn (js2-parse-bit-xor-expr)))
9437 (while (js2-match-token js2-BITOR)
9438 (setq pn (js2-make-binary js2-BITOR
9439 pn
9440 'js2-parse-bit-xor-expr)))
9441 pn))
9442
9443 (defun js2-parse-bit-xor-expr ()
9444 (let ((pn (js2-parse-bit-and-expr)))
9445 (while (js2-match-token js2-BITXOR)
9446 (setq pn (js2-make-binary js2-BITXOR
9447 pn
9448 'js2-parse-bit-and-expr)))
9449 pn))
9450
9451 (defun js2-parse-bit-and-expr ()
9452 (let ((pn (js2-parse-eq-expr)))
9453 (while (js2-match-token js2-BITAND)
9454 (setq pn (js2-make-binary js2-BITAND
9455 pn
9456 'js2-parse-eq-expr)))
9457 pn))
9458
9459 (defconst js2-parse-eq-ops
9460 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9461
9462 (defun js2-parse-eq-expr ()
9463 (let ((pn (js2-parse-rel-expr))
9464 tt)
9465 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9466 (setq pn (js2-make-binary tt
9467 pn
9468 'js2-parse-rel-expr)))
9469 (js2-unget-token)
9470 pn))
9471
9472 (defconst js2-parse-rel-ops
9473 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9474
9475 (defun js2-parse-rel-expr ()
9476 (let ((pn (js2-parse-shift-expr))
9477 (continue t)
9478 tt)
9479 (while continue
9480 (setq tt (js2-get-token))
9481 (cond
9482 ((and js2-in-for-init (= tt js2-IN))
9483 (js2-unget-token)
9484 (setq continue nil))
9485 ((memq tt js2-parse-rel-ops)
9486 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9487 (t
9488 (js2-unget-token)
9489 (setq continue nil))))
9490 pn))
9491
9492 (defconst js2-parse-shift-ops
9493 (list js2-LSH js2-URSH js2-RSH))
9494
9495 (defun js2-parse-shift-expr ()
9496 (let ((pn (js2-parse-add-expr))
9497 tt
9498 (continue t))
9499 (while continue
9500 (setq tt (js2-get-token))
9501 (if (memq tt js2-parse-shift-ops)
9502 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9503 (js2-unget-token)
9504 (setq continue nil)))
9505 pn))
9506
9507 (defun js2-parse-add-expr ()
9508 (let ((pn (js2-parse-mul-expr))
9509 tt
9510 (continue t))
9511 (while continue
9512 (setq tt (js2-get-token))
9513 (if (or (= tt js2-ADD) (= tt js2-SUB))
9514 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9515 (js2-unget-token)
9516 (setq continue nil)))
9517 pn))
9518
9519 (defconst js2-parse-mul-ops
9520 (list js2-MUL js2-DIV js2-MOD))
9521
9522 (defun js2-parse-mul-expr ()
9523 (let ((pn (js2-parse-unary-expr))
9524 tt
9525 (continue t))
9526 (while continue
9527 (setq tt (js2-get-token))
9528 (if (memq tt js2-parse-mul-ops)
9529 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9530 (js2-unget-token)
9531 (setq continue nil)))
9532 pn))
9533
9534 (defun js2-make-unary (type parser &rest args)
9535 "Make a unary node of type TYPE.
9536 PARSER is either a node (for postfix operators) or a function to call
9537 to parse the operand (for prefix operators)."
9538 (let* ((pos (js2-current-token-beg))
9539 (postfix (js2-node-p parser))
9540 (expr (if postfix
9541 parser
9542 (apply parser args)))
9543 end
9544 pn)
9545 (if postfix ; e.g. i++
9546 (setq pos (js2-node-pos expr)
9547 end (js2-current-token-end))
9548 (setq end (js2-node-end expr)))
9549 (setq pn (make-js2-unary-node :type type
9550 :pos pos
9551 :len (- end pos)
9552 :operand expr))
9553 (js2-node-add-children pn expr)
9554 pn))
9555
9556 (defconst js2-incrementable-node-types
9557 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9558 "Node types that can be the operand of a ++ or -- operator.")
9559
9560 (defun js2-check-bad-inc-dec (tt beg end unary)
9561 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9562 js2-incrementable-node-types)
9563 (js2-report-error (if (= tt js2-INC)
9564 "msg.bad.incr"
9565 "msg.bad.decr")
9566 nil beg (- end beg))))
9567
9568 (defun js2-parse-unary-expr ()
9569 (let ((tt (js2-current-token-type))
9570 pn expr beg end)
9571 (cond
9572 ((or (= tt js2-VOID)
9573 (= tt js2-NOT)
9574 (= tt js2-BITNOT)
9575 (= tt js2-TYPEOF))
9576 (js2-get-token)
9577 (js2-make-unary tt 'js2-parse-unary-expr))
9578 ((= tt js2-ADD)
9579 (js2-get-token)
9580 ;; Convert to special POS token in decompiler and parse tree
9581 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9582 ((= tt js2-SUB)
9583 (js2-get-token)
9584 ;; Convert to special NEG token in decompiler and parse tree
9585 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9586 ((or (= tt js2-INC)
9587 (= tt js2-DEC))
9588 (js2-get-token)
9589 (prog1
9590 (setq beg (js2-current-token-beg)
9591 end (js2-current-token-end)
9592 expr (js2-make-unary tt 'js2-parse-member-expr t))
9593 (js2-check-bad-inc-dec tt beg end expr)))
9594 ((= tt js2-DELPROP)
9595 (js2-get-token)
9596 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9597 ((= tt js2-ERROR)
9598 (js2-get-token)
9599 (make-js2-error-node)) ; try to continue
9600 ((and (= tt js2-LT)
9601 js2-compiler-xml-available)
9602 ;; XML stream encountered in expression.
9603 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9604 (t
9605 (setq pn (js2-parse-member-expr t)
9606 ;; Don't look across a newline boundary for a postfix incop.
9607 tt (js2-peek-token-or-eol))
9608 (when (or (= tt js2-INC) (= tt js2-DEC))
9609 (js2-get-token)
9610 (setf expr pn
9611 pn (js2-make-unary tt expr))
9612 (js2-node-set-prop pn 'postfix t)
9613 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9614 pn))))
9615
9616 (defun js2-parse-xml-initializer ()
9617 "Parse an E4X XML initializer.
9618 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9619 Then I'll postprocess the result, depending on whether we're in IDE
9620 mode or codegen mode, and generate the appropriate rewritten AST.
9621 IDE mode uses a rich AST that models the XML structure. Codegen mode
9622 just concatenates everything and makes a new XML or XMLList out of it."
9623 (let ((tt (js2-get-first-xml-token))
9624 pn-xml pn expr kids expr-pos
9625 (continue t)
9626 (first-token t))
9627 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9628 (js2-report-error "msg.syntax"))
9629 (setq pn-xml (make-js2-xml-node))
9630 (while continue
9631 (if first-token
9632 (setq first-token nil)
9633 (setq tt (js2-get-next-xml-token)))
9634 (cond
9635 ;; js2-XML means we found a {expr} in the XML stream.
9636 ;; The token string is the XML up to the left-curly.
9637 ((= tt js2-XML)
9638 (push (make-js2-string-node :pos (js2-current-token-beg)
9639 :len (- js2-ts-cursor (js2-current-token-beg)))
9640 kids)
9641 (js2-must-match js2-LC "msg.syntax")
9642 (setq expr-pos js2-ts-cursor
9643 expr (if (eq (js2-peek-token) js2-RC)
9644 (make-js2-empty-expr-node :pos expr-pos)
9645 (js2-parse-expr)))
9646 (js2-must-match js2-RC "msg.syntax")
9647 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9648 :len (js2-node-len expr)
9649 :expr expr))
9650 (js2-node-add-children pn expr)
9651 (push pn kids))
9652 ;; a js2-XMLEND token means we hit the final close-tag.
9653 ((= tt js2-XMLEND)
9654 (push (make-js2-string-node :pos (js2-current-token-beg)
9655 :len (- js2-ts-cursor (js2-current-token-beg)))
9656 kids)
9657 (dolist (kid (nreverse kids))
9658 (js2-block-node-push pn-xml kid))
9659 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9660 (js2-node-pos pn-xml))
9661 continue nil))
9662 (t
9663 (js2-report-error "msg.syntax")
9664 (setq continue nil))))
9665 pn-xml))
9666
9667
9668 (defun js2-parse-argument-list ()
9669 "Parse an argument list and return it as a Lisp list of nodes.
9670 Returns the list in reverse order. Consumes the right-paren token."
9671 (let (result)
9672 (unless (js2-match-token js2-RP)
9673 (cl-loop do
9674 (let ((tt (js2-get-token)))
9675 (if (= tt js2-YIELD)
9676 (js2-report-error "msg.yield.parenthesized"))
9677 (if (and (= tt js2-TRIPLEDOT)
9678 (>= js2-language-version 200))
9679 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9680 (js2-unget-token)
9681 (push (js2-parse-assign-expr) result)))
9682 while
9683 (js2-match-token js2-COMMA))
9684 (js2-must-match js2-RP "msg.no.paren.arg")
9685 result)))
9686
9687 (defun js2-parse-member-expr (&optional allow-call-syntax)
9688 (let ((tt (js2-current-token-type))
9689 pn pos target args beg end init)
9690 (if (/= tt js2-NEW)
9691 (setq pn (js2-parse-primary-expr))
9692 ;; parse a 'new' expression
9693 (js2-get-token)
9694 (setq pos (js2-current-token-beg)
9695 beg pos
9696 target (js2-parse-member-expr)
9697 end (js2-node-end target)
9698 pn (make-js2-new-node :pos pos
9699 :target target
9700 :len (- end pos)))
9701 (js2-highlight-function-call (js2-current-token))
9702 (js2-node-add-children pn target)
9703 (when (js2-match-token js2-LP)
9704 ;; Add the arguments to pn, if any are supplied.
9705 (setf beg pos ; start of "new" keyword
9706 pos (js2-current-token-beg)
9707 args (nreverse (js2-parse-argument-list))
9708 (js2-new-node-args pn) args
9709 end (js2-current-token-end)
9710 (js2-new-node-lp pn) (- pos beg)
9711 (js2-new-node-rp pn) (- end 1 beg))
9712 (apply #'js2-node-add-children pn args))
9713 (when (and js2-allow-rhino-new-expr-initializer
9714 (js2-match-token js2-LC))
9715 (setf init (js2-parse-object-literal)
9716 end (js2-node-end init)
9717 (js2-new-node-initializer pn) init)
9718 (js2-node-add-children pn init))
9719 (setf (js2-node-len pn) (- end beg))) ; end outer if
9720 (js2-parse-member-expr-tail allow-call-syntax pn)))
9721
9722 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9723 "Parse a chain of property/array accesses or function calls.
9724 Includes parsing for E4X operators like `..' and `.@'.
9725 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9726 Returns an expression tree that includes PN, the parent node."
9727 (let (tt
9728 (continue t))
9729 (while continue
9730 (setq tt (js2-get-token))
9731 (cond
9732 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9733 (setq pn (js2-parse-property-access tt pn)))
9734 ((= tt js2-DOTQUERY)
9735 (setq pn (js2-parse-dot-query pn)))
9736 ((= tt js2-LB)
9737 (setq pn (js2-parse-element-get pn)))
9738 ((= tt js2-LP)
9739 (js2-unget-token)
9740 (if allow-call-syntax
9741 (setq pn (js2-parse-function-call pn))
9742 (setq continue nil)))
9743 ((= tt js2-TEMPLATE_HEAD)
9744 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9745 ((= tt js2-NO_SUBS_TEMPLATE)
9746 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9747 (t
9748 (js2-unget-token)
9749 (setq continue nil))))
9750 (if (>= js2-highlight-level 2)
9751 (js2-parse-highlight-member-expr-node pn))
9752 pn))
9753
9754 (defun js2-parse-tagged-template (tag-node tpl-node)
9755 "Parse tagged template expression."
9756 (let* ((beg (js2-node-pos tag-node))
9757 (pn (make-js2-tagged-template-node :beg beg
9758 :len (- (js2-current-token-end) beg)
9759 :tag tag-node
9760 :template tpl-node)))
9761 (js2-node-add-children pn tag-node tpl-node)
9762 pn))
9763
9764 (defun js2-parse-dot-query (pn)
9765 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9766 Last token parsed must be `js2-DOTQUERY'."
9767 (let ((pos (js2-node-pos pn))
9768 op-pos expr end)
9769 (js2-must-have-xml)
9770 (js2-set-requires-activation)
9771 (setq op-pos (js2-current-token-beg)
9772 expr (js2-parse-expr)
9773 end (js2-node-end expr)
9774 pn (make-js2-xml-dot-query-node :left pn
9775 :pos pos
9776 :op-pos op-pos
9777 :right expr))
9778 (js2-node-add-children pn
9779 (js2-xml-dot-query-node-left pn)
9780 (js2-xml-dot-query-node-right pn))
9781 (if (js2-must-match js2-RP "msg.no.paren")
9782 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9783 end (js2-current-token-end)))
9784 (setf (js2-node-len pn) (- end pos))
9785 pn))
9786
9787 (defun js2-parse-element-get (pn)
9788 "Parse an element-get expression, e.g. foo[bar].
9789 Last token parsed must be `js2-RB'."
9790 (let ((lb (js2-current-token-beg))
9791 (pos (js2-node-pos pn))
9792 rb expr)
9793 (setq expr (js2-parse-expr))
9794 (if (js2-must-match js2-RB "msg.no.bracket.index")
9795 (setq rb (js2-current-token-beg)))
9796 (setq pn (make-js2-elem-get-node :target pn
9797 :pos pos
9798 :element expr
9799 :lb (js2-relpos lb pos)
9800 :rb (js2-relpos rb pos)
9801 :len (- (js2-current-token-end) pos)))
9802 (js2-node-add-children pn
9803 (js2-elem-get-node-target pn)
9804 (js2-elem-get-node-element pn))
9805 pn))
9806
9807 (defun js2-highlight-function-call (token)
9808 (when (eq (js2-token-type token) js2-NAME)
9809 (js2-record-face 'js2-function-call token)))
9810
9811 (defun js2-parse-function-call (pn)
9812 (js2-highlight-function-call (js2-current-token))
9813 (js2-get-token)
9814 (let (args
9815 (pos (js2-node-pos pn)))
9816 (setq pn (make-js2-call-node :pos pos
9817 :target pn
9818 :lp (- (js2-current-token-beg) pos)))
9819 (js2-node-add-children pn (js2-call-node-target pn))
9820 ;; Add the arguments to pn, if any are supplied.
9821 (setf args (nreverse (js2-parse-argument-list))
9822 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9823 (js2-call-node-args pn) args)
9824 (apply #'js2-node-add-children pn args)
9825 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9826 pn))
9827
9828 (defun js2-parse-property-access (tt pn)
9829 "Parse a property access, XML descendants access, or XML attr access."
9830 (let ((member-type-flags 0)
9831 (dot-pos (js2-current-token-beg))
9832 (dot-len (if (= tt js2-DOTDOT) 2 1))
9833 name
9834 ref ; right side of . or .. operator
9835 result)
9836 (when (= tt js2-DOTDOT)
9837 (js2-must-have-xml)
9838 (setq member-type-flags js2-descendants-flag))
9839 (if (not js2-compiler-xml-available)
9840 (progn
9841 (js2-must-match-prop-name "msg.no.name.after.dot")
9842 (setq name (js2-create-name-node t js2-GETPROP)
9843 result (make-js2-prop-get-node :left pn
9844 :pos (js2-current-token-beg)
9845 :right name
9846 :len (js2-current-token-len)))
9847 (js2-node-add-children result pn name)
9848 result)
9849 ;; otherwise look for XML operators
9850 (setf result (if (= tt js2-DOT)
9851 (make-js2-prop-get-node)
9852 (make-js2-infix-node :type js2-DOTDOT))
9853 (js2-node-pos result) (js2-node-pos pn)
9854 (js2-infix-node-op-pos result) dot-pos
9855 (js2-infix-node-left result) pn ; do this after setting position
9856 tt (js2-get-prop-name-token))
9857 (cond
9858 ;; handles: name, ns::name, ns::*, ns::[expr]
9859 ((= tt js2-NAME)
9860 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9861 ;; handles: *, *::name, *::*, *::[expr]
9862 ((= tt js2-MUL)
9863 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9864 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9865 ((= tt js2-XMLATTR)
9866 (setq result (js2-parse-attribute-access)))
9867 (t
9868 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9869 (if ref
9870 (setf (js2-node-len result) (- (js2-node-end ref)
9871 (js2-node-pos result))
9872 (js2-infix-node-right result) ref))
9873 (if (js2-infix-node-p result)
9874 (js2-node-add-children result
9875 (js2-infix-node-left result)
9876 (js2-infix-node-right result)))
9877 result)))
9878
9879 (defun js2-parse-attribute-access ()
9880 "Parse an E4X XML attribute expression.
9881 This includes expressions of the forms:
9882
9883 @attr @ns::attr @ns::*
9884 @* @*::attr @*::*
9885 @[expr] @*::[expr] @ns::[expr]
9886
9887 Called if we peeked an '@' token."
9888 (let ((tt (js2-get-prop-name-token))
9889 (at-pos (js2-current-token-beg)))
9890 (cond
9891 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9892 ((= tt js2-NAME)
9893 (js2-parse-property-name at-pos nil 0))
9894 ;; handles: @*, @*::name, @*::*, @*::[expr]
9895 ((= tt js2-MUL)
9896 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9897 ;; handles @[expr]
9898 ((= tt js2-LB)
9899 (js2-parse-xml-elem-ref at-pos))
9900 (t
9901 (js2-report-error "msg.no.name.after.xmlAttr")
9902 ;; Avoid cascaded errors that happen if we make an error node here.
9903 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9904
9905 (defun js2-parse-property-name (at-pos s member-type-flags)
9906 "Check if :: follows name in which case it becomes qualified name.
9907
9908 AT-POS is a natural number if we just read an '@' token, else nil.
9909 S is the name or string that was matched: an identifier, 'throw' or '*'.
9910 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9911
9912 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9913 operator, or the name is followed by ::. For a plain name, returns a
9914 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9915 (let ((pos (or at-pos (js2-current-token-beg)))
9916 colon-pos
9917 (name (js2-create-name-node t (js2-current-token-type) s))
9918 ns tt pn)
9919 (catch 'return
9920 (when (js2-match-token js2-COLONCOLON)
9921 (setq ns name
9922 colon-pos (js2-current-token-beg)
9923 tt (js2-get-prop-name-token))
9924 (cond
9925 ;; handles name::name
9926 ((= tt js2-NAME)
9927 (setq name (js2-create-name-node)))
9928 ;; handles name::*
9929 ((= tt js2-MUL)
9930 (setq name (js2-create-name-node nil nil "*")))
9931 ;; handles name::[expr]
9932 ((= tt js2-LB)
9933 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9934 (t
9935 (js2-report-error "msg.no.name.after.coloncolon"))))
9936 (if (and (null ns) (zerop member-type-flags))
9937 name
9938 (prog1
9939 (setq pn
9940 (make-js2-xml-prop-ref-node :pos pos
9941 :len (- (js2-node-end name) pos)
9942 :at-pos at-pos
9943 :colon-pos colon-pos
9944 :propname name))
9945 (js2-node-add-children pn name))))))
9946
9947 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9948 "Parse the [expr] portion of an xml element reference.
9949 For instance, @[expr], @*::[expr], or ns::[expr]."
9950 (let* ((lb (js2-current-token-beg))
9951 (pos (or at-pos lb))
9952 rb
9953 (expr (js2-parse-expr))
9954 (end (js2-node-end expr))
9955 pn)
9956 (if (js2-must-match js2-RB "msg.no.bracket.index")
9957 (setq rb (js2-current-token-beg)
9958 end (js2-current-token-end)))
9959 (prog1
9960 (setq pn
9961 (make-js2-xml-elem-ref-node :pos pos
9962 :len (- end pos)
9963 :namespace namespace
9964 :colon-pos colon-pos
9965 :at-pos at-pos
9966 :expr expr
9967 :lb (js2-relpos lb pos)
9968 :rb (js2-relpos rb pos)))
9969 (js2-node-add-children pn namespace expr))))
9970
9971 (defun js2-parse-destruct-primary-expr ()
9972 (let ((js2-is-in-destructuring t))
9973 (js2-parse-primary-expr)))
9974
9975 (defun js2-parse-primary-expr ()
9976 "Parse a literal (leaf) expression of some sort.
9977 Includes complex literals such as functions, object-literals,
9978 array-literals, array comprehensions and regular expressions."
9979 (let (tt)
9980 (setq tt (js2-current-token-type))
9981 (cond
9982 ((= tt js2-CLASS)
9983 (js2-parse-class-expr))
9984 ((= tt js2-FUNCTION)
9985 (js2-parse-function-expr))
9986 ((= tt js2-LB)
9987 (js2-parse-array-comp-or-literal))
9988 ((= tt js2-LC)
9989 (js2-parse-object-literal))
9990 ((= tt js2-LET)
9991 (js2-parse-let (js2-current-token-beg)))
9992 ((= tt js2-LP)
9993 (js2-parse-paren-expr-or-generator-comp))
9994 ((= tt js2-XMLATTR)
9995 (js2-must-have-xml)
9996 (js2-parse-attribute-access))
9997 ((= tt js2-NAME)
9998 (js2-parse-name tt))
9999 ((= tt js2-NUMBER)
10000 (make-js2-number-node))
10001 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10002 (make-js2-string-node :type tt))
10003 ((= tt js2-TEMPLATE_HEAD)
10004 (js2-parse-template-literal))
10005 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10006 ;; Got / or /= which in this context means a regexp literal
10007 (let ((px-pos (js2-current-token-beg))
10008 (flags (js2-read-regexp tt))
10009 (end (js2-current-token-end)))
10010 (prog1
10011 (make-js2-regexp-node :pos px-pos
10012 :len (- end px-pos)
10013 :value (js2-current-token-string)
10014 :flags flags)
10015 (js2-set-face px-pos end 'font-lock-string-face 'record)
10016 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10017 ((or (= tt js2-NULL)
10018 (= tt js2-THIS)
10019 (= tt js2-SUPER)
10020 (= tt js2-FALSE)
10021 (= tt js2-TRUE))
10022 (make-js2-keyword-node :type tt))
10023 ((= tt js2-TRIPLEDOT)
10024 ;; Likewise, only valid in an arrow function with a rest param.
10025 (if (and (js2-match-token js2-NAME)
10026 (js2-match-token js2-RP)
10027 (eq (js2-peek-token) js2-ARROW))
10028 (progn
10029 (js2-unget-token) ; Put back the right paren.
10030 ;; See the previous case.
10031 (make-js2-keyword-node :type js2-NULL))
10032 (js2-report-error "msg.syntax")
10033 (make-js2-error-node)))
10034 ((= tt js2-RESERVED)
10035 (js2-report-error "msg.reserved.id")
10036 (make-js2-name-node))
10037 ((= tt js2-ERROR)
10038 ;; the scanner or one of its subroutines reported the error.
10039 (make-js2-error-node))
10040 ((= tt js2-EOF)
10041 (let* ((px-pos (point-at-bol))
10042 (len (- js2-ts-cursor px-pos)))
10043 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10044 (make-js2-error-node :pos (1- js2-ts-cursor)))
10045 (t
10046 (js2-report-error "msg.syntax")
10047 (make-js2-error-node)))))
10048
10049 (defun js2-parse-template-literal ()
10050 (let ((beg (js2-current-token-beg))
10051 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10052 (tt js2-TEMPLATE_HEAD))
10053 (while (eq tt js2-TEMPLATE_HEAD)
10054 (push (js2-parse-expr) kids)
10055 (js2-must-match js2-RC "msg.syntax")
10056 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10057 (push (make-js2-string-node :type tt) kids))
10058 (setq kids (nreverse kids))
10059 (let ((tpl (make-js2-template-node :beg beg
10060 :len (- (js2-current-token-end) beg)
10061 :kids kids)))
10062 (apply #'js2-node-add-children tpl kids)
10063 tpl)))
10064
10065 (defun js2-parse-name (_tt)
10066 (let ((name (js2-current-token-string))
10067 node)
10068 (setq node (if js2-compiler-xml-available
10069 (js2-parse-property-name nil name 0)
10070 (js2-create-name-node 'check-activation nil name)))
10071 (if js2-highlight-external-variables
10072 (js2-record-name-node node))
10073 node))
10074
10075 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10076 (js2-add-strict-warning
10077 msg nil
10078 ;; back up from comma to beginning of line or array/objlit
10079 (max (if elems
10080 (js2-node-pos (car elems))
10081 pos)
10082 (save-excursion
10083 (goto-char comma-pos)
10084 (back-to-indentation)
10085 (point)))
10086 comma-pos))
10087
10088 (defun js2-parse-array-comp-or-literal ()
10089 (let ((pos (js2-current-token-beg)))
10090 (if (and (>= js2-language-version 200)
10091 (js2-match-token js2-FOR))
10092 (js2-parse-array-comp pos)
10093 (js2-parse-array-literal pos))))
10094
10095 (defun js2-parse-array-literal (pos)
10096 (let ((after-lb-or-comma t)
10097 after-comma tt elems pn
10098 (continue t))
10099 (unless js2-is-in-destructuring
10100 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10101 (while continue
10102 (setq tt (js2-get-token))
10103 (cond
10104 ;; comma
10105 ((= tt js2-COMMA)
10106 (setq after-comma (js2-current-token-end))
10107 (if (not after-lb-or-comma)
10108 (setq after-lb-or-comma t)
10109 (push nil elems)))
10110 ;; end of array
10111 ((or (= tt js2-RB)
10112 (= tt js2-EOF)) ; prevent infinite loop
10113 (if (= tt js2-EOF)
10114 (js2-report-error "msg.no.bracket.arg" nil pos))
10115 (when (and after-comma (< js2-language-version 170))
10116 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10117 pos (remove nil elems) after-comma))
10118 (setq continue nil
10119 pn (make-js2-array-node :pos pos
10120 :len (- js2-ts-cursor pos)
10121 :elems (nreverse elems)))
10122 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10123 ;; destructuring binding
10124 (js2-is-in-destructuring
10125 (push (if (or (= tt js2-LC)
10126 (= tt js2-LB)
10127 (= tt js2-NAME))
10128 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10129 (js2-parse-destruct-primary-expr)
10130 ;; invalid pattern
10131 (js2-report-error "msg.bad.var")
10132 (make-js2-error-node))
10133 elems)
10134 (setq after-lb-or-comma nil
10135 after-comma nil))
10136 ;; array comp
10137 ((and (>= js2-language-version 170)
10138 (= tt js2-FOR) ; check for array comprehension
10139 (not after-lb-or-comma) ; "for" can't follow a comma
10140 elems ; must have at least 1 element
10141 (not (cdr elems))) ; but no 2nd element
10142 (js2-unget-token)
10143 (setf continue nil
10144 pn (js2-parse-legacy-array-comp (car elems) pos)))
10145 ;; another element
10146 (t
10147 (unless after-lb-or-comma
10148 (js2-report-error "msg.no.bracket.arg"))
10149 (if (and (= tt js2-TRIPLEDOT)
10150 (>= js2-language-version 200))
10151 ;; spread operator
10152 (push (js2-make-unary tt 'js2-parse-assign-expr)
10153 elems)
10154 (js2-unget-token)
10155 (push (js2-parse-assign-expr) elems))
10156 (setq after-lb-or-comma nil
10157 after-comma nil))))
10158 (unless js2-is-in-destructuring
10159 (js2-pop-scope))
10160 pn))
10161
10162 (defun js2-parse-legacy-array-comp (expr pos)
10163 "Parse a legacy array comprehension (JavaScript 1.7).
10164 EXPR is the first expression after the opening left-bracket.
10165 POS is the beginning of the LB token preceding EXPR.
10166 We should have just parsed the 'for' keyword before calling this function."
10167 (let ((current-scope js2-current-scope)
10168 loops filter result)
10169 (unwind-protect
10170 (progn
10171 (while (js2-match-token js2-FOR)
10172 (let ((loop (make-js2-comp-loop-node)))
10173 (js2-push-scope loop)
10174 (push loop loops)
10175 (js2-parse-comp-loop loop)))
10176 ;; First loop takes expr scope's parent.
10177 (setf (js2-scope-parent-scope (car (last loops)))
10178 (js2-scope-parent-scope current-scope))
10179 ;; Set expr scope's parent to the last loop.
10180 (setf (js2-scope-parent-scope current-scope) (car loops))
10181 (if (/= (js2-get-token) js2-IF)
10182 (js2-unget-token)
10183 (setq filter (js2-parse-condition))))
10184 (dotimes (_ (1- (length loops)))
10185 (js2-pop-scope)))
10186 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10187 (setq result (make-js2-comp-node :pos pos
10188 :len (- js2-ts-cursor pos)
10189 :result expr
10190 :loops (nreverse loops)
10191 :filters (and filter (list (car filter)))
10192 :form 'LEGACY_ARRAY))
10193 ;; Set comp loop's parent to the last loop.
10194 ;; TODO: Get rid of the bogus expr scope.
10195 (setf (js2-scope-parent-scope result) first)
10196 (apply #'js2-node-add-children result expr (car filter)
10197 (js2-comp-node-loops result))
10198 result))
10199
10200 (defun js2-parse-array-comp (pos)
10201 "Parse an ES6 array comprehension.
10202 POS is the beginning of the LB token.
10203 We should have just parsed the 'for' keyword before calling this function."
10204 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10205 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10206 pn))
10207
10208 (defun js2-parse-generator-comp (pos)
10209 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10210 (js2-current-script-or-fn
10211 (make-js2-function-node :generator-type 'COMPREHENSION))
10212 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10213 (js2-must-match js2-RP "msg.no.paren" pos)
10214 pn))
10215
10216 (defun js2-parse-comprehension (pos form)
10217 (let (loops filters expr result)
10218 (unwind-protect
10219 (progn
10220 (js2-unget-token)
10221 (while (js2-match-token js2-FOR)
10222 (let ((loop (make-js2-comp-loop-node)))
10223 (js2-push-scope loop)
10224 (push loop loops)
10225 (js2-parse-comp-loop loop)))
10226 (while (js2-match-token js2-IF)
10227 (push (car (js2-parse-condition)) filters))
10228 (setq expr (js2-parse-assign-expr)))
10229 (dolist (_ loops)
10230 (js2-pop-scope)))
10231 (setq result (make-js2-comp-node :pos pos
10232 :len (- js2-ts-cursor pos)
10233 :result expr
10234 :loops (nreverse loops)
10235 :filters (nreverse filters)
10236 :form form))
10237 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10238 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10239 result))
10240
10241 (defun js2-parse-comp-loop (pn &optional only-of-p)
10242 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10243 The current token should be the initial FOR.
10244 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10245 (let ((pos (js2-comp-loop-node-pos pn))
10246 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10247 (when (and (not only-of-p) (js2-match-token js2-NAME))
10248 (if (string= (js2-current-token-string) "each")
10249 (progn
10250 (setq foreach-p t
10251 each-pos (- (js2-current-token-beg) pos)) ; relative
10252 (js2-record-face 'font-lock-keyword-face))
10253 (js2-report-error "msg.no.paren.for")))
10254 (if (js2-must-match js2-LP "msg.no.paren.for")
10255 (setq lp (- (js2-current-token-beg) pos)))
10256 (setq tt (js2-peek-token))
10257 (cond
10258 ((or (= tt js2-LB)
10259 (= tt js2-LC))
10260 (js2-get-token)
10261 (setq iter (js2-parse-destruct-primary-expr))
10262 (js2-define-destruct-symbols iter js2-LET
10263 'font-lock-variable-name-face t))
10264 ((js2-match-token js2-NAME)
10265 (setq iter (js2-create-name-node)))
10266 (t
10267 (js2-report-error "msg.bad.var")))
10268 ;; Define as a let since we want the scope of the variable to
10269 ;; be restricted to the array comprehension
10270 (if (js2-name-node-p iter)
10271 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10272 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10273 (and (>= js2-language-version 200)
10274 (js2-match-contextual-kwd "of")
10275 (setq forof-p t)))
10276 (setq in-pos (- (js2-current-token-beg) pos))
10277 (js2-report-error "msg.in.after.for.name"))
10278 (setq obj (js2-parse-expr))
10279 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10280 (setq rp (- (js2-current-token-beg) pos)))
10281 (setf (js2-node-pos pn) pos
10282 (js2-node-len pn) (- js2-ts-cursor pos)
10283 (js2-comp-loop-node-iterator pn) iter
10284 (js2-comp-loop-node-object pn) obj
10285 (js2-comp-loop-node-in-pos pn) in-pos
10286 (js2-comp-loop-node-each-pos pn) each-pos
10287 (js2-comp-loop-node-foreach-p pn) foreach-p
10288 (js2-comp-loop-node-forof-p pn) forof-p
10289 (js2-comp-loop-node-lp pn) lp
10290 (js2-comp-loop-node-rp pn) rp)
10291 (js2-node-add-children pn iter obj)
10292 pn))
10293
10294 (defun js2-parse-class-stmt ()
10295 (let ((pos (js2-current-token-beg))
10296 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10297 (name (js2-create-name-node t)))
10298 (js2-set-face (js2-node-pos name) (js2-node-end name)
10299 'font-lock-function-name-face 'record)
10300 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10301 (js2-define-symbol js2-FUNCTION
10302 (js2-name-node-name name)
10303 node)
10304 node)))
10305
10306 (defun js2-parse-class-expr ()
10307 (let ((pos (js2-current-token-beg))
10308 name)
10309 (when (js2-match-token js2-NAME)
10310 (setq name (js2-create-name-node t)))
10311 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10312
10313 (defun js2-parse-class (pos form name)
10314 ;; class X [extends ...] {
10315 (let (pn elems extends)
10316 (if (js2-match-token js2-EXTENDS)
10317 (if (= (js2-peek-token) js2-LC)
10318 (js2-report-error "msg.missing.extends")
10319 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10320 (setq extends (js2-parse-assign-expr))
10321 (if (not extends)
10322 (js2-report-error "msg.bad.extends"))))
10323 (js2-must-match js2-LC "msg.no.brace.class")
10324 (setq elems (js2-parse-object-literal-elems t)
10325 pn (make-js2-class-node :pos pos
10326 :len (- js2-ts-cursor pos)
10327 :form form
10328 :name name
10329 :extends extends
10330 :elems elems))
10331 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10332 pn))
10333
10334 (defun js2-parse-object-literal ()
10335 (let* ((pos (js2-current-token-beg))
10336 (elems (js2-parse-object-literal-elems))
10337 (result (make-js2-object-node :pos pos
10338 :len (- js2-ts-cursor pos)
10339 :elems elems)))
10340 (apply #'js2-node-add-children result (js2-object-node-elems result))
10341 result))
10342
10343 (defun js2-parse-object-literal-elems (&optional class-p)
10344 (let ((pos (js2-current-token-beg))
10345 (static nil)
10346 (continue t)
10347 tt elems elem after-comma)
10348 (while continue
10349 (setq tt (js2-get-prop-name-token)
10350 static nil
10351 elem nil)
10352 (when (and class-p (= js2-NAME tt)
10353 (string= "static" (js2-current-token-string)))
10354 (js2-record-face 'font-lock-keyword-face)
10355 (setq static t
10356 tt (js2-get-prop-name-token)))
10357 (cond
10358 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
10359 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
10360 ;; TODO(sdh): support *foo() {...}
10361 ((or (= js2-NAME tt)
10362 (= tt js2-STRING))
10363 (setq after-comma nil
10364 elem (js2-parse-named-prop tt))
10365 (if (and (null elem)
10366 (not js2-recover-from-parse-errors))
10367 (setq continue nil)))
10368 ;; {[Symbol.iterator]: ...}
10369 ((and (= tt js2-LB)
10370 (>= js2-language-version 200))
10371 (let ((expr (js2-parse-expr)))
10372 (js2-must-match js2-RB "msg.missing.computed.rb")
10373 (setq after-comma nil
10374 elem (js2-parse-plain-property expr))))
10375 ;; {12: x} or {10.7: x}
10376 ((= tt js2-NUMBER)
10377 (setq after-comma nil
10378 elem (js2-parse-plain-property (make-js2-number-node))))
10379 ;; Break out of loop, and handle trailing commas.
10380 ((or (= tt js2-RC)
10381 (= tt js2-EOF))
10382 (js2-unget-token)
10383 (setq continue nil)
10384 (if after-comma
10385 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10386 pos elems after-comma)))
10387 (t
10388 (js2-report-error "msg.bad.prop")
10389 (unless js2-recover-from-parse-errors
10390 (setq continue nil)))) ; end switch
10391 ;; Handle static for classes' codegen.
10392 (if static
10393 (if elem (js2-node-set-prop elem 'STATIC t)
10394 (js2-report-error "msg.unexpected.static")))
10395 ;; Handle commas, depending on class-p.
10396 (let ((tok (js2-get-prop-name-token)))
10397 (if (eq tok js2-COMMA)
10398 (if class-p
10399 (js2-report-error "msg.class.unexpected.comma")
10400 (setq after-comma (js2-current-token-end)))
10401 (js2-unget-token)
10402 (unless class-p (setq continue nil))))
10403 ;; Append any parsed element.
10404 (if elem (push elem elems))) ; end loop
10405 (js2-must-match js2-RC "msg.no.brace.prop")
10406 (nreverse elems)))
10407
10408 (defun js2-parse-named-prop (tt)
10409 "Parse a name, string, or getter/setter object property.
10410 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10411 (let ((string-prop (and (= tt js2-STRING)
10412 (make-js2-string-node)))
10413 expr
10414 (ppos (js2-current-token-beg))
10415 (pend (js2-current-token-end))
10416 (name (js2-create-name-node))
10417 (prop (js2-current-token-string)))
10418 (cond
10419 ;; getter/setter prop
10420 ((and (= tt js2-NAME)
10421 (= (js2-peek-token) js2-NAME)
10422 (or (string= prop "get")
10423 (string= prop "set")))
10424 (js2-get-token)
10425 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
10426 (js2-record-face 'font-lock-function-name-face) ; for peeked name
10427 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
10428 (js2-parse-getter-setter-prop ppos name prop))
10429 ;; method definition: {f() {...}}
10430 ((and (= (js2-peek-token) js2-LP)
10431 (>= js2-language-version 200))
10432 (js2-record-face 'font-lock-function-name-face) ; name
10433 (js2-parse-getter-setter-prop ppos name ""))
10434 ;; regular prop
10435 (t
10436 (prog1
10437 (setq expr (js2-parse-plain-property (or string-prop name)))
10438 (when (and (not string-prop)
10439 (not js2-is-in-destructuring)
10440 js2-highlight-external-variables
10441 (js2-node-get-prop expr 'SHORTHAND))
10442 (js2-record-name-node name))
10443 (js2-set-face ppos pend
10444 (if (js2-function-node-p
10445 (js2-object-prop-node-right expr))
10446 'font-lock-function-name-face
10447 'font-lock-variable-name-face)
10448 'record))))))
10449
10450 (defun js2-parse-plain-property (prop)
10451 "Parse a non-getter/setter property in an object literal.
10452 PROP is the node representing the property: a number, name or string."
10453 (let* ((tt (js2-get-token))
10454 (pos (js2-node-pos prop))
10455 colon expr result)
10456 (cond
10457 ;; Abbreviated property, as in {foo, bar}
10458 ((and (>= js2-language-version 200)
10459 (or (= tt js2-COMMA)
10460 (= tt js2-RC))
10461 (not (js2-number-node-p prop)))
10462 (js2-unget-token)
10463 (setq result (make-js2-object-prop-node
10464 :pos pos
10465 :left prop
10466 :right prop
10467 :op-pos (js2-current-token-len)))
10468 (js2-node-add-children result prop)
10469 (js2-node-set-prop result 'SHORTHAND t)
10470 result)
10471 ;; Normal property
10472 (t
10473 (if (= tt js2-COLON)
10474 (setq colon (- (js2-current-token-beg) pos)
10475 expr (js2-parse-assign-expr))
10476 (js2-report-error "msg.no.colon.prop")
10477 (setq expr (make-js2-error-node)))
10478 (setq result (make-js2-object-prop-node
10479 :pos pos
10480 ;; don't include last consumed token in length
10481 :len (- (+ (js2-node-pos expr)
10482 (js2-node-len expr))
10483 pos)
10484 :left prop
10485 :right expr
10486 :op-pos colon))
10487 (js2-node-add-children result prop expr)
10488 result))))
10489
10490 (defun js2-parse-getter-setter-prop (pos prop type-string)
10491 "Parse getter or setter property in an object literal.
10492 JavaScript syntax is:
10493
10494 { get foo() {...}, set foo(x) {...} }
10495
10496 and expression closure style is also supported
10497
10498 { get foo() x, set foo(x) _x = x }
10499
10500 POS is the start position of the `get' or `set' keyword.
10501 PROP is the `js2-name-node' representing the property name.
10502 GET-P is non-nil if the keyword was `get'."
10503 (let ((type (cond
10504 ((string= "get" type-string) js2-GET)
10505 ((string= "set" type-string) js2-SET)
10506 (t js2-FUNCTION)))
10507 result end
10508 (fn (js2-parse-function-expr)))
10509 ;; it has to be an anonymous function, as we already parsed the name
10510 (if (/= (js2-node-type fn) js2-FUNCTION)
10511 (js2-report-error "msg.bad.prop")
10512 (if (cl-plusp (length (js2-function-name fn)))
10513 (js2-report-error "msg.bad.prop")))
10514 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10515 (setq end (js2-node-end fn)
10516 result (make-js2-getter-setter-node :type type
10517 :pos pos
10518 :len (- end pos)
10519 :left prop
10520 :right fn))
10521 (js2-node-add-children result prop fn)
10522 result))
10523
10524 (defun js2-create-name-node (&optional check-activation-p token string)
10525 "Create a name node using the current token and, optionally, STRING.
10526 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10527 (let* ((beg (js2-current-token-beg))
10528 (tt (js2-current-token-type))
10529 (s (or string
10530 (if (= js2-NAME tt)
10531 (js2-current-token-string)
10532 (js2-tt-name tt))))
10533 name)
10534 (setq name (make-js2-name-node :pos beg
10535 :name s
10536 :len (length s)))
10537 (if check-activation-p
10538 (js2-check-activation-name s (or token js2-NAME)))
10539 name))
10540
10541 ;;; Indentation support
10542
10543 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10544 ;; Karl cleverly deduces that the desired indentation level is often a
10545 ;; function of paren/bracket/brace nesting depth, which can be determined
10546 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10547 ;; then does some equally clever checks to see if we're in the context of a
10548 ;; substatement of a possibly braceless statement keyword such as if, while,
10549 ;; or finally. This approach yields pretty good results.
10550
10551 ;; The indenter is often "wrong", however, and needs to be overridden.
10552 ;; The right long-term solution is probably to emulate (or integrate
10553 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10554 ;; parse tree from `js2-parse' is present, which is not true at the
10555 ;; moment the user is typing, computing indentation is still thousands
10556 ;; of lines of code to handle every possible syntactic edge case.
10557
10558 ;; In the meantime, the compromise solution is that we offer a "bounce
10559 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10560 ;; current line indent among various likely guess points. This approach
10561 ;; is far from perfect, but should at least make it slightly easier to
10562 ;; move the line towards its desired indentation when manually
10563 ;; overriding Karl's heuristic nesting guesser.
10564
10565 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10566 ;; extensions such as `let' and Array comprehensions. Major kudos to
10567 ;; Karl for coming up with the initial approach, which packs a lot of
10568 ;; punch for so little code.
10569
10570 (defconst js2-possibly-braceless-keywords-re
10571 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10572 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10573 "try" "while" "with" "let")))
10574 "Regular expression matching keywords that are optionally
10575 followed by an opening brace.")
10576
10577 (defconst js2-indent-operator-re
10578 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10579 (regexp-opt '("in" "instanceof") 'words))
10580 "Regular expression matching operators that affect indentation
10581 of continued expressions.")
10582
10583 (defconst js2-declaration-keyword-re
10584 (regexp-opt '("var" "let" "const") 'words)
10585 "Regular expression matching variable declaration keywords.")
10586
10587 (defun js2-re-search-forward-inner (regexp &optional bound count)
10588 "Auxiliary function for `js2-re-search-forward'."
10589 (let (parse saved-point)
10590 (while (> count 0)
10591 (re-search-forward regexp bound)
10592 (setq parse (if saved-point
10593 (parse-partial-sexp saved-point (point))
10594 (syntax-ppss (point))))
10595 (cond ((nth 3 parse)
10596 (re-search-forward
10597 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10598 (save-excursion (end-of-line) (point)) t))
10599 ((nth 7 parse)
10600 (forward-line))
10601 ((or (nth 4 parse)
10602 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10603 (re-search-forward "\\*/"))
10604 (t
10605 (setq count (1- count))))
10606 (setq saved-point (point))))
10607 (point))
10608
10609 (defun js2-re-search-forward (regexp &optional bound noerror count)
10610 "Search forward but ignore strings and comments.
10611 Invokes `re-search-forward' but treats the buffer as if strings
10612 and comments have been removed."
10613 (let ((saved-point (point)))
10614 (condition-case err
10615 (cond ((null count)
10616 (js2-re-search-forward-inner regexp bound 1))
10617 ((< count 0)
10618 (js2-re-search-backward-inner regexp bound (- count)))
10619 ((> count 0)
10620 (js2-re-search-forward-inner regexp bound count)))
10621 (search-failed
10622 (goto-char saved-point)
10623 (unless noerror
10624 (error (error-message-string err)))))))
10625
10626 (defun js2-re-search-backward-inner (regexp &optional bound count)
10627 "Auxiliary function for `js2-re-search-backward'."
10628 (let (parse)
10629 (while (> count 0)
10630 (re-search-backward regexp bound)
10631 (setq parse (syntax-ppss (point)))
10632 (cond ((nth 3 parse)
10633 (re-search-backward
10634 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10635 (line-beginning-position) t))
10636 ((nth 7 parse)
10637 (goto-char (nth 8 parse)))
10638 ((or (nth 4 parse)
10639 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10640 (re-search-backward "/\\*"))
10641 (t
10642 (setq count (1- count))))))
10643 (point))
10644
10645 (defun js2-re-search-backward (regexp &optional bound noerror count)
10646 "Search backward but ignore strings and comments.
10647 Invokes `re-search-backward' but treats the buffer as if strings
10648 and comments have been removed."
10649 (let ((saved-point (point)))
10650 (condition-case err
10651 (cond ((null count)
10652 (js2-re-search-backward-inner regexp bound 1))
10653 ((< count 0)
10654 (js2-re-search-forward-inner regexp bound (- count)))
10655 ((> count 0)
10656 (js2-re-search-backward-inner regexp bound count)))
10657 (search-failed
10658 (goto-char saved-point)
10659 (unless noerror
10660 (error (error-message-string err)))))))
10661
10662 (defun js2-looking-at-operator-p ()
10663 "Return non-nil if text after point is a non-comma operator."
10664 (and (looking-at js2-indent-operator-re)
10665 (or (not (looking-at ":"))
10666 (save-excursion
10667 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10668 (looking-at "?"))))))
10669
10670 (defun js2-continued-expression-p ()
10671 "Return non-nil if the current line continues an expression."
10672 (save-excursion
10673 (back-to-indentation)
10674 (or (js2-looking-at-operator-p)
10675 (when (catch 'found
10676 (while (and (re-search-backward "\n" nil t)
10677 (let ((state (syntax-ppss)))
10678 (when (nth 4 state)
10679 (goto-char (nth 8 state))) ;; skip comments
10680 (skip-chars-backward " \t")
10681 (if (bolp)
10682 t
10683 (throw 'found t))))))
10684 (backward-char)
10685 (when (js2-looking-at-operator-p)
10686 (backward-char)
10687 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10688
10689 (defun js2-end-of-do-while-loop-p ()
10690 "Return non-nil if word after point is `while' of a do-while
10691 statement, else returns nil. A braceless do-while statement
10692 spanning several lines requires that the start of the loop is
10693 indented to the same column as the current line."
10694 (interactive)
10695 (save-excursion
10696 (when (looking-at "\\s-*\\<while\\>")
10697 (if (save-excursion
10698 (skip-chars-backward "[ \t\n]*}")
10699 (looking-at "[ \t\n]*}"))
10700 (save-excursion
10701 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10702 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10703 (or (looking-at "\\<do\\>")
10704 (let ((saved-indent (current-indentation)))
10705 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10706 (/= (current-indentation) saved-indent)))
10707 (and (looking-at "[ \t]*\\<do\\>")
10708 (not (js2-re-search-forward
10709 "\\<while\\>" (point-at-eol) t))
10710 (= (current-indentation) saved-indent))))))))
10711
10712 (defun js2-multiline-decl-indentation ()
10713 "Return the declaration indentation column if the current line belongs
10714 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10715 (let (forward-sexp-function ; use Lisp version
10716 at-opening-bracket)
10717 (save-excursion
10718 (back-to-indentation)
10719 (when (not (looking-at js2-declaration-keyword-re))
10720 (when (looking-at js2-indent-operator-re)
10721 (goto-char (match-end 0))) ; continued expressions are ok
10722 (while (and (not at-opening-bracket)
10723 (not (bobp))
10724 (let ((pos (point)))
10725 (save-excursion
10726 (js2-backward-sws)
10727 (or (eq (char-before) ?,)
10728 (and (not (eq (char-before) ?\;))
10729 (prog2 (skip-syntax-backward ".")
10730 (looking-at js2-indent-operator-re)
10731 (js2-backward-sws))
10732 (not (eq (char-before) ?\;)))
10733 (js2-same-line pos)))))
10734 (condition-case _
10735 (backward-sexp)
10736 (scan-error (setq at-opening-bracket t))))
10737 (when (looking-at js2-declaration-keyword-re)
10738 (goto-char (match-end 0))
10739 (1+ (current-column)))))))
10740
10741 (defun js2-ctrl-statement-indentation ()
10742 "Return the proper indentation of current line if it is a control statement.
10743 Returns an indentation if this line starts the body of a control
10744 statement without braces, else returns nil."
10745 (let (forward-sexp-function)
10746 (save-excursion
10747 (back-to-indentation)
10748 (when (and (not (js2-same-line (point-min)))
10749 (not (looking-at "{"))
10750 (js2-re-search-backward "[[:graph:]]" nil t)
10751 (not (looking-at "[{([]"))
10752 (progn
10753 (forward-char)
10754 (when (= (char-before) ?\))
10755 ;; scan-sexps sometimes throws an error
10756 (ignore-errors (backward-sexp))
10757 (skip-chars-backward " \t" (point-at-bol)))
10758 (let ((pt (point)))
10759 (back-to-indentation)
10760 (when (looking-at "}[ \t]*")
10761 (goto-char (match-end 0)))
10762 (and (looking-at js2-possibly-braceless-keywords-re)
10763 (= (match-end 0) pt)
10764 (not (js2-end-of-do-while-loop-p))))))
10765 (+ (current-indentation) js2-basic-offset)))))
10766
10767 (defun js2-indent-in-array-comp (parse-status)
10768 "Return non-nil if we think we're in an array comprehension.
10769 In particular, return the buffer position of the first `for' kwd."
10770 (let ((bracket (nth 1 parse-status))
10771 (end (point)))
10772 (when bracket
10773 (save-excursion
10774 (goto-char bracket)
10775 (when (looking-at "\\[")
10776 (forward-char 1)
10777 (js2-forward-sws)
10778 (if (looking-at "[[{]")
10779 (let (forward-sexp-function) ; use Lisp version
10780 (forward-sexp) ; skip destructuring form
10781 (js2-forward-sws)
10782 (if (and (/= (char-after) ?,) ; regular array
10783 (looking-at "for"))
10784 (match-beginning 0)))
10785 ;; to skip arbitrary expressions we need the parser,
10786 ;; so we'll just guess at it.
10787 (if (and (> end (point)) ; not empty literal
10788 (re-search-forward "[^,]]* \\(for\\) " end t)
10789 ;; not inside comment or string literal
10790 (let ((state (parse-partial-sexp bracket (point))))
10791 (not (or (nth 3 state) (nth 4 state)))))
10792 (match-beginning 1))))))))
10793
10794 (defun js2-array-comp-indentation (parse-status for-kwd)
10795 (if (js2-same-line for-kwd)
10796 ;; first continuation line
10797 (save-excursion
10798 (goto-char (nth 1 parse-status))
10799 (forward-char 1)
10800 (skip-chars-forward " \t")
10801 (current-column))
10802 (save-excursion
10803 (goto-char for-kwd)
10804 (current-column))))
10805
10806 (defun js2-maybe-goto-declaration-keyword-end (bracket)
10807 "Helper function for `js2-proper-indentation'.
10808 Depending on the value of `js2-pretty-multiline-declarations',
10809 move point to the end of a variable declaration keyword so that
10810 indentation is aligned to that column."
10811 (cond
10812 ((eq js2-pretty-multiline-declarations 'all)
10813 (when (looking-at js2-declaration-keyword-re)
10814 (goto-char (1+ (match-end 0)))))
10815 ((eq js2-pretty-multiline-declarations 'dynamic)
10816 (let (declaration-keyword-end
10817 at-closing-bracket-p
10818 comma-p)
10819 (when (looking-at js2-declaration-keyword-re)
10820 ;; Preserve the match data lest it somehow be overridden.
10821 (setq declaration-keyword-end (match-end 0))
10822 (save-excursion
10823 (goto-char bracket)
10824 (setq at-closing-bracket-p
10825 ;; Handle scan errors gracefully.
10826 (condition-case nil
10827 (progn
10828 ;; Use the regular `forward-sexp-function' because the
10829 ;; normal one for this mode uses the AST.
10830 (let (forward-sexp-function)
10831 (forward-sexp))
10832 t)
10833 (error nil)))
10834 (when at-closing-bracket-p
10835 (js2-forward-sws)
10836 (setq comma-p (looking-at-p ","))))
10837 (when comma-p
10838 (goto-char (1+ declaration-keyword-end))))))))
10839
10840 (defun js2-proper-indentation (parse-status)
10841 "Return the proper indentation for the current line."
10842 (save-excursion
10843 (back-to-indentation)
10844 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10845 (at-closing-bracket (looking-at "[]})]"))
10846 (same-indent-p (or at-closing-bracket
10847 (looking-at "\\<case\\>[^:]")
10848 (and (looking-at "\\<default:")
10849 (save-excursion
10850 (js2-backward-sws)
10851 (not (memq (char-before) '(?, ?{)))))))
10852 (continued-expr-p (js2-continued-expression-p))
10853 (declaration-indent (and js2-pretty-multiline-declarations
10854 (js2-multiline-decl-indentation)))
10855 (bracket (nth 1 parse-status))
10856 beg indent)
10857 (cond
10858 ;; indent array comprehension continuation lines specially
10859 ((and bracket
10860 (>= js2-language-version 170)
10861 (not (js2-same-line bracket))
10862 (setq beg (js2-indent-in-array-comp parse-status))
10863 (>= (point) (save-excursion
10864 (goto-char beg)
10865 (point-at-bol)))) ; at or after first loop?
10866 (js2-array-comp-indentation parse-status beg))
10867
10868 (ctrl-stmt-indent)
10869
10870 ((and declaration-indent continued-expr-p)
10871 (+ declaration-indent js2-basic-offset))
10872
10873 (declaration-indent)
10874
10875 (bracket
10876 (goto-char bracket)
10877 (cond
10878 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10879 (when (save-excursion (skip-chars-backward " \t)")
10880 (looking-at ")"))
10881 (backward-list))
10882 (back-to-indentation)
10883 (js2-maybe-goto-declaration-keyword-end bracket)
10884 (setq indent
10885 (cond (same-indent-p
10886 (current-column))
10887 (continued-expr-p
10888 (+ (current-column) (* 2 js2-basic-offset)))
10889 (t
10890 (+ (current-column) js2-basic-offset))))
10891 (if (and js2-indent-switch-body
10892 (not at-closing-bracket)
10893 (looking-at "\\_<switch\\_>"))
10894 (+ indent js2-basic-offset)
10895 indent))
10896 (t
10897 (unless same-indent-p
10898 (forward-char)
10899 (skip-chars-forward " \t"))
10900 (current-column))))
10901
10902 (continued-expr-p js2-basic-offset)
10903
10904 (t 0)))))
10905
10906 (defun js2-lineup-comment (parse-status)
10907 "Indent a multi-line block comment continuation line."
10908 (let* ((beg (nth 8 parse-status))
10909 (first-line (js2-same-line beg))
10910 (offset (save-excursion
10911 (goto-char beg)
10912 (if (looking-at "/\\*")
10913 (+ 1 (current-column))
10914 0))))
10915 (unless first-line
10916 (indent-line-to offset))))
10917
10918 (defun js2-backward-sws ()
10919 "Move backward through whitespace and comments."
10920 (interactive)
10921 (while (forward-comment -1)))
10922
10923 (defun js2-forward-sws ()
10924 "Move forward through whitespace and comments."
10925 (interactive)
10926 (while (forward-comment 1)))
10927
10928 (defun js2-current-indent (&optional pos)
10929 "Return column of indentation on current line.
10930 If POS is non-nil, go to that point and return indentation for that line."
10931 (save-excursion
10932 (if pos
10933 (goto-char pos))
10934 (back-to-indentation)
10935 (current-column)))
10936
10937 (defun js2-arglist-close ()
10938 "Return non-nil if we're on a line beginning with a close-paren/brace."
10939 (save-excursion
10940 (goto-char (point-at-bol))
10941 (js2-forward-sws)
10942 (looking-at "[])}]")))
10943
10944 (defun js2-indent-looks-like-label-p ()
10945 (goto-char (point-at-bol))
10946 (js2-forward-sws)
10947 (looking-at (concat js2-mode-identifier-re ":")))
10948
10949 (defun js2-indent-in-objlit-p (parse-status)
10950 "Return non-nil if this looks like an object-literal entry."
10951 (let ((start (nth 1 parse-status)))
10952 (and
10953 start
10954 (save-excursion
10955 (and (zerop (forward-line -1))
10956 (not (< (point) start)) ; crossed a {} boundary
10957 (js2-indent-looks-like-label-p)))
10958 (save-excursion
10959 (js2-indent-looks-like-label-p)))))
10960
10961 ;; If prev line looks like foobar({ then we're passing an object
10962 ;; literal to a function call, and people pretty much always want to
10963 ;; de-dent back to the previous line, so move the 'basic-offset'
10964 ;; position to the front.
10965 (defun js2-indent-objlit-arg-p (parse-status)
10966 (save-excursion
10967 (back-to-indentation)
10968 (js2-backward-sws)
10969 (and (eq (1- (point)) (nth 1 parse-status))
10970 (eq (char-before) ?{)
10971 (progn
10972 (forward-char -1)
10973 (skip-chars-backward " \t")
10974 (eq (char-before) ?\()))))
10975
10976 (defun js2-indent-case-block-p ()
10977 (save-excursion
10978 (back-to-indentation)
10979 (js2-backward-sws)
10980 (goto-char (point-at-bol))
10981 (skip-chars-forward " \t")
10982 (looking-at "case\\s-.+:")))
10983
10984 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10985 "Cycle among alternate computed indentation positions.
10986 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10987 of the buffer to the current point. NORMAL-COL is the indentation
10988 column computed by the heuristic guesser based on current paren,
10989 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10990 in reverse."
10991 (let ((cur-indent (js2-current-indent))
10992 (old-buffer-undo-list buffer-undo-list)
10993 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10994 (current-line (save-excursion
10995 (forward-line 0) ; move to bol
10996 (1+ (count-lines (point-min) (point)))))
10997 positions pos main-pos anchor arglist-cont same-indent
10998 basic-offset computed-pos)
10999 ;; temporarily don't record undo info, if user requested this
11000 (when js2-mode-indent-inhibit-undo
11001 (setq buffer-undo-list t))
11002 (unwind-protect
11003 (progn
11004 ;; First likely point: indent from beginning of previous code line
11005 (push (setq basic-offset
11006 (+ (save-excursion
11007 (back-to-indentation)
11008 (js2-backward-sws)
11009 (back-to-indentation)
11010 (current-column))
11011 js2-basic-offset))
11012 positions)
11013
11014 ;; (First + epsilon) likely point: indent 2x from beginning of
11015 ;; previous code line. Google does it this way.
11016 (push (setq basic-offset
11017 (+ (save-excursion
11018 (back-to-indentation)
11019 (js2-backward-sws)
11020 (back-to-indentation)
11021 (current-column))
11022 (* 2 js2-basic-offset)))
11023 positions)
11024
11025 ;; Second likely point: indent from assign-expr RHS. This
11026 ;; is just a crude guess based on finding " = " on the previous
11027 ;; line containing actual code.
11028 (setq pos (save-excursion
11029 (forward-line -1)
11030 (goto-char (point-at-bol))
11031 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11032 (point-at-eol) t)
11033 (goto-char (match-end 1))
11034 (skip-chars-forward " \t\r\n")
11035 (current-column))))
11036 (when pos
11037 (cl-incf pos js2-basic-offset)
11038 (push pos positions))
11039
11040 ;; Third likely point: same indent as previous line of code.
11041 ;; Make it the first likely point if we're not on an
11042 ;; arglist-close line and previous line ends in a comma, or
11043 ;; both this line and prev line look like object-literal
11044 ;; elements.
11045 (setq pos (save-excursion
11046 (goto-char (point-at-bol))
11047 (js2-backward-sws)
11048 (back-to-indentation)
11049 (prog1
11050 (current-column)
11051 ;; while we're here, look for trailing comma
11052 (if (save-excursion
11053 (goto-char (point-at-eol))
11054 (js2-backward-sws)
11055 (eq (char-before) ?,))
11056 (setq arglist-cont (1- (point)))))))
11057 (when pos
11058 (if (and (or arglist-cont
11059 (js2-indent-in-objlit-p parse-status))
11060 (not (js2-arglist-close)))
11061 (setq same-indent pos))
11062 (push pos positions))
11063
11064 ;; Fourth likely point: first preceding code with less indentation.
11065 ;; than the immediately preceding code line.
11066 (setq pos (save-excursion
11067 (back-to-indentation)
11068 (js2-backward-sws)
11069 (back-to-indentation)
11070 (setq anchor (current-column))
11071 (while (and (zerop (forward-line -1))
11072 (>= (progn
11073 (back-to-indentation)
11074 (current-column))
11075 anchor)))
11076 (setq pos (current-column))))
11077 (push pos positions)
11078
11079 ;; nesting-heuristic position, main by default
11080 (push (setq main-pos normal-col) positions)
11081
11082 ;; delete duplicates and sort positions list
11083 (setq positions (sort (delete-dups positions) '<))
11084
11085 ;; comma-list continuation lines: prev line indent takes precedence
11086 (if same-indent
11087 (setq main-pos same-indent))
11088
11089 ;; common special cases where we want to indent in from previous line
11090 (if (or (js2-indent-case-block-p)
11091 (js2-indent-objlit-arg-p parse-status))
11092 (setq main-pos basic-offset))
11093
11094 ;; if bouncing backwards, reverse positions list
11095 (if backwards
11096 (setq positions (reverse positions)))
11097
11098 ;; record whether we're already sitting on one of the alternatives
11099 (setq pos (member cur-indent positions))
11100
11101 (cond
11102 ;; case 0: we're one one of the alternatives and this is the
11103 ;; first time they've pressed TAB on this line (best-guess).
11104 ((and js2-mode-indent-ignore-first-tab
11105 pos
11106 ;; first time pressing TAB on this line?
11107 (not (eq js2-mode-last-indented-line current-line)))
11108 ;; do nothing
11109 (setq computed-pos nil))
11110 ;; case 1: only one computed position => use it
11111 ((null (cdr positions))
11112 (setq computed-pos 0))
11113 ;; case 2: not on any of the computed spots => use main spot
11114 ((not pos)
11115 (setq computed-pos (js2-position main-pos positions)))
11116 ;; case 3: on last position: cycle to first position
11117 ((null (cdr pos))
11118 (setq computed-pos 0))
11119 ;; case 4: on intermediate position: cycle to next position
11120 (t
11121 (setq computed-pos (js2-position (cl-second pos) positions))))
11122
11123 ;; see if any hooks want to indent; otherwise we do it
11124 (cl-loop with result = nil
11125 for hook in js2-indent-hook
11126 while (null result)
11127 do
11128 (setq result (funcall hook positions computed-pos))
11129 finally do
11130 (unless (or result (null computed-pos))
11131 (indent-line-to (nth computed-pos positions)))))
11132
11133 ;; finally
11134 (if js2-mode-indent-inhibit-undo
11135 (setq buffer-undo-list old-buffer-undo-list))
11136 ;; see commentary for `js2-mode-last-indented-line'
11137 (setq js2-mode-last-indented-line current-line))))
11138
11139 (defun js2-indent-bounce-backwards ()
11140 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11141 cycles between the computed indentation positions in reverse order."
11142 (interactive)
11143 (js2-indent-line t))
11144
11145 (defun js2-1-line-comment-continuation-p ()
11146 "Return t if we're in a 1-line comment continuation.
11147 If so, we don't ever want to use bounce-indent."
11148 (save-excursion
11149 (and (progn
11150 (forward-line 0)
11151 (looking-at "\\s-*//"))
11152 (progn
11153 (forward-line -1)
11154 (forward-line 0)
11155 (when (looking-at "\\s-*$")
11156 (js2-backward-sws)
11157 (forward-line 0))
11158 (looking-at "\\s-*//")))))
11159
11160 (defun js2-indent-line (&optional bounce-backwards)
11161 "Indent the current line as JavaScript source text."
11162 (interactive)
11163 (let (parse-status offset indent-col
11164 ;; Don't whine about errors/warnings when we're indenting.
11165 ;; This has to be set before calling parse-partial-sexp below.
11166 (inhibit-point-motion-hooks t))
11167 (setq parse-status (save-excursion
11168 (syntax-ppss (point-at-bol)))
11169 offset (- (point) (save-excursion
11170 (back-to-indentation)
11171 (point))))
11172 ;; Don't touch multiline strings.
11173 (unless (nth 3 parse-status)
11174 (js2-with-underscore-as-word-syntax
11175 (if (nth 4 parse-status)
11176 (js2-lineup-comment parse-status)
11177 (setq indent-col (js2-proper-indentation parse-status))
11178 ;; See comments below about `js2-mode-last-indented-line'.
11179 (cond
11180 ;; bounce-indenting is disabled during electric-key indent.
11181 ;; It doesn't work well on first line of buffer.
11182 ((and js2-bounce-indent-p
11183 (not (js2-same-line (point-min)))
11184 (not (js2-1-line-comment-continuation-p)))
11185 (js2-bounce-indent indent-col parse-status bounce-backwards))
11186 ;; just indent to the guesser's likely spot
11187 (t (indent-line-to indent-col))))
11188 (when (cl-plusp offset)
11189 (forward-char offset))))))
11190
11191 (defun js2-indent-region (start end)
11192 "Indent the region, but don't use bounce indenting."
11193 (let ((js2-bounce-indent-p nil)
11194 (indent-region-function nil)
11195 (after-change-functions (remq 'js2-mode-edit
11196 after-change-functions)))
11197 (indent-region start end nil) ; nil for byte-compiler
11198 (js2-mode-edit start end (- end start))))
11199
11200 (defvar js2-minor-mode-map
11201 (let ((map (make-sparse-keymap)))
11202 (define-key map (kbd "C-c C-`") #'js2-next-error)
11203 (define-key map [mouse-1] #'js2-mode-show-node)
11204 map)
11205 "Keymap used when `js2-minor-mode' is active.")
11206
11207 ;;;###autoload
11208 (define-minor-mode js2-minor-mode
11209 "Minor mode for running js2 as a background linter.
11210 This allows you to use a different major mode for JavaScript editing,
11211 such as `js-mode', while retaining the asynchronous error/warning
11212 highlighting features of `js2-mode'."
11213 :group 'js2-mode
11214 :lighter " js-lint"
11215 (if js2-minor-mode
11216 (js2-minor-mode-enter)
11217 (js2-minor-mode-exit)))
11218
11219 (defun js2-minor-mode-enter ()
11220 "Initialization for `js2-minor-mode'."
11221 (set (make-local-variable 'max-lisp-eval-depth)
11222 (max max-lisp-eval-depth 3000))
11223 (setq next-error-function #'js2-next-error)
11224 (js2-set-default-externs)
11225 ;; Experiment: make reparse-delay longer for longer files.
11226 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11227 (setq js2-idle-timer-delay
11228 (* js2-idle-timer-delay
11229 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11230 (setq js2-mode-buffer-dirty-p t
11231 js2-mode-parsing nil)
11232 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11233 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11234 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11235 (when js2-include-jslint-globals
11236 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11237 (run-hooks 'js2-init-hook)
11238 (js2-reparse))
11239
11240 (defun js2-minor-mode-exit ()
11241 "Turn off `js2-minor-mode'."
11242 (setq next-error-function nil)
11243 (remove-hook 'after-change-functions #'js2-mode-edit t)
11244 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11245 (when js2-mode-node-overlay
11246 (delete-overlay js2-mode-node-overlay)
11247 (setq js2-mode-node-overlay nil))
11248 (js2-remove-overlays)
11249 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11250 (setq js2-mode-ast nil))
11251
11252 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11253 (make-variable-buffer-local 'js2-source-buffer)
11254
11255 (cl-defun js2-display-error-list ()
11256 "Display a navigable buffer listing parse errors/warnings."
11257 (interactive)
11258 (unless (js2-have-errors-p)
11259 (message "No errors")
11260 (cl-return-from js2-display-error-list))
11261 (cl-labels ((annotate-list
11262 (lst type)
11263 "Add diagnostic TYPE and line number to errs list"
11264 (mapcar (lambda (err)
11265 (list err type (line-number-at-pos (nth 1 err))))
11266 lst)))
11267 (let* ((srcbuf (current-buffer))
11268 (errbuf (get-buffer-create "*js-lint*"))
11269 (errors (annotate-list
11270 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11271 'js2-error)) ; must be a valid face name
11272 (warnings (annotate-list
11273 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11274 'js2-warning)) ; must be a valid face name
11275 (all-errs (sort (append errors warnings)
11276 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11277 (with-current-buffer errbuf
11278 (let ((inhibit-read-only t))
11279 (erase-buffer)
11280 (dolist (err all-errs)
11281 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11282 (insert-text-button
11283 (format "line %d: %s" line (js2-get-msg msg-key))
11284 'face type
11285 'follow-link "\C-m"
11286 'action 'js2-error-buffer-jump
11287 'js2-msg (js2-get-msg msg-key)
11288 'js2-pos beg)
11289 (insert "\n"))))
11290 (js2-error-buffer-mode)
11291 (setq js2-source-buffer srcbuf)
11292 (pop-to-buffer errbuf)
11293 (goto-char (point-min))
11294 (unless (eobp)
11295 (js2-error-buffer-view))))))
11296
11297 (defvar js2-error-buffer-mode-map
11298 (let ((map (make-sparse-keymap)))
11299 (define-key map "n" #'js2-error-buffer-next)
11300 (define-key map "p" #'js2-error-buffer-prev)
11301 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11302 (define-key map "o" #'js2-error-buffer-view)
11303 (define-key map "q" #'js2-error-buffer-quit)
11304 map)
11305 "Keymap used for js2 diagnostics buffers.")
11306
11307 (defun js2-error-buffer-mode ()
11308 "Major mode for js2 diagnostics buffers.
11309 Selecting an error will jump it to the corresponding source-buffer error.
11310 \\{js2-error-buffer-mode-map}"
11311 (interactive)
11312 (setq major-mode 'js2-error-buffer-mode
11313 mode-name "JS Lint Diagnostics")
11314 (use-local-map js2-error-buffer-mode-map)
11315 (setq truncate-lines t)
11316 (set-buffer-modified-p nil)
11317 (setq buffer-read-only t)
11318 (run-hooks 'js2-error-buffer-mode-hook))
11319
11320 (defun js2-error-buffer-next ()
11321 "Move to next error and view it."
11322 (interactive)
11323 (when (zerop (forward-line 1))
11324 (js2-error-buffer-view)))
11325
11326 (defun js2-error-buffer-prev ()
11327 "Move to previous error and view it."
11328 (interactive)
11329 (when (zerop (forward-line -1))
11330 (js2-error-buffer-view)))
11331
11332 (defun js2-error-buffer-quit ()
11333 "Kill the current buffer."
11334 (interactive)
11335 (kill-buffer))
11336
11337 (defun js2-error-buffer-jump (&rest ignored)
11338 "Jump cursor to current error in source buffer."
11339 (interactive)
11340 (when (js2-error-buffer-view)
11341 (pop-to-buffer js2-source-buffer)))
11342
11343 (defun js2-error-buffer-view ()
11344 "Scroll source buffer to show error at current line."
11345 (interactive)
11346 (cond
11347 ((not (eq major-mode 'js2-error-buffer-mode))
11348 (message "Not in a js2 errors buffer"))
11349 ((not (buffer-live-p js2-source-buffer))
11350 (message "Source buffer has been killed"))
11351 ((not (wholenump (get-text-property (point) 'js2-pos)))
11352 (message "There does not seem to be an error here"))
11353 (t
11354 (let ((pos (get-text-property (point) 'js2-pos))
11355 (msg (get-text-property (point) 'js2-msg)))
11356 (save-selected-window
11357 (pop-to-buffer js2-source-buffer)
11358 (goto-char pos)
11359 (message msg))))))
11360
11361 ;;;###autoload
11362 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11363 ;; FIXME: Should derive from js-mode.
11364 "Major mode for editing JavaScript code."
11365 ;; Used by comment-region; don't change it.
11366 (set (make-local-variable 'comment-start) "//")
11367 (set (make-local-variable 'comment-end) "")
11368 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11369 (set (make-local-variable 'max-lisp-eval-depth)
11370 (max max-lisp-eval-depth 3000))
11371 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11372 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11373 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11374 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11375 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11376 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11377 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11378 ;; for characters inside regexp literals.
11379 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11380 ;; this is necessary to make `show-paren-function' work properly
11381 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11382 ;; needed for M-x rgrep, among other things
11383 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11384
11385 (set (make-local-variable 'electric-indent-chars)
11386 (append "{}()[]:;,*." electric-indent-chars))
11387 (set (make-local-variable 'electric-layout-rules)
11388 '((?\; . after) (?\{ . after) (?\} . before)))
11389
11390 ;; some variables needed by cc-engine for paragraph-fill, etc.
11391 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11392 c-comment-start-regexp "/[*/]\\|\\s|"
11393 c-line-comment-starter "//"
11394 c-paragraph-start js2-paragraph-start
11395 c-paragraph-separate "$"
11396 c-syntactic-ws-start js2-syntactic-ws-start
11397 c-syntactic-ws-end js2-syntactic-ws-end
11398 c-syntactic-eol js2-syntactic-eol)
11399
11400 (let ((c-buffer-is-cc-mode t))
11401 ;; Copied from `js-mode'. Also see Bug#6071.
11402 (make-local-variable 'paragraph-start)
11403 (make-local-variable 'paragraph-separate)
11404 (make-local-variable 'paragraph-ignore-fill-prefix)
11405 (make-local-variable 'adaptive-fill-mode)
11406 (make-local-variable 'adaptive-fill-regexp)
11407 (c-setup-paragraph-variables))
11408
11409 (setq font-lock-defaults '(nil t))
11410
11411 ;; Experiment: make reparse-delay longer for longer files.
11412 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11413 (setq js2-idle-timer-delay
11414 (* js2-idle-timer-delay
11415 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11416
11417 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11418 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11419 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11420 (setq next-error-function #'js2-next-error)
11421 (imenu-add-to-menubar (concat "IM-" mode-name))
11422 (add-to-invisibility-spec '(js2-outline . t))
11423 (set (make-local-variable 'line-move-ignore-invisible) t)
11424 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11425 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11426
11427 (setq js2-mode-functions-hidden nil
11428 js2-mode-comments-hidden nil
11429 js2-mode-buffer-dirty-p t
11430 js2-mode-parsing nil)
11431
11432 (js2-set-default-externs)
11433
11434 (when js2-include-jslint-globals
11435 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11436
11437 (run-hooks 'js2-init-hook)
11438
11439 (js2-reparse))
11440
11441 (defun js2-mode-exit ()
11442 "Exit `js2-mode' and clean up."
11443 (interactive)
11444 (when js2-mode-node-overlay
11445 (delete-overlay js2-mode-node-overlay)
11446 (setq js2-mode-node-overlay nil))
11447 (js2-remove-overlays)
11448 (setq js2-mode-ast nil)
11449 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11450 (remove-from-invisibility-spec '(js2-outline . t))
11451 (js2-mode-show-all)
11452 (with-silent-modifications
11453 (js2-clear-face (point-min) (point-max))))
11454
11455 (defun js2-mode-reset-timer ()
11456 "Cancel any existing parse timer and schedule a new one."
11457 (if js2-mode-parse-timer
11458 (cancel-timer js2-mode-parse-timer))
11459 (setq js2-mode-parsing nil)
11460 (let ((timer (timer-create)))
11461 (setq js2-mode-parse-timer timer)
11462 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11463 (timer-set-idle-time timer js2-idle-timer-delay)
11464 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11465 (timer-activate-when-idle timer nil)))
11466
11467 (defun js2-mode-idle-reparse (buffer)
11468 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11469 it to be reparsed when the buffer is selected."
11470 (cond ((eq buffer (current-buffer))
11471 (js2-reparse))
11472 ((buffer-live-p buffer)
11473 ;; reparse when the buffer is selected again
11474 (with-current-buffer buffer
11475 (add-hook 'window-configuration-change-hook
11476 #'js2-mode-idle-reparse-inner
11477 nil t)))))
11478
11479 (defun js2-mode-idle-reparse-inner ()
11480 (remove-hook 'window-configuration-change-hook
11481 #'js2-mode-idle-reparse-inner
11482 t)
11483 (js2-reparse))
11484
11485 (defun js2-mode-edit (_beg _end _len)
11486 "Schedule a new parse after buffer is edited.
11487 Buffer edit spans from BEG to END and is of length LEN."
11488 (setq js2-mode-buffer-dirty-p t)
11489 (js2-mode-hide-overlay)
11490 (js2-mode-reset-timer))
11491
11492 (defun js2-minor-mode-edit (_beg _end _len)
11493 "Callback for buffer edits in `js2-mode'.
11494 Schedules a new parse after buffer is edited.
11495 Buffer edit spans from BEG to END and is of length LEN."
11496 (setq js2-mode-buffer-dirty-p t)
11497 (js2-mode-hide-overlay)
11498 (js2-mode-reset-timer))
11499
11500 (defun js2-reparse (&optional force)
11501 "Re-parse current buffer after user finishes some data entry.
11502 If we get any user input while parsing, including cursor motion,
11503 we discard the parse and reschedule it. If FORCE is nil, then the
11504 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11505 (let (time
11506 interrupted-p
11507 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11508 (unless js2-mode-parsing
11509 (setq js2-mode-parsing t)
11510 (unwind-protect
11511 (when (or js2-mode-buffer-dirty-p force)
11512 (js2-remove-overlays)
11513 (setq js2-mode-buffer-dirty-p nil
11514 js2-mode-fontifications nil
11515 js2-mode-deferred-properties nil)
11516 (if js2-mode-verbose-parse-p
11517 (message "parsing..."))
11518 (setq time
11519 (js2-time
11520 (setq interrupted-p
11521 (catch 'interrupted
11522 (js2-parse)
11523 (with-silent-modifications
11524 ;; if parsing is interrupted, comments and regex
11525 ;; literals stay ignored by `parse-partial-sexp'
11526 (remove-text-properties (point-min) (point-max)
11527 '(syntax-table))
11528 (js2-mode-apply-deferred-properties)
11529 (js2-mode-remove-suppressed-warnings)
11530 (js2-mode-show-warnings)
11531 (js2-mode-show-errors)
11532 (if (>= js2-highlight-level 1)
11533 (js2-highlight-jsdoc js2-mode-ast)))
11534 nil))))
11535 (if interrupted-p
11536 (progn
11537 ;; unfinished parse => try again
11538 (setq js2-mode-buffer-dirty-p t)
11539 (js2-mode-reset-timer))
11540 (if js2-mode-verbose-parse-p
11541 (message "Parse time: %s" time))))
11542 (setq js2-mode-parsing nil)
11543 (unless interrupted-p
11544 (setq js2-mode-parse-timer nil))))))
11545
11546 (defun js2-mode-show-node (event)
11547 "Debugging aid: highlight selected AST node on mouse click."
11548 (interactive "e")
11549 (mouse-set-point event)
11550 (setq deactivate-mark t)
11551 (when js2-mode-show-overlay
11552 (let ((node (js2-node-at-point))
11553 beg end)
11554 (if (null node)
11555 (message "No node found at location %s" (point))
11556 (setq beg (js2-node-abs-pos node)
11557 end (+ beg (js2-node-len node)))
11558 (if js2-mode-node-overlay
11559 (move-overlay js2-mode-node-overlay beg end)
11560 (setq js2-mode-node-overlay (make-overlay beg end))
11561 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11562 (with-silent-modifications
11563 (if (fboundp 'cursor-sensor-mode)
11564 (put-text-property beg end 'cursor-sensor-functions
11565 '(js2-mode-hide-overlay))
11566 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11567 (message "%s, parent: %s"
11568 (js2-node-short-name node)
11569 (if (js2-node-parent node)
11570 (js2-node-short-name (js2-node-parent node))
11571 "nil"))))))
11572
11573 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11574 "Remove the debugging overlay when point moves.
11575 ARG1, ARG2 and ARG3 have different values depending on whether this function
11576 was found on `point-left' or in `cursor-sensor-functions'."
11577 (when js2-mode-node-overlay
11578 (let ((beg (overlay-start js2-mode-node-overlay))
11579 (end (overlay-end js2-mode-node-overlay))
11580 (p2 (if (windowp arg1)
11581 ;; Called from cursor-sensor-functions.
11582 (window-point arg1)
11583 ;; Called from point-left.
11584 arg2)))
11585 ;; Sometimes we're called spuriously.
11586 (unless (and p2
11587 (>= p2 beg)
11588 (<= p2 end))
11589 (with-silent-modifications
11590 (remove-text-properties beg end
11591 '(point-left nil cursor-sensor-functions)))
11592 (delete-overlay js2-mode-node-overlay)
11593 (setq js2-mode-node-overlay nil)))))
11594
11595 (defun js2-mode-reset ()
11596 "Debugging helper: reset everything."
11597 (interactive)
11598 (js2-mode-exit)
11599 (js2-mode))
11600
11601 (defun js2-mode-show-warn-or-err (e face)
11602 "Highlight a warning or error E with FACE.
11603 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11604 The last element is optional. When present, use instead of FACE."
11605 (let* ((key (cl-first e))
11606 (beg (cl-second e))
11607 (end (+ beg (cl-third e)))
11608 ;; Don't inadvertently go out of bounds.
11609 (beg (max (point-min) (min beg (point-max))))
11610 (end (max (point-min) (min end (point-max))))
11611 (ovl (make-overlay beg end)))
11612 ;; FIXME: Why a mix of overlays and text-properties?
11613 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11614 (overlay-put ovl 'js2-error t)
11615 (put-text-property beg end 'help-echo (js2-get-msg key))
11616 (if (fboundp 'cursor-sensor-mode)
11617 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11618 (put-text-property beg end 'point-entered #'js2-echo-error))))
11619
11620 (defun js2-remove-overlays ()
11621 "Remove overlays from buffer that have a `js2-error' property."
11622 (let ((beg (point-min))
11623 (end (point-max)))
11624 (save-excursion
11625 (dolist (o (overlays-in beg end))
11626 (when (overlay-get o 'js2-error)
11627 (delete-overlay o))))))
11628
11629 (defun js2-mode-apply-deferred-properties ()
11630 "Apply fontifications and other text properties recorded during parsing."
11631 (when (cl-plusp js2-highlight-level)
11632 ;; We defer clearing faces as long as possible to eliminate flashing.
11633 (js2-clear-face (point-min) (point-max))
11634 ;; Have to reverse the recorded fontifications list so that errors
11635 ;; and warnings overwrite the normal fontifications.
11636 (dolist (f (nreverse js2-mode-fontifications))
11637 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11638 (setq js2-mode-fontifications nil))
11639 (dolist (p js2-mode-deferred-properties)
11640 (apply #'put-text-property p))
11641 (setq js2-mode-deferred-properties nil))
11642
11643 (defun js2-mode-show-errors ()
11644 "Highlight syntax errors."
11645 (when js2-mode-show-parse-errors
11646 (dolist (e (js2-ast-root-errors js2-mode-ast))
11647 (js2-mode-show-warn-or-err e 'js2-error))))
11648
11649 (defun js2-mode-remove-suppressed-warnings ()
11650 "Take suppressed warnings out of the AST warnings list.
11651 This ensures that the counts and `next-error' are correct."
11652 (setf (js2-ast-root-warnings js2-mode-ast)
11653 (js2-delete-if
11654 (lambda (e)
11655 (let ((key (caar e)))
11656 (or
11657 (and (not js2-strict-trailing-comma-warning)
11658 (string-match "trailing\\.comma" key))
11659 (and (not js2-strict-cond-assign-warning)
11660 (string= key "msg.equal.as.assign"))
11661 (and js2-missing-semi-one-line-override
11662 (string= key "msg.missing.semi")
11663 (let* ((beg (cl-second e))
11664 (node (js2-node-at-point beg))
11665 (fn (js2-mode-find-parent-fn node))
11666 (body (and fn (js2-function-node-body fn)))
11667 (lc (and body (js2-node-abs-pos body)))
11668 (rc (and lc (+ lc (js2-node-len body)))))
11669 (and fn
11670 (or (null body)
11671 (save-excursion
11672 (goto-char beg)
11673 (and (js2-same-line lc)
11674 (js2-same-line rc))))))))))
11675 (js2-ast-root-warnings js2-mode-ast))))
11676
11677 (defun js2-mode-show-warnings ()
11678 "Highlight strict-mode warnings."
11679 (when js2-mode-show-strict-warnings
11680 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11681 (js2-mode-show-warn-or-err e 'js2-warning))))
11682
11683 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11684 "Called by point-motion hooks.
11685 ARG1, ARG2 and ARG3 have different values depending on whether this function
11686 was found on `point-entered' or in `cursor-sensor-functions'."
11687 (let* ((new-point (if (windowp arg1)
11688 ;; Called from cursor-sensor-functions.
11689 (window-point arg1)
11690 ;; Called from point-left.
11691 arg2))
11692 (msg (get-text-property new-point 'help-echo)))
11693 (when (and (stringp msg)
11694 (not (active-minibuffer-window))
11695 (not (current-message)))
11696 (message msg))))
11697
11698 (defun js2-line-break (&optional _soft)
11699 "Break line at point and indent, continuing comment if within one.
11700 If inside a string, and `js2-concat-multiline-strings' is not
11701 nil, turn it into concatenation."
11702 (interactive)
11703 (let ((parse-status (syntax-ppss)))
11704 (cond
11705 ;; Check if we're inside a string.
11706 ((nth 3 parse-status)
11707 (if js2-concat-multiline-strings
11708 (js2-mode-split-string parse-status)
11709 (insert "\n")))
11710 ;; Check if inside a block comment.
11711 ((nth 4 parse-status)
11712 (js2-mode-extend-comment (nth 8 parse-status)))
11713 (t
11714 (newline-and-indent)))))
11715
11716 (defun js2-mode-split-string (parse-status)
11717 "Turn a newline in mid-string into a string concatenation.
11718 PARSE-STATUS is as documented in `parse-partial-sexp'."
11719 (let* ((quote-char (nth 3 parse-status))
11720 (at-eol (eq js2-concat-multiline-strings 'eol)))
11721 (insert quote-char)
11722 (insert (if at-eol " +\n" "\n"))
11723 (unless at-eol
11724 (insert "+ "))
11725 (js2-indent-line)
11726 (insert quote-char)
11727 (when (eolp)
11728 (insert quote-char)
11729 (backward-char 1))))
11730
11731 (defun js2-mode-extend-comment (start-pos)
11732 "Indent the line and, when inside a comment block, add comment prefix."
11733 (let (star single col first-line needs-close)
11734 (save-excursion
11735 (back-to-indentation)
11736 (when (< (point) start-pos)
11737 (goto-char start-pos))
11738 (cond
11739 ((looking-at "\\*[^/]")
11740 (setq star t
11741 col (current-column)))
11742 ((looking-at "/\\*")
11743 (setq star t
11744 first-line t
11745 col (1+ (current-column))))
11746 ((looking-at "//")
11747 (setq single t
11748 col (current-column)))))
11749 ;; Heuristic for whether we need to close the comment:
11750 ;; if we've got a parse error here, assume it's an unterminated
11751 ;; comment.
11752 (setq needs-close
11753 (or
11754 (get-char-property (1- (point)) 'js2-error)
11755 ;; The heuristic above doesn't work well when we're
11756 ;; creating a comment and there's another one downstream,
11757 ;; as our parser thinks this one ends at the end of the
11758 ;; next one. (You can have a /* inside a js block comment.)
11759 ;; So just close it if the next non-ws char isn't a *.
11760 (and first-line
11761 (eolp)
11762 (save-excursion
11763 (skip-chars-forward " \t\r\n")
11764 (not (eq (char-after) ?*))))))
11765 (delete-horizontal-space)
11766 (insert "\n")
11767 (cond
11768 (star
11769 (indent-to col)
11770 (insert "* ")
11771 (if (and first-line needs-close)
11772 (save-excursion
11773 (insert "\n")
11774 (indent-to col)
11775 (insert "*/"))))
11776 ((and single
11777 (save-excursion
11778 (and (zerop (forward-line 1))
11779 (looking-at "\\s-*//"))))
11780 (indent-to col)
11781 (insert "// ")))
11782 ;; Don't need to extend the comment after all.
11783 (js2-indent-line)))
11784
11785 (defun js2-beginning-of-line ()
11786 "Toggle point between bol and first non-whitespace char in line.
11787 Also moves past comment delimiters when inside comments."
11788 (interactive)
11789 (let (node)
11790 (cond
11791 ((bolp)
11792 (back-to-indentation))
11793 ((looking-at "//")
11794 (skip-chars-forward "/ \t"))
11795 ((and (eq (char-after) ?*)
11796 (setq node (js2-comment-at-point))
11797 (memq (js2-comment-node-format node) '(jsdoc block))
11798 (save-excursion
11799 (skip-chars-backward " \t")
11800 (bolp)))
11801 (skip-chars-forward "\* \t"))
11802 (t
11803 (goto-char (point-at-bol))))))
11804
11805 (defun js2-end-of-line ()
11806 "Toggle point between eol and last non-whitespace char in line."
11807 (interactive)
11808 (if (eolp)
11809 (skip-chars-backward " \t")
11810 (goto-char (point-at-eol))))
11811
11812 (defun js2-mode-wait-for-parse (callback)
11813 "Invoke CALLBACK when parsing is finished.
11814 If parsing is already finished, calls CALLBACK immediately."
11815 (if (not js2-mode-buffer-dirty-p)
11816 (funcall callback)
11817 (push callback js2-mode-pending-parse-callbacks)
11818 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11819
11820 (defun js2-mode-parse-finished ()
11821 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11822 ;; We can't let errors propagate up, since it prevents the
11823 ;; `js2-parse' method from completing normally and returning
11824 ;; the ast, which makes things mysteriously not work right.
11825 (unwind-protect
11826 (dolist (cb js2-mode-pending-parse-callbacks)
11827 (condition-case err
11828 (funcall cb)
11829 (error (message "%s" err))))
11830 (setq js2-mode-pending-parse-callbacks nil)))
11831
11832 (defun js2-mode-flag-region (from to flag)
11833 "Hide or show text from FROM to TO, according to FLAG.
11834 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11835 Returns the created overlay if FLAG is non-nil."
11836 (remove-overlays from to 'invisible 'js2-outline)
11837 (when flag
11838 (let ((o (make-overlay from to)))
11839 (overlay-put o 'invisible 'js2-outline)
11840 (overlay-put o 'isearch-open-invisible
11841 'js2-isearch-open-invisible)
11842 o)))
11843
11844 ;; Function to be set as an outline-isearch-open-invisible' property
11845 ;; to the overlay that makes the outline invisible (see
11846 ;; `js2-mode-flag-region').
11847 (defun js2-isearch-open-invisible (_overlay)
11848 ;; We rely on the fact that isearch places point on the matched text.
11849 (js2-mode-show-element))
11850
11851 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11852 "Return cons cell of bounds of folding overlay at POS.
11853 Returns nil if not found."
11854 (let ((overlays (overlays-at (or pos (point))))
11855 o)
11856 (while (and overlays
11857 (not o))
11858 (if (overlay-get (car overlays) 'invisible)
11859 (setq o (car overlays))
11860 (setq overlays (cdr overlays))))
11861 (if o
11862 (cons (overlay-start o) (overlay-end o)))))
11863
11864 (defun js2-mode-function-at-point (&optional pos)
11865 "Return the innermost function node enclosing current point.
11866 Returns nil if point is not in a function."
11867 (let ((node (js2-node-at-point pos)))
11868 (while (and node (not (js2-function-node-p node)))
11869 (setq node (js2-node-parent node)))
11870 (if (js2-function-node-p node)
11871 node)))
11872
11873 (defun js2-mode-toggle-element ()
11874 "Hide or show the foldable element at the point."
11875 (interactive)
11876 (let (comment fn pos)
11877 (save-excursion
11878 (cond
11879 ;; /* ... */ comment?
11880 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11881 (if (js2-mode-invisible-overlay-bounds
11882 (setq pos (+ 3 (js2-node-abs-pos comment))))
11883 (progn
11884 (goto-char pos)
11885 (js2-mode-show-element))
11886 (js2-mode-hide-element)))
11887 ;; //-comment?
11888 ((save-excursion
11889 (back-to-indentation)
11890 (looking-at js2-mode-//-comment-re))
11891 (js2-mode-toggle-//-comment))
11892 ;; function?
11893 ((setq fn (js2-mode-function-at-point))
11894 (setq pos (and (js2-function-node-body fn)
11895 (js2-node-abs-pos (js2-function-node-body fn))))
11896 (goto-char (1+ pos))
11897 (if (js2-mode-invisible-overlay-bounds)
11898 (js2-mode-show-element)
11899 (js2-mode-hide-element)))
11900 (t
11901 (message "Nothing at point to hide or show"))))))
11902
11903 (defun js2-mode-hide-element ()
11904 "Fold/hide contents of a block, showing ellipses.
11905 Show the hidden text with \\[js2-mode-show-element]."
11906 (interactive)
11907 (if js2-mode-buffer-dirty-p
11908 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11909 (let (node body beg end)
11910 (cond
11911 ((js2-mode-invisible-overlay-bounds)
11912 (message "already hidden"))
11913 (t
11914 (setq node (js2-node-at-point))
11915 (cond
11916 ((js2-block-comment-p node)
11917 (js2-mode-hide-comment node))
11918 (t
11919 (while (and node (not (js2-function-node-p node)))
11920 (setq node (js2-node-parent node)))
11921 (if (and node
11922 (setq body (js2-function-node-body node)))
11923 (progn
11924 (setq beg (js2-node-abs-pos body)
11925 end (+ beg (js2-node-len body)))
11926 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11927 (message "No collapsable element found at point"))))))))
11928
11929 (defun js2-mode-show-element ()
11930 "Show the hidden element at current point."
11931 (interactive)
11932 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11933 (if bounds
11934 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11935 (message "Nothing to un-hide"))))
11936
11937 (defun js2-mode-show-all ()
11938 "Show all of the text in the buffer."
11939 (interactive)
11940 (js2-mode-flag-region (point-min) (point-max) nil))
11941
11942 (defun js2-mode-toggle-hide-functions ()
11943 (interactive)
11944 (if js2-mode-functions-hidden
11945 (js2-mode-show-functions)
11946 (js2-mode-hide-functions)))
11947
11948 (defun js2-mode-hide-functions ()
11949 "Hides all non-nested function bodies in the buffer.
11950 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11951 to open an individual entry."
11952 (interactive)
11953 (if js2-mode-buffer-dirty-p
11954 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11955 (if (null js2-mode-ast)
11956 (message "Oops - parsing failed")
11957 (setq js2-mode-functions-hidden t)
11958 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11959
11960 (defun js2-mode-function-hider (n endp)
11961 (when (not endp)
11962 (let ((tt (js2-node-type n))
11963 body beg end)
11964 (cond
11965 ((and (= tt js2-FUNCTION)
11966 (setq body (js2-function-node-body n)))
11967 (setq beg (js2-node-abs-pos body)
11968 end (+ beg (js2-node-len body)))
11969 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11970 nil) ; don't process children of function
11971 (t
11972 t))))) ; keep processing other AST nodes
11973
11974 (defun js2-mode-show-functions ()
11975 "Un-hide any folded function bodies in the buffer."
11976 (interactive)
11977 (setq js2-mode-functions-hidden nil)
11978 (save-excursion
11979 (goto-char (point-min))
11980 (while (/= (goto-char (next-overlay-change (point)))
11981 (point-max))
11982 (dolist (o (overlays-at (point)))
11983 (when (and (overlay-get o 'invisible)
11984 (not (overlay-get o 'comment)))
11985 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11986
11987 (defun js2-mode-hide-comment (n)
11988 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11989 3 ; /**
11990 2)) ; /*
11991 (beg (+ (js2-node-abs-pos n) head))
11992 (end (- (+ beg (js2-node-len n)) head 2))
11993 (o (js2-mode-flag-region beg end 'hide)))
11994 (overlay-put o 'comment t)))
11995
11996 (defun js2-mode-toggle-hide-comments ()
11997 "Folds all block comments in the buffer.
11998 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11999 to open an individual entry."
12000 (interactive)
12001 (if js2-mode-comments-hidden
12002 (js2-mode-show-comments)
12003 (js2-mode-hide-comments)))
12004
12005 (defun js2-mode-hide-comments ()
12006 (interactive)
12007 (if js2-mode-buffer-dirty-p
12008 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12009 (if (null js2-mode-ast)
12010 (message "Oops - parsing failed")
12011 (setq js2-mode-comments-hidden t)
12012 (dolist (n (js2-ast-root-comments js2-mode-ast))
12013 (when (js2-block-comment-p n)
12014 (js2-mode-hide-comment n)))
12015 (js2-mode-hide-//-comments)))
12016
12017 (defun js2-mode-extend-//-comment (direction)
12018 "Find start or end of a block of similar //-comment lines.
12019 DIRECTION is -1 to look back, 1 to look forward.
12020 INDENT is the indentation level to match.
12021 Returns the end-of-line position of the furthest adjacent
12022 //-comment line with the same indentation as the current line.
12023 If there is no such matching line, returns current end of line."
12024 (let ((pos (point-at-eol))
12025 (indent (current-indentation)))
12026 (save-excursion
12027 (while (and (zerop (forward-line direction))
12028 (looking-at js2-mode-//-comment-re)
12029 (eq indent (length (match-string 1))))
12030 (setq pos (point-at-eol)))
12031 pos)))
12032
12033 (defun js2-mode-hide-//-comments ()
12034 "Fold adjacent 1-line comments, showing only snippet of first one."
12035 (let (beg end)
12036 (save-excursion
12037 (goto-char (point-min))
12038 (while (re-search-forward js2-mode-//-comment-re nil t)
12039 (setq beg (point)
12040 end (js2-mode-extend-//-comment 1))
12041 (unless (eq beg end)
12042 (overlay-put (js2-mode-flag-region beg end 'hide)
12043 'comment t))
12044 (goto-char end)
12045 (forward-char 1)))))
12046
12047 (defun js2-mode-toggle-//-comment ()
12048 "Fold or un-fold any multi-line //-comment at point.
12049 Caller should have determined that this line starts with a //-comment."
12050 (let* ((beg (point-at-eol))
12051 (end beg))
12052 (save-excursion
12053 (goto-char end)
12054 (if (js2-mode-invisible-overlay-bounds)
12055 (js2-mode-show-element)
12056 ;; else hide the comment
12057 (setq beg (js2-mode-extend-//-comment -1)
12058 end (js2-mode-extend-//-comment 1))
12059 (unless (eq beg end)
12060 (overlay-put (js2-mode-flag-region beg end 'hide)
12061 'comment t))))))
12062
12063 (defun js2-mode-show-comments ()
12064 "Un-hide any hidden comments, leaving other hidden elements alone."
12065 (interactive)
12066 (setq js2-mode-comments-hidden nil)
12067 (save-excursion
12068 (goto-char (point-min))
12069 (while (/= (goto-char (next-overlay-change (point)))
12070 (point-max))
12071 (dolist (o (overlays-at (point)))
12072 (when (overlay-get o 'comment)
12073 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12074
12075 (defun js2-mode-display-warnings-and-errors ()
12076 "Turn on display of warnings and errors."
12077 (interactive)
12078 (setq js2-mode-show-parse-errors t
12079 js2-mode-show-strict-warnings t)
12080 (js2-reparse 'force))
12081
12082 (defun js2-mode-hide-warnings-and-errors ()
12083 "Turn off display of warnings and errors."
12084 (interactive)
12085 (setq js2-mode-show-parse-errors nil
12086 js2-mode-show-strict-warnings nil)
12087 (js2-reparse 'force))
12088
12089 (defun js2-mode-toggle-warnings-and-errors ()
12090 "Toggle the display of warnings and errors.
12091 Some users don't like having warnings/errors reported while they type."
12092 (interactive)
12093 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12094 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12095 (if (called-interactively-p 'any)
12096 (message "warnings and errors %s"
12097 (if js2-mode-show-parse-errors
12098 "enabled"
12099 "disabled")))
12100 (js2-reparse 'force))
12101
12102 (defun js2-mode-customize ()
12103 (interactive)
12104 (customize-group 'js2-mode))
12105
12106 (defun js2-mode-forward-sexp (&optional arg)
12107 "Move forward across one statement or balanced expression.
12108 With ARG, do it that many times. Negative arg -N means
12109 move backward across N balanced expressions."
12110 (interactive "p")
12111 (setq arg (or arg 1))
12112 (save-restriction
12113 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12114 (js2-reparse)
12115 (let (forward-sexp-function
12116 node (start (point)) pos lp rp child)
12117 (cond
12118 ;; backward-sexp
12119 ;; could probably make this better for some cases:
12120 ;; - if in statement block (e.g. function body), go to parent
12121 ;; - infix exprs like (foo in bar) - maybe go to beginning
12122 ;; of infix expr if in the right-side expression?
12123 ((and arg (cl-minusp arg))
12124 (dotimes (_ (- arg))
12125 (js2-backward-sws)
12126 (forward-char -1) ; Enter the node we backed up to.
12127 (when (setq node (js2-node-at-point (point) t))
12128 (setq pos (js2-node-abs-pos node))
12129 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12130 (setq lp (car parens)
12131 rp (cdr parens)))
12132 (when (and lp (> start lp))
12133 (if (and rp (<= start rp))
12134 ;; Between parens, check if there's a child node we can jump.
12135 (when (setq child (js2-node-closest-child node (point) lp t))
12136 (setq pos (js2-node-abs-pos child)))
12137 ;; Before both parens.
12138 (setq pos lp)))
12139 (let ((state (parse-partial-sexp start pos)))
12140 (goto-char (if (not (zerop (car state)))
12141 ;; Stumble at the unbalanced paren if < 0, or
12142 ;; jump a bit further if > 0.
12143 (scan-sexps start -1)
12144 pos))))
12145 (unless pos (goto-char (point-min)))))
12146 (t
12147 ;; forward-sexp
12148 (dotimes (_ arg)
12149 (js2-forward-sws)
12150 (when (setq node (js2-node-at-point (point) t))
12151 (setq pos (js2-node-abs-pos node))
12152 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12153 (setq lp (car parens)
12154 rp (cdr parens)))
12155 (or
12156 (when (and rp (<= start rp))
12157 (if (> start lp)
12158 (when (setq child (js2-node-closest-child node (point) rp))
12159 (setq pos (js2-node-abs-end child)))
12160 (setq pos (1+ rp))))
12161 ;; No parens or child nodes, looks for the end of the current node.
12162 (cl-incf pos (js2-node-len
12163 (if (js2-expr-stmt-node-p (js2-node-parent node))
12164 ;; Stop after the semicolon.
12165 (js2-node-parent node)
12166 node))))
12167 (let ((state (save-excursion (parse-partial-sexp start pos))))
12168 (goto-char (if (not (zerop (car state)))
12169 (scan-sexps start 1)
12170 pos))))
12171 (unless pos (goto-char (point-max)))))))))
12172
12173 (defun js2-mode-forward-sexp-parens (node abs-pos)
12174 "Return a cons cell with positions of main parens in NODE."
12175 (cond
12176 ((or (js2-array-node-p node)
12177 (js2-object-node-p node)
12178 (js2-comp-node-p node)
12179 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12180 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12181 ((js2-paren-expr-node-p node)
12182 (let ((lp (js2-node-lp node))
12183 (rp (js2-node-rp node)))
12184 (cons (when lp (+ abs-pos lp))
12185 (when rp (+ abs-pos rp)))))))
12186
12187 (defun js2-node-closest-child (parent point limit &optional before)
12188 (let* ((parent-pos (js2-node-abs-pos parent))
12189 (rpoint (- point parent-pos))
12190 (rlimit (- limit parent-pos))
12191 (min (min rpoint rlimit))
12192 (max (max rpoint rlimit))
12193 found)
12194 (catch 'done
12195 (js2-visit-ast
12196 parent
12197 (lambda (node _end-p)
12198 (if (eq node parent)
12199 t
12200 (let ((pos (js2-node-pos node)) ;; Both relative values.
12201 (end (+ (js2-node-pos node) (js2-node-len node))))
12202 (when (and (>= pos min) (<= end max)
12203 (if before (< pos rpoint) (> end rpoint)))
12204 (setq found node))
12205 (when (> end rpoint)
12206 (throw 'done nil)))
12207 nil))))
12208 found))
12209
12210 (defun js2-errors ()
12211 "Return a list of errors found."
12212 (and js2-mode-ast
12213 (js2-ast-root-errors js2-mode-ast)))
12214
12215 (defun js2-warnings ()
12216 "Return a list of warnings found."
12217 (and js2-mode-ast
12218 (js2-ast-root-warnings js2-mode-ast)))
12219
12220 (defun js2-have-errors-p ()
12221 "Return non-nil if any parse errors or warnings were found."
12222 (or (js2-errors) (js2-warnings)))
12223
12224 (defun js2-errors-and-warnings ()
12225 "Return a copy of the concatenated errors and warnings lists.
12226 They are appended: first the errors, then the warnings.
12227 Entries are of the form (MSG BEG END)."
12228 (when js2-mode-ast
12229 (append (js2-ast-root-errors js2-mode-ast)
12230 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12231
12232 (defun js2-next-error (&optional arg reset)
12233 "Move to next parse error.
12234 Typically invoked via \\[next-error].
12235 ARG is the number of errors, forward or backward, to move.
12236 RESET means start over from the beginning."
12237 (interactive "p")
12238 (if (not (or (js2-errors) (js2-warnings)))
12239 (message "No errors")
12240 (when reset
12241 (goto-char (point-min)))
12242 (let* ((errs (js2-errors-and-warnings))
12243 (continue t)
12244 (start (point))
12245 (count (or arg 1))
12246 (backward (cl-minusp count))
12247 (sorter (if backward '> '<))
12248 (stopper (if backward '< '>))
12249 (count (abs count))
12250 all-errs err)
12251 ;; Sort by start position.
12252 (setq errs (sort errs (lambda (e1 e2)
12253 (funcall sorter (cl-second e1) (cl-second e2))))
12254 all-errs errs)
12255 ;; Find nth error with pos > start.
12256 (while (and errs continue)
12257 (when (funcall stopper (cl-cadar errs) start)
12258 (setq err (car errs))
12259 (if (zerop (cl-decf count))
12260 (setq continue nil)))
12261 (setq errs (cdr errs)))
12262 ;; Clear for `js2-echo-error'.
12263 (message nil)
12264 (if err
12265 (goto-char (cl-second err))
12266 ;; Wrap around to first error.
12267 (goto-char (cl-second (car all-errs)))
12268 ;; If we were already on it, echo msg again.
12269 (if (= (point) start)
12270 (js2-echo-error (point) (point)))))))
12271
12272 (defun js2-down-mouse-3 ()
12273 "Make right-click move the point to the click location.
12274 This makes right-click context menu operations a bit more intuitive.
12275 The point will not move if the region is active, however, to avoid
12276 destroying the region selection."
12277 (interactive)
12278 (when (and js2-move-point-on-right-click
12279 (not mark-active))
12280 (let ((e last-input-event))
12281 (ignore-errors
12282 (goto-char (cl-cadadr e))))))
12283
12284 (defun js2-mode-create-imenu-index ()
12285 "Return an alist for `imenu--index-alist'."
12286 ;; This is built up in `js2-parse-record-imenu' during parsing.
12287 (when js2-mode-ast
12288 ;; if we have an ast but no recorder, they're requesting a rescan
12289 (unless js2-imenu-recorder
12290 (js2-reparse 'force))
12291 (prog1
12292 (js2-build-imenu-index)
12293 (setq js2-imenu-recorder nil
12294 js2-imenu-function-map nil))))
12295
12296 (defun js2-mode-find-tag ()
12297 "Replacement for `find-tag-default'.
12298 `find-tag-default' returns a ridiculous answer inside comments."
12299 (let (beg end)
12300 (js2-with-underscore-as-word-syntax
12301 (save-excursion
12302 (if (and (not (looking-at "[[:alnum:]_$]"))
12303 (looking-back "[[:alnum:]_$]"))
12304 (setq beg (progn (forward-word -1) (point))
12305 end (progn (forward-word 1) (point)))
12306 (setq beg (progn (forward-word 1) (point))
12307 end (progn (forward-word -1) (point))))
12308 (replace-regexp-in-string
12309 "[\"']" ""
12310 (buffer-substring-no-properties beg end))))))
12311
12312 (defun js2-mode-forward-sibling ()
12313 "Move to the end of the sibling following point in parent.
12314 Returns non-nil if successful, or nil if there was no following sibling."
12315 (let* ((node (js2-node-at-point))
12316 (parent (js2-mode-find-enclosing-fn node))
12317 sib)
12318 (when (setq sib (js2-node-find-child-after (point) parent))
12319 (goto-char (+ (js2-node-abs-pos sib)
12320 (js2-node-len sib))))))
12321
12322 (defun js2-mode-backward-sibling ()
12323 "Move to the beginning of the sibling node preceding point in parent.
12324 Parent is defined as the enclosing script or function."
12325 (let* ((node (js2-node-at-point))
12326 (parent (js2-mode-find-enclosing-fn node))
12327 sib)
12328 (when (setq sib (js2-node-find-child-before (point) parent))
12329 (goto-char (js2-node-abs-pos sib)))))
12330
12331 (defun js2-beginning-of-defun (&optional arg)
12332 "Go to line on which current function starts, and return t on success.
12333 If we're not in a function or already at the beginning of one, go
12334 to beginning of previous script-level element.
12335 With ARG N, do that N times. If N is negative, move forward."
12336 (setq arg (or arg 1))
12337 (if (cl-plusp arg)
12338 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12339 (when (cond
12340 ((js2-function-node-p parent)
12341 (goto-char (js2-node-abs-pos parent)))
12342 (t
12343 (js2-mode-backward-sibling)))
12344 (if (> arg 1)
12345 (js2-beginning-of-defun (1- arg))
12346 t)))
12347 (when (js2-end-of-defun)
12348 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12349
12350 (defun js2-end-of-defun ()
12351 "Go to the char after the last position of the current function
12352 or script-level element."
12353 (let* ((node (js2-node-at-point))
12354 (parent (or (and (js2-function-node-p node) node)
12355 (js2-node-parent-script-or-fn node)))
12356 script)
12357 (unless (js2-function-node-p parent)
12358 ;; Use current script-level node, or, if none, the next one.
12359 (setq script (or parent node)
12360 parent (js2-node-find-child-before (point) script))
12361 (when (or (null parent)
12362 (>= (point) (+ (js2-node-abs-pos parent)
12363 (js2-node-len parent))))
12364 (setq parent (js2-node-find-child-after (point) script))))
12365 (when parent
12366 (goto-char (+ (js2-node-abs-pos parent)
12367 (js2-node-len parent))))))
12368
12369 (defun js2-mark-defun (&optional allow-extend)
12370 "Put mark at end of this function, point at beginning.
12371 The function marked is the one that contains point.
12372
12373 Interactively, if this command is repeated,
12374 or (in Transient Mark mode) if the mark is active,
12375 it marks the next defun after the ones already marked."
12376 (interactive "p")
12377 (let (extended)
12378 (when (and allow-extend
12379 (or (and (eq last-command this-command) (mark t))
12380 (and transient-mark-mode mark-active)))
12381 (let ((sib (save-excursion
12382 (goto-char (mark))
12383 (if (js2-mode-forward-sibling)
12384 (point)))))
12385 (if sib
12386 (progn
12387 (set-mark sib)
12388 (setq extended t))
12389 ;; no more siblings - try extending to enclosing node
12390 (goto-char (mark t)))))
12391 (when (not extended)
12392 (let ((node (js2-node-at-point (point) t)) ; skip comments
12393 ast fn stmt parent beg end)
12394 (when (js2-ast-root-p node)
12395 (setq ast node
12396 node (or (js2-node-find-child-after (point) node)
12397 (js2-node-find-child-before (point) node))))
12398 ;; only mark whole buffer if we can't find any children
12399 (if (null node)
12400 (setq node ast))
12401 (if (js2-function-node-p node)
12402 (setq parent node)
12403 (setq fn (js2-mode-find-enclosing-fn node)
12404 stmt (if (or (null fn)
12405 (js2-ast-root-p fn))
12406 (js2-mode-find-first-stmt node))
12407 parent (or stmt fn)))
12408 (setq beg (js2-node-abs-pos parent)
12409 end (+ beg (js2-node-len parent)))
12410 (push-mark beg)
12411 (goto-char end)
12412 (exchange-point-and-mark)))))
12413
12414 (defun js2-narrow-to-defun ()
12415 "Narrow to the function enclosing point."
12416 (interactive)
12417 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12418 (fn (if (js2-script-node-p node)
12419 node
12420 (js2-mode-find-enclosing-fn node)))
12421 (beg (js2-node-abs-pos fn)))
12422 (unless (js2-ast-root-p fn)
12423 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12424
12425 (provide 'js2-mode)
12426
12427 ;;; js2-mode.el ends here