]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Octal syntax is an error in strict mode
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2015 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20150202
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (require 'cl-lib)
89 (require 'imenu)
90 (require 'cc-cmds) ; for `c-fill-paragraph'
91
92 (eval-and-compile
93 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
94 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
95
96 (defvar electric-layout-rules)
97
98 ;;; Externs (variables presumed to be defined by the host system)
99
100 (defvar js2-ecma-262-externs
101 (mapcar 'symbol-name
102 '(Array Boolean Date Error EvalError Function Infinity JSON
103 Math NaN Number Object RangeError ReferenceError RegExp
104 String SyntaxError TypeError URIError
105 decodeURI decodeURIComponent encodeURI
106 encodeURIComponent escape eval isFinite isNaN
107 parseFloat parseInt undefined unescape))
108 "Ecma-262 externs. Included in `js2-externs' by default.")
109
110 (defvar js2-browser-externs
111 (mapcar 'symbol-name
112 '(;; DOM level 1
113 Attr CDATASection CharacterData Comment DOMException
114 DOMImplementation Document DocumentFragment
115 DocumentType Element Entity EntityReference
116 ExceptionCode NamedNodeMap Node NodeList Notation
117 ProcessingInstruction Text
118
119 ;; DOM level 2
120 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
121 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
122 HTMLBodyElement HTMLButtonElement HTMLCollection
123 HTMLDListElement HTMLDirectoryElement HTMLDivElement
124 HTMLDocument HTMLElement HTMLFieldSetElement
125 HTMLFontElement HTMLFormElement HTMLFrameElement
126 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
127 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
128 HTMLImageElement HTMLInputElement HTMLIsIndexElement
129 HTMLLIElement HTMLLabelElement HTMLLegendElement
130 HTMLLinkElement HTMLMapElement HTMLMenuElement
131 HTMLMetaElement HTMLModElement HTMLOListElement
132 HTMLObjectElement HTMLOptGroupElement
133 HTMLOptionElement HTMLOptionsCollection
134 HTMLParagraphElement HTMLParamElement HTMLPreElement
135 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
136 HTMLStyleElement HTMLTableCaptionElement
137 HTMLTableCellElement HTMLTableColElement
138 HTMLTableElement HTMLTableRowElement
139 HTMLTableSectionElement HTMLTextAreaElement
140 HTMLTitleElement HTMLUListElement
141
142 ;; DOM level 3
143 DOMConfiguration DOMError DOMException
144 DOMImplementationList DOMImplementationSource
145 DOMLocator DOMStringList NameList TypeInfo
146 UserDataHandler
147
148 ;; Window
149 window alert confirm document java navigator prompt screen
150 self top requestAnimationFrame cancelAnimationFrame
151
152 ;; W3C CSS
153 CSSCharsetRule CSSFontFace CSSFontFaceRule
154 CSSImportRule CSSMediaRule CSSPageRule
155 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
156 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
157 CSSValue CSSValueList Counter DOMImplementationCSS
158 DocumentCSS DocumentStyle ElementCSSInlineStyle
159 LinkStyle MediaList RGBColor Rect StyleSheet
160 StyleSheetList ViewCSS
161
162 ;; W3C Event
163 EventListener EventTarget Event DocumentEvent UIEvent
164 MouseEvent MutationEvent KeyboardEvent
165
166 ;; W3C Range
167 DocumentRange Range RangeException
168
169 ;; W3C XML
170 XPathResult XMLHttpRequest
171
172 ;; console object. Provided by at least Chrome and Firefox.
173 console))
174 "Browser externs.
175 You can cause these to be included or excluded with the custom
176 variable `js2-include-browser-externs'.")
177
178 (defvar js2-rhino-externs
179 (mapcar 'symbol-name
180 '(Packages importClass importPackage com org java
181 ;; Global object (shell) externs.
182 defineClass deserialize doctest gc help load
183 loadClass print quit readFile readUrl runCommand seal
184 serialize spawn sync toint32 version))
185 "Mozilla Rhino externs.
186 Set `js2-include-rhino-externs' to t to include them.")
187
188 (defvar js2-node-externs
189 (mapcar 'symbol-name
190 '(__dirname __filename Buffer clearInterval clearTimeout require
191 console exports global module process setInterval setTimeout
192 querystring))
193 "Node.js externs.
194 Set `js2-include-node-externs' to t to include them.")
195
196 (defvar js2-typed-array-externs
197 (mapcar 'symbol-name
198 '(ArrayBuffer Uint8ClampedArray DataView
199 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
200 Float32Array Float64Array))
201 "Khronos typed array externs. Available in most modern browsers and
202 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
203 are enabled, these will also be included.")
204
205 (defvar js2-harmony-externs
206 (mapcar 'symbol-name
207 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
208 "ES6 externs. If `js2-include-browser-externs' is enabled and
209 `js2-language-version' is sufficiently high, these will be included.")
210
211 ;;; Variables
212
213 (defun js2-mark-safe-local (name pred)
214 "Make the variable NAME buffer-local and mark it as safe file-local
215 variable with predicate PRED."
216 (make-variable-buffer-local name)
217 (put name 'safe-local-variable pred))
218
219 (defcustom js2-highlight-level 2
220 "Amount of syntax highlighting to perform.
221 0 or a negative value means none.
222 1 adds basic syntax highlighting.
223 2 adds highlighting of some Ecma built-in properties.
224 3 adds highlighting of many Ecma built-in functions."
225 :group 'js2-mode
226 :type '(choice (const :tag "None" 0)
227 (const :tag "Basic" 1)
228 (const :tag "Include Properties" 2)
229 (const :tag "Include Functions" 3)))
230
231 (defvar js2-mode-dev-mode-p nil
232 "Non-nil if running in development mode. Normally nil.")
233
234 (defgroup js2-mode nil
235 "An improved JavaScript mode."
236 :group 'languages)
237
238 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
239 (numberp c-basic-offset))
240 c-basic-offset
241 4)
242 "Number of spaces to indent nested statements.
243 Similar to `c-basic-offset'."
244 :group 'js2-mode
245 :type 'integer)
246 (js2-mark-safe-local 'js2-basic-offset 'integerp)
247
248 (defcustom js2-bounce-indent-p nil
249 "Non-nil to have indent-line function choose among alternatives.
250 If nil, the indent-line function will indent to a predetermined column
251 based on heuristic guessing. If non-nil, then if the current line is
252 already indented to that predetermined column, indenting will choose
253 another likely column and indent to that spot. Repeated invocation of
254 the indent-line function will cycle among the computed alternatives.
255 See the function `js2-bounce-indent' for details. When it is non-nil,
256 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
257 :type 'boolean
258 :group 'js2-mode)
259
260 (defcustom js2-pretty-multiline-declarations t
261 "Non-nil to line up multiline declarations vertically:
262
263 var a = 10,
264 b = 20,
265 c = 30;
266
267 If the value is t, and the first assigned value in the
268 declaration is a function/array/object literal spanning several
269 lines, it won't be indented additionally:
270
271 var o = { var bar = 2,
272 foo: 3 vs. o = {
273 }, foo: 3
274 bar = 2; };
275
276 If the value is `all', it will always be indented additionally:
277
278 var o = {
279 foo: 3
280 };
281
282 var o = {
283 foo: 3
284 },
285 bar = 2;
286
287 If the value is `dynamic', it will be indented additionally only
288 if the declaration contains more than one variable:
289
290 var o = {
291 foo: 3
292 };
293
294 var o = {
295 foo: 3
296 },
297 bar = 2;"
298 :group 'js2-mode
299 :type 'symbol)
300 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
301
302 (defcustom js2-indent-switch-body nil
303 "When nil, case labels are indented on the same level as the
304 containing switch statement. Otherwise, all lines inside
305 switch statement body are indented one additional level."
306 :type 'boolean
307 :group 'js2-mode)
308 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
309
310 (defcustom js2-idle-timer-delay 0.2
311 "Delay in secs before re-parsing after user makes changes.
312 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
313 :type 'number
314 :group 'js2-mode)
315 (make-variable-buffer-local 'js2-idle-timer-delay)
316
317 (defcustom js2-dynamic-idle-timer-adjust 0
318 "Positive to adjust `js2-idle-timer-delay' based on file size.
319 The idea is that for short files, parsing is faster so we can be
320 more responsive to user edits without interfering with editing.
321 The buffer length in characters (typically bytes) is divided by
322 this value and used to multiply `js2-idle-timer-delay' for the
323 buffer. For example, a 21k file and 10k adjust yields 21k/10k
324 == 2, so js2-idle-timer-delay is multiplied by 2.
325 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
326 `js2-idle-timer-delay' is not dependent on the file size."
327 :type 'number
328 :group 'js2-mode)
329
330 (defcustom js2-concat-multiline-strings t
331 "When non-nil, `js2-line-break' in mid-string will make it a
332 string concatenation. When `eol', the '+' will be inserted at the
333 end of the line, otherwise, at the beginning of the next line."
334 :type '(choice (const t) (const eol) (const nil))
335 :group 'js2-mode)
336
337 (defcustom js2-mode-show-parse-errors t
338 "True to highlight parse errors."
339 :type 'boolean
340 :group 'js2-mode)
341
342 (defcustom js2-mode-show-strict-warnings t
343 "Non-nil to emit Ecma strict-mode warnings.
344 Some of the warnings can be individually disabled by other flags,
345 even if this flag is non-nil."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-trailing-comma-warning t
350 "Non-nil to warn about trailing commas in array literals.
351 Ecma-262-5.1 allows them, but older versions of IE raise an error."
352 :type 'boolean
353 :group 'js2-mode)
354
355 (defcustom js2-strict-missing-semi-warning t
356 "Non-nil to warn about semicolon auto-insertion after statement.
357 Technically this is legal per Ecma-262, but some style guides disallow
358 depending on it."
359 :type 'boolean
360 :group 'js2-mode)
361
362 (defcustom js2-missing-semi-one-line-override nil
363 "Non-nil to permit missing semicolons in one-line functions.
364 In one-liner functions such as `function identity(x) {return x}'
365 people often omit the semicolon for a cleaner look. If you are
366 such a person, you can suppress the missing-semicolon warning
367 by setting this variable to t."
368 :type 'boolean
369 :group 'js2-mode)
370
371 (defcustom js2-strict-inconsistent-return-warning t
372 "Non-nil to warn about mixing returns with value-returns.
373 It's perfectly legal to have a `return' and a `return foo' in the
374 same function, but it's often an indicator of a bug, and it also
375 interferes with type inference (in systems that support it.)"
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-strict-cond-assign-warning t
380 "Non-nil to warn about expressions like if (a = b).
381 This often should have been '==' instead of '='. If the warning
382 is enabled, you can suppress it on a per-expression basis by
383 parenthesizing the expression, e.g. if ((a = b)) ..."
384 :type 'boolean
385 :group 'js2-mode)
386
387 (defcustom js2-strict-var-redeclaration-warning t
388 "Non-nil to warn about redeclaring variables in a script or function."
389 :type 'boolean
390 :group 'js2-mode)
391
392 (defcustom js2-strict-var-hides-function-arg-warning t
393 "Non-nil to warn about a var decl hiding a function argument."
394 :type 'boolean
395 :group 'js2-mode)
396
397 (defcustom js2-skip-preprocessor-directives nil
398 "Non-nil to treat lines beginning with # as comments.
399 Useful for viewing Mozilla JavaScript source code."
400 :type 'boolean
401 :group 'js2-mode)
402
403 (defcustom js2-language-version 200
404 "Configures what JavaScript language version to recognize.
405 Currently versions 150, 160, 170, 180 and 200 are supported,
406 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
407 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
408 yield, and Array comprehensions, and 1.8 adds function closures."
409 :type 'integer
410 :group 'js2-mode)
411
412 (defcustom js2-instanceof-has-side-effects nil
413 "If non-nil, treats the instanceof operator as having side effects.
414 This is useful for xulrunner apps."
415 :type 'boolean
416 :group 'js2-mode)
417
418 (defcustom js2-move-point-on-right-click t
419 "Non-nil to move insertion point when you right-click.
420 This makes right-click context menu behavior a bit more intuitive,
421 since menu operations generally apply to the point. The exception
422 is if there is a region selection, in which case the point does -not-
423 move, so cut/copy/paste can work properly.
424
425 Note that IntelliJ moves the point, and Eclipse leaves it alone,
426 so this behavior is customizable."
427 :group 'js2-mode
428 :type 'boolean)
429
430 (defcustom js2-allow-rhino-new-expr-initializer t
431 "Non-nil to support a Rhino's experimental syntactic construct.
432
433 Rhino supports the ability to follow a `new' expression with an object
434 literal, which is used to set additional properties on the new object
435 after calling its constructor. Syntax:
436
437 new <expr> [ ( arglist ) ] [initializer]
438
439 Hence, this expression:
440
441 new Object {a: 1, b: 2}
442
443 results in an Object with properties a=1 and b=2. This syntax is
444 apparently not configurable in Rhino - it's currently always enabled,
445 as of Rhino version 1.7R2."
446 :type 'boolean
447 :group 'js2-mode)
448
449 (defcustom js2-allow-member-expr-as-function-name nil
450 "Non-nil to support experimental Rhino syntax for function names.
451
452 Rhino supports an experimental syntax configured via the Rhino Context
453 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
454
455 function <member-expr> ( [ arg-list ] ) { <body> }
456
457 Where member-expr is a non-parenthesized 'member expression', which
458 is anything at the grammar level of a new-expression or lower, meaning
459 any expression that does not involve infix or unary operators.
460
461 When <member-expr> is not a simple identifier, then it is syntactic
462 sugar for assigning the anonymous function to the <member-expr>. Hence,
463 this code:
464
465 function a.b().c[2] (x, y) { ... }
466
467 is rewritten as:
468
469 a.b().c[2] = function(x, y) {...}
470
471 which doesn't seem particularly useful, but Rhino permits it."
472 :type 'boolean
473 :group 'js2-mode)
474
475 ;; scanner variables
476
477 (defmacro js2-deflocal (name value &optional comment)
478 "Define a buffer-local variable NAME with VALUE and COMMENT."
479 (declare (debug defvar) (doc-string 3))
480 `(progn
481 (defvar ,name ,value ,comment)
482 (make-variable-buffer-local ',name)))
483
484 (defvar js2-EOF_CHAR -1
485 "Represents end of stream. Distinct from js2-EOF token type.")
486
487 ;; I originally used symbols to represent tokens, but Rhino uses
488 ;; ints and then sets various flag bits in them, so ints it is.
489 ;; The upshot is that we need a `js2-' prefix in front of each name.
490 (defvar js2-ERROR -1)
491 (defvar js2-EOF 0)
492 (defvar js2-EOL 1)
493 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
494 (defvar js2-LEAVEWITH 3)
495 (defvar js2-RETURN 4)
496 (defvar js2-GOTO 5)
497 (defvar js2-IFEQ 6)
498 (defvar js2-IFNE 7)
499 (defvar js2-SETNAME 8)
500 (defvar js2-BITOR 9)
501 (defvar js2-BITXOR 10)
502 (defvar js2-BITAND 11)
503 (defvar js2-EQ 12)
504 (defvar js2-NE 13)
505 (defvar js2-LT 14)
506 (defvar js2-LE 15)
507 (defvar js2-GT 16)
508 (defvar js2-GE 17)
509 (defvar js2-LSH 18)
510 (defvar js2-RSH 19)
511 (defvar js2-URSH 20)
512 (defvar js2-ADD 21) ; infix plus
513 (defvar js2-SUB 22) ; infix minus
514 (defvar js2-MUL 23)
515 (defvar js2-DIV 24)
516 (defvar js2-MOD 25)
517 (defvar js2-NOT 26)
518 (defvar js2-BITNOT 27)
519 (defvar js2-POS 28) ; unary plus
520 (defvar js2-NEG 29) ; unary minus
521 (defvar js2-NEW 30)
522 (defvar js2-DELPROP 31)
523 (defvar js2-TYPEOF 32)
524 (defvar js2-GETPROP 33)
525 (defvar js2-GETPROPNOWARN 34)
526 (defvar js2-SETPROP 35)
527 (defvar js2-GETELEM 36)
528 (defvar js2-SETELEM 37)
529 (defvar js2-CALL 38)
530 (defvar js2-NAME 39) ; an identifier
531 (defvar js2-NUMBER 40)
532 (defvar js2-STRING 41)
533 (defvar js2-NULL 42)
534 (defvar js2-THIS 43)
535 (defvar js2-FALSE 44)
536 (defvar js2-TRUE 45)
537 (defvar js2-SHEQ 46) ; shallow equality (===)
538 (defvar js2-SHNE 47) ; shallow inequality (!==)
539 (defvar js2-REGEXP 48)
540 (defvar js2-BINDNAME 49)
541 (defvar js2-THROW 50)
542 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
543 (defvar js2-IN 52)
544 (defvar js2-INSTANCEOF 53)
545 (defvar js2-LOCAL_LOAD 54)
546 (defvar js2-GETVAR 55)
547 (defvar js2-SETVAR 56)
548 (defvar js2-CATCH_SCOPE 57)
549 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
550 (defvar js2-ENUM_INIT_VALUES 59)
551 (defvar js2-ENUM_INIT_ARRAY 60)
552 (defvar js2-ENUM_NEXT 61)
553 (defvar js2-ENUM_ID 62)
554 (defvar js2-THISFN 63)
555 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
556 (defvar js2-ARRAYLIT 65) ; array literal
557 (defvar js2-OBJECTLIT 66) ; object literal
558 (defvar js2-GET_REF 67) ; *reference
559 (defvar js2-SET_REF 68) ; *reference = something
560 (defvar js2-DEL_REF 69) ; delete reference
561 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
562 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
563 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
564
565 ;; XML support
566 (defvar js2-DEFAULTNAMESPACE 73)
567 (defvar js2-ESCXMLATTR 74)
568 (defvar js2-ESCXMLTEXT 75)
569 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
570 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
571 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
572 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
573
574 (defvar js2-first-bytecode js2-ENTERWITH)
575 (defvar js2-last-bytecode js2-REF_NS_NAME)
576
577 (defvar js2-TRY 80)
578 (defvar js2-SEMI 81) ; semicolon
579 (defvar js2-LB 82) ; left and right brackets
580 (defvar js2-RB 83)
581 (defvar js2-LC 84) ; left and right curly-braces
582 (defvar js2-RC 85)
583 (defvar js2-LP 86) ; left and right parens
584 (defvar js2-RP 87)
585 (defvar js2-COMMA 88) ; comma operator
586
587 (defvar js2-ASSIGN 89) ; simple assignment (=)
588 (defvar js2-ASSIGN_BITOR 90) ; |=
589 (defvar js2-ASSIGN_BITXOR 91) ; ^=
590 (defvar js2-ASSIGN_BITAND 92) ; &=
591 (defvar js2-ASSIGN_LSH 93) ; <<=
592 (defvar js2-ASSIGN_RSH 94) ; >>=
593 (defvar js2-ASSIGN_URSH 95) ; >>>=
594 (defvar js2-ASSIGN_ADD 96) ; +=
595 (defvar js2-ASSIGN_SUB 97) ; -=
596 (defvar js2-ASSIGN_MUL 98) ; *=
597 (defvar js2-ASSIGN_DIV 99) ; /=
598 (defvar js2-ASSIGN_MOD 100) ; %=
599
600 (defvar js2-first-assign js2-ASSIGN)
601 (defvar js2-last-assign js2-ASSIGN_MOD)
602
603 (defvar js2-HOOK 101) ; conditional (?:)
604 (defvar js2-COLON 102)
605 (defvar js2-OR 103) ; logical or (||)
606 (defvar js2-AND 104) ; logical and (&&)
607 (defvar js2-INC 105) ; increment/decrement (++ --)
608 (defvar js2-DEC 106)
609 (defvar js2-DOT 107) ; member operator (.)
610 (defvar js2-FUNCTION 108) ; function keyword
611 (defvar js2-EXPORT 109) ; export keyword
612 (defvar js2-IMPORT 110) ; import keyword
613 (defvar js2-IF 111) ; if keyword
614 (defvar js2-ELSE 112) ; else keyword
615 (defvar js2-SWITCH 113) ; switch keyword
616 (defvar js2-CASE 114) ; case keyword
617 (defvar js2-DEFAULT 115) ; default keyword
618 (defvar js2-WHILE 116) ; while keyword
619 (defvar js2-DO 117) ; do keyword
620 (defvar js2-FOR 118) ; for keyword
621 (defvar js2-BREAK 119) ; break keyword
622 (defvar js2-CONTINUE 120) ; continue keyword
623 (defvar js2-VAR 121) ; var keyword
624 (defvar js2-WITH 122) ; with keyword
625 (defvar js2-CATCH 123) ; catch keyword
626 (defvar js2-FINALLY 124) ; finally keyword
627 (defvar js2-VOID 125) ; void keyword
628 (defvar js2-RESERVED 126) ; reserved keywords
629
630 (defvar js2-EMPTY 127)
631
632 ;; Types used for the parse tree - never returned by scanner.
633
634 (defvar js2-BLOCK 128) ; statement block
635 (defvar js2-LABEL 129) ; label
636 (defvar js2-TARGET 130)
637 (defvar js2-LOOP 131)
638 (defvar js2-EXPR_VOID 132) ; expression statement in functions
639 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
640 (defvar js2-JSR 134)
641 (defvar js2-SCRIPT 135) ; top-level node for entire script
642 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
643 (defvar js2-USE_STACK 137)
644 (defvar js2-SETPROP_OP 138) ; x.y op= something
645 (defvar js2-SETELEM_OP 139) ; x[y] op= something
646 (defvar js2-LOCAL_BLOCK 140)
647 (defvar js2-SET_REF_OP 141) ; *reference op= something
648
649 ;; For XML support:
650 (defvar js2-DOTDOT 142) ; member operator (..)
651 (defvar js2-COLONCOLON 143) ; namespace::name
652 (defvar js2-XML 144) ; XML type
653 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
654 (defvar js2-XMLATTR 146) ; @
655 (defvar js2-XMLEND 147)
656
657 ;; Optimizer-only tokens
658 (defvar js2-TO_OBJECT 148)
659 (defvar js2-TO_DOUBLE 149)
660
661 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
662 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
663 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
664 (defvar js2-CONST 153)
665 (defvar js2-SETCONST 154)
666 (defvar js2-SETCONSTVAR 155)
667 (defvar js2-ARRAYCOMP 156)
668 (defvar js2-LETEXPR 157)
669 (defvar js2-WITHEXPR 158)
670 (defvar js2-DEBUGGER 159)
671
672 (defvar js2-COMMENT 160)
673 (defvar js2-TRIPLEDOT 161) ; for rest parameter
674 (defvar js2-ARROW 162) ; function arrow (=>)
675 (defvar js2-CLASS 163)
676 (defvar js2-EXTENDS 164)
677 (defvar js2-SUPER 165)
678 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
679 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
680 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
681
682 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
683
684 (defconst js2-debug-print-trees nil)
685
686 ;; Rhino accepts any string or stream as input. Emacs character
687 ;; processing works best in buffers, so we'll assume the input is a
688 ;; buffer. JavaScript strings can be copied into temp buffers before
689 ;; scanning them.
690
691 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
692 ;; They're the Emacs equivalent of instance variables, more or less.
693
694 (js2-deflocal js2-ts-dirty-line nil
695 "Token stream buffer-local variable.
696 Indicates stuff other than whitespace since start of line.")
697
698 (js2-deflocal js2-ts-hit-eof nil
699 "Token stream buffer-local variable.")
700
701 ;; FIXME: Unused.
702 (js2-deflocal js2-ts-line-start 0
703 "Token stream buffer-local variable.")
704
705 (js2-deflocal js2-ts-lineno 1
706 "Token stream buffer-local variable.")
707
708 ;; FIXME: Unused.
709 (js2-deflocal js2-ts-line-end-char -1
710 "Token stream buffer-local variable.")
711
712 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
713 "Token stream buffer-local variable.
714 Current scan position.")
715
716 ;; FIXME: Unused.
717 (js2-deflocal js2-ts-is-xml-attribute nil
718 "Token stream buffer-local variable.")
719
720 (js2-deflocal js2-ts-xml-is-tag-content nil
721 "Token stream buffer-local variable.")
722
723 (js2-deflocal js2-ts-xml-open-tags-count 0
724 "Token stream buffer-local variable.")
725
726 (js2-deflocal js2-ts-string-buffer nil
727 "Token stream buffer-local variable.
728 List of chars built up while scanning various tokens.")
729
730 (cl-defstruct (js2-token
731 (:constructor nil)
732 (:constructor make-js2-token (beg)))
733 "Value returned from the token stream."
734 (type js2-EOF)
735 (beg 1)
736 (end -1)
737 (string "")
738 number
739 number-base
740 regexp-flags
741 comment-type
742 follows-eol-p)
743
744 ;; Have to call `js2-init-scanner' to initialize the values.
745 (js2-deflocal js2-ti-tokens nil)
746 (js2-deflocal js2-ti-tokens-cursor nil)
747 (js2-deflocal js2-ti-lookahead nil)
748
749 (cl-defstruct (js2-ts-state
750 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
751 (cursor js2-ts-cursor)
752 (tokens (copy-sequence js2-ti-tokens))
753 (tokens-cursor js2-ti-tokens-cursor)
754 (lookahead js2-ti-lookahead))))
755 lineno
756 cursor
757 tokens
758 tokens-cursor
759 lookahead)
760
761 ;;; Parser variables
762
763 (js2-deflocal js2-parsed-errors nil
764 "List of errors produced during scanning/parsing.")
765
766 (js2-deflocal js2-parsed-warnings nil
767 "List of warnings produced during scanning/parsing.")
768
769 (js2-deflocal js2-recover-from-parse-errors t
770 "Non-nil to continue parsing after a syntax error.
771
772 In recovery mode, the AST will be built in full, and any error
773 nodes will be flagged with appropriate error information. If
774 this flag is nil, a syntax error will result in an error being
775 signaled.
776
777 The variable is automatically buffer-local, because different
778 modes that use the parser will need different settings.")
779
780 (js2-deflocal js2-parse-hook nil
781 "List of callbacks for receiving parsing progress.")
782
783 (defvar js2-parse-finished-hook nil
784 "List of callbacks to notify when parsing finishes.
785 Not called if parsing was interrupted.")
786
787 (js2-deflocal js2-is-eval-code nil
788 "True if we're evaluating code in a string.
789 If non-nil, the tokenizer will record the token text, and the AST nodes
790 will record their source text. Off by default for IDE modes, since the
791 text is available in the buffer.")
792
793 (defvar js2-parse-ide-mode t
794 "Non-nil if the parser is being used for `js2-mode'.
795 If non-nil, the parser will set text properties for fontification
796 and the syntax table. The value should be nil when using the
797 parser as a frontend to an interpreter or byte compiler.")
798
799 ;;; Parser instance variables (buffer-local vars for js2-parse)
800
801 (defconst js2-ti-after-eol (lsh 1 16)
802 "Flag: first token of the source line.")
803
804 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
805
806 (js2-deflocal js2-compiler-generate-debug-info t)
807 (js2-deflocal js2-compiler-use-dynamic-scope nil)
808 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
809 (js2-deflocal js2-compiler-xml-available t)
810 (js2-deflocal js2-compiler-optimization-level 0)
811 (js2-deflocal js2-compiler-generating-source t)
812 (js2-deflocal js2-compiler-strict-mode nil)
813 (js2-deflocal js2-compiler-report-warning-as-error nil)
814 (js2-deflocal js2-compiler-generate-observer-count nil)
815 (js2-deflocal js2-compiler-activation-names nil)
816
817 ;; SKIP: sourceURI
818
819 ;; There's a compileFunction method in Context.java - may need it.
820 (js2-deflocal js2-called-by-compile-function nil
821 "True if `js2-parse' was called by `js2-compile-function'.
822 Will only be used when we finish implementing the interpreter.")
823
824 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
825
826 ;; SKIP: node factory - we're going to just call functions directly,
827 ;; and eventually go to a unified AST format.
828
829 (js2-deflocal js2-nesting-of-function 0)
830
831 (js2-deflocal js2-recorded-identifiers nil
832 "Tracks identifiers found during parsing.")
833
834 (js2-deflocal js2-is-in-destructuring nil
835 "True while parsing destructuring expression.")
836
837 (js2-deflocal js2-in-use-strict-directive nil
838 "True while inside a script or function under strict mode.")
839
840 (defcustom js2-global-externs nil
841 "A list of any extern names you'd like to consider always declared.
842 This list is global and is used by all `js2-mode' files.
843 You can create buffer-local externs list using `js2-additional-externs'.
844
845 There is also a buffer-local variable `js2-default-externs',
846 which is initialized by default to include the Ecma-262 externs
847 and the standard browser externs. The three lists are all
848 checked during highlighting."
849 :type 'list
850 :group 'js2-mode)
851
852 (js2-deflocal js2-default-externs nil
853 "Default external declarations.
854
855 These are currently only used for highlighting undeclared variables,
856 which only worries about top-level (unqualified) references.
857 As js2-mode's processing improves, we will flesh out this list.
858
859 The initial value is set to `js2-ecma-262-externs', unless some
860 of the `js2-include-?-externs' variables are set to t, in which
861 case the browser, Rhino and/or Node.js externs are also included.
862
863 See `js2-additional-externs' for more information.")
864
865 (defcustom js2-include-browser-externs t
866 "Non-nil to include browser externs in the master externs list.
867 If you work on JavaScript files that are not intended for browsers,
868 such as Mozilla Rhino server-side JavaScript, set this to nil.
869 See `js2-additional-externs' for more information about externs."
870 :type 'boolean
871 :group 'js2-mode)
872
873 (defcustom js2-include-rhino-externs nil
874 "Non-nil to include Mozilla Rhino externs in the master externs list.
875 See `js2-additional-externs' for more information about externs."
876 :type 'boolean
877 :group 'js2-mode)
878
879 (defcustom js2-include-node-externs nil
880 "Non-nil to include Node.js externs in the master externs list.
881 See `js2-additional-externs' for more information about externs."
882 :type 'boolean
883 :group 'js2-mode)
884
885 (js2-deflocal js2-additional-externs nil
886 "A buffer-local list of additional external declarations.
887 It is used to decide whether variables are considered undeclared
888 for purposes of highlighting.
889
890 Each entry is a Lisp string. The string should be the fully qualified
891 name of an external entity. All externs should be added to this list,
892 so that as js2-mode's processing improves it can take advantage of them.
893
894 You may want to declare your externs in three ways.
895 First, you can add externs that are valid for all your JavaScript files.
896 You should probably do this by adding them to `js2-global-externs', which
897 is a global list used for all js2-mode files.
898
899 Next, you can add a function to `js2-init-hook' that adds additional
900 externs appropriate for the specific file, perhaps based on its path.
901 These should go in `js2-additional-externs', which is buffer-local.
902
903 Third, you can use JSLint's global declaration, as long as
904 `js2-include-jslint-globals' is non-nil, which see.
905
906 Finally, you can add a function to `js2-post-parse-callbacks',
907 which is called after parsing completes, and `js2-mode-ast' is bound to
908 the root of the parse tree. At this stage you can set up an AST
909 node visitor using `js2-visit-ast' and examine the parse tree
910 for specific import patterns that may imply the existence of
911 other externs, possibly tied to your build system. These should also
912 be added to `js2-additional-externs'.
913
914 Your post-parse callback may of course also use the simpler and
915 faster (but perhaps less robust) approach of simply scanning the
916 buffer text for your imports, using regular expressions.")
917
918 ;; SKIP: decompiler
919 ;; SKIP: encoded-source
920
921 ;;; The following variables are per-function and should be saved/restored
922 ;;; during function parsing...
923
924 (js2-deflocal js2-current-script-or-fn nil)
925 (js2-deflocal js2-current-scope nil)
926 (js2-deflocal js2-nesting-of-with 0)
927 (js2-deflocal js2-label-set nil
928 "An alist mapping label names to nodes.")
929
930 (js2-deflocal js2-loop-set nil)
931 (js2-deflocal js2-loop-and-switch-set nil)
932 (js2-deflocal js2-has-return-value nil)
933 (js2-deflocal js2-end-flags 0)
934
935 ;;; ...end of per function variables
936
937 ;; These flags enumerate the possible ways a statement/function can
938 ;; terminate. These flags are used by endCheck() and by the Parser to
939 ;; detect inconsistent return usage.
940 ;;
941 ;; END_UNREACHED is reserved for code paths that are assumed to always be
942 ;; able to execute (example: throw, continue)
943 ;;
944 ;; END_DROPS_OFF indicates if the statement can transfer control to the
945 ;; next one. Statement such as return dont. A compound statement may have
946 ;; some branch that drops off control to the next statement.
947 ;;
948 ;; END_RETURNS indicates that the statement can return (without arguments)
949 ;; END_RETURNS_VALUE indicates that the statement can return a value.
950 ;;
951 ;; A compound statement such as
952 ;; if (condition) {
953 ;; return value;
954 ;; }
955 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
956
957 (defconst js2-end-unreached #x0)
958 (defconst js2-end-drops-off #x1)
959 (defconst js2-end-returns #x2)
960 (defconst js2-end-returns-value #x4)
961
962 ;; Rhino awkwardly passes a statementLabel parameter to the
963 ;; statementHelper() function, the main statement parser, which
964 ;; is then used by quite a few of the sub-parsers. We just make
965 ;; it a buffer-local variable and make sure it's cleaned up properly.
966 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
967
968 ;; Similarly, Rhino passes an inForInit boolean through about half
969 ;; the expression parsers. We use a dynamically-scoped variable,
970 ;; which makes it easier to funcall the parsers individually without
971 ;; worrying about whether they take the parameter or not.
972 (js2-deflocal js2-in-for-init nil)
973 (js2-deflocal js2-temp-name-counter 0)
974 (js2-deflocal js2-parse-stmt-count 0)
975
976 (defsubst js2-get-next-temp-name ()
977 (format "$%d" (cl-incf js2-temp-name-counter)))
978
979 (defvar js2-parse-interruptable-p t
980 "Set this to nil to force parse to continue until finished.
981 This will mostly be useful for interpreters.")
982
983 (defvar js2-statements-per-pause 50
984 "Pause after this many statements to check for user input.
985 If user input is pending, stop the parse and discard the tree.
986 This makes for a smoother user experience for large files.
987 You may have to wait a second or two before the highlighting
988 and error-reporting appear, but you can always type ahead if
989 you wish. This appears to be more or less how Eclipse, IntelliJ
990 and other editors work.")
991
992 (js2-deflocal js2-record-comments t
993 "Instructs the scanner to record comments in `js2-scanned-comments'.")
994
995 (js2-deflocal js2-scanned-comments nil
996 "List of all comments from the current parse.")
997
998 (defcustom js2-mode-indent-inhibit-undo nil
999 "Non-nil to disable collection of Undo information when indenting lines.
1000 Some users have requested this behavior. It's nil by default because
1001 other Emacs modes don't work this way."
1002 :type 'boolean
1003 :group 'js2-mode)
1004
1005 (defcustom js2-mode-indent-ignore-first-tab nil
1006 "If non-nil, ignore first TAB keypress if we look indented properly.
1007 It's fairly common for users to navigate to an already-indented line
1008 and press TAB for reassurance that it's been indented. For this class
1009 of users, we want the first TAB press on a line to be ignored if the
1010 line is already indented to one of the precomputed alternatives.
1011
1012 This behavior is only partly implemented. If you TAB-indent a line,
1013 navigate to another line, and then navigate back, it fails to clear
1014 the last-indented variable, so it thinks you've already hit TAB once,
1015 and performs the indent. A full solution would involve getting on the
1016 point-motion hooks for the entire buffer. If we come across another
1017 use cases that requires watching point motion, I'll consider doing it.
1018
1019 If you set this variable to nil, then the TAB key will always change
1020 the indentation of the current line, if more than one alternative
1021 indentation spot exists."
1022 :type 'boolean
1023 :group 'js2-mode)
1024
1025 (defvar js2-indent-hook nil
1026 "A hook for user-defined indentation rules.
1027
1028 Functions on this hook should expect two arguments: (LIST INDEX)
1029 The LIST argument is the list of computed indentation points for
1030 the current line. INDEX is the list index of the indentation point
1031 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1032 indent function is not going to change the current line indentation.
1033
1034 If a hook function on this list returns a non-nil value, then
1035 `js2-bounce-indent' assumes the hook function has performed its own
1036 indentation, and will do nothing. If all hook functions on the list
1037 return nil, then `js2-bounce-indent' will use its computed indentation
1038 and reindent the line.
1039
1040 When hook functions on this hook list are called, the variable
1041 `js2-mode-ast' may or may not be set, depending on whether the
1042 parse tree is available. If the variable is nil, you can pass a
1043 callback to `js2-mode-wait-for-parse', and your callback will be
1044 called after the new parse tree is built. This can take some time
1045 in large files.")
1046
1047 (defface js2-warning
1048 `((((class color) (background light))
1049 (:underline "orange"))
1050 (((class color) (background dark))
1051 (:underline "orange"))
1052 (t (:underline t)))
1053 "Face for JavaScript warnings."
1054 :group 'js2-mode)
1055
1056 (defface js2-error
1057 `((((class color) (background light))
1058 (:foreground "red"))
1059 (((class color) (background dark))
1060 (:foreground "red"))
1061 (t (:foreground "red")))
1062 "Face for JavaScript errors."
1063 :group 'js2-mode)
1064
1065 (defface js2-jsdoc-tag
1066 '((t :foreground "SlateGray"))
1067 "Face used to highlight @whatever tags in jsdoc comments."
1068 :group 'js2-mode)
1069
1070 (defface js2-jsdoc-type
1071 '((t :foreground "SteelBlue"))
1072 "Face used to highlight {FooBar} types in jsdoc comments."
1073 :group 'js2-mode)
1074
1075 (defface js2-jsdoc-value
1076 '((t :foreground "PeachPuff3"))
1077 "Face used to highlight tag values in jsdoc comments."
1078 :group 'js2-mode)
1079
1080 (defface js2-function-param
1081 '((t :foreground "SeaGreen"))
1082 "Face used to highlight function parameters in javascript."
1083 :group 'js2-mode)
1084
1085 (defface js2-function-call
1086 '((t :inherit default))
1087 "Face used to highlight function name in calls."
1088 :group 'js2-mode)
1089
1090 (defface js2-instance-member
1091 '((t :foreground "DarkOrchid"))
1092 "Face used to highlight instance variables in javascript.
1093 Not currently used."
1094 :group 'js2-mode)
1095
1096 (defface js2-private-member
1097 '((t :foreground "PeachPuff3"))
1098 "Face used to highlight calls to private methods in javascript.
1099 Not currently used."
1100 :group 'js2-mode)
1101
1102 (defface js2-private-function-call
1103 '((t :foreground "goldenrod"))
1104 "Face used to highlight calls to private functions in javascript.
1105 Not currently used."
1106 :group 'js2-mode)
1107
1108 (defface js2-jsdoc-html-tag-name
1109 '((((class color) (min-colors 88) (background light))
1110 (:foreground "rosybrown"))
1111 (((class color) (min-colors 8) (background dark))
1112 (:foreground "yellow"))
1113 (((class color) (min-colors 8) (background light))
1114 (:foreground "magenta")))
1115 "Face used to highlight jsdoc html tag names"
1116 :group 'js2-mode)
1117
1118 (defface js2-jsdoc-html-tag-delimiter
1119 '((((class color) (min-colors 88) (background light))
1120 (:foreground "dark khaki"))
1121 (((class color) (min-colors 8) (background dark))
1122 (:foreground "green"))
1123 (((class color) (min-colors 8) (background light))
1124 (:foreground "green")))
1125 "Face used to highlight brackets in jsdoc html tags."
1126 :group 'js2-mode)
1127
1128 (defface js2-external-variable
1129 '((t :foreground "orange"))
1130 "Face used to highlight undeclared variable identifiers.")
1131
1132 (defcustom js2-init-hook nil
1133 "List of functions to be called after `js2-mode' or
1134 `js2-minor-mode' has initialized all variables, before parsing
1135 the buffer for the first time."
1136 :type 'hook
1137 :group 'js2-mode
1138 :version "20130608")
1139
1140 (defcustom js2-post-parse-callbacks nil
1141 "List of callback functions invoked after parsing finishes.
1142 Currently, the main use for this function is to add synthetic
1143 declarations to `js2-recorded-identifiers', which see."
1144 :type 'hook
1145 :group 'js2-mode)
1146
1147 (defcustom js2-build-imenu-callbacks nil
1148 "List of functions called during Imenu index generation.
1149 It's a good place to add additional entries to it, using
1150 `js2-record-imenu-entry'."
1151 :type 'hook
1152 :group 'js2-mode)
1153
1154 (defcustom js2-highlight-external-variables t
1155 "Non-nil to highlight undeclared variable identifiers.
1156 An undeclared variable is any variable not declared with var or let
1157 in the current scope or any lexically enclosing scope. If you use
1158 such a variable, then you are either expecting it to originate from
1159 another file, or you've got a potential bug."
1160 :type 'boolean
1161 :group 'js2-mode)
1162
1163 (defcustom js2-warn-about-unused-function-arguments nil
1164 "Non-nil to treat function arguments like declared-but-unused variables."
1165 :type 'booleanp
1166 :group 'js2-mode)
1167
1168 (defcustom js2-include-jslint-globals t
1169 "Non-nil to include the identifiers from JSLint global
1170 declaration (see http://www.jslint.com/lint.html#global) in the
1171 buffer-local externs list. See `js2-additional-externs' for more
1172 information."
1173 :type 'boolean
1174 :group 'js2-mode)
1175
1176 (defvar js2-mode-map
1177 (let ((map (make-sparse-keymap)))
1178 (define-key map [mouse-1] #'js2-mode-show-node)
1179 (define-key map (kbd "M-j") #'js2-line-break)
1180 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1181 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1182 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1183 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1184 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1185 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1186 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1187 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1188 (when js2-bounce-indent-p
1189 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1190
1191 (define-key map [menu-bar javascript]
1192 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1193
1194 (define-key map [menu-bar javascript customize-js2-mode]
1195 '(menu-item "Customize js2-mode" js2-mode-customize
1196 :help "Customize the behavior of this mode"))
1197
1198 (define-key map [menu-bar javascript js2-force-refresh]
1199 '(menu-item "Force buffer refresh" js2-mode-reset
1200 :help "Re-parse the buffer from scratch"))
1201
1202 (define-key map [menu-bar javascript separator-2]
1203 '("--"))
1204
1205 (define-key map [menu-bar javascript next-error]
1206 '(menu-item "Next warning or error" next-error
1207 :enabled (and js2-mode-ast
1208 (or (js2-ast-root-errors js2-mode-ast)
1209 (js2-ast-root-warnings js2-mode-ast)))
1210 :help "Move to next warning or error"))
1211
1212 (define-key map [menu-bar javascript display-errors]
1213 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1214 :visible (not js2-mode-show-parse-errors)
1215 :help "Turn on display of warnings and errors"))
1216
1217 (define-key map [menu-bar javascript hide-errors]
1218 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1219 :visible js2-mode-show-parse-errors
1220 :help "Turn off display of warnings and errors"))
1221
1222 (define-key map [menu-bar javascript separator-1]
1223 '("--"))
1224
1225 (define-key map [menu-bar javascript js2-toggle-function]
1226 '(menu-item "Show/collapse element" js2-mode-toggle-element
1227 :help "Hide or show function body or comment"))
1228
1229 (define-key map [menu-bar javascript show-comments]
1230 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1231 :visible js2-mode-comments-hidden
1232 :help "Expand all hidden block comments"))
1233
1234 (define-key map [menu-bar javascript hide-comments]
1235 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1236 :visible (not js2-mode-comments-hidden)
1237 :help "Show block comments as /*...*/"))
1238
1239 (define-key map [menu-bar javascript show-all-functions]
1240 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1241 :visible js2-mode-functions-hidden
1242 :help "Expand all hidden function bodies"))
1243
1244 (define-key map [menu-bar javascript hide-all-functions]
1245 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1246 :visible (not js2-mode-functions-hidden)
1247 :help "Show {...} for all top-level function bodies"))
1248
1249 map)
1250 "Keymap used in `js2-mode' buffers.")
1251
1252 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1253
1254 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1255 "Matches a //-comment line. Must be first non-whitespace on line.
1256 First match-group is the leading whitespace.")
1257
1258 (defvar js2-mode-hook nil)
1259
1260 (js2-deflocal js2-mode-ast nil "Private variable.")
1261 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1262 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1263 (js2-deflocal js2-mode-parsing nil "Private variable.")
1264 (js2-deflocal js2-mode-node-overlay nil)
1265
1266 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1267 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1268
1269 (js2-deflocal js2-mode-fontifications nil "Private variable")
1270 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1271 (js2-deflocal js2-imenu-recorder nil "Private variable")
1272 (js2-deflocal js2-imenu-function-map nil "Private variable")
1273
1274 (defvar js2-paragraph-start
1275 "\\(@[[:alpha:]]+\\>\\|$\\)")
1276
1277 ;; Note that we also set a 'c-in-sws text property in html comments,
1278 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1279 (defvar js2-syntactic-ws-start
1280 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1281
1282 (defvar js2-syntactic-ws-end
1283 "\\s \\|[\n\r/]\\|\\s!")
1284
1285 (defvar js2-syntactic-eol
1286 (concat "\\s *\\(/\\*[^*\n\r]*"
1287 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1288 "\\*+/\\s *\\)*"
1289 "\\(//\\|/\\*[^*\n\r]*"
1290 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1291 "\\|\\\\$\\|$\\)")
1292 "Copied from `java-mode'. Needed for some cc-engine functions.")
1293
1294 (defvar js2-comment-prefix-regexp
1295 "//+\\|\\**")
1296
1297 (defvar js2-comment-start-skip
1298 "\\(//+\\|/\\*+\\)\\s *")
1299
1300 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1301 "Non-nil to emit status messages during parsing.")
1302
1303 (defvar js2-mode-functions-hidden nil "Private variable.")
1304 (defvar js2-mode-comments-hidden nil "Private variable.")
1305
1306 (defvar js2-mode-syntax-table
1307 (let ((table (make-syntax-table)))
1308 (c-populate-syntax-table table)
1309 (modify-syntax-entry ?` "\"" table)
1310 table)
1311 "Syntax table used in `js2-mode' buffers.")
1312
1313 (defvar js2-mode-abbrev-table nil
1314 "Abbrev table in use in `js2-mode' buffers.")
1315 (define-abbrev-table 'js2-mode-abbrev-table ())
1316
1317 (defvar js2-mode-pending-parse-callbacks nil
1318 "List of functions waiting to be notified that parse is finished.")
1319
1320 (defvar js2-mode-last-indented-line -1)
1321
1322 ;;; Localizable error and warning messages
1323
1324 ;; Messages are copied from Rhino's Messages.properties.
1325 ;; Many of the Java-specific messages have been elided.
1326 ;; Add any js2-specific ones at the end, so we can keep
1327 ;; this file synced with changes to Rhino's.
1328
1329 (defvar js2-message-table
1330 (make-hash-table :test 'equal :size 250)
1331 "Contains localized messages for `js2-mode'.")
1332
1333 ;; TODO(stevey): construct this table at compile-time.
1334 (defmacro js2-msg (key &rest strings)
1335 `(puthash ,key (concat ,@strings)
1336 js2-message-table))
1337
1338 (defun js2-get-msg (msg-key)
1339 "Look up a localized message.
1340 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1341 the correct number of ARGS must be provided."
1342 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1343 (args (if (listp msg-key) (cdr msg-key)))
1344 (msg (gethash key js2-message-table)))
1345 (if msg
1346 (apply #'format msg args)
1347 key))) ; default to showing the key
1348
1349 (js2-msg "msg.dup.parms"
1350 "Duplicate parameter name '%s'.")
1351
1352 (js2-msg "msg.too.big.jump"
1353 "Program too complex: jump offset too big.")
1354
1355 (js2-msg "msg.too.big.index"
1356 "Program too complex: internal index exceeds 64K limit.")
1357
1358 (js2-msg "msg.while.compiling.fn"
1359 "Encountered code generation error while compiling function '%s': %s")
1360
1361 (js2-msg "msg.while.compiling.script"
1362 "Encountered code generation error while compiling script: %s")
1363
1364 ;; Context
1365 (js2-msg "msg.ctor.not.found"
1366 "Constructor for '%s' not found.")
1367
1368 (js2-msg "msg.not.ctor"
1369 "'%s' is not a constructor.")
1370
1371 ;; FunctionObject
1372 (js2-msg "msg.varargs.ctor"
1373 "Method or constructor '%s' must be static "
1374 "with the signature (Context cx, Object[] args, "
1375 "Function ctorObj, boolean inNewExpr) "
1376 "to define a variable arguments constructor.")
1377
1378 (js2-msg "msg.varargs.fun"
1379 "Method '%s' must be static with the signature "
1380 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1381 "to define a variable arguments function.")
1382
1383 (js2-msg "msg.incompat.call"
1384 "Method '%s' called on incompatible object.")
1385
1386 (js2-msg "msg.bad.parms"
1387 "Unsupported parameter type '%s' in method '%s'.")
1388
1389 (js2-msg "msg.bad.method.return"
1390 "Unsupported return type '%s' in method '%s'.")
1391
1392 (js2-msg "msg.bad.ctor.return"
1393 "Construction of objects of type '%s' is not supported.")
1394
1395 (js2-msg "msg.no.overload"
1396 "Method '%s' occurs multiple times in class '%s'.")
1397
1398 (js2-msg "msg.method.not.found"
1399 "Method '%s' not found in '%s'.")
1400
1401 ;; IRFactory
1402
1403 (js2-msg "msg.bad.for.in.lhs"
1404 "Invalid left-hand side of for..in loop.")
1405
1406 (js2-msg "msg.mult.index"
1407 "Only one variable allowed in for..in loop.")
1408
1409 (js2-msg "msg.bad.for.in.destruct"
1410 "Left hand side of for..in loop must be an array of "
1411 "length 2 to accept key/value pair.")
1412
1413 (js2-msg "msg.cant.convert"
1414 "Can't convert to type '%s'.")
1415
1416 (js2-msg "msg.bad.assign.left"
1417 "Invalid assignment left-hand side.")
1418
1419 (js2-msg "msg.bad.decr"
1420 "Invalid decrement operand.")
1421
1422 (js2-msg "msg.bad.incr"
1423 "Invalid increment operand.")
1424
1425 (js2-msg "msg.bad.yield"
1426 "yield must be in a function.")
1427
1428 (js2-msg "msg.yield.parenthesized"
1429 "yield expression must be parenthesized.")
1430
1431 ;; NativeGlobal
1432 (js2-msg "msg.cant.call.indirect"
1433 "Function '%s' must be called directly, and not by way of a "
1434 "function of another name.")
1435
1436 (js2-msg "msg.eval.nonstring"
1437 "Calling eval() with anything other than a primitive "
1438 "string value will simply return the value. "
1439 "Is this what you intended?")
1440
1441 (js2-msg "msg.eval.nonstring.strict"
1442 "Calling eval() with anything other than a primitive "
1443 "string value is not allowed in strict mode.")
1444
1445 (js2-msg "msg.bad.destruct.op"
1446 "Invalid destructuring assignment operator")
1447
1448 ;; NativeCall
1449 (js2-msg "msg.only.from.new"
1450 "'%s' may only be invoked from a `new' expression.")
1451
1452 (js2-msg "msg.deprec.ctor"
1453 "The '%s' constructor is deprecated.")
1454
1455 ;; NativeFunction
1456 (js2-msg "msg.no.function.ref.found"
1457 "no source found to decompile function reference %s")
1458
1459 (js2-msg "msg.arg.isnt.array"
1460 "second argument to Function.prototype.apply must be an array")
1461
1462 ;; NativeGlobal
1463 (js2-msg "msg.bad.esc.mask"
1464 "invalid string escape mask")
1465
1466 ;; NativeRegExp
1467 (js2-msg "msg.bad.quant"
1468 "Invalid quantifier %s")
1469
1470 (js2-msg "msg.overlarge.backref"
1471 "Overly large back reference %s")
1472
1473 (js2-msg "msg.overlarge.min"
1474 "Overly large minimum %s")
1475
1476 (js2-msg "msg.overlarge.max"
1477 "Overly large maximum %s")
1478
1479 (js2-msg "msg.zero.quant"
1480 "Zero quantifier %s")
1481
1482 (js2-msg "msg.max.lt.min"
1483 "Maximum %s less than minimum")
1484
1485 (js2-msg "msg.unterm.quant"
1486 "Unterminated quantifier %s")
1487
1488 (js2-msg "msg.unterm.paren"
1489 "Unterminated parenthetical %s")
1490
1491 (js2-msg "msg.unterm.class"
1492 "Unterminated character class %s")
1493
1494 (js2-msg "msg.bad.range"
1495 "Invalid range in character class.")
1496
1497 (js2-msg "msg.trail.backslash"
1498 "Trailing \\ in regular expression.")
1499
1500 (js2-msg "msg.re.unmatched.right.paren"
1501 "unmatched ) in regular expression.")
1502
1503 (js2-msg "msg.no.regexp"
1504 "Regular expressions are not available.")
1505
1506 (js2-msg "msg.bad.backref"
1507 "back-reference exceeds number of capturing parentheses.")
1508
1509 (js2-msg "msg.bad.regexp.compile"
1510 "Only one argument may be specified if the first "
1511 "argument to RegExp.prototype.compile is a RegExp object.")
1512
1513 ;; Parser
1514 (js2-msg "msg.got.syntax.errors"
1515 "Compilation produced %s syntax errors.")
1516
1517 (js2-msg "msg.var.redecl"
1518 "TypeError: redeclaration of var %s.")
1519
1520 (js2-msg "msg.const.redecl"
1521 "TypeError: redeclaration of const %s.")
1522
1523 (js2-msg "msg.let.redecl"
1524 "TypeError: redeclaration of variable %s.")
1525
1526 (js2-msg "msg.parm.redecl"
1527 "TypeError: redeclaration of formal parameter %s.")
1528
1529 (js2-msg "msg.fn.redecl"
1530 "TypeError: redeclaration of function %s.")
1531
1532 (js2-msg "msg.let.decl.not.in.block"
1533 "SyntaxError: let declaration not directly within block")
1534
1535 (js2-msg "msg.mod.import.decl.at.top.level"
1536 "SyntaxError: import declarations may only appear at the top level")
1537
1538 (js2-msg "msg.mod.as.after.reserved.word"
1539 "SyntaxError: missing keyword 'as' after reserved word %s")
1540
1541 (js2-msg "msg.mod.rc.after.import.spec.list"
1542 "SyntaxError: missing '}' after module specifier list")
1543
1544 (js2-msg "msg.mod.from.after.import.spec.set"
1545 "SyntaxError: missing keyword 'from' after import specifier set")
1546
1547 (js2-msg "msg.mod.declaration.after.import"
1548 "SyntaxError: missing declaration after 'import' keyword")
1549
1550 (js2-msg "msg.mod.spec.after.from"
1551 "SyntaxError: missing module specifier after 'from' keyword")
1552
1553 (js2-msg "msg.mod.export.decl.at.top.level"
1554 "SyntaxError: export declarations may only appear at top level")
1555
1556 (js2-msg "msg.mod.rc.after.export.spec.list"
1557 "SyntaxError: missing '}' after export specifier list")
1558
1559 ;; NodeTransformer
1560 (js2-msg "msg.dup.label"
1561 "duplicated label")
1562
1563 (js2-msg "msg.undef.label"
1564 "undefined label")
1565
1566 (js2-msg "msg.bad.break"
1567 "unlabelled break must be inside loop or switch")
1568
1569 (js2-msg "msg.continue.outside"
1570 "continue must be inside loop")
1571
1572 (js2-msg "msg.continue.nonloop"
1573 "continue can only use labels of iteration statements")
1574
1575 (js2-msg "msg.bad.throw.eol"
1576 "Line terminator is not allowed between the throw "
1577 "keyword and throw expression.")
1578
1579 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1580 "function statement requires a name")
1581
1582 (js2-msg "msg.no.paren.parms"
1583 "missing ( before function parameters.")
1584
1585 (js2-msg "msg.no.parm"
1586 "missing formal parameter")
1587
1588 (js2-msg "msg.no.paren.after.parms"
1589 "missing ) after formal parameters")
1590
1591 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1592 "parameter without default follows parameter with default")
1593
1594 (js2-msg "msg.param.after.rest" ; added by js2-mode
1595 "parameter after rest parameter")
1596
1597 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1598 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1599
1600 (js2-msg "msg.no.brace.body"
1601 "missing '{' before function body")
1602
1603 (js2-msg "msg.no.brace.after.body"
1604 "missing } after function body")
1605
1606 (js2-msg "msg.no.paren.cond"
1607 "missing ( before condition")
1608
1609 (js2-msg "msg.no.paren.after.cond"
1610 "missing ) after condition")
1611
1612 (js2-msg "msg.no.semi.stmt"
1613 "missing ; before statement")
1614
1615 (js2-msg "msg.missing.semi"
1616 "missing ; after statement")
1617
1618 (js2-msg "msg.no.name.after.dot"
1619 "missing name after . operator")
1620
1621 (js2-msg "msg.no.name.after.coloncolon"
1622 "missing name after :: operator")
1623
1624 (js2-msg "msg.no.name.after.dotdot"
1625 "missing name after .. operator")
1626
1627 (js2-msg "msg.no.name.after.xmlAttr"
1628 "missing name after .@")
1629
1630 (js2-msg "msg.no.bracket.index"
1631 "missing ] in index expression")
1632
1633 (js2-msg "msg.no.paren.switch"
1634 "missing ( before switch expression")
1635
1636 (js2-msg "msg.no.paren.after.switch"
1637 "missing ) after switch expression")
1638
1639 (js2-msg "msg.no.brace.switch"
1640 "missing '{' before switch body")
1641
1642 (js2-msg "msg.bad.switch"
1643 "invalid switch statement")
1644
1645 (js2-msg "msg.no.colon.case"
1646 "missing : after case expression")
1647
1648 (js2-msg "msg.double.switch.default"
1649 "double default label in the switch statement")
1650
1651 (js2-msg "msg.no.while.do"
1652 "missing while after do-loop body")
1653
1654 (js2-msg "msg.no.paren.for"
1655 "missing ( after for")
1656
1657 (js2-msg "msg.no.semi.for"
1658 "missing ; after for-loop initializer")
1659
1660 (js2-msg "msg.no.semi.for.cond"
1661 "missing ; after for-loop condition")
1662
1663 (js2-msg "msg.in.after.for.name"
1664 "missing in or of after for")
1665
1666 (js2-msg "msg.no.paren.for.ctrl"
1667 "missing ) after for-loop control")
1668
1669 (js2-msg "msg.no.paren.with"
1670 "missing ( before with-statement object")
1671
1672 (js2-msg "msg.no.paren.after.with"
1673 "missing ) after with-statement object")
1674
1675 (js2-msg "msg.no.with.strict"
1676 "with statements not allowed in strict mode")
1677
1678 (js2-msg "msg.no.paren.after.let"
1679 "missing ( after let")
1680
1681 (js2-msg "msg.no.paren.let"
1682 "missing ) after variable list")
1683
1684 (js2-msg "msg.no.curly.let"
1685 "missing } after let statement")
1686
1687 (js2-msg "msg.bad.return"
1688 "invalid return")
1689
1690 (js2-msg "msg.no.brace.block"
1691 "missing } in compound statement")
1692
1693 (js2-msg "msg.bad.label"
1694 "invalid label")
1695
1696 (js2-msg "msg.bad.var"
1697 "missing variable name")
1698
1699 (js2-msg "msg.bad.var.init"
1700 "invalid variable initialization")
1701
1702 (js2-msg "msg.no.colon.cond"
1703 "missing : in conditional expression")
1704
1705 (js2-msg "msg.no.paren.arg"
1706 "missing ) after argument list")
1707
1708 (js2-msg "msg.no.bracket.arg"
1709 "missing ] after element list")
1710
1711 (js2-msg "msg.bad.prop"
1712 "invalid property id")
1713
1714 (js2-msg "msg.no.colon.prop"
1715 "missing : after property id")
1716
1717 (js2-msg "msg.no.brace.prop"
1718 "missing } after property list")
1719
1720 (js2-msg "msg.no.paren"
1721 "missing ) in parenthetical")
1722
1723 (js2-msg "msg.reserved.id"
1724 "'%s' is a reserved identifier")
1725
1726 (js2-msg "msg.no.paren.catch"
1727 "missing ( before catch-block condition")
1728
1729 (js2-msg "msg.bad.catchcond"
1730 "invalid catch block condition")
1731
1732 (js2-msg "msg.catch.unreachable"
1733 "any catch clauses following an unqualified catch are unreachable")
1734
1735 (js2-msg "msg.no.brace.try"
1736 "missing '{' before try block")
1737
1738 (js2-msg "msg.no.brace.catchblock"
1739 "missing '{' before catch-block body")
1740
1741 (js2-msg "msg.try.no.catchfinally"
1742 "'try' without 'catch' or 'finally'")
1743
1744 (js2-msg "msg.no.return.value"
1745 "function %s does not always return a value")
1746
1747 (js2-msg "msg.anon.no.return.value"
1748 "anonymous function does not always return a value")
1749
1750 (js2-msg "msg.return.inconsistent"
1751 "return statement is inconsistent with previous usage")
1752
1753 (js2-msg "msg.generator.returns"
1754 "TypeError: legacy generator function '%s' returns a value")
1755
1756 (js2-msg "msg.anon.generator.returns"
1757 "TypeError: anonymous legacy generator function returns a value")
1758
1759 (js2-msg "msg.syntax"
1760 "syntax error")
1761
1762 (js2-msg "msg.unexpected.eof"
1763 "Unexpected end of file")
1764
1765 (js2-msg "msg.XML.bad.form"
1766 "illegally formed XML syntax")
1767
1768 (js2-msg "msg.XML.not.available"
1769 "XML runtime not available")
1770
1771 (js2-msg "msg.too.deep.parser.recursion"
1772 "Too deep recursion while parsing")
1773
1774 (js2-msg "msg.no.side.effects"
1775 "Code has no side effects")
1776
1777 (js2-msg "msg.extra.trailing.comma"
1778 "Trailing comma is not supported in some browsers")
1779
1780 (js2-msg "msg.array.trailing.comma"
1781 "Trailing comma yields different behavior across browsers")
1782
1783 (js2-msg "msg.equal.as.assign"
1784 (concat "Test for equality (==) mistyped as assignment (=)?"
1785 " (parenthesize to suppress warning)"))
1786
1787 (js2-msg "msg.var.hides.arg"
1788 "Variable %s hides argument")
1789
1790 (js2-msg "msg.destruct.assign.no.init"
1791 "Missing = in destructuring declaration")
1792
1793 (js2-msg "msg.no.octal.strict"
1794 "Octal numbers prohibited in strict mode.")
1795
1796 (js2-msg "msg.dup.param.strict"
1797 "Parameter '%s' already declared in this function.")
1798
1799 (js2-msg "msg.bad.id.strict"
1800 "'%s' is not a valid identifier for this use in strict mode.")
1801
1802 ;; ScriptRuntime
1803 (js2-msg "msg.no.properties"
1804 "%s has no properties.")
1805
1806 (js2-msg "msg.invalid.iterator"
1807 "Invalid iterator value")
1808
1809 (js2-msg "msg.iterator.primitive"
1810 "__iterator__ returned a primitive value")
1811
1812 (js2-msg "msg.assn.create.strict"
1813 "Assignment to undeclared variable %s")
1814
1815 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1816 "Undeclared variable or function '%s'")
1817
1818 (js2-msg "msg.unused.variable" ; added by js2-mode
1819 "Unused variable or function '%s'")
1820
1821 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1822 "Variable '%s' referenced but never initialized")
1823
1824 (js2-msg "msg.ref.undefined.prop"
1825 "Reference to undefined property '%s'")
1826
1827 (js2-msg "msg.prop.not.found"
1828 "Property %s not found.")
1829
1830 (js2-msg "msg.invalid.type"
1831 "Invalid JavaScript value of type %s")
1832
1833 (js2-msg "msg.primitive.expected"
1834 "Primitive type expected (had %s instead)")
1835
1836 (js2-msg "msg.namespace.expected"
1837 "Namespace object expected to left of :: (found %s instead)")
1838
1839 (js2-msg "msg.null.to.object"
1840 "Cannot convert null to an object.")
1841
1842 (js2-msg "msg.undef.to.object"
1843 "Cannot convert undefined to an object.")
1844
1845 (js2-msg "msg.cyclic.value"
1846 "Cyclic %s value not allowed.")
1847
1848 (js2-msg "msg.is.not.defined"
1849 "'%s' is not defined.")
1850
1851 (js2-msg "msg.undef.prop.read"
1852 "Cannot read property '%s' from %s")
1853
1854 (js2-msg "msg.undef.prop.write"
1855 "Cannot set property '%s' of %s to '%s'")
1856
1857 (js2-msg "msg.undef.prop.delete"
1858 "Cannot delete property '%s' of %s")
1859
1860 (js2-msg "msg.undef.method.call"
1861 "Cannot call method '%s' of %s")
1862
1863 (js2-msg "msg.undef.with"
1864 "Cannot apply 'with' to %s")
1865
1866 (js2-msg "msg.isnt.function"
1867 "%s is not a function, it is %s.")
1868
1869 (js2-msg "msg.isnt.function.in"
1870 "Cannot call property %s in object %s. "
1871 "It is not a function, it is '%s'.")
1872
1873 (js2-msg "msg.function.not.found"
1874 "Cannot find function %s.")
1875
1876 (js2-msg "msg.function.not.found.in"
1877 "Cannot find function %s in object %s.")
1878
1879 (js2-msg "msg.isnt.xml.object"
1880 "%s is not an xml object.")
1881
1882 (js2-msg "msg.no.ref.to.get"
1883 "%s is not a reference to read reference value.")
1884
1885 (js2-msg "msg.no.ref.to.set"
1886 "%s is not a reference to set reference value to %s.")
1887
1888 (js2-msg "msg.no.ref.from.function"
1889 "Function %s can not be used as the left-hand "
1890 "side of assignment or as an operand of ++ or -- operator.")
1891
1892 (js2-msg "msg.bad.default.value"
1893 "Object's getDefaultValue() method returned an object.")
1894
1895 (js2-msg "msg.instanceof.not.object"
1896 "Can't use instanceof on a non-object.")
1897
1898 (js2-msg "msg.instanceof.bad.prototype"
1899 "'prototype' property of %s is not an object.")
1900
1901 (js2-msg "msg.bad.radix"
1902 "illegal radix %s.")
1903
1904 ;; ScriptableObject
1905 (js2-msg "msg.default.value"
1906 "Cannot find default value for object.")
1907
1908 (js2-msg "msg.zero.arg.ctor"
1909 "Cannot load class '%s' which has no zero-parameter constructor.")
1910
1911 (js2-msg "msg.ctor.multiple.parms"
1912 "Can't define constructor or class %s since more than "
1913 "one constructor has multiple parameters.")
1914
1915 (js2-msg "msg.extend.scriptable"
1916 "%s must extend ScriptableObject in order to define property %s.")
1917
1918 (js2-msg "msg.bad.getter.parms"
1919 "In order to define a property, getter %s must have zero "
1920 "parameters or a single ScriptableObject parameter.")
1921
1922 (js2-msg "msg.obj.getter.parms"
1923 "Expected static or delegated getter %s to take "
1924 "a ScriptableObject parameter.")
1925
1926 (js2-msg "msg.getter.static"
1927 "Getter and setter must both be static or neither be static.")
1928
1929 (js2-msg "msg.setter.return"
1930 "Setter must have void return type: %s")
1931
1932 (js2-msg "msg.setter2.parms"
1933 "Two-parameter setter must take a ScriptableObject as "
1934 "its first parameter.")
1935
1936 (js2-msg "msg.setter1.parms"
1937 "Expected single parameter setter for %s")
1938
1939 (js2-msg "msg.setter2.expected"
1940 "Expected static or delegated setter %s to take two parameters.")
1941
1942 (js2-msg "msg.setter.parms"
1943 "Expected either one or two parameters for setter.")
1944
1945 (js2-msg "msg.setter.bad.type"
1946 "Unsupported parameter type '%s' in setter '%s'.")
1947
1948 (js2-msg "msg.add.sealed"
1949 "Cannot add a property to a sealed object: %s.")
1950
1951 (js2-msg "msg.remove.sealed"
1952 "Cannot remove a property from a sealed object: %s.")
1953
1954 (js2-msg "msg.modify.sealed"
1955 "Cannot modify a property of a sealed object: %s.")
1956
1957 (js2-msg "msg.modify.readonly"
1958 "Cannot modify readonly property: %s.")
1959
1960 ;; TokenStream
1961 (js2-msg "msg.missing.exponent"
1962 "missing exponent")
1963
1964 (js2-msg "msg.caught.nfe"
1965 "number format error")
1966
1967 (js2-msg "msg.unterminated.string.lit"
1968 "unterminated string literal")
1969
1970 (js2-msg "msg.unterminated.comment"
1971 "unterminated comment")
1972
1973 (js2-msg "msg.unterminated.re.lit"
1974 "unterminated regular expression literal")
1975
1976 (js2-msg "msg.invalid.re.flag"
1977 "invalid flag after regular expression")
1978
1979 (js2-msg "msg.no.re.input.for"
1980 "no input for %s")
1981
1982 (js2-msg "msg.illegal.character"
1983 "illegal character")
1984
1985 (js2-msg "msg.invalid.escape"
1986 "invalid Unicode escape sequence")
1987
1988 (js2-msg "msg.bad.namespace"
1989 "not a valid default namespace statement. "
1990 "Syntax is: default xml namespace = EXPRESSION;")
1991
1992 ;; TokensStream warnings
1993 (js2-msg "msg.bad.octal.literal"
1994 "illegal octal literal digit %s; "
1995 "interpreting it as a decimal digit")
1996
1997 (js2-msg "msg.missing.hex.digits"
1998 "missing hexadecimal digits after '0x'")
1999
2000 (js2-msg "msg.missing.binary.digits"
2001 "missing binary digits after '0b'")
2002
2003 (js2-msg "msg.missing.octal.digits"
2004 "missing octal digits after '0o'")
2005
2006 (js2-msg "msg.script.is.not.constructor"
2007 "Script objects are not constructors.")
2008
2009 ;; Arrays
2010 (js2-msg "msg.arraylength.bad"
2011 "Inappropriate array length.")
2012
2013 ;; Arrays
2014 (js2-msg "msg.arraylength.too.big"
2015 "Array length %s exceeds supported capacity limit.")
2016
2017 ;; URI
2018 (js2-msg "msg.bad.uri"
2019 "Malformed URI sequence.")
2020
2021 ;; Number
2022 (js2-msg "msg.bad.precision"
2023 "Precision %s out of range.")
2024
2025 ;; NativeGenerator
2026 (js2-msg "msg.send.newborn"
2027 "Attempt to send value to newborn generator")
2028
2029 (js2-msg "msg.already.exec.gen"
2030 "Already executing generator")
2031
2032 (js2-msg "msg.StopIteration.invalid"
2033 "StopIteration may not be changed to an arbitrary object.")
2034
2035 ;; Interpreter
2036 (js2-msg "msg.yield.closing"
2037 "Yield from closing generator")
2038
2039 ;; Classes
2040 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
2041 "class statement requires a name")
2042
2043 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
2044 "unexpected ',' between class properties")
2045
2046 (js2-msg "msg.unexpected.static" ; added by js2-mode
2047 "unexpected 'static'")
2048
2049 (js2-msg "msg.missing.extends" ; added by js2-mode
2050 "name is required after extends")
2051
2052 (js2-msg "msg.no.brace.class" ; added by js2-mode
2053 "missing '{' before class body")
2054
2055 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2056 "missing ']' after computed property expression")
2057
2058 ;;; Tokens Buffer
2059
2060 (defconst js2-ti-max-lookahead 2)
2061 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2062
2063 (defun js2-new-token (offset)
2064 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2065 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2066 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2067 token))
2068
2069 (defsubst js2-current-token ()
2070 (aref js2-ti-tokens js2-ti-tokens-cursor))
2071
2072 (defsubst js2-current-token-string ()
2073 (js2-token-string (js2-current-token)))
2074
2075 (defsubst js2-current-token-type ()
2076 (js2-token-type (js2-current-token)))
2077
2078 (defsubst js2-current-token-beg ()
2079 (js2-token-beg (js2-current-token)))
2080
2081 (defsubst js2-current-token-end ()
2082 (js2-token-end (js2-current-token)))
2083
2084 (defun js2-current-token-len ()
2085 (let ((token (js2-current-token)))
2086 (- (js2-token-end token)
2087 (js2-token-beg token))))
2088
2089 (defun js2-ts-seek (state)
2090 (setq js2-ts-lineno (js2-ts-state-lineno state)
2091 js2-ts-cursor (js2-ts-state-cursor state)
2092 js2-ti-tokens (js2-ts-state-tokens state)
2093 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2094 js2-ti-lookahead (js2-ts-state-lookahead state)))
2095
2096 ;;; Utilities
2097
2098 (defun js2-delete-if (predicate list)
2099 "Remove all items satisfying PREDICATE in LIST."
2100 (cl-loop for item in list
2101 if (not (funcall predicate item))
2102 collect item))
2103
2104 (defun js2-position (element list)
2105 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2106 Returns nil if element is not found in the list."
2107 (let ((count 0)
2108 found)
2109 (while (and list (not found))
2110 (if (eq element (car list))
2111 (setq found t)
2112 (setq count (1+ count)
2113 list (cdr list))))
2114 (if found count)))
2115
2116 (defun js2-find-if (predicate list)
2117 "Find first item satisfying PREDICATE in LIST."
2118 (let (result)
2119 (while (and list (not result))
2120 (if (funcall predicate (car list))
2121 (setq result (car list)))
2122 (setq list (cdr list)))
2123 result))
2124
2125 (defmacro js2-time (form)
2126 "Evaluate FORM, discard result, and return elapsed time in sec."
2127 (declare (debug t))
2128 (let ((beg (make-symbol "--js2-time-beg--")))
2129 `(let ((,beg (current-time)))
2130 ,form
2131 (/ (truncate (* (- (float-time (current-time))
2132 (float-time ,beg))
2133 10000))
2134 10000.0))))
2135
2136 (defsubst js2-same-line (pos)
2137 "Return t if POS is on the same line as current point."
2138 (and (>= pos (point-at-bol))
2139 (<= pos (point-at-eol))))
2140
2141 (defun js2-code-bug ()
2142 "Signal an error when we encounter an unexpected code path."
2143 (error "failed assertion"))
2144
2145 (defsubst js2-record-text-property (beg end prop value)
2146 "Record a text property to set when parsing finishes."
2147 (push (list beg end prop value) js2-mode-deferred-properties))
2148
2149 ;; I'd like to associate errors with nodes, but for now the
2150 ;; easiest thing to do is get the context info from the last token.
2151 (defun js2-record-parse-error (msg &optional arg pos len)
2152 (push (list (list msg arg)
2153 (or pos (js2-current-token-beg))
2154 (or len (js2-current-token-len)))
2155 js2-parsed-errors))
2156
2157 (defun js2-report-error (msg &optional msg-arg pos len)
2158 "Signal a syntax error or record a parse error."
2159 (if js2-recover-from-parse-errors
2160 (js2-record-parse-error msg msg-arg pos len)
2161 (signal 'js2-syntax-error
2162 (list msg
2163 js2-ts-lineno
2164 (save-excursion
2165 (goto-char js2-ts-cursor)
2166 (current-column))
2167 js2-ts-hit-eof))))
2168
2169 (defun js2-report-warning (msg &optional msg-arg pos len face)
2170 (if js2-compiler-report-warning-as-error
2171 (js2-report-error msg msg-arg pos len)
2172 (push (list (list msg msg-arg)
2173 (or pos (js2-current-token-beg))
2174 (or len (js2-current-token-len))
2175 face)
2176 js2-parsed-warnings)))
2177
2178 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2179 (if js2-compiler-strict-mode
2180 (js2-report-warning msg-id msg-arg beg
2181 (and beg end (- end beg)))))
2182
2183 (put 'js2-syntax-error 'error-conditions
2184 '(error syntax-error js2-syntax-error))
2185 (put 'js2-syntax-error 'error-message "Syntax error")
2186
2187 (put 'js2-parse-error 'error-conditions
2188 '(error parse-error js2-parse-error))
2189 (put 'js2-parse-error 'error-message "Parse error")
2190
2191 (defmacro js2-clear-flag (flags flag)
2192 `(setq ,flags (logand ,flags (lognot ,flag))))
2193
2194 (defmacro js2-set-flag (flags flag)
2195 "Logical-or FLAG into FLAGS."
2196 `(setq ,flags (logior ,flags ,flag)))
2197
2198 (defsubst js2-flag-set-p (flags flag)
2199 (/= 0 (logand flags flag)))
2200
2201 (defsubst js2-flag-not-set-p (flags flag)
2202 (zerop (logand flags flag)))
2203
2204 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2205 "Evaluate BODY with the _ character set to be word-syntax."
2206 (declare (indent 0) (debug t))
2207 (let ((old-syntax (make-symbol "old-syntax")))
2208 `(let ((,old-syntax (string (char-syntax ?_))))
2209 (unwind-protect
2210 (progn
2211 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2212 ,@body)
2213 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2214
2215 ;;; AST struct and function definitions
2216
2217 ;; flags for ast node property 'member-type (used for e4x operators)
2218 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2219 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2220 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2221
2222 (defsubst js2-relpos (pos anchor)
2223 "Convert POS to be relative to ANCHOR.
2224 If POS is nil, returns nil."
2225 (and pos (- pos anchor)))
2226
2227 (defun js2-make-pad (indent)
2228 (if (zerop indent)
2229 ""
2230 (make-string (* indent js2-basic-offset) ? )))
2231
2232 (defun js2-visit-ast (node callback)
2233 "Visit every node in ast NODE with visitor CALLBACK.
2234
2235 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2236 called twice: once to visit the node, and again after all the node's
2237 children have been processed. The END-P argument is nil on the first
2238 call and non-nil on the second call. The return value of the callback
2239 affects the traversal: if non-nil, the children of NODE are processed.
2240 If the callback returns nil, or if the node has no children, then the
2241 callback is called immediately with a non-nil END-P argument.
2242
2243 The node traversal is approximately lexical-order, although there
2244 are currently no guarantees around this."
2245 (when node
2246 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2247 ;; visit the node
2248 (when (funcall callback node nil)
2249 ;; visit the kids
2250 (cond
2251 ((eq vfunc 'js2-visit-none)
2252 nil) ; don't even bother calling it
2253 ;; Each AST node type has to define a `js2-visitor' function
2254 ;; that takes a node and a callback, and calls `js2-visit-ast'
2255 ;; on each child of the node.
2256 (vfunc
2257 (funcall vfunc node callback))
2258 (t
2259 (error "%s does not define a visitor-traversal function"
2260 (aref node 0)))))
2261 ;; call the end-visit
2262 (funcall callback node t))))
2263
2264 (cl-defstruct (js2-node
2265 (:constructor nil)) ; abstract
2266 "Base AST node type."
2267 (type -1) ; token type
2268 (pos -1) ; start position of this AST node in parsed input
2269 (len 1) ; num characters spanned by the node
2270 props ; optional node property list (an alist)
2271 parent) ; link to parent node; null for root
2272
2273 (defsubst js2-node-get-prop (node prop &optional default)
2274 (or (cadr (assoc prop (js2-node-props node))) default))
2275
2276 (defsubst js2-node-set-prop (node prop value)
2277 (setf (js2-node-props node)
2278 (cons (list prop value) (js2-node-props node))))
2279
2280 (defun js2-fixup-starts (n nodes)
2281 "Adjust the start positions of NODES to be relative to N.
2282 Any node in the list may be nil, for convenience."
2283 (dolist (node nodes)
2284 (when node
2285 (setf (js2-node-pos node) (- (js2-node-pos node)
2286 (js2-node-pos n))))))
2287
2288 (defun js2-node-add-children (parent &rest nodes)
2289 "Set parent node of NODES to PARENT, and return PARENT.
2290 Does nothing if we're not recording parent links.
2291 If any given node in NODES is nil, doesn't record that link."
2292 (js2-fixup-starts parent nodes)
2293 (dolist (node nodes)
2294 (and node
2295 (setf (js2-node-parent node) parent))))
2296
2297 ;; Non-recursive since it's called a frightening number of times.
2298 (defun js2-node-abs-pos (n)
2299 (let ((pos (js2-node-pos n)))
2300 (while (setq n (js2-node-parent n))
2301 (setq pos (+ pos (js2-node-pos n))))
2302 pos))
2303
2304 (defsubst js2-node-abs-end (n)
2305 "Return absolute buffer position of end of N."
2306 (+ (js2-node-abs-pos n) (js2-node-len n)))
2307
2308 ;; It's important to make sure block nodes have a Lisp list for the
2309 ;; child nodes, to limit printing recursion depth in an AST that
2310 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2311 ;; a sufficiently large vector tree.
2312
2313 (cl-defstruct (js2-block-node
2314 (:include js2-node)
2315 (:constructor nil)
2316 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2317 (pos (js2-current-token-beg))
2318 len
2319 props
2320 kids)))
2321 "A block of statements."
2322 kids) ; a Lisp list of the child statement nodes
2323
2324 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2325 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2326
2327 (defun js2-visit-block (ast callback)
2328 "Visit the `js2-block-node' children of AST."
2329 (dolist (kid (js2-block-node-kids ast))
2330 (js2-visit-ast kid callback)))
2331
2332 (defun js2-print-block (n i)
2333 (let ((pad (js2-make-pad i)))
2334 (insert pad "{\n")
2335 (dolist (kid (js2-block-node-kids n))
2336 (js2-print-ast kid (1+ i)))
2337 (insert pad "}")))
2338
2339 (cl-defstruct (js2-scope
2340 (:include js2-block-node)
2341 (:constructor nil)
2342 (:constructor make-js2-scope (&key (type js2-BLOCK)
2343 (pos (js2-current-token-beg))
2344 len
2345 kids)))
2346 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2347 ;; I don't have one of those handy, so I'll use an alist for now.
2348 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2349 ;; and is much lighter-weight to construct (both CPU and mem).
2350 ;; The keys are interned strings (symbols) for faster lookup.
2351 ;; Should switch to hybrid alist/hashtable eventually.
2352 symbol-table ; an alist of (symbol . js2-symbol)
2353 parent-scope ; a `js2-scope'
2354 top) ; top-level `js2-scope' (script/function)
2355
2356 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2357 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2358
2359 (defun js2-node-get-enclosing-scope (node)
2360 "Return the innermost `js2-scope' node surrounding NODE.
2361 Returns nil if there is no enclosing scope node."
2362 (while (and (setq node (js2-node-parent node))
2363 (not (js2-scope-p node))))
2364 node)
2365
2366 (defun js2-get-defining-scope (scope name &optional point)
2367 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2368 Returns `js2-scope' in which NAME is defined, or nil if not found.
2369
2370 If POINT is non-nil, and if the found declaration type is
2371 `js2-LET', also check that the declaration node is before POINT."
2372 (let ((sym (if (symbolp name)
2373 name
2374 (intern name)))
2375 result
2376 (continue t))
2377 (while (and scope continue)
2378 (if (or
2379 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2380 (and entry
2381 (or (not point)
2382 (not (eq js2-LET (js2-symbol-decl-type entry)))
2383 (>= point
2384 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2385 (and (eq sym 'arguments)
2386 (js2-function-node-p scope)))
2387 (setq continue nil
2388 result scope)
2389 (setq scope (js2-scope-parent-scope scope))))
2390 result))
2391
2392 (defun js2-scope-get-symbol (scope name)
2393 "Return symbol table entry for NAME in SCOPE.
2394 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2395 (and (js2-scope-symbol-table scope)
2396 (cdr (assq (if (symbolp name)
2397 name
2398 (intern name))
2399 (js2-scope-symbol-table scope)))))
2400
2401 (defun js2-scope-put-symbol (scope name symbol)
2402 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2403 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2404 (let* ((table (js2-scope-symbol-table scope))
2405 (sym (if (symbolp name) name (intern name)))
2406 (entry (assq sym table)))
2407 (if entry
2408 (setcdr entry symbol)
2409 (push (cons sym symbol)
2410 (js2-scope-symbol-table scope)))))
2411
2412 (cl-defstruct (js2-symbol
2413 (:constructor nil)
2414 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2415 "A symbol table entry."
2416 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2417 ;; js2-LET, or js2-CONST
2418 decl-type
2419 name ; string
2420 ast-node) ; a `js2-node'
2421
2422 (cl-defstruct (js2-error-node
2423 (:include js2-node)
2424 (:constructor nil) ; silence emacs21 byte-compiler
2425 (:constructor make-js2-error-node (&key (type js2-ERROR)
2426 (pos (js2-current-token-beg))
2427 len)))
2428 "AST node representing a parse error.")
2429
2430 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2431 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2432
2433 (cl-defstruct (js2-script-node
2434 (:include js2-scope)
2435 (:constructor nil)
2436 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2437 (pos (js2-current-token-beg))
2438 len
2439 ;; FIXME: What are those?
2440 var-decls
2441 fun-decls)))
2442 functions ; Lisp list of nested functions
2443 regexps ; Lisp list of (string . flags)
2444 symbols ; alist (every symbol gets unique index)
2445 (param-count 0)
2446 var-names ; vector of string names
2447 consts ; bool-vector matching var-decls
2448 (temp-number 0)) ; for generating temp variables
2449
2450 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2451 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2452
2453 (defun js2-print-script (node indent)
2454 (dolist (kid (js2-block-node-kids node))
2455 (js2-print-ast kid indent)))
2456
2457 (cl-defstruct (js2-ast-root
2458 (:include js2-script-node)
2459 (:constructor nil)
2460 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2461 (pos (js2-current-token-beg))
2462 len
2463 buffer)))
2464 "The root node of a js2 AST."
2465 buffer ; the source buffer from which the code was parsed
2466 comments ; a Lisp list of comments, ordered by start position
2467 errors ; a Lisp list of errors found during parsing
2468 warnings ; a Lisp list of warnings found during parsing
2469 node-count ; number of nodes in the tree, including the root
2470 in-strict-mode) ; t if the script is running under strict mode
2471
2472 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2473 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2474
2475 (defun js2-visit-ast-root (ast callback)
2476 (dolist (kid (js2-ast-root-kids ast))
2477 (js2-visit-ast kid callback))
2478 (dolist (comment (js2-ast-root-comments ast))
2479 (js2-visit-ast comment callback)))
2480
2481 (cl-defstruct (js2-comment-node
2482 (:include js2-node)
2483 (:constructor nil)
2484 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2485 (pos (js2-current-token-beg))
2486 len
2487 format)))
2488 format) ; 'line, 'block, 'jsdoc or 'html
2489
2490 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2491 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2492
2493 (defun js2-print-comment (n i)
2494 ;; We really ought to link end-of-line comments to their nodes.
2495 ;; Or maybe we could add a new comment type, 'endline.
2496 (insert (js2-make-pad i)
2497 (js2-node-string n)))
2498
2499 (cl-defstruct (js2-expr-stmt-node
2500 (:include js2-node)
2501 (:constructor nil)
2502 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2503 (pos js2-ts-cursor)
2504 len
2505 expr)))
2506 "An expression statement."
2507 expr)
2508
2509 (defsubst js2-expr-stmt-node-set-has-result (node)
2510 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2511 (setf (js2-node-type node) js2-EXPR_RESULT))
2512
2513 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2514 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2515
2516 (defun js2-visit-expr-stmt-node (n v)
2517 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2518
2519 (defun js2-print-expr-stmt-node (n indent)
2520 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2521 (insert ";\n"))
2522
2523 (cl-defstruct (js2-loop-node
2524 (:include js2-scope)
2525 (:constructor nil))
2526 "Abstract supertype of loop nodes."
2527 body ; a `js2-block-node'
2528 lp ; position of left-paren, nil if omitted
2529 rp) ; position of right-paren, nil if omitted
2530
2531 (cl-defstruct (js2-do-node
2532 (:include js2-loop-node)
2533 (:constructor nil)
2534 (:constructor make-js2-do-node (&key (type js2-DO)
2535 (pos (js2-current-token-beg))
2536 len
2537 body
2538 condition
2539 while-pos
2540 lp
2541 rp)))
2542 "AST node for do-loop."
2543 condition ; while (expression)
2544 while-pos) ; buffer position of 'while' keyword
2545
2546 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2547 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2548
2549 (defun js2-visit-do-node (n v)
2550 (js2-visit-ast (js2-do-node-body n) v)
2551 (js2-visit-ast (js2-do-node-condition n) v))
2552
2553 (defun js2-print-do-node (n i)
2554 (let ((pad (js2-make-pad i)))
2555 (insert pad "do {\n")
2556 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2557 (js2-print-ast kid (1+ i)))
2558 (insert pad "} while (")
2559 (js2-print-ast (js2-do-node-condition n) 0)
2560 (insert ");\n")))
2561
2562 (cl-defstruct (js2-export-node
2563 (:include js2-node)
2564 (:constructor nil)
2565 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2566 (pos (js2-current-token-beg))
2567 len
2568 exports-list
2569 from-clause
2570 declaration
2571 default)))
2572 "AST node for an export statement. There are many things that can be exported,
2573 so many of its properties will be nil.
2574 "
2575 exports-list ; lisp list of js2-export-binding-node to export
2576 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2577 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2578 default) ; js2-function-node or js2-assign-node
2579
2580 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2581 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2582
2583 (defun js2-visit-export-node (n v)
2584 (let ((exports-list (js2-export-node-exports-list n))
2585 (from (js2-export-node-from-clause n))
2586 (declaration (js2-export-node-declaration n))
2587 (default (js2-export-node-default n)))
2588 (when exports-list
2589 (dolist (export exports-list)
2590 (js2-visit-ast export v)))
2591 (when from
2592 (js2-visit-ast from v))
2593 (when declaration
2594 (js2-visit-ast declaration v))
2595 (when default
2596 (js2-visit-ast default v))))
2597
2598 (defun js2-print-export-node (n i)
2599 (let ((pad (js2-make-pad i))
2600 (exports-list (js2-export-node-exports-list n))
2601 (from (js2-export-node-from-clause n))
2602 (declaration (js2-export-node-declaration n))
2603 (default (js2-export-node-default n)))
2604 (insert pad "export ")
2605 (cond
2606 (default
2607 (insert "default ")
2608 (js2-print-ast default i))
2609 (declaration
2610 (js2-print-ast declaration i))
2611 ((and exports-list from)
2612 (js2-print-named-imports exports-list)
2613 (insert " ")
2614 (js2-print-from-clause from))
2615 (from
2616 (insert "* ")
2617 (js2-print-from-clause from))
2618 (exports-list
2619 (js2-print-named-imports exports-list)))
2620 (insert ";\n")))
2621
2622 (cl-defstruct (js2-while-node
2623 (:include js2-loop-node)
2624 (:constructor nil)
2625 (:constructor make-js2-while-node (&key (type js2-WHILE)
2626 (pos (js2-current-token-beg))
2627 len body
2628 condition lp
2629 rp)))
2630 "AST node for while-loop."
2631 condition) ; while-condition
2632
2633 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2634 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2635
2636 (defun js2-visit-while-node (n v)
2637 (js2-visit-ast (js2-while-node-condition n) v)
2638 (js2-visit-ast (js2-while-node-body n) v))
2639
2640 (defun js2-print-while-node (n i)
2641 (let ((pad (js2-make-pad i)))
2642 (insert pad "while (")
2643 (js2-print-ast (js2-while-node-condition n) 0)
2644 (insert ") {\n")
2645 (js2-print-body (js2-while-node-body n) (1+ i))
2646 (insert pad "}\n")))
2647
2648 (cl-defstruct (js2-for-node
2649 (:include js2-loop-node)
2650 (:constructor nil)
2651 (:constructor make-js2-for-node (&key (type js2-FOR)
2652 (pos js2-ts-cursor)
2653 len body init
2654 condition
2655 update lp rp)))
2656 "AST node for a C-style for-loop."
2657 init ; initialization expression
2658 condition ; loop condition
2659 update) ; update clause
2660
2661 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2662 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2663
2664 (defun js2-visit-for-node (n v)
2665 (js2-visit-ast (js2-for-node-init n) v)
2666 (js2-visit-ast (js2-for-node-condition n) v)
2667 (js2-visit-ast (js2-for-node-update n) v)
2668 (js2-visit-ast (js2-for-node-body n) v))
2669
2670 (defun js2-print-for-node (n i)
2671 (let ((pad (js2-make-pad i)))
2672 (insert pad "for (")
2673 (js2-print-ast (js2-for-node-init n) 0)
2674 (insert "; ")
2675 (js2-print-ast (js2-for-node-condition n) 0)
2676 (insert "; ")
2677 (js2-print-ast (js2-for-node-update n) 0)
2678 (insert ") {\n")
2679 (js2-print-body (js2-for-node-body n) (1+ i))
2680 (insert pad "}\n")))
2681
2682 (cl-defstruct (js2-for-in-node
2683 (:include js2-loop-node)
2684 (:constructor nil)
2685 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2686 (pos js2-ts-cursor)
2687 len body
2688 iterator
2689 object
2690 in-pos
2691 each-pos
2692 foreach-p forof-p
2693 lp rp)))
2694 "AST node for a for..in loop."
2695 iterator ; [var] foo in ...
2696 object ; object over which we're iterating
2697 in-pos ; buffer position of 'in' keyword
2698 each-pos ; buffer position of 'each' keyword, if foreach-p
2699 foreach-p ; t if it's a for-each loop
2700 forof-p) ; t if it's a for-of loop
2701
2702 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2703 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2704
2705 (defun js2-visit-for-in-node (n v)
2706 (js2-visit-ast (js2-for-in-node-iterator n) v)
2707 (js2-visit-ast (js2-for-in-node-object n) v)
2708 (js2-visit-ast (js2-for-in-node-body n) v))
2709
2710 (defun js2-print-for-in-node (n i)
2711 (let ((pad (js2-make-pad i))
2712 (foreach (js2-for-in-node-foreach-p n))
2713 (forof (js2-for-in-node-forof-p n)))
2714 (insert pad "for ")
2715 (if foreach
2716 (insert "each "))
2717 (insert "(")
2718 (js2-print-ast (js2-for-in-node-iterator n) 0)
2719 (insert (if forof " of " " in "))
2720 (js2-print-ast (js2-for-in-node-object n) 0)
2721 (insert ") {\n")
2722 (js2-print-body (js2-for-in-node-body n) (1+ i))
2723 (insert pad "}\n")))
2724
2725 (cl-defstruct (js2-return-node
2726 (:include js2-node)
2727 (:constructor nil)
2728 (:constructor make-js2-return-node (&key (type js2-RETURN)
2729 (pos js2-ts-cursor)
2730 len
2731 retval)))
2732 "AST node for a return statement."
2733 retval) ; expression to return, or 'undefined
2734
2735 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2736 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2737
2738 (defun js2-visit-return-node (n v)
2739 (js2-visit-ast (js2-return-node-retval n) v))
2740
2741 (defun js2-print-return-node (n i)
2742 (insert (js2-make-pad i) "return")
2743 (when (js2-return-node-retval n)
2744 (insert " ")
2745 (js2-print-ast (js2-return-node-retval n) 0))
2746 (insert ";\n"))
2747
2748 (cl-defstruct (js2-if-node
2749 (:include js2-node)
2750 (:constructor nil)
2751 (:constructor make-js2-if-node (&key (type js2-IF)
2752 (pos js2-ts-cursor)
2753 len condition
2754 then-part
2755 else-pos
2756 else-part lp
2757 rp)))
2758 "AST node for an if-statement."
2759 condition ; expression
2760 then-part ; statement or block
2761 else-pos ; optional buffer position of 'else' keyword
2762 else-part ; optional statement or block
2763 lp ; position of left-paren, nil if omitted
2764 rp) ; position of right-paren, nil if omitted
2765
2766 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2767 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2768
2769 (defun js2-visit-if-node (n v)
2770 (js2-visit-ast (js2-if-node-condition n) v)
2771 (js2-visit-ast (js2-if-node-then-part n) v)
2772 (js2-visit-ast (js2-if-node-else-part n) v))
2773
2774 (defun js2-print-if-node (n i)
2775 (let ((pad (js2-make-pad i))
2776 (then-part (js2-if-node-then-part n))
2777 (else-part (js2-if-node-else-part n)))
2778 (insert pad "if (")
2779 (js2-print-ast (js2-if-node-condition n) 0)
2780 (insert ") {\n")
2781 (js2-print-body then-part (1+ i))
2782 (insert pad "}")
2783 (cond
2784 ((not else-part)
2785 (insert "\n"))
2786 ((js2-if-node-p else-part)
2787 (insert " else ")
2788 (js2-print-body else-part i))
2789 (t
2790 (insert " else {\n")
2791 (js2-print-body else-part (1+ i))
2792 (insert pad "}\n")))))
2793
2794 (cl-defstruct (js2-export-binding-node
2795 (:include js2-node)
2796 (:constructor nil)
2797 (:constructor make-js2-export-binding-node (&key (type -1)
2798 pos
2799 len
2800 local-name
2801 extern-name)))
2802 "AST node for an external symbol binding.
2803 It contains a local-name node which is the name of the value in the
2804 current scope, and extern-name which is the name of the value in the
2805 imported or exported scope. By default these are the same, but if the
2806 name is aliased as in {foo as bar}, it would have an extern-name node
2807 containing 'foo' and a local-name node containing 'bar'."
2808 local-name ; js2-name-node with the variable name in this scope
2809 extern-name) ; js2-name-node with the value name in the exporting module
2810
2811 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2812 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2813
2814 (defun js2-visit-extern-binding (n v)
2815 "Visit an extern binding node. First visit the local-name, and, if
2816 different, visit the extern-name."
2817 (let ((local-name (js2-export-binding-node-local-name n))
2818 (extern-name (js2-export-binding-node-extern-name n)))
2819 (when local-name
2820 (js2-visit-ast local-name v))
2821 (when (not (equal local-name extern-name))
2822 (js2-visit-ast extern-name v))))
2823
2824 (defun js2-print-extern-binding (n _i)
2825 "Print a representation of a single extern binding. E.g. 'foo' or
2826 'foo as bar'."
2827 (let ((local-name (js2-export-binding-node-local-name n))
2828 (extern-name (js2-export-binding-node-extern-name n)))
2829 (insert (js2-name-node-name extern-name))
2830 (when (not (equal local-name extern-name))
2831 (insert " as ")
2832 (insert (js2-name-node-name local-name)))))
2833
2834
2835 (cl-defstruct (js2-import-node
2836 (:include js2-node)
2837 (:constructor nil)
2838 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2839 (pos (js2-current-token-beg))
2840 len
2841 import
2842 from
2843 module-id)))
2844 "AST node for an import statement. It follows the form
2845
2846 import ModuleSpecifier;
2847 import ImportClause FromClause;"
2848 import ; js2-import-clause-node specifying which names are to imported.
2849 from ; js2-from-clause-node indicating the module from which to import.
2850 module-id) ; module-id of the import. E.g. 'src/mylib'.
2851
2852 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2853 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2854
2855 (defun js2-visit-import (n v)
2856 (let ((import-clause (js2-import-node-import n))
2857 (from-clause (js2-import-node-from n)))
2858 (when import-clause
2859 (js2-visit-ast import-clause v))
2860 (when from-clause
2861 (js2-visit-ast from-clause v))))
2862
2863 (defun js2-print-import (n i)
2864 "Prints a representation of the import node"
2865 (let ((pad (js2-make-pad i))
2866 (import-clause (js2-import-node-import n))
2867 (from-clause (js2-import-node-from n))
2868 (module-id (js2-import-node-module-id n)))
2869 (insert pad "import ")
2870 (if import-clause
2871 (progn
2872 (js2-print-import-clause import-clause)
2873 (insert " ")
2874 (js2-print-from-clause from-clause))
2875 (insert "'")
2876 (insert module-id)
2877 (insert "'"))
2878 (insert ";\n")))
2879
2880 (cl-defstruct (js2-import-clause-node
2881 (:include js2-node)
2882 (:constructor nil)
2883 (:constructor make-js2-import-clause-node (&key (type -1)
2884 pos
2885 len
2886 namespace-import
2887 named-imports
2888 default-binding)))
2889 "AST node corresponding to the import clause of an import statement. This is
2890 the portion of the import that bindings names from the external context to the
2891 local context."
2892 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2893 named-imports ; lisp list of js2-export-binding-node for all named imports.
2894 default-binding) ; js2-export-binding-node for the default import binding
2895
2896 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2897 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2898
2899 (defun js2-visit-import-clause (n v)
2900 (let ((ns-import (js2-import-clause-node-namespace-import n))
2901 (named-imports (js2-import-clause-node-named-imports n))
2902 (default (js2-import-clause-node-default-binding n)))
2903 (when ns-import
2904 (js2-visit-ast ns-import v))
2905 (when named-imports
2906 (dolist (import named-imports)
2907 (js2-visit-ast import v)))
2908 (when default
2909 (js2-visit-ast default v))))
2910
2911 (defun js2-print-import-clause (n)
2912 (let ((ns-import (js2-import-clause-node-namespace-import n))
2913 (named-imports (js2-import-clause-node-named-imports n))
2914 (default (js2-import-clause-node-default-binding n)))
2915 (cond
2916 ((and default ns-import)
2917 (js2-print-ast default)
2918 (insert ", ")
2919 (js2-print-namespace-import ns-import))
2920 ((and default named-imports)
2921 (js2-print-ast default)
2922 (insert ", ")
2923 (js2-print-named-imports named-imports))
2924 (default
2925 (js2-print-ast default))
2926 (ns-import
2927 (js2-print-namespace-import ns-import))
2928 (named-imports
2929 (js2-print-named-imports named-imports)))))
2930
2931 (defun js2-print-namespace-import (node)
2932 (insert "* as ")
2933 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2934
2935 (defun js2-print-named-imports (imports)
2936 (insert "{")
2937 (let ((len (length imports))
2938 (n 0))
2939 (while (< n len)
2940 (js2-print-extern-binding (nth n imports) 0)
2941 (unless (= n (- len 1))
2942 (insert ", "))
2943 (setq n (+ n 1))))
2944 (insert "}"))
2945
2946 (cl-defstruct (js2-namespace-import-node
2947 (:include js2-node)
2948 (:constructor nil)
2949 (:constructor make-js2-namespace-import-node (&key (type -1)
2950 pos
2951 len
2952 name)))
2953 "AST node for a complete namespace import.
2954 E.g. the '* as lib' expression in:
2955
2956 import * as lib from 'src/lib'
2957
2958 It contains a single name node referring to the bound name."
2959 name) ; js2-name-node of the bound name.
2960
2961 (defun js2-visit-namespace-import (n v)
2962 (js2-visit-ast (js2-namespace-import-node-name n) v))
2963
2964 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2965 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2966
2967 (cl-defstruct (js2-from-clause-node
2968 (:include js2-node)
2969 (:constructor nil)
2970 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2971 pos
2972 len
2973 module-id
2974 metadata-p)))
2975 "AST node for the from clause in an import or export statement.
2976 E.g. from 'my/module'. It can refere to either an external module, or to the
2977 modules metadata itself."
2978 module-id ; string containing the module specifier.
2979 metadata-p) ; true if this clause refers to the module's metadata
2980
2981 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2982 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2983
2984 (defun js2-print-from-clause (n)
2985 (insert "from ")
2986 (if (js2-from-clause-node-metadata-p n)
2987 (insert "this module")
2988 (insert "'")
2989 (insert (js2-from-clause-node-module-id n))
2990 (insert "'")))
2991
2992 (cl-defstruct (js2-try-node
2993 (:include js2-node)
2994 (:constructor nil)
2995 (:constructor make-js2-try-node (&key (type js2-TRY)
2996 (pos js2-ts-cursor)
2997 len
2998 try-block
2999 catch-clauses
3000 finally-block)))
3001 "AST node for a try-statement."
3002 try-block
3003 catch-clauses ; a Lisp list of `js2-catch-node'
3004 finally-block) ; a `js2-finally-node'
3005
3006 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
3007 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
3008
3009 (defun js2-visit-try-node (n v)
3010 (js2-visit-ast (js2-try-node-try-block n) v)
3011 (dolist (clause (js2-try-node-catch-clauses n))
3012 (js2-visit-ast clause v))
3013 (js2-visit-ast (js2-try-node-finally-block n) v))
3014
3015 (defun js2-print-try-node (n i)
3016 (let ((pad (js2-make-pad i))
3017 (catches (js2-try-node-catch-clauses n))
3018 (finally (js2-try-node-finally-block n)))
3019 (insert pad "try {\n")
3020 (js2-print-body (js2-try-node-try-block n) (1+ i))
3021 (insert pad "}")
3022 (when catches
3023 (dolist (catch catches)
3024 (js2-print-ast catch i)))
3025 (if finally
3026 (js2-print-ast finally i)
3027 (insert "\n"))))
3028
3029 (cl-defstruct (js2-catch-node
3030 (:include js2-scope)
3031 (:constructor nil)
3032 (:constructor make-js2-catch-node (&key (type js2-CATCH)
3033 (pos js2-ts-cursor)
3034 len
3035 param
3036 guard-kwd
3037 guard-expr
3038 lp rp)))
3039 "AST node for a catch clause."
3040 param ; destructuring form or simple name node
3041 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
3042 guard-expr ; catch condition, a `js2-node'
3043 lp ; buffer position of left-paren, nil if omitted
3044 rp) ; buffer position of right-paren, nil if omitted
3045
3046 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
3047 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
3048
3049 (defun js2-visit-catch-node (n v)
3050 (js2-visit-ast (js2-catch-node-param n) v)
3051 (when (js2-catch-node-guard-kwd n)
3052 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3053 (js2-visit-block n v))
3054
3055 (defun js2-print-catch-node (n i)
3056 (let ((pad (js2-make-pad i))
3057 (guard-kwd (js2-catch-node-guard-kwd n))
3058 (guard-expr (js2-catch-node-guard-expr n)))
3059 (insert " catch (")
3060 (js2-print-ast (js2-catch-node-param n) 0)
3061 (when guard-kwd
3062 (insert " if ")
3063 (js2-print-ast guard-expr 0))
3064 (insert ") {\n")
3065 (js2-print-body n (1+ i))
3066 (insert pad "}")))
3067
3068 (cl-defstruct (js2-finally-node
3069 (:include js2-node)
3070 (:constructor nil)
3071 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3072 (pos js2-ts-cursor)
3073 len body)))
3074 "AST node for a finally clause."
3075 body) ; a `js2-node', often but not always a block node
3076
3077 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3078 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3079
3080 (defun js2-visit-finally-node (n v)
3081 (js2-visit-ast (js2-finally-node-body n) v))
3082
3083 (defun js2-print-finally-node (n i)
3084 (let ((pad (js2-make-pad i)))
3085 (insert " finally {\n")
3086 (js2-print-body (js2-finally-node-body n) (1+ i))
3087 (insert pad "}\n")))
3088
3089 (cl-defstruct (js2-switch-node
3090 (:include js2-node)
3091 (:constructor nil)
3092 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3093 (pos js2-ts-cursor)
3094 len
3095 discriminant
3096 cases lp
3097 rp)))
3098 "AST node for a switch statement."
3099 discriminant ; a `js2-node' (switch expression)
3100 cases ; a Lisp list of `js2-case-node'
3101 lp ; position of open-paren for discriminant, nil if omitted
3102 rp) ; position of close-paren for discriminant, nil if omitted
3103
3104 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3105 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3106
3107 (defun js2-visit-switch-node (n v)
3108 (js2-visit-ast (js2-switch-node-discriminant n) v)
3109 (dolist (c (js2-switch-node-cases n))
3110 (js2-visit-ast c v)))
3111
3112 (defun js2-print-switch-node (n i)
3113 (let ((pad (js2-make-pad i))
3114 (cases (js2-switch-node-cases n)))
3115 (insert pad "switch (")
3116 (js2-print-ast (js2-switch-node-discriminant n) 0)
3117 (insert ") {\n")
3118 (dolist (case cases)
3119 (js2-print-ast case i))
3120 (insert pad "}\n")))
3121
3122 (cl-defstruct (js2-case-node
3123 (:include js2-block-node)
3124 (:constructor nil)
3125 (:constructor make-js2-case-node (&key (type js2-CASE)
3126 (pos js2-ts-cursor)
3127 len kids expr)))
3128 "AST node for a case clause of a switch statement."
3129 expr) ; the case expression (nil for default)
3130
3131 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3132 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3133
3134 (defun js2-visit-case-node (n v)
3135 (js2-visit-ast (js2-case-node-expr n) v)
3136 (js2-visit-block n v))
3137
3138 (defun js2-print-case-node (n i)
3139 (let ((pad (js2-make-pad i))
3140 (expr (js2-case-node-expr n)))
3141 (insert pad)
3142 (if (null expr)
3143 (insert "default:\n")
3144 (insert "case ")
3145 (js2-print-ast expr 0)
3146 (insert ":\n"))
3147 (dolist (kid (js2-case-node-kids n))
3148 (js2-print-ast kid (1+ i)))))
3149
3150 (cl-defstruct (js2-throw-node
3151 (:include js2-node)
3152 (:constructor nil)
3153 (:constructor make-js2-throw-node (&key (type js2-THROW)
3154 (pos js2-ts-cursor)
3155 len expr)))
3156 "AST node for a throw statement."
3157 expr) ; the expression to throw
3158
3159 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3160 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3161
3162 (defun js2-visit-throw-node (n v)
3163 (js2-visit-ast (js2-throw-node-expr n) v))
3164
3165 (defun js2-print-throw-node (n i)
3166 (insert (js2-make-pad i) "throw ")
3167 (js2-print-ast (js2-throw-node-expr n) 0)
3168 (insert ";\n"))
3169
3170 (cl-defstruct (js2-with-node
3171 (:include js2-node)
3172 (:constructor nil)
3173 (:constructor make-js2-with-node (&key (type js2-WITH)
3174 (pos js2-ts-cursor)
3175 len object
3176 body lp rp)))
3177 "AST node for a with-statement."
3178 object
3179 body
3180 lp ; buffer position of left-paren around object, nil if omitted
3181 rp) ; buffer position of right-paren around object, nil if omitted
3182
3183 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3184 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3185
3186 (defun js2-visit-with-node (n v)
3187 (js2-visit-ast (js2-with-node-object n) v)
3188 (js2-visit-ast (js2-with-node-body n) v))
3189
3190 (defun js2-print-with-node (n i)
3191 (let ((pad (js2-make-pad i)))
3192 (insert pad "with (")
3193 (js2-print-ast (js2-with-node-object n) 0)
3194 (insert ") {\n")
3195 (js2-print-body (js2-with-node-body n) (1+ i))
3196 (insert pad "}\n")))
3197
3198 (cl-defstruct (js2-label-node
3199 (:include js2-node)
3200 (:constructor nil)
3201 (:constructor make-js2-label-node (&key (type js2-LABEL)
3202 (pos js2-ts-cursor)
3203 len name)))
3204 "AST node for a statement label or case label."
3205 name ; a string
3206 loop) ; for validating and code-generating continue-to-label
3207
3208 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3209 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3210
3211 (defun js2-print-label (n i)
3212 (insert (js2-make-pad i)
3213 (js2-label-node-name n)
3214 ":\n"))
3215
3216 (cl-defstruct (js2-labeled-stmt-node
3217 (:include js2-node)
3218 (:constructor nil)
3219 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3220 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3221 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3222 (pos js2-ts-cursor)
3223 len labels stmt)))
3224 "AST node for a statement with one or more labels.
3225 Multiple labels for a statement are collapsed into the labels field."
3226 labels ; Lisp list of `js2-label-node'
3227 stmt) ; the statement these labels are for
3228
3229 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3230 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3231
3232 (defun js2-get-label-by-name (lbl-stmt name)
3233 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3234 Returns nil if no such label is in the list."
3235 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3236 result)
3237 (while (and label-list (not result))
3238 (if (string= (js2-label-node-name (car label-list)) name)
3239 (setq result (car label-list))
3240 (setq label-list (cdr label-list))))
3241 result))
3242
3243 (defun js2-visit-labeled-stmt (n v)
3244 (dolist (label (js2-labeled-stmt-node-labels n))
3245 (js2-visit-ast label v))
3246 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3247
3248 (defun js2-print-labeled-stmt (n i)
3249 (dolist (label (js2-labeled-stmt-node-labels n))
3250 (js2-print-ast label i))
3251 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3252
3253 (defun js2-labeled-stmt-node-contains (node label)
3254 "Return t if NODE contains LABEL in its label set.
3255 NODE is a `js2-labels-node'. LABEL is an identifier."
3256 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3257 if (string= label (js2-label-node-name nl))
3258 return t
3259 finally return nil))
3260
3261 (defsubst js2-labeled-stmt-node-add-label (node label)
3262 "Add a `js2-label-node' to the label set for this statement."
3263 (setf (js2-labeled-stmt-node-labels node)
3264 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3265
3266 (cl-defstruct (js2-jump-node
3267 (:include js2-node)
3268 (:constructor nil))
3269 "Abstract supertype of break and continue nodes."
3270 label ; `js2-name-node' for location of label identifier, if present
3271 target) ; target js2-labels-node or loop/switch statement
3272
3273 (defun js2-visit-jump-node (n v)
3274 ;; We don't visit the target, since it's a back-link.
3275 (js2-visit-ast (js2-jump-node-label n) v))
3276
3277 (cl-defstruct (js2-break-node
3278 (:include js2-jump-node)
3279 (:constructor nil)
3280 (:constructor make-js2-break-node (&key (type js2-BREAK)
3281 (pos js2-ts-cursor)
3282 len label target)))
3283 "AST node for a break statement.
3284 The label field is a `js2-name-node', possibly nil, for the named label
3285 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3286 is the target of the break - a label node or enclosing loop/switch statement.")
3287
3288 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3289 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3290
3291 (defun js2-print-break-node (n i)
3292 (insert (js2-make-pad i) "break")
3293 (when (js2-break-node-label n)
3294 (insert " ")
3295 (js2-print-ast (js2-break-node-label n) 0))
3296 (insert ";\n"))
3297
3298 (cl-defstruct (js2-continue-node
3299 (:include js2-jump-node)
3300 (:constructor nil)
3301 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3302 (pos js2-ts-cursor)
3303 len label target)))
3304 "AST node for a continue statement.
3305 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3306 It is nil if continue specifies no label. The target field is the jump target:
3307 a `js2-label-node' or the innermost enclosing loop.")
3308
3309 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3310 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3311
3312 (defun js2-print-continue-node (n i)
3313 (insert (js2-make-pad i) "continue")
3314 (when (js2-continue-node-label n)
3315 (insert " ")
3316 (js2-print-ast (js2-continue-node-label n) 0))
3317 (insert ";\n"))
3318
3319 (cl-defstruct (js2-function-node
3320 (:include js2-script-node)
3321 (:constructor nil)
3322 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3323 (pos js2-ts-cursor)
3324 len
3325 (ftype 'FUNCTION)
3326 (form 'FUNCTION_STATEMENT)
3327 (name "")
3328 params rest-p
3329 body
3330 generator-type
3331 lp rp)))
3332 "AST node for a function declaration.
3333 The `params' field is a Lisp list of nodes. Each node is either a simple
3334 `js2-name-node', or if it's a destructuring-assignment parameter, a
3335 `js2-array-node' or `js2-object-node'."
3336 ftype ; FUNCTION, GETTER or SETTER
3337 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3338 name ; function name (a `js2-name-node', or nil if anonymous)
3339 params ; a Lisp list of destructuring forms or simple name nodes
3340 rest-p ; if t, the last parameter is rest parameter
3341 body ; a `js2-block-node' or expression node (1.8 only)
3342 lp ; position of arg-list open-paren, or nil if omitted
3343 rp ; position of arg-list close-paren, or nil if omitted
3344 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3345 needs-activation ; t if we need an activation object for this frame
3346 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3347 member-expr ; nonstandard Ecma extension from Rhino
3348 in-strict-mode) ; t if the function is running under strict mode
3349
3350 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3351 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3352
3353 (defun js2-visit-function-node (n v)
3354 (js2-visit-ast (js2-function-node-name n) v)
3355 (dolist (p (js2-function-node-params n))
3356 (js2-visit-ast p v))
3357 (js2-visit-ast (js2-function-node-body n) v))
3358
3359 (defun js2-print-function-node (n i)
3360 (let* ((pad (js2-make-pad i))
3361 (getter (js2-node-get-prop n 'GETTER_SETTER))
3362 (name (or (js2-function-node-name n)
3363 (js2-function-node-member-expr n)))
3364 (params (js2-function-node-params n))
3365 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3366 (rest-p (js2-function-node-rest-p n))
3367 (body (js2-function-node-body n))
3368 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3369 (unless (or getter arrow)
3370 (insert pad "function")
3371 (when (eq (js2-function-node-generator-type n) 'STAR)
3372 (insert "*")))
3373 (when name
3374 (insert " ")
3375 (js2-print-ast name 0))
3376 (insert "(")
3377 (cl-loop with len = (length params)
3378 for param in params
3379 for count from 1
3380 do
3381 (when (and rest-p (= count len))
3382 (insert "..."))
3383 (js2-print-ast param 0)
3384 (when (< count len)
3385 (insert ", ")))
3386 (insert ") ")
3387 (when arrow
3388 (insert "=> "))
3389 (insert "{")
3390 ;; TODO: fix this to be smarter about indenting, etc.
3391 (unless expr
3392 (insert "\n"))
3393 (if (js2-block-node-p body)
3394 (js2-print-body body (1+ i))
3395 (js2-print-ast body 0))
3396 (insert pad "}")
3397 (unless expr
3398 (insert "\n"))))
3399
3400 (defun js2-function-name (node)
3401 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3402 (and (js2-function-node-name node)
3403 (js2-name-node-name (js2-function-node-name node))))
3404
3405 ;; Having this be an expression node makes it more flexible.
3406 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3407 ;; that work better if you assume it's an expression. Whenever we have
3408 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3409 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3410 (cl-defstruct (js2-var-decl-node
3411 (:include js2-node)
3412 (:constructor nil)
3413 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3414 (pos (js2-current-token-beg))
3415 len kids
3416 decl-type)))
3417 "AST node for a variable declaration list (VAR, CONST or LET).
3418 The node bounds differ depending on the declaration type. For VAR or
3419 CONST declarations, the bounds include the var/const keyword. For LET
3420 declarations, the node begins at the position of the first child."
3421 kids ; a Lisp list of `js2-var-init-node' structs.
3422 decl-type) ; js2-VAR, js2-CONST or js2-LET
3423
3424 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3425 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3426
3427 (defun js2-visit-var-decl (n v)
3428 (dolist (kid (js2-var-decl-node-kids n))
3429 (js2-visit-ast kid v)))
3430
3431 (defun js2-print-var-decl (n i)
3432 (let ((pad (js2-make-pad i))
3433 (tt (js2-var-decl-node-decl-type n)))
3434 (insert pad)
3435 (insert (cond
3436 ((= tt js2-VAR) "var ")
3437 ((= tt js2-LET) "let ")
3438 ((= tt js2-CONST) "const ")
3439 (t
3440 (error "malformed var-decl node"))))
3441 (cl-loop with kids = (js2-var-decl-node-kids n)
3442 with len = (length kids)
3443 for kid in kids
3444 for count from 1
3445 do
3446 (js2-print-ast kid 0)
3447 (if (< count len)
3448 (insert ", ")))))
3449
3450 (cl-defstruct (js2-var-init-node
3451 (:include js2-node)
3452 (:constructor nil)
3453 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3454 (pos js2-ts-cursor)
3455 len target
3456 initializer)))
3457 "AST node for a variable declaration.
3458 The type field will be js2-CONST for a const decl."
3459 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3460 initializer) ; initializer expression, a `js2-node'
3461
3462 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3463 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3464
3465 (defun js2-visit-var-init-node (n v)
3466 (js2-visit-ast (js2-var-init-node-target n) v)
3467 (js2-visit-ast (js2-var-init-node-initializer n) v))
3468
3469 (defun js2-print-var-init-node (n i)
3470 (let ((pad (js2-make-pad i))
3471 (name (js2-var-init-node-target n))
3472 (init (js2-var-init-node-initializer n)))
3473 (insert pad)
3474 (js2-print-ast name 0)
3475 (when init
3476 (insert " = ")
3477 (js2-print-ast init 0))))
3478
3479 (cl-defstruct (js2-cond-node
3480 (:include js2-node)
3481 (:constructor nil)
3482 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3483 (pos js2-ts-cursor)
3484 len
3485 test-expr
3486 true-expr
3487 false-expr
3488 q-pos c-pos)))
3489 "AST node for the ternary operator"
3490 test-expr
3491 true-expr
3492 false-expr
3493 q-pos ; buffer position of ?
3494 c-pos) ; buffer position of :
3495
3496 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3497 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3498
3499 (defun js2-visit-cond-node (n v)
3500 (js2-visit-ast (js2-cond-node-test-expr n) v)
3501 (js2-visit-ast (js2-cond-node-true-expr n) v)
3502 (js2-visit-ast (js2-cond-node-false-expr n) v))
3503
3504 (defun js2-print-cond-node (n i)
3505 (let ((pad (js2-make-pad i)))
3506 (insert pad)
3507 (js2-print-ast (js2-cond-node-test-expr n) 0)
3508 (insert " ? ")
3509 (js2-print-ast (js2-cond-node-true-expr n) 0)
3510 (insert " : ")
3511 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3512
3513 (cl-defstruct (js2-infix-node
3514 (:include js2-node)
3515 (:constructor nil)
3516 (:constructor make-js2-infix-node (&key type
3517 (pos js2-ts-cursor)
3518 len op-pos
3519 left right)))
3520 "Represents infix expressions.
3521 Includes assignment ops like `|=', and the comma operator.
3522 The type field inherited from `js2-node' holds the operator."
3523 op-pos ; buffer position where operator begins
3524 left ; any `js2-node'
3525 right) ; any `js2-node'
3526
3527 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3528 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3529
3530 (defun js2-visit-infix-node (n v)
3531 (js2-visit-ast (js2-infix-node-left n) v)
3532 (js2-visit-ast (js2-infix-node-right n) v))
3533
3534 (defconst js2-operator-tokens
3535 (let ((table (make-hash-table :test 'eq))
3536 (tokens
3537 (list (cons js2-IN "in")
3538 (cons js2-TYPEOF "typeof")
3539 (cons js2-INSTANCEOF "instanceof")
3540 (cons js2-DELPROP "delete")
3541 (cons js2-COMMA ",")
3542 (cons js2-COLON ":")
3543 (cons js2-OR "||")
3544 (cons js2-AND "&&")
3545 (cons js2-INC "++")
3546 (cons js2-DEC "--")
3547 (cons js2-BITOR "|")
3548 (cons js2-BITXOR "^")
3549 (cons js2-BITAND "&")
3550 (cons js2-EQ "==")
3551 (cons js2-NE "!=")
3552 (cons js2-LT "<")
3553 (cons js2-LE "<=")
3554 (cons js2-GT ">")
3555 (cons js2-GE ">=")
3556 (cons js2-LSH "<<")
3557 (cons js2-RSH ">>")
3558 (cons js2-URSH ">>>")
3559 (cons js2-ADD "+") ; infix plus
3560 (cons js2-SUB "-") ; infix minus
3561 (cons js2-MUL "*")
3562 (cons js2-DIV "/")
3563 (cons js2-MOD "%")
3564 (cons js2-NOT "!")
3565 (cons js2-BITNOT "~")
3566 (cons js2-POS "+") ; unary plus
3567 (cons js2-NEG "-") ; unary minus
3568 (cons js2-TRIPLEDOT "...")
3569 (cons js2-SHEQ "===") ; shallow equality
3570 (cons js2-SHNE "!==") ; shallow inequality
3571 (cons js2-ASSIGN "=")
3572 (cons js2-ASSIGN_BITOR "|=")
3573 (cons js2-ASSIGN_BITXOR "^=")
3574 (cons js2-ASSIGN_BITAND "&=")
3575 (cons js2-ASSIGN_LSH "<<=")
3576 (cons js2-ASSIGN_RSH ">>=")
3577 (cons js2-ASSIGN_URSH ">>>=")
3578 (cons js2-ASSIGN_ADD "+=")
3579 (cons js2-ASSIGN_SUB "-=")
3580 (cons js2-ASSIGN_MUL "*=")
3581 (cons js2-ASSIGN_DIV "/=")
3582 (cons js2-ASSIGN_MOD "%="))))
3583 (cl-loop for (k . v) in tokens do
3584 (puthash k v table))
3585 table))
3586
3587 (defun js2-print-infix-node (n i)
3588 (let* ((tt (js2-node-type n))
3589 (op (gethash tt js2-operator-tokens)))
3590 (unless op
3591 (error "unrecognized infix operator %s" (js2-node-type n)))
3592 (insert (js2-make-pad i))
3593 (js2-print-ast (js2-infix-node-left n) 0)
3594 (unless (= tt js2-COMMA)
3595 (insert " "))
3596 (insert op)
3597 (insert " ")
3598 (js2-print-ast (js2-infix-node-right n) 0)))
3599
3600 (cl-defstruct (js2-assign-node
3601 (:include js2-infix-node)
3602 (:constructor nil)
3603 (:constructor make-js2-assign-node (&key type
3604 (pos js2-ts-cursor)
3605 len op-pos
3606 left right)))
3607 "Represents any assignment.
3608 The type field holds the actual assignment operator.")
3609
3610 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3611 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3612
3613 (cl-defstruct (js2-unary-node
3614 (:include js2-node)
3615 (:constructor nil)
3616 (:constructor make-js2-unary-node (&key type ; required
3617 (pos js2-ts-cursor)
3618 len operand)))
3619 "AST node type for unary operator nodes.
3620 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3621 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3622 property is added if the operator follows the operand."
3623 operand) ; a `js2-node' expression
3624
3625 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3626 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3627
3628 (defun js2-visit-unary-node (n v)
3629 (js2-visit-ast (js2-unary-node-operand n) v))
3630
3631 (defun js2-print-unary-node (n i)
3632 (let* ((tt (js2-node-type n))
3633 (op (gethash tt js2-operator-tokens))
3634 (postfix (js2-node-get-prop n 'postfix)))
3635 (unless op
3636 (error "unrecognized unary operator %s" tt))
3637 (insert (js2-make-pad i))
3638 (unless postfix
3639 (insert op))
3640 (if (or (= tt js2-TYPEOF)
3641 (= tt js2-DELPROP))
3642 (insert " "))
3643 (js2-print-ast (js2-unary-node-operand n) 0)
3644 (when postfix
3645 (insert op))))
3646
3647 (cl-defstruct (js2-let-node
3648 (:include js2-scope)
3649 (:constructor nil)
3650 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3651 (pos (js2-current-token-beg))
3652 len vars body
3653 lp rp)))
3654 "AST node for a let expression or a let statement.
3655 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3656 vars ; a `js2-var-decl-node'
3657 body ; a `js2-node' representing the expression or body block
3658 lp
3659 rp)
3660
3661 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3662 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3663
3664 (defun js2-visit-let-node (n v)
3665 (js2-visit-ast (js2-let-node-vars n) v)
3666 (js2-visit-ast (js2-let-node-body n) v))
3667
3668 (defun js2-print-let-node (n i)
3669 (insert (js2-make-pad i) "let (")
3670 (let ((p (point)))
3671 (js2-print-ast (js2-let-node-vars n) 0)
3672 (delete-region p (+ p 4)))
3673 (insert ") ")
3674 (js2-print-ast (js2-let-node-body n) i))
3675
3676 (cl-defstruct (js2-keyword-node
3677 (:include js2-node)
3678 (:constructor nil)
3679 (:constructor make-js2-keyword-node (&key type
3680 (pos (js2-current-token-beg))
3681 (len (- js2-ts-cursor pos)))))
3682 "AST node representing a literal keyword such as `null'.
3683 Used for `null', `this', `true', `false' and `debugger'.
3684 The node type is set to js2-NULL, js2-THIS, etc.")
3685
3686 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3687 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3688
3689 (defun js2-print-keyword-node (n i)
3690 (insert (js2-make-pad i)
3691 (let ((tt (js2-node-type n)))
3692 (cond
3693 ((= tt js2-THIS) "this")
3694 ((= tt js2-SUPER) "super")
3695 ((= tt js2-NULL) "null")
3696 ((= tt js2-TRUE) "true")
3697 ((= tt js2-FALSE) "false")
3698 ((= tt js2-DEBUGGER) "debugger")
3699 (t (error "Invalid keyword literal type: %d" tt))))))
3700
3701 (defsubst js2-this-or-super-node-p (node)
3702 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3703 (let ((type (js2-node-type node)))
3704 (or (eq type js2-THIS) (eq type js2-SUPER))))
3705
3706 (cl-defstruct (js2-new-node
3707 (:include js2-node)
3708 (:constructor nil)
3709 (:constructor make-js2-new-node (&key (type js2-NEW)
3710 (pos (js2-current-token-beg))
3711 len target
3712 args initializer
3713 lp rp)))
3714 "AST node for new-expression such as new Foo()."
3715 target ; an identifier or reference
3716 args ; a Lisp list of argument nodes
3717 lp ; position of left-paren, nil if omitted
3718 rp ; position of right-paren, nil if omitted
3719 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3720
3721 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3722 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3723
3724 (defun js2-visit-new-node (n v)
3725 (js2-visit-ast (js2-new-node-target n) v)
3726 (dolist (arg (js2-new-node-args n))
3727 (js2-visit-ast arg v))
3728 (js2-visit-ast (js2-new-node-initializer n) v))
3729
3730 (defun js2-print-new-node (n i)
3731 (insert (js2-make-pad i) "new ")
3732 (js2-print-ast (js2-new-node-target n))
3733 (insert "(")
3734 (js2-print-list (js2-new-node-args n))
3735 (insert ")")
3736 (when (js2-new-node-initializer n)
3737 (insert " ")
3738 (js2-print-ast (js2-new-node-initializer n))))
3739
3740 (cl-defstruct (js2-name-node
3741 (:include js2-node)
3742 (:constructor nil)
3743 (:constructor make-js2-name-node (&key (type js2-NAME)
3744 (pos (js2-current-token-beg))
3745 (len (- js2-ts-cursor
3746 (js2-current-token-beg)))
3747 (name (js2-current-token-string)))))
3748 "AST node for a JavaScript identifier"
3749 name ; a string
3750 scope) ; a `js2-scope' (optional, used for codegen)
3751
3752 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3753 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3754
3755 (defun js2-print-name-node (n i)
3756 (insert (js2-make-pad i)
3757 (js2-name-node-name n)))
3758
3759 (defsubst js2-name-node-length (node)
3760 "Return identifier length of NODE, a `js2-name-node'.
3761 Returns 0 if NODE is nil or its identifier field is nil."
3762 (if node
3763 (length (js2-name-node-name node))
3764 0))
3765
3766 (cl-defstruct (js2-number-node
3767 (:include js2-node)
3768 (:constructor nil)
3769 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3770 (pos (js2-current-token-beg))
3771 (len (- js2-ts-cursor
3772 (js2-current-token-beg)))
3773 (value (js2-current-token-string))
3774 (num-value (js2-token-number
3775 (js2-current-token)))
3776 (num-base (js2-token-number-base
3777 (js2-current-token))))))
3778 "AST node for a number literal."
3779 value ; the original string, e.g. "6.02e23"
3780 num-value ; the parsed number value
3781 num-base) ; the number's base
3782
3783 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3784 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3785
3786 (defun js2-print-number-node (n i)
3787 (insert (js2-make-pad i)
3788 (number-to-string (js2-number-node-num-value n))))
3789
3790 (cl-defstruct (js2-regexp-node
3791 (:include js2-node)
3792 (:constructor nil)
3793 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3794 (pos (js2-current-token-beg))
3795 (len (- js2-ts-cursor
3796 (js2-current-token-beg)))
3797 value flags)))
3798 "AST node for a regular expression literal."
3799 value ; the regexp string, without // delimiters
3800 flags) ; a string of flags, e.g. `mi'.
3801
3802 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3803 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3804
3805 (defun js2-print-regexp (n i)
3806 (insert (js2-make-pad i)
3807 "/"
3808 (js2-regexp-node-value n)
3809 "/")
3810 (if (js2-regexp-node-flags n)
3811 (insert (js2-regexp-node-flags n))))
3812
3813 (cl-defstruct (js2-string-node
3814 (:include js2-node)
3815 (:constructor nil)
3816 (:constructor make-js2-string-node (&key (type js2-STRING)
3817 (pos (js2-current-token-beg))
3818 (len (- js2-ts-cursor
3819 (js2-current-token-beg)))
3820 (value (js2-current-token-string)))))
3821 "String literal.
3822 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3823 You can tell the quote type by looking at the first character."
3824 value) ; the characters of the string, including the quotes
3825
3826 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3827 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3828
3829 (defun js2-print-string-node (n i)
3830 (insert (js2-make-pad i)
3831 (js2-node-string n)))
3832
3833 (cl-defstruct (js2-template-node
3834 (:include js2-node)
3835 (:constructor nil)
3836 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3837 beg len kids)))
3838 "Template literal."
3839 kids) ; `js2-string-node' is used for string segments, other nodes
3840 ; for substitutions inside.
3841
3842 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3843 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3844
3845 (defun js2-visit-template (n callback)
3846 (dolist (kid (js2-template-node-kids n))
3847 (js2-visit-ast kid callback)))
3848
3849 (defun js2-print-template (n i)
3850 (insert (js2-make-pad i))
3851 (dolist (kid (js2-template-node-kids n))
3852 (if (js2-string-node-p kid)
3853 (insert (js2-node-string kid))
3854 (js2-print-ast kid))))
3855
3856 (cl-defstruct (js2-tagged-template-node
3857 (:include js2-node)
3858 (:constructor nil)
3859 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3860 beg len tag template)))
3861 "Tagged template literal."
3862 tag ; `js2-node' with the tag expression.
3863 template) ; `js2-template-node' with the template.
3864
3865 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3866 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3867
3868 (defun js2-visit-tagged-template (n callback)
3869 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3870 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3871
3872 (defun js2-print-tagged-template (n i)
3873 (insert (js2-make-pad i))
3874 (js2-print-ast (js2-tagged-template-node-tag n))
3875 (js2-print-ast (js2-tagged-template-node-template n)))
3876
3877 (cl-defstruct (js2-array-node
3878 (:include js2-node)
3879 (:constructor nil)
3880 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3881 (pos js2-ts-cursor)
3882 len elems)))
3883 "AST node for an array literal."
3884 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3885
3886 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3887 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3888
3889 (defun js2-visit-array-node (n v)
3890 (dolist (e (js2-array-node-elems n))
3891 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3892
3893 (defun js2-print-array-node (n i)
3894 (insert (js2-make-pad i) "[")
3895 (let ((elems (js2-array-node-elems n)))
3896 (js2-print-list elems)
3897 (when (and elems (null (car (last elems))))
3898 (insert ",")))
3899 (insert "]"))
3900
3901 (cl-defstruct (js2-class-node
3902 (:include js2-node)
3903 (:constructor nil)
3904 (:constructor make-js2-class-node (&key (type js2-CLASS)
3905 (pos js2-ts-cursor)
3906 (form 'CLASS_STATEMENT)
3907 (name "")
3908 extends len elems)))
3909 "AST node for an class expression.
3910 `elems' is a list of `js2-object-prop-node', and `extends' is an
3911 optional `js2-expr-node'"
3912 form ; CLASS_{STATEMENT|EXPRESSION}
3913 name ; class name (a `js2-node-name', or nil if anonymous)
3914 extends ; class heritage (a `js2-expr-node', or nil if none)
3915 elems)
3916
3917 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3918 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3919
3920 (defun js2-visit-class-node (n v)
3921 (js2-visit-ast (js2-class-node-name n) v)
3922 (js2-visit-ast (js2-class-node-extends n) v)
3923 (dolist (e (js2-class-node-elems n))
3924 (js2-visit-ast e v)))
3925
3926 (defun js2-print-class-node (n i)
3927 (let* ((pad (js2-make-pad i))
3928 (name (js2-class-node-name n))
3929 (extends (js2-class-node-extends n))
3930 (elems (js2-class-node-elems n)))
3931 (insert pad "class")
3932 (when name
3933 (insert " ")
3934 (js2-print-ast name 0))
3935 (when extends
3936 (insert " extends ")
3937 (js2-print-ast extends))
3938 (insert " {")
3939 (dolist (elem elems)
3940 (insert "\n")
3941 (if (js2-node-get-prop elem 'STATIC)
3942 (progn (insert (js2-make-pad (1+ i)) "static ")
3943 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3944 (js2-print-ast elem (1+ i))))
3945 (insert "\n" pad "}")))
3946
3947 (cl-defstruct (js2-object-node
3948 (:include js2-node)
3949 (:constructor nil)
3950 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3951 (pos js2-ts-cursor)
3952 len
3953 elems)))
3954 "AST node for an object literal expression.
3955 `elems' is a list of `js2-object-prop-node'."
3956 elems)
3957
3958 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3959 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3960
3961 (defun js2-visit-object-node (n v)
3962 (dolist (e (js2-object-node-elems n))
3963 (js2-visit-ast e v)))
3964
3965 (defun js2-print-object-node (n i)
3966 (insert (js2-make-pad i) "{")
3967 (js2-print-list (js2-object-node-elems n))
3968 (insert "}"))
3969
3970 (cl-defstruct (js2-object-prop-node
3971 (:include js2-infix-node)
3972 (:constructor nil)
3973 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3974 (pos js2-ts-cursor)
3975 len left
3976 right op-pos)))
3977 "AST node for an object literal prop:value entry.
3978 The `left' field is the property: a name node, string node or number node.
3979 The `right' field is a `js2-node' representing the initializer value.
3980 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3981 and both fields have the same value.")
3982
3983 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3984 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3985
3986 (defun js2-print-object-prop-node (n i)
3987 (let* ((left (js2-object-prop-node-left n))
3988 (right (js2-object-prop-node-right n))
3989 (computed (not (or (js2-string-node-p left)
3990 (js2-number-node-p left)
3991 (js2-name-node-p left)))))
3992 (insert (js2-make-pad i))
3993 (if computed
3994 (insert "["))
3995 (js2-print-ast left 0)
3996 (if computed
3997 (insert "]"))
3998 (if (not (js2-node-get-prop n 'SHORTHAND))
3999 (progn
4000 (insert ": ")
4001 (js2-print-ast right 0)))))
4002
4003 (cl-defstruct (js2-getter-setter-node
4004 (:include js2-infix-node)
4005 (:constructor nil)
4006 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
4007 (pos js2-ts-cursor)
4008 len left right)))
4009 "AST node for a getter/setter property in an object literal.
4010 The `left' field is the `js2-name-node' naming the getter/setter prop.
4011 The `right' field is always an anonymous `js2-function-node' with a node
4012 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
4013
4014 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
4015 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
4016
4017 (defun js2-print-getter-setter (n i)
4018 (let* ((pad (js2-make-pad i))
4019 (left (js2-getter-setter-node-left n))
4020 (right (js2-getter-setter-node-right n))
4021 (computed (not (or (js2-string-node-p left)
4022 (js2-number-node-p left)
4023 (js2-name-node-p left)))))
4024 (insert pad)
4025 (if (/= (js2-node-type n) js2-FUNCTION)
4026 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
4027 (when (and (js2-function-node-p right)
4028 (eq 'STAR (js2-function-node-generator-type right)))
4029 (insert "*"))
4030 (when computed
4031 (insert "["))
4032 (js2-print-ast left 0)
4033 (when computed
4034 (insert "]"))
4035 (js2-print-ast right 0)))
4036
4037 (cl-defstruct (js2-prop-get-node
4038 (:include js2-infix-node)
4039 (:constructor nil)
4040 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
4041 (pos js2-ts-cursor)
4042 len left right)))
4043 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
4044
4045 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4046 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4047
4048 (defun js2-visit-prop-get-node (n v)
4049 (js2-visit-ast (js2-prop-get-node-left n) v)
4050 (js2-visit-ast (js2-prop-get-node-right n) v))
4051
4052 (defun js2-print-prop-get-node (n i)
4053 (insert (js2-make-pad i))
4054 (js2-print-ast (js2-prop-get-node-left n) 0)
4055 (insert ".")
4056 (js2-print-ast (js2-prop-get-node-right n) 0))
4057
4058 (cl-defstruct (js2-elem-get-node
4059 (:include js2-node)
4060 (:constructor nil)
4061 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4062 (pos js2-ts-cursor)
4063 len target element
4064 lb rb)))
4065 "AST node for an array index expression such as foo[bar]."
4066 target ; a `js2-node' - the expression preceding the "."
4067 element ; a `js2-node' - the expression in brackets
4068 lb ; position of left-bracket, nil if omitted
4069 rb) ; position of right-bracket, nil if omitted
4070
4071 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4072 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4073
4074 (defun js2-visit-elem-get-node (n v)
4075 (js2-visit-ast (js2-elem-get-node-target n) v)
4076 (js2-visit-ast (js2-elem-get-node-element n) v))
4077
4078 (defun js2-print-elem-get-node (n i)
4079 (insert (js2-make-pad i))
4080 (js2-print-ast (js2-elem-get-node-target n) 0)
4081 (insert "[")
4082 (js2-print-ast (js2-elem-get-node-element n) 0)
4083 (insert "]"))
4084
4085 (cl-defstruct (js2-call-node
4086 (:include js2-node)
4087 (:constructor nil)
4088 (:constructor make-js2-call-node (&key (type js2-CALL)
4089 (pos js2-ts-cursor)
4090 len target args
4091 lp rp)))
4092 "AST node for a JavaScript function call."
4093 target ; a `js2-node' evaluating to the function to call
4094 args ; a Lisp list of `js2-node' arguments
4095 lp ; position of open-paren, or nil if missing
4096 rp) ; position of close-paren, or nil if missing
4097
4098 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4099 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4100
4101 (defun js2-visit-call-node (n v)
4102 (js2-visit-ast (js2-call-node-target n) v)
4103 (dolist (arg (js2-call-node-args n))
4104 (js2-visit-ast arg v)))
4105
4106 (defun js2-print-call-node (n i)
4107 (insert (js2-make-pad i))
4108 (js2-print-ast (js2-call-node-target n) 0)
4109 (insert "(")
4110 (js2-print-list (js2-call-node-args n))
4111 (insert ")"))
4112
4113 (cl-defstruct (js2-yield-node
4114 (:include js2-node)
4115 (:constructor nil)
4116 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4117 (pos js2-ts-cursor)
4118 len value star-p)))
4119 "AST node for yield statement or expression."
4120 star-p ; whether it's yield*
4121 value) ; optional: value to be yielded
4122
4123 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4124 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4125
4126 (defun js2-visit-yield-node (n v)
4127 (js2-visit-ast (js2-yield-node-value n) v))
4128
4129 (defun js2-print-yield-node (n i)
4130 (insert (js2-make-pad i))
4131 (insert "yield")
4132 (when (js2-yield-node-star-p n)
4133 (insert "*"))
4134 (when (js2-yield-node-value n)
4135 (insert " ")
4136 (js2-print-ast (js2-yield-node-value n) 0)))
4137
4138 (cl-defstruct (js2-paren-node
4139 (:include js2-node)
4140 (:constructor nil)
4141 (:constructor make-js2-paren-node (&key (type js2-LP)
4142 (pos js2-ts-cursor)
4143 len expr)))
4144 "AST node for a parenthesized expression.
4145 In particular, used when the parens are syntactically optional,
4146 as opposed to required parens such as those enclosing an if-conditional."
4147 expr) ; `js2-node'
4148
4149 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4150 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4151
4152 (defun js2-visit-paren-node (n v)
4153 (js2-visit-ast (js2-paren-node-expr n) v))
4154
4155 (defun js2-print-paren-node (n i)
4156 (insert (js2-make-pad i))
4157 (insert "(")
4158 (js2-print-ast (js2-paren-node-expr n) 0)
4159 (insert ")"))
4160
4161 (cl-defstruct (js2-comp-node
4162 (:include js2-scope)
4163 (:constructor nil)
4164 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4165 (pos js2-ts-cursor)
4166 len result
4167 loops filters
4168 form)))
4169 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4170 result ; result expression (just after left-bracket)
4171 loops ; a Lisp list of `js2-comp-loop-node'
4172 filters ; a Lisp list of guard/filter expressions
4173 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4174 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4175 )
4176
4177 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4178 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4179
4180 (defun js2-visit-comp-node (n v)
4181 (js2-visit-ast (js2-comp-node-result n) v)
4182 (dolist (l (js2-comp-node-loops n))
4183 (js2-visit-ast l v))
4184 (dolist (f (js2-comp-node-filters n))
4185 (js2-visit-ast f v)))
4186
4187 (defun js2-print-comp-node (n i)
4188 (let ((pad (js2-make-pad i))
4189 (result (js2-comp-node-result n))
4190 (loops (js2-comp-node-loops n))
4191 (filters (js2-comp-node-filters n))
4192 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4193 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4194 (insert pad (if gen-p "(" "["))
4195 (when legacy-p
4196 (js2-print-ast result 0))
4197 (dolist (l loops)
4198 (when legacy-p
4199 (insert " "))
4200 (js2-print-ast l 0)
4201 (unless legacy-p
4202 (insert " ")))
4203 (dolist (f filters)
4204 (when legacy-p
4205 (insert " "))
4206 (insert "if (")
4207 (js2-print-ast f 0)
4208 (insert ")")
4209 (unless legacy-p
4210 (insert " ")))
4211 (unless legacy-p
4212 (js2-print-ast result 0))
4213 (insert (if gen-p ")" "]"))))
4214
4215 (cl-defstruct (js2-comp-loop-node
4216 (:include js2-for-in-node)
4217 (:constructor nil)
4218 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4219 (pos js2-ts-cursor)
4220 len iterator
4221 object in-pos
4222 foreach-p
4223 each-pos
4224 forof-p
4225 lp rp)))
4226 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4227
4228 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4229 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4230
4231 (defun js2-visit-comp-loop (n v)
4232 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4233 (js2-visit-ast (js2-comp-loop-node-object n) v))
4234
4235 (defun js2-print-comp-loop (n _i)
4236 (insert "for ")
4237 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4238 (insert "(")
4239 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4240 (insert (if (js2-comp-loop-node-forof-p n)
4241 " of " " in "))
4242 (js2-print-ast (js2-comp-loop-node-object n) 0)
4243 (insert ")"))
4244
4245 (cl-defstruct (js2-empty-expr-node
4246 (:include js2-node)
4247 (:constructor nil)
4248 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4249 (pos (js2-current-token-beg))
4250 len)))
4251 "AST node for an empty expression.")
4252
4253 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4254 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4255
4256 (cl-defstruct (js2-xml-node
4257 (:include js2-block-node)
4258 (:constructor nil)
4259 (:constructor make-js2-xml-node (&key (type js2-XML)
4260 (pos (js2-current-token-beg))
4261 len kids)))
4262 "AST node for initial parse of E4X literals.
4263 The kids field is a list of XML fragments, each a `js2-string-node' or
4264 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4265
4266 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4267 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4268
4269 (defun js2-print-xml-node (n i)
4270 (dolist (kid (js2-xml-node-kids n))
4271 (js2-print-ast kid i)))
4272
4273 (cl-defstruct (js2-xml-js-expr-node
4274 (:include js2-xml-node)
4275 (:constructor nil)
4276 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4277 (pos js2-ts-cursor)
4278 len expr)))
4279 "AST node for an embedded JavaScript {expression} in an E4X literal.
4280 The start and end fields correspond to the curly-braces."
4281 expr) ; a `js2-expr-node' of some sort
4282
4283 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4284 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4285
4286 (defun js2-visit-xml-js-expr (n v)
4287 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4288
4289 (defun js2-print-xml-js-expr (n i)
4290 (insert (js2-make-pad i))
4291 (insert "{")
4292 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4293 (insert "}"))
4294
4295 (cl-defstruct (js2-xml-dot-query-node
4296 (:include js2-infix-node)
4297 (:constructor nil)
4298 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4299 (pos js2-ts-cursor)
4300 op-pos len left
4301 right rp)))
4302 "AST node for an E4X foo.(bar) filter expression.
4303 Note that the left-paren is automatically the character immediately
4304 following the dot (.) in the operator. No whitespace is permitted
4305 between the dot and the lp by the scanner."
4306 rp)
4307
4308 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4309 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4310
4311 (defun js2-print-xml-dot-query (n i)
4312 (insert (js2-make-pad i))
4313 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4314 (insert ".(")
4315 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4316 (insert ")"))
4317
4318 (cl-defstruct (js2-xml-ref-node
4319 (:include js2-node)
4320 (:constructor nil)) ; abstract
4321 "Base type for E4X XML attribute-access or property-get expressions.
4322 Such expressions can take a variety of forms. The general syntax has
4323 three parts:
4324
4325 - (optional) an @ (specifying an attribute access)
4326 - (optional) a namespace (a `js2-name-node') and double-colon
4327 - (required) either a `js2-name-node' or a bracketed [expression]
4328
4329 The property-name expressions (examples: ns::name, @name) are
4330 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4331 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4332
4333 This node type (or more specifically, its subclasses) will sometimes
4334 be the right-hand child of a `js2-prop-get-node' or a
4335 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4336 The `js2-xml-ref-node' may also be a standalone primary expression with
4337 no explicit target, which is valid in certain expression contexts such as
4338
4339 company..employee.(@id < 100)
4340
4341 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4342 expression whose parent is a `js2-xml-dot-query-node'."
4343 namespace
4344 at-pos
4345 colon-pos)
4346
4347 (defsubst js2-xml-ref-node-attr-access-p (node)
4348 "Return non-nil if this expression began with an @-token."
4349 (and (numberp (js2-xml-ref-node-at-pos node))
4350 (cl-plusp (js2-xml-ref-node-at-pos node))))
4351
4352 (cl-defstruct (js2-xml-prop-ref-node
4353 (:include js2-xml-ref-node)
4354 (:constructor nil)
4355 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4356 (pos (js2-current-token-beg))
4357 len propname
4358 namespace at-pos
4359 colon-pos)))
4360 "AST node for an E4X XML [expr] property-ref expression.
4361 The JavaScript syntax is an optional @, an optional ns::, and a name.
4362
4363 [ '@' ] [ name '::' ] name
4364
4365 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4366 @ns::*, @*::attr, @*::*, and @*.
4367
4368 The node starts at the @ token, if present. Otherwise it starts at the
4369 namespace name. The node bounds extend through the closing right-bracket,
4370 or if it is missing due to a syntax error, through the end of the index
4371 expression."
4372 propname)
4373
4374 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4375 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4376
4377 (defun js2-visit-xml-prop-ref-node (n v)
4378 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4379 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4380
4381 (defun js2-print-xml-prop-ref-node (n i)
4382 (insert (js2-make-pad i))
4383 (if (js2-xml-ref-node-attr-access-p n)
4384 (insert "@"))
4385 (when (js2-xml-prop-ref-node-namespace n)
4386 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4387 (insert "::"))
4388 (if (js2-xml-prop-ref-node-propname n)
4389 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4390
4391 (cl-defstruct (js2-xml-elem-ref-node
4392 (:include js2-xml-ref-node)
4393 (:constructor nil)
4394 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4395 (pos (js2-current-token-beg))
4396 len expr lb rb
4397 namespace at-pos
4398 colon-pos)))
4399 "AST node for an E4X XML [expr] member-ref expression.
4400 Syntax:
4401
4402 [ '@' ] [ name '::' ] '[' expr ']'
4403
4404 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4405
4406 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4407 is not a legal E4X XML element-ref expression, since it's already used
4408 for standard JavaScript element-get array indexing. Hence, a
4409 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4410 non-nil namespace node, or both.
4411
4412 The node starts at the @ token, if present. Otherwise it starts
4413 at the namespace name. The node bounds extend through the closing
4414 right-bracket, or if it is missing due to a syntax error, through the
4415 end of the index expression."
4416 expr ; the bracketed index expression
4417 lb
4418 rb)
4419
4420 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4421 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4422
4423 (defun js2-visit-xml-elem-ref-node (n v)
4424 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4425 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4426
4427 (defun js2-print-xml-elem-ref-node (n i)
4428 (insert (js2-make-pad i))
4429 (if (js2-xml-ref-node-attr-access-p n)
4430 (insert "@"))
4431 (when (js2-xml-elem-ref-node-namespace n)
4432 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4433 (insert "::"))
4434 (insert "[")
4435 (if (js2-xml-elem-ref-node-expr n)
4436 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4437 (insert "]"))
4438
4439 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4440
4441 (cl-defstruct (js2-xml-start-tag-node
4442 (:include js2-xml-node)
4443 (:constructor nil)
4444 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4445 (pos js2-ts-cursor)
4446 len name attrs kids
4447 empty-p)))
4448 "AST node for an XML start-tag. Not currently used.
4449 The `kids' field is a Lisp list of child content nodes."
4450 name ; a `js2-xml-name-node'
4451 attrs ; a Lisp list of `js2-xml-attr-node'
4452 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4453
4454 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4455 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4456
4457 (defun js2-visit-xml-start-tag (n v)
4458 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4459 (dolist (attr (js2-xml-start-tag-node-attrs n))
4460 (js2-visit-ast attr v))
4461 (js2-visit-block n v))
4462
4463 (defun js2-print-xml-start-tag (n i)
4464 (insert (js2-make-pad i) "<")
4465 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4466 (when (js2-xml-start-tag-node-attrs n)
4467 (insert " ")
4468 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4469 (insert ">"))
4470
4471 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4472 ;; and add the end-tag to the kids list of the parent as well.
4473 (cl-defstruct (js2-xml-end-tag-node
4474 (:include js2-xml-node)
4475 (:constructor nil)
4476 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4477 (pos js2-ts-cursor)
4478 len name)))
4479 "AST node for an XML end-tag. Not currently used."
4480 name) ; a `js2-xml-name-node'
4481
4482 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4483 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4484
4485 (defun js2-visit-xml-end-tag (n v)
4486 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4487
4488 (defun js2-print-xml-end-tag (n i)
4489 (insert (js2-make-pad i))
4490 (insert "</")
4491 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4492 (insert ">"))
4493
4494 (cl-defstruct (js2-xml-name-node
4495 (:include js2-xml-node)
4496 (:constructor nil)
4497 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4498 (pos js2-ts-cursor)
4499 len namespace kids)))
4500 "AST node for an E4X XML name. Not currently used.
4501 Any XML name can be qualified with a namespace, hence the namespace field.
4502 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4503 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4504 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4505 namespace) ; a `js2-string-node'
4506
4507 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4508 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4509
4510 (defun js2-visit-xml-name-node (n v)
4511 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4512
4513 (defun js2-print-xml-name-node (n i)
4514 (insert (js2-make-pad i))
4515 (when (js2-xml-name-node-namespace n)
4516 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4517 (insert "::"))
4518 (dolist (kid (js2-xml-name-node-kids n))
4519 (js2-print-ast kid 0)))
4520
4521 (cl-defstruct (js2-xml-pi-node
4522 (:include js2-xml-node)
4523 (:constructor nil)
4524 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4525 (pos js2-ts-cursor)
4526 len name attrs)))
4527 "AST node for an E4X XML processing instruction. Not currently used."
4528 name ; a `js2-xml-name-node'
4529 attrs) ; a list of `js2-xml-attr-node'
4530
4531 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4532 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4533
4534 (defun js2-visit-xml-pi-node (n v)
4535 (js2-visit-ast (js2-xml-pi-node-name n) v)
4536 (dolist (attr (js2-xml-pi-node-attrs n))
4537 (js2-visit-ast attr v)))
4538
4539 (defun js2-print-xml-pi-node (n i)
4540 (insert (js2-make-pad i) "<?")
4541 (js2-print-ast (js2-xml-pi-node-name n))
4542 (when (js2-xml-pi-node-attrs n)
4543 (insert " ")
4544 (js2-print-list (js2-xml-pi-node-attrs n)))
4545 (insert "?>"))
4546
4547 (cl-defstruct (js2-xml-cdata-node
4548 (:include js2-xml-node)
4549 (:constructor nil)
4550 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4551 (pos js2-ts-cursor)
4552 len content)))
4553 "AST node for a CDATA escape section. Not currently used."
4554 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4555
4556 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4557 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4558
4559 (defun js2-visit-xml-cdata-node (n v)
4560 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4561
4562 (defun js2-print-xml-cdata-node (n i)
4563 (insert (js2-make-pad i))
4564 (js2-print-ast (js2-xml-cdata-node-content n)))
4565
4566 (cl-defstruct (js2-xml-attr-node
4567 (:include js2-xml-node)
4568 (:constructor nil)
4569 (:constructor make-js2-attr-node (&key (type js2-XML)
4570 (pos js2-ts-cursor)
4571 len name value
4572 eq-pos quote-type)))
4573 "AST node representing a foo='bar' XML attribute value. Not yet used."
4574 name ; a `js2-xml-name-node'
4575 value ; a `js2-xml-name-node'
4576 eq-pos ; buffer position of "=" sign
4577 quote-type) ; 'single or 'double
4578
4579 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4580 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4581
4582 (defun js2-visit-xml-attr-node (n v)
4583 (js2-visit-ast (js2-xml-attr-node-name n) v)
4584 (js2-visit-ast (js2-xml-attr-node-value n) v))
4585
4586 (defun js2-print-xml-attr-node (n i)
4587 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4588 "'"
4589 "\"")))
4590 (insert (js2-make-pad i))
4591 (js2-print-ast (js2-xml-attr-node-name n) 0)
4592 (insert "=" quote)
4593 (js2-print-ast (js2-xml-attr-node-value n) 0)
4594 (insert quote)))
4595
4596 (cl-defstruct (js2-xml-text-node
4597 (:include js2-xml-node)
4598 (:constructor nil)
4599 (:constructor make-js2-text-node (&key (type js2-XML)
4600 (pos js2-ts-cursor)
4601 len content)))
4602 "AST node for an E4X XML text node. Not currently used."
4603 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4604
4605 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4606 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4607
4608 (defun js2-visit-xml-text-node (n v)
4609 (js2-visit-ast (js2-xml-text-node-content n) v))
4610
4611 (defun js2-print-xml-text-node (n i)
4612 (insert (js2-make-pad i))
4613 (dolist (kid (js2-xml-text-node-content n))
4614 (js2-print-ast kid)))
4615
4616 (cl-defstruct (js2-xml-comment-node
4617 (:include js2-xml-node)
4618 (:constructor nil)
4619 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4620 (pos js2-ts-cursor)
4621 len)))
4622 "AST node for E4X XML comment. Not currently used.")
4623
4624 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4625 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4626
4627 (defun js2-print-xml-comment (n i)
4628 (insert (js2-make-pad i)
4629 (js2-node-string n)))
4630
4631 ;;; Node utilities
4632
4633 (defsubst js2-node-line (n)
4634 "Fetch the source line number at the start of node N.
4635 This is O(n) in the length of the source buffer; use prudently."
4636 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4637
4638 (defsubst js2-block-node-kid (n i)
4639 "Return child I of node N, or nil if there aren't that many."
4640 (nth i (js2-block-node-kids n)))
4641
4642 (defsubst js2-block-node-first (n)
4643 "Return first child of block node N, or nil if there is none."
4644 (cl-first (js2-block-node-kids n)))
4645
4646 (defun js2-node-root (n)
4647 "Return the root of the AST containing N.
4648 If N has no parent pointer, returns N."
4649 (let ((parent (js2-node-parent n)))
4650 (if parent
4651 (js2-node-root parent)
4652 n)))
4653
4654 (defsubst js2-node-short-name (n)
4655 "Return the short name of node N as a string, e.g. `js2-if-node'."
4656 (substring (symbol-name (aref n 0))
4657 (length "cl-struct-")))
4658
4659 (defun js2-node-child-list (node)
4660 "Return the child list for NODE, a Lisp list of nodes.
4661 Works for block nodes, array nodes, obj literals, funarg lists,
4662 var decls and try nodes (for catch clauses). Note that you should call
4663 `js2-block-node-kids' on the function body for the body statements.
4664 Returns nil for zero-length child lists or unsupported nodes."
4665 (cond
4666 ((js2-function-node-p node)
4667 (js2-function-node-params node))
4668 ((js2-block-node-p node)
4669 (js2-block-node-kids node))
4670 ((js2-try-node-p node)
4671 (js2-try-node-catch-clauses node))
4672 ((js2-array-node-p node)
4673 (js2-array-node-elems node))
4674 ((js2-object-node-p node)
4675 (js2-object-node-elems node))
4676 ((js2-call-node-p node)
4677 (js2-call-node-args node))
4678 ((js2-new-node-p node)
4679 (js2-new-node-args node))
4680 ((js2-var-decl-node-p node)
4681 (js2-var-decl-node-kids node))
4682 (t
4683 nil)))
4684
4685 (defun js2-node-set-child-list (node kids)
4686 "Set the child list for NODE to KIDS."
4687 (cond
4688 ((js2-function-node-p node)
4689 (setf (js2-function-node-params node) kids))
4690 ((js2-block-node-p node)
4691 (setf (js2-block-node-kids node) kids))
4692 ((js2-try-node-p node)
4693 (setf (js2-try-node-catch-clauses node) kids))
4694 ((js2-array-node-p node)
4695 (setf (js2-array-node-elems node) kids))
4696 ((js2-object-node-p node)
4697 (setf (js2-object-node-elems node) kids))
4698 ((js2-call-node-p node)
4699 (setf (js2-call-node-args node) kids))
4700 ((js2-new-node-p node)
4701 (setf (js2-new-node-args node) kids))
4702 ((js2-var-decl-node-p node)
4703 (setf (js2-var-decl-node-kids node) kids))
4704 (t
4705 (error "Unsupported node type: %s" (js2-node-short-name node))))
4706 kids)
4707
4708 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4709 (defconst js2-paren-expr-nodes
4710 '(cl-struct-js2-comp-loop-node
4711 cl-struct-js2-comp-node
4712 cl-struct-js2-call-node
4713 cl-struct-js2-catch-node
4714 cl-struct-js2-do-node
4715 cl-struct-js2-elem-get-node
4716 cl-struct-js2-for-in-node
4717 cl-struct-js2-for-node
4718 cl-struct-js2-function-node
4719 cl-struct-js2-if-node
4720 cl-struct-js2-let-node
4721 cl-struct-js2-new-node
4722 cl-struct-js2-paren-node
4723 cl-struct-js2-switch-node
4724 cl-struct-js2-while-node
4725 cl-struct-js2-with-node
4726 cl-struct-js2-xml-dot-query-node)
4727 "Node types that can have a parenthesized child expression.
4728 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4729
4730 (defsubst js2-paren-expr-node-p (node)
4731 "Return t for nodes that typically have a parenthesized child expression.
4732 Useful for computing the indentation anchors for arg-lists and conditions.
4733 Note that it may return a false positive, for instance when NODE is
4734 a `js2-new-node' and there are no arguments or parentheses."
4735 (memq (aref node 0) js2-paren-expr-nodes))
4736
4737 ;; Fake polymorphism... yech.
4738 (defun js2-node-lp (node)
4739 "Return relative left-paren position for NODE, if applicable.
4740 For `js2-elem-get-node' structs, returns left-bracket position.
4741 Note that the position may be nil in the case of a parse error."
4742 (cond
4743 ((js2-elem-get-node-p node)
4744 (js2-elem-get-node-lb node))
4745 ((js2-loop-node-p node)
4746 (js2-loop-node-lp node))
4747 ((js2-function-node-p node)
4748 (js2-function-node-lp node))
4749 ((js2-if-node-p node)
4750 (js2-if-node-lp node))
4751 ((js2-new-node-p node)
4752 (js2-new-node-lp node))
4753 ((js2-call-node-p node)
4754 (js2-call-node-lp node))
4755 ((js2-paren-node-p node)
4756 0)
4757 ((js2-switch-node-p node)
4758 (js2-switch-node-lp node))
4759 ((js2-catch-node-p node)
4760 (js2-catch-node-lp node))
4761 ((js2-let-node-p node)
4762 (js2-let-node-lp node))
4763 ((js2-comp-node-p node)
4764 0)
4765 ((js2-with-node-p node)
4766 (js2-with-node-lp node))
4767 ((js2-xml-dot-query-node-p node)
4768 (1+ (js2-infix-node-op-pos node)))
4769 (t
4770 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4771
4772 ;; Fake polymorphism... blech.
4773 (defun js2-node-rp (node)
4774 "Return relative right-paren position for NODE, if applicable.
4775 For `js2-elem-get-node' structs, returns right-bracket position.
4776 Note that the position may be nil in the case of a parse error."
4777 (cond
4778 ((js2-elem-get-node-p node)
4779 (js2-elem-get-node-rb node))
4780 ((js2-loop-node-p node)
4781 (js2-loop-node-rp node))
4782 ((js2-function-node-p node)
4783 (js2-function-node-rp node))
4784 ((js2-if-node-p node)
4785 (js2-if-node-rp node))
4786 ((js2-new-node-p node)
4787 (js2-new-node-rp node))
4788 ((js2-call-node-p node)
4789 (js2-call-node-rp node))
4790 ((js2-paren-node-p node)
4791 (1- (js2-node-len node)))
4792 ((js2-switch-node-p node)
4793 (js2-switch-node-rp node))
4794 ((js2-catch-node-p node)
4795 (js2-catch-node-rp node))
4796 ((js2-let-node-p node)
4797 (js2-let-node-rp node))
4798 ((js2-comp-node-p node)
4799 (1- (js2-node-len node)))
4800 ((js2-with-node-p node)
4801 (js2-with-node-rp node))
4802 ((js2-xml-dot-query-node-p node)
4803 (1+ (js2-xml-dot-query-node-rp node)))
4804 (t
4805 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4806
4807 (defsubst js2-node-first-child (node)
4808 "Return the first element of `js2-node-child-list' for NODE."
4809 (car (js2-node-child-list node)))
4810
4811 (defsubst js2-node-last-child (node)
4812 "Return the last element of `js2-node-last-child' for NODE."
4813 (car (last (js2-node-child-list node))))
4814
4815 (defun js2-node-prev-sibling (node)
4816 "Return the previous statement in parent.
4817 Works for parents supported by `js2-node-child-list'.
4818 Returns nil if NODE is not in the parent, or PARENT is
4819 not a supported node, or if NODE is the first child."
4820 (let* ((p (js2-node-parent node))
4821 (kids (js2-node-child-list p))
4822 (sib (car kids)))
4823 (while (and kids
4824 (not (eq node (cadr kids))))
4825 (setq kids (cdr kids)
4826 sib (car kids)))
4827 sib))
4828
4829 (defun js2-node-next-sibling (node)
4830 "Return the next statement in parent block.
4831 Returns nil if NODE is not in the block, or PARENT is not
4832 a block node, or if NODE is the last statement."
4833 (let* ((p (js2-node-parent node))
4834 (kids (js2-node-child-list p)))
4835 (while (and kids
4836 (not (eq node (car kids))))
4837 (setq kids (cdr kids)))
4838 (cadr kids)))
4839
4840 (defun js2-node-find-child-before (pos parent &optional after)
4841 "Find the last child that starts before POS in parent.
4842 If AFTER is non-nil, returns first child starting after POS.
4843 POS is an absolute buffer position. PARENT is any node
4844 supported by `js2-node-child-list'.
4845 Returns nil if no applicable child is found."
4846 (let ((kids (if (js2-function-node-p parent)
4847 (js2-block-node-kids (js2-function-node-body parent))
4848 (js2-node-child-list parent)))
4849 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4850 (js2-function-node-body parent)
4851 parent)))
4852 kid result fn
4853 (continue t))
4854 (setq fn (if after '>= '<))
4855 (while (and kids continue)
4856 (setq kid (car kids))
4857 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4858 (setq result kid
4859 continue (not after))
4860 (setq continue after))
4861 (setq kids (cdr kids)))
4862 result))
4863
4864 (defun js2-node-find-child-after (pos parent)
4865 "Find first child that starts after POS in parent.
4866 POS is an absolute buffer position. PARENT is any node
4867 supported by `js2-node-child-list'.
4868 Returns nil if no applicable child is found."
4869 (js2-node-find-child-before pos parent 'after))
4870
4871 (defun js2-node-replace-child (pos parent new-node)
4872 "Replace node at index POS in PARENT with NEW-NODE.
4873 Only works for parents supported by `js2-node-child-list'."
4874 (let ((kids (js2-node-child-list parent))
4875 (i 0))
4876 (while (< i pos)
4877 (setq kids (cdr kids)
4878 i (1+ i)))
4879 (setcar kids new-node)
4880 (js2-node-add-children parent new-node)))
4881
4882 (defun js2-node-buffer (n)
4883 "Return the buffer associated with AST N.
4884 Returns nil if the buffer is not set as a property on the root
4885 node, or if parent links were not recorded during parsing."
4886 (let ((root (js2-node-root n)))
4887 (and root
4888 (js2-ast-root-p root)
4889 (js2-ast-root-buffer root))))
4890
4891 (defun js2-block-node-push (n kid)
4892 "Push js2-node KID onto the end of js2-block-node N's child list.
4893 KID is always added to the -end- of the kids list.
4894 Function also calls `js2-node-add-children' to add the parent link."
4895 (let ((kids (js2-node-child-list n)))
4896 (if kids
4897 (setcdr kids (nconc (cdr kids) (list kid)))
4898 (js2-node-set-child-list n (list kid)))
4899 (js2-node-add-children n kid)))
4900
4901 (defun js2-node-string (node)
4902 (with-current-buffer (or (js2-node-buffer node)
4903 (error "No buffer available for node %s" node))
4904 (let ((pos (js2-node-abs-pos node)))
4905 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4906
4907 ;; Container for storing the node we're looking for in a traversal.
4908 (js2-deflocal js2-discovered-node nil)
4909
4910 ;; Keep track of absolute node position during traversals.
4911 (js2-deflocal js2-visitor-offset nil)
4912
4913 (js2-deflocal js2-node-search-point nil)
4914
4915 (when js2-mode-dev-mode-p
4916 (defun js2-find-node-at-point ()
4917 (interactive)
4918 (let ((node (js2-node-at-point)))
4919 (message "%s" (or node "No node found at point"))))
4920 (defun js2-node-name-at-point ()
4921 (interactive)
4922 (let ((node (js2-node-at-point)))
4923 (message "%s" (if node
4924 (js2-node-short-name node)
4925 "No node found at point.")))))
4926
4927 (defun js2-node-at-point (&optional pos skip-comments)
4928 "Return AST node at POS, a buffer position, defaulting to current point.
4929 The `js2-mode-ast' variable must be set to the current parse tree.
4930 Signals an error if the AST (`js2-mode-ast') is nil.
4931 Always returns a node - if it can't find one, it returns the root.
4932 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4933 (let ((ast js2-mode-ast)
4934 result)
4935 (unless ast
4936 (error "No JavaScript AST available"))
4937 ;; Look through comments first, since they may be inside nodes that
4938 ;; would otherwise report a match.
4939 (setq pos (or pos (point))
4940 result (if (> pos (js2-node-abs-end ast))
4941 ast
4942 (if (not skip-comments)
4943 (js2-comment-at-point pos))))
4944 (unless result
4945 (setq js2-discovered-node nil
4946 js2-visitor-offset 0
4947 js2-node-search-point pos)
4948 (unwind-protect
4949 (catch 'js2-visit-done
4950 (js2-visit-ast ast #'js2-node-at-point-visitor))
4951 (setq js2-visitor-offset nil
4952 js2-node-search-point nil))
4953 (setq result js2-discovered-node))
4954 ;; may have found a comment beyond end of last child node,
4955 ;; since visiting the ast-root looks at the comment-list last.
4956 (if (and skip-comments
4957 (js2-comment-node-p result))
4958 (setq result nil))
4959 (or result js2-mode-ast)))
4960
4961 (defun js2-node-at-point-visitor (node end-p)
4962 (let ((rel-pos (js2-node-pos node))
4963 abs-pos
4964 abs-end
4965 (point js2-node-search-point))
4966 (cond
4967 (end-p
4968 ;; this evaluates to a non-nil return value, even if it's zero
4969 (cl-decf js2-visitor-offset rel-pos))
4970 ;; we already looked for comments before visiting, and don't want them now
4971 ((js2-comment-node-p node)
4972 nil)
4973 (t
4974 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4975 ;; we only want to use the node if the point is before
4976 ;; the last character position in the node, so we decrement
4977 ;; the absolute end by 1.
4978 abs-end (+ abs-pos (js2-node-len node) -1))
4979 (cond
4980 ;; If this node starts after search-point, stop the search.
4981 ((> abs-pos point)
4982 (throw 'js2-visit-done nil))
4983 ;; If this node ends before the search-point, don't check kids.
4984 ((> point abs-end)
4985 nil)
4986 (t
4987 ;; Otherwise point is within this node, possibly in a child.
4988 (setq js2-discovered-node node)
4989 t)))))) ; keep processing kids to look for more specific match
4990
4991 (defsubst js2-block-comment-p (node)
4992 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4993 (and (js2-comment-node-p node)
4994 (memq (js2-comment-node-format node) '(jsdoc block))))
4995
4996 ;; TODO: put the comments in a vector and binary-search them instead
4997 (defun js2-comment-at-point (&optional pos)
4998 "Look through scanned comment nodes for one containing POS.
4999 POS is a buffer position that defaults to current point.
5000 Function returns nil if POS was not in any comment node."
5001 (let ((ast js2-mode-ast)
5002 (x (or pos (point)))
5003 beg end)
5004 (unless ast
5005 (error "No JavaScript AST available"))
5006 (catch 'done
5007 ;; Comments are stored in lexical order.
5008 (dolist (comment (js2-ast-root-comments ast) nil)
5009 (setq beg (js2-node-abs-pos comment)
5010 end (+ beg (js2-node-len comment)))
5011 (if (and (>= x beg)
5012 (<= x end))
5013 (throw 'done comment))))))
5014
5015 (defun js2-mode-find-parent-fn (node)
5016 "Find function enclosing NODE.
5017 Returns nil if NODE is not inside a function."
5018 (setq node (js2-node-parent node))
5019 (while (and node (not (js2-function-node-p node)))
5020 (setq node (js2-node-parent node)))
5021 (and (js2-function-node-p node) node))
5022
5023 (defun js2-mode-find-enclosing-fn (node)
5024 "Find function or root enclosing NODE."
5025 (if (js2-ast-root-p node)
5026 node
5027 (setq node (js2-node-parent node))
5028 (while (not (or (js2-ast-root-p node)
5029 (js2-function-node-p node)))
5030 (setq node (js2-node-parent node)))
5031 node))
5032
5033 (defun js2-mode-find-enclosing-node (beg end)
5034 "Find node fully enclosing BEG and END."
5035 (let ((node (js2-node-at-point beg))
5036 pos
5037 (continue t))
5038 (while continue
5039 (if (or (js2-ast-root-p node)
5040 (and
5041 (<= (setq pos (js2-node-abs-pos node)) beg)
5042 (>= (+ pos (js2-node-len node)) end)))
5043 (setq continue nil)
5044 (setq node (js2-node-parent node))))
5045 node))
5046
5047 (defun js2-node-parent-script-or-fn (node)
5048 "Find script or function immediately enclosing NODE.
5049 If NODE is the ast-root, returns nil."
5050 (if (js2-ast-root-p node)
5051 nil
5052 (setq node (js2-node-parent node))
5053 (while (and node (not (or (js2-function-node-p node)
5054 (js2-script-node-p node))))
5055 (setq node (js2-node-parent node)))
5056 node))
5057
5058 (defun js2-node-is-descendant (node ancestor)
5059 "Return t if NODE is a descendant of ANCESTOR."
5060 (while (and node
5061 (not (eq node ancestor)))
5062 (setq node (js2-node-parent node)))
5063 node)
5064
5065 ;;; visitor infrastructure
5066
5067 (defun js2-visit-none (_node _callback)
5068 "Visitor for AST node that have no node children."
5069 nil)
5070
5071 (defun js2-print-none (_node _indent)
5072 "Visitor for AST node with no printed representation.")
5073
5074 (defun js2-print-body (node indent)
5075 "Print a statement, or a block without braces."
5076 (if (js2-block-node-p node)
5077 (dolist (kid (js2-block-node-kids node))
5078 (js2-print-ast kid indent))
5079 (js2-print-ast node indent)))
5080
5081 (defun js2-print-list (args &optional delimiter)
5082 (cl-loop with len = (length args)
5083 for arg in args
5084 for count from 1
5085 do
5086 (when arg (js2-print-ast arg 0))
5087 (if (< count len)
5088 (insert (or delimiter ", ")))))
5089
5090 (defun js2-print-tree (ast)
5091 "Prints an AST to the current buffer.
5092 Makes `js2-ast-parent-nodes' available to the printer functions."
5093 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5094 (js2-print-ast ast)))
5095
5096 (defun js2-print-ast (node &optional indent)
5097 "Helper function for printing AST nodes.
5098 Requires `js2-ast-parent-nodes' to be non-nil.
5099 You should use `js2-print-tree' instead of this function."
5100 (let ((printer (get (aref node 0) 'js2-printer))
5101 (i (or indent 0)))
5102 ;; TODO: wedge comments in here somewhere
5103 (if printer
5104 (funcall printer node i))))
5105
5106 (defconst js2-side-effecting-tokens
5107 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5108 (dolist (tt (list js2-ASSIGN
5109 js2-ASSIGN_ADD
5110 js2-ASSIGN_BITAND
5111 js2-ASSIGN_BITOR
5112 js2-ASSIGN_BITXOR
5113 js2-ASSIGN_DIV
5114 js2-ASSIGN_LSH
5115 js2-ASSIGN_MOD
5116 js2-ASSIGN_MUL
5117 js2-ASSIGN_RSH
5118 js2-ASSIGN_SUB
5119 js2-ASSIGN_URSH
5120 js2-BLOCK
5121 js2-BREAK
5122 js2-CALL
5123 js2-CATCH
5124 js2-CATCH_SCOPE
5125 js2-CLASS
5126 js2-CONST
5127 js2-CONTINUE
5128 js2-DEBUGGER
5129 js2-DEC
5130 js2-DELPROP
5131 js2-DEL_REF
5132 js2-DO
5133 js2-ELSE
5134 js2-EMPTY
5135 js2-ENTERWITH
5136 js2-EXPORT
5137 js2-EXPR_RESULT
5138 js2-FINALLY
5139 js2-FOR
5140 js2-FUNCTION
5141 js2-GOTO
5142 js2-IF
5143 js2-IFEQ
5144 js2-IFNE
5145 js2-IMPORT
5146 js2-INC
5147 js2-JSR
5148 js2-LABEL
5149 js2-LEAVEWITH
5150 js2-LET
5151 js2-LETEXPR
5152 js2-LOCAL_BLOCK
5153 js2-LOOP
5154 js2-NEW
5155 js2-REF_CALL
5156 js2-RETHROW
5157 js2-RETURN
5158 js2-RETURN_RESULT
5159 js2-SEMI
5160 js2-SETELEM
5161 js2-SETELEM_OP
5162 js2-SETNAME
5163 js2-SETPROP
5164 js2-SETPROP_OP
5165 js2-SETVAR
5166 js2-SET_REF
5167 js2-SET_REF_OP
5168 js2-SWITCH
5169 js2-TARGET
5170 js2-THROW
5171 js2-TRY
5172 js2-VAR
5173 js2-WHILE
5174 js2-WITH
5175 js2-WITHEXPR
5176 js2-YIELD))
5177 (aset tokens tt t))
5178 (if js2-instanceof-has-side-effects
5179 (aset tokens js2-INSTANCEOF t))
5180 tokens))
5181
5182 (defun js2-node-has-side-effects (node)
5183 "Return t if NODE has side effects."
5184 (when node ; makes it easier to handle malformed expressions
5185 (let ((tt (js2-node-type node)))
5186 (cond
5187 ;; This doubtless needs some work, since EXPR_VOID is used
5188 ;; in several ways in Rhino and I may not have caught them all.
5189 ;; I'll wait for people to notice incorrect warnings.
5190 ((and (= tt js2-EXPR_VOID)
5191 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5192 (let ((expr (js2-expr-stmt-node-expr node)))
5193 (or (js2-node-has-side-effects expr)
5194 (when (js2-string-node-p expr)
5195 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5196 ((= tt js2-COMMA)
5197 (js2-node-has-side-effects (js2-infix-node-right node)))
5198 ((or (= tt js2-AND)
5199 (= tt js2-OR))
5200 (or (js2-node-has-side-effects (js2-infix-node-right node))
5201 (js2-node-has-side-effects (js2-infix-node-left node))))
5202 ((= tt js2-HOOK)
5203 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5204 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5205 ((js2-paren-node-p node)
5206 (js2-node-has-side-effects (js2-paren-node-expr node)))
5207 ((= tt js2-ERROR) ; avoid cascaded error messages
5208 nil)
5209 (t
5210 (aref js2-side-effecting-tokens tt))))))
5211
5212 (defconst js2-stmt-node-types
5213 (list js2-BLOCK
5214 js2-BREAK
5215 js2-CONTINUE
5216 js2-DEFAULT ; e4x "default xml namespace" statement
5217 js2-DO
5218 js2-EXPORT
5219 js2-EXPR_RESULT
5220 js2-EXPR_VOID
5221 js2-FOR
5222 js2-IF
5223 js2-IMPORT
5224 js2-RETURN
5225 js2-SWITCH
5226 js2-THROW
5227 js2-TRY
5228 js2-WHILE
5229 js2-WITH)
5230 "Node types that only appear in statement contexts.
5231 The list does not include nodes that always appear as the child
5232 of another specific statement type, such as switch-cases,
5233 catch and finally blocks, and else-clauses. The list also excludes
5234 nodes like yield, let and var, which may appear in either expression
5235 or statement context, and in the latter context always have a
5236 `js2-expr-stmt-node' parent. Finally, the list does not include
5237 functions or scripts, which are treated separately from statements
5238 by the JavaScript parser and runtime.")
5239
5240 (defun js2-stmt-node-p (node)
5241 "Heuristic for figuring out if NODE is a statement.
5242 Some node types can appear in either an expression context or a
5243 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5244 For these node types in a statement context, the parent will be a
5245 `js2-expr-stmt-node'.
5246 Functions aren't included in the check."
5247 (memq (js2-node-type node) js2-stmt-node-types))
5248
5249 (defun js2-mode-find-first-stmt (node)
5250 "Search upward starting from NODE looking for a statement.
5251 For purposes of this function, a `js2-function-node' counts."
5252 (while (not (or (js2-stmt-node-p node)
5253 (js2-function-node-p node)))
5254 (setq node (js2-node-parent node)))
5255 node)
5256
5257 (defun js2-node-parent-stmt (node)
5258 "Return the node's first ancestor that is a statement.
5259 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5260 appearing in a statement context will have a parent that is a
5261 `js2-expr-stmt-node' that will be returned by this function."
5262 (let ((parent (js2-node-parent node)))
5263 (if (or (null parent)
5264 (js2-stmt-node-p parent)
5265 (and (js2-function-node-p parent)
5266 (not (eq (js2-function-node-form parent)
5267 'FUNCTION_EXPRESSION))))
5268 parent
5269 (js2-node-parent-stmt parent))))
5270
5271 ;; In the Mozilla Rhino sources, Roshan James writes:
5272 ;; Does consistent-return analysis on the function body when strict mode is
5273 ;; enabled.
5274 ;;
5275 ;; function (x) { return (x+1) }
5276 ;;
5277 ;; is ok, but
5278 ;;
5279 ;; function (x) { if (x < 0) return (x+1); }
5280 ;;
5281 ;; is not because the function can potentially return a value when the
5282 ;; condition is satisfied and if not, the function does not explicitly
5283 ;; return a value.
5284 ;;
5285 ;; This extends to checking mismatches such as "return" and "return <value>"
5286 ;; used in the same function. Warnings are not emitted if inconsistent
5287 ;; returns exist in code that can be statically shown to be unreachable.
5288 ;; Ex.
5289 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5290 ;;
5291 ;; emits no warning. However if the loop had a break statement, then a
5292 ;; warning would be emitted.
5293 ;;
5294 ;; The consistency analysis looks at control structures such as loops, ifs,
5295 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5296 ;; warns the user about an inconsistent set of termination possibilities.
5297 ;;
5298 ;; These flags enumerate the possible ways a statement/function can
5299 ;; terminate. These flags are used by endCheck() and by the Parser to
5300 ;; detect inconsistent return usage.
5301 ;;
5302 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5303 ;; able to execute (example: throw, continue)
5304 ;;
5305 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5306 ;; next one. Statement such as return dont. A compound statement may have
5307 ;; some branch that drops off control to the next statement.
5308 ;;
5309 ;; END_RETURNS indicates that the statement can return with no value.
5310 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5311 ;;
5312 ;; A compound statement such as
5313 ;; if (condition) {
5314 ;; return value;
5315 ;; }
5316 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5317
5318 (defconst js2-END_UNREACHED 0)
5319 (defconst js2-END_DROPS_OFF 1)
5320 (defconst js2-END_RETURNS 2)
5321 (defconst js2-END_RETURNS_VALUE 4)
5322 (defconst js2-END_YIELDS 8)
5323
5324 (defun js2-has-consistent-return-usage (node)
5325 "Check that every return usage in a function body is consistent.
5326 Returns t if the function satisfies strict mode requirement."
5327 (let ((n (js2-end-check node)))
5328 ;; either it doesn't return a value in any branch...
5329 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5330 ;; or it returns a value (or is unreached) at every branch
5331 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5332 js2-END_RETURNS
5333 js2-END_YIELDS)))))
5334
5335 (defun js2-end-check-if (node)
5336 "Ensure that return usage in then/else blocks is consistent.
5337 If there is no else block, then the return statement can fall through.
5338 Returns logical OR of END_* flags"
5339 (let ((th (js2-if-node-then-part node))
5340 (el (js2-if-node-else-part node)))
5341 (if (null th)
5342 js2-END_UNREACHED
5343 (logior (js2-end-check th) (if el
5344 (js2-end-check el)
5345 js2-END_DROPS_OFF)))))
5346
5347 (defun js2-end-check-switch (node)
5348 "Consistency of return statements is checked between the case statements.
5349 If there is no default, then the switch can fall through. If there is a
5350 default, we check to see if all code paths in the default return or if
5351 there is a code path that can fall through.
5352 Returns logical OR of END_* flags."
5353 (let ((rv js2-END_UNREACHED)
5354 default-case)
5355 ;; examine the cases
5356 (catch 'break
5357 (dolist (c (js2-switch-node-cases node))
5358 (if (js2-case-node-expr c)
5359 (js2-set-flag rv (js2-end-check-block c))
5360 (setq default-case c)
5361 (throw 'break nil))))
5362 ;; we don't care how the cases drop into each other
5363 (js2-clear-flag rv js2-END_DROPS_OFF)
5364 ;; examine the default
5365 (js2-set-flag rv (if default-case
5366 (js2-end-check default-case)
5367 js2-END_DROPS_OFF))
5368 rv))
5369
5370 (defun js2-end-check-try (node)
5371 "If the block has a finally, return consistency is checked in the
5372 finally block. If all code paths in the finally return, then the
5373 returns in the try-catch blocks don't matter. If there is a code path
5374 that does not return or if there is no finally block, the returns
5375 of the try and catch blocks are checked for mismatch.
5376 Returns logical OR of END_* flags."
5377 (let ((finally (js2-try-node-finally-block node))
5378 rv)
5379 ;; check the finally if it exists
5380 (setq rv (if finally
5381 (js2-end-check (js2-finally-node-body finally))
5382 js2-END_DROPS_OFF))
5383 ;; If the finally block always returns, then none of the returns
5384 ;; in the try or catch blocks matter.
5385 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5386 (js2-clear-flag rv js2-END_DROPS_OFF)
5387 ;; examine the try block
5388 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5389 ;; check each catch block
5390 (dolist (cb (js2-try-node-catch-clauses node))
5391 (js2-set-flag rv (js2-end-check cb))))
5392 rv))
5393
5394 (defun js2-end-check-loop (node)
5395 "Return statement in the loop body must be consistent.
5396 The default assumption for any kind of a loop is that it will eventually
5397 terminate. The only exception is a loop with a constant true condition.
5398 Code that follows such a loop is examined only if one can determine
5399 statically that there is a break out of the loop.
5400
5401 for(... ; ... ; ...) {}
5402 for(... in ... ) {}
5403 while(...) { }
5404 do { } while(...)
5405
5406 Returns logical OR of END_* flags."
5407 (let ((rv (js2-end-check (js2-loop-node-body node)))
5408 (condition (cond
5409 ((js2-while-node-p node)
5410 (js2-while-node-condition node))
5411 ((js2-do-node-p node)
5412 (js2-do-node-condition node))
5413 ((js2-for-node-p node)
5414 (js2-for-node-condition node)))))
5415
5416 ;; check to see if the loop condition is always true
5417 (if (and condition
5418 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5419 (js2-clear-flag rv js2-END_DROPS_OFF))
5420
5421 ;; look for effect of breaks
5422 (js2-set-flag rv (js2-node-get-prop node
5423 'CONTROL_BLOCK_PROP
5424 js2-END_UNREACHED))
5425 rv))
5426
5427 (defun js2-end-check-block (node)
5428 "A general block of code is examined statement by statement.
5429 If any statement (even a compound one) returns in all branches, then
5430 subsequent statements are not examined.
5431 Returns logical OR of END_* flags."
5432 (let* ((rv js2-END_DROPS_OFF)
5433 (kids (js2-block-node-kids node))
5434 (n (car kids)))
5435 ;; Check each statement. If the statement can continue onto the next
5436 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5437 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5438 (js2-clear-flag rv js2-END_DROPS_OFF)
5439 (js2-set-flag rv (js2-end-check n))
5440 (setq kids (cdr kids)
5441 n (car kids)))
5442 rv))
5443
5444 (defun js2-end-check-label (node)
5445 "A labeled statement implies that there may be a break to the label.
5446 The function processes the labeled statement and then checks the
5447 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5448 particular label.
5449 Returns logical OR of END_* flags."
5450 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5451 (logior rv (js2-node-get-prop node
5452 'CONTROL_BLOCK_PROP
5453 js2-END_UNREACHED))))
5454
5455 (defun js2-end-check-break (node)
5456 "When a break is encountered annotate the statement being broken
5457 out of by setting its CONTROL_BLOCK_PROP property.
5458 Returns logical OR of END_* flags."
5459 (and (js2-break-node-target node)
5460 (js2-node-set-prop (js2-break-node-target node)
5461 'CONTROL_BLOCK_PROP
5462 js2-END_DROPS_OFF))
5463 js2-END_UNREACHED)
5464
5465 (defun js2-end-check (node)
5466 "Examine the body of a function, doing a basic reachability analysis.
5467 Returns a combination of flags END_* flags that indicate
5468 how the function execution can terminate. These constitute only the
5469 pessimistic set of termination conditions. It is possible that at
5470 runtime certain code paths will never be actually taken. Hence this
5471 analysis will flag errors in cases where there may not be errors.
5472 Returns logical OR of END_* flags"
5473 (let (kid)
5474 (cond
5475 ((js2-break-node-p node)
5476 (js2-end-check-break node))
5477 ((js2-expr-stmt-node-p node)
5478 (if (setq kid (js2-expr-stmt-node-expr node))
5479 (js2-end-check kid)
5480 js2-END_DROPS_OFF))
5481 ((or (js2-continue-node-p node)
5482 (js2-throw-node-p node))
5483 js2-END_UNREACHED)
5484 ((js2-return-node-p node)
5485 (if (setq kid (js2-return-node-retval node))
5486 js2-END_RETURNS_VALUE
5487 js2-END_RETURNS))
5488 ((js2-loop-node-p node)
5489 (js2-end-check-loop node))
5490 ((js2-switch-node-p node)
5491 (js2-end-check-switch node))
5492 ((js2-labeled-stmt-node-p node)
5493 (js2-end-check-label node))
5494 ((js2-if-node-p node)
5495 (js2-end-check-if node))
5496 ((js2-try-node-p node)
5497 (js2-end-check-try node))
5498 ((js2-block-node-p node)
5499 (if (null (js2-block-node-kids node))
5500 js2-END_DROPS_OFF
5501 (js2-end-check-block node)))
5502 ((js2-yield-node-p node)
5503 js2-END_YIELDS)
5504 (t
5505 js2-END_DROPS_OFF))))
5506
5507 (defun js2-always-defined-boolean-p (node)
5508 "Check if NODE always evaluates to true or false in boolean context.
5509 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5510 nor always false."
5511 (let ((tt (js2-node-type node))
5512 num)
5513 (cond
5514 ((or (= tt js2-FALSE) (= tt js2-NULL))
5515 'ALWAYS_FALSE)
5516 ((= tt js2-TRUE)
5517 'ALWAYS_TRUE)
5518 ((= tt js2-NUMBER)
5519 (setq num (js2-number-node-num-value node))
5520 (if (and (not (eq num 0.0e+NaN))
5521 (not (zerop num)))
5522 'ALWAYS_TRUE
5523 'ALWAYS_FALSE))
5524 (t
5525 nil))))
5526
5527 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5528 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5529
5530 (defvar js2-tokens nil
5531 "List of all defined token names.") ; initialized in `js2-token-names'
5532
5533 (defconst js2-token-names
5534 (let* ((names (make-vector js2-num-tokens -1))
5535 (case-fold-search nil) ; only match js2-UPPER_CASE
5536 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5537 (cl-loop for sym in syms
5538 for i from 0
5539 do
5540 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5541 (not (boundp sym)))
5542 (aset names (symbol-value sym) ; code, e.g. 152
5543 (downcase
5544 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5545 (push sym js2-tokens)))
5546 names)
5547 "Vector mapping int values to token string names, sans `js2-' prefix.")
5548
5549 (defun js2-tt-name (tok)
5550 "Return a string name for TOK, a token symbol or code.
5551 Signals an error if it's not a recognized token."
5552 (let ((code tok))
5553 (if (symbolp tok)
5554 (setq code (symbol-value tok)))
5555 (if (eq code -1)
5556 "ERROR"
5557 (if (and (numberp code)
5558 (not (cl-minusp code))
5559 (< code js2-num-tokens))
5560 (aref js2-token-names code)
5561 (error "Invalid token: %s" code)))))
5562
5563 (defsubst js2-tt-sym (tok)
5564 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5565 (intern (js2-tt-name tok)))
5566
5567 (defconst js2-token-codes
5568 (let ((table (make-hash-table :test 'eq :size 256)))
5569 (cl-loop for name across js2-token-names
5570 for sym = (intern (concat "js2-" (upcase name)))
5571 do
5572 (puthash sym (symbol-value sym) table))
5573 ;; clean up a few that are "wrong" in Rhino's token codes
5574 (puthash 'js2-DELETE js2-DELPROP table)
5575 table)
5576 "Hashtable mapping token type symbols to their bytecodes.")
5577
5578 (defsubst js2-tt-code (sym)
5579 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5580 (or (gethash sym js2-token-codes)
5581 (error "Invalid token symbol: %s " sym))) ; signal code bug
5582
5583 (defun js2-report-scan-error (msg &optional no-throw beg len)
5584 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5585 (js2-report-error msg nil
5586 (or beg (js2-current-token-beg))
5587 (or len (js2-current-token-len)))
5588 (unless no-throw
5589 (throw 'return js2-ERROR)))
5590
5591 (defun js2-set-string-from-buffer (token)
5592 "Set `string' and `end' slots for TOKEN, return the string."
5593 (setf (js2-token-end token) js2-ts-cursor
5594 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5595
5596 ;; TODO: could potentially avoid a lot of consing by allocating a
5597 ;; char buffer the way Rhino does.
5598 (defsubst js2-add-to-string (c)
5599 (push c js2-ts-string-buffer))
5600
5601 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5602 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5603 ;; any other character: when it's not part of the current token, we
5604 ;; unget it, allowing it to be read again by the following call.
5605 (defsubst js2-unget-char ()
5606 (cl-decf js2-ts-cursor))
5607
5608 ;; Rhino distinguishes \r and \n line endings. We don't need to
5609 ;; because we only scan from Emacs buffers, which always use \n.
5610 (defun js2-get-char ()
5611 "Read and return the next character from the input buffer.
5612 Increments `js2-ts-lineno' if the return value is a newline char.
5613 Updates `js2-ts-cursor' to the point after the returned char.
5614 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5615 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5616 (let (c)
5617 ;; check for end of buffer
5618 (if (>= js2-ts-cursor (point-max))
5619 (setq js2-ts-hit-eof t
5620 js2-ts-cursor (1+ js2-ts-cursor)
5621 c js2-EOF_CHAR) ; return value
5622 ;; otherwise read next char
5623 (setq c (char-before (cl-incf js2-ts-cursor)))
5624 ;; if we read a newline, update counters
5625 (if (= c ?\n)
5626 (setq js2-ts-line-start js2-ts-cursor
5627 js2-ts-lineno (1+ js2-ts-lineno)))
5628 ;; TODO: skip over format characters
5629 c)))
5630
5631 (defun js2-read-unicode-escape ()
5632 "Read a \\uNNNN sequence from the input.
5633 Assumes the ?\ and ?u have already been read.
5634 Returns the unicode character, or nil if it wasn't a valid character.
5635 Doesn't change the values of any scanner variables."
5636 ;; I really wish I knew a better way to do this, but I can't
5637 ;; find the Emacs function that takes a 16-bit int and converts
5638 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5639 ;; Have to first check that it's 4 hex characters or it may stop
5640 ;; the read early.
5641 (ignore-errors
5642 (let ((s (buffer-substring-no-properties js2-ts-cursor
5643 (+ 4 js2-ts-cursor))))
5644 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5645 (read (concat "?\\u" s))))))
5646
5647 (defun js2-match-char (test)
5648 "Consume and return next character if it matches TEST, a character.
5649 Returns nil and consumes nothing if TEST is not the next character."
5650 (let ((c (js2-get-char)))
5651 (if (eq c test)
5652 t
5653 (js2-unget-char)
5654 nil)))
5655
5656 (defun js2-peek-char ()
5657 (prog1
5658 (js2-get-char)
5659 (js2-unget-char)))
5660
5661 (defun js2-identifier-start-p (c)
5662 "Is C a valid start to an ES5 Identifier?
5663 See http://es5.github.io/#x7.6"
5664 (or
5665 (memq c '(?$ ?_))
5666 (memq (get-char-code-property c 'general-category)
5667 ;; Letters
5668 '(Lu Ll Lt Lm Lo Nl))))
5669
5670 (defun js2-identifier-part-p (c)
5671 "Is C a valid part of an ES5 Identifier?
5672 See http://es5.github.io/#x7.6"
5673 (or
5674 (memq c '(?$ ?_ ?\u200c ?\u200d))
5675 (memq (get-char-code-property c 'general-category)
5676 '(;; Letters
5677 Lu Ll Lt Lm Lo Nl
5678 ;; Combining Marks
5679 Mn Mc
5680 ;; Digits
5681 Nd
5682 ;; Connector Punctuation
5683 Pc))))
5684
5685 (defun js2-alpha-p (c)
5686 (cond ((and (<= ?A c) (<= c ?Z)) t)
5687 ((and (<= ?a c) (<= c ?z)) t)
5688 (t nil)))
5689
5690 (defsubst js2-digit-p (c)
5691 (and (<= ?0 c) (<= c ?9)))
5692
5693 (defun js2-js-space-p (c)
5694 (if (<= c 127)
5695 (memq c '(#x20 #x9 #xB #xC #xD))
5696 (or
5697 (eq c #xA0)
5698 ;; TODO: change this nil to check for Unicode space character
5699 nil)))
5700
5701 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5702
5703 (defun js2-skip-line ()
5704 "Skip to end of line."
5705 (while (not (memq (js2-get-char) js2-eol-chars)))
5706 (js2-unget-char)
5707 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5708
5709 (defun js2-init-scanner (&optional buf line)
5710 "Create token stream for BUF starting on LINE.
5711 BUF defaults to `current-buffer' and LINE defaults to 1.
5712
5713 A buffer can only have one scanner active at a time, which yields
5714 dramatically simpler code than using a defstruct. If you need to
5715 have simultaneous scanners in a buffer, copy the regions to scan
5716 into temp buffers."
5717 (with-current-buffer (or buf (current-buffer))
5718 (setq js2-ts-dirty-line nil
5719 js2-ts-hit-eof nil
5720 js2-ts-line-start 0
5721 js2-ts-lineno (or line 1)
5722 js2-ts-line-end-char -1
5723 js2-ts-cursor (point-min)
5724 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5725 js2-ti-tokens-cursor 0
5726 js2-ti-lookahead 0
5727 js2-ts-is-xml-attribute nil
5728 js2-ts-xml-is-tag-content nil
5729 js2-ts-xml-open-tags-count 0
5730 js2-ts-string-buffer nil)))
5731
5732 ;; This function uses the cached op, string and number fields in
5733 ;; TokenStream; if getToken has been called since the passed token
5734 ;; was scanned, the op or string printed may be incorrect.
5735 (defun js2-token-to-string (token)
5736 ;; Not sure where this function is used in Rhino. Not tested.
5737 (if (not js2-debug-print-trees)
5738 ""
5739 (let ((name (js2-tt-name token)))
5740 (cond
5741 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5742 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5743 (concat name " `" (js2-current-token-string) "'"))
5744 ((eq token js2-NUMBER)
5745 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5746 (t
5747 name)))))
5748
5749 (defconst js2-keywords
5750 '(break
5751 case catch class const continue
5752 debugger default delete do
5753 else extends export
5754 false finally for function
5755 if in instanceof import
5756 let
5757 new null
5758 return
5759 super switch
5760 this throw true try typeof
5761 var void
5762 while with
5763 yield))
5764
5765 ;; Token names aren't exactly the same as the keywords, unfortunately.
5766 ;; E.g. delete is js2-DELPROP.
5767 (defconst js2-kwd-tokens
5768 (let ((table (make-vector js2-num-tokens nil))
5769 (tokens
5770 (list js2-BREAK
5771 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5772 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5773 js2-ELSE js2-EXPORT
5774 js2-ELSE js2-EXTENDS js2-EXPORT
5775 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5776 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5777 js2-LET
5778 js2-NEW js2-NULL
5779 js2-RETURN
5780 js2-SUPER js2-SWITCH
5781 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5782 js2-VAR
5783 js2-WHILE js2-WITH
5784 js2-YIELD)))
5785 (dolist (i tokens)
5786 (aset table i 'font-lock-keyword-face))
5787 (aset table js2-STRING 'font-lock-string-face)
5788 (aset table js2-REGEXP 'font-lock-string-face)
5789 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5790 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5791 (aset table js2-COMMENT 'font-lock-comment-face)
5792 (aset table js2-THIS 'font-lock-builtin-face)
5793 (aset table js2-SUPER 'font-lock-builtin-face)
5794 (aset table js2-VOID 'font-lock-constant-face)
5795 (aset table js2-NULL 'font-lock-constant-face)
5796 (aset table js2-TRUE 'font-lock-constant-face)
5797 (aset table js2-FALSE 'font-lock-constant-face)
5798 (aset table js2-NOT 'font-lock-negation-char-face)
5799 table)
5800 "Vector whose values are non-nil for tokens that are keywords.
5801 The values are default faces to use for highlighting the keywords.")
5802
5803 ;; FIXME: Support strict mode-only future reserved words, after we know
5804 ;; which parts scopes are in strict mode, and which are not.
5805 (defconst js2-reserved-words '(class enum export extends import static super)
5806 "Future reserved keywords in ECMAScript 5.1.")
5807
5808 (defconst js2-keyword-names
5809 (let ((table (make-hash-table :test 'equal)))
5810 (cl-loop for k in js2-keywords
5811 do (puthash
5812 (symbol-name k) ; instanceof
5813 (intern (concat "js2-"
5814 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5815 table))
5816 table)
5817 "JavaScript keywords by name, mapped to their symbols.")
5818
5819 (defconst js2-reserved-word-names
5820 (let ((table (make-hash-table :test 'equal)))
5821 (cl-loop for k in js2-reserved-words
5822 do
5823 (puthash (symbol-name k) 'js2-RESERVED table))
5824 table)
5825 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5826
5827 (defun js2-collect-string (buf)
5828 "Convert BUF, a list of chars, to a string.
5829 Reverses BUF before converting."
5830 (if buf
5831 (apply #'string (nreverse buf))
5832 ""))
5833
5834 (defun js2-string-to-keyword (s)
5835 "Return token for S, a string, if S is a keyword or reserved word.
5836 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5837 (or (gethash s js2-keyword-names)
5838 (gethash s js2-reserved-word-names)))
5839
5840 (defsubst js2-ts-set-char-token-bounds (token)
5841 "Used when next token is one character."
5842 (setf (js2-token-beg token) (1- js2-ts-cursor)
5843 (js2-token-end token) js2-ts-cursor))
5844
5845 (defsubst js2-ts-return (token type)
5846 "Update the `end' and `type' slots of TOKEN,
5847 then throw `return' with value TYPE."
5848 (setf (js2-token-end token) js2-ts-cursor
5849 (js2-token-type token) type)
5850 (throw 'return type))
5851
5852 (defun js2-x-digit-to-int (c accumulator)
5853 "Build up a hex number.
5854 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5855 corresponding number. Otherwise return -1."
5856 (catch 'return
5857 (catch 'check
5858 ;; Use 0..9 < A..Z < a..z
5859 (cond
5860 ((<= c ?9)
5861 (cl-decf c ?0)
5862 (if (<= 0 c)
5863 (throw 'check nil)))
5864 ((<= c ?F)
5865 (when (<= ?A c)
5866 (cl-decf c (- ?A 10))
5867 (throw 'check nil)))
5868 ((<= c ?f)
5869 (when (<= ?a c)
5870 (cl-decf c (- ?a 10))
5871 (throw 'check nil))))
5872 (throw 'return -1))
5873 (logior c (lsh accumulator 4))))
5874
5875 (defun js2-get-token (&optional modifier)
5876 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5877 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5878 next saved token.
5879
5880 This function will not return a newline (js2-EOL) - instead, it
5881 gobbles newlines until it finds a non-newline token. Call
5882 `js2-peek-token-or-eol' when you care about newlines.
5883
5884 This function will also not return a js2-COMMENT. Instead, it
5885 records comments found in `js2-scanned-comments'. If the token
5886 returned by this function immediately follows a jsdoc comment,
5887 the token is flagged as such."
5888 (if (zerop js2-ti-lookahead)
5889 (js2-get-token-internal modifier)
5890 (cl-decf js2-ti-lookahead)
5891 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5892 (let ((tt (js2-current-token-type)))
5893 (cl-assert (not (= tt js2-EOL)))
5894 tt)))
5895
5896 (defun js2-unget-token ()
5897 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5898 (cl-incf js2-ti-lookahead)
5899 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5900
5901 (defun js2-get-token-internal (modifier)
5902 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5903 (tt (js2-token-type token))
5904 saw-eol
5905 face)
5906 ;; process comments
5907 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5908 (if (= tt js2-EOL)
5909 (setq saw-eol t)
5910 (setq saw-eol nil)
5911 (when js2-record-comments
5912 (js2-record-comment token)))
5913 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5914 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5915 tt (js2-token-type token)))
5916
5917 (when saw-eol
5918 (setf (js2-token-follows-eol-p token) t))
5919
5920 ;; perform lexical fontification as soon as token is scanned
5921 (when js2-parse-ide-mode
5922 (cond
5923 ((cl-minusp tt)
5924 (js2-record-face 'js2-error token))
5925 ((setq face (aref js2-kwd-tokens tt))
5926 (js2-record-face face token))
5927 ((and (= tt js2-NAME)
5928 (equal (js2-token-string token) "undefined"))
5929 (js2-record-face 'font-lock-constant-face token))))
5930 tt))
5931
5932 (defsubst js2-string-to-number (str base)
5933 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5934 (condition-case nil
5935 (string-to-number str base)
5936 (overflow-error -1)))
5937
5938 (defun js2-get-token-internal-1 (modifier)
5939 "Return next JavaScript token type, an int such as js2-RETURN.
5940 During operation, creates an instance of `js2-token' struct, sets
5941 its relevant fields and puts it into `js2-ti-tokens'."
5942 (let (identifier-start
5943 is-unicode-escape-start c
5944 contains-escape escape-val str result base
5945 look-for-slash continue tt
5946 (token (js2-new-token 0)))
5947 (setq
5948 tt
5949 (catch 'return
5950 (when (eq modifier 'TEMPLATE_TAIL)
5951 (setf (js2-token-beg token) (1- js2-ts-cursor))
5952 (throw 'return (js2-get-string-or-template-token ?` token)))
5953 (while t
5954 ;; Eat whitespace, possibly sensitive to newlines.
5955 (setq continue t)
5956 (while continue
5957 (setq c (js2-get-char))
5958 (cond
5959 ((eq c js2-EOF_CHAR)
5960 (js2-unget-char)
5961 (js2-ts-set-char-token-bounds token)
5962 (throw 'return js2-EOF))
5963 ((eq c ?\n)
5964 (js2-ts-set-char-token-bounds token)
5965 (setq js2-ts-dirty-line nil)
5966 (throw 'return js2-EOL))
5967 ((not (js2-js-space-p c))
5968 (if (/= c ?-) ; in case end of HTML comment
5969 (setq js2-ts-dirty-line t))
5970 (setq continue nil))))
5971 ;; Assume the token will be 1 char - fixed up below.
5972 (js2-ts-set-char-token-bounds token)
5973 (when (eq c ?@)
5974 (throw 'return js2-XMLATTR))
5975 ;; identifier/keyword/instanceof?
5976 ;; watch out for starting with a <backslash>
5977 (cond
5978 ((eq c ?\\)
5979 (setq c (js2-get-char))
5980 (if (eq c ?u)
5981 (setq identifier-start t
5982 is-unicode-escape-start t
5983 js2-ts-string-buffer nil)
5984 (setq identifier-start nil)
5985 (js2-unget-char)
5986 (setq c ?\\)))
5987 (t
5988 (when (setq identifier-start (js2-identifier-start-p c))
5989 (setq js2-ts-string-buffer nil)
5990 (js2-add-to-string c))))
5991 (when identifier-start
5992 (setq contains-escape is-unicode-escape-start)
5993 (catch 'break
5994 (while t
5995 (if is-unicode-escape-start
5996 ;; strictly speaking we should probably push-back
5997 ;; all the bad characters if the <backslash>uXXXX
5998 ;; sequence is malformed. But since there isn't a
5999 ;; correct context(is there?) for a bad Unicode
6000 ;; escape sequence in an identifier, we can report
6001 ;; an error here.
6002 (progn
6003 (setq escape-val 0)
6004 (dotimes (_ 4)
6005 (setq c (js2-get-char)
6006 escape-val (js2-x-digit-to-int c escape-val))
6007 ;; Next check takes care of c < 0 and bad escape
6008 (if (cl-minusp escape-val)
6009 (throw 'break nil)))
6010 (if (cl-minusp escape-val)
6011 (js2-report-scan-error "msg.invalid.escape" t))
6012 (js2-add-to-string escape-val)
6013 (setq is-unicode-escape-start nil))
6014 (setq c (js2-get-char))
6015 (cond
6016 ((eq c ?\\)
6017 (setq c (js2-get-char))
6018 (if (eq c ?u)
6019 (setq is-unicode-escape-start t
6020 contains-escape t)
6021 (js2-report-scan-error "msg.illegal.character" t)))
6022 (t
6023 (if (or (eq c js2-EOF_CHAR)
6024 (not (js2-identifier-part-p c)))
6025 (throw 'break nil))
6026 (js2-add-to-string c))))))
6027 (js2-unget-char)
6028 (setf str (js2-collect-string js2-ts-string-buffer)
6029 (js2-token-end token) js2-ts-cursor)
6030 ;; FIXME: Invalid in ES5 and ES6, see
6031 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
6032 ;; Probably should just drop this conditional.
6033 (unless contains-escape
6034 ;; OPT we shouldn't have to make a string (object!) to
6035 ;; check if it's a keyword.
6036 ;; Return the corresponding token if it's a keyword
6037 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
6038 (setq result (js2-string-to-keyword str)))
6039 (if (and (< js2-language-version 170)
6040 (memq result '(js2-LET js2-YIELD)))
6041 ;; LET and YIELD are tokens only in 1.7 and later
6042 (setq result 'js2-NAME))
6043 (when (eq result 'js2-RESERVED)
6044 (setf (js2-token-string token) str))
6045 (throw 'return (js2-tt-code result))))
6046 ;; If we want to intern these as Rhino does, just use (intern str)
6047 (setf (js2-token-string token) str)
6048 (throw 'return js2-NAME)) ; end identifier/kwd check
6049 ;; is it a number?
6050 (when (or (js2-digit-p c)
6051 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6052 (setq js2-ts-string-buffer nil
6053 base 10)
6054 (when (eq c ?0)
6055 (setq c (js2-get-char))
6056 (cond
6057 ((or (eq c ?x) (eq c ?X))
6058 (setq base 16)
6059 (setq c (js2-get-char)))
6060 ((and (or (eq c ?b) (eq c ?B))
6061 (>= js2-language-version 200))
6062 (setq base 2)
6063 (setq c (js2-get-char)))
6064 ((and (or (eq c ?o) (eq c ?O))
6065 (>= js2-language-version 200))
6066 (setq base 8)
6067 (setq c (js2-get-char)))
6068 ((js2-digit-p c)
6069 (setq base 'maybe-8))
6070 (t
6071 (js2-add-to-string ?0))))
6072 (cond
6073 ((eq base 16)
6074 (if (> 0 (js2-x-digit-to-int c 0))
6075 (js2-report-scan-error "msg.missing.hex.digits")
6076 (while (<= 0 (js2-x-digit-to-int c 0))
6077 (js2-add-to-string c)
6078 (setq c (js2-get-char)))))
6079 ((eq base 2)
6080 (if (not (memq c '(?0 ?1)))
6081 (js2-report-scan-error "msg.missing.binary.digits")
6082 (while (memq c '(?0 ?1))
6083 (js2-add-to-string c)
6084 (setq c (js2-get-char)))))
6085 ((eq base 8)
6086 (if (or (> ?0 c) (< ?7 c))
6087 (js2-report-scan-error "msg.missing.octal.digits")
6088 (while (and (<= ?0 c) (>= ?7 c))
6089 (js2-add-to-string c)
6090 (setq c (js2-get-char)))))
6091 (t
6092 (while (and (<= ?0 c) (<= c ?9))
6093 ;; We permit 08 and 09 as decimal numbers, which
6094 ;; makes our behavior a superset of the ECMA
6095 ;; numeric grammar. We might not always be so
6096 ;; permissive, so we warn about it.
6097 (when (and (eq base 'maybe-8) (>= c ?8))
6098 (js2-report-warning "msg.bad.octal.literal"
6099 (if (eq c ?8) "8" "9"))
6100 (setq base 10))
6101 (js2-add-to-string c)
6102 (setq c (js2-get-char)))
6103 (when (eq base 'maybe-8)
6104 (setq base 8))))
6105 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6106 (when (eq c ?.)
6107 (cl-loop do
6108 (js2-add-to-string c)
6109 (setq c (js2-get-char))
6110 while (js2-digit-p c)))
6111 (when (memq c '(?e ?E))
6112 (js2-add-to-string c)
6113 (setq c (js2-get-char))
6114 (when (memq c '(?+ ?-))
6115 (js2-add-to-string c)
6116 (setq c (js2-get-char)))
6117 (unless (js2-digit-p c)
6118 (js2-report-scan-error "msg.missing.exponent" t))
6119 (cl-loop do
6120 (js2-add-to-string c)
6121 (setq c (js2-get-char))
6122 while (js2-digit-p c))))
6123 (js2-unget-char)
6124 (let ((str (js2-set-string-from-buffer token)))
6125 (setf (js2-token-number token) (js2-string-to-number str base)
6126 (js2-token-number-base token) base))
6127 (throw 'return js2-NUMBER))
6128 ;; is it a string?
6129 (when (or (memq c '(?\" ?\'))
6130 (and (>= js2-language-version 200)
6131 (= c ?`)))
6132 (throw 'return
6133 (js2-get-string-or-template-token c token)))
6134 (js2-ts-return token
6135 (cl-case c
6136 (?\;
6137 (throw 'return js2-SEMI))
6138 (?\[
6139 (throw 'return js2-LB))
6140 (?\]
6141 (throw 'return js2-RB))
6142 (?{
6143 (throw 'return js2-LC))
6144 (?}
6145 (throw 'return js2-RC))
6146 (?\(
6147 (throw 'return js2-LP))
6148 (?\)
6149 (throw 'return js2-RP))
6150 (?,
6151 (throw 'return js2-COMMA))
6152 (??
6153 (throw 'return js2-HOOK))
6154 (?:
6155 (if (js2-match-char ?:)
6156 js2-COLONCOLON
6157 (throw 'return js2-COLON)))
6158 (?.
6159 (if (js2-match-char ?.)
6160 (if (js2-match-char ?.)
6161 js2-TRIPLEDOT js2-DOTDOT)
6162 (if (js2-match-char ?\()
6163 js2-DOTQUERY
6164 (throw 'return js2-DOT))))
6165 (?|
6166 (if (js2-match-char ?|)
6167 (throw 'return js2-OR)
6168 (if (js2-match-char ?=)
6169 js2-ASSIGN_BITOR
6170 (throw 'return js2-BITOR))))
6171 (?^
6172 (if (js2-match-char ?=)
6173 js2-ASSIGN_BITOR
6174 (throw 'return js2-BITXOR)))
6175 (?&
6176 (if (js2-match-char ?&)
6177 (throw 'return js2-AND)
6178 (if (js2-match-char ?=)
6179 js2-ASSIGN_BITAND
6180 (throw 'return js2-BITAND))))
6181 (?=
6182 (if (js2-match-char ?=)
6183 (if (js2-match-char ?=)
6184 js2-SHEQ
6185 (throw 'return js2-EQ))
6186 (if (js2-match-char ?>)
6187 (js2-ts-return token js2-ARROW)
6188 (throw 'return js2-ASSIGN))))
6189 (?!
6190 (if (js2-match-char ?=)
6191 (if (js2-match-char ?=)
6192 js2-SHNE
6193 js2-NE)
6194 (throw 'return js2-NOT)))
6195 (?<
6196 ;; NB:treat HTML begin-comment as comment-till-eol
6197 (when (js2-match-char ?!)
6198 (when (js2-match-char ?-)
6199 (when (js2-match-char ?-)
6200 (js2-skip-line)
6201 (setf (js2-token-comment-type (js2-current-token)) 'html)
6202 (throw 'return js2-COMMENT)))
6203 (js2-unget-char))
6204 (if (js2-match-char ?<)
6205 (if (js2-match-char ?=)
6206 js2-ASSIGN_LSH
6207 js2-LSH)
6208 (if (js2-match-char ?=)
6209 js2-LE
6210 (throw 'return js2-LT))))
6211 (?>
6212 (if (js2-match-char ?>)
6213 (if (js2-match-char ?>)
6214 (if (js2-match-char ?=)
6215 js2-ASSIGN_URSH
6216 js2-URSH)
6217 (if (js2-match-char ?=)
6218 js2-ASSIGN_RSH
6219 js2-RSH))
6220 (if (js2-match-char ?=)
6221 js2-GE
6222 (throw 'return js2-GT))))
6223 (?*
6224 (if (js2-match-char ?=)
6225 js2-ASSIGN_MUL
6226 (throw 'return js2-MUL)))
6227 (?/
6228 ;; is it a // comment?
6229 (when (js2-match-char ?/)
6230 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6231 (js2-skip-line)
6232 (setf (js2-token-comment-type token) 'line)
6233 ;; include newline so highlighting goes to end of
6234 ;; window, if there actually is a newline; if we
6235 ;; hit eof, then implicitly there isn't
6236 (unless js2-ts-hit-eof
6237 (cl-incf (js2-token-end token)))
6238 (throw 'return js2-COMMENT))
6239 ;; is it a /* comment?
6240 (when (js2-match-char ?*)
6241 (setf look-for-slash nil
6242 (js2-token-beg token) (- js2-ts-cursor 2)
6243 (js2-token-comment-type token)
6244 (if (js2-match-char ?*)
6245 (progn
6246 (setq look-for-slash t)
6247 'jsdoc)
6248 'block))
6249 (while t
6250 (setq c (js2-get-char))
6251 (cond
6252 ((eq c js2-EOF_CHAR)
6253 (setf (js2-token-end token) (1- js2-ts-cursor))
6254 (js2-report-error "msg.unterminated.comment")
6255 (throw 'return js2-COMMENT))
6256 ((eq c ?*)
6257 (setq look-for-slash t))
6258 ((eq c ?/)
6259 (if look-for-slash
6260 (js2-ts-return token js2-COMMENT)))
6261 (t
6262 (setf look-for-slash nil
6263 (js2-token-end token) js2-ts-cursor)))))
6264 (if (js2-match-char ?=)
6265 js2-ASSIGN_DIV
6266 (throw 'return js2-DIV)))
6267 (?#
6268 (when js2-skip-preprocessor-directives
6269 (js2-skip-line)
6270 (setf (js2-token-comment-type token) 'preprocessor
6271 (js2-token-end token) js2-ts-cursor)
6272 (throw 'return js2-COMMENT))
6273 (throw 'return js2-ERROR))
6274 (?%
6275 (if (js2-match-char ?=)
6276 js2-ASSIGN_MOD
6277 (throw 'return js2-MOD)))
6278 (?~
6279 (throw 'return js2-BITNOT))
6280 (?+
6281 (if (js2-match-char ?=)
6282 js2-ASSIGN_ADD
6283 (if (js2-match-char ?+)
6284 js2-INC
6285 (throw 'return js2-ADD))))
6286 (?-
6287 (cond
6288 ((js2-match-char ?=)
6289 (setq c js2-ASSIGN_SUB))
6290 ((js2-match-char ?-)
6291 (unless js2-ts-dirty-line
6292 ;; treat HTML end-comment after possible whitespace
6293 ;; after line start as comment-until-eol
6294 (when (js2-match-char ?>)
6295 (js2-skip-line)
6296 (setf (js2-token-comment-type (js2-current-token)) 'html)
6297 (throw 'return js2-COMMENT)))
6298 (setq c js2-DEC))
6299 (t
6300 (setq c js2-SUB)))
6301 (setq js2-ts-dirty-line t)
6302 c)
6303 (otherwise
6304 (js2-report-scan-error "msg.illegal.character")))))))
6305 (setf (js2-token-type token) tt)
6306 token))
6307
6308 (defun js2-get-string-or-template-token (quote-char token)
6309 ;; We attempt to accumulate a string the fast way, by
6310 ;; building it directly out of the reader. But if there
6311 ;; are any escaped characters in the string, we revert to
6312 ;; building it out of a string buffer.
6313 (let ((c (js2-get-char))
6314 js2-ts-string-buffer
6315 nc c1 val escape-val)
6316 (catch 'break
6317 (while (/= c quote-char)
6318 (catch 'continue
6319 (when (eq c js2-EOF_CHAR)
6320 (js2-unget-char)
6321 (js2-report-error "msg.unterminated.string.lit")
6322 (throw 'break nil))
6323 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6324 (js2-unget-char)
6325 (js2-report-error "msg.unterminated.string.lit")
6326 (throw 'break nil))
6327 (when (eq c ?\\)
6328 ;; We've hit an escaped character
6329 (setq c (js2-get-char))
6330 (cl-case c
6331 (?b (setq c ?\b))
6332 (?f (setq c ?\f))
6333 (?n (setq c ?\n))
6334 (?r (setq c ?\r))
6335 (?t (setq c ?\t))
6336 (?v (setq c ?\v))
6337 (?u
6338 (setq c1 (js2-read-unicode-escape))
6339 (if js2-parse-ide-mode
6340 (if c1
6341 (progn
6342 ;; just copy the string in IDE-mode
6343 (js2-add-to-string ?\\)
6344 (js2-add-to-string ?u)
6345 (dotimes (_ 3)
6346 (js2-add-to-string (js2-get-char)))
6347 (setq c (js2-get-char))) ; added at end of loop
6348 ;; flag it as an invalid escape
6349 (js2-report-warning "msg.invalid.escape"
6350 nil (- js2-ts-cursor 2) 6))
6351 ;; Get 4 hex digits; if the u escape is not
6352 ;; followed by 4 hex digits, use 'u' + the
6353 ;; literal character sequence that follows.
6354 (js2-add-to-string ?u)
6355 (setq escape-val 0)
6356 (dotimes (_ 4)
6357 (setq c (js2-get-char)
6358 escape-val (js2-x-digit-to-int c escape-val))
6359 (if (cl-minusp escape-val)
6360 (throw 'continue nil))
6361 (js2-add-to-string c))
6362 ;; prepare for replace of stored 'u' sequence by escape value
6363 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6364 c escape-val)))
6365 (?x
6366 ;; Get 2 hex digits, defaulting to 'x'+literal
6367 ;; sequence, as above.
6368 (setq c (js2-get-char)
6369 escape-val (js2-x-digit-to-int c 0))
6370 (if (cl-minusp escape-val)
6371 (progn
6372 (js2-add-to-string ?x)
6373 (throw 'continue nil))
6374 (setq c1 c
6375 c (js2-get-char)
6376 escape-val (js2-x-digit-to-int c escape-val))
6377 (if (cl-minusp escape-val)
6378 (progn
6379 (js2-add-to-string ?x)
6380 (js2-add-to-string c1)
6381 (throw 'continue nil))
6382 ;; got 2 hex digits
6383 (setq c escape-val))))
6384 (?\n
6385 ;; Remove line terminator after escape to follow
6386 ;; SpiderMonkey and C/C++
6387 (setq c (js2-get-char))
6388 (throw 'continue nil))
6389 (t
6390 (when (and (<= ?0 c) (< c ?8))
6391 (setq val (- c ?0)
6392 c (js2-get-char))
6393 (when (and (<= ?0 c) (< c ?8))
6394 (setq val (- (+ (* 8 val) c) ?0)
6395 c (js2-get-char))
6396 (when (and (<= ?0 c)
6397 (< c ?8)
6398 (< val #o37))
6399 ;; c is 3rd char of octal sequence only
6400 ;; if the resulting val <= 0377
6401 (setq val (- (+ (* 8 val) c) ?0)
6402 c (js2-get-char))))
6403 (js2-unget-char)
6404 (setq c val)))))
6405 (when (and (eq quote-char ?`) (eq c ?$))
6406 (when (eq (setq nc (js2-get-char)) ?\{)
6407 (throw 'break nil))
6408 (js2-unget-char))
6409 (js2-add-to-string c)
6410 (setq c (js2-get-char)))))
6411 (js2-set-string-from-buffer token)
6412 (if (not (eq quote-char ?`))
6413 js2-STRING
6414 (if (and (eq c ?$) (eq nc ?\{))
6415 js2-TEMPLATE_HEAD
6416 js2-NO_SUBS_TEMPLATE))))
6417
6418 (defun js2-read-regexp (start-tt)
6419 "Called by parser when it gets / or /= in literal context."
6420 (let (c err
6421 in-class ; inside a '[' .. ']' character-class
6422 flags
6423 (continue t)
6424 (token (js2-new-token 0)))
6425 (setq js2-ts-string-buffer nil)
6426 (if (eq start-tt js2-ASSIGN_DIV)
6427 ;; mis-scanned /=
6428 (js2-add-to-string ?=)
6429 (if (not (eq start-tt js2-DIV))
6430 (error "failed assertion")))
6431 (while (and (not err)
6432 (or (/= (setq c (js2-get-char)) ?/)
6433 in-class))
6434 (cond
6435 ((or (= c ?\n)
6436 (= c js2-EOF_CHAR))
6437 (setf (js2-token-end token) (1- js2-ts-cursor)
6438 err t
6439 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6440 (js2-report-error "msg.unterminated.re.lit"))
6441 (t (cond
6442 ((= c ?\\)
6443 (js2-add-to-string c)
6444 (setq c (js2-get-char)))
6445 ((= c ?\[)
6446 (setq in-class t))
6447 ((= c ?\])
6448 (setq in-class nil)))
6449 (js2-add-to-string c))))
6450 (unless err
6451 (while continue
6452 (cond
6453 ((js2-match-char ?g)
6454 (push ?g flags))
6455 ((js2-match-char ?i)
6456 (push ?i flags))
6457 ((js2-match-char ?m)
6458 (push ?m flags))
6459 ((and (js2-match-char ?u)
6460 (>= js2-language-version 200))
6461 (push ?u flags))
6462 ((and (js2-match-char ?y)
6463 (>= js2-language-version 200))
6464 (push ?y flags))
6465 (t
6466 (setq continue nil))))
6467 (if (js2-alpha-p (js2-peek-char))
6468 (js2-report-scan-error "msg.invalid.re.flag" t
6469 js2-ts-cursor 1))
6470 (js2-set-string-from-buffer token))
6471 (js2-collect-string flags)))
6472
6473 (defun js2-get-first-xml-token ()
6474 (setq js2-ts-xml-open-tags-count 0
6475 js2-ts-is-xml-attribute nil
6476 js2-ts-xml-is-tag-content nil)
6477 (js2-unget-char)
6478 (js2-get-next-xml-token))
6479
6480 (defun js2-xml-discard-string (token)
6481 "Throw away the string in progress and flag an XML parse error."
6482 (setf js2-ts-string-buffer nil
6483 (js2-token-string token) nil)
6484 (js2-report-scan-error "msg.XML.bad.form" t))
6485
6486 (defun js2-get-next-xml-token ()
6487 (setq js2-ts-string-buffer nil) ; for recording the XML
6488 (let ((token (js2-new-token 0))
6489 c result)
6490 (setq result
6491 (catch 'return
6492 (while t
6493 (setq c (js2-get-char))
6494 (cond
6495 ((= c js2-EOF_CHAR)
6496 (throw 'return js2-ERROR))
6497 (js2-ts-xml-is-tag-content
6498 (cl-case c
6499 (?>
6500 (js2-add-to-string c)
6501 (setq js2-ts-xml-is-tag-content nil
6502 js2-ts-is-xml-attribute nil))
6503 (?/
6504 (js2-add-to-string c)
6505 (when (eq ?> (js2-peek-char))
6506 (setq c (js2-get-char))
6507 (js2-add-to-string c)
6508 (setq js2-ts-xml-is-tag-content nil)
6509 (cl-decf js2-ts-xml-open-tags-count)))
6510 (?{
6511 (js2-unget-char)
6512 (js2-set-string-from-buffer token)
6513 (throw 'return js2-XML))
6514 ((?\' ?\")
6515 (js2-add-to-string c)
6516 (unless (js2-read-quoted-string c token)
6517 (throw 'return js2-ERROR)))
6518 (?=
6519 (js2-add-to-string c)
6520 (setq js2-ts-is-xml-attribute t))
6521 ((? ?\t ?\r ?\n)
6522 (js2-add-to-string c))
6523 (t
6524 (js2-add-to-string c)
6525 (setq js2-ts-is-xml-attribute nil)))
6526 (when (and (not js2-ts-xml-is-tag-content)
6527 (zerop js2-ts-xml-open-tags-count))
6528 (js2-set-string-from-buffer token)
6529 (throw 'return js2-XMLEND)))
6530 (t
6531 ;; else not tag content
6532 (cl-case c
6533 (?<
6534 (js2-add-to-string c)
6535 (setq c (js2-peek-char))
6536 (cl-case c
6537 (?!
6538 (setq c (js2-get-char)) ;; skip !
6539 (js2-add-to-string c)
6540 (setq c (js2-peek-char))
6541 (cl-case c
6542 (?-
6543 (setq c (js2-get-char)) ;; skip -
6544 (js2-add-to-string c)
6545 (if (eq c ?-)
6546 (progn
6547 (js2-add-to-string c)
6548 (unless (js2-read-xml-comment token)
6549 (throw 'return js2-ERROR)))
6550 (js2-xml-discard-string token)
6551 (throw 'return js2-ERROR)))
6552 (?\[
6553 (setq c (js2-get-char)) ;; skip [
6554 (js2-add-to-string c)
6555 (if (and (= (js2-get-char) ?C)
6556 (= (js2-get-char) ?D)
6557 (= (js2-get-char) ?A)
6558 (= (js2-get-char) ?T)
6559 (= (js2-get-char) ?A)
6560 (= (js2-get-char) ?\[))
6561 (progn
6562 (js2-add-to-string ?C)
6563 (js2-add-to-string ?D)
6564 (js2-add-to-string ?A)
6565 (js2-add-to-string ?T)
6566 (js2-add-to-string ?A)
6567 (js2-add-to-string ?\[)
6568 (unless (js2-read-cdata token)
6569 (throw 'return js2-ERROR)))
6570 (js2-xml-discard-string token)
6571 (throw 'return js2-ERROR)))
6572 (t
6573 (unless (js2-read-entity token)
6574 (throw 'return js2-ERROR))))
6575 ;; Allow bare CDATA section, e.g.:
6576 ;; let xml = <![CDATA[ foo bar baz ]]>;
6577 (when (zerop js2-ts-xml-open-tags-count)
6578 (throw 'return js2-XMLEND)))
6579 (??
6580 (setq c (js2-get-char)) ;; skip ?
6581 (js2-add-to-string c)
6582 (unless (js2-read-PI token)
6583 (throw 'return js2-ERROR)))
6584 (?/
6585 ;; end tag
6586 (setq c (js2-get-char)) ;; skip /
6587 (js2-add-to-string c)
6588 (when (zerop js2-ts-xml-open-tags-count)
6589 (js2-xml-discard-string token)
6590 (throw 'return js2-ERROR))
6591 (setq js2-ts-xml-is-tag-content t)
6592 (cl-decf js2-ts-xml-open-tags-count))
6593 (t
6594 ;; start tag
6595 (setq js2-ts-xml-is-tag-content t)
6596 (cl-incf js2-ts-xml-open-tags-count))))
6597 (?{
6598 (js2-unget-char)
6599 (js2-set-string-from-buffer token)
6600 (throw 'return js2-XML))
6601 (t
6602 (js2-add-to-string c))))))))
6603 (setf (js2-token-end token) js2-ts-cursor)
6604 (setf (js2-token-type token) result)
6605 result))
6606
6607 (defun js2-read-quoted-string (quote token)
6608 (let (c)
6609 (catch 'return
6610 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6611 (js2-add-to-string c)
6612 (if (eq c quote)
6613 (throw 'return t)))
6614 (js2-xml-discard-string token) ;; throw away string in progress
6615 nil)))
6616
6617 (defun js2-read-xml-comment (token)
6618 (let ((c (js2-get-char)))
6619 (catch 'return
6620 (while (/= c js2-EOF_CHAR)
6621 (catch 'continue
6622 (js2-add-to-string c)
6623 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6624 (setq c (js2-get-char))
6625 (js2-add-to-string c)
6626 (if (eq (js2-peek-char) ?>)
6627 (progn
6628 (setq c (js2-get-char)) ;; skip >
6629 (js2-add-to-string c)
6630 (throw 'return t))
6631 (throw 'continue nil)))
6632 (setq c (js2-get-char))))
6633 (js2-xml-discard-string token)
6634 nil)))
6635
6636 (defun js2-read-cdata (token)
6637 (let ((c (js2-get-char)))
6638 (catch 'return
6639 (while (/= c js2-EOF_CHAR)
6640 (catch 'continue
6641 (js2-add-to-string c)
6642 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6643 (setq c (js2-get-char))
6644 (js2-add-to-string c)
6645 (if (eq (js2-peek-char) ?>)
6646 (progn
6647 (setq c (js2-get-char)) ;; Skip >
6648 (js2-add-to-string c)
6649 (throw 'return t))
6650 (throw 'continue nil)))
6651 (setq c (js2-get-char))))
6652 (js2-xml-discard-string token)
6653 nil)))
6654
6655 (defun js2-read-entity (token)
6656 (let ((decl-tags 1)
6657 c)
6658 (catch 'return
6659 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6660 (js2-add-to-string c)
6661 (cl-case c
6662 (?<
6663 (cl-incf decl-tags))
6664 (?>
6665 (cl-decf decl-tags)
6666 (if (zerop decl-tags)
6667 (throw 'return t)))))
6668 (js2-xml-discard-string token)
6669 nil)))
6670
6671 (defun js2-read-PI (token)
6672 "Scan an XML processing instruction."
6673 (let (c)
6674 (catch 'return
6675 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6676 (js2-add-to-string c)
6677 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6678 (setq c (js2-get-char)) ;; Skip >
6679 (js2-add-to-string c)
6680 (throw 'return t)))
6681 (js2-xml-discard-string token)
6682 nil)))
6683
6684 ;;; Highlighting
6685
6686 (defun js2-set-face (beg end face &optional record)
6687 "Fontify a region. If RECORD is non-nil, record for later."
6688 (when (cl-plusp js2-highlight-level)
6689 (setq beg (min (point-max) beg)
6690 beg (max (point-min) beg)
6691 end (min (point-max) end)
6692 end (max (point-min) end))
6693 (if record
6694 (push (list beg end face) js2-mode-fontifications)
6695 (put-text-property beg end 'font-lock-face face))))
6696
6697 (defsubst js2-clear-face (beg end)
6698 (remove-text-properties beg end '(font-lock-face nil
6699 help-echo nil
6700 point-entered nil
6701 cursor-sensor-functions nil
6702 c-in-sws nil)))
6703
6704 (defconst js2-ecma-global-props
6705 (concat "^"
6706 (regexp-opt
6707 '("Infinity" "NaN" "undefined" "arguments") t)
6708 "$")
6709 "Value properties of the Ecma-262 Global Object.
6710 Shown at or above `js2-highlight-level' 2.")
6711
6712 ;; might want to add the name "arguments" to this list?
6713 (defconst js2-ecma-object-props
6714 (concat "^"
6715 (regexp-opt
6716 '("prototype" "__proto__" "__parent__") t)
6717 "$")
6718 "Value properties of the Ecma-262 Object constructor.
6719 Shown at or above `js2-highlight-level' 2.")
6720
6721 (defconst js2-ecma-global-funcs
6722 (concat
6723 "^"
6724 (regexp-opt
6725 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6726 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6727 "$")
6728 "Function properties of the Ecma-262 Global object.
6729 Shown at or above `js2-highlight-level' 2.")
6730
6731 (defconst js2-ecma-number-props
6732 (concat "^"
6733 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6734 "NEGATIVE_INFINITY"
6735 "POSITIVE_INFINITY") t)
6736 "$")
6737 "Properties of the Ecma-262 Number constructor.
6738 Shown at or above `js2-highlight-level' 2.")
6739
6740 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6741 "Properties of the Ecma-262 Date constructor.
6742 Shown at or above `js2-highlight-level' 2.")
6743
6744 (defconst js2-ecma-math-props
6745 (concat "^"
6746 (regexp-opt
6747 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6748 t)
6749 "$")
6750 "Properties of the Ecma-262 Math object.
6751 Shown at or above `js2-highlight-level' 2.")
6752
6753 (defconst js2-ecma-math-funcs
6754 (concat "^"
6755 (regexp-opt
6756 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6757 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6758 "$")
6759 "Function properties of the Ecma-262 Math object.
6760 Shown at or above `js2-highlight-level' 2.")
6761
6762 (defconst js2-ecma-function-props
6763 (concat
6764 "^"
6765 (regexp-opt
6766 '(;; properties of the Object prototype object
6767 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6768 "toLocaleString" "toString" "valueOf"
6769 ;; properties of the Function prototype object
6770 "apply" "call"
6771 ;; properties of the Array prototype object
6772 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6773 "splice" "unshift"
6774 ;; properties of the String prototype object
6775 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6776 "localeCompare" "match" "replace" "search" "split" "substring"
6777 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6778 "toUpperCase"
6779 ;; properties of the Number prototype object
6780 "toExponential" "toFixed" "toPrecision"
6781 ;; properties of the Date prototype object
6782 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6783 "getMinutes" "getMonth" "getSeconds" "getTime"
6784 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6785 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6786 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6787 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6788 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6789 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6790 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6791 "toTimeString" "toUTCString"
6792 ;; properties of the RegExp prototype object
6793 "exec" "test"
6794 ;; properties of the JSON prototype object
6795 "parse" "stringify"
6796 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6797 "toSource" "__defineGetter__" "__defineSetter__"
6798 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6799 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6800 t)
6801 "$")
6802 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6803 Shown at or above `js2-highlight-level' 3.")
6804
6805 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6806 (let ((target-name (and target
6807 (js2-name-node-p target)
6808 (js2-name-node-name target)))
6809 (prop-name (if prop (js2-name-node-name prop)))
6810 (level2 (>= js2-highlight-level 2))
6811 (level3 (>= js2-highlight-level 3)))
6812 (when level2
6813 (let ((face
6814 (if call-p
6815 (cond
6816 ((and target prop)
6817 (cond
6818 ((and level3 (string-match js2-ecma-function-props prop-name))
6819 'font-lock-builtin-face)
6820 ((and target-name prop)
6821 (cond
6822 ((string= target-name "Date")
6823 (if (string-match js2-ecma-date-props prop-name)
6824 'font-lock-builtin-face))
6825 ((string= target-name "Math")
6826 (if (string-match js2-ecma-math-funcs prop-name)
6827 'font-lock-builtin-face))))))
6828 (prop
6829 (if (string-match js2-ecma-global-funcs prop-name)
6830 'font-lock-builtin-face)))
6831 (cond
6832 ((and target prop)
6833 (cond
6834 ((string= target-name "Number")
6835 (if (string-match js2-ecma-number-props prop-name)
6836 'font-lock-constant-face))
6837 ((string= target-name "Math")
6838 (if (string-match js2-ecma-math-props prop-name)
6839 'font-lock-constant-face))))
6840 (prop
6841 (if (string-match js2-ecma-object-props prop-name)
6842 'font-lock-constant-face))))))
6843 (when face
6844 (let ((pos (+ (js2-node-pos parent) ; absolute
6845 (js2-node-pos prop)))) ; relative
6846 (js2-set-face pos
6847 (+ pos (js2-node-len prop))
6848 face 'record)))))))
6849
6850 (defun js2-parse-highlight-member-expr-node (node)
6851 "Perform syntax highlighting of EcmaScript built-in properties.
6852 The variable `js2-highlight-level' governs this highlighting."
6853 (let (face target prop name pos end parent call-p callee)
6854 (cond
6855 ;; case 1: simple name, e.g. foo
6856 ((js2-name-node-p node)
6857 (setq name (js2-name-node-name node))
6858 ;; possible for name to be nil in rare cases - saw it when
6859 ;; running js2-mode on an elisp buffer. Might as well try to
6860 ;; make it so js2-mode never barfs.
6861 (when name
6862 (setq face (if (string-match js2-ecma-global-props name)
6863 'font-lock-constant-face))
6864 (when face
6865 (setq pos (js2-node-pos node)
6866 end (+ pos (js2-node-len node)))
6867 (js2-set-face pos end face 'record))))
6868 ;; case 2: property access or function call
6869 ((or (js2-prop-get-node-p node)
6870 ;; highlight function call if expr is a prop-get node
6871 ;; or a plain name (i.e. unqualified function call)
6872 (and (setq call-p (js2-call-node-p node))
6873 (setq callee (js2-call-node-target node)) ; separate setq!
6874 (or (js2-prop-get-node-p callee)
6875 (js2-name-node-p callee))))
6876 (setq parent node
6877 node (if call-p callee node))
6878 (if (and call-p (js2-name-node-p callee))
6879 (setq prop callee)
6880 (setq target (js2-prop-get-node-left node)
6881 prop (js2-prop-get-node-right node)))
6882 (cond
6883 ((js2-name-node-p prop)
6884 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6885 (js2-parse-highlight-prop-get parent target prop call-p))
6886 ((js2-name-node-p target)
6887 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6888 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6889
6890 (defun js2-parse-highlight-member-expr-fn-name (expr)
6891 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6892 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6893 We currently only handle the case where the last component is a prop-get
6894 of a simple name. Called before EXPR has a parent node."
6895 (let (pos
6896 (name (and (js2-prop-get-node-p expr)
6897 (js2-prop-get-node-right expr))))
6898 (when (js2-name-node-p name)
6899 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6900 (js2-node-pos name)))
6901 (+ pos (js2-node-len name))
6902 'font-lock-function-name-face
6903 'record))))
6904
6905 ;; source: http://jsdoc.sourceforge.net/
6906 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6907 ;; allows type specifications, and needs work before entering the wild.
6908
6909 (defconst js2-jsdoc-param-tag-regexp
6910 (concat "^\\s-*\\*+\\s-*\\(@"
6911 "\\(?:param\\|argument\\)"
6912 "\\)"
6913 "\\s-*\\({[^}]+}\\)?" ; optional type
6914 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6915 "\\>")
6916 "Matches jsdoc tags with optional type and optional param name.")
6917
6918 (defconst js2-jsdoc-typed-tag-regexp
6919 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6920 (regexp-opt
6921 '("enum"
6922 "extends"
6923 "field"
6924 "id"
6925 "implements"
6926 "lends"
6927 "mods"
6928 "requires"
6929 "return"
6930 "returns"
6931 "throw"
6932 "throws"))
6933 "\\)\\)\\s-*\\({[^}]+}\\)?")
6934 "Matches jsdoc tags with optional type.")
6935
6936 (defconst js2-jsdoc-arg-tag-regexp
6937 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6938 (regexp-opt
6939 '("alias"
6940 "augments"
6941 "borrows"
6942 "bug"
6943 "base"
6944 "config"
6945 "default"
6946 "define"
6947 "exception"
6948 "function"
6949 "member"
6950 "memberOf"
6951 "name"
6952 "namespace"
6953 "property"
6954 "since"
6955 "suppress"
6956 "this"
6957 "throws"
6958 "type"
6959 "version"))
6960 "\\)\\)\\s-+\\([^ \t]+\\)")
6961 "Matches jsdoc tags with a single argument.")
6962
6963 (defconst js2-jsdoc-empty-tag-regexp
6964 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6965 (regexp-opt
6966 '("addon"
6967 "author"
6968 "class"
6969 "const"
6970 "constant"
6971 "constructor"
6972 "constructs"
6973 "deprecated"
6974 "desc"
6975 "description"
6976 "event"
6977 "example"
6978 "exec"
6979 "export"
6980 "fileoverview"
6981 "final"
6982 "function"
6983 "hidden"
6984 "ignore"
6985 "implicitCast"
6986 "inheritDoc"
6987 "inner"
6988 "interface"
6989 "license"
6990 "noalias"
6991 "noshadow"
6992 "notypecheck"
6993 "override"
6994 "owner"
6995 "preserve"
6996 "preserveTry"
6997 "private"
6998 "protected"
6999 "public"
7000 "static"
7001 "supported"
7002 ))
7003 "\\)\\)\\s-*")
7004 "Matches empty jsdoc tags.")
7005
7006 (defconst js2-jsdoc-link-tag-regexp
7007 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
7008 "Matches a jsdoc link or code tag.")
7009
7010 (defconst js2-jsdoc-see-tag-regexp
7011 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
7012 "Matches a jsdoc @see tag.")
7013
7014 (defconst js2-jsdoc-html-tag-regexp
7015 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
7016 "Matches a simple (no attributes) html start- or end-tag.")
7017
7018 (defun js2-jsdoc-highlight-helper ()
7019 (js2-set-face (match-beginning 1)
7020 (match-end 1)
7021 'js2-jsdoc-tag)
7022 (if (match-beginning 2)
7023 (if (save-excursion
7024 (goto-char (match-beginning 2))
7025 (= (char-after) ?{))
7026 (js2-set-face (1+ (match-beginning 2))
7027 (1- (match-end 2))
7028 'js2-jsdoc-type)
7029 (js2-set-face (match-beginning 2)
7030 (match-end 2)
7031 'js2-jsdoc-value)))
7032 (if (match-beginning 3)
7033 (js2-set-face (match-beginning 3)
7034 (match-end 3)
7035 'js2-jsdoc-value)))
7036
7037 (defun js2-highlight-jsdoc (ast)
7038 "Highlight doc comment tags."
7039 (let ((comments (js2-ast-root-comments ast))
7040 beg end)
7041 (save-excursion
7042 (dolist (node comments)
7043 (when (eq (js2-comment-node-format node) 'jsdoc)
7044 (setq beg (js2-node-abs-pos node)
7045 end (+ beg (js2-node-len node)))
7046 (save-restriction
7047 (narrow-to-region beg end)
7048 (dolist (re (list js2-jsdoc-param-tag-regexp
7049 js2-jsdoc-typed-tag-regexp
7050 js2-jsdoc-arg-tag-regexp
7051 js2-jsdoc-link-tag-regexp
7052 js2-jsdoc-see-tag-regexp
7053 js2-jsdoc-empty-tag-regexp))
7054 (goto-char beg)
7055 (while (re-search-forward re nil t)
7056 (js2-jsdoc-highlight-helper)))
7057 ;; simple highlighting for html tags
7058 (goto-char beg)
7059 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7060 (js2-set-face (match-beginning 1)
7061 (match-end 1)
7062 'js2-jsdoc-html-tag-delimiter)
7063 (js2-set-face (match-beginning 2)
7064 (match-end 2)
7065 'js2-jsdoc-html-tag-name)
7066 (js2-set-face (match-beginning 3)
7067 (match-end 3)
7068 'js2-jsdoc-html-tag-delimiter))))))))
7069
7070 (defun js2-highlight-assign-targets (_node left right)
7071 "Highlight function properties and external variables."
7072 (let (leftpos name)
7073 ;; highlight vars and props assigned function values
7074 (when (or (js2-function-node-p right)
7075 (js2-class-node-p right))
7076 (cond
7077 ;; var foo = function() {...}
7078 ((js2-name-node-p left)
7079 (setq name left))
7080 ;; foo.bar.baz = function() {...}
7081 ((and (js2-prop-get-node-p left)
7082 (js2-name-node-p (js2-prop-get-node-right left)))
7083 (setq name (js2-prop-get-node-right left))))
7084 (when name
7085 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7086 (+ leftpos (js2-node-len name))
7087 'font-lock-function-name-face
7088 'record)))))
7089
7090 (defun js2-record-name-node (node)
7091 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7092 later. NODE must be a name node."
7093 (let ((leftpos (js2-node-abs-pos node)))
7094 (push (list node js2-current-scope
7095 leftpos
7096 (+ leftpos (js2-node-len node)))
7097 js2-recorded-identifiers)))
7098
7099 (defun js2-highlight-undeclared-vars ()
7100 "After entire parse is finished, look for undeclared variable references.
7101 We have to wait until entire buffer is parsed, since JavaScript permits var
7102 decls to occur after they're used.
7103
7104 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7105 it is considered declared."
7106 (let (name)
7107 (dolist (entry js2-recorded-identifiers)
7108 (cl-destructuring-bind (name-node scope pos end) entry
7109 (setq name (js2-name-node-name name-node))
7110 (unless (or (member name js2-global-externs)
7111 (member name js2-default-externs)
7112 (member name js2-additional-externs)
7113 (js2-get-defining-scope scope name pos))
7114 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7115 'js2-external-variable))))))
7116
7117 (defun js2--add-or-update-symbol (symbol inition used vars)
7118 "Add or update SYMBOL entry in VARS, an hash table.
7119 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7120 respectively meaning that SYMBOL is a mere declaration, an
7121 assignment or a function parameter; when USED is t, the symbol
7122 node is assumed to be an usage and thus added to the list stored
7123 in the cdr of the entry.
7124 "
7125 (let* ((nm (js2-name-node-name symbol))
7126 (es (js2-node-get-enclosing-scope symbol))
7127 (ds (js2-get-defining-scope es nm)))
7128 (when (and ds (not (equal nm "arguments")))
7129 (let* ((sym (js2-scope-get-symbol ds nm))
7130 (var (gethash sym vars))
7131 (err-var-p (js2-catch-node-p ds)))
7132 (unless inition
7133 (setq inition err-var-p))
7134 (if var
7135 (progn
7136 (when (and inition (not (equal (car var) ?P)))
7137 (setcar var inition))
7138 (when used
7139 (push symbol (cdr var))))
7140 ;; do not consider the declaration of catch parameter as an usage
7141 (when (and err-var-p used)
7142 (setq used nil))
7143 (puthash sym (cons inition (if used (list symbol))) vars))))))
7144
7145 (defun js2--classify-variables ()
7146 "Collect and classify variables declared or used within js2-mode-ast.
7147 Traverse the whole ast tree returning a summary of the variables
7148 usage as an hash-table, keyed by their corresponding symbol table
7149 entry.
7150 Each variable is described by a tuple where the car is a flag
7151 indicating whether the variable has been initialized and the cdr
7152 is a possibly empty list of name nodes where it is used. External
7153 symbols, i.e. those not present in the whole scopes hierarchy,
7154 are ignored."
7155 (let ((vars (make-hash-table :test #'eq :size 100)))
7156 (js2-visit-ast
7157 js2-mode-ast
7158 (lambda (node end-p)
7159 (when (null end-p)
7160 (cond
7161 ((js2-var-init-node-p node)
7162 ;; take note about possibly initialized declarations
7163 (let ((target (js2-var-init-node-target node))
7164 (initializer (js2-var-init-node-initializer node)))
7165 (when target
7166 (let* ((parent (js2-node-parent node))
7167 (grandparent (if parent (js2-node-parent parent)))
7168 (inited (not (null initializer))))
7169 (unless inited
7170 (setq inited
7171 (and grandparent
7172 (js2-for-in-node-p grandparent)
7173 (memq target
7174 (mapcar #'js2-var-init-node-target
7175 (js2-var-decl-node-kids
7176 (js2-for-in-node-iterator grandparent)))))))
7177 (js2--add-or-update-symbol target inited nil vars)))))
7178
7179 ((js2-assign-node-p node)
7180 ;; take note about assignments
7181 (let ((left (js2-assign-node-left node)))
7182 (when (js2-name-node-p left)
7183 (js2--add-or-update-symbol left t nil vars))))
7184
7185 ((js2-prop-get-node-p node)
7186 ;; handle x.y.z nodes, considering only x
7187 (let ((left (js2-prop-get-node-left node)))
7188 (when (js2-name-node-p left)
7189 (js2--add-or-update-symbol left nil t vars))))
7190
7191 ((js2-name-node-p node)
7192 ;; take note about used variables
7193 (let ((parent (js2-node-parent node)))
7194 (when parent
7195 (unless (or (and (js2-var-init-node-p parent) ; handled above
7196 (eq node (js2-var-init-node-target parent)))
7197 (and (js2-assign-node-p parent)
7198 (eq node (js2-assign-node-left parent)))
7199 (js2-prop-get-node-p parent))
7200 (let ((used t) inited)
7201 (cond
7202 ((and (js2-function-node-p parent)
7203 (js2-wrapper-function-p parent))
7204 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7205
7206 ((js2-for-in-node-p parent)
7207 (if (eq node (js2-for-in-node-iterator parent))
7208 (setq inited t used nil)))
7209
7210 ((js2-function-node-p parent)
7211 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7212 used nil)))
7213
7214 (unless used
7215 (let ((grandparent (js2-node-parent parent)))
7216 (when grandparent
7217 (setq used (js2-return-node-p grandparent)))))
7218
7219 (js2--add-or-update-symbol node inited used vars))))))))
7220 t))
7221 vars))
7222
7223 (defun js2--get-name-node (node)
7224 (cond
7225 ((js2-name-node-p node) node)
7226 ((js2-function-node-p node)
7227 (js2-function-node-name node))
7228 ((js2-class-node-p node)
7229 (js2-class-node-name node))
7230 ((js2-comp-loop-node-p node)
7231 (js2-comp-loop-node-iterator node))
7232 (t node)))
7233
7234 (defun js2--highlight-unused-variable (symbol info)
7235 (let ((name (js2-symbol-name symbol))
7236 (inited (car info))
7237 (refs (cdr info))
7238 pos len)
7239 (unless (and inited refs)
7240 (if refs
7241 (dolist (ref refs)
7242 (setq pos (js2-node-abs-pos ref))
7243 (setq len (js2-name-node-len ref))
7244 (js2-report-warning "msg.uninitialized.variable" name pos len
7245 'js2-warning))
7246 (when (or js2-warn-about-unused-function-arguments
7247 (not (eq inited ?P)))
7248 (let* ((symn (js2-symbol-ast-node symbol))
7249 (namen (js2--get-name-node symn)))
7250 (unless (js2-node-top-level-decl-p namen)
7251 (setq pos (js2-node-abs-pos namen))
7252 (setq len (js2-name-node-len namen))
7253 (js2-report-warning "msg.unused.variable" name pos len
7254 'js2-warning))))))))
7255
7256 (defun js2-highlight-unused-variables ()
7257 "Highlight unused variables."
7258 (let ((vars (js2--classify-variables)))
7259 (maphash #'js2--highlight-unused-variable vars)))
7260
7261 ;;;###autoload
7262 (define-minor-mode js2-highlight-unused-variables-mode
7263 "Toggle highlight of unused variables."
7264 :lighter ""
7265 (if js2-highlight-unused-variables-mode
7266 (add-hook 'js2-post-parse-callbacks
7267 #'js2-highlight-unused-variables nil t)
7268 (remove-hook 'js2-post-parse-callbacks
7269 #'js2-highlight-unused-variables t)))
7270
7271 (defun js2-set-default-externs ()
7272 "Set the value of `js2-default-externs' based on the various
7273 `js2-include-?-externs' variables."
7274 (setq js2-default-externs
7275 (append js2-ecma-262-externs
7276 (if js2-include-browser-externs js2-browser-externs)
7277 (if (and js2-include-browser-externs
7278 (>= js2-language-version 200)) js2-harmony-externs)
7279 (if js2-include-rhino-externs js2-rhino-externs)
7280 (if js2-include-node-externs js2-node-externs)
7281 (if (or js2-include-browser-externs js2-include-node-externs)
7282 js2-typed-array-externs))))
7283
7284 (defun js2-apply-jslint-globals ()
7285 (setq js2-additional-externs
7286 (nconc (js2-get-jslint-globals)
7287 js2-additional-externs)))
7288
7289 (defun js2-get-jslint-globals ()
7290 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7291 when (and (eq 'block (js2-comment-node-format node))
7292 (save-excursion
7293 (goto-char (js2-node-abs-pos node))
7294 (looking-at "/\\*global ")))
7295 append (js2-get-jslint-globals-in
7296 (match-end 0)
7297 (js2-node-abs-end node))))
7298
7299 (defun js2-get-jslint-globals-in (beg end)
7300 (let (res)
7301 (save-excursion
7302 (goto-char beg)
7303 (while (re-search-forward js2-mode-identifier-re end t)
7304 (let ((match (match-string 0)))
7305 (unless (member match '("true" "false"))
7306 (push match res)))))
7307 (nreverse res)))
7308
7309 ;;; IMenu support
7310
7311 ;; We currently only support imenu, but eventually should support speedbar and
7312 ;; possibly other browsing mechanisms.
7313
7314 ;; The basic strategy is to identify function assignment targets of the form
7315 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7316 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7317 ;; for imenu after parsing is finished.
7318
7319 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7320 ;; JavaScript, and the general problem is undecidable. However, several forms
7321 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7322 ;; include:
7323
7324 ;; function foo() -- function declaration
7325 ;; foo = function() -- function expression assigned to variable
7326 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7327 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7328 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7329 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7330 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7331 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7332 ;; function foo() {function bar() {...}} -- nested function
7333 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7334
7335 ;; This list boils down to a few forms that can be combined recursively.
7336 ;; Top-level named function declarations include both the left-hand (name)
7337 ;; and the right-hand (function value) expressions needed to produce an imenu
7338 ;; entry. The other "right-hand" forms we need to look for are:
7339 ;; - functions declared as props/getters/setters in object literals
7340 ;; - nested named function declarations
7341 ;; The "left-hand" expressions that functions can be assigned to include:
7342 ;; - local/global variables
7343 ;; - nested property-get expressions like a.b.c.d
7344 ;; - element gets like foo[10] or foo['bar'] where the index
7345 ;; expression can be trivially converted to a property name. They
7346 ;; effectively then become property gets.
7347
7348 ;; All the different definition types are canonicalized into the form
7349 ;; foo.bar.baz = position-of-function-keyword
7350
7351 ;; We need to build a trie-like structure for imenu. As an example,
7352 ;; consider the following JavaScript code:
7353
7354 ;; a = function() {...} // function at position 5
7355 ;; b = function() {...} // function at position 25
7356 ;; foo = function() {...} // function at position 100
7357 ;; foo.bar = function() {...} // function at position 200
7358 ;; foo.bar.baz = function() {...} // function at position 300
7359 ;; foo.bar.zab = function() {...} // function at position 400
7360
7361 ;; During parsing we accumulate an entry for each definition in
7362 ;; the variable `js2-imenu-recorder', like so:
7363
7364 ;; '((fn a 5)
7365 ;; (fn b 25)
7366 ;; (fn foo 100)
7367 ;; (fn foo bar 200)
7368 ;; (fn foo bar baz 300)
7369 ;; (fn foo bar zab 400))
7370
7371 ;; Where 'fn' is the respective function node.
7372 ;; After parsing these entries are merged into this alist-trie:
7373
7374 ;; '((a . 1)
7375 ;; (b . 2)
7376 ;; (foo (<definition> . 3)
7377 ;; (bar (<definition> . 6)
7378 ;; (baz . 100)
7379 ;; (zab . 200))))
7380
7381 ;; Note the wacky need for a <definition> name. The token can be anything
7382 ;; that isn't a valid JavaScript identifier, because you might make foo
7383 ;; a function and then start setting properties on it that are also functions.
7384
7385 (defun js2-prop-node-name (node)
7386 "Return the name of a node that may be a property-get/property-name.
7387 If NODE is not a valid name-node, string-node or integral number-node,
7388 returns nil. Otherwise returns the string name/value of the node."
7389 (cond
7390 ((js2-name-node-p node)
7391 (js2-name-node-name node))
7392 ((js2-string-node-p node)
7393 (js2-string-node-value node))
7394 ((and (js2-number-node-p node)
7395 (string-match "^[0-9]+$" (js2-number-node-value node)))
7396 (js2-number-node-value node))
7397 ((eq (js2-node-type node) js2-THIS)
7398 "this")
7399 ((eq (js2-node-type node) js2-SUPER)
7400 "super")))
7401
7402 (defun js2-node-qname-component (node)
7403 "Return the name of this node, if it contributes to a qname.
7404 Returns nil if the node doesn't contribute."
7405 (copy-sequence
7406 (or (js2-prop-node-name node)
7407 (if (and (js2-function-node-p node)
7408 (js2-function-node-name node))
7409 (js2-name-node-name (js2-function-node-name node))))))
7410
7411 (defun js2-record-imenu-entry (fn-node qname pos)
7412 "Add an entry to `js2-imenu-recorder'.
7413 FN-NODE should be the current item's function node.
7414
7415 Associate FN-NODE with its QNAME for later lookup.
7416 This is used in postprocessing the chain list. For each chain, we find
7417 the parent function, look up its qname, then prepend a copy of it to the chain."
7418 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7419 (unless js2-imenu-function-map
7420 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7421 (puthash fn-node qname js2-imenu-function-map))
7422
7423 (defun js2-record-imenu-functions (node &optional var)
7424 "Record function definitions for imenu.
7425 NODE is a function node or an object literal.
7426 VAR, if non-nil, is the expression that NODE is being assigned to.
7427 When passed arguments of wrong type, does nothing."
7428 (when js2-parse-ide-mode
7429 (let ((fun-p (js2-function-node-p node))
7430 qname fname-node)
7431 (cond
7432 ;; non-anonymous function declaration?
7433 ((and fun-p
7434 (not var)
7435 (setq fname-node (js2-function-node-name node)))
7436 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7437 ;; for remaining forms, compute left-side tree branch first
7438 ((and var (setq qname (js2-compute-nested-prop-get var)))
7439 (cond
7440 ;; foo.bar.baz = function
7441 (fun-p
7442 (js2-record-imenu-entry node qname (js2-node-pos node)))
7443 ;; foo.bar.baz = object-literal
7444 ;; look for nested functions: {a: {b: function() {...} }}
7445 ((js2-object-node-p node)
7446 ;; Node position here is still absolute, since the parser
7447 ;; passes the assignment target and value expressions
7448 ;; to us before they are added as children of the assignment node.
7449 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7450
7451 (defun js2-compute-nested-prop-get (node)
7452 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7453 component nodes as a list. Otherwise return nil. Element-gets are treated
7454 as property-gets if the index expression is a string, or a positive integer."
7455 (let (left right head)
7456 (cond
7457 ((or (js2-name-node-p node)
7458 (js2-this-or-super-node-p node))
7459 (list node))
7460 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7461 ((js2-prop-get-node-p node) ; foo.bar
7462 (setq left (js2-prop-get-node-left node)
7463 right (js2-prop-get-node-right node))
7464 (if (setq head (js2-compute-nested-prop-get left))
7465 (nconc head (list right))))
7466 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7467 (setq left (js2-elem-get-node-target node)
7468 right (js2-elem-get-node-element node))
7469 (if (or (js2-string-node-p right) ; ['bar']
7470 (and (js2-number-node-p right) ; [10]
7471 (string-match "^[0-9]+$"
7472 (js2-number-node-value right))))
7473 (if (setq head (js2-compute-nested-prop-get left))
7474 (nconc head (list right))))))))
7475
7476 (defun js2-record-object-literal (node qname pos)
7477 "Recursively process an object literal looking for functions.
7478 NODE is an object literal that is the right-hand child of an assignment
7479 expression. QNAME is a list of nodes representing the assignment target,
7480 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7481 POS is the absolute position of the node.
7482 We do a depth-first traversal of NODE. For any functions we find,
7483 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7484 (let (right)
7485 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7486 (let ((left (js2-infix-node-left e))
7487 ;; Element positions are relative to the parent position.
7488 (pos (+ pos (js2-node-pos e))))
7489 (cond
7490 ;; foo: function() {...}
7491 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7492 (when (js2-prop-node-name left)
7493 ;; As a policy decision, we record the position of the property,
7494 ;; not the position of the `function' keyword, since the property
7495 ;; is effectively the name of the function.
7496 (js2-record-imenu-entry right (append qname (list left)) pos)))
7497 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7498 ((js2-object-node-p right)
7499 (js2-record-object-literal right
7500 (append qname (list (js2-infix-node-left e)))
7501 (+ pos (js2-node-pos right)))))))))
7502
7503 (defun js2-node-top-level-decl-p (node)
7504 "Return t if NODE's name is defined in the top-level scope.
7505 Also returns t if NODE's name is not defined in any scope, since it implies
7506 that it's an external variable, which must also be in the top-level scope."
7507 (let* ((name (js2-prop-node-name node))
7508 (this-scope (js2-node-get-enclosing-scope node))
7509 defining-scope)
7510 (cond
7511 ((js2-this-or-super-node-p node)
7512 nil)
7513 ((null this-scope)
7514 t)
7515 ((setq defining-scope (js2-get-defining-scope this-scope name))
7516 (js2-ast-root-p defining-scope))
7517 (t t))))
7518
7519 (defun js2-wrapper-function-p (node)
7520 "Return t if NODE is a function expression that's immediately invoked.
7521 NODE must be `js2-function-node'."
7522 (let ((parent (js2-node-parent node)))
7523 (or
7524 ;; function(){...}();
7525 (and (js2-call-node-p parent)
7526 (eq node (js2-call-node-target parent)))
7527 (and (js2-paren-node-p parent)
7528 ;; (function(){...})();
7529 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7530 ;; (function(){...}).call(this);
7531 (and (js2-prop-get-node-p parent)
7532 (member (js2-name-node-name (js2-prop-get-node-right parent))
7533 '("call" "apply"))
7534 (js2-call-node-p (js2-node-parent parent))))))))
7535
7536 (defun js2-browse-postprocess-chains ()
7537 "Modify function-declaration name chains after parsing finishes.
7538 Some of the information is only available after the parse tree is complete.
7539 For instance, processing a nested scope requires a parent function node."
7540 (let (result fn parent-qname p elem)
7541 (dolist (entry js2-imenu-recorder)
7542 ;; function node goes first
7543 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7544 ;; Examine head's defining scope:
7545 ;; Pre-processed chain, or top-level/external, keep as-is.
7546 (if (or (stringp head) (js2-node-top-level-decl-p head))
7547 (push chain result)
7548 (when (js2-this-or-super-node-p head)
7549 (setq chain (cdr chain))) ; discard this-node
7550 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7551 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7552 (when (eq parent-qname 'not-found)
7553 ;; anonymous function expressions are not recorded
7554 ;; during the parse, so we need to handle this case here
7555 (setq parent-qname
7556 (if (js2-wrapper-function-p fn)
7557 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7558 (if (js2-ast-root-p grandparent)
7559 nil
7560 (gethash grandparent js2-imenu-function-map 'skip)))
7561 'skip))
7562 (puthash fn parent-qname js2-imenu-function-map))
7563 (if (eq parent-qname 'skip)
7564 ;; We don't show it, let's record that fact.
7565 (remhash current-fn js2-imenu-function-map)
7566 ;; Prepend parent fn qname to this chain.
7567 (let ((qname (append parent-qname chain)))
7568 (puthash current-fn (butlast qname) js2-imenu-function-map)
7569 (push qname result)))))))
7570 ;; Collect chains obtained by third-party code.
7571 (let (js2-imenu-recorder)
7572 (run-hooks 'js2-build-imenu-callbacks)
7573 (dolist (entry js2-imenu-recorder)
7574 (push (cdr entry) result)))
7575 ;; Finally replace each node in each chain with its name.
7576 (dolist (chain result)
7577 (setq p chain)
7578 (while p
7579 (if (js2-node-p (setq elem (car p)))
7580 (setcar p (js2-node-qname-component elem)))
7581 (setq p (cdr p))))
7582 result))
7583
7584 ;; Merge name chains into a trie-like tree structure of nested lists.
7585 ;; To simplify construction of the trie, we first build it out using the rule
7586 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7587 ;; [key, num-or-list]. The second element can be a number; if so, this key
7588 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7589 ;; associated with the key at this level.) Otherwise the second element is
7590 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7591 ;; a simple recursive formulation.
7592 ;;
7593 ;; js2-mode is building the data structure for imenu. The imenu documentation
7594 ;; claims that it's the structure above, but in practice it wants the children
7595 ;; at the same list level as the key for that level, which is how I've drawn
7596 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7597 ;; list wrapper around the children at each level.
7598 ;;
7599 ;; A completed nested imenu-alist entry looks like this:
7600 ;; '(("foo"
7601 ;; ("<definition>" . 7)
7602 ;; ("bar"
7603 ;; ("a" . 40)
7604 ;; ("b" . 60))))
7605 ;;
7606 ;; In particular, the documentation for `imenu--index-alist' says that
7607 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7608 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7609
7610 (defun js2-treeify (lst)
7611 "Convert (a b c d) to (a ((b ((c d)))))."
7612 (if (null (cddr lst)) ; list length <= 2
7613 lst
7614 (list (car lst) (list (js2-treeify (cdr lst))))))
7615
7616 (defun js2-build-alist-trie (chains trie)
7617 "Merge declaration name chains into a trie-like alist structure for imenu.
7618 CHAINS is the qname chain list produced during parsing. TRIE is a
7619 list of elements built up so far."
7620 (let (head tail pos branch kids)
7621 (dolist (chain chains)
7622 (setq head (car chain)
7623 tail (cdr chain)
7624 pos (if (numberp (car tail)) (car tail))
7625 branch (js2-find-if (lambda (n)
7626 (string= (car n) head))
7627 trie)
7628 kids (cl-second branch))
7629 (cond
7630 ;; case 1: this key isn't in the trie yet
7631 ((null branch)
7632 (if trie
7633 (setcdr (last trie) (list (js2-treeify chain)))
7634 (setq trie (list (js2-treeify chain)))))
7635 ;; case 2: key is present with a single number entry: replace w/ list
7636 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7637 ;; ("<definition>" 20)))
7638 ((numberp kids)
7639 (setcar (cdr branch)
7640 (list (list "<definition-1>" kids)
7641 (if pos
7642 (list "<definition-2>" pos)
7643 (js2-treeify tail)))))
7644 ;; case 3: key is there (with kids), and we're a number entry
7645 (pos
7646 (setcdr (last kids)
7647 (list
7648 (list (format "<definition-%d>"
7649 (1+ (cl-loop for kid in kids
7650 count (eq ?< (aref (car kid) 0)))))
7651 pos))))
7652 ;; case 4: key is there with kids, need to merge in our chain
7653 (t
7654 (js2-build-alist-trie (list tail) kids))))
7655 trie))
7656
7657 (defun js2-flatten-trie (trie)
7658 "Convert TRIE to imenu-format.
7659 Recurses through nodes, and for each one whose second element is a list,
7660 appends the list's flattened elements to the current element. Also
7661 changes the tails into conses. For instance, this pre-flattened trie
7662
7663 '(a ((b 20)
7664 (c ((d 30)
7665 (e 40)))))
7666
7667 becomes
7668
7669 '(a (b . 20)
7670 (c (d . 30)
7671 (e . 40)))
7672
7673 Note that the root of the trie has no key, just a list of chains.
7674 This is also true for the value of any key with multiple children,
7675 e.g. key 'c' in the example above."
7676 (cond
7677 ((listp (car trie))
7678 (mapcar #'js2-flatten-trie trie))
7679 (t
7680 (if (numberp (cl-second trie))
7681 (cons (car trie) (cl-second trie))
7682 ;; else pop list and append its kids
7683 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7684
7685 (defun js2-build-imenu-index ()
7686 "Turn `js2-imenu-recorder' into an imenu data structure."
7687 (when (eq js2-imenu-recorder 'empty)
7688 (setq js2-imenu-recorder nil))
7689 (let* ((chains (js2-browse-postprocess-chains))
7690 (result (js2-build-alist-trie chains nil)))
7691 (js2-flatten-trie result)))
7692
7693 (defun js2-test-print-chains (chains)
7694 "Print a list of qname chains.
7695 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7696 i.e. one or more nodes, and an integer position as the list tail."
7697 (mapconcat (lambda (chain)
7698 (concat "("
7699 (mapconcat (lambda (elem)
7700 (if (js2-node-p elem)
7701 (or (js2-node-qname-component elem)
7702 "nil")
7703 (number-to-string elem)))
7704 chain
7705 " ")
7706 ")"))
7707 chains
7708 "\n"))
7709
7710 ;;; Parser
7711
7712 (defconst js2-version "1.8.5"
7713 "Version of JavaScript supported.")
7714
7715 (defun js2-record-face (face &optional token)
7716 "Record a style run of FACE for TOKEN or the current token."
7717 (unless token (setq token (js2-current-token)))
7718 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7719
7720 (defsubst js2-node-end (n)
7721 "Computes the absolute end of node N.
7722 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7723 is only true until the node is added to its parent; i.e., while parsing."
7724 (+ (js2-node-pos n)
7725 (js2-node-len n)))
7726
7727 (defun js2-record-comment (token)
7728 "Record a comment in `js2-scanned-comments'."
7729 (let ((ct (js2-token-comment-type token))
7730 (beg (js2-token-beg token))
7731 (end (js2-token-end token)))
7732 (push (make-js2-comment-node :len (- end beg)
7733 :format ct)
7734 js2-scanned-comments)
7735 (when js2-parse-ide-mode
7736 (js2-record-face (if (eq ct 'jsdoc)
7737 'font-lock-doc-face
7738 'font-lock-comment-face)
7739 token)
7740 (when (memq ct '(html preprocessor))
7741 ;; Tell cc-engine the bounds of the comment.
7742 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7743
7744 (defun js2-peek-token ()
7745 "Return the next token type without consuming it.
7746 If `js2-ti-lookahead' is positive, return the type of next token
7747 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7748 (if (not (zerop js2-ti-lookahead))
7749 (js2-token-type
7750 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7751 (let ((tt (js2-get-token-internal nil)))
7752 (js2-unget-token)
7753 tt)))
7754
7755 (defalias 'js2-next-token 'js2-get-token)
7756
7757 (defun js2-match-token (match &optional dont-unget)
7758 "Get next token and return t if it matches MATCH, a bytecode.
7759 Returns nil and consumes nothing if MATCH is not the next token."
7760 (if (/= (js2-get-token) match)
7761 (ignore (unless dont-unget (js2-unget-token)))
7762 t))
7763
7764 (defun js2-match-contextual-kwd (name)
7765 "Consume and return t if next token is `js2-NAME', and its
7766 string is NAME. Returns nil and keeps current token otherwise."
7767 (if (or (/= (js2-get-token) js2-NAME)
7768 (not (string= (js2-current-token-string) name)))
7769 (progn
7770 (js2-unget-token)
7771 nil)
7772 (js2-record-face 'font-lock-keyword-face)
7773 t))
7774
7775 (defun js2-get-prop-name-token ()
7776 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7777
7778 (defun js2-match-prop-name ()
7779 "Consume token and return t if next token is a valid property name.
7780 If `js2-language-version' is >= 180, a keyword or reserved word
7781 is considered valid name as well."
7782 (if (eq js2-NAME (js2-get-prop-name-token))
7783 t
7784 (js2-unget-token)
7785 nil))
7786
7787 (defun js2-must-match-prop-name (msg-id &optional pos len)
7788 (if (js2-match-prop-name)
7789 t
7790 (js2-report-error msg-id nil pos len)
7791 nil))
7792
7793 (defun js2-peek-token-or-eol ()
7794 "Return js2-EOL if the next token immediately follows a newline.
7795 Else returns the next token. Used in situations where we don't
7796 consider certain token types valid if they are preceded by a newline.
7797 One example is the postfix ++ or -- operator, which has to be on the
7798 same line as its operand."
7799 (let ((tt (js2-get-token))
7800 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7801 (js2-unget-token)
7802 (if follows-eol
7803 js2-EOL
7804 tt)))
7805
7806 (defun js2-must-match (token msg-id &optional pos len)
7807 "Match next token to token code TOKEN, or record a syntax error.
7808 MSG-ID is the error message to report if the match fails.
7809 Returns t on match, nil if no match."
7810 (if (js2-match-token token t)
7811 t
7812 (js2-report-error msg-id nil pos len)
7813 (js2-unget-token)
7814 nil))
7815
7816 (defun js2-must-match-name (msg-id)
7817 (if (js2-match-token js2-NAME t)
7818 t
7819 (if (eq (js2-current-token-type) js2-RESERVED)
7820 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7821 (js2-report-error msg-id)
7822 (js2-unget-token))
7823 nil))
7824
7825 (defsubst js2-inside-function ()
7826 (cl-plusp js2-nesting-of-function))
7827
7828 (defun js2-set-requires-activation ()
7829 (if (js2-function-node-p js2-current-script-or-fn)
7830 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7831
7832 (defun js2-check-activation-name (name _token)
7833 (when (js2-inside-function)
7834 ;; skip language-version 1.2 check from Rhino
7835 (if (or (string= "arguments" name)
7836 (and js2-compiler-activation-names ; only used in codegen
7837 (gethash name js2-compiler-activation-names)))
7838 (js2-set-requires-activation))))
7839
7840 (defun js2-set-is-generator ()
7841 (let ((fn-node js2-current-script-or-fn))
7842 (when (and (js2-function-node-p fn-node)
7843 (not (js2-function-node-generator-type fn-node)))
7844 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7845
7846 (defun js2-must-have-xml ()
7847 (unless js2-compiler-xml-available
7848 (js2-report-error "msg.XML.not.available")))
7849
7850 (defun js2-push-scope (scope)
7851 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7852 (cl-assert (js2-scope-p scope))
7853 (cl-assert (null (js2-scope-parent-scope scope)))
7854 (cl-assert (not (eq js2-current-scope scope)))
7855 (setf (js2-scope-parent-scope scope) js2-current-scope
7856 js2-current-scope scope))
7857
7858 (defsubst js2-pop-scope ()
7859 (setq js2-current-scope
7860 (js2-scope-parent-scope js2-current-scope)))
7861
7862 (defun js2-enter-loop (loop-node)
7863 (push loop-node js2-loop-set)
7864 (push loop-node js2-loop-and-switch-set)
7865 (js2-push-scope loop-node)
7866 ;; Tell the current labeled statement (if any) its statement,
7867 ;; and set the jump target of the first label to the loop.
7868 ;; These are used in `js2-parse-continue' to verify that the
7869 ;; continue target is an actual labeled loop. (And for codegen.)
7870 (when js2-labeled-stmt
7871 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7872 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7873 js2-labeled-stmt))) loop-node)))
7874
7875 (defun js2-exit-loop ()
7876 (pop js2-loop-set)
7877 (pop js2-loop-and-switch-set)
7878 (js2-pop-scope))
7879
7880 (defsubst js2-enter-switch (switch-node)
7881 (push switch-node js2-loop-and-switch-set))
7882
7883 (defsubst js2-exit-switch ()
7884 (pop js2-loop-and-switch-set))
7885
7886 (defsubst js2-get-directive (node)
7887 "Return NODE's value if it is a directive, nil otherwise.
7888
7889 A directive is an otherwise-meaningless expression statement
7890 consisting of a string literal, such as \"use strict\"."
7891 (and (js2-expr-stmt-node-p node)
7892 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7893 (js2-string-node-value node)))
7894
7895 (defun js2-parse (&optional buf cb)
7896 "Tell the js2 parser to parse a region of JavaScript.
7897
7898 BUF is a buffer or buffer name containing the code to parse.
7899 Call `narrow-to-region' first to parse only part of the buffer.
7900
7901 The returned AST root node is given some additional properties:
7902 `node-count' - total number of nodes in the AST
7903 `buffer' - BUF. The buffer it refers to may change or be killed,
7904 so the value is not necessarily reliable.
7905
7906 An optional callback CB can be specified to report parsing
7907 progress. If `(functionp CB)' returns t, it will be called with
7908 the current line number once before parsing begins, then again
7909 each time the lexer reaches a new line number.
7910
7911 CB can also be a list of the form `(symbol cb ...)' to specify
7912 multiple callbacks with different criteria. Each symbol is a
7913 criterion keyword, and the following element is the callback to
7914 call
7915
7916 :line - called whenever the line number changes
7917 :token - called for each new token consumed
7918
7919 The list of criteria could be extended to include entering or
7920 leaving a statement, an expression, or a function definition."
7921 (if (and cb (not (functionp cb)))
7922 (error "criteria callbacks not yet implemented"))
7923 (let ((inhibit-point-motion-hooks t)
7924 (js2-compiler-xml-available (>= js2-language-version 160))
7925 ;; This is a recursive-descent parser, so give it a big stack.
7926 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7927 (max-specpdl-size (max max-specpdl-size 3000))
7928 (case-fold-search nil)
7929 ast)
7930 (with-current-buffer (or buf (current-buffer))
7931 (setq js2-scanned-comments nil
7932 js2-parsed-errors nil
7933 js2-parsed-warnings nil
7934 js2-imenu-recorder nil
7935 js2-imenu-function-map nil
7936 js2-label-set nil)
7937 (js2-init-scanner)
7938 (setq ast (js2-do-parse))
7939 (unless js2-ts-hit-eof
7940 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7941 (setf (js2-ast-root-errors ast) js2-parsed-errors
7942 (js2-ast-root-warnings ast) js2-parsed-warnings)
7943 ;; if we didn't find any declarations, put a dummy in this list so we
7944 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7945 (unless js2-imenu-recorder
7946 (setq js2-imenu-recorder 'empty))
7947 (run-hooks 'js2-parse-finished-hook)
7948 ast)))
7949
7950 ;; Corresponds to Rhino's Parser.parse() method.
7951 (defun js2-do-parse ()
7952 "Parse current buffer starting from current point.
7953 Scanner should be initialized."
7954 (let ((pos js2-ts-cursor)
7955 (end js2-ts-cursor) ; in case file is empty
7956 root n tt
7957 (in-directive-prologue t)
7958 (saved-strict-mode js2-in-use-strict-directive)
7959 directive)
7960 ;; initialize buffer-local parsing vars
7961 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7962 js2-current-script-or-fn root
7963 js2-current-scope root
7964 js2-nesting-of-function 0
7965 js2-labeled-stmt nil
7966 js2-recorded-identifiers nil ; for js2-highlight
7967 js2-in-use-strict-directive nil)
7968 (while (/= (setq tt (js2-get-token)) js2-EOF)
7969 (if (= tt js2-FUNCTION)
7970 (progn
7971 (setq n (if js2-called-by-compile-function
7972 (js2-parse-function-expr)
7973 (js2-parse-function-stmt))))
7974 ;; not a function - parse a statement
7975 (js2-unget-token)
7976 (setq n (js2-parse-statement))
7977 (when in-directive-prologue
7978 (setq directive (js2-get-directive n))
7979 (cond
7980 ((null directive)
7981 (setq in-directive-prologue nil))
7982 ((string= directive "use strict")
7983 (setq js2-in-use-strict-directive t)
7984 (setf (js2-ast-root-in-strict-mode root) t)))))
7985 ;; add function or statement to script
7986 (setq end (js2-node-end n))
7987 (js2-block-node-push root n))
7988 (setq js2-in-use-strict-directive saved-strict-mode)
7989 ;; add comments to root in lexical order
7990 (when js2-scanned-comments
7991 ;; if we find a comment beyond end of normal kids, use its end
7992 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7993 (dolist (comment js2-scanned-comments)
7994 (push comment (js2-ast-root-comments root))
7995 (js2-node-add-children root comment)))
7996 (setf (js2-node-len root) (- end pos))
7997 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7998 ;; Give extensions a chance to muck with things before highlighting starts.
7999 (let ((js2-additional-externs js2-additional-externs))
8000 (save-excursion
8001 (run-hooks 'js2-post-parse-callbacks))
8002 (js2-highlight-undeclared-vars))
8003 root))
8004
8005 (defun js2-parse-function-closure-body (fn-node)
8006 "Parse a JavaScript 1.8 function closure body."
8007 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
8008 (if js2-ts-hit-eof
8009 (js2-report-error "msg.no.brace.body" nil
8010 (js2-node-pos fn-node)
8011 (- js2-ts-cursor (js2-node-pos fn-node)))
8012 (js2-node-add-children fn-node
8013 (setf (js2-function-node-body fn-node)
8014 (js2-parse-expr t))))))
8015
8016 (defun js2-parse-function-body (fn-node)
8017 (js2-must-match js2-LC "msg.no.brace.body"
8018 (js2-node-pos fn-node)
8019 (- js2-ts-cursor (js2-node-pos fn-node)))
8020 (let ((pos (js2-current-token-beg)) ; LC position
8021 (pn (make-js2-block-node)) ; starts at LC position
8022 tt
8023 end
8024 not-in-directive-prologue
8025 (saved-strict-mode js2-in-use-strict-directive)
8026 node
8027 directive)
8028 ;; Inherit strict mode.
8029 (setf (js2-function-node-in-strict-mode fn-node) js2-in-use-strict-directive)
8030 (cl-incf js2-nesting-of-function)
8031 (unwind-protect
8032 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
8033 (= tt js2-EOF)
8034 (= tt js2-RC)))
8035 (js2-block-node-push
8036 pn
8037 (if (/= tt js2-FUNCTION)
8038 (if not-in-directive-prologue
8039 (js2-parse-statement)
8040 (setq node (js2-parse-statement)
8041 directive (js2-get-directive node))
8042 (cond
8043 ((null directive)
8044 (setq not-in-directive-prologue t))
8045 ((string= directive "use strict")
8046 (setq js2-in-use-strict-directive t)
8047 (setf (js2-function-node-in-strict-mode fn-node) t)))
8048 node)
8049 (js2-get-token)
8050 (js2-parse-function-stmt))))
8051 (cl-decf js2-nesting-of-function)
8052 (setq js2-in-use-strict-directive saved-strict-mode))
8053 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
8054 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
8055 (setq end (js2-current-token-end)))
8056 (setf (js2-node-pos pn) pos
8057 (js2-node-len pn) (- end pos))
8058 (setf (js2-function-node-body fn-node) pn)
8059 (js2-node-add-children fn-node pn)
8060 pn))
8061
8062 (defun js2-define-destruct-symbols
8063 (node decl-type face &optional ignore-not-in-block name-nodes)
8064 "Declare and fontify destructuring parameters inside NODE.
8065 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
8066
8067 Return a list of `js2-name-node' nodes representing the symbols
8068 declared; probably to check them for errors."
8069 (cond
8070 ((js2-name-node-p node)
8071 (let (leftpos)
8072 (js2-define-symbol decl-type (js2-name-node-name node)
8073 node ignore-not-in-block)
8074 (when face
8075 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8076 (+ leftpos (js2-node-len node))
8077 face 'record))
8078 (setq name-nodes (append name-nodes (list node)))))
8079 ((js2-object-node-p node)
8080 (dolist (elem (js2-object-node-elems node))
8081 (setq name-nodes
8082 (append name-nodes
8083 (js2-define-destruct-symbols
8084 ;; In abbreviated destructuring {a, b}, right == left.
8085 (js2-object-prop-node-right elem)
8086 decl-type face ignore-not-in-block name-nodes)))))
8087 ((js2-array-node-p node)
8088 (dolist (elem (js2-array-node-elems node))
8089 (when elem
8090 (setq name-nodes
8091 (append name-nodes
8092 (js2-define-destruct-symbols
8093 elem decl-type face ignore-not-in-block name-nodes))))))
8094 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8095 (js2-node-len node))))
8096 name-nodes)
8097
8098 (defun js2-check-strict-identifier (name-node)
8099 "Check that NAME-NODE makes a legal strict mode identifier."
8100 (when js2-in-use-strict-directive
8101 (let ((param-name (js2-name-node-name name-node)))
8102 (when (or (string= param-name "eval")
8103 (string= param-name "arguments"))
8104 (js2-report-error "msg.bad.id.strict" param-name
8105 (js2-node-abs-pos name-node) (js2-node-len name-node))))))
8106
8107 (defun js2-check-strict-function-params (preceding-params params)
8108 "Given PRECEDING-PARAMS in a function's parameter list, check
8109 for strict mode errors caused by PARAMS."
8110 (when js2-in-use-strict-directive
8111 (dolist (param params)
8112 (let ((param-name (js2-name-node-name param)))
8113 (js2-check-strict-identifier param)
8114 (when (cl-some (lambda (param)
8115 (string= (js2-name-node-name param)
8116 param-name))
8117 preceding-params)
8118 (js2-report-error "msg.dup.param.strict" param-name
8119 (js2-node-abs-pos param) (js2-node-len param)))))))
8120
8121 (defun js2-parse-function-params (function-type fn-node pos)
8122 "Parse the parameters of a function of FUNCTION-TYPE
8123 represented by FN-NODE at POS.
8124
8125 Return a list of lists of arguments to apply many times to
8126 `js2-check-strict-function-params' to retroactively check for
8127 strict mode errors that occurred. Because the function body is
8128 parsed after its parameters, and the body might activate strict
8129 mode for that function, the check has to occur after the body is
8130 parsed."
8131 (if (js2-match-token js2-RP)
8132 (progn (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8133 ;; Return an empty list for consistency.
8134 '())
8135 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8136 (eq (js2-current-token-type) js2-NAME)))
8137 params param
8138 param-name-nodes new-param-name-nodes
8139 deferred-error-checking-arguments
8140 default-found rest-param-at)
8141 (when paren-free-arrow
8142 (js2-unget-token))
8143 (cl-loop for tt = (js2-peek-token)
8144 do
8145 (cond
8146 ;; destructuring param
8147 ((and (not paren-free-arrow)
8148 (or (= tt js2-LB) (= tt js2-LC)))
8149 (js2-get-token)
8150 (when default-found
8151 (js2-report-error "msg.no.default.after.default.param"))
8152 (setq param (js2-parse-destruct-primary-expr))
8153 (setq new-param-name-nodes (js2-define-destruct-symbols
8154 param js2-LP 'js2-function-param))
8155 (setq deferred-error-checking-arguments
8156 (append deferred-error-checking-arguments
8157 (list (list param-name-nodes
8158 new-param-name-nodes))))
8159 (setq param-name-nodes (append param-name-nodes new-param-name-nodes))
8160 (push param params))
8161 ;; variable name
8162 (t
8163 (when (and (>= js2-language-version 200)
8164 (not paren-free-arrow)
8165 (js2-match-token js2-TRIPLEDOT)
8166 (not rest-param-at))
8167 ;; to report errors if there are more parameters
8168 (setq rest-param-at (length params)))
8169 (js2-must-match-name "msg.no.parm")
8170 (js2-record-face 'js2-function-param)
8171 (setq param (js2-create-name-node))
8172 (js2-define-symbol js2-LP (js2-current-token-string) param)
8173 (setq deferred-error-checking-arguments
8174 (append deferred-error-checking-arguments
8175 (list (list param-name-nodes
8176 (list param)))))
8177 (setq param-name-nodes (append param-name-nodes (list param)))
8178 ;; default parameter value
8179 (when (or (and default-found
8180 (not rest-param-at)
8181 (js2-must-match js2-ASSIGN
8182 "msg.no.default.after.default.param"
8183 (js2-node-pos param)
8184 (js2-node-len param)))
8185 (and (>= js2-language-version 200)
8186 (js2-match-token js2-ASSIGN)))
8187 (cl-assert (not paren-free-arrow))
8188 (let* ((pos (js2-node-pos param))
8189 (tt (js2-current-token-type))
8190 (op-pos (- (js2-current-token-beg) pos))
8191 (left param)
8192 (right (js2-parse-assign-expr))
8193 (len (- (js2-node-end right) pos)))
8194 (setq param (make-js2-assign-node
8195 :type tt :pos pos :len len :op-pos op-pos
8196 :left left :right right)
8197 default-found t)
8198 (js2-node-add-children param left right)))
8199 (push param params)))
8200 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8201 (js2-report-error "msg.param.after.rest" nil
8202 (js2-node-pos param) (js2-node-len param)))
8203 while
8204 (js2-match-token js2-COMMA))
8205 (when (and (not paren-free-arrow)
8206 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8207 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8208 (when rest-param-at
8209 (setf (js2-function-node-rest-p fn-node) t))
8210 (dolist (p params)
8211 (js2-node-add-children fn-node p)
8212 (push p (js2-function-node-params fn-node)))
8213 deferred-error-checking-arguments)))
8214
8215 (defun js2-check-inconsistent-return-warning (fn-node name)
8216 "Possibly show inconsistent-return warning.
8217 Last token scanned is the close-curly for the function body."
8218 (when (and js2-mode-show-strict-warnings
8219 js2-strict-inconsistent-return-warning
8220 (not (js2-has-consistent-return-usage
8221 (js2-function-node-body fn-node))))
8222 ;; Have it extend from close-curly to bol or beginning of block.
8223 (let ((pos (save-excursion
8224 (goto-char (js2-current-token-end))
8225 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8226 (point-at-bol))))
8227 (end (js2-current-token-end)))
8228 (if (cl-plusp (js2-name-node-length name))
8229 (js2-add-strict-warning "msg.no.return.value"
8230 (js2-name-node-name name) pos end)
8231 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8232
8233 (defun js2-parse-function-stmt ()
8234 (let ((pos (js2-current-token-beg))
8235 (star-p (js2-match-token js2-MUL)))
8236 (js2-must-match-name "msg.unnamed.function.stmt")
8237 (let ((name (js2-create-name-node t))
8238 pn member-expr)
8239 (cond
8240 ((js2-match-token js2-LP)
8241 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8242 (js2-allow-member-expr-as-function-name
8243 (setq member-expr (js2-parse-member-expr-tail nil name))
8244 (js2-parse-highlight-member-expr-fn-name member-expr)
8245 (js2-must-match js2-LP "msg.no.paren.parms")
8246 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8247 (js2-function-node-member-expr pn) member-expr)
8248 pn)
8249 (t
8250 (js2-report-error "msg.no.paren.parms")
8251 (make-js2-error-node))))))
8252
8253 (defun js2-parse-function-expr ()
8254 (let ((pos (js2-current-token-beg))
8255 (star-p (js2-match-token js2-MUL))
8256 name)
8257 (when (js2-match-token js2-NAME)
8258 (setq name (js2-create-name-node t)))
8259 (js2-must-match js2-LP "msg.no.paren.parms")
8260 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8261
8262 (defun js2-parse-function (function-type pos star-p &optional name)
8263 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8264 beginning of the first token (function keyword, unless it's an
8265 arrow function), NAME is js2-name-node."
8266 (let (fn-node lp)
8267 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8268 (setq lp (js2-current-token-beg)))
8269 (setf fn-node (make-js2-function-node :pos pos
8270 :name name
8271 :form function-type
8272 :lp (if lp (- lp pos))
8273 :generator-type (and star-p 'STAR)))
8274 (when name
8275 (js2-set-face (js2-node-pos name) (js2-node-end name)
8276 'font-lock-function-name-face 'record)
8277 (when (and (eq function-type 'FUNCTION_STATEMENT)
8278 (cl-plusp (js2-name-node-length name)))
8279 ;; Function statements define a symbol in the enclosing scope
8280 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
8281 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8282 ;; 1. Nested functions are not affected by the dynamic scope flag
8283 ;; as dynamic scope is already a parent of their scope.
8284 ;; 2. Functions defined under the with statement also immune to
8285 ;; this setup, in which case dynamic scope is ignored in favor
8286 ;; of the with object.
8287 (setf (js2-function-node-ignore-dynamic fn-node) t))
8288 ;; dynamically bind all the per-function variables
8289 (let ((js2-current-script-or-fn fn-node)
8290 (js2-current-scope fn-node)
8291 (js2-nesting-of-with 0)
8292 (js2-end-flags 0)
8293 js2-label-set
8294 js2-loop-set
8295 js2-loop-and-switch-set
8296 deferred-error-checking-arguments)
8297 (setq deferred-error-checking-arguments
8298 (js2-parse-function-params function-type fn-node pos))
8299 (when (eq function-type 'FUNCTION_ARROW)
8300 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8301 (if (and (>= js2-language-version 180)
8302 (/= (js2-peek-token) js2-LC))
8303 (js2-parse-function-closure-body fn-node)
8304 (js2-parse-function-body fn-node))
8305 (when (js2-function-node-in-strict-mode fn-node)
8306 ;; Pretend that we're inside the function again. It cleans up its
8307 ;; `js2-in-use-strict-directive' binding.
8308 (let ((js2-in-use-strict-directive t))
8309 (when name
8310 (js2-check-strict-identifier name))
8311 (dolist (arguments deferred-error-checking-arguments)
8312 (apply #'js2-check-strict-function-params arguments))))
8313 (js2-check-inconsistent-return-warning fn-node name)
8314
8315 (when name
8316 (js2-node-add-children fn-node name)
8317 ;; Function expressions define a name only in the body of the
8318 ;; function, and only if not hidden by a parameter name
8319 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8320 (null (js2-scope-get-symbol js2-current-scope
8321 (js2-name-node-name name))))
8322 (js2-define-symbol js2-FUNCTION
8323 (js2-name-node-name name)
8324 fn-node))
8325 (when (eq function-type 'FUNCTION_STATEMENT)
8326 (js2-record-imenu-functions fn-node))))
8327
8328 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8329 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8330 ;; We wait until after parsing the function to set its parent scope,
8331 ;; since `js2-define-symbol' needs the defining-scope check to stop
8332 ;; at the function boundary when checking for redeclarations.
8333 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8334 fn-node))
8335
8336 (defun js2-parse-statements (&optional parent)
8337 "Parse a statement list. Last token consumed must be js2-LC.
8338
8339 PARENT can be a `js2-block-node', in which case the statements are
8340 appended to PARENT. Otherwise a new `js2-block-node' is created
8341 and returned.
8342
8343 This function does not match the closing js2-RC: the caller
8344 matches the RC so it can provide a suitable error message if not
8345 matched. This means it's up to the caller to set the length of
8346 the node to include the closing RC. The node start pos is set to
8347 the absolute buffer start position, and the caller should fix it
8348 up to be relative to the parent node. All children of this block
8349 node are given relative start positions and correct lengths."
8350 (let ((pn (or parent (make-js2-block-node)))
8351 tt)
8352 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8353 (/= tt js2-RC))
8354 (js2-block-node-push pn (js2-parse-statement)))
8355 pn))
8356
8357 (defun js2-parse-statement ()
8358 (let (pn beg end)
8359 ;; coarse-grained user-interrupt check - needs work
8360 (and js2-parse-interruptable-p
8361 (zerop (% (cl-incf js2-parse-stmt-count)
8362 js2-statements-per-pause))
8363 (input-pending-p)
8364 (throw 'interrupted t))
8365 (setq pn (js2-statement-helper))
8366 ;; no-side-effects warning check
8367 (unless (js2-node-has-side-effects pn)
8368 (setq end (js2-node-end pn))
8369 (save-excursion
8370 (goto-char end)
8371 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8372 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8373 pn))
8374
8375 ;; These correspond to the switch cases in Parser.statementHelper
8376 (defconst js2-parsers
8377 (let ((parsers (make-vector js2-num-tokens
8378 #'js2-parse-expr-stmt)))
8379 (aset parsers js2-BREAK #'js2-parse-break)
8380 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8381 (aset parsers js2-CONST #'js2-parse-const-var)
8382 (aset parsers js2-CONTINUE #'js2-parse-continue)
8383 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8384 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8385 (aset parsers js2-DO #'js2-parse-do)
8386 (aset parsers js2-EXPORT #'js2-parse-export)
8387 (aset parsers js2-FOR #'js2-parse-for)
8388 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8389 (aset parsers js2-IF #'js2-parse-if)
8390 (aset parsers js2-IMPORT #'js2-parse-import)
8391 (aset parsers js2-LC #'js2-parse-block)
8392 (aset parsers js2-LET #'js2-parse-let-stmt)
8393 (aset parsers js2-NAME #'js2-parse-name-or-label)
8394 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8395 (aset parsers js2-SEMI #'js2-parse-semi)
8396 (aset parsers js2-SWITCH #'js2-parse-switch)
8397 (aset parsers js2-THROW #'js2-parse-throw)
8398 (aset parsers js2-TRY #'js2-parse-try)
8399 (aset parsers js2-VAR #'js2-parse-const-var)
8400 (aset parsers js2-WHILE #'js2-parse-while)
8401 (aset parsers js2-WITH #'js2-parse-with)
8402 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8403 parsers)
8404 "A vector mapping token types to parser functions.")
8405
8406 (defun js2-parse-warn-missing-semi (beg end)
8407 (and js2-mode-show-strict-warnings
8408 js2-strict-missing-semi-warning
8409 (js2-add-strict-warning
8410 "msg.missing.semi" nil
8411 ;; back up to beginning of statement or line
8412 (max beg (save-excursion
8413 (goto-char end)
8414 (point-at-bol)))
8415 end)))
8416
8417 (defconst js2-no-semi-insertion
8418 (list js2-IF
8419 js2-SWITCH
8420 js2-WHILE
8421 js2-DO
8422 js2-FOR
8423 js2-TRY
8424 js2-WITH
8425 js2-LC
8426 js2-ERROR
8427 js2-SEMI
8428 js2-CLASS
8429 js2-FUNCTION
8430 js2-EXPORT)
8431 "List of tokens that don't do automatic semicolon insertion.")
8432
8433 (defconst js2-autoinsert-semi-and-warn
8434 (list js2-ERROR js2-EOF js2-RC))
8435
8436 (defun js2-statement-helper ()
8437 (let* ((tt (js2-get-token))
8438 (first-tt tt)
8439 (parser (if (= tt js2-ERROR)
8440 #'js2-parse-semi
8441 (aref js2-parsers tt)))
8442 pn)
8443 ;; If the statement is set, then it's been told its label by now.
8444 (and js2-labeled-stmt
8445 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8446 (setq js2-labeled-stmt nil))
8447 (setq pn (funcall parser))
8448 ;; Don't do auto semi insertion for certain statement types.
8449 (unless (or (memq first-tt js2-no-semi-insertion)
8450 (js2-labeled-stmt-node-p pn))
8451 (js2-auto-insert-semicolon pn))
8452 pn))
8453
8454 (defun js2-auto-insert-semicolon (pn)
8455 (let* ((tt (js2-get-token))
8456 (pos (js2-node-pos pn)))
8457 (cond
8458 ((= tt js2-SEMI)
8459 ;; extend the node bounds to include the semicolon.
8460 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8461 ((memq tt js2-autoinsert-semi-and-warn)
8462 (js2-unget-token) ; Not ';', do not consume.
8463 ;; Autoinsert ;
8464 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8465 (t
8466 (if (not (js2-token-follows-eol-p (js2-current-token)))
8467 ;; Report error if no EOL or autoinsert ';' otherwise
8468 (js2-report-error "msg.no.semi.stmt")
8469 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8470 (js2-unget-token) ; Not ';', do not consume.
8471 ))))
8472
8473 (defun js2-parse-condition ()
8474 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8475 The parens are discarded and the expression node is returned.
8476 The `pos' field of the return value is set to an absolute position
8477 that must be fixed up by the caller.
8478 Return value is a list (EXPR LP RP), with absolute paren positions."
8479 (let (pn lp rp)
8480 (if (js2-must-match js2-LP "msg.no.paren.cond")
8481 (setq lp (js2-current-token-beg)))
8482 (setq pn (js2-parse-expr))
8483 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8484 (setq rp (js2-current-token-beg)))
8485 ;; Report strict warning on code like "if (a = 7) ..."
8486 (if (and js2-strict-cond-assign-warning
8487 (js2-assign-node-p pn))
8488 (js2-add-strict-warning "msg.equal.as.assign" nil
8489 (js2-node-pos pn)
8490 (+ (js2-node-pos pn)
8491 (js2-node-len pn))))
8492 (list pn lp rp)))
8493
8494 (defun js2-parse-if ()
8495 "Parser for if-statement. Last matched token must be js2-IF."
8496 (let ((pos (js2-current-token-beg))
8497 cond if-true if-false else-pos end pn)
8498 (setq cond (js2-parse-condition)
8499 if-true (js2-parse-statement)
8500 if-false (if (js2-match-token js2-ELSE)
8501 (progn
8502 (setq else-pos (- (js2-current-token-beg) pos))
8503 (js2-parse-statement)))
8504 end (js2-node-end (or if-false if-true))
8505 pn (make-js2-if-node :pos pos
8506 :len (- end pos)
8507 :condition (car cond)
8508 :then-part if-true
8509 :else-part if-false
8510 :else-pos else-pos
8511 :lp (js2-relpos (cl-second cond) pos)
8512 :rp (js2-relpos (cl-third cond) pos)))
8513 (js2-node-add-children pn (car cond) if-true if-false)
8514 pn))
8515
8516 (defun js2-parse-import ()
8517 "Parse import statement. The current token must be js2-IMPORT."
8518 (unless (js2-ast-root-p js2-current-scope)
8519 (js2-report-error "msg.mod.import.decl.at.top.level"))
8520 (let ((beg (js2-current-token-beg)))
8521 (cond ((js2-match-token js2-STRING)
8522 (make-js2-import-node
8523 :pos beg
8524 :len (- (js2-current-token-end) beg)
8525 :module-id (js2-current-token-string)))
8526 (t
8527 (let* ((import-clause (js2-parse-import-clause))
8528 (from-clause (and import-clause (js2-parse-from-clause)))
8529 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8530 (node (make-js2-import-node
8531 :pos beg
8532 :len (- (js2-current-token-end) beg)
8533 :import import-clause
8534 :from from-clause
8535 :module-id module-id)))
8536 (when import-clause
8537 (js2-node-add-children node import-clause))
8538 (when from-clause
8539 (js2-node-add-children node from-clause))
8540 node)))))
8541
8542 (defun js2-parse-import-clause ()
8543 "Parse the bindings in an import statement.
8544 This can take many forms:
8545
8546 ImportedDefaultBinding -> 'foo'
8547 NameSpaceImport -> '* as lib'
8548 NamedImports -> '{foo as bar, bang}'
8549 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8550 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8551
8552 Try to match namespace imports and named imports first because nothing can
8553 come after them. If it is an imported default binding, then it could have named
8554 imports or a namespace import that follows it.
8555 "
8556 (let* ((beg (js2-current-token-beg))
8557 (clause (make-js2-import-clause-node
8558 :pos beg))
8559 (children (list)))
8560 (cond
8561 ((js2-match-token js2-MUL)
8562 (let ((ns-import (js2-parse-namespace-import)))
8563 (when ns-import
8564 (let ((name-node (js2-namespace-import-node-name ns-import)))
8565 (js2-define-symbol
8566 js2-LET (js2-name-node-name name-node) name-node t)))
8567 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8568 (push ns-import children)))
8569 ((js2-match-token js2-LC)
8570 (let ((imports (js2-parse-export-bindings t)))
8571 (setf (js2-import-clause-node-named-imports clause) imports)
8572 (dolist (import imports)
8573 (push import children)
8574 (let ((name-node (js2-export-binding-node-local-name import)))
8575 (when name-node
8576 (js2-define-symbol
8577 js2-LET (js2-name-node-name name-node) name-node t))))))
8578 ((= (js2-peek-token) js2-NAME)
8579 (let ((binding (js2-maybe-parse-export-binding)))
8580 (let ((node-name (js2-export-binding-node-local-name binding)))
8581 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8582 (setf (js2-import-clause-node-default-binding clause) binding)
8583 (push binding children))
8584 (when (js2-match-token js2-COMMA)
8585 (cond
8586 ((js2-match-token js2-MUL)
8587 (let ((ns-import (js2-parse-namespace-import)))
8588 (let ((name-node (js2-namespace-import-node-name ns-import)))
8589 (js2-define-symbol
8590 js2-LET (js2-name-node-name name-node) name-node t))
8591 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8592 (push ns-import children)))
8593 ((js2-match-token js2-LC)
8594 (let ((imports (js2-parse-export-bindings t)))
8595 (setf (js2-import-clause-node-named-imports clause) imports)
8596 (dolist (import imports)
8597 (push import children)
8598 (let ((name-node (js2-export-binding-node-local-name import)))
8599 (when name-node
8600 (js2-define-symbol
8601 js2-LET (js2-name-node-name name-node) name-node t))))))
8602 (t (js2-report-error "msg.syntax")))))
8603 (t (js2-report-error "msg.mod.declaration.after.import")))
8604 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8605 (apply #'js2-node-add-children clause children)
8606 clause))
8607
8608 (defun js2-parse-namespace-import ()
8609 "Parse a namespace import expression such as '* as bar'.
8610 The current token must be js2-MUL."
8611 (let ((beg (js2-current-token-beg)))
8612 (when (js2-must-match js2-NAME "msg.syntax")
8613 (if (equal "as" (js2-current-token-string))
8614 (when (js2-must-match-prop-name "msg.syntax")
8615 (let ((node (make-js2-namespace-import-node
8616 :pos beg
8617 :len (- (js2-current-token-end) beg)
8618 :name (make-js2-name-node
8619 :pos (js2-current-token-beg)
8620 :len (js2-current-token-end)
8621 :name (js2-current-token-string)))))
8622 (js2-node-add-children node (js2-namespace-import-node-name node))
8623 node))
8624 (js2-unget-token)
8625 (js2-report-error "msg.syntax")))))
8626
8627
8628 (defun js2-parse-from-clause ()
8629 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8630 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8631 (let ((beg (js2-current-token-beg)))
8632 (if (equal "from" (js2-current-token-string))
8633 (cond
8634 ((js2-match-token js2-STRING)
8635 (make-js2-from-clause-node
8636 :pos beg
8637 :len (- (js2-current-token-end) beg)
8638 :module-id (js2-current-token-string)
8639 :metadata-p nil))
8640 ((js2-match-token js2-THIS)
8641 (when (js2-must-match-name "msg.mod.spec.after.from")
8642 (if (equal "module" (js2-current-token-string))
8643 (make-js2-from-clause-node
8644 :pos beg
8645 :len (- (js2-current-token-end) beg)
8646 :module-id "this"
8647 :metadata-p t)
8648 (js2-unget-token)
8649 (js2-unget-token)
8650 (js2-report-error "msg.mod.spec.after.from")
8651 nil)))
8652 (t (js2-report-error "msg.mod.spec.after.from") nil))
8653 (js2-unget-token)
8654 (js2-report-error "msg.mod.from.after.import.spec.set")
8655 nil))))
8656
8657 (defun js2-parse-export-bindings (&optional import-p)
8658 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8659 {foo as bar, baz as bang}. The current token must be
8660 js2-LC. Return a lisp list of js2-export-binding-node"
8661 (let ((bindings (list)))
8662 (while
8663 (let ((binding (js2-maybe-parse-export-binding)))
8664 (when binding
8665 (push binding bindings))
8666 (js2-match-token js2-COMMA)))
8667 (when (js2-must-match js2-RC (if import-p
8668 "msg.mod.rc.after.import.spec.list"
8669 "msg.mod.rc.after.export.spec.list"))
8670 (reverse bindings))))
8671
8672 (defun js2-maybe-parse-export-binding ()
8673 "Attempt to parse a binding expression found inside an import/export statement.
8674 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8675 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8676 js2-export-binding-node and consume all the tokens. If it does not match, it
8677 consumes no tokens."
8678 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8679 (beg (js2-current-token-beg))
8680 (extern-name-len (js2-current-token-len))
8681 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8682 (aref js2-kwd-tokens (js2-current-token-type)))))
8683 (if extern-name
8684 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8685 (if (and as (equal "as" (js2-current-token-string)))
8686 (let ((name
8687 (or
8688 (and (js2-match-token js2-DEFAULT) "default")
8689 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8690 (if name
8691 (let ((node (make-js2-export-binding-node
8692 :pos beg
8693 :len (- (js2-current-token-end) beg)
8694 :local-name (make-js2-name-node
8695 :name name
8696 :pos (js2-current-token-beg)
8697 :len (js2-current-token-len))
8698 :extern-name (make-js2-name-node
8699 :name extern-name
8700 :pos beg
8701 :len extern-name-len))))
8702 (js2-node-add-children
8703 node
8704 (js2-export-binding-node-local-name node)
8705 (js2-export-binding-node-extern-name node))
8706 node)
8707 (js2-unget-token)
8708 nil))
8709 (when as (js2-unget-token))
8710 (let* ((name-node (make-js2-name-node
8711 :name (js2-current-token-string)
8712 :pos (js2-current-token-beg)
8713 :len (js2-current-token-len)))
8714 (node (make-js2-export-binding-node
8715 :pos (js2-current-token-beg)
8716 :len (js2-current-token-len)
8717 :local-name name-node
8718 :extern-name name-node)))
8719 (when is-reserved-name
8720 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8721 (js2-node-add-children node name-node)
8722 node)))
8723 nil)))
8724
8725 (defun js2-parse-switch ()
8726 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8727 (let ((pos (js2-current-token-beg))
8728 tt pn discriminant has-default case-expr case-node
8729 case-pos cases stmt lp)
8730 (if (js2-must-match js2-LP "msg.no.paren.switch")
8731 (setq lp (js2-current-token-beg)))
8732 (setq discriminant (js2-parse-expr)
8733 pn (make-js2-switch-node :discriminant discriminant
8734 :pos pos
8735 :lp (js2-relpos lp pos)))
8736 (js2-node-add-children pn discriminant)
8737 (js2-enter-switch pn)
8738 (unwind-protect
8739 (progn
8740 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8741 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8742 (js2-must-match js2-LC "msg.no.brace.switch")
8743 (catch 'break
8744 (while t
8745 (setq tt (js2-next-token)
8746 case-pos (js2-current-token-beg))
8747 (cond
8748 ((= tt js2-RC)
8749 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8750 (throw 'break nil)) ; done
8751 ((= tt js2-CASE)
8752 (setq case-expr (js2-parse-expr))
8753 (js2-must-match js2-COLON "msg.no.colon.case"))
8754 ((= tt js2-DEFAULT)
8755 (if has-default
8756 (js2-report-error "msg.double.switch.default"))
8757 (setq has-default t
8758 case-expr nil)
8759 (js2-must-match js2-COLON "msg.no.colon.case"))
8760 (t
8761 (js2-report-error "msg.bad.switch")
8762 (throw 'break nil)))
8763 (setq case-node (make-js2-case-node :pos case-pos
8764 :len (- (js2-current-token-end) case-pos)
8765 :expr case-expr))
8766 (js2-node-add-children case-node case-expr)
8767 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8768 (/= tt js2-CASE)
8769 (/= tt js2-DEFAULT)
8770 (/= tt js2-EOF))
8771 (setf stmt (js2-parse-statement)
8772 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8773 (js2-block-node-push case-node stmt))
8774 (push case-node cases)))
8775 ;; add cases last, as pushing reverses the order to be correct
8776 (dolist (kid cases)
8777 (js2-node-add-children pn kid)
8778 (push kid (js2-switch-node-cases pn)))
8779 pn) ; return value
8780 (js2-exit-switch))))
8781
8782 (defun js2-parse-while ()
8783 "Parser for while-statement. Last matched token must be js2-WHILE."
8784 (let ((pos (js2-current-token-beg))
8785 (pn (make-js2-while-node))
8786 cond body)
8787 (js2-enter-loop pn)
8788 (unwind-protect
8789 (progn
8790 (setf cond (js2-parse-condition)
8791 (js2-while-node-condition pn) (car cond)
8792 body (js2-parse-statement)
8793 (js2-while-node-body pn) body
8794 (js2-node-len pn) (- (js2-node-end body) pos)
8795 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8796 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8797 (js2-node-add-children pn body (car cond)))
8798 (js2-exit-loop))
8799 pn))
8800
8801 (defun js2-parse-do ()
8802 "Parser for do-statement. Last matched token must be js2-DO."
8803 (let ((pos (js2-current-token-beg))
8804 (pn (make-js2-do-node))
8805 cond body end)
8806 (js2-enter-loop pn)
8807 (unwind-protect
8808 (progn
8809 (setq body (js2-parse-statement))
8810 (js2-must-match js2-WHILE "msg.no.while.do")
8811 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8812 cond (js2-parse-condition)
8813 (js2-do-node-condition pn) (car cond)
8814 (js2-do-node-body pn) body
8815 end js2-ts-cursor
8816 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8817 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8818 (js2-node-add-children pn (car cond) body))
8819 (js2-exit-loop))
8820 ;; Always auto-insert semicolon to follow SpiderMonkey:
8821 ;; It is required by ECMAScript but is ignored by the rest of
8822 ;; world; see bug 238945
8823 (if (js2-match-token js2-SEMI)
8824 (setq end js2-ts-cursor))
8825 (setf (js2-node-len pn) (- end pos))
8826 pn))
8827
8828 (defun js2-parse-export ()
8829 "Parse an export statement.
8830 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8831 expressions should only be either hoistable expressions (function or generator)
8832 or assignment expressions, but there is no checking to enforce that and so it
8833 will parse without error a small subset of
8834 invalid export statements."
8835 (unless (js2-ast-root-p js2-current-scope)
8836 (js2-report-error "msg.mod.export.decl.at.top.level"))
8837 (let ((beg (js2-current-token-beg))
8838 (children (list))
8839 exports-list from-clause declaration default)
8840 (cond
8841 ((js2-match-token js2-MUL)
8842 (setq from-clause (js2-parse-from-clause))
8843 (when from-clause
8844 (push from-clause children)))
8845 ((js2-match-token js2-LC)
8846 (setq exports-list (js2-parse-export-bindings))
8847 (when exports-list
8848 (dolist (export exports-list)
8849 (push export children)))
8850 (when (js2-match-token js2-NAME)
8851 (if (equal "from" (js2-current-token-string))
8852 (progn
8853 (js2-unget-token)
8854 (setq from-clause (js2-parse-from-clause)))
8855 (js2-unget-token))))
8856 ((js2-match-token js2-DEFAULT)
8857 (setq default (js2-parse-expr)))
8858 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8859 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8860 (t
8861 (setq declaration (js2-parse-expr))))
8862 (when from-clause
8863 (push from-clause children))
8864 (when declaration
8865 (push declaration children)
8866 (when (not (js2-function-node-p declaration))
8867 (js2-auto-insert-semicolon declaration)))
8868 (when default
8869 (push default children)
8870 (when (not (js2-function-node-p default))
8871 (js2-auto-insert-semicolon default)))
8872 (let ((node (make-js2-export-node
8873 :pos beg
8874 :len (- (js2-current-token-end) beg)
8875 :exports-list exports-list
8876 :from-clause from-clause
8877 :declaration declaration
8878 :default default)))
8879 (apply #'js2-node-add-children node children)
8880 node)))
8881
8882 (defun js2-parse-for ()
8883 "Parse a for, for-in or for each-in statement.
8884 Last matched token must be js2-FOR."
8885 (let ((for-pos (js2-current-token-beg))
8886 (tmp-scope (make-js2-scope))
8887 pn is-for-each is-for-in-or-of is-for-of
8888 in-pos each-pos tmp-pos
8889 init ; Node init is also foo in 'foo in object'.
8890 cond ; Node cond is also object in 'foo in object'.
8891 incr ; 3rd section of for-loop initializer.
8892 body tt lp rp)
8893 ;; See if this is a for each () instead of just a for ()
8894 (when (js2-match-token js2-NAME)
8895 (if (string= "each" (js2-current-token-string))
8896 (progn
8897 (setq is-for-each t
8898 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8899 (js2-record-face 'font-lock-keyword-face))
8900 (js2-report-error "msg.no.paren.for")))
8901 (if (js2-must-match js2-LP "msg.no.paren.for")
8902 (setq lp (- (js2-current-token-beg) for-pos)))
8903 (setq tt (js2-get-token))
8904 ;; Capture identifiers inside parens. We can't create the node
8905 ;; (and use it as the current scope) until we know its type.
8906 (js2-push-scope tmp-scope)
8907 (unwind-protect
8908 (progn
8909 ;; parse init clause
8910 (let ((js2-in-for-init t)) ; set as dynamic variable
8911 (cond
8912 ((= tt js2-SEMI)
8913 (js2-unget-token)
8914 (setq init (make-js2-empty-expr-node)))
8915 ((or (= tt js2-VAR) (= tt js2-LET))
8916 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8917 (t
8918 (js2-unget-token)
8919 (setq init (js2-parse-expr)))))
8920 (if (or (js2-match-token js2-IN)
8921 (and (>= js2-language-version 200)
8922 (js2-match-contextual-kwd "of")
8923 (setq is-for-of t)))
8924 (setq is-for-in-or-of t
8925 in-pos (- (js2-current-token-beg) for-pos)
8926 ;; scope of iteration target object is not the scope we've created above.
8927 ;; stash current scope temporary.
8928 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8929 (js2-parse-expr))) ; object over which we're iterating
8930 ;; else ordinary for loop - parse cond and incr
8931 (js2-must-match js2-SEMI "msg.no.semi.for")
8932 (setq cond (if (= (js2-peek-token) js2-SEMI)
8933 (make-js2-empty-expr-node) ; no loop condition
8934 (js2-parse-expr)))
8935 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8936 (setq tmp-pos (js2-current-token-end)
8937 incr (if (= (js2-peek-token) js2-RP)
8938 (make-js2-empty-expr-node :pos tmp-pos)
8939 (js2-parse-expr)))))
8940 (js2-pop-scope))
8941 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8942 (setq rp (- (js2-current-token-beg) for-pos)))
8943 (if (not is-for-in-or-of)
8944 (setq pn (make-js2-for-node :init init
8945 :condition cond
8946 :update incr
8947 :lp lp
8948 :rp rp))
8949 ;; cond could be null if 'in obj' got eaten by the init node.
8950 (if (js2-infix-node-p init)
8951 ;; it was (foo in bar) instead of (var foo in bar)
8952 (setq cond (js2-infix-node-right init)
8953 init (js2-infix-node-left init))
8954 (if (and (js2-var-decl-node-p init)
8955 (> (length (js2-var-decl-node-kids init)) 1))
8956 (js2-report-error "msg.mult.index")))
8957 (setq pn (make-js2-for-in-node :iterator init
8958 :object cond
8959 :in-pos in-pos
8960 :foreach-p is-for-each
8961 :each-pos each-pos
8962 :forof-p is-for-of
8963 :lp lp
8964 :rp rp)))
8965 ;; Transplant the declarations.
8966 (setf (js2-scope-symbol-table pn)
8967 (js2-scope-symbol-table tmp-scope))
8968 (unwind-protect
8969 (progn
8970 (js2-enter-loop pn)
8971 ;; We have to parse the body -after- creating the loop node,
8972 ;; so that the loop node appears in the js2-loop-set, allowing
8973 ;; break/continue statements to find the enclosing loop.
8974 (setf body (js2-parse-statement)
8975 (js2-loop-node-body pn) body
8976 (js2-node-pos pn) for-pos
8977 (js2-node-len pn) (- (js2-node-end body) for-pos))
8978 (js2-node-add-children pn init cond incr body))
8979 ;; finally
8980 (js2-exit-loop))
8981 pn))
8982
8983 (defun js2-parse-try ()
8984 "Parse a try statement. Last matched token must be js2-TRY."
8985 (let ((try-pos (js2-current-token-beg))
8986 try-end
8987 try-block
8988 catch-blocks
8989 finally-block
8990 saw-default-catch
8991 peek)
8992 (if (/= (js2-peek-token) js2-LC)
8993 (js2-report-error "msg.no.brace.try"))
8994 (setq try-block (js2-parse-statement)
8995 try-end (js2-node-end try-block)
8996 peek (js2-peek-token))
8997 (cond
8998 ((= peek js2-CATCH)
8999 (while (js2-match-token js2-CATCH)
9000 (let* ((catch-pos (js2-current-token-beg))
9001 (catch-node (make-js2-catch-node :pos catch-pos))
9002 param
9003 guard-kwd
9004 catch-cond
9005 lp rp)
9006 (if saw-default-catch
9007 (js2-report-error "msg.catch.unreachable"))
9008 (if (js2-must-match js2-LP "msg.no.paren.catch")
9009 (setq lp (- (js2-current-token-beg) catch-pos)))
9010 (js2-push-scope catch-node)
9011 (let ((tt (js2-peek-token)))
9012 (cond
9013 ;; Destructuring pattern:
9014 ;; catch ({ message, file }) { ... }
9015 ((or (= tt js2-LB) (= tt js2-LC))
9016 (js2-get-token)
9017 (setq param (js2-parse-destruct-primary-expr))
9018 (js2-define-destruct-symbols param js2-LET nil))
9019 ;; Simple name.
9020 (t
9021 (js2-must-match-name "msg.bad.catchcond")
9022 (setq param (js2-create-name-node))
9023 (js2-define-symbol js2-LET (js2-current-token-string) param)
9024 (js2-check-strict-identifier param))))
9025 ;; Catch condition.
9026 (if (js2-match-token js2-IF)
9027 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
9028 catch-cond (js2-parse-expr))
9029 (setq saw-default-catch t))
9030 (if (js2-must-match js2-RP "msg.bad.catchcond")
9031 (setq rp (- (js2-current-token-beg) catch-pos)))
9032 (js2-must-match js2-LC "msg.no.brace.catchblock")
9033 (js2-parse-statements catch-node)
9034 (if (js2-must-match js2-RC "msg.no.brace.after.body")
9035 (setq try-end (js2-current-token-end)))
9036 (js2-pop-scope)
9037 (setf (js2-node-len catch-node) (- try-end catch-pos)
9038 (js2-catch-node-param catch-node) param
9039 (js2-catch-node-guard-expr catch-node) catch-cond
9040 (js2-catch-node-guard-kwd catch-node) guard-kwd
9041 (js2-catch-node-lp catch-node) lp
9042 (js2-catch-node-rp catch-node) rp)
9043 (js2-node-add-children catch-node param catch-cond)
9044 (push catch-node catch-blocks))))
9045 ((/= peek js2-FINALLY)
9046 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
9047 (js2-node-pos try-block)
9048 (- (setq try-end (js2-node-end try-block))
9049 (js2-node-pos try-block)))))
9050 (when (js2-match-token js2-FINALLY)
9051 (let ((finally-pos (js2-current-token-beg))
9052 (block (js2-parse-statement)))
9053 (setq try-end (js2-node-end block)
9054 finally-block (make-js2-finally-node :pos finally-pos
9055 :len (- try-end finally-pos)
9056 :body block))
9057 (js2-node-add-children finally-block block)))
9058 (let ((pn (make-js2-try-node :pos try-pos
9059 :len (- try-end try-pos)
9060 :try-block try-block
9061 :finally-block finally-block)))
9062 (js2-node-add-children pn try-block finally-block)
9063 ;; Push them onto the try-node, which reverses and corrects their order.
9064 (dolist (cb catch-blocks)
9065 (js2-node-add-children pn cb)
9066 (push cb (js2-try-node-catch-clauses pn)))
9067 pn)))
9068
9069 (defun js2-parse-throw ()
9070 "Parser for throw-statement. Last matched token must be js2-THROW."
9071 (let ((pos (js2-current-token-beg))
9072 expr pn)
9073 (if (= (js2-peek-token-or-eol) js2-EOL)
9074 ;; ECMAScript does not allow new lines before throw expression,
9075 ;; see bug 256617
9076 (js2-report-error "msg.bad.throw.eol"))
9077 (setq expr (js2-parse-expr)
9078 pn (make-js2-throw-node :pos pos
9079 :len (- (js2-node-end expr) pos)
9080 :expr expr))
9081 (js2-node-add-children pn expr)
9082 pn))
9083
9084 (defun js2-match-jump-label-name (label-name)
9085 "If break/continue specified a label, return that label's labeled stmt.
9086 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9087 does not match an existing label, reports an error and returns nil."
9088 (let ((bundle (cdr (assoc label-name js2-label-set))))
9089 (if (null bundle)
9090 (js2-report-error "msg.undef.label"))
9091 bundle))
9092
9093 (defun js2-parse-break ()
9094 "Parser for break-statement. Last matched token must be js2-BREAK."
9095 (let ((pos (js2-current-token-beg))
9096 (end (js2-current-token-end))
9097 break-target ; statement to break from
9098 break-label ; in "break foo", name-node representing the foo
9099 labels ; matching labeled statement to break to
9100 pn)
9101 (when (eq (js2-peek-token-or-eol) js2-NAME)
9102 (js2-get-token)
9103 (setq break-label (js2-create-name-node)
9104 end (js2-node-end break-label)
9105 ;; matchJumpLabelName only matches if there is one
9106 labels (js2-match-jump-label-name (js2-current-token-string))
9107 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9108 (unless (or break-target break-label)
9109 ;; no break target specified - try for innermost enclosing loop/switch
9110 (if (null js2-loop-and-switch-set)
9111 (unless break-label
9112 (js2-report-error "msg.bad.break" nil pos (length "break")))
9113 (setq break-target (car js2-loop-and-switch-set))))
9114 (setq pn (make-js2-break-node :pos pos
9115 :len (- end pos)
9116 :label break-label
9117 :target break-target))
9118 (js2-node-add-children pn break-label) ; but not break-target
9119 pn))
9120
9121 (defun js2-parse-continue ()
9122 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9123 (let ((pos (js2-current-token-beg))
9124 (end (js2-current-token-end))
9125 label ; optional user-specified label, a `js2-name-node'
9126 labels ; current matching labeled stmt, if any
9127 target ; the `js2-loop-node' target of this continue stmt
9128 pn)
9129 (when (= (js2-peek-token-or-eol) js2-NAME)
9130 (js2-get-token)
9131 (setq label (js2-create-name-node)
9132 end (js2-node-end label)
9133 ;; matchJumpLabelName only matches if there is one
9134 labels (js2-match-jump-label-name (js2-current-token-string))))
9135 (cond
9136 ((null labels) ; no current label to go to
9137 (if (null js2-loop-set) ; no loop to continue to
9138 (js2-report-error "msg.continue.outside" nil pos
9139 (length "continue"))
9140 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9141 (t
9142 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9143 (setq target (js2-labeled-stmt-node-stmt labels))
9144 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9145 (setq pn (make-js2-continue-node :pos pos
9146 :len (- end pos)
9147 :label label
9148 :target target))
9149 (js2-node-add-children pn label) ; but not target - it's not our child
9150 pn))
9151
9152 (defun js2-parse-with ()
9153 "Parser for with-statement. Last matched token must be js2-WITH."
9154 (when js2-in-use-strict-directive
9155 (js2-report-error "msg.no.with.strict"))
9156 (let ((pos (js2-current-token-beg))
9157 obj body pn lp rp)
9158 (if (js2-must-match js2-LP "msg.no.paren.with")
9159 (setq lp (js2-current-token-beg)))
9160 (setq obj (js2-parse-expr))
9161 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9162 (setq rp (js2-current-token-beg)))
9163 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9164 (setq body (js2-parse-statement)))
9165 (setq pn (make-js2-with-node :pos pos
9166 :len (- (js2-node-end body) pos)
9167 :object obj
9168 :body body
9169 :lp (js2-relpos lp pos)
9170 :rp (js2-relpos rp pos)))
9171 (js2-node-add-children pn obj body)
9172 pn))
9173
9174 (defun js2-parse-const-var ()
9175 "Parser for var- or const-statement.
9176 Last matched token must be js2-CONST or js2-VAR."
9177 (let ((tt (js2-current-token-type))
9178 (pos (js2-current-token-beg))
9179 expr pn)
9180 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9181 pn (make-js2-expr-stmt-node :pos pos
9182 :len (- (js2-node-end expr) pos)
9183 :expr expr))
9184 (js2-node-add-children pn expr)
9185 pn))
9186
9187 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9188 (let ((pn (make-js2-expr-stmt-node :pos pos
9189 :len (js2-node-len expr)
9190 :type (if (js2-inside-function)
9191 js2-EXPR_VOID
9192 js2-EXPR_RESULT)
9193 :expr expr)))
9194 (if add-child
9195 (js2-node-add-children pn expr))
9196 pn))
9197
9198 (defun js2-parse-let-stmt ()
9199 "Parser for let-statement. Last matched token must be js2-LET."
9200 (let ((pos (js2-current-token-beg))
9201 expr pn)
9202 (if (= (js2-peek-token) js2-LP)
9203 ;; let expression in statement context
9204 (setq expr (js2-parse-let pos 'statement)
9205 pn (js2-wrap-with-expr-stmt pos expr t))
9206 ;; else we're looking at a statement like let x=6, y=7;
9207 (setf expr (js2-parse-variables js2-LET pos)
9208 pn (js2-wrap-with-expr-stmt pos expr t)
9209 (js2-node-type pn) js2-EXPR_RESULT))
9210 pn))
9211
9212 (defun js2-parse-ret-yield ()
9213 (js2-parse-return-or-yield (js2-current-token-type) nil))
9214
9215 (defconst js2-parse-return-stmt-enders
9216 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9217
9218 (defsubst js2-now-all-set (before after mask)
9219 "Return whether or not the bits in the mask have changed to all set.
9220 BEFORE is bits before change, AFTER is bits after change, and MASK is
9221 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9222 but not BEFORE."
9223 (and (/= (logand before mask) mask)
9224 (= (logand after mask) mask)))
9225
9226 (defun js2-parse-return-or-yield (tt expr-context)
9227 (let* ((pos (js2-current-token-beg))
9228 (end (js2-current-token-end))
9229 (before js2-end-flags)
9230 (inside-function (js2-inside-function))
9231 (gen-type (and inside-function (js2-function-node-generator-type
9232 js2-current-script-or-fn)))
9233 e ret name yield-star-p)
9234 (unless inside-function
9235 (js2-report-error (if (eq tt js2-RETURN)
9236 "msg.bad.return"
9237 "msg.bad.yield")))
9238 (when (and inside-function
9239 (eq gen-type 'STAR)
9240 (js2-match-token js2-MUL))
9241 (setq yield-star-p t))
9242 ;; This is ugly, but we don't want to require a semicolon.
9243 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9244 (setq e (js2-parse-expr)
9245 end (js2-node-end e)))
9246 (cond
9247 ((eq tt js2-RETURN)
9248 (js2-set-flag js2-end-flags (if (null e)
9249 js2-end-returns
9250 js2-end-returns-value))
9251 (setq ret (make-js2-return-node :pos pos
9252 :len (- end pos)
9253 :retval e))
9254 (js2-node-add-children ret e)
9255 ;; See if we need a strict mode warning.
9256 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9257 ;; more thorough and accurate than this before/after flag check.
9258 ;; E.g. if there's a finally-block that always returns, we shouldn't
9259 ;; show a warning generated by inconsistent returns in the catch blocks.
9260 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9261 ;; so we know which returns/yields to highlight, and we should get rid of
9262 ;; all the checking in `js2-parse-return-or-yield'.
9263 (if (and js2-strict-inconsistent-return-warning
9264 (js2-now-all-set before js2-end-flags
9265 (logior js2-end-returns js2-end-returns-value)))
9266 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9267 ((eq gen-type 'COMPREHENSION)
9268 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9269 ;; like SpiderMonkey does.
9270 (js2-report-error "msg.syntax" nil pos 5))
9271 (t
9272 (setq ret (make-js2-yield-node :pos pos
9273 :len (- end pos)
9274 :value e
9275 :star-p yield-star-p))
9276 (js2-node-add-children ret e)
9277 (unless expr-context
9278 (setq e ret
9279 ret (js2-wrap-with-expr-stmt pos e t))
9280 (js2-set-requires-activation)
9281 (js2-set-is-generator))))
9282 ;; see if we are mixing yields and value returns.
9283 (when (and inside-function
9284 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9285 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9286 'LEGACY))
9287 (setq name (js2-function-name js2-current-script-or-fn))
9288 (if (zerop (length name))
9289 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9290 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9291 ret))
9292
9293 (defun js2-parse-debugger ()
9294 (make-js2-keyword-node :type js2-DEBUGGER))
9295
9296 (defun js2-parse-block ()
9297 "Parser for a curly-delimited statement block.
9298 Last token matched must be `js2-LC'."
9299 (let ((pos (js2-current-token-beg))
9300 (pn (make-js2-scope)))
9301 (js2-push-scope pn)
9302 (unwind-protect
9303 (progn
9304 (js2-parse-statements pn)
9305 (js2-must-match js2-RC "msg.no.brace.block")
9306 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9307 (js2-pop-scope))
9308 pn))
9309
9310 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9311 (defun js2-parse-semi ()
9312 "Parse a statement or handle an error.
9313 Current token type is `js2-SEMI' or `js2-ERROR'."
9314 (let ((tt (js2-current-token-type)) pos len)
9315 (if (eq tt js2-SEMI)
9316 (make-js2-empty-expr-node :len 1)
9317 (setq pos (js2-current-token-beg)
9318 len (- (js2-current-token-end) pos))
9319 (js2-report-error "msg.syntax" nil pos len)
9320 (make-js2-error-node :pos pos :len len))))
9321
9322 (defun js2-parse-default-xml-namespace ()
9323 "Parse a `default xml namespace = <expr>' e4x statement."
9324 (let ((pos (js2-current-token-beg))
9325 end len expr unary)
9326 (js2-must-have-xml)
9327 (js2-set-requires-activation)
9328 (setq len (- js2-ts-cursor pos))
9329 (unless (and (js2-match-token js2-NAME)
9330 (string= (js2-current-token-string) "xml"))
9331 (js2-report-error "msg.bad.namespace" nil pos len))
9332 (unless (and (js2-match-token js2-NAME)
9333 (string= (js2-current-token-string) "namespace"))
9334 (js2-report-error "msg.bad.namespace" nil pos len))
9335 (unless (js2-match-token js2-ASSIGN)
9336 (js2-report-error "msg.bad.namespace" nil pos len))
9337 (setq expr (js2-parse-expr)
9338 end (js2-node-end expr)
9339 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9340 :pos pos
9341 :len (- end pos)
9342 :operand expr))
9343 (js2-node-add-children unary expr)
9344 (make-js2-expr-stmt-node :pos pos
9345 :len (- end pos)
9346 :expr unary)))
9347
9348 (defun js2-record-label (label bundle)
9349 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9350 (js2-get-token)
9351 (let ((name (js2-label-node-name label))
9352 labeled-stmt
9353 dup)
9354 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9355 ;; flag both labels if possible when used in editing mode
9356 (if (and js2-parse-ide-mode
9357 (setq dup (js2-get-label-by-name labeled-stmt name)))
9358 (js2-report-error "msg.dup.label" nil
9359 (js2-node-abs-pos dup) (js2-node-len dup)))
9360 (js2-report-error "msg.dup.label" nil
9361 (js2-node-pos label) (js2-node-len label)))
9362 (js2-labeled-stmt-node-add-label bundle label)
9363 (js2-node-add-children bundle label)
9364 ;; Add one reference to the bundle per label in `js2-label-set'
9365 (push (cons name bundle) js2-label-set)))
9366
9367 (defun js2-parse-name-or-label ()
9368 "Parser for identifier or label. Last token matched must be js2-NAME.
9369 Called when we found a name in a statement context. If it's a label, we gather
9370 up any following labels and the next non-label statement into a
9371 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9372 expression and return it wrapped in a `js2-expr-stmt-node'."
9373 (let ((pos (js2-current-token-beg))
9374 expr stmt bundle
9375 (continue t))
9376 ;; set check for label and call down to `js2-parse-primary-expr'
9377 (setq expr (js2-maybe-parse-label))
9378 (if (null expr)
9379 ;; Parse the non-label expression and wrap with expression stmt.
9380 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9381 ;; else parsed a label
9382 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9383 (js2-record-label expr bundle)
9384 ;; look for more labels
9385 (while (and continue (= (js2-get-token) js2-NAME))
9386 (if (setq expr (js2-maybe-parse-label))
9387 (js2-record-label expr bundle)
9388 (setq expr (js2-parse-expr)
9389 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9390 continue nil)
9391 (js2-auto-insert-semicolon stmt)))
9392 ;; no more labels; now parse the labeled statement
9393 (unwind-protect
9394 (unless stmt
9395 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9396 (js2-unget-token)
9397 (setq stmt (js2-statement-helper))))
9398 ;; remove the labels for this statement from the global set
9399 (dolist (label (js2-labeled-stmt-node-labels bundle))
9400 (setq js2-label-set (remove label js2-label-set))))
9401 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9402 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9403 (js2-node-add-children bundle stmt)
9404 bundle)))
9405
9406 (defun js2-maybe-parse-label ()
9407 (cl-assert (= (js2-current-token-type) js2-NAME))
9408 (let (label-pos
9409 (next-tt (js2-get-token))
9410 (label-end (js2-current-token-end)))
9411 ;; Do not consume colon, it is used as unwind indicator
9412 ;; to return to statementHelper.
9413 (js2-unget-token)
9414 (if (= next-tt js2-COLON)
9415 (prog2
9416 (setq label-pos (js2-current-token-beg))
9417 (make-js2-label-node :pos label-pos
9418 :len (- label-end label-pos)
9419 :name (js2-current-token-string))
9420 (js2-set-face label-pos
9421 label-end
9422 'font-lock-variable-name-face 'record))
9423 ;; Backtrack from the name token, too.
9424 (js2-unget-token)
9425 nil)))
9426
9427 (defun js2-parse-expr-stmt ()
9428 "Default parser in statement context, if no recognized statement found."
9429 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9430 (progn
9431 (js2-unget-token)
9432 (js2-parse-expr)) t))
9433
9434 (defun js2-parse-variables (decl-type pos)
9435 "Parse a comma-separated list of variable declarations.
9436 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9437
9438 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9439 For 'var' or 'const', the keyword should be the token last scanned.
9440
9441 POS is the position where the node should start. It's sometimes the
9442 var/const/let keyword, and other times the beginning of the first token
9443 in the first variable declaration.
9444
9445 Returns the parsed `js2-var-decl-node' expression node."
9446 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9447 :pos pos))
9448 destructuring kid-pos tt init name end nbeg nend vi
9449 (continue t))
9450 ;; Example:
9451 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9452 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9453 ;; var {a, b} = baz;
9454 (while continue
9455 (setq destructuring nil
9456 name nil
9457 tt (js2-get-token)
9458 kid-pos (js2-current-token-beg)
9459 end (js2-current-token-end)
9460 init nil)
9461 (if (or (= tt js2-LB) (= tt js2-LC))
9462 ;; Destructuring assignment, e.g., var [a, b] = ...
9463 (setq destructuring (js2-parse-destruct-primary-expr)
9464 end (js2-node-end destructuring))
9465 ;; Simple variable name
9466 (js2-unget-token)
9467 (when (js2-must-match-name "msg.bad.var")
9468 (setq name (js2-create-name-node)
9469 nbeg (js2-current-token-beg)
9470 nend (js2-current-token-end)
9471 end nend)
9472 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
9473 (js2-check-strict-identifier name)))
9474 (when (js2-match-token js2-ASSIGN)
9475 (setq init (js2-parse-assign-expr)
9476 end (js2-node-end init))
9477 (js2-record-imenu-functions init name))
9478 (when name
9479 (js2-set-face nbeg nend (if (js2-function-node-p init)
9480 'font-lock-function-name-face
9481 'font-lock-variable-name-face)
9482 'record))
9483 (setq vi (make-js2-var-init-node :pos kid-pos
9484 :len (- end kid-pos)
9485 :type decl-type))
9486 (if destructuring
9487 (progn
9488 (if (and (null init) (not js2-in-for-init))
9489 (js2-report-error "msg.destruct.assign.no.init"))
9490 (js2-define-destruct-symbols destructuring
9491 decl-type
9492 'font-lock-variable-name-face)
9493 (setf (js2-var-init-node-target vi) destructuring))
9494 (setf (js2-var-init-node-target vi) name))
9495 (setf (js2-var-init-node-initializer vi) init)
9496 (js2-node-add-children vi name destructuring init)
9497 (js2-block-node-push result vi)
9498 (unless (js2-match-token js2-COMMA)
9499 (setq continue nil)))
9500 (setf (js2-node-len result) (- end pos))
9501 result))
9502
9503 (defun js2-parse-let (pos &optional stmt-p)
9504 "Parse a let expression or statement.
9505 A let-expression is of the form `let (vars) expr'.
9506 A let-statement is of the form `let (vars) {statements}'.
9507 The third form of let is a variable declaration list, handled
9508 by `js2-parse-variables'."
9509 (let ((pn (make-js2-let-node :pos pos))
9510 beg vars body)
9511 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9512 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9513 (js2-push-scope pn)
9514 (unwind-protect
9515 (progn
9516 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9517 (if (js2-must-match js2-RP "msg.no.paren.let")
9518 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9519 (if (and stmt-p (js2-match-token js2-LC))
9520 ;; let statement
9521 (progn
9522 (setf beg (js2-current-token-beg) ; position stmt at LC
9523 body (js2-parse-statements))
9524 (js2-must-match js2-RC "msg.no.curly.let")
9525 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9526 (js2-node-len pn) (- (js2-current-token-end) pos)
9527 (js2-let-node-body pn) body
9528 (js2-node-type pn) js2-LET))
9529 ;; let expression
9530 (setf body (js2-parse-expr)
9531 (js2-node-len pn) (- (js2-node-end body) pos)
9532 (js2-let-node-body pn) body))
9533 (setf (js2-let-node-vars pn) vars)
9534 (js2-node-add-children pn vars body))
9535 (js2-pop-scope))
9536 pn))
9537
9538 (defun js2-define-new-symbol (decl-type name node &optional scope)
9539 (js2-scope-put-symbol (or scope js2-current-scope)
9540 name
9541 (make-js2-symbol decl-type name node)))
9542
9543 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9544 "Define a symbol in the current scope.
9545 If NODE is non-nil, it is the AST node associated with the symbol."
9546 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9547 (symbol (if defining-scope
9548 (js2-scope-get-symbol defining-scope name)))
9549 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9550 (pos (if node (js2-node-abs-pos node)))
9551 (len (if node (js2-node-len node))))
9552 (cond
9553 ((and symbol ; already defined
9554 (or (= sdt js2-CONST) ; old version is const
9555 (= decl-type js2-CONST) ; new version is const
9556 ;; two let-bound vars in this block have same name
9557 (and (= sdt js2-LET)
9558 (eq defining-scope js2-current-scope))))
9559 (js2-report-error
9560 (cond
9561 ((= sdt js2-CONST) "msg.const.redecl")
9562 ((= sdt js2-LET) "msg.let.redecl")
9563 ((= sdt js2-VAR) "msg.var.redecl")
9564 ((= sdt js2-FUNCTION) "msg.function.redecl")
9565 (t "msg.parm.redecl"))
9566 name pos len))
9567 ((or (= decl-type js2-LET)
9568 ;; strict mode const is scoped to the current LexicalEnvironment
9569 (and js2-in-use-strict-directive
9570 (= decl-type js2-CONST)))
9571 (if (and (= decl-type js2-LET)
9572 (not ignore-not-in-block)
9573 (or (= (js2-node-type js2-current-scope) js2-IF)
9574 (js2-loop-node-p js2-current-scope)))
9575 (js2-report-error "msg.let.decl.not.in.block")
9576 (js2-define-new-symbol decl-type name node)))
9577 ((or (= decl-type js2-VAR)
9578 (= decl-type js2-FUNCTION)
9579 ;; sloppy mode const is scoped to the current VariableEnvironment
9580 (and (not js2-in-use-strict-directive)
9581 (= decl-type js2-CONST)))
9582 (if symbol
9583 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9584 (js2-add-strict-warning "msg.var.redecl" name)
9585 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9586 (js2-add-strict-warning "msg.var.hides.arg" name)))
9587 (js2-define-new-symbol decl-type name node
9588 js2-current-script-or-fn)))
9589 ((= decl-type js2-LP)
9590 (if symbol
9591 ;; must be duplicate parameter. Second parameter hides the
9592 ;; first, so go ahead and add the second pararameter
9593 (js2-report-warning "msg.dup.parms" name))
9594 (js2-define-new-symbol decl-type name node))
9595 (t (js2-code-bug)))))
9596
9597 (defun js2-parse-paren-expr-or-generator-comp ()
9598 (let ((px-pos (js2-current-token-beg)))
9599 (cond
9600 ((and (>= js2-language-version 200)
9601 (js2-match-token js2-FOR))
9602 (js2-parse-generator-comp px-pos))
9603 ((and (>= js2-language-version 200)
9604 (js2-match-token js2-RP))
9605 ;; Not valid expression syntax, but this is valid in an arrow
9606 ;; function with no params: () => body.
9607 (if (eq (js2-peek-token) js2-ARROW)
9608 ;; Return whatever, it will hopefully be rewinded and
9609 ;; reparsed when we reach the =>.
9610 (make-js2-keyword-node :type js2-NULL)
9611 (js2-report-error "msg.syntax")
9612 (make-js2-error-node)))
9613 (t
9614 (let* ((js2-in-for-init nil)
9615 (expr (js2-parse-expr))
9616 (pn (make-js2-paren-node :pos px-pos
9617 :expr expr)))
9618 (js2-node-add-children pn (js2-paren-node-expr pn))
9619 (js2-must-match js2-RP "msg.no.paren")
9620 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9621 pn)))))
9622
9623 (defun js2-parse-expr (&optional oneshot)
9624 (let* ((pn (js2-parse-assign-expr))
9625 (pos (js2-node-pos pn))
9626 left
9627 right
9628 op-pos)
9629 (while (and (not oneshot)
9630 (js2-match-token js2-COMMA))
9631 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9632 (if (= (js2-peek-token) js2-YIELD)
9633 (js2-report-error "msg.yield.parenthesized"))
9634 (setq right (js2-parse-assign-expr)
9635 left pn
9636 pn (make-js2-infix-node :type js2-COMMA
9637 :pos pos
9638 :len (- js2-ts-cursor pos)
9639 :op-pos op-pos
9640 :left left
9641 :right right))
9642 (js2-node-add-children pn left right))
9643 pn))
9644
9645 (defun js2-parse-assign-expr ()
9646 (let ((tt (js2-get-token))
9647 (pos (js2-current-token-beg))
9648 pn left right op-pos
9649 ts-state recorded-identifiers parsed-errors)
9650 (if (= tt js2-YIELD)
9651 (js2-parse-return-or-yield tt t)
9652 ;; Save the tokenizer state in case we find an arrow function
9653 ;; and have to rewind.
9654 (setq ts-state (make-js2-ts-state)
9655 recorded-identifiers js2-recorded-identifiers
9656 parsed-errors js2-parsed-errors)
9657 ;; not yield - parse assignment expression
9658 (setq pn (js2-parse-cond-expr)
9659 tt (js2-get-token))
9660 (cond
9661 ((and (<= js2-first-assign tt)
9662 (<= tt js2-last-assign))
9663 ;; tt express assignment (=, |=, ^=, ..., %=)
9664 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9665 left pn)
9666 (js2-check-strict-identifier left)
9667 (setq right (js2-parse-assign-expr)
9668 pn (make-js2-assign-node :type tt
9669 :pos pos
9670 :len (- (js2-node-end right) pos)
9671 :op-pos op-pos
9672 :left left
9673 :right right))
9674 (when js2-parse-ide-mode
9675 (js2-highlight-assign-targets pn left right)
9676 (js2-record-imenu-functions right left))
9677 ;; do this last so ide checks above can use absolute positions
9678 (js2-node-add-children pn left right))
9679 ((and (= tt js2-ARROW)
9680 (>= js2-language-version 200))
9681 (js2-ts-seek ts-state)
9682 (setq js2-recorded-identifiers recorded-identifiers
9683 js2-parsed-errors parsed-errors)
9684 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9685 (t
9686 (js2-unget-token)))
9687 pn)))
9688
9689 (defun js2-parse-cond-expr ()
9690 (let ((pos (js2-current-token-beg))
9691 (pn (js2-parse-or-expr))
9692 test-expr
9693 if-true
9694 if-false
9695 q-pos
9696 c-pos)
9697 (when (js2-match-token js2-HOOK)
9698 (setq q-pos (- (js2-current-token-beg) pos)
9699 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9700 (js2-must-match js2-COLON "msg.no.colon.cond")
9701 (setq c-pos (- (js2-current-token-beg) pos)
9702 if-false (js2-parse-assign-expr)
9703 test-expr pn
9704 pn (make-js2-cond-node :pos pos
9705 :len (- (js2-node-end if-false) pos)
9706 :test-expr test-expr
9707 :true-expr if-true
9708 :false-expr if-false
9709 :q-pos q-pos
9710 :c-pos c-pos))
9711 (js2-node-add-children pn test-expr if-true if-false))
9712 pn))
9713
9714 (defun js2-make-binary (type left parser)
9715 "Helper for constructing a binary-operator AST node.
9716 LEFT is the left-side-expression, already parsed, and the
9717 binary operator should have just been matched.
9718 PARSER is a function to call to parse the right operand,
9719 or a `js2-node' struct if it has already been parsed.
9720 FIXME: The latter option is unused?"
9721 (let* ((pos (js2-node-pos left))
9722 (op-pos (- (js2-current-token-beg) pos))
9723 (right (if (js2-node-p parser)
9724 parser
9725 (js2-get-token)
9726 (funcall parser)))
9727 (pn (make-js2-infix-node :type type
9728 :pos pos
9729 :len (- (js2-node-end right) pos)
9730 :op-pos op-pos
9731 :left left
9732 :right right)))
9733 (js2-node-add-children pn left right)
9734 pn))
9735
9736 (defun js2-parse-or-expr ()
9737 (let ((pn (js2-parse-and-expr)))
9738 (when (js2-match-token js2-OR)
9739 (setq pn (js2-make-binary js2-OR
9740 pn
9741 'js2-parse-or-expr)))
9742 pn))
9743
9744 (defun js2-parse-and-expr ()
9745 (let ((pn (js2-parse-bit-or-expr)))
9746 (when (js2-match-token js2-AND)
9747 (setq pn (js2-make-binary js2-AND
9748 pn
9749 'js2-parse-and-expr)))
9750 pn))
9751
9752 (defun js2-parse-bit-or-expr ()
9753 (let ((pn (js2-parse-bit-xor-expr)))
9754 (while (js2-match-token js2-BITOR)
9755 (setq pn (js2-make-binary js2-BITOR
9756 pn
9757 'js2-parse-bit-xor-expr)))
9758 pn))
9759
9760 (defun js2-parse-bit-xor-expr ()
9761 (let ((pn (js2-parse-bit-and-expr)))
9762 (while (js2-match-token js2-BITXOR)
9763 (setq pn (js2-make-binary js2-BITXOR
9764 pn
9765 'js2-parse-bit-and-expr)))
9766 pn))
9767
9768 (defun js2-parse-bit-and-expr ()
9769 (let ((pn (js2-parse-eq-expr)))
9770 (while (js2-match-token js2-BITAND)
9771 (setq pn (js2-make-binary js2-BITAND
9772 pn
9773 'js2-parse-eq-expr)))
9774 pn))
9775
9776 (defconst js2-parse-eq-ops
9777 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9778
9779 (defun js2-parse-eq-expr ()
9780 (let ((pn (js2-parse-rel-expr))
9781 tt)
9782 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9783 (setq pn (js2-make-binary tt
9784 pn
9785 'js2-parse-rel-expr)))
9786 (js2-unget-token)
9787 pn))
9788
9789 (defconst js2-parse-rel-ops
9790 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9791
9792 (defun js2-parse-rel-expr ()
9793 (let ((pn (js2-parse-shift-expr))
9794 (continue t)
9795 tt)
9796 (while continue
9797 (setq tt (js2-get-token))
9798 (cond
9799 ((and js2-in-for-init (= tt js2-IN))
9800 (js2-unget-token)
9801 (setq continue nil))
9802 ((memq tt js2-parse-rel-ops)
9803 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9804 (t
9805 (js2-unget-token)
9806 (setq continue nil))))
9807 pn))
9808
9809 (defconst js2-parse-shift-ops
9810 (list js2-LSH js2-URSH js2-RSH))
9811
9812 (defun js2-parse-shift-expr ()
9813 (let ((pn (js2-parse-add-expr))
9814 tt
9815 (continue t))
9816 (while continue
9817 (setq tt (js2-get-token))
9818 (if (memq tt js2-parse-shift-ops)
9819 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9820 (js2-unget-token)
9821 (setq continue nil)))
9822 pn))
9823
9824 (defun js2-parse-add-expr ()
9825 (let ((pn (js2-parse-mul-expr))
9826 tt
9827 (continue t))
9828 (while continue
9829 (setq tt (js2-get-token))
9830 (if (or (= tt js2-ADD) (= tt js2-SUB))
9831 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9832 (js2-unget-token)
9833 (setq continue nil)))
9834 pn))
9835
9836 (defconst js2-parse-mul-ops
9837 (list js2-MUL js2-DIV js2-MOD))
9838
9839 (defun js2-parse-mul-expr ()
9840 (let ((pn (js2-parse-unary-expr))
9841 tt
9842 (continue t))
9843 (while continue
9844 (setq tt (js2-get-token))
9845 (if (memq tt js2-parse-mul-ops)
9846 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9847 (js2-unget-token)
9848 (setq continue nil)))
9849 pn))
9850
9851 (defun js2-make-unary (type parser &rest args)
9852 "Make a unary node of type TYPE.
9853 PARSER is either a node (for postfix operators) or a function to call
9854 to parse the operand (for prefix operators)."
9855 (let* ((pos (js2-current-token-beg))
9856 (postfix (js2-node-p parser))
9857 (expr (if postfix
9858 parser
9859 (apply parser args)))
9860 end
9861 pn)
9862 (if postfix ; e.g. i++
9863 (setq pos (js2-node-pos expr)
9864 end (js2-current-token-end))
9865 (setq end (js2-node-end expr)))
9866 (setq pn (make-js2-unary-node :type type
9867 :pos pos
9868 :len (- end pos)
9869 :operand expr))
9870 (js2-node-add-children pn expr)
9871 pn))
9872
9873 (defconst js2-incrementable-node-types
9874 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9875 "Node types that can be the operand of a ++ or -- operator.")
9876
9877 (defun js2-check-bad-inc-dec (tt beg end unary)
9878 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9879 js2-incrementable-node-types)
9880 (js2-report-error (if (= tt js2-INC)
9881 "msg.bad.incr"
9882 "msg.bad.decr")
9883 nil beg (- end beg))))
9884
9885 (defun js2-parse-unary-expr ()
9886 (let ((tt (js2-current-token-type))
9887 pn expr beg end)
9888 (cond
9889 ((or (= tt js2-VOID)
9890 (= tt js2-NOT)
9891 (= tt js2-BITNOT)
9892 (= tt js2-TYPEOF))
9893 (js2-get-token)
9894 (js2-make-unary tt 'js2-parse-unary-expr))
9895 ((= tt js2-ADD)
9896 (js2-get-token)
9897 ;; Convert to special POS token in decompiler and parse tree
9898 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9899 ((= tt js2-SUB)
9900 (js2-get-token)
9901 ;; Convert to special NEG token in decompiler and parse tree
9902 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9903 ((or (= tt js2-INC)
9904 (= tt js2-DEC))
9905 (js2-get-token)
9906 (prog1
9907 (setq beg (js2-current-token-beg)
9908 end (js2-current-token-end)
9909 expr (js2-make-unary tt 'js2-parse-member-expr t))
9910 (js2-check-bad-inc-dec tt beg end expr)))
9911 ((= tt js2-DELPROP)
9912 (js2-get-token)
9913 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9914 ((= tt js2-ERROR)
9915 (js2-get-token)
9916 (make-js2-error-node)) ; try to continue
9917 ((and (= tt js2-LT)
9918 js2-compiler-xml-available)
9919 ;; XML stream encountered in expression.
9920 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9921 (t
9922 (setq pn (js2-parse-member-expr t)
9923 ;; Don't look across a newline boundary for a postfix incop.
9924 tt (js2-peek-token-or-eol))
9925 (when (or (= tt js2-INC) (= tt js2-DEC))
9926 (js2-get-token)
9927 (setf expr pn
9928 pn (js2-make-unary tt expr))
9929 (js2-node-set-prop pn 'postfix t)
9930 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9931 pn))))
9932
9933 (defun js2-parse-xml-initializer ()
9934 "Parse an E4X XML initializer.
9935 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9936 Then I'll postprocess the result, depending on whether we're in IDE
9937 mode or codegen mode, and generate the appropriate rewritten AST.
9938 IDE mode uses a rich AST that models the XML structure. Codegen mode
9939 just concatenates everything and makes a new XML or XMLList out of it."
9940 (let ((tt (js2-get-first-xml-token))
9941 pn-xml pn expr kids expr-pos
9942 (continue t)
9943 (first-token t))
9944 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9945 (js2-report-error "msg.syntax"))
9946 (setq pn-xml (make-js2-xml-node))
9947 (while continue
9948 (if first-token
9949 (setq first-token nil)
9950 (setq tt (js2-get-next-xml-token)))
9951 (cond
9952 ;; js2-XML means we found a {expr} in the XML stream.
9953 ;; The token string is the XML up to the left-curly.
9954 ((= tt js2-XML)
9955 (push (make-js2-string-node :pos (js2-current-token-beg)
9956 :len (- js2-ts-cursor (js2-current-token-beg)))
9957 kids)
9958 (js2-must-match js2-LC "msg.syntax")
9959 (setq expr-pos js2-ts-cursor
9960 expr (if (eq (js2-peek-token) js2-RC)
9961 (make-js2-empty-expr-node :pos expr-pos)
9962 (js2-parse-expr)))
9963 (js2-must-match js2-RC "msg.syntax")
9964 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9965 :len (js2-node-len expr)
9966 :expr expr))
9967 (js2-node-add-children pn expr)
9968 (push pn kids))
9969 ;; a js2-XMLEND token means we hit the final close-tag.
9970 ((= tt js2-XMLEND)
9971 (push (make-js2-string-node :pos (js2-current-token-beg)
9972 :len (- js2-ts-cursor (js2-current-token-beg)))
9973 kids)
9974 (dolist (kid (nreverse kids))
9975 (js2-block-node-push pn-xml kid))
9976 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9977 (js2-node-pos pn-xml))
9978 continue nil))
9979 (t
9980 (js2-report-error "msg.syntax")
9981 (setq continue nil))))
9982 pn-xml))
9983
9984
9985 (defun js2-parse-argument-list ()
9986 "Parse an argument list and return it as a Lisp list of nodes.
9987 Returns the list in reverse order. Consumes the right-paren token."
9988 (let (result)
9989 (unless (js2-match-token js2-RP)
9990 (cl-loop do
9991 (let ((tt (js2-get-token)))
9992 (if (= tt js2-YIELD)
9993 (js2-report-error "msg.yield.parenthesized"))
9994 (if (and (= tt js2-TRIPLEDOT)
9995 (>= js2-language-version 200))
9996 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9997 (js2-unget-token)
9998 (push (js2-parse-assign-expr) result)))
9999 while
10000 (js2-match-token js2-COMMA))
10001 (js2-must-match js2-RP "msg.no.paren.arg")
10002 result)))
10003
10004 (defun js2-parse-member-expr (&optional allow-call-syntax)
10005 (let ((tt (js2-current-token-type))
10006 pn pos target args beg end init)
10007 (if (/= tt js2-NEW)
10008 (setq pn (js2-parse-primary-expr))
10009 ;; parse a 'new' expression
10010 (js2-get-token)
10011 (setq pos (js2-current-token-beg)
10012 beg pos
10013 target (js2-parse-member-expr)
10014 end (js2-node-end target)
10015 pn (make-js2-new-node :pos pos
10016 :target target
10017 :len (- end pos)))
10018 (js2-highlight-function-call (js2-current-token))
10019 (js2-node-add-children pn target)
10020 (when (js2-match-token js2-LP)
10021 ;; Add the arguments to pn, if any are supplied.
10022 (setf beg pos ; start of "new" keyword
10023 pos (js2-current-token-beg)
10024 args (nreverse (js2-parse-argument-list))
10025 (js2-new-node-args pn) args
10026 end (js2-current-token-end)
10027 (js2-new-node-lp pn) (- pos beg)
10028 (js2-new-node-rp pn) (- end 1 beg))
10029 (apply #'js2-node-add-children pn args))
10030 (when (and js2-allow-rhino-new-expr-initializer
10031 (js2-match-token js2-LC))
10032 (setf init (js2-parse-object-literal)
10033 end (js2-node-end init)
10034 (js2-new-node-initializer pn) init)
10035 (js2-node-add-children pn init))
10036 (setf (js2-node-len pn) (- end beg))) ; end outer if
10037 (js2-parse-member-expr-tail allow-call-syntax pn)))
10038
10039 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
10040 "Parse a chain of property/array accesses or function calls.
10041 Includes parsing for E4X operators like `..' and `.@'.
10042 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
10043 Returns an expression tree that includes PN, the parent node."
10044 (let (tt
10045 (continue t))
10046 (while continue
10047 (setq tt (js2-get-token))
10048 (cond
10049 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
10050 (setq pn (js2-parse-property-access tt pn)))
10051 ((= tt js2-DOTQUERY)
10052 (setq pn (js2-parse-dot-query pn)))
10053 ((= tt js2-LB)
10054 (setq pn (js2-parse-element-get pn)))
10055 ((= tt js2-LP)
10056 (js2-unget-token)
10057 (if allow-call-syntax
10058 (setq pn (js2-parse-function-call pn))
10059 (setq continue nil)))
10060 ((= tt js2-TEMPLATE_HEAD)
10061 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
10062 ((= tt js2-NO_SUBS_TEMPLATE)
10063 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
10064 (t
10065 (js2-unget-token)
10066 (setq continue nil))))
10067 (if (>= js2-highlight-level 2)
10068 (js2-parse-highlight-member-expr-node pn))
10069 pn))
10070
10071 (defun js2-parse-tagged-template (tag-node tpl-node)
10072 "Parse tagged template expression."
10073 (let* ((beg (js2-node-pos tag-node))
10074 (pn (make-js2-tagged-template-node :beg beg
10075 :len (- (js2-current-token-end) beg)
10076 :tag tag-node
10077 :template tpl-node)))
10078 (js2-node-add-children pn tag-node tpl-node)
10079 pn))
10080
10081 (defun js2-parse-dot-query (pn)
10082 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
10083 Last token parsed must be `js2-DOTQUERY'."
10084 (let ((pos (js2-node-pos pn))
10085 op-pos expr end)
10086 (js2-must-have-xml)
10087 (js2-set-requires-activation)
10088 (setq op-pos (js2-current-token-beg)
10089 expr (js2-parse-expr)
10090 end (js2-node-end expr)
10091 pn (make-js2-xml-dot-query-node :left pn
10092 :pos pos
10093 :op-pos op-pos
10094 :right expr))
10095 (js2-node-add-children pn
10096 (js2-xml-dot-query-node-left pn)
10097 (js2-xml-dot-query-node-right pn))
10098 (if (js2-must-match js2-RP "msg.no.paren")
10099 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10100 end (js2-current-token-end)))
10101 (setf (js2-node-len pn) (- end pos))
10102 pn))
10103
10104 (defun js2-parse-element-get (pn)
10105 "Parse an element-get expression, e.g. foo[bar].
10106 Last token parsed must be `js2-RB'."
10107 (let ((lb (js2-current-token-beg))
10108 (pos (js2-node-pos pn))
10109 rb expr)
10110 (setq expr (js2-parse-expr))
10111 (if (js2-must-match js2-RB "msg.no.bracket.index")
10112 (setq rb (js2-current-token-beg)))
10113 (setq pn (make-js2-elem-get-node :target pn
10114 :pos pos
10115 :element expr
10116 :lb (js2-relpos lb pos)
10117 :rb (js2-relpos rb pos)
10118 :len (- (js2-current-token-end) pos)))
10119 (js2-node-add-children pn
10120 (js2-elem-get-node-target pn)
10121 (js2-elem-get-node-element pn))
10122 pn))
10123
10124 (defun js2-highlight-function-call (token)
10125 (when (eq (js2-token-type token) js2-NAME)
10126 (js2-record-face 'js2-function-call token)))
10127
10128 (defun js2-parse-function-call (pn)
10129 (js2-highlight-function-call (js2-current-token))
10130 (js2-get-token)
10131 (let (args
10132 (pos (js2-node-pos pn)))
10133 (setq pn (make-js2-call-node :pos pos
10134 :target pn
10135 :lp (- (js2-current-token-beg) pos)))
10136 (js2-node-add-children pn (js2-call-node-target pn))
10137 ;; Add the arguments to pn, if any are supplied.
10138 (setf args (nreverse (js2-parse-argument-list))
10139 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10140 (js2-call-node-args pn) args)
10141 (apply #'js2-node-add-children pn args)
10142 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10143 pn))
10144
10145 (defun js2-parse-property-access (tt pn)
10146 "Parse a property access, XML descendants access, or XML attr access."
10147 (let ((member-type-flags 0)
10148 (dot-pos (js2-current-token-beg))
10149 (dot-len (if (= tt js2-DOTDOT) 2 1))
10150 name
10151 ref ; right side of . or .. operator
10152 result)
10153 (when (= tt js2-DOTDOT)
10154 (js2-must-have-xml)
10155 (setq member-type-flags js2-descendants-flag))
10156 (if (not js2-compiler-xml-available)
10157 (progn
10158 (js2-must-match-prop-name "msg.no.name.after.dot")
10159 (setq name (js2-create-name-node t js2-GETPROP)
10160 result (make-js2-prop-get-node :left pn
10161 :pos (js2-current-token-beg)
10162 :right name
10163 :len (js2-current-token-len)))
10164 (js2-node-add-children result pn name)
10165 result)
10166 ;; otherwise look for XML operators
10167 (setf result (if (= tt js2-DOT)
10168 (make-js2-prop-get-node)
10169 (make-js2-infix-node :type js2-DOTDOT))
10170 (js2-node-pos result) (js2-node-pos pn)
10171 (js2-infix-node-op-pos result) dot-pos
10172 (js2-infix-node-left result) pn ; do this after setting position
10173 tt (js2-get-prop-name-token))
10174 (cond
10175 ;; handles: name, ns::name, ns::*, ns::[expr]
10176 ((= tt js2-NAME)
10177 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10178 ;; handles: *, *::name, *::*, *::[expr]
10179 ((= tt js2-MUL)
10180 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10181 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10182 ((= tt js2-XMLATTR)
10183 (setq result (js2-parse-attribute-access)))
10184 (t
10185 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10186 (if ref
10187 (setf (js2-node-len result) (- (js2-node-end ref)
10188 (js2-node-pos result))
10189 (js2-infix-node-right result) ref))
10190 (if (js2-infix-node-p result)
10191 (js2-node-add-children result
10192 (js2-infix-node-left result)
10193 (js2-infix-node-right result)))
10194 result)))
10195
10196 (defun js2-parse-attribute-access ()
10197 "Parse an E4X XML attribute expression.
10198 This includes expressions of the forms:
10199
10200 @attr @ns::attr @ns::*
10201 @* @*::attr @*::*
10202 @[expr] @*::[expr] @ns::[expr]
10203
10204 Called if we peeked an '@' token."
10205 (let ((tt (js2-get-prop-name-token))
10206 (at-pos (js2-current-token-beg)))
10207 (cond
10208 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10209 ((= tt js2-NAME)
10210 (js2-parse-property-name at-pos nil 0))
10211 ;; handles: @*, @*::name, @*::*, @*::[expr]
10212 ((= tt js2-MUL)
10213 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10214 ;; handles @[expr]
10215 ((= tt js2-LB)
10216 (js2-parse-xml-elem-ref at-pos))
10217 (t
10218 (js2-report-error "msg.no.name.after.xmlAttr")
10219 ;; Avoid cascaded errors that happen if we make an error node here.
10220 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10221
10222 (defun js2-parse-property-name (at-pos s member-type-flags)
10223 "Check if :: follows name in which case it becomes qualified name.
10224
10225 AT-POS is a natural number if we just read an '@' token, else nil.
10226 S is the name or string that was matched: an identifier, 'throw' or '*'.
10227 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10228
10229 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10230 operator, or the name is followed by ::. For a plain name, returns a
10231 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10232 (let ((pos (or at-pos (js2-current-token-beg)))
10233 colon-pos
10234 (name (js2-create-name-node t (js2-current-token-type) s))
10235 ns tt pn)
10236 (catch 'return
10237 (when (js2-match-token js2-COLONCOLON)
10238 (setq ns name
10239 colon-pos (js2-current-token-beg)
10240 tt (js2-get-prop-name-token))
10241 (cond
10242 ;; handles name::name
10243 ((= tt js2-NAME)
10244 (setq name (js2-create-name-node)))
10245 ;; handles name::*
10246 ((= tt js2-MUL)
10247 (setq name (js2-create-name-node nil nil "*")))
10248 ;; handles name::[expr]
10249 ((= tt js2-LB)
10250 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10251 (t
10252 (js2-report-error "msg.no.name.after.coloncolon"))))
10253 (if (and (null ns) (zerop member-type-flags))
10254 name
10255 (prog1
10256 (setq pn
10257 (make-js2-xml-prop-ref-node :pos pos
10258 :len (- (js2-node-end name) pos)
10259 :at-pos at-pos
10260 :colon-pos colon-pos
10261 :propname name))
10262 (js2-node-add-children pn name))))))
10263
10264 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10265 "Parse the [expr] portion of an xml element reference.
10266 For instance, @[expr], @*::[expr], or ns::[expr]."
10267 (let* ((lb (js2-current-token-beg))
10268 (pos (or at-pos lb))
10269 rb
10270 (expr (js2-parse-expr))
10271 (end (js2-node-end expr))
10272 pn)
10273 (if (js2-must-match js2-RB "msg.no.bracket.index")
10274 (setq rb (js2-current-token-beg)
10275 end (js2-current-token-end)))
10276 (prog1
10277 (setq pn
10278 (make-js2-xml-elem-ref-node :pos pos
10279 :len (- end pos)
10280 :namespace namespace
10281 :colon-pos colon-pos
10282 :at-pos at-pos
10283 :expr expr
10284 :lb (js2-relpos lb pos)
10285 :rb (js2-relpos rb pos)))
10286 (js2-node-add-children pn namespace expr))))
10287
10288 (defun js2-parse-destruct-primary-expr ()
10289 (let ((js2-is-in-destructuring t))
10290 (js2-parse-primary-expr)))
10291
10292 (defun js2-parse-primary-expr ()
10293 "Parse a literal (leaf) expression of some sort.
10294 Includes complex literals such as functions, object-literals,
10295 array-literals, array comprehensions and regular expressions."
10296 (let (tt node)
10297 (setq tt (js2-current-token-type))
10298 (cond
10299 ((= tt js2-CLASS)
10300 (js2-parse-class-expr))
10301 ((= tt js2-FUNCTION)
10302 (js2-parse-function-expr))
10303 ((= tt js2-LB)
10304 (js2-parse-array-comp-or-literal))
10305 ((= tt js2-LC)
10306 (js2-parse-object-literal))
10307 ((= tt js2-LET)
10308 (js2-parse-let (js2-current-token-beg)))
10309 ((= tt js2-LP)
10310 (js2-parse-paren-expr-or-generator-comp))
10311 ((= tt js2-XMLATTR)
10312 (js2-must-have-xml)
10313 (js2-parse-attribute-access))
10314 ((= tt js2-NAME)
10315 (js2-parse-name tt))
10316 ((= tt js2-NUMBER)
10317 (setq node (make-js2-number-node))
10318 (when (and js2-in-use-strict-directive
10319 (= (js2-number-node-num-base node) 8))
10320 (js2-report-error "msg.no.octal.literal"))
10321 node)
10322 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10323 (make-js2-string-node :type tt))
10324 ((= tt js2-TEMPLATE_HEAD)
10325 (js2-parse-template-literal))
10326 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10327 ;; Got / or /= which in this context means a regexp literal
10328 (let ((px-pos (js2-current-token-beg))
10329 (flags (js2-read-regexp tt))
10330 (end (js2-current-token-end)))
10331 (prog1
10332 (make-js2-regexp-node :pos px-pos
10333 :len (- end px-pos)
10334 :value (js2-current-token-string)
10335 :flags flags)
10336 (js2-set-face px-pos end 'font-lock-string-face 'record)
10337 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10338 ((or (= tt js2-NULL)
10339 (= tt js2-THIS)
10340 (= tt js2-SUPER)
10341 (= tt js2-FALSE)
10342 (= tt js2-TRUE))
10343 (make-js2-keyword-node :type tt))
10344 ((= tt js2-TRIPLEDOT)
10345 ;; Likewise, only valid in an arrow function with a rest param.
10346 (if (and (js2-match-token js2-NAME)
10347 (js2-match-token js2-RP)
10348 (eq (js2-peek-token) js2-ARROW))
10349 (progn
10350 (js2-unget-token) ; Put back the right paren.
10351 ;; See the previous case.
10352 (make-js2-keyword-node :type js2-NULL))
10353 (js2-report-error "msg.syntax")
10354 (make-js2-error-node)))
10355 ((= tt js2-RESERVED)
10356 (js2-report-error "msg.reserved.id")
10357 (make-js2-name-node))
10358 ((= tt js2-ERROR)
10359 ;; the scanner or one of its subroutines reported the error.
10360 (make-js2-error-node))
10361 ((= tt js2-EOF)
10362 (let* ((px-pos (point-at-bol))
10363 (len (- js2-ts-cursor px-pos)))
10364 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10365 (make-js2-error-node :pos (1- js2-ts-cursor)))
10366 (t
10367 (js2-report-error "msg.syntax")
10368 (make-js2-error-node)))))
10369
10370 (defun js2-parse-template-literal ()
10371 (let ((beg (js2-current-token-beg))
10372 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10373 (tt js2-TEMPLATE_HEAD))
10374 (while (eq tt js2-TEMPLATE_HEAD)
10375 (push (js2-parse-expr) kids)
10376 (js2-must-match js2-RC "msg.syntax")
10377 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10378 (push (make-js2-string-node :type tt) kids))
10379 (setq kids (nreverse kids))
10380 (let ((tpl (make-js2-template-node :beg beg
10381 :len (- (js2-current-token-end) beg)
10382 :kids kids)))
10383 (apply #'js2-node-add-children tpl kids)
10384 tpl)))
10385
10386 (defun js2-parse-name (_tt)
10387 (let ((name (js2-current-token-string))
10388 node)
10389 (setq node (if js2-compiler-xml-available
10390 (js2-parse-property-name nil name 0)
10391 (js2-create-name-node 'check-activation nil name)))
10392 (if js2-highlight-external-variables
10393 (js2-record-name-node node))
10394 node))
10395
10396 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10397 (js2-add-strict-warning
10398 msg nil
10399 ;; back up from comma to beginning of line or array/objlit
10400 (max (if elems
10401 (js2-node-pos (car elems))
10402 pos)
10403 (save-excursion
10404 (goto-char comma-pos)
10405 (back-to-indentation)
10406 (point)))
10407 comma-pos))
10408
10409 (defun js2-parse-array-comp-or-literal ()
10410 (let ((pos (js2-current-token-beg)))
10411 (if (and (>= js2-language-version 200)
10412 (js2-match-token js2-FOR))
10413 (js2-parse-array-comp pos)
10414 (js2-parse-array-literal pos))))
10415
10416 (defun js2-parse-array-literal (pos)
10417 (let ((after-lb-or-comma t)
10418 after-comma tt elems pn
10419 (continue t))
10420 (unless js2-is-in-destructuring
10421 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10422 (while continue
10423 (setq tt (js2-get-token))
10424 (cond
10425 ;; comma
10426 ((= tt js2-COMMA)
10427 (setq after-comma (js2-current-token-end))
10428 (if (not after-lb-or-comma)
10429 (setq after-lb-or-comma t)
10430 (push nil elems)))
10431 ;; end of array
10432 ((or (= tt js2-RB)
10433 (= tt js2-EOF)) ; prevent infinite loop
10434 (if (= tt js2-EOF)
10435 (js2-report-error "msg.no.bracket.arg" nil pos))
10436 (when (and after-comma (< js2-language-version 170))
10437 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10438 pos (remove nil elems) after-comma))
10439 (setq continue nil
10440 pn (make-js2-array-node :pos pos
10441 :len (- js2-ts-cursor pos)
10442 :elems (nreverse elems)))
10443 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10444 ;; destructuring binding
10445 (js2-is-in-destructuring
10446 (push (if (or (= tt js2-LC)
10447 (= tt js2-LB)
10448 (= tt js2-NAME))
10449 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10450 (js2-parse-destruct-primary-expr)
10451 ;; invalid pattern
10452 (js2-report-error "msg.bad.var")
10453 (make-js2-error-node))
10454 elems)
10455 (setq after-lb-or-comma nil
10456 after-comma nil))
10457 ;; array comp
10458 ((and (>= js2-language-version 170)
10459 (= tt js2-FOR) ; check for array comprehension
10460 (not after-lb-or-comma) ; "for" can't follow a comma
10461 elems ; must have at least 1 element
10462 (not (cdr elems))) ; but no 2nd element
10463 (js2-unget-token)
10464 (setf continue nil
10465 pn (js2-parse-legacy-array-comp (car elems) pos)))
10466 ;; another element
10467 (t
10468 (unless after-lb-or-comma
10469 (js2-report-error "msg.no.bracket.arg"))
10470 (if (and (= tt js2-TRIPLEDOT)
10471 (>= js2-language-version 200))
10472 ;; spread operator
10473 (push (js2-make-unary tt 'js2-parse-assign-expr)
10474 elems)
10475 (js2-unget-token)
10476 (push (js2-parse-assign-expr) elems))
10477 (setq after-lb-or-comma nil
10478 after-comma nil))))
10479 (unless js2-is-in-destructuring
10480 (js2-pop-scope))
10481 pn))
10482
10483 (defun js2-parse-legacy-array-comp (expr pos)
10484 "Parse a legacy array comprehension (JavaScript 1.7).
10485 EXPR is the first expression after the opening left-bracket.
10486 POS is the beginning of the LB token preceding EXPR.
10487 We should have just parsed the 'for' keyword before calling this function."
10488 (let ((current-scope js2-current-scope)
10489 loops first filter result)
10490 (unwind-protect
10491 (progn
10492 (while (js2-match-token js2-FOR)
10493 (let ((loop (make-js2-comp-loop-node)))
10494 (js2-push-scope loop)
10495 (push loop loops)
10496 (js2-parse-comp-loop loop)))
10497 ;; First loop takes expr scope's parent.
10498 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10499 (js2-scope-parent-scope current-scope))
10500 ;; Set expr scope's parent to the last loop.
10501 (setf (js2-scope-parent-scope current-scope) (car loops))
10502 (if (/= (js2-get-token) js2-IF)
10503 (js2-unget-token)
10504 (setq filter (js2-parse-condition))))
10505 (dotimes (_ (1- (length loops)))
10506 (js2-pop-scope)))
10507 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10508 (setq result (make-js2-comp-node :pos pos
10509 :len (- js2-ts-cursor pos)
10510 :result expr
10511 :loops (nreverse loops)
10512 :filters (and filter (list (car filter)))
10513 :form 'LEGACY_ARRAY))
10514 ;; Set comp loop's parent to the last loop.
10515 ;; TODO: Get rid of the bogus expr scope.
10516 (setf (js2-scope-parent-scope result) first)
10517 (apply #'js2-node-add-children result expr (car filter)
10518 (js2-comp-node-loops result))
10519 result))
10520
10521 (defun js2-parse-array-comp (pos)
10522 "Parse an ES6 array comprehension.
10523 POS is the beginning of the LB token.
10524 We should have just parsed the 'for' keyword before calling this function."
10525 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10526 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10527 pn))
10528
10529 (defun js2-parse-generator-comp (pos)
10530 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10531 (js2-current-script-or-fn
10532 (make-js2-function-node :generator-type 'COMPREHENSION))
10533 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10534 (js2-must-match js2-RP "msg.no.paren" pos)
10535 pn))
10536
10537 (defun js2-parse-comprehension (pos form)
10538 (let (loops filters expr result last)
10539 (unwind-protect
10540 (progn
10541 (js2-unget-token)
10542 (while (js2-match-token js2-FOR)
10543 (let ((loop (make-js2-comp-loop-node)))
10544 (js2-push-scope loop)
10545 (push loop loops)
10546 (js2-parse-comp-loop loop)))
10547 (while (js2-match-token js2-IF)
10548 (push (car (js2-parse-condition)) filters))
10549 (setq expr (js2-parse-assign-expr))
10550 (setq last (car loops)))
10551 (dolist (_ loops)
10552 (js2-pop-scope)))
10553 (setq result (make-js2-comp-node :pos pos
10554 :len (- js2-ts-cursor pos)
10555 :result expr
10556 :loops (nreverse loops)
10557 :filters (nreverse filters)
10558 :form form))
10559 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10560 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10561 (setf (js2-scope-parent-scope result) last)
10562 result))
10563
10564 (defun js2-parse-comp-loop (pn &optional only-of-p)
10565 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10566 The current token should be the initial FOR.
10567 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10568 (let ((pos (js2-comp-loop-node-pos pn))
10569 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10570 (when (and (not only-of-p) (js2-match-token js2-NAME))
10571 (if (string= (js2-current-token-string) "each")
10572 (progn
10573 (setq foreach-p t
10574 each-pos (- (js2-current-token-beg) pos)) ; relative
10575 (js2-record-face 'font-lock-keyword-face))
10576 (js2-report-error "msg.no.paren.for")))
10577 (if (js2-must-match js2-LP "msg.no.paren.for")
10578 (setq lp (- (js2-current-token-beg) pos)))
10579 (setq tt (js2-peek-token))
10580 (cond
10581 ((or (= tt js2-LB)
10582 (= tt js2-LC))
10583 (js2-get-token)
10584 (setq iter (js2-parse-destruct-primary-expr))
10585 (js2-define-destruct-symbols iter js2-LET
10586 'font-lock-variable-name-face t))
10587 ((js2-match-token js2-NAME)
10588 (setq iter (js2-create-name-node)))
10589 (t
10590 (js2-report-error "msg.bad.var")))
10591 ;; Define as a let since we want the scope of the variable to
10592 ;; be restricted to the array comprehension
10593 (if (js2-name-node-p iter)
10594 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10595 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10596 (and (>= js2-language-version 200)
10597 (js2-match-contextual-kwd "of")
10598 (setq forof-p t)))
10599 (setq in-pos (- (js2-current-token-beg) pos))
10600 (js2-report-error "msg.in.after.for.name"))
10601 (setq obj (js2-parse-expr))
10602 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10603 (setq rp (- (js2-current-token-beg) pos)))
10604 (setf (js2-node-pos pn) pos
10605 (js2-node-len pn) (- js2-ts-cursor pos)
10606 (js2-comp-loop-node-iterator pn) iter
10607 (js2-comp-loop-node-object pn) obj
10608 (js2-comp-loop-node-in-pos pn) in-pos
10609 (js2-comp-loop-node-each-pos pn) each-pos
10610 (js2-comp-loop-node-foreach-p pn) foreach-p
10611 (js2-comp-loop-node-forof-p pn) forof-p
10612 (js2-comp-loop-node-lp pn) lp
10613 (js2-comp-loop-node-rp pn) rp)
10614 (js2-node-add-children pn iter obj)
10615 pn))
10616
10617 (defun js2-parse-class-stmt ()
10618 (let ((pos (js2-current-token-beg))
10619 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10620 (name (js2-create-name-node t)))
10621 (js2-set-face (js2-node-pos name) (js2-node-end name)
10622 'font-lock-function-name-face 'record)
10623 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10624 (js2-define-symbol js2-FUNCTION
10625 (js2-name-node-name name)
10626 node)
10627 node)))
10628
10629 (defun js2-parse-class-expr ()
10630 (let ((pos (js2-current-token-beg))
10631 name)
10632 (when (js2-match-token js2-NAME)
10633 (setq name (js2-create-name-node t)))
10634 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10635
10636 (defun js2-parse-class (pos form name)
10637 ;; class X [extends ...] {
10638 (let (pn elems extends)
10639 (if (js2-match-token js2-EXTENDS)
10640 (if (= (js2-peek-token) js2-LC)
10641 (js2-report-error "msg.missing.extends")
10642 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10643 (setq extends (js2-parse-assign-expr))
10644 (if (not extends)
10645 (js2-report-error "msg.bad.extends"))))
10646 (js2-must-match js2-LC "msg.no.brace.class")
10647 (setq elems (js2-parse-object-literal-elems t)
10648 pn (make-js2-class-node :pos pos
10649 :len (- js2-ts-cursor pos)
10650 :form form
10651 :name name
10652 :extends extends
10653 :elems elems))
10654 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10655 pn))
10656
10657 (defun js2-parse-object-literal ()
10658 (let* ((pos (js2-current-token-beg))
10659 (elems (js2-parse-object-literal-elems))
10660 (result (make-js2-object-node :pos pos
10661 :len (- js2-ts-cursor pos)
10662 :elems elems)))
10663 (apply #'js2-node-add-children result (js2-object-node-elems result))
10664 result))
10665
10666 (defun js2-parse-object-literal-elems (&optional class-p)
10667 (let ((pos (js2-current-token-beg))
10668 (static nil)
10669 (continue t)
10670 tt elems elem after-comma previous-token)
10671 (while continue
10672 (setq tt (js2-get-prop-name-token)
10673 static nil
10674 elem nil
10675 previous-token nil)
10676 ;; Handle 'static' keyword only if we're in a class
10677 (when (and class-p (= js2-NAME tt)
10678 (string= "static" (js2-current-token-string)))
10679 (js2-record-face 'font-lock-keyword-face)
10680 (setq static t
10681 tt (js2-get-prop-name-token)))
10682 ;; Handle generator * before the property name for in-line functions
10683 (when (and (>= js2-language-version 200)
10684 (= js2-MUL tt))
10685 (setq previous-token (js2-current-token)
10686 tt (js2-get-prop-name-token)))
10687 ;; Handle 'get' or 'set' keywords
10688 (let ((prop (js2-current-token-string)))
10689 (when (and (>= js2-language-version 200)
10690 (= js2-NAME tt)
10691 (or (string= prop "get")
10692 (string= prop "set"))
10693 (member (js2-peek-token)
10694 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10695 (setq previous-token (js2-current-token)
10696 tt (js2-get-prop-name-token))))
10697 (cond
10698 ;; Found a property (of any sort)
10699 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10700 (setq after-comma nil
10701 elem (js2-parse-named-prop tt pos previous-token))
10702 (if (and (null elem)
10703 (not js2-recover-from-parse-errors))
10704 (setq continue nil)))
10705 ;; Break out of loop, and handle trailing commas.
10706 ((or (= tt js2-RC)
10707 (= tt js2-EOF))
10708 (js2-unget-token)
10709 (setq continue nil)
10710 (if after-comma
10711 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10712 pos elems after-comma)))
10713 (t
10714 (js2-report-error "msg.bad.prop")
10715 (unless js2-recover-from-parse-errors
10716 (setq continue nil)))) ; end switch
10717 ;; Handle static for classes' codegen.
10718 (if static
10719 (if elem (js2-node-set-prop elem 'STATIC t)
10720 (js2-report-error "msg.unexpected.static")))
10721 ;; Handle commas, depending on class-p.
10722 (let ((tok (js2-get-prop-name-token)))
10723 (if (eq tok js2-COMMA)
10724 (if class-p
10725 (js2-report-error "msg.class.unexpected.comma")
10726 (setq after-comma (js2-current-token-end)))
10727 (js2-unget-token)
10728 (unless class-p (setq continue nil))))
10729 ;; Append any parsed element.
10730 (if elem (push elem elems))) ; end loop
10731 (js2-must-match js2-RC "msg.no.brace.prop")
10732 (nreverse elems)))
10733
10734 (defun js2-parse-named-prop (tt pos previous-token)
10735 "Parse a name, string, or getter/setter object property.
10736 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10737 (let ((key (cond
10738 ;; Literal string keys: {'foo': 'bar'}
10739 ((= tt js2-STRING)
10740 (make-js2-string-node))
10741 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10742 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10743 ((and (= tt js2-LB)
10744 (>= js2-language-version 200))
10745 (prog1 (js2-parse-expr)
10746 (js2-must-match js2-RB "msg.missing.computed.rb")))
10747 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10748 ((= tt js2-NUMBER)
10749 (make-js2-number-node))
10750 ;; Unquoted names: {foo: 12}
10751 ((= tt js2-NAME)
10752 (js2-create-name-node))
10753 ;; Anything else is an error
10754 (t (js2-report-error "msg.bad.prop"))))
10755 (prop (and previous-token (js2-token-string previous-token)))
10756 (property-type (when previous-token
10757 (if (= (js2-token-type previous-token) js2-MUL)
10758 "*"
10759 (js2-token-string previous-token)))))
10760 (when (or (string= prop "get")
10761 (string= prop "set"))
10762 (js2-set-face (js2-token-beg previous-token)
10763 (js2-token-end previous-token)
10764 'font-lock-keyword-face 'record)) ; get/set
10765 (cond
10766 ;; method definition: {f() {...}}
10767 ((and (= (js2-peek-token) js2-LP)
10768 (>= js2-language-version 200))
10769 (when (js2-name-node-p key) ; highlight function name properties
10770 (js2-record-face 'font-lock-function-name-face))
10771 (js2-parse-getter-setter-prop pos key property-type))
10772 ;; regular prop
10773 (t
10774 (let ((beg (js2-current-token-beg))
10775 (end (js2-current-token-end))
10776 (expr (js2-parse-plain-property key)))
10777 (when (and (= tt js2-NAME)
10778 (not js2-is-in-destructuring)
10779 js2-highlight-external-variables
10780 (js2-node-get-prop expr 'SHORTHAND))
10781 (js2-record-name-node key))
10782 (js2-set-face beg end
10783 (if (js2-function-node-p
10784 (js2-object-prop-node-right expr))
10785 'font-lock-function-name-face
10786 'font-lock-variable-name-face)
10787 'record)
10788 expr)))))
10789
10790 (defun js2-parse-plain-property (prop)
10791 "Parse a non-getter/setter property in an object literal.
10792 PROP is the node representing the property: a number, name or string."
10793 (let* ((tt (js2-get-token))
10794 (pos (js2-node-pos prop))
10795 colon expr result)
10796 (cond
10797 ;; Abbreviated property, as in {foo, bar}
10798 ((and (>= js2-language-version 200)
10799 (or (= tt js2-COMMA)
10800 (= tt js2-RC))
10801 (not (js2-number-node-p prop)))
10802 (js2-unget-token)
10803 (setq result (make-js2-object-prop-node
10804 :pos pos
10805 :left prop
10806 :right prop
10807 :op-pos (js2-current-token-len)))
10808 (js2-node-add-children result prop)
10809 (js2-node-set-prop result 'SHORTHAND t)
10810 result)
10811 ;; Normal property
10812 (t
10813 (if (= tt js2-COLON)
10814 (setq colon (- (js2-current-token-beg) pos)
10815 expr (js2-parse-assign-expr))
10816 (js2-report-error "msg.no.colon.prop")
10817 (setq expr (make-js2-error-node)))
10818 (setq result (make-js2-object-prop-node
10819 :pos pos
10820 ;; don't include last consumed token in length
10821 :len (- (+ (js2-node-pos expr)
10822 (js2-node-len expr))
10823 pos)
10824 :left prop
10825 :right expr
10826 :op-pos colon))
10827 (js2-node-add-children result prop expr)
10828 result))))
10829
10830 (defun js2-parse-getter-setter-prop (pos prop type-string)
10831 "Parse getter or setter property in an object literal.
10832 JavaScript syntax is:
10833
10834 { get foo() {...}, set foo(x) {...} }
10835
10836 and expression closure style is also supported
10837
10838 { get foo() x, set foo(x) _x = x }
10839
10840 POS is the start position of the `get' or `set' keyword.
10841 PROP is the `js2-name-node' representing the property name.
10842 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10843 (let ((type (cond
10844 ((string= "get" type-string) js2-GET)
10845 ((string= "set" type-string) js2-SET)
10846 (t js2-FUNCTION)))
10847 result end
10848 (fn (js2-parse-function-expr)))
10849 ;; it has to be an anonymous function, as we already parsed the name
10850 (if (/= (js2-node-type fn) js2-FUNCTION)
10851 (js2-report-error "msg.bad.prop")
10852 (if (cl-plusp (length (js2-function-name fn)))
10853 (js2-report-error "msg.bad.prop")))
10854 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10855 (when (string= type-string "*")
10856 (setf (js2-function-node-generator-type fn) 'STAR))
10857 (setq end (js2-node-end fn)
10858 result (make-js2-getter-setter-node :type type
10859 :pos pos
10860 :len (- end pos)
10861 :left prop
10862 :right fn))
10863 (js2-node-add-children result prop fn)
10864 result))
10865
10866 (defun js2-create-name-node (&optional check-activation-p token string)
10867 "Create a name node using the current token and, optionally, STRING.
10868 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10869 (let* ((beg (js2-current-token-beg))
10870 (tt (js2-current-token-type))
10871 (s (or string
10872 (if (= js2-NAME tt)
10873 (js2-current-token-string)
10874 (js2-tt-name tt))))
10875 name)
10876 (setq name (make-js2-name-node :pos beg
10877 :name s
10878 :len (length s)))
10879 (if check-activation-p
10880 (js2-check-activation-name s (or token js2-NAME)))
10881 name))
10882
10883 ;;; Indentation support
10884
10885 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10886 ;; Karl cleverly deduces that the desired indentation level is often a
10887 ;; function of paren/bracket/brace nesting depth, which can be determined
10888 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10889 ;; then does some equally clever checks to see if we're in the context of a
10890 ;; substatement of a possibly braceless statement keyword such as if, while,
10891 ;; or finally. This approach yields pretty good results.
10892
10893 ;; The indenter is often "wrong", however, and needs to be overridden.
10894 ;; The right long-term solution is probably to emulate (or integrate
10895 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10896 ;; parse tree from `js2-parse' is present, which is not true at the
10897 ;; moment the user is typing, computing indentation is still thousands
10898 ;; of lines of code to handle every possible syntactic edge case.
10899
10900 ;; In the meantime, the compromise solution is that we offer a "bounce
10901 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10902 ;; current line indent among various likely guess points. This approach
10903 ;; is far from perfect, but should at least make it slightly easier to
10904 ;; move the line towards its desired indentation when manually
10905 ;; overriding Karl's heuristic nesting guesser.
10906
10907 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10908 ;; extensions such as `let' and Array comprehensions. Major kudos to
10909 ;; Karl for coming up with the initial approach, which packs a lot of
10910 ;; punch for so little code.
10911
10912 (defconst js2-possibly-braceless-keywords-re
10913 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10914 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10915 "try" "while" "with" "let")))
10916 "Regular expression matching keywords that are optionally
10917 followed by an opening brace.")
10918
10919 (defconst js2-indent-operator-re
10920 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10921 (regexp-opt '("in" "instanceof") 'words))
10922 "Regular expression matching operators that affect indentation
10923 of continued expressions.")
10924
10925 (defconst js2-declaration-keyword-re
10926 (regexp-opt '("var" "let" "const") 'words)
10927 "Regular expression matching variable declaration keywords.")
10928
10929 (defun js2-re-search-forward-inner (regexp &optional bound count)
10930 "Auxiliary function for `js2-re-search-forward'."
10931 (let (parse saved-point)
10932 (while (> count 0)
10933 (re-search-forward regexp bound)
10934 (setq parse (if saved-point
10935 (parse-partial-sexp saved-point (point))
10936 (syntax-ppss (point))))
10937 (cond ((nth 3 parse)
10938 (re-search-forward
10939 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10940 (save-excursion (end-of-line) (point)) t))
10941 ((nth 7 parse)
10942 (forward-line))
10943 ((or (nth 4 parse)
10944 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10945 (re-search-forward "\\*/"))
10946 (t
10947 (setq count (1- count))))
10948 (setq saved-point (point))))
10949 (point))
10950
10951 (defun js2-re-search-forward (regexp &optional bound noerror count)
10952 "Search forward but ignore strings and comments.
10953 Invokes `re-search-forward' but treats the buffer as if strings
10954 and comments have been removed."
10955 (let ((saved-point (point)))
10956 (condition-case err
10957 (cond ((null count)
10958 (js2-re-search-forward-inner regexp bound 1))
10959 ((< count 0)
10960 (js2-re-search-backward-inner regexp bound (- count)))
10961 ((> count 0)
10962 (js2-re-search-forward-inner regexp bound count)))
10963 (search-failed
10964 (goto-char saved-point)
10965 (unless noerror
10966 (error (error-message-string err)))))))
10967
10968 (defun js2-re-search-backward-inner (regexp &optional bound count)
10969 "Auxiliary function for `js2-re-search-backward'."
10970 (let (parse)
10971 (while (> count 0)
10972 (re-search-backward regexp bound)
10973 (setq parse (syntax-ppss (point)))
10974 (cond ((nth 3 parse)
10975 (re-search-backward
10976 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10977 (line-beginning-position) t))
10978 ((nth 7 parse)
10979 (goto-char (nth 8 parse)))
10980 ((or (nth 4 parse)
10981 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10982 (re-search-backward "/\\*"))
10983 (t
10984 (setq count (1- count))))))
10985 (point))
10986
10987 (defun js2-re-search-backward (regexp &optional bound noerror count)
10988 "Search backward but ignore strings and comments.
10989 Invokes `re-search-backward' but treats the buffer as if strings
10990 and comments have been removed."
10991 (let ((saved-point (point)))
10992 (condition-case err
10993 (cond ((null count)
10994 (js2-re-search-backward-inner regexp bound 1))
10995 ((< count 0)
10996 (js2-re-search-forward-inner regexp bound (- count)))
10997 ((> count 0)
10998 (js2-re-search-backward-inner regexp bound count)))
10999 (search-failed
11000 (goto-char saved-point)
11001 (unless noerror
11002 (error (error-message-string err)))))))
11003
11004 (defun js2-looking-at-operator-p ()
11005 "Return non-nil if text after point is a non-comma operator."
11006 (and (looking-at js2-indent-operator-re)
11007 (or (not (looking-at ":"))
11008 (save-excursion
11009 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
11010 (looking-at "?"))))))
11011
11012 (defun js2-continued-expression-p ()
11013 "Return non-nil if the current line continues an expression."
11014 (save-excursion
11015 (back-to-indentation)
11016 (or (js2-looking-at-operator-p)
11017 (when (catch 'found
11018 (while (and (re-search-backward "\n" nil t)
11019 (let ((state (syntax-ppss)))
11020 (when (nth 4 state)
11021 (goto-char (nth 8 state))) ;; skip comments
11022 (skip-chars-backward " \t")
11023 (if (bolp)
11024 t
11025 (throw 'found t))))))
11026 (backward-char)
11027 (when (js2-looking-at-operator-p)
11028 (backward-char)
11029 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
11030
11031 (defun js2-end-of-do-while-loop-p ()
11032 "Return non-nil if word after point is `while' of a do-while
11033 statement, else returns nil. A braceless do-while statement
11034 spanning several lines requires that the start of the loop is
11035 indented to the same column as the current line."
11036 (interactive)
11037 (save-excursion
11038 (when (looking-at "\\s-*\\<while\\>")
11039 (if (save-excursion
11040 (skip-chars-backward "[ \t\n]*}")
11041 (looking-at "[ \t\n]*}"))
11042 (save-excursion
11043 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
11044 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
11045 (or (looking-at "\\<do\\>")
11046 (let ((saved-indent (current-indentation)))
11047 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
11048 (/= (current-indentation) saved-indent)))
11049 (and (looking-at "[ \t]*\\<do\\>")
11050 (not (js2-re-search-forward
11051 "\\<while\\>" (point-at-eol) t))
11052 (= (current-indentation) saved-indent))))))))
11053
11054 (defun js2-multiline-decl-indentation ()
11055 "Return the declaration indentation column if the current line belongs
11056 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
11057 (let (forward-sexp-function ; use Lisp version
11058 at-opening-bracket)
11059 (save-excursion
11060 (back-to-indentation)
11061 (when (not (looking-at js2-declaration-keyword-re))
11062 (when (looking-at js2-indent-operator-re)
11063 (goto-char (match-end 0))) ; continued expressions are ok
11064 (while (and (not at-opening-bracket)
11065 (not (bobp))
11066 (let ((pos (point)))
11067 (save-excursion
11068 (js2-backward-sws)
11069 (or (eq (char-before) ?,)
11070 (and (not (eq (char-before) ?\;))
11071 (prog2 (skip-syntax-backward ".")
11072 (looking-at js2-indent-operator-re)
11073 (js2-backward-sws))
11074 (not (eq (char-before) ?\;)))
11075 (js2-same-line pos)))))
11076 (condition-case _
11077 (backward-sexp)
11078 (scan-error (setq at-opening-bracket t))))
11079 (when (looking-at js2-declaration-keyword-re)
11080 (goto-char (match-end 0))
11081 (1+ (current-column)))))))
11082
11083 (defun js2-ctrl-statement-indentation ()
11084 "Return the proper indentation of current line if it is a control statement.
11085 Returns an indentation if this line starts the body of a control
11086 statement without braces, else returns nil."
11087 (let (forward-sexp-function)
11088 (save-excursion
11089 (back-to-indentation)
11090 (when (and (not (js2-same-line (point-min)))
11091 (not (looking-at "{"))
11092 (js2-re-search-backward "[[:graph:]]" nil t)
11093 (not (looking-at "[{([]"))
11094 (progn
11095 (forward-char)
11096 (when (= (char-before) ?\))
11097 ;; scan-sexps sometimes throws an error
11098 (ignore-errors (backward-sexp))
11099 (skip-chars-backward " \t" (point-at-bol)))
11100 (let ((pt (point)))
11101 (back-to-indentation)
11102 (when (looking-at "}[ \t]*")
11103 (goto-char (match-end 0)))
11104 (and (looking-at js2-possibly-braceless-keywords-re)
11105 (= (match-end 0) pt)
11106 (not (js2-end-of-do-while-loop-p))))))
11107 (+ (current-indentation) js2-basic-offset)))))
11108
11109 (defun js2-indent-in-array-comp (parse-status)
11110 "Return non-nil if we think we're in an array comprehension.
11111 In particular, return the buffer position of the first `for' kwd."
11112 (let ((bracket (nth 1 parse-status))
11113 (end (point)))
11114 (when bracket
11115 (save-excursion
11116 (goto-char bracket)
11117 (when (looking-at "\\[")
11118 (forward-char 1)
11119 (js2-forward-sws)
11120 (if (looking-at "[[{]")
11121 (let (forward-sexp-function) ; use Lisp version
11122 (forward-sexp) ; skip destructuring form
11123 (js2-forward-sws)
11124 (if (and (/= (char-after) ?,) ; regular array
11125 (looking-at "for"))
11126 (match-beginning 0)))
11127 ;; to skip arbitrary expressions we need the parser,
11128 ;; so we'll just guess at it.
11129 (if (and (> end (point)) ; not empty literal
11130 (re-search-forward "[^,]]* \\(for\\) " end t)
11131 ;; not inside comment or string literal
11132 (let ((state (parse-partial-sexp bracket (point))))
11133 (not (or (nth 3 state) (nth 4 state)))))
11134 (match-beginning 1))))))))
11135
11136 (defun js2-array-comp-indentation (parse-status for-kwd)
11137 (if (js2-same-line for-kwd)
11138 ;; first continuation line
11139 (save-excursion
11140 (goto-char (nth 1 parse-status))
11141 (forward-char 1)
11142 (skip-chars-forward " \t")
11143 (current-column))
11144 (save-excursion
11145 (goto-char for-kwd)
11146 (current-column))))
11147
11148 (defun js2-maybe-goto-declaration-keyword-end (bracket)
11149 "Helper function for `js2-proper-indentation'.
11150 Depending on the value of `js2-pretty-multiline-declarations',
11151 move point to the end of a variable declaration keyword so that
11152 indentation is aligned to that column."
11153 (cond
11154 ((eq js2-pretty-multiline-declarations 'all)
11155 (when (looking-at js2-declaration-keyword-re)
11156 (goto-char (1+ (match-end 0)))))
11157 ((eq js2-pretty-multiline-declarations 'dynamic)
11158 (let (declaration-keyword-end
11159 at-closing-bracket-p
11160 comma-p)
11161 (when (looking-at js2-declaration-keyword-re)
11162 ;; Preserve the match data lest it somehow be overridden.
11163 (setq declaration-keyword-end (match-end 0))
11164 (save-excursion
11165 (goto-char bracket)
11166 (setq at-closing-bracket-p
11167 ;; Handle scan errors gracefully.
11168 (condition-case nil
11169 (progn
11170 ;; Use the regular `forward-sexp-function' because the
11171 ;; normal one for this mode uses the AST.
11172 (let (forward-sexp-function)
11173 (forward-sexp))
11174 t)
11175 (error nil)))
11176 (when at-closing-bracket-p
11177 (js2-forward-sws)
11178 (setq comma-p (looking-at-p ","))))
11179 (when comma-p
11180 (goto-char (1+ declaration-keyword-end))))))))
11181
11182 (defun js2-proper-indentation (parse-status)
11183 "Return the proper indentation for the current line."
11184 (save-excursion
11185 (back-to-indentation)
11186 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
11187 (at-closing-bracket (looking-at "[]})]"))
11188 (same-indent-p (or at-closing-bracket
11189 (looking-at "\\<case\\>[^:]")
11190 (and (looking-at "\\<default:")
11191 (save-excursion
11192 (js2-backward-sws)
11193 (not (memq (char-before) '(?, ?{)))))))
11194 (continued-expr-p (js2-continued-expression-p))
11195 (declaration-indent (and js2-pretty-multiline-declarations
11196 (js2-multiline-decl-indentation)))
11197 (bracket (nth 1 parse-status))
11198 beg indent)
11199 (cond
11200 ;; indent array comprehension continuation lines specially
11201 ((and bracket
11202 (>= js2-language-version 170)
11203 (not (js2-same-line bracket))
11204 (setq beg (js2-indent-in-array-comp parse-status))
11205 (>= (point) (save-excursion
11206 (goto-char beg)
11207 (point-at-bol)))) ; at or after first loop?
11208 (js2-array-comp-indentation parse-status beg))
11209
11210 (ctrl-stmt-indent)
11211
11212 ((and declaration-indent continued-expr-p)
11213 (+ declaration-indent js2-basic-offset))
11214
11215 (declaration-indent)
11216
11217 (bracket
11218 (goto-char bracket)
11219 (cond
11220 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
11221 (when (save-excursion (skip-chars-backward " \t)")
11222 (looking-at ")"))
11223 (backward-list))
11224 (back-to-indentation)
11225 (js2-maybe-goto-declaration-keyword-end bracket)
11226 (setq indent
11227 (cond (same-indent-p
11228 (current-column))
11229 (continued-expr-p
11230 (+ (current-column) (* 2 js2-basic-offset)))
11231 (t
11232 (+ (current-column) js2-basic-offset))))
11233 (if (and js2-indent-switch-body
11234 (not at-closing-bracket)
11235 (looking-at "\\_<switch\\_>"))
11236 (+ indent js2-basic-offset)
11237 indent))
11238 (t
11239 (unless same-indent-p
11240 (forward-char)
11241 (skip-chars-forward " \t"))
11242 (current-column))))
11243
11244 (continued-expr-p js2-basic-offset)
11245
11246 (t 0)))))
11247
11248 (defun js2-lineup-comment (parse-status)
11249 "Indent a multi-line block comment continuation line."
11250 (let* ((beg (nth 8 parse-status))
11251 (first-line (js2-same-line beg))
11252 (offset (save-excursion
11253 (goto-char beg)
11254 (if (looking-at "/\\*")
11255 (+ 1 (current-column))
11256 0))))
11257 (unless first-line
11258 (indent-line-to offset))))
11259
11260 (defun js2-backward-sws ()
11261 "Move backward through whitespace and comments."
11262 (interactive)
11263 (while (forward-comment -1)))
11264
11265 (defun js2-forward-sws ()
11266 "Move forward through whitespace and comments."
11267 (interactive)
11268 (while (forward-comment 1)))
11269
11270 (defun js2-current-indent (&optional pos)
11271 "Return column of indentation on current line.
11272 If POS is non-nil, go to that point and return indentation for that line."
11273 (save-excursion
11274 (if pos
11275 (goto-char pos))
11276 (back-to-indentation)
11277 (current-column)))
11278
11279 (defun js2-arglist-close ()
11280 "Return non-nil if we're on a line beginning with a close-paren/brace."
11281 (save-excursion
11282 (goto-char (point-at-bol))
11283 (js2-forward-sws)
11284 (looking-at "[])}]")))
11285
11286 (defun js2-indent-looks-like-label-p ()
11287 (goto-char (point-at-bol))
11288 (js2-forward-sws)
11289 (looking-at (concat js2-mode-identifier-re ":")))
11290
11291 (defun js2-indent-in-objlit-p (parse-status)
11292 "Return non-nil if this looks like an object-literal entry."
11293 (let ((start (nth 1 parse-status)))
11294 (and
11295 start
11296 (save-excursion
11297 (and (zerop (forward-line -1))
11298 (not (< (point) start)) ; crossed a {} boundary
11299 (js2-indent-looks-like-label-p)))
11300 (save-excursion
11301 (js2-indent-looks-like-label-p)))))
11302
11303 ;; If prev line looks like foobar({ then we're passing an object
11304 ;; literal to a function call, and people pretty much always want to
11305 ;; de-dent back to the previous line, so move the 'basic-offset'
11306 ;; position to the front.
11307 (defun js2-indent-objlit-arg-p (parse-status)
11308 (save-excursion
11309 (back-to-indentation)
11310 (js2-backward-sws)
11311 (and (eq (1- (point)) (nth 1 parse-status))
11312 (eq (char-before) ?{)
11313 (progn
11314 (forward-char -1)
11315 (skip-chars-backward " \t")
11316 (eq (char-before) ?\()))))
11317
11318 (defun js2-indent-case-block-p ()
11319 (save-excursion
11320 (back-to-indentation)
11321 (js2-backward-sws)
11322 (goto-char (point-at-bol))
11323 (skip-chars-forward " \t")
11324 (looking-at "case\\s-.+:")))
11325
11326 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
11327 "Cycle among alternate computed indentation positions.
11328 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11329 of the buffer to the current point. NORMAL-COL is the indentation
11330 column computed by the heuristic guesser based on current paren,
11331 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11332 in reverse."
11333 (let ((cur-indent (js2-current-indent))
11334 (old-buffer-undo-list buffer-undo-list)
11335 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11336 (current-line (save-excursion
11337 (forward-line 0) ; move to bol
11338 (1+ (count-lines (point-min) (point)))))
11339 positions pos main-pos anchor arglist-cont same-indent
11340 basic-offset computed-pos)
11341 ;; temporarily don't record undo info, if user requested this
11342 (when js2-mode-indent-inhibit-undo
11343 (setq buffer-undo-list t))
11344 (unwind-protect
11345 (progn
11346 ;; First likely point: indent from beginning of previous code line
11347 (push (setq basic-offset
11348 (+ (save-excursion
11349 (back-to-indentation)
11350 (js2-backward-sws)
11351 (back-to-indentation)
11352 (current-column))
11353 js2-basic-offset))
11354 positions)
11355
11356 ;; (First + epsilon) likely point: indent 2x from beginning of
11357 ;; previous code line. Google does it this way.
11358 (push (setq basic-offset
11359 (+ (save-excursion
11360 (back-to-indentation)
11361 (js2-backward-sws)
11362 (back-to-indentation)
11363 (current-column))
11364 (* 2 js2-basic-offset)))
11365 positions)
11366
11367 ;; Second likely point: indent from assign-expr RHS. This
11368 ;; is just a crude guess based on finding " = " on the previous
11369 ;; line containing actual code.
11370 (setq pos (save-excursion
11371 (forward-line -1)
11372 (goto-char (point-at-bol))
11373 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11374 (point-at-eol) t)
11375 (goto-char (match-end 1))
11376 (skip-chars-forward " \t\r\n")
11377 (current-column))))
11378 (when pos
11379 (cl-incf pos js2-basic-offset)
11380 (push pos positions))
11381
11382 ;; Third likely point: same indent as previous line of code.
11383 ;; Make it the first likely point if we're not on an
11384 ;; arglist-close line and previous line ends in a comma, or
11385 ;; both this line and prev line look like object-literal
11386 ;; elements.
11387 (setq pos (save-excursion
11388 (goto-char (point-at-bol))
11389 (js2-backward-sws)
11390 (back-to-indentation)
11391 (prog1
11392 (current-column)
11393 ;; while we're here, look for trailing comma
11394 (if (save-excursion
11395 (goto-char (point-at-eol))
11396 (js2-backward-sws)
11397 (eq (char-before) ?,))
11398 (setq arglist-cont (1- (point)))))))
11399 (when pos
11400 (if (and (or arglist-cont
11401 (js2-indent-in-objlit-p parse-status))
11402 (not (js2-arglist-close)))
11403 (setq same-indent pos))
11404 (push pos positions))
11405
11406 ;; Fourth likely point: first preceding code with less indentation.
11407 ;; than the immediately preceding code line.
11408 (setq pos (save-excursion
11409 (back-to-indentation)
11410 (js2-backward-sws)
11411 (back-to-indentation)
11412 (setq anchor (current-column))
11413 (while (and (zerop (forward-line -1))
11414 (>= (progn
11415 (back-to-indentation)
11416 (current-column))
11417 anchor)))
11418 (setq pos (current-column))))
11419 (push pos positions)
11420
11421 ;; nesting-heuristic position, main by default
11422 (push (setq main-pos normal-col) positions)
11423
11424 ;; delete duplicates and sort positions list
11425 (setq positions (sort (delete-dups positions) '<))
11426
11427 ;; comma-list continuation lines: prev line indent takes precedence
11428 (if same-indent
11429 (setq main-pos same-indent))
11430
11431 ;; common special cases where we want to indent in from previous line
11432 (if (or (js2-indent-case-block-p)
11433 (js2-indent-objlit-arg-p parse-status))
11434 (setq main-pos basic-offset))
11435
11436 ;; if bouncing backwards, reverse positions list
11437 (if backwards
11438 (setq positions (reverse positions)))
11439
11440 ;; record whether we're already sitting on one of the alternatives
11441 (setq pos (member cur-indent positions))
11442
11443 (cond
11444 ;; case 0: we're one one of the alternatives and this is the
11445 ;; first time they've pressed TAB on this line (best-guess).
11446 ((and js2-mode-indent-ignore-first-tab
11447 pos
11448 ;; first time pressing TAB on this line?
11449 (not (eq js2-mode-last-indented-line current-line)))
11450 ;; do nothing
11451 (setq computed-pos nil))
11452 ;; case 1: only one computed position => use it
11453 ((null (cdr positions))
11454 (setq computed-pos 0))
11455 ;; case 2: not on any of the computed spots => use main spot
11456 ((not pos)
11457 (setq computed-pos (js2-position main-pos positions)))
11458 ;; case 3: on last position: cycle to first position
11459 ((null (cdr pos))
11460 (setq computed-pos 0))
11461 ;; case 4: on intermediate position: cycle to next position
11462 (t
11463 (setq computed-pos (js2-position (cl-second pos) positions))))
11464
11465 ;; see if any hooks want to indent; otherwise we do it
11466 (cl-loop with result = nil
11467 for hook in js2-indent-hook
11468 while (null result)
11469 do
11470 (setq result (funcall hook positions computed-pos))
11471 finally do
11472 (unless (or result (null computed-pos))
11473 (indent-line-to (nth computed-pos positions)))))
11474
11475 ;; finally
11476 (if js2-mode-indent-inhibit-undo
11477 (setq buffer-undo-list old-buffer-undo-list))
11478 ;; see commentary for `js2-mode-last-indented-line'
11479 (setq js2-mode-last-indented-line current-line))))
11480
11481 (defun js2-indent-bounce-backwards ()
11482 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11483 cycles between the computed indentation positions in reverse order."
11484 (interactive)
11485 (js2-indent-line t))
11486
11487 (defun js2-1-line-comment-continuation-p ()
11488 "Return t if we're in a 1-line comment continuation.
11489 If so, we don't ever want to use bounce-indent."
11490 (save-excursion
11491 (and (progn
11492 (forward-line 0)
11493 (looking-at "\\s-*//"))
11494 (progn
11495 (forward-line -1)
11496 (forward-line 0)
11497 (when (looking-at "\\s-*$")
11498 (js2-backward-sws)
11499 (forward-line 0))
11500 (looking-at "\\s-*//")))))
11501
11502 (defun js2-indent-line (&optional bounce-backwards)
11503 "Indent the current line as JavaScript source text."
11504 (interactive)
11505 (let (parse-status offset indent-col
11506 ;; Don't whine about errors/warnings when we're indenting.
11507 ;; This has to be set before calling parse-partial-sexp below.
11508 (inhibit-point-motion-hooks t))
11509 (setq parse-status (save-excursion
11510 (syntax-ppss (point-at-bol)))
11511 offset (- (point) (save-excursion
11512 (back-to-indentation)
11513 (point))))
11514 ;; Don't touch multiline strings.
11515 (unless (nth 3 parse-status)
11516 (js2-with-underscore-as-word-syntax
11517 (if (nth 4 parse-status)
11518 (js2-lineup-comment parse-status)
11519 (setq indent-col (js2-proper-indentation parse-status))
11520 ;; See comments below about `js2-mode-last-indented-line'.
11521 (cond
11522 ;; bounce-indenting is disabled during electric-key indent.
11523 ;; It doesn't work well on first line of buffer.
11524 ((and js2-bounce-indent-p
11525 (not (js2-same-line (point-min)))
11526 (not (js2-1-line-comment-continuation-p)))
11527 (js2-bounce-indent indent-col parse-status bounce-backwards))
11528 ;; just indent to the guesser's likely spot
11529 (t (indent-line-to indent-col))))
11530 (when (cl-plusp offset)
11531 (forward-char offset))))))
11532
11533 (defun js2-indent-region (start end)
11534 "Indent the region, but don't use bounce indenting."
11535 (let ((js2-bounce-indent-p nil)
11536 (indent-region-function nil)
11537 (after-change-functions (remq 'js2-mode-edit
11538 after-change-functions)))
11539 (indent-region start end nil) ; nil for byte-compiler
11540 (js2-mode-edit start end (- end start))))
11541
11542 (defvar js2-minor-mode-map
11543 (let ((map (make-sparse-keymap)))
11544 (define-key map (kbd "C-c C-`") #'js2-next-error)
11545 (define-key map [mouse-1] #'js2-mode-show-node)
11546 map)
11547 "Keymap used when `js2-minor-mode' is active.")
11548
11549 ;;;###autoload
11550 (define-minor-mode js2-minor-mode
11551 "Minor mode for running js2 as a background linter.
11552 This allows you to use a different major mode for JavaScript editing,
11553 such as `js-mode', while retaining the asynchronous error/warning
11554 highlighting features of `js2-mode'."
11555 :group 'js2-mode
11556 :lighter " js-lint"
11557 (if js2-minor-mode
11558 (js2-minor-mode-enter)
11559 (js2-minor-mode-exit)))
11560
11561 (defun js2-minor-mode-enter ()
11562 "Initialization for `js2-minor-mode'."
11563 (set (make-local-variable 'max-lisp-eval-depth)
11564 (max max-lisp-eval-depth 3000))
11565 (setq next-error-function #'js2-next-error)
11566 (js2-set-default-externs)
11567 ;; Experiment: make reparse-delay longer for longer files.
11568 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11569 (setq js2-idle-timer-delay
11570 (* js2-idle-timer-delay
11571 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11572 (setq js2-mode-buffer-dirty-p t
11573 js2-mode-parsing nil)
11574 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11575 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11576 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11577 (when js2-include-jslint-globals
11578 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11579 (run-hooks 'js2-init-hook)
11580 (js2-reparse))
11581
11582 (defun js2-minor-mode-exit ()
11583 "Turn off `js2-minor-mode'."
11584 (setq next-error-function nil)
11585 (remove-hook 'after-change-functions #'js2-mode-edit t)
11586 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11587 (when js2-mode-node-overlay
11588 (delete-overlay js2-mode-node-overlay)
11589 (setq js2-mode-node-overlay nil))
11590 (js2-remove-overlays)
11591 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11592 (setq js2-mode-ast nil))
11593
11594 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11595 (make-variable-buffer-local 'js2-source-buffer)
11596
11597 (cl-defun js2-display-error-list ()
11598 "Display a navigable buffer listing parse errors/warnings."
11599 (interactive)
11600 (unless (js2-have-errors-p)
11601 (message "No errors")
11602 (cl-return-from js2-display-error-list))
11603 (cl-labels ((annotate-list
11604 (lst type)
11605 "Add diagnostic TYPE and line number to errs list"
11606 (mapcar (lambda (err)
11607 (list err type (line-number-at-pos (nth 1 err))))
11608 lst)))
11609 (let* ((srcbuf (current-buffer))
11610 (errbuf (get-buffer-create "*js-lint*"))
11611 (errors (annotate-list
11612 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11613 'js2-error)) ; must be a valid face name
11614 (warnings (annotate-list
11615 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11616 'js2-warning)) ; must be a valid face name
11617 (all-errs (sort (append errors warnings)
11618 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11619 (with-current-buffer errbuf
11620 (let ((inhibit-read-only t))
11621 (erase-buffer)
11622 (dolist (err all-errs)
11623 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11624 (insert-text-button
11625 (format "line %d: %s" line (js2-get-msg msg-key))
11626 'face type
11627 'follow-link "\C-m"
11628 'action 'js2-error-buffer-jump
11629 'js2-msg (js2-get-msg msg-key)
11630 'js2-pos beg)
11631 (insert "\n"))))
11632 (js2-error-buffer-mode)
11633 (setq js2-source-buffer srcbuf)
11634 (pop-to-buffer errbuf)
11635 (goto-char (point-min))
11636 (unless (eobp)
11637 (js2-error-buffer-view))))))
11638
11639 (defvar js2-error-buffer-mode-map
11640 (let ((map (make-sparse-keymap)))
11641 (define-key map "n" #'js2-error-buffer-next)
11642 (define-key map "p" #'js2-error-buffer-prev)
11643 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11644 (define-key map "o" #'js2-error-buffer-view)
11645 (define-key map "q" #'js2-error-buffer-quit)
11646 map)
11647 "Keymap used for js2 diagnostics buffers.")
11648
11649 (defun js2-error-buffer-mode ()
11650 "Major mode for js2 diagnostics buffers.
11651 Selecting an error will jump it to the corresponding source-buffer error.
11652 \\{js2-error-buffer-mode-map}"
11653 (interactive)
11654 (setq major-mode 'js2-error-buffer-mode
11655 mode-name "JS Lint Diagnostics")
11656 (use-local-map js2-error-buffer-mode-map)
11657 (setq truncate-lines t)
11658 (set-buffer-modified-p nil)
11659 (setq buffer-read-only t)
11660 (run-hooks 'js2-error-buffer-mode-hook))
11661
11662 (defun js2-error-buffer-next ()
11663 "Move to next error and view it."
11664 (interactive)
11665 (when (zerop (forward-line 1))
11666 (js2-error-buffer-view)))
11667
11668 (defun js2-error-buffer-prev ()
11669 "Move to previous error and view it."
11670 (interactive)
11671 (when (zerop (forward-line -1))
11672 (js2-error-buffer-view)))
11673
11674 (defun js2-error-buffer-quit ()
11675 "Kill the current buffer."
11676 (interactive)
11677 (kill-buffer))
11678
11679 (defun js2-error-buffer-jump (&rest ignored)
11680 "Jump cursor to current error in source buffer."
11681 (interactive)
11682 (when (js2-error-buffer-view)
11683 (pop-to-buffer js2-source-buffer)))
11684
11685 (defun js2-error-buffer-view ()
11686 "Scroll source buffer to show error at current line."
11687 (interactive)
11688 (cond
11689 ((not (eq major-mode 'js2-error-buffer-mode))
11690 (message "Not in a js2 errors buffer"))
11691 ((not (buffer-live-p js2-source-buffer))
11692 (message "Source buffer has been killed"))
11693 ((not (wholenump (get-text-property (point) 'js2-pos)))
11694 (message "There does not seem to be an error here"))
11695 (t
11696 (let ((pos (get-text-property (point) 'js2-pos))
11697 (msg (get-text-property (point) 'js2-msg)))
11698 (save-selected-window
11699 (pop-to-buffer js2-source-buffer)
11700 (goto-char pos)
11701 (message msg))))))
11702
11703 ;;;###autoload
11704 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11705 ;; FIXME: Should derive from js-mode.
11706 "Major mode for editing JavaScript code."
11707 ;; Used by comment-region; don't change it.
11708 (set (make-local-variable 'comment-start) "//")
11709 (set (make-local-variable 'comment-end) "")
11710 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11711 (set (make-local-variable 'max-lisp-eval-depth)
11712 (max max-lisp-eval-depth 3000))
11713 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11714 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11715 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11716 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11717 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11718 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11719 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11720 ;; for characters inside regexp literals.
11721 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11722 ;; this is necessary to make `show-paren-function' work properly
11723 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11724 ;; needed for M-x rgrep, among other things
11725 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11726
11727 (set (make-local-variable 'electric-indent-chars)
11728 (append "{}()[]:;,*." electric-indent-chars))
11729 (set (make-local-variable 'electric-layout-rules)
11730 '((?\; . after) (?\{ . after) (?\} . before)))
11731
11732 ;; some variables needed by cc-engine for paragraph-fill, etc.
11733 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11734 c-comment-start-regexp "/[*/]\\|\\s|"
11735 c-line-comment-starter "//"
11736 c-paragraph-start js2-paragraph-start
11737 c-paragraph-separate "$"
11738 c-syntactic-ws-start js2-syntactic-ws-start
11739 c-syntactic-ws-end js2-syntactic-ws-end
11740 c-syntactic-eol js2-syntactic-eol)
11741
11742 (let ((c-buffer-is-cc-mode t))
11743 ;; Copied from `js-mode'. Also see Bug#6071.
11744 (make-local-variable 'paragraph-start)
11745 (make-local-variable 'paragraph-separate)
11746 (make-local-variable 'paragraph-ignore-fill-prefix)
11747 (make-local-variable 'adaptive-fill-mode)
11748 (make-local-variable 'adaptive-fill-regexp)
11749 (c-setup-paragraph-variables))
11750
11751 (setq font-lock-defaults '(nil t))
11752
11753 ;; Experiment: make reparse-delay longer for longer files.
11754 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11755 (setq js2-idle-timer-delay
11756 (* js2-idle-timer-delay
11757 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11758
11759 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11760 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11761 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11762 (setq next-error-function #'js2-next-error)
11763 (imenu-add-to-menubar (concat "IM-" mode-name))
11764 (add-to-invisibility-spec '(js2-outline . t))
11765 (set (make-local-variable 'line-move-ignore-invisible) t)
11766 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11767 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11768
11769 (setq js2-mode-functions-hidden nil
11770 js2-mode-comments-hidden nil
11771 js2-mode-buffer-dirty-p t
11772 js2-mode-parsing nil)
11773
11774 (js2-set-default-externs)
11775
11776 (when js2-include-jslint-globals
11777 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11778
11779 (run-hooks 'js2-init-hook)
11780
11781 (js2-reparse))
11782
11783 (defun js2-mode-exit ()
11784 "Exit `js2-mode' and clean up."
11785 (interactive)
11786 (when js2-mode-node-overlay
11787 (delete-overlay js2-mode-node-overlay)
11788 (setq js2-mode-node-overlay nil))
11789 (js2-remove-overlays)
11790 (setq js2-mode-ast nil)
11791 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11792 (remove-from-invisibility-spec '(js2-outline . t))
11793 (js2-mode-show-all)
11794 (with-silent-modifications
11795 (js2-clear-face (point-min) (point-max))))
11796
11797 (defun js2-mode-reset-timer ()
11798 "Cancel any existing parse timer and schedule a new one."
11799 (if js2-mode-parse-timer
11800 (cancel-timer js2-mode-parse-timer))
11801 (setq js2-mode-parsing nil)
11802 (let ((timer (timer-create)))
11803 (setq js2-mode-parse-timer timer)
11804 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11805 (timer-set-idle-time timer js2-idle-timer-delay)
11806 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11807 (timer-activate-when-idle timer nil)))
11808
11809 (defun js2-mode-idle-reparse (buffer)
11810 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11811 it to be reparsed when the buffer is selected."
11812 (cond ((eq buffer (current-buffer))
11813 (js2-reparse))
11814 ((buffer-live-p buffer)
11815 ;; reparse when the buffer is selected again
11816 (with-current-buffer buffer
11817 (add-hook 'window-configuration-change-hook
11818 #'js2-mode-idle-reparse-inner
11819 nil t)))))
11820
11821 (defun js2-mode-idle-reparse-inner ()
11822 (remove-hook 'window-configuration-change-hook
11823 #'js2-mode-idle-reparse-inner
11824 t)
11825 (js2-reparse))
11826
11827 (defun js2-mode-edit (_beg _end _len)
11828 "Schedule a new parse after buffer is edited.
11829 Buffer edit spans from BEG to END and is of length LEN."
11830 (setq js2-mode-buffer-dirty-p t)
11831 (js2-mode-hide-overlay)
11832 (js2-mode-reset-timer))
11833
11834 (defun js2-minor-mode-edit (_beg _end _len)
11835 "Callback for buffer edits in `js2-mode'.
11836 Schedules a new parse after buffer is edited.
11837 Buffer edit spans from BEG to END and is of length LEN."
11838 (setq js2-mode-buffer-dirty-p t)
11839 (js2-mode-hide-overlay)
11840 (js2-mode-reset-timer))
11841
11842 (defun js2-reparse (&optional force)
11843 "Re-parse current buffer after user finishes some data entry.
11844 If we get any user input while parsing, including cursor motion,
11845 we discard the parse and reschedule it. If FORCE is nil, then the
11846 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11847 (let (time
11848 interrupted-p
11849 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11850 (unless js2-mode-parsing
11851 (setq js2-mode-parsing t)
11852 (unwind-protect
11853 (when (or js2-mode-buffer-dirty-p force)
11854 (js2-remove-overlays)
11855 (setq js2-mode-buffer-dirty-p nil
11856 js2-mode-fontifications nil
11857 js2-mode-deferred-properties nil)
11858 (if js2-mode-verbose-parse-p
11859 (message "parsing..."))
11860 (setq time
11861 (js2-time
11862 (setq interrupted-p
11863 (catch 'interrupted
11864 (js2-parse)
11865 (with-silent-modifications
11866 ;; if parsing is interrupted, comments and regex
11867 ;; literals stay ignored by `parse-partial-sexp'
11868 (remove-text-properties (point-min) (point-max)
11869 '(syntax-table))
11870 (js2-mode-apply-deferred-properties)
11871 (js2-mode-remove-suppressed-warnings)
11872 (js2-mode-show-warnings)
11873 (js2-mode-show-errors)
11874 (if (>= js2-highlight-level 1)
11875 (js2-highlight-jsdoc js2-mode-ast)))
11876 nil))))
11877 (if interrupted-p
11878 (progn
11879 ;; unfinished parse => try again
11880 (setq js2-mode-buffer-dirty-p t)
11881 (js2-mode-reset-timer))
11882 (if js2-mode-verbose-parse-p
11883 (message "Parse time: %s" time))))
11884 (setq js2-mode-parsing nil)
11885 (unless interrupted-p
11886 (setq js2-mode-parse-timer nil))))))
11887
11888 (defun js2-mode-show-node (event)
11889 "Debugging aid: highlight selected AST node on mouse click."
11890 (interactive "e")
11891 (mouse-set-point event)
11892 (setq deactivate-mark t)
11893 (when js2-mode-show-overlay
11894 (let ((node (js2-node-at-point))
11895 beg end)
11896 (if (null node)
11897 (message "No node found at location %s" (point))
11898 (setq beg (js2-node-abs-pos node)
11899 end (+ beg (js2-node-len node)))
11900 (if js2-mode-node-overlay
11901 (move-overlay js2-mode-node-overlay beg end)
11902 (setq js2-mode-node-overlay (make-overlay beg end))
11903 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11904 (with-silent-modifications
11905 (if (fboundp 'cursor-sensor-mode)
11906 (put-text-property beg end 'cursor-sensor-functions
11907 '(js2-mode-hide-overlay))
11908 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11909 (message "%s, parent: %s"
11910 (js2-node-short-name node)
11911 (if (js2-node-parent node)
11912 (js2-node-short-name (js2-node-parent node))
11913 "nil"))))))
11914
11915 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11916 "Remove the debugging overlay when point moves.
11917 ARG1, ARG2 and ARG3 have different values depending on whether this function
11918 was found on `point-left' or in `cursor-sensor-functions'."
11919 (when js2-mode-node-overlay
11920 (let ((beg (overlay-start js2-mode-node-overlay))
11921 (end (overlay-end js2-mode-node-overlay))
11922 (p2 (if (windowp arg1)
11923 ;; Called from cursor-sensor-functions.
11924 (window-point arg1)
11925 ;; Called from point-left.
11926 arg2)))
11927 ;; Sometimes we're called spuriously.
11928 (unless (and p2
11929 (>= p2 beg)
11930 (<= p2 end))
11931 (with-silent-modifications
11932 (remove-text-properties beg end
11933 '(point-left nil cursor-sensor-functions)))
11934 (delete-overlay js2-mode-node-overlay)
11935 (setq js2-mode-node-overlay nil)))))
11936
11937 (defun js2-mode-reset ()
11938 "Debugging helper: reset everything."
11939 (interactive)
11940 (js2-mode-exit)
11941 (js2-mode))
11942
11943 (defun js2-mode-show-warn-or-err (e face)
11944 "Highlight a warning or error E with FACE.
11945 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11946 The last element is optional. When present, use instead of FACE."
11947 (let* ((key (cl-first e))
11948 (beg (cl-second e))
11949 (end (+ beg (cl-third e)))
11950 ;; Don't inadvertently go out of bounds.
11951 (beg (max (point-min) (min beg (point-max))))
11952 (end (max (point-min) (min end (point-max))))
11953 (ovl (make-overlay beg end)))
11954 ;; FIXME: Why a mix of overlays and text-properties?
11955 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11956 (overlay-put ovl 'js2-error t)
11957 (put-text-property beg end 'help-echo (js2-get-msg key))
11958 (if (fboundp 'cursor-sensor-mode)
11959 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11960 (put-text-property beg end 'point-entered #'js2-echo-error))))
11961
11962 (defun js2-remove-overlays ()
11963 "Remove overlays from buffer that have a `js2-error' property."
11964 (let ((beg (point-min))
11965 (end (point-max)))
11966 (save-excursion
11967 (dolist (o (overlays-in beg end))
11968 (when (overlay-get o 'js2-error)
11969 (delete-overlay o))))))
11970
11971 (defun js2-mode-apply-deferred-properties ()
11972 "Apply fontifications and other text properties recorded during parsing."
11973 (when (cl-plusp js2-highlight-level)
11974 ;; We defer clearing faces as long as possible to eliminate flashing.
11975 (js2-clear-face (point-min) (point-max))
11976 ;; Have to reverse the recorded fontifications list so that errors
11977 ;; and warnings overwrite the normal fontifications.
11978 (dolist (f (nreverse js2-mode-fontifications))
11979 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11980 (setq js2-mode-fontifications nil))
11981 (dolist (p js2-mode-deferred-properties)
11982 (apply #'put-text-property p))
11983 (setq js2-mode-deferred-properties nil))
11984
11985 (defun js2-mode-show-errors ()
11986 "Highlight syntax errors."
11987 (when js2-mode-show-parse-errors
11988 (dolist (e (js2-ast-root-errors js2-mode-ast))
11989 (js2-mode-show-warn-or-err e 'js2-error))))
11990
11991 (defun js2-mode-remove-suppressed-warnings ()
11992 "Take suppressed warnings out of the AST warnings list.
11993 This ensures that the counts and `next-error' are correct."
11994 (setf (js2-ast-root-warnings js2-mode-ast)
11995 (js2-delete-if
11996 (lambda (e)
11997 (let ((key (caar e)))
11998 (or
11999 (and (not js2-strict-trailing-comma-warning)
12000 (string-match "trailing\\.comma" key))
12001 (and (not js2-strict-cond-assign-warning)
12002 (string= key "msg.equal.as.assign"))
12003 (and js2-missing-semi-one-line-override
12004 (string= key "msg.missing.semi")
12005 (let* ((beg (cl-second e))
12006 (node (js2-node-at-point beg))
12007 (fn (js2-mode-find-parent-fn node))
12008 (body (and fn (js2-function-node-body fn)))
12009 (lc (and body (js2-node-abs-pos body)))
12010 (rc (and lc (+ lc (js2-node-len body)))))
12011 (and fn
12012 (or (null body)
12013 (save-excursion
12014 (goto-char beg)
12015 (and (js2-same-line lc)
12016 (js2-same-line rc))))))))))
12017 (js2-ast-root-warnings js2-mode-ast))))
12018
12019 (defun js2-mode-show-warnings ()
12020 "Highlight strict-mode warnings."
12021 (when js2-mode-show-strict-warnings
12022 (dolist (e (js2-ast-root-warnings js2-mode-ast))
12023 (js2-mode-show-warn-or-err e 'js2-warning))))
12024
12025 (defun js2-echo-error (arg1 arg2 &optional _arg3)
12026 "Called by point-motion hooks.
12027 ARG1, ARG2 and ARG3 have different values depending on whether this function
12028 was found on `point-entered' or in `cursor-sensor-functions'."
12029 (let* ((new-point (if (windowp arg1)
12030 ;; Called from cursor-sensor-functions.
12031 (window-point arg1)
12032 ;; Called from point-left.
12033 arg2))
12034 (msg (get-text-property new-point 'help-echo)))
12035 (when (and (stringp msg)
12036 (not (active-minibuffer-window))
12037 (not (current-message)))
12038 (message msg))))
12039
12040 (defun js2-line-break (&optional _soft)
12041 "Break line at point and indent, continuing comment if within one.
12042 If inside a string, and `js2-concat-multiline-strings' is not
12043 nil, turn it into concatenation."
12044 (interactive)
12045 (let ((parse-status (syntax-ppss)))
12046 (cond
12047 ;; Check if we're inside a string.
12048 ((nth 3 parse-status)
12049 (if js2-concat-multiline-strings
12050 (js2-mode-split-string parse-status)
12051 (insert "\n")))
12052 ;; Check if inside a block comment.
12053 ((nth 4 parse-status)
12054 (js2-mode-extend-comment (nth 8 parse-status)))
12055 (t
12056 (newline-and-indent)))))
12057
12058 (defun js2-mode-split-string (parse-status)
12059 "Turn a newline in mid-string into a string concatenation.
12060 PARSE-STATUS is as documented in `parse-partial-sexp'."
12061 (let* ((quote-char (nth 3 parse-status))
12062 (at-eol (eq js2-concat-multiline-strings 'eol)))
12063 (insert quote-char)
12064 (insert (if at-eol " +\n" "\n"))
12065 (unless at-eol
12066 (insert "+ "))
12067 (js2-indent-line)
12068 (insert quote-char)
12069 (when (eolp)
12070 (insert quote-char)
12071 (backward-char 1))))
12072
12073 (defun js2-mode-extend-comment (start-pos)
12074 "Indent the line and, when inside a comment block, add comment prefix."
12075 (let (star single col first-line needs-close)
12076 (save-excursion
12077 (back-to-indentation)
12078 (when (< (point) start-pos)
12079 (goto-char start-pos))
12080 (cond
12081 ((looking-at "\\*[^/]")
12082 (setq star t
12083 col (current-column)))
12084 ((looking-at "/\\*")
12085 (setq star t
12086 first-line t
12087 col (1+ (current-column))))
12088 ((looking-at "//")
12089 (setq single t
12090 col (current-column)))))
12091 ;; Heuristic for whether we need to close the comment:
12092 ;; if we've got a parse error here, assume it's an unterminated
12093 ;; comment.
12094 (setq needs-close
12095 (or
12096 (get-char-property (1- (point)) 'js2-error)
12097 ;; The heuristic above doesn't work well when we're
12098 ;; creating a comment and there's another one downstream,
12099 ;; as our parser thinks this one ends at the end of the
12100 ;; next one. (You can have a /* inside a js block comment.)
12101 ;; So just close it if the next non-ws char isn't a *.
12102 (and first-line
12103 (eolp)
12104 (save-excursion
12105 (skip-chars-forward " \t\r\n")
12106 (not (eq (char-after) ?*))))))
12107 (delete-horizontal-space)
12108 (insert "\n")
12109 (cond
12110 (star
12111 (indent-to col)
12112 (insert "* ")
12113 (if (and first-line needs-close)
12114 (save-excursion
12115 (insert "\n")
12116 (indent-to col)
12117 (insert "*/"))))
12118 ((and single
12119 (save-excursion
12120 (and (zerop (forward-line 1))
12121 (looking-at "\\s-*//"))))
12122 (indent-to col)
12123 (insert "// ")))
12124 ;; Don't need to extend the comment after all.
12125 (js2-indent-line)))
12126
12127 (defun js2-beginning-of-line ()
12128 "Toggle point between bol and first non-whitespace char in line.
12129 Also moves past comment delimiters when inside comments."
12130 (interactive)
12131 (let (node)
12132 (cond
12133 ((bolp)
12134 (back-to-indentation))
12135 ((looking-at "//")
12136 (skip-chars-forward "/ \t"))
12137 ((and (eq (char-after) ?*)
12138 (setq node (js2-comment-at-point))
12139 (memq (js2-comment-node-format node) '(jsdoc block))
12140 (save-excursion
12141 (skip-chars-backward " \t")
12142 (bolp)))
12143 (skip-chars-forward "\* \t"))
12144 (t
12145 (goto-char (point-at-bol))))))
12146
12147 (defun js2-end-of-line ()
12148 "Toggle point between eol and last non-whitespace char in line."
12149 (interactive)
12150 (if (eolp)
12151 (skip-chars-backward " \t")
12152 (goto-char (point-at-eol))))
12153
12154 (defun js2-mode-wait-for-parse (callback)
12155 "Invoke CALLBACK when parsing is finished.
12156 If parsing is already finished, calls CALLBACK immediately."
12157 (if (not js2-mode-buffer-dirty-p)
12158 (funcall callback)
12159 (push callback js2-mode-pending-parse-callbacks)
12160 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
12161
12162 (defun js2-mode-parse-finished ()
12163 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
12164 ;; We can't let errors propagate up, since it prevents the
12165 ;; `js2-parse' method from completing normally and returning
12166 ;; the ast, which makes things mysteriously not work right.
12167 (unwind-protect
12168 (dolist (cb js2-mode-pending-parse-callbacks)
12169 (condition-case err
12170 (funcall cb)
12171 (error (message "%s" err))))
12172 (setq js2-mode-pending-parse-callbacks nil)))
12173
12174 (defun js2-mode-flag-region (from to flag)
12175 "Hide or show text from FROM to TO, according to FLAG.
12176 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
12177 Returns the created overlay if FLAG is non-nil."
12178 (remove-overlays from to 'invisible 'js2-outline)
12179 (when flag
12180 (let ((o (make-overlay from to)))
12181 (overlay-put o 'invisible 'js2-outline)
12182 (overlay-put o 'isearch-open-invisible
12183 'js2-isearch-open-invisible)
12184 o)))
12185
12186 ;; Function to be set as an outline-isearch-open-invisible' property
12187 ;; to the overlay that makes the outline invisible (see
12188 ;; `js2-mode-flag-region').
12189 (defun js2-isearch-open-invisible (_overlay)
12190 ;; We rely on the fact that isearch places point on the matched text.
12191 (js2-mode-show-element))
12192
12193 (defun js2-mode-invisible-overlay-bounds (&optional pos)
12194 "Return cons cell of bounds of folding overlay at POS.
12195 Returns nil if not found."
12196 (let ((overlays (overlays-at (or pos (point))))
12197 o)
12198 (while (and overlays
12199 (not o))
12200 (if (overlay-get (car overlays) 'invisible)
12201 (setq o (car overlays))
12202 (setq overlays (cdr overlays))))
12203 (if o
12204 (cons (overlay-start o) (overlay-end o)))))
12205
12206 (defun js2-mode-function-at-point (&optional pos)
12207 "Return the innermost function node enclosing current point.
12208 Returns nil if point is not in a function."
12209 (let ((node (js2-node-at-point pos)))
12210 (while (and node (not (js2-function-node-p node)))
12211 (setq node (js2-node-parent node)))
12212 (if (js2-function-node-p node)
12213 node)))
12214
12215 (defun js2-mode-toggle-element ()
12216 "Hide or show the foldable element at the point."
12217 (interactive)
12218 (let (comment fn pos)
12219 (save-excursion
12220 (cond
12221 ;; /* ... */ comment?
12222 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
12223 (if (js2-mode-invisible-overlay-bounds
12224 (setq pos (+ 3 (js2-node-abs-pos comment))))
12225 (progn
12226 (goto-char pos)
12227 (js2-mode-show-element))
12228 (js2-mode-hide-element)))
12229 ;; //-comment?
12230 ((save-excursion
12231 (back-to-indentation)
12232 (looking-at js2-mode-//-comment-re))
12233 (js2-mode-toggle-//-comment))
12234 ;; function?
12235 ((setq fn (js2-mode-function-at-point))
12236 (setq pos (and (js2-function-node-body fn)
12237 (js2-node-abs-pos (js2-function-node-body fn))))
12238 (goto-char (1+ pos))
12239 (if (js2-mode-invisible-overlay-bounds)
12240 (js2-mode-show-element)
12241 (js2-mode-hide-element)))
12242 (t
12243 (message "Nothing at point to hide or show"))))))
12244
12245 (defun js2-mode-hide-element ()
12246 "Fold/hide contents of a block, showing ellipses.
12247 Show the hidden text with \\[js2-mode-show-element]."
12248 (interactive)
12249 (if js2-mode-buffer-dirty-p
12250 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12251 (let (node body beg end)
12252 (cond
12253 ((js2-mode-invisible-overlay-bounds)
12254 (message "already hidden"))
12255 (t
12256 (setq node (js2-node-at-point))
12257 (cond
12258 ((js2-block-comment-p node)
12259 (js2-mode-hide-comment node))
12260 (t
12261 (while (and node (not (js2-function-node-p node)))
12262 (setq node (js2-node-parent node)))
12263 (if (and node
12264 (setq body (js2-function-node-body node)))
12265 (progn
12266 (setq beg (js2-node-abs-pos body)
12267 end (+ beg (js2-node-len body)))
12268 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12269 (message "No collapsable element found at point"))))))))
12270
12271 (defun js2-mode-show-element ()
12272 "Show the hidden element at current point."
12273 (interactive)
12274 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12275 (if bounds
12276 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12277 (message "Nothing to un-hide"))))
12278
12279 (defun js2-mode-show-all ()
12280 "Show all of the text in the buffer."
12281 (interactive)
12282 (js2-mode-flag-region (point-min) (point-max) nil))
12283
12284 (defun js2-mode-toggle-hide-functions ()
12285 (interactive)
12286 (if js2-mode-functions-hidden
12287 (js2-mode-show-functions)
12288 (js2-mode-hide-functions)))
12289
12290 (defun js2-mode-hide-functions ()
12291 "Hides all non-nested function bodies in the buffer.
12292 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12293 to open an individual entry."
12294 (interactive)
12295 (if js2-mode-buffer-dirty-p
12296 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12297 (if (null js2-mode-ast)
12298 (message "Oops - parsing failed")
12299 (setq js2-mode-functions-hidden t)
12300 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12301
12302 (defun js2-mode-function-hider (n endp)
12303 (when (not endp)
12304 (let ((tt (js2-node-type n))
12305 body beg end)
12306 (cond
12307 ((and (= tt js2-FUNCTION)
12308 (setq body (js2-function-node-body n)))
12309 (setq beg (js2-node-abs-pos body)
12310 end (+ beg (js2-node-len body)))
12311 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12312 nil) ; don't process children of function
12313 (t
12314 t))))) ; keep processing other AST nodes
12315
12316 (defun js2-mode-show-functions ()
12317 "Un-hide any folded function bodies in the buffer."
12318 (interactive)
12319 (setq js2-mode-functions-hidden nil)
12320 (save-excursion
12321 (goto-char (point-min))
12322 (while (/= (goto-char (next-overlay-change (point)))
12323 (point-max))
12324 (dolist (o (overlays-at (point)))
12325 (when (and (overlay-get o 'invisible)
12326 (not (overlay-get o 'comment)))
12327 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12328
12329 (defun js2-mode-hide-comment (n)
12330 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12331 3 ; /**
12332 2)) ; /*
12333 (beg (+ (js2-node-abs-pos n) head))
12334 (end (- (+ beg (js2-node-len n)) head 2))
12335 (o (js2-mode-flag-region beg end 'hide)))
12336 (overlay-put o 'comment t)))
12337
12338 (defun js2-mode-toggle-hide-comments ()
12339 "Folds all block comments in the buffer.
12340 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12341 to open an individual entry."
12342 (interactive)
12343 (if js2-mode-comments-hidden
12344 (js2-mode-show-comments)
12345 (js2-mode-hide-comments)))
12346
12347 (defun js2-mode-hide-comments ()
12348 (interactive)
12349 (if js2-mode-buffer-dirty-p
12350 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12351 (if (null js2-mode-ast)
12352 (message "Oops - parsing failed")
12353 (setq js2-mode-comments-hidden t)
12354 (dolist (n (js2-ast-root-comments js2-mode-ast))
12355 (when (js2-block-comment-p n)
12356 (js2-mode-hide-comment n)))
12357 (js2-mode-hide-//-comments)))
12358
12359 (defun js2-mode-extend-//-comment (direction)
12360 "Find start or end of a block of similar //-comment lines.
12361 DIRECTION is -1 to look back, 1 to look forward.
12362 INDENT is the indentation level to match.
12363 Returns the end-of-line position of the furthest adjacent
12364 //-comment line with the same indentation as the current line.
12365 If there is no such matching line, returns current end of line."
12366 (let ((pos (point-at-eol))
12367 (indent (current-indentation)))
12368 (save-excursion
12369 (while (and (zerop (forward-line direction))
12370 (looking-at js2-mode-//-comment-re)
12371 (eq indent (length (match-string 1))))
12372 (setq pos (point-at-eol)))
12373 pos)))
12374
12375 (defun js2-mode-hide-//-comments ()
12376 "Fold adjacent 1-line comments, showing only snippet of first one."
12377 (let (beg end)
12378 (save-excursion
12379 (goto-char (point-min))
12380 (while (re-search-forward js2-mode-//-comment-re nil t)
12381 (setq beg (point)
12382 end (js2-mode-extend-//-comment 1))
12383 (unless (eq beg end)
12384 (overlay-put (js2-mode-flag-region beg end 'hide)
12385 'comment t))
12386 (goto-char end)
12387 (forward-char 1)))))
12388
12389 (defun js2-mode-toggle-//-comment ()
12390 "Fold or un-fold any multi-line //-comment at point.
12391 Caller should have determined that this line starts with a //-comment."
12392 (let* ((beg (point-at-eol))
12393 (end beg))
12394 (save-excursion
12395 (goto-char end)
12396 (if (js2-mode-invisible-overlay-bounds)
12397 (js2-mode-show-element)
12398 ;; else hide the comment
12399 (setq beg (js2-mode-extend-//-comment -1)
12400 end (js2-mode-extend-//-comment 1))
12401 (unless (eq beg end)
12402 (overlay-put (js2-mode-flag-region beg end 'hide)
12403 'comment t))))))
12404
12405 (defun js2-mode-show-comments ()
12406 "Un-hide any hidden comments, leaving other hidden elements alone."
12407 (interactive)
12408 (setq js2-mode-comments-hidden nil)
12409 (save-excursion
12410 (goto-char (point-min))
12411 (while (/= (goto-char (next-overlay-change (point)))
12412 (point-max))
12413 (dolist (o (overlays-at (point)))
12414 (when (overlay-get o 'comment)
12415 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12416
12417 (defun js2-mode-display-warnings-and-errors ()
12418 "Turn on display of warnings and errors."
12419 (interactive)
12420 (setq js2-mode-show-parse-errors t
12421 js2-mode-show-strict-warnings t)
12422 (js2-reparse 'force))
12423
12424 (defun js2-mode-hide-warnings-and-errors ()
12425 "Turn off display of warnings and errors."
12426 (interactive)
12427 (setq js2-mode-show-parse-errors nil
12428 js2-mode-show-strict-warnings nil)
12429 (js2-reparse 'force))
12430
12431 (defun js2-mode-toggle-warnings-and-errors ()
12432 "Toggle the display of warnings and errors.
12433 Some users don't like having warnings/errors reported while they type."
12434 (interactive)
12435 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12436 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12437 (if (called-interactively-p 'any)
12438 (message "warnings and errors %s"
12439 (if js2-mode-show-parse-errors
12440 "enabled"
12441 "disabled")))
12442 (js2-reparse 'force))
12443
12444 (defun js2-mode-customize ()
12445 (interactive)
12446 (customize-group 'js2-mode))
12447
12448 (defun js2-mode-forward-sexp (&optional arg)
12449 "Move forward across one statement or balanced expression.
12450 With ARG, do it that many times. Negative arg -N means
12451 move backward across N balanced expressions."
12452 (interactive "p")
12453 (setq arg (or arg 1))
12454 (save-restriction
12455 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12456 (js2-reparse)
12457 (let (forward-sexp-function
12458 node (start (point)) pos lp rp child)
12459 (cond
12460 ;; backward-sexp
12461 ;; could probably make this better for some cases:
12462 ;; - if in statement block (e.g. function body), go to parent
12463 ;; - infix exprs like (foo in bar) - maybe go to beginning
12464 ;; of infix expr if in the right-side expression?
12465 ((and arg (cl-minusp arg))
12466 (dotimes (_ (- arg))
12467 (js2-backward-sws)
12468 (forward-char -1) ; Enter the node we backed up to.
12469 (when (setq node (js2-node-at-point (point) t))
12470 (setq pos (js2-node-abs-pos node))
12471 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12472 (setq lp (car parens)
12473 rp (cdr parens)))
12474 (when (and lp (> start lp))
12475 (if (and rp (<= start rp))
12476 ;; Between parens, check if there's a child node we can jump.
12477 (when (setq child (js2-node-closest-child node (point) lp t))
12478 (setq pos (js2-node-abs-pos child)))
12479 ;; Before both parens.
12480 (setq pos lp)))
12481 (let ((state (parse-partial-sexp start pos)))
12482 (goto-char (if (not (zerop (car state)))
12483 ;; Stumble at the unbalanced paren if < 0, or
12484 ;; jump a bit further if > 0.
12485 (scan-sexps start -1)
12486 pos))))
12487 (unless pos (goto-char (point-min)))))
12488 (t
12489 ;; forward-sexp
12490 (dotimes (_ arg)
12491 (js2-forward-sws)
12492 (when (setq node (js2-node-at-point (point) t))
12493 (setq pos (js2-node-abs-pos node))
12494 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12495 (setq lp (car parens)
12496 rp (cdr parens)))
12497 (or
12498 (when (and rp (<= start rp))
12499 (if (> start lp)
12500 (when (setq child (js2-node-closest-child node (point) rp))
12501 (setq pos (js2-node-abs-end child)))
12502 (setq pos (1+ rp))))
12503 ;; No parens or child nodes, looks for the end of the current node.
12504 (cl-incf pos (js2-node-len
12505 (if (js2-expr-stmt-node-p (js2-node-parent node))
12506 ;; Stop after the semicolon.
12507 (js2-node-parent node)
12508 node))))
12509 (let ((state (save-excursion (parse-partial-sexp start pos))))
12510 (goto-char (if (not (zerop (car state)))
12511 (scan-sexps start 1)
12512 pos))))
12513 (unless pos (goto-char (point-max)))))))))
12514
12515 (defun js2-mode-forward-sexp-parens (node abs-pos)
12516 "Return a cons cell with positions of main parens in NODE."
12517 (cond
12518 ((or (js2-array-node-p node)
12519 (js2-object-node-p node)
12520 (js2-comp-node-p node)
12521 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12522 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12523 ((js2-paren-expr-node-p node)
12524 (let ((lp (js2-node-lp node))
12525 (rp (js2-node-rp node)))
12526 (cons (when lp (+ abs-pos lp))
12527 (when rp (+ abs-pos rp)))))))
12528
12529 (defun js2-node-closest-child (parent point limit &optional before)
12530 (let* ((parent-pos (js2-node-abs-pos parent))
12531 (rpoint (- point parent-pos))
12532 (rlimit (- limit parent-pos))
12533 (min (min rpoint rlimit))
12534 (max (max rpoint rlimit))
12535 found)
12536 (catch 'done
12537 (js2-visit-ast
12538 parent
12539 (lambda (node _end-p)
12540 (if (eq node parent)
12541 t
12542 (let ((pos (js2-node-pos node)) ;; Both relative values.
12543 (end (+ (js2-node-pos node) (js2-node-len node))))
12544 (when (and (>= pos min) (<= end max)
12545 (if before (< pos rpoint) (> end rpoint)))
12546 (setq found node))
12547 (when (> end rpoint)
12548 (throw 'done nil)))
12549 nil))))
12550 found))
12551
12552 (defun js2-errors ()
12553 "Return a list of errors found."
12554 (and js2-mode-ast
12555 (js2-ast-root-errors js2-mode-ast)))
12556
12557 (defun js2-warnings ()
12558 "Return a list of warnings found."
12559 (and js2-mode-ast
12560 (js2-ast-root-warnings js2-mode-ast)))
12561
12562 (defun js2-have-errors-p ()
12563 "Return non-nil if any parse errors or warnings were found."
12564 (or (js2-errors) (js2-warnings)))
12565
12566 (defun js2-errors-and-warnings ()
12567 "Return a copy of the concatenated errors and warnings lists.
12568 They are appended: first the errors, then the warnings.
12569 Entries are of the form (MSG BEG END)."
12570 (when js2-mode-ast
12571 (append (js2-ast-root-errors js2-mode-ast)
12572 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12573
12574 (defun js2-next-error (&optional arg reset)
12575 "Move to next parse error.
12576 Typically invoked via \\[next-error].
12577 ARG is the number of errors, forward or backward, to move.
12578 RESET means start over from the beginning."
12579 (interactive "p")
12580 (if (not (or (js2-errors) (js2-warnings)))
12581 (message "No errors")
12582 (when reset
12583 (goto-char (point-min)))
12584 (let* ((errs (js2-errors-and-warnings))
12585 (continue t)
12586 (start (point))
12587 (count (or arg 1))
12588 (backward (cl-minusp count))
12589 (sorter (if backward '> '<))
12590 (stopper (if backward '< '>))
12591 (count (abs count))
12592 all-errs err)
12593 ;; Sort by start position.
12594 (setq errs (sort errs (lambda (e1 e2)
12595 (funcall sorter (cl-second e1) (cl-second e2))))
12596 all-errs errs)
12597 ;; Find nth error with pos > start.
12598 (while (and errs continue)
12599 (when (funcall stopper (cl-cadar errs) start)
12600 (setq err (car errs))
12601 (if (zerop (cl-decf count))
12602 (setq continue nil)))
12603 (setq errs (cdr errs)))
12604 ;; Clear for `js2-echo-error'.
12605 (message nil)
12606 (if err
12607 (goto-char (cl-second err))
12608 ;; Wrap around to first error.
12609 (goto-char (cl-second (car all-errs)))
12610 ;; If we were already on it, echo msg again.
12611 (if (= (point) start)
12612 (js2-echo-error (point) (point)))))))
12613
12614 (defun js2-down-mouse-3 ()
12615 "Make right-click move the point to the click location.
12616 This makes right-click context menu operations a bit more intuitive.
12617 The point will not move if the region is active, however, to avoid
12618 destroying the region selection."
12619 (interactive)
12620 (when (and js2-move-point-on-right-click
12621 (not mark-active))
12622 (let ((e last-input-event))
12623 (ignore-errors
12624 (goto-char (cl-cadadr e))))))
12625
12626 (defun js2-mode-create-imenu-index ()
12627 "Return an alist for `imenu--index-alist'."
12628 ;; This is built up in `js2-parse-record-imenu' during parsing.
12629 (when js2-mode-ast
12630 ;; if we have an ast but no recorder, they're requesting a rescan
12631 (unless js2-imenu-recorder
12632 (js2-reparse 'force))
12633 (prog1
12634 (js2-build-imenu-index)
12635 (setq js2-imenu-recorder nil
12636 js2-imenu-function-map nil))))
12637
12638 (defun js2-mode-find-tag ()
12639 "Replacement for `find-tag-default'.
12640 `find-tag-default' returns a ridiculous answer inside comments."
12641 (let (beg end)
12642 (js2-with-underscore-as-word-syntax
12643 (save-excursion
12644 (if (and (not (looking-at "[[:alnum:]_$]"))
12645 (looking-back "[[:alnum:]_$]"))
12646 (setq beg (progn (forward-word -1) (point))
12647 end (progn (forward-word 1) (point)))
12648 (setq beg (progn (forward-word 1) (point))
12649 end (progn (forward-word -1) (point))))
12650 (replace-regexp-in-string
12651 "[\"']" ""
12652 (buffer-substring-no-properties beg end))))))
12653
12654 (defun js2-mode-forward-sibling ()
12655 "Move to the end of the sibling following point in parent.
12656 Returns non-nil if successful, or nil if there was no following sibling."
12657 (let* ((node (js2-node-at-point))
12658 (parent (js2-mode-find-enclosing-fn node))
12659 sib)
12660 (when (setq sib (js2-node-find-child-after (point) parent))
12661 (goto-char (+ (js2-node-abs-pos sib)
12662 (js2-node-len sib))))))
12663
12664 (defun js2-mode-backward-sibling ()
12665 "Move to the beginning of the sibling node preceding point in parent.
12666 Parent is defined as the enclosing script or function."
12667 (let* ((node (js2-node-at-point))
12668 (parent (js2-mode-find-enclosing-fn node))
12669 sib)
12670 (when (setq sib (js2-node-find-child-before (point) parent))
12671 (goto-char (js2-node-abs-pos sib)))))
12672
12673 (defun js2-beginning-of-defun (&optional arg)
12674 "Go to line on which current function starts, and return t on success.
12675 If we're not in a function or already at the beginning of one, go
12676 to beginning of previous script-level element.
12677 With ARG N, do that N times. If N is negative, move forward."
12678 (setq arg (or arg 1))
12679 (if (cl-plusp arg)
12680 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12681 (when (cond
12682 ((js2-function-node-p parent)
12683 (goto-char (js2-node-abs-pos parent)))
12684 (t
12685 (js2-mode-backward-sibling)))
12686 (if (> arg 1)
12687 (js2-beginning-of-defun (1- arg))
12688 t)))
12689 (when (js2-end-of-defun)
12690 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12691
12692 (defun js2-end-of-defun ()
12693 "Go to the char after the last position of the current function
12694 or script-level element."
12695 (let* ((node (js2-node-at-point))
12696 (parent (or (and (js2-function-node-p node) node)
12697 (js2-node-parent-script-or-fn node)))
12698 script)
12699 (unless (js2-function-node-p parent)
12700 ;; Use current script-level node, or, if none, the next one.
12701 (setq script (or parent node)
12702 parent (js2-node-find-child-before (point) script))
12703 (when (or (null parent)
12704 (>= (point) (+ (js2-node-abs-pos parent)
12705 (js2-node-len parent))))
12706 (setq parent (js2-node-find-child-after (point) script))))
12707 (when parent
12708 (goto-char (+ (js2-node-abs-pos parent)
12709 (js2-node-len parent))))))
12710
12711 (defun js2-mark-defun (&optional allow-extend)
12712 "Put mark at end of this function, point at beginning.
12713 The function marked is the one that contains point.
12714
12715 Interactively, if this command is repeated,
12716 or (in Transient Mark mode) if the mark is active,
12717 it marks the next defun after the ones already marked."
12718 (interactive "p")
12719 (let (extended)
12720 (when (and allow-extend
12721 (or (and (eq last-command this-command) (mark t))
12722 (and transient-mark-mode mark-active)))
12723 (let ((sib (save-excursion
12724 (goto-char (mark))
12725 (if (js2-mode-forward-sibling)
12726 (point)))))
12727 (if sib
12728 (progn
12729 (set-mark sib)
12730 (setq extended t))
12731 ;; no more siblings - try extending to enclosing node
12732 (goto-char (mark t)))))
12733 (when (not extended)
12734 (let ((node (js2-node-at-point (point) t)) ; skip comments
12735 ast fn stmt parent beg end)
12736 (when (js2-ast-root-p node)
12737 (setq ast node
12738 node (or (js2-node-find-child-after (point) node)
12739 (js2-node-find-child-before (point) node))))
12740 ;; only mark whole buffer if we can't find any children
12741 (if (null node)
12742 (setq node ast))
12743 (if (js2-function-node-p node)
12744 (setq parent node)
12745 (setq fn (js2-mode-find-enclosing-fn node)
12746 stmt (if (or (null fn)
12747 (js2-ast-root-p fn))
12748 (js2-mode-find-first-stmt node))
12749 parent (or stmt fn)))
12750 (setq beg (js2-node-abs-pos parent)
12751 end (+ beg (js2-node-len parent)))
12752 (push-mark beg)
12753 (goto-char end)
12754 (exchange-point-and-mark)))))
12755
12756 (defun js2-narrow-to-defun ()
12757 "Narrow to the function enclosing point."
12758 (interactive)
12759 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12760 (fn (if (js2-script-node-p node)
12761 node
12762 (js2-mode-find-enclosing-fn node)))
12763 (beg (js2-node-abs-pos fn)))
12764 (unless (js2-ast-root-p fn)
12765 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12766
12767 (provide 'js2-mode)
12768
12769 ;;; js2-mode.el ends here