]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Test const scoping.
[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 regexp-flags
740 comment-type
741 follows-eol-p)
742
743 ;; Have to call `js2-init-scanner' to initialize the values.
744 (js2-deflocal js2-ti-tokens nil)
745 (js2-deflocal js2-ti-tokens-cursor nil)
746 (js2-deflocal js2-ti-lookahead nil)
747
748 (cl-defstruct (js2-ts-state
749 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
750 (cursor js2-ts-cursor)
751 (tokens (copy-sequence js2-ti-tokens))
752 (tokens-cursor js2-ti-tokens-cursor)
753 (lookahead js2-ti-lookahead))))
754 lineno
755 cursor
756 tokens
757 tokens-cursor
758 lookahead)
759
760 ;;; Parser variables
761
762 (js2-deflocal js2-parsed-errors nil
763 "List of errors produced during scanning/parsing.")
764
765 (js2-deflocal js2-parsed-warnings nil
766 "List of warnings produced during scanning/parsing.")
767
768 (js2-deflocal js2-recover-from-parse-errors t
769 "Non-nil to continue parsing after a syntax error.
770
771 In recovery mode, the AST will be built in full, and any error
772 nodes will be flagged with appropriate error information. If
773 this flag is nil, a syntax error will result in an error being
774 signaled.
775
776 The variable is automatically buffer-local, because different
777 modes that use the parser will need different settings.")
778
779 (js2-deflocal js2-parse-hook nil
780 "List of callbacks for receiving parsing progress.")
781
782 (defvar js2-parse-finished-hook nil
783 "List of callbacks to notify when parsing finishes.
784 Not called if parsing was interrupted.")
785
786 (js2-deflocal js2-is-eval-code nil
787 "True if we're evaluating code in a string.
788 If non-nil, the tokenizer will record the token text, and the AST nodes
789 will record their source text. Off by default for IDE modes, since the
790 text is available in the buffer.")
791
792 (defvar js2-parse-ide-mode t
793 "Non-nil if the parser is being used for `js2-mode'.
794 If non-nil, the parser will set text properties for fontification
795 and the syntax table. The value should be nil when using the
796 parser as a frontend to an interpreter or byte compiler.")
797
798 ;;; Parser instance variables (buffer-local vars for js2-parse)
799
800 (defconst js2-ti-after-eol (lsh 1 16)
801 "Flag: first token of the source line.")
802
803 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
804
805 (js2-deflocal js2-compiler-generate-debug-info t)
806 (js2-deflocal js2-compiler-use-dynamic-scope nil)
807 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
808 (js2-deflocal js2-compiler-xml-available t)
809 (js2-deflocal js2-compiler-optimization-level 0)
810 (js2-deflocal js2-compiler-generating-source t)
811 (js2-deflocal js2-compiler-strict-mode nil)
812 (js2-deflocal js2-compiler-report-warning-as-error nil)
813 (js2-deflocal js2-compiler-generate-observer-count nil)
814 (js2-deflocal js2-compiler-activation-names nil)
815
816 ;; SKIP: sourceURI
817
818 ;; There's a compileFunction method in Context.java - may need it.
819 (js2-deflocal js2-called-by-compile-function nil
820 "True if `js2-parse' was called by `js2-compile-function'.
821 Will only be used when we finish implementing the interpreter.")
822
823 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
824
825 ;; SKIP: node factory - we're going to just call functions directly,
826 ;; and eventually go to a unified AST format.
827
828 (js2-deflocal js2-nesting-of-function 0)
829
830 (js2-deflocal js2-recorded-identifiers nil
831 "Tracks identifiers found during parsing.")
832
833 (js2-deflocal js2-is-in-destructuring nil
834 "True while parsing destructuring expression.")
835
836 (js2-deflocal js2-in-use-strict-directive nil
837 "True while inside a script or function under strict mode.")
838
839 (defcustom js2-global-externs nil
840 "A list of any extern names you'd like to consider always declared.
841 This list is global and is used by all `js2-mode' files.
842 You can create buffer-local externs list using `js2-additional-externs'.
843
844 There is also a buffer-local variable `js2-default-externs',
845 which is initialized by default to include the Ecma-262 externs
846 and the standard browser externs. The three lists are all
847 checked during highlighting."
848 :type 'list
849 :group 'js2-mode)
850
851 (js2-deflocal js2-default-externs nil
852 "Default external declarations.
853
854 These are currently only used for highlighting undeclared variables,
855 which only worries about top-level (unqualified) references.
856 As js2-mode's processing improves, we will flesh out this list.
857
858 The initial value is set to `js2-ecma-262-externs', unless some
859 of the `js2-include-?-externs' variables are set to t, in which
860 case the browser, Rhino and/or Node.js externs are also included.
861
862 See `js2-additional-externs' for more information.")
863
864 (defcustom js2-include-browser-externs t
865 "Non-nil to include browser externs in the master externs list.
866 If you work on JavaScript files that are not intended for browsers,
867 such as Mozilla Rhino server-side JavaScript, set this to nil.
868 See `js2-additional-externs' for more information about externs."
869 :type 'boolean
870 :group 'js2-mode)
871
872 (defcustom js2-include-rhino-externs nil
873 "Non-nil to include Mozilla Rhino externs in the master externs list.
874 See `js2-additional-externs' for more information about externs."
875 :type 'boolean
876 :group 'js2-mode)
877
878 (defcustom js2-include-node-externs nil
879 "Non-nil to include Node.js externs in the master externs list.
880 See `js2-additional-externs' for more information about externs."
881 :type 'boolean
882 :group 'js2-mode)
883
884 (js2-deflocal js2-additional-externs nil
885 "A buffer-local list of additional external declarations.
886 It is used to decide whether variables are considered undeclared
887 for purposes of highlighting.
888
889 Each entry is a Lisp string. The string should be the fully qualified
890 name of an external entity. All externs should be added to this list,
891 so that as js2-mode's processing improves it can take advantage of them.
892
893 You may want to declare your externs in three ways.
894 First, you can add externs that are valid for all your JavaScript files.
895 You should probably do this by adding them to `js2-global-externs', which
896 is a global list used for all js2-mode files.
897
898 Next, you can add a function to `js2-init-hook' that adds additional
899 externs appropriate for the specific file, perhaps based on its path.
900 These should go in `js2-additional-externs', which is buffer-local.
901
902 Third, you can use JSLint's global declaration, as long as
903 `js2-include-jslint-globals' is non-nil, which see.
904
905 Finally, you can add a function to `js2-post-parse-callbacks',
906 which is called after parsing completes, and `js2-mode-ast' is bound to
907 the root of the parse tree. At this stage you can set up an AST
908 node visitor using `js2-visit-ast' and examine the parse tree
909 for specific import patterns that may imply the existence of
910 other externs, possibly tied to your build system. These should also
911 be added to `js2-additional-externs'.
912
913 Your post-parse callback may of course also use the simpler and
914 faster (but perhaps less robust) approach of simply scanning the
915 buffer text for your imports, using regular expressions.")
916
917 ;; SKIP: decompiler
918 ;; SKIP: encoded-source
919
920 ;;; The following variables are per-function and should be saved/restored
921 ;;; during function parsing...
922
923 (js2-deflocal js2-current-script-or-fn nil)
924 (js2-deflocal js2-current-scope nil)
925 (js2-deflocal js2-nesting-of-with 0)
926 (js2-deflocal js2-label-set nil
927 "An alist mapping label names to nodes.")
928
929 (js2-deflocal js2-loop-set nil)
930 (js2-deflocal js2-loop-and-switch-set nil)
931 (js2-deflocal js2-has-return-value nil)
932 (js2-deflocal js2-end-flags 0)
933
934 ;;; ...end of per function variables
935
936 ;; These flags enumerate the possible ways a statement/function can
937 ;; terminate. These flags are used by endCheck() and by the Parser to
938 ;; detect inconsistent return usage.
939 ;;
940 ;; END_UNREACHED is reserved for code paths that are assumed to always be
941 ;; able to execute (example: throw, continue)
942 ;;
943 ;; END_DROPS_OFF indicates if the statement can transfer control to the
944 ;; next one. Statement such as return dont. A compound statement may have
945 ;; some branch that drops off control to the next statement.
946 ;;
947 ;; END_RETURNS indicates that the statement can return (without arguments)
948 ;; END_RETURNS_VALUE indicates that the statement can return a value.
949 ;;
950 ;; A compound statement such as
951 ;; if (condition) {
952 ;; return value;
953 ;; }
954 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
955
956 (defconst js2-end-unreached #x0)
957 (defconst js2-end-drops-off #x1)
958 (defconst js2-end-returns #x2)
959 (defconst js2-end-returns-value #x4)
960
961 ;; Rhino awkwardly passes a statementLabel parameter to the
962 ;; statementHelper() function, the main statement parser, which
963 ;; is then used by quite a few of the sub-parsers. We just make
964 ;; it a buffer-local variable and make sure it's cleaned up properly.
965 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
966
967 ;; Similarly, Rhino passes an inForInit boolean through about half
968 ;; the expression parsers. We use a dynamically-scoped variable,
969 ;; which makes it easier to funcall the parsers individually without
970 ;; worrying about whether they take the parameter or not.
971 (js2-deflocal js2-in-for-init nil)
972 (js2-deflocal js2-temp-name-counter 0)
973 (js2-deflocal js2-parse-stmt-count 0)
974
975 (defsubst js2-get-next-temp-name ()
976 (format "$%d" (cl-incf js2-temp-name-counter)))
977
978 (defvar js2-parse-interruptable-p t
979 "Set this to nil to force parse to continue until finished.
980 This will mostly be useful for interpreters.")
981
982 (defvar js2-statements-per-pause 50
983 "Pause after this many statements to check for user input.
984 If user input is pending, stop the parse and discard the tree.
985 This makes for a smoother user experience for large files.
986 You may have to wait a second or two before the highlighting
987 and error-reporting appear, but you can always type ahead if
988 you wish. This appears to be more or less how Eclipse, IntelliJ
989 and other editors work.")
990
991 (js2-deflocal js2-record-comments t
992 "Instructs the scanner to record comments in `js2-scanned-comments'.")
993
994 (js2-deflocal js2-scanned-comments nil
995 "List of all comments from the current parse.")
996
997 (defcustom js2-mode-indent-inhibit-undo nil
998 "Non-nil to disable collection of Undo information when indenting lines.
999 Some users have requested this behavior. It's nil by default because
1000 other Emacs modes don't work this way."
1001 :type 'boolean
1002 :group 'js2-mode)
1003
1004 (defcustom js2-mode-indent-ignore-first-tab nil
1005 "If non-nil, ignore first TAB keypress if we look indented properly.
1006 It's fairly common for users to navigate to an already-indented line
1007 and press TAB for reassurance that it's been indented. For this class
1008 of users, we want the first TAB press on a line to be ignored if the
1009 line is already indented to one of the precomputed alternatives.
1010
1011 This behavior is only partly implemented. If you TAB-indent a line,
1012 navigate to another line, and then navigate back, it fails to clear
1013 the last-indented variable, so it thinks you've already hit TAB once,
1014 and performs the indent. A full solution would involve getting on the
1015 point-motion hooks for the entire buffer. If we come across another
1016 use cases that requires watching point motion, I'll consider doing it.
1017
1018 If you set this variable to nil, then the TAB key will always change
1019 the indentation of the current line, if more than one alternative
1020 indentation spot exists."
1021 :type 'boolean
1022 :group 'js2-mode)
1023
1024 (defvar js2-indent-hook nil
1025 "A hook for user-defined indentation rules.
1026
1027 Functions on this hook should expect two arguments: (LIST INDEX)
1028 The LIST argument is the list of computed indentation points for
1029 the current line. INDEX is the list index of the indentation point
1030 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1031 indent function is not going to change the current line indentation.
1032
1033 If a hook function on this list returns a non-nil value, then
1034 `js2-bounce-indent' assumes the hook function has performed its own
1035 indentation, and will do nothing. If all hook functions on the list
1036 return nil, then `js2-bounce-indent' will use its computed indentation
1037 and reindent the line.
1038
1039 When hook functions on this hook list are called, the variable
1040 `js2-mode-ast' may or may not be set, depending on whether the
1041 parse tree is available. If the variable is nil, you can pass a
1042 callback to `js2-mode-wait-for-parse', and your callback will be
1043 called after the new parse tree is built. This can take some time
1044 in large files.")
1045
1046 (defface js2-warning
1047 `((((class color) (background light))
1048 (:underline "orange"))
1049 (((class color) (background dark))
1050 (:underline "orange"))
1051 (t (:underline t)))
1052 "Face for JavaScript warnings."
1053 :group 'js2-mode)
1054
1055 (defface js2-error
1056 `((((class color) (background light))
1057 (:foreground "red"))
1058 (((class color) (background dark))
1059 (:foreground "red"))
1060 (t (:foreground "red")))
1061 "Face for JavaScript errors."
1062 :group 'js2-mode)
1063
1064 (defface js2-jsdoc-tag
1065 '((t :foreground "SlateGray"))
1066 "Face used to highlight @whatever tags in jsdoc comments."
1067 :group 'js2-mode)
1068
1069 (defface js2-jsdoc-type
1070 '((t :foreground "SteelBlue"))
1071 "Face used to highlight {FooBar} types in jsdoc comments."
1072 :group 'js2-mode)
1073
1074 (defface js2-jsdoc-value
1075 '((t :foreground "PeachPuff3"))
1076 "Face used to highlight tag values in jsdoc comments."
1077 :group 'js2-mode)
1078
1079 (defface js2-function-param
1080 '((t :foreground "SeaGreen"))
1081 "Face used to highlight function parameters in javascript."
1082 :group 'js2-mode)
1083
1084 (defface js2-function-call
1085 '((t :inherit default))
1086 "Face used to highlight function name in calls."
1087 :group 'js2-mode)
1088
1089 (defface js2-instance-member
1090 '((t :foreground "DarkOrchid"))
1091 "Face used to highlight instance variables in javascript.
1092 Not currently used."
1093 :group 'js2-mode)
1094
1095 (defface js2-private-member
1096 '((t :foreground "PeachPuff3"))
1097 "Face used to highlight calls to private methods in javascript.
1098 Not currently used."
1099 :group 'js2-mode)
1100
1101 (defface js2-private-function-call
1102 '((t :foreground "goldenrod"))
1103 "Face used to highlight calls to private functions in javascript.
1104 Not currently used."
1105 :group 'js2-mode)
1106
1107 (defface js2-jsdoc-html-tag-name
1108 '((((class color) (min-colors 88) (background light))
1109 (:foreground "rosybrown"))
1110 (((class color) (min-colors 8) (background dark))
1111 (:foreground "yellow"))
1112 (((class color) (min-colors 8) (background light))
1113 (:foreground "magenta")))
1114 "Face used to highlight jsdoc html tag names"
1115 :group 'js2-mode)
1116
1117 (defface js2-jsdoc-html-tag-delimiter
1118 '((((class color) (min-colors 88) (background light))
1119 (:foreground "dark khaki"))
1120 (((class color) (min-colors 8) (background dark))
1121 (:foreground "green"))
1122 (((class color) (min-colors 8) (background light))
1123 (:foreground "green")))
1124 "Face used to highlight brackets in jsdoc html tags."
1125 :group 'js2-mode)
1126
1127 (defface js2-external-variable
1128 '((t :foreground "orange"))
1129 "Face used to highlight undeclared variable identifiers.")
1130
1131 (defcustom js2-init-hook nil
1132 "List of functions to be called after `js2-mode' or
1133 `js2-minor-mode' has initialized all variables, before parsing
1134 the buffer for the first time."
1135 :type 'hook
1136 :group 'js2-mode
1137 :version "20130608")
1138
1139 (defcustom js2-post-parse-callbacks nil
1140 "List of callback functions invoked after parsing finishes.
1141 Currently, the main use for this function is to add synthetic
1142 declarations to `js2-recorded-identifiers', which see."
1143 :type 'hook
1144 :group 'js2-mode)
1145
1146 (defcustom js2-build-imenu-callbacks nil
1147 "List of functions called during Imenu index generation.
1148 It's a good place to add additional entries to it, using
1149 `js2-record-imenu-entry'."
1150 :type 'hook
1151 :group 'js2-mode)
1152
1153 (defcustom js2-highlight-external-variables t
1154 "Non-nil to highlight undeclared variable identifiers.
1155 An undeclared variable is any variable not declared with var or let
1156 in the current scope or any lexically enclosing scope. If you use
1157 such a variable, then you are either expecting it to originate from
1158 another file, or you've got a potential bug."
1159 :type 'boolean
1160 :group 'js2-mode)
1161
1162 (defcustom js2-warn-about-unused-function-arguments nil
1163 "Non-nil to treat function arguments like declared-but-unused variables."
1164 :type 'booleanp
1165 :group 'js2-mode)
1166
1167 (defcustom js2-include-jslint-globals t
1168 "Non-nil to include the identifiers from JSLint global
1169 declaration (see http://www.jslint.com/lint.html#global) in the
1170 buffer-local externs list. See `js2-additional-externs' for more
1171 information."
1172 :type 'boolean
1173 :group 'js2-mode)
1174
1175 (defvar js2-mode-map
1176 (let ((map (make-sparse-keymap)))
1177 (define-key map [mouse-1] #'js2-mode-show-node)
1178 (define-key map (kbd "M-j") #'js2-line-break)
1179 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1180 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1181 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1182 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1183 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1184 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1185 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1186 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1187 (when js2-bounce-indent-p
1188 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1189
1190 (define-key map [menu-bar javascript]
1191 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1192
1193 (define-key map [menu-bar javascript customize-js2-mode]
1194 '(menu-item "Customize js2-mode" js2-mode-customize
1195 :help "Customize the behavior of this mode"))
1196
1197 (define-key map [menu-bar javascript js2-force-refresh]
1198 '(menu-item "Force buffer refresh" js2-mode-reset
1199 :help "Re-parse the buffer from scratch"))
1200
1201 (define-key map [menu-bar javascript separator-2]
1202 '("--"))
1203
1204 (define-key map [menu-bar javascript next-error]
1205 '(menu-item "Next warning or error" next-error
1206 :enabled (and js2-mode-ast
1207 (or (js2-ast-root-errors js2-mode-ast)
1208 (js2-ast-root-warnings js2-mode-ast)))
1209 :help "Move to next warning or error"))
1210
1211 (define-key map [menu-bar javascript display-errors]
1212 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1213 :visible (not js2-mode-show-parse-errors)
1214 :help "Turn on display of warnings and errors"))
1215
1216 (define-key map [menu-bar javascript hide-errors]
1217 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1218 :visible js2-mode-show-parse-errors
1219 :help "Turn off display of warnings and errors"))
1220
1221 (define-key map [menu-bar javascript separator-1]
1222 '("--"))
1223
1224 (define-key map [menu-bar javascript js2-toggle-function]
1225 '(menu-item "Show/collapse element" js2-mode-toggle-element
1226 :help "Hide or show function body or comment"))
1227
1228 (define-key map [menu-bar javascript show-comments]
1229 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1230 :visible js2-mode-comments-hidden
1231 :help "Expand all hidden block comments"))
1232
1233 (define-key map [menu-bar javascript hide-comments]
1234 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1235 :visible (not js2-mode-comments-hidden)
1236 :help "Show block comments as /*...*/"))
1237
1238 (define-key map [menu-bar javascript show-all-functions]
1239 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1240 :visible js2-mode-functions-hidden
1241 :help "Expand all hidden function bodies"))
1242
1243 (define-key map [menu-bar javascript hide-all-functions]
1244 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1245 :visible (not js2-mode-functions-hidden)
1246 :help "Show {...} for all top-level function bodies"))
1247
1248 map)
1249 "Keymap used in `js2-mode' buffers.")
1250
1251 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1252
1253 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1254 "Matches a //-comment line. Must be first non-whitespace on line.
1255 First match-group is the leading whitespace.")
1256
1257 (defvar js2-mode-hook nil)
1258
1259 (js2-deflocal js2-mode-ast nil "Private variable.")
1260 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1261 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1262 (js2-deflocal js2-mode-parsing nil "Private variable.")
1263 (js2-deflocal js2-mode-node-overlay nil)
1264
1265 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1266 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1267
1268 (js2-deflocal js2-mode-fontifications nil "Private variable")
1269 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1270 (js2-deflocal js2-imenu-recorder nil "Private variable")
1271 (js2-deflocal js2-imenu-function-map nil "Private variable")
1272
1273 (defvar js2-paragraph-start
1274 "\\(@[[:alpha:]]+\\>\\|$\\)")
1275
1276 ;; Note that we also set a 'c-in-sws text property in html comments,
1277 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1278 (defvar js2-syntactic-ws-start
1279 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1280
1281 (defvar js2-syntactic-ws-end
1282 "\\s \\|[\n\r/]\\|\\s!")
1283
1284 (defvar js2-syntactic-eol
1285 (concat "\\s *\\(/\\*[^*\n\r]*"
1286 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1287 "\\*+/\\s *\\)*"
1288 "\\(//\\|/\\*[^*\n\r]*"
1289 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1290 "\\|\\\\$\\|$\\)")
1291 "Copied from `java-mode'. Needed for some cc-engine functions.")
1292
1293 (defvar js2-comment-prefix-regexp
1294 "//+\\|\\**")
1295
1296 (defvar js2-comment-start-skip
1297 "\\(//+\\|/\\*+\\)\\s *")
1298
1299 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1300 "Non-nil to emit status messages during parsing.")
1301
1302 (defvar js2-mode-functions-hidden nil "Private variable.")
1303 (defvar js2-mode-comments-hidden nil "Private variable.")
1304
1305 (defvar js2-mode-syntax-table
1306 (let ((table (make-syntax-table)))
1307 (c-populate-syntax-table table)
1308 (modify-syntax-entry ?` "\"" table)
1309 table)
1310 "Syntax table used in `js2-mode' buffers.")
1311
1312 (defvar js2-mode-abbrev-table nil
1313 "Abbrev table in use in `js2-mode' buffers.")
1314 (define-abbrev-table 'js2-mode-abbrev-table ())
1315
1316 (defvar js2-mode-pending-parse-callbacks nil
1317 "List of functions waiting to be notified that parse is finished.")
1318
1319 (defvar js2-mode-last-indented-line -1)
1320
1321 ;;; Localizable error and warning messages
1322
1323 ;; Messages are copied from Rhino's Messages.properties.
1324 ;; Many of the Java-specific messages have been elided.
1325 ;; Add any js2-specific ones at the end, so we can keep
1326 ;; this file synced with changes to Rhino's.
1327
1328 (defvar js2-message-table
1329 (make-hash-table :test 'equal :size 250)
1330 "Contains localized messages for `js2-mode'.")
1331
1332 ;; TODO(stevey): construct this table at compile-time.
1333 (defmacro js2-msg (key &rest strings)
1334 `(puthash ,key (concat ,@strings)
1335 js2-message-table))
1336
1337 (defun js2-get-msg (msg-key)
1338 "Look up a localized message.
1339 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1340 the correct number of ARGS must be provided."
1341 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1342 (args (if (listp msg-key) (cdr msg-key)))
1343 (msg (gethash key js2-message-table)))
1344 (if msg
1345 (apply #'format msg args)
1346 key))) ; default to showing the key
1347
1348 (js2-msg "msg.dup.parms"
1349 "Duplicate parameter name '%s'.")
1350
1351 (js2-msg "msg.too.big.jump"
1352 "Program too complex: jump offset too big.")
1353
1354 (js2-msg "msg.too.big.index"
1355 "Program too complex: internal index exceeds 64K limit.")
1356
1357 (js2-msg "msg.while.compiling.fn"
1358 "Encountered code generation error while compiling function '%s': %s")
1359
1360 (js2-msg "msg.while.compiling.script"
1361 "Encountered code generation error while compiling script: %s")
1362
1363 ;; Context
1364 (js2-msg "msg.ctor.not.found"
1365 "Constructor for '%s' not found.")
1366
1367 (js2-msg "msg.not.ctor"
1368 "'%s' is not a constructor.")
1369
1370 ;; FunctionObject
1371 (js2-msg "msg.varargs.ctor"
1372 "Method or constructor '%s' must be static "
1373 "with the signature (Context cx, Object[] args, "
1374 "Function ctorObj, boolean inNewExpr) "
1375 "to define a variable arguments constructor.")
1376
1377 (js2-msg "msg.varargs.fun"
1378 "Method '%s' must be static with the signature "
1379 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1380 "to define a variable arguments function.")
1381
1382 (js2-msg "msg.incompat.call"
1383 "Method '%s' called on incompatible object.")
1384
1385 (js2-msg "msg.bad.parms"
1386 "Unsupported parameter type '%s' in method '%s'.")
1387
1388 (js2-msg "msg.bad.method.return"
1389 "Unsupported return type '%s' in method '%s'.")
1390
1391 (js2-msg "msg.bad.ctor.return"
1392 "Construction of objects of type '%s' is not supported.")
1393
1394 (js2-msg "msg.no.overload"
1395 "Method '%s' occurs multiple times in class '%s'.")
1396
1397 (js2-msg "msg.method.not.found"
1398 "Method '%s' not found in '%s'.")
1399
1400 ;; IRFactory
1401
1402 (js2-msg "msg.bad.for.in.lhs"
1403 "Invalid left-hand side of for..in loop.")
1404
1405 (js2-msg "msg.mult.index"
1406 "Only one variable allowed in for..in loop.")
1407
1408 (js2-msg "msg.bad.for.in.destruct"
1409 "Left hand side of for..in loop must be an array of "
1410 "length 2 to accept key/value pair.")
1411
1412 (js2-msg "msg.cant.convert"
1413 "Can't convert to type '%s'.")
1414
1415 (js2-msg "msg.bad.assign.left"
1416 "Invalid assignment left-hand side.")
1417
1418 (js2-msg "msg.bad.decr"
1419 "Invalid decrement operand.")
1420
1421 (js2-msg "msg.bad.incr"
1422 "Invalid increment operand.")
1423
1424 (js2-msg "msg.bad.yield"
1425 "yield must be in a function.")
1426
1427 (js2-msg "msg.yield.parenthesized"
1428 "yield expression must be parenthesized.")
1429
1430 ;; NativeGlobal
1431 (js2-msg "msg.cant.call.indirect"
1432 "Function '%s' must be called directly, and not by way of a "
1433 "function of another name.")
1434
1435 (js2-msg "msg.eval.nonstring"
1436 "Calling eval() with anything other than a primitive "
1437 "string value will simply return the value. "
1438 "Is this what you intended?")
1439
1440 (js2-msg "msg.eval.nonstring.strict"
1441 "Calling eval() with anything other than a primitive "
1442 "string value is not allowed in strict mode.")
1443
1444 (js2-msg "msg.bad.destruct.op"
1445 "Invalid destructuring assignment operator")
1446
1447 ;; NativeCall
1448 (js2-msg "msg.only.from.new"
1449 "'%s' may only be invoked from a `new' expression.")
1450
1451 (js2-msg "msg.deprec.ctor"
1452 "The '%s' constructor is deprecated.")
1453
1454 ;; NativeFunction
1455 (js2-msg "msg.no.function.ref.found"
1456 "no source found to decompile function reference %s")
1457
1458 (js2-msg "msg.arg.isnt.array"
1459 "second argument to Function.prototype.apply must be an array")
1460
1461 ;; NativeGlobal
1462 (js2-msg "msg.bad.esc.mask"
1463 "invalid string escape mask")
1464
1465 ;; NativeRegExp
1466 (js2-msg "msg.bad.quant"
1467 "Invalid quantifier %s")
1468
1469 (js2-msg "msg.overlarge.backref"
1470 "Overly large back reference %s")
1471
1472 (js2-msg "msg.overlarge.min"
1473 "Overly large minimum %s")
1474
1475 (js2-msg "msg.overlarge.max"
1476 "Overly large maximum %s")
1477
1478 (js2-msg "msg.zero.quant"
1479 "Zero quantifier %s")
1480
1481 (js2-msg "msg.max.lt.min"
1482 "Maximum %s less than minimum")
1483
1484 (js2-msg "msg.unterm.quant"
1485 "Unterminated quantifier %s")
1486
1487 (js2-msg "msg.unterm.paren"
1488 "Unterminated parenthetical %s")
1489
1490 (js2-msg "msg.unterm.class"
1491 "Unterminated character class %s")
1492
1493 (js2-msg "msg.bad.range"
1494 "Invalid range in character class.")
1495
1496 (js2-msg "msg.trail.backslash"
1497 "Trailing \\ in regular expression.")
1498
1499 (js2-msg "msg.re.unmatched.right.paren"
1500 "unmatched ) in regular expression.")
1501
1502 (js2-msg "msg.no.regexp"
1503 "Regular expressions are not available.")
1504
1505 (js2-msg "msg.bad.backref"
1506 "back-reference exceeds number of capturing parentheses.")
1507
1508 (js2-msg "msg.bad.regexp.compile"
1509 "Only one argument may be specified if the first "
1510 "argument to RegExp.prototype.compile is a RegExp object.")
1511
1512 ;; Parser
1513 (js2-msg "msg.got.syntax.errors"
1514 "Compilation produced %s syntax errors.")
1515
1516 (js2-msg "msg.var.redecl"
1517 "TypeError: redeclaration of var %s.")
1518
1519 (js2-msg "msg.const.redecl"
1520 "TypeError: redeclaration of const %s.")
1521
1522 (js2-msg "msg.let.redecl"
1523 "TypeError: redeclaration of variable %s.")
1524
1525 (js2-msg "msg.parm.redecl"
1526 "TypeError: redeclaration of formal parameter %s.")
1527
1528 (js2-msg "msg.fn.redecl"
1529 "TypeError: redeclaration of function %s.")
1530
1531 (js2-msg "msg.let.decl.not.in.block"
1532 "SyntaxError: let declaration not directly within block")
1533
1534 (js2-msg "msg.mod.import.decl.at.top.level"
1535 "SyntaxError: import declarations may only appear at the top level")
1536
1537 (js2-msg "msg.mod.as.after.reserved.word"
1538 "SyntaxError: missing keyword 'as' after reserved word %s")
1539
1540 (js2-msg "msg.mod.rc.after.import.spec.list"
1541 "SyntaxError: missing '}' after module specifier list")
1542
1543 (js2-msg "msg.mod.from.after.import.spec.set"
1544 "SyntaxError: missing keyword 'from' after import specifier set")
1545
1546 (js2-msg "msg.mod.declaration.after.import"
1547 "SyntaxError: missing declaration after 'import' keyword")
1548
1549 (js2-msg "msg.mod.spec.after.from"
1550 "SyntaxError: missing module specifier after 'from' keyword")
1551
1552 (js2-msg "msg.mod.export.decl.at.top.level"
1553 "SyntaxError: export declarations may only appear at top level")
1554
1555 (js2-msg "msg.mod.rc.after.export.spec.list"
1556 "SyntaxError: missing '}' after export specifier list")
1557
1558 ;; NodeTransformer
1559 (js2-msg "msg.dup.label"
1560 "duplicated label")
1561
1562 (js2-msg "msg.undef.label"
1563 "undefined label")
1564
1565 (js2-msg "msg.bad.break"
1566 "unlabelled break must be inside loop or switch")
1567
1568 (js2-msg "msg.continue.outside"
1569 "continue must be inside loop")
1570
1571 (js2-msg "msg.continue.nonloop"
1572 "continue can only use labels of iteration statements")
1573
1574 (js2-msg "msg.bad.throw.eol"
1575 "Line terminator is not allowed between the throw "
1576 "keyword and throw expression.")
1577
1578 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1579 "function statement requires a name")
1580
1581 (js2-msg "msg.no.paren.parms"
1582 "missing ( before function parameters.")
1583
1584 (js2-msg "msg.no.parm"
1585 "missing formal parameter")
1586
1587 (js2-msg "msg.no.paren.after.parms"
1588 "missing ) after formal parameters")
1589
1590 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1591 "parameter without default follows parameter with default")
1592
1593 (js2-msg "msg.param.after.rest" ; added by js2-mode
1594 "parameter after rest parameter")
1595
1596 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1597 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1598
1599 (js2-msg "msg.no.brace.body"
1600 "missing '{' before function body")
1601
1602 (js2-msg "msg.no.brace.after.body"
1603 "missing } after function body")
1604
1605 (js2-msg "msg.no.paren.cond"
1606 "missing ( before condition")
1607
1608 (js2-msg "msg.no.paren.after.cond"
1609 "missing ) after condition")
1610
1611 (js2-msg "msg.no.semi.stmt"
1612 "missing ; before statement")
1613
1614 (js2-msg "msg.missing.semi"
1615 "missing ; after statement")
1616
1617 (js2-msg "msg.no.name.after.dot"
1618 "missing name after . operator")
1619
1620 (js2-msg "msg.no.name.after.coloncolon"
1621 "missing name after :: operator")
1622
1623 (js2-msg "msg.no.name.after.dotdot"
1624 "missing name after .. operator")
1625
1626 (js2-msg "msg.no.name.after.xmlAttr"
1627 "missing name after .@")
1628
1629 (js2-msg "msg.no.bracket.index"
1630 "missing ] in index expression")
1631
1632 (js2-msg "msg.no.paren.switch"
1633 "missing ( before switch expression")
1634
1635 (js2-msg "msg.no.paren.after.switch"
1636 "missing ) after switch expression")
1637
1638 (js2-msg "msg.no.brace.switch"
1639 "missing '{' before switch body")
1640
1641 (js2-msg "msg.bad.switch"
1642 "invalid switch statement")
1643
1644 (js2-msg "msg.no.colon.case"
1645 "missing : after case expression")
1646
1647 (js2-msg "msg.double.switch.default"
1648 "double default label in the switch statement")
1649
1650 (js2-msg "msg.no.while.do"
1651 "missing while after do-loop body")
1652
1653 (js2-msg "msg.no.paren.for"
1654 "missing ( after for")
1655
1656 (js2-msg "msg.no.semi.for"
1657 "missing ; after for-loop initializer")
1658
1659 (js2-msg "msg.no.semi.for.cond"
1660 "missing ; after for-loop condition")
1661
1662 (js2-msg "msg.in.after.for.name"
1663 "missing in or of after for")
1664
1665 (js2-msg "msg.no.paren.for.ctrl"
1666 "missing ) after for-loop control")
1667
1668 (js2-msg "msg.no.paren.with"
1669 "missing ( before with-statement object")
1670
1671 (js2-msg "msg.no.paren.after.with"
1672 "missing ) after with-statement object")
1673
1674 (js2-msg "msg.no.paren.after.let"
1675 "missing ( after let")
1676
1677 (js2-msg "msg.no.paren.let"
1678 "missing ) after variable list")
1679
1680 (js2-msg "msg.no.curly.let"
1681 "missing } after let statement")
1682
1683 (js2-msg "msg.bad.return"
1684 "invalid return")
1685
1686 (js2-msg "msg.no.brace.block"
1687 "missing } in compound statement")
1688
1689 (js2-msg "msg.bad.label"
1690 "invalid label")
1691
1692 (js2-msg "msg.bad.var"
1693 "missing variable name")
1694
1695 (js2-msg "msg.bad.var.init"
1696 "invalid variable initialization")
1697
1698 (js2-msg "msg.no.colon.cond"
1699 "missing : in conditional expression")
1700
1701 (js2-msg "msg.no.paren.arg"
1702 "missing ) after argument list")
1703
1704 (js2-msg "msg.no.bracket.arg"
1705 "missing ] after element list")
1706
1707 (js2-msg "msg.bad.prop"
1708 "invalid property id")
1709
1710 (js2-msg "msg.no.colon.prop"
1711 "missing : after property id")
1712
1713 (js2-msg "msg.no.brace.prop"
1714 "missing } after property list")
1715
1716 (js2-msg "msg.no.paren"
1717 "missing ) in parenthetical")
1718
1719 (js2-msg "msg.reserved.id"
1720 "'%s' is a reserved identifier")
1721
1722 (js2-msg "msg.no.paren.catch"
1723 "missing ( before catch-block condition")
1724
1725 (js2-msg "msg.bad.catchcond"
1726 "invalid catch block condition")
1727
1728 (js2-msg "msg.catch.unreachable"
1729 "any catch clauses following an unqualified catch are unreachable")
1730
1731 (js2-msg "msg.no.brace.try"
1732 "missing '{' before try block")
1733
1734 (js2-msg "msg.no.brace.catchblock"
1735 "missing '{' before catch-block body")
1736
1737 (js2-msg "msg.try.no.catchfinally"
1738 "'try' without 'catch' or 'finally'")
1739
1740 (js2-msg "msg.no.return.value"
1741 "function %s does not always return a value")
1742
1743 (js2-msg "msg.anon.no.return.value"
1744 "anonymous function does not always return a value")
1745
1746 (js2-msg "msg.return.inconsistent"
1747 "return statement is inconsistent with previous usage")
1748
1749 (js2-msg "msg.generator.returns"
1750 "TypeError: legacy generator function '%s' returns a value")
1751
1752 (js2-msg "msg.anon.generator.returns"
1753 "TypeError: anonymous legacy generator function returns a value")
1754
1755 (js2-msg "msg.syntax"
1756 "syntax error")
1757
1758 (js2-msg "msg.unexpected.eof"
1759 "Unexpected end of file")
1760
1761 (js2-msg "msg.XML.bad.form"
1762 "illegally formed XML syntax")
1763
1764 (js2-msg "msg.XML.not.available"
1765 "XML runtime not available")
1766
1767 (js2-msg "msg.too.deep.parser.recursion"
1768 "Too deep recursion while parsing")
1769
1770 (js2-msg "msg.no.side.effects"
1771 "Code has no side effects")
1772
1773 (js2-msg "msg.extra.trailing.comma"
1774 "Trailing comma is not supported in some browsers")
1775
1776 (js2-msg "msg.array.trailing.comma"
1777 "Trailing comma yields different behavior across browsers")
1778
1779 (js2-msg "msg.equal.as.assign"
1780 (concat "Test for equality (==) mistyped as assignment (=)?"
1781 " (parenthesize to suppress warning)"))
1782
1783 (js2-msg "msg.var.hides.arg"
1784 "Variable %s hides argument")
1785
1786 (js2-msg "msg.destruct.assign.no.init"
1787 "Missing = in destructuring declaration")
1788
1789 ;; ScriptRuntime
1790 (js2-msg "msg.no.properties"
1791 "%s has no properties.")
1792
1793 (js2-msg "msg.invalid.iterator"
1794 "Invalid iterator value")
1795
1796 (js2-msg "msg.iterator.primitive"
1797 "__iterator__ returned a primitive value")
1798
1799 (js2-msg "msg.assn.create.strict"
1800 "Assignment to undeclared variable %s")
1801
1802 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1803 "Undeclared variable or function '%s'")
1804
1805 (js2-msg "msg.unused.variable" ; added by js2-mode
1806 "Unused variable or function '%s'")
1807
1808 (js2-msg "msg.uninitialized.variable" ; added by js2-mode
1809 "Variable '%s' referenced but never initialized")
1810
1811 (js2-msg "msg.ref.undefined.prop"
1812 "Reference to undefined property '%s'")
1813
1814 (js2-msg "msg.prop.not.found"
1815 "Property %s not found.")
1816
1817 (js2-msg "msg.invalid.type"
1818 "Invalid JavaScript value of type %s")
1819
1820 (js2-msg "msg.primitive.expected"
1821 "Primitive type expected (had %s instead)")
1822
1823 (js2-msg "msg.namespace.expected"
1824 "Namespace object expected to left of :: (found %s instead)")
1825
1826 (js2-msg "msg.null.to.object"
1827 "Cannot convert null to an object.")
1828
1829 (js2-msg "msg.undef.to.object"
1830 "Cannot convert undefined to an object.")
1831
1832 (js2-msg "msg.cyclic.value"
1833 "Cyclic %s value not allowed.")
1834
1835 (js2-msg "msg.is.not.defined"
1836 "'%s' is not defined.")
1837
1838 (js2-msg "msg.undef.prop.read"
1839 "Cannot read property '%s' from %s")
1840
1841 (js2-msg "msg.undef.prop.write"
1842 "Cannot set property '%s' of %s to '%s'")
1843
1844 (js2-msg "msg.undef.prop.delete"
1845 "Cannot delete property '%s' of %s")
1846
1847 (js2-msg "msg.undef.method.call"
1848 "Cannot call method '%s' of %s")
1849
1850 (js2-msg "msg.undef.with"
1851 "Cannot apply 'with' to %s")
1852
1853 (js2-msg "msg.isnt.function"
1854 "%s is not a function, it is %s.")
1855
1856 (js2-msg "msg.isnt.function.in"
1857 "Cannot call property %s in object %s. "
1858 "It is not a function, it is '%s'.")
1859
1860 (js2-msg "msg.function.not.found"
1861 "Cannot find function %s.")
1862
1863 (js2-msg "msg.function.not.found.in"
1864 "Cannot find function %s in object %s.")
1865
1866 (js2-msg "msg.isnt.xml.object"
1867 "%s is not an xml object.")
1868
1869 (js2-msg "msg.no.ref.to.get"
1870 "%s is not a reference to read reference value.")
1871
1872 (js2-msg "msg.no.ref.to.set"
1873 "%s is not a reference to set reference value to %s.")
1874
1875 (js2-msg "msg.no.ref.from.function"
1876 "Function %s can not be used as the left-hand "
1877 "side of assignment or as an operand of ++ or -- operator.")
1878
1879 (js2-msg "msg.bad.default.value"
1880 "Object's getDefaultValue() method returned an object.")
1881
1882 (js2-msg "msg.instanceof.not.object"
1883 "Can't use instanceof on a non-object.")
1884
1885 (js2-msg "msg.instanceof.bad.prototype"
1886 "'prototype' property of %s is not an object.")
1887
1888 (js2-msg "msg.bad.radix"
1889 "illegal radix %s.")
1890
1891 ;; ScriptableObject
1892 (js2-msg "msg.default.value"
1893 "Cannot find default value for object.")
1894
1895 (js2-msg "msg.zero.arg.ctor"
1896 "Cannot load class '%s' which has no zero-parameter constructor.")
1897
1898 (js2-msg "msg.ctor.multiple.parms"
1899 "Can't define constructor or class %s since more than "
1900 "one constructor has multiple parameters.")
1901
1902 (js2-msg "msg.extend.scriptable"
1903 "%s must extend ScriptableObject in order to define property %s.")
1904
1905 (js2-msg "msg.bad.getter.parms"
1906 "In order to define a property, getter %s must have zero "
1907 "parameters or a single ScriptableObject parameter.")
1908
1909 (js2-msg "msg.obj.getter.parms"
1910 "Expected static or delegated getter %s to take "
1911 "a ScriptableObject parameter.")
1912
1913 (js2-msg "msg.getter.static"
1914 "Getter and setter must both be static or neither be static.")
1915
1916 (js2-msg "msg.setter.return"
1917 "Setter must have void return type: %s")
1918
1919 (js2-msg "msg.setter2.parms"
1920 "Two-parameter setter must take a ScriptableObject as "
1921 "its first parameter.")
1922
1923 (js2-msg "msg.setter1.parms"
1924 "Expected single parameter setter for %s")
1925
1926 (js2-msg "msg.setter2.expected"
1927 "Expected static or delegated setter %s to take two parameters.")
1928
1929 (js2-msg "msg.setter.parms"
1930 "Expected either one or two parameters for setter.")
1931
1932 (js2-msg "msg.setter.bad.type"
1933 "Unsupported parameter type '%s' in setter '%s'.")
1934
1935 (js2-msg "msg.add.sealed"
1936 "Cannot add a property to a sealed object: %s.")
1937
1938 (js2-msg "msg.remove.sealed"
1939 "Cannot remove a property from a sealed object: %s.")
1940
1941 (js2-msg "msg.modify.sealed"
1942 "Cannot modify a property of a sealed object: %s.")
1943
1944 (js2-msg "msg.modify.readonly"
1945 "Cannot modify readonly property: %s.")
1946
1947 ;; TokenStream
1948 (js2-msg "msg.missing.exponent"
1949 "missing exponent")
1950
1951 (js2-msg "msg.caught.nfe"
1952 "number format error")
1953
1954 (js2-msg "msg.unterminated.string.lit"
1955 "unterminated string literal")
1956
1957 (js2-msg "msg.unterminated.comment"
1958 "unterminated comment")
1959
1960 (js2-msg "msg.unterminated.re.lit"
1961 "unterminated regular expression literal")
1962
1963 (js2-msg "msg.invalid.re.flag"
1964 "invalid flag after regular expression")
1965
1966 (js2-msg "msg.no.re.input.for"
1967 "no input for %s")
1968
1969 (js2-msg "msg.illegal.character"
1970 "illegal character")
1971
1972 (js2-msg "msg.invalid.escape"
1973 "invalid Unicode escape sequence")
1974
1975 (js2-msg "msg.bad.namespace"
1976 "not a valid default namespace statement. "
1977 "Syntax is: default xml namespace = EXPRESSION;")
1978
1979 ;; TokensStream warnings
1980 (js2-msg "msg.bad.octal.literal"
1981 "illegal octal literal digit %s; "
1982 "interpreting it as a decimal digit")
1983
1984 (js2-msg "msg.missing.hex.digits"
1985 "missing hexadecimal digits after '0x'")
1986
1987 (js2-msg "msg.missing.binary.digits"
1988 "missing binary digits after '0b'")
1989
1990 (js2-msg "msg.missing.octal.digits"
1991 "missing octal digits after '0o'")
1992
1993 (js2-msg "msg.script.is.not.constructor"
1994 "Script objects are not constructors.")
1995
1996 ;; Arrays
1997 (js2-msg "msg.arraylength.bad"
1998 "Inappropriate array length.")
1999
2000 ;; Arrays
2001 (js2-msg "msg.arraylength.too.big"
2002 "Array length %s exceeds supported capacity limit.")
2003
2004 ;; URI
2005 (js2-msg "msg.bad.uri"
2006 "Malformed URI sequence.")
2007
2008 ;; Number
2009 (js2-msg "msg.bad.precision"
2010 "Precision %s out of range.")
2011
2012 ;; NativeGenerator
2013 (js2-msg "msg.send.newborn"
2014 "Attempt to send value to newborn generator")
2015
2016 (js2-msg "msg.already.exec.gen"
2017 "Already executing generator")
2018
2019 (js2-msg "msg.StopIteration.invalid"
2020 "StopIteration may not be changed to an arbitrary object.")
2021
2022 ;; Interpreter
2023 (js2-msg "msg.yield.closing"
2024 "Yield from closing generator")
2025
2026 ;; Classes
2027 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
2028 "class statement requires a name")
2029
2030 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
2031 "unexpected ',' between class properties")
2032
2033 (js2-msg "msg.unexpected.static" ; added by js2-mode
2034 "unexpected 'static'")
2035
2036 (js2-msg "msg.missing.extends" ; added by js2-mode
2037 "name is required after extends")
2038
2039 (js2-msg "msg.no.brace.class" ; added by js2-mode
2040 "missing '{' before class body")
2041
2042 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2043 "missing ']' after computed property expression")
2044
2045 ;;; Tokens Buffer
2046
2047 (defconst js2-ti-max-lookahead 2)
2048 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2049
2050 (defun js2-new-token (offset)
2051 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2052 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2053 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2054 token))
2055
2056 (defsubst js2-current-token ()
2057 (aref js2-ti-tokens js2-ti-tokens-cursor))
2058
2059 (defsubst js2-current-token-string ()
2060 (js2-token-string (js2-current-token)))
2061
2062 (defsubst js2-current-token-type ()
2063 (js2-token-type (js2-current-token)))
2064
2065 (defsubst js2-current-token-beg ()
2066 (js2-token-beg (js2-current-token)))
2067
2068 (defsubst js2-current-token-end ()
2069 (js2-token-end (js2-current-token)))
2070
2071 (defun js2-current-token-len ()
2072 (let ((token (js2-current-token)))
2073 (- (js2-token-end token)
2074 (js2-token-beg token))))
2075
2076 (defun js2-ts-seek (state)
2077 (setq js2-ts-lineno (js2-ts-state-lineno state)
2078 js2-ts-cursor (js2-ts-state-cursor state)
2079 js2-ti-tokens (js2-ts-state-tokens state)
2080 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2081 js2-ti-lookahead (js2-ts-state-lookahead state)))
2082
2083 ;;; Utilities
2084
2085 (defun js2-delete-if (predicate list)
2086 "Remove all items satisfying PREDICATE in LIST."
2087 (cl-loop for item in list
2088 if (not (funcall predicate item))
2089 collect item))
2090
2091 (defun js2-position (element list)
2092 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2093 Returns nil if element is not found in the list."
2094 (let ((count 0)
2095 found)
2096 (while (and list (not found))
2097 (if (eq element (car list))
2098 (setq found t)
2099 (setq count (1+ count)
2100 list (cdr list))))
2101 (if found count)))
2102
2103 (defun js2-find-if (predicate list)
2104 "Find first item satisfying PREDICATE in LIST."
2105 (let (result)
2106 (while (and list (not result))
2107 (if (funcall predicate (car list))
2108 (setq result (car list)))
2109 (setq list (cdr list)))
2110 result))
2111
2112 (defmacro js2-time (form)
2113 "Evaluate FORM, discard result, and return elapsed time in sec."
2114 (declare (debug t))
2115 (let ((beg (make-symbol "--js2-time-beg--")))
2116 `(let ((,beg (current-time)))
2117 ,form
2118 (/ (truncate (* (- (float-time (current-time))
2119 (float-time ,beg))
2120 10000))
2121 10000.0))))
2122
2123 (defsubst js2-same-line (pos)
2124 "Return t if POS is on the same line as current point."
2125 (and (>= pos (point-at-bol))
2126 (<= pos (point-at-eol))))
2127
2128 (defun js2-code-bug ()
2129 "Signal an error when we encounter an unexpected code path."
2130 (error "failed assertion"))
2131
2132 (defsubst js2-record-text-property (beg end prop value)
2133 "Record a text property to set when parsing finishes."
2134 (push (list beg end prop value) js2-mode-deferred-properties))
2135
2136 ;; I'd like to associate errors with nodes, but for now the
2137 ;; easiest thing to do is get the context info from the last token.
2138 (defun js2-record-parse-error (msg &optional arg pos len)
2139 (push (list (list msg arg)
2140 (or pos (js2-current-token-beg))
2141 (or len (js2-current-token-len)))
2142 js2-parsed-errors))
2143
2144 (defun js2-report-error (msg &optional msg-arg pos len)
2145 "Signal a syntax error or record a parse error."
2146 (if js2-recover-from-parse-errors
2147 (js2-record-parse-error msg msg-arg pos len)
2148 (signal 'js2-syntax-error
2149 (list msg
2150 js2-ts-lineno
2151 (save-excursion
2152 (goto-char js2-ts-cursor)
2153 (current-column))
2154 js2-ts-hit-eof))))
2155
2156 (defun js2-report-warning (msg &optional msg-arg pos len face)
2157 (if js2-compiler-report-warning-as-error
2158 (js2-report-error msg msg-arg pos len)
2159 (push (list (list msg msg-arg)
2160 (or pos (js2-current-token-beg))
2161 (or len (js2-current-token-len))
2162 face)
2163 js2-parsed-warnings)))
2164
2165 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2166 (if js2-compiler-strict-mode
2167 (js2-report-warning msg-id msg-arg beg
2168 (and beg end (- end beg)))))
2169
2170 (put 'js2-syntax-error 'error-conditions
2171 '(error syntax-error js2-syntax-error))
2172 (put 'js2-syntax-error 'error-message "Syntax error")
2173
2174 (put 'js2-parse-error 'error-conditions
2175 '(error parse-error js2-parse-error))
2176 (put 'js2-parse-error 'error-message "Parse error")
2177
2178 (defmacro js2-clear-flag (flags flag)
2179 `(setq ,flags (logand ,flags (lognot ,flag))))
2180
2181 (defmacro js2-set-flag (flags flag)
2182 "Logical-or FLAG into FLAGS."
2183 `(setq ,flags (logior ,flags ,flag)))
2184
2185 (defsubst js2-flag-set-p (flags flag)
2186 (/= 0 (logand flags flag)))
2187
2188 (defsubst js2-flag-not-set-p (flags flag)
2189 (zerop (logand flags flag)))
2190
2191 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2192 "Evaluate BODY with the _ character set to be word-syntax."
2193 (declare (indent 0) (debug t))
2194 (let ((old-syntax (make-symbol "old-syntax")))
2195 `(let ((,old-syntax (string (char-syntax ?_))))
2196 (unwind-protect
2197 (progn
2198 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2199 ,@body)
2200 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2201
2202 ;;; AST struct and function definitions
2203
2204 ;; flags for ast node property 'member-type (used for e4x operators)
2205 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2206 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2207 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2208
2209 (defsubst js2-relpos (pos anchor)
2210 "Convert POS to be relative to ANCHOR.
2211 If POS is nil, returns nil."
2212 (and pos (- pos anchor)))
2213
2214 (defun js2-make-pad (indent)
2215 (if (zerop indent)
2216 ""
2217 (make-string (* indent js2-basic-offset) ? )))
2218
2219 (defun js2-visit-ast (node callback)
2220 "Visit every node in ast NODE with visitor CALLBACK.
2221
2222 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2223 called twice: once to visit the node, and again after all the node's
2224 children have been processed. The END-P argument is nil on the first
2225 call and non-nil on the second call. The return value of the callback
2226 affects the traversal: if non-nil, the children of NODE are processed.
2227 If the callback returns nil, or if the node has no children, then the
2228 callback is called immediately with a non-nil END-P argument.
2229
2230 The node traversal is approximately lexical-order, although there
2231 are currently no guarantees around this."
2232 (when node
2233 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2234 ;; visit the node
2235 (when (funcall callback node nil)
2236 ;; visit the kids
2237 (cond
2238 ((eq vfunc 'js2-visit-none)
2239 nil) ; don't even bother calling it
2240 ;; Each AST node type has to define a `js2-visitor' function
2241 ;; that takes a node and a callback, and calls `js2-visit-ast'
2242 ;; on each child of the node.
2243 (vfunc
2244 (funcall vfunc node callback))
2245 (t
2246 (error "%s does not define a visitor-traversal function"
2247 (aref node 0)))))
2248 ;; call the end-visit
2249 (funcall callback node t))))
2250
2251 (cl-defstruct (js2-node
2252 (:constructor nil)) ; abstract
2253 "Base AST node type."
2254 (type -1) ; token type
2255 (pos -1) ; start position of this AST node in parsed input
2256 (len 1) ; num characters spanned by the node
2257 props ; optional node property list (an alist)
2258 parent) ; link to parent node; null for root
2259
2260 (defsubst js2-node-get-prop (node prop &optional default)
2261 (or (cadr (assoc prop (js2-node-props node))) default))
2262
2263 (defsubst js2-node-set-prop (node prop value)
2264 (setf (js2-node-props node)
2265 (cons (list prop value) (js2-node-props node))))
2266
2267 (defun js2-fixup-starts (n nodes)
2268 "Adjust the start positions of NODES to be relative to N.
2269 Any node in the list may be nil, for convenience."
2270 (dolist (node nodes)
2271 (when node
2272 (setf (js2-node-pos node) (- (js2-node-pos node)
2273 (js2-node-pos n))))))
2274
2275 (defun js2-node-add-children (parent &rest nodes)
2276 "Set parent node of NODES to PARENT, and return PARENT.
2277 Does nothing if we're not recording parent links.
2278 If any given node in NODES is nil, doesn't record that link."
2279 (js2-fixup-starts parent nodes)
2280 (dolist (node nodes)
2281 (and node
2282 (setf (js2-node-parent node) parent))))
2283
2284 ;; Non-recursive since it's called a frightening number of times.
2285 (defun js2-node-abs-pos (n)
2286 (let ((pos (js2-node-pos n)))
2287 (while (setq n (js2-node-parent n))
2288 (setq pos (+ pos (js2-node-pos n))))
2289 pos))
2290
2291 (defsubst js2-node-abs-end (n)
2292 "Return absolute buffer position of end of N."
2293 (+ (js2-node-abs-pos n) (js2-node-len n)))
2294
2295 ;; It's important to make sure block nodes have a Lisp list for the
2296 ;; child nodes, to limit printing recursion depth in an AST that
2297 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2298 ;; a sufficiently large vector tree.
2299
2300 (cl-defstruct (js2-block-node
2301 (:include js2-node)
2302 (:constructor nil)
2303 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2304 (pos (js2-current-token-beg))
2305 len
2306 props
2307 kids)))
2308 "A block of statements."
2309 kids) ; a Lisp list of the child statement nodes
2310
2311 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2312 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2313
2314 (defun js2-visit-block (ast callback)
2315 "Visit the `js2-block-node' children of AST."
2316 (dolist (kid (js2-block-node-kids ast))
2317 (js2-visit-ast kid callback)))
2318
2319 (defun js2-print-block (n i)
2320 (let ((pad (js2-make-pad i)))
2321 (insert pad "{\n")
2322 (dolist (kid (js2-block-node-kids n))
2323 (js2-print-ast kid (1+ i)))
2324 (insert pad "}")))
2325
2326 (cl-defstruct (js2-scope
2327 (:include js2-block-node)
2328 (:constructor nil)
2329 (:constructor make-js2-scope (&key (type js2-BLOCK)
2330 (pos (js2-current-token-beg))
2331 len
2332 kids)))
2333 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2334 ;; I don't have one of those handy, so I'll use an alist for now.
2335 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2336 ;; and is much lighter-weight to construct (both CPU and mem).
2337 ;; The keys are interned strings (symbols) for faster lookup.
2338 ;; Should switch to hybrid alist/hashtable eventually.
2339 symbol-table ; an alist of (symbol . js2-symbol)
2340 parent-scope ; a `js2-scope'
2341 top) ; top-level `js2-scope' (script/function)
2342
2343 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2344 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2345
2346 (defun js2-node-get-enclosing-scope (node)
2347 "Return the innermost `js2-scope' node surrounding NODE.
2348 Returns nil if there is no enclosing scope node."
2349 (while (and (setq node (js2-node-parent node))
2350 (not (js2-scope-p node))))
2351 node)
2352
2353 (defun js2-get-defining-scope (scope name &optional point)
2354 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2355 Returns `js2-scope' in which NAME is defined, or nil if not found.
2356
2357 If POINT is non-nil, and if the found declaration type is
2358 `js2-LET', also check that the declaration node is before POINT."
2359 (let ((sym (if (symbolp name)
2360 name
2361 (intern name)))
2362 result
2363 (continue t))
2364 (while (and scope continue)
2365 (if (or
2366 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2367 (and entry
2368 (or (not point)
2369 (not (eq js2-LET (js2-symbol-decl-type entry)))
2370 (>= point
2371 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2372 (and (eq sym 'arguments)
2373 (js2-function-node-p scope)))
2374 (setq continue nil
2375 result scope)
2376 (setq scope (js2-scope-parent-scope scope))))
2377 result))
2378
2379 (defun js2-scope-get-symbol (scope name)
2380 "Return symbol table entry for NAME in SCOPE.
2381 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2382 (and (js2-scope-symbol-table scope)
2383 (cdr (assq (if (symbolp name)
2384 name
2385 (intern name))
2386 (js2-scope-symbol-table scope)))))
2387
2388 (defun js2-scope-put-symbol (scope name symbol)
2389 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2390 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2391 (let* ((table (js2-scope-symbol-table scope))
2392 (sym (if (symbolp name) name (intern name)))
2393 (entry (assq sym table)))
2394 (if entry
2395 (setcdr entry symbol)
2396 (push (cons sym symbol)
2397 (js2-scope-symbol-table scope)))))
2398
2399 (cl-defstruct (js2-symbol
2400 (:constructor nil)
2401 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2402 "A symbol table entry."
2403 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2404 ;; js2-LET, or js2-CONST
2405 decl-type
2406 name ; string
2407 ast-node) ; a `js2-node'
2408
2409 (cl-defstruct (js2-error-node
2410 (:include js2-node)
2411 (:constructor nil) ; silence emacs21 byte-compiler
2412 (:constructor make-js2-error-node (&key (type js2-ERROR)
2413 (pos (js2-current-token-beg))
2414 len)))
2415 "AST node representing a parse error.")
2416
2417 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2418 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2419
2420 (cl-defstruct (js2-script-node
2421 (:include js2-scope)
2422 (:constructor nil)
2423 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2424 (pos (js2-current-token-beg))
2425 len
2426 ;; FIXME: What are those?
2427 var-decls
2428 fun-decls)))
2429 functions ; Lisp list of nested functions
2430 regexps ; Lisp list of (string . flags)
2431 symbols ; alist (every symbol gets unique index)
2432 (param-count 0)
2433 var-names ; vector of string names
2434 consts ; bool-vector matching var-decls
2435 (temp-number 0)) ; for generating temp variables
2436
2437 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2438 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2439
2440 (defun js2-print-script (node indent)
2441 (dolist (kid (js2-block-node-kids node))
2442 (js2-print-ast kid indent)))
2443
2444 (cl-defstruct (js2-ast-root
2445 (:include js2-script-node)
2446 (:constructor nil)
2447 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2448 (pos (js2-current-token-beg))
2449 len
2450 buffer)))
2451 "The root node of a js2 AST."
2452 buffer ; the source buffer from which the code was parsed
2453 comments ; a Lisp list of comments, ordered by start position
2454 errors ; a Lisp list of errors found during parsing
2455 warnings ; a Lisp list of warnings found during parsing
2456 node-count ; number of nodes in the tree, including the root
2457 in-strict-mode) ; t if the script is running under strict mode
2458
2459 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2460 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2461
2462 (defun js2-visit-ast-root (ast callback)
2463 (dolist (kid (js2-ast-root-kids ast))
2464 (js2-visit-ast kid callback))
2465 (dolist (comment (js2-ast-root-comments ast))
2466 (js2-visit-ast comment callback)))
2467
2468 (cl-defstruct (js2-comment-node
2469 (:include js2-node)
2470 (:constructor nil)
2471 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2472 (pos (js2-current-token-beg))
2473 len
2474 format)))
2475 format) ; 'line, 'block, 'jsdoc or 'html
2476
2477 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2478 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2479
2480 (defun js2-print-comment (n i)
2481 ;; We really ought to link end-of-line comments to their nodes.
2482 ;; Or maybe we could add a new comment type, 'endline.
2483 (insert (js2-make-pad i)
2484 (js2-node-string n)))
2485
2486 (cl-defstruct (js2-expr-stmt-node
2487 (:include js2-node)
2488 (:constructor nil)
2489 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2490 (pos js2-ts-cursor)
2491 len
2492 expr)))
2493 "An expression statement."
2494 expr)
2495
2496 (defsubst js2-expr-stmt-node-set-has-result (node)
2497 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2498 (setf (js2-node-type node) js2-EXPR_RESULT))
2499
2500 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2501 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2502
2503 (defun js2-visit-expr-stmt-node (n v)
2504 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2505
2506 (defun js2-print-expr-stmt-node (n indent)
2507 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2508 (insert ";\n"))
2509
2510 (cl-defstruct (js2-loop-node
2511 (:include js2-scope)
2512 (:constructor nil))
2513 "Abstract supertype of loop nodes."
2514 body ; a `js2-block-node'
2515 lp ; position of left-paren, nil if omitted
2516 rp) ; position of right-paren, nil if omitted
2517
2518 (cl-defstruct (js2-do-node
2519 (:include js2-loop-node)
2520 (:constructor nil)
2521 (:constructor make-js2-do-node (&key (type js2-DO)
2522 (pos (js2-current-token-beg))
2523 len
2524 body
2525 condition
2526 while-pos
2527 lp
2528 rp)))
2529 "AST node for do-loop."
2530 condition ; while (expression)
2531 while-pos) ; buffer position of 'while' keyword
2532
2533 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2534 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2535
2536 (defun js2-visit-do-node (n v)
2537 (js2-visit-ast (js2-do-node-body n) v)
2538 (js2-visit-ast (js2-do-node-condition n) v))
2539
2540 (defun js2-print-do-node (n i)
2541 (let ((pad (js2-make-pad i)))
2542 (insert pad "do {\n")
2543 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2544 (js2-print-ast kid (1+ i)))
2545 (insert pad "} while (")
2546 (js2-print-ast (js2-do-node-condition n) 0)
2547 (insert ");\n")))
2548
2549 (cl-defstruct (js2-export-node
2550 (:include js2-node)
2551 (:constructor nil)
2552 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2553 (pos (js2-current-token-beg))
2554 len
2555 exports-list
2556 from-clause
2557 declaration
2558 default)))
2559 "AST node for an export statement. There are many things that can be exported,
2560 so many of its properties will be nil.
2561 "
2562 exports-list ; lisp list of js2-export-binding-node to export
2563 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2564 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2565 default) ; js2-function-node or js2-assign-node
2566
2567 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2568 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2569
2570 (defun js2-visit-export-node (n v)
2571 (let ((exports-list (js2-export-node-exports-list n))
2572 (from (js2-export-node-from-clause n))
2573 (declaration (js2-export-node-declaration n))
2574 (default (js2-export-node-default n)))
2575 (when exports-list
2576 (dolist (export exports-list)
2577 (js2-visit-ast export v)))
2578 (when from
2579 (js2-visit-ast from v))
2580 (when declaration
2581 (js2-visit-ast declaration v))
2582 (when default
2583 (js2-visit-ast default v))))
2584
2585 (defun js2-print-export-node (n i)
2586 (let ((pad (js2-make-pad i))
2587 (exports-list (js2-export-node-exports-list n))
2588 (from (js2-export-node-from-clause n))
2589 (declaration (js2-export-node-declaration n))
2590 (default (js2-export-node-default n)))
2591 (insert pad "export ")
2592 (cond
2593 (default
2594 (insert "default ")
2595 (js2-print-ast default i))
2596 (declaration
2597 (js2-print-ast declaration i))
2598 ((and exports-list from)
2599 (js2-print-named-imports exports-list)
2600 (insert " ")
2601 (js2-print-from-clause from))
2602 (from
2603 (insert "* ")
2604 (js2-print-from-clause from))
2605 (exports-list
2606 (js2-print-named-imports exports-list)))
2607 (insert ";\n")))
2608
2609 (cl-defstruct (js2-while-node
2610 (:include js2-loop-node)
2611 (:constructor nil)
2612 (:constructor make-js2-while-node (&key (type js2-WHILE)
2613 (pos (js2-current-token-beg))
2614 len body
2615 condition lp
2616 rp)))
2617 "AST node for while-loop."
2618 condition) ; while-condition
2619
2620 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2621 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2622
2623 (defun js2-visit-while-node (n v)
2624 (js2-visit-ast (js2-while-node-condition n) v)
2625 (js2-visit-ast (js2-while-node-body n) v))
2626
2627 (defun js2-print-while-node (n i)
2628 (let ((pad (js2-make-pad i)))
2629 (insert pad "while (")
2630 (js2-print-ast (js2-while-node-condition n) 0)
2631 (insert ") {\n")
2632 (js2-print-body (js2-while-node-body n) (1+ i))
2633 (insert pad "}\n")))
2634
2635 (cl-defstruct (js2-for-node
2636 (:include js2-loop-node)
2637 (:constructor nil)
2638 (:constructor make-js2-for-node (&key (type js2-FOR)
2639 (pos js2-ts-cursor)
2640 len body init
2641 condition
2642 update lp rp)))
2643 "AST node for a C-style for-loop."
2644 init ; initialization expression
2645 condition ; loop condition
2646 update) ; update clause
2647
2648 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2649 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2650
2651 (defun js2-visit-for-node (n v)
2652 (js2-visit-ast (js2-for-node-init n) v)
2653 (js2-visit-ast (js2-for-node-condition n) v)
2654 (js2-visit-ast (js2-for-node-update n) v)
2655 (js2-visit-ast (js2-for-node-body n) v))
2656
2657 (defun js2-print-for-node (n i)
2658 (let ((pad (js2-make-pad i)))
2659 (insert pad "for (")
2660 (js2-print-ast (js2-for-node-init n) 0)
2661 (insert "; ")
2662 (js2-print-ast (js2-for-node-condition n) 0)
2663 (insert "; ")
2664 (js2-print-ast (js2-for-node-update n) 0)
2665 (insert ") {\n")
2666 (js2-print-body (js2-for-node-body n) (1+ i))
2667 (insert pad "}\n")))
2668
2669 (cl-defstruct (js2-for-in-node
2670 (:include js2-loop-node)
2671 (:constructor nil)
2672 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2673 (pos js2-ts-cursor)
2674 len body
2675 iterator
2676 object
2677 in-pos
2678 each-pos
2679 foreach-p forof-p
2680 lp rp)))
2681 "AST node for a for..in loop."
2682 iterator ; [var] foo in ...
2683 object ; object over which we're iterating
2684 in-pos ; buffer position of 'in' keyword
2685 each-pos ; buffer position of 'each' keyword, if foreach-p
2686 foreach-p ; t if it's a for-each loop
2687 forof-p) ; t if it's a for-of loop
2688
2689 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2690 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2691
2692 (defun js2-visit-for-in-node (n v)
2693 (js2-visit-ast (js2-for-in-node-iterator n) v)
2694 (js2-visit-ast (js2-for-in-node-object n) v)
2695 (js2-visit-ast (js2-for-in-node-body n) v))
2696
2697 (defun js2-print-for-in-node (n i)
2698 (let ((pad (js2-make-pad i))
2699 (foreach (js2-for-in-node-foreach-p n))
2700 (forof (js2-for-in-node-forof-p n)))
2701 (insert pad "for ")
2702 (if foreach
2703 (insert "each "))
2704 (insert "(")
2705 (js2-print-ast (js2-for-in-node-iterator n) 0)
2706 (insert (if forof " of " " in "))
2707 (js2-print-ast (js2-for-in-node-object n) 0)
2708 (insert ") {\n")
2709 (js2-print-body (js2-for-in-node-body n) (1+ i))
2710 (insert pad "}\n")))
2711
2712 (cl-defstruct (js2-return-node
2713 (:include js2-node)
2714 (:constructor nil)
2715 (:constructor make-js2-return-node (&key (type js2-RETURN)
2716 (pos js2-ts-cursor)
2717 len
2718 retval)))
2719 "AST node for a return statement."
2720 retval) ; expression to return, or 'undefined
2721
2722 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2723 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2724
2725 (defun js2-visit-return-node (n v)
2726 (js2-visit-ast (js2-return-node-retval n) v))
2727
2728 (defun js2-print-return-node (n i)
2729 (insert (js2-make-pad i) "return")
2730 (when (js2-return-node-retval n)
2731 (insert " ")
2732 (js2-print-ast (js2-return-node-retval n) 0))
2733 (insert ";\n"))
2734
2735 (cl-defstruct (js2-if-node
2736 (:include js2-node)
2737 (:constructor nil)
2738 (:constructor make-js2-if-node (&key (type js2-IF)
2739 (pos js2-ts-cursor)
2740 len condition
2741 then-part
2742 else-pos
2743 else-part lp
2744 rp)))
2745 "AST node for an if-statement."
2746 condition ; expression
2747 then-part ; statement or block
2748 else-pos ; optional buffer position of 'else' keyword
2749 else-part ; optional statement or block
2750 lp ; position of left-paren, nil if omitted
2751 rp) ; position of right-paren, nil if omitted
2752
2753 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2754 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2755
2756 (defun js2-visit-if-node (n v)
2757 (js2-visit-ast (js2-if-node-condition n) v)
2758 (js2-visit-ast (js2-if-node-then-part n) v)
2759 (js2-visit-ast (js2-if-node-else-part n) v))
2760
2761 (defun js2-print-if-node (n i)
2762 (let ((pad (js2-make-pad i))
2763 (then-part (js2-if-node-then-part n))
2764 (else-part (js2-if-node-else-part n)))
2765 (insert pad "if (")
2766 (js2-print-ast (js2-if-node-condition n) 0)
2767 (insert ") {\n")
2768 (js2-print-body then-part (1+ i))
2769 (insert pad "}")
2770 (cond
2771 ((not else-part)
2772 (insert "\n"))
2773 ((js2-if-node-p else-part)
2774 (insert " else ")
2775 (js2-print-body else-part i))
2776 (t
2777 (insert " else {\n")
2778 (js2-print-body else-part (1+ i))
2779 (insert pad "}\n")))))
2780
2781 (cl-defstruct (js2-export-binding-node
2782 (:include js2-node)
2783 (:constructor nil)
2784 (:constructor make-js2-export-binding-node (&key (type -1)
2785 pos
2786 len
2787 local-name
2788 extern-name)))
2789 "AST node for an external symbol binding.
2790 It contains a local-name node which is the name of the value in the
2791 current scope, and extern-name which is the name of the value in the
2792 imported or exported scope. By default these are the same, but if the
2793 name is aliased as in {foo as bar}, it would have an extern-name node
2794 containing 'foo' and a local-name node containing 'bar'."
2795 local-name ; js2-name-node with the variable name in this scope
2796 extern-name) ; js2-name-node with the value name in the exporting module
2797
2798 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2799 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2800
2801 (defun js2-visit-extern-binding (n v)
2802 "Visit an extern binding node. First visit the local-name, and, if
2803 different, visit the extern-name."
2804 (let ((local-name (js2-export-binding-node-local-name n))
2805 (extern-name (js2-export-binding-node-extern-name n)))
2806 (when local-name
2807 (js2-visit-ast local-name v))
2808 (when (not (equal local-name extern-name))
2809 (js2-visit-ast extern-name v))))
2810
2811 (defun js2-print-extern-binding (n _i)
2812 "Print a representation of a single extern binding. E.g. 'foo' or
2813 'foo as bar'."
2814 (let ((local-name (js2-export-binding-node-local-name n))
2815 (extern-name (js2-export-binding-node-extern-name n)))
2816 (insert (js2-name-node-name extern-name))
2817 (when (not (equal local-name extern-name))
2818 (insert " as ")
2819 (insert (js2-name-node-name local-name)))))
2820
2821
2822 (cl-defstruct (js2-import-node
2823 (:include js2-node)
2824 (:constructor nil)
2825 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2826 (pos (js2-current-token-beg))
2827 len
2828 import
2829 from
2830 module-id)))
2831 "AST node for an import statement. It follows the form
2832
2833 import ModuleSpecifier;
2834 import ImportClause FromClause;"
2835 import ; js2-import-clause-node specifying which names are to imported.
2836 from ; js2-from-clause-node indicating the module from which to import.
2837 module-id) ; module-id of the import. E.g. 'src/mylib'.
2838
2839 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2840 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2841
2842 (defun js2-visit-import (n v)
2843 (let ((import-clause (js2-import-node-import n))
2844 (from-clause (js2-import-node-from n)))
2845 (when import-clause
2846 (js2-visit-ast import-clause v))
2847 (when from-clause
2848 (js2-visit-ast from-clause v))))
2849
2850 (defun js2-print-import (n i)
2851 "Prints a representation of the import node"
2852 (let ((pad (js2-make-pad i))
2853 (import-clause (js2-import-node-import n))
2854 (from-clause (js2-import-node-from n))
2855 (module-id (js2-import-node-module-id n)))
2856 (insert pad "import ")
2857 (if import-clause
2858 (progn
2859 (js2-print-import-clause import-clause)
2860 (insert " ")
2861 (js2-print-from-clause from-clause))
2862 (insert "'")
2863 (insert module-id)
2864 (insert "'"))
2865 (insert ";\n")))
2866
2867 (cl-defstruct (js2-import-clause-node
2868 (:include js2-node)
2869 (:constructor nil)
2870 (:constructor make-js2-import-clause-node (&key (type -1)
2871 pos
2872 len
2873 namespace-import
2874 named-imports
2875 default-binding)))
2876 "AST node corresponding to the import clause of an import statement. This is
2877 the portion of the import that bindings names from the external context to the
2878 local context."
2879 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2880 named-imports ; lisp list of js2-export-binding-node for all named imports.
2881 default-binding) ; js2-export-binding-node for the default import binding
2882
2883 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2884 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2885
2886 (defun js2-visit-import-clause (n v)
2887 (let ((ns-import (js2-import-clause-node-namespace-import n))
2888 (named-imports (js2-import-clause-node-named-imports n))
2889 (default (js2-import-clause-node-default-binding n)))
2890 (when ns-import
2891 (js2-visit-ast ns-import v))
2892 (when named-imports
2893 (dolist (import named-imports)
2894 (js2-visit-ast import v)))
2895 (when default
2896 (js2-visit-ast default v))))
2897
2898 (defun js2-print-import-clause (n)
2899 (let ((ns-import (js2-import-clause-node-namespace-import n))
2900 (named-imports (js2-import-clause-node-named-imports n))
2901 (default (js2-import-clause-node-default-binding n)))
2902 (cond
2903 ((and default ns-import)
2904 (js2-print-ast default)
2905 (insert ", ")
2906 (js2-print-namespace-import ns-import))
2907 ((and default named-imports)
2908 (js2-print-ast default)
2909 (insert ", ")
2910 (js2-print-named-imports named-imports))
2911 (default
2912 (js2-print-ast default))
2913 (ns-import
2914 (js2-print-namespace-import ns-import))
2915 (named-imports
2916 (js2-print-named-imports named-imports)))))
2917
2918 (defun js2-print-namespace-import (node)
2919 (insert "* as ")
2920 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2921
2922 (defun js2-print-named-imports (imports)
2923 (insert "{")
2924 (let ((len (length imports))
2925 (n 0))
2926 (while (< n len)
2927 (js2-print-extern-binding (nth n imports) 0)
2928 (unless (= n (- len 1))
2929 (insert ", "))
2930 (setq n (+ n 1))))
2931 (insert "}"))
2932
2933 (cl-defstruct (js2-namespace-import-node
2934 (:include js2-node)
2935 (:constructor nil)
2936 (:constructor make-js2-namespace-import-node (&key (type -1)
2937 pos
2938 len
2939 name)))
2940 "AST node for a complete namespace import.
2941 E.g. the '* as lib' expression in:
2942
2943 import * as lib from 'src/lib'
2944
2945 It contains a single name node referring to the bound name."
2946 name) ; js2-name-node of the bound name.
2947
2948 (defun js2-visit-namespace-import (n v)
2949 (js2-visit-ast (js2-namespace-import-node-name n) v))
2950
2951 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2952 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2953
2954 (cl-defstruct (js2-from-clause-node
2955 (:include js2-node)
2956 (:constructor nil)
2957 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2958 pos
2959 len
2960 module-id
2961 metadata-p)))
2962 "AST node for the from clause in an import or export statement.
2963 E.g. from 'my/module'. It can refere to either an external module, or to the
2964 modules metadata itself."
2965 module-id ; string containing the module specifier.
2966 metadata-p) ; true if this clause refers to the module's metadata
2967
2968 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2969 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2970
2971 (defun js2-print-from-clause (n)
2972 (insert "from ")
2973 (if (js2-from-clause-node-metadata-p n)
2974 (insert "this module")
2975 (insert "'")
2976 (insert (js2-from-clause-node-module-id n))
2977 (insert "'")))
2978
2979 (cl-defstruct (js2-try-node
2980 (:include js2-node)
2981 (:constructor nil)
2982 (:constructor make-js2-try-node (&key (type js2-TRY)
2983 (pos js2-ts-cursor)
2984 len
2985 try-block
2986 catch-clauses
2987 finally-block)))
2988 "AST node for a try-statement."
2989 try-block
2990 catch-clauses ; a Lisp list of `js2-catch-node'
2991 finally-block) ; a `js2-finally-node'
2992
2993 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2994 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2995
2996 (defun js2-visit-try-node (n v)
2997 (js2-visit-ast (js2-try-node-try-block n) v)
2998 (dolist (clause (js2-try-node-catch-clauses n))
2999 (js2-visit-ast clause v))
3000 (js2-visit-ast (js2-try-node-finally-block n) v))
3001
3002 (defun js2-print-try-node (n i)
3003 (let ((pad (js2-make-pad i))
3004 (catches (js2-try-node-catch-clauses n))
3005 (finally (js2-try-node-finally-block n)))
3006 (insert pad "try {\n")
3007 (js2-print-body (js2-try-node-try-block n) (1+ i))
3008 (insert pad "}")
3009 (when catches
3010 (dolist (catch catches)
3011 (js2-print-ast catch i)))
3012 (if finally
3013 (js2-print-ast finally i)
3014 (insert "\n"))))
3015
3016 (cl-defstruct (js2-catch-node
3017 (:include js2-scope)
3018 (:constructor nil)
3019 (:constructor make-js2-catch-node (&key (type js2-CATCH)
3020 (pos js2-ts-cursor)
3021 len
3022 param
3023 guard-kwd
3024 guard-expr
3025 lp rp)))
3026 "AST node for a catch clause."
3027 param ; destructuring form or simple name node
3028 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
3029 guard-expr ; catch condition, a `js2-node'
3030 lp ; buffer position of left-paren, nil if omitted
3031 rp) ; buffer position of right-paren, nil if omitted
3032
3033 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
3034 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
3035
3036 (defun js2-visit-catch-node (n v)
3037 (js2-visit-ast (js2-catch-node-param n) v)
3038 (when (js2-catch-node-guard-kwd n)
3039 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3040 (js2-visit-block n v))
3041
3042 (defun js2-print-catch-node (n i)
3043 (let ((pad (js2-make-pad i))
3044 (guard-kwd (js2-catch-node-guard-kwd n))
3045 (guard-expr (js2-catch-node-guard-expr n)))
3046 (insert " catch (")
3047 (js2-print-ast (js2-catch-node-param n) 0)
3048 (when guard-kwd
3049 (insert " if ")
3050 (js2-print-ast guard-expr 0))
3051 (insert ") {\n")
3052 (js2-print-body n (1+ i))
3053 (insert pad "}")))
3054
3055 (cl-defstruct (js2-finally-node
3056 (:include js2-node)
3057 (:constructor nil)
3058 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3059 (pos js2-ts-cursor)
3060 len body)))
3061 "AST node for a finally clause."
3062 body) ; a `js2-node', often but not always a block node
3063
3064 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3065 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3066
3067 (defun js2-visit-finally-node (n v)
3068 (js2-visit-ast (js2-finally-node-body n) v))
3069
3070 (defun js2-print-finally-node (n i)
3071 (let ((pad (js2-make-pad i)))
3072 (insert " finally {\n")
3073 (js2-print-body (js2-finally-node-body n) (1+ i))
3074 (insert pad "}\n")))
3075
3076 (cl-defstruct (js2-switch-node
3077 (:include js2-node)
3078 (:constructor nil)
3079 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3080 (pos js2-ts-cursor)
3081 len
3082 discriminant
3083 cases lp
3084 rp)))
3085 "AST node for a switch statement."
3086 discriminant ; a `js2-node' (switch expression)
3087 cases ; a Lisp list of `js2-case-node'
3088 lp ; position of open-paren for discriminant, nil if omitted
3089 rp) ; position of close-paren for discriminant, nil if omitted
3090
3091 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3092 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3093
3094 (defun js2-visit-switch-node (n v)
3095 (js2-visit-ast (js2-switch-node-discriminant n) v)
3096 (dolist (c (js2-switch-node-cases n))
3097 (js2-visit-ast c v)))
3098
3099 (defun js2-print-switch-node (n i)
3100 (let ((pad (js2-make-pad i))
3101 (cases (js2-switch-node-cases n)))
3102 (insert pad "switch (")
3103 (js2-print-ast (js2-switch-node-discriminant n) 0)
3104 (insert ") {\n")
3105 (dolist (case cases)
3106 (js2-print-ast case i))
3107 (insert pad "}\n")))
3108
3109 (cl-defstruct (js2-case-node
3110 (:include js2-block-node)
3111 (:constructor nil)
3112 (:constructor make-js2-case-node (&key (type js2-CASE)
3113 (pos js2-ts-cursor)
3114 len kids expr)))
3115 "AST node for a case clause of a switch statement."
3116 expr) ; the case expression (nil for default)
3117
3118 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3119 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3120
3121 (defun js2-visit-case-node (n v)
3122 (js2-visit-ast (js2-case-node-expr n) v)
3123 (js2-visit-block n v))
3124
3125 (defun js2-print-case-node (n i)
3126 (let ((pad (js2-make-pad i))
3127 (expr (js2-case-node-expr n)))
3128 (insert pad)
3129 (if (null expr)
3130 (insert "default:\n")
3131 (insert "case ")
3132 (js2-print-ast expr 0)
3133 (insert ":\n"))
3134 (dolist (kid (js2-case-node-kids n))
3135 (js2-print-ast kid (1+ i)))))
3136
3137 (cl-defstruct (js2-throw-node
3138 (:include js2-node)
3139 (:constructor nil)
3140 (:constructor make-js2-throw-node (&key (type js2-THROW)
3141 (pos js2-ts-cursor)
3142 len expr)))
3143 "AST node for a throw statement."
3144 expr) ; the expression to throw
3145
3146 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3147 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3148
3149 (defun js2-visit-throw-node (n v)
3150 (js2-visit-ast (js2-throw-node-expr n) v))
3151
3152 (defun js2-print-throw-node (n i)
3153 (insert (js2-make-pad i) "throw ")
3154 (js2-print-ast (js2-throw-node-expr n) 0)
3155 (insert ";\n"))
3156
3157 (cl-defstruct (js2-with-node
3158 (:include js2-node)
3159 (:constructor nil)
3160 (:constructor make-js2-with-node (&key (type js2-WITH)
3161 (pos js2-ts-cursor)
3162 len object
3163 body lp rp)))
3164 "AST node for a with-statement."
3165 object
3166 body
3167 lp ; buffer position of left-paren around object, nil if omitted
3168 rp) ; buffer position of right-paren around object, nil if omitted
3169
3170 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3171 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3172
3173 (defun js2-visit-with-node (n v)
3174 (js2-visit-ast (js2-with-node-object n) v)
3175 (js2-visit-ast (js2-with-node-body n) v))
3176
3177 (defun js2-print-with-node (n i)
3178 (let ((pad (js2-make-pad i)))
3179 (insert pad "with (")
3180 (js2-print-ast (js2-with-node-object n) 0)
3181 (insert ") {\n")
3182 (js2-print-body (js2-with-node-body n) (1+ i))
3183 (insert pad "}\n")))
3184
3185 (cl-defstruct (js2-label-node
3186 (:include js2-node)
3187 (:constructor nil)
3188 (:constructor make-js2-label-node (&key (type js2-LABEL)
3189 (pos js2-ts-cursor)
3190 len name)))
3191 "AST node for a statement label or case label."
3192 name ; a string
3193 loop) ; for validating and code-generating continue-to-label
3194
3195 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3196 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3197
3198 (defun js2-print-label (n i)
3199 (insert (js2-make-pad i)
3200 (js2-label-node-name n)
3201 ":\n"))
3202
3203 (cl-defstruct (js2-labeled-stmt-node
3204 (:include js2-node)
3205 (:constructor nil)
3206 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3207 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3208 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3209 (pos js2-ts-cursor)
3210 len labels stmt)))
3211 "AST node for a statement with one or more labels.
3212 Multiple labels for a statement are collapsed into the labels field."
3213 labels ; Lisp list of `js2-label-node'
3214 stmt) ; the statement these labels are for
3215
3216 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3217 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3218
3219 (defun js2-get-label-by-name (lbl-stmt name)
3220 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3221 Returns nil if no such label is in the list."
3222 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3223 result)
3224 (while (and label-list (not result))
3225 (if (string= (js2-label-node-name (car label-list)) name)
3226 (setq result (car label-list))
3227 (setq label-list (cdr label-list))))
3228 result))
3229
3230 (defun js2-visit-labeled-stmt (n v)
3231 (dolist (label (js2-labeled-stmt-node-labels n))
3232 (js2-visit-ast label v))
3233 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3234
3235 (defun js2-print-labeled-stmt (n i)
3236 (dolist (label (js2-labeled-stmt-node-labels n))
3237 (js2-print-ast label i))
3238 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3239
3240 (defun js2-labeled-stmt-node-contains (node label)
3241 "Return t if NODE contains LABEL in its label set.
3242 NODE is a `js2-labels-node'. LABEL is an identifier."
3243 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3244 if (string= label (js2-label-node-name nl))
3245 return t
3246 finally return nil))
3247
3248 (defsubst js2-labeled-stmt-node-add-label (node label)
3249 "Add a `js2-label-node' to the label set for this statement."
3250 (setf (js2-labeled-stmt-node-labels node)
3251 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3252
3253 (cl-defstruct (js2-jump-node
3254 (:include js2-node)
3255 (:constructor nil))
3256 "Abstract supertype of break and continue nodes."
3257 label ; `js2-name-node' for location of label identifier, if present
3258 target) ; target js2-labels-node or loop/switch statement
3259
3260 (defun js2-visit-jump-node (n v)
3261 ;; We don't visit the target, since it's a back-link.
3262 (js2-visit-ast (js2-jump-node-label n) v))
3263
3264 (cl-defstruct (js2-break-node
3265 (:include js2-jump-node)
3266 (:constructor nil)
3267 (:constructor make-js2-break-node (&key (type js2-BREAK)
3268 (pos js2-ts-cursor)
3269 len label target)))
3270 "AST node for a break statement.
3271 The label field is a `js2-name-node', possibly nil, for the named label
3272 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3273 is the target of the break - a label node or enclosing loop/switch statement.")
3274
3275 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3276 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3277
3278 (defun js2-print-break-node (n i)
3279 (insert (js2-make-pad i) "break")
3280 (when (js2-break-node-label n)
3281 (insert " ")
3282 (js2-print-ast (js2-break-node-label n) 0))
3283 (insert ";\n"))
3284
3285 (cl-defstruct (js2-continue-node
3286 (:include js2-jump-node)
3287 (:constructor nil)
3288 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3289 (pos js2-ts-cursor)
3290 len label target)))
3291 "AST node for a continue statement.
3292 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3293 It is nil if continue specifies no label. The target field is the jump target:
3294 a `js2-label-node' or the innermost enclosing loop.")
3295
3296 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3297 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3298
3299 (defun js2-print-continue-node (n i)
3300 (insert (js2-make-pad i) "continue")
3301 (when (js2-continue-node-label n)
3302 (insert " ")
3303 (js2-print-ast (js2-continue-node-label n) 0))
3304 (insert ";\n"))
3305
3306 (cl-defstruct (js2-function-node
3307 (:include js2-script-node)
3308 (:constructor nil)
3309 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3310 (pos js2-ts-cursor)
3311 len
3312 (ftype 'FUNCTION)
3313 (form 'FUNCTION_STATEMENT)
3314 (name "")
3315 params rest-p
3316 body
3317 generator-type
3318 lp rp)))
3319 "AST node for a function declaration.
3320 The `params' field is a Lisp list of nodes. Each node is either a simple
3321 `js2-name-node', or if it's a destructuring-assignment parameter, a
3322 `js2-array-node' or `js2-object-node'."
3323 ftype ; FUNCTION, GETTER or SETTER
3324 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3325 name ; function name (a `js2-name-node', or nil if anonymous)
3326 params ; a Lisp list of destructuring forms or simple name nodes
3327 rest-p ; if t, the last parameter is rest parameter
3328 body ; a `js2-block-node' or expression node (1.8 only)
3329 lp ; position of arg-list open-paren, or nil if omitted
3330 rp ; position of arg-list close-paren, or nil if omitted
3331 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3332 needs-activation ; t if we need an activation object for this frame
3333 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3334 member-expr ; nonstandard Ecma extension from Rhino
3335 in-strict-mode) ; t if the function is running under strict mode
3336
3337 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3338 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3339
3340 (defun js2-visit-function-node (n v)
3341 (js2-visit-ast (js2-function-node-name n) v)
3342 (dolist (p (js2-function-node-params n))
3343 (js2-visit-ast p v))
3344 (js2-visit-ast (js2-function-node-body n) v))
3345
3346 (defun js2-print-function-node (n i)
3347 (let* ((pad (js2-make-pad i))
3348 (getter (js2-node-get-prop n 'GETTER_SETTER))
3349 (name (or (js2-function-node-name n)
3350 (js2-function-node-member-expr n)))
3351 (params (js2-function-node-params n))
3352 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3353 (rest-p (js2-function-node-rest-p n))
3354 (body (js2-function-node-body n))
3355 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3356 (unless (or getter arrow)
3357 (insert pad "function")
3358 (when (eq (js2-function-node-generator-type n) 'STAR)
3359 (insert "*")))
3360 (when name
3361 (insert " ")
3362 (js2-print-ast name 0))
3363 (insert "(")
3364 (cl-loop with len = (length params)
3365 for param in params
3366 for count from 1
3367 do
3368 (when (and rest-p (= count len))
3369 (insert "..."))
3370 (js2-print-ast param 0)
3371 (when (< count len)
3372 (insert ", ")))
3373 (insert ") ")
3374 (when arrow
3375 (insert "=> "))
3376 (insert "{")
3377 ;; TODO: fix this to be smarter about indenting, etc.
3378 (unless expr
3379 (insert "\n"))
3380 (if (js2-block-node-p body)
3381 (js2-print-body body (1+ i))
3382 (js2-print-ast body 0))
3383 (insert pad "}")
3384 (unless expr
3385 (insert "\n"))))
3386
3387 (defun js2-function-name (node)
3388 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3389 (and (js2-function-node-name node)
3390 (js2-name-node-name (js2-function-node-name node))))
3391
3392 ;; Having this be an expression node makes it more flexible.
3393 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3394 ;; that work better if you assume it's an expression. Whenever we have
3395 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3396 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3397 (cl-defstruct (js2-var-decl-node
3398 (:include js2-node)
3399 (:constructor nil)
3400 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3401 (pos (js2-current-token-beg))
3402 len kids
3403 decl-type)))
3404 "AST node for a variable declaration list (VAR, CONST or LET).
3405 The node bounds differ depending on the declaration type. For VAR or
3406 CONST declarations, the bounds include the var/const keyword. For LET
3407 declarations, the node begins at the position of the first child."
3408 kids ; a Lisp list of `js2-var-init-node' structs.
3409 decl-type) ; js2-VAR, js2-CONST or js2-LET
3410
3411 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3412 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3413
3414 (defun js2-visit-var-decl (n v)
3415 (dolist (kid (js2-var-decl-node-kids n))
3416 (js2-visit-ast kid v)))
3417
3418 (defun js2-print-var-decl (n i)
3419 (let ((pad (js2-make-pad i))
3420 (tt (js2-var-decl-node-decl-type n)))
3421 (insert pad)
3422 (insert (cond
3423 ((= tt js2-VAR) "var ")
3424 ((= tt js2-LET) "let ")
3425 ((= tt js2-CONST) "const ")
3426 (t
3427 (error "malformed var-decl node"))))
3428 (cl-loop with kids = (js2-var-decl-node-kids n)
3429 with len = (length kids)
3430 for kid in kids
3431 for count from 1
3432 do
3433 (js2-print-ast kid 0)
3434 (if (< count len)
3435 (insert ", ")))))
3436
3437 (cl-defstruct (js2-var-init-node
3438 (:include js2-node)
3439 (:constructor nil)
3440 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3441 (pos js2-ts-cursor)
3442 len target
3443 initializer)))
3444 "AST node for a variable declaration.
3445 The type field will be js2-CONST for a const decl."
3446 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3447 initializer) ; initializer expression, a `js2-node'
3448
3449 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3450 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3451
3452 (defun js2-visit-var-init-node (n v)
3453 (js2-visit-ast (js2-var-init-node-target n) v)
3454 (js2-visit-ast (js2-var-init-node-initializer n) v))
3455
3456 (defun js2-print-var-init-node (n i)
3457 (let ((pad (js2-make-pad i))
3458 (name (js2-var-init-node-target n))
3459 (init (js2-var-init-node-initializer n)))
3460 (insert pad)
3461 (js2-print-ast name 0)
3462 (when init
3463 (insert " = ")
3464 (js2-print-ast init 0))))
3465
3466 (cl-defstruct (js2-cond-node
3467 (:include js2-node)
3468 (:constructor nil)
3469 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3470 (pos js2-ts-cursor)
3471 len
3472 test-expr
3473 true-expr
3474 false-expr
3475 q-pos c-pos)))
3476 "AST node for the ternary operator"
3477 test-expr
3478 true-expr
3479 false-expr
3480 q-pos ; buffer position of ?
3481 c-pos) ; buffer position of :
3482
3483 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3484 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3485
3486 (defun js2-visit-cond-node (n v)
3487 (js2-visit-ast (js2-cond-node-test-expr n) v)
3488 (js2-visit-ast (js2-cond-node-true-expr n) v)
3489 (js2-visit-ast (js2-cond-node-false-expr n) v))
3490
3491 (defun js2-print-cond-node (n i)
3492 (let ((pad (js2-make-pad i)))
3493 (insert pad)
3494 (js2-print-ast (js2-cond-node-test-expr n) 0)
3495 (insert " ? ")
3496 (js2-print-ast (js2-cond-node-true-expr n) 0)
3497 (insert " : ")
3498 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3499
3500 (cl-defstruct (js2-infix-node
3501 (:include js2-node)
3502 (:constructor nil)
3503 (:constructor make-js2-infix-node (&key type
3504 (pos js2-ts-cursor)
3505 len op-pos
3506 left right)))
3507 "Represents infix expressions.
3508 Includes assignment ops like `|=', and the comma operator.
3509 The type field inherited from `js2-node' holds the operator."
3510 op-pos ; buffer position where operator begins
3511 left ; any `js2-node'
3512 right) ; any `js2-node'
3513
3514 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3515 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3516
3517 (defun js2-visit-infix-node (n v)
3518 (js2-visit-ast (js2-infix-node-left n) v)
3519 (js2-visit-ast (js2-infix-node-right n) v))
3520
3521 (defconst js2-operator-tokens
3522 (let ((table (make-hash-table :test 'eq))
3523 (tokens
3524 (list (cons js2-IN "in")
3525 (cons js2-TYPEOF "typeof")
3526 (cons js2-INSTANCEOF "instanceof")
3527 (cons js2-DELPROP "delete")
3528 (cons js2-COMMA ",")
3529 (cons js2-COLON ":")
3530 (cons js2-OR "||")
3531 (cons js2-AND "&&")
3532 (cons js2-INC "++")
3533 (cons js2-DEC "--")
3534 (cons js2-BITOR "|")
3535 (cons js2-BITXOR "^")
3536 (cons js2-BITAND "&")
3537 (cons js2-EQ "==")
3538 (cons js2-NE "!=")
3539 (cons js2-LT "<")
3540 (cons js2-LE "<=")
3541 (cons js2-GT ">")
3542 (cons js2-GE ">=")
3543 (cons js2-LSH "<<")
3544 (cons js2-RSH ">>")
3545 (cons js2-URSH ">>>")
3546 (cons js2-ADD "+") ; infix plus
3547 (cons js2-SUB "-") ; infix minus
3548 (cons js2-MUL "*")
3549 (cons js2-DIV "/")
3550 (cons js2-MOD "%")
3551 (cons js2-NOT "!")
3552 (cons js2-BITNOT "~")
3553 (cons js2-POS "+") ; unary plus
3554 (cons js2-NEG "-") ; unary minus
3555 (cons js2-TRIPLEDOT "...")
3556 (cons js2-SHEQ "===") ; shallow equality
3557 (cons js2-SHNE "!==") ; shallow inequality
3558 (cons js2-ASSIGN "=")
3559 (cons js2-ASSIGN_BITOR "|=")
3560 (cons js2-ASSIGN_BITXOR "^=")
3561 (cons js2-ASSIGN_BITAND "&=")
3562 (cons js2-ASSIGN_LSH "<<=")
3563 (cons js2-ASSIGN_RSH ">>=")
3564 (cons js2-ASSIGN_URSH ">>>=")
3565 (cons js2-ASSIGN_ADD "+=")
3566 (cons js2-ASSIGN_SUB "-=")
3567 (cons js2-ASSIGN_MUL "*=")
3568 (cons js2-ASSIGN_DIV "/=")
3569 (cons js2-ASSIGN_MOD "%="))))
3570 (cl-loop for (k . v) in tokens do
3571 (puthash k v table))
3572 table))
3573
3574 (defun js2-print-infix-node (n i)
3575 (let* ((tt (js2-node-type n))
3576 (op (gethash tt js2-operator-tokens)))
3577 (unless op
3578 (error "unrecognized infix operator %s" (js2-node-type n)))
3579 (insert (js2-make-pad i))
3580 (js2-print-ast (js2-infix-node-left n) 0)
3581 (unless (= tt js2-COMMA)
3582 (insert " "))
3583 (insert op)
3584 (insert " ")
3585 (js2-print-ast (js2-infix-node-right n) 0)))
3586
3587 (cl-defstruct (js2-assign-node
3588 (:include js2-infix-node)
3589 (:constructor nil)
3590 (:constructor make-js2-assign-node (&key type
3591 (pos js2-ts-cursor)
3592 len op-pos
3593 left right)))
3594 "Represents any assignment.
3595 The type field holds the actual assignment operator.")
3596
3597 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3598 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3599
3600 (cl-defstruct (js2-unary-node
3601 (:include js2-node)
3602 (:constructor nil)
3603 (:constructor make-js2-unary-node (&key type ; required
3604 (pos js2-ts-cursor)
3605 len operand)))
3606 "AST node type for unary operator nodes.
3607 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3608 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3609 property is added if the operator follows the operand."
3610 operand) ; a `js2-node' expression
3611
3612 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3613 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3614
3615 (defun js2-visit-unary-node (n v)
3616 (js2-visit-ast (js2-unary-node-operand n) v))
3617
3618 (defun js2-print-unary-node (n i)
3619 (let* ((tt (js2-node-type n))
3620 (op (gethash tt js2-operator-tokens))
3621 (postfix (js2-node-get-prop n 'postfix)))
3622 (unless op
3623 (error "unrecognized unary operator %s" tt))
3624 (insert (js2-make-pad i))
3625 (unless postfix
3626 (insert op))
3627 (if (or (= tt js2-TYPEOF)
3628 (= tt js2-DELPROP))
3629 (insert " "))
3630 (js2-print-ast (js2-unary-node-operand n) 0)
3631 (when postfix
3632 (insert op))))
3633
3634 (cl-defstruct (js2-let-node
3635 (:include js2-scope)
3636 (:constructor nil)
3637 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3638 (pos (js2-current-token-beg))
3639 len vars body
3640 lp rp)))
3641 "AST node for a let expression or a let statement.
3642 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3643 vars ; a `js2-var-decl-node'
3644 body ; a `js2-node' representing the expression or body block
3645 lp
3646 rp)
3647
3648 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3649 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3650
3651 (defun js2-visit-let-node (n v)
3652 (js2-visit-ast (js2-let-node-vars n) v)
3653 (js2-visit-ast (js2-let-node-body n) v))
3654
3655 (defun js2-print-let-node (n i)
3656 (insert (js2-make-pad i) "let (")
3657 (let ((p (point)))
3658 (js2-print-ast (js2-let-node-vars n) 0)
3659 (delete-region p (+ p 4)))
3660 (insert ") ")
3661 (js2-print-ast (js2-let-node-body n) i))
3662
3663 (cl-defstruct (js2-keyword-node
3664 (:include js2-node)
3665 (:constructor nil)
3666 (:constructor make-js2-keyword-node (&key type
3667 (pos (js2-current-token-beg))
3668 (len (- js2-ts-cursor pos)))))
3669 "AST node representing a literal keyword such as `null'.
3670 Used for `null', `this', `true', `false' and `debugger'.
3671 The node type is set to js2-NULL, js2-THIS, etc.")
3672
3673 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3674 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3675
3676 (defun js2-print-keyword-node (n i)
3677 (insert (js2-make-pad i)
3678 (let ((tt (js2-node-type n)))
3679 (cond
3680 ((= tt js2-THIS) "this")
3681 ((= tt js2-SUPER) "super")
3682 ((= tt js2-NULL) "null")
3683 ((= tt js2-TRUE) "true")
3684 ((= tt js2-FALSE) "false")
3685 ((= tt js2-DEBUGGER) "debugger")
3686 (t (error "Invalid keyword literal type: %d" tt))))))
3687
3688 (defsubst js2-this-or-super-node-p (node)
3689 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3690 (let ((type (js2-node-type node)))
3691 (or (eq type js2-THIS) (eq type js2-SUPER))))
3692
3693 (cl-defstruct (js2-new-node
3694 (:include js2-node)
3695 (:constructor nil)
3696 (:constructor make-js2-new-node (&key (type js2-NEW)
3697 (pos (js2-current-token-beg))
3698 len target
3699 args initializer
3700 lp rp)))
3701 "AST node for new-expression such as new Foo()."
3702 target ; an identifier or reference
3703 args ; a Lisp list of argument nodes
3704 lp ; position of left-paren, nil if omitted
3705 rp ; position of right-paren, nil if omitted
3706 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3707
3708 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3709 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3710
3711 (defun js2-visit-new-node (n v)
3712 (js2-visit-ast (js2-new-node-target n) v)
3713 (dolist (arg (js2-new-node-args n))
3714 (js2-visit-ast arg v))
3715 (js2-visit-ast (js2-new-node-initializer n) v))
3716
3717 (defun js2-print-new-node (n i)
3718 (insert (js2-make-pad i) "new ")
3719 (js2-print-ast (js2-new-node-target n))
3720 (insert "(")
3721 (js2-print-list (js2-new-node-args n))
3722 (insert ")")
3723 (when (js2-new-node-initializer n)
3724 (insert " ")
3725 (js2-print-ast (js2-new-node-initializer n))))
3726
3727 (cl-defstruct (js2-name-node
3728 (:include js2-node)
3729 (:constructor nil)
3730 (:constructor make-js2-name-node (&key (type js2-NAME)
3731 (pos (js2-current-token-beg))
3732 (len (- js2-ts-cursor
3733 (js2-current-token-beg)))
3734 (name (js2-current-token-string)))))
3735 "AST node for a JavaScript identifier"
3736 name ; a string
3737 scope) ; a `js2-scope' (optional, used for codegen)
3738
3739 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3740 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3741
3742 (defun js2-print-name-node (n i)
3743 (insert (js2-make-pad i)
3744 (js2-name-node-name n)))
3745
3746 (defsubst js2-name-node-length (node)
3747 "Return identifier length of NODE, a `js2-name-node'.
3748 Returns 0 if NODE is nil or its identifier field is nil."
3749 (if node
3750 (length (js2-name-node-name node))
3751 0))
3752
3753 (cl-defstruct (js2-number-node
3754 (:include js2-node)
3755 (:constructor nil)
3756 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3757 (pos (js2-current-token-beg))
3758 (len (- js2-ts-cursor
3759 (js2-current-token-beg)))
3760 (value (js2-current-token-string))
3761 (num-value (js2-token-number
3762 (js2-current-token))))))
3763 "AST node for a number literal."
3764 value ; the original string, e.g. "6.02e23"
3765 num-value) ; the parsed number value
3766
3767 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3768 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3769
3770 (defun js2-print-number-node (n i)
3771 (insert (js2-make-pad i)
3772 (number-to-string (js2-number-node-num-value n))))
3773
3774 (cl-defstruct (js2-regexp-node
3775 (:include js2-node)
3776 (:constructor nil)
3777 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3778 (pos (js2-current-token-beg))
3779 (len (- js2-ts-cursor
3780 (js2-current-token-beg)))
3781 value flags)))
3782 "AST node for a regular expression literal."
3783 value ; the regexp string, without // delimiters
3784 flags) ; a string of flags, e.g. `mi'.
3785
3786 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3787 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3788
3789 (defun js2-print-regexp (n i)
3790 (insert (js2-make-pad i)
3791 "/"
3792 (js2-regexp-node-value n)
3793 "/")
3794 (if (js2-regexp-node-flags n)
3795 (insert (js2-regexp-node-flags n))))
3796
3797 (cl-defstruct (js2-string-node
3798 (:include js2-node)
3799 (:constructor nil)
3800 (:constructor make-js2-string-node (&key (type js2-STRING)
3801 (pos (js2-current-token-beg))
3802 (len (- js2-ts-cursor
3803 (js2-current-token-beg)))
3804 (value (js2-current-token-string)))))
3805 "String literal.
3806 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3807 You can tell the quote type by looking at the first character."
3808 value) ; the characters of the string, including the quotes
3809
3810 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3811 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3812
3813 (defun js2-print-string-node (n i)
3814 (insert (js2-make-pad i)
3815 (js2-node-string n)))
3816
3817 (cl-defstruct (js2-template-node
3818 (:include js2-node)
3819 (:constructor nil)
3820 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3821 beg len kids)))
3822 "Template literal."
3823 kids) ; `js2-string-node' is used for string segments, other nodes
3824 ; for substitutions inside.
3825
3826 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3827 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3828
3829 (defun js2-visit-template (n callback)
3830 (dolist (kid (js2-template-node-kids n))
3831 (js2-visit-ast kid callback)))
3832
3833 (defun js2-print-template (n i)
3834 (insert (js2-make-pad i))
3835 (dolist (kid (js2-template-node-kids n))
3836 (if (js2-string-node-p kid)
3837 (insert (js2-node-string kid))
3838 (js2-print-ast kid))))
3839
3840 (cl-defstruct (js2-tagged-template-node
3841 (:include js2-node)
3842 (:constructor nil)
3843 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3844 beg len tag template)))
3845 "Tagged template literal."
3846 tag ; `js2-node' with the tag expression.
3847 template) ; `js2-template-node' with the template.
3848
3849 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3850 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3851
3852 (defun js2-visit-tagged-template (n callback)
3853 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3854 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3855
3856 (defun js2-print-tagged-template (n i)
3857 (insert (js2-make-pad i))
3858 (js2-print-ast (js2-tagged-template-node-tag n))
3859 (js2-print-ast (js2-tagged-template-node-template n)))
3860
3861 (cl-defstruct (js2-array-node
3862 (:include js2-node)
3863 (:constructor nil)
3864 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3865 (pos js2-ts-cursor)
3866 len elems)))
3867 "AST node for an array literal."
3868 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3869
3870 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3871 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3872
3873 (defun js2-visit-array-node (n v)
3874 (dolist (e (js2-array-node-elems n))
3875 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3876
3877 (defun js2-print-array-node (n i)
3878 (insert (js2-make-pad i) "[")
3879 (let ((elems (js2-array-node-elems n)))
3880 (js2-print-list elems)
3881 (when (and elems (null (car (last elems))))
3882 (insert ",")))
3883 (insert "]"))
3884
3885 (cl-defstruct (js2-class-node
3886 (:include js2-node)
3887 (:constructor nil)
3888 (:constructor make-js2-class-node (&key (type js2-CLASS)
3889 (pos js2-ts-cursor)
3890 (form 'CLASS_STATEMENT)
3891 (name "")
3892 extends len elems)))
3893 "AST node for an class expression.
3894 `elems' is a list of `js2-object-prop-node', and `extends' is an
3895 optional `js2-expr-node'"
3896 form ; CLASS_{STATEMENT|EXPRESSION}
3897 name ; class name (a `js2-node-name', or nil if anonymous)
3898 extends ; class heritage (a `js2-expr-node', or nil if none)
3899 elems)
3900
3901 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3902 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3903
3904 (defun js2-visit-class-node (n v)
3905 (js2-visit-ast (js2-class-node-name n) v)
3906 (js2-visit-ast (js2-class-node-extends n) v)
3907 (dolist (e (js2-class-node-elems n))
3908 (js2-visit-ast e v)))
3909
3910 (defun js2-print-class-node (n i)
3911 (let* ((pad (js2-make-pad i))
3912 (name (js2-class-node-name n))
3913 (extends (js2-class-node-extends n))
3914 (elems (js2-class-node-elems n)))
3915 (insert pad "class")
3916 (when name
3917 (insert " ")
3918 (js2-print-ast name 0))
3919 (when extends
3920 (insert " extends ")
3921 (js2-print-ast extends))
3922 (insert " {")
3923 (dolist (elem elems)
3924 (insert "\n")
3925 (if (js2-node-get-prop elem 'STATIC)
3926 (progn (insert (js2-make-pad (1+ i)) "static ")
3927 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3928 (js2-print-ast elem (1+ i))))
3929 (insert "\n" pad "}")))
3930
3931 (cl-defstruct (js2-object-node
3932 (:include js2-node)
3933 (:constructor nil)
3934 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3935 (pos js2-ts-cursor)
3936 len
3937 elems)))
3938 "AST node for an object literal expression.
3939 `elems' is a list of `js2-object-prop-node'."
3940 elems)
3941
3942 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3943 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3944
3945 (defun js2-visit-object-node (n v)
3946 (dolist (e (js2-object-node-elems n))
3947 (js2-visit-ast e v)))
3948
3949 (defun js2-print-object-node (n i)
3950 (insert (js2-make-pad i) "{")
3951 (js2-print-list (js2-object-node-elems n))
3952 (insert "}"))
3953
3954 (cl-defstruct (js2-object-prop-node
3955 (:include js2-infix-node)
3956 (:constructor nil)
3957 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3958 (pos js2-ts-cursor)
3959 len left
3960 right op-pos)))
3961 "AST node for an object literal prop:value entry.
3962 The `left' field is the property: a name node, string node or number node.
3963 The `right' field is a `js2-node' representing the initializer value.
3964 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3965 and both fields have the same value.")
3966
3967 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3968 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3969
3970 (defun js2-print-object-prop-node (n i)
3971 (let* ((left (js2-object-prop-node-left n))
3972 (right (js2-object-prop-node-right n))
3973 (computed (not (or (js2-string-node-p left)
3974 (js2-number-node-p left)
3975 (js2-name-node-p left)))))
3976 (insert (js2-make-pad i))
3977 (if computed
3978 (insert "["))
3979 (js2-print-ast left 0)
3980 (if computed
3981 (insert "]"))
3982 (if (not (js2-node-get-prop n 'SHORTHAND))
3983 (progn
3984 (insert ": ")
3985 (js2-print-ast right 0)))))
3986
3987 (cl-defstruct (js2-getter-setter-node
3988 (:include js2-infix-node)
3989 (:constructor nil)
3990 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3991 (pos js2-ts-cursor)
3992 len left right)))
3993 "AST node for a getter/setter property in an object literal.
3994 The `left' field is the `js2-name-node' naming the getter/setter prop.
3995 The `right' field is always an anonymous `js2-function-node' with a node
3996 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3997
3998 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3999 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
4000
4001 (defun js2-print-getter-setter (n i)
4002 (let* ((pad (js2-make-pad i))
4003 (left (js2-getter-setter-node-left n))
4004 (right (js2-getter-setter-node-right n))
4005 (computed (not (or (js2-string-node-p left)
4006 (js2-number-node-p left)
4007 (js2-name-node-p left)))))
4008 (insert pad)
4009 (if (/= (js2-node-type n) js2-FUNCTION)
4010 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
4011 (when (and (js2-function-node-p right)
4012 (eq 'STAR (js2-function-node-generator-type right)))
4013 (insert "*"))
4014 (when computed
4015 (insert "["))
4016 (js2-print-ast left 0)
4017 (when computed
4018 (insert "]"))
4019 (js2-print-ast right 0)))
4020
4021 (cl-defstruct (js2-prop-get-node
4022 (:include js2-infix-node)
4023 (:constructor nil)
4024 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
4025 (pos js2-ts-cursor)
4026 len left right)))
4027 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
4028
4029 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
4030 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
4031
4032 (defun js2-visit-prop-get-node (n v)
4033 (js2-visit-ast (js2-prop-get-node-left n) v)
4034 (js2-visit-ast (js2-prop-get-node-right n) v))
4035
4036 (defun js2-print-prop-get-node (n i)
4037 (insert (js2-make-pad i))
4038 (js2-print-ast (js2-prop-get-node-left n) 0)
4039 (insert ".")
4040 (js2-print-ast (js2-prop-get-node-right n) 0))
4041
4042 (cl-defstruct (js2-elem-get-node
4043 (:include js2-node)
4044 (:constructor nil)
4045 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
4046 (pos js2-ts-cursor)
4047 len target element
4048 lb rb)))
4049 "AST node for an array index expression such as foo[bar]."
4050 target ; a `js2-node' - the expression preceding the "."
4051 element ; a `js2-node' - the expression in brackets
4052 lb ; position of left-bracket, nil if omitted
4053 rb) ; position of right-bracket, nil if omitted
4054
4055 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4056 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4057
4058 (defun js2-visit-elem-get-node (n v)
4059 (js2-visit-ast (js2-elem-get-node-target n) v)
4060 (js2-visit-ast (js2-elem-get-node-element n) v))
4061
4062 (defun js2-print-elem-get-node (n i)
4063 (insert (js2-make-pad i))
4064 (js2-print-ast (js2-elem-get-node-target n) 0)
4065 (insert "[")
4066 (js2-print-ast (js2-elem-get-node-element n) 0)
4067 (insert "]"))
4068
4069 (cl-defstruct (js2-call-node
4070 (:include js2-node)
4071 (:constructor nil)
4072 (:constructor make-js2-call-node (&key (type js2-CALL)
4073 (pos js2-ts-cursor)
4074 len target args
4075 lp rp)))
4076 "AST node for a JavaScript function call."
4077 target ; a `js2-node' evaluating to the function to call
4078 args ; a Lisp list of `js2-node' arguments
4079 lp ; position of open-paren, or nil if missing
4080 rp) ; position of close-paren, or nil if missing
4081
4082 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4083 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4084
4085 (defun js2-visit-call-node (n v)
4086 (js2-visit-ast (js2-call-node-target n) v)
4087 (dolist (arg (js2-call-node-args n))
4088 (js2-visit-ast arg v)))
4089
4090 (defun js2-print-call-node (n i)
4091 (insert (js2-make-pad i))
4092 (js2-print-ast (js2-call-node-target n) 0)
4093 (insert "(")
4094 (js2-print-list (js2-call-node-args n))
4095 (insert ")"))
4096
4097 (cl-defstruct (js2-yield-node
4098 (:include js2-node)
4099 (:constructor nil)
4100 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4101 (pos js2-ts-cursor)
4102 len value star-p)))
4103 "AST node for yield statement or expression."
4104 star-p ; whether it's yield*
4105 value) ; optional: value to be yielded
4106
4107 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4108 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4109
4110 (defun js2-visit-yield-node (n v)
4111 (js2-visit-ast (js2-yield-node-value n) v))
4112
4113 (defun js2-print-yield-node (n i)
4114 (insert (js2-make-pad i))
4115 (insert "yield")
4116 (when (js2-yield-node-star-p n)
4117 (insert "*"))
4118 (when (js2-yield-node-value n)
4119 (insert " ")
4120 (js2-print-ast (js2-yield-node-value n) 0)))
4121
4122 (cl-defstruct (js2-paren-node
4123 (:include js2-node)
4124 (:constructor nil)
4125 (:constructor make-js2-paren-node (&key (type js2-LP)
4126 (pos js2-ts-cursor)
4127 len expr)))
4128 "AST node for a parenthesized expression.
4129 In particular, used when the parens are syntactically optional,
4130 as opposed to required parens such as those enclosing an if-conditional."
4131 expr) ; `js2-node'
4132
4133 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4134 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4135
4136 (defun js2-visit-paren-node (n v)
4137 (js2-visit-ast (js2-paren-node-expr n) v))
4138
4139 (defun js2-print-paren-node (n i)
4140 (insert (js2-make-pad i))
4141 (insert "(")
4142 (js2-print-ast (js2-paren-node-expr n) 0)
4143 (insert ")"))
4144
4145 (cl-defstruct (js2-comp-node
4146 (:include js2-scope)
4147 (:constructor nil)
4148 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4149 (pos js2-ts-cursor)
4150 len result
4151 loops filters
4152 form)))
4153 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4154 result ; result expression (just after left-bracket)
4155 loops ; a Lisp list of `js2-comp-loop-node'
4156 filters ; a Lisp list of guard/filter expressions
4157 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4158 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4159 )
4160
4161 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4162 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4163
4164 (defun js2-visit-comp-node (n v)
4165 (js2-visit-ast (js2-comp-node-result n) v)
4166 (dolist (l (js2-comp-node-loops n))
4167 (js2-visit-ast l v))
4168 (dolist (f (js2-comp-node-filters n))
4169 (js2-visit-ast f v)))
4170
4171 (defun js2-print-comp-node (n i)
4172 (let ((pad (js2-make-pad i))
4173 (result (js2-comp-node-result n))
4174 (loops (js2-comp-node-loops n))
4175 (filters (js2-comp-node-filters n))
4176 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4177 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4178 (insert pad (if gen-p "(" "["))
4179 (when legacy-p
4180 (js2-print-ast result 0))
4181 (dolist (l loops)
4182 (when legacy-p
4183 (insert " "))
4184 (js2-print-ast l 0)
4185 (unless legacy-p
4186 (insert " ")))
4187 (dolist (f filters)
4188 (when legacy-p
4189 (insert " "))
4190 (insert "if (")
4191 (js2-print-ast f 0)
4192 (insert ")")
4193 (unless legacy-p
4194 (insert " ")))
4195 (unless legacy-p
4196 (js2-print-ast result 0))
4197 (insert (if gen-p ")" "]"))))
4198
4199 (cl-defstruct (js2-comp-loop-node
4200 (:include js2-for-in-node)
4201 (:constructor nil)
4202 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4203 (pos js2-ts-cursor)
4204 len iterator
4205 object in-pos
4206 foreach-p
4207 each-pos
4208 forof-p
4209 lp rp)))
4210 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4211
4212 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4213 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4214
4215 (defun js2-visit-comp-loop (n v)
4216 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4217 (js2-visit-ast (js2-comp-loop-node-object n) v))
4218
4219 (defun js2-print-comp-loop (n _i)
4220 (insert "for ")
4221 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4222 (insert "(")
4223 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4224 (insert (if (js2-comp-loop-node-forof-p n)
4225 " of " " in "))
4226 (js2-print-ast (js2-comp-loop-node-object n) 0)
4227 (insert ")"))
4228
4229 (cl-defstruct (js2-empty-expr-node
4230 (:include js2-node)
4231 (:constructor nil)
4232 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4233 (pos (js2-current-token-beg))
4234 len)))
4235 "AST node for an empty expression.")
4236
4237 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4238 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4239
4240 (cl-defstruct (js2-xml-node
4241 (:include js2-block-node)
4242 (:constructor nil)
4243 (:constructor make-js2-xml-node (&key (type js2-XML)
4244 (pos (js2-current-token-beg))
4245 len kids)))
4246 "AST node for initial parse of E4X literals.
4247 The kids field is a list of XML fragments, each a `js2-string-node' or
4248 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4249
4250 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4251 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4252
4253 (defun js2-print-xml-node (n i)
4254 (dolist (kid (js2-xml-node-kids n))
4255 (js2-print-ast kid i)))
4256
4257 (cl-defstruct (js2-xml-js-expr-node
4258 (:include js2-xml-node)
4259 (:constructor nil)
4260 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4261 (pos js2-ts-cursor)
4262 len expr)))
4263 "AST node for an embedded JavaScript {expression} in an E4X literal.
4264 The start and end fields correspond to the curly-braces."
4265 expr) ; a `js2-expr-node' of some sort
4266
4267 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4268 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4269
4270 (defun js2-visit-xml-js-expr (n v)
4271 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4272
4273 (defun js2-print-xml-js-expr (n i)
4274 (insert (js2-make-pad i))
4275 (insert "{")
4276 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4277 (insert "}"))
4278
4279 (cl-defstruct (js2-xml-dot-query-node
4280 (:include js2-infix-node)
4281 (:constructor nil)
4282 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4283 (pos js2-ts-cursor)
4284 op-pos len left
4285 right rp)))
4286 "AST node for an E4X foo.(bar) filter expression.
4287 Note that the left-paren is automatically the character immediately
4288 following the dot (.) in the operator. No whitespace is permitted
4289 between the dot and the lp by the scanner."
4290 rp)
4291
4292 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4293 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4294
4295 (defun js2-print-xml-dot-query (n i)
4296 (insert (js2-make-pad i))
4297 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4298 (insert ".(")
4299 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4300 (insert ")"))
4301
4302 (cl-defstruct (js2-xml-ref-node
4303 (:include js2-node)
4304 (:constructor nil)) ; abstract
4305 "Base type for E4X XML attribute-access or property-get expressions.
4306 Such expressions can take a variety of forms. The general syntax has
4307 three parts:
4308
4309 - (optional) an @ (specifying an attribute access)
4310 - (optional) a namespace (a `js2-name-node') and double-colon
4311 - (required) either a `js2-name-node' or a bracketed [expression]
4312
4313 The property-name expressions (examples: ns::name, @name) are
4314 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4315 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4316
4317 This node type (or more specifically, its subclasses) will sometimes
4318 be the right-hand child of a `js2-prop-get-node' or a
4319 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4320 The `js2-xml-ref-node' may also be a standalone primary expression with
4321 no explicit target, which is valid in certain expression contexts such as
4322
4323 company..employee.(@id < 100)
4324
4325 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4326 expression whose parent is a `js2-xml-dot-query-node'."
4327 namespace
4328 at-pos
4329 colon-pos)
4330
4331 (defsubst js2-xml-ref-node-attr-access-p (node)
4332 "Return non-nil if this expression began with an @-token."
4333 (and (numberp (js2-xml-ref-node-at-pos node))
4334 (cl-plusp (js2-xml-ref-node-at-pos node))))
4335
4336 (cl-defstruct (js2-xml-prop-ref-node
4337 (:include js2-xml-ref-node)
4338 (:constructor nil)
4339 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4340 (pos (js2-current-token-beg))
4341 len propname
4342 namespace at-pos
4343 colon-pos)))
4344 "AST node for an E4X XML [expr] property-ref expression.
4345 The JavaScript syntax is an optional @, an optional ns::, and a name.
4346
4347 [ '@' ] [ name '::' ] name
4348
4349 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4350 @ns::*, @*::attr, @*::*, and @*.
4351
4352 The node starts at the @ token, if present. Otherwise it starts at the
4353 namespace name. The node bounds extend through the closing right-bracket,
4354 or if it is missing due to a syntax error, through the end of the index
4355 expression."
4356 propname)
4357
4358 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4359 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4360
4361 (defun js2-visit-xml-prop-ref-node (n v)
4362 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4363 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4364
4365 (defun js2-print-xml-prop-ref-node (n i)
4366 (insert (js2-make-pad i))
4367 (if (js2-xml-ref-node-attr-access-p n)
4368 (insert "@"))
4369 (when (js2-xml-prop-ref-node-namespace n)
4370 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4371 (insert "::"))
4372 (if (js2-xml-prop-ref-node-propname n)
4373 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4374
4375 (cl-defstruct (js2-xml-elem-ref-node
4376 (:include js2-xml-ref-node)
4377 (:constructor nil)
4378 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4379 (pos (js2-current-token-beg))
4380 len expr lb rb
4381 namespace at-pos
4382 colon-pos)))
4383 "AST node for an E4X XML [expr] member-ref expression.
4384 Syntax:
4385
4386 [ '@' ] [ name '::' ] '[' expr ']'
4387
4388 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4389
4390 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4391 is not a legal E4X XML element-ref expression, since it's already used
4392 for standard JavaScript element-get array indexing. Hence, a
4393 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4394 non-nil namespace node, or both.
4395
4396 The node starts at the @ token, if present. Otherwise it starts
4397 at the namespace name. The node bounds extend through the closing
4398 right-bracket, or if it is missing due to a syntax error, through the
4399 end of the index expression."
4400 expr ; the bracketed index expression
4401 lb
4402 rb)
4403
4404 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4405 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4406
4407 (defun js2-visit-xml-elem-ref-node (n v)
4408 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4409 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4410
4411 (defun js2-print-xml-elem-ref-node (n i)
4412 (insert (js2-make-pad i))
4413 (if (js2-xml-ref-node-attr-access-p n)
4414 (insert "@"))
4415 (when (js2-xml-elem-ref-node-namespace n)
4416 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4417 (insert "::"))
4418 (insert "[")
4419 (if (js2-xml-elem-ref-node-expr n)
4420 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4421 (insert "]"))
4422
4423 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4424
4425 (cl-defstruct (js2-xml-start-tag-node
4426 (:include js2-xml-node)
4427 (:constructor nil)
4428 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4429 (pos js2-ts-cursor)
4430 len name attrs kids
4431 empty-p)))
4432 "AST node for an XML start-tag. Not currently used.
4433 The `kids' field is a Lisp list of child content nodes."
4434 name ; a `js2-xml-name-node'
4435 attrs ; a Lisp list of `js2-xml-attr-node'
4436 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4437
4438 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4439 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4440
4441 (defun js2-visit-xml-start-tag (n v)
4442 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4443 (dolist (attr (js2-xml-start-tag-node-attrs n))
4444 (js2-visit-ast attr v))
4445 (js2-visit-block n v))
4446
4447 (defun js2-print-xml-start-tag (n i)
4448 (insert (js2-make-pad i) "<")
4449 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4450 (when (js2-xml-start-tag-node-attrs n)
4451 (insert " ")
4452 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4453 (insert ">"))
4454
4455 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4456 ;; and add the end-tag to the kids list of the parent as well.
4457 (cl-defstruct (js2-xml-end-tag-node
4458 (:include js2-xml-node)
4459 (:constructor nil)
4460 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4461 (pos js2-ts-cursor)
4462 len name)))
4463 "AST node for an XML end-tag. Not currently used."
4464 name) ; a `js2-xml-name-node'
4465
4466 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4467 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4468
4469 (defun js2-visit-xml-end-tag (n v)
4470 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4471
4472 (defun js2-print-xml-end-tag (n i)
4473 (insert (js2-make-pad i))
4474 (insert "</")
4475 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4476 (insert ">"))
4477
4478 (cl-defstruct (js2-xml-name-node
4479 (:include js2-xml-node)
4480 (:constructor nil)
4481 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4482 (pos js2-ts-cursor)
4483 len namespace kids)))
4484 "AST node for an E4X XML name. Not currently used.
4485 Any XML name can be qualified with a namespace, hence the namespace field.
4486 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4487 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4488 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4489 namespace) ; a `js2-string-node'
4490
4491 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4492 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4493
4494 (defun js2-visit-xml-name-node (n v)
4495 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4496
4497 (defun js2-print-xml-name-node (n i)
4498 (insert (js2-make-pad i))
4499 (when (js2-xml-name-node-namespace n)
4500 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4501 (insert "::"))
4502 (dolist (kid (js2-xml-name-node-kids n))
4503 (js2-print-ast kid 0)))
4504
4505 (cl-defstruct (js2-xml-pi-node
4506 (:include js2-xml-node)
4507 (:constructor nil)
4508 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4509 (pos js2-ts-cursor)
4510 len name attrs)))
4511 "AST node for an E4X XML processing instruction. Not currently used."
4512 name ; a `js2-xml-name-node'
4513 attrs) ; a list of `js2-xml-attr-node'
4514
4515 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4516 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4517
4518 (defun js2-visit-xml-pi-node (n v)
4519 (js2-visit-ast (js2-xml-pi-node-name n) v)
4520 (dolist (attr (js2-xml-pi-node-attrs n))
4521 (js2-visit-ast attr v)))
4522
4523 (defun js2-print-xml-pi-node (n i)
4524 (insert (js2-make-pad i) "<?")
4525 (js2-print-ast (js2-xml-pi-node-name n))
4526 (when (js2-xml-pi-node-attrs n)
4527 (insert " ")
4528 (js2-print-list (js2-xml-pi-node-attrs n)))
4529 (insert "?>"))
4530
4531 (cl-defstruct (js2-xml-cdata-node
4532 (:include js2-xml-node)
4533 (:constructor nil)
4534 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4535 (pos js2-ts-cursor)
4536 len content)))
4537 "AST node for a CDATA escape section. Not currently used."
4538 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4539
4540 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4541 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4542
4543 (defun js2-visit-xml-cdata-node (n v)
4544 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4545
4546 (defun js2-print-xml-cdata-node (n i)
4547 (insert (js2-make-pad i))
4548 (js2-print-ast (js2-xml-cdata-node-content n)))
4549
4550 (cl-defstruct (js2-xml-attr-node
4551 (:include js2-xml-node)
4552 (:constructor nil)
4553 (:constructor make-js2-attr-node (&key (type js2-XML)
4554 (pos js2-ts-cursor)
4555 len name value
4556 eq-pos quote-type)))
4557 "AST node representing a foo='bar' XML attribute value. Not yet used."
4558 name ; a `js2-xml-name-node'
4559 value ; a `js2-xml-name-node'
4560 eq-pos ; buffer position of "=" sign
4561 quote-type) ; 'single or 'double
4562
4563 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4564 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4565
4566 (defun js2-visit-xml-attr-node (n v)
4567 (js2-visit-ast (js2-xml-attr-node-name n) v)
4568 (js2-visit-ast (js2-xml-attr-node-value n) v))
4569
4570 (defun js2-print-xml-attr-node (n i)
4571 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4572 "'"
4573 "\"")))
4574 (insert (js2-make-pad i))
4575 (js2-print-ast (js2-xml-attr-node-name n) 0)
4576 (insert "=" quote)
4577 (js2-print-ast (js2-xml-attr-node-value n) 0)
4578 (insert quote)))
4579
4580 (cl-defstruct (js2-xml-text-node
4581 (:include js2-xml-node)
4582 (:constructor nil)
4583 (:constructor make-js2-text-node (&key (type js2-XML)
4584 (pos js2-ts-cursor)
4585 len content)))
4586 "AST node for an E4X XML text node. Not currently used."
4587 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4588
4589 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4590 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4591
4592 (defun js2-visit-xml-text-node (n v)
4593 (js2-visit-ast (js2-xml-text-node-content n) v))
4594
4595 (defun js2-print-xml-text-node (n i)
4596 (insert (js2-make-pad i))
4597 (dolist (kid (js2-xml-text-node-content n))
4598 (js2-print-ast kid)))
4599
4600 (cl-defstruct (js2-xml-comment-node
4601 (:include js2-xml-node)
4602 (:constructor nil)
4603 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4604 (pos js2-ts-cursor)
4605 len)))
4606 "AST node for E4X XML comment. Not currently used.")
4607
4608 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4609 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4610
4611 (defun js2-print-xml-comment (n i)
4612 (insert (js2-make-pad i)
4613 (js2-node-string n)))
4614
4615 ;;; Node utilities
4616
4617 (defsubst js2-node-line (n)
4618 "Fetch the source line number at the start of node N.
4619 This is O(n) in the length of the source buffer; use prudently."
4620 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4621
4622 (defsubst js2-block-node-kid (n i)
4623 "Return child I of node N, or nil if there aren't that many."
4624 (nth i (js2-block-node-kids n)))
4625
4626 (defsubst js2-block-node-first (n)
4627 "Return first child of block node N, or nil if there is none."
4628 (cl-first (js2-block-node-kids n)))
4629
4630 (defun js2-node-root (n)
4631 "Return the root of the AST containing N.
4632 If N has no parent pointer, returns N."
4633 (let ((parent (js2-node-parent n)))
4634 (if parent
4635 (js2-node-root parent)
4636 n)))
4637
4638 (defsubst js2-node-short-name (n)
4639 "Return the short name of node N as a string, e.g. `js2-if-node'."
4640 (substring (symbol-name (aref n 0))
4641 (length "cl-struct-")))
4642
4643 (defun js2-node-child-list (node)
4644 "Return the child list for NODE, a Lisp list of nodes.
4645 Works for block nodes, array nodes, obj literals, funarg lists,
4646 var decls and try nodes (for catch clauses). Note that you should call
4647 `js2-block-node-kids' on the function body for the body statements.
4648 Returns nil for zero-length child lists or unsupported nodes."
4649 (cond
4650 ((js2-function-node-p node)
4651 (js2-function-node-params node))
4652 ((js2-block-node-p node)
4653 (js2-block-node-kids node))
4654 ((js2-try-node-p node)
4655 (js2-try-node-catch-clauses node))
4656 ((js2-array-node-p node)
4657 (js2-array-node-elems node))
4658 ((js2-object-node-p node)
4659 (js2-object-node-elems node))
4660 ((js2-call-node-p node)
4661 (js2-call-node-args node))
4662 ((js2-new-node-p node)
4663 (js2-new-node-args node))
4664 ((js2-var-decl-node-p node)
4665 (js2-var-decl-node-kids node))
4666 (t
4667 nil)))
4668
4669 (defun js2-node-set-child-list (node kids)
4670 "Set the child list for NODE to KIDS."
4671 (cond
4672 ((js2-function-node-p node)
4673 (setf (js2-function-node-params node) kids))
4674 ((js2-block-node-p node)
4675 (setf (js2-block-node-kids node) kids))
4676 ((js2-try-node-p node)
4677 (setf (js2-try-node-catch-clauses node) kids))
4678 ((js2-array-node-p node)
4679 (setf (js2-array-node-elems node) kids))
4680 ((js2-object-node-p node)
4681 (setf (js2-object-node-elems node) kids))
4682 ((js2-call-node-p node)
4683 (setf (js2-call-node-args node) kids))
4684 ((js2-new-node-p node)
4685 (setf (js2-new-node-args node) kids))
4686 ((js2-var-decl-node-p node)
4687 (setf (js2-var-decl-node-kids node) kids))
4688 (t
4689 (error "Unsupported node type: %s" (js2-node-short-name node))))
4690 kids)
4691
4692 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4693 (defconst js2-paren-expr-nodes
4694 '(cl-struct-js2-comp-loop-node
4695 cl-struct-js2-comp-node
4696 cl-struct-js2-call-node
4697 cl-struct-js2-catch-node
4698 cl-struct-js2-do-node
4699 cl-struct-js2-elem-get-node
4700 cl-struct-js2-for-in-node
4701 cl-struct-js2-for-node
4702 cl-struct-js2-function-node
4703 cl-struct-js2-if-node
4704 cl-struct-js2-let-node
4705 cl-struct-js2-new-node
4706 cl-struct-js2-paren-node
4707 cl-struct-js2-switch-node
4708 cl-struct-js2-while-node
4709 cl-struct-js2-with-node
4710 cl-struct-js2-xml-dot-query-node)
4711 "Node types that can have a parenthesized child expression.
4712 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4713
4714 (defsubst js2-paren-expr-node-p (node)
4715 "Return t for nodes that typically have a parenthesized child expression.
4716 Useful for computing the indentation anchors for arg-lists and conditions.
4717 Note that it may return a false positive, for instance when NODE is
4718 a `js2-new-node' and there are no arguments or parentheses."
4719 (memq (aref node 0) js2-paren-expr-nodes))
4720
4721 ;; Fake polymorphism... yech.
4722 (defun js2-node-lp (node)
4723 "Return relative left-paren position for NODE, if applicable.
4724 For `js2-elem-get-node' structs, returns left-bracket position.
4725 Note that the position may be nil in the case of a parse error."
4726 (cond
4727 ((js2-elem-get-node-p node)
4728 (js2-elem-get-node-lb node))
4729 ((js2-loop-node-p node)
4730 (js2-loop-node-lp node))
4731 ((js2-function-node-p node)
4732 (js2-function-node-lp node))
4733 ((js2-if-node-p node)
4734 (js2-if-node-lp node))
4735 ((js2-new-node-p node)
4736 (js2-new-node-lp node))
4737 ((js2-call-node-p node)
4738 (js2-call-node-lp node))
4739 ((js2-paren-node-p node)
4740 0)
4741 ((js2-switch-node-p node)
4742 (js2-switch-node-lp node))
4743 ((js2-catch-node-p node)
4744 (js2-catch-node-lp node))
4745 ((js2-let-node-p node)
4746 (js2-let-node-lp node))
4747 ((js2-comp-node-p node)
4748 0)
4749 ((js2-with-node-p node)
4750 (js2-with-node-lp node))
4751 ((js2-xml-dot-query-node-p node)
4752 (1+ (js2-infix-node-op-pos node)))
4753 (t
4754 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4755
4756 ;; Fake polymorphism... blech.
4757 (defun js2-node-rp (node)
4758 "Return relative right-paren position for NODE, if applicable.
4759 For `js2-elem-get-node' structs, returns right-bracket position.
4760 Note that the position may be nil in the case of a parse error."
4761 (cond
4762 ((js2-elem-get-node-p node)
4763 (js2-elem-get-node-rb node))
4764 ((js2-loop-node-p node)
4765 (js2-loop-node-rp node))
4766 ((js2-function-node-p node)
4767 (js2-function-node-rp node))
4768 ((js2-if-node-p node)
4769 (js2-if-node-rp node))
4770 ((js2-new-node-p node)
4771 (js2-new-node-rp node))
4772 ((js2-call-node-p node)
4773 (js2-call-node-rp node))
4774 ((js2-paren-node-p node)
4775 (1- (js2-node-len node)))
4776 ((js2-switch-node-p node)
4777 (js2-switch-node-rp node))
4778 ((js2-catch-node-p node)
4779 (js2-catch-node-rp node))
4780 ((js2-let-node-p node)
4781 (js2-let-node-rp node))
4782 ((js2-comp-node-p node)
4783 (1- (js2-node-len node)))
4784 ((js2-with-node-p node)
4785 (js2-with-node-rp node))
4786 ((js2-xml-dot-query-node-p node)
4787 (1+ (js2-xml-dot-query-node-rp node)))
4788 (t
4789 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4790
4791 (defsubst js2-node-first-child (node)
4792 "Return the first element of `js2-node-child-list' for NODE."
4793 (car (js2-node-child-list node)))
4794
4795 (defsubst js2-node-last-child (node)
4796 "Return the last element of `js2-node-last-child' for NODE."
4797 (car (last (js2-node-child-list node))))
4798
4799 (defun js2-node-prev-sibling (node)
4800 "Return the previous statement in parent.
4801 Works for parents supported by `js2-node-child-list'.
4802 Returns nil if NODE is not in the parent, or PARENT is
4803 not a supported node, or if NODE is the first child."
4804 (let* ((p (js2-node-parent node))
4805 (kids (js2-node-child-list p))
4806 (sib (car kids)))
4807 (while (and kids
4808 (not (eq node (cadr kids))))
4809 (setq kids (cdr kids)
4810 sib (car kids)))
4811 sib))
4812
4813 (defun js2-node-next-sibling (node)
4814 "Return the next statement in parent block.
4815 Returns nil if NODE is not in the block, or PARENT is not
4816 a block node, or if NODE is the last statement."
4817 (let* ((p (js2-node-parent node))
4818 (kids (js2-node-child-list p)))
4819 (while (and kids
4820 (not (eq node (car kids))))
4821 (setq kids (cdr kids)))
4822 (cadr kids)))
4823
4824 (defun js2-node-find-child-before (pos parent &optional after)
4825 "Find the last child that starts before POS in parent.
4826 If AFTER is non-nil, returns first child starting after POS.
4827 POS is an absolute buffer position. PARENT is any node
4828 supported by `js2-node-child-list'.
4829 Returns nil if no applicable child is found."
4830 (let ((kids (if (js2-function-node-p parent)
4831 (js2-block-node-kids (js2-function-node-body parent))
4832 (js2-node-child-list parent)))
4833 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4834 (js2-function-node-body parent)
4835 parent)))
4836 kid result fn
4837 (continue t))
4838 (setq fn (if after '>= '<))
4839 (while (and kids continue)
4840 (setq kid (car kids))
4841 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4842 (setq result kid
4843 continue (not after))
4844 (setq continue after))
4845 (setq kids (cdr kids)))
4846 result))
4847
4848 (defun js2-node-find-child-after (pos parent)
4849 "Find first child that starts after POS in parent.
4850 POS is an absolute buffer position. PARENT is any node
4851 supported by `js2-node-child-list'.
4852 Returns nil if no applicable child is found."
4853 (js2-node-find-child-before pos parent 'after))
4854
4855 (defun js2-node-replace-child (pos parent new-node)
4856 "Replace node at index POS in PARENT with NEW-NODE.
4857 Only works for parents supported by `js2-node-child-list'."
4858 (let ((kids (js2-node-child-list parent))
4859 (i 0))
4860 (while (< i pos)
4861 (setq kids (cdr kids)
4862 i (1+ i)))
4863 (setcar kids new-node)
4864 (js2-node-add-children parent new-node)))
4865
4866 (defun js2-node-buffer (n)
4867 "Return the buffer associated with AST N.
4868 Returns nil if the buffer is not set as a property on the root
4869 node, or if parent links were not recorded during parsing."
4870 (let ((root (js2-node-root n)))
4871 (and root
4872 (js2-ast-root-p root)
4873 (js2-ast-root-buffer root))))
4874
4875 (defun js2-block-node-push (n kid)
4876 "Push js2-node KID onto the end of js2-block-node N's child list.
4877 KID is always added to the -end- of the kids list.
4878 Function also calls `js2-node-add-children' to add the parent link."
4879 (let ((kids (js2-node-child-list n)))
4880 (if kids
4881 (setcdr kids (nconc (cdr kids) (list kid)))
4882 (js2-node-set-child-list n (list kid)))
4883 (js2-node-add-children n kid)))
4884
4885 (defun js2-node-string (node)
4886 (with-current-buffer (or (js2-node-buffer node)
4887 (error "No buffer available for node %s" node))
4888 (let ((pos (js2-node-abs-pos node)))
4889 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4890
4891 ;; Container for storing the node we're looking for in a traversal.
4892 (js2-deflocal js2-discovered-node nil)
4893
4894 ;; Keep track of absolute node position during traversals.
4895 (js2-deflocal js2-visitor-offset nil)
4896
4897 (js2-deflocal js2-node-search-point nil)
4898
4899 (when js2-mode-dev-mode-p
4900 (defun js2-find-node-at-point ()
4901 (interactive)
4902 (let ((node (js2-node-at-point)))
4903 (message "%s" (or node "No node found at point"))))
4904 (defun js2-node-name-at-point ()
4905 (interactive)
4906 (let ((node (js2-node-at-point)))
4907 (message "%s" (if node
4908 (js2-node-short-name node)
4909 "No node found at point.")))))
4910
4911 (defun js2-node-at-point (&optional pos skip-comments)
4912 "Return AST node at POS, a buffer position, defaulting to current point.
4913 The `js2-mode-ast' variable must be set to the current parse tree.
4914 Signals an error if the AST (`js2-mode-ast') is nil.
4915 Always returns a node - if it can't find one, it returns the root.
4916 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4917 (let ((ast js2-mode-ast)
4918 result)
4919 (unless ast
4920 (error "No JavaScript AST available"))
4921 ;; Look through comments first, since they may be inside nodes that
4922 ;; would otherwise report a match.
4923 (setq pos (or pos (point))
4924 result (if (> pos (js2-node-abs-end ast))
4925 ast
4926 (if (not skip-comments)
4927 (js2-comment-at-point pos))))
4928 (unless result
4929 (setq js2-discovered-node nil
4930 js2-visitor-offset 0
4931 js2-node-search-point pos)
4932 (unwind-protect
4933 (catch 'js2-visit-done
4934 (js2-visit-ast ast #'js2-node-at-point-visitor))
4935 (setq js2-visitor-offset nil
4936 js2-node-search-point nil))
4937 (setq result js2-discovered-node))
4938 ;; may have found a comment beyond end of last child node,
4939 ;; since visiting the ast-root looks at the comment-list last.
4940 (if (and skip-comments
4941 (js2-comment-node-p result))
4942 (setq result nil))
4943 (or result js2-mode-ast)))
4944
4945 (defun js2-node-at-point-visitor (node end-p)
4946 (let ((rel-pos (js2-node-pos node))
4947 abs-pos
4948 abs-end
4949 (point js2-node-search-point))
4950 (cond
4951 (end-p
4952 ;; this evaluates to a non-nil return value, even if it's zero
4953 (cl-decf js2-visitor-offset rel-pos))
4954 ;; we already looked for comments before visiting, and don't want them now
4955 ((js2-comment-node-p node)
4956 nil)
4957 (t
4958 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4959 ;; we only want to use the node if the point is before
4960 ;; the last character position in the node, so we decrement
4961 ;; the absolute end by 1.
4962 abs-end (+ abs-pos (js2-node-len node) -1))
4963 (cond
4964 ;; If this node starts after search-point, stop the search.
4965 ((> abs-pos point)
4966 (throw 'js2-visit-done nil))
4967 ;; If this node ends before the search-point, don't check kids.
4968 ((> point abs-end)
4969 nil)
4970 (t
4971 ;; Otherwise point is within this node, possibly in a child.
4972 (setq js2-discovered-node node)
4973 t)))))) ; keep processing kids to look for more specific match
4974
4975 (defsubst js2-block-comment-p (node)
4976 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4977 (and (js2-comment-node-p node)
4978 (memq (js2-comment-node-format node) '(jsdoc block))))
4979
4980 ;; TODO: put the comments in a vector and binary-search them instead
4981 (defun js2-comment-at-point (&optional pos)
4982 "Look through scanned comment nodes for one containing POS.
4983 POS is a buffer position that defaults to current point.
4984 Function returns nil if POS was not in any comment node."
4985 (let ((ast js2-mode-ast)
4986 (x (or pos (point)))
4987 beg end)
4988 (unless ast
4989 (error "No JavaScript AST available"))
4990 (catch 'done
4991 ;; Comments are stored in lexical order.
4992 (dolist (comment (js2-ast-root-comments ast) nil)
4993 (setq beg (js2-node-abs-pos comment)
4994 end (+ beg (js2-node-len comment)))
4995 (if (and (>= x beg)
4996 (<= x end))
4997 (throw 'done comment))))))
4998
4999 (defun js2-mode-find-parent-fn (node)
5000 "Find function enclosing NODE.
5001 Returns nil if NODE is not inside a function."
5002 (setq node (js2-node-parent node))
5003 (while (and node (not (js2-function-node-p node)))
5004 (setq node (js2-node-parent node)))
5005 (and (js2-function-node-p node) node))
5006
5007 (defun js2-mode-find-enclosing-fn (node)
5008 "Find function or root enclosing NODE."
5009 (if (js2-ast-root-p node)
5010 node
5011 (setq node (js2-node-parent node))
5012 (while (not (or (js2-ast-root-p node)
5013 (js2-function-node-p node)))
5014 (setq node (js2-node-parent node)))
5015 node))
5016
5017 (defun js2-mode-find-enclosing-node (beg end)
5018 "Find node fully enclosing BEG and END."
5019 (let ((node (js2-node-at-point beg))
5020 pos
5021 (continue t))
5022 (while continue
5023 (if (or (js2-ast-root-p node)
5024 (and
5025 (<= (setq pos (js2-node-abs-pos node)) beg)
5026 (>= (+ pos (js2-node-len node)) end)))
5027 (setq continue nil)
5028 (setq node (js2-node-parent node))))
5029 node))
5030
5031 (defun js2-node-parent-script-or-fn (node)
5032 "Find script or function immediately enclosing NODE.
5033 If NODE is the ast-root, returns nil."
5034 (if (js2-ast-root-p node)
5035 nil
5036 (setq node (js2-node-parent node))
5037 (while (and node (not (or (js2-function-node-p node)
5038 (js2-script-node-p node))))
5039 (setq node (js2-node-parent node)))
5040 node))
5041
5042 (defun js2-node-is-descendant (node ancestor)
5043 "Return t if NODE is a descendant of ANCESTOR."
5044 (while (and node
5045 (not (eq node ancestor)))
5046 (setq node (js2-node-parent node)))
5047 node)
5048
5049 ;;; visitor infrastructure
5050
5051 (defun js2-visit-none (_node _callback)
5052 "Visitor for AST node that have no node children."
5053 nil)
5054
5055 (defun js2-print-none (_node _indent)
5056 "Visitor for AST node with no printed representation.")
5057
5058 (defun js2-print-body (node indent)
5059 "Print a statement, or a block without braces."
5060 (if (js2-block-node-p node)
5061 (dolist (kid (js2-block-node-kids node))
5062 (js2-print-ast kid indent))
5063 (js2-print-ast node indent)))
5064
5065 (defun js2-print-list (args &optional delimiter)
5066 (cl-loop with len = (length args)
5067 for arg in args
5068 for count from 1
5069 do
5070 (when arg (js2-print-ast arg 0))
5071 (if (< count len)
5072 (insert (or delimiter ", ")))))
5073
5074 (defun js2-print-tree (ast)
5075 "Prints an AST to the current buffer.
5076 Makes `js2-ast-parent-nodes' available to the printer functions."
5077 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5078 (js2-print-ast ast)))
5079
5080 (defun js2-print-ast (node &optional indent)
5081 "Helper function for printing AST nodes.
5082 Requires `js2-ast-parent-nodes' to be non-nil.
5083 You should use `js2-print-tree' instead of this function."
5084 (let ((printer (get (aref node 0) 'js2-printer))
5085 (i (or indent 0)))
5086 ;; TODO: wedge comments in here somewhere
5087 (if printer
5088 (funcall printer node i))))
5089
5090 (defconst js2-side-effecting-tokens
5091 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5092 (dolist (tt (list js2-ASSIGN
5093 js2-ASSIGN_ADD
5094 js2-ASSIGN_BITAND
5095 js2-ASSIGN_BITOR
5096 js2-ASSIGN_BITXOR
5097 js2-ASSIGN_DIV
5098 js2-ASSIGN_LSH
5099 js2-ASSIGN_MOD
5100 js2-ASSIGN_MUL
5101 js2-ASSIGN_RSH
5102 js2-ASSIGN_SUB
5103 js2-ASSIGN_URSH
5104 js2-BLOCK
5105 js2-BREAK
5106 js2-CALL
5107 js2-CATCH
5108 js2-CATCH_SCOPE
5109 js2-CLASS
5110 js2-CONST
5111 js2-CONTINUE
5112 js2-DEBUGGER
5113 js2-DEC
5114 js2-DELPROP
5115 js2-DEL_REF
5116 js2-DO
5117 js2-ELSE
5118 js2-EMPTY
5119 js2-ENTERWITH
5120 js2-EXPORT
5121 js2-EXPR_RESULT
5122 js2-FINALLY
5123 js2-FOR
5124 js2-FUNCTION
5125 js2-GOTO
5126 js2-IF
5127 js2-IFEQ
5128 js2-IFNE
5129 js2-IMPORT
5130 js2-INC
5131 js2-JSR
5132 js2-LABEL
5133 js2-LEAVEWITH
5134 js2-LET
5135 js2-LETEXPR
5136 js2-LOCAL_BLOCK
5137 js2-LOOP
5138 js2-NEW
5139 js2-REF_CALL
5140 js2-RETHROW
5141 js2-RETURN
5142 js2-RETURN_RESULT
5143 js2-SEMI
5144 js2-SETELEM
5145 js2-SETELEM_OP
5146 js2-SETNAME
5147 js2-SETPROP
5148 js2-SETPROP_OP
5149 js2-SETVAR
5150 js2-SET_REF
5151 js2-SET_REF_OP
5152 js2-SWITCH
5153 js2-TARGET
5154 js2-THROW
5155 js2-TRY
5156 js2-VAR
5157 js2-WHILE
5158 js2-WITH
5159 js2-WITHEXPR
5160 js2-YIELD))
5161 (aset tokens tt t))
5162 (if js2-instanceof-has-side-effects
5163 (aset tokens js2-INSTANCEOF t))
5164 tokens))
5165
5166 (defun js2-node-has-side-effects (node)
5167 "Return t if NODE has side effects."
5168 (when node ; makes it easier to handle malformed expressions
5169 (let ((tt (js2-node-type node)))
5170 (cond
5171 ;; This doubtless needs some work, since EXPR_VOID is used
5172 ;; in several ways in Rhino and I may not have caught them all.
5173 ;; I'll wait for people to notice incorrect warnings.
5174 ((and (= tt js2-EXPR_VOID)
5175 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5176 (let ((expr (js2-expr-stmt-node-expr node)))
5177 (or (js2-node-has-side-effects expr)
5178 (when (js2-string-node-p expr)
5179 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5180 ((= tt js2-COMMA)
5181 (js2-node-has-side-effects (js2-infix-node-right node)))
5182 ((or (= tt js2-AND)
5183 (= tt js2-OR))
5184 (or (js2-node-has-side-effects (js2-infix-node-right node))
5185 (js2-node-has-side-effects (js2-infix-node-left node))))
5186 ((= tt js2-HOOK)
5187 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5188 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5189 ((js2-paren-node-p node)
5190 (js2-node-has-side-effects (js2-paren-node-expr node)))
5191 ((= tt js2-ERROR) ; avoid cascaded error messages
5192 nil)
5193 (t
5194 (aref js2-side-effecting-tokens tt))))))
5195
5196 (defconst js2-stmt-node-types
5197 (list js2-BLOCK
5198 js2-BREAK
5199 js2-CONTINUE
5200 js2-DEFAULT ; e4x "default xml namespace" statement
5201 js2-DO
5202 js2-EXPORT
5203 js2-EXPR_RESULT
5204 js2-EXPR_VOID
5205 js2-FOR
5206 js2-IF
5207 js2-IMPORT
5208 js2-RETURN
5209 js2-SWITCH
5210 js2-THROW
5211 js2-TRY
5212 js2-WHILE
5213 js2-WITH)
5214 "Node types that only appear in statement contexts.
5215 The list does not include nodes that always appear as the child
5216 of another specific statement type, such as switch-cases,
5217 catch and finally blocks, and else-clauses. The list also excludes
5218 nodes like yield, let and var, which may appear in either expression
5219 or statement context, and in the latter context always have a
5220 `js2-expr-stmt-node' parent. Finally, the list does not include
5221 functions or scripts, which are treated separately from statements
5222 by the JavaScript parser and runtime.")
5223
5224 (defun js2-stmt-node-p (node)
5225 "Heuristic for figuring out if NODE is a statement.
5226 Some node types can appear in either an expression context or a
5227 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5228 For these node types in a statement context, the parent will be a
5229 `js2-expr-stmt-node'.
5230 Functions aren't included in the check."
5231 (memq (js2-node-type node) js2-stmt-node-types))
5232
5233 (defun js2-mode-find-first-stmt (node)
5234 "Search upward starting from NODE looking for a statement.
5235 For purposes of this function, a `js2-function-node' counts."
5236 (while (not (or (js2-stmt-node-p node)
5237 (js2-function-node-p node)))
5238 (setq node (js2-node-parent node)))
5239 node)
5240
5241 (defun js2-node-parent-stmt (node)
5242 "Return the node's first ancestor that is a statement.
5243 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5244 appearing in a statement context will have a parent that is a
5245 `js2-expr-stmt-node' that will be returned by this function."
5246 (let ((parent (js2-node-parent node)))
5247 (if (or (null parent)
5248 (js2-stmt-node-p parent)
5249 (and (js2-function-node-p parent)
5250 (not (eq (js2-function-node-form parent)
5251 'FUNCTION_EXPRESSION))))
5252 parent
5253 (js2-node-parent-stmt parent))))
5254
5255 ;; In the Mozilla Rhino sources, Roshan James writes:
5256 ;; Does consistent-return analysis on the function body when strict mode is
5257 ;; enabled.
5258 ;;
5259 ;; function (x) { return (x+1) }
5260 ;;
5261 ;; is ok, but
5262 ;;
5263 ;; function (x) { if (x < 0) return (x+1); }
5264 ;;
5265 ;; is not because the function can potentially return a value when the
5266 ;; condition is satisfied and if not, the function does not explicitly
5267 ;; return a value.
5268 ;;
5269 ;; This extends to checking mismatches such as "return" and "return <value>"
5270 ;; used in the same function. Warnings are not emitted if inconsistent
5271 ;; returns exist in code that can be statically shown to be unreachable.
5272 ;; Ex.
5273 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5274 ;;
5275 ;; emits no warning. However if the loop had a break statement, then a
5276 ;; warning would be emitted.
5277 ;;
5278 ;; The consistency analysis looks at control structures such as loops, ifs,
5279 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5280 ;; warns the user about an inconsistent set of termination possibilities.
5281 ;;
5282 ;; These flags enumerate the possible ways a statement/function can
5283 ;; terminate. These flags are used by endCheck() and by the Parser to
5284 ;; detect inconsistent return usage.
5285 ;;
5286 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5287 ;; able to execute (example: throw, continue)
5288 ;;
5289 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5290 ;; next one. Statement such as return dont. A compound statement may have
5291 ;; some branch that drops off control to the next statement.
5292 ;;
5293 ;; END_RETURNS indicates that the statement can return with no value.
5294 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5295 ;;
5296 ;; A compound statement such as
5297 ;; if (condition) {
5298 ;; return value;
5299 ;; }
5300 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5301
5302 (defconst js2-END_UNREACHED 0)
5303 (defconst js2-END_DROPS_OFF 1)
5304 (defconst js2-END_RETURNS 2)
5305 (defconst js2-END_RETURNS_VALUE 4)
5306 (defconst js2-END_YIELDS 8)
5307
5308 (defun js2-has-consistent-return-usage (node)
5309 "Check that every return usage in a function body is consistent.
5310 Returns t if the function satisfies strict mode requirement."
5311 (let ((n (js2-end-check node)))
5312 ;; either it doesn't return a value in any branch...
5313 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5314 ;; or it returns a value (or is unreached) at every branch
5315 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5316 js2-END_RETURNS
5317 js2-END_YIELDS)))))
5318
5319 (defun js2-end-check-if (node)
5320 "Ensure that return usage in then/else blocks is consistent.
5321 If there is no else block, then the return statement can fall through.
5322 Returns logical OR of END_* flags"
5323 (let ((th (js2-if-node-then-part node))
5324 (el (js2-if-node-else-part node)))
5325 (if (null th)
5326 js2-END_UNREACHED
5327 (logior (js2-end-check th) (if el
5328 (js2-end-check el)
5329 js2-END_DROPS_OFF)))))
5330
5331 (defun js2-end-check-switch (node)
5332 "Consistency of return statements is checked between the case statements.
5333 If there is no default, then the switch can fall through. If there is a
5334 default, we check to see if all code paths in the default return or if
5335 there is a code path that can fall through.
5336 Returns logical OR of END_* flags."
5337 (let ((rv js2-END_UNREACHED)
5338 default-case)
5339 ;; examine the cases
5340 (catch 'break
5341 (dolist (c (js2-switch-node-cases node))
5342 (if (js2-case-node-expr c)
5343 (js2-set-flag rv (js2-end-check-block c))
5344 (setq default-case c)
5345 (throw 'break nil))))
5346 ;; we don't care how the cases drop into each other
5347 (js2-clear-flag rv js2-END_DROPS_OFF)
5348 ;; examine the default
5349 (js2-set-flag rv (if default-case
5350 (js2-end-check default-case)
5351 js2-END_DROPS_OFF))
5352 rv))
5353
5354 (defun js2-end-check-try (node)
5355 "If the block has a finally, return consistency is checked in the
5356 finally block. If all code paths in the finally return, then the
5357 returns in the try-catch blocks don't matter. If there is a code path
5358 that does not return or if there is no finally block, the returns
5359 of the try and catch blocks are checked for mismatch.
5360 Returns logical OR of END_* flags."
5361 (let ((finally (js2-try-node-finally-block node))
5362 rv)
5363 ;; check the finally if it exists
5364 (setq rv (if finally
5365 (js2-end-check (js2-finally-node-body finally))
5366 js2-END_DROPS_OFF))
5367 ;; If the finally block always returns, then none of the returns
5368 ;; in the try or catch blocks matter.
5369 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5370 (js2-clear-flag rv js2-END_DROPS_OFF)
5371 ;; examine the try block
5372 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5373 ;; check each catch block
5374 (dolist (cb (js2-try-node-catch-clauses node))
5375 (js2-set-flag rv (js2-end-check cb))))
5376 rv))
5377
5378 (defun js2-end-check-loop (node)
5379 "Return statement in the loop body must be consistent.
5380 The default assumption for any kind of a loop is that it will eventually
5381 terminate. The only exception is a loop with a constant true condition.
5382 Code that follows such a loop is examined only if one can determine
5383 statically that there is a break out of the loop.
5384
5385 for(... ; ... ; ...) {}
5386 for(... in ... ) {}
5387 while(...) { }
5388 do { } while(...)
5389
5390 Returns logical OR of END_* flags."
5391 (let ((rv (js2-end-check (js2-loop-node-body node)))
5392 (condition (cond
5393 ((js2-while-node-p node)
5394 (js2-while-node-condition node))
5395 ((js2-do-node-p node)
5396 (js2-do-node-condition node))
5397 ((js2-for-node-p node)
5398 (js2-for-node-condition node)))))
5399
5400 ;; check to see if the loop condition is always true
5401 (if (and condition
5402 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5403 (js2-clear-flag rv js2-END_DROPS_OFF))
5404
5405 ;; look for effect of breaks
5406 (js2-set-flag rv (js2-node-get-prop node
5407 'CONTROL_BLOCK_PROP
5408 js2-END_UNREACHED))
5409 rv))
5410
5411 (defun js2-end-check-block (node)
5412 "A general block of code is examined statement by statement.
5413 If any statement (even a compound one) returns in all branches, then
5414 subsequent statements are not examined.
5415 Returns logical OR of END_* flags."
5416 (let* ((rv js2-END_DROPS_OFF)
5417 (kids (js2-block-node-kids node))
5418 (n (car kids)))
5419 ;; Check each statement. If the statement can continue onto the next
5420 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5421 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5422 (js2-clear-flag rv js2-END_DROPS_OFF)
5423 (js2-set-flag rv (js2-end-check n))
5424 (setq kids (cdr kids)
5425 n (car kids)))
5426 rv))
5427
5428 (defun js2-end-check-label (node)
5429 "A labeled statement implies that there may be a break to the label.
5430 The function processes the labeled statement and then checks the
5431 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5432 particular label.
5433 Returns logical OR of END_* flags."
5434 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5435 (logior rv (js2-node-get-prop node
5436 'CONTROL_BLOCK_PROP
5437 js2-END_UNREACHED))))
5438
5439 (defun js2-end-check-break (node)
5440 "When a break is encountered annotate the statement being broken
5441 out of by setting its CONTROL_BLOCK_PROP property.
5442 Returns logical OR of END_* flags."
5443 (and (js2-break-node-target node)
5444 (js2-node-set-prop (js2-break-node-target node)
5445 'CONTROL_BLOCK_PROP
5446 js2-END_DROPS_OFF))
5447 js2-END_UNREACHED)
5448
5449 (defun js2-end-check (node)
5450 "Examine the body of a function, doing a basic reachability analysis.
5451 Returns a combination of flags END_* flags that indicate
5452 how the function execution can terminate. These constitute only the
5453 pessimistic set of termination conditions. It is possible that at
5454 runtime certain code paths will never be actually taken. Hence this
5455 analysis will flag errors in cases where there may not be errors.
5456 Returns logical OR of END_* flags"
5457 (let (kid)
5458 (cond
5459 ((js2-break-node-p node)
5460 (js2-end-check-break node))
5461 ((js2-expr-stmt-node-p node)
5462 (if (setq kid (js2-expr-stmt-node-expr node))
5463 (js2-end-check kid)
5464 js2-END_DROPS_OFF))
5465 ((or (js2-continue-node-p node)
5466 (js2-throw-node-p node))
5467 js2-END_UNREACHED)
5468 ((js2-return-node-p node)
5469 (if (setq kid (js2-return-node-retval node))
5470 js2-END_RETURNS_VALUE
5471 js2-END_RETURNS))
5472 ((js2-loop-node-p node)
5473 (js2-end-check-loop node))
5474 ((js2-switch-node-p node)
5475 (js2-end-check-switch node))
5476 ((js2-labeled-stmt-node-p node)
5477 (js2-end-check-label node))
5478 ((js2-if-node-p node)
5479 (js2-end-check-if node))
5480 ((js2-try-node-p node)
5481 (js2-end-check-try node))
5482 ((js2-block-node-p node)
5483 (if (null (js2-block-node-kids node))
5484 js2-END_DROPS_OFF
5485 (js2-end-check-block node)))
5486 ((js2-yield-node-p node)
5487 js2-END_YIELDS)
5488 (t
5489 js2-END_DROPS_OFF))))
5490
5491 (defun js2-always-defined-boolean-p (node)
5492 "Check if NODE always evaluates to true or false in boolean context.
5493 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5494 nor always false."
5495 (let ((tt (js2-node-type node))
5496 num)
5497 (cond
5498 ((or (= tt js2-FALSE) (= tt js2-NULL))
5499 'ALWAYS_FALSE)
5500 ((= tt js2-TRUE)
5501 'ALWAYS_TRUE)
5502 ((= tt js2-NUMBER)
5503 (setq num (js2-number-node-num-value node))
5504 (if (and (not (eq num 0.0e+NaN))
5505 (not (zerop num)))
5506 'ALWAYS_TRUE
5507 'ALWAYS_FALSE))
5508 (t
5509 nil))))
5510
5511 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5512 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5513
5514 (defvar js2-tokens nil
5515 "List of all defined token names.") ; initialized in `js2-token-names'
5516
5517 (defconst js2-token-names
5518 (let* ((names (make-vector js2-num-tokens -1))
5519 (case-fold-search nil) ; only match js2-UPPER_CASE
5520 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5521 (cl-loop for sym in syms
5522 for i from 0
5523 do
5524 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5525 (not (boundp sym)))
5526 (aset names (symbol-value sym) ; code, e.g. 152
5527 (downcase
5528 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5529 (push sym js2-tokens)))
5530 names)
5531 "Vector mapping int values to token string names, sans `js2-' prefix.")
5532
5533 (defun js2-tt-name (tok)
5534 "Return a string name for TOK, a token symbol or code.
5535 Signals an error if it's not a recognized token."
5536 (let ((code tok))
5537 (if (symbolp tok)
5538 (setq code (symbol-value tok)))
5539 (if (eq code -1)
5540 "ERROR"
5541 (if (and (numberp code)
5542 (not (cl-minusp code))
5543 (< code js2-num-tokens))
5544 (aref js2-token-names code)
5545 (error "Invalid token: %s" code)))))
5546
5547 (defsubst js2-tt-sym (tok)
5548 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5549 (intern (js2-tt-name tok)))
5550
5551 (defconst js2-token-codes
5552 (let ((table (make-hash-table :test 'eq :size 256)))
5553 (cl-loop for name across js2-token-names
5554 for sym = (intern (concat "js2-" (upcase name)))
5555 do
5556 (puthash sym (symbol-value sym) table))
5557 ;; clean up a few that are "wrong" in Rhino's token codes
5558 (puthash 'js2-DELETE js2-DELPROP table)
5559 table)
5560 "Hashtable mapping token type symbols to their bytecodes.")
5561
5562 (defsubst js2-tt-code (sym)
5563 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5564 (or (gethash sym js2-token-codes)
5565 (error "Invalid token symbol: %s " sym))) ; signal code bug
5566
5567 (defun js2-report-scan-error (msg &optional no-throw beg len)
5568 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5569 (js2-report-error msg nil
5570 (or beg (js2-current-token-beg))
5571 (or len (js2-current-token-len)))
5572 (unless no-throw
5573 (throw 'return js2-ERROR)))
5574
5575 (defun js2-set-string-from-buffer (token)
5576 "Set `string' and `end' slots for TOKEN, return the string."
5577 (setf (js2-token-end token) js2-ts-cursor
5578 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5579
5580 ;; TODO: could potentially avoid a lot of consing by allocating a
5581 ;; char buffer the way Rhino does.
5582 (defsubst js2-add-to-string (c)
5583 (push c js2-ts-string-buffer))
5584
5585 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5586 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5587 ;; any other character: when it's not part of the current token, we
5588 ;; unget it, allowing it to be read again by the following call.
5589 (defsubst js2-unget-char ()
5590 (cl-decf js2-ts-cursor))
5591
5592 ;; Rhino distinguishes \r and \n line endings. We don't need to
5593 ;; because we only scan from Emacs buffers, which always use \n.
5594 (defun js2-get-char ()
5595 "Read and return the next character from the input buffer.
5596 Increments `js2-ts-lineno' if the return value is a newline char.
5597 Updates `js2-ts-cursor' to the point after the returned char.
5598 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5599 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5600 (let (c)
5601 ;; check for end of buffer
5602 (if (>= js2-ts-cursor (point-max))
5603 (setq js2-ts-hit-eof t
5604 js2-ts-cursor (1+ js2-ts-cursor)
5605 c js2-EOF_CHAR) ; return value
5606 ;; otherwise read next char
5607 (setq c (char-before (cl-incf js2-ts-cursor)))
5608 ;; if we read a newline, update counters
5609 (if (= c ?\n)
5610 (setq js2-ts-line-start js2-ts-cursor
5611 js2-ts-lineno (1+ js2-ts-lineno)))
5612 ;; TODO: skip over format characters
5613 c)))
5614
5615 (defun js2-read-unicode-escape ()
5616 "Read a \\uNNNN sequence from the input.
5617 Assumes the ?\ and ?u have already been read.
5618 Returns the unicode character, or nil if it wasn't a valid character.
5619 Doesn't change the values of any scanner variables."
5620 ;; I really wish I knew a better way to do this, but I can't
5621 ;; find the Emacs function that takes a 16-bit int and converts
5622 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5623 ;; Have to first check that it's 4 hex characters or it may stop
5624 ;; the read early.
5625 (ignore-errors
5626 (let ((s (buffer-substring-no-properties js2-ts-cursor
5627 (+ 4 js2-ts-cursor))))
5628 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5629 (read (concat "?\\u" s))))))
5630
5631 (defun js2-match-char (test)
5632 "Consume and return next character if it matches TEST, a character.
5633 Returns nil and consumes nothing if TEST is not the next character."
5634 (let ((c (js2-get-char)))
5635 (if (eq c test)
5636 t
5637 (js2-unget-char)
5638 nil)))
5639
5640 (defun js2-peek-char ()
5641 (prog1
5642 (js2-get-char)
5643 (js2-unget-char)))
5644
5645 (defun js2-identifier-start-p (c)
5646 "Is C a valid start to an ES5 Identifier?
5647 See http://es5.github.io/#x7.6"
5648 (or
5649 (memq c '(?$ ?_))
5650 (memq (get-char-code-property c 'general-category)
5651 ;; Letters
5652 '(Lu Ll Lt Lm Lo Nl))))
5653
5654 (defun js2-identifier-part-p (c)
5655 "Is C a valid part of an ES5 Identifier?
5656 See http://es5.github.io/#x7.6"
5657 (or
5658 (memq c '(?$ ?_ ?\u200c ?\u200d))
5659 (memq (get-char-code-property c 'general-category)
5660 '(;; Letters
5661 Lu Ll Lt Lm Lo Nl
5662 ;; Combining Marks
5663 Mn Mc
5664 ;; Digits
5665 Nd
5666 ;; Connector Punctuation
5667 Pc))))
5668
5669 (defun js2-alpha-p (c)
5670 (cond ((and (<= ?A c) (<= c ?Z)) t)
5671 ((and (<= ?a c) (<= c ?z)) t)
5672 (t nil)))
5673
5674 (defsubst js2-digit-p (c)
5675 (and (<= ?0 c) (<= c ?9)))
5676
5677 (defun js2-js-space-p (c)
5678 (if (<= c 127)
5679 (memq c '(#x20 #x9 #xB #xC #xD))
5680 (or
5681 (eq c #xA0)
5682 ;; TODO: change this nil to check for Unicode space character
5683 nil)))
5684
5685 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5686
5687 (defun js2-skip-line ()
5688 "Skip to end of line."
5689 (while (not (memq (js2-get-char) js2-eol-chars)))
5690 (js2-unget-char)
5691 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5692
5693 (defun js2-init-scanner (&optional buf line)
5694 "Create token stream for BUF starting on LINE.
5695 BUF defaults to `current-buffer' and LINE defaults to 1.
5696
5697 A buffer can only have one scanner active at a time, which yields
5698 dramatically simpler code than using a defstruct. If you need to
5699 have simultaneous scanners in a buffer, copy the regions to scan
5700 into temp buffers."
5701 (with-current-buffer (or buf (current-buffer))
5702 (setq js2-ts-dirty-line nil
5703 js2-ts-hit-eof nil
5704 js2-ts-line-start 0
5705 js2-ts-lineno (or line 1)
5706 js2-ts-line-end-char -1
5707 js2-ts-cursor (point-min)
5708 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5709 js2-ti-tokens-cursor 0
5710 js2-ti-lookahead 0
5711 js2-ts-is-xml-attribute nil
5712 js2-ts-xml-is-tag-content nil
5713 js2-ts-xml-open-tags-count 0
5714 js2-ts-string-buffer nil)))
5715
5716 ;; This function uses the cached op, string and number fields in
5717 ;; TokenStream; if getToken has been called since the passed token
5718 ;; was scanned, the op or string printed may be incorrect.
5719 (defun js2-token-to-string (token)
5720 ;; Not sure where this function is used in Rhino. Not tested.
5721 (if (not js2-debug-print-trees)
5722 ""
5723 (let ((name (js2-tt-name token)))
5724 (cond
5725 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5726 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5727 (concat name " `" (js2-current-token-string) "'"))
5728 ((eq token js2-NUMBER)
5729 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5730 (t
5731 name)))))
5732
5733 (defconst js2-keywords
5734 '(break
5735 case catch class const continue
5736 debugger default delete do
5737 else extends export
5738 false finally for function
5739 if in instanceof import
5740 let
5741 new null
5742 return
5743 super switch
5744 this throw true try typeof
5745 var void
5746 while with
5747 yield))
5748
5749 ;; Token names aren't exactly the same as the keywords, unfortunately.
5750 ;; E.g. delete is js2-DELPROP.
5751 (defconst js2-kwd-tokens
5752 (let ((table (make-vector js2-num-tokens nil))
5753 (tokens
5754 (list js2-BREAK
5755 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5756 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5757 js2-ELSE js2-EXPORT
5758 js2-ELSE js2-EXTENDS js2-EXPORT
5759 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5760 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5761 js2-LET
5762 js2-NEW js2-NULL
5763 js2-RETURN
5764 js2-SUPER js2-SWITCH
5765 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5766 js2-VAR
5767 js2-WHILE js2-WITH
5768 js2-YIELD)))
5769 (dolist (i tokens)
5770 (aset table i 'font-lock-keyword-face))
5771 (aset table js2-STRING 'font-lock-string-face)
5772 (aset table js2-REGEXP 'font-lock-string-face)
5773 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5774 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5775 (aset table js2-COMMENT 'font-lock-comment-face)
5776 (aset table js2-THIS 'font-lock-builtin-face)
5777 (aset table js2-SUPER 'font-lock-builtin-face)
5778 (aset table js2-VOID 'font-lock-constant-face)
5779 (aset table js2-NULL 'font-lock-constant-face)
5780 (aset table js2-TRUE 'font-lock-constant-face)
5781 (aset table js2-FALSE 'font-lock-constant-face)
5782 (aset table js2-NOT 'font-lock-negation-char-face)
5783 table)
5784 "Vector whose values are non-nil for tokens that are keywords.
5785 The values are default faces to use for highlighting the keywords.")
5786
5787 ;; FIXME: Support strict mode-only future reserved words, after we know
5788 ;; which parts scopes are in strict mode, and which are not.
5789 (defconst js2-reserved-words '(class enum export extends import static super)
5790 "Future reserved keywords in ECMAScript 5.1.")
5791
5792 (defconst js2-keyword-names
5793 (let ((table (make-hash-table :test 'equal)))
5794 (cl-loop for k in js2-keywords
5795 do (puthash
5796 (symbol-name k) ; instanceof
5797 (intern (concat "js2-"
5798 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5799 table))
5800 table)
5801 "JavaScript keywords by name, mapped to their symbols.")
5802
5803 (defconst js2-reserved-word-names
5804 (let ((table (make-hash-table :test 'equal)))
5805 (cl-loop for k in js2-reserved-words
5806 do
5807 (puthash (symbol-name k) 'js2-RESERVED table))
5808 table)
5809 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5810
5811 (defun js2-collect-string (buf)
5812 "Convert BUF, a list of chars, to a string.
5813 Reverses BUF before converting."
5814 (if buf
5815 (apply #'string (nreverse buf))
5816 ""))
5817
5818 (defun js2-string-to-keyword (s)
5819 "Return token for S, a string, if S is a keyword or reserved word.
5820 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5821 (or (gethash s js2-keyword-names)
5822 (gethash s js2-reserved-word-names)))
5823
5824 (defsubst js2-ts-set-char-token-bounds (token)
5825 "Used when next token is one character."
5826 (setf (js2-token-beg token) (1- js2-ts-cursor)
5827 (js2-token-end token) js2-ts-cursor))
5828
5829 (defsubst js2-ts-return (token type)
5830 "Update the `end' and `type' slots of TOKEN,
5831 then throw `return' with value TYPE."
5832 (setf (js2-token-end token) js2-ts-cursor
5833 (js2-token-type token) type)
5834 (throw 'return type))
5835
5836 (defun js2-x-digit-to-int (c accumulator)
5837 "Build up a hex number.
5838 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5839 corresponding number. Otherwise return -1."
5840 (catch 'return
5841 (catch 'check
5842 ;; Use 0..9 < A..Z < a..z
5843 (cond
5844 ((<= c ?9)
5845 (cl-decf c ?0)
5846 (if (<= 0 c)
5847 (throw 'check nil)))
5848 ((<= c ?F)
5849 (when (<= ?A c)
5850 (cl-decf c (- ?A 10))
5851 (throw 'check nil)))
5852 ((<= c ?f)
5853 (when (<= ?a c)
5854 (cl-decf c (- ?a 10))
5855 (throw 'check nil))))
5856 (throw 'return -1))
5857 (logior c (lsh accumulator 4))))
5858
5859 (defun js2-get-token (&optional modifier)
5860 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5861 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5862 next saved token.
5863
5864 This function will not return a newline (js2-EOL) - instead, it
5865 gobbles newlines until it finds a non-newline token. Call
5866 `js2-peek-token-or-eol' when you care about newlines.
5867
5868 This function will also not return a js2-COMMENT. Instead, it
5869 records comments found in `js2-scanned-comments'. If the token
5870 returned by this function immediately follows a jsdoc comment,
5871 the token is flagged as such."
5872 (if (zerop js2-ti-lookahead)
5873 (js2-get-token-internal modifier)
5874 (cl-decf js2-ti-lookahead)
5875 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5876 (let ((tt (js2-current-token-type)))
5877 (cl-assert (not (= tt js2-EOL)))
5878 tt)))
5879
5880 (defun js2-unget-token ()
5881 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5882 (cl-incf js2-ti-lookahead)
5883 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5884
5885 (defun js2-get-token-internal (modifier)
5886 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5887 (tt (js2-token-type token))
5888 saw-eol
5889 face)
5890 ;; process comments
5891 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5892 (if (= tt js2-EOL)
5893 (setq saw-eol t)
5894 (setq saw-eol nil)
5895 (when js2-record-comments
5896 (js2-record-comment token)))
5897 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5898 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5899 tt (js2-token-type token)))
5900
5901 (when saw-eol
5902 (setf (js2-token-follows-eol-p token) t))
5903
5904 ;; perform lexical fontification as soon as token is scanned
5905 (when js2-parse-ide-mode
5906 (cond
5907 ((cl-minusp tt)
5908 (js2-record-face 'js2-error token))
5909 ((setq face (aref js2-kwd-tokens tt))
5910 (js2-record-face face token))
5911 ((and (= tt js2-NAME)
5912 (equal (js2-token-string token) "undefined"))
5913 (js2-record-face 'font-lock-constant-face token))))
5914 tt))
5915
5916 (defsubst js2-string-to-number (str base)
5917 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5918 (condition-case nil
5919 (string-to-number str base)
5920 (overflow-error -1)))
5921
5922 (defun js2-get-token-internal-1 (modifier)
5923 "Return next JavaScript token type, an int such as js2-RETURN.
5924 During operation, creates an instance of `js2-token' struct, sets
5925 its relevant fields and puts it into `js2-ti-tokens'."
5926 (let (identifier-start
5927 is-unicode-escape-start c
5928 contains-escape escape-val str result base
5929 look-for-slash continue tt
5930 (token (js2-new-token 0)))
5931 (setq
5932 tt
5933 (catch 'return
5934 (when (eq modifier 'TEMPLATE_TAIL)
5935 (setf (js2-token-beg token) (1- js2-ts-cursor))
5936 (throw 'return (js2-get-string-or-template-token ?` token)))
5937 (while t
5938 ;; Eat whitespace, possibly sensitive to newlines.
5939 (setq continue t)
5940 (while continue
5941 (setq c (js2-get-char))
5942 (cond
5943 ((eq c js2-EOF_CHAR)
5944 (js2-unget-char)
5945 (js2-ts-set-char-token-bounds token)
5946 (throw 'return js2-EOF))
5947 ((eq c ?\n)
5948 (js2-ts-set-char-token-bounds token)
5949 (setq js2-ts-dirty-line nil)
5950 (throw 'return js2-EOL))
5951 ((not (js2-js-space-p c))
5952 (if (/= c ?-) ; in case end of HTML comment
5953 (setq js2-ts-dirty-line t))
5954 (setq continue nil))))
5955 ;; Assume the token will be 1 char - fixed up below.
5956 (js2-ts-set-char-token-bounds token)
5957 (when (eq c ?@)
5958 (throw 'return js2-XMLATTR))
5959 ;; identifier/keyword/instanceof?
5960 ;; watch out for starting with a <backslash>
5961 (cond
5962 ((eq c ?\\)
5963 (setq c (js2-get-char))
5964 (if (eq c ?u)
5965 (setq identifier-start t
5966 is-unicode-escape-start t
5967 js2-ts-string-buffer nil)
5968 (setq identifier-start nil)
5969 (js2-unget-char)
5970 (setq c ?\\)))
5971 (t
5972 (when (setq identifier-start (js2-identifier-start-p c))
5973 (setq js2-ts-string-buffer nil)
5974 (js2-add-to-string c))))
5975 (when identifier-start
5976 (setq contains-escape is-unicode-escape-start)
5977 (catch 'break
5978 (while t
5979 (if is-unicode-escape-start
5980 ;; strictly speaking we should probably push-back
5981 ;; all the bad characters if the <backslash>uXXXX
5982 ;; sequence is malformed. But since there isn't a
5983 ;; correct context(is there?) for a bad Unicode
5984 ;; escape sequence in an identifier, we can report
5985 ;; an error here.
5986 (progn
5987 (setq escape-val 0)
5988 (dotimes (_ 4)
5989 (setq c (js2-get-char)
5990 escape-val (js2-x-digit-to-int c escape-val))
5991 ;; Next check takes care of c < 0 and bad escape
5992 (if (cl-minusp escape-val)
5993 (throw 'break nil)))
5994 (if (cl-minusp escape-val)
5995 (js2-report-scan-error "msg.invalid.escape" t))
5996 (js2-add-to-string escape-val)
5997 (setq is-unicode-escape-start nil))
5998 (setq c (js2-get-char))
5999 (cond
6000 ((eq c ?\\)
6001 (setq c (js2-get-char))
6002 (if (eq c ?u)
6003 (setq is-unicode-escape-start t
6004 contains-escape t)
6005 (js2-report-scan-error "msg.illegal.character" t)))
6006 (t
6007 (if (or (eq c js2-EOF_CHAR)
6008 (not (js2-identifier-part-p c)))
6009 (throw 'break nil))
6010 (js2-add-to-string c))))))
6011 (js2-unget-char)
6012 (setf str (js2-collect-string js2-ts-string-buffer)
6013 (js2-token-end token) js2-ts-cursor)
6014 ;; FIXME: Invalid in ES5 and ES6, see
6015 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
6016 ;; Probably should just drop this conditional.
6017 (unless contains-escape
6018 ;; OPT we shouldn't have to make a string (object!) to
6019 ;; check if it's a keyword.
6020 ;; Return the corresponding token if it's a keyword
6021 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
6022 (setq result (js2-string-to-keyword str)))
6023 (if (and (< js2-language-version 170)
6024 (memq result '(js2-LET js2-YIELD)))
6025 ;; LET and YIELD are tokens only in 1.7 and later
6026 (setq result 'js2-NAME))
6027 (when (eq result 'js2-RESERVED)
6028 (setf (js2-token-string token) str))
6029 (throw 'return (js2-tt-code result))))
6030 ;; If we want to intern these as Rhino does, just use (intern str)
6031 (setf (js2-token-string token) str)
6032 (throw 'return js2-NAME)) ; end identifier/kwd check
6033 ;; is it a number?
6034 (when (or (js2-digit-p c)
6035 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
6036 (setq js2-ts-string-buffer nil
6037 base 10)
6038 (when (eq c ?0)
6039 (setq c (js2-get-char))
6040 (cond
6041 ((or (eq c ?x) (eq c ?X))
6042 (setq base 16)
6043 (setq c (js2-get-char)))
6044 ((and (or (eq c ?b) (eq c ?B))
6045 (>= js2-language-version 200))
6046 (setq base 2)
6047 (setq c (js2-get-char)))
6048 ((and (or (eq c ?o) (eq c ?O))
6049 (>= js2-language-version 200))
6050 (setq base 8)
6051 (setq c (js2-get-char)))
6052 ((js2-digit-p c)
6053 (setq base 'maybe-8))
6054 (t
6055 (js2-add-to-string ?0))))
6056 (cond
6057 ((eq base 16)
6058 (if (> 0 (js2-x-digit-to-int c 0))
6059 (js2-report-scan-error "msg.missing.hex.digits")
6060 (while (<= 0 (js2-x-digit-to-int c 0))
6061 (js2-add-to-string c)
6062 (setq c (js2-get-char)))))
6063 ((eq base 2)
6064 (if (not (memq c '(?0 ?1)))
6065 (js2-report-scan-error "msg.missing.binary.digits")
6066 (while (memq c '(?0 ?1))
6067 (js2-add-to-string c)
6068 (setq c (js2-get-char)))))
6069 ((eq base 8)
6070 (if (or (> ?0 c) (< ?7 c))
6071 (js2-report-scan-error "msg.missing.octal.digits")
6072 (while (and (<= ?0 c) (>= ?7 c))
6073 (js2-add-to-string c)
6074 (setq c (js2-get-char)))))
6075 (t
6076 (while (and (<= ?0 c) (<= c ?9))
6077 ;; We permit 08 and 09 as decimal numbers, which
6078 ;; makes our behavior a superset of the ECMA
6079 ;; numeric grammar. We might not always be so
6080 ;; permissive, so we warn about it.
6081 (when (and (eq base 'maybe-8) (>= c ?8))
6082 (js2-report-warning "msg.bad.octal.literal"
6083 (if (eq c ?8) "8" "9"))
6084 (setq base 10))
6085 (js2-add-to-string c)
6086 (setq c (js2-get-char)))
6087 (when (eq base 'maybe-8)
6088 (setq base 8))))
6089 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6090 (when (eq c ?.)
6091 (cl-loop do
6092 (js2-add-to-string c)
6093 (setq c (js2-get-char))
6094 while (js2-digit-p c)))
6095 (when (memq c '(?e ?E))
6096 (js2-add-to-string c)
6097 (setq c (js2-get-char))
6098 (when (memq c '(?+ ?-))
6099 (js2-add-to-string c)
6100 (setq c (js2-get-char)))
6101 (unless (js2-digit-p c)
6102 (js2-report-scan-error "msg.missing.exponent" t))
6103 (cl-loop do
6104 (js2-add-to-string c)
6105 (setq c (js2-get-char))
6106 while (js2-digit-p c))))
6107 (js2-unget-char)
6108 (let ((str (js2-set-string-from-buffer token)))
6109 (setf (js2-token-number token)
6110 (js2-string-to-number str base)))
6111 (throw 'return js2-NUMBER))
6112 ;; is it a string?
6113 (when (or (memq c '(?\" ?\'))
6114 (and (>= js2-language-version 200)
6115 (= c ?`)))
6116 (throw 'return
6117 (js2-get-string-or-template-token c token)))
6118 (js2-ts-return token
6119 (cl-case c
6120 (?\;
6121 (throw 'return js2-SEMI))
6122 (?\[
6123 (throw 'return js2-LB))
6124 (?\]
6125 (throw 'return js2-RB))
6126 (?{
6127 (throw 'return js2-LC))
6128 (?}
6129 (throw 'return js2-RC))
6130 (?\(
6131 (throw 'return js2-LP))
6132 (?\)
6133 (throw 'return js2-RP))
6134 (?,
6135 (throw 'return js2-COMMA))
6136 (??
6137 (throw 'return js2-HOOK))
6138 (?:
6139 (if (js2-match-char ?:)
6140 js2-COLONCOLON
6141 (throw 'return js2-COLON)))
6142 (?.
6143 (if (js2-match-char ?.)
6144 (if (js2-match-char ?.)
6145 js2-TRIPLEDOT js2-DOTDOT)
6146 (if (js2-match-char ?\()
6147 js2-DOTQUERY
6148 (throw 'return js2-DOT))))
6149 (?|
6150 (if (js2-match-char ?|)
6151 (throw 'return js2-OR)
6152 (if (js2-match-char ?=)
6153 js2-ASSIGN_BITOR
6154 (throw 'return js2-BITOR))))
6155 (?^
6156 (if (js2-match-char ?=)
6157 js2-ASSIGN_BITOR
6158 (throw 'return js2-BITXOR)))
6159 (?&
6160 (if (js2-match-char ?&)
6161 (throw 'return js2-AND)
6162 (if (js2-match-char ?=)
6163 js2-ASSIGN_BITAND
6164 (throw 'return js2-BITAND))))
6165 (?=
6166 (if (js2-match-char ?=)
6167 (if (js2-match-char ?=)
6168 js2-SHEQ
6169 (throw 'return js2-EQ))
6170 (if (js2-match-char ?>)
6171 (js2-ts-return token js2-ARROW)
6172 (throw 'return js2-ASSIGN))))
6173 (?!
6174 (if (js2-match-char ?=)
6175 (if (js2-match-char ?=)
6176 js2-SHNE
6177 js2-NE)
6178 (throw 'return js2-NOT)))
6179 (?<
6180 ;; NB:treat HTML begin-comment as comment-till-eol
6181 (when (js2-match-char ?!)
6182 (when (js2-match-char ?-)
6183 (when (js2-match-char ?-)
6184 (js2-skip-line)
6185 (setf (js2-token-comment-type (js2-current-token)) 'html)
6186 (throw 'return js2-COMMENT)))
6187 (js2-unget-char))
6188 (if (js2-match-char ?<)
6189 (if (js2-match-char ?=)
6190 js2-ASSIGN_LSH
6191 js2-LSH)
6192 (if (js2-match-char ?=)
6193 js2-LE
6194 (throw 'return js2-LT))))
6195 (?>
6196 (if (js2-match-char ?>)
6197 (if (js2-match-char ?>)
6198 (if (js2-match-char ?=)
6199 js2-ASSIGN_URSH
6200 js2-URSH)
6201 (if (js2-match-char ?=)
6202 js2-ASSIGN_RSH
6203 js2-RSH))
6204 (if (js2-match-char ?=)
6205 js2-GE
6206 (throw 'return js2-GT))))
6207 (?*
6208 (if (js2-match-char ?=)
6209 js2-ASSIGN_MUL
6210 (throw 'return js2-MUL)))
6211 (?/
6212 ;; is it a // comment?
6213 (when (js2-match-char ?/)
6214 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6215 (js2-skip-line)
6216 (setf (js2-token-comment-type token) 'line)
6217 ;; include newline so highlighting goes to end of
6218 ;; window, if there actually is a newline; if we
6219 ;; hit eof, then implicitly there isn't
6220 (unless js2-ts-hit-eof
6221 (cl-incf (js2-token-end token)))
6222 (throw 'return js2-COMMENT))
6223 ;; is it a /* comment?
6224 (when (js2-match-char ?*)
6225 (setf look-for-slash nil
6226 (js2-token-beg token) (- js2-ts-cursor 2)
6227 (js2-token-comment-type token)
6228 (if (js2-match-char ?*)
6229 (progn
6230 (setq look-for-slash t)
6231 'jsdoc)
6232 'block))
6233 (while t
6234 (setq c (js2-get-char))
6235 (cond
6236 ((eq c js2-EOF_CHAR)
6237 (setf (js2-token-end token) (1- js2-ts-cursor))
6238 (js2-report-error "msg.unterminated.comment")
6239 (throw 'return js2-COMMENT))
6240 ((eq c ?*)
6241 (setq look-for-slash t))
6242 ((eq c ?/)
6243 (if look-for-slash
6244 (js2-ts-return token js2-COMMENT)))
6245 (t
6246 (setf look-for-slash nil
6247 (js2-token-end token) js2-ts-cursor)))))
6248 (if (js2-match-char ?=)
6249 js2-ASSIGN_DIV
6250 (throw 'return js2-DIV)))
6251 (?#
6252 (when js2-skip-preprocessor-directives
6253 (js2-skip-line)
6254 (setf (js2-token-comment-type token) 'preprocessor
6255 (js2-token-end token) js2-ts-cursor)
6256 (throw 'return js2-COMMENT))
6257 (throw 'return js2-ERROR))
6258 (?%
6259 (if (js2-match-char ?=)
6260 js2-ASSIGN_MOD
6261 (throw 'return js2-MOD)))
6262 (?~
6263 (throw 'return js2-BITNOT))
6264 (?+
6265 (if (js2-match-char ?=)
6266 js2-ASSIGN_ADD
6267 (if (js2-match-char ?+)
6268 js2-INC
6269 (throw 'return js2-ADD))))
6270 (?-
6271 (cond
6272 ((js2-match-char ?=)
6273 (setq c js2-ASSIGN_SUB))
6274 ((js2-match-char ?-)
6275 (unless js2-ts-dirty-line
6276 ;; treat HTML end-comment after possible whitespace
6277 ;; after line start as comment-until-eol
6278 (when (js2-match-char ?>)
6279 (js2-skip-line)
6280 (setf (js2-token-comment-type (js2-current-token)) 'html)
6281 (throw 'return js2-COMMENT)))
6282 (setq c js2-DEC))
6283 (t
6284 (setq c js2-SUB)))
6285 (setq js2-ts-dirty-line t)
6286 c)
6287 (otherwise
6288 (js2-report-scan-error "msg.illegal.character")))))))
6289 (setf (js2-token-type token) tt)
6290 token))
6291
6292 (defun js2-get-string-or-template-token (quote-char token)
6293 ;; We attempt to accumulate a string the fast way, by
6294 ;; building it directly out of the reader. But if there
6295 ;; are any escaped characters in the string, we revert to
6296 ;; building it out of a string buffer.
6297 (let ((c (js2-get-char))
6298 js2-ts-string-buffer
6299 nc c1 val escape-val)
6300 (catch 'break
6301 (while (/= c quote-char)
6302 (catch 'continue
6303 (when (eq c js2-EOF_CHAR)
6304 (js2-unget-char)
6305 (js2-report-error "msg.unterminated.string.lit")
6306 (throw 'break nil))
6307 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6308 (js2-unget-char)
6309 (js2-report-error "msg.unterminated.string.lit")
6310 (throw 'break nil))
6311 (when (eq c ?\\)
6312 ;; We've hit an escaped character
6313 (setq c (js2-get-char))
6314 (cl-case c
6315 (?b (setq c ?\b))
6316 (?f (setq c ?\f))
6317 (?n (setq c ?\n))
6318 (?r (setq c ?\r))
6319 (?t (setq c ?\t))
6320 (?v (setq c ?\v))
6321 (?u
6322 (setq c1 (js2-read-unicode-escape))
6323 (if js2-parse-ide-mode
6324 (if c1
6325 (progn
6326 ;; just copy the string in IDE-mode
6327 (js2-add-to-string ?\\)
6328 (js2-add-to-string ?u)
6329 (dotimes (_ 3)
6330 (js2-add-to-string (js2-get-char)))
6331 (setq c (js2-get-char))) ; added at end of loop
6332 ;; flag it as an invalid escape
6333 (js2-report-warning "msg.invalid.escape"
6334 nil (- js2-ts-cursor 2) 6))
6335 ;; Get 4 hex digits; if the u escape is not
6336 ;; followed by 4 hex digits, use 'u' + the
6337 ;; literal character sequence that follows.
6338 (js2-add-to-string ?u)
6339 (setq escape-val 0)
6340 (dotimes (_ 4)
6341 (setq c (js2-get-char)
6342 escape-val (js2-x-digit-to-int c escape-val))
6343 (if (cl-minusp escape-val)
6344 (throw 'continue nil))
6345 (js2-add-to-string c))
6346 ;; prepare for replace of stored 'u' sequence by escape value
6347 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6348 c escape-val)))
6349 (?x
6350 ;; Get 2 hex digits, defaulting to 'x'+literal
6351 ;; sequence, as above.
6352 (setq c (js2-get-char)
6353 escape-val (js2-x-digit-to-int c 0))
6354 (if (cl-minusp escape-val)
6355 (progn
6356 (js2-add-to-string ?x)
6357 (throw 'continue nil))
6358 (setq c1 c
6359 c (js2-get-char)
6360 escape-val (js2-x-digit-to-int c escape-val))
6361 (if (cl-minusp escape-val)
6362 (progn
6363 (js2-add-to-string ?x)
6364 (js2-add-to-string c1)
6365 (throw 'continue nil))
6366 ;; got 2 hex digits
6367 (setq c escape-val))))
6368 (?\n
6369 ;; Remove line terminator after escape to follow
6370 ;; SpiderMonkey and C/C++
6371 (setq c (js2-get-char))
6372 (throw 'continue nil))
6373 (t
6374 (when (and (<= ?0 c) (< c ?8))
6375 (setq val (- c ?0)
6376 c (js2-get-char))
6377 (when (and (<= ?0 c) (< c ?8))
6378 (setq val (- (+ (* 8 val) c) ?0)
6379 c (js2-get-char))
6380 (when (and (<= ?0 c)
6381 (< c ?8)
6382 (< val #o37))
6383 ;; c is 3rd char of octal sequence only
6384 ;; if the resulting val <= 0377
6385 (setq val (- (+ (* 8 val) c) ?0)
6386 c (js2-get-char))))
6387 (js2-unget-char)
6388 (setq c val)))))
6389 (when (and (eq quote-char ?`) (eq c ?$))
6390 (when (eq (setq nc (js2-get-char)) ?\{)
6391 (throw 'break nil))
6392 (js2-unget-char))
6393 (js2-add-to-string c)
6394 (setq c (js2-get-char)))))
6395 (js2-set-string-from-buffer token)
6396 (if (not (eq quote-char ?`))
6397 js2-STRING
6398 (if (and (eq c ?$) (eq nc ?\{))
6399 js2-TEMPLATE_HEAD
6400 js2-NO_SUBS_TEMPLATE))))
6401
6402 (defun js2-read-regexp (start-tt)
6403 "Called by parser when it gets / or /= in literal context."
6404 (let (c err
6405 in-class ; inside a '[' .. ']' character-class
6406 flags
6407 (continue t)
6408 (token (js2-new-token 0)))
6409 (setq js2-ts-string-buffer nil)
6410 (if (eq start-tt js2-ASSIGN_DIV)
6411 ;; mis-scanned /=
6412 (js2-add-to-string ?=)
6413 (if (not (eq start-tt js2-DIV))
6414 (error "failed assertion")))
6415 (while (and (not err)
6416 (or (/= (setq c (js2-get-char)) ?/)
6417 in-class))
6418 (cond
6419 ((or (= c ?\n)
6420 (= c js2-EOF_CHAR))
6421 (setf (js2-token-end token) (1- js2-ts-cursor)
6422 err t
6423 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6424 (js2-report-error "msg.unterminated.re.lit"))
6425 (t (cond
6426 ((= c ?\\)
6427 (js2-add-to-string c)
6428 (setq c (js2-get-char)))
6429 ((= c ?\[)
6430 (setq in-class t))
6431 ((= c ?\])
6432 (setq in-class nil)))
6433 (js2-add-to-string c))))
6434 (unless err
6435 (while continue
6436 (cond
6437 ((js2-match-char ?g)
6438 (push ?g flags))
6439 ((js2-match-char ?i)
6440 (push ?i flags))
6441 ((js2-match-char ?m)
6442 (push ?m flags))
6443 ((and (js2-match-char ?u)
6444 (>= js2-language-version 200))
6445 (push ?u flags))
6446 ((and (js2-match-char ?y)
6447 (>= js2-language-version 200))
6448 (push ?y flags))
6449 (t
6450 (setq continue nil))))
6451 (if (js2-alpha-p (js2-peek-char))
6452 (js2-report-scan-error "msg.invalid.re.flag" t
6453 js2-ts-cursor 1))
6454 (js2-set-string-from-buffer token))
6455 (js2-collect-string flags)))
6456
6457 (defun js2-get-first-xml-token ()
6458 (setq js2-ts-xml-open-tags-count 0
6459 js2-ts-is-xml-attribute nil
6460 js2-ts-xml-is-tag-content nil)
6461 (js2-unget-char)
6462 (js2-get-next-xml-token))
6463
6464 (defun js2-xml-discard-string (token)
6465 "Throw away the string in progress and flag an XML parse error."
6466 (setf js2-ts-string-buffer nil
6467 (js2-token-string token) nil)
6468 (js2-report-scan-error "msg.XML.bad.form" t))
6469
6470 (defun js2-get-next-xml-token ()
6471 (setq js2-ts-string-buffer nil) ; for recording the XML
6472 (let ((token (js2-new-token 0))
6473 c result)
6474 (setq result
6475 (catch 'return
6476 (while t
6477 (setq c (js2-get-char))
6478 (cond
6479 ((= c js2-EOF_CHAR)
6480 (throw 'return js2-ERROR))
6481 (js2-ts-xml-is-tag-content
6482 (cl-case c
6483 (?>
6484 (js2-add-to-string c)
6485 (setq js2-ts-xml-is-tag-content nil
6486 js2-ts-is-xml-attribute nil))
6487 (?/
6488 (js2-add-to-string c)
6489 (when (eq ?> (js2-peek-char))
6490 (setq c (js2-get-char))
6491 (js2-add-to-string c)
6492 (setq js2-ts-xml-is-tag-content nil)
6493 (cl-decf js2-ts-xml-open-tags-count)))
6494 (?{
6495 (js2-unget-char)
6496 (js2-set-string-from-buffer token)
6497 (throw 'return js2-XML))
6498 ((?\' ?\")
6499 (js2-add-to-string c)
6500 (unless (js2-read-quoted-string c token)
6501 (throw 'return js2-ERROR)))
6502 (?=
6503 (js2-add-to-string c)
6504 (setq js2-ts-is-xml-attribute t))
6505 ((? ?\t ?\r ?\n)
6506 (js2-add-to-string c))
6507 (t
6508 (js2-add-to-string c)
6509 (setq js2-ts-is-xml-attribute nil)))
6510 (when (and (not js2-ts-xml-is-tag-content)
6511 (zerop js2-ts-xml-open-tags-count))
6512 (js2-set-string-from-buffer token)
6513 (throw 'return js2-XMLEND)))
6514 (t
6515 ;; else not tag content
6516 (cl-case c
6517 (?<
6518 (js2-add-to-string c)
6519 (setq c (js2-peek-char))
6520 (cl-case c
6521 (?!
6522 (setq c (js2-get-char)) ;; skip !
6523 (js2-add-to-string c)
6524 (setq c (js2-peek-char))
6525 (cl-case c
6526 (?-
6527 (setq c (js2-get-char)) ;; skip -
6528 (js2-add-to-string c)
6529 (if (eq c ?-)
6530 (progn
6531 (js2-add-to-string c)
6532 (unless (js2-read-xml-comment token)
6533 (throw 'return js2-ERROR)))
6534 (js2-xml-discard-string token)
6535 (throw 'return js2-ERROR)))
6536 (?\[
6537 (setq c (js2-get-char)) ;; skip [
6538 (js2-add-to-string c)
6539 (if (and (= (js2-get-char) ?C)
6540 (= (js2-get-char) ?D)
6541 (= (js2-get-char) ?A)
6542 (= (js2-get-char) ?T)
6543 (= (js2-get-char) ?A)
6544 (= (js2-get-char) ?\[))
6545 (progn
6546 (js2-add-to-string ?C)
6547 (js2-add-to-string ?D)
6548 (js2-add-to-string ?A)
6549 (js2-add-to-string ?T)
6550 (js2-add-to-string ?A)
6551 (js2-add-to-string ?\[)
6552 (unless (js2-read-cdata token)
6553 (throw 'return js2-ERROR)))
6554 (js2-xml-discard-string token)
6555 (throw 'return js2-ERROR)))
6556 (t
6557 (unless (js2-read-entity token)
6558 (throw 'return js2-ERROR))))
6559 ;; Allow bare CDATA section, e.g.:
6560 ;; let xml = <![CDATA[ foo bar baz ]]>;
6561 (when (zerop js2-ts-xml-open-tags-count)
6562 (throw 'return js2-XMLEND)))
6563 (??
6564 (setq c (js2-get-char)) ;; skip ?
6565 (js2-add-to-string c)
6566 (unless (js2-read-PI token)
6567 (throw 'return js2-ERROR)))
6568 (?/
6569 ;; end tag
6570 (setq c (js2-get-char)) ;; skip /
6571 (js2-add-to-string c)
6572 (when (zerop js2-ts-xml-open-tags-count)
6573 (js2-xml-discard-string token)
6574 (throw 'return js2-ERROR))
6575 (setq js2-ts-xml-is-tag-content t)
6576 (cl-decf js2-ts-xml-open-tags-count))
6577 (t
6578 ;; start tag
6579 (setq js2-ts-xml-is-tag-content t)
6580 (cl-incf js2-ts-xml-open-tags-count))))
6581 (?{
6582 (js2-unget-char)
6583 (js2-set-string-from-buffer token)
6584 (throw 'return js2-XML))
6585 (t
6586 (js2-add-to-string c))))))))
6587 (setf (js2-token-end token) js2-ts-cursor)
6588 (setf (js2-token-type token) result)
6589 result))
6590
6591 (defun js2-read-quoted-string (quote token)
6592 (let (c)
6593 (catch 'return
6594 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6595 (js2-add-to-string c)
6596 (if (eq c quote)
6597 (throw 'return t)))
6598 (js2-xml-discard-string token) ;; throw away string in progress
6599 nil)))
6600
6601 (defun js2-read-xml-comment (token)
6602 (let ((c (js2-get-char)))
6603 (catch 'return
6604 (while (/= c js2-EOF_CHAR)
6605 (catch 'continue
6606 (js2-add-to-string c)
6607 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6608 (setq c (js2-get-char))
6609 (js2-add-to-string c)
6610 (if (eq (js2-peek-char) ?>)
6611 (progn
6612 (setq c (js2-get-char)) ;; skip >
6613 (js2-add-to-string c)
6614 (throw 'return t))
6615 (throw 'continue nil)))
6616 (setq c (js2-get-char))))
6617 (js2-xml-discard-string token)
6618 nil)))
6619
6620 (defun js2-read-cdata (token)
6621 (let ((c (js2-get-char)))
6622 (catch 'return
6623 (while (/= c js2-EOF_CHAR)
6624 (catch 'continue
6625 (js2-add-to-string c)
6626 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6627 (setq c (js2-get-char))
6628 (js2-add-to-string c)
6629 (if (eq (js2-peek-char) ?>)
6630 (progn
6631 (setq c (js2-get-char)) ;; Skip >
6632 (js2-add-to-string c)
6633 (throw 'return t))
6634 (throw 'continue nil)))
6635 (setq c (js2-get-char))))
6636 (js2-xml-discard-string token)
6637 nil)))
6638
6639 (defun js2-read-entity (token)
6640 (let ((decl-tags 1)
6641 c)
6642 (catch 'return
6643 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6644 (js2-add-to-string c)
6645 (cl-case c
6646 (?<
6647 (cl-incf decl-tags))
6648 (?>
6649 (cl-decf decl-tags)
6650 (if (zerop decl-tags)
6651 (throw 'return t)))))
6652 (js2-xml-discard-string token)
6653 nil)))
6654
6655 (defun js2-read-PI (token)
6656 "Scan an XML processing instruction."
6657 (let (c)
6658 (catch 'return
6659 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6660 (js2-add-to-string c)
6661 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6662 (setq c (js2-get-char)) ;; Skip >
6663 (js2-add-to-string c)
6664 (throw 'return t)))
6665 (js2-xml-discard-string token)
6666 nil)))
6667
6668 ;;; Highlighting
6669
6670 (defun js2-set-face (beg end face &optional record)
6671 "Fontify a region. If RECORD is non-nil, record for later."
6672 (when (cl-plusp js2-highlight-level)
6673 (setq beg (min (point-max) beg)
6674 beg (max (point-min) beg)
6675 end (min (point-max) end)
6676 end (max (point-min) end))
6677 (if record
6678 (push (list beg end face) js2-mode-fontifications)
6679 (put-text-property beg end 'font-lock-face face))))
6680
6681 (defsubst js2-clear-face (beg end)
6682 (remove-text-properties beg end '(font-lock-face nil
6683 help-echo nil
6684 point-entered nil
6685 cursor-sensor-functions nil
6686 c-in-sws nil)))
6687
6688 (defconst js2-ecma-global-props
6689 (concat "^"
6690 (regexp-opt
6691 '("Infinity" "NaN" "undefined" "arguments") t)
6692 "$")
6693 "Value properties of the Ecma-262 Global Object.
6694 Shown at or above `js2-highlight-level' 2.")
6695
6696 ;; might want to add the name "arguments" to this list?
6697 (defconst js2-ecma-object-props
6698 (concat "^"
6699 (regexp-opt
6700 '("prototype" "__proto__" "__parent__") t)
6701 "$")
6702 "Value properties of the Ecma-262 Object constructor.
6703 Shown at or above `js2-highlight-level' 2.")
6704
6705 (defconst js2-ecma-global-funcs
6706 (concat
6707 "^"
6708 (regexp-opt
6709 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6710 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6711 "$")
6712 "Function properties of the Ecma-262 Global object.
6713 Shown at or above `js2-highlight-level' 2.")
6714
6715 (defconst js2-ecma-number-props
6716 (concat "^"
6717 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6718 "NEGATIVE_INFINITY"
6719 "POSITIVE_INFINITY") t)
6720 "$")
6721 "Properties of the Ecma-262 Number constructor.
6722 Shown at or above `js2-highlight-level' 2.")
6723
6724 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6725 "Properties of the Ecma-262 Date constructor.
6726 Shown at or above `js2-highlight-level' 2.")
6727
6728 (defconst js2-ecma-math-props
6729 (concat "^"
6730 (regexp-opt
6731 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6732 t)
6733 "$")
6734 "Properties of the Ecma-262 Math object.
6735 Shown at or above `js2-highlight-level' 2.")
6736
6737 (defconst js2-ecma-math-funcs
6738 (concat "^"
6739 (regexp-opt
6740 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6741 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6742 "$")
6743 "Function properties of the Ecma-262 Math object.
6744 Shown at or above `js2-highlight-level' 2.")
6745
6746 (defconst js2-ecma-function-props
6747 (concat
6748 "^"
6749 (regexp-opt
6750 '(;; properties of the Object prototype object
6751 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6752 "toLocaleString" "toString" "valueOf"
6753 ;; properties of the Function prototype object
6754 "apply" "call"
6755 ;; properties of the Array prototype object
6756 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6757 "splice" "unshift"
6758 ;; properties of the String prototype object
6759 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6760 "localeCompare" "match" "replace" "search" "split" "substring"
6761 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6762 "toUpperCase"
6763 ;; properties of the Number prototype object
6764 "toExponential" "toFixed" "toPrecision"
6765 ;; properties of the Date prototype object
6766 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6767 "getMinutes" "getMonth" "getSeconds" "getTime"
6768 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6769 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6770 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6771 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6772 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6773 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6774 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6775 "toTimeString" "toUTCString"
6776 ;; properties of the RegExp prototype object
6777 "exec" "test"
6778 ;; properties of the JSON prototype object
6779 "parse" "stringify"
6780 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6781 "toSource" "__defineGetter__" "__defineSetter__"
6782 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6783 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6784 t)
6785 "$")
6786 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6787 Shown at or above `js2-highlight-level' 3.")
6788
6789 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6790 (let ((target-name (and target
6791 (js2-name-node-p target)
6792 (js2-name-node-name target)))
6793 (prop-name (if prop (js2-name-node-name prop)))
6794 (level2 (>= js2-highlight-level 2))
6795 (level3 (>= js2-highlight-level 3)))
6796 (when level2
6797 (let ((face
6798 (if call-p
6799 (cond
6800 ((and target prop)
6801 (cond
6802 ((and level3 (string-match js2-ecma-function-props prop-name))
6803 'font-lock-builtin-face)
6804 ((and target-name prop)
6805 (cond
6806 ((string= target-name "Date")
6807 (if (string-match js2-ecma-date-props prop-name)
6808 'font-lock-builtin-face))
6809 ((string= target-name "Math")
6810 (if (string-match js2-ecma-math-funcs prop-name)
6811 'font-lock-builtin-face))))))
6812 (prop
6813 (if (string-match js2-ecma-global-funcs prop-name)
6814 'font-lock-builtin-face)))
6815 (cond
6816 ((and target prop)
6817 (cond
6818 ((string= target-name "Number")
6819 (if (string-match js2-ecma-number-props prop-name)
6820 'font-lock-constant-face))
6821 ((string= target-name "Math")
6822 (if (string-match js2-ecma-math-props prop-name)
6823 'font-lock-constant-face))))
6824 (prop
6825 (if (string-match js2-ecma-object-props prop-name)
6826 'font-lock-constant-face))))))
6827 (when face
6828 (let ((pos (+ (js2-node-pos parent) ; absolute
6829 (js2-node-pos prop)))) ; relative
6830 (js2-set-face pos
6831 (+ pos (js2-node-len prop))
6832 face 'record)))))))
6833
6834 (defun js2-parse-highlight-member-expr-node (node)
6835 "Perform syntax highlighting of EcmaScript built-in properties.
6836 The variable `js2-highlight-level' governs this highlighting."
6837 (let (face target prop name pos end parent call-p callee)
6838 (cond
6839 ;; case 1: simple name, e.g. foo
6840 ((js2-name-node-p node)
6841 (setq name (js2-name-node-name node))
6842 ;; possible for name to be nil in rare cases - saw it when
6843 ;; running js2-mode on an elisp buffer. Might as well try to
6844 ;; make it so js2-mode never barfs.
6845 (when name
6846 (setq face (if (string-match js2-ecma-global-props name)
6847 'font-lock-constant-face))
6848 (when face
6849 (setq pos (js2-node-pos node)
6850 end (+ pos (js2-node-len node)))
6851 (js2-set-face pos end face 'record))))
6852 ;; case 2: property access or function call
6853 ((or (js2-prop-get-node-p node)
6854 ;; highlight function call if expr is a prop-get node
6855 ;; or a plain name (i.e. unqualified function call)
6856 (and (setq call-p (js2-call-node-p node))
6857 (setq callee (js2-call-node-target node)) ; separate setq!
6858 (or (js2-prop-get-node-p callee)
6859 (js2-name-node-p callee))))
6860 (setq parent node
6861 node (if call-p callee node))
6862 (if (and call-p (js2-name-node-p callee))
6863 (setq prop callee)
6864 (setq target (js2-prop-get-node-left node)
6865 prop (js2-prop-get-node-right node)))
6866 (cond
6867 ((js2-name-node-p prop)
6868 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6869 (js2-parse-highlight-prop-get parent target prop call-p))
6870 ((js2-name-node-p target)
6871 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6872 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6873
6874 (defun js2-parse-highlight-member-expr-fn-name (expr)
6875 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6876 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6877 We currently only handle the case where the last component is a prop-get
6878 of a simple name. Called before EXPR has a parent node."
6879 (let (pos
6880 (name (and (js2-prop-get-node-p expr)
6881 (js2-prop-get-node-right expr))))
6882 (when (js2-name-node-p name)
6883 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6884 (js2-node-pos name)))
6885 (+ pos (js2-node-len name))
6886 'font-lock-function-name-face
6887 'record))))
6888
6889 ;; source: http://jsdoc.sourceforge.net/
6890 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6891 ;; allows type specifications, and needs work before entering the wild.
6892
6893 (defconst js2-jsdoc-param-tag-regexp
6894 (concat "^\\s-*\\*+\\s-*\\(@"
6895 "\\(?:param\\|argument\\)"
6896 "\\)"
6897 "\\s-*\\({[^}]+}\\)?" ; optional type
6898 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6899 "\\>")
6900 "Matches jsdoc tags with optional type and optional param name.")
6901
6902 (defconst js2-jsdoc-typed-tag-regexp
6903 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6904 (regexp-opt
6905 '("enum"
6906 "extends"
6907 "field"
6908 "id"
6909 "implements"
6910 "lends"
6911 "mods"
6912 "requires"
6913 "return"
6914 "returns"
6915 "throw"
6916 "throws"))
6917 "\\)\\)\\s-*\\({[^}]+}\\)?")
6918 "Matches jsdoc tags with optional type.")
6919
6920 (defconst js2-jsdoc-arg-tag-regexp
6921 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6922 (regexp-opt
6923 '("alias"
6924 "augments"
6925 "borrows"
6926 "bug"
6927 "base"
6928 "config"
6929 "default"
6930 "define"
6931 "exception"
6932 "function"
6933 "member"
6934 "memberOf"
6935 "name"
6936 "namespace"
6937 "property"
6938 "since"
6939 "suppress"
6940 "this"
6941 "throws"
6942 "type"
6943 "version"))
6944 "\\)\\)\\s-+\\([^ \t]+\\)")
6945 "Matches jsdoc tags with a single argument.")
6946
6947 (defconst js2-jsdoc-empty-tag-regexp
6948 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6949 (regexp-opt
6950 '("addon"
6951 "author"
6952 "class"
6953 "const"
6954 "constant"
6955 "constructor"
6956 "constructs"
6957 "deprecated"
6958 "desc"
6959 "description"
6960 "event"
6961 "example"
6962 "exec"
6963 "export"
6964 "fileoverview"
6965 "final"
6966 "function"
6967 "hidden"
6968 "ignore"
6969 "implicitCast"
6970 "inheritDoc"
6971 "inner"
6972 "interface"
6973 "license"
6974 "noalias"
6975 "noshadow"
6976 "notypecheck"
6977 "override"
6978 "owner"
6979 "preserve"
6980 "preserveTry"
6981 "private"
6982 "protected"
6983 "public"
6984 "static"
6985 "supported"
6986 ))
6987 "\\)\\)\\s-*")
6988 "Matches empty jsdoc tags.")
6989
6990 (defconst js2-jsdoc-link-tag-regexp
6991 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6992 "Matches a jsdoc link or code tag.")
6993
6994 (defconst js2-jsdoc-see-tag-regexp
6995 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6996 "Matches a jsdoc @see tag.")
6997
6998 (defconst js2-jsdoc-html-tag-regexp
6999 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
7000 "Matches a simple (no attributes) html start- or end-tag.")
7001
7002 (defun js2-jsdoc-highlight-helper ()
7003 (js2-set-face (match-beginning 1)
7004 (match-end 1)
7005 'js2-jsdoc-tag)
7006 (if (match-beginning 2)
7007 (if (save-excursion
7008 (goto-char (match-beginning 2))
7009 (= (char-after) ?{))
7010 (js2-set-face (1+ (match-beginning 2))
7011 (1- (match-end 2))
7012 'js2-jsdoc-type)
7013 (js2-set-face (match-beginning 2)
7014 (match-end 2)
7015 'js2-jsdoc-value)))
7016 (if (match-beginning 3)
7017 (js2-set-face (match-beginning 3)
7018 (match-end 3)
7019 'js2-jsdoc-value)))
7020
7021 (defun js2-highlight-jsdoc (ast)
7022 "Highlight doc comment tags."
7023 (let ((comments (js2-ast-root-comments ast))
7024 beg end)
7025 (save-excursion
7026 (dolist (node comments)
7027 (when (eq (js2-comment-node-format node) 'jsdoc)
7028 (setq beg (js2-node-abs-pos node)
7029 end (+ beg (js2-node-len node)))
7030 (save-restriction
7031 (narrow-to-region beg end)
7032 (dolist (re (list js2-jsdoc-param-tag-regexp
7033 js2-jsdoc-typed-tag-regexp
7034 js2-jsdoc-arg-tag-regexp
7035 js2-jsdoc-link-tag-regexp
7036 js2-jsdoc-see-tag-regexp
7037 js2-jsdoc-empty-tag-regexp))
7038 (goto-char beg)
7039 (while (re-search-forward re nil t)
7040 (js2-jsdoc-highlight-helper)))
7041 ;; simple highlighting for html tags
7042 (goto-char beg)
7043 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
7044 (js2-set-face (match-beginning 1)
7045 (match-end 1)
7046 'js2-jsdoc-html-tag-delimiter)
7047 (js2-set-face (match-beginning 2)
7048 (match-end 2)
7049 'js2-jsdoc-html-tag-name)
7050 (js2-set-face (match-beginning 3)
7051 (match-end 3)
7052 'js2-jsdoc-html-tag-delimiter))))))))
7053
7054 (defun js2-highlight-assign-targets (_node left right)
7055 "Highlight function properties and external variables."
7056 (let (leftpos name)
7057 ;; highlight vars and props assigned function values
7058 (when (or (js2-function-node-p right)
7059 (js2-class-node-p right))
7060 (cond
7061 ;; var foo = function() {...}
7062 ((js2-name-node-p left)
7063 (setq name left))
7064 ;; foo.bar.baz = function() {...}
7065 ((and (js2-prop-get-node-p left)
7066 (js2-name-node-p (js2-prop-get-node-right left)))
7067 (setq name (js2-prop-get-node-right left))))
7068 (when name
7069 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7070 (+ leftpos (js2-node-len name))
7071 'font-lock-function-name-face
7072 'record)))))
7073
7074 (defun js2-record-name-node (node)
7075 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7076 later. NODE must be a name node."
7077 (let ((leftpos (js2-node-abs-pos node)))
7078 (push (list node js2-current-scope
7079 leftpos
7080 (+ leftpos (js2-node-len node)))
7081 js2-recorded-identifiers)))
7082
7083 (defun js2-highlight-undeclared-vars ()
7084 "After entire parse is finished, look for undeclared variable references.
7085 We have to wait until entire buffer is parsed, since JavaScript permits var
7086 decls to occur after they're used.
7087
7088 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7089 it is considered declared."
7090 (let (name)
7091 (dolist (entry js2-recorded-identifiers)
7092 (cl-destructuring-bind (name-node scope pos end) entry
7093 (setq name (js2-name-node-name name-node))
7094 (unless (or (member name js2-global-externs)
7095 (member name js2-default-externs)
7096 (member name js2-additional-externs)
7097 (js2-get-defining-scope scope name pos))
7098 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7099 'js2-external-variable))))))
7100
7101 (defun js2--add-or-update-symbol (symbol inition used vars)
7102 "Add or update SYMBOL entry in VARS, an hash table.
7103 SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
7104 respectively meaning that SYMBOL is a mere declaration, an
7105 assignment or a function parameter; when USED is t, the symbol
7106 node is assumed to be an usage and thus added to the list stored
7107 in the cdr of the entry.
7108 "
7109 (let* ((nm (js2-name-node-name symbol))
7110 (es (js2-node-get-enclosing-scope symbol))
7111 (ds (js2-get-defining-scope es nm)))
7112 (when (and ds (not (equal nm "arguments")))
7113 (let* ((sym (js2-scope-get-symbol ds nm))
7114 (var (gethash sym vars))
7115 (err-var-p (js2-catch-node-p ds)))
7116 (unless inition
7117 (setq inition err-var-p))
7118 (if var
7119 (progn
7120 (when (and inition (not (equal (car var) ?P)))
7121 (setcar var inition))
7122 (when used
7123 (push symbol (cdr var))))
7124 ;; do not consider the declaration of catch parameter as an usage
7125 (when (and err-var-p used)
7126 (setq used nil))
7127 (puthash sym (cons inition (if used (list symbol))) vars))))))
7128
7129 (defun js2--classify-variables ()
7130 "Collect and classify variables declared or used within js2-mode-ast.
7131 Traverse the whole ast tree returning a summary of the variables
7132 usage as an hash-table, keyed by their corresponding symbol table
7133 entry.
7134 Each variable is described by a tuple where the car is a flag
7135 indicating whether the variable has been initialized and the cdr
7136 is a possibly empty list of name nodes where it is used. External
7137 symbols, i.e. those not present in the whole scopes hierarchy,
7138 are ignored."
7139 (let ((vars (make-hash-table :test #'eq :size 100)))
7140 (js2-visit-ast
7141 js2-mode-ast
7142 (lambda (node end-p)
7143 (when (null end-p)
7144 (cond
7145 ((js2-var-init-node-p node)
7146 ;; take note about possibly initialized declarations
7147 (let ((target (js2-var-init-node-target node))
7148 (initializer (js2-var-init-node-initializer node)))
7149 (when target
7150 (let* ((parent (js2-node-parent node))
7151 (grandparent (if parent (js2-node-parent parent)))
7152 (inited (not (null initializer))))
7153 (unless inited
7154 (setq inited
7155 (and grandparent
7156 (js2-for-in-node-p grandparent)
7157 (memq target
7158 (mapcar #'js2-var-init-node-target
7159 (js2-var-decl-node-kids
7160 (js2-for-in-node-iterator grandparent)))))))
7161 (js2--add-or-update-symbol target inited nil vars)))))
7162
7163 ((js2-assign-node-p node)
7164 ;; take note about assignments
7165 (let ((left (js2-assign-node-left node)))
7166 (when (js2-name-node-p left)
7167 (js2--add-or-update-symbol left t nil vars))))
7168
7169 ((js2-prop-get-node-p node)
7170 ;; handle x.y.z nodes, considering only x
7171 (let ((left (js2-prop-get-node-left node)))
7172 (when (js2-name-node-p left)
7173 (js2--add-or-update-symbol left nil t vars))))
7174
7175 ((js2-name-node-p node)
7176 ;; take note about used variables
7177 (let ((parent (js2-node-parent node)))
7178 (when parent
7179 (unless (or (and (js2-var-init-node-p parent) ; handled above
7180 (eq node (js2-var-init-node-target parent)))
7181 (and (js2-assign-node-p parent)
7182 (eq node (js2-assign-node-left parent)))
7183 (js2-prop-get-node-p parent))
7184 (let ((used t) inited)
7185 (cond
7186 ((and (js2-function-node-p parent)
7187 (js2-wrapper-function-p parent))
7188 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)))
7189
7190 ((js2-for-in-node-p parent)
7191 (if (eq node (js2-for-in-node-iterator parent))
7192 (setq inited t used nil)))
7193
7194 ((js2-function-node-p parent)
7195 (setq inited (if (memq node (js2-function-node-params parent)) ?P t)
7196 used nil)))
7197
7198 (unless used
7199 (let ((grandparent (js2-node-parent parent)))
7200 (when grandparent
7201 (setq used (js2-return-node-p grandparent)))))
7202
7203 (js2--add-or-update-symbol node inited used vars))))))))
7204 t))
7205 vars))
7206
7207 (defun js2--get-name-node (node)
7208 (cond
7209 ((js2-name-node-p node) node)
7210 ((js2-function-node-p node)
7211 (js2-function-node-name node))
7212 ((js2-class-node-p node)
7213 (js2-class-node-name node))
7214 ((js2-comp-loop-node-p node)
7215 (js2-comp-loop-node-iterator node))
7216 (t node)))
7217
7218 (defun js2--highlight-unused-variable (symbol info)
7219 (let ((name (js2-symbol-name symbol))
7220 (inited (car info))
7221 (refs (cdr info))
7222 pos len)
7223 (unless (and inited refs)
7224 (if refs
7225 (dolist (ref refs)
7226 (setq pos (js2-node-abs-pos ref))
7227 (setq len (js2-name-node-len ref))
7228 (js2-report-warning "msg.uninitialized.variable" name pos len
7229 'js2-warning))
7230 (when (or js2-warn-about-unused-function-arguments
7231 (not (eq inited ?P)))
7232 (let* ((symn (js2-symbol-ast-node symbol))
7233 (namen (js2--get-name-node symn)))
7234 (unless (js2-node-top-level-decl-p namen)
7235 (setq pos (js2-node-abs-pos namen))
7236 (setq len (js2-name-node-len namen))
7237 (js2-report-warning "msg.unused.variable" name pos len
7238 'js2-warning))))))))
7239
7240 (defun js2-highlight-unused-variables ()
7241 "Highlight unused variables."
7242 (let ((vars (js2--classify-variables)))
7243 (maphash #'js2--highlight-unused-variable vars)))
7244
7245 ;;;###autoload
7246 (define-minor-mode js2-highlight-unused-variables-mode
7247 "Toggle highlight of unused variables."
7248 :lighter ""
7249 (if js2-highlight-unused-variables-mode
7250 (add-hook 'js2-post-parse-callbacks
7251 #'js2-highlight-unused-variables nil t)
7252 (remove-hook 'js2-post-parse-callbacks
7253 #'js2-highlight-unused-variables t)))
7254
7255 (defun js2-set-default-externs ()
7256 "Set the value of `js2-default-externs' based on the various
7257 `js2-include-?-externs' variables."
7258 (setq js2-default-externs
7259 (append js2-ecma-262-externs
7260 (if js2-include-browser-externs js2-browser-externs)
7261 (if (and js2-include-browser-externs
7262 (>= js2-language-version 200)) js2-harmony-externs)
7263 (if js2-include-rhino-externs js2-rhino-externs)
7264 (if js2-include-node-externs js2-node-externs)
7265 (if (or js2-include-browser-externs js2-include-node-externs)
7266 js2-typed-array-externs))))
7267
7268 (defun js2-apply-jslint-globals ()
7269 (setq js2-additional-externs
7270 (nconc (js2-get-jslint-globals)
7271 js2-additional-externs)))
7272
7273 (defun js2-get-jslint-globals ()
7274 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7275 when (and (eq 'block (js2-comment-node-format node))
7276 (save-excursion
7277 (goto-char (js2-node-abs-pos node))
7278 (looking-at "/\\*global ")))
7279 append (js2-get-jslint-globals-in
7280 (match-end 0)
7281 (js2-node-abs-end node))))
7282
7283 (defun js2-get-jslint-globals-in (beg end)
7284 (let (res)
7285 (save-excursion
7286 (goto-char beg)
7287 (while (re-search-forward js2-mode-identifier-re end t)
7288 (let ((match (match-string 0)))
7289 (unless (member match '("true" "false"))
7290 (push match res)))))
7291 (nreverse res)))
7292
7293 ;;; IMenu support
7294
7295 ;; We currently only support imenu, but eventually should support speedbar and
7296 ;; possibly other browsing mechanisms.
7297
7298 ;; The basic strategy is to identify function assignment targets of the form
7299 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7300 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7301 ;; for imenu after parsing is finished.
7302
7303 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7304 ;; JavaScript, and the general problem is undecidable. However, several forms
7305 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7306 ;; include:
7307
7308 ;; function foo() -- function declaration
7309 ;; foo = function() -- function expression assigned to variable
7310 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7311 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7312 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7313 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7314 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7315 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7316 ;; function foo() {function bar() {...}} -- nested function
7317 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7318
7319 ;; This list boils down to a few forms that can be combined recursively.
7320 ;; Top-level named function declarations include both the left-hand (name)
7321 ;; and the right-hand (function value) expressions needed to produce an imenu
7322 ;; entry. The other "right-hand" forms we need to look for are:
7323 ;; - functions declared as props/getters/setters in object literals
7324 ;; - nested named function declarations
7325 ;; The "left-hand" expressions that functions can be assigned to include:
7326 ;; - local/global variables
7327 ;; - nested property-get expressions like a.b.c.d
7328 ;; - element gets like foo[10] or foo['bar'] where the index
7329 ;; expression can be trivially converted to a property name. They
7330 ;; effectively then become property gets.
7331
7332 ;; All the different definition types are canonicalized into the form
7333 ;; foo.bar.baz = position-of-function-keyword
7334
7335 ;; We need to build a trie-like structure for imenu. As an example,
7336 ;; consider the following JavaScript code:
7337
7338 ;; a = function() {...} // function at position 5
7339 ;; b = function() {...} // function at position 25
7340 ;; foo = function() {...} // function at position 100
7341 ;; foo.bar = function() {...} // function at position 200
7342 ;; foo.bar.baz = function() {...} // function at position 300
7343 ;; foo.bar.zab = function() {...} // function at position 400
7344
7345 ;; During parsing we accumulate an entry for each definition in
7346 ;; the variable `js2-imenu-recorder', like so:
7347
7348 ;; '((fn a 5)
7349 ;; (fn b 25)
7350 ;; (fn foo 100)
7351 ;; (fn foo bar 200)
7352 ;; (fn foo bar baz 300)
7353 ;; (fn foo bar zab 400))
7354
7355 ;; Where 'fn' is the respective function node.
7356 ;; After parsing these entries are merged into this alist-trie:
7357
7358 ;; '((a . 1)
7359 ;; (b . 2)
7360 ;; (foo (<definition> . 3)
7361 ;; (bar (<definition> . 6)
7362 ;; (baz . 100)
7363 ;; (zab . 200))))
7364
7365 ;; Note the wacky need for a <definition> name. The token can be anything
7366 ;; that isn't a valid JavaScript identifier, because you might make foo
7367 ;; a function and then start setting properties on it that are also functions.
7368
7369 (defun js2-prop-node-name (node)
7370 "Return the name of a node that may be a property-get/property-name.
7371 If NODE is not a valid name-node, string-node or integral number-node,
7372 returns nil. Otherwise returns the string name/value of the node."
7373 (cond
7374 ((js2-name-node-p node)
7375 (js2-name-node-name node))
7376 ((js2-string-node-p node)
7377 (js2-string-node-value node))
7378 ((and (js2-number-node-p node)
7379 (string-match "^[0-9]+$" (js2-number-node-value node)))
7380 (js2-number-node-value node))
7381 ((eq (js2-node-type node) js2-THIS)
7382 "this")
7383 ((eq (js2-node-type node) js2-SUPER)
7384 "super")))
7385
7386 (defun js2-node-qname-component (node)
7387 "Return the name of this node, if it contributes to a qname.
7388 Returns nil if the node doesn't contribute."
7389 (copy-sequence
7390 (or (js2-prop-node-name node)
7391 (if (and (js2-function-node-p node)
7392 (js2-function-node-name node))
7393 (js2-name-node-name (js2-function-node-name node))))))
7394
7395 (defun js2-record-imenu-entry (fn-node qname pos)
7396 "Add an entry to `js2-imenu-recorder'.
7397 FN-NODE should be the current item's function node.
7398
7399 Associate FN-NODE with its QNAME for later lookup.
7400 This is used in postprocessing the chain list. For each chain, we find
7401 the parent function, look up its qname, then prepend a copy of it to the chain."
7402 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7403 (unless js2-imenu-function-map
7404 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7405 (puthash fn-node qname js2-imenu-function-map))
7406
7407 (defun js2-record-imenu-functions (node &optional var)
7408 "Record function definitions for imenu.
7409 NODE is a function node or an object literal.
7410 VAR, if non-nil, is the expression that NODE is being assigned to.
7411 When passed arguments of wrong type, does nothing."
7412 (when js2-parse-ide-mode
7413 (let ((fun-p (js2-function-node-p node))
7414 qname fname-node)
7415 (cond
7416 ;; non-anonymous function declaration?
7417 ((and fun-p
7418 (not var)
7419 (setq fname-node (js2-function-node-name node)))
7420 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7421 ;; for remaining forms, compute left-side tree branch first
7422 ((and var (setq qname (js2-compute-nested-prop-get var)))
7423 (cond
7424 ;; foo.bar.baz = function
7425 (fun-p
7426 (js2-record-imenu-entry node qname (js2-node-pos node)))
7427 ;; foo.bar.baz = object-literal
7428 ;; look for nested functions: {a: {b: function() {...} }}
7429 ((js2-object-node-p node)
7430 ;; Node position here is still absolute, since the parser
7431 ;; passes the assignment target and value expressions
7432 ;; to us before they are added as children of the assignment node.
7433 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7434
7435 (defun js2-compute-nested-prop-get (node)
7436 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7437 component nodes as a list. Otherwise return nil. Element-gets are treated
7438 as property-gets if the index expression is a string, or a positive integer."
7439 (let (left right head)
7440 (cond
7441 ((or (js2-name-node-p node)
7442 (js2-this-or-super-node-p node))
7443 (list node))
7444 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7445 ((js2-prop-get-node-p node) ; foo.bar
7446 (setq left (js2-prop-get-node-left node)
7447 right (js2-prop-get-node-right node))
7448 (if (setq head (js2-compute-nested-prop-get left))
7449 (nconc head (list right))))
7450 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7451 (setq left (js2-elem-get-node-target node)
7452 right (js2-elem-get-node-element node))
7453 (if (or (js2-string-node-p right) ; ['bar']
7454 (and (js2-number-node-p right) ; [10]
7455 (string-match "^[0-9]+$"
7456 (js2-number-node-value right))))
7457 (if (setq head (js2-compute-nested-prop-get left))
7458 (nconc head (list right))))))))
7459
7460 (defun js2-record-object-literal (node qname pos)
7461 "Recursively process an object literal looking for functions.
7462 NODE is an object literal that is the right-hand child of an assignment
7463 expression. QNAME is a list of nodes representing the assignment target,
7464 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7465 POS is the absolute position of the node.
7466 We do a depth-first traversal of NODE. For any functions we find,
7467 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7468 (let (right)
7469 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7470 (let ((left (js2-infix-node-left e))
7471 ;; Element positions are relative to the parent position.
7472 (pos (+ pos (js2-node-pos e))))
7473 (cond
7474 ;; foo: function() {...}
7475 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7476 (when (js2-prop-node-name left)
7477 ;; As a policy decision, we record the position of the property,
7478 ;; not the position of the `function' keyword, since the property
7479 ;; is effectively the name of the function.
7480 (js2-record-imenu-entry right (append qname (list left)) pos)))
7481 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7482 ((js2-object-node-p right)
7483 (js2-record-object-literal right
7484 (append qname (list (js2-infix-node-left e)))
7485 (+ pos (js2-node-pos right)))))))))
7486
7487 (defun js2-node-top-level-decl-p (node)
7488 "Return t if NODE's name is defined in the top-level scope.
7489 Also returns t if NODE's name is not defined in any scope, since it implies
7490 that it's an external variable, which must also be in the top-level scope."
7491 (let* ((name (js2-prop-node-name node))
7492 (this-scope (js2-node-get-enclosing-scope node))
7493 defining-scope)
7494 (cond
7495 ((js2-this-or-super-node-p node)
7496 nil)
7497 ((null this-scope)
7498 t)
7499 ((setq defining-scope (js2-get-defining-scope this-scope name))
7500 (js2-ast-root-p defining-scope))
7501 (t t))))
7502
7503 (defun js2-wrapper-function-p (node)
7504 "Return t if NODE is a function expression that's immediately invoked.
7505 NODE must be `js2-function-node'."
7506 (let ((parent (js2-node-parent node)))
7507 (or
7508 ;; function(){...}();
7509 (and (js2-call-node-p parent)
7510 (eq node (js2-call-node-target parent)))
7511 (and (js2-paren-node-p parent)
7512 ;; (function(){...})();
7513 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7514 ;; (function(){...}).call(this);
7515 (and (js2-prop-get-node-p parent)
7516 (member (js2-name-node-name (js2-prop-get-node-right parent))
7517 '("call" "apply"))
7518 (js2-call-node-p (js2-node-parent parent))))))))
7519
7520 (defun js2-browse-postprocess-chains ()
7521 "Modify function-declaration name chains after parsing finishes.
7522 Some of the information is only available after the parse tree is complete.
7523 For instance, processing a nested scope requires a parent function node."
7524 (let (result fn parent-qname p elem)
7525 (dolist (entry js2-imenu-recorder)
7526 ;; function node goes first
7527 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7528 ;; Examine head's defining scope:
7529 ;; Pre-processed chain, or top-level/external, keep as-is.
7530 (if (or (stringp head) (js2-node-top-level-decl-p head))
7531 (push chain result)
7532 (when (js2-this-or-super-node-p head)
7533 (setq chain (cdr chain))) ; discard this-node
7534 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7535 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7536 (when (eq parent-qname 'not-found)
7537 ;; anonymous function expressions are not recorded
7538 ;; during the parse, so we need to handle this case here
7539 (setq parent-qname
7540 (if (js2-wrapper-function-p fn)
7541 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7542 (if (js2-ast-root-p grandparent)
7543 nil
7544 (gethash grandparent js2-imenu-function-map 'skip)))
7545 'skip))
7546 (puthash fn parent-qname js2-imenu-function-map))
7547 (if (eq parent-qname 'skip)
7548 ;; We don't show it, let's record that fact.
7549 (remhash current-fn js2-imenu-function-map)
7550 ;; Prepend parent fn qname to this chain.
7551 (let ((qname (append parent-qname chain)))
7552 (puthash current-fn (butlast qname) js2-imenu-function-map)
7553 (push qname result)))))))
7554 ;; Collect chains obtained by third-party code.
7555 (let (js2-imenu-recorder)
7556 (run-hooks 'js2-build-imenu-callbacks)
7557 (dolist (entry js2-imenu-recorder)
7558 (push (cdr entry) result)))
7559 ;; Finally replace each node in each chain with its name.
7560 (dolist (chain result)
7561 (setq p chain)
7562 (while p
7563 (if (js2-node-p (setq elem (car p)))
7564 (setcar p (js2-node-qname-component elem)))
7565 (setq p (cdr p))))
7566 result))
7567
7568 ;; Merge name chains into a trie-like tree structure of nested lists.
7569 ;; To simplify construction of the trie, we first build it out using the rule
7570 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7571 ;; [key, num-or-list]. The second element can be a number; if so, this key
7572 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7573 ;; associated with the key at this level.) Otherwise the second element is
7574 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7575 ;; a simple recursive formulation.
7576 ;;
7577 ;; js2-mode is building the data structure for imenu. The imenu documentation
7578 ;; claims that it's the structure above, but in practice it wants the children
7579 ;; at the same list level as the key for that level, which is how I've drawn
7580 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7581 ;; list wrapper around the children at each level.
7582 ;;
7583 ;; A completed nested imenu-alist entry looks like this:
7584 ;; '(("foo"
7585 ;; ("<definition>" . 7)
7586 ;; ("bar"
7587 ;; ("a" . 40)
7588 ;; ("b" . 60))))
7589 ;;
7590 ;; In particular, the documentation for `imenu--index-alist' says that
7591 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7592 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7593
7594 (defun js2-treeify (lst)
7595 "Convert (a b c d) to (a ((b ((c d)))))."
7596 (if (null (cddr lst)) ; list length <= 2
7597 lst
7598 (list (car lst) (list (js2-treeify (cdr lst))))))
7599
7600 (defun js2-build-alist-trie (chains trie)
7601 "Merge declaration name chains into a trie-like alist structure for imenu.
7602 CHAINS is the qname chain list produced during parsing. TRIE is a
7603 list of elements built up so far."
7604 (let (head tail pos branch kids)
7605 (dolist (chain chains)
7606 (setq head (car chain)
7607 tail (cdr chain)
7608 pos (if (numberp (car tail)) (car tail))
7609 branch (js2-find-if (lambda (n)
7610 (string= (car n) head))
7611 trie)
7612 kids (cl-second branch))
7613 (cond
7614 ;; case 1: this key isn't in the trie yet
7615 ((null branch)
7616 (if trie
7617 (setcdr (last trie) (list (js2-treeify chain)))
7618 (setq trie (list (js2-treeify chain)))))
7619 ;; case 2: key is present with a single number entry: replace w/ list
7620 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7621 ;; ("<definition>" 20)))
7622 ((numberp kids)
7623 (setcar (cdr branch)
7624 (list (list "<definition-1>" kids)
7625 (if pos
7626 (list "<definition-2>" pos)
7627 (js2-treeify tail)))))
7628 ;; case 3: key is there (with kids), and we're a number entry
7629 (pos
7630 (setcdr (last kids)
7631 (list
7632 (list (format "<definition-%d>"
7633 (1+ (cl-loop for kid in kids
7634 count (eq ?< (aref (car kid) 0)))))
7635 pos))))
7636 ;; case 4: key is there with kids, need to merge in our chain
7637 (t
7638 (js2-build-alist-trie (list tail) kids))))
7639 trie))
7640
7641 (defun js2-flatten-trie (trie)
7642 "Convert TRIE to imenu-format.
7643 Recurses through nodes, and for each one whose second element is a list,
7644 appends the list's flattened elements to the current element. Also
7645 changes the tails into conses. For instance, this pre-flattened trie
7646
7647 '(a ((b 20)
7648 (c ((d 30)
7649 (e 40)))))
7650
7651 becomes
7652
7653 '(a (b . 20)
7654 (c (d . 30)
7655 (e . 40)))
7656
7657 Note that the root of the trie has no key, just a list of chains.
7658 This is also true for the value of any key with multiple children,
7659 e.g. key 'c' in the example above."
7660 (cond
7661 ((listp (car trie))
7662 (mapcar #'js2-flatten-trie trie))
7663 (t
7664 (if (numberp (cl-second trie))
7665 (cons (car trie) (cl-second trie))
7666 ;; else pop list and append its kids
7667 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7668
7669 (defun js2-build-imenu-index ()
7670 "Turn `js2-imenu-recorder' into an imenu data structure."
7671 (when (eq js2-imenu-recorder 'empty)
7672 (setq js2-imenu-recorder nil))
7673 (let* ((chains (js2-browse-postprocess-chains))
7674 (result (js2-build-alist-trie chains nil)))
7675 (js2-flatten-trie result)))
7676
7677 (defun js2-test-print-chains (chains)
7678 "Print a list of qname chains.
7679 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7680 i.e. one or more nodes, and an integer position as the list tail."
7681 (mapconcat (lambda (chain)
7682 (concat "("
7683 (mapconcat (lambda (elem)
7684 (if (js2-node-p elem)
7685 (or (js2-node-qname-component elem)
7686 "nil")
7687 (number-to-string elem)))
7688 chain
7689 " ")
7690 ")"))
7691 chains
7692 "\n"))
7693
7694 ;;; Parser
7695
7696 (defconst js2-version "1.8.5"
7697 "Version of JavaScript supported.")
7698
7699 (defun js2-record-face (face &optional token)
7700 "Record a style run of FACE for TOKEN or the current token."
7701 (unless token (setq token (js2-current-token)))
7702 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7703
7704 (defsubst js2-node-end (n)
7705 "Computes the absolute end of node N.
7706 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7707 is only true until the node is added to its parent; i.e., while parsing."
7708 (+ (js2-node-pos n)
7709 (js2-node-len n)))
7710
7711 (defun js2-record-comment (token)
7712 "Record a comment in `js2-scanned-comments'."
7713 (let ((ct (js2-token-comment-type token))
7714 (beg (js2-token-beg token))
7715 (end (js2-token-end token)))
7716 (push (make-js2-comment-node :len (- end beg)
7717 :format ct)
7718 js2-scanned-comments)
7719 (when js2-parse-ide-mode
7720 (js2-record-face (if (eq ct 'jsdoc)
7721 'font-lock-doc-face
7722 'font-lock-comment-face)
7723 token)
7724 (when (memq ct '(html preprocessor))
7725 ;; Tell cc-engine the bounds of the comment.
7726 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7727
7728 (defun js2-peek-token ()
7729 "Return the next token type without consuming it.
7730 If `js2-ti-lookahead' is positive, return the type of next token
7731 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7732 (if (not (zerop js2-ti-lookahead))
7733 (js2-token-type
7734 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7735 (let ((tt (js2-get-token-internal nil)))
7736 (js2-unget-token)
7737 tt)))
7738
7739 (defalias 'js2-next-token 'js2-get-token)
7740
7741 (defun js2-match-token (match &optional dont-unget)
7742 "Get next token and return t if it matches MATCH, a bytecode.
7743 Returns nil and consumes nothing if MATCH is not the next token."
7744 (if (/= (js2-get-token) match)
7745 (ignore (unless dont-unget (js2-unget-token)))
7746 t))
7747
7748 (defun js2-match-contextual-kwd (name)
7749 "Consume and return t if next token is `js2-NAME', and its
7750 string is NAME. Returns nil and keeps current token otherwise."
7751 (if (or (/= (js2-get-token) js2-NAME)
7752 (not (string= (js2-current-token-string) name)))
7753 (progn
7754 (js2-unget-token)
7755 nil)
7756 (js2-record-face 'font-lock-keyword-face)
7757 t))
7758
7759 (defun js2-get-prop-name-token ()
7760 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7761
7762 (defun js2-match-prop-name ()
7763 "Consume token and return t if next token is a valid property name.
7764 If `js2-language-version' is >= 180, a keyword or reserved word
7765 is considered valid name as well."
7766 (if (eq js2-NAME (js2-get-prop-name-token))
7767 t
7768 (js2-unget-token)
7769 nil))
7770
7771 (defun js2-must-match-prop-name (msg-id &optional pos len)
7772 (if (js2-match-prop-name)
7773 t
7774 (js2-report-error msg-id nil pos len)
7775 nil))
7776
7777 (defun js2-peek-token-or-eol ()
7778 "Return js2-EOL if the next token immediately follows a newline.
7779 Else returns the next token. Used in situations where we don't
7780 consider certain token types valid if they are preceded by a newline.
7781 One example is the postfix ++ or -- operator, which has to be on the
7782 same line as its operand."
7783 (let ((tt (js2-get-token))
7784 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7785 (js2-unget-token)
7786 (if follows-eol
7787 js2-EOL
7788 tt)))
7789
7790 (defun js2-must-match (token msg-id &optional pos len)
7791 "Match next token to token code TOKEN, or record a syntax error.
7792 MSG-ID is the error message to report if the match fails.
7793 Returns t on match, nil if no match."
7794 (if (js2-match-token token t)
7795 t
7796 (js2-report-error msg-id nil pos len)
7797 (js2-unget-token)
7798 nil))
7799
7800 (defun js2-must-match-name (msg-id)
7801 (if (js2-match-token js2-NAME t)
7802 t
7803 (if (eq (js2-current-token-type) js2-RESERVED)
7804 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7805 (js2-report-error msg-id)
7806 (js2-unget-token))
7807 nil))
7808
7809 (defsubst js2-inside-function ()
7810 (cl-plusp js2-nesting-of-function))
7811
7812 (defun js2-set-requires-activation ()
7813 (if (js2-function-node-p js2-current-script-or-fn)
7814 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7815
7816 (defun js2-check-activation-name (name _token)
7817 (when (js2-inside-function)
7818 ;; skip language-version 1.2 check from Rhino
7819 (if (or (string= "arguments" name)
7820 (and js2-compiler-activation-names ; only used in codegen
7821 (gethash name js2-compiler-activation-names)))
7822 (js2-set-requires-activation))))
7823
7824 (defun js2-set-is-generator ()
7825 (let ((fn-node js2-current-script-or-fn))
7826 (when (and (js2-function-node-p fn-node)
7827 (not (js2-function-node-generator-type fn-node)))
7828 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7829
7830 (defun js2-must-have-xml ()
7831 (unless js2-compiler-xml-available
7832 (js2-report-error "msg.XML.not.available")))
7833
7834 (defun js2-push-scope (scope)
7835 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7836 (cl-assert (js2-scope-p scope))
7837 (cl-assert (null (js2-scope-parent-scope scope)))
7838 (cl-assert (not (eq js2-current-scope scope)))
7839 (setf (js2-scope-parent-scope scope) js2-current-scope
7840 js2-current-scope scope))
7841
7842 (defsubst js2-pop-scope ()
7843 (setq js2-current-scope
7844 (js2-scope-parent-scope js2-current-scope)))
7845
7846 (defun js2-enter-loop (loop-node)
7847 (push loop-node js2-loop-set)
7848 (push loop-node js2-loop-and-switch-set)
7849 (js2-push-scope loop-node)
7850 ;; Tell the current labeled statement (if any) its statement,
7851 ;; and set the jump target of the first label to the loop.
7852 ;; These are used in `js2-parse-continue' to verify that the
7853 ;; continue target is an actual labeled loop. (And for codegen.)
7854 (when js2-labeled-stmt
7855 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7856 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7857 js2-labeled-stmt))) loop-node)))
7858
7859 (defun js2-exit-loop ()
7860 (pop js2-loop-set)
7861 (pop js2-loop-and-switch-set)
7862 (js2-pop-scope))
7863
7864 (defsubst js2-enter-switch (switch-node)
7865 (push switch-node js2-loop-and-switch-set))
7866
7867 (defsubst js2-exit-switch ()
7868 (pop js2-loop-and-switch-set))
7869
7870 (defsubst js2-get-directive (node)
7871 "Return NODE's value if it is a directive, nil otherwise.
7872
7873 A directive is an otherwise-meaningless expression statement
7874 consisting of a string literal, such as \"use strict\"."
7875 (and (js2-expr-stmt-node-p node)
7876 (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
7877 (js2-string-node-value node)))
7878
7879 (defun js2-parse (&optional buf cb)
7880 "Tell the js2 parser to parse a region of JavaScript.
7881
7882 BUF is a buffer or buffer name containing the code to parse.
7883 Call `narrow-to-region' first to parse only part of the buffer.
7884
7885 The returned AST root node is given some additional properties:
7886 `node-count' - total number of nodes in the AST
7887 `buffer' - BUF. The buffer it refers to may change or be killed,
7888 so the value is not necessarily reliable.
7889
7890 An optional callback CB can be specified to report parsing
7891 progress. If `(functionp CB)' returns t, it will be called with
7892 the current line number once before parsing begins, then again
7893 each time the lexer reaches a new line number.
7894
7895 CB can also be a list of the form `(symbol cb ...)' to specify
7896 multiple callbacks with different criteria. Each symbol is a
7897 criterion keyword, and the following element is the callback to
7898 call
7899
7900 :line - called whenever the line number changes
7901 :token - called for each new token consumed
7902
7903 The list of criteria could be extended to include entering or
7904 leaving a statement, an expression, or a function definition."
7905 (if (and cb (not (functionp cb)))
7906 (error "criteria callbacks not yet implemented"))
7907 (let ((inhibit-point-motion-hooks t)
7908 (js2-compiler-xml-available (>= js2-language-version 160))
7909 ;; This is a recursive-descent parser, so give it a big stack.
7910 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7911 (max-specpdl-size (max max-specpdl-size 3000))
7912 (case-fold-search nil)
7913 ast)
7914 (with-current-buffer (or buf (current-buffer))
7915 (setq js2-scanned-comments nil
7916 js2-parsed-errors nil
7917 js2-parsed-warnings nil
7918 js2-imenu-recorder nil
7919 js2-imenu-function-map nil
7920 js2-label-set nil)
7921 (js2-init-scanner)
7922 (setq ast (js2-do-parse))
7923 (unless js2-ts-hit-eof
7924 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7925 (setf (js2-ast-root-errors ast) js2-parsed-errors
7926 (js2-ast-root-warnings ast) js2-parsed-warnings)
7927 ;; if we didn't find any declarations, put a dummy in this list so we
7928 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7929 (unless js2-imenu-recorder
7930 (setq js2-imenu-recorder 'empty))
7931 (run-hooks 'js2-parse-finished-hook)
7932 ast)))
7933
7934 ;; Corresponds to Rhino's Parser.parse() method.
7935 (defun js2-do-parse ()
7936 "Parse current buffer starting from current point.
7937 Scanner should be initialized."
7938 (let ((pos js2-ts-cursor)
7939 (end js2-ts-cursor) ; in case file is empty
7940 root n tt
7941 (in-directive-prologue t)
7942 (saved-strict-mode js2-in-use-strict-directive)
7943 directive)
7944 ;; initialize buffer-local parsing vars
7945 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7946 js2-current-script-or-fn root
7947 js2-current-scope root
7948 js2-nesting-of-function 0
7949 js2-labeled-stmt nil
7950 js2-recorded-identifiers nil ; for js2-highlight
7951 js2-in-use-strict-directive nil)
7952 (while (/= (setq tt (js2-get-token)) js2-EOF)
7953 (if (= tt js2-FUNCTION)
7954 (progn
7955 (setq n (if js2-called-by-compile-function
7956 (js2-parse-function-expr)
7957 (js2-parse-function-stmt))))
7958 ;; not a function - parse a statement
7959 (js2-unget-token)
7960 (setq n (js2-parse-statement))
7961 (when in-directive-prologue
7962 (setq directive (js2-get-directive n))
7963 (cond
7964 ((null directive)
7965 (setq in-directive-prologue nil))
7966 ((string= directive "use strict")
7967 (setq js2-in-use-strict-directive t)
7968 (setf (js2-ast-root-in-strict-mode root) t)))))
7969 ;; add function or statement to script
7970 (setq end (js2-node-end n))
7971 (js2-block-node-push root n))
7972 (setq js2-in-use-strict-directive saved-strict-mode)
7973 ;; add comments to root in lexical order
7974 (when js2-scanned-comments
7975 ;; if we find a comment beyond end of normal kids, use its end
7976 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7977 (dolist (comment js2-scanned-comments)
7978 (push comment (js2-ast-root-comments root))
7979 (js2-node-add-children root comment)))
7980 (setf (js2-node-len root) (- end pos))
7981 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7982 ;; Give extensions a chance to muck with things before highlighting starts.
7983 (let ((js2-additional-externs js2-additional-externs))
7984 (save-excursion
7985 (run-hooks 'js2-post-parse-callbacks))
7986 (js2-highlight-undeclared-vars))
7987 root))
7988
7989 (defun js2-parse-function-closure-body (fn-node)
7990 "Parse a JavaScript 1.8 function closure body."
7991 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7992 (if js2-ts-hit-eof
7993 (js2-report-error "msg.no.brace.body" nil
7994 (js2-node-pos fn-node)
7995 (- js2-ts-cursor (js2-node-pos fn-node)))
7996 (js2-node-add-children fn-node
7997 (setf (js2-function-node-body fn-node)
7998 (js2-parse-expr t))))))
7999
8000 (defun js2-parse-function-body (fn-node)
8001 (js2-must-match js2-LC "msg.no.brace.body"
8002 (js2-node-pos fn-node)
8003 (- js2-ts-cursor (js2-node-pos fn-node)))
8004 (let ((pos (js2-current-token-beg)) ; LC position
8005 (pn (make-js2-block-node)) ; starts at LC position
8006 tt
8007 end
8008 not-in-directive-prologue
8009 (saved-strict-mode js2-in-use-strict-directive)
8010 node
8011 directive)
8012 (cl-incf js2-nesting-of-function)
8013 (unwind-protect
8014 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
8015 (= tt js2-EOF)
8016 (= tt js2-RC)))
8017 (js2-block-node-push
8018 pn
8019 (if (/= tt js2-FUNCTION)
8020 (if not-in-directive-prologue
8021 (js2-parse-statement)
8022 (setq node (js2-parse-statement)
8023 directive (js2-get-directive node))
8024 (cond
8025 ((null directive)
8026 (setq not-in-directive-prologue t))
8027 ((string= directive "use strict")
8028 (setq js2-in-use-strict-directive t)
8029 (setf (js2-function-node-in-strict-mode fn-node) t)))
8030 node)
8031 (js2-get-token)
8032 (js2-parse-function-stmt))))
8033 (cl-decf js2-nesting-of-function)
8034 (setq js2-in-use-strict-directive saved-strict-mode))
8035 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
8036 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
8037 (setq end (js2-current-token-end)))
8038 (setf (js2-node-pos pn) pos
8039 (js2-node-len pn) (- end pos))
8040 (setf (js2-function-node-body fn-node) pn)
8041 (js2-node-add-children fn-node pn)
8042 pn))
8043
8044 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
8045 "Declare and fontify destructuring parameters inside NODE.
8046 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
8047 (cond
8048 ((js2-name-node-p node)
8049 (let (leftpos)
8050 (js2-define-symbol decl-type (js2-name-node-name node)
8051 node ignore-not-in-block)
8052 (when face
8053 (js2-set-face (setq leftpos (js2-node-abs-pos node))
8054 (+ leftpos (js2-node-len node))
8055 face 'record))))
8056 ((js2-object-node-p node)
8057 (dolist (elem (js2-object-node-elems node))
8058 (js2-define-destruct-symbols
8059 ;; In abbreviated destructuring {a, b}, right == left.
8060 (js2-object-prop-node-right elem)
8061 decl-type face ignore-not-in-block)))
8062 ((js2-array-node-p node)
8063 (dolist (elem (js2-array-node-elems node))
8064 (when elem
8065 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
8066 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
8067 (js2-node-len node)))))
8068
8069 (defun js2-parse-function-params (function-type fn-node pos)
8070 (if (js2-match-token js2-RP)
8071 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
8072 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
8073 (eq (js2-current-token-type) js2-NAME)))
8074 params param default-found rest-param-at)
8075 (when paren-free-arrow
8076 (js2-unget-token))
8077 (cl-loop for tt = (js2-peek-token)
8078 do
8079 (cond
8080 ;; destructuring param
8081 ((and (not paren-free-arrow)
8082 (or (= tt js2-LB) (= tt js2-LC)))
8083 (js2-get-token)
8084 (when default-found
8085 (js2-report-error "msg.no.default.after.default.param"))
8086 (setq param (js2-parse-destruct-primary-expr))
8087 (js2-define-destruct-symbols param
8088 js2-LP
8089 'js2-function-param)
8090 (push param params))
8091 ;; variable name
8092 (t
8093 (when (and (>= js2-language-version 200)
8094 (not paren-free-arrow)
8095 (js2-match-token js2-TRIPLEDOT)
8096 (not rest-param-at))
8097 ;; to report errors if there are more parameters
8098 (setq rest-param-at (length params)))
8099 (js2-must-match-name "msg.no.parm")
8100 (js2-record-face 'js2-function-param)
8101 (setq param (js2-create-name-node))
8102 (js2-define-symbol js2-LP (js2-current-token-string) param)
8103 ;; default parameter value
8104 (when (or (and default-found
8105 (not rest-param-at)
8106 (js2-must-match js2-ASSIGN
8107 "msg.no.default.after.default.param"
8108 (js2-node-pos param)
8109 (js2-node-len param)))
8110 (and (>= js2-language-version 200)
8111 (js2-match-token js2-ASSIGN)))
8112 (cl-assert (not paren-free-arrow))
8113 (let* ((pos (js2-node-pos param))
8114 (tt (js2-current-token-type))
8115 (op-pos (- (js2-current-token-beg) pos))
8116 (left param)
8117 (right (js2-parse-assign-expr))
8118 (len (- (js2-node-end right) pos)))
8119 (setq param (make-js2-assign-node
8120 :type tt :pos pos :len len :op-pos op-pos
8121 :left left :right right)
8122 default-found t)
8123 (js2-node-add-children param left right)))
8124 (push param params)))
8125 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
8126 (js2-report-error "msg.param.after.rest" nil
8127 (js2-node-pos param) (js2-node-len param)))
8128 while
8129 (js2-match-token js2-COMMA))
8130 (when (and (not paren-free-arrow)
8131 (js2-must-match js2-RP "msg.no.paren.after.parms"))
8132 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
8133 (when rest-param-at
8134 (setf (js2-function-node-rest-p fn-node) t))
8135 (dolist (p params)
8136 (js2-node-add-children fn-node p)
8137 (push p (js2-function-node-params fn-node))))))
8138
8139 (defun js2-check-inconsistent-return-warning (fn-node name)
8140 "Possibly show inconsistent-return warning.
8141 Last token scanned is the close-curly for the function body."
8142 (when (and js2-mode-show-strict-warnings
8143 js2-strict-inconsistent-return-warning
8144 (not (js2-has-consistent-return-usage
8145 (js2-function-node-body fn-node))))
8146 ;; Have it extend from close-curly to bol or beginning of block.
8147 (let ((pos (save-excursion
8148 (goto-char (js2-current-token-end))
8149 (max (js2-node-abs-pos (js2-function-node-body fn-node))
8150 (point-at-bol))))
8151 (end (js2-current-token-end)))
8152 (if (cl-plusp (js2-name-node-length name))
8153 (js2-add-strict-warning "msg.no.return.value"
8154 (js2-name-node-name name) pos end)
8155 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
8156
8157 (defun js2-parse-function-stmt ()
8158 (let ((pos (js2-current-token-beg))
8159 (star-p (js2-match-token js2-MUL)))
8160 (js2-must-match-name "msg.unnamed.function.stmt")
8161 (let ((name (js2-create-name-node t))
8162 pn member-expr)
8163 (cond
8164 ((js2-match-token js2-LP)
8165 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
8166 (js2-allow-member-expr-as-function-name
8167 (setq member-expr (js2-parse-member-expr-tail nil name))
8168 (js2-parse-highlight-member-expr-fn-name member-expr)
8169 (js2-must-match js2-LP "msg.no.paren.parms")
8170 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
8171 (js2-function-node-member-expr pn) member-expr)
8172 pn)
8173 (t
8174 (js2-report-error "msg.no.paren.parms")
8175 (make-js2-error-node))))))
8176
8177 (defun js2-parse-function-expr ()
8178 (let ((pos (js2-current-token-beg))
8179 (star-p (js2-match-token js2-MUL))
8180 name)
8181 (when (js2-match-token js2-NAME)
8182 (setq name (js2-create-name-node t)))
8183 (js2-must-match js2-LP "msg.no.paren.parms")
8184 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
8185
8186 (defun js2-parse-function (function-type pos star-p &optional name)
8187 "Function parser. FUNCTION-TYPE is a symbol, POS is the
8188 beginning of the first token (function keyword, unless it's an
8189 arrow function), NAME is js2-name-node."
8190 (let (fn-node lp)
8191 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
8192 (setq lp (js2-current-token-beg)))
8193 (setf fn-node (make-js2-function-node :pos pos
8194 :name name
8195 :form function-type
8196 :lp (if lp (- lp pos))
8197 :generator-type (and star-p 'STAR)))
8198 (when name
8199 (js2-set-face (js2-node-pos name) (js2-node-end name)
8200 'font-lock-function-name-face 'record)
8201 (when (and (eq function-type 'FUNCTION_STATEMENT)
8202 (cl-plusp (js2-name-node-length name)))
8203 ;; Function statements define a symbol in the enclosing scope
8204 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
8205 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
8206 ;; 1. Nested functions are not affected by the dynamic scope flag
8207 ;; as dynamic scope is already a parent of their scope.
8208 ;; 2. Functions defined under the with statement also immune to
8209 ;; this setup, in which case dynamic scope is ignored in favor
8210 ;; of the with object.
8211 (setf (js2-function-node-ignore-dynamic fn-node) t))
8212 ;; dynamically bind all the per-function variables
8213 (let ((js2-current-script-or-fn fn-node)
8214 (js2-current-scope fn-node)
8215 (js2-nesting-of-with 0)
8216 (js2-end-flags 0)
8217 js2-label-set
8218 js2-loop-set
8219 js2-loop-and-switch-set)
8220 (js2-parse-function-params function-type fn-node pos)
8221 (when (eq function-type 'FUNCTION_ARROW)
8222 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
8223 (if (and (>= js2-language-version 180)
8224 (/= (js2-peek-token) js2-LC))
8225 (js2-parse-function-closure-body fn-node)
8226 (js2-parse-function-body fn-node))
8227 (js2-check-inconsistent-return-warning fn-node name)
8228
8229 (when name
8230 (js2-node-add-children fn-node name)
8231 ;; Function expressions define a name only in the body of the
8232 ;; function, and only if not hidden by a parameter name
8233 (when (and (eq function-type 'FUNCTION_EXPRESSION)
8234 (null (js2-scope-get-symbol js2-current-scope
8235 (js2-name-node-name name))))
8236 (js2-define-symbol js2-FUNCTION
8237 (js2-name-node-name name)
8238 fn-node))
8239 (when (eq function-type 'FUNCTION_STATEMENT)
8240 (js2-record-imenu-functions fn-node))))
8241
8242 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
8243 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8244 ;; We wait until after parsing the function to set its parent scope,
8245 ;; since `js2-define-symbol' needs the defining-scope check to stop
8246 ;; at the function boundary when checking for redeclarations.
8247 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8248 fn-node))
8249
8250 (defun js2-parse-statements (&optional parent)
8251 "Parse a statement list. Last token consumed must be js2-LC.
8252
8253 PARENT can be a `js2-block-node', in which case the statements are
8254 appended to PARENT. Otherwise a new `js2-block-node' is created
8255 and returned.
8256
8257 This function does not match the closing js2-RC: the caller
8258 matches the RC so it can provide a suitable error message if not
8259 matched. This means it's up to the caller to set the length of
8260 the node to include the closing RC. The node start pos is set to
8261 the absolute buffer start position, and the caller should fix it
8262 up to be relative to the parent node. All children of this block
8263 node are given relative start positions and correct lengths."
8264 (let ((pn (or parent (make-js2-block-node)))
8265 tt)
8266 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8267 (/= tt js2-RC))
8268 (js2-block-node-push pn (js2-parse-statement)))
8269 pn))
8270
8271 (defun js2-parse-statement ()
8272 (let (pn beg end)
8273 ;; coarse-grained user-interrupt check - needs work
8274 (and js2-parse-interruptable-p
8275 (zerop (% (cl-incf js2-parse-stmt-count)
8276 js2-statements-per-pause))
8277 (input-pending-p)
8278 (throw 'interrupted t))
8279 (setq pn (js2-statement-helper))
8280 ;; no-side-effects warning check
8281 (unless (js2-node-has-side-effects pn)
8282 (setq end (js2-node-end pn))
8283 (save-excursion
8284 (goto-char end)
8285 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8286 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8287 pn))
8288
8289 ;; These correspond to the switch cases in Parser.statementHelper
8290 (defconst js2-parsers
8291 (let ((parsers (make-vector js2-num-tokens
8292 #'js2-parse-expr-stmt)))
8293 (aset parsers js2-BREAK #'js2-parse-break)
8294 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8295 (aset parsers js2-CONST #'js2-parse-const-var)
8296 (aset parsers js2-CONTINUE #'js2-parse-continue)
8297 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8298 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8299 (aset parsers js2-DO #'js2-parse-do)
8300 (aset parsers js2-EXPORT #'js2-parse-export)
8301 (aset parsers js2-FOR #'js2-parse-for)
8302 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8303 (aset parsers js2-IF #'js2-parse-if)
8304 (aset parsers js2-IMPORT #'js2-parse-import)
8305 (aset parsers js2-LC #'js2-parse-block)
8306 (aset parsers js2-LET #'js2-parse-let-stmt)
8307 (aset parsers js2-NAME #'js2-parse-name-or-label)
8308 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8309 (aset parsers js2-SEMI #'js2-parse-semi)
8310 (aset parsers js2-SWITCH #'js2-parse-switch)
8311 (aset parsers js2-THROW #'js2-parse-throw)
8312 (aset parsers js2-TRY #'js2-parse-try)
8313 (aset parsers js2-VAR #'js2-parse-const-var)
8314 (aset parsers js2-WHILE #'js2-parse-while)
8315 (aset parsers js2-WITH #'js2-parse-with)
8316 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8317 parsers)
8318 "A vector mapping token types to parser functions.")
8319
8320 (defun js2-parse-warn-missing-semi (beg end)
8321 (and js2-mode-show-strict-warnings
8322 js2-strict-missing-semi-warning
8323 (js2-add-strict-warning
8324 "msg.missing.semi" nil
8325 ;; back up to beginning of statement or line
8326 (max beg (save-excursion
8327 (goto-char end)
8328 (point-at-bol)))
8329 end)))
8330
8331 (defconst js2-no-semi-insertion
8332 (list js2-IF
8333 js2-SWITCH
8334 js2-WHILE
8335 js2-DO
8336 js2-FOR
8337 js2-TRY
8338 js2-WITH
8339 js2-LC
8340 js2-ERROR
8341 js2-SEMI
8342 js2-CLASS
8343 js2-FUNCTION
8344 js2-EXPORT)
8345 "List of tokens that don't do automatic semicolon insertion.")
8346
8347 (defconst js2-autoinsert-semi-and-warn
8348 (list js2-ERROR js2-EOF js2-RC))
8349
8350 (defun js2-statement-helper ()
8351 (let* ((tt (js2-get-token))
8352 (first-tt tt)
8353 (parser (if (= tt js2-ERROR)
8354 #'js2-parse-semi
8355 (aref js2-parsers tt)))
8356 pn)
8357 ;; If the statement is set, then it's been told its label by now.
8358 (and js2-labeled-stmt
8359 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8360 (setq js2-labeled-stmt nil))
8361 (setq pn (funcall parser))
8362 ;; Don't do auto semi insertion for certain statement types.
8363 (unless (or (memq first-tt js2-no-semi-insertion)
8364 (js2-labeled-stmt-node-p pn))
8365 (js2-auto-insert-semicolon pn))
8366 pn))
8367
8368 (defun js2-auto-insert-semicolon (pn)
8369 (let* ((tt (js2-get-token))
8370 (pos (js2-node-pos pn)))
8371 (cond
8372 ((= tt js2-SEMI)
8373 ;; extend the node bounds to include the semicolon.
8374 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8375 ((memq tt js2-autoinsert-semi-and-warn)
8376 (js2-unget-token) ; Not ';', do not consume.
8377 ;; Autoinsert ;
8378 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8379 (t
8380 (if (not (js2-token-follows-eol-p (js2-current-token)))
8381 ;; Report error if no EOL or autoinsert ';' otherwise
8382 (js2-report-error "msg.no.semi.stmt")
8383 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8384 (js2-unget-token) ; Not ';', do not consume.
8385 ))))
8386
8387 (defun js2-parse-condition ()
8388 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8389 The parens are discarded and the expression node is returned.
8390 The `pos' field of the return value is set to an absolute position
8391 that must be fixed up by the caller.
8392 Return value is a list (EXPR LP RP), with absolute paren positions."
8393 (let (pn lp rp)
8394 (if (js2-must-match js2-LP "msg.no.paren.cond")
8395 (setq lp (js2-current-token-beg)))
8396 (setq pn (js2-parse-expr))
8397 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8398 (setq rp (js2-current-token-beg)))
8399 ;; Report strict warning on code like "if (a = 7) ..."
8400 (if (and js2-strict-cond-assign-warning
8401 (js2-assign-node-p pn))
8402 (js2-add-strict-warning "msg.equal.as.assign" nil
8403 (js2-node-pos pn)
8404 (+ (js2-node-pos pn)
8405 (js2-node-len pn))))
8406 (list pn lp rp)))
8407
8408 (defun js2-parse-if ()
8409 "Parser for if-statement. Last matched token must be js2-IF."
8410 (let ((pos (js2-current-token-beg))
8411 cond if-true if-false else-pos end pn)
8412 (setq cond (js2-parse-condition)
8413 if-true (js2-parse-statement)
8414 if-false (if (js2-match-token js2-ELSE)
8415 (progn
8416 (setq else-pos (- (js2-current-token-beg) pos))
8417 (js2-parse-statement)))
8418 end (js2-node-end (or if-false if-true))
8419 pn (make-js2-if-node :pos pos
8420 :len (- end pos)
8421 :condition (car cond)
8422 :then-part if-true
8423 :else-part if-false
8424 :else-pos else-pos
8425 :lp (js2-relpos (cl-second cond) pos)
8426 :rp (js2-relpos (cl-third cond) pos)))
8427 (js2-node-add-children pn (car cond) if-true if-false)
8428 pn))
8429
8430 (defun js2-parse-import ()
8431 "Parse import statement. The current token must be js2-IMPORT."
8432 (unless (js2-ast-root-p js2-current-scope)
8433 (js2-report-error "msg.mod.import.decl.at.top.level"))
8434 (let ((beg (js2-current-token-beg)))
8435 (cond ((js2-match-token js2-STRING)
8436 (make-js2-import-node
8437 :pos beg
8438 :len (- (js2-current-token-end) beg)
8439 :module-id (js2-current-token-string)))
8440 (t
8441 (let* ((import-clause (js2-parse-import-clause))
8442 (from-clause (and import-clause (js2-parse-from-clause)))
8443 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8444 (node (make-js2-import-node
8445 :pos beg
8446 :len (- (js2-current-token-end) beg)
8447 :import import-clause
8448 :from from-clause
8449 :module-id module-id)))
8450 (when import-clause
8451 (js2-node-add-children node import-clause))
8452 (when from-clause
8453 (js2-node-add-children node from-clause))
8454 node)))))
8455
8456 (defun js2-parse-import-clause ()
8457 "Parse the bindings in an import statement.
8458 This can take many forms:
8459
8460 ImportedDefaultBinding -> 'foo'
8461 NameSpaceImport -> '* as lib'
8462 NamedImports -> '{foo as bar, bang}'
8463 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8464 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8465
8466 Try to match namespace imports and named imports first because nothing can
8467 come after them. If it is an imported default binding, then it could have named
8468 imports or a namespace import that follows it.
8469 "
8470 (let* ((beg (js2-current-token-beg))
8471 (clause (make-js2-import-clause-node
8472 :pos beg))
8473 (children (list)))
8474 (cond
8475 ((js2-match-token js2-MUL)
8476 (let ((ns-import (js2-parse-namespace-import)))
8477 (when ns-import
8478 (let ((name-node (js2-namespace-import-node-name ns-import)))
8479 (js2-define-symbol
8480 js2-LET (js2-name-node-name name-node) name-node t)))
8481 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8482 (push ns-import children)))
8483 ((js2-match-token js2-LC)
8484 (let ((imports (js2-parse-export-bindings t)))
8485 (setf (js2-import-clause-node-named-imports clause) imports)
8486 (dolist (import imports)
8487 (push import children)
8488 (let ((name-node (js2-export-binding-node-local-name import)))
8489 (when name-node
8490 (js2-define-symbol
8491 js2-LET (js2-name-node-name name-node) name-node t))))))
8492 ((= (js2-peek-token) js2-NAME)
8493 (let ((binding (js2-maybe-parse-export-binding)))
8494 (let ((node-name (js2-export-binding-node-local-name binding)))
8495 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8496 (setf (js2-import-clause-node-default-binding clause) binding)
8497 (push binding children))
8498 (when (js2-match-token js2-COMMA)
8499 (cond
8500 ((js2-match-token js2-MUL)
8501 (let ((ns-import (js2-parse-namespace-import)))
8502 (let ((name-node (js2-namespace-import-node-name ns-import)))
8503 (js2-define-symbol
8504 js2-LET (js2-name-node-name name-node) name-node t))
8505 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8506 (push ns-import children)))
8507 ((js2-match-token js2-LC)
8508 (let ((imports (js2-parse-export-bindings t)))
8509 (setf (js2-import-clause-node-named-imports clause) imports)
8510 (dolist (import imports)
8511 (push import children)
8512 (let ((name-node (js2-export-binding-node-local-name import)))
8513 (when name-node
8514 (js2-define-symbol
8515 js2-LET (js2-name-node-name name-node) name-node t))))))
8516 (t (js2-report-error "msg.syntax")))))
8517 (t (js2-report-error "msg.mod.declaration.after.import")))
8518 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8519 (apply #'js2-node-add-children clause children)
8520 clause))
8521
8522 (defun js2-parse-namespace-import ()
8523 "Parse a namespace import expression such as '* as bar'.
8524 The current token must be js2-MUL."
8525 (let ((beg (js2-current-token-beg)))
8526 (when (js2-must-match js2-NAME "msg.syntax")
8527 (if (equal "as" (js2-current-token-string))
8528 (when (js2-must-match-prop-name "msg.syntax")
8529 (let ((node (make-js2-namespace-import-node
8530 :pos beg
8531 :len (- (js2-current-token-end) beg)
8532 :name (make-js2-name-node
8533 :pos (js2-current-token-beg)
8534 :len (js2-current-token-end)
8535 :name (js2-current-token-string)))))
8536 (js2-node-add-children node (js2-namespace-import-node-name node))
8537 node))
8538 (js2-unget-token)
8539 (js2-report-error "msg.syntax")))))
8540
8541
8542 (defun js2-parse-from-clause ()
8543 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8544 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8545 (let ((beg (js2-current-token-beg)))
8546 (if (equal "from" (js2-current-token-string))
8547 (cond
8548 ((js2-match-token js2-STRING)
8549 (make-js2-from-clause-node
8550 :pos beg
8551 :len (- (js2-current-token-end) beg)
8552 :module-id (js2-current-token-string)
8553 :metadata-p nil))
8554 ((js2-match-token js2-THIS)
8555 (when (js2-must-match-name "msg.mod.spec.after.from")
8556 (if (equal "module" (js2-current-token-string))
8557 (make-js2-from-clause-node
8558 :pos beg
8559 :len (- (js2-current-token-end) beg)
8560 :module-id "this"
8561 :metadata-p t)
8562 (js2-unget-token)
8563 (js2-unget-token)
8564 (js2-report-error "msg.mod.spec.after.from")
8565 nil)))
8566 (t (js2-report-error "msg.mod.spec.after.from") nil))
8567 (js2-unget-token)
8568 (js2-report-error "msg.mod.from.after.import.spec.set")
8569 nil))))
8570
8571 (defun js2-parse-export-bindings (&optional import-p)
8572 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8573 {foo as bar, baz as bang}. The current token must be
8574 js2-LC. Return a lisp list of js2-export-binding-node"
8575 (let ((bindings (list)))
8576 (while
8577 (let ((binding (js2-maybe-parse-export-binding)))
8578 (when binding
8579 (push binding bindings))
8580 (js2-match-token js2-COMMA)))
8581 (when (js2-must-match js2-RC (if import-p
8582 "msg.mod.rc.after.import.spec.list"
8583 "msg.mod.rc.after.export.spec.list"))
8584 (reverse bindings))))
8585
8586 (defun js2-maybe-parse-export-binding ()
8587 "Attempt to parse a binding expression found inside an import/export statement.
8588 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8589 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8590 js2-export-binding-node and consume all the tokens. If it does not match, it
8591 consumes no tokens."
8592 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8593 (beg (js2-current-token-beg))
8594 (extern-name-len (js2-current-token-len))
8595 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8596 (aref js2-kwd-tokens (js2-current-token-type)))))
8597 (if extern-name
8598 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8599 (if (and as (equal "as" (js2-current-token-string)))
8600 (let ((name
8601 (or
8602 (and (js2-match-token js2-DEFAULT) "default")
8603 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8604 (if name
8605 (let ((node (make-js2-export-binding-node
8606 :pos beg
8607 :len (- (js2-current-token-end) beg)
8608 :local-name (make-js2-name-node
8609 :name name
8610 :pos (js2-current-token-beg)
8611 :len (js2-current-token-len))
8612 :extern-name (make-js2-name-node
8613 :name extern-name
8614 :pos beg
8615 :len extern-name-len))))
8616 (js2-node-add-children
8617 node
8618 (js2-export-binding-node-local-name node)
8619 (js2-export-binding-node-extern-name node))
8620 node)
8621 (js2-unget-token)
8622 nil))
8623 (when as (js2-unget-token))
8624 (let* ((name-node (make-js2-name-node
8625 :name (js2-current-token-string)
8626 :pos (js2-current-token-beg)
8627 :len (js2-current-token-len)))
8628 (node (make-js2-export-binding-node
8629 :pos (js2-current-token-beg)
8630 :len (js2-current-token-len)
8631 :local-name name-node
8632 :extern-name name-node)))
8633 (when is-reserved-name
8634 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8635 (js2-node-add-children node name-node)
8636 node)))
8637 nil)))
8638
8639 (defun js2-parse-switch ()
8640 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8641 (let ((pos (js2-current-token-beg))
8642 tt pn discriminant has-default case-expr case-node
8643 case-pos cases stmt lp)
8644 (if (js2-must-match js2-LP "msg.no.paren.switch")
8645 (setq lp (js2-current-token-beg)))
8646 (setq discriminant (js2-parse-expr)
8647 pn (make-js2-switch-node :discriminant discriminant
8648 :pos pos
8649 :lp (js2-relpos lp pos)))
8650 (js2-node-add-children pn discriminant)
8651 (js2-enter-switch pn)
8652 (unwind-protect
8653 (progn
8654 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8655 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8656 (js2-must-match js2-LC "msg.no.brace.switch")
8657 (catch 'break
8658 (while t
8659 (setq tt (js2-next-token)
8660 case-pos (js2-current-token-beg))
8661 (cond
8662 ((= tt js2-RC)
8663 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8664 (throw 'break nil)) ; done
8665 ((= tt js2-CASE)
8666 (setq case-expr (js2-parse-expr))
8667 (js2-must-match js2-COLON "msg.no.colon.case"))
8668 ((= tt js2-DEFAULT)
8669 (if has-default
8670 (js2-report-error "msg.double.switch.default"))
8671 (setq has-default t
8672 case-expr nil)
8673 (js2-must-match js2-COLON "msg.no.colon.case"))
8674 (t
8675 (js2-report-error "msg.bad.switch")
8676 (throw 'break nil)))
8677 (setq case-node (make-js2-case-node :pos case-pos
8678 :len (- (js2-current-token-end) case-pos)
8679 :expr case-expr))
8680 (js2-node-add-children case-node case-expr)
8681 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8682 (/= tt js2-CASE)
8683 (/= tt js2-DEFAULT)
8684 (/= tt js2-EOF))
8685 (setf stmt (js2-parse-statement)
8686 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8687 (js2-block-node-push case-node stmt))
8688 (push case-node cases)))
8689 ;; add cases last, as pushing reverses the order to be correct
8690 (dolist (kid cases)
8691 (js2-node-add-children pn kid)
8692 (push kid (js2-switch-node-cases pn)))
8693 pn) ; return value
8694 (js2-exit-switch))))
8695
8696 (defun js2-parse-while ()
8697 "Parser for while-statement. Last matched token must be js2-WHILE."
8698 (let ((pos (js2-current-token-beg))
8699 (pn (make-js2-while-node))
8700 cond body)
8701 (js2-enter-loop pn)
8702 (unwind-protect
8703 (progn
8704 (setf cond (js2-parse-condition)
8705 (js2-while-node-condition pn) (car cond)
8706 body (js2-parse-statement)
8707 (js2-while-node-body pn) body
8708 (js2-node-len pn) (- (js2-node-end body) pos)
8709 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8710 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8711 (js2-node-add-children pn body (car cond)))
8712 (js2-exit-loop))
8713 pn))
8714
8715 (defun js2-parse-do ()
8716 "Parser for do-statement. Last matched token must be js2-DO."
8717 (let ((pos (js2-current-token-beg))
8718 (pn (make-js2-do-node))
8719 cond body end)
8720 (js2-enter-loop pn)
8721 (unwind-protect
8722 (progn
8723 (setq body (js2-parse-statement))
8724 (js2-must-match js2-WHILE "msg.no.while.do")
8725 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8726 cond (js2-parse-condition)
8727 (js2-do-node-condition pn) (car cond)
8728 (js2-do-node-body pn) body
8729 end js2-ts-cursor
8730 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8731 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8732 (js2-node-add-children pn (car cond) body))
8733 (js2-exit-loop))
8734 ;; Always auto-insert semicolon to follow SpiderMonkey:
8735 ;; It is required by ECMAScript but is ignored by the rest of
8736 ;; world; see bug 238945
8737 (if (js2-match-token js2-SEMI)
8738 (setq end js2-ts-cursor))
8739 (setf (js2-node-len pn) (- end pos))
8740 pn))
8741
8742 (defun js2-parse-export ()
8743 "Parse an export statement.
8744 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8745 expressions should only be either hoistable expressions (function or generator)
8746 or assignment expressions, but there is no checking to enforce that and so it
8747 will parse without error a small subset of
8748 invalid export statements."
8749 (unless (js2-ast-root-p js2-current-scope)
8750 (js2-report-error "msg.mod.export.decl.at.top.level"))
8751 (let ((beg (js2-current-token-beg))
8752 (children (list))
8753 exports-list from-clause declaration default)
8754 (cond
8755 ((js2-match-token js2-MUL)
8756 (setq from-clause (js2-parse-from-clause))
8757 (when from-clause
8758 (push from-clause children)))
8759 ((js2-match-token js2-LC)
8760 (setq exports-list (js2-parse-export-bindings))
8761 (when exports-list
8762 (dolist (export exports-list)
8763 (push export children)))
8764 (when (js2-match-token js2-NAME)
8765 (if (equal "from" (js2-current-token-string))
8766 (progn
8767 (js2-unget-token)
8768 (setq from-clause (js2-parse-from-clause)))
8769 (js2-unget-token))))
8770 ((js2-match-token js2-DEFAULT)
8771 (setq default (js2-parse-expr)))
8772 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8773 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8774 (t
8775 (setq declaration (js2-parse-expr))))
8776 (when from-clause
8777 (push from-clause children))
8778 (when declaration
8779 (push declaration children)
8780 (when (not (js2-function-node-p declaration))
8781 (js2-auto-insert-semicolon declaration)))
8782 (when default
8783 (push default children)
8784 (when (not (js2-function-node-p default))
8785 (js2-auto-insert-semicolon default)))
8786 (let ((node (make-js2-export-node
8787 :pos beg
8788 :len (- (js2-current-token-end) beg)
8789 :exports-list exports-list
8790 :from-clause from-clause
8791 :declaration declaration
8792 :default default)))
8793 (apply #'js2-node-add-children node children)
8794 node)))
8795
8796 (defun js2-parse-for ()
8797 "Parse a for, for-in or for each-in statement.
8798 Last matched token must be js2-FOR."
8799 (let ((for-pos (js2-current-token-beg))
8800 (tmp-scope (make-js2-scope))
8801 pn is-for-each is-for-in-or-of is-for-of
8802 in-pos each-pos tmp-pos
8803 init ; Node init is also foo in 'foo in object'.
8804 cond ; Node cond is also object in 'foo in object'.
8805 incr ; 3rd section of for-loop initializer.
8806 body tt lp rp)
8807 ;; See if this is a for each () instead of just a for ()
8808 (when (js2-match-token js2-NAME)
8809 (if (string= "each" (js2-current-token-string))
8810 (progn
8811 (setq is-for-each t
8812 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8813 (js2-record-face 'font-lock-keyword-face))
8814 (js2-report-error "msg.no.paren.for")))
8815 (if (js2-must-match js2-LP "msg.no.paren.for")
8816 (setq lp (- (js2-current-token-beg) for-pos)))
8817 (setq tt (js2-get-token))
8818 ;; Capture identifiers inside parens. We can't create the node
8819 ;; (and use it as the current scope) until we know its type.
8820 (js2-push-scope tmp-scope)
8821 (unwind-protect
8822 (progn
8823 ;; parse init clause
8824 (let ((js2-in-for-init t)) ; set as dynamic variable
8825 (cond
8826 ((= tt js2-SEMI)
8827 (js2-unget-token)
8828 (setq init (make-js2-empty-expr-node)))
8829 ((or (= tt js2-VAR) (= tt js2-LET))
8830 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8831 (t
8832 (js2-unget-token)
8833 (setq init (js2-parse-expr)))))
8834 (if (or (js2-match-token js2-IN)
8835 (and (>= js2-language-version 200)
8836 (js2-match-contextual-kwd "of")
8837 (setq is-for-of t)))
8838 (setq is-for-in-or-of t
8839 in-pos (- (js2-current-token-beg) for-pos)
8840 ;; scope of iteration target object is not the scope we've created above.
8841 ;; stash current scope temporary.
8842 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8843 (js2-parse-expr))) ; object over which we're iterating
8844 ;; else ordinary for loop - parse cond and incr
8845 (js2-must-match js2-SEMI "msg.no.semi.for")
8846 (setq cond (if (= (js2-peek-token) js2-SEMI)
8847 (make-js2-empty-expr-node) ; no loop condition
8848 (js2-parse-expr)))
8849 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8850 (setq tmp-pos (js2-current-token-end)
8851 incr (if (= (js2-peek-token) js2-RP)
8852 (make-js2-empty-expr-node :pos tmp-pos)
8853 (js2-parse-expr)))))
8854 (js2-pop-scope))
8855 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8856 (setq rp (- (js2-current-token-beg) for-pos)))
8857 (if (not is-for-in-or-of)
8858 (setq pn (make-js2-for-node :init init
8859 :condition cond
8860 :update incr
8861 :lp lp
8862 :rp rp))
8863 ;; cond could be null if 'in obj' got eaten by the init node.
8864 (if (js2-infix-node-p init)
8865 ;; it was (foo in bar) instead of (var foo in bar)
8866 (setq cond (js2-infix-node-right init)
8867 init (js2-infix-node-left init))
8868 (if (and (js2-var-decl-node-p init)
8869 (> (length (js2-var-decl-node-kids init)) 1))
8870 (js2-report-error "msg.mult.index")))
8871 (setq pn (make-js2-for-in-node :iterator init
8872 :object cond
8873 :in-pos in-pos
8874 :foreach-p is-for-each
8875 :each-pos each-pos
8876 :forof-p is-for-of
8877 :lp lp
8878 :rp rp)))
8879 ;; Transplant the declarations.
8880 (setf (js2-scope-symbol-table pn)
8881 (js2-scope-symbol-table tmp-scope))
8882 (unwind-protect
8883 (progn
8884 (js2-enter-loop pn)
8885 ;; We have to parse the body -after- creating the loop node,
8886 ;; so that the loop node appears in the js2-loop-set, allowing
8887 ;; break/continue statements to find the enclosing loop.
8888 (setf body (js2-parse-statement)
8889 (js2-loop-node-body pn) body
8890 (js2-node-pos pn) for-pos
8891 (js2-node-len pn) (- (js2-node-end body) for-pos))
8892 (js2-node-add-children pn init cond incr body))
8893 ;; finally
8894 (js2-exit-loop))
8895 pn))
8896
8897 (defun js2-parse-try ()
8898 "Parse a try statement. Last matched token must be js2-TRY."
8899 (let ((try-pos (js2-current-token-beg))
8900 try-end
8901 try-block
8902 catch-blocks
8903 finally-block
8904 saw-default-catch
8905 peek)
8906 (if (/= (js2-peek-token) js2-LC)
8907 (js2-report-error "msg.no.brace.try"))
8908 (setq try-block (js2-parse-statement)
8909 try-end (js2-node-end try-block)
8910 peek (js2-peek-token))
8911 (cond
8912 ((= peek js2-CATCH)
8913 (while (js2-match-token js2-CATCH)
8914 (let* ((catch-pos (js2-current-token-beg))
8915 (catch-node (make-js2-catch-node :pos catch-pos))
8916 param
8917 guard-kwd
8918 catch-cond
8919 lp rp)
8920 (if saw-default-catch
8921 (js2-report-error "msg.catch.unreachable"))
8922 (if (js2-must-match js2-LP "msg.no.paren.catch")
8923 (setq lp (- (js2-current-token-beg) catch-pos)))
8924 (js2-push-scope catch-node)
8925 (let ((tt (js2-peek-token)))
8926 (cond
8927 ;; Destructuring pattern:
8928 ;; catch ({ message, file }) { ... }
8929 ((or (= tt js2-LB) (= tt js2-LC))
8930 (js2-get-token)
8931 (setq param (js2-parse-destruct-primary-expr))
8932 (js2-define-destruct-symbols param js2-LET nil))
8933 ;; Simple name.
8934 (t
8935 (js2-must-match-name "msg.bad.catchcond")
8936 (setq param (js2-create-name-node))
8937 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8938 ;; Catch condition.
8939 (if (js2-match-token js2-IF)
8940 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8941 catch-cond (js2-parse-expr))
8942 (setq saw-default-catch t))
8943 (if (js2-must-match js2-RP "msg.bad.catchcond")
8944 (setq rp (- (js2-current-token-beg) catch-pos)))
8945 (js2-must-match js2-LC "msg.no.brace.catchblock")
8946 (js2-parse-statements catch-node)
8947 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8948 (setq try-end (js2-current-token-end)))
8949 (js2-pop-scope)
8950 (setf (js2-node-len catch-node) (- try-end catch-pos)
8951 (js2-catch-node-param catch-node) param
8952 (js2-catch-node-guard-expr catch-node) catch-cond
8953 (js2-catch-node-guard-kwd catch-node) guard-kwd
8954 (js2-catch-node-lp catch-node) lp
8955 (js2-catch-node-rp catch-node) rp)
8956 (js2-node-add-children catch-node param catch-cond)
8957 (push catch-node catch-blocks))))
8958 ((/= peek js2-FINALLY)
8959 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8960 (js2-node-pos try-block)
8961 (- (setq try-end (js2-node-end try-block))
8962 (js2-node-pos try-block)))))
8963 (when (js2-match-token js2-FINALLY)
8964 (let ((finally-pos (js2-current-token-beg))
8965 (block (js2-parse-statement)))
8966 (setq try-end (js2-node-end block)
8967 finally-block (make-js2-finally-node :pos finally-pos
8968 :len (- try-end finally-pos)
8969 :body block))
8970 (js2-node-add-children finally-block block)))
8971 (let ((pn (make-js2-try-node :pos try-pos
8972 :len (- try-end try-pos)
8973 :try-block try-block
8974 :finally-block finally-block)))
8975 (js2-node-add-children pn try-block finally-block)
8976 ;; Push them onto the try-node, which reverses and corrects their order.
8977 (dolist (cb catch-blocks)
8978 (js2-node-add-children pn cb)
8979 (push cb (js2-try-node-catch-clauses pn)))
8980 pn)))
8981
8982 (defun js2-parse-throw ()
8983 "Parser for throw-statement. Last matched token must be js2-THROW."
8984 (let ((pos (js2-current-token-beg))
8985 expr pn)
8986 (if (= (js2-peek-token-or-eol) js2-EOL)
8987 ;; ECMAScript does not allow new lines before throw expression,
8988 ;; see bug 256617
8989 (js2-report-error "msg.bad.throw.eol"))
8990 (setq expr (js2-parse-expr)
8991 pn (make-js2-throw-node :pos pos
8992 :len (- (js2-node-end expr) pos)
8993 :expr expr))
8994 (js2-node-add-children pn expr)
8995 pn))
8996
8997 (defun js2-match-jump-label-name (label-name)
8998 "If break/continue specified a label, return that label's labeled stmt.
8999 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
9000 does not match an existing label, reports an error and returns nil."
9001 (let ((bundle (cdr (assoc label-name js2-label-set))))
9002 (if (null bundle)
9003 (js2-report-error "msg.undef.label"))
9004 bundle))
9005
9006 (defun js2-parse-break ()
9007 "Parser for break-statement. Last matched token must be js2-BREAK."
9008 (let ((pos (js2-current-token-beg))
9009 (end (js2-current-token-end))
9010 break-target ; statement to break from
9011 break-label ; in "break foo", name-node representing the foo
9012 labels ; matching labeled statement to break to
9013 pn)
9014 (when (eq (js2-peek-token-or-eol) js2-NAME)
9015 (js2-get-token)
9016 (setq break-label (js2-create-name-node)
9017 end (js2-node-end break-label)
9018 ;; matchJumpLabelName only matches if there is one
9019 labels (js2-match-jump-label-name (js2-current-token-string))
9020 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
9021 (unless (or break-target break-label)
9022 ;; no break target specified - try for innermost enclosing loop/switch
9023 (if (null js2-loop-and-switch-set)
9024 (unless break-label
9025 (js2-report-error "msg.bad.break" nil pos (length "break")))
9026 (setq break-target (car js2-loop-and-switch-set))))
9027 (setq pn (make-js2-break-node :pos pos
9028 :len (- end pos)
9029 :label break-label
9030 :target break-target))
9031 (js2-node-add-children pn break-label) ; but not break-target
9032 pn))
9033
9034 (defun js2-parse-continue ()
9035 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
9036 (let ((pos (js2-current-token-beg))
9037 (end (js2-current-token-end))
9038 label ; optional user-specified label, a `js2-name-node'
9039 labels ; current matching labeled stmt, if any
9040 target ; the `js2-loop-node' target of this continue stmt
9041 pn)
9042 (when (= (js2-peek-token-or-eol) js2-NAME)
9043 (js2-get-token)
9044 (setq label (js2-create-name-node)
9045 end (js2-node-end label)
9046 ;; matchJumpLabelName only matches if there is one
9047 labels (js2-match-jump-label-name (js2-current-token-string))))
9048 (cond
9049 ((null labels) ; no current label to go to
9050 (if (null js2-loop-set) ; no loop to continue to
9051 (js2-report-error "msg.continue.outside" nil pos
9052 (length "continue"))
9053 (setq target (car js2-loop-set)))) ; innermost enclosing loop
9054 (t
9055 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
9056 (setq target (js2-labeled-stmt-node-stmt labels))
9057 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
9058 (setq pn (make-js2-continue-node :pos pos
9059 :len (- end pos)
9060 :label label
9061 :target target))
9062 (js2-node-add-children pn label) ; but not target - it's not our child
9063 pn))
9064
9065 (defun js2-parse-with ()
9066 "Parser for with-statement. Last matched token must be js2-WITH."
9067 (let ((pos (js2-current-token-beg))
9068 obj body pn lp rp)
9069 (if (js2-must-match js2-LP "msg.no.paren.with")
9070 (setq lp (js2-current-token-beg)))
9071 (setq obj (js2-parse-expr))
9072 (if (js2-must-match js2-RP "msg.no.paren.after.with")
9073 (setq rp (js2-current-token-beg)))
9074 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
9075 (setq body (js2-parse-statement)))
9076 (setq pn (make-js2-with-node :pos pos
9077 :len (- (js2-node-end body) pos)
9078 :object obj
9079 :body body
9080 :lp (js2-relpos lp pos)
9081 :rp (js2-relpos rp pos)))
9082 (js2-node-add-children pn obj body)
9083 pn))
9084
9085 (defun js2-parse-const-var ()
9086 "Parser for var- or const-statement.
9087 Last matched token must be js2-CONST or js2-VAR."
9088 (let ((tt (js2-current-token-type))
9089 (pos (js2-current-token-beg))
9090 expr pn)
9091 (setq expr (js2-parse-variables tt (js2-current-token-beg))
9092 pn (make-js2-expr-stmt-node :pos pos
9093 :len (- (js2-node-end expr) pos)
9094 :expr expr))
9095 (js2-node-add-children pn expr)
9096 pn))
9097
9098 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
9099 (let ((pn (make-js2-expr-stmt-node :pos pos
9100 :len (js2-node-len expr)
9101 :type (if (js2-inside-function)
9102 js2-EXPR_VOID
9103 js2-EXPR_RESULT)
9104 :expr expr)))
9105 (if add-child
9106 (js2-node-add-children pn expr))
9107 pn))
9108
9109 (defun js2-parse-let-stmt ()
9110 "Parser for let-statement. Last matched token must be js2-LET."
9111 (let ((pos (js2-current-token-beg))
9112 expr pn)
9113 (if (= (js2-peek-token) js2-LP)
9114 ;; let expression in statement context
9115 (setq expr (js2-parse-let pos 'statement)
9116 pn (js2-wrap-with-expr-stmt pos expr t))
9117 ;; else we're looking at a statement like let x=6, y=7;
9118 (setf expr (js2-parse-variables js2-LET pos)
9119 pn (js2-wrap-with-expr-stmt pos expr t)
9120 (js2-node-type pn) js2-EXPR_RESULT))
9121 pn))
9122
9123 (defun js2-parse-ret-yield ()
9124 (js2-parse-return-or-yield (js2-current-token-type) nil))
9125
9126 (defconst js2-parse-return-stmt-enders
9127 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
9128
9129 (defsubst js2-now-all-set (before after mask)
9130 "Return whether or not the bits in the mask have changed to all set.
9131 BEFORE is bits before change, AFTER is bits after change, and MASK is
9132 the mask for bits. Returns t if all the bits in the mask are set in AFTER
9133 but not BEFORE."
9134 (and (/= (logand before mask) mask)
9135 (= (logand after mask) mask)))
9136
9137 (defun js2-parse-return-or-yield (tt expr-context)
9138 (let* ((pos (js2-current-token-beg))
9139 (end (js2-current-token-end))
9140 (before js2-end-flags)
9141 (inside-function (js2-inside-function))
9142 (gen-type (and inside-function (js2-function-node-generator-type
9143 js2-current-script-or-fn)))
9144 e ret name yield-star-p)
9145 (unless inside-function
9146 (js2-report-error (if (eq tt js2-RETURN)
9147 "msg.bad.return"
9148 "msg.bad.yield")))
9149 (when (and inside-function
9150 (eq gen-type 'STAR)
9151 (js2-match-token js2-MUL))
9152 (setq yield-star-p t))
9153 ;; This is ugly, but we don't want to require a semicolon.
9154 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
9155 (setq e (js2-parse-expr)
9156 end (js2-node-end e)))
9157 (cond
9158 ((eq tt js2-RETURN)
9159 (js2-set-flag js2-end-flags (if (null e)
9160 js2-end-returns
9161 js2-end-returns-value))
9162 (setq ret (make-js2-return-node :pos pos
9163 :len (- end pos)
9164 :retval e))
9165 (js2-node-add-children ret e)
9166 ;; See if we need a strict mode warning.
9167 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
9168 ;; more thorough and accurate than this before/after flag check.
9169 ;; E.g. if there's a finally-block that always returns, we shouldn't
9170 ;; show a warning generated by inconsistent returns in the catch blocks.
9171 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
9172 ;; so we know which returns/yields to highlight, and we should get rid of
9173 ;; all the checking in `js2-parse-return-or-yield'.
9174 (if (and js2-strict-inconsistent-return-warning
9175 (js2-now-all-set before js2-end-flags
9176 (logior js2-end-returns js2-end-returns-value)))
9177 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
9178 ((eq gen-type 'COMPREHENSION)
9179 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
9180 ;; like SpiderMonkey does.
9181 (js2-report-error "msg.syntax" nil pos 5))
9182 (t
9183 (setq ret (make-js2-yield-node :pos pos
9184 :len (- end pos)
9185 :value e
9186 :star-p yield-star-p))
9187 (js2-node-add-children ret e)
9188 (unless expr-context
9189 (setq e ret
9190 ret (js2-wrap-with-expr-stmt pos e t))
9191 (js2-set-requires-activation)
9192 (js2-set-is-generator))))
9193 ;; see if we are mixing yields and value returns.
9194 (when (and inside-function
9195 (js2-flag-set-p js2-end-flags js2-end-returns-value)
9196 (eq (js2-function-node-generator-type js2-current-script-or-fn)
9197 'LEGACY))
9198 (setq name (js2-function-name js2-current-script-or-fn))
9199 (if (zerop (length name))
9200 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
9201 (js2-report-error "msg.generator.returns" name pos (- end pos))))
9202 ret))
9203
9204 (defun js2-parse-debugger ()
9205 (make-js2-keyword-node :type js2-DEBUGGER))
9206
9207 (defun js2-parse-block ()
9208 "Parser for a curly-delimited statement block.
9209 Last token matched must be `js2-LC'."
9210 (let ((pos (js2-current-token-beg))
9211 (pn (make-js2-scope)))
9212 (js2-push-scope pn)
9213 (unwind-protect
9214 (progn
9215 (js2-parse-statements pn)
9216 (js2-must-match js2-RC "msg.no.brace.block")
9217 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
9218 (js2-pop-scope))
9219 pn))
9220
9221 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
9222 (defun js2-parse-semi ()
9223 "Parse a statement or handle an error.
9224 Current token type is `js2-SEMI' or `js2-ERROR'."
9225 (let ((tt (js2-current-token-type)) pos len)
9226 (if (eq tt js2-SEMI)
9227 (make-js2-empty-expr-node :len 1)
9228 (setq pos (js2-current-token-beg)
9229 len (- (js2-current-token-end) pos))
9230 (js2-report-error "msg.syntax" nil pos len)
9231 (make-js2-error-node :pos pos :len len))))
9232
9233 (defun js2-parse-default-xml-namespace ()
9234 "Parse a `default xml namespace = <expr>' e4x statement."
9235 (let ((pos (js2-current-token-beg))
9236 end len expr unary)
9237 (js2-must-have-xml)
9238 (js2-set-requires-activation)
9239 (setq len (- js2-ts-cursor pos))
9240 (unless (and (js2-match-token js2-NAME)
9241 (string= (js2-current-token-string) "xml"))
9242 (js2-report-error "msg.bad.namespace" nil pos len))
9243 (unless (and (js2-match-token js2-NAME)
9244 (string= (js2-current-token-string) "namespace"))
9245 (js2-report-error "msg.bad.namespace" nil pos len))
9246 (unless (js2-match-token js2-ASSIGN)
9247 (js2-report-error "msg.bad.namespace" nil pos len))
9248 (setq expr (js2-parse-expr)
9249 end (js2-node-end expr)
9250 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9251 :pos pos
9252 :len (- end pos)
9253 :operand expr))
9254 (js2-node-add-children unary expr)
9255 (make-js2-expr-stmt-node :pos pos
9256 :len (- end pos)
9257 :expr unary)))
9258
9259 (defun js2-record-label (label bundle)
9260 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9261 (js2-get-token)
9262 (let ((name (js2-label-node-name label))
9263 labeled-stmt
9264 dup)
9265 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9266 ;; flag both labels if possible when used in editing mode
9267 (if (and js2-parse-ide-mode
9268 (setq dup (js2-get-label-by-name labeled-stmt name)))
9269 (js2-report-error "msg.dup.label" nil
9270 (js2-node-abs-pos dup) (js2-node-len dup)))
9271 (js2-report-error "msg.dup.label" nil
9272 (js2-node-pos label) (js2-node-len label)))
9273 (js2-labeled-stmt-node-add-label bundle label)
9274 (js2-node-add-children bundle label)
9275 ;; Add one reference to the bundle per label in `js2-label-set'
9276 (push (cons name bundle) js2-label-set)))
9277
9278 (defun js2-parse-name-or-label ()
9279 "Parser for identifier or label. Last token matched must be js2-NAME.
9280 Called when we found a name in a statement context. If it's a label, we gather
9281 up any following labels and the next non-label statement into a
9282 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9283 expression and return it wrapped in a `js2-expr-stmt-node'."
9284 (let ((pos (js2-current-token-beg))
9285 expr stmt bundle
9286 (continue t))
9287 ;; set check for label and call down to `js2-parse-primary-expr'
9288 (setq expr (js2-maybe-parse-label))
9289 (if (null expr)
9290 ;; Parse the non-label expression and wrap with expression stmt.
9291 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9292 ;; else parsed a label
9293 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9294 (js2-record-label expr bundle)
9295 ;; look for more labels
9296 (while (and continue (= (js2-get-token) js2-NAME))
9297 (if (setq expr (js2-maybe-parse-label))
9298 (js2-record-label expr bundle)
9299 (setq expr (js2-parse-expr)
9300 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9301 continue nil)
9302 (js2-auto-insert-semicolon stmt)))
9303 ;; no more labels; now parse the labeled statement
9304 (unwind-protect
9305 (unless stmt
9306 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9307 (js2-unget-token)
9308 (setq stmt (js2-statement-helper))))
9309 ;; remove the labels for this statement from the global set
9310 (dolist (label (js2-labeled-stmt-node-labels bundle))
9311 (setq js2-label-set (remove label js2-label-set))))
9312 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9313 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9314 (js2-node-add-children bundle stmt)
9315 bundle)))
9316
9317 (defun js2-maybe-parse-label ()
9318 (cl-assert (= (js2-current-token-type) js2-NAME))
9319 (let (label-pos
9320 (next-tt (js2-get-token))
9321 (label-end (js2-current-token-end)))
9322 ;; Do not consume colon, it is used as unwind indicator
9323 ;; to return to statementHelper.
9324 (js2-unget-token)
9325 (if (= next-tt js2-COLON)
9326 (prog2
9327 (setq label-pos (js2-current-token-beg))
9328 (make-js2-label-node :pos label-pos
9329 :len (- label-end label-pos)
9330 :name (js2-current-token-string))
9331 (js2-set-face label-pos
9332 label-end
9333 'font-lock-variable-name-face 'record))
9334 ;; Backtrack from the name token, too.
9335 (js2-unget-token)
9336 nil)))
9337
9338 (defun js2-parse-expr-stmt ()
9339 "Default parser in statement context, if no recognized statement found."
9340 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9341 (progn
9342 (js2-unget-token)
9343 (js2-parse-expr)) t))
9344
9345 (defun js2-parse-variables (decl-type pos)
9346 "Parse a comma-separated list of variable declarations.
9347 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9348
9349 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9350 For 'var' or 'const', the keyword should be the token last scanned.
9351
9352 POS is the position where the node should start. It's sometimes the
9353 var/const/let keyword, and other times the beginning of the first token
9354 in the first variable declaration.
9355
9356 Returns the parsed `js2-var-decl-node' expression node."
9357 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9358 :pos pos))
9359 destructuring kid-pos tt init name end nbeg nend vi
9360 (continue t))
9361 ;; Example:
9362 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9363 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9364 ;; var {a, b} = baz;
9365 (while continue
9366 (setq destructuring nil
9367 name nil
9368 tt (js2-get-token)
9369 kid-pos (js2-current-token-beg)
9370 end (js2-current-token-end)
9371 init nil)
9372 (if (or (= tt js2-LB) (= tt js2-LC))
9373 ;; Destructuring assignment, e.g., var [a, b] = ...
9374 (setq destructuring (js2-parse-destruct-primary-expr)
9375 end (js2-node-end destructuring))
9376 ;; Simple variable name
9377 (js2-unget-token)
9378 (when (js2-must-match-name "msg.bad.var")
9379 (setq name (js2-create-name-node)
9380 nbeg (js2-current-token-beg)
9381 nend (js2-current-token-end)
9382 end nend)
9383 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9384 (when (js2-match-token js2-ASSIGN)
9385 (setq init (js2-parse-assign-expr)
9386 end (js2-node-end init))
9387 (js2-record-imenu-functions init name))
9388 (when name
9389 (js2-set-face nbeg nend (if (js2-function-node-p init)
9390 'font-lock-function-name-face
9391 'font-lock-variable-name-face)
9392 'record))
9393 (setq vi (make-js2-var-init-node :pos kid-pos
9394 :len (- end kid-pos)
9395 :type decl-type))
9396 (if destructuring
9397 (progn
9398 (if (and (null init) (not js2-in-for-init))
9399 (js2-report-error "msg.destruct.assign.no.init"))
9400 (js2-define-destruct-symbols destructuring
9401 decl-type
9402 'font-lock-variable-name-face)
9403 (setf (js2-var-init-node-target vi) destructuring))
9404 (setf (js2-var-init-node-target vi) name))
9405 (setf (js2-var-init-node-initializer vi) init)
9406 (js2-node-add-children vi name destructuring init)
9407 (js2-block-node-push result vi)
9408 (unless (js2-match-token js2-COMMA)
9409 (setq continue nil)))
9410 (setf (js2-node-len result) (- end pos))
9411 result))
9412
9413 (defun js2-parse-let (pos &optional stmt-p)
9414 "Parse a let expression or statement.
9415 A let-expression is of the form `let (vars) expr'.
9416 A let-statement is of the form `let (vars) {statements}'.
9417 The third form of let is a variable declaration list, handled
9418 by `js2-parse-variables'."
9419 (let ((pn (make-js2-let-node :pos pos))
9420 beg vars body)
9421 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9422 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9423 (js2-push-scope pn)
9424 (unwind-protect
9425 (progn
9426 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9427 (if (js2-must-match js2-RP "msg.no.paren.let")
9428 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9429 (if (and stmt-p (js2-match-token js2-LC))
9430 ;; let statement
9431 (progn
9432 (setf beg (js2-current-token-beg) ; position stmt at LC
9433 body (js2-parse-statements))
9434 (js2-must-match js2-RC "msg.no.curly.let")
9435 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9436 (js2-node-len pn) (- (js2-current-token-end) pos)
9437 (js2-let-node-body pn) body
9438 (js2-node-type pn) js2-LET))
9439 ;; let expression
9440 (setf body (js2-parse-expr)
9441 (js2-node-len pn) (- (js2-node-end body) pos)
9442 (js2-let-node-body pn) body))
9443 (setf (js2-let-node-vars pn) vars)
9444 (js2-node-add-children pn vars body))
9445 (js2-pop-scope))
9446 pn))
9447
9448 (defun js2-define-new-symbol (decl-type name node &optional scope)
9449 (js2-scope-put-symbol (or scope js2-current-scope)
9450 name
9451 (make-js2-symbol decl-type name node)))
9452
9453 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9454 "Define a symbol in the current scope.
9455 If NODE is non-nil, it is the AST node associated with the symbol."
9456 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9457 (symbol (if defining-scope
9458 (js2-scope-get-symbol defining-scope name)))
9459 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9460 (pos (if node (js2-node-abs-pos node)))
9461 (len (if node (js2-node-len node))))
9462 (cond
9463 ((and symbol ; already defined
9464 (or (= sdt js2-CONST) ; old version is const
9465 (= decl-type js2-CONST) ; new version is const
9466 ;; two let-bound vars in this block have same name
9467 (and (= sdt js2-LET)
9468 (eq defining-scope js2-current-scope))))
9469 (js2-report-error
9470 (cond
9471 ((= sdt js2-CONST) "msg.const.redecl")
9472 ((= sdt js2-LET) "msg.let.redecl")
9473 ((= sdt js2-VAR) "msg.var.redecl")
9474 ((= sdt js2-FUNCTION) "msg.function.redecl")
9475 (t "msg.parm.redecl"))
9476 name pos len))
9477 ((or (= decl-type js2-LET)
9478 ;; strict mode const is scoped to the current LexicalEnvironment
9479 (and js2-in-use-strict-directive
9480 (= decl-type js2-CONST)))
9481 (if (and (= decl-type js2-LET)
9482 (not ignore-not-in-block)
9483 (or (= (js2-node-type js2-current-scope) js2-IF)
9484 (js2-loop-node-p js2-current-scope)))
9485 (js2-report-error "msg.let.decl.not.in.block")
9486 (js2-define-new-symbol decl-type name node)))
9487 ((or (= decl-type js2-VAR)
9488 (= decl-type js2-FUNCTION)
9489 ;; sloppy mode const is scoped to the current VariableEnvironment
9490 (and (not js2-in-use-strict-directive)
9491 (= decl-type js2-CONST)))
9492 (if symbol
9493 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9494 (js2-add-strict-warning "msg.var.redecl" name)
9495 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9496 (js2-add-strict-warning "msg.var.hides.arg" name)))
9497 (js2-define-new-symbol decl-type name node
9498 js2-current-script-or-fn)))
9499 ((= decl-type js2-LP)
9500 (if symbol
9501 ;; must be duplicate parameter. Second parameter hides the
9502 ;; first, so go ahead and add the second pararameter
9503 (js2-report-warning "msg.dup.parms" name))
9504 (js2-define-new-symbol decl-type name node))
9505 (t (js2-code-bug)))))
9506
9507 (defun js2-parse-paren-expr-or-generator-comp ()
9508 (let ((px-pos (js2-current-token-beg)))
9509 (cond
9510 ((and (>= js2-language-version 200)
9511 (js2-match-token js2-FOR))
9512 (js2-parse-generator-comp px-pos))
9513 ((and (>= js2-language-version 200)
9514 (js2-match-token js2-RP))
9515 ;; Not valid expression syntax, but this is valid in an arrow
9516 ;; function with no params: () => body.
9517 (if (eq (js2-peek-token) js2-ARROW)
9518 ;; Return whatever, it will hopefully be rewinded and
9519 ;; reparsed when we reach the =>.
9520 (make-js2-keyword-node :type js2-NULL)
9521 (js2-report-error "msg.syntax")
9522 (make-js2-error-node)))
9523 (t
9524 (let* ((js2-in-for-init nil)
9525 (expr (js2-parse-expr))
9526 (pn (make-js2-paren-node :pos px-pos
9527 :expr expr)))
9528 (js2-node-add-children pn (js2-paren-node-expr pn))
9529 (js2-must-match js2-RP "msg.no.paren")
9530 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9531 pn)))))
9532
9533 (defun js2-parse-expr (&optional oneshot)
9534 (let* ((pn (js2-parse-assign-expr))
9535 (pos (js2-node-pos pn))
9536 left
9537 right
9538 op-pos)
9539 (while (and (not oneshot)
9540 (js2-match-token js2-COMMA))
9541 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9542 (if (= (js2-peek-token) js2-YIELD)
9543 (js2-report-error "msg.yield.parenthesized"))
9544 (setq right (js2-parse-assign-expr)
9545 left pn
9546 pn (make-js2-infix-node :type js2-COMMA
9547 :pos pos
9548 :len (- js2-ts-cursor pos)
9549 :op-pos op-pos
9550 :left left
9551 :right right))
9552 (js2-node-add-children pn left right))
9553 pn))
9554
9555 (defun js2-parse-assign-expr ()
9556 (let ((tt (js2-get-token))
9557 (pos (js2-current-token-beg))
9558 pn left right op-pos
9559 ts-state recorded-identifiers parsed-errors)
9560 (if (= tt js2-YIELD)
9561 (js2-parse-return-or-yield tt t)
9562 ;; Save the tokenizer state in case we find an arrow function
9563 ;; and have to rewind.
9564 (setq ts-state (make-js2-ts-state)
9565 recorded-identifiers js2-recorded-identifiers
9566 parsed-errors js2-parsed-errors)
9567 ;; not yield - parse assignment expression
9568 (setq pn (js2-parse-cond-expr)
9569 tt (js2-get-token))
9570 (cond
9571 ((and (<= js2-first-assign tt)
9572 (<= tt js2-last-assign))
9573 ;; tt express assignment (=, |=, ^=, ..., %=)
9574 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9575 left pn)
9576 (setq right (js2-parse-assign-expr)
9577 pn (make-js2-assign-node :type tt
9578 :pos pos
9579 :len (- (js2-node-end right) pos)
9580 :op-pos op-pos
9581 :left left
9582 :right right))
9583 (when js2-parse-ide-mode
9584 (js2-highlight-assign-targets pn left right)
9585 (js2-record-imenu-functions right left))
9586 ;; do this last so ide checks above can use absolute positions
9587 (js2-node-add-children pn left right))
9588 ((and (= tt js2-ARROW)
9589 (>= js2-language-version 200))
9590 (js2-ts-seek ts-state)
9591 (setq js2-recorded-identifiers recorded-identifiers
9592 js2-parsed-errors parsed-errors)
9593 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9594 (t
9595 (js2-unget-token)))
9596 pn)))
9597
9598 (defun js2-parse-cond-expr ()
9599 (let ((pos (js2-current-token-beg))
9600 (pn (js2-parse-or-expr))
9601 test-expr
9602 if-true
9603 if-false
9604 q-pos
9605 c-pos)
9606 (when (js2-match-token js2-HOOK)
9607 (setq q-pos (- (js2-current-token-beg) pos)
9608 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9609 (js2-must-match js2-COLON "msg.no.colon.cond")
9610 (setq c-pos (- (js2-current-token-beg) pos)
9611 if-false (js2-parse-assign-expr)
9612 test-expr pn
9613 pn (make-js2-cond-node :pos pos
9614 :len (- (js2-node-end if-false) pos)
9615 :test-expr test-expr
9616 :true-expr if-true
9617 :false-expr if-false
9618 :q-pos q-pos
9619 :c-pos c-pos))
9620 (js2-node-add-children pn test-expr if-true if-false))
9621 pn))
9622
9623 (defun js2-make-binary (type left parser)
9624 "Helper for constructing a binary-operator AST node.
9625 LEFT is the left-side-expression, already parsed, and the
9626 binary operator should have just been matched.
9627 PARSER is a function to call to parse the right operand,
9628 or a `js2-node' struct if it has already been parsed.
9629 FIXME: The latter option is unused?"
9630 (let* ((pos (js2-node-pos left))
9631 (op-pos (- (js2-current-token-beg) pos))
9632 (right (if (js2-node-p parser)
9633 parser
9634 (js2-get-token)
9635 (funcall parser)))
9636 (pn (make-js2-infix-node :type type
9637 :pos pos
9638 :len (- (js2-node-end right) 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-or-expr ()
9646 (let ((pn (js2-parse-and-expr)))
9647 (when (js2-match-token js2-OR)
9648 (setq pn (js2-make-binary js2-OR
9649 pn
9650 'js2-parse-or-expr)))
9651 pn))
9652
9653 (defun js2-parse-and-expr ()
9654 (let ((pn (js2-parse-bit-or-expr)))
9655 (when (js2-match-token js2-AND)
9656 (setq pn (js2-make-binary js2-AND
9657 pn
9658 'js2-parse-and-expr)))
9659 pn))
9660
9661 (defun js2-parse-bit-or-expr ()
9662 (let ((pn (js2-parse-bit-xor-expr)))
9663 (while (js2-match-token js2-BITOR)
9664 (setq pn (js2-make-binary js2-BITOR
9665 pn
9666 'js2-parse-bit-xor-expr)))
9667 pn))
9668
9669 (defun js2-parse-bit-xor-expr ()
9670 (let ((pn (js2-parse-bit-and-expr)))
9671 (while (js2-match-token js2-BITXOR)
9672 (setq pn (js2-make-binary js2-BITXOR
9673 pn
9674 'js2-parse-bit-and-expr)))
9675 pn))
9676
9677 (defun js2-parse-bit-and-expr ()
9678 (let ((pn (js2-parse-eq-expr)))
9679 (while (js2-match-token js2-BITAND)
9680 (setq pn (js2-make-binary js2-BITAND
9681 pn
9682 'js2-parse-eq-expr)))
9683 pn))
9684
9685 (defconst js2-parse-eq-ops
9686 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9687
9688 (defun js2-parse-eq-expr ()
9689 (let ((pn (js2-parse-rel-expr))
9690 tt)
9691 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9692 (setq pn (js2-make-binary tt
9693 pn
9694 'js2-parse-rel-expr)))
9695 (js2-unget-token)
9696 pn))
9697
9698 (defconst js2-parse-rel-ops
9699 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9700
9701 (defun js2-parse-rel-expr ()
9702 (let ((pn (js2-parse-shift-expr))
9703 (continue t)
9704 tt)
9705 (while continue
9706 (setq tt (js2-get-token))
9707 (cond
9708 ((and js2-in-for-init (= tt js2-IN))
9709 (js2-unget-token)
9710 (setq continue nil))
9711 ((memq tt js2-parse-rel-ops)
9712 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9713 (t
9714 (js2-unget-token)
9715 (setq continue nil))))
9716 pn))
9717
9718 (defconst js2-parse-shift-ops
9719 (list js2-LSH js2-URSH js2-RSH))
9720
9721 (defun js2-parse-shift-expr ()
9722 (let ((pn (js2-parse-add-expr))
9723 tt
9724 (continue t))
9725 (while continue
9726 (setq tt (js2-get-token))
9727 (if (memq tt js2-parse-shift-ops)
9728 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9729 (js2-unget-token)
9730 (setq continue nil)))
9731 pn))
9732
9733 (defun js2-parse-add-expr ()
9734 (let ((pn (js2-parse-mul-expr))
9735 tt
9736 (continue t))
9737 (while continue
9738 (setq tt (js2-get-token))
9739 (if (or (= tt js2-ADD) (= tt js2-SUB))
9740 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9741 (js2-unget-token)
9742 (setq continue nil)))
9743 pn))
9744
9745 (defconst js2-parse-mul-ops
9746 (list js2-MUL js2-DIV js2-MOD))
9747
9748 (defun js2-parse-mul-expr ()
9749 (let ((pn (js2-parse-unary-expr))
9750 tt
9751 (continue t))
9752 (while continue
9753 (setq tt (js2-get-token))
9754 (if (memq tt js2-parse-mul-ops)
9755 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9756 (js2-unget-token)
9757 (setq continue nil)))
9758 pn))
9759
9760 (defun js2-make-unary (type parser &rest args)
9761 "Make a unary node of type TYPE.
9762 PARSER is either a node (for postfix operators) or a function to call
9763 to parse the operand (for prefix operators)."
9764 (let* ((pos (js2-current-token-beg))
9765 (postfix (js2-node-p parser))
9766 (expr (if postfix
9767 parser
9768 (apply parser args)))
9769 end
9770 pn)
9771 (if postfix ; e.g. i++
9772 (setq pos (js2-node-pos expr)
9773 end (js2-current-token-end))
9774 (setq end (js2-node-end expr)))
9775 (setq pn (make-js2-unary-node :type type
9776 :pos pos
9777 :len (- end pos)
9778 :operand expr))
9779 (js2-node-add-children pn expr)
9780 pn))
9781
9782 (defconst js2-incrementable-node-types
9783 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9784 "Node types that can be the operand of a ++ or -- operator.")
9785
9786 (defun js2-check-bad-inc-dec (tt beg end unary)
9787 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9788 js2-incrementable-node-types)
9789 (js2-report-error (if (= tt js2-INC)
9790 "msg.bad.incr"
9791 "msg.bad.decr")
9792 nil beg (- end beg))))
9793
9794 (defun js2-parse-unary-expr ()
9795 (let ((tt (js2-current-token-type))
9796 pn expr beg end)
9797 (cond
9798 ((or (= tt js2-VOID)
9799 (= tt js2-NOT)
9800 (= tt js2-BITNOT)
9801 (= tt js2-TYPEOF))
9802 (js2-get-token)
9803 (js2-make-unary tt 'js2-parse-unary-expr))
9804 ((= tt js2-ADD)
9805 (js2-get-token)
9806 ;; Convert to special POS token in decompiler and parse tree
9807 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9808 ((= tt js2-SUB)
9809 (js2-get-token)
9810 ;; Convert to special NEG token in decompiler and parse tree
9811 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9812 ((or (= tt js2-INC)
9813 (= tt js2-DEC))
9814 (js2-get-token)
9815 (prog1
9816 (setq beg (js2-current-token-beg)
9817 end (js2-current-token-end)
9818 expr (js2-make-unary tt 'js2-parse-member-expr t))
9819 (js2-check-bad-inc-dec tt beg end expr)))
9820 ((= tt js2-DELPROP)
9821 (js2-get-token)
9822 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9823 ((= tt js2-ERROR)
9824 (js2-get-token)
9825 (make-js2-error-node)) ; try to continue
9826 ((and (= tt js2-LT)
9827 js2-compiler-xml-available)
9828 ;; XML stream encountered in expression.
9829 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9830 (t
9831 (setq pn (js2-parse-member-expr t)
9832 ;; Don't look across a newline boundary for a postfix incop.
9833 tt (js2-peek-token-or-eol))
9834 (when (or (= tt js2-INC) (= tt js2-DEC))
9835 (js2-get-token)
9836 (setf expr pn
9837 pn (js2-make-unary tt expr))
9838 (js2-node-set-prop pn 'postfix t)
9839 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9840 pn))))
9841
9842 (defun js2-parse-xml-initializer ()
9843 "Parse an E4X XML initializer.
9844 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9845 Then I'll postprocess the result, depending on whether we're in IDE
9846 mode or codegen mode, and generate the appropriate rewritten AST.
9847 IDE mode uses a rich AST that models the XML structure. Codegen mode
9848 just concatenates everything and makes a new XML or XMLList out of it."
9849 (let ((tt (js2-get-first-xml-token))
9850 pn-xml pn expr kids expr-pos
9851 (continue t)
9852 (first-token t))
9853 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9854 (js2-report-error "msg.syntax"))
9855 (setq pn-xml (make-js2-xml-node))
9856 (while continue
9857 (if first-token
9858 (setq first-token nil)
9859 (setq tt (js2-get-next-xml-token)))
9860 (cond
9861 ;; js2-XML means we found a {expr} in the XML stream.
9862 ;; The token string is the XML up to the left-curly.
9863 ((= tt js2-XML)
9864 (push (make-js2-string-node :pos (js2-current-token-beg)
9865 :len (- js2-ts-cursor (js2-current-token-beg)))
9866 kids)
9867 (js2-must-match js2-LC "msg.syntax")
9868 (setq expr-pos js2-ts-cursor
9869 expr (if (eq (js2-peek-token) js2-RC)
9870 (make-js2-empty-expr-node :pos expr-pos)
9871 (js2-parse-expr)))
9872 (js2-must-match js2-RC "msg.syntax")
9873 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9874 :len (js2-node-len expr)
9875 :expr expr))
9876 (js2-node-add-children pn expr)
9877 (push pn kids))
9878 ;; a js2-XMLEND token means we hit the final close-tag.
9879 ((= tt js2-XMLEND)
9880 (push (make-js2-string-node :pos (js2-current-token-beg)
9881 :len (- js2-ts-cursor (js2-current-token-beg)))
9882 kids)
9883 (dolist (kid (nreverse kids))
9884 (js2-block-node-push pn-xml kid))
9885 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9886 (js2-node-pos pn-xml))
9887 continue nil))
9888 (t
9889 (js2-report-error "msg.syntax")
9890 (setq continue nil))))
9891 pn-xml))
9892
9893
9894 (defun js2-parse-argument-list ()
9895 "Parse an argument list and return it as a Lisp list of nodes.
9896 Returns the list in reverse order. Consumes the right-paren token."
9897 (let (result)
9898 (unless (js2-match-token js2-RP)
9899 (cl-loop do
9900 (let ((tt (js2-get-token)))
9901 (if (= tt js2-YIELD)
9902 (js2-report-error "msg.yield.parenthesized"))
9903 (if (and (= tt js2-TRIPLEDOT)
9904 (>= js2-language-version 200))
9905 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9906 (js2-unget-token)
9907 (push (js2-parse-assign-expr) result)))
9908 while
9909 (js2-match-token js2-COMMA))
9910 (js2-must-match js2-RP "msg.no.paren.arg")
9911 result)))
9912
9913 (defun js2-parse-member-expr (&optional allow-call-syntax)
9914 (let ((tt (js2-current-token-type))
9915 pn pos target args beg end init)
9916 (if (/= tt js2-NEW)
9917 (setq pn (js2-parse-primary-expr))
9918 ;; parse a 'new' expression
9919 (js2-get-token)
9920 (setq pos (js2-current-token-beg)
9921 beg pos
9922 target (js2-parse-member-expr)
9923 end (js2-node-end target)
9924 pn (make-js2-new-node :pos pos
9925 :target target
9926 :len (- end pos)))
9927 (js2-highlight-function-call (js2-current-token))
9928 (js2-node-add-children pn target)
9929 (when (js2-match-token js2-LP)
9930 ;; Add the arguments to pn, if any are supplied.
9931 (setf beg pos ; start of "new" keyword
9932 pos (js2-current-token-beg)
9933 args (nreverse (js2-parse-argument-list))
9934 (js2-new-node-args pn) args
9935 end (js2-current-token-end)
9936 (js2-new-node-lp pn) (- pos beg)
9937 (js2-new-node-rp pn) (- end 1 beg))
9938 (apply #'js2-node-add-children pn args))
9939 (when (and js2-allow-rhino-new-expr-initializer
9940 (js2-match-token js2-LC))
9941 (setf init (js2-parse-object-literal)
9942 end (js2-node-end init)
9943 (js2-new-node-initializer pn) init)
9944 (js2-node-add-children pn init))
9945 (setf (js2-node-len pn) (- end beg))) ; end outer if
9946 (js2-parse-member-expr-tail allow-call-syntax pn)))
9947
9948 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9949 "Parse a chain of property/array accesses or function calls.
9950 Includes parsing for E4X operators like `..' and `.@'.
9951 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9952 Returns an expression tree that includes PN, the parent node."
9953 (let (tt
9954 (continue t))
9955 (while continue
9956 (setq tt (js2-get-token))
9957 (cond
9958 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9959 (setq pn (js2-parse-property-access tt pn)))
9960 ((= tt js2-DOTQUERY)
9961 (setq pn (js2-parse-dot-query pn)))
9962 ((= tt js2-LB)
9963 (setq pn (js2-parse-element-get pn)))
9964 ((= tt js2-LP)
9965 (js2-unget-token)
9966 (if allow-call-syntax
9967 (setq pn (js2-parse-function-call pn))
9968 (setq continue nil)))
9969 ((= tt js2-TEMPLATE_HEAD)
9970 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9971 ((= tt js2-NO_SUBS_TEMPLATE)
9972 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9973 (t
9974 (js2-unget-token)
9975 (setq continue nil))))
9976 (if (>= js2-highlight-level 2)
9977 (js2-parse-highlight-member-expr-node pn))
9978 pn))
9979
9980 (defun js2-parse-tagged-template (tag-node tpl-node)
9981 "Parse tagged template expression."
9982 (let* ((beg (js2-node-pos tag-node))
9983 (pn (make-js2-tagged-template-node :beg beg
9984 :len (- (js2-current-token-end) beg)
9985 :tag tag-node
9986 :template tpl-node)))
9987 (js2-node-add-children pn tag-node tpl-node)
9988 pn))
9989
9990 (defun js2-parse-dot-query (pn)
9991 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9992 Last token parsed must be `js2-DOTQUERY'."
9993 (let ((pos (js2-node-pos pn))
9994 op-pos expr end)
9995 (js2-must-have-xml)
9996 (js2-set-requires-activation)
9997 (setq op-pos (js2-current-token-beg)
9998 expr (js2-parse-expr)
9999 end (js2-node-end expr)
10000 pn (make-js2-xml-dot-query-node :left pn
10001 :pos pos
10002 :op-pos op-pos
10003 :right expr))
10004 (js2-node-add-children pn
10005 (js2-xml-dot-query-node-left pn)
10006 (js2-xml-dot-query-node-right pn))
10007 (if (js2-must-match js2-RP "msg.no.paren")
10008 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
10009 end (js2-current-token-end)))
10010 (setf (js2-node-len pn) (- end pos))
10011 pn))
10012
10013 (defun js2-parse-element-get (pn)
10014 "Parse an element-get expression, e.g. foo[bar].
10015 Last token parsed must be `js2-RB'."
10016 (let ((lb (js2-current-token-beg))
10017 (pos (js2-node-pos pn))
10018 rb expr)
10019 (setq expr (js2-parse-expr))
10020 (if (js2-must-match js2-RB "msg.no.bracket.index")
10021 (setq rb (js2-current-token-beg)))
10022 (setq pn (make-js2-elem-get-node :target pn
10023 :pos pos
10024 :element expr
10025 :lb (js2-relpos lb pos)
10026 :rb (js2-relpos rb pos)
10027 :len (- (js2-current-token-end) pos)))
10028 (js2-node-add-children pn
10029 (js2-elem-get-node-target pn)
10030 (js2-elem-get-node-element pn))
10031 pn))
10032
10033 (defun js2-highlight-function-call (token)
10034 (when (eq (js2-token-type token) js2-NAME)
10035 (js2-record-face 'js2-function-call token)))
10036
10037 (defun js2-parse-function-call (pn)
10038 (js2-highlight-function-call (js2-current-token))
10039 (js2-get-token)
10040 (let (args
10041 (pos (js2-node-pos pn)))
10042 (setq pn (make-js2-call-node :pos pos
10043 :target pn
10044 :lp (- (js2-current-token-beg) pos)))
10045 (js2-node-add-children pn (js2-call-node-target pn))
10046 ;; Add the arguments to pn, if any are supplied.
10047 (setf args (nreverse (js2-parse-argument-list))
10048 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
10049 (js2-call-node-args pn) args)
10050 (apply #'js2-node-add-children pn args)
10051 (setf (js2-node-len pn) (- js2-ts-cursor pos))
10052 pn))
10053
10054 (defun js2-parse-property-access (tt pn)
10055 "Parse a property access, XML descendants access, or XML attr access."
10056 (let ((member-type-flags 0)
10057 (dot-pos (js2-current-token-beg))
10058 (dot-len (if (= tt js2-DOTDOT) 2 1))
10059 name
10060 ref ; right side of . or .. operator
10061 result)
10062 (when (= tt js2-DOTDOT)
10063 (js2-must-have-xml)
10064 (setq member-type-flags js2-descendants-flag))
10065 (if (not js2-compiler-xml-available)
10066 (progn
10067 (js2-must-match-prop-name "msg.no.name.after.dot")
10068 (setq name (js2-create-name-node t js2-GETPROP)
10069 result (make-js2-prop-get-node :left pn
10070 :pos (js2-current-token-beg)
10071 :right name
10072 :len (js2-current-token-len)))
10073 (js2-node-add-children result pn name)
10074 result)
10075 ;; otherwise look for XML operators
10076 (setf result (if (= tt js2-DOT)
10077 (make-js2-prop-get-node)
10078 (make-js2-infix-node :type js2-DOTDOT))
10079 (js2-node-pos result) (js2-node-pos pn)
10080 (js2-infix-node-op-pos result) dot-pos
10081 (js2-infix-node-left result) pn ; do this after setting position
10082 tt (js2-get-prop-name-token))
10083 (cond
10084 ;; handles: name, ns::name, ns::*, ns::[expr]
10085 ((= tt js2-NAME)
10086 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
10087 ;; handles: *, *::name, *::*, *::[expr]
10088 ((= tt js2-MUL)
10089 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
10090 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
10091 ((= tt js2-XMLATTR)
10092 (setq result (js2-parse-attribute-access)))
10093 (t
10094 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
10095 (if ref
10096 (setf (js2-node-len result) (- (js2-node-end ref)
10097 (js2-node-pos result))
10098 (js2-infix-node-right result) ref))
10099 (if (js2-infix-node-p result)
10100 (js2-node-add-children result
10101 (js2-infix-node-left result)
10102 (js2-infix-node-right result)))
10103 result)))
10104
10105 (defun js2-parse-attribute-access ()
10106 "Parse an E4X XML attribute expression.
10107 This includes expressions of the forms:
10108
10109 @attr @ns::attr @ns::*
10110 @* @*::attr @*::*
10111 @[expr] @*::[expr] @ns::[expr]
10112
10113 Called if we peeked an '@' token."
10114 (let ((tt (js2-get-prop-name-token))
10115 (at-pos (js2-current-token-beg)))
10116 (cond
10117 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
10118 ((= tt js2-NAME)
10119 (js2-parse-property-name at-pos nil 0))
10120 ;; handles: @*, @*::name, @*::*, @*::[expr]
10121 ((= tt js2-MUL)
10122 (js2-parse-property-name (js2-current-token-beg) "*" 0))
10123 ;; handles @[expr]
10124 ((= tt js2-LB)
10125 (js2-parse-xml-elem-ref at-pos))
10126 (t
10127 (js2-report-error "msg.no.name.after.xmlAttr")
10128 ;; Avoid cascaded errors that happen if we make an error node here.
10129 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
10130
10131 (defun js2-parse-property-name (at-pos s member-type-flags)
10132 "Check if :: follows name in which case it becomes qualified name.
10133
10134 AT-POS is a natural number if we just read an '@' token, else nil.
10135 S is the name or string that was matched: an identifier, 'throw' or '*'.
10136 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
10137
10138 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
10139 operator, or the name is followed by ::. For a plain name, returns a
10140 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
10141 (let ((pos (or at-pos (js2-current-token-beg)))
10142 colon-pos
10143 (name (js2-create-name-node t (js2-current-token-type) s))
10144 ns tt pn)
10145 (catch 'return
10146 (when (js2-match-token js2-COLONCOLON)
10147 (setq ns name
10148 colon-pos (js2-current-token-beg)
10149 tt (js2-get-prop-name-token))
10150 (cond
10151 ;; handles name::name
10152 ((= tt js2-NAME)
10153 (setq name (js2-create-name-node)))
10154 ;; handles name::*
10155 ((= tt js2-MUL)
10156 (setq name (js2-create-name-node nil nil "*")))
10157 ;; handles name::[expr]
10158 ((= tt js2-LB)
10159 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
10160 (t
10161 (js2-report-error "msg.no.name.after.coloncolon"))))
10162 (if (and (null ns) (zerop member-type-flags))
10163 name
10164 (prog1
10165 (setq pn
10166 (make-js2-xml-prop-ref-node :pos pos
10167 :len (- (js2-node-end name) pos)
10168 :at-pos at-pos
10169 :colon-pos colon-pos
10170 :propname name))
10171 (js2-node-add-children pn name))))))
10172
10173 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
10174 "Parse the [expr] portion of an xml element reference.
10175 For instance, @[expr], @*::[expr], or ns::[expr]."
10176 (let* ((lb (js2-current-token-beg))
10177 (pos (or at-pos lb))
10178 rb
10179 (expr (js2-parse-expr))
10180 (end (js2-node-end expr))
10181 pn)
10182 (if (js2-must-match js2-RB "msg.no.bracket.index")
10183 (setq rb (js2-current-token-beg)
10184 end (js2-current-token-end)))
10185 (prog1
10186 (setq pn
10187 (make-js2-xml-elem-ref-node :pos pos
10188 :len (- end pos)
10189 :namespace namespace
10190 :colon-pos colon-pos
10191 :at-pos at-pos
10192 :expr expr
10193 :lb (js2-relpos lb pos)
10194 :rb (js2-relpos rb pos)))
10195 (js2-node-add-children pn namespace expr))))
10196
10197 (defun js2-parse-destruct-primary-expr ()
10198 (let ((js2-is-in-destructuring t))
10199 (js2-parse-primary-expr)))
10200
10201 (defun js2-parse-primary-expr ()
10202 "Parse a literal (leaf) expression of some sort.
10203 Includes complex literals such as functions, object-literals,
10204 array-literals, array comprehensions and regular expressions."
10205 (let (tt)
10206 (setq tt (js2-current-token-type))
10207 (cond
10208 ((= tt js2-CLASS)
10209 (js2-parse-class-expr))
10210 ((= tt js2-FUNCTION)
10211 (js2-parse-function-expr))
10212 ((= tt js2-LB)
10213 (js2-parse-array-comp-or-literal))
10214 ((= tt js2-LC)
10215 (js2-parse-object-literal))
10216 ((= tt js2-LET)
10217 (js2-parse-let (js2-current-token-beg)))
10218 ((= tt js2-LP)
10219 (js2-parse-paren-expr-or-generator-comp))
10220 ((= tt js2-XMLATTR)
10221 (js2-must-have-xml)
10222 (js2-parse-attribute-access))
10223 ((= tt js2-NAME)
10224 (js2-parse-name tt))
10225 ((= tt js2-NUMBER)
10226 (make-js2-number-node))
10227 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
10228 (make-js2-string-node :type tt))
10229 ((= tt js2-TEMPLATE_HEAD)
10230 (js2-parse-template-literal))
10231 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
10232 ;; Got / or /= which in this context means a regexp literal
10233 (let ((px-pos (js2-current-token-beg))
10234 (flags (js2-read-regexp tt))
10235 (end (js2-current-token-end)))
10236 (prog1
10237 (make-js2-regexp-node :pos px-pos
10238 :len (- end px-pos)
10239 :value (js2-current-token-string)
10240 :flags flags)
10241 (js2-set-face px-pos end 'font-lock-string-face 'record)
10242 (js2-record-text-property px-pos end 'syntax-table '(2)))))
10243 ((or (= tt js2-NULL)
10244 (= tt js2-THIS)
10245 (= tt js2-SUPER)
10246 (= tt js2-FALSE)
10247 (= tt js2-TRUE))
10248 (make-js2-keyword-node :type tt))
10249 ((= tt js2-TRIPLEDOT)
10250 ;; Likewise, only valid in an arrow function with a rest param.
10251 (if (and (js2-match-token js2-NAME)
10252 (js2-match-token js2-RP)
10253 (eq (js2-peek-token) js2-ARROW))
10254 (progn
10255 (js2-unget-token) ; Put back the right paren.
10256 ;; See the previous case.
10257 (make-js2-keyword-node :type js2-NULL))
10258 (js2-report-error "msg.syntax")
10259 (make-js2-error-node)))
10260 ((= tt js2-RESERVED)
10261 (js2-report-error "msg.reserved.id")
10262 (make-js2-name-node))
10263 ((= tt js2-ERROR)
10264 ;; the scanner or one of its subroutines reported the error.
10265 (make-js2-error-node))
10266 ((= tt js2-EOF)
10267 (let* ((px-pos (point-at-bol))
10268 (len (- js2-ts-cursor px-pos)))
10269 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10270 (make-js2-error-node :pos (1- js2-ts-cursor)))
10271 (t
10272 (js2-report-error "msg.syntax")
10273 (make-js2-error-node)))))
10274
10275 (defun js2-parse-template-literal ()
10276 (let ((beg (js2-current-token-beg))
10277 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10278 (tt js2-TEMPLATE_HEAD))
10279 (while (eq tt js2-TEMPLATE_HEAD)
10280 (push (js2-parse-expr) kids)
10281 (js2-must-match js2-RC "msg.syntax")
10282 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10283 (push (make-js2-string-node :type tt) kids))
10284 (setq kids (nreverse kids))
10285 (let ((tpl (make-js2-template-node :beg beg
10286 :len (- (js2-current-token-end) beg)
10287 :kids kids)))
10288 (apply #'js2-node-add-children tpl kids)
10289 tpl)))
10290
10291 (defun js2-parse-name (_tt)
10292 (let ((name (js2-current-token-string))
10293 node)
10294 (setq node (if js2-compiler-xml-available
10295 (js2-parse-property-name nil name 0)
10296 (js2-create-name-node 'check-activation nil name)))
10297 (if js2-highlight-external-variables
10298 (js2-record-name-node node))
10299 node))
10300
10301 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10302 (js2-add-strict-warning
10303 msg nil
10304 ;; back up from comma to beginning of line or array/objlit
10305 (max (if elems
10306 (js2-node-pos (car elems))
10307 pos)
10308 (save-excursion
10309 (goto-char comma-pos)
10310 (back-to-indentation)
10311 (point)))
10312 comma-pos))
10313
10314 (defun js2-parse-array-comp-or-literal ()
10315 (let ((pos (js2-current-token-beg)))
10316 (if (and (>= js2-language-version 200)
10317 (js2-match-token js2-FOR))
10318 (js2-parse-array-comp pos)
10319 (js2-parse-array-literal pos))))
10320
10321 (defun js2-parse-array-literal (pos)
10322 (let ((after-lb-or-comma t)
10323 after-comma tt elems pn
10324 (continue t))
10325 (unless js2-is-in-destructuring
10326 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10327 (while continue
10328 (setq tt (js2-get-token))
10329 (cond
10330 ;; comma
10331 ((= tt js2-COMMA)
10332 (setq after-comma (js2-current-token-end))
10333 (if (not after-lb-or-comma)
10334 (setq after-lb-or-comma t)
10335 (push nil elems)))
10336 ;; end of array
10337 ((or (= tt js2-RB)
10338 (= tt js2-EOF)) ; prevent infinite loop
10339 (if (= tt js2-EOF)
10340 (js2-report-error "msg.no.bracket.arg" nil pos))
10341 (when (and after-comma (< js2-language-version 170))
10342 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10343 pos (remove nil elems) after-comma))
10344 (setq continue nil
10345 pn (make-js2-array-node :pos pos
10346 :len (- js2-ts-cursor pos)
10347 :elems (nreverse elems)))
10348 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10349 ;; destructuring binding
10350 (js2-is-in-destructuring
10351 (push (if (or (= tt js2-LC)
10352 (= tt js2-LB)
10353 (= tt js2-NAME))
10354 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10355 (js2-parse-destruct-primary-expr)
10356 ;; invalid pattern
10357 (js2-report-error "msg.bad.var")
10358 (make-js2-error-node))
10359 elems)
10360 (setq after-lb-or-comma nil
10361 after-comma nil))
10362 ;; array comp
10363 ((and (>= js2-language-version 170)
10364 (= tt js2-FOR) ; check for array comprehension
10365 (not after-lb-or-comma) ; "for" can't follow a comma
10366 elems ; must have at least 1 element
10367 (not (cdr elems))) ; but no 2nd element
10368 (js2-unget-token)
10369 (setf continue nil
10370 pn (js2-parse-legacy-array-comp (car elems) pos)))
10371 ;; another element
10372 (t
10373 (unless after-lb-or-comma
10374 (js2-report-error "msg.no.bracket.arg"))
10375 (if (and (= tt js2-TRIPLEDOT)
10376 (>= js2-language-version 200))
10377 ;; spread operator
10378 (push (js2-make-unary tt 'js2-parse-assign-expr)
10379 elems)
10380 (js2-unget-token)
10381 (push (js2-parse-assign-expr) elems))
10382 (setq after-lb-or-comma nil
10383 after-comma nil))))
10384 (unless js2-is-in-destructuring
10385 (js2-pop-scope))
10386 pn))
10387
10388 (defun js2-parse-legacy-array-comp (expr pos)
10389 "Parse a legacy array comprehension (JavaScript 1.7).
10390 EXPR is the first expression after the opening left-bracket.
10391 POS is the beginning of the LB token preceding EXPR.
10392 We should have just parsed the 'for' keyword before calling this function."
10393 (let ((current-scope js2-current-scope)
10394 loops first filter result)
10395 (unwind-protect
10396 (progn
10397 (while (js2-match-token js2-FOR)
10398 (let ((loop (make-js2-comp-loop-node)))
10399 (js2-push-scope loop)
10400 (push loop loops)
10401 (js2-parse-comp-loop loop)))
10402 ;; First loop takes expr scope's parent.
10403 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10404 (js2-scope-parent-scope current-scope))
10405 ;; Set expr scope's parent to the last loop.
10406 (setf (js2-scope-parent-scope current-scope) (car loops))
10407 (if (/= (js2-get-token) js2-IF)
10408 (js2-unget-token)
10409 (setq filter (js2-parse-condition))))
10410 (dotimes (_ (1- (length loops)))
10411 (js2-pop-scope)))
10412 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10413 (setq result (make-js2-comp-node :pos pos
10414 :len (- js2-ts-cursor pos)
10415 :result expr
10416 :loops (nreverse loops)
10417 :filters (and filter (list (car filter)))
10418 :form 'LEGACY_ARRAY))
10419 ;; Set comp loop's parent to the last loop.
10420 ;; TODO: Get rid of the bogus expr scope.
10421 (setf (js2-scope-parent-scope result) first)
10422 (apply #'js2-node-add-children result expr (car filter)
10423 (js2-comp-node-loops result))
10424 result))
10425
10426 (defun js2-parse-array-comp (pos)
10427 "Parse an ES6 array comprehension.
10428 POS is the beginning of the LB token.
10429 We should have just parsed the 'for' keyword before calling this function."
10430 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10431 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10432 pn))
10433
10434 (defun js2-parse-generator-comp (pos)
10435 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10436 (js2-current-script-or-fn
10437 (make-js2-function-node :generator-type 'COMPREHENSION))
10438 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10439 (js2-must-match js2-RP "msg.no.paren" pos)
10440 pn))
10441
10442 (defun js2-parse-comprehension (pos form)
10443 (let (loops filters expr result last)
10444 (unwind-protect
10445 (progn
10446 (js2-unget-token)
10447 (while (js2-match-token js2-FOR)
10448 (let ((loop (make-js2-comp-loop-node)))
10449 (js2-push-scope loop)
10450 (push loop loops)
10451 (js2-parse-comp-loop loop)))
10452 (while (js2-match-token js2-IF)
10453 (push (car (js2-parse-condition)) filters))
10454 (setq expr (js2-parse-assign-expr))
10455 (setq last (car loops)))
10456 (dolist (_ loops)
10457 (js2-pop-scope)))
10458 (setq result (make-js2-comp-node :pos pos
10459 :len (- js2-ts-cursor pos)
10460 :result expr
10461 :loops (nreverse loops)
10462 :filters (nreverse filters)
10463 :form form))
10464 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10465 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10466 (setf (js2-scope-parent-scope result) last)
10467 result))
10468
10469 (defun js2-parse-comp-loop (pn &optional only-of-p)
10470 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10471 The current token should be the initial FOR.
10472 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10473 (let ((pos (js2-comp-loop-node-pos pn))
10474 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10475 (when (and (not only-of-p) (js2-match-token js2-NAME))
10476 (if (string= (js2-current-token-string) "each")
10477 (progn
10478 (setq foreach-p t
10479 each-pos (- (js2-current-token-beg) pos)) ; relative
10480 (js2-record-face 'font-lock-keyword-face))
10481 (js2-report-error "msg.no.paren.for")))
10482 (if (js2-must-match js2-LP "msg.no.paren.for")
10483 (setq lp (- (js2-current-token-beg) pos)))
10484 (setq tt (js2-peek-token))
10485 (cond
10486 ((or (= tt js2-LB)
10487 (= tt js2-LC))
10488 (js2-get-token)
10489 (setq iter (js2-parse-destruct-primary-expr))
10490 (js2-define-destruct-symbols iter js2-LET
10491 'font-lock-variable-name-face t))
10492 ((js2-match-token js2-NAME)
10493 (setq iter (js2-create-name-node)))
10494 (t
10495 (js2-report-error "msg.bad.var")))
10496 ;; Define as a let since we want the scope of the variable to
10497 ;; be restricted to the array comprehension
10498 (if (js2-name-node-p iter)
10499 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10500 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10501 (and (>= js2-language-version 200)
10502 (js2-match-contextual-kwd "of")
10503 (setq forof-p t)))
10504 (setq in-pos (- (js2-current-token-beg) pos))
10505 (js2-report-error "msg.in.after.for.name"))
10506 (setq obj (js2-parse-expr))
10507 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10508 (setq rp (- (js2-current-token-beg) pos)))
10509 (setf (js2-node-pos pn) pos
10510 (js2-node-len pn) (- js2-ts-cursor pos)
10511 (js2-comp-loop-node-iterator pn) iter
10512 (js2-comp-loop-node-object pn) obj
10513 (js2-comp-loop-node-in-pos pn) in-pos
10514 (js2-comp-loop-node-each-pos pn) each-pos
10515 (js2-comp-loop-node-foreach-p pn) foreach-p
10516 (js2-comp-loop-node-forof-p pn) forof-p
10517 (js2-comp-loop-node-lp pn) lp
10518 (js2-comp-loop-node-rp pn) rp)
10519 (js2-node-add-children pn iter obj)
10520 pn))
10521
10522 (defun js2-parse-class-stmt ()
10523 (let ((pos (js2-current-token-beg))
10524 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10525 (name (js2-create-name-node t)))
10526 (js2-set-face (js2-node-pos name) (js2-node-end name)
10527 'font-lock-function-name-face 'record)
10528 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10529 (js2-define-symbol js2-FUNCTION
10530 (js2-name-node-name name)
10531 node)
10532 node)))
10533
10534 (defun js2-parse-class-expr ()
10535 (let ((pos (js2-current-token-beg))
10536 name)
10537 (when (js2-match-token js2-NAME)
10538 (setq name (js2-create-name-node t)))
10539 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10540
10541 (defun js2-parse-class (pos form name)
10542 ;; class X [extends ...] {
10543 (let (pn elems extends)
10544 (if (js2-match-token js2-EXTENDS)
10545 (if (= (js2-peek-token) js2-LC)
10546 (js2-report-error "msg.missing.extends")
10547 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10548 (setq extends (js2-parse-assign-expr))
10549 (if (not extends)
10550 (js2-report-error "msg.bad.extends"))))
10551 (js2-must-match js2-LC "msg.no.brace.class")
10552 (setq elems (js2-parse-object-literal-elems t)
10553 pn (make-js2-class-node :pos pos
10554 :len (- js2-ts-cursor pos)
10555 :form form
10556 :name name
10557 :extends extends
10558 :elems elems))
10559 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10560 pn))
10561
10562 (defun js2-parse-object-literal ()
10563 (let* ((pos (js2-current-token-beg))
10564 (elems (js2-parse-object-literal-elems))
10565 (result (make-js2-object-node :pos pos
10566 :len (- js2-ts-cursor pos)
10567 :elems elems)))
10568 (apply #'js2-node-add-children result (js2-object-node-elems result))
10569 result))
10570
10571 (defun js2-parse-object-literal-elems (&optional class-p)
10572 (let ((pos (js2-current-token-beg))
10573 (static nil)
10574 (continue t)
10575 tt elems elem after-comma previous-token)
10576 (while continue
10577 (setq tt (js2-get-prop-name-token)
10578 static nil
10579 elem nil
10580 previous-token nil)
10581 ;; Handle 'static' keyword only if we're in a class
10582 (when (and class-p (= js2-NAME tt)
10583 (string= "static" (js2-current-token-string)))
10584 (js2-record-face 'font-lock-keyword-face)
10585 (setq static t
10586 tt (js2-get-prop-name-token)))
10587 ;; Handle generator * before the property name for in-line functions
10588 (when (and (>= js2-language-version 200)
10589 (= js2-MUL tt))
10590 (setq previous-token (js2-current-token)
10591 tt (js2-get-prop-name-token)))
10592 ;; Handle 'get' or 'set' keywords
10593 (let ((prop (js2-current-token-string)))
10594 (when (and (>= js2-language-version 200)
10595 (= js2-NAME tt)
10596 (or (string= prop "get")
10597 (string= prop "set"))
10598 (member (js2-peek-token)
10599 (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
10600 (setq previous-token (js2-current-token)
10601 tt (js2-get-prop-name-token))))
10602 (cond
10603 ;; Found a property (of any sort)
10604 ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
10605 (setq after-comma nil
10606 elem (js2-parse-named-prop tt pos previous-token))
10607 (if (and (null elem)
10608 (not js2-recover-from-parse-errors))
10609 (setq continue nil)))
10610 ;; Break out of loop, and handle trailing commas.
10611 ((or (= tt js2-RC)
10612 (= tt js2-EOF))
10613 (js2-unget-token)
10614 (setq continue nil)
10615 (if after-comma
10616 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10617 pos elems after-comma)))
10618 (t
10619 (js2-report-error "msg.bad.prop")
10620 (unless js2-recover-from-parse-errors
10621 (setq continue nil)))) ; end switch
10622 ;; Handle static for classes' codegen.
10623 (if static
10624 (if elem (js2-node-set-prop elem 'STATIC t)
10625 (js2-report-error "msg.unexpected.static")))
10626 ;; Handle commas, depending on class-p.
10627 (let ((tok (js2-get-prop-name-token)))
10628 (if (eq tok js2-COMMA)
10629 (if class-p
10630 (js2-report-error "msg.class.unexpected.comma")
10631 (setq after-comma (js2-current-token-end)))
10632 (js2-unget-token)
10633 (unless class-p (setq continue nil))))
10634 ;; Append any parsed element.
10635 (if elem (push elem elems))) ; end loop
10636 (js2-must-match js2-RC "msg.no.brace.prop")
10637 (nreverse elems)))
10638
10639 (defun js2-parse-named-prop (tt pos previous-token)
10640 "Parse a name, string, or getter/setter object property.
10641 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10642 (let ((key (cond
10643 ;; Literal string keys: {'foo': 'bar'}
10644 ((= tt js2-STRING)
10645 (make-js2-string-node))
10646 ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
10647 ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
10648 ((and (= tt js2-LB)
10649 (>= js2-language-version 200))
10650 (prog1 (js2-parse-expr)
10651 (js2-must-match js2-RB "msg.missing.computed.rb")))
10652 ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
10653 ((= tt js2-NUMBER)
10654 (make-js2-number-node))
10655 ;; Unquoted names: {foo: 12}
10656 ((= tt js2-NAME)
10657 (js2-create-name-node))
10658 ;; Anything else is an error
10659 (t (js2-report-error "msg.bad.prop"))))
10660 (prop (and previous-token (js2-token-string previous-token)))
10661 (property-type (when previous-token
10662 (if (= (js2-token-type previous-token) js2-MUL)
10663 "*"
10664 (js2-token-string previous-token)))))
10665 (when (or (string= prop "get")
10666 (string= prop "set"))
10667 (js2-set-face (js2-token-beg previous-token)
10668 (js2-token-end previous-token)
10669 'font-lock-keyword-face 'record)) ; get/set
10670 (cond
10671 ;; method definition: {f() {...}}
10672 ((and (= (js2-peek-token) js2-LP)
10673 (>= js2-language-version 200))
10674 (when (js2-name-node-p key) ; highlight function name properties
10675 (js2-record-face 'font-lock-function-name-face))
10676 (js2-parse-getter-setter-prop pos key property-type))
10677 ;; regular prop
10678 (t
10679 (let ((beg (js2-current-token-beg))
10680 (end (js2-current-token-end))
10681 (expr (js2-parse-plain-property key)))
10682 (when (and (= tt js2-NAME)
10683 (not js2-is-in-destructuring)
10684 js2-highlight-external-variables
10685 (js2-node-get-prop expr 'SHORTHAND))
10686 (js2-record-name-node key))
10687 (js2-set-face beg end
10688 (if (js2-function-node-p
10689 (js2-object-prop-node-right expr))
10690 'font-lock-function-name-face
10691 'font-lock-variable-name-face)
10692 'record)
10693 expr)))))
10694
10695 (defun js2-parse-plain-property (prop)
10696 "Parse a non-getter/setter property in an object literal.
10697 PROP is the node representing the property: a number, name or string."
10698 (let* ((tt (js2-get-token))
10699 (pos (js2-node-pos prop))
10700 colon expr result)
10701 (cond
10702 ;; Abbreviated property, as in {foo, bar}
10703 ((and (>= js2-language-version 200)
10704 (or (= tt js2-COMMA)
10705 (= tt js2-RC))
10706 (not (js2-number-node-p prop)))
10707 (js2-unget-token)
10708 (setq result (make-js2-object-prop-node
10709 :pos pos
10710 :left prop
10711 :right prop
10712 :op-pos (js2-current-token-len)))
10713 (js2-node-add-children result prop)
10714 (js2-node-set-prop result 'SHORTHAND t)
10715 result)
10716 ;; Normal property
10717 (t
10718 (if (= tt js2-COLON)
10719 (setq colon (- (js2-current-token-beg) pos)
10720 expr (js2-parse-assign-expr))
10721 (js2-report-error "msg.no.colon.prop")
10722 (setq expr (make-js2-error-node)))
10723 (setq result (make-js2-object-prop-node
10724 :pos pos
10725 ;; don't include last consumed token in length
10726 :len (- (+ (js2-node-pos expr)
10727 (js2-node-len expr))
10728 pos)
10729 :left prop
10730 :right expr
10731 :op-pos colon))
10732 (js2-node-add-children result prop expr)
10733 result))))
10734
10735 (defun js2-parse-getter-setter-prop (pos prop type-string)
10736 "Parse getter or setter property in an object literal.
10737 JavaScript syntax is:
10738
10739 { get foo() {...}, set foo(x) {...} }
10740
10741 and expression closure style is also supported
10742
10743 { get foo() x, set foo(x) _x = x }
10744
10745 POS is the start position of the `get' or `set' keyword.
10746 PROP is the `js2-name-node' representing the property name.
10747 TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
10748 (let ((type (cond
10749 ((string= "get" type-string) js2-GET)
10750 ((string= "set" type-string) js2-SET)
10751 (t js2-FUNCTION)))
10752 result end
10753 (fn (js2-parse-function-expr)))
10754 ;; it has to be an anonymous function, as we already parsed the name
10755 (if (/= (js2-node-type fn) js2-FUNCTION)
10756 (js2-report-error "msg.bad.prop")
10757 (if (cl-plusp (length (js2-function-name fn)))
10758 (js2-report-error "msg.bad.prop")))
10759 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10760 (when (string= type-string "*")
10761 (setf (js2-function-node-generator-type fn) 'STAR))
10762 (setq end (js2-node-end fn)
10763 result (make-js2-getter-setter-node :type type
10764 :pos pos
10765 :len (- end pos)
10766 :left prop
10767 :right fn))
10768 (js2-node-add-children result prop fn)
10769 result))
10770
10771 (defun js2-create-name-node (&optional check-activation-p token string)
10772 "Create a name node using the current token and, optionally, STRING.
10773 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10774 (let* ((beg (js2-current-token-beg))
10775 (tt (js2-current-token-type))
10776 (s (or string
10777 (if (= js2-NAME tt)
10778 (js2-current-token-string)
10779 (js2-tt-name tt))))
10780 name)
10781 (setq name (make-js2-name-node :pos beg
10782 :name s
10783 :len (length s)))
10784 (if check-activation-p
10785 (js2-check-activation-name s (or token js2-NAME)))
10786 name))
10787
10788 ;;; Indentation support
10789
10790 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10791 ;; Karl cleverly deduces that the desired indentation level is often a
10792 ;; function of paren/bracket/brace nesting depth, which can be determined
10793 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10794 ;; then does some equally clever checks to see if we're in the context of a
10795 ;; substatement of a possibly braceless statement keyword such as if, while,
10796 ;; or finally. This approach yields pretty good results.
10797
10798 ;; The indenter is often "wrong", however, and needs to be overridden.
10799 ;; The right long-term solution is probably to emulate (or integrate
10800 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10801 ;; parse tree from `js2-parse' is present, which is not true at the
10802 ;; moment the user is typing, computing indentation is still thousands
10803 ;; of lines of code to handle every possible syntactic edge case.
10804
10805 ;; In the meantime, the compromise solution is that we offer a "bounce
10806 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10807 ;; current line indent among various likely guess points. This approach
10808 ;; is far from perfect, but should at least make it slightly easier to
10809 ;; move the line towards its desired indentation when manually
10810 ;; overriding Karl's heuristic nesting guesser.
10811
10812 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10813 ;; extensions such as `let' and Array comprehensions. Major kudos to
10814 ;; Karl for coming up with the initial approach, which packs a lot of
10815 ;; punch for so little code.
10816
10817 (defconst js2-possibly-braceless-keywords-re
10818 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10819 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10820 "try" "while" "with" "let")))
10821 "Regular expression matching keywords that are optionally
10822 followed by an opening brace.")
10823
10824 (defconst js2-indent-operator-re
10825 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10826 (regexp-opt '("in" "instanceof") 'words))
10827 "Regular expression matching operators that affect indentation
10828 of continued expressions.")
10829
10830 (defconst js2-declaration-keyword-re
10831 (regexp-opt '("var" "let" "const") 'words)
10832 "Regular expression matching variable declaration keywords.")
10833
10834 (defun js2-re-search-forward-inner (regexp &optional bound count)
10835 "Auxiliary function for `js2-re-search-forward'."
10836 (let (parse saved-point)
10837 (while (> count 0)
10838 (re-search-forward regexp bound)
10839 (setq parse (if saved-point
10840 (parse-partial-sexp saved-point (point))
10841 (syntax-ppss (point))))
10842 (cond ((nth 3 parse)
10843 (re-search-forward
10844 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10845 (save-excursion (end-of-line) (point)) t))
10846 ((nth 7 parse)
10847 (forward-line))
10848 ((or (nth 4 parse)
10849 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10850 (re-search-forward "\\*/"))
10851 (t
10852 (setq count (1- count))))
10853 (setq saved-point (point))))
10854 (point))
10855
10856 (defun js2-re-search-forward (regexp &optional bound noerror count)
10857 "Search forward but ignore strings and comments.
10858 Invokes `re-search-forward' but treats the buffer as if strings
10859 and comments have been removed."
10860 (let ((saved-point (point)))
10861 (condition-case err
10862 (cond ((null count)
10863 (js2-re-search-forward-inner regexp bound 1))
10864 ((< count 0)
10865 (js2-re-search-backward-inner regexp bound (- count)))
10866 ((> count 0)
10867 (js2-re-search-forward-inner regexp bound count)))
10868 (search-failed
10869 (goto-char saved-point)
10870 (unless noerror
10871 (error (error-message-string err)))))))
10872
10873 (defun js2-re-search-backward-inner (regexp &optional bound count)
10874 "Auxiliary function for `js2-re-search-backward'."
10875 (let (parse)
10876 (while (> count 0)
10877 (re-search-backward regexp bound)
10878 (setq parse (syntax-ppss (point)))
10879 (cond ((nth 3 parse)
10880 (re-search-backward
10881 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10882 (line-beginning-position) t))
10883 ((nth 7 parse)
10884 (goto-char (nth 8 parse)))
10885 ((or (nth 4 parse)
10886 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10887 (re-search-backward "/\\*"))
10888 (t
10889 (setq count (1- count))))))
10890 (point))
10891
10892 (defun js2-re-search-backward (regexp &optional bound noerror count)
10893 "Search backward but ignore strings and comments.
10894 Invokes `re-search-backward' but treats the buffer as if strings
10895 and comments have been removed."
10896 (let ((saved-point (point)))
10897 (condition-case err
10898 (cond ((null count)
10899 (js2-re-search-backward-inner regexp bound 1))
10900 ((< count 0)
10901 (js2-re-search-forward-inner regexp bound (- count)))
10902 ((> count 0)
10903 (js2-re-search-backward-inner regexp bound count)))
10904 (search-failed
10905 (goto-char saved-point)
10906 (unless noerror
10907 (error (error-message-string err)))))))
10908
10909 (defun js2-looking-at-operator-p ()
10910 "Return non-nil if text after point is a non-comma operator."
10911 (and (looking-at js2-indent-operator-re)
10912 (or (not (looking-at ":"))
10913 (save-excursion
10914 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10915 (looking-at "?"))))))
10916
10917 (defun js2-continued-expression-p ()
10918 "Return non-nil if the current line continues an expression."
10919 (save-excursion
10920 (back-to-indentation)
10921 (or (js2-looking-at-operator-p)
10922 (when (catch 'found
10923 (while (and (re-search-backward "\n" nil t)
10924 (let ((state (syntax-ppss)))
10925 (when (nth 4 state)
10926 (goto-char (nth 8 state))) ;; skip comments
10927 (skip-chars-backward " \t")
10928 (if (bolp)
10929 t
10930 (throw 'found t))))))
10931 (backward-char)
10932 (when (js2-looking-at-operator-p)
10933 (backward-char)
10934 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10935
10936 (defun js2-end-of-do-while-loop-p ()
10937 "Return non-nil if word after point is `while' of a do-while
10938 statement, else returns nil. A braceless do-while statement
10939 spanning several lines requires that the start of the loop is
10940 indented to the same column as the current line."
10941 (interactive)
10942 (save-excursion
10943 (when (looking-at "\\s-*\\<while\\>")
10944 (if (save-excursion
10945 (skip-chars-backward "[ \t\n]*}")
10946 (looking-at "[ \t\n]*}"))
10947 (save-excursion
10948 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10949 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10950 (or (looking-at "\\<do\\>")
10951 (let ((saved-indent (current-indentation)))
10952 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10953 (/= (current-indentation) saved-indent)))
10954 (and (looking-at "[ \t]*\\<do\\>")
10955 (not (js2-re-search-forward
10956 "\\<while\\>" (point-at-eol) t))
10957 (= (current-indentation) saved-indent))))))))
10958
10959 (defun js2-multiline-decl-indentation ()
10960 "Return the declaration indentation column if the current line belongs
10961 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10962 (let (forward-sexp-function ; use Lisp version
10963 at-opening-bracket)
10964 (save-excursion
10965 (back-to-indentation)
10966 (when (not (looking-at js2-declaration-keyword-re))
10967 (when (looking-at js2-indent-operator-re)
10968 (goto-char (match-end 0))) ; continued expressions are ok
10969 (while (and (not at-opening-bracket)
10970 (not (bobp))
10971 (let ((pos (point)))
10972 (save-excursion
10973 (js2-backward-sws)
10974 (or (eq (char-before) ?,)
10975 (and (not (eq (char-before) ?\;))
10976 (prog2 (skip-syntax-backward ".")
10977 (looking-at js2-indent-operator-re)
10978 (js2-backward-sws))
10979 (not (eq (char-before) ?\;)))
10980 (js2-same-line pos)))))
10981 (condition-case _
10982 (backward-sexp)
10983 (scan-error (setq at-opening-bracket t))))
10984 (when (looking-at js2-declaration-keyword-re)
10985 (goto-char (match-end 0))
10986 (1+ (current-column)))))))
10987
10988 (defun js2-ctrl-statement-indentation ()
10989 "Return the proper indentation of current line if it is a control statement.
10990 Returns an indentation if this line starts the body of a control
10991 statement without braces, else returns nil."
10992 (let (forward-sexp-function)
10993 (save-excursion
10994 (back-to-indentation)
10995 (when (and (not (js2-same-line (point-min)))
10996 (not (looking-at "{"))
10997 (js2-re-search-backward "[[:graph:]]" nil t)
10998 (not (looking-at "[{([]"))
10999 (progn
11000 (forward-char)
11001 (when (= (char-before) ?\))
11002 ;; scan-sexps sometimes throws an error
11003 (ignore-errors (backward-sexp))
11004 (skip-chars-backward " \t" (point-at-bol)))
11005 (let ((pt (point)))
11006 (back-to-indentation)
11007 (when (looking-at "}[ \t]*")
11008 (goto-char (match-end 0)))
11009 (and (looking-at js2-possibly-braceless-keywords-re)
11010 (= (match-end 0) pt)
11011 (not (js2-end-of-do-while-loop-p))))))
11012 (+ (current-indentation) js2-basic-offset)))))
11013
11014 (defun js2-indent-in-array-comp (parse-status)
11015 "Return non-nil if we think we're in an array comprehension.
11016 In particular, return the buffer position of the first `for' kwd."
11017 (let ((bracket (nth 1 parse-status))
11018 (end (point)))
11019 (when bracket
11020 (save-excursion
11021 (goto-char bracket)
11022 (when (looking-at "\\[")
11023 (forward-char 1)
11024 (js2-forward-sws)
11025 (if (looking-at "[[{]")
11026 (let (forward-sexp-function) ; use Lisp version
11027 (forward-sexp) ; skip destructuring form
11028 (js2-forward-sws)
11029 (if (and (/= (char-after) ?,) ; regular array
11030 (looking-at "for"))
11031 (match-beginning 0)))
11032 ;; to skip arbitrary expressions we need the parser,
11033 ;; so we'll just guess at it.
11034 (if (and (> end (point)) ; not empty literal
11035 (re-search-forward "[^,]]* \\(for\\) " end t)
11036 ;; not inside comment or string literal
11037 (let ((state (parse-partial-sexp bracket (point))))
11038 (not (or (nth 3 state) (nth 4 state)))))
11039 (match-beginning 1))))))))
11040
11041 (defun js2-array-comp-indentation (parse-status for-kwd)
11042 (if (js2-same-line for-kwd)
11043 ;; first continuation line
11044 (save-excursion
11045 (goto-char (nth 1 parse-status))
11046 (forward-char 1)
11047 (skip-chars-forward " \t")
11048 (current-column))
11049 (save-excursion
11050 (goto-char for-kwd)
11051 (current-column))))
11052
11053 (defun js2-maybe-goto-declaration-keyword-end (bracket)
11054 "Helper function for `js2-proper-indentation'.
11055 Depending on the value of `js2-pretty-multiline-declarations',
11056 move point to the end of a variable declaration keyword so that
11057 indentation is aligned to that column."
11058 (cond
11059 ((eq js2-pretty-multiline-declarations 'all)
11060 (when (looking-at js2-declaration-keyword-re)
11061 (goto-char (1+ (match-end 0)))))
11062 ((eq js2-pretty-multiline-declarations 'dynamic)
11063 (let (declaration-keyword-end
11064 at-closing-bracket-p
11065 comma-p)
11066 (when (looking-at js2-declaration-keyword-re)
11067 ;; Preserve the match data lest it somehow be overridden.
11068 (setq declaration-keyword-end (match-end 0))
11069 (save-excursion
11070 (goto-char bracket)
11071 (setq at-closing-bracket-p
11072 ;; Handle scan errors gracefully.
11073 (condition-case nil
11074 (progn
11075 ;; Use the regular `forward-sexp-function' because the
11076 ;; normal one for this mode uses the AST.
11077 (let (forward-sexp-function)
11078 (forward-sexp))
11079 t)
11080 (error nil)))
11081 (when at-closing-bracket-p
11082 (js2-forward-sws)
11083 (setq comma-p (looking-at-p ","))))
11084 (when comma-p
11085 (goto-char (1+ declaration-keyword-end))))))))
11086
11087 (defun js2-proper-indentation (parse-status)
11088 "Return the proper indentation for the current line."
11089 (save-excursion
11090 (back-to-indentation)
11091 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
11092 (at-closing-bracket (looking-at "[]})]"))
11093 (same-indent-p (or at-closing-bracket
11094 (looking-at "\\<case\\>[^:]")
11095 (and (looking-at "\\<default:")
11096 (save-excursion
11097 (js2-backward-sws)
11098 (not (memq (char-before) '(?, ?{)))))))
11099 (continued-expr-p (js2-continued-expression-p))
11100 (declaration-indent (and js2-pretty-multiline-declarations
11101 (js2-multiline-decl-indentation)))
11102 (bracket (nth 1 parse-status))
11103 beg indent)
11104 (cond
11105 ;; indent array comprehension continuation lines specially
11106 ((and bracket
11107 (>= js2-language-version 170)
11108 (not (js2-same-line bracket))
11109 (setq beg (js2-indent-in-array-comp parse-status))
11110 (>= (point) (save-excursion
11111 (goto-char beg)
11112 (point-at-bol)))) ; at or after first loop?
11113 (js2-array-comp-indentation parse-status beg))
11114
11115 (ctrl-stmt-indent)
11116
11117 ((and declaration-indent continued-expr-p)
11118 (+ declaration-indent js2-basic-offset))
11119
11120 (declaration-indent)
11121
11122 (bracket
11123 (goto-char bracket)
11124 (cond
11125 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
11126 (when (save-excursion (skip-chars-backward " \t)")
11127 (looking-at ")"))
11128 (backward-list))
11129 (back-to-indentation)
11130 (js2-maybe-goto-declaration-keyword-end bracket)
11131 (setq indent
11132 (cond (same-indent-p
11133 (current-column))
11134 (continued-expr-p
11135 (+ (current-column) (* 2 js2-basic-offset)))
11136 (t
11137 (+ (current-column) js2-basic-offset))))
11138 (if (and js2-indent-switch-body
11139 (not at-closing-bracket)
11140 (looking-at "\\_<switch\\_>"))
11141 (+ indent js2-basic-offset)
11142 indent))
11143 (t
11144 (unless same-indent-p
11145 (forward-char)
11146 (skip-chars-forward " \t"))
11147 (current-column))))
11148
11149 (continued-expr-p js2-basic-offset)
11150
11151 (t 0)))))
11152
11153 (defun js2-lineup-comment (parse-status)
11154 "Indent a multi-line block comment continuation line."
11155 (let* ((beg (nth 8 parse-status))
11156 (first-line (js2-same-line beg))
11157 (offset (save-excursion
11158 (goto-char beg)
11159 (if (looking-at "/\\*")
11160 (+ 1 (current-column))
11161 0))))
11162 (unless first-line
11163 (indent-line-to offset))))
11164
11165 (defun js2-backward-sws ()
11166 "Move backward through whitespace and comments."
11167 (interactive)
11168 (while (forward-comment -1)))
11169
11170 (defun js2-forward-sws ()
11171 "Move forward through whitespace and comments."
11172 (interactive)
11173 (while (forward-comment 1)))
11174
11175 (defun js2-current-indent (&optional pos)
11176 "Return column of indentation on current line.
11177 If POS is non-nil, go to that point and return indentation for that line."
11178 (save-excursion
11179 (if pos
11180 (goto-char pos))
11181 (back-to-indentation)
11182 (current-column)))
11183
11184 (defun js2-arglist-close ()
11185 "Return non-nil if we're on a line beginning with a close-paren/brace."
11186 (save-excursion
11187 (goto-char (point-at-bol))
11188 (js2-forward-sws)
11189 (looking-at "[])}]")))
11190
11191 (defun js2-indent-looks-like-label-p ()
11192 (goto-char (point-at-bol))
11193 (js2-forward-sws)
11194 (looking-at (concat js2-mode-identifier-re ":")))
11195
11196 (defun js2-indent-in-objlit-p (parse-status)
11197 "Return non-nil if this looks like an object-literal entry."
11198 (let ((start (nth 1 parse-status)))
11199 (and
11200 start
11201 (save-excursion
11202 (and (zerop (forward-line -1))
11203 (not (< (point) start)) ; crossed a {} boundary
11204 (js2-indent-looks-like-label-p)))
11205 (save-excursion
11206 (js2-indent-looks-like-label-p)))))
11207
11208 ;; If prev line looks like foobar({ then we're passing an object
11209 ;; literal to a function call, and people pretty much always want to
11210 ;; de-dent back to the previous line, so move the 'basic-offset'
11211 ;; position to the front.
11212 (defun js2-indent-objlit-arg-p (parse-status)
11213 (save-excursion
11214 (back-to-indentation)
11215 (js2-backward-sws)
11216 (and (eq (1- (point)) (nth 1 parse-status))
11217 (eq (char-before) ?{)
11218 (progn
11219 (forward-char -1)
11220 (skip-chars-backward " \t")
11221 (eq (char-before) ?\()))))
11222
11223 (defun js2-indent-case-block-p ()
11224 (save-excursion
11225 (back-to-indentation)
11226 (js2-backward-sws)
11227 (goto-char (point-at-bol))
11228 (skip-chars-forward " \t")
11229 (looking-at "case\\s-.+:")))
11230
11231 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
11232 "Cycle among alternate computed indentation positions.
11233 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
11234 of the buffer to the current point. NORMAL-COL is the indentation
11235 column computed by the heuristic guesser based on current paren,
11236 bracket, brace and statement nesting. If BACKWARDS, cycle positions
11237 in reverse."
11238 (let ((cur-indent (js2-current-indent))
11239 (old-buffer-undo-list buffer-undo-list)
11240 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
11241 (current-line (save-excursion
11242 (forward-line 0) ; move to bol
11243 (1+ (count-lines (point-min) (point)))))
11244 positions pos main-pos anchor arglist-cont same-indent
11245 basic-offset computed-pos)
11246 ;; temporarily don't record undo info, if user requested this
11247 (when js2-mode-indent-inhibit-undo
11248 (setq buffer-undo-list t))
11249 (unwind-protect
11250 (progn
11251 ;; First likely point: indent from beginning of previous code line
11252 (push (setq basic-offset
11253 (+ (save-excursion
11254 (back-to-indentation)
11255 (js2-backward-sws)
11256 (back-to-indentation)
11257 (current-column))
11258 js2-basic-offset))
11259 positions)
11260
11261 ;; (First + epsilon) likely point: indent 2x from beginning of
11262 ;; previous code line. Google does it this way.
11263 (push (setq basic-offset
11264 (+ (save-excursion
11265 (back-to-indentation)
11266 (js2-backward-sws)
11267 (back-to-indentation)
11268 (current-column))
11269 (* 2 js2-basic-offset)))
11270 positions)
11271
11272 ;; Second likely point: indent from assign-expr RHS. This
11273 ;; is just a crude guess based on finding " = " on the previous
11274 ;; line containing actual code.
11275 (setq pos (save-excursion
11276 (forward-line -1)
11277 (goto-char (point-at-bol))
11278 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
11279 (point-at-eol) t)
11280 (goto-char (match-end 1))
11281 (skip-chars-forward " \t\r\n")
11282 (current-column))))
11283 (when pos
11284 (cl-incf pos js2-basic-offset)
11285 (push pos positions))
11286
11287 ;; Third likely point: same indent as previous line of code.
11288 ;; Make it the first likely point if we're not on an
11289 ;; arglist-close line and previous line ends in a comma, or
11290 ;; both this line and prev line look like object-literal
11291 ;; elements.
11292 (setq pos (save-excursion
11293 (goto-char (point-at-bol))
11294 (js2-backward-sws)
11295 (back-to-indentation)
11296 (prog1
11297 (current-column)
11298 ;; while we're here, look for trailing comma
11299 (if (save-excursion
11300 (goto-char (point-at-eol))
11301 (js2-backward-sws)
11302 (eq (char-before) ?,))
11303 (setq arglist-cont (1- (point)))))))
11304 (when pos
11305 (if (and (or arglist-cont
11306 (js2-indent-in-objlit-p parse-status))
11307 (not (js2-arglist-close)))
11308 (setq same-indent pos))
11309 (push pos positions))
11310
11311 ;; Fourth likely point: first preceding code with less indentation.
11312 ;; than the immediately preceding code line.
11313 (setq pos (save-excursion
11314 (back-to-indentation)
11315 (js2-backward-sws)
11316 (back-to-indentation)
11317 (setq anchor (current-column))
11318 (while (and (zerop (forward-line -1))
11319 (>= (progn
11320 (back-to-indentation)
11321 (current-column))
11322 anchor)))
11323 (setq pos (current-column))))
11324 (push pos positions)
11325
11326 ;; nesting-heuristic position, main by default
11327 (push (setq main-pos normal-col) positions)
11328
11329 ;; delete duplicates and sort positions list
11330 (setq positions (sort (delete-dups positions) '<))
11331
11332 ;; comma-list continuation lines: prev line indent takes precedence
11333 (if same-indent
11334 (setq main-pos same-indent))
11335
11336 ;; common special cases where we want to indent in from previous line
11337 (if (or (js2-indent-case-block-p)
11338 (js2-indent-objlit-arg-p parse-status))
11339 (setq main-pos basic-offset))
11340
11341 ;; if bouncing backwards, reverse positions list
11342 (if backwards
11343 (setq positions (reverse positions)))
11344
11345 ;; record whether we're already sitting on one of the alternatives
11346 (setq pos (member cur-indent positions))
11347
11348 (cond
11349 ;; case 0: we're one one of the alternatives and this is the
11350 ;; first time they've pressed TAB on this line (best-guess).
11351 ((and js2-mode-indent-ignore-first-tab
11352 pos
11353 ;; first time pressing TAB on this line?
11354 (not (eq js2-mode-last-indented-line current-line)))
11355 ;; do nothing
11356 (setq computed-pos nil))
11357 ;; case 1: only one computed position => use it
11358 ((null (cdr positions))
11359 (setq computed-pos 0))
11360 ;; case 2: not on any of the computed spots => use main spot
11361 ((not pos)
11362 (setq computed-pos (js2-position main-pos positions)))
11363 ;; case 3: on last position: cycle to first position
11364 ((null (cdr pos))
11365 (setq computed-pos 0))
11366 ;; case 4: on intermediate position: cycle to next position
11367 (t
11368 (setq computed-pos (js2-position (cl-second pos) positions))))
11369
11370 ;; see if any hooks want to indent; otherwise we do it
11371 (cl-loop with result = nil
11372 for hook in js2-indent-hook
11373 while (null result)
11374 do
11375 (setq result (funcall hook positions computed-pos))
11376 finally do
11377 (unless (or result (null computed-pos))
11378 (indent-line-to (nth computed-pos positions)))))
11379
11380 ;; finally
11381 (if js2-mode-indent-inhibit-undo
11382 (setq buffer-undo-list old-buffer-undo-list))
11383 ;; see commentary for `js2-mode-last-indented-line'
11384 (setq js2-mode-last-indented-line current-line))))
11385
11386 (defun js2-indent-bounce-backwards ()
11387 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11388 cycles between the computed indentation positions in reverse order."
11389 (interactive)
11390 (js2-indent-line t))
11391
11392 (defun js2-1-line-comment-continuation-p ()
11393 "Return t if we're in a 1-line comment continuation.
11394 If so, we don't ever want to use bounce-indent."
11395 (save-excursion
11396 (and (progn
11397 (forward-line 0)
11398 (looking-at "\\s-*//"))
11399 (progn
11400 (forward-line -1)
11401 (forward-line 0)
11402 (when (looking-at "\\s-*$")
11403 (js2-backward-sws)
11404 (forward-line 0))
11405 (looking-at "\\s-*//")))))
11406
11407 (defun js2-indent-line (&optional bounce-backwards)
11408 "Indent the current line as JavaScript source text."
11409 (interactive)
11410 (let (parse-status offset indent-col
11411 ;; Don't whine about errors/warnings when we're indenting.
11412 ;; This has to be set before calling parse-partial-sexp below.
11413 (inhibit-point-motion-hooks t))
11414 (setq parse-status (save-excursion
11415 (syntax-ppss (point-at-bol)))
11416 offset (- (point) (save-excursion
11417 (back-to-indentation)
11418 (point))))
11419 ;; Don't touch multiline strings.
11420 (unless (nth 3 parse-status)
11421 (js2-with-underscore-as-word-syntax
11422 (if (nth 4 parse-status)
11423 (js2-lineup-comment parse-status)
11424 (setq indent-col (js2-proper-indentation parse-status))
11425 ;; See comments below about `js2-mode-last-indented-line'.
11426 (cond
11427 ;; bounce-indenting is disabled during electric-key indent.
11428 ;; It doesn't work well on first line of buffer.
11429 ((and js2-bounce-indent-p
11430 (not (js2-same-line (point-min)))
11431 (not (js2-1-line-comment-continuation-p)))
11432 (js2-bounce-indent indent-col parse-status bounce-backwards))
11433 ;; just indent to the guesser's likely spot
11434 (t (indent-line-to indent-col))))
11435 (when (cl-plusp offset)
11436 (forward-char offset))))))
11437
11438 (defun js2-indent-region (start end)
11439 "Indent the region, but don't use bounce indenting."
11440 (let ((js2-bounce-indent-p nil)
11441 (indent-region-function nil)
11442 (after-change-functions (remq 'js2-mode-edit
11443 after-change-functions)))
11444 (indent-region start end nil) ; nil for byte-compiler
11445 (js2-mode-edit start end (- end start))))
11446
11447 (defvar js2-minor-mode-map
11448 (let ((map (make-sparse-keymap)))
11449 (define-key map (kbd "C-c C-`") #'js2-next-error)
11450 (define-key map [mouse-1] #'js2-mode-show-node)
11451 map)
11452 "Keymap used when `js2-minor-mode' is active.")
11453
11454 ;;;###autoload
11455 (define-minor-mode js2-minor-mode
11456 "Minor mode for running js2 as a background linter.
11457 This allows you to use a different major mode for JavaScript editing,
11458 such as `js-mode', while retaining the asynchronous error/warning
11459 highlighting features of `js2-mode'."
11460 :group 'js2-mode
11461 :lighter " js-lint"
11462 (if js2-minor-mode
11463 (js2-minor-mode-enter)
11464 (js2-minor-mode-exit)))
11465
11466 (defun js2-minor-mode-enter ()
11467 "Initialization for `js2-minor-mode'."
11468 (set (make-local-variable 'max-lisp-eval-depth)
11469 (max max-lisp-eval-depth 3000))
11470 (setq next-error-function #'js2-next-error)
11471 (js2-set-default-externs)
11472 ;; Experiment: make reparse-delay longer for longer files.
11473 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11474 (setq js2-idle-timer-delay
11475 (* js2-idle-timer-delay
11476 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11477 (setq js2-mode-buffer-dirty-p t
11478 js2-mode-parsing nil)
11479 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11480 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11481 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11482 (when js2-include-jslint-globals
11483 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11484 (run-hooks 'js2-init-hook)
11485 (js2-reparse))
11486
11487 (defun js2-minor-mode-exit ()
11488 "Turn off `js2-minor-mode'."
11489 (setq next-error-function nil)
11490 (remove-hook 'after-change-functions #'js2-mode-edit t)
11491 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11492 (when js2-mode-node-overlay
11493 (delete-overlay js2-mode-node-overlay)
11494 (setq js2-mode-node-overlay nil))
11495 (js2-remove-overlays)
11496 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11497 (setq js2-mode-ast nil))
11498
11499 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11500 (make-variable-buffer-local 'js2-source-buffer)
11501
11502 (cl-defun js2-display-error-list ()
11503 "Display a navigable buffer listing parse errors/warnings."
11504 (interactive)
11505 (unless (js2-have-errors-p)
11506 (message "No errors")
11507 (cl-return-from js2-display-error-list))
11508 (cl-labels ((annotate-list
11509 (lst type)
11510 "Add diagnostic TYPE and line number to errs list"
11511 (mapcar (lambda (err)
11512 (list err type (line-number-at-pos (nth 1 err))))
11513 lst)))
11514 (let* ((srcbuf (current-buffer))
11515 (errbuf (get-buffer-create "*js-lint*"))
11516 (errors (annotate-list
11517 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11518 'js2-error)) ; must be a valid face name
11519 (warnings (annotate-list
11520 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11521 'js2-warning)) ; must be a valid face name
11522 (all-errs (sort (append errors warnings)
11523 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11524 (with-current-buffer errbuf
11525 (let ((inhibit-read-only t))
11526 (erase-buffer)
11527 (dolist (err all-errs)
11528 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11529 (insert-text-button
11530 (format "line %d: %s" line (js2-get-msg msg-key))
11531 'face type
11532 'follow-link "\C-m"
11533 'action 'js2-error-buffer-jump
11534 'js2-msg (js2-get-msg msg-key)
11535 'js2-pos beg)
11536 (insert "\n"))))
11537 (js2-error-buffer-mode)
11538 (setq js2-source-buffer srcbuf)
11539 (pop-to-buffer errbuf)
11540 (goto-char (point-min))
11541 (unless (eobp)
11542 (js2-error-buffer-view))))))
11543
11544 (defvar js2-error-buffer-mode-map
11545 (let ((map (make-sparse-keymap)))
11546 (define-key map "n" #'js2-error-buffer-next)
11547 (define-key map "p" #'js2-error-buffer-prev)
11548 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11549 (define-key map "o" #'js2-error-buffer-view)
11550 (define-key map "q" #'js2-error-buffer-quit)
11551 map)
11552 "Keymap used for js2 diagnostics buffers.")
11553
11554 (defun js2-error-buffer-mode ()
11555 "Major mode for js2 diagnostics buffers.
11556 Selecting an error will jump it to the corresponding source-buffer error.
11557 \\{js2-error-buffer-mode-map}"
11558 (interactive)
11559 (setq major-mode 'js2-error-buffer-mode
11560 mode-name "JS Lint Diagnostics")
11561 (use-local-map js2-error-buffer-mode-map)
11562 (setq truncate-lines t)
11563 (set-buffer-modified-p nil)
11564 (setq buffer-read-only t)
11565 (run-hooks 'js2-error-buffer-mode-hook))
11566
11567 (defun js2-error-buffer-next ()
11568 "Move to next error and view it."
11569 (interactive)
11570 (when (zerop (forward-line 1))
11571 (js2-error-buffer-view)))
11572
11573 (defun js2-error-buffer-prev ()
11574 "Move to previous error and view it."
11575 (interactive)
11576 (when (zerop (forward-line -1))
11577 (js2-error-buffer-view)))
11578
11579 (defun js2-error-buffer-quit ()
11580 "Kill the current buffer."
11581 (interactive)
11582 (kill-buffer))
11583
11584 (defun js2-error-buffer-jump (&rest ignored)
11585 "Jump cursor to current error in source buffer."
11586 (interactive)
11587 (when (js2-error-buffer-view)
11588 (pop-to-buffer js2-source-buffer)))
11589
11590 (defun js2-error-buffer-view ()
11591 "Scroll source buffer to show error at current line."
11592 (interactive)
11593 (cond
11594 ((not (eq major-mode 'js2-error-buffer-mode))
11595 (message "Not in a js2 errors buffer"))
11596 ((not (buffer-live-p js2-source-buffer))
11597 (message "Source buffer has been killed"))
11598 ((not (wholenump (get-text-property (point) 'js2-pos)))
11599 (message "There does not seem to be an error here"))
11600 (t
11601 (let ((pos (get-text-property (point) 'js2-pos))
11602 (msg (get-text-property (point) 'js2-msg)))
11603 (save-selected-window
11604 (pop-to-buffer js2-source-buffer)
11605 (goto-char pos)
11606 (message msg))))))
11607
11608 ;;;###autoload
11609 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11610 ;; FIXME: Should derive from js-mode.
11611 "Major mode for editing JavaScript code."
11612 ;; Used by comment-region; don't change it.
11613 (set (make-local-variable 'comment-start) "//")
11614 (set (make-local-variable 'comment-end) "")
11615 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11616 (set (make-local-variable 'max-lisp-eval-depth)
11617 (max max-lisp-eval-depth 3000))
11618 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11619 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11620 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11621 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11622 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11623 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11624 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11625 ;; for characters inside regexp literals.
11626 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11627 ;; this is necessary to make `show-paren-function' work properly
11628 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11629 ;; needed for M-x rgrep, among other things
11630 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11631
11632 (set (make-local-variable 'electric-indent-chars)
11633 (append "{}()[]:;,*." electric-indent-chars))
11634 (set (make-local-variable 'electric-layout-rules)
11635 '((?\; . after) (?\{ . after) (?\} . before)))
11636
11637 ;; some variables needed by cc-engine for paragraph-fill, etc.
11638 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11639 c-comment-start-regexp "/[*/]\\|\\s|"
11640 c-line-comment-starter "//"
11641 c-paragraph-start js2-paragraph-start
11642 c-paragraph-separate "$"
11643 c-syntactic-ws-start js2-syntactic-ws-start
11644 c-syntactic-ws-end js2-syntactic-ws-end
11645 c-syntactic-eol js2-syntactic-eol)
11646
11647 (let ((c-buffer-is-cc-mode t))
11648 ;; Copied from `js-mode'. Also see Bug#6071.
11649 (make-local-variable 'paragraph-start)
11650 (make-local-variable 'paragraph-separate)
11651 (make-local-variable 'paragraph-ignore-fill-prefix)
11652 (make-local-variable 'adaptive-fill-mode)
11653 (make-local-variable 'adaptive-fill-regexp)
11654 (c-setup-paragraph-variables))
11655
11656 (setq font-lock-defaults '(nil t))
11657
11658 ;; Experiment: make reparse-delay longer for longer files.
11659 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11660 (setq js2-idle-timer-delay
11661 (* js2-idle-timer-delay
11662 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11663
11664 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11665 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11666 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11667 (setq next-error-function #'js2-next-error)
11668 (imenu-add-to-menubar (concat "IM-" mode-name))
11669 (add-to-invisibility-spec '(js2-outline . t))
11670 (set (make-local-variable 'line-move-ignore-invisible) t)
11671 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11672 (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
11673
11674 (setq js2-mode-functions-hidden nil
11675 js2-mode-comments-hidden nil
11676 js2-mode-buffer-dirty-p t
11677 js2-mode-parsing nil)
11678
11679 (js2-set-default-externs)
11680
11681 (when js2-include-jslint-globals
11682 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11683
11684 (run-hooks 'js2-init-hook)
11685
11686 (js2-reparse))
11687
11688 (defun js2-mode-exit ()
11689 "Exit `js2-mode' and clean up."
11690 (interactive)
11691 (when js2-mode-node-overlay
11692 (delete-overlay js2-mode-node-overlay)
11693 (setq js2-mode-node-overlay nil))
11694 (js2-remove-overlays)
11695 (setq js2-mode-ast nil)
11696 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11697 (remove-from-invisibility-spec '(js2-outline . t))
11698 (js2-mode-show-all)
11699 (with-silent-modifications
11700 (js2-clear-face (point-min) (point-max))))
11701
11702 (defun js2-mode-reset-timer ()
11703 "Cancel any existing parse timer and schedule a new one."
11704 (if js2-mode-parse-timer
11705 (cancel-timer js2-mode-parse-timer))
11706 (setq js2-mode-parsing nil)
11707 (let ((timer (timer-create)))
11708 (setq js2-mode-parse-timer timer)
11709 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11710 (timer-set-idle-time timer js2-idle-timer-delay)
11711 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11712 (timer-activate-when-idle timer nil)))
11713
11714 (defun js2-mode-idle-reparse (buffer)
11715 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11716 it to be reparsed when the buffer is selected."
11717 (cond ((eq buffer (current-buffer))
11718 (js2-reparse))
11719 ((buffer-live-p buffer)
11720 ;; reparse when the buffer is selected again
11721 (with-current-buffer buffer
11722 (add-hook 'window-configuration-change-hook
11723 #'js2-mode-idle-reparse-inner
11724 nil t)))))
11725
11726 (defun js2-mode-idle-reparse-inner ()
11727 (remove-hook 'window-configuration-change-hook
11728 #'js2-mode-idle-reparse-inner
11729 t)
11730 (js2-reparse))
11731
11732 (defun js2-mode-edit (_beg _end _len)
11733 "Schedule a new parse after buffer is edited.
11734 Buffer edit spans from BEG to END and is of length LEN."
11735 (setq js2-mode-buffer-dirty-p t)
11736 (js2-mode-hide-overlay)
11737 (js2-mode-reset-timer))
11738
11739 (defun js2-minor-mode-edit (_beg _end _len)
11740 "Callback for buffer edits in `js2-mode'.
11741 Schedules a new parse after buffer is edited.
11742 Buffer edit spans from BEG to END and is of length LEN."
11743 (setq js2-mode-buffer-dirty-p t)
11744 (js2-mode-hide-overlay)
11745 (js2-mode-reset-timer))
11746
11747 (defun js2-reparse (&optional force)
11748 "Re-parse current buffer after user finishes some data entry.
11749 If we get any user input while parsing, including cursor motion,
11750 we discard the parse and reschedule it. If FORCE is nil, then the
11751 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11752 (let (time
11753 interrupted-p
11754 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11755 (unless js2-mode-parsing
11756 (setq js2-mode-parsing t)
11757 (unwind-protect
11758 (when (or js2-mode-buffer-dirty-p force)
11759 (js2-remove-overlays)
11760 (setq js2-mode-buffer-dirty-p nil
11761 js2-mode-fontifications nil
11762 js2-mode-deferred-properties nil)
11763 (if js2-mode-verbose-parse-p
11764 (message "parsing..."))
11765 (setq time
11766 (js2-time
11767 (setq interrupted-p
11768 (catch 'interrupted
11769 (js2-parse)
11770 (with-silent-modifications
11771 ;; if parsing is interrupted, comments and regex
11772 ;; literals stay ignored by `parse-partial-sexp'
11773 (remove-text-properties (point-min) (point-max)
11774 '(syntax-table))
11775 (js2-mode-apply-deferred-properties)
11776 (js2-mode-remove-suppressed-warnings)
11777 (js2-mode-show-warnings)
11778 (js2-mode-show-errors)
11779 (if (>= js2-highlight-level 1)
11780 (js2-highlight-jsdoc js2-mode-ast)))
11781 nil))))
11782 (if interrupted-p
11783 (progn
11784 ;; unfinished parse => try again
11785 (setq js2-mode-buffer-dirty-p t)
11786 (js2-mode-reset-timer))
11787 (if js2-mode-verbose-parse-p
11788 (message "Parse time: %s" time))))
11789 (setq js2-mode-parsing nil)
11790 (unless interrupted-p
11791 (setq js2-mode-parse-timer nil))))))
11792
11793 (defun js2-mode-show-node (event)
11794 "Debugging aid: highlight selected AST node on mouse click."
11795 (interactive "e")
11796 (mouse-set-point event)
11797 (setq deactivate-mark t)
11798 (when js2-mode-show-overlay
11799 (let ((node (js2-node-at-point))
11800 beg end)
11801 (if (null node)
11802 (message "No node found at location %s" (point))
11803 (setq beg (js2-node-abs-pos node)
11804 end (+ beg (js2-node-len node)))
11805 (if js2-mode-node-overlay
11806 (move-overlay js2-mode-node-overlay beg end)
11807 (setq js2-mode-node-overlay (make-overlay beg end))
11808 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11809 (with-silent-modifications
11810 (if (fboundp 'cursor-sensor-mode)
11811 (put-text-property beg end 'cursor-sensor-functions
11812 '(js2-mode-hide-overlay))
11813 (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
11814 (message "%s, parent: %s"
11815 (js2-node-short-name node)
11816 (if (js2-node-parent node)
11817 (js2-node-short-name (js2-node-parent node))
11818 "nil"))))))
11819
11820 (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
11821 "Remove the debugging overlay when point moves.
11822 ARG1, ARG2 and ARG3 have different values depending on whether this function
11823 was found on `point-left' or in `cursor-sensor-functions'."
11824 (when js2-mode-node-overlay
11825 (let ((beg (overlay-start js2-mode-node-overlay))
11826 (end (overlay-end js2-mode-node-overlay))
11827 (p2 (if (windowp arg1)
11828 ;; Called from cursor-sensor-functions.
11829 (window-point arg1)
11830 ;; Called from point-left.
11831 arg2)))
11832 ;; Sometimes we're called spuriously.
11833 (unless (and p2
11834 (>= p2 beg)
11835 (<= p2 end))
11836 (with-silent-modifications
11837 (remove-text-properties beg end
11838 '(point-left nil cursor-sensor-functions)))
11839 (delete-overlay js2-mode-node-overlay)
11840 (setq js2-mode-node-overlay nil)))))
11841
11842 (defun js2-mode-reset ()
11843 "Debugging helper: reset everything."
11844 (interactive)
11845 (js2-mode-exit)
11846 (js2-mode))
11847
11848 (defun js2-mode-show-warn-or-err (e face)
11849 "Highlight a warning or error E with FACE.
11850 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11851 The last element is optional. When present, use instead of FACE."
11852 (let* ((key (cl-first e))
11853 (beg (cl-second e))
11854 (end (+ beg (cl-third e)))
11855 ;; Don't inadvertently go out of bounds.
11856 (beg (max (point-min) (min beg (point-max))))
11857 (end (max (point-min) (min end (point-max))))
11858 (ovl (make-overlay beg end)))
11859 ;; FIXME: Why a mix of overlays and text-properties?
11860 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11861 (overlay-put ovl 'js2-error t)
11862 (put-text-property beg end 'help-echo (js2-get-msg key))
11863 (if (fboundp 'cursor-sensor-mode)
11864 (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
11865 (put-text-property beg end 'point-entered #'js2-echo-error))))
11866
11867 (defun js2-remove-overlays ()
11868 "Remove overlays from buffer that have a `js2-error' property."
11869 (let ((beg (point-min))
11870 (end (point-max)))
11871 (save-excursion
11872 (dolist (o (overlays-in beg end))
11873 (when (overlay-get o 'js2-error)
11874 (delete-overlay o))))))
11875
11876 (defun js2-mode-apply-deferred-properties ()
11877 "Apply fontifications and other text properties recorded during parsing."
11878 (when (cl-plusp js2-highlight-level)
11879 ;; We defer clearing faces as long as possible to eliminate flashing.
11880 (js2-clear-face (point-min) (point-max))
11881 ;; Have to reverse the recorded fontifications list so that errors
11882 ;; and warnings overwrite the normal fontifications.
11883 (dolist (f (nreverse js2-mode-fontifications))
11884 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11885 (setq js2-mode-fontifications nil))
11886 (dolist (p js2-mode-deferred-properties)
11887 (apply #'put-text-property p))
11888 (setq js2-mode-deferred-properties nil))
11889
11890 (defun js2-mode-show-errors ()
11891 "Highlight syntax errors."
11892 (when js2-mode-show-parse-errors
11893 (dolist (e (js2-ast-root-errors js2-mode-ast))
11894 (js2-mode-show-warn-or-err e 'js2-error))))
11895
11896 (defun js2-mode-remove-suppressed-warnings ()
11897 "Take suppressed warnings out of the AST warnings list.
11898 This ensures that the counts and `next-error' are correct."
11899 (setf (js2-ast-root-warnings js2-mode-ast)
11900 (js2-delete-if
11901 (lambda (e)
11902 (let ((key (caar e)))
11903 (or
11904 (and (not js2-strict-trailing-comma-warning)
11905 (string-match "trailing\\.comma" key))
11906 (and (not js2-strict-cond-assign-warning)
11907 (string= key "msg.equal.as.assign"))
11908 (and js2-missing-semi-one-line-override
11909 (string= key "msg.missing.semi")
11910 (let* ((beg (cl-second e))
11911 (node (js2-node-at-point beg))
11912 (fn (js2-mode-find-parent-fn node))
11913 (body (and fn (js2-function-node-body fn)))
11914 (lc (and body (js2-node-abs-pos body)))
11915 (rc (and lc (+ lc (js2-node-len body)))))
11916 (and fn
11917 (or (null body)
11918 (save-excursion
11919 (goto-char beg)
11920 (and (js2-same-line lc)
11921 (js2-same-line rc))))))))))
11922 (js2-ast-root-warnings js2-mode-ast))))
11923
11924 (defun js2-mode-show-warnings ()
11925 "Highlight strict-mode warnings."
11926 (when js2-mode-show-strict-warnings
11927 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11928 (js2-mode-show-warn-or-err e 'js2-warning))))
11929
11930 (defun js2-echo-error (arg1 arg2 &optional _arg3)
11931 "Called by point-motion hooks.
11932 ARG1, ARG2 and ARG3 have different values depending on whether this function
11933 was found on `point-entered' or in `cursor-sensor-functions'."
11934 (let* ((new-point (if (windowp arg1)
11935 ;; Called from cursor-sensor-functions.
11936 (window-point arg1)
11937 ;; Called from point-left.
11938 arg2))
11939 (msg (get-text-property new-point 'help-echo)))
11940 (when (and (stringp msg)
11941 (not (active-minibuffer-window))
11942 (not (current-message)))
11943 (message msg))))
11944
11945 (defun js2-line-break (&optional _soft)
11946 "Break line at point and indent, continuing comment if within one.
11947 If inside a string, and `js2-concat-multiline-strings' is not
11948 nil, turn it into concatenation."
11949 (interactive)
11950 (let ((parse-status (syntax-ppss)))
11951 (cond
11952 ;; Check if we're inside a string.
11953 ((nth 3 parse-status)
11954 (if js2-concat-multiline-strings
11955 (js2-mode-split-string parse-status)
11956 (insert "\n")))
11957 ;; Check if inside a block comment.
11958 ((nth 4 parse-status)
11959 (js2-mode-extend-comment (nth 8 parse-status)))
11960 (t
11961 (newline-and-indent)))))
11962
11963 (defun js2-mode-split-string (parse-status)
11964 "Turn a newline in mid-string into a string concatenation.
11965 PARSE-STATUS is as documented in `parse-partial-sexp'."
11966 (let* ((quote-char (nth 3 parse-status))
11967 (at-eol (eq js2-concat-multiline-strings 'eol)))
11968 (insert quote-char)
11969 (insert (if at-eol " +\n" "\n"))
11970 (unless at-eol
11971 (insert "+ "))
11972 (js2-indent-line)
11973 (insert quote-char)
11974 (when (eolp)
11975 (insert quote-char)
11976 (backward-char 1))))
11977
11978 (defun js2-mode-extend-comment (start-pos)
11979 "Indent the line and, when inside a comment block, add comment prefix."
11980 (let (star single col first-line needs-close)
11981 (save-excursion
11982 (back-to-indentation)
11983 (when (< (point) start-pos)
11984 (goto-char start-pos))
11985 (cond
11986 ((looking-at "\\*[^/]")
11987 (setq star t
11988 col (current-column)))
11989 ((looking-at "/\\*")
11990 (setq star t
11991 first-line t
11992 col (1+ (current-column))))
11993 ((looking-at "//")
11994 (setq single t
11995 col (current-column)))))
11996 ;; Heuristic for whether we need to close the comment:
11997 ;; if we've got a parse error here, assume it's an unterminated
11998 ;; comment.
11999 (setq needs-close
12000 (or
12001 (get-char-property (1- (point)) 'js2-error)
12002 ;; The heuristic above doesn't work well when we're
12003 ;; creating a comment and there's another one downstream,
12004 ;; as our parser thinks this one ends at the end of the
12005 ;; next one. (You can have a /* inside a js block comment.)
12006 ;; So just close it if the next non-ws char isn't a *.
12007 (and first-line
12008 (eolp)
12009 (save-excursion
12010 (skip-chars-forward " \t\r\n")
12011 (not (eq (char-after) ?*))))))
12012 (delete-horizontal-space)
12013 (insert "\n")
12014 (cond
12015 (star
12016 (indent-to col)
12017 (insert "* ")
12018 (if (and first-line needs-close)
12019 (save-excursion
12020 (insert "\n")
12021 (indent-to col)
12022 (insert "*/"))))
12023 ((and single
12024 (save-excursion
12025 (and (zerop (forward-line 1))
12026 (looking-at "\\s-*//"))))
12027 (indent-to col)
12028 (insert "// ")))
12029 ;; Don't need to extend the comment after all.
12030 (js2-indent-line)))
12031
12032 (defun js2-beginning-of-line ()
12033 "Toggle point between bol and first non-whitespace char in line.
12034 Also moves past comment delimiters when inside comments."
12035 (interactive)
12036 (let (node)
12037 (cond
12038 ((bolp)
12039 (back-to-indentation))
12040 ((looking-at "//")
12041 (skip-chars-forward "/ \t"))
12042 ((and (eq (char-after) ?*)
12043 (setq node (js2-comment-at-point))
12044 (memq (js2-comment-node-format node) '(jsdoc block))
12045 (save-excursion
12046 (skip-chars-backward " \t")
12047 (bolp)))
12048 (skip-chars-forward "\* \t"))
12049 (t
12050 (goto-char (point-at-bol))))))
12051
12052 (defun js2-end-of-line ()
12053 "Toggle point between eol and last non-whitespace char in line."
12054 (interactive)
12055 (if (eolp)
12056 (skip-chars-backward " \t")
12057 (goto-char (point-at-eol))))
12058
12059 (defun js2-mode-wait-for-parse (callback)
12060 "Invoke CALLBACK when parsing is finished.
12061 If parsing is already finished, calls CALLBACK immediately."
12062 (if (not js2-mode-buffer-dirty-p)
12063 (funcall callback)
12064 (push callback js2-mode-pending-parse-callbacks)
12065 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
12066
12067 (defun js2-mode-parse-finished ()
12068 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
12069 ;; We can't let errors propagate up, since it prevents the
12070 ;; `js2-parse' method from completing normally and returning
12071 ;; the ast, which makes things mysteriously not work right.
12072 (unwind-protect
12073 (dolist (cb js2-mode-pending-parse-callbacks)
12074 (condition-case err
12075 (funcall cb)
12076 (error (message "%s" err))))
12077 (setq js2-mode-pending-parse-callbacks nil)))
12078
12079 (defun js2-mode-flag-region (from to flag)
12080 "Hide or show text from FROM to TO, according to FLAG.
12081 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
12082 Returns the created overlay if FLAG is non-nil."
12083 (remove-overlays from to 'invisible 'js2-outline)
12084 (when flag
12085 (let ((o (make-overlay from to)))
12086 (overlay-put o 'invisible 'js2-outline)
12087 (overlay-put o 'isearch-open-invisible
12088 'js2-isearch-open-invisible)
12089 o)))
12090
12091 ;; Function to be set as an outline-isearch-open-invisible' property
12092 ;; to the overlay that makes the outline invisible (see
12093 ;; `js2-mode-flag-region').
12094 (defun js2-isearch-open-invisible (_overlay)
12095 ;; We rely on the fact that isearch places point on the matched text.
12096 (js2-mode-show-element))
12097
12098 (defun js2-mode-invisible-overlay-bounds (&optional pos)
12099 "Return cons cell of bounds of folding overlay at POS.
12100 Returns nil if not found."
12101 (let ((overlays (overlays-at (or pos (point))))
12102 o)
12103 (while (and overlays
12104 (not o))
12105 (if (overlay-get (car overlays) 'invisible)
12106 (setq o (car overlays))
12107 (setq overlays (cdr overlays))))
12108 (if o
12109 (cons (overlay-start o) (overlay-end o)))))
12110
12111 (defun js2-mode-function-at-point (&optional pos)
12112 "Return the innermost function node enclosing current point.
12113 Returns nil if point is not in a function."
12114 (let ((node (js2-node-at-point pos)))
12115 (while (and node (not (js2-function-node-p node)))
12116 (setq node (js2-node-parent node)))
12117 (if (js2-function-node-p node)
12118 node)))
12119
12120 (defun js2-mode-toggle-element ()
12121 "Hide or show the foldable element at the point."
12122 (interactive)
12123 (let (comment fn pos)
12124 (save-excursion
12125 (cond
12126 ;; /* ... */ comment?
12127 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
12128 (if (js2-mode-invisible-overlay-bounds
12129 (setq pos (+ 3 (js2-node-abs-pos comment))))
12130 (progn
12131 (goto-char pos)
12132 (js2-mode-show-element))
12133 (js2-mode-hide-element)))
12134 ;; //-comment?
12135 ((save-excursion
12136 (back-to-indentation)
12137 (looking-at js2-mode-//-comment-re))
12138 (js2-mode-toggle-//-comment))
12139 ;; function?
12140 ((setq fn (js2-mode-function-at-point))
12141 (setq pos (and (js2-function-node-body fn)
12142 (js2-node-abs-pos (js2-function-node-body fn))))
12143 (goto-char (1+ pos))
12144 (if (js2-mode-invisible-overlay-bounds)
12145 (js2-mode-show-element)
12146 (js2-mode-hide-element)))
12147 (t
12148 (message "Nothing at point to hide or show"))))))
12149
12150 (defun js2-mode-hide-element ()
12151 "Fold/hide contents of a block, showing ellipses.
12152 Show the hidden text with \\[js2-mode-show-element]."
12153 (interactive)
12154 (if js2-mode-buffer-dirty-p
12155 (js2-mode-wait-for-parse #'js2-mode-hide-element))
12156 (let (node body beg end)
12157 (cond
12158 ((js2-mode-invisible-overlay-bounds)
12159 (message "already hidden"))
12160 (t
12161 (setq node (js2-node-at-point))
12162 (cond
12163 ((js2-block-comment-p node)
12164 (js2-mode-hide-comment node))
12165 (t
12166 (while (and node (not (js2-function-node-p node)))
12167 (setq node (js2-node-parent node)))
12168 (if (and node
12169 (setq body (js2-function-node-body node)))
12170 (progn
12171 (setq beg (js2-node-abs-pos body)
12172 end (+ beg (js2-node-len body)))
12173 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
12174 (message "No collapsable element found at point"))))))))
12175
12176 (defun js2-mode-show-element ()
12177 "Show the hidden element at current point."
12178 (interactive)
12179 (let ((bounds (js2-mode-invisible-overlay-bounds)))
12180 (if bounds
12181 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
12182 (message "Nothing to un-hide"))))
12183
12184 (defun js2-mode-show-all ()
12185 "Show all of the text in the buffer."
12186 (interactive)
12187 (js2-mode-flag-region (point-min) (point-max) nil))
12188
12189 (defun js2-mode-toggle-hide-functions ()
12190 (interactive)
12191 (if js2-mode-functions-hidden
12192 (js2-mode-show-functions)
12193 (js2-mode-hide-functions)))
12194
12195 (defun js2-mode-hide-functions ()
12196 "Hides all non-nested function bodies in the buffer.
12197 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12198 to open an individual entry."
12199 (interactive)
12200 (if js2-mode-buffer-dirty-p
12201 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
12202 (if (null js2-mode-ast)
12203 (message "Oops - parsing failed")
12204 (setq js2-mode-functions-hidden t)
12205 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
12206
12207 (defun js2-mode-function-hider (n endp)
12208 (when (not endp)
12209 (let ((tt (js2-node-type n))
12210 body beg end)
12211 (cond
12212 ((and (= tt js2-FUNCTION)
12213 (setq body (js2-function-node-body n)))
12214 (setq beg (js2-node-abs-pos body)
12215 end (+ beg (js2-node-len body)))
12216 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
12217 nil) ; don't process children of function
12218 (t
12219 t))))) ; keep processing other AST nodes
12220
12221 (defun js2-mode-show-functions ()
12222 "Un-hide any folded function bodies in the buffer."
12223 (interactive)
12224 (setq js2-mode-functions-hidden nil)
12225 (save-excursion
12226 (goto-char (point-min))
12227 (while (/= (goto-char (next-overlay-change (point)))
12228 (point-max))
12229 (dolist (o (overlays-at (point)))
12230 (when (and (overlay-get o 'invisible)
12231 (not (overlay-get o 'comment)))
12232 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12233
12234 (defun js2-mode-hide-comment (n)
12235 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
12236 3 ; /**
12237 2)) ; /*
12238 (beg (+ (js2-node-abs-pos n) head))
12239 (end (- (+ beg (js2-node-len n)) head 2))
12240 (o (js2-mode-flag-region beg end 'hide)))
12241 (overlay-put o 'comment t)))
12242
12243 (defun js2-mode-toggle-hide-comments ()
12244 "Folds all block comments in the buffer.
12245 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
12246 to open an individual entry."
12247 (interactive)
12248 (if js2-mode-comments-hidden
12249 (js2-mode-show-comments)
12250 (js2-mode-hide-comments)))
12251
12252 (defun js2-mode-hide-comments ()
12253 (interactive)
12254 (if js2-mode-buffer-dirty-p
12255 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
12256 (if (null js2-mode-ast)
12257 (message "Oops - parsing failed")
12258 (setq js2-mode-comments-hidden t)
12259 (dolist (n (js2-ast-root-comments js2-mode-ast))
12260 (when (js2-block-comment-p n)
12261 (js2-mode-hide-comment n)))
12262 (js2-mode-hide-//-comments)))
12263
12264 (defun js2-mode-extend-//-comment (direction)
12265 "Find start or end of a block of similar //-comment lines.
12266 DIRECTION is -1 to look back, 1 to look forward.
12267 INDENT is the indentation level to match.
12268 Returns the end-of-line position of the furthest adjacent
12269 //-comment line with the same indentation as the current line.
12270 If there is no such matching line, returns current end of line."
12271 (let ((pos (point-at-eol))
12272 (indent (current-indentation)))
12273 (save-excursion
12274 (while (and (zerop (forward-line direction))
12275 (looking-at js2-mode-//-comment-re)
12276 (eq indent (length (match-string 1))))
12277 (setq pos (point-at-eol)))
12278 pos)))
12279
12280 (defun js2-mode-hide-//-comments ()
12281 "Fold adjacent 1-line comments, showing only snippet of first one."
12282 (let (beg end)
12283 (save-excursion
12284 (goto-char (point-min))
12285 (while (re-search-forward js2-mode-//-comment-re nil t)
12286 (setq beg (point)
12287 end (js2-mode-extend-//-comment 1))
12288 (unless (eq beg end)
12289 (overlay-put (js2-mode-flag-region beg end 'hide)
12290 'comment t))
12291 (goto-char end)
12292 (forward-char 1)))))
12293
12294 (defun js2-mode-toggle-//-comment ()
12295 "Fold or un-fold any multi-line //-comment at point.
12296 Caller should have determined that this line starts with a //-comment."
12297 (let* ((beg (point-at-eol))
12298 (end beg))
12299 (save-excursion
12300 (goto-char end)
12301 (if (js2-mode-invisible-overlay-bounds)
12302 (js2-mode-show-element)
12303 ;; else hide the comment
12304 (setq beg (js2-mode-extend-//-comment -1)
12305 end (js2-mode-extend-//-comment 1))
12306 (unless (eq beg end)
12307 (overlay-put (js2-mode-flag-region beg end 'hide)
12308 'comment t))))))
12309
12310 (defun js2-mode-show-comments ()
12311 "Un-hide any hidden comments, leaving other hidden elements alone."
12312 (interactive)
12313 (setq js2-mode-comments-hidden nil)
12314 (save-excursion
12315 (goto-char (point-min))
12316 (while (/= (goto-char (next-overlay-change (point)))
12317 (point-max))
12318 (dolist (o (overlays-at (point)))
12319 (when (overlay-get o 'comment)
12320 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12321
12322 (defun js2-mode-display-warnings-and-errors ()
12323 "Turn on display of warnings and errors."
12324 (interactive)
12325 (setq js2-mode-show-parse-errors t
12326 js2-mode-show-strict-warnings t)
12327 (js2-reparse 'force))
12328
12329 (defun js2-mode-hide-warnings-and-errors ()
12330 "Turn off display of warnings and errors."
12331 (interactive)
12332 (setq js2-mode-show-parse-errors nil
12333 js2-mode-show-strict-warnings nil)
12334 (js2-reparse 'force))
12335
12336 (defun js2-mode-toggle-warnings-and-errors ()
12337 "Toggle the display of warnings and errors.
12338 Some users don't like having warnings/errors reported while they type."
12339 (interactive)
12340 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12341 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12342 (if (called-interactively-p 'any)
12343 (message "warnings and errors %s"
12344 (if js2-mode-show-parse-errors
12345 "enabled"
12346 "disabled")))
12347 (js2-reparse 'force))
12348
12349 (defun js2-mode-customize ()
12350 (interactive)
12351 (customize-group 'js2-mode))
12352
12353 (defun js2-mode-forward-sexp (&optional arg)
12354 "Move forward across one statement or balanced expression.
12355 With ARG, do it that many times. Negative arg -N means
12356 move backward across N balanced expressions."
12357 (interactive "p")
12358 (setq arg (or arg 1))
12359 (save-restriction
12360 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12361 (js2-reparse)
12362 (let (forward-sexp-function
12363 node (start (point)) pos lp rp child)
12364 (cond
12365 ;; backward-sexp
12366 ;; could probably make this better for some cases:
12367 ;; - if in statement block (e.g. function body), go to parent
12368 ;; - infix exprs like (foo in bar) - maybe go to beginning
12369 ;; of infix expr if in the right-side expression?
12370 ((and arg (cl-minusp arg))
12371 (dotimes (_ (- arg))
12372 (js2-backward-sws)
12373 (forward-char -1) ; Enter the node we backed up to.
12374 (when (setq node (js2-node-at-point (point) t))
12375 (setq pos (js2-node-abs-pos node))
12376 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12377 (setq lp (car parens)
12378 rp (cdr parens)))
12379 (when (and lp (> start lp))
12380 (if (and rp (<= start rp))
12381 ;; Between parens, check if there's a child node we can jump.
12382 (when (setq child (js2-node-closest-child node (point) lp t))
12383 (setq pos (js2-node-abs-pos child)))
12384 ;; Before both parens.
12385 (setq pos lp)))
12386 (let ((state (parse-partial-sexp start pos)))
12387 (goto-char (if (not (zerop (car state)))
12388 ;; Stumble at the unbalanced paren if < 0, or
12389 ;; jump a bit further if > 0.
12390 (scan-sexps start -1)
12391 pos))))
12392 (unless pos (goto-char (point-min)))))
12393 (t
12394 ;; forward-sexp
12395 (dotimes (_ arg)
12396 (js2-forward-sws)
12397 (when (setq node (js2-node-at-point (point) t))
12398 (setq pos (js2-node-abs-pos node))
12399 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12400 (setq lp (car parens)
12401 rp (cdr parens)))
12402 (or
12403 (when (and rp (<= start rp))
12404 (if (> start lp)
12405 (when (setq child (js2-node-closest-child node (point) rp))
12406 (setq pos (js2-node-abs-end child)))
12407 (setq pos (1+ rp))))
12408 ;; No parens or child nodes, looks for the end of the current node.
12409 (cl-incf pos (js2-node-len
12410 (if (js2-expr-stmt-node-p (js2-node-parent node))
12411 ;; Stop after the semicolon.
12412 (js2-node-parent node)
12413 node))))
12414 (let ((state (save-excursion (parse-partial-sexp start pos))))
12415 (goto-char (if (not (zerop (car state)))
12416 (scan-sexps start 1)
12417 pos))))
12418 (unless pos (goto-char (point-max)))))))))
12419
12420 (defun js2-mode-forward-sexp-parens (node abs-pos)
12421 "Return a cons cell with positions of main parens in NODE."
12422 (cond
12423 ((or (js2-array-node-p node)
12424 (js2-object-node-p node)
12425 (js2-comp-node-p node)
12426 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12427 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12428 ((js2-paren-expr-node-p node)
12429 (let ((lp (js2-node-lp node))
12430 (rp (js2-node-rp node)))
12431 (cons (when lp (+ abs-pos lp))
12432 (when rp (+ abs-pos rp)))))))
12433
12434 (defun js2-node-closest-child (parent point limit &optional before)
12435 (let* ((parent-pos (js2-node-abs-pos parent))
12436 (rpoint (- point parent-pos))
12437 (rlimit (- limit parent-pos))
12438 (min (min rpoint rlimit))
12439 (max (max rpoint rlimit))
12440 found)
12441 (catch 'done
12442 (js2-visit-ast
12443 parent
12444 (lambda (node _end-p)
12445 (if (eq node parent)
12446 t
12447 (let ((pos (js2-node-pos node)) ;; Both relative values.
12448 (end (+ (js2-node-pos node) (js2-node-len node))))
12449 (when (and (>= pos min) (<= end max)
12450 (if before (< pos rpoint) (> end rpoint)))
12451 (setq found node))
12452 (when (> end rpoint)
12453 (throw 'done nil)))
12454 nil))))
12455 found))
12456
12457 (defun js2-errors ()
12458 "Return a list of errors found."
12459 (and js2-mode-ast
12460 (js2-ast-root-errors js2-mode-ast)))
12461
12462 (defun js2-warnings ()
12463 "Return a list of warnings found."
12464 (and js2-mode-ast
12465 (js2-ast-root-warnings js2-mode-ast)))
12466
12467 (defun js2-have-errors-p ()
12468 "Return non-nil if any parse errors or warnings were found."
12469 (or (js2-errors) (js2-warnings)))
12470
12471 (defun js2-errors-and-warnings ()
12472 "Return a copy of the concatenated errors and warnings lists.
12473 They are appended: first the errors, then the warnings.
12474 Entries are of the form (MSG BEG END)."
12475 (when js2-mode-ast
12476 (append (js2-ast-root-errors js2-mode-ast)
12477 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12478
12479 (defun js2-next-error (&optional arg reset)
12480 "Move to next parse error.
12481 Typically invoked via \\[next-error].
12482 ARG is the number of errors, forward or backward, to move.
12483 RESET means start over from the beginning."
12484 (interactive "p")
12485 (if (not (or (js2-errors) (js2-warnings)))
12486 (message "No errors")
12487 (when reset
12488 (goto-char (point-min)))
12489 (let* ((errs (js2-errors-and-warnings))
12490 (continue t)
12491 (start (point))
12492 (count (or arg 1))
12493 (backward (cl-minusp count))
12494 (sorter (if backward '> '<))
12495 (stopper (if backward '< '>))
12496 (count (abs count))
12497 all-errs err)
12498 ;; Sort by start position.
12499 (setq errs (sort errs (lambda (e1 e2)
12500 (funcall sorter (cl-second e1) (cl-second e2))))
12501 all-errs errs)
12502 ;; Find nth error with pos > start.
12503 (while (and errs continue)
12504 (when (funcall stopper (cl-cadar errs) start)
12505 (setq err (car errs))
12506 (if (zerop (cl-decf count))
12507 (setq continue nil)))
12508 (setq errs (cdr errs)))
12509 ;; Clear for `js2-echo-error'.
12510 (message nil)
12511 (if err
12512 (goto-char (cl-second err))
12513 ;; Wrap around to first error.
12514 (goto-char (cl-second (car all-errs)))
12515 ;; If we were already on it, echo msg again.
12516 (if (= (point) start)
12517 (js2-echo-error (point) (point)))))))
12518
12519 (defun js2-down-mouse-3 ()
12520 "Make right-click move the point to the click location.
12521 This makes right-click context menu operations a bit more intuitive.
12522 The point will not move if the region is active, however, to avoid
12523 destroying the region selection."
12524 (interactive)
12525 (when (and js2-move-point-on-right-click
12526 (not mark-active))
12527 (let ((e last-input-event))
12528 (ignore-errors
12529 (goto-char (cl-cadadr e))))))
12530
12531 (defun js2-mode-create-imenu-index ()
12532 "Return an alist for `imenu--index-alist'."
12533 ;; This is built up in `js2-parse-record-imenu' during parsing.
12534 (when js2-mode-ast
12535 ;; if we have an ast but no recorder, they're requesting a rescan
12536 (unless js2-imenu-recorder
12537 (js2-reparse 'force))
12538 (prog1
12539 (js2-build-imenu-index)
12540 (setq js2-imenu-recorder nil
12541 js2-imenu-function-map nil))))
12542
12543 (defun js2-mode-find-tag ()
12544 "Replacement for `find-tag-default'.
12545 `find-tag-default' returns a ridiculous answer inside comments."
12546 (let (beg end)
12547 (js2-with-underscore-as-word-syntax
12548 (save-excursion
12549 (if (and (not (looking-at "[[:alnum:]_$]"))
12550 (looking-back "[[:alnum:]_$]"))
12551 (setq beg (progn (forward-word -1) (point))
12552 end (progn (forward-word 1) (point)))
12553 (setq beg (progn (forward-word 1) (point))
12554 end (progn (forward-word -1) (point))))
12555 (replace-regexp-in-string
12556 "[\"']" ""
12557 (buffer-substring-no-properties beg end))))))
12558
12559 (defun js2-mode-forward-sibling ()
12560 "Move to the end of the sibling following point in parent.
12561 Returns non-nil if successful, or nil if there was no following sibling."
12562 (let* ((node (js2-node-at-point))
12563 (parent (js2-mode-find-enclosing-fn node))
12564 sib)
12565 (when (setq sib (js2-node-find-child-after (point) parent))
12566 (goto-char (+ (js2-node-abs-pos sib)
12567 (js2-node-len sib))))))
12568
12569 (defun js2-mode-backward-sibling ()
12570 "Move to the beginning of the sibling node preceding point in parent.
12571 Parent is defined as the enclosing script or function."
12572 (let* ((node (js2-node-at-point))
12573 (parent (js2-mode-find-enclosing-fn node))
12574 sib)
12575 (when (setq sib (js2-node-find-child-before (point) parent))
12576 (goto-char (js2-node-abs-pos sib)))))
12577
12578 (defun js2-beginning-of-defun (&optional arg)
12579 "Go to line on which current function starts, and return t on success.
12580 If we're not in a function or already at the beginning of one, go
12581 to beginning of previous script-level element.
12582 With ARG N, do that N times. If N is negative, move forward."
12583 (setq arg (or arg 1))
12584 (if (cl-plusp arg)
12585 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12586 (when (cond
12587 ((js2-function-node-p parent)
12588 (goto-char (js2-node-abs-pos parent)))
12589 (t
12590 (js2-mode-backward-sibling)))
12591 (if (> arg 1)
12592 (js2-beginning-of-defun (1- arg))
12593 t)))
12594 (when (js2-end-of-defun)
12595 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12596
12597 (defun js2-end-of-defun ()
12598 "Go to the char after the last position of the current function
12599 or script-level element."
12600 (let* ((node (js2-node-at-point))
12601 (parent (or (and (js2-function-node-p node) node)
12602 (js2-node-parent-script-or-fn node)))
12603 script)
12604 (unless (js2-function-node-p parent)
12605 ;; Use current script-level node, or, if none, the next one.
12606 (setq script (or parent node)
12607 parent (js2-node-find-child-before (point) script))
12608 (when (or (null parent)
12609 (>= (point) (+ (js2-node-abs-pos parent)
12610 (js2-node-len parent))))
12611 (setq parent (js2-node-find-child-after (point) script))))
12612 (when parent
12613 (goto-char (+ (js2-node-abs-pos parent)
12614 (js2-node-len parent))))))
12615
12616 (defun js2-mark-defun (&optional allow-extend)
12617 "Put mark at end of this function, point at beginning.
12618 The function marked is the one that contains point.
12619
12620 Interactively, if this command is repeated,
12621 or (in Transient Mark mode) if the mark is active,
12622 it marks the next defun after the ones already marked."
12623 (interactive "p")
12624 (let (extended)
12625 (when (and allow-extend
12626 (or (and (eq last-command this-command) (mark t))
12627 (and transient-mark-mode mark-active)))
12628 (let ((sib (save-excursion
12629 (goto-char (mark))
12630 (if (js2-mode-forward-sibling)
12631 (point)))))
12632 (if sib
12633 (progn
12634 (set-mark sib)
12635 (setq extended t))
12636 ;; no more siblings - try extending to enclosing node
12637 (goto-char (mark t)))))
12638 (when (not extended)
12639 (let ((node (js2-node-at-point (point) t)) ; skip comments
12640 ast fn stmt parent beg end)
12641 (when (js2-ast-root-p node)
12642 (setq ast node
12643 node (or (js2-node-find-child-after (point) node)
12644 (js2-node-find-child-before (point) node))))
12645 ;; only mark whole buffer if we can't find any children
12646 (if (null node)
12647 (setq node ast))
12648 (if (js2-function-node-p node)
12649 (setq parent node)
12650 (setq fn (js2-mode-find-enclosing-fn node)
12651 stmt (if (or (null fn)
12652 (js2-ast-root-p fn))
12653 (js2-mode-find-first-stmt node))
12654 parent (or stmt fn)))
12655 (setq beg (js2-node-abs-pos parent)
12656 end (+ beg (js2-node-len parent)))
12657 (push-mark beg)
12658 (goto-char end)
12659 (exchange-point-and-mark)))))
12660
12661 (defun js2-narrow-to-defun ()
12662 "Narrow to the function enclosing point."
12663 (interactive)
12664 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12665 (fn (if (js2-script-node-p node)
12666 node
12667 (js2-mode-find-enclosing-fn node)))
12668 (beg (js2-node-abs-pos fn)))
12669 (unless (js2-ast-root-p fn)
12670 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12671
12672 (provide 'js2-mode)
12673
12674 ;;; js2-mode.el ends here