]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
2fd0630192c3fc12746970924ad889d651ecc117
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2015 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20150202
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (require 'cl-lib)
89 (require 'imenu)
90 (require 'cc-cmds) ; for `c-fill-paragraph'
91
92 (eval-and-compile
93 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
94 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
95
96 (defvar electric-layout-rules)
97
98 ;;; Externs (variables presumed to be defined by the host system)
99
100 (defvar js2-ecma-262-externs
101 (mapcar 'symbol-name
102 '(Array Boolean Date Error EvalError Function Infinity JSON
103 Math NaN Number Object RangeError ReferenceError RegExp
104 String SyntaxError TypeError URIError
105 decodeURI decodeURIComponent encodeURI
106 encodeURIComponent escape eval isFinite isNaN
107 parseFloat parseInt undefined unescape))
108 "Ecma-262 externs. Included in `js2-externs' by default.")
109
110 (defvar js2-browser-externs
111 (mapcar 'symbol-name
112 '(;; DOM level 1
113 Attr CDATASection CharacterData Comment DOMException
114 DOMImplementation Document DocumentFragment
115 DocumentType Element Entity EntityReference
116 ExceptionCode NamedNodeMap Node NodeList Notation
117 ProcessingInstruction Text
118
119 ;; DOM level 2
120 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
121 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
122 HTMLBodyElement HTMLButtonElement HTMLCollection
123 HTMLDListElement HTMLDirectoryElement HTMLDivElement
124 HTMLDocument HTMLElement HTMLFieldSetElement
125 HTMLFontElement HTMLFormElement HTMLFrameElement
126 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
127 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
128 HTMLImageElement HTMLInputElement HTMLIsIndexElement
129 HTMLLIElement HTMLLabelElement HTMLLegendElement
130 HTMLLinkElement HTMLMapElement HTMLMenuElement
131 HTMLMetaElement HTMLModElement HTMLOListElement
132 HTMLObjectElement HTMLOptGroupElement
133 HTMLOptionElement HTMLOptionsCollection
134 HTMLParagraphElement HTMLParamElement HTMLPreElement
135 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
136 HTMLStyleElement HTMLTableCaptionElement
137 HTMLTableCellElement HTMLTableColElement
138 HTMLTableElement HTMLTableRowElement
139 HTMLTableSectionElement HTMLTextAreaElement
140 HTMLTitleElement HTMLUListElement
141
142 ;; DOM level 3
143 DOMConfiguration DOMError DOMException
144 DOMImplementationList DOMImplementationSource
145 DOMLocator DOMStringList NameList TypeInfo
146 UserDataHandler
147
148 ;; Window
149 window alert confirm document java navigator prompt screen
150 self top requestAnimationFrame cancelAnimationFrame
151
152 ;; W3C CSS
153 CSSCharsetRule CSSFontFace CSSFontFaceRule
154 CSSImportRule CSSMediaRule CSSPageRule
155 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
156 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
157 CSSValue CSSValueList Counter DOMImplementationCSS
158 DocumentCSS DocumentStyle ElementCSSInlineStyle
159 LinkStyle MediaList RGBColor Rect StyleSheet
160 StyleSheetList ViewCSS
161
162 ;; W3C Event
163 EventListener EventTarget Event DocumentEvent UIEvent
164 MouseEvent MutationEvent KeyboardEvent
165
166 ;; W3C Range
167 DocumentRange Range RangeException
168
169 ;; W3C XML
170 XPathResult XMLHttpRequest
171
172 ;; console object. Provided by at least Chrome and Firefox.
173 console))
174 "Browser externs.
175 You can cause these to be included or excluded with the custom
176 variable `js2-include-browser-externs'.")
177
178 (defvar js2-rhino-externs
179 (mapcar 'symbol-name
180 '(Packages importClass importPackage com org java
181 ;; Global object (shell) externs.
182 defineClass deserialize doctest gc help load
183 loadClass print quit readFile readUrl runCommand seal
184 serialize spawn sync toint32 version))
185 "Mozilla Rhino externs.
186 Set `js2-include-rhino-externs' to t to include them.")
187
188 (defvar js2-node-externs
189 (mapcar 'symbol-name
190 '(__dirname __filename Buffer clearInterval clearTimeout require
191 console exports global module process setInterval setTimeout))
192 "Node.js externs.
193 Set `js2-include-node-externs' to t to include them.")
194
195 (defvar js2-typed-array-externs
196 (mapcar 'symbol-name
197 '(ArrayBuffer Uint8ClampedArray DataView
198 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
199 Float32Array Float64Array))
200 "Khronos typed array externs. Available in most modern browsers and
201 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
202 are enabled, these will also be included.")
203
204 (defvar js2-harmony-externs
205 (mapcar 'symbol-name
206 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
207 "ES6 externs. If `js2-include-browser-externs' is enabled and
208 `js2-language-version' is sufficiently high, these will be included.")
209
210 ;;; Variables
211
212 (defun js2-mark-safe-local (name pred)
213 "Make the variable NAME buffer-local and mark it as safe file-local
214 variable with predicate PRED."
215 (make-variable-buffer-local name)
216 (put name 'safe-local-variable pred))
217
218 (defcustom js2-highlight-level 2
219 "Amount of syntax highlighting to perform.
220 0 or a negative value means none.
221 1 adds basic syntax highlighting.
222 2 adds highlighting of some Ecma built-in properties.
223 3 adds highlighting of many Ecma built-in functions."
224 :group 'js2-mode
225 :type '(choice (const :tag "None" 0)
226 (const :tag "Basic" 1)
227 (const :tag "Include Properties" 2)
228 (const :tag "Include Functions" 3)))
229
230 (defvar js2-mode-dev-mode-p nil
231 "Non-nil if running in development mode. Normally nil.")
232
233 (defgroup js2-mode nil
234 "An improved JavaScript mode."
235 :group 'languages)
236
237 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
238 (numberp c-basic-offset))
239 c-basic-offset
240 4)
241 "Number of spaces to indent nested statements.
242 Similar to `c-basic-offset'."
243 :group 'js2-mode
244 :type 'integer)
245 (js2-mark-safe-local 'js2-basic-offset 'integerp)
246
247 (defcustom js2-bounce-indent-p nil
248 "Non-nil to have indent-line function choose among alternatives.
249 If nil, the indent-line function will indent to a predetermined column
250 based on heuristic guessing. If non-nil, then if the current line is
251 already indented to that predetermined column, indenting will choose
252 another likely column and indent to that spot. Repeated invocation of
253 the indent-line function will cycle among the computed alternatives.
254 See the function `js2-bounce-indent' for details. When it is non-nil,
255 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
256 :type 'boolean
257 :group 'js2-mode)
258
259 (defcustom js2-pretty-multiline-declarations t
260 "Non-nil to line up multiline declarations vertically:
261
262 var a = 10,
263 b = 20,
264 c = 30;
265
266 If the value is not `all', and the first assigned value in
267 declaration is a function/array/object literal spanning several
268 lines, it won't be indented additionally:
269
270 var o = { var bar = 2,
271 foo: 3 vs. o = {
272 }, foo: 3
273 bar = 2; };"
274 :group 'js2-mode
275 :type 'symbol)
276 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
277
278 (defcustom js2-indent-switch-body nil
279 "When nil, case labels are indented on the same level as the
280 containing switch statement. Otherwise, all lines inside
281 switch statement body are indented one additional level."
282 :type 'boolean
283 :group 'js2-mode)
284 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
285
286 (defcustom js2-idle-timer-delay 0.2
287 "Delay in secs before re-parsing after user makes changes.
288 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
289 :type 'number
290 :group 'js2-mode)
291 (make-variable-buffer-local 'js2-idle-timer-delay)
292
293 (defcustom js2-dynamic-idle-timer-adjust 0
294 "Positive to adjust `js2-idle-timer-delay' based on file size.
295 The idea is that for short files, parsing is faster so we can be
296 more responsive to user edits without interfering with editing.
297 The buffer length in characters (typically bytes) is divided by
298 this value and used to multiply `js2-idle-timer-delay' for the
299 buffer. For example, a 21k file and 10k adjust yields 21k/10k
300 == 2, so js2-idle-timer-delay is multiplied by 2.
301 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
302 `js2-idle-timer-delay' is not dependent on the file size."
303 :type 'number
304 :group 'js2-mode)
305
306 (defcustom js2-concat-multiline-strings t
307 "When non-nil, `js2-line-break' in mid-string will make it a
308 string concatenation. When `eol', the '+' will be inserted at the
309 end of the line, otherwise, at the beginning of the next line."
310 :type '(choice (const t) (const eol) (const nil))
311 :group 'js2-mode)
312
313 (defcustom js2-mode-show-parse-errors t
314 "True to highlight parse errors."
315 :type 'boolean
316 :group 'js2-mode)
317
318 (defcustom js2-mode-show-strict-warnings t
319 "Non-nil to emit Ecma strict-mode warnings.
320 Some of the warnings can be individually disabled by other flags,
321 even if this flag is non-nil."
322 :type 'boolean
323 :group 'js2-mode)
324
325 (defcustom js2-strict-trailing-comma-warning t
326 "Non-nil to warn about trailing commas in array literals.
327 Ecma-262-5.1 allows them, but older versions of IE raise an error."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-strict-missing-semi-warning t
332 "Non-nil to warn about semicolon auto-insertion after statement.
333 Technically this is legal per Ecma-262, but some style guides disallow
334 depending on it."
335 :type 'boolean
336 :group 'js2-mode)
337
338 (defcustom js2-missing-semi-one-line-override nil
339 "Non-nil to permit missing semicolons in one-line functions.
340 In one-liner functions such as `function identity(x) {return x}'
341 people often omit the semicolon for a cleaner look. If you are
342 such a person, you can suppress the missing-semicolon warning
343 by setting this variable to t."
344 :type 'boolean
345 :group 'js2-mode)
346
347 (defcustom js2-strict-inconsistent-return-warning t
348 "Non-nil to warn about mixing returns with value-returns.
349 It's perfectly legal to have a `return' and a `return foo' in the
350 same function, but it's often an indicator of a bug, and it also
351 interferes with type inference (in systems that support it.)"
352 :type 'boolean
353 :group 'js2-mode)
354
355 (defcustom js2-strict-cond-assign-warning t
356 "Non-nil to warn about expressions like if (a = b).
357 This often should have been '==' instead of '='. If the warning
358 is enabled, you can suppress it on a per-expression basis by
359 parenthesizing the expression, e.g. if ((a = b)) ..."
360 :type 'boolean
361 :group 'js2-mode)
362
363 (defcustom js2-strict-var-redeclaration-warning t
364 "Non-nil to warn about redeclaring variables in a script or function."
365 :type 'boolean
366 :group 'js2-mode)
367
368 (defcustom js2-strict-var-hides-function-arg-warning t
369 "Non-nil to warn about a var decl hiding a function argument."
370 :type 'boolean
371 :group 'js2-mode)
372
373 (defcustom js2-skip-preprocessor-directives nil
374 "Non-nil to treat lines beginning with # as comments.
375 Useful for viewing Mozilla JavaScript source code."
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-language-version 200
380 "Configures what JavaScript language version to recognize.
381 Currently versions 150, 160, 170, 180 and 200 are supported,
382 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
383 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
384 yield, and Array comprehensions, and 1.8 adds function closures."
385 :type 'integer
386 :group 'js2-mode)
387
388 (defcustom js2-instanceof-has-side-effects nil
389 "If non-nil, treats the instanceof operator as having side effects.
390 This is useful for xulrunner apps."
391 :type 'boolean
392 :group 'js2-mode)
393
394 (defcustom js2-move-point-on-right-click t
395 "Non-nil to move insertion point when you right-click.
396 This makes right-click context menu behavior a bit more intuitive,
397 since menu operations generally apply to the point. The exception
398 is if there is a region selection, in which case the point does -not-
399 move, so cut/copy/paste can work properly.
400
401 Note that IntelliJ moves the point, and Eclipse leaves it alone,
402 so this behavior is customizable."
403 :group 'js2-mode
404 :type 'boolean)
405
406 (defcustom js2-allow-rhino-new-expr-initializer t
407 "Non-nil to support a Rhino's experimental syntactic construct.
408
409 Rhino supports the ability to follow a `new' expression with an object
410 literal, which is used to set additional properties on the new object
411 after calling its constructor. Syntax:
412
413 new <expr> [ ( arglist ) ] [initializer]
414
415 Hence, this expression:
416
417 new Object {a: 1, b: 2}
418
419 results in an Object with properties a=1 and b=2. This syntax is
420 apparently not configurable in Rhino - it's currently always enabled,
421 as of Rhino version 1.7R2."
422 :type 'boolean
423 :group 'js2-mode)
424
425 (defcustom js2-allow-member-expr-as-function-name nil
426 "Non-nil to support experimental Rhino syntax for function names.
427
428 Rhino supports an experimental syntax configured via the Rhino Context
429 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
430
431 function <member-expr> ( [ arg-list ] ) { <body> }
432
433 Where member-expr is a non-parenthesized 'member expression', which
434 is anything at the grammar level of a new-expression or lower, meaning
435 any expression that does not involve infix or unary operators.
436
437 When <member-expr> is not a simple identifier, then it is syntactic
438 sugar for assigning the anonymous function to the <member-expr>. Hence,
439 this code:
440
441 function a.b().c[2] (x, y) { ... }
442
443 is rewritten as:
444
445 a.b().c[2] = function(x, y) {...}
446
447 which doesn't seem particularly useful, but Rhino permits it."
448 :type 'boolean
449 :group 'js2-mode)
450
451 ;; scanner variables
452
453 (defmacro js2-deflocal (name value &optional comment)
454 "Define a buffer-local variable NAME with VALUE and COMMENT."
455 (declare (debug defvar) (doc-string 3))
456 `(progn
457 (defvar ,name ,value ,comment)
458 (make-variable-buffer-local ',name)))
459
460 (defvar js2-EOF_CHAR -1
461 "Represents end of stream. Distinct from js2-EOF token type.")
462
463 ;; I originally used symbols to represent tokens, but Rhino uses
464 ;; ints and then sets various flag bits in them, so ints it is.
465 ;; The upshot is that we need a `js2-' prefix in front of each name.
466 (defvar js2-ERROR -1)
467 (defvar js2-EOF 0)
468 (defvar js2-EOL 1)
469 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
470 (defvar js2-LEAVEWITH 3)
471 (defvar js2-RETURN 4)
472 (defvar js2-GOTO 5)
473 (defvar js2-IFEQ 6)
474 (defvar js2-IFNE 7)
475 (defvar js2-SETNAME 8)
476 (defvar js2-BITOR 9)
477 (defvar js2-BITXOR 10)
478 (defvar js2-BITAND 11)
479 (defvar js2-EQ 12)
480 (defvar js2-NE 13)
481 (defvar js2-LT 14)
482 (defvar js2-LE 15)
483 (defvar js2-GT 16)
484 (defvar js2-GE 17)
485 (defvar js2-LSH 18)
486 (defvar js2-RSH 19)
487 (defvar js2-URSH 20)
488 (defvar js2-ADD 21) ; infix plus
489 (defvar js2-SUB 22) ; infix minus
490 (defvar js2-MUL 23)
491 (defvar js2-DIV 24)
492 (defvar js2-MOD 25)
493 (defvar js2-NOT 26)
494 (defvar js2-BITNOT 27)
495 (defvar js2-POS 28) ; unary plus
496 (defvar js2-NEG 29) ; unary minus
497 (defvar js2-NEW 30)
498 (defvar js2-DELPROP 31)
499 (defvar js2-TYPEOF 32)
500 (defvar js2-GETPROP 33)
501 (defvar js2-GETPROPNOWARN 34)
502 (defvar js2-SETPROP 35)
503 (defvar js2-GETELEM 36)
504 (defvar js2-SETELEM 37)
505 (defvar js2-CALL 38)
506 (defvar js2-NAME 39) ; an identifier
507 (defvar js2-NUMBER 40)
508 (defvar js2-STRING 41)
509 (defvar js2-NULL 42)
510 (defvar js2-THIS 43)
511 (defvar js2-FALSE 44)
512 (defvar js2-TRUE 45)
513 (defvar js2-SHEQ 46) ; shallow equality (===)
514 (defvar js2-SHNE 47) ; shallow inequality (!==)
515 (defvar js2-REGEXP 48)
516 (defvar js2-BINDNAME 49)
517 (defvar js2-THROW 50)
518 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
519 (defvar js2-IN 52)
520 (defvar js2-INSTANCEOF 53)
521 (defvar js2-LOCAL_LOAD 54)
522 (defvar js2-GETVAR 55)
523 (defvar js2-SETVAR 56)
524 (defvar js2-CATCH_SCOPE 57)
525 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
526 (defvar js2-ENUM_INIT_VALUES 59)
527 (defvar js2-ENUM_INIT_ARRAY 60)
528 (defvar js2-ENUM_NEXT 61)
529 (defvar js2-ENUM_ID 62)
530 (defvar js2-THISFN 63)
531 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
532 (defvar js2-ARRAYLIT 65) ; array literal
533 (defvar js2-OBJECTLIT 66) ; object literal
534 (defvar js2-GET_REF 67) ; *reference
535 (defvar js2-SET_REF 68) ; *reference = something
536 (defvar js2-DEL_REF 69) ; delete reference
537 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
538 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
539 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
540
541 ;; XML support
542 (defvar js2-DEFAULTNAMESPACE 73)
543 (defvar js2-ESCXMLATTR 74)
544 (defvar js2-ESCXMLTEXT 75)
545 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
546 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
547 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
548 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
549
550 (defvar js2-first-bytecode js2-ENTERWITH)
551 (defvar js2-last-bytecode js2-REF_NS_NAME)
552
553 (defvar js2-TRY 80)
554 (defvar js2-SEMI 81) ; semicolon
555 (defvar js2-LB 82) ; left and right brackets
556 (defvar js2-RB 83)
557 (defvar js2-LC 84) ; left and right curly-braces
558 (defvar js2-RC 85)
559 (defvar js2-LP 86) ; left and right parens
560 (defvar js2-RP 87)
561 (defvar js2-COMMA 88) ; comma operator
562
563 (defvar js2-ASSIGN 89) ; simple assignment (=)
564 (defvar js2-ASSIGN_BITOR 90) ; |=
565 (defvar js2-ASSIGN_BITXOR 91) ; ^=
566 (defvar js2-ASSIGN_BITAND 92) ; &=
567 (defvar js2-ASSIGN_LSH 93) ; <<=
568 (defvar js2-ASSIGN_RSH 94) ; >>=
569 (defvar js2-ASSIGN_URSH 95) ; >>>=
570 (defvar js2-ASSIGN_ADD 96) ; +=
571 (defvar js2-ASSIGN_SUB 97) ; -=
572 (defvar js2-ASSIGN_MUL 98) ; *=
573 (defvar js2-ASSIGN_DIV 99) ; /=
574 (defvar js2-ASSIGN_MOD 100) ; %=
575
576 (defvar js2-first-assign js2-ASSIGN)
577 (defvar js2-last-assign js2-ASSIGN_MOD)
578
579 (defvar js2-HOOK 101) ; conditional (?:)
580 (defvar js2-COLON 102)
581 (defvar js2-OR 103) ; logical or (||)
582 (defvar js2-AND 104) ; logical and (&&)
583 (defvar js2-INC 105) ; increment/decrement (++ --)
584 (defvar js2-DEC 106)
585 (defvar js2-DOT 107) ; member operator (.)
586 (defvar js2-FUNCTION 108) ; function keyword
587 (defvar js2-EXPORT 109) ; export keyword
588 (defvar js2-IMPORT 110) ; import keyword
589 (defvar js2-IF 111) ; if keyword
590 (defvar js2-ELSE 112) ; else keyword
591 (defvar js2-SWITCH 113) ; switch keyword
592 (defvar js2-CASE 114) ; case keyword
593 (defvar js2-DEFAULT 115) ; default keyword
594 (defvar js2-WHILE 116) ; while keyword
595 (defvar js2-DO 117) ; do keyword
596 (defvar js2-FOR 118) ; for keyword
597 (defvar js2-BREAK 119) ; break keyword
598 (defvar js2-CONTINUE 120) ; continue keyword
599 (defvar js2-VAR 121) ; var keyword
600 (defvar js2-WITH 122) ; with keyword
601 (defvar js2-CATCH 123) ; catch keyword
602 (defvar js2-FINALLY 124) ; finally keyword
603 (defvar js2-VOID 125) ; void keyword
604 (defvar js2-RESERVED 126) ; reserved keywords
605
606 (defvar js2-EMPTY 127)
607
608 ;; Types used for the parse tree - never returned by scanner.
609
610 (defvar js2-BLOCK 128) ; statement block
611 (defvar js2-LABEL 129) ; label
612 (defvar js2-TARGET 130)
613 (defvar js2-LOOP 131)
614 (defvar js2-EXPR_VOID 132) ; expression statement in functions
615 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
616 (defvar js2-JSR 134)
617 (defvar js2-SCRIPT 135) ; top-level node for entire script
618 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
619 (defvar js2-USE_STACK 137)
620 (defvar js2-SETPROP_OP 138) ; x.y op= something
621 (defvar js2-SETELEM_OP 139) ; x[y] op= something
622 (defvar js2-LOCAL_BLOCK 140)
623 (defvar js2-SET_REF_OP 141) ; *reference op= something
624
625 ;; For XML support:
626 (defvar js2-DOTDOT 142) ; member operator (..)
627 (defvar js2-COLONCOLON 143) ; namespace::name
628 (defvar js2-XML 144) ; XML type
629 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
630 (defvar js2-XMLATTR 146) ; @
631 (defvar js2-XMLEND 147)
632
633 ;; Optimizer-only tokens
634 (defvar js2-TO_OBJECT 148)
635 (defvar js2-TO_DOUBLE 149)
636
637 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
638 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
639 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
640 (defvar js2-CONST 153)
641 (defvar js2-SETCONST 154)
642 (defvar js2-SETCONSTVAR 155)
643 (defvar js2-ARRAYCOMP 156)
644 (defvar js2-LETEXPR 157)
645 (defvar js2-WITHEXPR 158)
646 (defvar js2-DEBUGGER 159)
647
648 (defvar js2-COMMENT 160)
649 (defvar js2-TRIPLEDOT 161) ; for rest parameter
650 (defvar js2-ARROW 162) ; function arrow (=>)
651 (defvar js2-CLASS 163)
652 (defvar js2-EXTENDS 164)
653 (defvar js2-STATIC 165)
654 (defvar js2-SUPER 166)
655 (defvar js2-TEMPLATE_HEAD 167) ; part of template literal before substitution
656 (defvar js2-NO_SUBS_TEMPLATE 168) ; template literal without substitutions
657 (defvar js2-TAGGED_TEMPLATE 169) ; tagged template literal
658
659 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
660
661 (defconst js2-debug-print-trees nil)
662
663 ;; Rhino accepts any string or stream as input. Emacs character
664 ;; processing works best in buffers, so we'll assume the input is a
665 ;; buffer. JavaScript strings can be copied into temp buffers before
666 ;; scanning them.
667
668 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
669 ;; They're the Emacs equivalent of instance variables, more or less.
670
671 (js2-deflocal js2-ts-dirty-line nil
672 "Token stream buffer-local variable.
673 Indicates stuff other than whitespace since start of line.")
674
675 (js2-deflocal js2-ts-hit-eof nil
676 "Token stream buffer-local variable.")
677
678 ;; FIXME: Unused.
679 (js2-deflocal js2-ts-line-start 0
680 "Token stream buffer-local variable.")
681
682 (js2-deflocal js2-ts-lineno 1
683 "Token stream buffer-local variable.")
684
685 ;; FIXME: Unused.
686 (js2-deflocal js2-ts-line-end-char -1
687 "Token stream buffer-local variable.")
688
689 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
690 "Token stream buffer-local variable.
691 Current scan position.")
692
693 ;; FIXME: Unused.
694 (js2-deflocal js2-ts-is-xml-attribute nil
695 "Token stream buffer-local variable.")
696
697 (js2-deflocal js2-ts-xml-is-tag-content nil
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-xml-open-tags-count 0
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-string-buffer nil
704 "Token stream buffer-local variable.
705 List of chars built up while scanning various tokens.")
706
707 (cl-defstruct (js2-token
708 (:constructor nil)
709 (:constructor make-js2-token (beg)))
710 "Value returned from the token stream."
711 (type js2-EOF)
712 (beg 1)
713 (end -1)
714 (string "")
715 number
716 regexp-flags
717 comment-type
718 follows-eol-p)
719
720 ;; Have to call `js2-init-scanner' to initialize the values.
721 (js2-deflocal js2-ti-tokens nil)
722 (js2-deflocal js2-ti-tokens-cursor nil)
723 (js2-deflocal js2-ti-lookahead nil)
724
725 (cl-defstruct (js2-ts-state
726 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
727 (cursor js2-ts-cursor)
728 (tokens (copy-sequence js2-ti-tokens))
729 (tokens-cursor js2-ti-tokens-cursor)
730 (lookahead js2-ti-lookahead))))
731 lineno
732 cursor
733 tokens
734 tokens-cursor
735 lookahead)
736
737 ;;; Parser variables
738
739 (js2-deflocal js2-parsed-errors nil
740 "List of errors produced during scanning/parsing.")
741
742 (js2-deflocal js2-parsed-warnings nil
743 "List of warnings produced during scanning/parsing.")
744
745 (js2-deflocal js2-recover-from-parse-errors t
746 "Non-nil to continue parsing after a syntax error.
747
748 In recovery mode, the AST will be built in full, and any error
749 nodes will be flagged with appropriate error information. If
750 this flag is nil, a syntax error will result in an error being
751 signaled.
752
753 The variable is automatically buffer-local, because different
754 modes that use the parser will need different settings.")
755
756 (js2-deflocal js2-parse-hook nil
757 "List of callbacks for receiving parsing progress.")
758
759 (defvar js2-parse-finished-hook nil
760 "List of callbacks to notify when parsing finishes.
761 Not called if parsing was interrupted.")
762
763 (js2-deflocal js2-is-eval-code nil
764 "True if we're evaluating code in a string.
765 If non-nil, the tokenizer will record the token text, and the AST nodes
766 will record their source text. Off by default for IDE modes, since the
767 text is available in the buffer.")
768
769 (defvar js2-parse-ide-mode t
770 "Non-nil if the parser is being used for `js2-mode'.
771 If non-nil, the parser will set text properties for fontification
772 and the syntax table. The value should be nil when using the
773 parser as a frontend to an interpreter or byte compiler.")
774
775 ;;; Parser instance variables (buffer-local vars for js2-parse)
776
777 (defconst js2-ti-after-eol (lsh 1 16)
778 "Flag: first token of the source line.")
779
780 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
781
782 (js2-deflocal js2-compiler-generate-debug-info t)
783 (js2-deflocal js2-compiler-use-dynamic-scope nil)
784 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
785 (js2-deflocal js2-compiler-xml-available t)
786 (js2-deflocal js2-compiler-optimization-level 0)
787 (js2-deflocal js2-compiler-generating-source t)
788 (js2-deflocal js2-compiler-strict-mode nil)
789 (js2-deflocal js2-compiler-report-warning-as-error nil)
790 (js2-deflocal js2-compiler-generate-observer-count nil)
791 (js2-deflocal js2-compiler-activation-names nil)
792
793 ;; SKIP: sourceURI
794
795 ;; There's a compileFunction method in Context.java - may need it.
796 (js2-deflocal js2-called-by-compile-function nil
797 "True if `js2-parse' was called by `js2-compile-function'.
798 Will only be used when we finish implementing the interpreter.")
799
800 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
801
802 ;; SKIP: node factory - we're going to just call functions directly,
803 ;; and eventually go to a unified AST format.
804
805 (js2-deflocal js2-nesting-of-function 0)
806
807 (js2-deflocal js2-recorded-identifiers nil
808 "Tracks identifiers found during parsing.")
809
810 (js2-deflocal js2-is-in-destructuring nil
811 "True while parsing destructuring expression.")
812
813 (defcustom js2-global-externs nil
814 "A list of any extern names you'd like to consider always declared.
815 This list is global and is used by all `js2-mode' files.
816 You can create buffer-local externs list using `js2-additional-externs'.
817
818 There is also a buffer-local variable `js2-default-externs',
819 which is initialized by default to include the Ecma-262 externs
820 and the standard browser externs. The three lists are all
821 checked during highlighting."
822 :type 'list
823 :group 'js2-mode)
824
825 (js2-deflocal js2-default-externs nil
826 "Default external declarations.
827
828 These are currently only used for highlighting undeclared variables,
829 which only worries about top-level (unqualified) references.
830 As js2-mode's processing improves, we will flesh out this list.
831
832 The initial value is set to `js2-ecma-262-externs', unless some
833 of the `js2-include-?-externs' variables are set to t, in which
834 case the browser, Rhino and/or Node.js externs are also included.
835
836 See `js2-additional-externs' for more information.")
837
838 (defcustom js2-include-browser-externs t
839 "Non-nil to include browser externs in the master externs list.
840 If you work on JavaScript files that are not intended for browsers,
841 such as Mozilla Rhino server-side JavaScript, set this to nil.
842 See `js2-additional-externs' for more information about externs."
843 :type 'boolean
844 :group 'js2-mode)
845
846 (defcustom js2-include-rhino-externs nil
847 "Non-nil to include Mozilla Rhino externs in the master externs list.
848 See `js2-additional-externs' for more information about externs."
849 :type 'boolean
850 :group 'js2-mode)
851
852 (defcustom js2-include-node-externs nil
853 "Non-nil to include Node.js externs in the master externs list.
854 See `js2-additional-externs' for more information about externs."
855 :type 'boolean
856 :group 'js2-mode)
857
858 (js2-deflocal js2-additional-externs nil
859 "A buffer-local list of additional external declarations.
860 It is used to decide whether variables are considered undeclared
861 for purposes of highlighting.
862
863 Each entry is a Lisp string. The string should be the fully qualified
864 name of an external entity. All externs should be added to this list,
865 so that as js2-mode's processing improves it can take advantage of them.
866
867 You may want to declare your externs in three ways.
868 First, you can add externs that are valid for all your JavaScript files.
869 You should probably do this by adding them to `js2-global-externs', which
870 is a global list used for all js2-mode files.
871
872 Next, you can add a function to `js2-init-hook' that adds additional
873 externs appropriate for the specific file, perhaps based on its path.
874 These should go in `js2-additional-externs', which is buffer-local.
875
876 Third, you can use JSLint's global declaration, as long as
877 `js2-include-jslint-globals' is non-nil, which see.
878
879 Finally, you can add a function to `js2-post-parse-callbacks',
880 which is called after parsing completes, and `js2-mode-ast' is bound to
881 the root of the parse tree. At this stage you can set up an AST
882 node visitor using `js2-visit-ast' and examine the parse tree
883 for specific import patterns that may imply the existence of
884 other externs, possibly tied to your build system. These should also
885 be added to `js2-additional-externs'.
886
887 Your post-parse callback may of course also use the simpler and
888 faster (but perhaps less robust) approach of simply scanning the
889 buffer text for your imports, using regular expressions.")
890
891 ;; SKIP: decompiler
892 ;; SKIP: encoded-source
893
894 ;;; The following variables are per-function and should be saved/restored
895 ;;; during function parsing...
896
897 (js2-deflocal js2-current-script-or-fn nil)
898 (js2-deflocal js2-current-scope nil)
899 (js2-deflocal js2-nesting-of-with 0)
900 (js2-deflocal js2-label-set nil
901 "An alist mapping label names to nodes.")
902
903 (js2-deflocal js2-loop-set nil)
904 (js2-deflocal js2-loop-and-switch-set nil)
905 (js2-deflocal js2-has-return-value nil)
906 (js2-deflocal js2-end-flags 0)
907
908 ;;; ...end of per function variables
909
910 ;; These flags enumerate the possible ways a statement/function can
911 ;; terminate. These flags are used by endCheck() and by the Parser to
912 ;; detect inconsistent return usage.
913 ;;
914 ;; END_UNREACHED is reserved for code paths that are assumed to always be
915 ;; able to execute (example: throw, continue)
916 ;;
917 ;; END_DROPS_OFF indicates if the statement can transfer control to the
918 ;; next one. Statement such as return dont. A compound statement may have
919 ;; some branch that drops off control to the next statement.
920 ;;
921 ;; END_RETURNS indicates that the statement can return (without arguments)
922 ;; END_RETURNS_VALUE indicates that the statement can return a value.
923 ;;
924 ;; A compound statement such as
925 ;; if (condition) {
926 ;; return value;
927 ;; }
928 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
929
930 (defconst js2-end-unreached #x0)
931 (defconst js2-end-drops-off #x1)
932 (defconst js2-end-returns #x2)
933 (defconst js2-end-returns-value #x4)
934
935 ;; Rhino awkwardly passes a statementLabel parameter to the
936 ;; statementHelper() function, the main statement parser, which
937 ;; is then used by quite a few of the sub-parsers. We just make
938 ;; it a buffer-local variable and make sure it's cleaned up properly.
939 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
940
941 ;; Similarly, Rhino passes an inForInit boolean through about half
942 ;; the expression parsers. We use a dynamically-scoped variable,
943 ;; which makes it easier to funcall the parsers individually without
944 ;; worrying about whether they take the parameter or not.
945 (js2-deflocal js2-in-for-init nil)
946 (js2-deflocal js2-temp-name-counter 0)
947 (js2-deflocal js2-parse-stmt-count 0)
948
949 (defsubst js2-get-next-temp-name ()
950 (format "$%d" (cl-incf js2-temp-name-counter)))
951
952 (defvar js2-parse-interruptable-p t
953 "Set this to nil to force parse to continue until finished.
954 This will mostly be useful for interpreters.")
955
956 (defvar js2-statements-per-pause 50
957 "Pause after this many statements to check for user input.
958 If user input is pending, stop the parse and discard the tree.
959 This makes for a smoother user experience for large files.
960 You may have to wait a second or two before the highlighting
961 and error-reporting appear, but you can always type ahead if
962 you wish. This appears to be more or less how Eclipse, IntelliJ
963 and other editors work.")
964
965 (js2-deflocal js2-record-comments t
966 "Instructs the scanner to record comments in `js2-scanned-comments'.")
967
968 (js2-deflocal js2-scanned-comments nil
969 "List of all comments from the current parse.")
970
971 (defcustom js2-mode-indent-inhibit-undo nil
972 "Non-nil to disable collection of Undo information when indenting lines.
973 Some users have requested this behavior. It's nil by default because
974 other Emacs modes don't work this way."
975 :type 'boolean
976 :group 'js2-mode)
977
978 (defcustom js2-mode-indent-ignore-first-tab nil
979 "If non-nil, ignore first TAB keypress if we look indented properly.
980 It's fairly common for users to navigate to an already-indented line
981 and press TAB for reassurance that it's been indented. For this class
982 of users, we want the first TAB press on a line to be ignored if the
983 line is already indented to one of the precomputed alternatives.
984
985 This behavior is only partly implemented. If you TAB-indent a line,
986 navigate to another line, and then navigate back, it fails to clear
987 the last-indented variable, so it thinks you've already hit TAB once,
988 and performs the indent. A full solution would involve getting on the
989 point-motion hooks for the entire buffer. If we come across another
990 use cases that requires watching point motion, I'll consider doing it.
991
992 If you set this variable to nil, then the TAB key will always change
993 the indentation of the current line, if more than one alternative
994 indentation spot exists."
995 :type 'boolean
996 :group 'js2-mode)
997
998 (defvar js2-indent-hook nil
999 "A hook for user-defined indentation rules.
1000
1001 Functions on this hook should expect two arguments: (LIST INDEX)
1002 The LIST argument is the list of computed indentation points for
1003 the current line. INDEX is the list index of the indentation point
1004 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1005 indent function is not going to change the current line indentation.
1006
1007 If a hook function on this list returns a non-nil value, then
1008 `js2-bounce-indent' assumes the hook function has performed its own
1009 indentation, and will do nothing. If all hook functions on the list
1010 return nil, then `js2-bounce-indent' will use its computed indentation
1011 and reindent the line.
1012
1013 When hook functions on this hook list are called, the variable
1014 `js2-mode-ast' may or may not be set, depending on whether the
1015 parse tree is available. If the variable is nil, you can pass a
1016 callback to `js2-mode-wait-for-parse', and your callback will be
1017 called after the new parse tree is built. This can take some time
1018 in large files.")
1019
1020 (defface js2-warning
1021 `((((class color) (background light))
1022 (:underline "orange"))
1023 (((class color) (background dark))
1024 (:underline "orange"))
1025 (t (:underline t)))
1026 "Face for JavaScript warnings."
1027 :group 'js2-mode)
1028
1029 (defface js2-error
1030 `((((class color) (background light))
1031 (:foreground "red"))
1032 (((class color) (background dark))
1033 (:foreground "red"))
1034 (t (:foreground "red")))
1035 "Face for JavaScript errors."
1036 :group 'js2-mode)
1037
1038 (defface js2-jsdoc-tag
1039 '((t :foreground "SlateGray"))
1040 "Face used to highlight @whatever tags in jsdoc comments."
1041 :group 'js2-mode)
1042
1043 (defface js2-jsdoc-type
1044 '((t :foreground "SteelBlue"))
1045 "Face used to highlight {FooBar} types in jsdoc comments."
1046 :group 'js2-mode)
1047
1048 (defface js2-jsdoc-value
1049 '((t :foreground "PeachPuff3"))
1050 "Face used to highlight tag values in jsdoc comments."
1051 :group 'js2-mode)
1052
1053 (defface js2-function-param
1054 '((t :foreground "SeaGreen"))
1055 "Face used to highlight function parameters in javascript."
1056 :group 'js2-mode)
1057
1058 (defface js2-function-call
1059 '((t :inherit default))
1060 "Face used to highlight function name in calls."
1061 :group 'js2-mode)
1062
1063 (defface js2-instance-member
1064 '((t :foreground "DarkOrchid"))
1065 "Face used to highlight instance variables in javascript.
1066 Not currently used."
1067 :group 'js2-mode)
1068
1069 (defface js2-private-member
1070 '((t :foreground "PeachPuff3"))
1071 "Face used to highlight calls to private methods in javascript.
1072 Not currently used."
1073 :group 'js2-mode)
1074
1075 (defface js2-private-function-call
1076 '((t :foreground "goldenrod"))
1077 "Face used to highlight calls to private functions in javascript.
1078 Not currently used."
1079 :group 'js2-mode)
1080
1081 (defface js2-jsdoc-html-tag-name
1082 '((((class color) (min-colors 88) (background light))
1083 (:foreground "rosybrown"))
1084 (((class color) (min-colors 8) (background dark))
1085 (:foreground "yellow"))
1086 (((class color) (min-colors 8) (background light))
1087 (:foreground "magenta")))
1088 "Face used to highlight jsdoc html tag names"
1089 :group 'js2-mode)
1090
1091 (defface js2-jsdoc-html-tag-delimiter
1092 '((((class color) (min-colors 88) (background light))
1093 (:foreground "dark khaki"))
1094 (((class color) (min-colors 8) (background dark))
1095 (:foreground "green"))
1096 (((class color) (min-colors 8) (background light))
1097 (:foreground "green")))
1098 "Face used to highlight brackets in jsdoc html tags."
1099 :group 'js2-mode)
1100
1101 (defface js2-external-variable
1102 '((t :foreground "orange"))
1103 "Face used to highlight undeclared variable identifiers.")
1104
1105 (defcustom js2-init-hook nil
1106 "List of functions to be called after `js2-mode' or
1107 `js2-minor-mode' has initialized all variables, before parsing
1108 the buffer for the first time."
1109 :type 'hook
1110 :group 'js2-mode
1111 :version "20130608")
1112
1113 (defcustom js2-post-parse-callbacks nil
1114 "List of callback functions invoked after parsing finishes.
1115 Currently, the main use for this function is to add synthetic
1116 declarations to `js2-recorded-identifiers', which see."
1117 :type 'hook
1118 :group 'js2-mode)
1119
1120 (defcustom js2-build-imenu-callbacks nil
1121 "List of functions called during Imenu index generation.
1122 It's a good place to add additional entries to it, using
1123 `js2-record-imenu-entry'."
1124 :type 'hook
1125 :group 'js2-mode)
1126
1127 (defcustom js2-highlight-external-variables t
1128 "Non-nil to highlight undeclared variable identifiers.
1129 An undeclared variable is any variable not declared with var or let
1130 in the current scope or any lexically enclosing scope. If you use
1131 such a variable, then you are either expecting it to originate from
1132 another file, or you've got a potential bug."
1133 :type 'boolean
1134 :group 'js2-mode)
1135
1136 (defcustom js2-include-jslint-globals t
1137 "Non-nil to include the identifiers from JSLint global
1138 declaration (see http://www.jslint.com/lint.html#global) in the
1139 buffer-local externs list. See `js2-additional-externs' for more
1140 information."
1141 :type 'boolean
1142 :group 'js2-mode)
1143
1144 (defvar js2-mode-map
1145 (let ((map (make-sparse-keymap)))
1146 (define-key map [mouse-1] #'js2-mode-show-node)
1147 (define-key map (kbd "M-j") #'js2-line-break)
1148 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1149 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1150 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1151 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1152 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1153 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1154 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1155 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1156 (when js2-bounce-indent-p
1157 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1158
1159 (define-key map [menu-bar javascript]
1160 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1161
1162 (define-key map [menu-bar javascript customize-js2-mode]
1163 '(menu-item "Customize js2-mode" js2-mode-customize
1164 :help "Customize the behavior of this mode"))
1165
1166 (define-key map [menu-bar javascript js2-force-refresh]
1167 '(menu-item "Force buffer refresh" js2-mode-reset
1168 :help "Re-parse the buffer from scratch"))
1169
1170 (define-key map [menu-bar javascript separator-2]
1171 '("--"))
1172
1173 (define-key map [menu-bar javascript next-error]
1174 '(menu-item "Next warning or error" next-error
1175 :enabled (and js2-mode-ast
1176 (or (js2-ast-root-errors js2-mode-ast)
1177 (js2-ast-root-warnings js2-mode-ast)))
1178 :help "Move to next warning or error"))
1179
1180 (define-key map [menu-bar javascript display-errors]
1181 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1182 :visible (not js2-mode-show-parse-errors)
1183 :help "Turn on display of warnings and errors"))
1184
1185 (define-key map [menu-bar javascript hide-errors]
1186 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1187 :visible js2-mode-show-parse-errors
1188 :help "Turn off display of warnings and errors"))
1189
1190 (define-key map [menu-bar javascript separator-1]
1191 '("--"))
1192
1193 (define-key map [menu-bar javascript js2-toggle-function]
1194 '(menu-item "Show/collapse element" js2-mode-toggle-element
1195 :help "Hide or show function body or comment"))
1196
1197 (define-key map [menu-bar javascript show-comments]
1198 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1199 :visible js2-mode-comments-hidden
1200 :help "Expand all hidden block comments"))
1201
1202 (define-key map [menu-bar javascript hide-comments]
1203 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1204 :visible (not js2-mode-comments-hidden)
1205 :help "Show block comments as /*...*/"))
1206
1207 (define-key map [menu-bar javascript show-all-functions]
1208 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1209 :visible js2-mode-functions-hidden
1210 :help "Expand all hidden function bodies"))
1211
1212 (define-key map [menu-bar javascript hide-all-functions]
1213 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1214 :visible (not js2-mode-functions-hidden)
1215 :help "Show {...} for all top-level function bodies"))
1216
1217 map)
1218 "Keymap used in `js2-mode' buffers.")
1219
1220 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1221
1222 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1223 "Matches a //-comment line. Must be first non-whitespace on line.
1224 First match-group is the leading whitespace.")
1225
1226 (defvar js2-mode-hook nil)
1227
1228 (js2-deflocal js2-mode-ast nil "Private variable.")
1229 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1230 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1231 (js2-deflocal js2-mode-parsing nil "Private variable.")
1232 (js2-deflocal js2-mode-node-overlay nil)
1233
1234 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1235 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1236
1237 (js2-deflocal js2-mode-fontifications nil "Private variable")
1238 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1239 (js2-deflocal js2-imenu-recorder nil "Private variable")
1240 (js2-deflocal js2-imenu-function-map nil "Private variable")
1241
1242 (defvar js2-paragraph-start
1243 "\\(@[[:alpha:]]+\\>\\|$\\)")
1244
1245 ;; Note that we also set a 'c-in-sws text property in html comments,
1246 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1247 (defvar js2-syntactic-ws-start
1248 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1249
1250 (defvar js2-syntactic-ws-end
1251 "\\s \\|[\n\r/]\\|\\s!")
1252
1253 (defvar js2-syntactic-eol
1254 (concat "\\s *\\(/\\*[^*\n\r]*"
1255 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1256 "\\*+/\\s *\\)*"
1257 "\\(//\\|/\\*[^*\n\r]*"
1258 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1259 "\\|\\\\$\\|$\\)")
1260 "Copied from `java-mode'. Needed for some cc-engine functions.")
1261
1262 (defvar js2-comment-prefix-regexp
1263 "//+\\|\\**")
1264
1265 (defvar js2-comment-start-skip
1266 "\\(//+\\|/\\*+\\)\\s *")
1267
1268 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1269 "Non-nil to emit status messages during parsing.")
1270
1271 (defvar js2-mode-functions-hidden nil "Private variable.")
1272 (defvar js2-mode-comments-hidden nil "Private variable.")
1273
1274 (defvar js2-mode-syntax-table
1275 (let ((table (make-syntax-table)))
1276 (c-populate-syntax-table table)
1277 table)
1278 "Syntax table used in `js2-mode' buffers.")
1279
1280 (defvar js2-mode-abbrev-table nil
1281 "Abbrev table in use in `js2-mode' buffers.")
1282 (define-abbrev-table 'js2-mode-abbrev-table ())
1283
1284 (defvar js2-mode-pending-parse-callbacks nil
1285 "List of functions waiting to be notified that parse is finished.")
1286
1287 (defvar js2-mode-last-indented-line -1)
1288
1289 ;;; Localizable error and warning messages
1290
1291 ;; Messages are copied from Rhino's Messages.properties.
1292 ;; Many of the Java-specific messages have been elided.
1293 ;; Add any js2-specific ones at the end, so we can keep
1294 ;; this file synced with changes to Rhino's.
1295
1296 (defvar js2-message-table
1297 (make-hash-table :test 'equal :size 250)
1298 "Contains localized messages for `js2-mode'.")
1299
1300 ;; TODO(stevey): construct this table at compile-time.
1301 (defmacro js2-msg (key &rest strings)
1302 `(puthash ,key (concat ,@strings)
1303 js2-message-table))
1304
1305 (defun js2-get-msg (msg-key)
1306 "Look up a localized message.
1307 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1308 the correct number of ARGS must be provided."
1309 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1310 (args (if (listp msg-key) (cdr msg-key)))
1311 (msg (gethash key js2-message-table)))
1312 (if msg
1313 (apply #'format msg args)
1314 key))) ; default to showing the key
1315
1316 (js2-msg "msg.dup.parms"
1317 "Duplicate parameter name '%s'.")
1318
1319 (js2-msg "msg.too.big.jump"
1320 "Program too complex: jump offset too big.")
1321
1322 (js2-msg "msg.too.big.index"
1323 "Program too complex: internal index exceeds 64K limit.")
1324
1325 (js2-msg "msg.while.compiling.fn"
1326 "Encountered code generation error while compiling function '%s': %s")
1327
1328 (js2-msg "msg.while.compiling.script"
1329 "Encountered code generation error while compiling script: %s")
1330
1331 ;; Context
1332 (js2-msg "msg.ctor.not.found"
1333 "Constructor for '%s' not found.")
1334
1335 (js2-msg "msg.not.ctor"
1336 "'%s' is not a constructor.")
1337
1338 ;; FunctionObject
1339 (js2-msg "msg.varargs.ctor"
1340 "Method or constructor '%s' must be static "
1341 "with the signature (Context cx, Object[] args, "
1342 "Function ctorObj, boolean inNewExpr) "
1343 "to define a variable arguments constructor.")
1344
1345 (js2-msg "msg.varargs.fun"
1346 "Method '%s' must be static with the signature "
1347 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1348 "to define a variable arguments function.")
1349
1350 (js2-msg "msg.incompat.call"
1351 "Method '%s' called on incompatible object.")
1352
1353 (js2-msg "msg.bad.parms"
1354 "Unsupported parameter type '%s' in method '%s'.")
1355
1356 (js2-msg "msg.bad.method.return"
1357 "Unsupported return type '%s' in method '%s'.")
1358
1359 (js2-msg "msg.bad.ctor.return"
1360 "Construction of objects of type '%s' is not supported.")
1361
1362 (js2-msg "msg.no.overload"
1363 "Method '%s' occurs multiple times in class '%s'.")
1364
1365 (js2-msg "msg.method.not.found"
1366 "Method '%s' not found in '%s'.")
1367
1368 ;; IRFactory
1369
1370 (js2-msg "msg.bad.for.in.lhs"
1371 "Invalid left-hand side of for..in loop.")
1372
1373 (js2-msg "msg.mult.index"
1374 "Only one variable allowed in for..in loop.")
1375
1376 (js2-msg "msg.bad.for.in.destruct"
1377 "Left hand side of for..in loop must be an array of "
1378 "length 2 to accept key/value pair.")
1379
1380 (js2-msg "msg.cant.convert"
1381 "Can't convert to type '%s'.")
1382
1383 (js2-msg "msg.bad.assign.left"
1384 "Invalid assignment left-hand side.")
1385
1386 (js2-msg "msg.bad.decr"
1387 "Invalid decerement operand.")
1388
1389 (js2-msg "msg.bad.incr"
1390 "Invalid increment operand.")
1391
1392 (js2-msg "msg.bad.yield"
1393 "yield must be in a function.")
1394
1395 (js2-msg "msg.yield.parenthesized"
1396 "yield expression must be parenthesized.")
1397
1398 ;; NativeGlobal
1399 (js2-msg "msg.cant.call.indirect"
1400 "Function '%s' must be called directly, and not by way of a "
1401 "function of another name.")
1402
1403 (js2-msg "msg.eval.nonstring"
1404 "Calling eval() with anything other than a primitive "
1405 "string value will simply return the value. "
1406 "Is this what you intended?")
1407
1408 (js2-msg "msg.eval.nonstring.strict"
1409 "Calling eval() with anything other than a primitive "
1410 "string value is not allowed in strict mode.")
1411
1412 (js2-msg "msg.bad.destruct.op"
1413 "Invalid destructuring assignment operator")
1414
1415 ;; NativeCall
1416 (js2-msg "msg.only.from.new"
1417 "'%s' may only be invoked from a `new' expression.")
1418
1419 (js2-msg "msg.deprec.ctor"
1420 "The '%s' constructor is deprecated.")
1421
1422 ;; NativeFunction
1423 (js2-msg "msg.no.function.ref.found"
1424 "no source found to decompile function reference %s")
1425
1426 (js2-msg "msg.arg.isnt.array"
1427 "second argument to Function.prototype.apply must be an array")
1428
1429 ;; NativeGlobal
1430 (js2-msg "msg.bad.esc.mask"
1431 "invalid string escape mask")
1432
1433 ;; NativeRegExp
1434 (js2-msg "msg.bad.quant"
1435 "Invalid quantifier %s")
1436
1437 (js2-msg "msg.overlarge.backref"
1438 "Overly large back reference %s")
1439
1440 (js2-msg "msg.overlarge.min"
1441 "Overly large minimum %s")
1442
1443 (js2-msg "msg.overlarge.max"
1444 "Overly large maximum %s")
1445
1446 (js2-msg "msg.zero.quant"
1447 "Zero quantifier %s")
1448
1449 (js2-msg "msg.max.lt.min"
1450 "Maximum %s less than minimum")
1451
1452 (js2-msg "msg.unterm.quant"
1453 "Unterminated quantifier %s")
1454
1455 (js2-msg "msg.unterm.paren"
1456 "Unterminated parenthetical %s")
1457
1458 (js2-msg "msg.unterm.class"
1459 "Unterminated character class %s")
1460
1461 (js2-msg "msg.bad.range"
1462 "Invalid range in character class.")
1463
1464 (js2-msg "msg.trail.backslash"
1465 "Trailing \\ in regular expression.")
1466
1467 (js2-msg "msg.re.unmatched.right.paren"
1468 "unmatched ) in regular expression.")
1469
1470 (js2-msg "msg.no.regexp"
1471 "Regular expressions are not available.")
1472
1473 (js2-msg "msg.bad.backref"
1474 "back-reference exceeds number of capturing parentheses.")
1475
1476 (js2-msg "msg.bad.regexp.compile"
1477 "Only one argument may be specified if the first "
1478 "argument to RegExp.prototype.compile is a RegExp object.")
1479
1480 ;; Parser
1481 (js2-msg "msg.got.syntax.errors"
1482 "Compilation produced %s syntax errors.")
1483
1484 (js2-msg "msg.var.redecl"
1485 "TypeError: redeclaration of var %s.")
1486
1487 (js2-msg "msg.const.redecl"
1488 "TypeError: redeclaration of const %s.")
1489
1490 (js2-msg "msg.let.redecl"
1491 "TypeError: redeclaration of variable %s.")
1492
1493 (js2-msg "msg.parm.redecl"
1494 "TypeError: redeclaration of formal parameter %s.")
1495
1496 (js2-msg "msg.fn.redecl"
1497 "TypeError: redeclaration of function %s.")
1498
1499 (js2-msg "msg.let.decl.not.in.block"
1500 "SyntaxError: let declaration not directly within block")
1501
1502 (js2-msg "msg.mod.import.decl.at.top.level"
1503 "SyntaxError: import declarations may only appear at the top level")
1504
1505 (js2-msg "msg.mod.as.after.reserved.word"
1506 "SyntaxError: missing keyword 'as' after reserved word %s")
1507
1508 (js2-msg "msg.mod.rc.after.import.spec.list"
1509 "SyntaxError: missing '}' after module specifier list")
1510
1511 (js2-msg "msg.mod.from.after.import.spec.set"
1512 "SyntaxError: missing keyword 'from' after import specifier set")
1513
1514 (js2-msg "msg.mod.declaration.after.import"
1515 "SyntaxError: missing declaration after 'import' keyword")
1516
1517 (js2-msg "msg.mod.spec.after.from"
1518 "SyntaxError: missing module specifier after 'from' keyword")
1519
1520 (js2-msg "msg.mod.export.decl.at.top.level"
1521 "SyntaxError: export declarations may only appear at top level")
1522
1523 (js2-msg "msg.mod.rc.after.export.spec.list"
1524 "SyntaxError: missing '}' after export specifier list")
1525
1526 ;; NodeTransformer
1527 (js2-msg "msg.dup.label"
1528 "duplicated label")
1529
1530 (js2-msg "msg.undef.label"
1531 "undefined label")
1532
1533 (js2-msg "msg.bad.break"
1534 "unlabelled break must be inside loop or switch")
1535
1536 (js2-msg "msg.continue.outside"
1537 "continue must be inside loop")
1538
1539 (js2-msg "msg.continue.nonloop"
1540 "continue can only use labels of iteration statements")
1541
1542 (js2-msg "msg.bad.throw.eol"
1543 "Line terminator is not allowed between the throw "
1544 "keyword and throw expression.")
1545
1546 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1547 "function statement requires a name")
1548
1549 (js2-msg "msg.no.paren.parms"
1550 "missing ( before function parameters.")
1551
1552 (js2-msg "msg.no.parm"
1553 "missing formal parameter")
1554
1555 (js2-msg "msg.no.paren.after.parms"
1556 "missing ) after formal parameters")
1557
1558 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1559 "parameter without default follows parameter with default")
1560
1561 (js2-msg "msg.param.after.rest" ; added by js2-mode
1562 "parameter after rest parameter")
1563
1564 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1565 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1566
1567 (js2-msg "msg.no.brace.body"
1568 "missing '{' before function body")
1569
1570 (js2-msg "msg.no.brace.after.body"
1571 "missing } after function body")
1572
1573 (js2-msg "msg.no.paren.cond"
1574 "missing ( before condition")
1575
1576 (js2-msg "msg.no.paren.after.cond"
1577 "missing ) after condition")
1578
1579 (js2-msg "msg.no.semi.stmt"
1580 "missing ; before statement")
1581
1582 (js2-msg "msg.missing.semi"
1583 "missing ; after statement")
1584
1585 (js2-msg "msg.no.name.after.dot"
1586 "missing name after . operator")
1587
1588 (js2-msg "msg.no.name.after.coloncolon"
1589 "missing name after :: operator")
1590
1591 (js2-msg "msg.no.name.after.dotdot"
1592 "missing name after .. operator")
1593
1594 (js2-msg "msg.no.name.after.xmlAttr"
1595 "missing name after .@")
1596
1597 (js2-msg "msg.no.bracket.index"
1598 "missing ] in index expression")
1599
1600 (js2-msg "msg.no.paren.switch"
1601 "missing ( before switch expression")
1602
1603 (js2-msg "msg.no.paren.after.switch"
1604 "missing ) after switch expression")
1605
1606 (js2-msg "msg.no.brace.switch"
1607 "missing '{' before switch body")
1608
1609 (js2-msg "msg.bad.switch"
1610 "invalid switch statement")
1611
1612 (js2-msg "msg.no.colon.case"
1613 "missing : after case expression")
1614
1615 (js2-msg "msg.double.switch.default"
1616 "double default label in the switch statement")
1617
1618 (js2-msg "msg.no.while.do"
1619 "missing while after do-loop body")
1620
1621 (js2-msg "msg.no.paren.for"
1622 "missing ( after for")
1623
1624 (js2-msg "msg.no.semi.for"
1625 "missing ; after for-loop initializer")
1626
1627 (js2-msg "msg.no.semi.for.cond"
1628 "missing ; after for-loop condition")
1629
1630 (js2-msg "msg.in.after.for.name"
1631 "missing in or of after for")
1632
1633 (js2-msg "msg.no.paren.for.ctrl"
1634 "missing ) after for-loop control")
1635
1636 (js2-msg "msg.no.paren.with"
1637 "missing ( before with-statement object")
1638
1639 (js2-msg "msg.no.paren.after.with"
1640 "missing ) after with-statement object")
1641
1642 (js2-msg "msg.no.paren.after.let"
1643 "missing ( after let")
1644
1645 (js2-msg "msg.no.paren.let"
1646 "missing ) after variable list")
1647
1648 (js2-msg "msg.no.curly.let"
1649 "missing } after let statement")
1650
1651 (js2-msg "msg.bad.return"
1652 "invalid return")
1653
1654 (js2-msg "msg.no.brace.block"
1655 "missing } in compound statement")
1656
1657 (js2-msg "msg.bad.label"
1658 "invalid label")
1659
1660 (js2-msg "msg.bad.var"
1661 "missing variable name")
1662
1663 (js2-msg "msg.bad.var.init"
1664 "invalid variable initialization")
1665
1666 (js2-msg "msg.no.colon.cond"
1667 "missing : in conditional expression")
1668
1669 (js2-msg "msg.no.paren.arg"
1670 "missing ) after argument list")
1671
1672 (js2-msg "msg.no.bracket.arg"
1673 "missing ] after element list")
1674
1675 (js2-msg "msg.bad.prop"
1676 "invalid property id")
1677
1678 (js2-msg "msg.no.colon.prop"
1679 "missing : after property id")
1680
1681 (js2-msg "msg.no.brace.prop"
1682 "missing } after property list")
1683
1684 (js2-msg "msg.no.paren"
1685 "missing ) in parenthetical")
1686
1687 (js2-msg "msg.reserved.id"
1688 "'%s' is a reserved identifier")
1689
1690 (js2-msg "msg.no.paren.catch"
1691 "missing ( before catch-block condition")
1692
1693 (js2-msg "msg.bad.catchcond"
1694 "invalid catch block condition")
1695
1696 (js2-msg "msg.catch.unreachable"
1697 "any catch clauses following an unqualified catch are unreachable")
1698
1699 (js2-msg "msg.no.brace.try"
1700 "missing '{' before try block")
1701
1702 (js2-msg "msg.no.brace.catchblock"
1703 "missing '{' before catch-block body")
1704
1705 (js2-msg "msg.try.no.catchfinally"
1706 "'try' without 'catch' or 'finally'")
1707
1708 (js2-msg "msg.no.return.value"
1709 "function %s does not always return a value")
1710
1711 (js2-msg "msg.anon.no.return.value"
1712 "anonymous function does not always return a value")
1713
1714 (js2-msg "msg.return.inconsistent"
1715 "return statement is inconsistent with previous usage")
1716
1717 (js2-msg "msg.generator.returns"
1718 "TypeError: legacy generator function '%s' returns a value")
1719
1720 (js2-msg "msg.anon.generator.returns"
1721 "TypeError: anonymous legacy generator function returns a value")
1722
1723 (js2-msg "msg.syntax"
1724 "syntax error")
1725
1726 (js2-msg "msg.unexpected.eof"
1727 "Unexpected end of file")
1728
1729 (js2-msg "msg.XML.bad.form"
1730 "illegally formed XML syntax")
1731
1732 (js2-msg "msg.XML.not.available"
1733 "XML runtime not available")
1734
1735 (js2-msg "msg.too.deep.parser.recursion"
1736 "Too deep recursion while parsing")
1737
1738 (js2-msg "msg.no.side.effects"
1739 "Code has no side effects")
1740
1741 (js2-msg "msg.extra.trailing.comma"
1742 "Trailing comma is not supported in some browsers")
1743
1744 (js2-msg "msg.array.trailing.comma"
1745 "Trailing comma yields different behavior across browsers")
1746
1747 (js2-msg "msg.equal.as.assign"
1748 (concat "Test for equality (==) mistyped as assignment (=)?"
1749 " (parenthesize to suppress warning)"))
1750
1751 (js2-msg "msg.var.hides.arg"
1752 "Variable %s hides argument")
1753
1754 (js2-msg "msg.destruct.assign.no.init"
1755 "Missing = in destructuring declaration")
1756
1757 ;; ScriptRuntime
1758 (js2-msg "msg.no.properties"
1759 "%s has no properties.")
1760
1761 (js2-msg "msg.invalid.iterator"
1762 "Invalid iterator value")
1763
1764 (js2-msg "msg.iterator.primitive"
1765 "__iterator__ returned a primitive value")
1766
1767 (js2-msg "msg.assn.create.strict"
1768 "Assignment to undeclared variable %s")
1769
1770 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1771 "Undeclared variable or function '%s'")
1772
1773 (js2-msg "msg.ref.undefined.prop"
1774 "Reference to undefined property '%s'")
1775
1776 (js2-msg "msg.prop.not.found"
1777 "Property %s not found.")
1778
1779 (js2-msg "msg.invalid.type"
1780 "Invalid JavaScript value of type %s")
1781
1782 (js2-msg "msg.primitive.expected"
1783 "Primitive type expected (had %s instead)")
1784
1785 (js2-msg "msg.namespace.expected"
1786 "Namespace object expected to left of :: (found %s instead)")
1787
1788 (js2-msg "msg.null.to.object"
1789 "Cannot convert null to an object.")
1790
1791 (js2-msg "msg.undef.to.object"
1792 "Cannot convert undefined to an object.")
1793
1794 (js2-msg "msg.cyclic.value"
1795 "Cyclic %s value not allowed.")
1796
1797 (js2-msg "msg.is.not.defined"
1798 "'%s' is not defined.")
1799
1800 (js2-msg "msg.undef.prop.read"
1801 "Cannot read property '%s' from %s")
1802
1803 (js2-msg "msg.undef.prop.write"
1804 "Cannot set property '%s' of %s to '%s'")
1805
1806 (js2-msg "msg.undef.prop.delete"
1807 "Cannot delete property '%s' of %s")
1808
1809 (js2-msg "msg.undef.method.call"
1810 "Cannot call method '%s' of %s")
1811
1812 (js2-msg "msg.undef.with"
1813 "Cannot apply 'with' to %s")
1814
1815 (js2-msg "msg.isnt.function"
1816 "%s is not a function, it is %s.")
1817
1818 (js2-msg "msg.isnt.function.in"
1819 "Cannot call property %s in object %s. "
1820 "It is not a function, it is '%s'.")
1821
1822 (js2-msg "msg.function.not.found"
1823 "Cannot find function %s.")
1824
1825 (js2-msg "msg.function.not.found.in"
1826 "Cannot find function %s in object %s.")
1827
1828 (js2-msg "msg.isnt.xml.object"
1829 "%s is not an xml object.")
1830
1831 (js2-msg "msg.no.ref.to.get"
1832 "%s is not a reference to read reference value.")
1833
1834 (js2-msg "msg.no.ref.to.set"
1835 "%s is not a reference to set reference value to %s.")
1836
1837 (js2-msg "msg.no.ref.from.function"
1838 "Function %s can not be used as the left-hand "
1839 "side of assignment or as an operand of ++ or -- operator.")
1840
1841 (js2-msg "msg.bad.default.value"
1842 "Object's getDefaultValue() method returned an object.")
1843
1844 (js2-msg "msg.instanceof.not.object"
1845 "Can't use instanceof on a non-object.")
1846
1847 (js2-msg "msg.instanceof.bad.prototype"
1848 "'prototype' property of %s is not an object.")
1849
1850 (js2-msg "msg.bad.radix"
1851 "illegal radix %s.")
1852
1853 ;; ScriptableObject
1854 (js2-msg "msg.default.value"
1855 "Cannot find default value for object.")
1856
1857 (js2-msg "msg.zero.arg.ctor"
1858 "Cannot load class '%s' which has no zero-parameter constructor.")
1859
1860 (js2-msg "msg.ctor.multiple.parms"
1861 "Can't define constructor or class %s since more than "
1862 "one constructor has multiple parameters.")
1863
1864 (js2-msg "msg.extend.scriptable"
1865 "%s must extend ScriptableObject in order to define property %s.")
1866
1867 (js2-msg "msg.bad.getter.parms"
1868 "In order to define a property, getter %s must have zero "
1869 "parameters or a single ScriptableObject parameter.")
1870
1871 (js2-msg "msg.obj.getter.parms"
1872 "Expected static or delegated getter %s to take "
1873 "a ScriptableObject parameter.")
1874
1875 (js2-msg "msg.getter.static"
1876 "Getter and setter must both be static or neither be static.")
1877
1878 (js2-msg "msg.setter.return"
1879 "Setter must have void return type: %s")
1880
1881 (js2-msg "msg.setter2.parms"
1882 "Two-parameter setter must take a ScriptableObject as "
1883 "its first parameter.")
1884
1885 (js2-msg "msg.setter1.parms"
1886 "Expected single parameter setter for %s")
1887
1888 (js2-msg "msg.setter2.expected"
1889 "Expected static or delegated setter %s to take two parameters.")
1890
1891 (js2-msg "msg.setter.parms"
1892 "Expected either one or two parameters for setter.")
1893
1894 (js2-msg "msg.setter.bad.type"
1895 "Unsupported parameter type '%s' in setter '%s'.")
1896
1897 (js2-msg "msg.add.sealed"
1898 "Cannot add a property to a sealed object: %s.")
1899
1900 (js2-msg "msg.remove.sealed"
1901 "Cannot remove a property from a sealed object: %s.")
1902
1903 (js2-msg "msg.modify.sealed"
1904 "Cannot modify a property of a sealed object: %s.")
1905
1906 (js2-msg "msg.modify.readonly"
1907 "Cannot modify readonly property: %s.")
1908
1909 ;; TokenStream
1910 (js2-msg "msg.missing.exponent"
1911 "missing exponent")
1912
1913 (js2-msg "msg.caught.nfe"
1914 "number format error")
1915
1916 (js2-msg "msg.unterminated.string.lit"
1917 "unterminated string literal")
1918
1919 (js2-msg "msg.unterminated.comment"
1920 "unterminated comment")
1921
1922 (js2-msg "msg.unterminated.re.lit"
1923 "unterminated regular expression literal")
1924
1925 (js2-msg "msg.invalid.re.flag"
1926 "invalid flag after regular expression")
1927
1928 (js2-msg "msg.no.re.input.for"
1929 "no input for %s")
1930
1931 (js2-msg "msg.illegal.character"
1932 "illegal character")
1933
1934 (js2-msg "msg.invalid.escape"
1935 "invalid Unicode escape sequence")
1936
1937 (js2-msg "msg.bad.namespace"
1938 "not a valid default namespace statement. "
1939 "Syntax is: default xml namespace = EXPRESSION;")
1940
1941 ;; TokensStream warnings
1942 (js2-msg "msg.bad.octal.literal"
1943 "illegal octal literal digit %s; "
1944 "interpreting it as a decimal digit")
1945
1946 (js2-msg "msg.missing.hex.digits"
1947 "missing hexadecimal digits after '0x'")
1948
1949 (js2-msg "msg.missing.binary.digits"
1950 "missing binary digits after '0b'")
1951
1952 (js2-msg "msg.missing.octal.digits"
1953 "missing octal digits after '0o'")
1954
1955 (js2-msg "msg.script.is.not.constructor"
1956 "Script objects are not constructors.")
1957
1958 ;; Arrays
1959 (js2-msg "msg.arraylength.bad"
1960 "Inappropriate array length.")
1961
1962 ;; Arrays
1963 (js2-msg "msg.arraylength.too.big"
1964 "Array length %s exceeds supported capacity limit.")
1965
1966 ;; URI
1967 (js2-msg "msg.bad.uri"
1968 "Malformed URI sequence.")
1969
1970 ;; Number
1971 (js2-msg "msg.bad.precision"
1972 "Precision %s out of range.")
1973
1974 ;; NativeGenerator
1975 (js2-msg "msg.send.newborn"
1976 "Attempt to send value to newborn generator")
1977
1978 (js2-msg "msg.already.exec.gen"
1979 "Already executing generator")
1980
1981 (js2-msg "msg.StopIteration.invalid"
1982 "StopIteration may not be changed to an arbitrary object.")
1983
1984 ;; Interpreter
1985 (js2-msg "msg.yield.closing"
1986 "Yield from closing generator")
1987
1988 ;; Classes
1989 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1990 "class statement requires a name")
1991
1992 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1993 "unexpected ',' between class properties")
1994
1995 (js2-msg "msg.unexpected.static" ; added by js2-mode
1996 "unexpected 'static'")
1997
1998 (js2-msg "msg.missing.extends" ; added by js2-mode
1999 "name is required after extends")
2000
2001 (js2-msg "msg.no.brace.class" ; added by js2-mode
2002 "missing '{' before class body")
2003
2004 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2005 "missing ']' after computed property expression")
2006
2007 ;;; Tokens Buffer
2008
2009 (defconst js2-ti-max-lookahead 2)
2010 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2011
2012 (defun js2-new-token (offset)
2013 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2014 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2015 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2016 token))
2017
2018 (defsubst js2-current-token ()
2019 (aref js2-ti-tokens js2-ti-tokens-cursor))
2020
2021 (defsubst js2-current-token-string ()
2022 (js2-token-string (js2-current-token)))
2023
2024 (defsubst js2-current-token-type ()
2025 (js2-token-type (js2-current-token)))
2026
2027 (defsubst js2-current-token-beg ()
2028 (js2-token-beg (js2-current-token)))
2029
2030 (defsubst js2-current-token-end ()
2031 (js2-token-end (js2-current-token)))
2032
2033 (defun js2-current-token-len ()
2034 (let ((token (js2-current-token)))
2035 (- (js2-token-end token)
2036 (js2-token-beg token))))
2037
2038 (defun js2-ts-seek (state)
2039 (setq js2-ts-lineno (js2-ts-state-lineno state)
2040 js2-ts-cursor (js2-ts-state-cursor state)
2041 js2-ti-tokens (js2-ts-state-tokens state)
2042 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2043 js2-ti-lookahead (js2-ts-state-lookahead state)))
2044
2045 ;;; Utilities
2046
2047 (defun js2-delete-if (predicate list)
2048 "Remove all items satisfying PREDICATE in LIST."
2049 (cl-loop for item in list
2050 if (not (funcall predicate item))
2051 collect item))
2052
2053 (defun js2-position (element list)
2054 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2055 Returns nil if element is not found in the list."
2056 (let ((count 0)
2057 found)
2058 (while (and list (not found))
2059 (if (eq element (car list))
2060 (setq found t)
2061 (setq count (1+ count)
2062 list (cdr list))))
2063 (if found count)))
2064
2065 (defun js2-find-if (predicate list)
2066 "Find first item satisfying PREDICATE in LIST."
2067 (let (result)
2068 (while (and list (not result))
2069 (if (funcall predicate (car list))
2070 (setq result (car list)))
2071 (setq list (cdr list)))
2072 result))
2073
2074 (defmacro js2-time (form)
2075 "Evaluate FORM, discard result, and return elapsed time in sec."
2076 (declare (debug t))
2077 (let ((beg (make-symbol "--js2-time-beg--")))
2078 `(let ((,beg (current-time)))
2079 ,form
2080 (/ (truncate (* (- (float-time (current-time))
2081 (float-time ,beg))
2082 10000))
2083 10000.0))))
2084
2085 (defsubst js2-same-line (pos)
2086 "Return t if POS is on the same line as current point."
2087 (and (>= pos (point-at-bol))
2088 (<= pos (point-at-eol))))
2089
2090 (defun js2-code-bug ()
2091 "Signal an error when we encounter an unexpected code path."
2092 (error "failed assertion"))
2093
2094 (defsubst js2-record-text-property (beg end prop value)
2095 "Record a text property to set when parsing finishes."
2096 (push (list beg end prop value) js2-mode-deferred-properties))
2097
2098 ;; I'd like to associate errors with nodes, but for now the
2099 ;; easiest thing to do is get the context info from the last token.
2100 (defun js2-record-parse-error (msg &optional arg pos len)
2101 (push (list (list msg arg)
2102 (or pos (js2-current-token-beg))
2103 (or len (js2-current-token-len)))
2104 js2-parsed-errors))
2105
2106 (defun js2-report-error (msg &optional msg-arg pos len)
2107 "Signal a syntax error or record a parse error."
2108 (if js2-recover-from-parse-errors
2109 (js2-record-parse-error msg msg-arg pos len)
2110 (signal 'js2-syntax-error
2111 (list msg
2112 js2-ts-lineno
2113 (save-excursion
2114 (goto-char js2-ts-cursor)
2115 (current-column))
2116 js2-ts-hit-eof))))
2117
2118 (defun js2-report-warning (msg &optional msg-arg pos len face)
2119 (if js2-compiler-report-warning-as-error
2120 (js2-report-error msg msg-arg pos len)
2121 (push (list (list msg msg-arg)
2122 (or pos (js2-current-token-beg))
2123 (or len (js2-current-token-len))
2124 face)
2125 js2-parsed-warnings)))
2126
2127 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2128 (if js2-compiler-strict-mode
2129 (js2-report-warning msg-id msg-arg beg
2130 (and beg end (- end beg)))))
2131
2132 (put 'js2-syntax-error 'error-conditions
2133 '(error syntax-error js2-syntax-error))
2134 (put 'js2-syntax-error 'error-message "Syntax error")
2135
2136 (put 'js2-parse-error 'error-conditions
2137 '(error parse-error js2-parse-error))
2138 (put 'js2-parse-error 'error-message "Parse error")
2139
2140 (defmacro js2-clear-flag (flags flag)
2141 `(setq ,flags (logand ,flags (lognot ,flag))))
2142
2143 (defmacro js2-set-flag (flags flag)
2144 "Logical-or FLAG into FLAGS."
2145 `(setq ,flags (logior ,flags ,flag)))
2146
2147 (defsubst js2-flag-set-p (flags flag)
2148 (/= 0 (logand flags flag)))
2149
2150 (defsubst js2-flag-not-set-p (flags flag)
2151 (zerop (logand flags flag)))
2152
2153 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2154 "Evaluate BODY with the _ character set to be word-syntax."
2155 (declare (indent 0) (debug t))
2156 (let ((old-syntax (make-symbol "old-syntax")))
2157 `(let ((,old-syntax (string (char-syntax ?_))))
2158 (unwind-protect
2159 (progn
2160 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2161 ,@body)
2162 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2163
2164 ;;; AST struct and function definitions
2165
2166 ;; flags for ast node property 'member-type (used for e4x operators)
2167 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2168 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2169 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2170
2171 (defsubst js2-relpos (pos anchor)
2172 "Convert POS to be relative to ANCHOR.
2173 If POS is nil, returns nil."
2174 (and pos (- pos anchor)))
2175
2176 (defun js2-make-pad (indent)
2177 (if (zerop indent)
2178 ""
2179 (make-string (* indent js2-basic-offset) ? )))
2180
2181 (defun js2-visit-ast (node callback)
2182 "Visit every node in ast NODE with visitor CALLBACK.
2183
2184 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2185 called twice: once to visit the node, and again after all the node's
2186 children have been processed. The END-P argument is nil on the first
2187 call and non-nil on the second call. The return value of the callback
2188 affects the traversal: if non-nil, the children of NODE are processed.
2189 If the callback returns nil, or if the node has no children, then the
2190 callback is called immediately with a non-nil END-P argument.
2191
2192 The node traversal is approximately lexical-order, although there
2193 are currently no guarantees around this."
2194 (when node
2195 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2196 ;; visit the node
2197 (when (funcall callback node nil)
2198 ;; visit the kids
2199 (cond
2200 ((eq vfunc 'js2-visit-none)
2201 nil) ; don't even bother calling it
2202 ;; Each AST node type has to define a `js2-visitor' function
2203 ;; that takes a node and a callback, and calls `js2-visit-ast'
2204 ;; on each child of the node.
2205 (vfunc
2206 (funcall vfunc node callback))
2207 (t
2208 (error "%s does not define a visitor-traversal function"
2209 (aref node 0)))))
2210 ;; call the end-visit
2211 (funcall callback node t))))
2212
2213 (cl-defstruct (js2-node
2214 (:constructor nil)) ; abstract
2215 "Base AST node type."
2216 (type -1) ; token type
2217 (pos -1) ; start position of this AST node in parsed input
2218 (len 1) ; num characters spanned by the node
2219 props ; optional node property list (an alist)
2220 parent) ; link to parent node; null for root
2221
2222 (defsubst js2-node-get-prop (node prop &optional default)
2223 (or (cadr (assoc prop (js2-node-props node))) default))
2224
2225 (defsubst js2-node-set-prop (node prop value)
2226 (setf (js2-node-props node)
2227 (cons (list prop value) (js2-node-props node))))
2228
2229 (defun js2-fixup-starts (n nodes)
2230 "Adjust the start positions of NODES to be relative to N.
2231 Any node in the list may be nil, for convenience."
2232 (dolist (node nodes)
2233 (when node
2234 (setf (js2-node-pos node) (- (js2-node-pos node)
2235 (js2-node-pos n))))))
2236
2237 (defun js2-node-add-children (parent &rest nodes)
2238 "Set parent node of NODES to PARENT, and return PARENT.
2239 Does nothing if we're not recording parent links.
2240 If any given node in NODES is nil, doesn't record that link."
2241 (js2-fixup-starts parent nodes)
2242 (dolist (node nodes)
2243 (and node
2244 (setf (js2-node-parent node) parent))))
2245
2246 ;; Non-recursive since it's called a frightening number of times.
2247 (defun js2-node-abs-pos (n)
2248 (let ((pos (js2-node-pos n)))
2249 (while (setq n (js2-node-parent n))
2250 (setq pos (+ pos (js2-node-pos n))))
2251 pos))
2252
2253 (defsubst js2-node-abs-end (n)
2254 "Return absolute buffer position of end of N."
2255 (+ (js2-node-abs-pos n) (js2-node-len n)))
2256
2257 ;; It's important to make sure block nodes have a Lisp list for the
2258 ;; child nodes, to limit printing recursion depth in an AST that
2259 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2260 ;; a sufficiently large vector tree.
2261
2262 (cl-defstruct (js2-block-node
2263 (:include js2-node)
2264 (:constructor nil)
2265 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2266 (pos (js2-current-token-beg))
2267 len
2268 props
2269 kids)))
2270 "A block of statements."
2271 kids) ; a Lisp list of the child statement nodes
2272
2273 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2274 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2275
2276 (defun js2-visit-block (ast callback)
2277 "Visit the `js2-block-node' children of AST."
2278 (dolist (kid (js2-block-node-kids ast))
2279 (js2-visit-ast kid callback)))
2280
2281 (defun js2-print-block (n i)
2282 (let ((pad (js2-make-pad i)))
2283 (insert pad "{\n")
2284 (dolist (kid (js2-block-node-kids n))
2285 (js2-print-ast kid (1+ i)))
2286 (insert pad "}")))
2287
2288 (cl-defstruct (js2-scope
2289 (:include js2-block-node)
2290 (:constructor nil)
2291 (:constructor make-js2-scope (&key (type js2-BLOCK)
2292 (pos (js2-current-token-beg))
2293 len
2294 kids)))
2295 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2296 ;; I don't have one of those handy, so I'll use an alist for now.
2297 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2298 ;; and is much lighter-weight to construct (both CPU and mem).
2299 ;; The keys are interned strings (symbols) for faster lookup.
2300 ;; Should switch to hybrid alist/hashtable eventually.
2301 symbol-table ; an alist of (symbol . js2-symbol)
2302 parent-scope ; a `js2-scope'
2303 top) ; top-level `js2-scope' (script/function)
2304
2305 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2306 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2307
2308 (defun js2-node-get-enclosing-scope (node)
2309 "Return the innermost `js2-scope' node surrounding NODE.
2310 Returns nil if there is no enclosing scope node."
2311 (let ((parent (js2-node-parent node)))
2312 (while (not (js2-scope-p parent))
2313 (setq parent (js2-node-parent parent)))
2314 parent))
2315
2316 (defun js2-get-defining-scope (scope name &optional point)
2317 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2318 Returns `js2-scope' in which NAME is defined, or nil if not found.
2319
2320 If POINT is non-nil, and if the found declaration type is
2321 `js2-LET', also check that the declaration node is before POINT."
2322 (let ((sym (if (symbolp name)
2323 name
2324 (intern name)))
2325 result
2326 (continue t))
2327 (while (and scope continue)
2328 (if (or
2329 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2330 (and entry
2331 (or (not point)
2332 (not (eq js2-LET (js2-symbol-decl-type entry)))
2333 (>= point
2334 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2335 (and (eq sym 'arguments)
2336 (js2-function-node-p scope)))
2337 (setq continue nil
2338 result scope)
2339 (setq scope (js2-scope-parent-scope scope))))
2340 result))
2341
2342 (defun js2-scope-get-symbol (scope name)
2343 "Return symbol table entry for NAME in SCOPE.
2344 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2345 (and (js2-scope-symbol-table scope)
2346 (cdr (assq (if (symbolp name)
2347 name
2348 (intern name))
2349 (js2-scope-symbol-table scope)))))
2350
2351 (defun js2-scope-put-symbol (scope name symbol)
2352 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2353 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2354 (let* ((table (js2-scope-symbol-table scope))
2355 (sym (if (symbolp name) name (intern name)))
2356 (entry (assq sym table)))
2357 (if entry
2358 (setcdr entry symbol)
2359 (push (cons sym symbol)
2360 (js2-scope-symbol-table scope)))))
2361
2362 (cl-defstruct (js2-symbol
2363 (:constructor nil)
2364 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2365 "A symbol table entry."
2366 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2367 ;; js2-LET, or js2-CONST
2368 decl-type
2369 name ; string
2370 ast-node) ; a `js2-node'
2371
2372 (cl-defstruct (js2-error-node
2373 (:include js2-node)
2374 (:constructor nil) ; silence emacs21 byte-compiler
2375 (:constructor make-js2-error-node (&key (type js2-ERROR)
2376 (pos (js2-current-token-beg))
2377 len)))
2378 "AST node representing a parse error.")
2379
2380 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2381 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2382
2383 (cl-defstruct (js2-script-node
2384 (:include js2-scope)
2385 (:constructor nil)
2386 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2387 (pos (js2-current-token-beg))
2388 len
2389 ;; FIXME: What are those?
2390 var-decls
2391 fun-decls)))
2392 functions ; Lisp list of nested functions
2393 regexps ; Lisp list of (string . flags)
2394 symbols ; alist (every symbol gets unique index)
2395 (param-count 0)
2396 var-names ; vector of string names
2397 consts ; bool-vector matching var-decls
2398 (temp-number 0)) ; for generating temp variables
2399
2400 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2401 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2402
2403 (defun js2-print-script (node indent)
2404 (dolist (kid (js2-block-node-kids node))
2405 (js2-print-ast kid indent)))
2406
2407 (cl-defstruct (js2-ast-root
2408 (:include js2-script-node)
2409 (:constructor nil)
2410 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2411 (pos (js2-current-token-beg))
2412 len
2413 buffer)))
2414 "The root node of a js2 AST."
2415 buffer ; the source buffer from which the code was parsed
2416 comments ; a Lisp list of comments, ordered by start position
2417 errors ; a Lisp list of errors found during parsing
2418 warnings ; a Lisp list of warnings found during parsing
2419 node-count) ; number of nodes in the tree, including the root
2420
2421 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2422 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2423
2424 (defun js2-visit-ast-root (ast callback)
2425 (dolist (kid (js2-ast-root-kids ast))
2426 (js2-visit-ast kid callback))
2427 (dolist (comment (js2-ast-root-comments ast))
2428 (js2-visit-ast comment callback)))
2429
2430 (cl-defstruct (js2-comment-node
2431 (:include js2-node)
2432 (:constructor nil)
2433 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2434 (pos (js2-current-token-beg))
2435 len
2436 format)))
2437 format) ; 'line, 'block, 'jsdoc or 'html
2438
2439 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2440 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2441
2442 (defun js2-print-comment (n i)
2443 ;; We really ought to link end-of-line comments to their nodes.
2444 ;; Or maybe we could add a new comment type, 'endline.
2445 (insert (js2-make-pad i)
2446 (js2-node-string n)))
2447
2448 (cl-defstruct (js2-expr-stmt-node
2449 (:include js2-node)
2450 (:constructor nil)
2451 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2452 (pos js2-ts-cursor)
2453 len
2454 expr)))
2455 "An expression statement."
2456 expr)
2457
2458 (defsubst js2-expr-stmt-node-set-has-result (node)
2459 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2460 (setf (js2-node-type node) js2-EXPR_RESULT))
2461
2462 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2463 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2464
2465 (defun js2-visit-expr-stmt-node (n v)
2466 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2467
2468 (defun js2-print-expr-stmt-node (n indent)
2469 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2470 (insert ";\n"))
2471
2472 (cl-defstruct (js2-loop-node
2473 (:include js2-scope)
2474 (:constructor nil))
2475 "Abstract supertype of loop nodes."
2476 body ; a `js2-block-node'
2477 lp ; position of left-paren, nil if omitted
2478 rp) ; position of right-paren, nil if omitted
2479
2480 (cl-defstruct (js2-do-node
2481 (:include js2-loop-node)
2482 (:constructor nil)
2483 (:constructor make-js2-do-node (&key (type js2-DO)
2484 (pos (js2-current-token-beg))
2485 len
2486 body
2487 condition
2488 while-pos
2489 lp
2490 rp)))
2491 "AST node for do-loop."
2492 condition ; while (expression)
2493 while-pos) ; buffer position of 'while' keyword
2494
2495 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2496 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2497
2498 (defun js2-visit-do-node (n v)
2499 (js2-visit-ast (js2-do-node-body n) v)
2500 (js2-visit-ast (js2-do-node-condition n) v))
2501
2502 (defun js2-print-do-node (n i)
2503 (let ((pad (js2-make-pad i)))
2504 (insert pad "do {\n")
2505 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2506 (js2-print-ast kid (1+ i)))
2507 (insert pad "} while (")
2508 (js2-print-ast (js2-do-node-condition n) 0)
2509 (insert ");\n")))
2510
2511 (cl-defstruct (js2-export-node
2512 (:include js2-node)
2513 (:constructor nil)
2514 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2515 (pos) (js2-current-token-beg)
2516 len
2517 exports-list
2518 from-clause
2519 declaration
2520 default)))
2521 "AST node for an export statement. There are many things that can be exported,
2522 so many of its properties will be nil.
2523 "
2524 exports-list ; lisp list of js2-export-binding-node to export
2525 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2526 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2527 default) ; js2-function-node or js2-assign-node
2528
2529 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2530 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2531
2532 (defun js2-visit-export-node (n v)
2533 (let ((exports-list (js2-export-node-exports-list n))
2534 (from (js2-export-node-from-clause n))
2535 (declaration (js2-export-node-declaration n))
2536 (default (js2-export-node-default n)))
2537 (when exports-list
2538 (dolist (export exports-list)
2539 (js2-visit-ast export v)))
2540 (when from
2541 (js2-visit-ast from v))
2542 (when declaration
2543 (js2-visit-ast declaration v))
2544 (when default
2545 (js2-visit-ast default v))))
2546
2547 (defun js2-print-export-node (n i)
2548 (let ((pad (js2-make-pad i))
2549 (exports-list (js2-export-node-exports-list n))
2550 (from (js2-export-node-from-clause n))
2551 (declaration (js2-export-node-declaration n))
2552 (default (js2-export-node-default n)))
2553 (insert pad "export ")
2554 (cond
2555 (default
2556 (insert "default ")
2557 (js2-print-ast default i))
2558 (declaration
2559 (js2-print-ast declaration i))
2560 ((and exports-list from)
2561 (js2-print-named-imports exports-list)
2562 (insert " ")
2563 (js2-print-from-clause from))
2564 (from
2565 (insert "* ")
2566 (js2-print-from-clause from))
2567 (exports-list
2568 (js2-print-named-imports exports-list)))
2569 (insert ";\n")))
2570
2571 (cl-defstruct (js2-while-node
2572 (:include js2-loop-node)
2573 (:constructor nil)
2574 (:constructor make-js2-while-node (&key (type js2-WHILE)
2575 (pos (js2-current-token-beg))
2576 len body
2577 condition lp
2578 rp)))
2579 "AST node for while-loop."
2580 condition) ; while-condition
2581
2582 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2583 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2584
2585 (defun js2-visit-while-node (n v)
2586 (js2-visit-ast (js2-while-node-condition n) v)
2587 (js2-visit-ast (js2-while-node-body n) v))
2588
2589 (defun js2-print-while-node (n i)
2590 (let ((pad (js2-make-pad i)))
2591 (insert pad "while (")
2592 (js2-print-ast (js2-while-node-condition n) 0)
2593 (insert ") {\n")
2594 (js2-print-body (js2-while-node-body n) (1+ i))
2595 (insert pad "}\n")))
2596
2597 (cl-defstruct (js2-for-node
2598 (:include js2-loop-node)
2599 (:constructor nil)
2600 (:constructor make-js2-for-node (&key (type js2-FOR)
2601 (pos js2-ts-cursor)
2602 len body init
2603 condition
2604 update lp rp)))
2605 "AST node for a C-style for-loop."
2606 init ; initialization expression
2607 condition ; loop condition
2608 update) ; update clause
2609
2610 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2611 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2612
2613 (defun js2-visit-for-node (n v)
2614 (js2-visit-ast (js2-for-node-init n) v)
2615 (js2-visit-ast (js2-for-node-condition n) v)
2616 (js2-visit-ast (js2-for-node-update n) v)
2617 (js2-visit-ast (js2-for-node-body n) v))
2618
2619 (defun js2-print-for-node (n i)
2620 (let ((pad (js2-make-pad i)))
2621 (insert pad "for (")
2622 (js2-print-ast (js2-for-node-init n) 0)
2623 (insert "; ")
2624 (js2-print-ast (js2-for-node-condition n) 0)
2625 (insert "; ")
2626 (js2-print-ast (js2-for-node-update n) 0)
2627 (insert ") {\n")
2628 (js2-print-body (js2-for-node-body n) (1+ i))
2629 (insert pad "}\n")))
2630
2631 (cl-defstruct (js2-for-in-node
2632 (:include js2-loop-node)
2633 (:constructor nil)
2634 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2635 (pos js2-ts-cursor)
2636 len body
2637 iterator
2638 object
2639 in-pos
2640 each-pos
2641 foreach-p forof-p
2642 lp rp)))
2643 "AST node for a for..in loop."
2644 iterator ; [var] foo in ...
2645 object ; object over which we're iterating
2646 in-pos ; buffer position of 'in' keyword
2647 each-pos ; buffer position of 'each' keyword, if foreach-p
2648 foreach-p ; t if it's a for-each loop
2649 forof-p) ; t if it's a for-of loop
2650
2651 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2652 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2653
2654 (defun js2-visit-for-in-node (n v)
2655 (js2-visit-ast (js2-for-in-node-iterator n) v)
2656 (js2-visit-ast (js2-for-in-node-object n) v)
2657 (js2-visit-ast (js2-for-in-node-body n) v))
2658
2659 (defun js2-print-for-in-node (n i)
2660 (let ((pad (js2-make-pad i))
2661 (foreach (js2-for-in-node-foreach-p n))
2662 (forof (js2-for-in-node-forof-p n)))
2663 (insert pad "for ")
2664 (if foreach
2665 (insert "each "))
2666 (insert "(")
2667 (js2-print-ast (js2-for-in-node-iterator n) 0)
2668 (insert (if forof " of " " in "))
2669 (js2-print-ast (js2-for-in-node-object n) 0)
2670 (insert ") {\n")
2671 (js2-print-body (js2-for-in-node-body n) (1+ i))
2672 (insert pad "}\n")))
2673
2674 (cl-defstruct (js2-return-node
2675 (:include js2-node)
2676 (:constructor nil)
2677 (:constructor make-js2-return-node (&key (type js2-RETURN)
2678 (pos js2-ts-cursor)
2679 len
2680 retval)))
2681 "AST node for a return statement."
2682 retval) ; expression to return, or 'undefined
2683
2684 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2685 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2686
2687 (defun js2-visit-return-node (n v)
2688 (js2-visit-ast (js2-return-node-retval n) v))
2689
2690 (defun js2-print-return-node (n i)
2691 (insert (js2-make-pad i) "return")
2692 (when (js2-return-node-retval n)
2693 (insert " ")
2694 (js2-print-ast (js2-return-node-retval n) 0))
2695 (insert ";\n"))
2696
2697 (cl-defstruct (js2-if-node
2698 (:include js2-node)
2699 (:constructor nil)
2700 (:constructor make-js2-if-node (&key (type js2-IF)
2701 (pos js2-ts-cursor)
2702 len condition
2703 then-part
2704 else-pos
2705 else-part lp
2706 rp)))
2707 "AST node for an if-statement."
2708 condition ; expression
2709 then-part ; statement or block
2710 else-pos ; optional buffer position of 'else' keyword
2711 else-part ; optional statement or block
2712 lp ; position of left-paren, nil if omitted
2713 rp) ; position of right-paren, nil if omitted
2714
2715 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2716 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2717
2718 (defun js2-visit-if-node (n v)
2719 (js2-visit-ast (js2-if-node-condition n) v)
2720 (js2-visit-ast (js2-if-node-then-part n) v)
2721 (js2-visit-ast (js2-if-node-else-part n) v))
2722
2723 (defun js2-print-if-node (n i)
2724 (let ((pad (js2-make-pad i))
2725 (then-part (js2-if-node-then-part n))
2726 (else-part (js2-if-node-else-part n)))
2727 (insert pad "if (")
2728 (js2-print-ast (js2-if-node-condition n) 0)
2729 (insert ") {\n")
2730 (js2-print-body then-part (1+ i))
2731 (insert pad "}")
2732 (cond
2733 ((not else-part)
2734 (insert "\n"))
2735 ((js2-if-node-p else-part)
2736 (insert " else ")
2737 (js2-print-body else-part i))
2738 (t
2739 (insert " else {\n")
2740 (js2-print-body else-part (1+ i))
2741 (insert pad "}\n")))))
2742
2743 (cl-defstruct (js2-export-binding-node
2744 (:include js2-node)
2745 (:constructor nil)
2746 (:constructor make-js2-export-binding-node (&key (type -1)
2747 pos
2748 len
2749 local-name
2750 extern-name)))
2751 "AST node for an external symbol binding.
2752 It contains a local-name node which is the name of the value in the
2753 current scope, and extern-name which is the name of the value in the
2754 imported or exported scope. By default these are the same, but if the
2755 name is aliased as in {foo as bar}, it would have an extern-name node
2756 containing 'foo' and a local-name node containing 'bar'."
2757 local-name ; js2-name-node with the variable name in this scope
2758 extern-name) ; js2-name-node with the value name in the exporting module
2759
2760 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2761 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2762
2763 (defun js2-visit-extern-binding (n v)
2764 "Visit an extern binding node. First visit the local-name, and, if
2765 different, visit the extern-name."
2766 (let ((local-name (js2-export-binding-node-local-name n))
2767 (extern-name (js2-export-binding-node-extern-name n)))
2768 (when local-name
2769 (js2-visit-ast local-name v))
2770 (when (not (equal local-name extern-name))
2771 (js2-visit-ast extern-name v))))
2772
2773 (defun js2-print-extern-binding (n i)
2774 "Print a representation of a single extern binding. E.g. 'foo' or
2775 'foo as bar'."
2776 (let ((local-name (js2-export-binding-node-local-name n))
2777 (extern-name (js2-export-binding-node-extern-name n)))
2778 (insert (js2-name-node-name extern-name))
2779 (when (not (equal local-name extern-name))
2780 (insert " as ")
2781 (insert (js2-name-node-name local-name)))))
2782
2783
2784 (cl-defstruct (js2-import-node
2785 (:include js2-node)
2786 (:constructor nil)
2787 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2788 (pos (js2-current-token-beg))
2789 len
2790 import
2791 from
2792 module-id)))
2793 "AST node for an import statement. It follows the form
2794
2795 import ModuleSpecifier;
2796 import ImportClause FromClause;"
2797 import ; js2-import-clause-node specifying which names are to imported.
2798 from ; js2-from-clause-node indicating the module from which to import.
2799 module-id) ; module-id of the import. E.g. 'src/mylib'.
2800
2801 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2802 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2803
2804 (defun js2-visit-import (n v)
2805 (let ((import-clause (js2-import-node-import n))
2806 (from-clause (js2-import-node-from n)))
2807 (when import-clause
2808 (js2-visit-ast import-clause v))
2809 (when from-clause
2810 (js2-visit-ast from-clause v))))
2811
2812 (defun js2-print-import (n i)
2813 "Prints a representation of the import node"
2814 (let ((pad (js2-make-pad i))
2815 (import-clause (js2-import-node-import n))
2816 (from-clause (js2-import-node-from n))
2817 (module-id (js2-import-node-module-id n)))
2818 (insert pad "import ")
2819 (if import-clause
2820 (progn
2821 (js2-print-import-clause import-clause)
2822 (insert " ")
2823 (js2-print-from-clause from-clause))
2824 (insert "'")
2825 (insert module-id)
2826 (insert "'"))
2827 (insert ";\n")))
2828
2829 (cl-defstruct (js2-import-clause-node
2830 (:include js2-node)
2831 (:constructor nil)
2832 (:constructor make-js2-import-clause-node (&key (type -1)
2833 pos
2834 len
2835 namespace-import
2836 named-imports
2837 default-binding)))
2838 "AST node corresponding to the import clause of an import statement. This is
2839 the portion of the import that bindings names from the external context to the
2840 local context."
2841 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2842 named-imports ; lisp list of js2-export-binding-node for all named imports.
2843 default-binding) ; js2-export-binding-node for the default import binding
2844
2845 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2846 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2847
2848 (defun js2-visit-import-clause (n v)
2849 (let ((ns-import (js2-import-clause-node-namespace-import n))
2850 (named-imports (js2-import-clause-node-named-imports n))
2851 (default (js2-import-clause-node-default-binding n)))
2852 (when ns-import
2853 (js2-visit-ast ns-import v))
2854 (when named-imports
2855 (dolist (import named-imports)
2856 (js2-visit-ast import v)))
2857 (when default
2858 (js2-visit-ast default v))))
2859
2860 (defun js2-print-import-clause (n)
2861 (let ((ns-import (js2-import-clause-node-namespace-import n))
2862 (named-imports (js2-import-clause-node-named-imports n))
2863 (default (js2-import-clause-node-default-binding n)))
2864 (cond
2865 ((and default ns-import)
2866 (js2-print-ast default)
2867 (insert ", ")
2868 (js2-print-namespace-import ns-import))
2869 ((and default named-imports)
2870 (js2-print-ast default)
2871 (insert ", ")
2872 (js2-print-named-imports named-imports))
2873 (default
2874 (js2-print-ast default))
2875 (ns-import
2876 (js2-print-namespace-import ns-import))
2877 (named-imports
2878 (js2-print-named-imports named-imports)))))
2879
2880 (defun js2-print-namespace-import (node)
2881 (insert "* as ")
2882 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2883
2884 (defun js2-print-named-imports (imports)
2885 (insert "{")
2886 (let ((len (length imports))
2887 (n 0))
2888 (while (< n len)
2889 (js2-print-extern-binding (nth n imports) 0)
2890 (unless (= n (- len 1))
2891 (insert ", "))
2892 (setq n (+ n 1))))
2893 (insert "}"))
2894
2895 (cl-defstruct (js2-namespace-import-node
2896 (:include js2-node)
2897 (:constructor nil)
2898 (:constructor make-js2-namespace-import-node (&key (type -1)
2899 pos
2900 len
2901 name)))
2902 "AST node for a complete namespace import.
2903 E.g. the '* as lib' expression in:
2904
2905 import * as lib from 'src/lib'
2906
2907 It contains a single name node referring to the bound name."
2908 name) ; js2-name-node of the bound name.
2909
2910 (defun js2-visit-namespace-import (n v)
2911 (js2-visit-ast (js2-namespace-import-node-name n) v))
2912
2913 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2914 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2915
2916 (cl-defstruct (js2-from-clause-node
2917 (:include js2-node)
2918 (:constructor nil)
2919 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2920 pos
2921 len
2922 module-id
2923 metadata-p)))
2924 "AST node for the from clause in an import or export statement.
2925 E.g. from 'my/module'. It can refere to either an external module, or to the
2926 modules metadata itself."
2927 module-id ; string containing the module specifier.
2928 metadata-p) ; true if this clause refers to the module's metadata
2929
2930 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2931 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2932
2933 (defun js2-print-from-clause (n)
2934 (insert "from ")
2935 (if (js2-from-clause-node-metadata-p n)
2936 (insert "this module")
2937 (insert "'")
2938 (insert (js2-from-clause-node-module-id n))
2939 (insert "'")))
2940
2941 (cl-defstruct (js2-try-node
2942 (:include js2-node)
2943 (:constructor nil)
2944 (:constructor make-js2-try-node (&key (type js2-TRY)
2945 (pos js2-ts-cursor)
2946 len
2947 try-block
2948 catch-clauses
2949 finally-block)))
2950 "AST node for a try-statement."
2951 try-block
2952 catch-clauses ; a Lisp list of `js2-catch-node'
2953 finally-block) ; a `js2-finally-node'
2954
2955 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2956 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2957
2958 (defun js2-visit-try-node (n v)
2959 (js2-visit-ast (js2-try-node-try-block n) v)
2960 (dolist (clause (js2-try-node-catch-clauses n))
2961 (js2-visit-ast clause v))
2962 (js2-visit-ast (js2-try-node-finally-block n) v))
2963
2964 (defun js2-print-try-node (n i)
2965 (let ((pad (js2-make-pad i))
2966 (catches (js2-try-node-catch-clauses n))
2967 (finally (js2-try-node-finally-block n)))
2968 (insert pad "try {\n")
2969 (js2-print-body (js2-try-node-try-block n) (1+ i))
2970 (insert pad "}")
2971 (when catches
2972 (dolist (catch catches)
2973 (js2-print-ast catch i)))
2974 (if finally
2975 (js2-print-ast finally i)
2976 (insert "\n"))))
2977
2978 (cl-defstruct (js2-catch-node
2979 (:include js2-scope)
2980 (:constructor nil)
2981 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2982 (pos js2-ts-cursor)
2983 len
2984 param
2985 guard-kwd
2986 guard-expr
2987 lp rp)))
2988 "AST node for a catch clause."
2989 param ; destructuring form or simple name node
2990 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2991 guard-expr ; catch condition, a `js2-node'
2992 lp ; buffer position of left-paren, nil if omitted
2993 rp) ; buffer position of right-paren, nil if omitted
2994
2995 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2996 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2997
2998 (defun js2-visit-catch-node (n v)
2999 (js2-visit-ast (js2-catch-node-param n) v)
3000 (when (js2-catch-node-guard-kwd n)
3001 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3002 (js2-visit-block n v))
3003
3004 (defun js2-print-catch-node (n i)
3005 (let ((pad (js2-make-pad i))
3006 (guard-kwd (js2-catch-node-guard-kwd n))
3007 (guard-expr (js2-catch-node-guard-expr n)))
3008 (insert " catch (")
3009 (js2-print-ast (js2-catch-node-param n) 0)
3010 (when guard-kwd
3011 (insert " if ")
3012 (js2-print-ast guard-expr 0))
3013 (insert ") {\n")
3014 (js2-print-body n (1+ i))
3015 (insert pad "}")))
3016
3017 (cl-defstruct (js2-finally-node
3018 (:include js2-node)
3019 (:constructor nil)
3020 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3021 (pos js2-ts-cursor)
3022 len body)))
3023 "AST node for a finally clause."
3024 body) ; a `js2-node', often but not always a block node
3025
3026 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3027 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3028
3029 (defun js2-visit-finally-node (n v)
3030 (js2-visit-ast (js2-finally-node-body n) v))
3031
3032 (defun js2-print-finally-node (n i)
3033 (let ((pad (js2-make-pad i)))
3034 (insert " finally {\n")
3035 (js2-print-body (js2-finally-node-body n) (1+ i))
3036 (insert pad "}\n")))
3037
3038 (cl-defstruct (js2-switch-node
3039 (:include js2-node)
3040 (:constructor nil)
3041 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3042 (pos js2-ts-cursor)
3043 len
3044 discriminant
3045 cases lp
3046 rp)))
3047 "AST node for a switch statement."
3048 discriminant ; a `js2-node' (switch expression)
3049 cases ; a Lisp list of `js2-case-node'
3050 lp ; position of open-paren for discriminant, nil if omitted
3051 rp) ; position of close-paren for discriminant, nil if omitted
3052
3053 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3054 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3055
3056 (defun js2-visit-switch-node (n v)
3057 (js2-visit-ast (js2-switch-node-discriminant n) v)
3058 (dolist (c (js2-switch-node-cases n))
3059 (js2-visit-ast c v)))
3060
3061 (defun js2-print-switch-node (n i)
3062 (let ((pad (js2-make-pad i))
3063 (cases (js2-switch-node-cases n)))
3064 (insert pad "switch (")
3065 (js2-print-ast (js2-switch-node-discriminant n) 0)
3066 (insert ") {\n")
3067 (dolist (case cases)
3068 (js2-print-ast case i))
3069 (insert pad "}\n")))
3070
3071 (cl-defstruct (js2-case-node
3072 (:include js2-block-node)
3073 (:constructor nil)
3074 (:constructor make-js2-case-node (&key (type js2-CASE)
3075 (pos js2-ts-cursor)
3076 len kids expr)))
3077 "AST node for a case clause of a switch statement."
3078 expr) ; the case expression (nil for default)
3079
3080 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3081 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3082
3083 (defun js2-visit-case-node (n v)
3084 (js2-visit-ast (js2-case-node-expr n) v)
3085 (js2-visit-block n v))
3086
3087 (defun js2-print-case-node (n i)
3088 (let ((pad (js2-make-pad i))
3089 (expr (js2-case-node-expr n)))
3090 (insert pad)
3091 (if (null expr)
3092 (insert "default:\n")
3093 (insert "case ")
3094 (js2-print-ast expr 0)
3095 (insert ":\n"))
3096 (dolist (kid (js2-case-node-kids n))
3097 (js2-print-ast kid (1+ i)))))
3098
3099 (cl-defstruct (js2-throw-node
3100 (:include js2-node)
3101 (:constructor nil)
3102 (:constructor make-js2-throw-node (&key (type js2-THROW)
3103 (pos js2-ts-cursor)
3104 len expr)))
3105 "AST node for a throw statement."
3106 expr) ; the expression to throw
3107
3108 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3109 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3110
3111 (defun js2-visit-throw-node (n v)
3112 (js2-visit-ast (js2-throw-node-expr n) v))
3113
3114 (defun js2-print-throw-node (n i)
3115 (insert (js2-make-pad i) "throw ")
3116 (js2-print-ast (js2-throw-node-expr n) 0)
3117 (insert ";\n"))
3118
3119 (cl-defstruct (js2-with-node
3120 (:include js2-node)
3121 (:constructor nil)
3122 (:constructor make-js2-with-node (&key (type js2-WITH)
3123 (pos js2-ts-cursor)
3124 len object
3125 body lp rp)))
3126 "AST node for a with-statement."
3127 object
3128 body
3129 lp ; buffer position of left-paren around object, nil if omitted
3130 rp) ; buffer position of right-paren around object, nil if omitted
3131
3132 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3133 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3134
3135 (defun js2-visit-with-node (n v)
3136 (js2-visit-ast (js2-with-node-object n) v)
3137 (js2-visit-ast (js2-with-node-body n) v))
3138
3139 (defun js2-print-with-node (n i)
3140 (let ((pad (js2-make-pad i)))
3141 (insert pad "with (")
3142 (js2-print-ast (js2-with-node-object n) 0)
3143 (insert ") {\n")
3144 (js2-print-body (js2-with-node-body n) (1+ i))
3145 (insert pad "}\n")))
3146
3147 (cl-defstruct (js2-label-node
3148 (:include js2-node)
3149 (:constructor nil)
3150 (:constructor make-js2-label-node (&key (type js2-LABEL)
3151 (pos js2-ts-cursor)
3152 len name)))
3153 "AST node for a statement label or case label."
3154 name ; a string
3155 loop) ; for validating and code-generating continue-to-label
3156
3157 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3158 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3159
3160 (defun js2-print-label (n i)
3161 (insert (js2-make-pad i)
3162 (js2-label-node-name n)
3163 ":\n"))
3164
3165 (cl-defstruct (js2-labeled-stmt-node
3166 (:include js2-node)
3167 (:constructor nil)
3168 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3169 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3170 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3171 (pos js2-ts-cursor)
3172 len labels stmt)))
3173 "AST node for a statement with one or more labels.
3174 Multiple labels for a statement are collapsed into the labels field."
3175 labels ; Lisp list of `js2-label-node'
3176 stmt) ; the statement these labels are for
3177
3178 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3179 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3180
3181 (defun js2-get-label-by-name (lbl-stmt name)
3182 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3183 Returns nil if no such label is in the list."
3184 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3185 result)
3186 (while (and label-list (not result))
3187 (if (string= (js2-label-node-name (car label-list)) name)
3188 (setq result (car label-list))
3189 (setq label-list (cdr label-list))))
3190 result))
3191
3192 (defun js2-visit-labeled-stmt (n v)
3193 (dolist (label (js2-labeled-stmt-node-labels n))
3194 (js2-visit-ast label v))
3195 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3196
3197 (defun js2-print-labeled-stmt (n i)
3198 (dolist (label (js2-labeled-stmt-node-labels n))
3199 (js2-print-ast label i))
3200 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3201
3202 (defun js2-labeled-stmt-node-contains (node label)
3203 "Return t if NODE contains LABEL in its label set.
3204 NODE is a `js2-labels-node'. LABEL is an identifier."
3205 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3206 if (string= label (js2-label-node-name nl))
3207 return t
3208 finally return nil))
3209
3210 (defsubst js2-labeled-stmt-node-add-label (node label)
3211 "Add a `js2-label-node' to the label set for this statement."
3212 (setf (js2-labeled-stmt-node-labels node)
3213 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3214
3215 (cl-defstruct (js2-jump-node
3216 (:include js2-node)
3217 (:constructor nil))
3218 "Abstract supertype of break and continue nodes."
3219 label ; `js2-name-node' for location of label identifier, if present
3220 target) ; target js2-labels-node or loop/switch statement
3221
3222 (defun js2-visit-jump-node (n v)
3223 ;; We don't visit the target, since it's a back-link.
3224 (js2-visit-ast (js2-jump-node-label n) v))
3225
3226 (cl-defstruct (js2-break-node
3227 (:include js2-jump-node)
3228 (:constructor nil)
3229 (:constructor make-js2-break-node (&key (type js2-BREAK)
3230 (pos js2-ts-cursor)
3231 len label target)))
3232 "AST node for a break statement.
3233 The label field is a `js2-name-node', possibly nil, for the named label
3234 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3235 is the target of the break - a label node or enclosing loop/switch statement.")
3236
3237 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3238 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3239
3240 (defun js2-print-break-node (n i)
3241 (insert (js2-make-pad i) "break")
3242 (when (js2-break-node-label n)
3243 (insert " ")
3244 (js2-print-ast (js2-break-node-label n) 0))
3245 (insert ";\n"))
3246
3247 (cl-defstruct (js2-continue-node
3248 (:include js2-jump-node)
3249 (:constructor nil)
3250 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3251 (pos js2-ts-cursor)
3252 len label target)))
3253 "AST node for a continue statement.
3254 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3255 It is nil if continue specifies no label. The target field is the jump target:
3256 a `js2-label-node' or the innermost enclosing loop.")
3257
3258 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3259 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3260
3261 (defun js2-print-continue-node (n i)
3262 (insert (js2-make-pad i) "continue")
3263 (when (js2-continue-node-label n)
3264 (insert " ")
3265 (js2-print-ast (js2-continue-node-label n) 0))
3266 (insert ";\n"))
3267
3268 (cl-defstruct (js2-function-node
3269 (:include js2-script-node)
3270 (:constructor nil)
3271 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3272 (pos js2-ts-cursor)
3273 len
3274 (ftype 'FUNCTION)
3275 (form 'FUNCTION_STATEMENT)
3276 (name "")
3277 params rest-p
3278 body
3279 generator-type
3280 lp rp)))
3281 "AST node for a function declaration.
3282 The `params' field is a Lisp list of nodes. Each node is either a simple
3283 `js2-name-node', or if it's a destructuring-assignment parameter, a
3284 `js2-array-node' or `js2-object-node'."
3285 ftype ; FUNCTION, GETTER or SETTER
3286 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3287 name ; function name (a `js2-name-node', or nil if anonymous)
3288 params ; a Lisp list of destructuring forms or simple name nodes
3289 rest-p ; if t, the last parameter is rest parameter
3290 body ; a `js2-block-node' or expression node (1.8 only)
3291 lp ; position of arg-list open-paren, or nil if omitted
3292 rp ; position of arg-list close-paren, or nil if omitted
3293 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3294 needs-activation ; t if we need an activation object for this frame
3295 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3296 member-expr) ; nonstandard Ecma extension from Rhino
3297
3298 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3299 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3300
3301 (defun js2-visit-function-node (n v)
3302 (js2-visit-ast (js2-function-node-name n) v)
3303 (dolist (p (js2-function-node-params n))
3304 (js2-visit-ast p v))
3305 (js2-visit-ast (js2-function-node-body n) v))
3306
3307 (defun js2-print-function-node (n i)
3308 (let* ((pad (js2-make-pad i))
3309 (getter (js2-node-get-prop n 'GETTER_SETTER))
3310 (name (or (js2-function-node-name n)
3311 (js2-function-node-member-expr n)))
3312 (params (js2-function-node-params n))
3313 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3314 (rest-p (js2-function-node-rest-p n))
3315 (body (js2-function-node-body n))
3316 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3317 (unless (or getter arrow)
3318 (insert pad "function")
3319 (when (eq (js2-function-node-generator-type n) 'STAR)
3320 (insert "*")))
3321 (when name
3322 (insert " ")
3323 (js2-print-ast name 0))
3324 (insert "(")
3325 (cl-loop with len = (length params)
3326 for param in params
3327 for count from 1
3328 do
3329 (when (and rest-p (= count len))
3330 (insert "..."))
3331 (js2-print-ast param 0)
3332 (when (< count len)
3333 (insert ", ")))
3334 (insert ") ")
3335 (when arrow
3336 (insert "=> "))
3337 (insert "{")
3338 ;; TODO: fix this to be smarter about indenting, etc.
3339 (unless expr
3340 (insert "\n"))
3341 (if (js2-block-node-p body)
3342 (js2-print-body body (1+ i))
3343 (js2-print-ast body 0))
3344 (insert pad "}")
3345 (unless expr
3346 (insert "\n"))))
3347
3348 (defun js2-function-name (node)
3349 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3350 (and (js2-function-node-name node)
3351 (js2-name-node-name (js2-function-node-name node))))
3352
3353 ;; Having this be an expression node makes it more flexible.
3354 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3355 ;; that work better if you assume it's an expression. Whenever we have
3356 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3357 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3358 (cl-defstruct (js2-var-decl-node
3359 (:include js2-node)
3360 (:constructor nil)
3361 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3362 (pos (js2-current-token-beg))
3363 len kids
3364 decl-type)))
3365 "AST node for a variable declaration list (VAR, CONST or LET).
3366 The node bounds differ depending on the declaration type. For VAR or
3367 CONST declarations, the bounds include the var/const keyword. For LET
3368 declarations, the node begins at the position of the first child."
3369 kids ; a Lisp list of `js2-var-init-node' structs.
3370 decl-type) ; js2-VAR, js2-CONST or js2-LET
3371
3372 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3373 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3374
3375 (defun js2-visit-var-decl (n v)
3376 (dolist (kid (js2-var-decl-node-kids n))
3377 (js2-visit-ast kid v)))
3378
3379 (defun js2-print-var-decl (n i)
3380 (let ((pad (js2-make-pad i))
3381 (tt (js2-var-decl-node-decl-type n)))
3382 (insert pad)
3383 (insert (cond
3384 ((= tt js2-VAR) "var ")
3385 ((= tt js2-LET) "let ")
3386 ((= tt js2-CONST) "const ")
3387 (t
3388 (error "malformed var-decl node"))))
3389 (cl-loop with kids = (js2-var-decl-node-kids n)
3390 with len = (length kids)
3391 for kid in kids
3392 for count from 1
3393 do
3394 (js2-print-ast kid 0)
3395 (if (< count len)
3396 (insert ", ")))))
3397
3398 (cl-defstruct (js2-var-init-node
3399 (:include js2-node)
3400 (:constructor nil)
3401 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3402 (pos js2-ts-cursor)
3403 len target
3404 initializer)))
3405 "AST node for a variable declaration.
3406 The type field will be js2-CONST for a const decl."
3407 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3408 initializer) ; initializer expression, a `js2-node'
3409
3410 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3411 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3412
3413 (defun js2-visit-var-init-node (n v)
3414 (js2-visit-ast (js2-var-init-node-target n) v)
3415 (js2-visit-ast (js2-var-init-node-initializer n) v))
3416
3417 (defun js2-print-var-init-node (n i)
3418 (let ((pad (js2-make-pad i))
3419 (name (js2-var-init-node-target n))
3420 (init (js2-var-init-node-initializer n)))
3421 (insert pad)
3422 (js2-print-ast name 0)
3423 (when init
3424 (insert " = ")
3425 (js2-print-ast init 0))))
3426
3427 (cl-defstruct (js2-cond-node
3428 (:include js2-node)
3429 (:constructor nil)
3430 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3431 (pos js2-ts-cursor)
3432 len
3433 test-expr
3434 true-expr
3435 false-expr
3436 q-pos c-pos)))
3437 "AST node for the ternary operator"
3438 test-expr
3439 true-expr
3440 false-expr
3441 q-pos ; buffer position of ?
3442 c-pos) ; buffer position of :
3443
3444 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3445 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3446
3447 (defun js2-visit-cond-node (n v)
3448 (js2-visit-ast (js2-cond-node-test-expr n) v)
3449 (js2-visit-ast (js2-cond-node-true-expr n) v)
3450 (js2-visit-ast (js2-cond-node-false-expr n) v))
3451
3452 (defun js2-print-cond-node (n i)
3453 (let ((pad (js2-make-pad i)))
3454 (insert pad)
3455 (js2-print-ast (js2-cond-node-test-expr n) 0)
3456 (insert " ? ")
3457 (js2-print-ast (js2-cond-node-true-expr n) 0)
3458 (insert " : ")
3459 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3460
3461 (cl-defstruct (js2-infix-node
3462 (:include js2-node)
3463 (:constructor nil)
3464 (:constructor make-js2-infix-node (&key type
3465 (pos js2-ts-cursor)
3466 len op-pos
3467 left right)))
3468 "Represents infix expressions.
3469 Includes assignment ops like `|=', and the comma operator.
3470 The type field inherited from `js2-node' holds the operator."
3471 op-pos ; buffer position where operator begins
3472 left ; any `js2-node'
3473 right) ; any `js2-node'
3474
3475 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3476 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3477
3478 (defun js2-visit-infix-node (n v)
3479 (js2-visit-ast (js2-infix-node-left n) v)
3480 (js2-visit-ast (js2-infix-node-right n) v))
3481
3482 (defconst js2-operator-tokens
3483 (let ((table (make-hash-table :test 'eq))
3484 (tokens
3485 (list (cons js2-IN "in")
3486 (cons js2-TYPEOF "typeof")
3487 (cons js2-INSTANCEOF "instanceof")
3488 (cons js2-DELPROP "delete")
3489 (cons js2-COMMA ",")
3490 (cons js2-COLON ":")
3491 (cons js2-OR "||")
3492 (cons js2-AND "&&")
3493 (cons js2-INC "++")
3494 (cons js2-DEC "--")
3495 (cons js2-BITOR "|")
3496 (cons js2-BITXOR "^")
3497 (cons js2-BITAND "&")
3498 (cons js2-EQ "==")
3499 (cons js2-NE "!=")
3500 (cons js2-LT "<")
3501 (cons js2-LE "<=")
3502 (cons js2-GT ">")
3503 (cons js2-GE ">=")
3504 (cons js2-LSH "<<")
3505 (cons js2-RSH ">>")
3506 (cons js2-URSH ">>>")
3507 (cons js2-ADD "+") ; infix plus
3508 (cons js2-SUB "-") ; infix minus
3509 (cons js2-MUL "*")
3510 (cons js2-DIV "/")
3511 (cons js2-MOD "%")
3512 (cons js2-NOT "!")
3513 (cons js2-BITNOT "~")
3514 (cons js2-POS "+") ; unary plus
3515 (cons js2-NEG "-") ; unary minus
3516 (cons js2-TRIPLEDOT "...")
3517 (cons js2-SHEQ "===") ; shallow equality
3518 (cons js2-SHNE "!==") ; shallow inequality
3519 (cons js2-ASSIGN "=")
3520 (cons js2-ASSIGN_BITOR "|=")
3521 (cons js2-ASSIGN_BITXOR "^=")
3522 (cons js2-ASSIGN_BITAND "&=")
3523 (cons js2-ASSIGN_LSH "<<=")
3524 (cons js2-ASSIGN_RSH ">>=")
3525 (cons js2-ASSIGN_URSH ">>>=")
3526 (cons js2-ASSIGN_ADD "+=")
3527 (cons js2-ASSIGN_SUB "-=")
3528 (cons js2-ASSIGN_MUL "*=")
3529 (cons js2-ASSIGN_DIV "/=")
3530 (cons js2-ASSIGN_MOD "%="))))
3531 (cl-loop for (k . v) in tokens do
3532 (puthash k v table))
3533 table))
3534
3535 (defun js2-print-infix-node (n i)
3536 (let* ((tt (js2-node-type n))
3537 (op (gethash tt js2-operator-tokens)))
3538 (unless op
3539 (error "unrecognized infix operator %s" (js2-node-type n)))
3540 (insert (js2-make-pad i))
3541 (js2-print-ast (js2-infix-node-left n) 0)
3542 (unless (= tt js2-COMMA)
3543 (insert " "))
3544 (insert op)
3545 (insert " ")
3546 (js2-print-ast (js2-infix-node-right n) 0)))
3547
3548 (cl-defstruct (js2-assign-node
3549 (:include js2-infix-node)
3550 (:constructor nil)
3551 (:constructor make-js2-assign-node (&key type
3552 (pos js2-ts-cursor)
3553 len op-pos
3554 left right)))
3555 "Represents any assignment.
3556 The type field holds the actual assignment operator.")
3557
3558 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3559 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3560
3561 (cl-defstruct (js2-unary-node
3562 (:include js2-node)
3563 (:constructor nil)
3564 (:constructor make-js2-unary-node (&key type ; required
3565 (pos js2-ts-cursor)
3566 len operand)))
3567 "AST node type for unary operator nodes.
3568 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3569 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3570 property is added if the operator follows the operand."
3571 operand) ; a `js2-node' expression
3572
3573 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3574 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3575
3576 (defun js2-visit-unary-node (n v)
3577 (js2-visit-ast (js2-unary-node-operand n) v))
3578
3579 (defun js2-print-unary-node (n i)
3580 (let* ((tt (js2-node-type n))
3581 (op (gethash tt js2-operator-tokens))
3582 (postfix (js2-node-get-prop n 'postfix)))
3583 (unless op
3584 (error "unrecognized unary operator %s" tt))
3585 (insert (js2-make-pad i))
3586 (unless postfix
3587 (insert op))
3588 (if (or (= tt js2-TYPEOF)
3589 (= tt js2-DELPROP))
3590 (insert " "))
3591 (js2-print-ast (js2-unary-node-operand n) 0)
3592 (when postfix
3593 (insert op))))
3594
3595 (cl-defstruct (js2-let-node
3596 (:include js2-scope)
3597 (:constructor nil)
3598 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3599 (pos (js2-current-token-beg))
3600 len vars body
3601 lp rp)))
3602 "AST node for a let expression or a let statement.
3603 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3604 vars ; a `js2-var-decl-node'
3605 body ; a `js2-node' representing the expression or body block
3606 lp
3607 rp)
3608
3609 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3610 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3611
3612 (defun js2-visit-let-node (n v)
3613 (js2-visit-ast (js2-let-node-vars n) v)
3614 (js2-visit-ast (js2-let-node-body n) v))
3615
3616 (defun js2-print-let-node (n i)
3617 (insert (js2-make-pad i) "let (")
3618 (let ((p (point)))
3619 (js2-print-ast (js2-let-node-vars n) 0)
3620 (delete-region p (+ p 4)))
3621 (insert ") ")
3622 (js2-print-ast (js2-let-node-body n) i))
3623
3624 (cl-defstruct (js2-keyword-node
3625 (:include js2-node)
3626 (:constructor nil)
3627 (:constructor make-js2-keyword-node (&key type
3628 (pos (js2-current-token-beg))
3629 (len (- js2-ts-cursor pos)))))
3630 "AST node representing a literal keyword such as `null'.
3631 Used for `null', `this', `true', `false' and `debugger'.
3632 The node type is set to js2-NULL, js2-THIS, etc.")
3633
3634 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3635 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3636
3637 (defun js2-print-keyword-node (n i)
3638 (insert (js2-make-pad i)
3639 (let ((tt (js2-node-type n)))
3640 (cond
3641 ((= tt js2-THIS) "this")
3642 ((= tt js2-SUPER) "super")
3643 ((= tt js2-NULL) "null")
3644 ((= tt js2-TRUE) "true")
3645 ((= tt js2-FALSE) "false")
3646 ((= tt js2-DEBUGGER) "debugger")
3647 (t (error "Invalid keyword literal type: %d" tt))))))
3648
3649 (defsubst js2-this-or-super-node-p (node)
3650 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3651 (let ((type (js2-node-type node)))
3652 (or (eq type js2-THIS) (eq type js2-SUPER))))
3653
3654 (cl-defstruct (js2-new-node
3655 (:include js2-node)
3656 (:constructor nil)
3657 (:constructor make-js2-new-node (&key (type js2-NEW)
3658 (pos (js2-current-token-beg))
3659 len target
3660 args initializer
3661 lp rp)))
3662 "AST node for new-expression such as new Foo()."
3663 target ; an identifier or reference
3664 args ; a Lisp list of argument nodes
3665 lp ; position of left-paren, nil if omitted
3666 rp ; position of right-paren, nil if omitted
3667 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3668
3669 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3670 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3671
3672 (defun js2-visit-new-node (n v)
3673 (js2-visit-ast (js2-new-node-target n) v)
3674 (dolist (arg (js2-new-node-args n))
3675 (js2-visit-ast arg v))
3676 (js2-visit-ast (js2-new-node-initializer n) v))
3677
3678 (defun js2-print-new-node (n i)
3679 (insert (js2-make-pad i) "new ")
3680 (js2-print-ast (js2-new-node-target n))
3681 (insert "(")
3682 (js2-print-list (js2-new-node-args n))
3683 (insert ")")
3684 (when (js2-new-node-initializer n)
3685 (insert " ")
3686 (js2-print-ast (js2-new-node-initializer n))))
3687
3688 (cl-defstruct (js2-name-node
3689 (:include js2-node)
3690 (:constructor nil)
3691 (:constructor make-js2-name-node (&key (type js2-NAME)
3692 (pos (js2-current-token-beg))
3693 (len (- js2-ts-cursor
3694 (js2-current-token-beg)))
3695 (name (js2-current-token-string)))))
3696 "AST node for a JavaScript identifier"
3697 name ; a string
3698 scope) ; a `js2-scope' (optional, used for codegen)
3699
3700 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3701 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3702
3703 (defun js2-print-name-node (n i)
3704 (insert (js2-make-pad i)
3705 (js2-name-node-name n)))
3706
3707 (defsubst js2-name-node-length (node)
3708 "Return identifier length of NODE, a `js2-name-node'.
3709 Returns 0 if NODE is nil or its identifier field is nil."
3710 (if node
3711 (length (js2-name-node-name node))
3712 0))
3713
3714 (cl-defstruct (js2-number-node
3715 (:include js2-node)
3716 (:constructor nil)
3717 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3718 (pos (js2-current-token-beg))
3719 (len (- js2-ts-cursor
3720 (js2-current-token-beg)))
3721 (value (js2-current-token-string))
3722 (num-value (js2-token-number
3723 (js2-current-token))))))
3724 "AST node for a number literal."
3725 value ; the original string, e.g. "6.02e23"
3726 num-value) ; the parsed number value
3727
3728 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3729 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3730
3731 (defun js2-print-number-node (n i)
3732 (insert (js2-make-pad i)
3733 (number-to-string (js2-number-node-num-value n))))
3734
3735 (cl-defstruct (js2-regexp-node
3736 (:include js2-node)
3737 (:constructor nil)
3738 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3739 (pos (js2-current-token-beg))
3740 (len (- js2-ts-cursor
3741 (js2-current-token-beg)))
3742 value flags)))
3743 "AST node for a regular expression literal."
3744 value ; the regexp string, without // delimiters
3745 flags) ; a string of flags, e.g. `mi'.
3746
3747 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3748 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3749
3750 (defun js2-print-regexp (n i)
3751 (insert (js2-make-pad i)
3752 "/"
3753 (js2-regexp-node-value n)
3754 "/")
3755 (if (js2-regexp-node-flags n)
3756 (insert (js2-regexp-node-flags n))))
3757
3758 (cl-defstruct (js2-string-node
3759 (:include js2-node)
3760 (:constructor nil)
3761 (:constructor make-js2-string-node (&key (type js2-STRING)
3762 (pos (js2-current-token-beg))
3763 (len (- js2-ts-cursor
3764 (js2-current-token-beg)))
3765 (value (js2-current-token-string)))))
3766 "String literal.
3767 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3768 You can tell the quote type by looking at the first character."
3769 value) ; the characters of the string, including the quotes
3770
3771 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3772 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3773
3774 (defun js2-print-string-node (n i)
3775 (insert (js2-make-pad i)
3776 (js2-node-string n)))
3777
3778 (cl-defstruct (js2-template-node
3779 (:include js2-node)
3780 (:constructor nil)
3781 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3782 beg len kids)))
3783 "Template literal."
3784 kids) ; `js2-string-node' is used for string segments, other nodes
3785 ; for substitutions inside.
3786
3787 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3788 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3789
3790 (defun js2-visit-template (n callback)
3791 (dolist (kid (js2-template-node-kids n))
3792 (js2-visit-ast kid callback)))
3793
3794 (defun js2-print-template (n i)
3795 (insert (js2-make-pad i))
3796 (dolist (kid (js2-template-node-kids n))
3797 (if (js2-string-node-p kid)
3798 (insert (js2-node-string kid))
3799 (js2-print-ast kid))))
3800
3801 (cl-defstruct (js2-tagged-template-node
3802 (:include js2-node)
3803 (:constructor nil)
3804 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3805 beg len tag template)))
3806 "Tagged template literal."
3807 tag ; `js2-node' with the tag expression.
3808 template) ; `js2-template-node' with the template.
3809
3810 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3811 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3812
3813 (defun js2-visit-tagged-template (n callback)
3814 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3815 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3816
3817 (defun js2-print-tagged-template (n i)
3818 (insert (js2-make-pad i))
3819 (js2-print-ast (js2-tagged-template-node-tag n))
3820 (js2-print-ast (js2-tagged-template-node-template n)))
3821
3822 (cl-defstruct (js2-array-node
3823 (:include js2-node)
3824 (:constructor nil)
3825 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3826 (pos js2-ts-cursor)
3827 len elems)))
3828 "AST node for an array literal."
3829 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3830
3831 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3832 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3833
3834 (defun js2-visit-array-node (n v)
3835 (dolist (e (js2-array-node-elems n))
3836 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3837
3838 (defun js2-print-array-node (n i)
3839 (insert (js2-make-pad i) "[")
3840 (let ((elems (js2-array-node-elems n)))
3841 (js2-print-list elems)
3842 (when (and elems (null (car (last elems))))
3843 (insert ",")))
3844 (insert "]"))
3845
3846 (cl-defstruct (js2-class-node
3847 (:include js2-node)
3848 (:constructor nil)
3849 (:constructor make-js2-class-node (&key (type js2-CLASS)
3850 (pos js2-ts-cursor)
3851 (form 'CLASS_STATEMENT)
3852 (name "")
3853 extends len elems)))
3854 "AST node for an class expression.
3855 `elems' is a list of `js2-object-prop-node', and `extends' is an
3856 optional `js2-expr-node'"
3857 form ; CLASS_{STATEMENT|EXPRESSION}
3858 name ; class name (a `js2-node-name', or nil if anonymous)
3859 extends ; class heritage (a `js2-expr-node', or nil if none)
3860 elems)
3861
3862 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3863 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3864
3865 (defun js2-visit-class-node (n v)
3866 (js2-visit-ast (js2-class-node-name n) v)
3867 (js2-visit-ast (js2-class-node-extends n) v)
3868 (dolist (e (js2-class-node-elems n))
3869 (js2-visit-ast e v)))
3870
3871 (defun js2-print-class-node (n i)
3872 (let* ((pad (js2-make-pad i))
3873 (name (js2-class-node-name n))
3874 (extends (js2-class-node-extends n))
3875 (elems (js2-class-node-elems n)))
3876 (insert pad "class")
3877 (when name
3878 (insert " ")
3879 (js2-print-ast name 0))
3880 (when extends
3881 (insert " extends ")
3882 (js2-print-ast extends))
3883 (insert " {")
3884 (dolist (elem elems)
3885 (insert "\n")
3886 (if (js2-node-get-prop elem 'STATIC)
3887 (progn (insert (js2-make-pad (1+ i)) "static ")
3888 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3889 (js2-print-ast elem (1+ i))))
3890 (insert "\n" pad "}")))
3891
3892 (cl-defstruct (js2-object-node
3893 (:include js2-node)
3894 (:constructor nil)
3895 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3896 (pos js2-ts-cursor)
3897 len
3898 elems)))
3899 "AST node for an object literal expression.
3900 `elems' is a list of `js2-object-prop-node'."
3901 elems)
3902
3903 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3904 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3905
3906 (defun js2-visit-object-node (n v)
3907 (dolist (e (js2-object-node-elems n))
3908 (js2-visit-ast e v)))
3909
3910 (defun js2-print-object-node (n i)
3911 (insert (js2-make-pad i) "{")
3912 (js2-print-list (js2-object-node-elems n))
3913 (insert "}"))
3914
3915 (cl-defstruct (js2-object-prop-node
3916 (:include js2-infix-node)
3917 (:constructor nil)
3918 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3919 (pos js2-ts-cursor)
3920 len left
3921 right op-pos)))
3922 "AST node for an object literal prop:value entry.
3923 The `left' field is the property: a name node, string node or number node.
3924 The `right' field is a `js2-node' representing the initializer value.
3925 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3926 and both fields have the same value.")
3927
3928 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3929 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3930
3931 (defun js2-print-object-prop-node (n i)
3932 (let* ((left (js2-object-prop-node-left n))
3933 (computed (not (or (js2-string-node-p left)
3934 (js2-number-node-p left)
3935 (js2-name-node-p left)))))
3936 (insert (js2-make-pad i))
3937 (if computed
3938 (insert "["))
3939 (js2-print-ast left 0)
3940 (if computed
3941 (insert "]"))
3942 (if (not (js2-node-get-prop n 'SHORTHAND))
3943 (progn
3944 (insert ": ")
3945 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3946
3947 (cl-defstruct (js2-getter-setter-node
3948 (:include js2-infix-node)
3949 (:constructor nil)
3950 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3951 (pos js2-ts-cursor)
3952 len left right)))
3953 "AST node for a getter/setter property in an object literal.
3954 The `left' field is the `js2-name-node' naming the getter/setter prop.
3955 The `right' field is always an anonymous `js2-function-node' with a node
3956 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3957
3958 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3959 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3960
3961 (defun js2-print-getter-setter (n i)
3962 (let ((pad (js2-make-pad i))
3963 (left (js2-getter-setter-node-left n))
3964 (right (js2-getter-setter-node-right n)))
3965 (insert pad)
3966 (if (/= (js2-node-type n) js2-FUNCTION)
3967 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3968 (js2-print-ast left 0)
3969 (js2-print-ast right 0)))
3970
3971 (cl-defstruct (js2-prop-get-node
3972 (:include js2-infix-node)
3973 (:constructor nil)
3974 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3975 (pos js2-ts-cursor)
3976 len left right)))
3977 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3978
3979 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3980 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3981
3982 (defun js2-visit-prop-get-node (n v)
3983 (js2-visit-ast (js2-prop-get-node-left n) v)
3984 (js2-visit-ast (js2-prop-get-node-right n) v))
3985
3986 (defun js2-print-prop-get-node (n i)
3987 (insert (js2-make-pad i))
3988 (js2-print-ast (js2-prop-get-node-left n) 0)
3989 (insert ".")
3990 (js2-print-ast (js2-prop-get-node-right n) 0))
3991
3992 (cl-defstruct (js2-elem-get-node
3993 (:include js2-node)
3994 (:constructor nil)
3995 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3996 (pos js2-ts-cursor)
3997 len target element
3998 lb rb)))
3999 "AST node for an array index expression such as foo[bar]."
4000 target ; a `js2-node' - the expression preceding the "."
4001 element ; a `js2-node' - the expression in brackets
4002 lb ; position of left-bracket, nil if omitted
4003 rb) ; position of right-bracket, nil if omitted
4004
4005 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4006 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4007
4008 (defun js2-visit-elem-get-node (n v)
4009 (js2-visit-ast (js2-elem-get-node-target n) v)
4010 (js2-visit-ast (js2-elem-get-node-element n) v))
4011
4012 (defun js2-print-elem-get-node (n i)
4013 (insert (js2-make-pad i))
4014 (js2-print-ast (js2-elem-get-node-target n) 0)
4015 (insert "[")
4016 (js2-print-ast (js2-elem-get-node-element n) 0)
4017 (insert "]"))
4018
4019 (cl-defstruct (js2-call-node
4020 (:include js2-node)
4021 (:constructor nil)
4022 (:constructor make-js2-call-node (&key (type js2-CALL)
4023 (pos js2-ts-cursor)
4024 len target args
4025 lp rp)))
4026 "AST node for a JavaScript function call."
4027 target ; a `js2-node' evaluating to the function to call
4028 args ; a Lisp list of `js2-node' arguments
4029 lp ; position of open-paren, or nil if missing
4030 rp) ; position of close-paren, or nil if missing
4031
4032 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4033 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4034
4035 (defun js2-visit-call-node (n v)
4036 (js2-visit-ast (js2-call-node-target n) v)
4037 (dolist (arg (js2-call-node-args n))
4038 (js2-visit-ast arg v)))
4039
4040 (defun js2-print-call-node (n i)
4041 (insert (js2-make-pad i))
4042 (js2-print-ast (js2-call-node-target n) 0)
4043 (insert "(")
4044 (js2-print-list (js2-call-node-args n))
4045 (insert ")"))
4046
4047 (cl-defstruct (js2-yield-node
4048 (:include js2-node)
4049 (:constructor nil)
4050 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4051 (pos js2-ts-cursor)
4052 len value star-p)))
4053 "AST node for yield statement or expression."
4054 star-p ; whether it's yield*
4055 value) ; optional: value to be yielded
4056
4057 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4058 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4059
4060 (defun js2-visit-yield-node (n v)
4061 (js2-visit-ast (js2-yield-node-value n) v))
4062
4063 (defun js2-print-yield-node (n i)
4064 (insert (js2-make-pad i))
4065 (insert "yield")
4066 (when (js2-yield-node-star-p n)
4067 (insert "*"))
4068 (when (js2-yield-node-value n)
4069 (insert " ")
4070 (js2-print-ast (js2-yield-node-value n) 0)))
4071
4072 (cl-defstruct (js2-paren-node
4073 (:include js2-node)
4074 (:constructor nil)
4075 (:constructor make-js2-paren-node (&key (type js2-LP)
4076 (pos js2-ts-cursor)
4077 len expr)))
4078 "AST node for a parenthesized expression.
4079 In particular, used when the parens are syntactically optional,
4080 as opposed to required parens such as those enclosing an if-conditional."
4081 expr) ; `js2-node'
4082
4083 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4084 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4085
4086 (defun js2-visit-paren-node (n v)
4087 (js2-visit-ast (js2-paren-node-expr n) v))
4088
4089 (defun js2-print-paren-node (n i)
4090 (insert (js2-make-pad i))
4091 (insert "(")
4092 (js2-print-ast (js2-paren-node-expr n) 0)
4093 (insert ")"))
4094
4095 (cl-defstruct (js2-comp-node
4096 (:include js2-scope)
4097 (:constructor nil)
4098 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4099 (pos js2-ts-cursor)
4100 len result
4101 loops filters
4102 form)))
4103 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4104 result ; result expression (just after left-bracket)
4105 loops ; a Lisp list of `js2-comp-loop-node'
4106 filters ; a Lisp list of guard/filter expressions
4107 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4108 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4109 )
4110
4111 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4112 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4113
4114 (defun js2-visit-comp-node (n v)
4115 (js2-visit-ast (js2-comp-node-result n) v)
4116 (dolist (l (js2-comp-node-loops n))
4117 (js2-visit-ast l v))
4118 (dolist (f (js2-comp-node-filters n))
4119 (js2-visit-ast f v)))
4120
4121 (defun js2-print-comp-node (n i)
4122 (let ((pad (js2-make-pad i))
4123 (result (js2-comp-node-result n))
4124 (loops (js2-comp-node-loops n))
4125 (filters (js2-comp-node-filters n))
4126 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4127 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4128 (insert pad (if gen-p "(" "["))
4129 (when legacy-p
4130 (js2-print-ast result 0))
4131 (dolist (l loops)
4132 (when legacy-p
4133 (insert " "))
4134 (js2-print-ast l 0)
4135 (unless legacy-p
4136 (insert " ")))
4137 (dolist (f filters)
4138 (when legacy-p
4139 (insert " "))
4140 (insert "if (")
4141 (js2-print-ast f 0)
4142 (insert ")")
4143 (unless legacy-p
4144 (insert " ")))
4145 (unless legacy-p
4146 (js2-print-ast result 0))
4147 (insert (if gen-p ")" "]"))))
4148
4149 (cl-defstruct (js2-comp-loop-node
4150 (:include js2-for-in-node)
4151 (:constructor nil)
4152 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4153 (pos js2-ts-cursor)
4154 len iterator
4155 object in-pos
4156 foreach-p
4157 each-pos
4158 forof-p
4159 lp rp)))
4160 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4161
4162 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4163 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4164
4165 (defun js2-visit-comp-loop (n v)
4166 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4167 (js2-visit-ast (js2-comp-loop-node-object n) v))
4168
4169 (defun js2-print-comp-loop (n _i)
4170 (insert "for ")
4171 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4172 (insert "(")
4173 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4174 (insert (if (js2-comp-loop-node-forof-p n)
4175 " of " " in "))
4176 (js2-print-ast (js2-comp-loop-node-object n) 0)
4177 (insert ")"))
4178
4179 (cl-defstruct (js2-empty-expr-node
4180 (:include js2-node)
4181 (:constructor nil)
4182 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4183 (pos (js2-current-token-beg))
4184 len)))
4185 "AST node for an empty expression.")
4186
4187 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4188 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4189
4190 (cl-defstruct (js2-xml-node
4191 (:include js2-block-node)
4192 (:constructor nil)
4193 (:constructor make-js2-xml-node (&key (type js2-XML)
4194 (pos (js2-current-token-beg))
4195 len kids)))
4196 "AST node for initial parse of E4X literals.
4197 The kids field is a list of XML fragments, each a `js2-string-node' or
4198 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4199
4200 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4201 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4202
4203 (defun js2-print-xml-node (n i)
4204 (dolist (kid (js2-xml-node-kids n))
4205 (js2-print-ast kid i)))
4206
4207 (cl-defstruct (js2-xml-js-expr-node
4208 (:include js2-xml-node)
4209 (:constructor nil)
4210 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4211 (pos js2-ts-cursor)
4212 len expr)))
4213 "AST node for an embedded JavaScript {expression} in an E4X literal.
4214 The start and end fields correspond to the curly-braces."
4215 expr) ; a `js2-expr-node' of some sort
4216
4217 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4218 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4219
4220 (defun js2-visit-xml-js-expr (n v)
4221 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4222
4223 (defun js2-print-xml-js-expr (n i)
4224 (insert (js2-make-pad i))
4225 (insert "{")
4226 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4227 (insert "}"))
4228
4229 (cl-defstruct (js2-xml-dot-query-node
4230 (:include js2-infix-node)
4231 (:constructor nil)
4232 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4233 (pos js2-ts-cursor)
4234 op-pos len left
4235 right rp)))
4236 "AST node for an E4X foo.(bar) filter expression.
4237 Note that the left-paren is automatically the character immediately
4238 following the dot (.) in the operator. No whitespace is permitted
4239 between the dot and the lp by the scanner."
4240 rp)
4241
4242 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4243 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4244
4245 (defun js2-print-xml-dot-query (n i)
4246 (insert (js2-make-pad i))
4247 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4248 (insert ".(")
4249 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4250 (insert ")"))
4251
4252 (cl-defstruct (js2-xml-ref-node
4253 (:include js2-node)
4254 (:constructor nil)) ; abstract
4255 "Base type for E4X XML attribute-access or property-get expressions.
4256 Such expressions can take a variety of forms. The general syntax has
4257 three parts:
4258
4259 - (optional) an @ (specifying an attribute access)
4260 - (optional) a namespace (a `js2-name-node') and double-colon
4261 - (required) either a `js2-name-node' or a bracketed [expression]
4262
4263 The property-name expressions (examples: ns::name, @name) are
4264 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4265 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4266
4267 This node type (or more specifically, its subclasses) will sometimes
4268 be the right-hand child of a `js2-prop-get-node' or a
4269 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4270 The `js2-xml-ref-node' may also be a standalone primary expression with
4271 no explicit target, which is valid in certain expression contexts such as
4272
4273 company..employee.(@id < 100)
4274
4275 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4276 expression whose parent is a `js2-xml-dot-query-node'."
4277 namespace
4278 at-pos
4279 colon-pos)
4280
4281 (defsubst js2-xml-ref-node-attr-access-p (node)
4282 "Return non-nil if this expression began with an @-token."
4283 (and (numberp (js2-xml-ref-node-at-pos node))
4284 (cl-plusp (js2-xml-ref-node-at-pos node))))
4285
4286 (cl-defstruct (js2-xml-prop-ref-node
4287 (:include js2-xml-ref-node)
4288 (:constructor nil)
4289 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4290 (pos (js2-current-token-beg))
4291 len propname
4292 namespace at-pos
4293 colon-pos)))
4294 "AST node for an E4X XML [expr] property-ref expression.
4295 The JavaScript syntax is an optional @, an optional ns::, and a name.
4296
4297 [ '@' ] [ name '::' ] name
4298
4299 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4300 @ns::*, @*::attr, @*::*, and @*.
4301
4302 The node starts at the @ token, if present. Otherwise it starts at the
4303 namespace name. The node bounds extend through the closing right-bracket,
4304 or if it is missing due to a syntax error, through the end of the index
4305 expression."
4306 propname)
4307
4308 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4309 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4310
4311 (defun js2-visit-xml-prop-ref-node (n v)
4312 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4313 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4314
4315 (defun js2-print-xml-prop-ref-node (n i)
4316 (insert (js2-make-pad i))
4317 (if (js2-xml-ref-node-attr-access-p n)
4318 (insert "@"))
4319 (when (js2-xml-prop-ref-node-namespace n)
4320 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4321 (insert "::"))
4322 (if (js2-xml-prop-ref-node-propname n)
4323 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4324
4325 (cl-defstruct (js2-xml-elem-ref-node
4326 (:include js2-xml-ref-node)
4327 (:constructor nil)
4328 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4329 (pos (js2-current-token-beg))
4330 len expr lb rb
4331 namespace at-pos
4332 colon-pos)))
4333 "AST node for an E4X XML [expr] member-ref expression.
4334 Syntax:
4335
4336 [ '@' ] [ name '::' ] '[' expr ']'
4337
4338 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4339
4340 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4341 is not a legal E4X XML element-ref expression, since it's already used
4342 for standard JavaScript element-get array indexing. Hence, a
4343 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4344 non-nil namespace node, or both.
4345
4346 The node starts at the @ token, if present. Otherwise it starts
4347 at the namespace name. The node bounds extend through the closing
4348 right-bracket, or if it is missing due to a syntax error, through the
4349 end of the index expression."
4350 expr ; the bracketed index expression
4351 lb
4352 rb)
4353
4354 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4355 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4356
4357 (defun js2-visit-xml-elem-ref-node (n v)
4358 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4359 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4360
4361 (defun js2-print-xml-elem-ref-node (n i)
4362 (insert (js2-make-pad i))
4363 (if (js2-xml-ref-node-attr-access-p n)
4364 (insert "@"))
4365 (when (js2-xml-elem-ref-node-namespace n)
4366 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4367 (insert "::"))
4368 (insert "[")
4369 (if (js2-xml-elem-ref-node-expr n)
4370 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4371 (insert "]"))
4372
4373 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4374
4375 (cl-defstruct (js2-xml-start-tag-node
4376 (:include js2-xml-node)
4377 (:constructor nil)
4378 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4379 (pos js2-ts-cursor)
4380 len name attrs kids
4381 empty-p)))
4382 "AST node for an XML start-tag. Not currently used.
4383 The `kids' field is a Lisp list of child content nodes."
4384 name ; a `js2-xml-name-node'
4385 attrs ; a Lisp list of `js2-xml-attr-node'
4386 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4387
4388 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4389 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4390
4391 (defun js2-visit-xml-start-tag (n v)
4392 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4393 (dolist (attr (js2-xml-start-tag-node-attrs n))
4394 (js2-visit-ast attr v))
4395 (js2-visit-block n v))
4396
4397 (defun js2-print-xml-start-tag (n i)
4398 (insert (js2-make-pad i) "<")
4399 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4400 (when (js2-xml-start-tag-node-attrs n)
4401 (insert " ")
4402 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4403 (insert ">"))
4404
4405 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4406 ;; and add the end-tag to the kids list of the parent as well.
4407 (cl-defstruct (js2-xml-end-tag-node
4408 (:include js2-xml-node)
4409 (:constructor nil)
4410 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4411 (pos js2-ts-cursor)
4412 len name)))
4413 "AST node for an XML end-tag. Not currently used."
4414 name) ; a `js2-xml-name-node'
4415
4416 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4417 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4418
4419 (defun js2-visit-xml-end-tag (n v)
4420 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4421
4422 (defun js2-print-xml-end-tag (n i)
4423 (insert (js2-make-pad i))
4424 (insert "</")
4425 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4426 (insert ">"))
4427
4428 (cl-defstruct (js2-xml-name-node
4429 (:include js2-xml-node)
4430 (:constructor nil)
4431 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4432 (pos js2-ts-cursor)
4433 len namespace kids)))
4434 "AST node for an E4X XML name. Not currently used.
4435 Any XML name can be qualified with a namespace, hence the namespace field.
4436 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4437 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4438 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4439 namespace) ; a `js2-string-node'
4440
4441 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4442 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4443
4444 (defun js2-visit-xml-name-node (n v)
4445 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4446
4447 (defun js2-print-xml-name-node (n i)
4448 (insert (js2-make-pad i))
4449 (when (js2-xml-name-node-namespace n)
4450 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4451 (insert "::"))
4452 (dolist (kid (js2-xml-name-node-kids n))
4453 (js2-print-ast kid 0)))
4454
4455 (cl-defstruct (js2-xml-pi-node
4456 (:include js2-xml-node)
4457 (:constructor nil)
4458 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4459 (pos js2-ts-cursor)
4460 len name attrs)))
4461 "AST node for an E4X XML processing instruction. Not currently used."
4462 name ; a `js2-xml-name-node'
4463 attrs) ; a list of `js2-xml-attr-node'
4464
4465 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4466 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4467
4468 (defun js2-visit-xml-pi-node (n v)
4469 (js2-visit-ast (js2-xml-pi-node-name n) v)
4470 (dolist (attr (js2-xml-pi-node-attrs n))
4471 (js2-visit-ast attr v)))
4472
4473 (defun js2-print-xml-pi-node (n i)
4474 (insert (js2-make-pad i) "<?")
4475 (js2-print-ast (js2-xml-pi-node-name n))
4476 (when (js2-xml-pi-node-attrs n)
4477 (insert " ")
4478 (js2-print-list (js2-xml-pi-node-attrs n)))
4479 (insert "?>"))
4480
4481 (cl-defstruct (js2-xml-cdata-node
4482 (:include js2-xml-node)
4483 (:constructor nil)
4484 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4485 (pos js2-ts-cursor)
4486 len content)))
4487 "AST node for a CDATA escape section. Not currently used."
4488 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4489
4490 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4491 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4492
4493 (defun js2-visit-xml-cdata-node (n v)
4494 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4495
4496 (defun js2-print-xml-cdata-node (n i)
4497 (insert (js2-make-pad i))
4498 (js2-print-ast (js2-xml-cdata-node-content n)))
4499
4500 (cl-defstruct (js2-xml-attr-node
4501 (:include js2-xml-node)
4502 (:constructor nil)
4503 (:constructor make-js2-attr-node (&key (type js2-XML)
4504 (pos js2-ts-cursor)
4505 len name value
4506 eq-pos quote-type)))
4507 "AST node representing a foo='bar' XML attribute value. Not yet used."
4508 name ; a `js2-xml-name-node'
4509 value ; a `js2-xml-name-node'
4510 eq-pos ; buffer position of "=" sign
4511 quote-type) ; 'single or 'double
4512
4513 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4514 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4515
4516 (defun js2-visit-xml-attr-node (n v)
4517 (js2-visit-ast (js2-xml-attr-node-name n) v)
4518 (js2-visit-ast (js2-xml-attr-node-value n) v))
4519
4520 (defun js2-print-xml-attr-node (n i)
4521 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4522 "'"
4523 "\"")))
4524 (insert (js2-make-pad i))
4525 (js2-print-ast (js2-xml-attr-node-name n) 0)
4526 (insert "=" quote)
4527 (js2-print-ast (js2-xml-attr-node-value n) 0)
4528 (insert quote)))
4529
4530 (cl-defstruct (js2-xml-text-node
4531 (:include js2-xml-node)
4532 (:constructor nil)
4533 (:constructor make-js2-text-node (&key (type js2-XML)
4534 (pos js2-ts-cursor)
4535 len content)))
4536 "AST node for an E4X XML text node. Not currently used."
4537 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4538
4539 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4540 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4541
4542 (defun js2-visit-xml-text-node (n v)
4543 (js2-visit-ast (js2-xml-text-node-content n) v))
4544
4545 (defun js2-print-xml-text-node (n i)
4546 (insert (js2-make-pad i))
4547 (dolist (kid (js2-xml-text-node-content n))
4548 (js2-print-ast kid)))
4549
4550 (cl-defstruct (js2-xml-comment-node
4551 (:include js2-xml-node)
4552 (:constructor nil)
4553 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4554 (pos js2-ts-cursor)
4555 len)))
4556 "AST node for E4X XML comment. Not currently used.")
4557
4558 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4559 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4560
4561 (defun js2-print-xml-comment (n i)
4562 (insert (js2-make-pad i)
4563 (js2-node-string n)))
4564
4565 ;;; Node utilities
4566
4567 (defsubst js2-node-line (n)
4568 "Fetch the source line number at the start of node N.
4569 This is O(n) in the length of the source buffer; use prudently."
4570 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4571
4572 (defsubst js2-block-node-kid (n i)
4573 "Return child I of node N, or nil if there aren't that many."
4574 (nth i (js2-block-node-kids n)))
4575
4576 (defsubst js2-block-node-first (n)
4577 "Return first child of block node N, or nil if there is none."
4578 (cl-first (js2-block-node-kids n)))
4579
4580 (defun js2-node-root (n)
4581 "Return the root of the AST containing N.
4582 If N has no parent pointer, returns N."
4583 (let ((parent (js2-node-parent n)))
4584 (if parent
4585 (js2-node-root parent)
4586 n)))
4587
4588 (defsubst js2-node-short-name (n)
4589 "Return the short name of node N as a string, e.g. `js2-if-node'."
4590 (substring (symbol-name (aref n 0))
4591 (length "cl-struct-")))
4592
4593 (defun js2-node-child-list (node)
4594 "Return the child list for NODE, a Lisp list of nodes.
4595 Works for block nodes, array nodes, obj literals, funarg lists,
4596 var decls and try nodes (for catch clauses). Note that you should call
4597 `js2-block-node-kids' on the function body for the body statements.
4598 Returns nil for zero-length child lists or unsupported nodes."
4599 (cond
4600 ((js2-function-node-p node)
4601 (js2-function-node-params node))
4602 ((js2-block-node-p node)
4603 (js2-block-node-kids node))
4604 ((js2-try-node-p node)
4605 (js2-try-node-catch-clauses node))
4606 ((js2-array-node-p node)
4607 (js2-array-node-elems node))
4608 ((js2-object-node-p node)
4609 (js2-object-node-elems node))
4610 ((js2-call-node-p node)
4611 (js2-call-node-args node))
4612 ((js2-new-node-p node)
4613 (js2-new-node-args node))
4614 ((js2-var-decl-node-p node)
4615 (js2-var-decl-node-kids node))
4616 (t
4617 nil)))
4618
4619 (defun js2-node-set-child-list (node kids)
4620 "Set the child list for NODE to KIDS."
4621 (cond
4622 ((js2-function-node-p node)
4623 (setf (js2-function-node-params node) kids))
4624 ((js2-block-node-p node)
4625 (setf (js2-block-node-kids node) kids))
4626 ((js2-try-node-p node)
4627 (setf (js2-try-node-catch-clauses node) kids))
4628 ((js2-array-node-p node)
4629 (setf (js2-array-node-elems node) kids))
4630 ((js2-object-node-p node)
4631 (setf (js2-object-node-elems node) kids))
4632 ((js2-call-node-p node)
4633 (setf (js2-call-node-args node) kids))
4634 ((js2-new-node-p node)
4635 (setf (js2-new-node-args node) kids))
4636 ((js2-var-decl-node-p node)
4637 (setf (js2-var-decl-node-kids node) kids))
4638 (t
4639 (error "Unsupported node type: %s" (js2-node-short-name node))))
4640 kids)
4641
4642 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4643 (defconst js2-paren-expr-nodes
4644 '(cl-struct-js2-comp-loop-node
4645 cl-struct-js2-comp-node
4646 cl-struct-js2-call-node
4647 cl-struct-js2-catch-node
4648 cl-struct-js2-do-node
4649 cl-struct-js2-elem-get-node
4650 cl-struct-js2-for-in-node
4651 cl-struct-js2-for-node
4652 cl-struct-js2-function-node
4653 cl-struct-js2-if-node
4654 cl-struct-js2-let-node
4655 cl-struct-js2-new-node
4656 cl-struct-js2-paren-node
4657 cl-struct-js2-switch-node
4658 cl-struct-js2-while-node
4659 cl-struct-js2-with-node
4660 cl-struct-js2-xml-dot-query-node)
4661 "Node types that can have a parenthesized child expression.
4662 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4663
4664 (defsubst js2-paren-expr-node-p (node)
4665 "Return t for nodes that typically have a parenthesized child expression.
4666 Useful for computing the indentation anchors for arg-lists and conditions.
4667 Note that it may return a false positive, for instance when NODE is
4668 a `js2-new-node' and there are no arguments or parentheses."
4669 (memq (aref node 0) js2-paren-expr-nodes))
4670
4671 ;; Fake polymorphism... yech.
4672 (defun js2-node-lp (node)
4673 "Return relative left-paren position for NODE, if applicable.
4674 For `js2-elem-get-node' structs, returns left-bracket position.
4675 Note that the position may be nil in the case of a parse error."
4676 (cond
4677 ((js2-elem-get-node-p node)
4678 (js2-elem-get-node-lb node))
4679 ((js2-loop-node-p node)
4680 (js2-loop-node-lp node))
4681 ((js2-function-node-p node)
4682 (js2-function-node-lp node))
4683 ((js2-if-node-p node)
4684 (js2-if-node-lp node))
4685 ((js2-new-node-p node)
4686 (js2-new-node-lp node))
4687 ((js2-call-node-p node)
4688 (js2-call-node-lp node))
4689 ((js2-paren-node-p node)
4690 0)
4691 ((js2-switch-node-p node)
4692 (js2-switch-node-lp node))
4693 ((js2-catch-node-p node)
4694 (js2-catch-node-lp node))
4695 ((js2-let-node-p node)
4696 (js2-let-node-lp node))
4697 ((js2-comp-node-p node)
4698 0)
4699 ((js2-with-node-p node)
4700 (js2-with-node-lp node))
4701 ((js2-xml-dot-query-node-p node)
4702 (1+ (js2-infix-node-op-pos node)))
4703 (t
4704 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4705
4706 ;; Fake polymorphism... blech.
4707 (defun js2-node-rp (node)
4708 "Return relative right-paren position for NODE, if applicable.
4709 For `js2-elem-get-node' structs, returns right-bracket position.
4710 Note that the position may be nil in the case of a parse error."
4711 (cond
4712 ((js2-elem-get-node-p node)
4713 (js2-elem-get-node-rb node))
4714 ((js2-loop-node-p node)
4715 (js2-loop-node-rp node))
4716 ((js2-function-node-p node)
4717 (js2-function-node-rp node))
4718 ((js2-if-node-p node)
4719 (js2-if-node-rp node))
4720 ((js2-new-node-p node)
4721 (js2-new-node-rp node))
4722 ((js2-call-node-p node)
4723 (js2-call-node-rp node))
4724 ((js2-paren-node-p node)
4725 (1- (js2-node-len node)))
4726 ((js2-switch-node-p node)
4727 (js2-switch-node-rp node))
4728 ((js2-catch-node-p node)
4729 (js2-catch-node-rp node))
4730 ((js2-let-node-p node)
4731 (js2-let-node-rp node))
4732 ((js2-comp-node-p node)
4733 (1- (js2-node-len node)))
4734 ((js2-with-node-p node)
4735 (js2-with-node-rp node))
4736 ((js2-xml-dot-query-node-p node)
4737 (1+ (js2-xml-dot-query-node-rp node)))
4738 (t
4739 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4740
4741 (defsubst js2-node-first-child (node)
4742 "Return the first element of `js2-node-child-list' for NODE."
4743 (car (js2-node-child-list node)))
4744
4745 (defsubst js2-node-last-child (node)
4746 "Return the last element of `js2-node-last-child' for NODE."
4747 (car (last (js2-node-child-list node))))
4748
4749 (defun js2-node-prev-sibling (node)
4750 "Return the previous statement in parent.
4751 Works for parents supported by `js2-node-child-list'.
4752 Returns nil if NODE is not in the parent, or PARENT is
4753 not a supported node, or if NODE is the first child."
4754 (let* ((p (js2-node-parent node))
4755 (kids (js2-node-child-list p))
4756 (sib (car kids)))
4757 (while (and kids
4758 (not (eq node (cadr kids))))
4759 (setq kids (cdr kids)
4760 sib (car kids)))
4761 sib))
4762
4763 (defun js2-node-next-sibling (node)
4764 "Return the next statement in parent block.
4765 Returns nil if NODE is not in the block, or PARENT is not
4766 a block node, or if NODE is the last statement."
4767 (let* ((p (js2-node-parent node))
4768 (kids (js2-node-child-list p)))
4769 (while (and kids
4770 (not (eq node (car kids))))
4771 (setq kids (cdr kids)))
4772 (cadr kids)))
4773
4774 (defun js2-node-find-child-before (pos parent &optional after)
4775 "Find the last child that starts before POS in parent.
4776 If AFTER is non-nil, returns first child starting after POS.
4777 POS is an absolute buffer position. PARENT is any node
4778 supported by `js2-node-child-list'.
4779 Returns nil if no applicable child is found."
4780 (let ((kids (if (js2-function-node-p parent)
4781 (js2-block-node-kids (js2-function-node-body parent))
4782 (js2-node-child-list parent)))
4783 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4784 (js2-function-node-body parent)
4785 parent)))
4786 kid result fn
4787 (continue t))
4788 (setq fn (if after '>= '<))
4789 (while (and kids continue)
4790 (setq kid (car kids))
4791 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4792 (setq result kid
4793 continue (not after))
4794 (setq continue after))
4795 (setq kids (cdr kids)))
4796 result))
4797
4798 (defun js2-node-find-child-after (pos parent)
4799 "Find first child that starts after POS in parent.
4800 POS is an absolute buffer position. PARENT is any node
4801 supported by `js2-node-child-list'.
4802 Returns nil if no applicable child is found."
4803 (js2-node-find-child-before pos parent 'after))
4804
4805 (defun js2-node-replace-child (pos parent new-node)
4806 "Replace node at index POS in PARENT with NEW-NODE.
4807 Only works for parents supported by `js2-node-child-list'."
4808 (let ((kids (js2-node-child-list parent))
4809 (i 0))
4810 (while (< i pos)
4811 (setq kids (cdr kids)
4812 i (1+ i)))
4813 (setcar kids new-node)
4814 (js2-node-add-children parent new-node)))
4815
4816 (defun js2-node-buffer (n)
4817 "Return the buffer associated with AST N.
4818 Returns nil if the buffer is not set as a property on the root
4819 node, or if parent links were not recorded during parsing."
4820 (let ((root (js2-node-root n)))
4821 (and root
4822 (js2-ast-root-p root)
4823 (js2-ast-root-buffer root))))
4824
4825 (defun js2-block-node-push (n kid)
4826 "Push js2-node KID onto the end of js2-block-node N's child list.
4827 KID is always added to the -end- of the kids list.
4828 Function also calls `js2-node-add-children' to add the parent link."
4829 (let ((kids (js2-node-child-list n)))
4830 (if kids
4831 (setcdr kids (nconc (cdr kids) (list kid)))
4832 (js2-node-set-child-list n (list kid)))
4833 (js2-node-add-children n kid)))
4834
4835 (defun js2-node-string (node)
4836 (with-current-buffer (or (js2-node-buffer node)
4837 (error "No buffer available for node %s" node))
4838 (let ((pos (js2-node-abs-pos node)))
4839 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4840
4841 ;; Container for storing the node we're looking for in a traversal.
4842 (js2-deflocal js2-discovered-node nil)
4843
4844 ;; Keep track of absolute node position during traversals.
4845 (js2-deflocal js2-visitor-offset nil)
4846
4847 (js2-deflocal js2-node-search-point nil)
4848
4849 (when js2-mode-dev-mode-p
4850 (defun js2-find-node-at-point ()
4851 (interactive)
4852 (let ((node (js2-node-at-point)))
4853 (message "%s" (or node "No node found at point"))))
4854 (defun js2-node-name-at-point ()
4855 (interactive)
4856 (let ((node (js2-node-at-point)))
4857 (message "%s" (if node
4858 (js2-node-short-name node)
4859 "No node found at point.")))))
4860
4861 (defun js2-node-at-point (&optional pos skip-comments)
4862 "Return AST node at POS, a buffer position, defaulting to current point.
4863 The `js2-mode-ast' variable must be set to the current parse tree.
4864 Signals an error if the AST (`js2-mode-ast') is nil.
4865 Always returns a node - if it can't find one, it returns the root.
4866 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4867 (let ((ast js2-mode-ast)
4868 result)
4869 (unless ast
4870 (error "No JavaScript AST available"))
4871 ;; Look through comments first, since they may be inside nodes that
4872 ;; would otherwise report a match.
4873 (setq pos (or pos (point))
4874 result (if (> pos (js2-node-abs-end ast))
4875 ast
4876 (if (not skip-comments)
4877 (js2-comment-at-point pos))))
4878 (unless result
4879 (setq js2-discovered-node nil
4880 js2-visitor-offset 0
4881 js2-node-search-point pos)
4882 (unwind-protect
4883 (catch 'js2-visit-done
4884 (js2-visit-ast ast #'js2-node-at-point-visitor))
4885 (setq js2-visitor-offset nil
4886 js2-node-search-point nil))
4887 (setq result js2-discovered-node))
4888 ;; may have found a comment beyond end of last child node,
4889 ;; since visiting the ast-root looks at the comment-list last.
4890 (if (and skip-comments
4891 (js2-comment-node-p result))
4892 (setq result nil))
4893 (or result js2-mode-ast)))
4894
4895 (defun js2-node-at-point-visitor (node end-p)
4896 (let ((rel-pos (js2-node-pos node))
4897 abs-pos
4898 abs-end
4899 (point js2-node-search-point))
4900 (cond
4901 (end-p
4902 ;; this evaluates to a non-nil return value, even if it's zero
4903 (cl-decf js2-visitor-offset rel-pos))
4904 ;; we already looked for comments before visiting, and don't want them now
4905 ((js2-comment-node-p node)
4906 nil)
4907 (t
4908 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4909 ;; we only want to use the node if the point is before
4910 ;; the last character position in the node, so we decrement
4911 ;; the absolute end by 1.
4912 abs-end (+ abs-pos (js2-node-len node) -1))
4913 (cond
4914 ;; If this node starts after search-point, stop the search.
4915 ((> abs-pos point)
4916 (throw 'js2-visit-done nil))
4917 ;; If this node ends before the search-point, don't check kids.
4918 ((> point abs-end)
4919 nil)
4920 (t
4921 ;; Otherwise point is within this node, possibly in a child.
4922 (setq js2-discovered-node node)
4923 t)))))) ; keep processing kids to look for more specific match
4924
4925 (defsubst js2-block-comment-p (node)
4926 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4927 (and (js2-comment-node-p node)
4928 (memq (js2-comment-node-format node) '(jsdoc block))))
4929
4930 ;; TODO: put the comments in a vector and binary-search them instead
4931 (defun js2-comment-at-point (&optional pos)
4932 "Look through scanned comment nodes for one containing POS.
4933 POS is a buffer position that defaults to current point.
4934 Function returns nil if POS was not in any comment node."
4935 (let ((ast js2-mode-ast)
4936 (x (or pos (point)))
4937 beg end)
4938 (unless ast
4939 (error "No JavaScript AST available"))
4940 (catch 'done
4941 ;; Comments are stored in lexical order.
4942 (dolist (comment (js2-ast-root-comments ast) nil)
4943 (setq beg (js2-node-abs-pos comment)
4944 end (+ beg (js2-node-len comment)))
4945 (if (and (>= x beg)
4946 (<= x end))
4947 (throw 'done comment))))))
4948
4949 (defun js2-mode-find-parent-fn (node)
4950 "Find function enclosing NODE.
4951 Returns nil if NODE is not inside a function."
4952 (setq node (js2-node-parent node))
4953 (while (and node (not (js2-function-node-p node)))
4954 (setq node (js2-node-parent node)))
4955 (and (js2-function-node-p node) node))
4956
4957 (defun js2-mode-find-enclosing-fn (node)
4958 "Find function or root enclosing NODE."
4959 (if (js2-ast-root-p node)
4960 node
4961 (setq node (js2-node-parent node))
4962 (while (not (or (js2-ast-root-p node)
4963 (js2-function-node-p node)))
4964 (setq node (js2-node-parent node)))
4965 node))
4966
4967 (defun js2-mode-find-enclosing-node (beg end)
4968 "Find node fully enclosing BEG and END."
4969 (let ((node (js2-node-at-point beg))
4970 pos
4971 (continue t))
4972 (while continue
4973 (if (or (js2-ast-root-p node)
4974 (and
4975 (<= (setq pos (js2-node-abs-pos node)) beg)
4976 (>= (+ pos (js2-node-len node)) end)))
4977 (setq continue nil)
4978 (setq node (js2-node-parent node))))
4979 node))
4980
4981 (defun js2-node-parent-script-or-fn (node)
4982 "Find script or function immediately enclosing NODE.
4983 If NODE is the ast-root, returns nil."
4984 (if (js2-ast-root-p node)
4985 nil
4986 (setq node (js2-node-parent node))
4987 (while (and node (not (or (js2-function-node-p node)
4988 (js2-script-node-p node))))
4989 (setq node (js2-node-parent node)))
4990 node))
4991
4992 (defun js2-node-is-descendant (node ancestor)
4993 "Return t if NODE is a descendant of ANCESTOR."
4994 (while (and node
4995 (not (eq node ancestor)))
4996 (setq node (js2-node-parent node)))
4997 node)
4998
4999 ;;; visitor infrastructure
5000
5001 (defun js2-visit-none (_node _callback)
5002 "Visitor for AST node that have no node children."
5003 nil)
5004
5005 (defun js2-print-none (_node _indent)
5006 "Visitor for AST node with no printed representation.")
5007
5008 (defun js2-print-body (node indent)
5009 "Print a statement, or a block without braces."
5010 (if (js2-block-node-p node)
5011 (dolist (kid (js2-block-node-kids node))
5012 (js2-print-ast kid indent))
5013 (js2-print-ast node indent)))
5014
5015 (defun js2-print-list (args &optional delimiter)
5016 (cl-loop with len = (length args)
5017 for arg in args
5018 for count from 1
5019 do
5020 (when arg (js2-print-ast arg 0))
5021 (if (< count len)
5022 (insert (or delimiter ", ")))))
5023
5024 (defun js2-print-tree (ast)
5025 "Prints an AST to the current buffer.
5026 Makes `js2-ast-parent-nodes' available to the printer functions."
5027 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5028 (js2-print-ast ast)))
5029
5030 (defun js2-print-ast (node &optional indent)
5031 "Helper function for printing AST nodes.
5032 Requires `js2-ast-parent-nodes' to be non-nil.
5033 You should use `js2-print-tree' instead of this function."
5034 (let ((printer (get (aref node 0) 'js2-printer))
5035 (i (or indent 0)))
5036 ;; TODO: wedge comments in here somewhere
5037 (if printer
5038 (funcall printer node i))))
5039
5040 (defconst js2-side-effecting-tokens
5041 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5042 (dolist (tt (list js2-ASSIGN
5043 js2-ASSIGN_ADD
5044 js2-ASSIGN_BITAND
5045 js2-ASSIGN_BITOR
5046 js2-ASSIGN_BITXOR
5047 js2-ASSIGN_DIV
5048 js2-ASSIGN_LSH
5049 js2-ASSIGN_MOD
5050 js2-ASSIGN_MUL
5051 js2-ASSIGN_RSH
5052 js2-ASSIGN_SUB
5053 js2-ASSIGN_URSH
5054 js2-BLOCK
5055 js2-BREAK
5056 js2-CALL
5057 js2-CATCH
5058 js2-CATCH_SCOPE
5059 js2-CLASS
5060 js2-CONST
5061 js2-CONTINUE
5062 js2-DEBUGGER
5063 js2-DEC
5064 js2-DELPROP
5065 js2-DEL_REF
5066 js2-DO
5067 js2-ELSE
5068 js2-EMPTY
5069 js2-ENTERWITH
5070 js2-EXPORT
5071 js2-EXPR_RESULT
5072 js2-FINALLY
5073 js2-FOR
5074 js2-FUNCTION
5075 js2-GOTO
5076 js2-IF
5077 js2-IFEQ
5078 js2-IFNE
5079 js2-IMPORT
5080 js2-INC
5081 js2-JSR
5082 js2-LABEL
5083 js2-LEAVEWITH
5084 js2-LET
5085 js2-LETEXPR
5086 js2-LOCAL_BLOCK
5087 js2-LOOP
5088 js2-NEW
5089 js2-REF_CALL
5090 js2-RETHROW
5091 js2-RETURN
5092 js2-RETURN_RESULT
5093 js2-SEMI
5094 js2-SETELEM
5095 js2-SETELEM_OP
5096 js2-SETNAME
5097 js2-SETPROP
5098 js2-SETPROP_OP
5099 js2-SETVAR
5100 js2-SET_REF
5101 js2-SET_REF_OP
5102 js2-SWITCH
5103 js2-TARGET
5104 js2-THROW
5105 js2-TRY
5106 js2-VAR
5107 js2-WHILE
5108 js2-WITH
5109 js2-WITHEXPR
5110 js2-YIELD))
5111 (aset tokens tt t))
5112 (if js2-instanceof-has-side-effects
5113 (aset tokens js2-INSTANCEOF t))
5114 tokens))
5115
5116 (defun js2-node-has-side-effects (node)
5117 "Return t if NODE has side effects."
5118 (when node ; makes it easier to handle malformed expressions
5119 (let ((tt (js2-node-type node)))
5120 (cond
5121 ;; This doubtless needs some work, since EXPR_VOID is used
5122 ;; in several ways in Rhino and I may not have caught them all.
5123 ;; I'll wait for people to notice incorrect warnings.
5124 ((and (= tt js2-EXPR_VOID)
5125 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5126 (let ((expr (js2-expr-stmt-node-expr node)))
5127 (or (js2-node-has-side-effects expr)
5128 (when (js2-string-node-p expr)
5129 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5130 ((= tt js2-COMMA)
5131 (js2-node-has-side-effects (js2-infix-node-right node)))
5132 ((or (= tt js2-AND)
5133 (= tt js2-OR))
5134 (or (js2-node-has-side-effects (js2-infix-node-right node))
5135 (js2-node-has-side-effects (js2-infix-node-left node))))
5136 ((= tt js2-HOOK)
5137 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5138 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5139 ((js2-paren-node-p node)
5140 (js2-node-has-side-effects (js2-paren-node-expr node)))
5141 ((= tt js2-ERROR) ; avoid cascaded error messages
5142 nil)
5143 (t
5144 (aref js2-side-effecting-tokens tt))))))
5145
5146 (defconst js2-stmt-node-types
5147 (list js2-BLOCK
5148 js2-BREAK
5149 js2-CONTINUE
5150 js2-DEFAULT ; e4x "default xml namespace" statement
5151 js2-DO
5152 js2-EXPORT
5153 js2-EXPR_RESULT
5154 js2-EXPR_VOID
5155 js2-FOR
5156 js2-IF
5157 js2-IMPORT
5158 js2-RETURN
5159 js2-SWITCH
5160 js2-THROW
5161 js2-TRY
5162 js2-WHILE
5163 js2-WITH)
5164 "Node types that only appear in statement contexts.
5165 The list does not include nodes that always appear as the child
5166 of another specific statement type, such as switch-cases,
5167 catch and finally blocks, and else-clauses. The list also excludes
5168 nodes like yield, let and var, which may appear in either expression
5169 or statement context, and in the latter context always have a
5170 `js2-expr-stmt-node' parent. Finally, the list does not include
5171 functions or scripts, which are treated separately from statements
5172 by the JavaScript parser and runtime.")
5173
5174 (defun js2-stmt-node-p (node)
5175 "Heuristic for figuring out if NODE is a statement.
5176 Some node types can appear in either an expression context or a
5177 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5178 For these node types in a statement context, the parent will be a
5179 `js2-expr-stmt-node'.
5180 Functions aren't included in the check."
5181 (memq (js2-node-type node) js2-stmt-node-types))
5182
5183 (defun js2-mode-find-first-stmt (node)
5184 "Search upward starting from NODE looking for a statement.
5185 For purposes of this function, a `js2-function-node' counts."
5186 (while (not (or (js2-stmt-node-p node)
5187 (js2-function-node-p node)))
5188 (setq node (js2-node-parent node)))
5189 node)
5190
5191 (defun js2-node-parent-stmt (node)
5192 "Return the node's first ancestor that is a statement.
5193 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5194 appearing in a statement context will have a parent that is a
5195 `js2-expr-stmt-node' that will be returned by this function."
5196 (let ((parent (js2-node-parent node)))
5197 (if (or (null parent)
5198 (js2-stmt-node-p parent)
5199 (and (js2-function-node-p parent)
5200 (not (eq (js2-function-node-form parent)
5201 'FUNCTION_EXPRESSION))))
5202 parent
5203 (js2-node-parent-stmt parent))))
5204
5205 ;; In the Mozilla Rhino sources, Roshan James writes:
5206 ;; Does consistent-return analysis on the function body when strict mode is
5207 ;; enabled.
5208 ;;
5209 ;; function (x) { return (x+1) }
5210 ;;
5211 ;; is ok, but
5212 ;;
5213 ;; function (x) { if (x < 0) return (x+1); }
5214 ;;
5215 ;; is not because the function can potentially return a value when the
5216 ;; condition is satisfied and if not, the function does not explicitly
5217 ;; return a value.
5218 ;;
5219 ;; This extends to checking mismatches such as "return" and "return <value>"
5220 ;; used in the same function. Warnings are not emitted if inconsistent
5221 ;; returns exist in code that can be statically shown to be unreachable.
5222 ;; Ex.
5223 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5224 ;;
5225 ;; emits no warning. However if the loop had a break statement, then a
5226 ;; warning would be emitted.
5227 ;;
5228 ;; The consistency analysis looks at control structures such as loops, ifs,
5229 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5230 ;; warns the user about an inconsistent set of termination possibilities.
5231 ;;
5232 ;; These flags enumerate the possible ways a statement/function can
5233 ;; terminate. These flags are used by endCheck() and by the Parser to
5234 ;; detect inconsistent return usage.
5235 ;;
5236 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5237 ;; able to execute (example: throw, continue)
5238 ;;
5239 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5240 ;; next one. Statement such as return dont. A compound statement may have
5241 ;; some branch that drops off control to the next statement.
5242 ;;
5243 ;; END_RETURNS indicates that the statement can return with no value.
5244 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5245 ;;
5246 ;; A compound statement such as
5247 ;; if (condition) {
5248 ;; return value;
5249 ;; }
5250 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5251
5252 (defconst js2-END_UNREACHED 0)
5253 (defconst js2-END_DROPS_OFF 1)
5254 (defconst js2-END_RETURNS 2)
5255 (defconst js2-END_RETURNS_VALUE 4)
5256 (defconst js2-END_YIELDS 8)
5257
5258 (defun js2-has-consistent-return-usage (node)
5259 "Check that every return usage in a function body is consistent.
5260 Returns t if the function satisfies strict mode requirement."
5261 (let ((n (js2-end-check node)))
5262 ;; either it doesn't return a value in any branch...
5263 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5264 ;; or it returns a value (or is unreached) at every branch
5265 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5266 js2-END_RETURNS
5267 js2-END_YIELDS)))))
5268
5269 (defun js2-end-check-if (node)
5270 "Ensure that return usage in then/else blocks is consistent.
5271 If there is no else block, then the return statement can fall through.
5272 Returns logical OR of END_* flags"
5273 (let ((th (js2-if-node-then-part node))
5274 (el (js2-if-node-else-part node)))
5275 (if (null th)
5276 js2-END_UNREACHED
5277 (logior (js2-end-check th) (if el
5278 (js2-end-check el)
5279 js2-END_DROPS_OFF)))))
5280
5281 (defun js2-end-check-switch (node)
5282 "Consistency of return statements is checked between the case statements.
5283 If there is no default, then the switch can fall through. If there is a
5284 default, we check to see if all code paths in the default return or if
5285 there is a code path that can fall through.
5286 Returns logical OR of END_* flags."
5287 (let ((rv js2-END_UNREACHED)
5288 default-case)
5289 ;; examine the cases
5290 (catch 'break
5291 (dolist (c (js2-switch-node-cases node))
5292 (if (js2-case-node-expr c)
5293 (js2-set-flag rv (js2-end-check-block c))
5294 (setq default-case c)
5295 (throw 'break nil))))
5296 ;; we don't care how the cases drop into each other
5297 (js2-clear-flag rv js2-END_DROPS_OFF)
5298 ;; examine the default
5299 (js2-set-flag rv (if default-case
5300 (js2-end-check default-case)
5301 js2-END_DROPS_OFF))
5302 rv))
5303
5304 (defun js2-end-check-try (node)
5305 "If the block has a finally, return consistency is checked in the
5306 finally block. If all code paths in the finally return, then the
5307 returns in the try-catch blocks don't matter. If there is a code path
5308 that does not return or if there is no finally block, the returns
5309 of the try and catch blocks are checked for mismatch.
5310 Returns logical OR of END_* flags."
5311 (let ((finally (js2-try-node-finally-block node))
5312 rv)
5313 ;; check the finally if it exists
5314 (setq rv (if finally
5315 (js2-end-check (js2-finally-node-body finally))
5316 js2-END_DROPS_OFF))
5317 ;; If the finally block always returns, then none of the returns
5318 ;; in the try or catch blocks matter.
5319 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5320 (js2-clear-flag rv js2-END_DROPS_OFF)
5321 ;; examine the try block
5322 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5323 ;; check each catch block
5324 (dolist (cb (js2-try-node-catch-clauses node))
5325 (js2-set-flag rv (js2-end-check cb))))
5326 rv))
5327
5328 (defun js2-end-check-loop (node)
5329 "Return statement in the loop body must be consistent.
5330 The default assumption for any kind of a loop is that it will eventually
5331 terminate. The only exception is a loop with a constant true condition.
5332 Code that follows such a loop is examined only if one can determine
5333 statically that there is a break out of the loop.
5334
5335 for(... ; ... ; ...) {}
5336 for(... in ... ) {}
5337 while(...) { }
5338 do { } while(...)
5339
5340 Returns logical OR of END_* flags."
5341 (let ((rv (js2-end-check (js2-loop-node-body node)))
5342 (condition (cond
5343 ((js2-while-node-p node)
5344 (js2-while-node-condition node))
5345 ((js2-do-node-p node)
5346 (js2-do-node-condition node))
5347 ((js2-for-node-p node)
5348 (js2-for-node-condition node)))))
5349
5350 ;; check to see if the loop condition is always true
5351 (if (and condition
5352 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5353 (js2-clear-flag rv js2-END_DROPS_OFF))
5354
5355 ;; look for effect of breaks
5356 (js2-set-flag rv (js2-node-get-prop node
5357 'CONTROL_BLOCK_PROP
5358 js2-END_UNREACHED))
5359 rv))
5360
5361 (defun js2-end-check-block (node)
5362 "A general block of code is examined statement by statement.
5363 If any statement (even a compound one) returns in all branches, then
5364 subsequent statements are not examined.
5365 Returns logical OR of END_* flags."
5366 (let* ((rv js2-END_DROPS_OFF)
5367 (kids (js2-block-node-kids node))
5368 (n (car kids)))
5369 ;; Check each statment. If the statement can continue onto the next
5370 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5371 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5372 (js2-clear-flag rv js2-END_DROPS_OFF)
5373 (js2-set-flag rv (js2-end-check n))
5374 (setq kids (cdr kids)
5375 n (car kids)))
5376 rv))
5377
5378 (defun js2-end-check-label (node)
5379 "A labeled statement implies that there may be a break to the label.
5380 The function processes the labeled statement and then checks the
5381 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5382 particular label.
5383 Returns logical OR of END_* flags."
5384 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5385 (logior rv (js2-node-get-prop node
5386 'CONTROL_BLOCK_PROP
5387 js2-END_UNREACHED))))
5388
5389 (defun js2-end-check-break (node)
5390 "When a break is encountered annotate the statement being broken
5391 out of by setting its CONTROL_BLOCK_PROP property.
5392 Returns logical OR of END_* flags."
5393 (and (js2-break-node-target node)
5394 (js2-node-set-prop (js2-break-node-target node)
5395 'CONTROL_BLOCK_PROP
5396 js2-END_DROPS_OFF))
5397 js2-END_UNREACHED)
5398
5399 (defun js2-end-check (node)
5400 "Examine the body of a function, doing a basic reachability analysis.
5401 Returns a combination of flags END_* flags that indicate
5402 how the function execution can terminate. These constitute only the
5403 pessimistic set of termination conditions. It is possible that at
5404 runtime certain code paths will never be actually taken. Hence this
5405 analysis will flag errors in cases where there may not be errors.
5406 Returns logical OR of END_* flags"
5407 (let (kid)
5408 (cond
5409 ((js2-break-node-p node)
5410 (js2-end-check-break node))
5411 ((js2-expr-stmt-node-p node)
5412 (if (setq kid (js2-expr-stmt-node-expr node))
5413 (js2-end-check kid)
5414 js2-END_DROPS_OFF))
5415 ((or (js2-continue-node-p node)
5416 (js2-throw-node-p node))
5417 js2-END_UNREACHED)
5418 ((js2-return-node-p node)
5419 (if (setq kid (js2-return-node-retval node))
5420 js2-END_RETURNS_VALUE
5421 js2-END_RETURNS))
5422 ((js2-loop-node-p node)
5423 (js2-end-check-loop node))
5424 ((js2-switch-node-p node)
5425 (js2-end-check-switch node))
5426 ((js2-labeled-stmt-node-p node)
5427 (js2-end-check-label node))
5428 ((js2-if-node-p node)
5429 (js2-end-check-if node))
5430 ((js2-try-node-p node)
5431 (js2-end-check-try node))
5432 ((js2-block-node-p node)
5433 (if (null (js2-block-node-kids node))
5434 js2-END_DROPS_OFF
5435 (js2-end-check-block node)))
5436 ((js2-yield-node-p node)
5437 js2-END_YIELDS)
5438 (t
5439 js2-END_DROPS_OFF))))
5440
5441 (defun js2-always-defined-boolean-p (node)
5442 "Check if NODE always evaluates to true or false in boolean context.
5443 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5444 nor always false."
5445 (let ((tt (js2-node-type node))
5446 num)
5447 (cond
5448 ((or (= tt js2-FALSE) (= tt js2-NULL))
5449 'ALWAYS_FALSE)
5450 ((= tt js2-TRUE)
5451 'ALWAYS_TRUE)
5452 ((= tt js2-NUMBER)
5453 (setq num (js2-number-node-num-value node))
5454 (if (and (not (eq num 0.0e+NaN))
5455 (not (zerop num)))
5456 'ALWAYS_TRUE
5457 'ALWAYS_FALSE))
5458 (t
5459 nil))))
5460
5461 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5462 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5463
5464 (defvar js2-tokens nil
5465 "List of all defined token names.") ; initialized in `js2-token-names'
5466
5467 (defconst js2-token-names
5468 (let* ((names (make-vector js2-num-tokens -1))
5469 (case-fold-search nil) ; only match js2-UPPER_CASE
5470 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5471 (cl-loop for sym in syms
5472 for i from 0
5473 do
5474 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5475 (not (boundp sym)))
5476 (aset names (symbol-value sym) ; code, e.g. 152
5477 (downcase
5478 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5479 (push sym js2-tokens)))
5480 names)
5481 "Vector mapping int values to token string names, sans `js2-' prefix.")
5482
5483 (defun js2-tt-name (tok)
5484 "Return a string name for TOK, a token symbol or code.
5485 Signals an error if it's not a recognized token."
5486 (let ((code tok))
5487 (if (symbolp tok)
5488 (setq code (symbol-value tok)))
5489 (if (eq code -1)
5490 "ERROR"
5491 (if (and (numberp code)
5492 (not (cl-minusp code))
5493 (< code js2-num-tokens))
5494 (aref js2-token-names code)
5495 (error "Invalid token: %s" code)))))
5496
5497 (defsubst js2-tt-sym (tok)
5498 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5499 (intern (js2-tt-name tok)))
5500
5501 (defconst js2-token-codes
5502 (let ((table (make-hash-table :test 'eq :size 256)))
5503 (cl-loop for name across js2-token-names
5504 for sym = (intern (concat "js2-" (upcase name)))
5505 do
5506 (puthash sym (symbol-value sym) table))
5507 ;; clean up a few that are "wrong" in Rhino's token codes
5508 (puthash 'js2-DELETE js2-DELPROP table)
5509 table)
5510 "Hashtable mapping token type symbols to their bytecodes.")
5511
5512 (defsubst js2-tt-code (sym)
5513 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5514 (or (gethash sym js2-token-codes)
5515 (error "Invalid token symbol: %s " sym))) ; signal code bug
5516
5517 (defun js2-report-scan-error (msg &optional no-throw beg len)
5518 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5519 (js2-report-error msg nil
5520 (or beg (js2-current-token-beg))
5521 (or len (js2-current-token-len)))
5522 (unless no-throw
5523 (throw 'return js2-ERROR)))
5524
5525 (defun js2-set-string-from-buffer (token)
5526 "Set `string' and `end' slots for TOKEN, return the string."
5527 (setf (js2-token-end token) js2-ts-cursor
5528 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5529
5530 ;; TODO: could potentially avoid a lot of consing by allocating a
5531 ;; char buffer the way Rhino does.
5532 (defsubst js2-add-to-string (c)
5533 (push c js2-ts-string-buffer))
5534
5535 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5536 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5537 ;; any other character: when it's not part of the current token, we
5538 ;; unget it, allowing it to be read again by the following call.
5539 (defsubst js2-unget-char ()
5540 (cl-decf js2-ts-cursor))
5541
5542 ;; Rhino distinguishes \r and \n line endings. We don't need to
5543 ;; because we only scan from Emacs buffers, which always use \n.
5544 (defun js2-get-char ()
5545 "Read and return the next character from the input buffer.
5546 Increments `js2-ts-lineno' if the return value is a newline char.
5547 Updates `js2-ts-cursor' to the point after the returned char.
5548 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5549 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5550 (let (c)
5551 ;; check for end of buffer
5552 (if (>= js2-ts-cursor (point-max))
5553 (setq js2-ts-hit-eof t
5554 js2-ts-cursor (1+ js2-ts-cursor)
5555 c js2-EOF_CHAR) ; return value
5556 ;; otherwise read next char
5557 (setq c (char-before (cl-incf js2-ts-cursor)))
5558 ;; if we read a newline, update counters
5559 (if (= c ?\n)
5560 (setq js2-ts-line-start js2-ts-cursor
5561 js2-ts-lineno (1+ js2-ts-lineno)))
5562 ;; TODO: skip over format characters
5563 c)))
5564
5565 (defun js2-read-unicode-escape ()
5566 "Read a \\uNNNN sequence from the input.
5567 Assumes the ?\ and ?u have already been read.
5568 Returns the unicode character, or nil if it wasn't a valid character.
5569 Doesn't change the values of any scanner variables."
5570 ;; I really wish I knew a better way to do this, but I can't
5571 ;; find the Emacs function that takes a 16-bit int and converts
5572 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5573 ;; Have to first check that it's 4 hex characters or it may stop
5574 ;; the read early.
5575 (ignore-errors
5576 (let ((s (buffer-substring-no-properties js2-ts-cursor
5577 (+ 4 js2-ts-cursor))))
5578 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5579 (read (concat "?\\u" s))))))
5580
5581 (defun js2-match-char (test)
5582 "Consume and return next character if it matches TEST, a character.
5583 Returns nil and consumes nothing if TEST is not the next character."
5584 (let ((c (js2-get-char)))
5585 (if (eq c test)
5586 t
5587 (js2-unget-char)
5588 nil)))
5589
5590 (defun js2-peek-char ()
5591 (prog1
5592 (js2-get-char)
5593 (js2-unget-char)))
5594
5595 (defun js2-identifier-start-p (c)
5596 "Is C a valid start to an ES5 Identifier?
5597 See http://es5.github.io/#x7.6"
5598 (or
5599 (memq c '(?$ ?_))
5600 (memq (get-char-code-property c 'general-category)
5601 ;; Letters
5602 '(Lu Ll Lt Lm Lo Nl))))
5603
5604 (defun js2-identifier-part-p (c)
5605 "Is C a valid part of an ES5 Identifier?
5606 See http://es5.github.io/#x7.6"
5607 (or
5608 (memq c '(?$ ?_ ?\u200c ?\u200d))
5609 (memq (get-char-code-property c 'general-category)
5610 '(;; Letters
5611 Lu Ll Lt Lm Lo Nl
5612 ;; Combining Marks
5613 Mn Mc
5614 ;; Digits
5615 Nd
5616 ;; Connector Punctuation
5617 Pc))))
5618
5619 (defun js2-alpha-p (c)
5620 (cond ((and (<= ?A c) (<= c ?Z)) t)
5621 ((and (<= ?a c) (<= c ?z)) t)
5622 (t nil)))
5623
5624 (defsubst js2-digit-p (c)
5625 (and (<= ?0 c) (<= c ?9)))
5626
5627 (defun js2-js-space-p (c)
5628 (if (<= c 127)
5629 (memq c '(#x20 #x9 #xB #xC #xD))
5630 (or
5631 (eq c #xA0)
5632 ;; TODO: change this nil to check for Unicode space character
5633 nil)))
5634
5635 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5636
5637 (defun js2-skip-line ()
5638 "Skip to end of line."
5639 (while (not (memq (js2-get-char) js2-eol-chars)))
5640 (js2-unget-char)
5641 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5642
5643 (defun js2-init-scanner (&optional buf line)
5644 "Create token stream for BUF starting on LINE.
5645 BUF defaults to `current-buffer' and LINE defaults to 1.
5646
5647 A buffer can only have one scanner active at a time, which yields
5648 dramatically simpler code than using a defstruct. If you need to
5649 have simultaneous scanners in a buffer, copy the regions to scan
5650 into temp buffers."
5651 (with-current-buffer (or buf (current-buffer))
5652 (setq js2-ts-dirty-line nil
5653 js2-ts-hit-eof nil
5654 js2-ts-line-start 0
5655 js2-ts-lineno (or line 1)
5656 js2-ts-line-end-char -1
5657 js2-ts-cursor (point-min)
5658 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5659 js2-ti-tokens-cursor 0
5660 js2-ti-lookahead 0
5661 js2-ts-is-xml-attribute nil
5662 js2-ts-xml-is-tag-content nil
5663 js2-ts-xml-open-tags-count 0
5664 js2-ts-string-buffer nil)))
5665
5666 ;; This function uses the cached op, string and number fields in
5667 ;; TokenStream; if getToken has been called since the passed token
5668 ;; was scanned, the op or string printed may be incorrect.
5669 (defun js2-token-to-string (token)
5670 ;; Not sure where this function is used in Rhino. Not tested.
5671 (if (not js2-debug-print-trees)
5672 ""
5673 (let ((name (js2-tt-name token)))
5674 (cond
5675 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5676 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5677 (concat name " `" (js2-current-token-string) "'"))
5678 ((eq token js2-NUMBER)
5679 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5680 (t
5681 name)))))
5682
5683 (defconst js2-keywords
5684 '(break
5685 case catch class const continue
5686 debugger default delete do
5687 else extends export
5688 false finally for function
5689 if in instanceof import
5690 let
5691 new null
5692 return
5693 static super switch
5694 this throw true try typeof
5695 var void
5696 while with
5697 yield))
5698
5699 ;; Token names aren't exactly the same as the keywords, unfortunately.
5700 ;; E.g. delete is js2-DELPROP.
5701 (defconst js2-kwd-tokens
5702 (let ((table (make-vector js2-num-tokens nil))
5703 (tokens
5704 (list js2-BREAK
5705 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5706 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5707 js2-ELSE js2-EXPORT
5708 js2-ELSE js2-EXTENDS js2-EXPORT
5709 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5710 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5711 js2-LET
5712 js2-NEW js2-NULL
5713 js2-RETURN
5714 js2-STATIC js2-SUPER js2-SWITCH
5715 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5716 js2-VAR
5717 js2-WHILE js2-WITH
5718 js2-YIELD)))
5719 (dolist (i tokens)
5720 (aset table i 'font-lock-keyword-face))
5721 (aset table js2-STRING 'font-lock-string-face)
5722 (aset table js2-REGEXP 'font-lock-string-face)
5723 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5724 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5725 (aset table js2-COMMENT 'font-lock-comment-face)
5726 (aset table js2-THIS 'font-lock-builtin-face)
5727 (aset table js2-SUPER 'font-lock-builtin-face)
5728 (aset table js2-VOID 'font-lock-constant-face)
5729 (aset table js2-NULL 'font-lock-constant-face)
5730 (aset table js2-TRUE 'font-lock-constant-face)
5731 (aset table js2-FALSE 'font-lock-constant-face)
5732 (aset table js2-NOT 'font-lock-negation-char-face)
5733 table)
5734 "Vector whose values are non-nil for tokens that are keywords.
5735 The values are default faces to use for highlighting the keywords.")
5736
5737 ;; FIXME: Support strict mode-only future reserved words, after we know
5738 ;; which parts scopes are in strict mode, and which are not.
5739 (defconst js2-reserved-words '(class enum export extends import super)
5740 "Future reserved keywords in ECMAScript 5.1.")
5741
5742 (defconst js2-keyword-names
5743 (let ((table (make-hash-table :test 'equal)))
5744 (cl-loop for k in js2-keywords
5745 do (puthash
5746 (symbol-name k) ; instanceof
5747 (intern (concat "js2-"
5748 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5749 table))
5750 table)
5751 "JavaScript keywords by name, mapped to their symbols.")
5752
5753 (defconst js2-reserved-word-names
5754 (let ((table (make-hash-table :test 'equal)))
5755 (cl-loop for k in js2-reserved-words
5756 do
5757 (puthash (symbol-name k) 'js2-RESERVED table))
5758 table)
5759 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5760
5761 (defun js2-collect-string (buf)
5762 "Convert BUF, a list of chars, to a string.
5763 Reverses BUF before converting."
5764 (if buf
5765 (apply #'string (nreverse buf))
5766 ""))
5767
5768 (defun js2-string-to-keyword (s)
5769 "Return token for S, a string, if S is a keyword or reserved word.
5770 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5771 (or (gethash s js2-keyword-names)
5772 (gethash s js2-reserved-word-names)))
5773
5774 (defsubst js2-ts-set-char-token-bounds (token)
5775 "Used when next token is one character."
5776 (setf (js2-token-beg token) (1- js2-ts-cursor)
5777 (js2-token-end token) js2-ts-cursor))
5778
5779 (defsubst js2-ts-return (token type)
5780 "Update the `end' and `type' slots of TOKEN,
5781 then throw `return' with value TYPE."
5782 (setf (js2-token-end token) js2-ts-cursor
5783 (js2-token-type token) type)
5784 (throw 'return type))
5785
5786 (defun js2-x-digit-to-int (c accumulator)
5787 "Build up a hex number.
5788 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5789 corresponding number. Otherwise return -1."
5790 (catch 'return
5791 (catch 'check
5792 ;; Use 0..9 < A..Z < a..z
5793 (cond
5794 ((<= c ?9)
5795 (cl-decf c ?0)
5796 (if (<= 0 c)
5797 (throw 'check nil)))
5798 ((<= c ?F)
5799 (when (<= ?A c)
5800 (cl-decf c (- ?A 10))
5801 (throw 'check nil)))
5802 ((<= c ?f)
5803 (when (<= ?a c)
5804 (cl-decf c (- ?a 10))
5805 (throw 'check nil))))
5806 (throw 'return -1))
5807 (logior c (lsh accumulator 4))))
5808
5809 (defun js2-get-token (&optional modifier)
5810 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5811 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5812 next saved token.
5813
5814 This function will not return a newline (js2-EOL) - instead, it
5815 gobbles newlines until it finds a non-newline token. Call
5816 `js2-peek-token-or-eol' when you care about newlines.
5817
5818 This function will also not return a js2-COMMENT. Instead, it
5819 records comments found in `js2-scanned-comments'. If the token
5820 returned by this function immediately follows a jsdoc comment,
5821 the token is flagged as such."
5822 (if (zerop js2-ti-lookahead)
5823 (js2-get-token-internal modifier)
5824 (cl-decf js2-ti-lookahead)
5825 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5826 (let ((tt (js2-current-token-type)))
5827 (cl-assert (not (= tt js2-EOL)))
5828 tt)))
5829
5830 (defun js2-unget-token ()
5831 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5832 (cl-incf js2-ti-lookahead)
5833 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5834
5835 (defun js2-get-token-internal (modifier)
5836 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5837 (tt (js2-token-type token))
5838 saw-eol
5839 face)
5840 ;; process comments
5841 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5842 (if (= tt js2-EOL)
5843 (setq saw-eol t)
5844 (setq saw-eol nil)
5845 (when js2-record-comments
5846 (js2-record-comment token)))
5847 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5848 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5849 tt (js2-token-type token)))
5850
5851 (when saw-eol
5852 (setf (js2-token-follows-eol-p token) t))
5853
5854 ;; perform lexical fontification as soon as token is scanned
5855 (when js2-parse-ide-mode
5856 (cond
5857 ((cl-minusp tt)
5858 (js2-record-face 'js2-error token))
5859 ((setq face (aref js2-kwd-tokens tt))
5860 (js2-record-face face token))
5861 ((and (= tt js2-NAME)
5862 (equal (js2-token-string token) "undefined"))
5863 (js2-record-face 'font-lock-constant-face token))))
5864 tt))
5865
5866 (defsubst js2-string-to-number (str base)
5867 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5868 (condition-case nil
5869 (string-to-number str base)
5870 (overflow-error -1)))
5871
5872 (defun js2-get-token-internal-1 (modifier)
5873 "Return next JavaScript token type, an int such as js2-RETURN.
5874 During operation, creates an instance of `js2-token' struct, sets
5875 its relevant fields and puts it into `js2-ti-tokens'."
5876 (let (identifier-start
5877 is-unicode-escape-start c
5878 contains-escape escape-val str result base
5879 quote-char look-for-slash continue tt
5880 (token (js2-new-token 0)))
5881 (setq
5882 tt
5883 (catch 'return
5884 (when (eq modifier 'TEMPLATE_TAIL)
5885 (setf (js2-token-beg token) (1- js2-ts-cursor))
5886 (throw 'return (js2-get-string-or-template-token ?` token)))
5887 (while t
5888 ;; Eat whitespace, possibly sensitive to newlines.
5889 (setq continue t)
5890 (while continue
5891 (setq c (js2-get-char))
5892 (cond
5893 ((eq c js2-EOF_CHAR)
5894 (js2-unget-char)
5895 (js2-ts-set-char-token-bounds token)
5896 (throw 'return js2-EOF))
5897 ((eq c ?\n)
5898 (js2-ts-set-char-token-bounds token)
5899 (setq js2-ts-dirty-line nil)
5900 (throw 'return js2-EOL))
5901 ((not (js2-js-space-p c))
5902 (if (/= c ?-) ; in case end of HTML comment
5903 (setq js2-ts-dirty-line t))
5904 (setq continue nil))))
5905 ;; Assume the token will be 1 char - fixed up below.
5906 (js2-ts-set-char-token-bounds token)
5907 (when (eq c ?@)
5908 (throw 'return js2-XMLATTR))
5909 ;; identifier/keyword/instanceof?
5910 ;; watch out for starting with a <backslash>
5911 (cond
5912 ((eq c ?\\)
5913 (setq c (js2-get-char))
5914 (if (eq c ?u)
5915 (setq identifier-start t
5916 is-unicode-escape-start t
5917 js2-ts-string-buffer nil)
5918 (setq identifier-start nil)
5919 (js2-unget-char)
5920 (setq c ?\\)))
5921 (t
5922 (when (setq identifier-start (js2-identifier-start-p c))
5923 (setq js2-ts-string-buffer nil)
5924 (js2-add-to-string c))))
5925 (when identifier-start
5926 (setq contains-escape is-unicode-escape-start)
5927 (catch 'break
5928 (while t
5929 (if is-unicode-escape-start
5930 ;; strictly speaking we should probably push-back
5931 ;; all the bad characters if the <backslash>uXXXX
5932 ;; sequence is malformed. But since there isn't a
5933 ;; correct context(is there?) for a bad Unicode
5934 ;; escape sequence in an identifier, we can report
5935 ;; an error here.
5936 (progn
5937 (setq escape-val 0)
5938 (dotimes (_ 4)
5939 (setq c (js2-get-char)
5940 escape-val (js2-x-digit-to-int c escape-val))
5941 ;; Next check takes care of c < 0 and bad escape
5942 (if (cl-minusp escape-val)
5943 (throw 'break nil)))
5944 (if (cl-minusp escape-val)
5945 (js2-report-scan-error "msg.invalid.escape" t))
5946 (js2-add-to-string escape-val)
5947 (setq is-unicode-escape-start nil))
5948 (setq c (js2-get-char))
5949 (cond
5950 ((eq c ?\\)
5951 (setq c (js2-get-char))
5952 (if (eq c ?u)
5953 (setq is-unicode-escape-start t
5954 contains-escape t)
5955 (js2-report-scan-error "msg.illegal.character" t)))
5956 (t
5957 (if (or (eq c js2-EOF_CHAR)
5958 (not (js2-identifier-part-p c)))
5959 (throw 'break nil))
5960 (js2-add-to-string c))))))
5961 (js2-unget-char)
5962 (setf str (js2-collect-string js2-ts-string-buffer)
5963 (js2-token-end token) js2-ts-cursor)
5964 ;; FIXME: Invalid in ES5 and ES6, see
5965 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5966 ;; Probably should just drop this conditional.
5967 (unless contains-escape
5968 ;; OPT we shouldn't have to make a string (object!) to
5969 ;; check if it's a keyword.
5970 ;; Return the corresponding token if it's a keyword
5971 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5972 (setq result (js2-string-to-keyword str)))
5973 (if (and (< js2-language-version 170)
5974 (memq result '(js2-LET js2-YIELD)))
5975 ;; LET and YIELD are tokens only in 1.7 and later
5976 (setq result 'js2-NAME))
5977 (when (eq result 'js2-RESERVED)
5978 (setf (js2-token-string token) str))
5979 (throw 'return (js2-tt-code result))))
5980 ;; If we want to intern these as Rhino does, just use (intern str)
5981 (setf (js2-token-string token) str)
5982 (throw 'return js2-NAME)) ; end identifier/kwd check
5983 ;; is it a number?
5984 (when (or (js2-digit-p c)
5985 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5986 (setq js2-ts-string-buffer nil
5987 base 10)
5988 (when (eq c ?0)
5989 (setq c (js2-get-char))
5990 (cond
5991 ((or (eq c ?x) (eq c ?X))
5992 (setq base 16)
5993 (setq c (js2-get-char)))
5994 ((and (or (eq c ?b) (eq c ?B))
5995 (>= js2-language-version 200))
5996 (setq base 2)
5997 (setq c (js2-get-char)))
5998 ((and (or (eq c ?o) (eq c ?O))
5999 (>= js2-language-version 200))
6000 (setq base 8)
6001 (setq c (js2-get-char)))
6002 ((js2-digit-p c)
6003 (setq base 'maybe-8))
6004 (t
6005 (js2-add-to-string ?0))))
6006 (cond
6007 ((eq base 16)
6008 (if (> 0 (js2-x-digit-to-int c 0))
6009 (js2-report-scan-error "msg.missing.hex.digits")
6010 (while (<= 0 (js2-x-digit-to-int c 0))
6011 (js2-add-to-string c)
6012 (setq c (js2-get-char)))))
6013 ((eq base 2)
6014 (if (not (memq c '(?0 ?1)))
6015 (js2-report-scan-error "msg.missing.binary.digits")
6016 (while (memq c '(?0 ?1))
6017 (js2-add-to-string c)
6018 (setq c (js2-get-char)))))
6019 ((eq base 8)
6020 (if (or (> ?0 c) (< ?7 c))
6021 (js2-report-scan-error "msg.missing.octal.digits")
6022 (while (and (<= ?0 c) (>= ?7 c))
6023 (js2-add-to-string c)
6024 (setq c (js2-get-char)))))
6025 (t
6026 (while (and (<= ?0 c) (<= c ?9))
6027 ;; We permit 08 and 09 as decimal numbers, which
6028 ;; makes our behavior a superset of the ECMA
6029 ;; numeric grammar. We might not always be so
6030 ;; permissive, so we warn about it.
6031 (when (and (eq base 'maybe-8) (>= c ?8))
6032 (js2-report-warning "msg.bad.octal.literal"
6033 (if (eq c ?8) "8" "9"))
6034 (setq base 10))
6035 (js2-add-to-string c)
6036 (setq c (js2-get-char)))
6037 (when (eq base 'maybe-8)
6038 (setq base 8))))
6039 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6040 (when (eq c ?.)
6041 (cl-loop do
6042 (js2-add-to-string c)
6043 (setq c (js2-get-char))
6044 while (js2-digit-p c)))
6045 (when (memq c '(?e ?E))
6046 (js2-add-to-string c)
6047 (setq c (js2-get-char))
6048 (when (memq c '(?+ ?-))
6049 (js2-add-to-string c)
6050 (setq c (js2-get-char)))
6051 (unless (js2-digit-p c)
6052 (js2-report-scan-error "msg.missing.exponent" t))
6053 (cl-loop do
6054 (js2-add-to-string c)
6055 (setq c (js2-get-char))
6056 while (js2-digit-p c))))
6057 (js2-unget-char)
6058 (let ((str (js2-set-string-from-buffer token)))
6059 (setf (js2-token-number token)
6060 (js2-string-to-number str base)))
6061 (throw 'return js2-NUMBER))
6062 ;; is it a string?
6063 (when (or (memq c '(?\" ?\'))
6064 (and (>= js2-language-version 200)
6065 (= c ?`)))
6066 (throw 'return
6067 (js2-get-string-or-template-token c token)))
6068 (js2-ts-return token
6069 (cl-case c
6070 (?\;
6071 (throw 'return js2-SEMI))
6072 (?\[
6073 (throw 'return js2-LB))
6074 (?\]
6075 (throw 'return js2-RB))
6076 (?{
6077 (throw 'return js2-LC))
6078 (?}
6079 (throw 'return js2-RC))
6080 (?\(
6081 (throw 'return js2-LP))
6082 (?\)
6083 (throw 'return js2-RP))
6084 (?,
6085 (throw 'return js2-COMMA))
6086 (??
6087 (throw 'return js2-HOOK))
6088 (?:
6089 (if (js2-match-char ?:)
6090 js2-COLONCOLON
6091 (throw 'return js2-COLON)))
6092 (?.
6093 (if (js2-match-char ?.)
6094 (if (js2-match-char ?.)
6095 js2-TRIPLEDOT js2-DOTDOT)
6096 (if (js2-match-char ?\()
6097 js2-DOTQUERY
6098 (throw 'return js2-DOT))))
6099 (?|
6100 (if (js2-match-char ?|)
6101 (throw 'return js2-OR)
6102 (if (js2-match-char ?=)
6103 js2-ASSIGN_BITOR
6104 (throw 'return js2-BITOR))))
6105 (?^
6106 (if (js2-match-char ?=)
6107 js2-ASSIGN_BITOR
6108 (throw 'return js2-BITXOR)))
6109 (?&
6110 (if (js2-match-char ?&)
6111 (throw 'return js2-AND)
6112 (if (js2-match-char ?=)
6113 js2-ASSIGN_BITAND
6114 (throw 'return js2-BITAND))))
6115 (?=
6116 (if (js2-match-char ?=)
6117 (if (js2-match-char ?=)
6118 js2-SHEQ
6119 (throw 'return js2-EQ))
6120 (if (js2-match-char ?>)
6121 (js2-ts-return token js2-ARROW)
6122 (throw 'return js2-ASSIGN))))
6123 (?!
6124 (if (js2-match-char ?=)
6125 (if (js2-match-char ?=)
6126 js2-SHNE
6127 js2-NE)
6128 (throw 'return js2-NOT)))
6129 (?<
6130 ;; NB:treat HTML begin-comment as comment-till-eol
6131 (when (js2-match-char ?!)
6132 (when (js2-match-char ?-)
6133 (when (js2-match-char ?-)
6134 (js2-skip-line)
6135 (setf (js2-token-comment-type (js2-current-token)) 'html)
6136 (throw 'return js2-COMMENT)))
6137 (js2-unget-char))
6138 (if (js2-match-char ?<)
6139 (if (js2-match-char ?=)
6140 js2-ASSIGN_LSH
6141 js2-LSH)
6142 (if (js2-match-char ?=)
6143 js2-LE
6144 (throw 'return js2-LT))))
6145 (?>
6146 (if (js2-match-char ?>)
6147 (if (js2-match-char ?>)
6148 (if (js2-match-char ?=)
6149 js2-ASSIGN_URSH
6150 js2-URSH)
6151 (if (js2-match-char ?=)
6152 js2-ASSIGN_RSH
6153 js2-RSH))
6154 (if (js2-match-char ?=)
6155 js2-GE
6156 (throw 'return js2-GT))))
6157 (?*
6158 (if (js2-match-char ?=)
6159 js2-ASSIGN_MUL
6160 (throw 'return js2-MUL)))
6161 (?/
6162 ;; is it a // comment?
6163 (when (js2-match-char ?/)
6164 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6165 (js2-skip-line)
6166 (setf (js2-token-comment-type token) 'line)
6167 ;; include newline so highlighting goes to end of window
6168 (cl-incf (js2-token-end token))
6169 (throw 'return js2-COMMENT))
6170 ;; is it a /* comment?
6171 (when (js2-match-char ?*)
6172 (setf look-for-slash nil
6173 (js2-token-beg token) (- js2-ts-cursor 2)
6174 (js2-token-comment-type token)
6175 (if (js2-match-char ?*)
6176 (progn
6177 (setq look-for-slash t)
6178 'jsdoc)
6179 'block))
6180 (while t
6181 (setq c (js2-get-char))
6182 (cond
6183 ((eq c js2-EOF_CHAR)
6184 (setf (js2-token-end token) (1- js2-ts-cursor))
6185 (js2-report-error "msg.unterminated.comment")
6186 (throw 'return js2-COMMENT))
6187 ((eq c ?*)
6188 (setq look-for-slash t))
6189 ((eq c ?/)
6190 (if look-for-slash
6191 (js2-ts-return token js2-COMMENT)))
6192 (t
6193 (setf look-for-slash nil
6194 (js2-token-end token) js2-ts-cursor)))))
6195 (if (js2-match-char ?=)
6196 js2-ASSIGN_DIV
6197 (throw 'return js2-DIV)))
6198 (?#
6199 (when js2-skip-preprocessor-directives
6200 (js2-skip-line)
6201 (setf (js2-token-comment-type token) 'preprocessor
6202 (js2-token-end token) js2-ts-cursor)
6203 (throw 'return js2-COMMENT))
6204 (throw 'return js2-ERROR))
6205 (?%
6206 (if (js2-match-char ?=)
6207 js2-ASSIGN_MOD
6208 (throw 'return js2-MOD)))
6209 (?~
6210 (throw 'return js2-BITNOT))
6211 (?+
6212 (if (js2-match-char ?=)
6213 js2-ASSIGN_ADD
6214 (if (js2-match-char ?+)
6215 js2-INC
6216 (throw 'return js2-ADD))))
6217 (?-
6218 (cond
6219 ((js2-match-char ?=)
6220 (setq c js2-ASSIGN_SUB))
6221 ((js2-match-char ?-)
6222 (unless js2-ts-dirty-line
6223 ;; treat HTML end-comment after possible whitespace
6224 ;; after line start as comment-until-eol
6225 (when (js2-match-char ?>)
6226 (js2-skip-line)
6227 (setf (js2-token-comment-type (js2-current-token)) 'html)
6228 (throw 'return js2-COMMENT)))
6229 (setq c js2-DEC))
6230 (t
6231 (setq c js2-SUB)))
6232 (setq js2-ts-dirty-line t)
6233 c)
6234 (otherwise
6235 (js2-report-scan-error "msg.illegal.character")))))))
6236 (setf (js2-token-type token) tt)
6237 token))
6238
6239 (defun js2-get-string-or-template-token (quote-char token)
6240 ;; We attempt to accumulate a string the fast way, by
6241 ;; building it directly out of the reader. But if there
6242 ;; are any escaped characters in the string, we revert to
6243 ;; building it out of a string buffer.
6244 (let ((c (js2-get-char))
6245 js2-ts-string-buffer
6246 nc c1 val escape-val)
6247 (catch 'break
6248 (while (/= c quote-char)
6249 (catch 'continue
6250 (when (eq c js2-EOF_CHAR)
6251 (js2-unget-char)
6252 (js2-report-error "msg.unterminated.string.lit")
6253 (throw 'break nil))
6254 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6255 (js2-unget-char)
6256 (js2-report-error "msg.unterminated.string.lit")
6257 (throw 'break nil))
6258 (when (eq c ?\\)
6259 ;; We've hit an escaped character
6260 (setq c (js2-get-char))
6261 (cl-case c
6262 (?b (setq c ?\b))
6263 (?f (setq c ?\f))
6264 (?n (setq c ?\n))
6265 (?r (setq c ?\r))
6266 (?t (setq c ?\t))
6267 (?v (setq c ?\v))
6268 (?u
6269 (setq c1 (js2-read-unicode-escape))
6270 (if js2-parse-ide-mode
6271 (if c1
6272 (progn
6273 ;; just copy the string in IDE-mode
6274 (js2-add-to-string ?\\)
6275 (js2-add-to-string ?u)
6276 (dotimes (_ 3)
6277 (js2-add-to-string (js2-get-char)))
6278 (setq c (js2-get-char))) ; added at end of loop
6279 ;; flag it as an invalid escape
6280 (js2-report-warning "msg.invalid.escape"
6281 nil (- js2-ts-cursor 2) 6))
6282 ;; Get 4 hex digits; if the u escape is not
6283 ;; followed by 4 hex digits, use 'u' + the
6284 ;; literal character sequence that follows.
6285 (js2-add-to-string ?u)
6286 (setq escape-val 0)
6287 (dotimes (_ 4)
6288 (setq c (js2-get-char)
6289 escape-val (js2-x-digit-to-int c escape-val))
6290 (if (cl-minusp escape-val)
6291 (throw 'continue nil))
6292 (js2-add-to-string c))
6293 ;; prepare for replace of stored 'u' sequence by escape value
6294 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6295 c escape-val)))
6296 (?x
6297 ;; Get 2 hex digits, defaulting to 'x'+literal
6298 ;; sequence, as above.
6299 (setq c (js2-get-char)
6300 escape-val (js2-x-digit-to-int c 0))
6301 (if (cl-minusp escape-val)
6302 (progn
6303 (js2-add-to-string ?x)
6304 (throw 'continue nil))
6305 (setq c1 c
6306 c (js2-get-char)
6307 escape-val (js2-x-digit-to-int c escape-val))
6308 (if (cl-minusp escape-val)
6309 (progn
6310 (js2-add-to-string ?x)
6311 (js2-add-to-string c1)
6312 (throw 'continue nil))
6313 ;; got 2 hex digits
6314 (setq c escape-val))))
6315 (?\n
6316 ;; Remove line terminator after escape to follow
6317 ;; SpiderMonkey and C/C++
6318 (setq c (js2-get-char))
6319 (throw 'continue nil))
6320 (t
6321 (when (and (<= ?0 c) (< c ?8))
6322 (setq val (- c ?0)
6323 c (js2-get-char))
6324 (when (and (<= ?0 c) (< c ?8))
6325 (setq val (- (+ (* 8 val) c) ?0)
6326 c (js2-get-char))
6327 (when (and (<= ?0 c)
6328 (< c ?8)
6329 (< val #o37))
6330 ;; c is 3rd char of octal sequence only
6331 ;; if the resulting val <= 0377
6332 (setq val (- (+ (* 8 val) c) ?0)
6333 c (js2-get-char))))
6334 (js2-unget-char)
6335 (setq c val)))))
6336 (when (and (eq quote-char ?`) (eq c ?$))
6337 (when (eq (setq nc (js2-get-char)) ?\{)
6338 (throw 'break nil))
6339 (js2-unget-char))
6340 (js2-add-to-string c)
6341 (setq c (js2-get-char)))))
6342 (js2-set-string-from-buffer token)
6343 (if (not (eq quote-char ?`))
6344 js2-STRING
6345 (if (and (eq c ?$) (eq nc ?\{))
6346 js2-TEMPLATE_HEAD
6347 js2-NO_SUBS_TEMPLATE))))
6348
6349 (defun js2-read-regexp (start-tt)
6350 "Called by parser when it gets / or /= in literal context."
6351 (let (c err
6352 in-class ; inside a '[' .. ']' character-class
6353 flags
6354 (continue t)
6355 (token (js2-new-token 0)))
6356 (setq js2-ts-string-buffer nil)
6357 (if (eq start-tt js2-ASSIGN_DIV)
6358 ;; mis-scanned /=
6359 (js2-add-to-string ?=)
6360 (if (not (eq start-tt js2-DIV))
6361 (error "failed assertion")))
6362 (while (and (not err)
6363 (or (/= (setq c (js2-get-char)) ?/)
6364 in-class))
6365 (cond
6366 ((or (= c ?\n)
6367 (= c js2-EOF_CHAR))
6368 (setf (js2-token-end token) (1- js2-ts-cursor)
6369 err t
6370 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6371 (js2-report-error "msg.unterminated.re.lit"))
6372 (t (cond
6373 ((= c ?\\)
6374 (js2-add-to-string c)
6375 (setq c (js2-get-char)))
6376 ((= c ?\[)
6377 (setq in-class t))
6378 ((= c ?\])
6379 (setq in-class nil)))
6380 (js2-add-to-string c))))
6381 (unless err
6382 (while continue
6383 (cond
6384 ((js2-match-char ?g)
6385 (push ?g flags))
6386 ((js2-match-char ?i)
6387 (push ?i flags))
6388 ((js2-match-char ?m)
6389 (push ?m flags))
6390 ((and (js2-match-char ?u)
6391 (>= js2-language-version 200))
6392 (push ?u flags))
6393 ((and (js2-match-char ?y)
6394 (>= js2-language-version 200))
6395 (push ?y flags))
6396 (t
6397 (setq continue nil))))
6398 (if (js2-alpha-p (js2-peek-char))
6399 (js2-report-scan-error "msg.invalid.re.flag" t
6400 js2-ts-cursor 1))
6401 (js2-set-string-from-buffer token))
6402 (js2-collect-string flags)))
6403
6404 (defun js2-get-first-xml-token ()
6405 (setq js2-ts-xml-open-tags-count 0
6406 js2-ts-is-xml-attribute nil
6407 js2-ts-xml-is-tag-content nil)
6408 (js2-unget-char)
6409 (js2-get-next-xml-token))
6410
6411 (defun js2-xml-discard-string (token)
6412 "Throw away the string in progress and flag an XML parse error."
6413 (setf js2-ts-string-buffer nil
6414 (js2-token-string token) nil)
6415 (js2-report-scan-error "msg.XML.bad.form" t))
6416
6417 (defun js2-get-next-xml-token ()
6418 (setq js2-ts-string-buffer nil) ; for recording the XML
6419 (let ((token (js2-new-token 0))
6420 c result)
6421 (setq result
6422 (catch 'return
6423 (while t
6424 (setq c (js2-get-char))
6425 (cond
6426 ((= c js2-EOF_CHAR)
6427 (throw 'return js2-ERROR))
6428 (js2-ts-xml-is-tag-content
6429 (cl-case c
6430 (?>
6431 (js2-add-to-string c)
6432 (setq js2-ts-xml-is-tag-content nil
6433 js2-ts-is-xml-attribute nil))
6434 (?/
6435 (js2-add-to-string c)
6436 (when (eq ?> (js2-peek-char))
6437 (setq c (js2-get-char))
6438 (js2-add-to-string c)
6439 (setq js2-ts-xml-is-tag-content nil)
6440 (cl-decf js2-ts-xml-open-tags-count)))
6441 (?{
6442 (js2-unget-char)
6443 (js2-set-string-from-buffer token)
6444 (throw 'return js2-XML))
6445 ((?\' ?\")
6446 (js2-add-to-string c)
6447 (unless (js2-read-quoted-string c token)
6448 (throw 'return js2-ERROR)))
6449 (?=
6450 (js2-add-to-string c)
6451 (setq js2-ts-is-xml-attribute t))
6452 ((? ?\t ?\r ?\n)
6453 (js2-add-to-string c))
6454 (t
6455 (js2-add-to-string c)
6456 (setq js2-ts-is-xml-attribute nil)))
6457 (when (and (not js2-ts-xml-is-tag-content)
6458 (zerop js2-ts-xml-open-tags-count))
6459 (js2-set-string-from-buffer token)
6460 (throw 'return js2-XMLEND)))
6461 (t
6462 ;; else not tag content
6463 (cl-case c
6464 (?<
6465 (js2-add-to-string c)
6466 (setq c (js2-peek-char))
6467 (cl-case c
6468 (?!
6469 (setq c (js2-get-char)) ;; skip !
6470 (js2-add-to-string c)
6471 (setq c (js2-peek-char))
6472 (cl-case c
6473 (?-
6474 (setq c (js2-get-char)) ;; skip -
6475 (js2-add-to-string c)
6476 (if (eq c ?-)
6477 (progn
6478 (js2-add-to-string c)
6479 (unless (js2-read-xml-comment token)
6480 (throw 'return js2-ERROR)))
6481 (js2-xml-discard-string token)
6482 (throw 'return js2-ERROR)))
6483 (?\[
6484 (setq c (js2-get-char)) ;; skip [
6485 (js2-add-to-string c)
6486 (if (and (= (js2-get-char) ?C)
6487 (= (js2-get-char) ?D)
6488 (= (js2-get-char) ?A)
6489 (= (js2-get-char) ?T)
6490 (= (js2-get-char) ?A)
6491 (= (js2-get-char) ?\[))
6492 (progn
6493 (js2-add-to-string ?C)
6494 (js2-add-to-string ?D)
6495 (js2-add-to-string ?A)
6496 (js2-add-to-string ?T)
6497 (js2-add-to-string ?A)
6498 (js2-add-to-string ?\[)
6499 (unless (js2-read-cdata token)
6500 (throw 'return js2-ERROR)))
6501 (js2-xml-discard-string token)
6502 (throw 'return js2-ERROR)))
6503 (t
6504 (unless (js2-read-entity token)
6505 (throw 'return js2-ERROR))))
6506 ;; Allow bare CDATA section, e.g.:
6507 ;; let xml = <![CDATA[ foo bar baz ]]>;
6508 (when (zerop js2-ts-xml-open-tags-count)
6509 (throw 'return js2-XMLEND)))
6510 (??
6511 (setq c (js2-get-char)) ;; skip ?
6512 (js2-add-to-string c)
6513 (unless (js2-read-PI token)
6514 (throw 'return js2-ERROR)))
6515 (?/
6516 ;; end tag
6517 (setq c (js2-get-char)) ;; skip /
6518 (js2-add-to-string c)
6519 (when (zerop js2-ts-xml-open-tags-count)
6520 (js2-xml-discard-string token)
6521 (throw 'return js2-ERROR))
6522 (setq js2-ts-xml-is-tag-content t)
6523 (cl-decf js2-ts-xml-open-tags-count))
6524 (t
6525 ;; start tag
6526 (setq js2-ts-xml-is-tag-content t)
6527 (cl-incf js2-ts-xml-open-tags-count))))
6528 (?{
6529 (js2-unget-char)
6530 (js2-set-string-from-buffer token)
6531 (throw 'return js2-XML))
6532 (t
6533 (js2-add-to-string c))))))))
6534 (setf (js2-token-end token) js2-ts-cursor)
6535 (setf (js2-token-type token) result)
6536 result))
6537
6538 (defun js2-read-quoted-string (quote token)
6539 (let (c)
6540 (catch 'return
6541 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6542 (js2-add-to-string c)
6543 (if (eq c quote)
6544 (throw 'return t)))
6545 (js2-xml-discard-string token) ;; throw away string in progress
6546 nil)))
6547
6548 (defun js2-read-xml-comment (token)
6549 (let ((c (js2-get-char)))
6550 (catch 'return
6551 (while (/= c js2-EOF_CHAR)
6552 (catch 'continue
6553 (js2-add-to-string c)
6554 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6555 (setq c (js2-get-char))
6556 (js2-add-to-string c)
6557 (if (eq (js2-peek-char) ?>)
6558 (progn
6559 (setq c (js2-get-char)) ;; skip >
6560 (js2-add-to-string c)
6561 (throw 'return t))
6562 (throw 'continue nil)))
6563 (setq c (js2-get-char))))
6564 (js2-xml-discard-string token)
6565 nil)))
6566
6567 (defun js2-read-cdata (token)
6568 (let ((c (js2-get-char)))
6569 (catch 'return
6570 (while (/= c js2-EOF_CHAR)
6571 (catch 'continue
6572 (js2-add-to-string c)
6573 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6574 (setq c (js2-get-char))
6575 (js2-add-to-string c)
6576 (if (eq (js2-peek-char) ?>)
6577 (progn
6578 (setq c (js2-get-char)) ;; Skip >
6579 (js2-add-to-string c)
6580 (throw 'return t))
6581 (throw 'continue nil)))
6582 (setq c (js2-get-char))))
6583 (js2-xml-discard-string token)
6584 nil)))
6585
6586 (defun js2-read-entity (token)
6587 (let ((decl-tags 1)
6588 c)
6589 (catch 'return
6590 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6591 (js2-add-to-string c)
6592 (cl-case c
6593 (?<
6594 (cl-incf decl-tags))
6595 (?>
6596 (cl-decf decl-tags)
6597 (if (zerop decl-tags)
6598 (throw 'return t)))))
6599 (js2-xml-discard-string token)
6600 nil)))
6601
6602 (defun js2-read-PI (token)
6603 "Scan an XML processing instruction."
6604 (let (c)
6605 (catch 'return
6606 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6607 (js2-add-to-string c)
6608 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6609 (setq c (js2-get-char)) ;; Skip >
6610 (js2-add-to-string c)
6611 (throw 'return t)))
6612 (js2-xml-discard-string token)
6613 nil)))
6614
6615 ;;; Highlighting
6616
6617 (defun js2-set-face (beg end face &optional record)
6618 "Fontify a region. If RECORD is non-nil, record for later."
6619 (when (cl-plusp js2-highlight-level)
6620 (setq beg (min (point-max) beg)
6621 beg (max (point-min) beg)
6622 end (min (point-max) end)
6623 end (max (point-min) end))
6624 (if record
6625 (push (list beg end face) js2-mode-fontifications)
6626 (put-text-property beg end 'font-lock-face face))))
6627
6628 (defsubst js2-clear-face (beg end)
6629 (remove-text-properties beg end '(font-lock-face nil
6630 help-echo nil
6631 point-entered nil
6632 c-in-sws nil)))
6633
6634 (defconst js2-ecma-global-props
6635 (concat "^"
6636 (regexp-opt
6637 '("Infinity" "NaN" "undefined" "arguments") t)
6638 "$")
6639 "Value properties of the Ecma-262 Global Object.
6640 Shown at or above `js2-highlight-level' 2.")
6641
6642 ;; might want to add the name "arguments" to this list?
6643 (defconst js2-ecma-object-props
6644 (concat "^"
6645 (regexp-opt
6646 '("prototype" "__proto__" "__parent__") t)
6647 "$")
6648 "Value properties of the Ecma-262 Object constructor.
6649 Shown at or above `js2-highlight-level' 2.")
6650
6651 (defconst js2-ecma-global-funcs
6652 (concat
6653 "^"
6654 (regexp-opt
6655 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6656 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6657 "$")
6658 "Function properties of the Ecma-262 Global object.
6659 Shown at or above `js2-highlight-level' 2.")
6660
6661 (defconst js2-ecma-number-props
6662 (concat "^"
6663 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6664 "NEGATIVE_INFINITY"
6665 "POSITIVE_INFINITY") t)
6666 "$")
6667 "Properties of the Ecma-262 Number constructor.
6668 Shown at or above `js2-highlight-level' 2.")
6669
6670 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6671 "Properties of the Ecma-262 Date constructor.
6672 Shown at or above `js2-highlight-level' 2.")
6673
6674 (defconst js2-ecma-math-props
6675 (concat "^"
6676 (regexp-opt
6677 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6678 t)
6679 "$")
6680 "Properties of the Ecma-262 Math object.
6681 Shown at or above `js2-highlight-level' 2.")
6682
6683 (defconst js2-ecma-math-funcs
6684 (concat "^"
6685 (regexp-opt
6686 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6687 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6688 "$")
6689 "Function properties of the Ecma-262 Math object.
6690 Shown at or above `js2-highlight-level' 2.")
6691
6692 (defconst js2-ecma-function-props
6693 (concat
6694 "^"
6695 (regexp-opt
6696 '(;; properties of the Object prototype object
6697 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6698 "toLocaleString" "toString" "valueOf"
6699 ;; properties of the Function prototype object
6700 "apply" "call"
6701 ;; properties of the Array prototype object
6702 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6703 "splice" "unshift"
6704 ;; properties of the String prototype object
6705 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6706 "localeCompare" "match" "replace" "search" "split" "substring"
6707 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6708 "toUpperCase"
6709 ;; properties of the Number prototype object
6710 "toExponential" "toFixed" "toPrecision"
6711 ;; properties of the Date prototype object
6712 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6713 "getMinutes" "getMonth" "getSeconds" "getTime"
6714 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6715 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6716 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6717 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6718 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6719 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6720 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6721 "toTimeString" "toUTCString"
6722 ;; properties of the RegExp prototype object
6723 "exec" "test"
6724 ;; properties of the JSON prototype object
6725 "parse" "stringify"
6726 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6727 "toSource" "__defineGetter__" "__defineSetter__"
6728 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6729 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6730 t)
6731 "$")
6732 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6733 Shown at or above `js2-highlight-level' 3.")
6734
6735 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6736 (let ((target-name (and target
6737 (js2-name-node-p target)
6738 (js2-name-node-name target)))
6739 (prop-name (if prop (js2-name-node-name prop)))
6740 (level2 (>= js2-highlight-level 2))
6741 (level3 (>= js2-highlight-level 3)))
6742 (when level2
6743 (let ((face
6744 (if call-p
6745 (cond
6746 ((and target prop)
6747 (cond
6748 ((and level3 (string-match js2-ecma-function-props prop-name))
6749 'font-lock-builtin-face)
6750 ((and target-name prop)
6751 (cond
6752 ((string= target-name "Date")
6753 (if (string-match js2-ecma-date-props prop-name)
6754 'font-lock-builtin-face))
6755 ((string= target-name "Math")
6756 (if (string-match js2-ecma-math-funcs prop-name)
6757 'font-lock-builtin-face))))))
6758 (prop
6759 (if (string-match js2-ecma-global-funcs prop-name)
6760 'font-lock-builtin-face)))
6761 (cond
6762 ((and target prop)
6763 (cond
6764 ((string= target-name "Number")
6765 (if (string-match js2-ecma-number-props prop-name)
6766 'font-lock-constant-face))
6767 ((string= target-name "Math")
6768 (if (string-match js2-ecma-math-props prop-name)
6769 'font-lock-constant-face))))
6770 (prop
6771 (if (string-match js2-ecma-object-props prop-name)
6772 'font-lock-constant-face))))))
6773 (when face
6774 (let ((pos (+ (js2-node-pos parent) ; absolute
6775 (js2-node-pos prop)))) ; relative
6776 (js2-set-face pos
6777 (+ pos (js2-node-len prop))
6778 face 'record)))))))
6779
6780 (defun js2-parse-highlight-member-expr-node (node)
6781 "Perform syntax highlighting of EcmaScript built-in properties.
6782 The variable `js2-highlight-level' governs this highighting."
6783 (let (face target prop name pos end parent call-p callee)
6784 (cond
6785 ;; case 1: simple name, e.g. foo
6786 ((js2-name-node-p node)
6787 (setq name (js2-name-node-name node))
6788 ;; possible for name to be nil in rare cases - saw it when
6789 ;; running js2-mode on an elisp buffer. Might as well try to
6790 ;; make it so js2-mode never barfs.
6791 (when name
6792 (setq face (if (string-match js2-ecma-global-props name)
6793 'font-lock-constant-face))
6794 (when face
6795 (setq pos (js2-node-pos node)
6796 end (+ pos (js2-node-len node)))
6797 (js2-set-face pos end face 'record))))
6798 ;; case 2: property access or function call
6799 ((or (js2-prop-get-node-p node)
6800 ;; highlight function call if expr is a prop-get node
6801 ;; or a plain name (i.e. unqualified function call)
6802 (and (setq call-p (js2-call-node-p node))
6803 (setq callee (js2-call-node-target node)) ; separate setq!
6804 (or (js2-prop-get-node-p callee)
6805 (js2-name-node-p callee))))
6806 (setq parent node
6807 node (if call-p callee node))
6808 (if (and call-p (js2-name-node-p callee))
6809 (setq prop callee)
6810 (setq target (js2-prop-get-node-left node)
6811 prop (js2-prop-get-node-right node)))
6812 (cond
6813 ((js2-name-node-p prop)
6814 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6815 (js2-parse-highlight-prop-get parent target prop call-p))
6816 ((js2-name-node-p target)
6817 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6818 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6819
6820 (defun js2-parse-highlight-member-expr-fn-name (expr)
6821 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6822 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6823 We currently only handle the case where the last component is a prop-get
6824 of a simple name. Called before EXPR has a parent node."
6825 (let (pos
6826 (name (and (js2-prop-get-node-p expr)
6827 (js2-prop-get-node-right expr))))
6828 (when (js2-name-node-p name)
6829 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6830 (js2-node-pos name)))
6831 (+ pos (js2-node-len name))
6832 'font-lock-function-name-face
6833 'record))))
6834
6835 ;; source: http://jsdoc.sourceforge.net/
6836 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6837 ;; allows type specifications, and needs work before entering the wild.
6838
6839 (defconst js2-jsdoc-param-tag-regexp
6840 (concat "^\\s-*\\*+\\s-*\\(@"
6841 "\\(?:param\\|argument\\)"
6842 "\\)"
6843 "\\s-*\\({[^}]+}\\)?" ; optional type
6844 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6845 "\\>")
6846 "Matches jsdoc tags with optional type and optional param name.")
6847
6848 (defconst js2-jsdoc-typed-tag-regexp
6849 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6850 (regexp-opt
6851 '("enum"
6852 "extends"
6853 "field"
6854 "id"
6855 "implements"
6856 "lends"
6857 "mods"
6858 "requires"
6859 "return"
6860 "returns"
6861 "throw"
6862 "throws"))
6863 "\\)\\)\\s-*\\({[^}]+}\\)?")
6864 "Matches jsdoc tags with optional type.")
6865
6866 (defconst js2-jsdoc-arg-tag-regexp
6867 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6868 (regexp-opt
6869 '("alias"
6870 "augments"
6871 "borrows"
6872 "bug"
6873 "base"
6874 "config"
6875 "default"
6876 "define"
6877 "exception"
6878 "function"
6879 "member"
6880 "memberOf"
6881 "name"
6882 "namespace"
6883 "property"
6884 "since"
6885 "suppress"
6886 "this"
6887 "throws"
6888 "type"
6889 "version"))
6890 "\\)\\)\\s-+\\([^ \t]+\\)")
6891 "Matches jsdoc tags with a single argument.")
6892
6893 (defconst js2-jsdoc-empty-tag-regexp
6894 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6895 (regexp-opt
6896 '("addon"
6897 "author"
6898 "class"
6899 "const"
6900 "constant"
6901 "constructor"
6902 "constructs"
6903 "deprecated"
6904 "desc"
6905 "description"
6906 "event"
6907 "example"
6908 "exec"
6909 "export"
6910 "fileoverview"
6911 "final"
6912 "function"
6913 "hidden"
6914 "ignore"
6915 "implicitCast"
6916 "inheritDoc"
6917 "inner"
6918 "interface"
6919 "license"
6920 "noalias"
6921 "noshadow"
6922 "notypecheck"
6923 "override"
6924 "owner"
6925 "preserve"
6926 "preserveTry"
6927 "private"
6928 "protected"
6929 "public"
6930 "static"
6931 "supported"
6932 ))
6933 "\\)\\)\\s-*")
6934 "Matches empty jsdoc tags.")
6935
6936 (defconst js2-jsdoc-link-tag-regexp
6937 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6938 "Matches a jsdoc link or code tag.")
6939
6940 (defconst js2-jsdoc-see-tag-regexp
6941 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6942 "Matches a jsdoc @see tag.")
6943
6944 (defconst js2-jsdoc-html-tag-regexp
6945 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6946 "Matches a simple (no attributes) html start- or end-tag.")
6947
6948 (defun js2-jsdoc-highlight-helper ()
6949 (js2-set-face (match-beginning 1)
6950 (match-end 1)
6951 'js2-jsdoc-tag)
6952 (if (match-beginning 2)
6953 (if (save-excursion
6954 (goto-char (match-beginning 2))
6955 (= (char-after) ?{))
6956 (js2-set-face (1+ (match-beginning 2))
6957 (1- (match-end 2))
6958 'js2-jsdoc-type)
6959 (js2-set-face (match-beginning 2)
6960 (match-end 2)
6961 'js2-jsdoc-value)))
6962 (if (match-beginning 3)
6963 (js2-set-face (match-beginning 3)
6964 (match-end 3)
6965 'js2-jsdoc-value)))
6966
6967 (defun js2-highlight-jsdoc (ast)
6968 "Highlight doc comment tags."
6969 (let ((comments (js2-ast-root-comments ast))
6970 beg end)
6971 (save-excursion
6972 (dolist (node comments)
6973 (when (eq (js2-comment-node-format node) 'jsdoc)
6974 (setq beg (js2-node-abs-pos node)
6975 end (+ beg (js2-node-len node)))
6976 (save-restriction
6977 (narrow-to-region beg end)
6978 (dolist (re (list js2-jsdoc-param-tag-regexp
6979 js2-jsdoc-typed-tag-regexp
6980 js2-jsdoc-arg-tag-regexp
6981 js2-jsdoc-link-tag-regexp
6982 js2-jsdoc-see-tag-regexp
6983 js2-jsdoc-empty-tag-regexp))
6984 (goto-char beg)
6985 (while (re-search-forward re nil t)
6986 (js2-jsdoc-highlight-helper)))
6987 ;; simple highlighting for html tags
6988 (goto-char beg)
6989 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6990 (js2-set-face (match-beginning 1)
6991 (match-end 1)
6992 'js2-jsdoc-html-tag-delimiter)
6993 (js2-set-face (match-beginning 2)
6994 (match-end 2)
6995 'js2-jsdoc-html-tag-name)
6996 (js2-set-face (match-beginning 3)
6997 (match-end 3)
6998 'js2-jsdoc-html-tag-delimiter))))))))
6999
7000 (defun js2-highlight-assign-targets (_node left right)
7001 "Highlight function properties and external variables."
7002 (let (leftpos name)
7003 ;; highlight vars and props assigned function values
7004 (when (or (js2-function-node-p right)
7005 (js2-class-node-p right))
7006 (cond
7007 ;; var foo = function() {...}
7008 ((js2-name-node-p left)
7009 (setq name left))
7010 ;; foo.bar.baz = function() {...}
7011 ((and (js2-prop-get-node-p left)
7012 (js2-name-node-p (js2-prop-get-node-right left)))
7013 (setq name (js2-prop-get-node-right left))))
7014 (when name
7015 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7016 (+ leftpos (js2-node-len name))
7017 'font-lock-function-name-face
7018 'record)))))
7019
7020 (defun js2-record-name-node (node)
7021 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7022 later. NODE must be a name node."
7023 (let ((leftpos (js2-node-abs-pos node)))
7024 (push (list node js2-current-scope
7025 leftpos
7026 (+ leftpos (js2-node-len node)))
7027 js2-recorded-identifiers)))
7028
7029 (defun js2-highlight-undeclared-vars ()
7030 "After entire parse is finished, look for undeclared variable references.
7031 We have to wait until entire buffer is parsed, since JavaScript permits var
7032 decls to occur after they're used.
7033
7034 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7035 it is considered declared."
7036 (let (name)
7037 (dolist (entry js2-recorded-identifiers)
7038 (cl-destructuring-bind (name-node scope pos end) entry
7039 (setq name (js2-name-node-name name-node))
7040 (unless (or (member name js2-global-externs)
7041 (member name js2-default-externs)
7042 (member name js2-additional-externs)
7043 (js2-get-defining-scope scope name pos))
7044 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7045 'js2-external-variable))))
7046 (setq js2-recorded-identifiers nil)))
7047
7048 (defun js2-set-default-externs ()
7049 "Set the value of `js2-default-externs' based on the various
7050 `js2-include-?-externs' variables."
7051 (setq js2-default-externs
7052 (append js2-ecma-262-externs
7053 (if js2-include-browser-externs js2-browser-externs)
7054 (if (and js2-include-browser-externs
7055 (>= js2-language-version 200)) js2-harmony-externs)
7056 (if js2-include-rhino-externs js2-rhino-externs)
7057 (if js2-include-node-externs js2-node-externs)
7058 (if (or js2-include-browser-externs js2-include-node-externs)
7059 js2-typed-array-externs))))
7060
7061 (defun js2-apply-jslint-globals ()
7062 (setq js2-additional-externs
7063 (nconc (js2-get-jslint-globals)
7064 js2-additional-externs)))
7065
7066 (defun js2-get-jslint-globals ()
7067 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7068 when (and (eq 'block (js2-comment-node-format node))
7069 (save-excursion
7070 (goto-char (js2-node-abs-pos node))
7071 (looking-at "/\\*global ")))
7072 append (js2-get-jslint-globals-in
7073 (match-end 0)
7074 (js2-node-abs-end node))))
7075
7076 (defun js2-get-jslint-globals-in (beg end)
7077 (let (res)
7078 (save-excursion
7079 (goto-char beg)
7080 (while (re-search-forward js2-mode-identifier-re end t)
7081 (let ((match (match-string 0)))
7082 (unless (member match '("true" "false"))
7083 (push match res)))))
7084 (nreverse res)))
7085
7086 ;;; IMenu support
7087
7088 ;; We currently only support imenu, but eventually should support speedbar and
7089 ;; possibly other browsing mechanisms.
7090
7091 ;; The basic strategy is to identify function assignment targets of the form
7092 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7093 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7094 ;; for imenu after parsing is finished.
7095
7096 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7097 ;; JavaScript, and the general problem is undecidable. However, several forms
7098 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7099 ;; include:
7100
7101 ;; function foo() -- function declaration
7102 ;; foo = function() -- function expression assigned to variable
7103 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7104 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7105 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7106 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7107 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7108 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7109 ;; function foo() {function bar() {...}} -- nested function
7110 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7111
7112 ;; This list boils down to a few forms that can be combined recursively.
7113 ;; Top-level named function declarations include both the left-hand (name)
7114 ;; and the right-hand (function value) expressions needed to produce an imenu
7115 ;; entry. The other "right-hand" forms we need to look for are:
7116 ;; - functions declared as props/getters/setters in object literals
7117 ;; - nested named function declarations
7118 ;; The "left-hand" expressions that functions can be assigned to include:
7119 ;; - local/global variables
7120 ;; - nested property-get expressions like a.b.c.d
7121 ;; - element gets like foo[10] or foo['bar'] where the index
7122 ;; expression can be trivially converted to a property name. They
7123 ;; effectively then become property gets.
7124
7125 ;; All the different definition types are canonicalized into the form
7126 ;; foo.bar.baz = position-of-function-keyword
7127
7128 ;; We need to build a trie-like structure for imenu. As an example,
7129 ;; consider the following JavaScript code:
7130
7131 ;; a = function() {...} // function at position 5
7132 ;; b = function() {...} // function at position 25
7133 ;; foo = function() {...} // function at position 100
7134 ;; foo.bar = function() {...} // function at position 200
7135 ;; foo.bar.baz = function() {...} // function at position 300
7136 ;; foo.bar.zab = function() {...} // function at position 400
7137
7138 ;; During parsing we accumulate an entry for each definition in
7139 ;; the variable `js2-imenu-recorder', like so:
7140
7141 ;; '((fn a 5)
7142 ;; (fn b 25)
7143 ;; (fn foo 100)
7144 ;; (fn foo bar 200)
7145 ;; (fn foo bar baz 300)
7146 ;; (fn foo bar zab 400))
7147
7148 ;; Where 'fn' is the respective function node.
7149 ;; After parsing these entries are merged into this alist-trie:
7150
7151 ;; '((a . 1)
7152 ;; (b . 2)
7153 ;; (foo (<definition> . 3)
7154 ;; (bar (<definition> . 6)
7155 ;; (baz . 100)
7156 ;; (zab . 200))))
7157
7158 ;; Note the wacky need for a <definition> name. The token can be anything
7159 ;; that isn't a valid JavaScript identifier, because you might make foo
7160 ;; a function and then start setting properties on it that are also functions.
7161
7162 (defun js2-prop-node-name (node)
7163 "Return the name of a node that may be a property-get/property-name.
7164 If NODE is not a valid name-node, string-node or integral number-node,
7165 returns nil. Otherwise returns the string name/value of the node."
7166 (cond
7167 ((js2-name-node-p node)
7168 (js2-name-node-name node))
7169 ((js2-string-node-p node)
7170 (js2-string-node-value node))
7171 ((and (js2-number-node-p node)
7172 (string-match "^[0-9]+$" (js2-number-node-value node)))
7173 (js2-number-node-value node))
7174 ((eq (js2-node-type node) js2-THIS)
7175 "this")
7176 ((eq (js2-node-type node) js2-SUPER)
7177 "super")))
7178
7179 (defun js2-node-qname-component (node)
7180 "Return the name of this node, if it contributes to a qname.
7181 Returns nil if the node doesn't contribute."
7182 (copy-sequence
7183 (or (js2-prop-node-name node)
7184 (if (and (js2-function-node-p node)
7185 (js2-function-node-name node))
7186 (js2-name-node-name (js2-function-node-name node))))))
7187
7188 (defun js2-record-imenu-entry (fn-node qname pos)
7189 "Add an entry to `js2-imenu-recorder'.
7190 FN-NODE should be the current item's function node.
7191
7192 Associate FN-NODE with its QNAME for later lookup.
7193 This is used in postprocessing the chain list. For each chain, we find
7194 the parent function, look up its qname, then prepend a copy of it to the chain."
7195 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7196 (unless js2-imenu-function-map
7197 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7198 (puthash fn-node qname js2-imenu-function-map))
7199
7200 (defun js2-record-imenu-functions (node &optional var)
7201 "Record function definitions for imenu.
7202 NODE is a function node or an object literal.
7203 VAR, if non-nil, is the expression that NODE is being assigned to.
7204 When passed arguments of wrong type, does nothing."
7205 (when js2-parse-ide-mode
7206 (let ((fun-p (js2-function-node-p node))
7207 qname fname-node)
7208 (cond
7209 ;; non-anonymous function declaration?
7210 ((and fun-p
7211 (not var)
7212 (setq fname-node (js2-function-node-name node)))
7213 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7214 ;; for remaining forms, compute left-side tree branch first
7215 ((and var (setq qname (js2-compute-nested-prop-get var)))
7216 (cond
7217 ;; foo.bar.baz = function
7218 (fun-p
7219 (js2-record-imenu-entry node qname (js2-node-pos node)))
7220 ;; foo.bar.baz = object-literal
7221 ;; look for nested functions: {a: {b: function() {...} }}
7222 ((js2-object-node-p node)
7223 ;; Node position here is still absolute, since the parser
7224 ;; passes the assignment target and value expressions
7225 ;; to us before they are added as children of the assignment node.
7226 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7227
7228 (defun js2-compute-nested-prop-get (node)
7229 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7230 component nodes as a list. Otherwise return nil. Element-gets are treated
7231 as property-gets if the index expression is a string, or a positive integer."
7232 (let (left right head)
7233 (cond
7234 ((or (js2-name-node-p node)
7235 (js2-this-or-super-node-p node))
7236 (list node))
7237 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7238 ((js2-prop-get-node-p node) ; foo.bar
7239 (setq left (js2-prop-get-node-left node)
7240 right (js2-prop-get-node-right node))
7241 (if (setq head (js2-compute-nested-prop-get left))
7242 (nconc head (list right))))
7243 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7244 (setq left (js2-elem-get-node-target node)
7245 right (js2-elem-get-node-element node))
7246 (if (or (js2-string-node-p right) ; ['bar']
7247 (and (js2-number-node-p right) ; [10]
7248 (string-match "^[0-9]+$"
7249 (js2-number-node-value right))))
7250 (if (setq head (js2-compute-nested-prop-get left))
7251 (nconc head (list right))))))))
7252
7253 (defun js2-record-object-literal (node qname pos)
7254 "Recursively process an object literal looking for functions.
7255 NODE is an object literal that is the right-hand child of an assignment
7256 expression. QNAME is a list of nodes representing the assignment target,
7257 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7258 POS is the absolute position of the node.
7259 We do a depth-first traversal of NODE. For any functions we find,
7260 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7261 (let (right)
7262 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7263 (let ((left (js2-infix-node-left e))
7264 ;; Element positions are relative to the parent position.
7265 (pos (+ pos (js2-node-pos e))))
7266 (cond
7267 ;; foo: function() {...}
7268 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7269 (when (js2-prop-node-name left)
7270 ;; As a policy decision, we record the position of the property,
7271 ;; not the position of the `function' keyword, since the property
7272 ;; is effectively the name of the function.
7273 (js2-record-imenu-entry right (append qname (list left)) pos)))
7274 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7275 ((js2-object-node-p right)
7276 (js2-record-object-literal right
7277 (append qname (list (js2-infix-node-left e)))
7278 (+ pos (js2-node-pos right)))))))))
7279
7280 (defun js2-node-top-level-decl-p (node)
7281 "Return t if NODE's name is defined in the top-level scope.
7282 Also returns t if NODE's name is not defined in any scope, since it implies
7283 that it's an external variable, which must also be in the top-level scope."
7284 (let* ((name (js2-prop-node-name node))
7285 (this-scope (js2-node-get-enclosing-scope node))
7286 defining-scope)
7287 (cond
7288 ((js2-this-or-super-node-p node)
7289 nil)
7290 ((null this-scope)
7291 t)
7292 ((setq defining-scope (js2-get-defining-scope this-scope name))
7293 (js2-ast-root-p defining-scope))
7294 (t t))))
7295
7296 (defun js2-wrapper-function-p (node)
7297 "Return t if NODE is a function expression that's immediately invoked.
7298 NODE must be `js2-function-node'."
7299 (let ((parent (js2-node-parent node)))
7300 (or
7301 ;; function(){...}();
7302 (and (js2-call-node-p parent)
7303 (eq node (js2-call-node-target parent)))
7304 (and (js2-paren-node-p parent)
7305 ;; (function(){...})();
7306 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7307 ;; (function(){...}).call(this);
7308 (and (js2-prop-get-node-p parent)
7309 (member (js2-name-node-name (js2-prop-get-node-right parent))
7310 '("call" "apply"))
7311 (js2-call-node-p (js2-node-parent parent))))))))
7312
7313 (defun js2-browse-postprocess-chains ()
7314 "Modify function-declaration name chains after parsing finishes.
7315 Some of the information is only available after the parse tree is complete.
7316 For instance, processing a nested scope requires a parent function node."
7317 (let (result fn parent-qname p elem)
7318 (dolist (entry js2-imenu-recorder)
7319 ;; function node goes first
7320 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7321 ;; Examine head's defining scope:
7322 ;; Pre-processed chain, or top-level/external, keep as-is.
7323 (if (or (stringp head) (js2-node-top-level-decl-p head))
7324 (push chain result)
7325 (when (js2-this-or-super-node-p head)
7326 (setq chain (cdr chain))) ; discard this-node
7327 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7328 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7329 (when (eq parent-qname 'not-found)
7330 ;; anonymous function expressions are not recorded
7331 ;; during the parse, so we need to handle this case here
7332 (setq parent-qname
7333 (if (js2-wrapper-function-p fn)
7334 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7335 (if (js2-ast-root-p grandparent)
7336 nil
7337 (gethash grandparent js2-imenu-function-map 'skip)))
7338 'skip))
7339 (puthash fn parent-qname js2-imenu-function-map))
7340 (if (eq parent-qname 'skip)
7341 ;; We don't show it, let's record that fact.
7342 (remhash current-fn js2-imenu-function-map)
7343 ;; Prepend parent fn qname to this chain.
7344 (let ((qname (append parent-qname chain)))
7345 (puthash current-fn (butlast qname) js2-imenu-function-map)
7346 (push qname result)))))))
7347 ;; Collect chains obtained by third-party code.
7348 (let (js2-imenu-recorder)
7349 (run-hooks 'js2-build-imenu-callbacks)
7350 (dolist (entry js2-imenu-recorder)
7351 (push (cdr entry) result)))
7352 ;; Finally replace each node in each chain with its name.
7353 (dolist (chain result)
7354 (setq p chain)
7355 (while p
7356 (if (js2-node-p (setq elem (car p)))
7357 (setcar p (js2-node-qname-component elem)))
7358 (setq p (cdr p))))
7359 result))
7360
7361 ;; Merge name chains into a trie-like tree structure of nested lists.
7362 ;; To simplify construction of the trie, we first build it out using the rule
7363 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7364 ;; [key, num-or-list]. The second element can be a number; if so, this key
7365 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7366 ;; associated with the key at this level.) Otherwise the second element is
7367 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7368 ;; a simple recursive formulation.
7369 ;;
7370 ;; js2-mode is building the data structure for imenu. The imenu documentation
7371 ;; claims that it's the structure above, but in practice it wants the children
7372 ;; at the same list level as the key for that level, which is how I've drawn
7373 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7374 ;; list wrapper around the children at each level.
7375 ;;
7376 ;; A completed nested imenu-alist entry looks like this:
7377 ;; '(("foo"
7378 ;; ("<definition>" . 7)
7379 ;; ("bar"
7380 ;; ("a" . 40)
7381 ;; ("b" . 60))))
7382 ;;
7383 ;; In particular, the documentation for `imenu--index-alist' says that
7384 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7385 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7386
7387 (defun js2-treeify (lst)
7388 "Convert (a b c d) to (a ((b ((c d)))))."
7389 (if (null (cddr lst)) ; list length <= 2
7390 lst
7391 (list (car lst) (list (js2-treeify (cdr lst))))))
7392
7393 (defun js2-build-alist-trie (chains trie)
7394 "Merge declaration name chains into a trie-like alist structure for imenu.
7395 CHAINS is the qname chain list produced during parsing. TRIE is a
7396 list of elements built up so far."
7397 (let (head tail pos branch kids)
7398 (dolist (chain chains)
7399 (setq head (car chain)
7400 tail (cdr chain)
7401 pos (if (numberp (car tail)) (car tail))
7402 branch (js2-find-if (lambda (n)
7403 (string= (car n) head))
7404 trie)
7405 kids (cl-second branch))
7406 (cond
7407 ;; case 1: this key isn't in the trie yet
7408 ((null branch)
7409 (if trie
7410 (setcdr (last trie) (list (js2-treeify chain)))
7411 (setq trie (list (js2-treeify chain)))))
7412 ;; case 2: key is present with a single number entry: replace w/ list
7413 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7414 ;; ("<definition>" 20)))
7415 ((numberp kids)
7416 (setcar (cdr branch)
7417 (list (list "<definition-1>" kids)
7418 (if pos
7419 (list "<definition-2>" pos)
7420 (js2-treeify tail)))))
7421 ;; case 3: key is there (with kids), and we're a number entry
7422 (pos
7423 (setcdr (last kids)
7424 (list
7425 (list (format "<definition-%d>"
7426 (1+ (cl-loop for kid in kids
7427 count (eq ?< (aref (car kid) 0)))))
7428 pos))))
7429 ;; case 4: key is there with kids, need to merge in our chain
7430 (t
7431 (js2-build-alist-trie (list tail) kids))))
7432 trie))
7433
7434 (defun js2-flatten-trie (trie)
7435 "Convert TRIE to imenu-format.
7436 Recurses through nodes, and for each one whose second element is a list,
7437 appends the list's flattened elements to the current element. Also
7438 changes the tails into conses. For instance, this pre-flattened trie
7439
7440 '(a ((b 20)
7441 (c ((d 30)
7442 (e 40)))))
7443
7444 becomes
7445
7446 '(a (b . 20)
7447 (c (d . 30)
7448 (e . 40)))
7449
7450 Note that the root of the trie has no key, just a list of chains.
7451 This is also true for the value of any key with multiple children,
7452 e.g. key 'c' in the example above."
7453 (cond
7454 ((listp (car trie))
7455 (mapcar #'js2-flatten-trie trie))
7456 (t
7457 (if (numberp (cl-second trie))
7458 (cons (car trie) (cl-second trie))
7459 ;; else pop list and append its kids
7460 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7461
7462 (defun js2-build-imenu-index ()
7463 "Turn `js2-imenu-recorder' into an imenu data structure."
7464 (when (eq js2-imenu-recorder 'empty)
7465 (setq js2-imenu-recorder nil))
7466 (let* ((chains (js2-browse-postprocess-chains))
7467 (result (js2-build-alist-trie chains nil)))
7468 (js2-flatten-trie result)))
7469
7470 (defun js2-test-print-chains (chains)
7471 "Print a list of qname chains.
7472 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7473 i.e. one or more nodes, and an integer position as the list tail."
7474 (mapconcat (lambda (chain)
7475 (concat "("
7476 (mapconcat (lambda (elem)
7477 (if (js2-node-p elem)
7478 (or (js2-node-qname-component elem)
7479 "nil")
7480 (number-to-string elem)))
7481 chain
7482 " ")
7483 ")"))
7484 chains
7485 "\n"))
7486
7487 ;;; Parser
7488
7489 (defconst js2-version "1.8.5"
7490 "Version of JavaScript supported.")
7491
7492 (defun js2-record-face (face &optional token)
7493 "Record a style run of FACE for TOKEN or the current token."
7494 (unless token (setq token (js2-current-token)))
7495 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7496
7497 (defsubst js2-node-end (n)
7498 "Computes the absolute end of node N.
7499 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7500 is only true until the node is added to its parent; i.e., while parsing."
7501 (+ (js2-node-pos n)
7502 (js2-node-len n)))
7503
7504 (defun js2-record-comment (token)
7505 "Record a comment in `js2-scanned-comments'."
7506 (let ((ct (js2-token-comment-type token))
7507 (beg (js2-token-beg token))
7508 (end (js2-token-end token)))
7509 (push (make-js2-comment-node :len (- end beg)
7510 :format ct)
7511 js2-scanned-comments)
7512 (when js2-parse-ide-mode
7513 (js2-record-face (if (eq ct 'jsdoc)
7514 'font-lock-doc-face
7515 'font-lock-comment-face)
7516 token)
7517 (when (memq ct '(html preprocessor))
7518 ;; Tell cc-engine the bounds of the comment.
7519 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7520
7521 (defun js2-peek-token ()
7522 "Return the next token type without consuming it.
7523 If `js2-ti-lookahead' is positive, return the type of next token
7524 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7525 (if (not (zerop js2-ti-lookahead))
7526 (js2-token-type
7527 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7528 (let ((tt (js2-get-token-internal nil)))
7529 (js2-unget-token)
7530 tt)))
7531
7532 (defalias 'js2-next-token 'js2-get-token)
7533
7534 (defun js2-match-token (match &optional dont-unget)
7535 "Get next token and return t if it matches MATCH, a bytecode.
7536 Returns nil and consumes nothing if MATCH is not the next token."
7537 (if (/= (js2-get-token) match)
7538 (ignore (unless dont-unget (js2-unget-token)))
7539 t))
7540
7541 (defun js2-match-contextual-kwd (name)
7542 "Consume and return t if next token is `js2-NAME', and its
7543 string is NAME. Returns nil and keeps current token otherwise."
7544 (if (or (/= (js2-get-token) js2-NAME)
7545 (not (string= (js2-current-token-string) name)))
7546 (progn
7547 (js2-unget-token)
7548 nil)
7549 (js2-record-face 'font-lock-keyword-face)
7550 t))
7551
7552 (defun js2-get-prop-name-token ()
7553 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7554
7555 (defun js2-match-prop-name ()
7556 "Consume token and return t if next token is a valid property name.
7557 If `js2-language-version' is >= 180, a keyword or reserved word
7558 is considered valid name as well."
7559 (if (eq js2-NAME (js2-get-prop-name-token))
7560 t
7561 (js2-unget-token)
7562 nil))
7563
7564 (defun js2-must-match-prop-name (msg-id &optional pos len)
7565 (if (js2-match-prop-name)
7566 t
7567 (js2-report-error msg-id nil pos len)
7568 nil))
7569
7570 (defun js2-peek-token-or-eol ()
7571 "Return js2-EOL if the next token immediately follows a newline.
7572 Else returns the next token. Used in situations where we don't
7573 consider certain token types valid if they are preceded by a newline.
7574 One example is the postfix ++ or -- operator, which has to be on the
7575 same line as its operand."
7576 (let ((tt (js2-get-token))
7577 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7578 (js2-unget-token)
7579 (if follows-eol
7580 js2-EOL
7581 tt)))
7582
7583 (defun js2-must-match (token msg-id &optional pos len)
7584 "Match next token to token code TOKEN, or record a syntax error.
7585 MSG-ID is the error message to report if the match fails.
7586 Returns t on match, nil if no match."
7587 (if (js2-match-token token t)
7588 t
7589 (js2-report-error msg-id nil pos len)
7590 (js2-unget-token)
7591 nil))
7592
7593 (defun js2-must-match-name (msg-id)
7594 (if (js2-match-token js2-NAME t)
7595 t
7596 (if (eq (js2-current-token-type) js2-RESERVED)
7597 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7598 (js2-report-error msg-id)
7599 (js2-unget-token))
7600 nil))
7601
7602 (defsubst js2-inside-function ()
7603 (cl-plusp js2-nesting-of-function))
7604
7605 (defun js2-set-requires-activation ()
7606 (if (js2-function-node-p js2-current-script-or-fn)
7607 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7608
7609 (defun js2-check-activation-name (name _token)
7610 (when (js2-inside-function)
7611 ;; skip language-version 1.2 check from Rhino
7612 (if (or (string= "arguments" name)
7613 (and js2-compiler-activation-names ; only used in codegen
7614 (gethash name js2-compiler-activation-names)))
7615 (js2-set-requires-activation))))
7616
7617 (defun js2-set-is-generator ()
7618 (let ((fn-node js2-current-script-or-fn))
7619 (when (and (js2-function-node-p fn-node)
7620 (not (js2-function-node-generator-type fn-node)))
7621 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7622
7623 (defun js2-must-have-xml ()
7624 (unless js2-compiler-xml-available
7625 (js2-report-error "msg.XML.not.available")))
7626
7627 (defun js2-push-scope (scope)
7628 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7629 (cl-assert (js2-scope-p scope))
7630 (cl-assert (null (js2-scope-parent-scope scope)))
7631 (cl-assert (not (eq js2-current-scope scope)))
7632 (setf (js2-scope-parent-scope scope) js2-current-scope
7633 js2-current-scope scope))
7634
7635 (defsubst js2-pop-scope ()
7636 (setq js2-current-scope
7637 (js2-scope-parent-scope js2-current-scope)))
7638
7639 (defun js2-enter-loop (loop-node)
7640 (push loop-node js2-loop-set)
7641 (push loop-node js2-loop-and-switch-set)
7642 (js2-push-scope loop-node)
7643 ;; Tell the current labeled statement (if any) its statement,
7644 ;; and set the jump target of the first label to the loop.
7645 ;; These are used in `js2-parse-continue' to verify that the
7646 ;; continue target is an actual labeled loop. (And for codegen.)
7647 (when js2-labeled-stmt
7648 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7649 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7650 js2-labeled-stmt))) loop-node)))
7651
7652 (defun js2-exit-loop ()
7653 (pop js2-loop-set)
7654 (pop js2-loop-and-switch-set)
7655 (js2-pop-scope))
7656
7657 (defsubst js2-enter-switch (switch-node)
7658 (push switch-node js2-loop-and-switch-set))
7659
7660 (defsubst js2-exit-switch ()
7661 (pop js2-loop-and-switch-set))
7662
7663 (defun js2-parse (&optional buf cb)
7664 "Tell the js2 parser to parse a region of JavaScript.
7665
7666 BUF is a buffer or buffer name containing the code to parse.
7667 Call `narrow-to-region' first to parse only part of the buffer.
7668
7669 The returned AST root node is given some additional properties:
7670 `node-count' - total number of nodes in the AST
7671 `buffer' - BUF. The buffer it refers to may change or be killed,
7672 so the value is not necessarily reliable.
7673
7674 An optional callback CB can be specified to report parsing
7675 progress. If `(functionp CB)' returns t, it will be called with
7676 the current line number once before parsing begins, then again
7677 each time the lexer reaches a new line number.
7678
7679 CB can also be a list of the form `(symbol cb ...)' to specify
7680 multiple callbacks with different criteria. Each symbol is a
7681 criterion keyword, and the following element is the callback to
7682 call
7683
7684 :line - called whenever the line number changes
7685 :token - called for each new token consumed
7686
7687 The list of criteria could be extended to include entering or
7688 leaving a statement, an expression, or a function definition."
7689 (if (and cb (not (functionp cb)))
7690 (error "criteria callbacks not yet implemented"))
7691 (let ((inhibit-point-motion-hooks t)
7692 (js2-compiler-xml-available (>= js2-language-version 160))
7693 ;; This is a recursive-descent parser, so give it a big stack.
7694 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7695 (max-specpdl-size (max max-specpdl-size 3000))
7696 (case-fold-search nil)
7697 ast)
7698 (with-current-buffer (or buf (current-buffer))
7699 (setq js2-scanned-comments nil
7700 js2-parsed-errors nil
7701 js2-parsed-warnings nil
7702 js2-imenu-recorder nil
7703 js2-imenu-function-map nil
7704 js2-label-set nil)
7705 (js2-init-scanner)
7706 (setq ast (js2-do-parse))
7707 (unless js2-ts-hit-eof
7708 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7709 (setf (js2-ast-root-errors ast) js2-parsed-errors
7710 (js2-ast-root-warnings ast) js2-parsed-warnings)
7711 ;; if we didn't find any declarations, put a dummy in this list so we
7712 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7713 (unless js2-imenu-recorder
7714 (setq js2-imenu-recorder 'empty))
7715 (run-hooks 'js2-parse-finished-hook)
7716 ast)))
7717
7718 ;; Corresponds to Rhino's Parser.parse() method.
7719 (defun js2-do-parse ()
7720 "Parse current buffer starting from current point.
7721 Scanner should be initialized."
7722 (let ((pos js2-ts-cursor)
7723 (end js2-ts-cursor) ; in case file is empty
7724 root n tt)
7725 ;; initialize buffer-local parsing vars
7726 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7727 js2-current-script-or-fn root
7728 js2-current-scope root
7729 js2-nesting-of-function 0
7730 js2-labeled-stmt nil
7731 js2-recorded-identifiers nil) ; for js2-highlight
7732 (while (/= (setq tt (js2-get-token)) js2-EOF)
7733 (if (= tt js2-FUNCTION)
7734 (progn
7735 (setq n (if js2-called-by-compile-function
7736 (js2-parse-function-expr)
7737 (js2-parse-function-stmt))))
7738 ;; not a function - parse a statement
7739 (js2-unget-token)
7740 (setq n (js2-parse-statement)))
7741 ;; add function or statement to script
7742 (setq end (js2-node-end n))
7743 (js2-block-node-push root n))
7744 ;; add comments to root in lexical order
7745 (when js2-scanned-comments
7746 ;; if we find a comment beyond end of normal kids, use its end
7747 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7748 (dolist (comment js2-scanned-comments)
7749 (push comment (js2-ast-root-comments root))
7750 (js2-node-add-children root comment)))
7751 (setf (js2-node-len root) (- end pos))
7752 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7753 ;; Give extensions a chance to muck with things before highlighting starts.
7754 (let ((js2-additional-externs js2-additional-externs))
7755 (save-excursion
7756 (run-hooks 'js2-post-parse-callbacks))
7757 (js2-highlight-undeclared-vars))
7758 root))
7759
7760 (defun js2-parse-function-closure-body (fn-node)
7761 "Parse a JavaScript 1.8 function closure body."
7762 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7763 (if js2-ts-hit-eof
7764 (js2-report-error "msg.no.brace.body" nil
7765 (js2-node-pos fn-node)
7766 (- js2-ts-cursor (js2-node-pos fn-node)))
7767 (js2-node-add-children fn-node
7768 (setf (js2-function-node-body fn-node)
7769 (js2-parse-expr t))))))
7770
7771 (defun js2-parse-function-body (fn-node)
7772 (js2-must-match js2-LC "msg.no.brace.body"
7773 (js2-node-pos fn-node)
7774 (- js2-ts-cursor (js2-node-pos fn-node)))
7775 (let ((pos (js2-current-token-beg)) ; LC position
7776 (pn (make-js2-block-node)) ; starts at LC position
7777 tt
7778 end)
7779 (cl-incf js2-nesting-of-function)
7780 (unwind-protect
7781 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7782 (= tt js2-EOF)
7783 (= tt js2-RC)))
7784 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7785 (js2-parse-statement)
7786 (js2-get-token)
7787 (js2-parse-function-stmt))))
7788 (cl-decf js2-nesting-of-function))
7789 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7790 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7791 (setq end (js2-current-token-end)))
7792 (setf (js2-node-pos pn) pos
7793 (js2-node-len pn) (- end pos))
7794 (setf (js2-function-node-body fn-node) pn)
7795 (js2-node-add-children fn-node pn)
7796 pn))
7797
7798 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7799 "Declare and fontify destructuring parameters inside NODE.
7800 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7801 (cond
7802 ((js2-name-node-p node)
7803 (let (leftpos)
7804 (js2-define-symbol decl-type (js2-name-node-name node)
7805 node ignore-not-in-block)
7806 (when face
7807 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7808 (+ leftpos (js2-node-len node))
7809 face 'record))))
7810 ((js2-object-node-p node)
7811 (dolist (elem (js2-object-node-elems node))
7812 (js2-define-destruct-symbols
7813 ;; In abbreviated destructuring {a, b}, right == left.
7814 (js2-object-prop-node-right elem)
7815 decl-type face ignore-not-in-block)))
7816 ((js2-array-node-p node)
7817 (dolist (elem (js2-array-node-elems node))
7818 (when elem
7819 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7820 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7821 (js2-node-len node)))))
7822
7823 (defun js2-parse-function-params (function-type fn-node pos)
7824 (if (js2-match-token js2-RP)
7825 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7826 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7827 (eq (js2-current-token-type) js2-NAME)))
7828 params param default-found rest-param-at)
7829 (when paren-free-arrow
7830 (js2-unget-token))
7831 (cl-loop for tt = (js2-peek-token)
7832 do
7833 (cond
7834 ;; destructuring param
7835 ((and (not paren-free-arrow)
7836 (or (= tt js2-LB) (= tt js2-LC)))
7837 (js2-get-token)
7838 (when default-found
7839 (js2-report-error "msg.no.default.after.default.param"))
7840 (setq param (js2-parse-destruct-primary-expr))
7841 (js2-define-destruct-symbols param
7842 js2-LP
7843 'js2-function-param)
7844 (push param params))
7845 ;; variable name
7846 (t
7847 (when (and (>= js2-language-version 200)
7848 (not paren-free-arrow)
7849 (js2-match-token js2-TRIPLEDOT)
7850 (not rest-param-at))
7851 ;; to report errors if there are more parameters
7852 (setq rest-param-at (length params)))
7853 (js2-must-match-name "msg.no.parm")
7854 (js2-record-face 'js2-function-param)
7855 (setq param (js2-create-name-node))
7856 (js2-define-symbol js2-LP (js2-current-token-string) param)
7857 ;; default parameter value
7858 (when (or (and default-found
7859 (not rest-param-at)
7860 (js2-must-match js2-ASSIGN
7861 "msg.no.default.after.default.param"
7862 (js2-node-pos param)
7863 (js2-node-len param)))
7864 (and (>= js2-language-version 200)
7865 (js2-match-token js2-ASSIGN)))
7866 (cl-assert (not paren-free-arrow))
7867 (let* ((pos (js2-node-pos param))
7868 (tt (js2-current-token-type))
7869 (op-pos (- (js2-current-token-beg) pos))
7870 (left param)
7871 (right (js2-parse-assign-expr))
7872 (len (- (js2-node-end right) pos)))
7873 (setq param (make-js2-assign-node
7874 :type tt :pos pos :len len :op-pos op-pos
7875 :left left :right right)
7876 default-found t)
7877 (js2-node-add-children param left right)))
7878 (push param params)))
7879 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7880 (js2-report-error "msg.param.after.rest" nil
7881 (js2-node-pos param) (js2-node-len param)))
7882 while
7883 (js2-match-token js2-COMMA))
7884 (when (and (not paren-free-arrow)
7885 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7886 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7887 (when rest-param-at
7888 (setf (js2-function-node-rest-p fn-node) t))
7889 (dolist (p params)
7890 (js2-node-add-children fn-node p)
7891 (push p (js2-function-node-params fn-node))))))
7892
7893 (defun js2-check-inconsistent-return-warning (fn-node name)
7894 "Possibly show inconsistent-return warning.
7895 Last token scanned is the close-curly for the function body."
7896 (when (and js2-mode-show-strict-warnings
7897 js2-strict-inconsistent-return-warning
7898 (not (js2-has-consistent-return-usage
7899 (js2-function-node-body fn-node))))
7900 ;; Have it extend from close-curly to bol or beginning of block.
7901 (let ((pos (save-excursion
7902 (goto-char (js2-current-token-end))
7903 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7904 (point-at-bol))))
7905 (end (js2-current-token-end)))
7906 (if (cl-plusp (js2-name-node-length name))
7907 (js2-add-strict-warning "msg.no.return.value"
7908 (js2-name-node-name name) pos end)
7909 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7910
7911 (defun js2-parse-function-stmt ()
7912 (let ((pos (js2-current-token-beg))
7913 (star-p (js2-match-token js2-MUL)))
7914 (js2-must-match-name "msg.unnamed.function.stmt")
7915 (let ((name (js2-create-name-node t))
7916 pn member-expr)
7917 (cond
7918 ((js2-match-token js2-LP)
7919 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7920 (js2-allow-member-expr-as-function-name
7921 (setq member-expr (js2-parse-member-expr-tail nil name))
7922 (js2-parse-highlight-member-expr-fn-name member-expr)
7923 (js2-must-match js2-LP "msg.no.paren.parms")
7924 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7925 (js2-function-node-member-expr pn) member-expr)
7926 pn)
7927 (t
7928 (js2-report-error "msg.no.paren.parms")
7929 (make-js2-error-node))))))
7930
7931 (defun js2-parse-function-expr ()
7932 (let ((pos (js2-current-token-beg))
7933 (star-p (js2-match-token js2-MUL))
7934 name)
7935 (when (js2-match-token js2-NAME)
7936 (setq name (js2-create-name-node t)))
7937 (js2-must-match js2-LP "msg.no.paren.parms")
7938 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7939
7940 (defun js2-parse-function (function-type pos star-p &optional name)
7941 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7942 beginning of the first token (function keyword, unless it's an
7943 arrow function), NAME is js2-name-node."
7944 (let (fn-node lp)
7945 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7946 (setq lp (js2-current-token-beg)))
7947 (setf fn-node (make-js2-function-node :pos pos
7948 :name name
7949 :form function-type
7950 :lp (if lp (- lp pos))
7951 :generator-type (and star-p 'STAR)))
7952 (when name
7953 (js2-set-face (js2-node-pos name) (js2-node-end name)
7954 'font-lock-function-name-face 'record)
7955 (when (and (eq function-type 'FUNCTION_STATEMENT)
7956 (cl-plusp (js2-name-node-length name)))
7957 ;; Function statements define a symbol in the enclosing scope
7958 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7959 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
7960 ;; 1. Nested functions are not affected by the dynamic scope flag
7961 ;; as dynamic scope is already a parent of their scope.
7962 ;; 2. Functions defined under the with statement also immune to
7963 ;; this setup, in which case dynamic scope is ignored in favor
7964 ;; of the with object.
7965 (setf (js2-function-node-ignore-dynamic fn-node) t))
7966 ;; dynamically bind all the per-function variables
7967 (let ((js2-current-script-or-fn fn-node)
7968 (js2-current-scope fn-node)
7969 (js2-nesting-of-with 0)
7970 (js2-end-flags 0)
7971 js2-label-set
7972 js2-loop-set
7973 js2-loop-and-switch-set)
7974 (js2-parse-function-params function-type fn-node pos)
7975 (when (eq function-type 'FUNCTION_ARROW)
7976 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7977 (if (and (>= js2-language-version 180)
7978 (/= (js2-peek-token) js2-LC))
7979 (js2-parse-function-closure-body fn-node)
7980 (js2-parse-function-body fn-node))
7981 (js2-check-inconsistent-return-warning fn-node name)
7982
7983 (when name
7984 (js2-node-add-children fn-node name)
7985 ;; Function expressions define a name only in the body of the
7986 ;; function, and only if not hidden by a parameter name
7987 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7988 (null (js2-scope-get-symbol js2-current-scope
7989 (js2-name-node-name name))))
7990 (js2-define-symbol js2-FUNCTION
7991 (js2-name-node-name name)
7992 fn-node))
7993 (when (eq function-type 'FUNCTION_STATEMENT)
7994 (js2-record-imenu-functions fn-node))))
7995
7996 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7997 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7998 ;; We wait until after parsing the function to set its parent scope,
7999 ;; since `js2-define-symbol' needs the defining-scope check to stop
8000 ;; at the function boundary when checking for redeclarations.
8001 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8002 fn-node))
8003
8004 (defun js2-parse-statements (&optional parent)
8005 "Parse a statement list. Last token consumed must be js2-LC.
8006
8007 PARENT can be a `js2-block-node', in which case the statements are
8008 appended to PARENT. Otherwise a new `js2-block-node' is created
8009 and returned.
8010
8011 This function does not match the closing js2-RC: the caller
8012 matches the RC so it can provide a suitable error message if not
8013 matched. This means it's up to the caller to set the length of
8014 the node to include the closing RC. The node start pos is set to
8015 the absolute buffer start position, and the caller should fix it
8016 up to be relative to the parent node. All children of this block
8017 node are given relative start positions and correct lengths."
8018 (let ((pn (or parent (make-js2-block-node)))
8019 tt)
8020 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8021 (/= tt js2-RC))
8022 (js2-block-node-push pn (js2-parse-statement)))
8023 pn))
8024
8025 (defun js2-parse-statement ()
8026 (let (pn beg end)
8027 ;; coarse-grained user-interrupt check - needs work
8028 (and js2-parse-interruptable-p
8029 (zerop (% (cl-incf js2-parse-stmt-count)
8030 js2-statements-per-pause))
8031 (input-pending-p)
8032 (throw 'interrupted t))
8033 (setq pn (js2-statement-helper))
8034 ;; no-side-effects warning check
8035 (unless (js2-node-has-side-effects pn)
8036 (setq end (js2-node-end pn))
8037 (save-excursion
8038 (goto-char end)
8039 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8040 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8041 pn))
8042
8043 ;; These correspond to the switch cases in Parser.statementHelper
8044 (defconst js2-parsers
8045 (let ((parsers (make-vector js2-num-tokens
8046 #'js2-parse-expr-stmt)))
8047 (aset parsers js2-BREAK #'js2-parse-break)
8048 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8049 (aset parsers js2-CONST #'js2-parse-const-var)
8050 (aset parsers js2-CONTINUE #'js2-parse-continue)
8051 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8052 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8053 (aset parsers js2-DO #'js2-parse-do)
8054 (aset parsers js2-EXPORT #'js2-parse-export)
8055 (aset parsers js2-FOR #'js2-parse-for)
8056 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8057 (aset parsers js2-IF #'js2-parse-if)
8058 (aset parsers js2-IMPORT #'js2-parse-import)
8059 (aset parsers js2-LC #'js2-parse-block)
8060 (aset parsers js2-LET #'js2-parse-let-stmt)
8061 (aset parsers js2-NAME #'js2-parse-name-or-label)
8062 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8063 (aset parsers js2-SEMI #'js2-parse-semi)
8064 (aset parsers js2-SWITCH #'js2-parse-switch)
8065 (aset parsers js2-THROW #'js2-parse-throw)
8066 (aset parsers js2-TRY #'js2-parse-try)
8067 (aset parsers js2-VAR #'js2-parse-const-var)
8068 (aset parsers js2-WHILE #'js2-parse-while)
8069 (aset parsers js2-WITH #'js2-parse-with)
8070 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8071 parsers)
8072 "A vector mapping token types to parser functions.")
8073
8074 (defun js2-parse-warn-missing-semi (beg end)
8075 (and js2-mode-show-strict-warnings
8076 js2-strict-missing-semi-warning
8077 (js2-add-strict-warning
8078 "msg.missing.semi" nil
8079 ;; back up to beginning of statement or line
8080 (max beg (save-excursion
8081 (goto-char end)
8082 (point-at-bol)))
8083 end)))
8084
8085 (defconst js2-no-semi-insertion
8086 (list js2-IF
8087 js2-SWITCH
8088 js2-WHILE
8089 js2-DO
8090 js2-FOR
8091 js2-TRY
8092 js2-WITH
8093 js2-LC
8094 js2-ERROR
8095 js2-SEMI
8096 js2-CLASS
8097 js2-FUNCTION)
8098 "List of tokens that don't do automatic semicolon insertion.")
8099
8100 (defconst js2-autoinsert-semi-and-warn
8101 (list js2-ERROR js2-EOF js2-RC))
8102
8103 (defun js2-statement-helper ()
8104 (let* ((tt (js2-get-token))
8105 (first-tt tt)
8106 (parser (if (= tt js2-ERROR)
8107 #'js2-parse-semi
8108 (aref js2-parsers tt)))
8109 pn)
8110 ;; If the statement is set, then it's been told its label by now.
8111 (and js2-labeled-stmt
8112 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8113 (setq js2-labeled-stmt nil))
8114 (setq pn (funcall parser))
8115 ;; Don't do auto semi insertion for certain statement types.
8116 (unless (or (memq first-tt js2-no-semi-insertion)
8117 (js2-labeled-stmt-node-p pn))
8118 (js2-auto-insert-semicolon pn))
8119 pn))
8120
8121 (defun js2-auto-insert-semicolon (pn)
8122 (let* ((tt (js2-get-token))
8123 (pos (js2-node-pos pn)))
8124 (cond
8125 ((= tt js2-SEMI)
8126 ;; extend the node bounds to include the semicolon.
8127 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8128 ((memq tt js2-autoinsert-semi-and-warn)
8129 (js2-unget-token) ; Not ';', do not consume.
8130 ;; Autoinsert ;
8131 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8132 (t
8133 (if (not (js2-token-follows-eol-p (js2-current-token)))
8134 ;; Report error if no EOL or autoinsert ';' otherwise
8135 (js2-report-error "msg.no.semi.stmt")
8136 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8137 (js2-unget-token) ; Not ';', do not consume.
8138 ))))
8139
8140 (defun js2-parse-condition ()
8141 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8142 The parens are discarded and the expression node is returned.
8143 The `pos' field of the return value is set to an absolute position
8144 that must be fixed up by the caller.
8145 Return value is a list (EXPR LP RP), with absolute paren positions."
8146 (let (pn lp rp)
8147 (if (js2-must-match js2-LP "msg.no.paren.cond")
8148 (setq lp (js2-current-token-beg)))
8149 (setq pn (js2-parse-expr))
8150 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8151 (setq rp (js2-current-token-beg)))
8152 ;; Report strict warning on code like "if (a = 7) ..."
8153 (if (and js2-strict-cond-assign-warning
8154 (js2-assign-node-p pn))
8155 (js2-add-strict-warning "msg.equal.as.assign" nil
8156 (js2-node-pos pn)
8157 (+ (js2-node-pos pn)
8158 (js2-node-len pn))))
8159 (list pn lp rp)))
8160
8161 (defun js2-parse-if ()
8162 "Parser for if-statement. Last matched token must be js2-IF."
8163 (let ((pos (js2-current-token-beg))
8164 cond if-true if-false else-pos end pn)
8165 (setq cond (js2-parse-condition)
8166 if-true (js2-parse-statement)
8167 if-false (if (js2-match-token js2-ELSE)
8168 (progn
8169 (setq else-pos (- (js2-current-token-beg) pos))
8170 (js2-parse-statement)))
8171 end (js2-node-end (or if-false if-true))
8172 pn (make-js2-if-node :pos pos
8173 :len (- end pos)
8174 :condition (car cond)
8175 :then-part if-true
8176 :else-part if-false
8177 :else-pos else-pos
8178 :lp (js2-relpos (cl-second cond) pos)
8179 :rp (js2-relpos (cl-third cond) pos)))
8180 (js2-node-add-children pn (car cond) if-true if-false)
8181 pn))
8182
8183 (defun js2-parse-import ()
8184 "Parse import statement. The current token must be js2-IMPORT."
8185 (unless (js2-ast-root-p js2-current-scope)
8186 (js2-report-error "msg.mod.import.decl.at.top.level"))
8187 (let ((beg (js2-current-token-beg)))
8188 (cond ((js2-match-token js2-STRING)
8189 (make-js2-import-node
8190 :pos beg
8191 :len (- (js2-current-token-end) beg)
8192 :module-id (js2-current-token-string)))
8193 (t
8194 (let* ((import-clause (js2-parse-import-clause))
8195 (from-clause (and import-clause (js2-parse-from-clause)))
8196 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8197 (node (make-js2-import-node
8198 :pos beg
8199 :len (- (js2-current-token-end) beg)
8200 :import import-clause
8201 :from from-clause
8202 :module-id module-id)))
8203 (when import-clause
8204 (js2-node-add-children node import-clause))
8205 (when from-clause
8206 (js2-node-add-children node from-clause))
8207 node)))))
8208
8209 (defun js2-parse-import-clause ()
8210 "Parse the bindings in an import statement.
8211 This can take many forms:
8212
8213 ImportedDefaultBinding -> 'foo'
8214 NameSpaceImport -> '* as lib'
8215 NamedImports -> '{foo as bar, bang}'
8216 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8217 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8218
8219 Try to match namespace imports and named imports first because nothing can
8220 come after them. If it is an imported default binding, then it could have named
8221 imports or a namespace import that follows it.
8222 "
8223 (let* ((beg (js2-current-token-beg))
8224 (clause (make-js2-import-clause-node
8225 :pos beg))
8226 (children (list)))
8227 (cond
8228 ((js2-match-token js2-MUL)
8229 (let ((ns-import (js2-parse-namespace-import)))
8230 (when ns-import
8231 (let ((name-node (js2-namespace-import-node-name ns-import)))
8232 (js2-define-symbol
8233 js2-LET (js2-name-node-name name-node) name-node t)))
8234 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8235 (push ns-import children)))
8236 ((js2-match-token js2-LC)
8237 (let ((imports (js2-parse-export-bindings t)))
8238 (setf (js2-import-clause-node-named-imports clause) imports)
8239 (dolist (import imports)
8240 (push import children)
8241 (let ((name-node (js2-export-binding-node-local-name import)))
8242 (when name-node
8243 (js2-define-symbol
8244 js2-LET (js2-name-node-name name-node) name-node t))))))
8245 ((= (js2-peek-token) js2-NAME)
8246 (let ((binding (js2-maybe-parse-export-binding)))
8247 (let ((node-name (js2-export-binding-node-local-name binding)))
8248 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8249 (setf (js2-import-clause-node-default-binding clause) binding)
8250 (push binding children))
8251 (when (js2-match-token js2-COMMA)
8252 (cond
8253 ((js2-match-token js2-MUL)
8254 (let ((ns-import (js2-parse-namespace-import)))
8255 (let ((name-node (js2-namespace-import-node-name ns-import)))
8256 (js2-define-symbol
8257 js2-LET (js2-name-node-name name-node) name-node t))
8258 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8259 (push ns-import children)))
8260 ((js2-match-token js2-LC)
8261 (let ((imports (js2-parse-export-bindings t)))
8262 (setf (js2-import-clause-node-named-imports clause) imports)
8263 (dolist (import imports)
8264 (push import children)
8265 (let ((name-node (js2-export-binding-node-local-name import)))
8266 (when name-node
8267 (js2-define-symbol
8268 js2-LET (js2-name-node-name name-node) name-node t))))))
8269 (t (js2-report-error "msg.syntax")))))
8270 (t (js2-report-error "msg.mod.declaration.after.import")))
8271 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8272 (apply #'js2-node-add-children clause children)
8273 clause))
8274
8275 (defun js2-parse-namespace-import ()
8276 "Parse a namespace import expression such as '* as bar'.
8277 The current token must be js2-MUL."
8278 (let ((beg (js2-current-token-beg)))
8279 (when (js2-must-match js2-NAME "msg.syntax")
8280 (if (equal "as" (js2-current-token-string))
8281 (when (js2-must-match-prop-name "msg.syntax")
8282 (let ((node (make-js2-namespace-import-node
8283 :pos beg
8284 :len (- (js2-current-token-end) beg)
8285 :name (make-js2-name-node
8286 :pos (js2-current-token-beg)
8287 :len (js2-current-token-end)
8288 :name (js2-current-token-string)))))
8289 (js2-node-add-children node (js2-namespace-import-node-name node))
8290 node))
8291 (js2-unget-token)
8292 (js2-report-error "msg.syntax")))))
8293
8294
8295 (defun js2-parse-from-clause ()
8296 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8297 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8298 (let ((beg (js2-current-token-beg)))
8299 (if (equal "from" (js2-current-token-string))
8300 (cond
8301 ((js2-match-token js2-STRING)
8302 (make-js2-from-clause-node
8303 :pos beg
8304 :len (- (js2-current-token-end) beg)
8305 :module-id (js2-current-token-string)
8306 :metadata-p nil))
8307 ((js2-match-token js2-THIS)
8308 (when (js2-must-match-name "msg.mod.spec.after.from")
8309 (if (equal "module" (js2-current-token-string))
8310 (make-js2-from-clause-node
8311 :pos beg
8312 :len (- (js2-current-token-end) beg)
8313 :module-id "this"
8314 :metadata-p t)
8315 (js2-unget-token)
8316 (js2-unget-token)
8317 (js2-report-error "msg.mod.spec.after.from")
8318 nil)))
8319 (t (js2-report-error "msg.mod.spec.after.from") nil))
8320 (js2-unget-token)
8321 (js2-report-error "msg.mod.from.after.import.spec.set")
8322 nil))))
8323
8324 (defun js2-parse-export-bindings (&optional import-p)
8325 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8326 {foo as bar, baz as bang}. The current token must be
8327 js2-LC. Return a lisp list of js2-export-binding-node"
8328 (let ((bindings (list)))
8329 (while
8330 (let ((binding (js2-maybe-parse-export-binding)))
8331 (when binding
8332 (push binding bindings))
8333 (js2-match-token js2-COMMA)))
8334 (when (js2-must-match js2-RC (if import-p
8335 "msg.mod.rc.after.import.spec.list"
8336 "msg.mod.rc.after.export.spec.list"))
8337 (reverse bindings))))
8338
8339 (defun js2-maybe-parse-export-binding ()
8340 "Attempt to parse a binding expression found inside an import/export statement.
8341 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8342 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8343 js2-export-binding-node and consume all the tokens. If it does not match, it
8344 consumes no tokens."
8345 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8346 (beg (js2-current-token-beg))
8347 (extern-name-len (js2-current-token-len))
8348 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8349 (aref js2-kwd-tokens (js2-current-token-type)))))
8350 (if extern-name
8351 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8352 (if (and as (equal "as" (js2-current-token-string)))
8353 (let ((name
8354 (or
8355 (and (js2-match-token js2-DEFAULT) "default")
8356 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8357 (if name
8358 (let ((node (make-js2-export-binding-node
8359 :pos beg
8360 :len (- (js2-current-token-end) beg)
8361 :local-name (make-js2-name-node
8362 :name name
8363 :pos (js2-current-token-beg)
8364 :len (js2-current-token-len))
8365 :extern-name (make-js2-name-node
8366 :name extern-name
8367 :pos beg
8368 :len extern-name-len))))
8369 (js2-node-add-children
8370 node
8371 (js2-export-binding-node-local-name node)
8372 (js2-export-binding-node-extern-name node))
8373 node)
8374 (js2-unget-token)
8375 nil))
8376 (when as (js2-unget-token))
8377 (let* ((name-node (make-js2-name-node
8378 :name (js2-current-token-string)
8379 :pos (js2-current-token-beg)
8380 :len (js2-current-token-len)))
8381 (node (make-js2-export-binding-node
8382 :pos (js2-current-token-beg)
8383 :len (js2-current-token-len)
8384 :local-name name-node
8385 :extern-name name-node)))
8386 (when is-reserved-name
8387 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8388 (js2-node-add-children node name-node)
8389 node)))
8390 nil)))
8391
8392 (defun js2-parse-switch ()
8393 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8394 (let ((pos (js2-current-token-beg))
8395 tt pn discriminant has-default case-expr case-node
8396 case-pos cases stmt lp)
8397 (if (js2-must-match js2-LP "msg.no.paren.switch")
8398 (setq lp (js2-current-token-beg)))
8399 (setq discriminant (js2-parse-expr)
8400 pn (make-js2-switch-node :discriminant discriminant
8401 :pos pos
8402 :lp (js2-relpos lp pos)))
8403 (js2-node-add-children pn discriminant)
8404 (js2-enter-switch pn)
8405 (unwind-protect
8406 (progn
8407 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8408 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8409 (js2-must-match js2-LC "msg.no.brace.switch")
8410 (catch 'break
8411 (while t
8412 (setq tt (js2-next-token)
8413 case-pos (js2-current-token-beg))
8414 (cond
8415 ((= tt js2-RC)
8416 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8417 (throw 'break nil)) ; done
8418 ((= tt js2-CASE)
8419 (setq case-expr (js2-parse-expr))
8420 (js2-must-match js2-COLON "msg.no.colon.case"))
8421 ((= tt js2-DEFAULT)
8422 (if has-default
8423 (js2-report-error "msg.double.switch.default"))
8424 (setq has-default t
8425 case-expr nil)
8426 (js2-must-match js2-COLON "msg.no.colon.case"))
8427 (t
8428 (js2-report-error "msg.bad.switch")
8429 (throw 'break nil)))
8430 (setq case-node (make-js2-case-node :pos case-pos
8431 :len (- (js2-current-token-end) case-pos)
8432 :expr case-expr))
8433 (js2-node-add-children case-node case-expr)
8434 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8435 (/= tt js2-CASE)
8436 (/= tt js2-DEFAULT)
8437 (/= tt js2-EOF))
8438 (setf stmt (js2-parse-statement)
8439 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8440 (js2-block-node-push case-node stmt))
8441 (push case-node cases)))
8442 ;; add cases last, as pushing reverses the order to be correct
8443 (dolist (kid cases)
8444 (js2-node-add-children pn kid)
8445 (push kid (js2-switch-node-cases pn)))
8446 pn) ; return value
8447 (js2-exit-switch))))
8448
8449 (defun js2-parse-while ()
8450 "Parser for while-statement. Last matched token must be js2-WHILE."
8451 (let ((pos (js2-current-token-beg))
8452 (pn (make-js2-while-node))
8453 cond body)
8454 (js2-enter-loop pn)
8455 (unwind-protect
8456 (progn
8457 (setf cond (js2-parse-condition)
8458 (js2-while-node-condition pn) (car cond)
8459 body (js2-parse-statement)
8460 (js2-while-node-body pn) body
8461 (js2-node-len pn) (- (js2-node-end body) pos)
8462 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8463 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8464 (js2-node-add-children pn body (car cond)))
8465 (js2-exit-loop))
8466 pn))
8467
8468 (defun js2-parse-do ()
8469 "Parser for do-statement. Last matched token must be js2-DO."
8470 (let ((pos (js2-current-token-beg))
8471 (pn (make-js2-do-node))
8472 cond body end)
8473 (js2-enter-loop pn)
8474 (unwind-protect
8475 (progn
8476 (setq body (js2-parse-statement))
8477 (js2-must-match js2-WHILE "msg.no.while.do")
8478 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8479 cond (js2-parse-condition)
8480 (js2-do-node-condition pn) (car cond)
8481 (js2-do-node-body pn) body
8482 end js2-ts-cursor
8483 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8484 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8485 (js2-node-add-children pn (car cond) body))
8486 (js2-exit-loop))
8487 ;; Always auto-insert semicolon to follow SpiderMonkey:
8488 ;; It is required by ECMAScript but is ignored by the rest of
8489 ;; world; see bug 238945
8490 (if (js2-match-token js2-SEMI)
8491 (setq end js2-ts-cursor))
8492 (setf (js2-node-len pn) (- end pos))
8493 pn))
8494
8495 (defun js2-parse-export ()
8496 "Parse an export statement.
8497 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8498 expressions should only be either hoistable expressions (function or generator)
8499 or assignment expressions, but there is no checking to enforce that and so it
8500 will parse without error a small subset of
8501 invalid export statements."
8502 (unless (js2-ast-root-p js2-current-scope)
8503 (js2-report-error "msg.mod.export.decl.at.top.level"))
8504 (let ((beg (js2-current-token-beg))
8505 (children (list))
8506 exports-list from-clause declaration default)
8507 (cond
8508 ((js2-match-token js2-MUL)
8509 (setq from-clause (js2-parse-from-clause))
8510 (when from-clause
8511 (push from-clause children)))
8512 ((js2-match-token js2-LC)
8513 (setq exports-list (js2-parse-export-bindings))
8514 (when exports-list
8515 (dolist (export exports-list)
8516 (push export children)))
8517 (when (js2-match-token js2-NAME)
8518 (if (equal "from" (js2-current-token-string))
8519 (progn
8520 (js2-unget-token)
8521 (setq from-clause (js2-parse-from-clause)))
8522 (js2-unget-token))))
8523 ((js2-match-token js2-DEFAULT)
8524 (setq default (js2-parse-expr)))
8525 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8526 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8527 (t
8528 (setq declaration (js2-parse-expr))))
8529 (when from-clause
8530 (push from-clause children))
8531 (when declaration
8532 (push declaration children))
8533 (when default
8534 (push default children))
8535 (let ((node (make-js2-export-node
8536 :pos beg
8537 :len (- (js2-current-token-end) beg)
8538 :exports-list exports-list
8539 :from-clause from-clause
8540 :declaration declaration
8541 :default default)))
8542 (apply #'js2-node-add-children node children)
8543 node)))
8544
8545 (defun js2-parse-for ()
8546 "Parse a for, for-in or for each-in statement.
8547 Last matched token must be js2-FOR."
8548 (let ((for-pos (js2-current-token-beg))
8549 pn is-for-each is-for-in-or-of is-for-of
8550 in-pos each-pos tmp-pos
8551 init ; Node init is also foo in 'foo in object'.
8552 cond ; Node cond is also object in 'foo in object'.
8553 incr ; 3rd section of for-loop initializer.
8554 body tt lp rp)
8555 ;; See if this is a for each () instead of just a for ()
8556 (when (js2-match-token js2-NAME)
8557 (if (string= "each" (js2-current-token-string))
8558 (progn
8559 (setq is-for-each t
8560 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8561 (js2-record-face 'font-lock-keyword-face))
8562 (js2-report-error "msg.no.paren.for")))
8563 (if (js2-must-match js2-LP "msg.no.paren.for")
8564 (setq lp (- (js2-current-token-beg) for-pos)))
8565 (setq tt (js2-get-token))
8566 ;; 'for' makes local scope
8567 (js2-push-scope (make-js2-scope))
8568 (unwind-protect
8569 ;; parse init clause
8570 (let ((js2-in-for-init t)) ; set as dynamic variable
8571 (cond
8572 ((= tt js2-SEMI)
8573 (js2-unget-token)
8574 (setq init (make-js2-empty-expr-node)))
8575 ((or (= tt js2-VAR) (= tt js2-LET))
8576 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8577 (t
8578 (js2-unget-token)
8579 (setq init (js2-parse-expr)))))
8580 (if (or (js2-match-token js2-IN)
8581 (and (>= js2-language-version 200)
8582 (js2-match-contextual-kwd "of")
8583 (setq is-for-of t)))
8584 (setq is-for-in-or-of t
8585 in-pos (- (js2-current-token-beg) for-pos)
8586 ;; scope of iteration target object is not the scope we've created above.
8587 ;; stash current scope temporary.
8588 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8589 (js2-parse-expr))) ; object over which we're iterating
8590 ;; else ordinary for loop - parse cond and incr
8591 (js2-must-match js2-SEMI "msg.no.semi.for")
8592 (setq cond (if (= (js2-peek-token) js2-SEMI)
8593 (make-js2-empty-expr-node) ; no loop condition
8594 (js2-parse-expr)))
8595 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8596 (setq tmp-pos (js2-current-token-end)
8597 incr (if (= (js2-peek-token) js2-RP)
8598 (make-js2-empty-expr-node :pos tmp-pos)
8599 (js2-parse-expr))))
8600 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8601 (setq rp (- (js2-current-token-beg) for-pos)))
8602 (if (not is-for-in-or-of)
8603 (setq pn (make-js2-for-node :init init
8604 :condition cond
8605 :update incr
8606 :lp lp
8607 :rp rp))
8608 ;; cond could be null if 'in obj' got eaten by the init node.
8609 (if (js2-infix-node-p init)
8610 ;; it was (foo in bar) instead of (var foo in bar)
8611 (setq cond (js2-infix-node-right init)
8612 init (js2-infix-node-left init))
8613 (if (and (js2-var-decl-node-p init)
8614 (> (length (js2-var-decl-node-kids init)) 1))
8615 (js2-report-error "msg.mult.index")))
8616 (setq pn (make-js2-for-in-node :iterator init
8617 :object cond
8618 :in-pos in-pos
8619 :foreach-p is-for-each
8620 :each-pos each-pos
8621 :forof-p is-for-of
8622 :lp lp
8623 :rp rp)))
8624 (unwind-protect
8625 (progn
8626 (js2-enter-loop pn)
8627 ;; We have to parse the body -after- creating the loop node,
8628 ;; so that the loop node appears in the js2-loop-set, allowing
8629 ;; break/continue statements to find the enclosing loop.
8630 (setf body (js2-parse-statement)
8631 (js2-loop-node-body pn) body
8632 (js2-node-pos pn) for-pos
8633 (js2-node-len pn) (- (js2-node-end body) for-pos))
8634 (js2-node-add-children pn init cond incr body))
8635 ;; finally
8636 (js2-exit-loop))
8637 (js2-pop-scope))
8638 pn))
8639
8640 (defun js2-parse-try ()
8641 "Parse a try statement. Last matched token must be js2-TRY."
8642 (let ((try-pos (js2-current-token-beg))
8643 try-end
8644 try-block
8645 catch-blocks
8646 finally-block
8647 saw-default-catch
8648 peek)
8649 (if (/= (js2-peek-token) js2-LC)
8650 (js2-report-error "msg.no.brace.try"))
8651 (setq try-block (js2-parse-statement)
8652 try-end (js2-node-end try-block)
8653 peek (js2-peek-token))
8654 (cond
8655 ((= peek js2-CATCH)
8656 (while (js2-match-token js2-CATCH)
8657 (let* ((catch-pos (js2-current-token-beg))
8658 (catch-node (make-js2-catch-node :pos catch-pos))
8659 param
8660 guard-kwd
8661 catch-cond
8662 lp rp)
8663 (if saw-default-catch
8664 (js2-report-error "msg.catch.unreachable"))
8665 (if (js2-must-match js2-LP "msg.no.paren.catch")
8666 (setq lp (- (js2-current-token-beg) catch-pos)))
8667 (js2-push-scope catch-node)
8668 (let ((tt (js2-peek-token)))
8669 (cond
8670 ;; Destructuring pattern:
8671 ;; catch ({ message, file }) { ... }
8672 ((or (= tt js2-LB) (= tt js2-LC))
8673 (js2-get-token)
8674 (setq param (js2-parse-destruct-primary-expr))
8675 (js2-define-destruct-symbols param js2-LET nil))
8676 ;; Simple name.
8677 (t
8678 (js2-must-match-name "msg.bad.catchcond")
8679 (setq param (js2-create-name-node))
8680 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8681 ;; Catch condition.
8682 (if (js2-match-token js2-IF)
8683 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8684 catch-cond (js2-parse-expr))
8685 (setq saw-default-catch t))
8686 (if (js2-must-match js2-RP "msg.bad.catchcond")
8687 (setq rp (- (js2-current-token-beg) catch-pos)))
8688 (js2-must-match js2-LC "msg.no.brace.catchblock")
8689 (js2-parse-statements catch-node)
8690 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8691 (setq try-end (js2-current-token-end)))
8692 (js2-pop-scope)
8693 (setf (js2-node-len catch-node) (- try-end catch-pos)
8694 (js2-catch-node-param catch-node) param
8695 (js2-catch-node-guard-expr catch-node) catch-cond
8696 (js2-catch-node-guard-kwd catch-node) guard-kwd
8697 (js2-catch-node-lp catch-node) lp
8698 (js2-catch-node-rp catch-node) rp)
8699 (js2-node-add-children catch-node param catch-cond)
8700 (push catch-node catch-blocks))))
8701 ((/= peek js2-FINALLY)
8702 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8703 (js2-node-pos try-block)
8704 (- (setq try-end (js2-node-end try-block))
8705 (js2-node-pos try-block)))))
8706 (when (js2-match-token js2-FINALLY)
8707 (let ((finally-pos (js2-current-token-beg))
8708 (block (js2-parse-statement)))
8709 (setq try-end (js2-node-end block)
8710 finally-block (make-js2-finally-node :pos finally-pos
8711 :len (- try-end finally-pos)
8712 :body block))
8713 (js2-node-add-children finally-block block)))
8714 (let ((pn (make-js2-try-node :pos try-pos
8715 :len (- try-end try-pos)
8716 :try-block try-block
8717 :finally-block finally-block)))
8718 (js2-node-add-children pn try-block finally-block)
8719 ;; Push them onto the try-node, which reverses and corrects their order.
8720 (dolist (cb catch-blocks)
8721 (js2-node-add-children pn cb)
8722 (push cb (js2-try-node-catch-clauses pn)))
8723 pn)))
8724
8725 (defun js2-parse-throw ()
8726 "Parser for throw-statement. Last matched token must be js2-THROW."
8727 (let ((pos (js2-current-token-beg))
8728 expr pn)
8729 (if (= (js2-peek-token-or-eol) js2-EOL)
8730 ;; ECMAScript does not allow new lines before throw expression,
8731 ;; see bug 256617
8732 (js2-report-error "msg.bad.throw.eol"))
8733 (setq expr (js2-parse-expr)
8734 pn (make-js2-throw-node :pos pos
8735 :len (- (js2-node-end expr) pos)
8736 :expr expr))
8737 (js2-node-add-children pn expr)
8738 pn))
8739
8740 (defun js2-match-jump-label-name (label-name)
8741 "If break/continue specified a label, return that label's labeled stmt.
8742 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8743 does not match an existing label, reports an error and returns nil."
8744 (let ((bundle (cdr (assoc label-name js2-label-set))))
8745 (if (null bundle)
8746 (js2-report-error "msg.undef.label"))
8747 bundle))
8748
8749 (defun js2-parse-break ()
8750 "Parser for break-statement. Last matched token must be js2-BREAK."
8751 (let ((pos (js2-current-token-beg))
8752 (end (js2-current-token-end))
8753 break-target ; statement to break from
8754 break-label ; in "break foo", name-node representing the foo
8755 labels ; matching labeled statement to break to
8756 pn)
8757 (when (eq (js2-peek-token-or-eol) js2-NAME)
8758 (js2-get-token)
8759 (setq break-label (js2-create-name-node)
8760 end (js2-node-end break-label)
8761 ;; matchJumpLabelName only matches if there is one
8762 labels (js2-match-jump-label-name (js2-current-token-string))
8763 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8764 (unless (or break-target break-label)
8765 ;; no break target specified - try for innermost enclosing loop/switch
8766 (if (null js2-loop-and-switch-set)
8767 (unless break-label
8768 (js2-report-error "msg.bad.break" nil pos (length "break")))
8769 (setq break-target (car js2-loop-and-switch-set))))
8770 (setq pn (make-js2-break-node :pos pos
8771 :len (- end pos)
8772 :label break-label
8773 :target break-target))
8774 (js2-node-add-children pn break-label) ; but not break-target
8775 pn))
8776
8777 (defun js2-parse-continue ()
8778 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8779 (let ((pos (js2-current-token-beg))
8780 (end (js2-current-token-end))
8781 label ; optional user-specified label, a `js2-name-node'
8782 labels ; current matching labeled stmt, if any
8783 target ; the `js2-loop-node' target of this continue stmt
8784 pn)
8785 (when (= (js2-peek-token-or-eol) js2-NAME)
8786 (js2-get-token)
8787 (setq label (js2-create-name-node)
8788 end (js2-node-end label)
8789 ;; matchJumpLabelName only matches if there is one
8790 labels (js2-match-jump-label-name (js2-current-token-string))))
8791 (cond
8792 ((null labels) ; no current label to go to
8793 (if (null js2-loop-set) ; no loop to continue to
8794 (js2-report-error "msg.continue.outside" nil pos
8795 (length "continue"))
8796 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8797 (t
8798 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8799 (setq target (js2-labeled-stmt-node-stmt labels))
8800 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8801 (setq pn (make-js2-continue-node :pos pos
8802 :len (- end pos)
8803 :label label
8804 :target target))
8805 (js2-node-add-children pn label) ; but not target - it's not our child
8806 pn))
8807
8808 (defun js2-parse-with ()
8809 "Parser for with-statement. Last matched token must be js2-WITH."
8810 (let ((pos (js2-current-token-beg))
8811 obj body pn lp rp)
8812 (if (js2-must-match js2-LP "msg.no.paren.with")
8813 (setq lp (js2-current-token-beg)))
8814 (setq obj (js2-parse-expr))
8815 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8816 (setq rp (js2-current-token-beg)))
8817 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8818 (setq body (js2-parse-statement)))
8819 (setq pn (make-js2-with-node :pos pos
8820 :len (- (js2-node-end body) pos)
8821 :object obj
8822 :body body
8823 :lp (js2-relpos lp pos)
8824 :rp (js2-relpos rp pos)))
8825 (js2-node-add-children pn obj body)
8826 pn))
8827
8828 (defun js2-parse-const-var ()
8829 "Parser for var- or const-statement.
8830 Last matched token must be js2-CONST or js2-VAR."
8831 (let ((tt (js2-current-token-type))
8832 (pos (js2-current-token-beg))
8833 expr pn)
8834 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8835 pn (make-js2-expr-stmt-node :pos pos
8836 :len (- (js2-node-end expr) pos)
8837 :expr expr))
8838 (js2-node-add-children pn expr)
8839 pn))
8840
8841 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8842 (let ((pn (make-js2-expr-stmt-node :pos pos
8843 :len (js2-node-len expr)
8844 :type (if (js2-inside-function)
8845 js2-EXPR_VOID
8846 js2-EXPR_RESULT)
8847 :expr expr)))
8848 (if add-child
8849 (js2-node-add-children pn expr))
8850 pn))
8851
8852 (defun js2-parse-let-stmt ()
8853 "Parser for let-statement. Last matched token must be js2-LET."
8854 (let ((pos (js2-current-token-beg))
8855 expr pn)
8856 (if (= (js2-peek-token) js2-LP)
8857 ;; let expression in statement context
8858 (setq expr (js2-parse-let pos 'statement)
8859 pn (js2-wrap-with-expr-stmt pos expr t))
8860 ;; else we're looking at a statement like let x=6, y=7;
8861 (setf expr (js2-parse-variables js2-LET pos)
8862 pn (js2-wrap-with-expr-stmt pos expr t)
8863 (js2-node-type pn) js2-EXPR_RESULT))
8864 pn))
8865
8866 (defun js2-parse-ret-yield ()
8867 (js2-parse-return-or-yield (js2-current-token-type) nil))
8868
8869 (defconst js2-parse-return-stmt-enders
8870 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8871
8872 (defsubst js2-now-all-set (before after mask)
8873 "Return whether or not the bits in the mask have changed to all set.
8874 BEFORE is bits before change, AFTER is bits after change, and MASK is
8875 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8876 but not BEFORE."
8877 (and (/= (logand before mask) mask)
8878 (= (logand after mask) mask)))
8879
8880 (defun js2-parse-return-or-yield (tt expr-context)
8881 (let* ((pos (js2-current-token-beg))
8882 (end (js2-current-token-end))
8883 (before js2-end-flags)
8884 (inside-function (js2-inside-function))
8885 (gen-type (and inside-function (js2-function-node-generator-type
8886 js2-current-script-or-fn)))
8887 e ret name yield-star-p)
8888 (unless inside-function
8889 (js2-report-error (if (eq tt js2-RETURN)
8890 "msg.bad.return"
8891 "msg.bad.yield")))
8892 (when (and inside-function
8893 (eq gen-type 'STAR)
8894 (js2-match-token js2-MUL))
8895 (setq yield-star-p t))
8896 ;; This is ugly, but we don't want to require a semicolon.
8897 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8898 (setq e (js2-parse-expr)
8899 end (js2-node-end e)))
8900 (cond
8901 ((eq tt js2-RETURN)
8902 (js2-set-flag js2-end-flags (if (null e)
8903 js2-end-returns
8904 js2-end-returns-value))
8905 (setq ret (make-js2-return-node :pos pos
8906 :len (- end pos)
8907 :retval e))
8908 (js2-node-add-children ret e)
8909 ;; See if we need a strict mode warning.
8910 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8911 ;; more thorough and accurate than this before/after flag check.
8912 ;; E.g. if there's a finally-block that always returns, we shouldn't
8913 ;; show a warning generated by inconsistent returns in the catch blocks.
8914 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8915 ;; so we know which returns/yields to highlight, and we should get rid of
8916 ;; all the checking in `js2-parse-return-or-yield'.
8917 (if (and js2-strict-inconsistent-return-warning
8918 (js2-now-all-set before js2-end-flags
8919 (logior js2-end-returns js2-end-returns-value)))
8920 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8921 ((eq gen-type 'COMPREHENSION)
8922 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8923 ;; like SpiderMonkey does.
8924 (js2-report-error "msg.syntax" nil pos 5))
8925 (t
8926 (setq ret (make-js2-yield-node :pos pos
8927 :len (- end pos)
8928 :value e
8929 :star-p yield-star-p))
8930 (js2-node-add-children ret e)
8931 (unless expr-context
8932 (setq e ret
8933 ret (js2-wrap-with-expr-stmt pos e t))
8934 (js2-set-requires-activation)
8935 (js2-set-is-generator))))
8936 ;; see if we are mixing yields and value returns.
8937 (when (and inside-function
8938 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8939 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8940 'LEGACY))
8941 (setq name (js2-function-name js2-current-script-or-fn))
8942 (if (zerop (length name))
8943 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8944 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8945 ret))
8946
8947 (defun js2-parse-debugger ()
8948 (make-js2-keyword-node :type js2-DEBUGGER))
8949
8950 (defun js2-parse-block ()
8951 "Parser for a curly-delimited statement block.
8952 Last token matched must be `js2-LC'."
8953 (let ((pos (js2-current-token-beg))
8954 (pn (make-js2-scope)))
8955 (js2-push-scope pn)
8956 (unwind-protect
8957 (progn
8958 (js2-parse-statements pn)
8959 (js2-must-match js2-RC "msg.no.brace.block")
8960 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8961 (js2-pop-scope))
8962 pn))
8963
8964 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8965 (defun js2-parse-semi ()
8966 "Parse a statement or handle an error.
8967 Current token type is `js2-SEMI' or `js2-ERROR'."
8968 (let ((tt (js2-current-token-type)) pos len)
8969 (if (eq tt js2-SEMI)
8970 (make-js2-empty-expr-node :len 1)
8971 (setq pos (js2-current-token-beg)
8972 len (- (js2-current-token-end) pos))
8973 (js2-report-error "msg.syntax" nil pos len)
8974 (make-js2-error-node :pos pos :len len))))
8975
8976 (defun js2-parse-default-xml-namespace ()
8977 "Parse a `default xml namespace = <expr>' e4x statement."
8978 (let ((pos (js2-current-token-beg))
8979 end len expr unary)
8980 (js2-must-have-xml)
8981 (js2-set-requires-activation)
8982 (setq len (- js2-ts-cursor pos))
8983 (unless (and (js2-match-token js2-NAME)
8984 (string= (js2-current-token-string) "xml"))
8985 (js2-report-error "msg.bad.namespace" nil pos len))
8986 (unless (and (js2-match-token js2-NAME)
8987 (string= (js2-current-token-string) "namespace"))
8988 (js2-report-error "msg.bad.namespace" nil pos len))
8989 (unless (js2-match-token js2-ASSIGN)
8990 (js2-report-error "msg.bad.namespace" nil pos len))
8991 (setq expr (js2-parse-expr)
8992 end (js2-node-end expr)
8993 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8994 :pos pos
8995 :len (- end pos)
8996 :operand expr))
8997 (js2-node-add-children unary expr)
8998 (make-js2-expr-stmt-node :pos pos
8999 :len (- end pos)
9000 :expr unary)))
9001
9002 (defun js2-record-label (label bundle)
9003 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9004 (js2-get-token)
9005 (let ((name (js2-label-node-name label))
9006 labeled-stmt
9007 dup)
9008 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9009 ;; flag both labels if possible when used in editing mode
9010 (if (and js2-parse-ide-mode
9011 (setq dup (js2-get-label-by-name labeled-stmt name)))
9012 (js2-report-error "msg.dup.label" nil
9013 (js2-node-abs-pos dup) (js2-node-len dup)))
9014 (js2-report-error "msg.dup.label" nil
9015 (js2-node-pos label) (js2-node-len label)))
9016 (js2-labeled-stmt-node-add-label bundle label)
9017 (js2-node-add-children bundle label)
9018 ;; Add one reference to the bundle per label in `js2-label-set'
9019 (push (cons name bundle) js2-label-set)))
9020
9021 (defun js2-parse-name-or-label ()
9022 "Parser for identifier or label. Last token matched must be js2-NAME.
9023 Called when we found a name in a statement context. If it's a label, we gather
9024 up any following labels and the next non-label statement into a
9025 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9026 expression and return it wrapped in a `js2-expr-stmt-node'."
9027 (let ((pos (js2-current-token-beg))
9028 expr stmt bundle
9029 (continue t))
9030 ;; set check for label and call down to `js2-parse-primary-expr'
9031 (setq expr (js2-maybe-parse-label))
9032 (if (null expr)
9033 ;; Parse the non-label expression and wrap with expression stmt.
9034 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9035 ;; else parsed a label
9036 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9037 (js2-record-label expr bundle)
9038 ;; look for more labels
9039 (while (and continue (= (js2-get-token) js2-NAME))
9040 (if (setq expr (js2-maybe-parse-label))
9041 (js2-record-label expr bundle)
9042 (setq expr (js2-parse-expr)
9043 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9044 continue nil)
9045 (js2-auto-insert-semicolon stmt)))
9046 ;; no more labels; now parse the labeled statement
9047 (unwind-protect
9048 (unless stmt
9049 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9050 (js2-unget-token)
9051 (setq stmt (js2-statement-helper))))
9052 ;; remove the labels for this statement from the global set
9053 (dolist (label (js2-labeled-stmt-node-labels bundle))
9054 (setq js2-label-set (remove label js2-label-set))))
9055 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9056 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9057 (js2-node-add-children bundle stmt)
9058 bundle)))
9059
9060 (defun js2-maybe-parse-label ()
9061 (cl-assert (= (js2-current-token-type) js2-NAME))
9062 (let (label-pos
9063 (next-tt (js2-get-token))
9064 (label-end (js2-current-token-end)))
9065 ;; Do not consume colon, it is used as unwind indicator
9066 ;; to return to statementHelper.
9067 (js2-unget-token)
9068 (if (= next-tt js2-COLON)
9069 (prog2
9070 (setq label-pos (js2-current-token-beg))
9071 (make-js2-label-node :pos label-pos
9072 :len (- label-end label-pos)
9073 :name (js2-current-token-string))
9074 (js2-set-face label-pos
9075 label-end
9076 'font-lock-variable-name-face 'record))
9077 ;; Backtrack from the name token, too.
9078 (js2-unget-token)
9079 nil)))
9080
9081 (defun js2-parse-expr-stmt ()
9082 "Default parser in statement context, if no recognized statement found."
9083 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9084 (progn
9085 (js2-unget-token)
9086 (js2-parse-expr)) t))
9087
9088 (defun js2-parse-variables (decl-type pos)
9089 "Parse a comma-separated list of variable declarations.
9090 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9091
9092 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9093 For 'var' or 'const', the keyword should be the token last scanned.
9094
9095 POS is the position where the node should start. It's sometimes the
9096 var/const/let keyword, and other times the beginning of the first token
9097 in the first variable declaration.
9098
9099 Returns the parsed `js2-var-decl-node' expression node."
9100 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9101 :pos pos))
9102 destructuring kid-pos tt init name end nbeg nend vi
9103 (continue t))
9104 ;; Example:
9105 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9106 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9107 ;; var {a, b} = baz;
9108 (while continue
9109 (setq destructuring nil
9110 name nil
9111 tt (js2-get-token)
9112 kid-pos (js2-current-token-beg)
9113 end (js2-current-token-end)
9114 init nil)
9115 (if (or (= tt js2-LB) (= tt js2-LC))
9116 ;; Destructuring assignment, e.g., var [a, b] = ...
9117 (setq destructuring (js2-parse-destruct-primary-expr)
9118 end (js2-node-end destructuring))
9119 ;; Simple variable name
9120 (js2-unget-token)
9121 (when (js2-must-match-name "msg.bad.var")
9122 (setq name (js2-create-name-node)
9123 nbeg (js2-current-token-beg)
9124 nend (js2-current-token-end)
9125 end nend)
9126 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9127 (when (js2-match-token js2-ASSIGN)
9128 (setq init (js2-parse-assign-expr)
9129 end (js2-node-end init))
9130 (js2-record-imenu-functions init name))
9131 (when name
9132 (js2-set-face nbeg nend (if (js2-function-node-p init)
9133 'font-lock-function-name-face
9134 'font-lock-variable-name-face)
9135 'record))
9136 (setq vi (make-js2-var-init-node :pos kid-pos
9137 :len (- end kid-pos)
9138 :type decl-type))
9139 (if destructuring
9140 (progn
9141 (if (and (null init) (not js2-in-for-init))
9142 (js2-report-error "msg.destruct.assign.no.init"))
9143 (js2-define-destruct-symbols destructuring
9144 decl-type
9145 'font-lock-variable-name-face)
9146 (setf (js2-var-init-node-target vi) destructuring))
9147 (setf (js2-var-init-node-target vi) name))
9148 (setf (js2-var-init-node-initializer vi) init)
9149 (js2-node-add-children vi name destructuring init)
9150 (js2-block-node-push result vi)
9151 (unless (js2-match-token js2-COMMA)
9152 (setq continue nil)))
9153 (setf (js2-node-len result) (- end pos))
9154 result))
9155
9156 (defun js2-parse-let (pos &optional stmt-p)
9157 "Parse a let expression or statement.
9158 A let-expression is of the form `let (vars) expr'.
9159 A let-statment is of the form `let (vars) {statements}'.
9160 The third form of let is a variable declaration list, handled
9161 by `js2-parse-variables'."
9162 (let ((pn (make-js2-let-node :pos pos))
9163 beg vars body)
9164 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9165 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9166 (js2-push-scope pn)
9167 (unwind-protect
9168 (progn
9169 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9170 (if (js2-must-match js2-RP "msg.no.paren.let")
9171 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9172 (if (and stmt-p (js2-match-token js2-LC))
9173 ;; let statement
9174 (progn
9175 (setf beg (js2-current-token-beg) ; position stmt at LC
9176 body (js2-parse-statements))
9177 (js2-must-match js2-RC "msg.no.curly.let")
9178 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9179 (js2-node-len pn) (- (js2-current-token-end) pos)
9180 (js2-let-node-body pn) body
9181 (js2-node-type pn) js2-LET))
9182 ;; let expression
9183 (setf body (js2-parse-expr)
9184 (js2-node-len pn) (- (js2-node-end body) pos)
9185 (js2-let-node-body pn) body))
9186 (setf (js2-let-node-vars pn) vars)
9187 (js2-node-add-children pn vars body))
9188 (js2-pop-scope))
9189 pn))
9190
9191 (defun js2-define-new-symbol (decl-type name node &optional scope)
9192 (js2-scope-put-symbol (or scope js2-current-scope)
9193 name
9194 (make-js2-symbol decl-type name node)))
9195
9196 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9197 "Define a symbol in the current scope.
9198 If NODE is non-nil, it is the AST node associated with the symbol."
9199 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9200 (symbol (if defining-scope
9201 (js2-scope-get-symbol defining-scope name)))
9202 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9203 (pos (if node (js2-node-abs-pos node)))
9204 (len (if node (js2-node-len node))))
9205 (cond
9206 ((and symbol ; already defined
9207 (or (= sdt js2-CONST) ; old version is const
9208 (= decl-type js2-CONST) ; new version is const
9209 ;; two let-bound vars in this block have same name
9210 (and (= sdt js2-LET)
9211 (eq defining-scope js2-current-scope))))
9212 (js2-report-error
9213 (cond
9214 ((= sdt js2-CONST) "msg.const.redecl")
9215 ((= sdt js2-LET) "msg.let.redecl")
9216 ((= sdt js2-VAR) "msg.var.redecl")
9217 ((= sdt js2-FUNCTION) "msg.function.redecl")
9218 (t "msg.parm.redecl"))
9219 name pos len))
9220 ((= decl-type js2-LET)
9221 (if (and (not ignore-not-in-block)
9222 (or (= (js2-node-type js2-current-scope) js2-IF)
9223 (js2-loop-node-p js2-current-scope)))
9224 (js2-report-error "msg.let.decl.not.in.block")
9225 (js2-define-new-symbol decl-type name node)))
9226 ((or (= decl-type js2-VAR)
9227 (= decl-type js2-CONST)
9228 (= decl-type js2-FUNCTION))
9229 (if symbol
9230 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9231 (js2-add-strict-warning "msg.var.redecl" name)
9232 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9233 (js2-add-strict-warning "msg.var.hides.arg" name)))
9234 (js2-define-new-symbol decl-type name node
9235 js2-current-script-or-fn)))
9236 ((= decl-type js2-LP)
9237 (if symbol
9238 ;; must be duplicate parameter. Second parameter hides the
9239 ;; first, so go ahead and add the second pararameter
9240 (js2-report-warning "msg.dup.parms" name))
9241 (js2-define-new-symbol decl-type name node))
9242 (t (js2-code-bug)))))
9243
9244 (defun js2-parse-paren-expr-or-generator-comp ()
9245 (let ((px-pos (js2-current-token-beg)))
9246 (cond
9247 ((and (>= js2-language-version 200)
9248 (js2-match-token js2-FOR))
9249 (js2-parse-generator-comp px-pos))
9250 ((and (>= js2-language-version 200)
9251 (js2-match-token js2-RP))
9252 ;; Not valid expression syntax, but this is valid in an arrow
9253 ;; function with no params: () => body.
9254 (if (eq (js2-peek-token) js2-ARROW)
9255 ;; Return whatever, it will hopefully be rewinded and
9256 ;; reparsed when we reach the =>.
9257 (make-js2-keyword-node :type js2-NULL)
9258 (js2-report-error "msg.syntax")
9259 (make-js2-error-node)))
9260 (t
9261 (let* ((js2-in-for-init nil)
9262 (expr (js2-parse-expr))
9263 (pn (make-js2-paren-node :pos px-pos
9264 :expr expr
9265 :len (- (js2-current-token-end)
9266 px-pos))))
9267 (js2-node-add-children pn (js2-paren-node-expr pn))
9268 (js2-must-match js2-RP "msg.no.paren")
9269 pn)))))
9270
9271 (defun js2-parse-expr (&optional oneshot)
9272 (let* ((pn (js2-parse-assign-expr))
9273 (pos (js2-node-pos pn))
9274 left
9275 right
9276 op-pos)
9277 (while (and (not oneshot)
9278 (js2-match-token js2-COMMA))
9279 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9280 (if (= (js2-peek-token) js2-YIELD)
9281 (js2-report-error "msg.yield.parenthesized"))
9282 (setq right (js2-parse-assign-expr)
9283 left pn
9284 pn (make-js2-infix-node :type js2-COMMA
9285 :pos pos
9286 :len (- js2-ts-cursor pos)
9287 :op-pos op-pos
9288 :left left
9289 :right right))
9290 (js2-node-add-children pn left right))
9291 pn))
9292
9293 (defun js2-parse-assign-expr ()
9294 (let ((tt (js2-get-token))
9295 (pos (js2-current-token-beg))
9296 pn left right op-pos
9297 ts-state recorded-identifiers parsed-errors)
9298 (if (= tt js2-YIELD)
9299 (js2-parse-return-or-yield tt t)
9300 ;; Save the tokenizer state in case we find an arrow function
9301 ;; and have to rewind.
9302 (setq ts-state (make-js2-ts-state)
9303 recorded-identifiers js2-recorded-identifiers
9304 parsed-errors js2-parsed-errors)
9305 ;; not yield - parse assignment expression
9306 (setq pn (js2-parse-cond-expr)
9307 tt (js2-get-token))
9308 (cond
9309 ((and (<= js2-first-assign tt)
9310 (<= tt js2-last-assign))
9311 ;; tt express assignment (=, |=, ^=, ..., %=)
9312 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9313 left pn)
9314 (setq right (js2-parse-assign-expr)
9315 pn (make-js2-assign-node :type tt
9316 :pos pos
9317 :len (- (js2-node-end right) pos)
9318 :op-pos op-pos
9319 :left left
9320 :right right))
9321 (when js2-parse-ide-mode
9322 (js2-highlight-assign-targets pn left right)
9323 (js2-record-imenu-functions right left))
9324 ;; do this last so ide checks above can use absolute positions
9325 (js2-node-add-children pn left right))
9326 ((and (= tt js2-ARROW)
9327 (>= js2-language-version 200))
9328 (js2-ts-seek ts-state)
9329 (setq js2-recorded-identifiers recorded-identifiers
9330 js2-parsed-errors parsed-errors)
9331 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9332 (t
9333 (js2-unget-token)))
9334 pn)))
9335
9336 (defun js2-parse-cond-expr ()
9337 (let ((pos (js2-current-token-beg))
9338 (pn (js2-parse-or-expr))
9339 test-expr
9340 if-true
9341 if-false
9342 q-pos
9343 c-pos)
9344 (when (js2-match-token js2-HOOK)
9345 (setq q-pos (- (js2-current-token-beg) pos)
9346 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9347 (js2-must-match js2-COLON "msg.no.colon.cond")
9348 (setq c-pos (- (js2-current-token-beg) pos)
9349 if-false (js2-parse-assign-expr)
9350 test-expr pn
9351 pn (make-js2-cond-node :pos pos
9352 :len (- (js2-node-end if-false) pos)
9353 :test-expr test-expr
9354 :true-expr if-true
9355 :false-expr if-false
9356 :q-pos q-pos
9357 :c-pos c-pos))
9358 (js2-node-add-children pn test-expr if-true if-false))
9359 pn))
9360
9361 (defun js2-make-binary (type left parser)
9362 "Helper for constructing a binary-operator AST node.
9363 LEFT is the left-side-expression, already parsed, and the
9364 binary operator should have just been matched.
9365 PARSER is a function to call to parse the right operand,
9366 or a `js2-node' struct if it has already been parsed.
9367 FIXME: The latter option is unused?"
9368 (let* ((pos (js2-node-pos left))
9369 (op-pos (- (js2-current-token-beg) pos))
9370 (right (if (js2-node-p parser)
9371 parser
9372 (js2-get-token)
9373 (funcall parser)))
9374 (pn (make-js2-infix-node :type type
9375 :pos pos
9376 :len (- (js2-node-end right) pos)
9377 :op-pos op-pos
9378 :left left
9379 :right right)))
9380 (js2-node-add-children pn left right)
9381 pn))
9382
9383 (defun js2-parse-or-expr ()
9384 (let ((pn (js2-parse-and-expr)))
9385 (when (js2-match-token js2-OR)
9386 (setq pn (js2-make-binary js2-OR
9387 pn
9388 'js2-parse-or-expr)))
9389 pn))
9390
9391 (defun js2-parse-and-expr ()
9392 (let ((pn (js2-parse-bit-or-expr)))
9393 (when (js2-match-token js2-AND)
9394 (setq pn (js2-make-binary js2-AND
9395 pn
9396 'js2-parse-and-expr)))
9397 pn))
9398
9399 (defun js2-parse-bit-or-expr ()
9400 (let ((pn (js2-parse-bit-xor-expr)))
9401 (while (js2-match-token js2-BITOR)
9402 (setq pn (js2-make-binary js2-BITOR
9403 pn
9404 'js2-parse-bit-xor-expr)))
9405 pn))
9406
9407 (defun js2-parse-bit-xor-expr ()
9408 (let ((pn (js2-parse-bit-and-expr)))
9409 (while (js2-match-token js2-BITXOR)
9410 (setq pn (js2-make-binary js2-BITXOR
9411 pn
9412 'js2-parse-bit-and-expr)))
9413 pn))
9414
9415 (defun js2-parse-bit-and-expr ()
9416 (let ((pn (js2-parse-eq-expr)))
9417 (while (js2-match-token js2-BITAND)
9418 (setq pn (js2-make-binary js2-BITAND
9419 pn
9420 'js2-parse-eq-expr)))
9421 pn))
9422
9423 (defconst js2-parse-eq-ops
9424 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9425
9426 (defun js2-parse-eq-expr ()
9427 (let ((pn (js2-parse-rel-expr))
9428 tt)
9429 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9430 (setq pn (js2-make-binary tt
9431 pn
9432 'js2-parse-rel-expr)))
9433 (js2-unget-token)
9434 pn))
9435
9436 (defconst js2-parse-rel-ops
9437 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9438
9439 (defun js2-parse-rel-expr ()
9440 (let ((pn (js2-parse-shift-expr))
9441 (continue t)
9442 tt)
9443 (while continue
9444 (setq tt (js2-get-token))
9445 (cond
9446 ((and js2-in-for-init (= tt js2-IN))
9447 (js2-unget-token)
9448 (setq continue nil))
9449 ((memq tt js2-parse-rel-ops)
9450 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9451 (t
9452 (js2-unget-token)
9453 (setq continue nil))))
9454 pn))
9455
9456 (defconst js2-parse-shift-ops
9457 (list js2-LSH js2-URSH js2-RSH))
9458
9459 (defun js2-parse-shift-expr ()
9460 (let ((pn (js2-parse-add-expr))
9461 tt
9462 (continue t))
9463 (while continue
9464 (setq tt (js2-get-token))
9465 (if (memq tt js2-parse-shift-ops)
9466 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9467 (js2-unget-token)
9468 (setq continue nil)))
9469 pn))
9470
9471 (defun js2-parse-add-expr ()
9472 (let ((pn (js2-parse-mul-expr))
9473 tt
9474 (continue t))
9475 (while continue
9476 (setq tt (js2-get-token))
9477 (if (or (= tt js2-ADD) (= tt js2-SUB))
9478 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9479 (js2-unget-token)
9480 (setq continue nil)))
9481 pn))
9482
9483 (defconst js2-parse-mul-ops
9484 (list js2-MUL js2-DIV js2-MOD))
9485
9486 (defun js2-parse-mul-expr ()
9487 (let ((pn (js2-parse-unary-expr))
9488 tt
9489 (continue t))
9490 (while continue
9491 (setq tt (js2-get-token))
9492 (if (memq tt js2-parse-mul-ops)
9493 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9494 (js2-unget-token)
9495 (setq continue nil)))
9496 pn))
9497
9498 (defun js2-make-unary (type parser &rest args)
9499 "Make a unary node of type TYPE.
9500 PARSER is either a node (for postfix operators) or a function to call
9501 to parse the operand (for prefix operators)."
9502 (let* ((pos (js2-current-token-beg))
9503 (postfix (js2-node-p parser))
9504 (expr (if postfix
9505 parser
9506 (apply parser args)))
9507 end
9508 pn)
9509 (if postfix ; e.g. i++
9510 (setq pos (js2-node-pos expr)
9511 end (js2-current-token-end))
9512 (setq end (js2-node-end expr)))
9513 (setq pn (make-js2-unary-node :type type
9514 :pos pos
9515 :len (- end pos)
9516 :operand expr))
9517 (js2-node-add-children pn expr)
9518 pn))
9519
9520 (defconst js2-incrementable-node-types
9521 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9522 "Node types that can be the operand of a ++ or -- operator.")
9523
9524 (defun js2-check-bad-inc-dec (tt beg end unary)
9525 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9526 js2-incrementable-node-types)
9527 (js2-report-error (if (= tt js2-INC)
9528 "msg.bad.incr"
9529 "msg.bad.decr")
9530 nil beg (- end beg))))
9531
9532 (defun js2-parse-unary-expr ()
9533 (let ((tt (js2-current-token-type))
9534 pn expr beg end)
9535 (cond
9536 ((or (= tt js2-VOID)
9537 (= tt js2-NOT)
9538 (= tt js2-BITNOT)
9539 (= tt js2-TYPEOF))
9540 (js2-get-token)
9541 (js2-make-unary tt 'js2-parse-unary-expr))
9542 ((= tt js2-ADD)
9543 (js2-get-token)
9544 ;; Convert to special POS token in decompiler and parse tree
9545 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9546 ((= tt js2-SUB)
9547 (js2-get-token)
9548 ;; Convert to special NEG token in decompiler and parse tree
9549 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9550 ((or (= tt js2-INC)
9551 (= tt js2-DEC))
9552 (js2-get-token)
9553 (prog1
9554 (setq beg (js2-current-token-beg)
9555 end (js2-current-token-end)
9556 expr (js2-make-unary tt 'js2-parse-member-expr t))
9557 (js2-check-bad-inc-dec tt beg end expr)))
9558 ((= tt js2-DELPROP)
9559 (js2-get-token)
9560 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9561 ((= tt js2-ERROR)
9562 (js2-get-token)
9563 (make-js2-error-node)) ; try to continue
9564 ((and (= tt js2-LT)
9565 js2-compiler-xml-available)
9566 ;; XML stream encountered in expression.
9567 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9568 (t
9569 (setq pn (js2-parse-member-expr t)
9570 ;; Don't look across a newline boundary for a postfix incop.
9571 tt (js2-peek-token-or-eol))
9572 (when (or (= tt js2-INC) (= tt js2-DEC))
9573 (js2-get-token)
9574 (setf expr pn
9575 pn (js2-make-unary tt expr))
9576 (js2-node-set-prop pn 'postfix t)
9577 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9578 pn))))
9579
9580 (defun js2-parse-xml-initializer ()
9581 "Parse an E4X XML initializer.
9582 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9583 Then I'll postprocess the result, depending on whether we're in IDE
9584 mode or codegen mode, and generate the appropriate rewritten AST.
9585 IDE mode uses a rich AST that models the XML structure. Codegen mode
9586 just concatenates everything and makes a new XML or XMLList out of it."
9587 (let ((tt (js2-get-first-xml-token))
9588 pn-xml pn expr kids expr-pos
9589 (continue t)
9590 (first-token t))
9591 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9592 (js2-report-error "msg.syntax"))
9593 (setq pn-xml (make-js2-xml-node))
9594 (while continue
9595 (if first-token
9596 (setq first-token nil)
9597 (setq tt (js2-get-next-xml-token)))
9598 (cond
9599 ;; js2-XML means we found a {expr} in the XML stream.
9600 ;; The token string is the XML up to the left-curly.
9601 ((= tt js2-XML)
9602 (push (make-js2-string-node :pos (js2-current-token-beg)
9603 :len (- js2-ts-cursor (js2-current-token-beg)))
9604 kids)
9605 (js2-must-match js2-LC "msg.syntax")
9606 (setq expr-pos js2-ts-cursor
9607 expr (if (eq (js2-peek-token) js2-RC)
9608 (make-js2-empty-expr-node :pos expr-pos)
9609 (js2-parse-expr)))
9610 (js2-must-match js2-RC "msg.syntax")
9611 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9612 :len (js2-node-len expr)
9613 :expr expr))
9614 (js2-node-add-children pn expr)
9615 (push pn kids))
9616 ;; a js2-XMLEND token means we hit the final close-tag.
9617 ((= tt js2-XMLEND)
9618 (push (make-js2-string-node :pos (js2-current-token-beg)
9619 :len (- js2-ts-cursor (js2-current-token-beg)))
9620 kids)
9621 (dolist (kid (nreverse kids))
9622 (js2-block-node-push pn-xml kid))
9623 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9624 (js2-node-pos pn-xml))
9625 continue nil))
9626 (t
9627 (js2-report-error "msg.syntax")
9628 (setq continue nil))))
9629 pn-xml))
9630
9631
9632 (defun js2-parse-argument-list ()
9633 "Parse an argument list and return it as a Lisp list of nodes.
9634 Returns the list in reverse order. Consumes the right-paren token."
9635 (let (result)
9636 (unless (js2-match-token js2-RP)
9637 (cl-loop do
9638 (let ((tt (js2-get-token)))
9639 (if (= tt js2-YIELD)
9640 (js2-report-error "msg.yield.parenthesized"))
9641 (if (and (= tt js2-TRIPLEDOT)
9642 (>= js2-language-version 200))
9643 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9644 (js2-unget-token)
9645 (push (js2-parse-assign-expr) result)))
9646 while
9647 (js2-match-token js2-COMMA))
9648 (js2-must-match js2-RP "msg.no.paren.arg")
9649 result)))
9650
9651 (defun js2-parse-member-expr (&optional allow-call-syntax)
9652 (let ((tt (js2-current-token-type))
9653 pn pos target args beg end init)
9654 (if (/= tt js2-NEW)
9655 (setq pn (js2-parse-primary-expr))
9656 ;; parse a 'new' expression
9657 (js2-get-token)
9658 (setq pos (js2-current-token-beg)
9659 beg pos
9660 target (js2-parse-member-expr)
9661 end (js2-node-end target)
9662 pn (make-js2-new-node :pos pos
9663 :target target
9664 :len (- end pos)))
9665 (js2-highlight-function-call (js2-current-token))
9666 (js2-node-add-children pn target)
9667 (when (js2-match-token js2-LP)
9668 ;; Add the arguments to pn, if any are supplied.
9669 (setf beg pos ; start of "new" keyword
9670 pos (js2-current-token-beg)
9671 args (nreverse (js2-parse-argument-list))
9672 (js2-new-node-args pn) args
9673 end (js2-current-token-end)
9674 (js2-new-node-lp pn) (- pos beg)
9675 (js2-new-node-rp pn) (- end 1 beg))
9676 (apply #'js2-node-add-children pn args))
9677 (when (and js2-allow-rhino-new-expr-initializer
9678 (js2-match-token js2-LC))
9679 (setf init (js2-parse-object-literal)
9680 end (js2-node-end init)
9681 (js2-new-node-initializer pn) init)
9682 (js2-node-add-children pn init))
9683 (setf (js2-node-len pn) (- end beg))) ; end outer if
9684 (js2-parse-member-expr-tail allow-call-syntax pn)))
9685
9686 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9687 "Parse a chain of property/array accesses or function calls.
9688 Includes parsing for E4X operators like `..' and `.@'.
9689 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9690 Returns an expression tree that includes PN, the parent node."
9691 (let (tt
9692 (continue t))
9693 (while continue
9694 (setq tt (js2-get-token))
9695 (cond
9696 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9697 (setq pn (js2-parse-property-access tt pn)))
9698 ((= tt js2-DOTQUERY)
9699 (setq pn (js2-parse-dot-query pn)))
9700 ((= tt js2-LB)
9701 (setq pn (js2-parse-element-get pn)))
9702 ((= tt js2-LP)
9703 (js2-unget-token)
9704 (if allow-call-syntax
9705 (setq pn (js2-parse-function-call pn))
9706 (setq continue nil)))
9707 ((= tt js2-TEMPLATE_HEAD)
9708 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9709 ((= tt js2-NO_SUBS_TEMPLATE)
9710 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9711 (t
9712 (js2-unget-token)
9713 (setq continue nil))))
9714 (if (>= js2-highlight-level 2)
9715 (js2-parse-highlight-member-expr-node pn))
9716 pn))
9717
9718 (defun js2-parse-tagged-template (tag-node tpl-node)
9719 "Parse tagged template expression."
9720 (let* ((beg (js2-node-pos tag-node))
9721 (pn (make-js2-tagged-template-node :beg beg
9722 :len (- (js2-current-token-end) beg)
9723 :tag tag-node
9724 :template tpl-node)))
9725 (js2-node-add-children pn tag-node tpl-node)
9726 pn))
9727
9728 (defun js2-parse-dot-query (pn)
9729 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9730 Last token parsed must be `js2-DOTQUERY'."
9731 (let ((pos (js2-node-pos pn))
9732 op-pos expr end)
9733 (js2-must-have-xml)
9734 (js2-set-requires-activation)
9735 (setq op-pos (js2-current-token-beg)
9736 expr (js2-parse-expr)
9737 end (js2-node-end expr)
9738 pn (make-js2-xml-dot-query-node :left pn
9739 :pos pos
9740 :op-pos op-pos
9741 :right expr))
9742 (js2-node-add-children pn
9743 (js2-xml-dot-query-node-left pn)
9744 (js2-xml-dot-query-node-right pn))
9745 (if (js2-must-match js2-RP "msg.no.paren")
9746 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9747 end (js2-current-token-end)))
9748 (setf (js2-node-len pn) (- end pos))
9749 pn))
9750
9751 (defun js2-parse-element-get (pn)
9752 "Parse an element-get expression, e.g. foo[bar].
9753 Last token parsed must be `js2-RB'."
9754 (let ((lb (js2-current-token-beg))
9755 (pos (js2-node-pos pn))
9756 rb expr)
9757 (setq expr (js2-parse-expr))
9758 (if (js2-must-match js2-RB "msg.no.bracket.index")
9759 (setq rb (js2-current-token-beg)))
9760 (setq pn (make-js2-elem-get-node :target pn
9761 :pos pos
9762 :element expr
9763 :lb (js2-relpos lb pos)
9764 :rb (js2-relpos rb pos)
9765 :len (- (js2-current-token-end) pos)))
9766 (js2-node-add-children pn
9767 (js2-elem-get-node-target pn)
9768 (js2-elem-get-node-element pn))
9769 pn))
9770
9771 (defun js2-highlight-function-call (token)
9772 (when (eq (js2-token-type token) js2-NAME)
9773 (js2-record-face 'js2-function-call token)))
9774
9775 (defun js2-parse-function-call (pn)
9776 (js2-highlight-function-call (js2-current-token))
9777 (js2-get-token)
9778 (let (args
9779 (pos (js2-node-pos pn)))
9780 (setq pn (make-js2-call-node :pos pos
9781 :target pn
9782 :lp (- (js2-current-token-beg) pos)))
9783 (js2-node-add-children pn (js2-call-node-target pn))
9784 ;; Add the arguments to pn, if any are supplied.
9785 (setf args (nreverse (js2-parse-argument-list))
9786 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9787 (js2-call-node-args pn) args)
9788 (apply #'js2-node-add-children pn args)
9789 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9790 pn))
9791
9792 (defun js2-parse-property-access (tt pn)
9793 "Parse a property access, XML descendants access, or XML attr access."
9794 (let ((member-type-flags 0)
9795 (dot-pos (js2-current-token-beg))
9796 (dot-len (if (= tt js2-DOTDOT) 2 1))
9797 name
9798 ref ; right side of . or .. operator
9799 result)
9800 (when (= tt js2-DOTDOT)
9801 (js2-must-have-xml)
9802 (setq member-type-flags js2-descendants-flag))
9803 (if (not js2-compiler-xml-available)
9804 (progn
9805 (js2-must-match-prop-name "msg.no.name.after.dot")
9806 (setq name (js2-create-name-node t js2-GETPROP)
9807 result (make-js2-prop-get-node :left pn
9808 :pos (js2-current-token-beg)
9809 :right name
9810 :len (js2-current-token-len)))
9811 (js2-node-add-children result pn name)
9812 result)
9813 ;; otherwise look for XML operators
9814 (setf result (if (= tt js2-DOT)
9815 (make-js2-prop-get-node)
9816 (make-js2-infix-node :type js2-DOTDOT))
9817 (js2-node-pos result) (js2-node-pos pn)
9818 (js2-infix-node-op-pos result) dot-pos
9819 (js2-infix-node-left result) pn ; do this after setting position
9820 tt (js2-get-prop-name-token))
9821 (cond
9822 ;; handles: name, ns::name, ns::*, ns::[expr]
9823 ((= tt js2-NAME)
9824 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9825 ;; handles: *, *::name, *::*, *::[expr]
9826 ((= tt js2-MUL)
9827 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9828 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9829 ((= tt js2-XMLATTR)
9830 (setq result (js2-parse-attribute-access)))
9831 (t
9832 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9833 (if ref
9834 (setf (js2-node-len result) (- (js2-node-end ref)
9835 (js2-node-pos result))
9836 (js2-infix-node-right result) ref))
9837 (if (js2-infix-node-p result)
9838 (js2-node-add-children result
9839 (js2-infix-node-left result)
9840 (js2-infix-node-right result)))
9841 result)))
9842
9843 (defun js2-parse-attribute-access ()
9844 "Parse an E4X XML attribute expression.
9845 This includes expressions of the forms:
9846
9847 @attr @ns::attr @ns::*
9848 @* @*::attr @*::*
9849 @[expr] @*::[expr] @ns::[expr]
9850
9851 Called if we peeked an '@' token."
9852 (let ((tt (js2-get-prop-name-token))
9853 (at-pos (js2-current-token-beg)))
9854 (cond
9855 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9856 ((= tt js2-NAME)
9857 (js2-parse-property-name at-pos nil 0))
9858 ;; handles: @*, @*::name, @*::*, @*::[expr]
9859 ((= tt js2-MUL)
9860 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9861 ;; handles @[expr]
9862 ((= tt js2-LB)
9863 (js2-parse-xml-elem-ref at-pos))
9864 (t
9865 (js2-report-error "msg.no.name.after.xmlAttr")
9866 ;; Avoid cascaded errors that happen if we make an error node here.
9867 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9868
9869 (defun js2-parse-property-name (at-pos s member-type-flags)
9870 "Check if :: follows name in which case it becomes qualified name.
9871
9872 AT-POS is a natural number if we just read an '@' token, else nil.
9873 S is the name or string that was matched: an identifier, 'throw' or '*'.
9874 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9875
9876 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9877 operator, or the name is followed by ::. For a plain name, returns a
9878 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9879 (let ((pos (or at-pos (js2-current-token-beg)))
9880 colon-pos
9881 (name (js2-create-name-node t (js2-current-token-type) s))
9882 ns tt pn)
9883 (catch 'return
9884 (when (js2-match-token js2-COLONCOLON)
9885 (setq ns name
9886 colon-pos (js2-current-token-beg)
9887 tt (js2-get-prop-name-token))
9888 (cond
9889 ;; handles name::name
9890 ((= tt js2-NAME)
9891 (setq name (js2-create-name-node)))
9892 ;; handles name::*
9893 ((= tt js2-MUL)
9894 (setq name (js2-create-name-node nil nil "*")))
9895 ;; handles name::[expr]
9896 ((= tt js2-LB)
9897 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9898 (t
9899 (js2-report-error "msg.no.name.after.coloncolon"))))
9900 (if (and (null ns) (zerop member-type-flags))
9901 name
9902 (prog1
9903 (setq pn
9904 (make-js2-xml-prop-ref-node :pos pos
9905 :len (- (js2-node-end name) pos)
9906 :at-pos at-pos
9907 :colon-pos colon-pos
9908 :propname name))
9909 (js2-node-add-children pn name))))))
9910
9911 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9912 "Parse the [expr] portion of an xml element reference.
9913 For instance, @[expr], @*::[expr], or ns::[expr]."
9914 (let* ((lb (js2-current-token-beg))
9915 (pos (or at-pos lb))
9916 rb
9917 (expr (js2-parse-expr))
9918 (end (js2-node-end expr))
9919 pn)
9920 (if (js2-must-match js2-RB "msg.no.bracket.index")
9921 (setq rb (js2-current-token-beg)
9922 end (js2-current-token-end)))
9923 (prog1
9924 (setq pn
9925 (make-js2-xml-elem-ref-node :pos pos
9926 :len (- end pos)
9927 :namespace namespace
9928 :colon-pos colon-pos
9929 :at-pos at-pos
9930 :expr expr
9931 :lb (js2-relpos lb pos)
9932 :rb (js2-relpos rb pos)))
9933 (js2-node-add-children pn namespace expr))))
9934
9935 (defun js2-parse-destruct-primary-expr ()
9936 (let ((js2-is-in-destructuring t))
9937 (js2-parse-primary-expr)))
9938
9939 (defun js2-parse-primary-expr ()
9940 "Parse a literal (leaf) expression of some sort.
9941 Includes complex literals such as functions, object-literals,
9942 array-literals, array comprehensions and regular expressions."
9943 (let (pn ; parent node (usually return value)
9944 tt)
9945 (setq tt (js2-current-token-type))
9946 (cond
9947 ((= tt js2-CLASS)
9948 (js2-parse-class-expr))
9949 ((= tt js2-FUNCTION)
9950 (js2-parse-function-expr))
9951 ((= tt js2-LB)
9952 (js2-parse-array-comp-or-literal))
9953 ((= tt js2-LC)
9954 (js2-parse-object-literal))
9955 ((= tt js2-LET)
9956 (js2-parse-let (js2-current-token-beg)))
9957 ((= tt js2-LP)
9958 (js2-parse-paren-expr-or-generator-comp))
9959 ((= tt js2-XMLATTR)
9960 (js2-must-have-xml)
9961 (js2-parse-attribute-access))
9962 ((= tt js2-NAME)
9963 (js2-parse-name tt))
9964 ((= tt js2-NUMBER)
9965 (make-js2-number-node))
9966 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9967 (make-js2-string-node :type tt))
9968 ((= tt js2-TEMPLATE_HEAD)
9969 (js2-parse-template-literal))
9970 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9971 ;; Got / or /= which in this context means a regexp literal
9972 (let ((px-pos (js2-current-token-beg))
9973 (flags (js2-read-regexp tt))
9974 (end (js2-current-token-end)))
9975 (prog1
9976 (make-js2-regexp-node :pos px-pos
9977 :len (- end px-pos)
9978 :value (js2-current-token-string)
9979 :flags flags)
9980 (js2-set-face px-pos end 'font-lock-string-face 'record)
9981 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9982 ((or (= tt js2-NULL)
9983 (= tt js2-THIS)
9984 (= tt js2-SUPER)
9985 (= tt js2-FALSE)
9986 (= tt js2-TRUE))
9987 (make-js2-keyword-node :type tt))
9988 ((= tt js2-TRIPLEDOT)
9989 ;; Likewise, only valid in an arrow function with a rest param.
9990 (if (and (js2-match-token js2-NAME)
9991 (js2-match-token js2-RP)
9992 (eq (js2-peek-token) js2-ARROW))
9993 (progn
9994 (js2-unget-token) ; Put back the right paren.
9995 ;; See the previous case.
9996 (make-js2-keyword-node :type js2-NULL))
9997 (js2-report-error "msg.syntax")
9998 (make-js2-error-node)))
9999 ((= tt js2-RESERVED)
10000 (js2-report-error "msg.reserved.id")
10001 (make-js2-name-node))
10002 ((= tt js2-ERROR)
10003 ;; the scanner or one of its subroutines reported the error.
10004 (make-js2-error-node))
10005 ((= tt js2-EOF)
10006 (let* ((px-pos (point-at-bol))
10007 (len (- js2-ts-cursor px-pos)))
10008 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10009 (make-js2-error-node :pos (1- js2-ts-cursor)))
10010 (t
10011 (js2-report-error "msg.syntax")
10012 (make-js2-error-node)))))
10013
10014 (defun js2-parse-template-literal ()
10015 (let ((beg (js2-current-token-beg))
10016 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10017 (tt js2-TEMPLATE_HEAD))
10018 (while (eq tt js2-TEMPLATE_HEAD)
10019 (push (js2-parse-expr) kids)
10020 (js2-must-match js2-RC "msg.syntax")
10021 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10022 (push (make-js2-string-node :type tt) kids))
10023 (setq kids (nreverse kids))
10024 (let ((tpl (make-js2-template-node :beg beg
10025 :len (- (js2-current-token-end) beg)
10026 :kids kids)))
10027 (apply #'js2-node-add-children tpl kids)
10028 tpl)))
10029
10030 (defun js2-parse-name (_tt)
10031 (let ((name (js2-current-token-string))
10032 node)
10033 (setq node (if js2-compiler-xml-available
10034 (js2-parse-property-name nil name 0)
10035 (js2-create-name-node 'check-activation nil name)))
10036 (if js2-highlight-external-variables
10037 (js2-record-name-node node))
10038 node))
10039
10040 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10041 (js2-add-strict-warning
10042 msg nil
10043 ;; back up from comma to beginning of line or array/objlit
10044 (max (if elems
10045 (js2-node-pos (car elems))
10046 pos)
10047 (save-excursion
10048 (goto-char comma-pos)
10049 (back-to-indentation)
10050 (point)))
10051 comma-pos))
10052
10053 (defun js2-parse-array-comp-or-literal ()
10054 (let ((pos (js2-current-token-beg)))
10055 (if (and (>= js2-language-version 200)
10056 (js2-match-token js2-FOR))
10057 (js2-parse-array-comp pos)
10058 (js2-parse-array-literal pos))))
10059
10060 (defun js2-parse-array-literal (pos)
10061 (let ((after-lb-or-comma t)
10062 after-comma tt elems pn
10063 (continue t))
10064 (unless js2-is-in-destructuring
10065 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10066 (while continue
10067 (setq tt (js2-get-token))
10068 (cond
10069 ;; comma
10070 ((= tt js2-COMMA)
10071 (setq after-comma (js2-current-token-end))
10072 (if (not after-lb-or-comma)
10073 (setq after-lb-or-comma t)
10074 (push nil elems)))
10075 ;; end of array
10076 ((or (= tt js2-RB)
10077 (= tt js2-EOF)) ; prevent infinite loop
10078 (if (= tt js2-EOF)
10079 (js2-report-error "msg.no.bracket.arg" nil pos))
10080 (when (and after-comma (< js2-language-version 170))
10081 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10082 pos (remove nil elems) after-comma))
10083 (setq continue nil
10084 pn (make-js2-array-node :pos pos
10085 :len (- js2-ts-cursor pos)
10086 :elems (nreverse elems)))
10087 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10088 ;; destructuring binding
10089 (js2-is-in-destructuring
10090 (push (if (or (= tt js2-LC)
10091 (= tt js2-LB)
10092 (= tt js2-NAME))
10093 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10094 (js2-parse-destruct-primary-expr)
10095 ;; invalid pattern
10096 (js2-report-error "msg.bad.var")
10097 (make-js2-error-node))
10098 elems)
10099 (setq after-lb-or-comma nil
10100 after-comma nil))
10101 ;; array comp
10102 ((and (>= js2-language-version 170)
10103 (= tt js2-FOR) ; check for array comprehension
10104 (not after-lb-or-comma) ; "for" can't follow a comma
10105 elems ; must have at least 1 element
10106 (not (cdr elems))) ; but no 2nd element
10107 (js2-unget-token)
10108 (setf continue nil
10109 pn (js2-parse-legacy-array-comp (car elems) pos)))
10110 ;; another element
10111 (t
10112 (unless after-lb-or-comma
10113 (js2-report-error "msg.no.bracket.arg"))
10114 (if (and (= tt js2-TRIPLEDOT)
10115 (>= js2-language-version 200))
10116 ;; spread operator
10117 (push (js2-make-unary tt 'js2-parse-assign-expr)
10118 elems)
10119 (js2-unget-token)
10120 (push (js2-parse-assign-expr) elems))
10121 (setq after-lb-or-comma nil
10122 after-comma nil))))
10123 (unless js2-is-in-destructuring
10124 (js2-pop-scope))
10125 pn))
10126
10127 (defun js2-parse-legacy-array-comp (expr pos)
10128 "Parse a legacy array comprehension (JavaScript 1.7).
10129 EXPR is the first expression after the opening left-bracket.
10130 POS is the beginning of the LB token preceding EXPR.
10131 We should have just parsed the 'for' keyword before calling this function."
10132 (let ((current-scope js2-current-scope)
10133 loops first filter result)
10134 (unwind-protect
10135 (progn
10136 (while (js2-match-token js2-FOR)
10137 (let ((loop (make-js2-comp-loop-node)))
10138 (js2-push-scope loop)
10139 (push loop loops)
10140 (js2-parse-comp-loop loop)))
10141 ;; First loop takes expr scope's parent.
10142 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10143 (js2-scope-parent-scope current-scope))
10144 ;; Set expr scope's parent to the last loop.
10145 (setf (js2-scope-parent-scope current-scope) (car loops))
10146 (if (/= (js2-get-token) js2-IF)
10147 (js2-unget-token)
10148 (setq filter (js2-parse-condition))))
10149 (dotimes (_ (1- (length loops)))
10150 (js2-pop-scope)))
10151 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10152 (setq result (make-js2-comp-node :pos pos
10153 :len (- js2-ts-cursor pos)
10154 :result expr
10155 :loops (nreverse loops)
10156 :filters (and filter (list (car filter)))
10157 :form 'LEGACY_ARRAY))
10158 (apply #'js2-node-add-children result expr (car filter)
10159 (js2-comp-node-loops result))
10160 result))
10161
10162 (defun js2-parse-array-comp (pos)
10163 "Parse an ES6 array comprehension.
10164 POS is the beginning of the LB token.
10165 We should have just parsed the 'for' keyword before calling this function."
10166 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10167 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10168 pn))
10169
10170 (defun js2-parse-generator-comp (pos)
10171 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10172 (js2-current-script-or-fn
10173 (make-js2-function-node :generator-type 'COMPREHENSION))
10174 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10175 (js2-must-match js2-RP "msg.no.paren" pos)
10176 pn))
10177
10178 (defun js2-parse-comprehension (pos form)
10179 (let (loops filters expr result)
10180 (unwind-protect
10181 (progn
10182 (js2-unget-token)
10183 (while (js2-match-token js2-FOR)
10184 (let ((loop (make-js2-comp-loop-node)))
10185 (js2-push-scope loop)
10186 (push loop loops)
10187 (js2-parse-comp-loop loop)))
10188 (while (js2-match-token js2-IF)
10189 (push (car (js2-parse-condition)) filters))
10190 (setq expr (js2-parse-assign-expr)))
10191 (dolist (_ loops)
10192 (js2-pop-scope)))
10193 (setq result (make-js2-comp-node :pos pos
10194 :len (- js2-ts-cursor pos)
10195 :result expr
10196 :loops (nreverse loops)
10197 :filters (nreverse filters)
10198 :form form))
10199 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10200 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10201 result))
10202
10203 (defun js2-parse-comp-loop (pn &optional only-of-p)
10204 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10205 The current token should be the initial FOR.
10206 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10207 (let ((pos (js2-comp-loop-node-pos pn))
10208 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10209 (when (and (not only-of-p) (js2-match-token js2-NAME))
10210 (if (string= (js2-current-token-string) "each")
10211 (progn
10212 (setq foreach-p t
10213 each-pos (- (js2-current-token-beg) pos)) ; relative
10214 (js2-record-face 'font-lock-keyword-face))
10215 (js2-report-error "msg.no.paren.for")))
10216 (if (js2-must-match js2-LP "msg.no.paren.for")
10217 (setq lp (- (js2-current-token-beg) pos)))
10218 (setq tt (js2-peek-token))
10219 (cond
10220 ((or (= tt js2-LB)
10221 (= tt js2-LC))
10222 (js2-get-token)
10223 (setq iter (js2-parse-destruct-primary-expr))
10224 (js2-define-destruct-symbols iter js2-LET
10225 'font-lock-variable-name-face t))
10226 ((js2-match-token js2-NAME)
10227 (setq iter (js2-create-name-node)))
10228 (t
10229 (js2-report-error "msg.bad.var")))
10230 ;; Define as a let since we want the scope of the variable to
10231 ;; be restricted to the array comprehension
10232 (if (js2-name-node-p iter)
10233 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10234 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10235 (and (>= js2-language-version 200)
10236 (js2-match-contextual-kwd "of")
10237 (setq forof-p t)))
10238 (setq in-pos (- (js2-current-token-beg) pos))
10239 (js2-report-error "msg.in.after.for.name"))
10240 (setq obj (js2-parse-expr))
10241 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10242 (setq rp (- (js2-current-token-beg) pos)))
10243 (setf (js2-node-pos pn) pos
10244 (js2-node-len pn) (- js2-ts-cursor pos)
10245 (js2-comp-loop-node-iterator pn) iter
10246 (js2-comp-loop-node-object pn) obj
10247 (js2-comp-loop-node-in-pos pn) in-pos
10248 (js2-comp-loop-node-each-pos pn) each-pos
10249 (js2-comp-loop-node-foreach-p pn) foreach-p
10250 (js2-comp-loop-node-forof-p pn) forof-p
10251 (js2-comp-loop-node-lp pn) lp
10252 (js2-comp-loop-node-rp pn) rp)
10253 (js2-node-add-children pn iter obj)
10254 pn))
10255
10256 (defun js2-parse-class-stmt ()
10257 (let ((pos (js2-current-token-beg))
10258 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10259 (name (js2-create-name-node t)))
10260 (js2-set-face (js2-node-pos name) (js2-node-end name)
10261 'font-lock-function-name-face 'record)
10262 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10263 (js2-define-symbol js2-FUNCTION
10264 (js2-name-node-name name)
10265 node)
10266 node)))
10267
10268 (defun js2-parse-class-expr ()
10269 (let ((pos (js2-current-token-beg))
10270 name)
10271 (when (js2-match-token js2-NAME)
10272 (setq name (js2-create-name-node t)))
10273 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10274
10275 (defun js2-parse-class (pos form name)
10276 ;; class X [extends ...] {
10277 (let (pn elems extends)
10278 (if (js2-match-token js2-EXTENDS)
10279 (if (= (js2-peek-token) js2-LC)
10280 (js2-report-error "msg.missing.extends")
10281 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10282 (setq extends (js2-parse-assign-expr))
10283 (if (not extends)
10284 (js2-report-error "msg.bad.extends"))))
10285 (js2-must-match js2-LC "msg.no.brace.class")
10286 (setq elems (js2-parse-object-literal-elems t)
10287 pn (make-js2-class-node :pos pos
10288 :len (- js2-ts-cursor pos)
10289 :form form
10290 :name name
10291 :extends extends
10292 :elems elems))
10293 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10294 pn))
10295
10296 (defun js2-parse-object-literal ()
10297 (let* ((pos (js2-current-token-beg))
10298 (elems (js2-parse-object-literal-elems))
10299 (result (make-js2-object-node :pos pos
10300 :len (- js2-ts-cursor pos)
10301 :elems elems)))
10302 (apply #'js2-node-add-children result (js2-object-node-elems result))
10303 result))
10304
10305 (defun js2-parse-object-literal-elems (&optional class-p)
10306 (let ((pos (js2-current-token-beg))
10307 (static nil)
10308 (continue t)
10309 tt elems elem after-comma)
10310 (while continue
10311 (setq static (and class-p (js2-match-token js2-STATIC))
10312 tt (js2-get-prop-name-token)
10313 elem nil)
10314 (cond
10315 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
10316 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
10317 ;; TODO(sdh): support *foo() {...}
10318 ((or (= js2-NAME tt)
10319 (= tt js2-STRING))
10320 (setq after-comma nil
10321 elem (js2-parse-named-prop tt))
10322 (if (and (null elem)
10323 (not js2-recover-from-parse-errors))
10324 (setq continue nil)))
10325 ;; {[Symbol.iterator]: ...}
10326 ((and (= tt js2-LB)
10327 (>= js2-language-version 200))
10328 (let ((expr (js2-parse-expr)))
10329 (js2-must-match js2-RB "msg.missing.computed.rb")
10330 (setq after-comma nil
10331 elem (js2-parse-plain-property expr))))
10332 ;; {12: x} or {10.7: x}
10333 ((= tt js2-NUMBER)
10334 (setq after-comma nil
10335 elem (js2-parse-plain-property (make-js2-number-node))))
10336 ;; Break out of loop, and handle trailing commas.
10337 ((or (= tt js2-RC)
10338 (= tt js2-EOF))
10339 (js2-unget-token)
10340 (setq continue nil)
10341 (if after-comma
10342 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10343 pos elems after-comma)))
10344 (t
10345 (js2-report-error "msg.bad.prop")
10346 (unless js2-recover-from-parse-errors
10347 (setq continue nil)))) ; end switch
10348 ;; Handle static for classes' codegen.
10349 (if static
10350 (if elem (js2-node-set-prop elem 'STATIC t)
10351 (js2-report-error "msg.unexpected.static")))
10352 ;; Handle commas, depending on class-p.
10353 (let ((comma (js2-match-token js2-COMMA)))
10354 (if class-p
10355 (if comma
10356 (js2-report-error "msg.class.unexpected.comma"))
10357 (if comma
10358 (setq after-comma (js2-current-token-end))
10359 (setq continue nil))))
10360 ;; Append any parsed element.
10361 (if elem (push elem elems))) ; end loop
10362 (js2-must-match js2-RC "msg.no.brace.prop")
10363 (nreverse elems)))
10364
10365 (defun js2-parse-named-prop (tt)
10366 "Parse a name, string, or getter/setter object property.
10367 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10368 (let ((string-prop (and (= tt js2-STRING)
10369 (make-js2-string-node)))
10370 expr
10371 (ppos (js2-current-token-beg))
10372 (pend (js2-current-token-end))
10373 (name (js2-create-name-node))
10374 (prop (js2-current-token-string)))
10375 (cond
10376 ;; getter/setter prop
10377 ((and (= tt js2-NAME)
10378 (= (js2-peek-token) js2-NAME)
10379 (or (string= prop "get")
10380 (string= prop "set")))
10381 (js2-get-token)
10382 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
10383 (js2-record-face 'font-lock-function-name-face) ; for peeked name
10384 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
10385 (js2-parse-getter-setter-prop ppos name prop))
10386 ;; method definition: {f() {...}}
10387 ((and (= (js2-peek-token) js2-LP)
10388 (>= js2-language-version 200))
10389 (js2-record-face 'font-lock-function-name-face) ; name
10390 (js2-parse-getter-setter-prop ppos name ""))
10391 ;; regular prop
10392 (t
10393 (prog1
10394 (setq expr (js2-parse-plain-property (or string-prop name)))
10395 (when (and (not string-prop)
10396 (not js2-is-in-destructuring)
10397 js2-highlight-external-variables
10398 (js2-node-get-prop expr 'SHORTHAND))
10399 (js2-record-name-node name))
10400 (js2-set-face ppos pend
10401 (if (js2-function-node-p
10402 (js2-object-prop-node-right expr))
10403 'font-lock-function-name-face
10404 'font-lock-variable-name-face)
10405 'record))))))
10406
10407 (defun js2-parse-plain-property (prop)
10408 "Parse a non-getter/setter property in an object literal.
10409 PROP is the node representing the property: a number, name or string."
10410 (let* ((tt (js2-get-token))
10411 (pos (js2-node-pos prop))
10412 colon expr result)
10413 (cond
10414 ;; Abbreviated property, as in {foo, bar}
10415 ((and (>= js2-language-version 200)
10416 (or (= tt js2-COMMA)
10417 (= tt js2-RC))
10418 (not (js2-number-node-p prop)))
10419 (js2-unget-token)
10420 (setq result (make-js2-object-prop-node
10421 :pos pos
10422 :left prop
10423 :right prop
10424 :op-pos (js2-current-token-len)))
10425 (js2-node-add-children result prop)
10426 (js2-node-set-prop result 'SHORTHAND t)
10427 result)
10428 ;; Normal property
10429 (t
10430 (if (= tt js2-COLON)
10431 (setq colon (- (js2-current-token-beg) pos)
10432 expr (js2-parse-assign-expr))
10433 (js2-report-error "msg.no.colon.prop")
10434 (setq expr (make-js2-error-node)))
10435 (setq result (make-js2-object-prop-node
10436 :pos pos
10437 ;; don't include last consumed token in length
10438 :len (- (+ (js2-node-pos expr)
10439 (js2-node-len expr))
10440 pos)
10441 :left prop
10442 :right expr
10443 :op-pos colon))
10444 (js2-node-add-children result prop expr)
10445 result))))
10446
10447 (defun js2-parse-getter-setter-prop (pos prop type-string)
10448 "Parse getter or setter property in an object literal.
10449 JavaScript syntax is:
10450
10451 { get foo() {...}, set foo(x) {...} }
10452
10453 and expression closure style is also supported
10454
10455 { get foo() x, set foo(x) _x = x }
10456
10457 POS is the start position of the `get' or `set' keyword.
10458 PROP is the `js2-name-node' representing the property name.
10459 GET-P is non-nil if the keyword was `get'."
10460 (let ((type (cond
10461 ((string= "get" type-string) js2-GET)
10462 ((string= "set" type-string) js2-SET)
10463 (t js2-FUNCTION)))
10464 result end
10465 (fn (js2-parse-function-expr)))
10466 ;; it has to be an anonymous function, as we already parsed the name
10467 (if (/= (js2-node-type fn) js2-FUNCTION)
10468 (js2-report-error "msg.bad.prop")
10469 (if (cl-plusp (length (js2-function-name fn)))
10470 (js2-report-error "msg.bad.prop")))
10471 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10472 (setq end (js2-node-end fn)
10473 result (make-js2-getter-setter-node :type type
10474 :pos pos
10475 :len (- end pos)
10476 :left prop
10477 :right fn))
10478 (js2-node-add-children result prop fn)
10479 result))
10480
10481 (defun js2-create-name-node (&optional check-activation-p token string)
10482 "Create a name node using the current token and, optionally, STRING.
10483 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10484 (let* ((beg (js2-current-token-beg))
10485 (tt (js2-current-token-type))
10486 (s (or string
10487 (if (= js2-NAME tt)
10488 (js2-current-token-string)
10489 (js2-tt-name tt))))
10490 name)
10491 (setq name (make-js2-name-node :pos beg
10492 :name s
10493 :len (length s)))
10494 (if check-activation-p
10495 (js2-check-activation-name s (or token js2-NAME)))
10496 name))
10497
10498 ;;; Indentation support
10499
10500 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10501 ;; Karl cleverly deduces that the desired indentation level is often a
10502 ;; function of paren/bracket/brace nesting depth, which can be determined
10503 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10504 ;; then does some equally clever checks to see if we're in the context of a
10505 ;; substatement of a possibly braceless statement keyword such as if, while,
10506 ;; or finally. This approach yields pretty good results.
10507
10508 ;; The indenter is often "wrong", however, and needs to be overridden.
10509 ;; The right long-term solution is probably to emulate (or integrate
10510 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10511 ;; parse tree from `js2-parse' is present, which is not true at the
10512 ;; moment the user is typing, computing indentation is still thousands
10513 ;; of lines of code to handle every possible syntactic edge case.
10514
10515 ;; In the meantime, the compromise solution is that we offer a "bounce
10516 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10517 ;; current line indent among various likely guess points. This approach
10518 ;; is far from perfect, but should at least make it slightly easier to
10519 ;; move the line towards its desired indentation when manually
10520 ;; overriding Karl's heuristic nesting guesser.
10521
10522 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10523 ;; extensions such as `let' and Array comprehensions. Major kudos to
10524 ;; Karl for coming up with the initial approach, which packs a lot of
10525 ;; punch for so little code.
10526
10527 (defconst js2-possibly-braceless-keywords-re
10528 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10529 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10530 "try" "while" "with" "let")))
10531 "Regular expression matching keywords that are optionally
10532 followed by an opening brace.")
10533
10534 (defconst js2-indent-operator-re
10535 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10536 (regexp-opt '("in" "instanceof") 'words))
10537 "Regular expression matching operators that affect indentation
10538 of continued expressions.")
10539
10540 (defconst js2-declaration-keyword-re
10541 (regexp-opt '("var" "let" "const") 'words)
10542 "Regular expression matching variable declaration keywords.")
10543
10544 (defun js2-re-search-forward-inner (regexp &optional bound count)
10545 "Auxiliary function for `js2-re-search-forward'."
10546 (let (parse saved-point)
10547 (while (> count 0)
10548 (re-search-forward regexp bound)
10549 (setq parse (if saved-point
10550 (parse-partial-sexp saved-point (point))
10551 (syntax-ppss (point))))
10552 (cond ((nth 3 parse)
10553 (re-search-forward
10554 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10555 (save-excursion (end-of-line) (point)) t))
10556 ((nth 7 parse)
10557 (forward-line))
10558 ((or (nth 4 parse)
10559 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10560 (re-search-forward "\\*/"))
10561 (t
10562 (setq count (1- count))))
10563 (setq saved-point (point))))
10564 (point))
10565
10566 (defun js2-re-search-forward (regexp &optional bound noerror count)
10567 "Search forward but ignore strings and comments.
10568 Invokes `re-search-forward' but treats the buffer as if strings
10569 and comments have been removed."
10570 (let ((saved-point (point)))
10571 (condition-case err
10572 (cond ((null count)
10573 (js2-re-search-forward-inner regexp bound 1))
10574 ((< count 0)
10575 (js2-re-search-backward-inner regexp bound (- count)))
10576 ((> count 0)
10577 (js2-re-search-forward-inner regexp bound count)))
10578 (search-failed
10579 (goto-char saved-point)
10580 (unless noerror
10581 (error (error-message-string err)))))))
10582
10583 (defun js2-re-search-backward-inner (regexp &optional bound count)
10584 "Auxiliary function for `js2-re-search-backward'."
10585 (let (parse)
10586 (while (> count 0)
10587 (re-search-backward regexp bound)
10588 (setq parse (syntax-ppss (point)))
10589 (cond ((nth 3 parse)
10590 (re-search-backward
10591 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10592 (line-beginning-position) t))
10593 ((nth 7 parse)
10594 (goto-char (nth 8 parse)))
10595 ((or (nth 4 parse)
10596 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10597 (re-search-backward "/\\*"))
10598 (t
10599 (setq count (1- count))))))
10600 (point))
10601
10602 (defun js2-re-search-backward (regexp &optional bound noerror count)
10603 "Search backward but ignore strings and comments.
10604 Invokes `re-search-backward' but treats the buffer as if strings
10605 and comments have been removed."
10606 (let ((saved-point (point)))
10607 (condition-case err
10608 (cond ((null count)
10609 (js2-re-search-backward-inner regexp bound 1))
10610 ((< count 0)
10611 (js2-re-search-forward-inner regexp bound (- count)))
10612 ((> count 0)
10613 (js2-re-search-backward-inner regexp bound count)))
10614 (search-failed
10615 (goto-char saved-point)
10616 (unless noerror
10617 (error (error-message-string err)))))))
10618
10619 (defun js2-looking-at-operator-p ()
10620 "Return non-nil if text after point is a non-comma operator."
10621 (and (looking-at js2-indent-operator-re)
10622 (or (not (looking-at ":"))
10623 (save-excursion
10624 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10625 (looking-at "?"))))))
10626
10627 (defun js2-continued-expression-p ()
10628 "Return non-nil if the current line continues an expression."
10629 (save-excursion
10630 (back-to-indentation)
10631 (or (js2-looking-at-operator-p)
10632 (when (catch 'found
10633 (while (and (re-search-backward "\n" nil t)
10634 (let ((state (syntax-ppss)))
10635 (when (nth 4 state)
10636 (goto-char (nth 8 state))) ;; skip comments
10637 (skip-chars-backward " \t")
10638 (if (bolp)
10639 t
10640 (throw 'found t))))))
10641 (backward-char)
10642 (when (js2-looking-at-operator-p)
10643 (backward-char)
10644 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10645
10646 (defun js2-end-of-do-while-loop-p ()
10647 "Return non-nil if word after point is `while' of a do-while
10648 statement, else returns nil. A braceless do-while statement
10649 spanning several lines requires that the start of the loop is
10650 indented to the same column as the current line."
10651 (interactive)
10652 (save-excursion
10653 (when (looking-at "\\s-*\\<while\\>")
10654 (if (save-excursion
10655 (skip-chars-backward "[ \t\n]*}")
10656 (looking-at "[ \t\n]*}"))
10657 (save-excursion
10658 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10659 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10660 (or (looking-at "\\<do\\>")
10661 (let ((saved-indent (current-indentation)))
10662 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10663 (/= (current-indentation) saved-indent)))
10664 (and (looking-at "[ \t]*\\<do\\>")
10665 (not (js2-re-search-forward
10666 "\\<while\\>" (point-at-eol) t))
10667 (= (current-indentation) saved-indent))))))))
10668
10669 (defun js2-multiline-decl-indentation ()
10670 "Return the declaration indentation column if the current line belongs
10671 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10672 (let (forward-sexp-function ; use Lisp version
10673 at-opening-bracket)
10674 (save-excursion
10675 (back-to-indentation)
10676 (when (not (looking-at js2-declaration-keyword-re))
10677 (when (looking-at js2-indent-operator-re)
10678 (goto-char (match-end 0))) ; continued expressions are ok
10679 (while (and (not at-opening-bracket)
10680 (not (bobp))
10681 (let ((pos (point)))
10682 (save-excursion
10683 (js2-backward-sws)
10684 (or (eq (char-before) ?,)
10685 (and (not (eq (char-before) ?\;))
10686 (prog2 (skip-syntax-backward ".")
10687 (looking-at js2-indent-operator-re)
10688 (js2-backward-sws))
10689 (not (eq (char-before) ?\;)))
10690 (js2-same-line pos)))))
10691 (condition-case _
10692 (backward-sexp)
10693 (scan-error (setq at-opening-bracket t))))
10694 (when (looking-at js2-declaration-keyword-re)
10695 (goto-char (match-end 0))
10696 (1+ (current-column)))))))
10697
10698 (defun js2-ctrl-statement-indentation ()
10699 "Return the proper indentation of current line if it is a control statement.
10700 Returns an indentation if this line starts the body of a control
10701 statement without braces, else returns nil."
10702 (let (forward-sexp-function)
10703 (save-excursion
10704 (back-to-indentation)
10705 (when (and (not (js2-same-line (point-min)))
10706 (not (looking-at "{"))
10707 (js2-re-search-backward "[[:graph:]]" nil t)
10708 (not (looking-at "[{([]"))
10709 (progn
10710 (forward-char)
10711 (when (= (char-before) ?\))
10712 ;; scan-sexps sometimes throws an error
10713 (ignore-errors (backward-sexp))
10714 (skip-chars-backward " \t" (point-at-bol)))
10715 (let ((pt (point)))
10716 (back-to-indentation)
10717 (when (looking-at "}[ \t]*")
10718 (goto-char (match-end 0)))
10719 (and (looking-at js2-possibly-braceless-keywords-re)
10720 (= (match-end 0) pt)
10721 (not (js2-end-of-do-while-loop-p))))))
10722 (+ (current-indentation) js2-basic-offset)))))
10723
10724 (defun js2-indent-in-array-comp (parse-status)
10725 "Return non-nil if we think we're in an array comprehension.
10726 In particular, return the buffer position of the first `for' kwd."
10727 (let ((bracket (nth 1 parse-status))
10728 (end (point)))
10729 (when bracket
10730 (save-excursion
10731 (goto-char bracket)
10732 (when (looking-at "\\[")
10733 (forward-char 1)
10734 (js2-forward-sws)
10735 (if (looking-at "[[{]")
10736 (let (forward-sexp-function) ; use Lisp version
10737 (forward-sexp) ; skip destructuring form
10738 (js2-forward-sws)
10739 (if (and (/= (char-after) ?,) ; regular array
10740 (looking-at "for"))
10741 (match-beginning 0)))
10742 ;; to skip arbitrary expressions we need the parser,
10743 ;; so we'll just guess at it.
10744 (if (and (> end (point)) ; not empty literal
10745 (re-search-forward "[^,]]* \\(for\\) " end t)
10746 ;; not inside comment or string literal
10747 (let ((state (parse-partial-sexp bracket (point))))
10748 (not (or (nth 3 state) (nth 4 state)))))
10749 (match-beginning 1))))))))
10750
10751 (defun js2-array-comp-indentation (parse-status for-kwd)
10752 (if (js2-same-line for-kwd)
10753 ;; first continuation line
10754 (save-excursion
10755 (goto-char (nth 1 parse-status))
10756 (forward-char 1)
10757 (skip-chars-forward " \t")
10758 (current-column))
10759 (save-excursion
10760 (goto-char for-kwd)
10761 (current-column))))
10762
10763 (defun js2-proper-indentation (parse-status)
10764 "Return the proper indentation for the current line."
10765 (save-excursion
10766 (back-to-indentation)
10767 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10768 (at-closing-bracket (looking-at "[]})]"))
10769 (same-indent-p (or at-closing-bracket
10770 (looking-at "\\<case\\>[^:]")
10771 (and (looking-at "\\<default:")
10772 (save-excursion
10773 (js2-backward-sws)
10774 (not (memq (char-before) '(?, ?{)))))))
10775 (continued-expr-p (js2-continued-expression-p))
10776 (declaration-indent (and js2-pretty-multiline-declarations
10777 (js2-multiline-decl-indentation)))
10778 (bracket (nth 1 parse-status))
10779 beg indent)
10780 (cond
10781 ;; indent array comprehension continuation lines specially
10782 ((and bracket
10783 (>= js2-language-version 170)
10784 (not (js2-same-line bracket))
10785 (setq beg (js2-indent-in-array-comp parse-status))
10786 (>= (point) (save-excursion
10787 (goto-char beg)
10788 (point-at-bol)))) ; at or after first loop?
10789 (js2-array-comp-indentation parse-status beg))
10790
10791 (ctrl-stmt-indent)
10792
10793 ((and declaration-indent continued-expr-p)
10794 (+ declaration-indent js2-basic-offset))
10795
10796 (declaration-indent)
10797
10798 (bracket
10799 (goto-char bracket)
10800 (cond
10801 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10802 (when (save-excursion (skip-chars-backward " \t)")
10803 (looking-at ")"))
10804 (backward-list))
10805 (back-to-indentation)
10806 (and (eq js2-pretty-multiline-declarations 'all)
10807 (looking-at js2-declaration-keyword-re)
10808 (goto-char (1+ (match-end 0))))
10809 (setq indent
10810 (cond (same-indent-p
10811 (current-column))
10812 (continued-expr-p
10813 (+ (current-column) (* 2 js2-basic-offset)))
10814 (t
10815 (+ (current-column) js2-basic-offset))))
10816 (if (and js2-indent-switch-body
10817 (not at-closing-bracket)
10818 (looking-at "\\_<switch\\_>"))
10819 (+ indent js2-basic-offset)
10820 indent))
10821 (t
10822 (unless same-indent-p
10823 (forward-char)
10824 (skip-chars-forward " \t"))
10825 (current-column))))
10826
10827 (continued-expr-p js2-basic-offset)
10828
10829 (t 0)))))
10830
10831 (defun js2-lineup-comment (parse-status)
10832 "Indent a multi-line block comment continuation line."
10833 (let* ((beg (nth 8 parse-status))
10834 (first-line (js2-same-line beg))
10835 (offset (save-excursion
10836 (goto-char beg)
10837 (if (looking-at "/\\*")
10838 (+ 1 (current-column))
10839 0))))
10840 (unless first-line
10841 (indent-line-to offset))))
10842
10843 (defun js2-backward-sws ()
10844 "Move backward through whitespace and comments."
10845 (interactive)
10846 (while (forward-comment -1)))
10847
10848 (defun js2-forward-sws ()
10849 "Move forward through whitespace and comments."
10850 (interactive)
10851 (while (forward-comment 1)))
10852
10853 (defun js2-current-indent (&optional pos)
10854 "Return column of indentation on current line.
10855 If POS is non-nil, go to that point and return indentation for that line."
10856 (save-excursion
10857 (if pos
10858 (goto-char pos))
10859 (back-to-indentation)
10860 (current-column)))
10861
10862 (defun js2-arglist-close ()
10863 "Return non-nil if we're on a line beginning with a close-paren/brace."
10864 (save-excursion
10865 (goto-char (point-at-bol))
10866 (js2-forward-sws)
10867 (looking-at "[])}]")))
10868
10869 (defun js2-indent-looks-like-label-p ()
10870 (goto-char (point-at-bol))
10871 (js2-forward-sws)
10872 (looking-at (concat js2-mode-identifier-re ":")))
10873
10874 (defun js2-indent-in-objlit-p (parse-status)
10875 "Return non-nil if this looks like an object-literal entry."
10876 (let ((start (nth 1 parse-status)))
10877 (and
10878 start
10879 (save-excursion
10880 (and (zerop (forward-line -1))
10881 (not (< (point) start)) ; crossed a {} boundary
10882 (js2-indent-looks-like-label-p)))
10883 (save-excursion
10884 (js2-indent-looks-like-label-p)))))
10885
10886 ;; If prev line looks like foobar({ then we're passing an object
10887 ;; literal to a function call, and people pretty much always want to
10888 ;; de-dent back to the previous line, so move the 'basic-offset'
10889 ;; position to the front.
10890 (defun js2-indent-objlit-arg-p (parse-status)
10891 (save-excursion
10892 (back-to-indentation)
10893 (js2-backward-sws)
10894 (and (eq (1- (point)) (nth 1 parse-status))
10895 (eq (char-before) ?{)
10896 (progn
10897 (forward-char -1)
10898 (skip-chars-backward " \t")
10899 (eq (char-before) ?\()))))
10900
10901 (defun js2-indent-case-block-p ()
10902 (save-excursion
10903 (back-to-indentation)
10904 (js2-backward-sws)
10905 (goto-char (point-at-bol))
10906 (skip-chars-forward " \t")
10907 (looking-at "case\\s-.+:")))
10908
10909 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10910 "Cycle among alternate computed indentation positions.
10911 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10912 of the buffer to the current point. NORMAL-COL is the indentation
10913 column computed by the heuristic guesser based on current paren,
10914 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10915 in reverse."
10916 (let ((cur-indent (js2-current-indent))
10917 (old-buffer-undo-list buffer-undo-list)
10918 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10919 (current-line (save-excursion
10920 (forward-line 0) ; move to bol
10921 (1+ (count-lines (point-min) (point)))))
10922 positions pos main-pos anchor arglist-cont same-indent
10923 basic-offset computed-pos)
10924 ;; temporarily don't record undo info, if user requested this
10925 (when js2-mode-indent-inhibit-undo
10926 (setq buffer-undo-list t))
10927 (unwind-protect
10928 (progn
10929 ;; First likely point: indent from beginning of previous code line
10930 (push (setq basic-offset
10931 (+ (save-excursion
10932 (back-to-indentation)
10933 (js2-backward-sws)
10934 (back-to-indentation)
10935 (current-column))
10936 js2-basic-offset))
10937 positions)
10938
10939 ;; (First + epsilon) likely point: indent 2x from beginning of
10940 ;; previous code line. Google does it this way.
10941 (push (setq basic-offset
10942 (+ (save-excursion
10943 (back-to-indentation)
10944 (js2-backward-sws)
10945 (back-to-indentation)
10946 (current-column))
10947 (* 2 js2-basic-offset)))
10948 positions)
10949
10950 ;; Second likely point: indent from assign-expr RHS. This
10951 ;; is just a crude guess based on finding " = " on the previous
10952 ;; line containing actual code.
10953 (setq pos (save-excursion
10954 (forward-line -1)
10955 (goto-char (point-at-bol))
10956 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10957 (point-at-eol) t)
10958 (goto-char (match-end 1))
10959 (skip-chars-forward " \t\r\n")
10960 (current-column))))
10961 (when pos
10962 (cl-incf pos js2-basic-offset)
10963 (push pos positions))
10964
10965 ;; Third likely point: same indent as previous line of code.
10966 ;; Make it the first likely point if we're not on an
10967 ;; arglist-close line and previous line ends in a comma, or
10968 ;; both this line and prev line look like object-literal
10969 ;; elements.
10970 (setq pos (save-excursion
10971 (goto-char (point-at-bol))
10972 (js2-backward-sws)
10973 (back-to-indentation)
10974 (prog1
10975 (current-column)
10976 ;; while we're here, look for trailing comma
10977 (if (save-excursion
10978 (goto-char (point-at-eol))
10979 (js2-backward-sws)
10980 (eq (char-before) ?,))
10981 (setq arglist-cont (1- (point)))))))
10982 (when pos
10983 (if (and (or arglist-cont
10984 (js2-indent-in-objlit-p parse-status))
10985 (not (js2-arglist-close)))
10986 (setq same-indent pos))
10987 (push pos positions))
10988
10989 ;; Fourth likely point: first preceding code with less indentation.
10990 ;; than the immediately preceding code line.
10991 (setq pos (save-excursion
10992 (back-to-indentation)
10993 (js2-backward-sws)
10994 (back-to-indentation)
10995 (setq anchor (current-column))
10996 (while (and (zerop (forward-line -1))
10997 (>= (progn
10998 (back-to-indentation)
10999 (current-column))
11000 anchor)))
11001 (setq pos (current-column))))
11002 (push pos positions)
11003
11004 ;; nesting-heuristic position, main by default
11005 (push (setq main-pos normal-col) positions)
11006
11007 ;; delete duplicates and sort positions list
11008 (setq positions (sort (delete-dups positions) '<))
11009
11010 ;; comma-list continuation lines: prev line indent takes precedence
11011 (if same-indent
11012 (setq main-pos same-indent))
11013
11014 ;; common special cases where we want to indent in from previous line
11015 (if (or (js2-indent-case-block-p)
11016 (js2-indent-objlit-arg-p parse-status))
11017 (setq main-pos basic-offset))
11018
11019 ;; if bouncing backwards, reverse positions list
11020 (if backwards
11021 (setq positions (reverse positions)))
11022
11023 ;; record whether we're already sitting on one of the alternatives
11024 (setq pos (member cur-indent positions))
11025
11026 (cond
11027 ;; case 0: we're one one of the alternatives and this is the
11028 ;; first time they've pressed TAB on this line (best-guess).
11029 ((and js2-mode-indent-ignore-first-tab
11030 pos
11031 ;; first time pressing TAB on this line?
11032 (not (eq js2-mode-last-indented-line current-line)))
11033 ;; do nothing
11034 (setq computed-pos nil))
11035 ;; case 1: only one computed position => use it
11036 ((null (cdr positions))
11037 (setq computed-pos 0))
11038 ;; case 2: not on any of the computed spots => use main spot
11039 ((not pos)
11040 (setq computed-pos (js2-position main-pos positions)))
11041 ;; case 3: on last position: cycle to first position
11042 ((null (cdr pos))
11043 (setq computed-pos 0))
11044 ;; case 4: on intermediate position: cycle to next position
11045 (t
11046 (setq computed-pos (js2-position (cl-second pos) positions))))
11047
11048 ;; see if any hooks want to indent; otherwise we do it
11049 (cl-loop with result = nil
11050 for hook in js2-indent-hook
11051 while (null result)
11052 do
11053 (setq result (funcall hook positions computed-pos))
11054 finally do
11055 (unless (or result (null computed-pos))
11056 (indent-line-to (nth computed-pos positions)))))
11057
11058 ;; finally
11059 (if js2-mode-indent-inhibit-undo
11060 (setq buffer-undo-list old-buffer-undo-list))
11061 ;; see commentary for `js2-mode-last-indented-line'
11062 (setq js2-mode-last-indented-line current-line))))
11063
11064 (defun js2-indent-bounce-backwards ()
11065 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11066 cycles between the computed indentation positions in reverse order."
11067 (interactive)
11068 (js2-indent-line t))
11069
11070 (defun js2-1-line-comment-continuation-p ()
11071 "Return t if we're in a 1-line comment continuation.
11072 If so, we don't ever want to use bounce-indent."
11073 (save-excursion
11074 (and (progn
11075 (forward-line 0)
11076 (looking-at "\\s-*//"))
11077 (progn
11078 (forward-line -1)
11079 (forward-line 0)
11080 (when (looking-at "\\s-*$")
11081 (js2-backward-sws)
11082 (forward-line 0))
11083 (looking-at "\\s-*//")))))
11084
11085 (defun js2-indent-line (&optional bounce-backwards)
11086 "Indent the current line as JavaScript source text."
11087 (interactive)
11088 (let (parse-status offset indent-col
11089 ;; Don't whine about errors/warnings when we're indenting.
11090 ;; This has to be set before calling parse-partial-sexp below.
11091 (inhibit-point-motion-hooks t))
11092 (setq parse-status (save-excursion
11093 (syntax-ppss (point-at-bol)))
11094 offset (- (point) (save-excursion
11095 (back-to-indentation)
11096 (point))))
11097 (js2-with-underscore-as-word-syntax
11098 (if (nth 4 parse-status)
11099 (js2-lineup-comment parse-status)
11100 (setq indent-col (js2-proper-indentation parse-status))
11101 ;; See comments below about `js2-mode-last-indented-line'.
11102 (cond
11103 ;; bounce-indenting is disabled during electric-key indent.
11104 ;; It doesn't work well on first line of buffer.
11105 ((and js2-bounce-indent-p
11106 (not (js2-same-line (point-min)))
11107 (not (js2-1-line-comment-continuation-p)))
11108 (js2-bounce-indent indent-col parse-status bounce-backwards))
11109 ;; just indent to the guesser's likely spot
11110 (t (indent-line-to indent-col))))
11111 (when (cl-plusp offset)
11112 (forward-char offset)))))
11113
11114 (defun js2-indent-region (start end)
11115 "Indent the region, but don't use bounce indenting."
11116 (let ((js2-bounce-indent-p nil)
11117 (indent-region-function nil)
11118 (after-change-functions (remq 'js2-mode-edit
11119 after-change-functions)))
11120 (indent-region start end nil) ; nil for byte-compiler
11121 (js2-mode-edit start end (- end start))))
11122
11123 (defvar js2-minor-mode-map
11124 (let ((map (make-sparse-keymap)))
11125 (define-key map (kbd "C-c C-`") #'js2-next-error)
11126 (define-key map [mouse-1] #'js2-mode-show-node)
11127 map)
11128 "Keymap used when `js2-minor-mode' is active.")
11129
11130 ;;;###autoload
11131 (define-minor-mode js2-minor-mode
11132 "Minor mode for running js2 as a background linter.
11133 This allows you to use a different major mode for JavaScript editing,
11134 such as `js-mode', while retaining the asynchronous error/warning
11135 highlighting features of `js2-mode'."
11136 :group 'js2-mode
11137 :lighter " js-lint"
11138 (if js2-minor-mode
11139 (js2-minor-mode-enter)
11140 (js2-minor-mode-exit)))
11141
11142 (defun js2-minor-mode-enter ()
11143 "Initialization for `js2-minor-mode'."
11144 (set (make-local-variable 'max-lisp-eval-depth)
11145 (max max-lisp-eval-depth 3000))
11146 (setq next-error-function #'js2-next-error)
11147 (js2-set-default-externs)
11148 ;; Experiment: make reparse-delay longer for longer files.
11149 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11150 (setq js2-idle-timer-delay
11151 (* js2-idle-timer-delay
11152 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11153 (setq js2-mode-buffer-dirty-p t
11154 js2-mode-parsing nil)
11155 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11156 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11157 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11158 (when js2-include-jslint-globals
11159 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11160 (run-hooks 'js2-init-hook)
11161 (js2-reparse))
11162
11163 (defun js2-minor-mode-exit ()
11164 "Turn off `js2-minor-mode'."
11165 (setq next-error-function nil)
11166 (remove-hook 'after-change-functions #'js2-mode-edit t)
11167 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11168 (when js2-mode-node-overlay
11169 (delete-overlay js2-mode-node-overlay)
11170 (setq js2-mode-node-overlay nil))
11171 (js2-remove-overlays)
11172 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11173 (setq js2-mode-ast nil))
11174
11175 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11176 (make-variable-buffer-local 'js2-source-buffer)
11177
11178 (cl-defun js2-display-error-list ()
11179 "Display a navigable buffer listing parse errors/warnings."
11180 (interactive)
11181 (unless (js2-have-errors-p)
11182 (message "No errors")
11183 (cl-return-from js2-display-error-list))
11184 (cl-labels ((annotate-list
11185 (lst type)
11186 "Add diagnostic TYPE and line number to errs list"
11187 (mapcar (lambda (err)
11188 (list err type (line-number-at-pos (nth 1 err))))
11189 lst)))
11190 (let* ((srcbuf (current-buffer))
11191 (errbuf (get-buffer-create "*js-lint*"))
11192 (errors (annotate-list
11193 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11194 'js2-error)) ; must be a valid face name
11195 (warnings (annotate-list
11196 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11197 'js2-warning)) ; must be a valid face name
11198 (all-errs (sort (append errors warnings)
11199 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11200 (with-current-buffer errbuf
11201 (let ((inhibit-read-only t))
11202 (erase-buffer)
11203 (dolist (err all-errs)
11204 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11205 (insert-text-button
11206 (format "line %d: %s" line (js2-get-msg msg-key))
11207 'face type
11208 'follow-link "\C-m"
11209 'action 'js2-error-buffer-jump
11210 'js2-msg (js2-get-msg msg-key)
11211 'js2-pos beg)
11212 (insert "\n"))))
11213 (js2-error-buffer-mode)
11214 (setq js2-source-buffer srcbuf)
11215 (pop-to-buffer errbuf)
11216 (goto-char (point-min))
11217 (unless (eobp)
11218 (js2-error-buffer-view))))))
11219
11220 (defvar js2-error-buffer-mode-map
11221 (let ((map (make-sparse-keymap)))
11222 (define-key map "n" #'js2-error-buffer-next)
11223 (define-key map "p" #'js2-error-buffer-prev)
11224 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11225 (define-key map "o" #'js2-error-buffer-view)
11226 (define-key map "q" #'js2-error-buffer-quit)
11227 map)
11228 "Keymap used for js2 diagnostics buffers.")
11229
11230 (defun js2-error-buffer-mode ()
11231 "Major mode for js2 diagnostics buffers.
11232 Selecting an error will jump it to the corresponding source-buffer error.
11233 \\{js2-error-buffer-mode-map}"
11234 (interactive)
11235 (setq major-mode 'js2-error-buffer-mode
11236 mode-name "JS Lint Diagnostics")
11237 (use-local-map js2-error-buffer-mode-map)
11238 (setq truncate-lines t)
11239 (set-buffer-modified-p nil)
11240 (setq buffer-read-only t)
11241 (run-hooks 'js2-error-buffer-mode-hook))
11242
11243 (defun js2-error-buffer-next ()
11244 "Move to next error and view it."
11245 (interactive)
11246 (when (zerop (forward-line 1))
11247 (js2-error-buffer-view)))
11248
11249 (defun js2-error-buffer-prev ()
11250 "Move to previous error and view it."
11251 (interactive)
11252 (when (zerop (forward-line -1))
11253 (js2-error-buffer-view)))
11254
11255 (defun js2-error-buffer-quit ()
11256 "Kill the current buffer."
11257 (interactive)
11258 (kill-buffer))
11259
11260 (defun js2-error-buffer-jump (&rest ignored)
11261 "Jump cursor to current error in source buffer."
11262 (interactive)
11263 (when (js2-error-buffer-view)
11264 (pop-to-buffer js2-source-buffer)))
11265
11266 (defun js2-error-buffer-view ()
11267 "Scroll source buffer to show error at current line."
11268 (interactive)
11269 (cond
11270 ((not (eq major-mode 'js2-error-buffer-mode))
11271 (message "Not in a js2 errors buffer"))
11272 ((not (buffer-live-p js2-source-buffer))
11273 (message "Source buffer has been killed"))
11274 ((not (wholenump (get-text-property (point) 'js2-pos)))
11275 (message "There does not seem to be an error here"))
11276 (t
11277 (let ((pos (get-text-property (point) 'js2-pos))
11278 (msg (get-text-property (point) 'js2-msg)))
11279 (save-selected-window
11280 (pop-to-buffer js2-source-buffer)
11281 (goto-char pos)
11282 (message msg))))))
11283
11284 ;;;###autoload
11285 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11286 ;; FIXME: Should derive from js-mode.
11287 "Major mode for editing JavaScript code."
11288 ;; Used by comment-region; don't change it.
11289 (set (make-local-variable 'comment-start) "//")
11290 (set (make-local-variable 'comment-end) "")
11291 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11292 (set (make-local-variable 'max-lisp-eval-depth)
11293 (max max-lisp-eval-depth 3000))
11294 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11295 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11296 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11297 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11298 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11299 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11300 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11301 ;; for characters inside regexp literals.
11302 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11303 ;; this is necessary to make `show-paren-function' work properly
11304 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11305 ;; needed for M-x rgrep, among other things
11306 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11307
11308 (set (make-local-variable 'electric-indent-chars)
11309 (append "{}()[]:;,*." electric-indent-chars))
11310 (set (make-local-variable 'electric-layout-rules)
11311 '((?\; . after) (?\{ . after) (?\} . before)))
11312
11313 ;; some variables needed by cc-engine for paragraph-fill, etc.
11314 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11315 c-comment-start-regexp "/[*/]\\|\\s|"
11316 c-line-comment-starter "//"
11317 c-paragraph-start js2-paragraph-start
11318 c-paragraph-separate "$"
11319 c-syntactic-ws-start js2-syntactic-ws-start
11320 c-syntactic-ws-end js2-syntactic-ws-end
11321 c-syntactic-eol js2-syntactic-eol)
11322
11323 (let ((c-buffer-is-cc-mode t))
11324 ;; Copied from `js-mode'. Also see Bug#6071.
11325 (make-local-variable 'paragraph-start)
11326 (make-local-variable 'paragraph-separate)
11327 (make-local-variable 'paragraph-ignore-fill-prefix)
11328 (make-local-variable 'adaptive-fill-mode)
11329 (make-local-variable 'adaptive-fill-regexp)
11330 (c-setup-paragraph-variables))
11331
11332 (setq font-lock-defaults '(nil t))
11333
11334 ;; Experiment: make reparse-delay longer for longer files.
11335 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11336 (setq js2-idle-timer-delay
11337 (* js2-idle-timer-delay
11338 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11339
11340 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11341 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11342 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11343 (setq next-error-function #'js2-next-error)
11344 (imenu-add-to-menubar (concat "IM-" mode-name))
11345 (add-to-invisibility-spec '(js2-outline . t))
11346 (set (make-local-variable 'line-move-ignore-invisible) t)
11347 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11348
11349 (setq js2-mode-functions-hidden nil
11350 js2-mode-comments-hidden nil
11351 js2-mode-buffer-dirty-p t
11352 js2-mode-parsing nil)
11353
11354 (js2-set-default-externs)
11355
11356 (when js2-include-jslint-globals
11357 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11358
11359 (run-hooks 'js2-init-hook)
11360
11361 (js2-reparse))
11362
11363 (defun js2-mode-exit ()
11364 "Exit `js2-mode' and clean up."
11365 (interactive)
11366 (when js2-mode-node-overlay
11367 (delete-overlay js2-mode-node-overlay)
11368 (setq js2-mode-node-overlay nil))
11369 (js2-remove-overlays)
11370 (setq js2-mode-ast nil)
11371 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11372 (remove-from-invisibility-spec '(js2-outline . t))
11373 (js2-mode-show-all)
11374 (with-silent-modifications
11375 (js2-clear-face (point-min) (point-max))))
11376
11377 (defun js2-mode-reset-timer ()
11378 "Cancel any existing parse timer and schedule a new one."
11379 (if js2-mode-parse-timer
11380 (cancel-timer js2-mode-parse-timer))
11381 (setq js2-mode-parsing nil)
11382 (let ((timer (timer-create)))
11383 (setq js2-mode-parse-timer timer)
11384 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11385 (timer-set-idle-time timer js2-idle-timer-delay)
11386 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11387 (timer-activate-when-idle timer nil)))
11388
11389 (defun js2-mode-idle-reparse (buffer)
11390 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11391 it to be reparsed when the buffer is selected."
11392 (cond ((eq buffer (current-buffer))
11393 (js2-reparse))
11394 ((buffer-live-p buffer)
11395 ;; reparse when the buffer is selected again
11396 (with-current-buffer buffer
11397 (add-hook 'window-configuration-change-hook
11398 #'js2-mode-idle-reparse-inner
11399 nil t)))))
11400
11401 (defun js2-mode-idle-reparse-inner ()
11402 (remove-hook 'window-configuration-change-hook
11403 #'js2-mode-idle-reparse-inner
11404 t)
11405 (js2-reparse))
11406
11407 (defun js2-mode-edit (_beg _end _len)
11408 "Schedule a new parse after buffer is edited.
11409 Buffer edit spans from BEG to END and is of length LEN."
11410 (setq js2-mode-buffer-dirty-p t)
11411 (js2-mode-hide-overlay)
11412 (js2-mode-reset-timer))
11413
11414 (defun js2-minor-mode-edit (_beg _end _len)
11415 "Callback for buffer edits in `js2-mode'.
11416 Schedules a new parse after buffer is edited.
11417 Buffer edit spans from BEG to END and is of length LEN."
11418 (setq js2-mode-buffer-dirty-p t)
11419 (js2-mode-hide-overlay)
11420 (js2-mode-reset-timer))
11421
11422 (defun js2-reparse (&optional force)
11423 "Re-parse current buffer after user finishes some data entry.
11424 If we get any user input while parsing, including cursor motion,
11425 we discard the parse and reschedule it. If FORCE is nil, then the
11426 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11427 (let (time
11428 interrupted-p
11429 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11430 (unless js2-mode-parsing
11431 (setq js2-mode-parsing t)
11432 (unwind-protect
11433 (when (or js2-mode-buffer-dirty-p force)
11434 (js2-remove-overlays)
11435 (setq js2-mode-buffer-dirty-p nil
11436 js2-mode-fontifications nil
11437 js2-mode-deferred-properties nil)
11438 (if js2-mode-verbose-parse-p
11439 (message "parsing..."))
11440 (setq time
11441 (js2-time
11442 (setq interrupted-p
11443 (catch 'interrupted
11444 (js2-parse)
11445 (with-silent-modifications
11446 ;; if parsing is interrupted, comments and regex
11447 ;; literals stay ignored by `parse-partial-sexp'
11448 (remove-text-properties (point-min) (point-max)
11449 '(syntax-table))
11450 (js2-mode-apply-deferred-properties)
11451 (js2-mode-remove-suppressed-warnings)
11452 (js2-mode-show-warnings)
11453 (js2-mode-show-errors)
11454 (if (>= js2-highlight-level 1)
11455 (js2-highlight-jsdoc js2-mode-ast)))
11456 nil))))
11457 (if interrupted-p
11458 (progn
11459 ;; unfinished parse => try again
11460 (setq js2-mode-buffer-dirty-p t)
11461 (js2-mode-reset-timer))
11462 (if js2-mode-verbose-parse-p
11463 (message "Parse time: %s" time))))
11464 (setq js2-mode-parsing nil)
11465 (unless interrupted-p
11466 (setq js2-mode-parse-timer nil))))))
11467
11468 (defun js2-mode-show-node (event)
11469 "Debugging aid: highlight selected AST node on mouse click."
11470 (interactive "e")
11471 (mouse-set-point event)
11472 (setq deactivate-mark t)
11473 (when js2-mode-show-overlay
11474 (let ((node (js2-node-at-point))
11475 beg end)
11476 (if (null node)
11477 (message "No node found at location %s" (point))
11478 (setq beg (js2-node-abs-pos node)
11479 end (+ beg (js2-node-len node)))
11480 (if js2-mode-node-overlay
11481 (move-overlay js2-mode-node-overlay beg end)
11482 (setq js2-mode-node-overlay (make-overlay beg end))
11483 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11484 (with-silent-modifications
11485 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
11486 (message "%s, parent: %s"
11487 (js2-node-short-name node)
11488 (if (js2-node-parent node)
11489 (js2-node-short-name (js2-node-parent node))
11490 "nil"))))))
11491
11492 (defun js2-mode-hide-overlay (&optional _p1 p2)
11493 "Remove the debugging overlay when the point moves.
11494 P1 and P2 are the old and new values of point, respectively."
11495 (when js2-mode-node-overlay
11496 (let ((beg (overlay-start js2-mode-node-overlay))
11497 (end (overlay-end js2-mode-node-overlay)))
11498 ;; Sometimes we're called spuriously.
11499 (unless (and p2
11500 (>= p2 beg)
11501 (<= p2 end))
11502 (with-silent-modifications
11503 (remove-text-properties beg end '(point-left nil)))
11504 (delete-overlay js2-mode-node-overlay)
11505 (setq js2-mode-node-overlay nil)))))
11506
11507 (defun js2-mode-reset ()
11508 "Debugging helper: reset everything."
11509 (interactive)
11510 (js2-mode-exit)
11511 (js2-mode))
11512
11513 (defun js2-mode-show-warn-or-err (e face)
11514 "Highlight a warning or error E with FACE.
11515 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11516 The last element is optional. When present, use instead of FACE."
11517 (let* ((key (cl-first e))
11518 (beg (cl-second e))
11519 (end (+ beg (cl-third e)))
11520 ;; Don't inadvertently go out of bounds.
11521 (beg (max (point-min) (min beg (point-max))))
11522 (end (max (point-min) (min end (point-max))))
11523 (ovl (make-overlay beg end)))
11524 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11525 (overlay-put ovl 'js2-error t)
11526 (put-text-property beg end 'help-echo (js2-get-msg key))
11527 (put-text-property beg end 'point-entered #'js2-echo-error)))
11528
11529 (defun js2-remove-overlays ()
11530 "Remove overlays from buffer that have a `js2-error' property."
11531 (let ((beg (point-min))
11532 (end (point-max)))
11533 (save-excursion
11534 (dolist (o (overlays-in beg end))
11535 (when (overlay-get o 'js2-error)
11536 (delete-overlay o))))))
11537
11538 (defun js2-error-at-point (&optional pos)
11539 "Return non-nil if there's an error overlay at POS.
11540 Defaults to point."
11541 (cl-loop with pos = (or pos (point))
11542 for o in (overlays-at pos)
11543 thereis (overlay-get o 'js2-error)))
11544
11545 (defun js2-mode-apply-deferred-properties ()
11546 "Apply fontifications and other text properties recorded during parsing."
11547 (when (cl-plusp js2-highlight-level)
11548 ;; We defer clearing faces as long as possible to eliminate flashing.
11549 (js2-clear-face (point-min) (point-max))
11550 ;; Have to reverse the recorded fontifications list so that errors
11551 ;; and warnings overwrite the normal fontifications.
11552 (dolist (f (nreverse js2-mode-fontifications))
11553 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11554 (setq js2-mode-fontifications nil))
11555 (dolist (p js2-mode-deferred-properties)
11556 (apply #'put-text-property p))
11557 (setq js2-mode-deferred-properties nil))
11558
11559 (defun js2-mode-show-errors ()
11560 "Highlight syntax errors."
11561 (when js2-mode-show-parse-errors
11562 (dolist (e (js2-ast-root-errors js2-mode-ast))
11563 (js2-mode-show-warn-or-err e 'js2-error))))
11564
11565 (defun js2-mode-remove-suppressed-warnings ()
11566 "Take suppressed warnings out of the AST warnings list.
11567 This ensures that the counts and `next-error' are correct."
11568 (setf (js2-ast-root-warnings js2-mode-ast)
11569 (js2-delete-if
11570 (lambda (e)
11571 (let ((key (caar e)))
11572 (or
11573 (and (not js2-strict-trailing-comma-warning)
11574 (string-match "trailing\\.comma" key))
11575 (and (not js2-strict-cond-assign-warning)
11576 (string= key "msg.equal.as.assign"))
11577 (and js2-missing-semi-one-line-override
11578 (string= key "msg.missing.semi")
11579 (let* ((beg (cl-second e))
11580 (node (js2-node-at-point beg))
11581 (fn (js2-mode-find-parent-fn node))
11582 (body (and fn (js2-function-node-body fn)))
11583 (lc (and body (js2-node-abs-pos body)))
11584 (rc (and lc (+ lc (js2-node-len body)))))
11585 (and fn
11586 (or (null body)
11587 (save-excursion
11588 (goto-char beg)
11589 (and (js2-same-line lc)
11590 (js2-same-line rc))))))))))
11591 (js2-ast-root-warnings js2-mode-ast))))
11592
11593 (defun js2-mode-show-warnings ()
11594 "Highlight strict-mode warnings."
11595 (when js2-mode-show-strict-warnings
11596 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11597 (js2-mode-show-warn-or-err e 'js2-warning))))
11598
11599 (defun js2-echo-error (_old-point new-point)
11600 "Called by point-motion hooks."
11601 (let ((msg (get-text-property new-point 'help-echo)))
11602 (when (and (stringp msg)
11603 (not (active-minibuffer-window))
11604 (not (current-message)))
11605 (message msg))))
11606
11607 (defalias 'js2-echo-help #'js2-echo-error)
11608
11609 (defun js2-line-break (&optional _soft)
11610 "Break line at point and indent, continuing comment if within one.
11611 If inside a string, and `js2-concat-multiline-strings' is not
11612 nil, turn it into concatenation."
11613 (interactive)
11614 (let ((parse-status (syntax-ppss)))
11615 (cond
11616 ;; Check if we're inside a string.
11617 ((nth 3 parse-status)
11618 (if js2-concat-multiline-strings
11619 (js2-mode-split-string parse-status)
11620 (insert "\n")))
11621 ;; Check if inside a block comment.
11622 ((nth 4 parse-status)
11623 (js2-mode-extend-comment (nth 8 parse-status)))
11624 (t
11625 (newline-and-indent)))))
11626
11627 (defun js2-mode-split-string (parse-status)
11628 "Turn a newline in mid-string into a string concatenation.
11629 PARSE-STATUS is as documented in `parse-partial-sexp'."
11630 (let* ((quote-char (nth 3 parse-status))
11631 (at-eol (eq js2-concat-multiline-strings 'eol)))
11632 (insert quote-char)
11633 (insert (if at-eol " +\n" "\n"))
11634 (unless at-eol
11635 (insert "+ "))
11636 (js2-indent-line)
11637 (insert quote-char)
11638 (when (eolp)
11639 (insert quote-char)
11640 (backward-char 1))))
11641
11642 (defun js2-mode-extend-comment (start-pos)
11643 "Indent the line and, when inside a comment block, add comment prefix."
11644 (let (star single col first-line needs-close)
11645 (save-excursion
11646 (back-to-indentation)
11647 (when (< (point) start-pos)
11648 (goto-char start-pos))
11649 (cond
11650 ((looking-at "\\*[^/]")
11651 (setq star t
11652 col (current-column)))
11653 ((looking-at "/\\*")
11654 (setq star t
11655 first-line t
11656 col (1+ (current-column))))
11657 ((looking-at "//")
11658 (setq single t
11659 col (current-column)))))
11660 ;; Heuristic for whether we need to close the comment:
11661 ;; if we've got a parse error here, assume it's an unterminated
11662 ;; comment.
11663 (setq needs-close
11664 (or
11665 (eq (get-text-property (1- (point)) 'point-entered)
11666 'js2-echo-error)
11667 ;; The heuristic above doesn't work well when we're
11668 ;; creating a comment and there's another one downstream,
11669 ;; as our parser thinks this one ends at the end of the
11670 ;; next one. (You can have a /* inside a js block comment.)
11671 ;; So just close it if the next non-ws char isn't a *.
11672 (and first-line
11673 (eolp)
11674 (save-excursion
11675 (skip-chars-forward " \t\r\n")
11676 (not (eq (char-after) ?*))))))
11677 (delete-horizontal-space)
11678 (insert "\n")
11679 (cond
11680 (star
11681 (indent-to col)
11682 (insert "* ")
11683 (if (and first-line needs-close)
11684 (save-excursion
11685 (insert "\n")
11686 (indent-to col)
11687 (insert "*/"))))
11688 ((and single
11689 (save-excursion
11690 (and (zerop (forward-line 1))
11691 (looking-at "\\s-*//"))))
11692 (indent-to col)
11693 (insert "// ")))
11694 ;; Don't need to extend the comment after all.
11695 (js2-indent-line)))
11696
11697 (defun js2-beginning-of-line ()
11698 "Toggle point between bol and first non-whitespace char in line.
11699 Also moves past comment delimiters when inside comments."
11700 (interactive)
11701 (let (node)
11702 (cond
11703 ((bolp)
11704 (back-to-indentation))
11705 ((looking-at "//")
11706 (skip-chars-forward "/ \t"))
11707 ((and (eq (char-after) ?*)
11708 (setq node (js2-comment-at-point))
11709 (memq (js2-comment-node-format node) '(jsdoc block))
11710 (save-excursion
11711 (skip-chars-backward " \t")
11712 (bolp)))
11713 (skip-chars-forward "\* \t"))
11714 (t
11715 (goto-char (point-at-bol))))))
11716
11717 (defun js2-end-of-line ()
11718 "Toggle point between eol and last non-whitespace char in line."
11719 (interactive)
11720 (if (eolp)
11721 (skip-chars-backward " \t")
11722 (goto-char (point-at-eol))))
11723
11724 (defun js2-mode-wait-for-parse (callback)
11725 "Invoke CALLBACK when parsing is finished.
11726 If parsing is already finished, calls CALLBACK immediately."
11727 (if (not js2-mode-buffer-dirty-p)
11728 (funcall callback)
11729 (push callback js2-mode-pending-parse-callbacks)
11730 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11731
11732 (defun js2-mode-parse-finished ()
11733 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11734 ;; We can't let errors propagate up, since it prevents the
11735 ;; `js2-parse' method from completing normally and returning
11736 ;; the ast, which makes things mysteriously not work right.
11737 (unwind-protect
11738 (dolist (cb js2-mode-pending-parse-callbacks)
11739 (condition-case err
11740 (funcall cb)
11741 (error (message "%s" err))))
11742 (setq js2-mode-pending-parse-callbacks nil)))
11743
11744 (defun js2-mode-flag-region (from to flag)
11745 "Hide or show text from FROM to TO, according to FLAG.
11746 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11747 Returns the created overlay if FLAG is non-nil."
11748 (remove-overlays from to 'invisible 'js2-outline)
11749 (when flag
11750 (let ((o (make-overlay from to)))
11751 (overlay-put o 'invisible 'js2-outline)
11752 (overlay-put o 'isearch-open-invisible
11753 'js2-isearch-open-invisible)
11754 o)))
11755
11756 ;; Function to be set as an outline-isearch-open-invisible' property
11757 ;; to the overlay that makes the outline invisible (see
11758 ;; `js2-mode-flag-region').
11759 (defun js2-isearch-open-invisible (_overlay)
11760 ;; We rely on the fact that isearch places point on the matched text.
11761 (js2-mode-show-element))
11762
11763 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11764 "Return cons cell of bounds of folding overlay at POS.
11765 Returns nil if not found."
11766 (let ((overlays (overlays-at (or pos (point))))
11767 o)
11768 (while (and overlays
11769 (not o))
11770 (if (overlay-get (car overlays) 'invisible)
11771 (setq o (car overlays))
11772 (setq overlays (cdr overlays))))
11773 (if o
11774 (cons (overlay-start o) (overlay-end o)))))
11775
11776 (defun js2-mode-function-at-point (&optional pos)
11777 "Return the innermost function node enclosing current point.
11778 Returns nil if point is not in a function."
11779 (let ((node (js2-node-at-point pos)))
11780 (while (and node (not (js2-function-node-p node)))
11781 (setq node (js2-node-parent node)))
11782 (if (js2-function-node-p node)
11783 node)))
11784
11785 (defun js2-mode-toggle-element ()
11786 "Hide or show the foldable element at the point."
11787 (interactive)
11788 (let (comment fn pos)
11789 (save-excursion
11790 (cond
11791 ;; /* ... */ comment?
11792 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11793 (if (js2-mode-invisible-overlay-bounds
11794 (setq pos (+ 3 (js2-node-abs-pos comment))))
11795 (progn
11796 (goto-char pos)
11797 (js2-mode-show-element))
11798 (js2-mode-hide-element)))
11799 ;; //-comment?
11800 ((save-excursion
11801 (back-to-indentation)
11802 (looking-at js2-mode-//-comment-re))
11803 (js2-mode-toggle-//-comment))
11804 ;; function?
11805 ((setq fn (js2-mode-function-at-point))
11806 (setq pos (and (js2-function-node-body fn)
11807 (js2-node-abs-pos (js2-function-node-body fn))))
11808 (goto-char (1+ pos))
11809 (if (js2-mode-invisible-overlay-bounds)
11810 (js2-mode-show-element)
11811 (js2-mode-hide-element)))
11812 (t
11813 (message "Nothing at point to hide or show"))))))
11814
11815 (defun js2-mode-hide-element ()
11816 "Fold/hide contents of a block, showing ellipses.
11817 Show the hidden text with \\[js2-mode-show-element]."
11818 (interactive)
11819 (if js2-mode-buffer-dirty-p
11820 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11821 (let (node body beg end)
11822 (cond
11823 ((js2-mode-invisible-overlay-bounds)
11824 (message "already hidden"))
11825 (t
11826 (setq node (js2-node-at-point))
11827 (cond
11828 ((js2-block-comment-p node)
11829 (js2-mode-hide-comment node))
11830 (t
11831 (while (and node (not (js2-function-node-p node)))
11832 (setq node (js2-node-parent node)))
11833 (if (and node
11834 (setq body (js2-function-node-body node)))
11835 (progn
11836 (setq beg (js2-node-abs-pos body)
11837 end (+ beg (js2-node-len body)))
11838 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11839 (message "No collapsable element found at point"))))))))
11840
11841 (defun js2-mode-show-element ()
11842 "Show the hidden element at current point."
11843 (interactive)
11844 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11845 (if bounds
11846 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11847 (message "Nothing to un-hide"))))
11848
11849 (defun js2-mode-show-all ()
11850 "Show all of the text in the buffer."
11851 (interactive)
11852 (js2-mode-flag-region (point-min) (point-max) nil))
11853
11854 (defun js2-mode-toggle-hide-functions ()
11855 (interactive)
11856 (if js2-mode-functions-hidden
11857 (js2-mode-show-functions)
11858 (js2-mode-hide-functions)))
11859
11860 (defun js2-mode-hide-functions ()
11861 "Hides all non-nested function bodies in the buffer.
11862 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11863 to open an individual entry."
11864 (interactive)
11865 (if js2-mode-buffer-dirty-p
11866 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11867 (if (null js2-mode-ast)
11868 (message "Oops - parsing failed")
11869 (setq js2-mode-functions-hidden t)
11870 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11871
11872 (defun js2-mode-function-hider (n endp)
11873 (when (not endp)
11874 (let ((tt (js2-node-type n))
11875 body beg end)
11876 (cond
11877 ((and (= tt js2-FUNCTION)
11878 (setq body (js2-function-node-body n)))
11879 (setq beg (js2-node-abs-pos body)
11880 end (+ beg (js2-node-len body)))
11881 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11882 nil) ; don't process children of function
11883 (t
11884 t))))) ; keep processing other AST nodes
11885
11886 (defun js2-mode-show-functions ()
11887 "Un-hide any folded function bodies in the buffer."
11888 (interactive)
11889 (setq js2-mode-functions-hidden nil)
11890 (save-excursion
11891 (goto-char (point-min))
11892 (while (/= (goto-char (next-overlay-change (point)))
11893 (point-max))
11894 (dolist (o (overlays-at (point)))
11895 (when (and (overlay-get o 'invisible)
11896 (not (overlay-get o 'comment)))
11897 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11898
11899 (defun js2-mode-hide-comment (n)
11900 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11901 3 ; /**
11902 2)) ; /*
11903 (beg (+ (js2-node-abs-pos n) head))
11904 (end (- (+ beg (js2-node-len n)) head 2))
11905 (o (js2-mode-flag-region beg end 'hide)))
11906 (overlay-put o 'comment t)))
11907
11908 (defun js2-mode-toggle-hide-comments ()
11909 "Folds all block comments in the buffer.
11910 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11911 to open an individual entry."
11912 (interactive)
11913 (if js2-mode-comments-hidden
11914 (js2-mode-show-comments)
11915 (js2-mode-hide-comments)))
11916
11917 (defun js2-mode-hide-comments ()
11918 (interactive)
11919 (if js2-mode-buffer-dirty-p
11920 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11921 (if (null js2-mode-ast)
11922 (message "Oops - parsing failed")
11923 (setq js2-mode-comments-hidden t)
11924 (dolist (n (js2-ast-root-comments js2-mode-ast))
11925 (when (js2-block-comment-p n)
11926 (js2-mode-hide-comment n)))
11927 (js2-mode-hide-//-comments)))
11928
11929 (defun js2-mode-extend-//-comment (direction)
11930 "Find start or end of a block of similar //-comment lines.
11931 DIRECTION is -1 to look back, 1 to look forward.
11932 INDENT is the indentation level to match.
11933 Returns the end-of-line position of the furthest adjacent
11934 //-comment line with the same indentation as the current line.
11935 If there is no such matching line, returns current end of line."
11936 (let ((pos (point-at-eol))
11937 (indent (current-indentation)))
11938 (save-excursion
11939 (while (and (zerop (forward-line direction))
11940 (looking-at js2-mode-//-comment-re)
11941 (eq indent (length (match-string 1))))
11942 (setq pos (point-at-eol)))
11943 pos)))
11944
11945 (defun js2-mode-hide-//-comments ()
11946 "Fold adjacent 1-line comments, showing only snippet of first one."
11947 (let (beg end)
11948 (save-excursion
11949 (goto-char (point-min))
11950 (while (re-search-forward js2-mode-//-comment-re nil t)
11951 (setq beg (point)
11952 end (js2-mode-extend-//-comment 1))
11953 (unless (eq beg end)
11954 (overlay-put (js2-mode-flag-region beg end 'hide)
11955 'comment t))
11956 (goto-char end)
11957 (forward-char 1)))))
11958
11959 (defun js2-mode-toggle-//-comment ()
11960 "Fold or un-fold any multi-line //-comment at point.
11961 Caller should have determined that this line starts with a //-comment."
11962 (let* ((beg (point-at-eol))
11963 (end beg))
11964 (save-excursion
11965 (goto-char end)
11966 (if (js2-mode-invisible-overlay-bounds)
11967 (js2-mode-show-element)
11968 ;; else hide the comment
11969 (setq beg (js2-mode-extend-//-comment -1)
11970 end (js2-mode-extend-//-comment 1))
11971 (unless (eq beg end)
11972 (overlay-put (js2-mode-flag-region beg end 'hide)
11973 'comment t))))))
11974
11975 (defun js2-mode-show-comments ()
11976 "Un-hide any hidden comments, leaving other hidden elements alone."
11977 (interactive)
11978 (setq js2-mode-comments-hidden nil)
11979 (save-excursion
11980 (goto-char (point-min))
11981 (while (/= (goto-char (next-overlay-change (point)))
11982 (point-max))
11983 (dolist (o (overlays-at (point)))
11984 (when (overlay-get o 'comment)
11985 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11986
11987 (defun js2-mode-display-warnings-and-errors ()
11988 "Turn on display of warnings and errors."
11989 (interactive)
11990 (setq js2-mode-show-parse-errors t
11991 js2-mode-show-strict-warnings t)
11992 (js2-reparse 'force))
11993
11994 (defun js2-mode-hide-warnings-and-errors ()
11995 "Turn off display of warnings and errors."
11996 (interactive)
11997 (setq js2-mode-show-parse-errors nil
11998 js2-mode-show-strict-warnings nil)
11999 (js2-reparse 'force))
12000
12001 (defun js2-mode-toggle-warnings-and-errors ()
12002 "Toggle the display of warnings and errors.
12003 Some users don't like having warnings/errors reported while they type."
12004 (interactive)
12005 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12006 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12007 (if (called-interactively-p 'any)
12008 (message "warnings and errors %s"
12009 (if js2-mode-show-parse-errors
12010 "enabled"
12011 "disabled")))
12012 (js2-reparse 'force))
12013
12014 (defun js2-mode-customize ()
12015 (interactive)
12016 (customize-group 'js2-mode))
12017
12018 (defun js2-mode-forward-sexp (&optional arg)
12019 "Move forward across one statement or balanced expression.
12020 With ARG, do it that many times. Negative arg -N means
12021 move backward across N balanced expressions."
12022 (interactive "p")
12023 (setq arg (or arg 1))
12024 (save-restriction
12025 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12026 (js2-reparse)
12027 (let (forward-sexp-function
12028 node (start (point)) pos lp rp child)
12029 (cond
12030 ;; backward-sexp
12031 ;; could probably make this better for some cases:
12032 ;; - if in statement block (e.g. function body), go to parent
12033 ;; - infix exprs like (foo in bar) - maybe go to beginning
12034 ;; of infix expr if in the right-side expression?
12035 ((and arg (cl-minusp arg))
12036 (dotimes (_ (- arg))
12037 (js2-backward-sws)
12038 (forward-char -1) ; Enter the node we backed up to.
12039 (when (setq node (js2-node-at-point (point) t))
12040 (setq pos (js2-node-abs-pos node))
12041 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12042 (setq lp (car parens)
12043 rp (cdr parens)))
12044 (when (and lp (> start lp))
12045 (if (and rp (<= start rp))
12046 ;; Between parens, check if there's a child node we can jump.
12047 (when (setq child (js2-node-closest-child node (point) lp t))
12048 (setq pos (js2-node-abs-pos child)))
12049 ;; Before both parens.
12050 (setq pos lp)))
12051 (let ((state (parse-partial-sexp start pos)))
12052 (goto-char (if (not (zerop (car state)))
12053 ;; Stumble at the unbalanced paren if < 0, or
12054 ;; jump a bit further if > 0.
12055 (scan-sexps start -1)
12056 pos))))
12057 (unless pos (goto-char (point-min)))))
12058 (t
12059 ;; forward-sexp
12060 (dotimes (_ arg)
12061 (js2-forward-sws)
12062 (when (setq node (js2-node-at-point (point) t))
12063 (setq pos (js2-node-abs-pos node))
12064 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12065 (setq lp (car parens)
12066 rp (cdr parens)))
12067 (or
12068 (when (and rp (<= start rp))
12069 (if (> start lp)
12070 (when (setq child (js2-node-closest-child node (point) rp))
12071 (setq pos (js2-node-abs-end child)))
12072 (setq pos (1+ rp))))
12073 ;; No parens or child nodes, looks for the end of the curren node.
12074 (cl-incf pos (js2-node-len
12075 (if (js2-expr-stmt-node-p (js2-node-parent node))
12076 ;; Stop after the semicolon.
12077 (js2-node-parent node)
12078 node))))
12079 (let ((state (save-excursion (parse-partial-sexp start pos))))
12080 (goto-char (if (not (zerop (car state)))
12081 (scan-sexps start 1)
12082 pos))))
12083 (unless pos (goto-char (point-max)))))))))
12084
12085 (defun js2-mode-forward-sexp-parens (node abs-pos)
12086 "Return a cons cell with positions of main parens in NODE."
12087 (cond
12088 ((or (js2-array-node-p node)
12089 (js2-object-node-p node)
12090 (js2-comp-node-p node)
12091 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12092 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12093 ((js2-paren-expr-node-p node)
12094 (let ((lp (js2-node-lp node))
12095 (rp (js2-node-rp node)))
12096 (cons (when lp (+ abs-pos lp))
12097 (when rp (+ abs-pos rp)))))))
12098
12099 (defun js2-node-closest-child (parent point limit &optional before)
12100 (let* ((parent-pos (js2-node-abs-pos parent))
12101 (rpoint (- point parent-pos))
12102 (rlimit (- limit parent-pos))
12103 (min (min rpoint rlimit))
12104 (max (max rpoint rlimit))
12105 found)
12106 (catch 'done
12107 (js2-visit-ast
12108 parent
12109 (lambda (node _end-p)
12110 (if (eq node parent)
12111 t
12112 (let ((pos (js2-node-pos node)) ;; Both relative values.
12113 (end (+ (js2-node-pos node) (js2-node-len node))))
12114 (when (and (>= pos min) (<= end max)
12115 (if before (< pos rpoint) (> end rpoint)))
12116 (setq found node))
12117 (when (> end rpoint)
12118 (throw 'done nil)))
12119 nil))))
12120 found))
12121
12122 (defun js2-errors ()
12123 "Return a list of errors found."
12124 (and js2-mode-ast
12125 (js2-ast-root-errors js2-mode-ast)))
12126
12127 (defun js2-warnings ()
12128 "Return a list of warnings found."
12129 (and js2-mode-ast
12130 (js2-ast-root-warnings js2-mode-ast)))
12131
12132 (defun js2-have-errors-p ()
12133 "Return non-nil if any parse errors or warnings were found."
12134 (or (js2-errors) (js2-warnings)))
12135
12136 (defun js2-errors-and-warnings ()
12137 "Return a copy of the concatenated errors and warnings lists.
12138 They are appended: first the errors, then the warnings.
12139 Entries are of the form (MSG BEG END)."
12140 (when js2-mode-ast
12141 (append (js2-ast-root-errors js2-mode-ast)
12142 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12143
12144 (defun js2-next-error (&optional arg reset)
12145 "Move to next parse error.
12146 Typically invoked via \\[next-error].
12147 ARG is the number of errors, forward or backward, to move.
12148 RESET means start over from the beginning."
12149 (interactive "p")
12150 (if (not (or (js2-errors) (js2-warnings)))
12151 (message "No errors")
12152 (when reset
12153 (goto-char (point-min)))
12154 (let* ((errs (js2-errors-and-warnings))
12155 (continue t)
12156 (start (point))
12157 (count (or arg 1))
12158 (backward (cl-minusp count))
12159 (sorter (if backward '> '<))
12160 (stopper (if backward '< '>))
12161 (count (abs count))
12162 all-errs err)
12163 ;; Sort by start position.
12164 (setq errs (sort errs (lambda (e1 e2)
12165 (funcall sorter (cl-second e1) (cl-second e2))))
12166 all-errs errs)
12167 ;; Find nth error with pos > start.
12168 (while (and errs continue)
12169 (when (funcall stopper (cl-cadar errs) start)
12170 (setq err (car errs))
12171 (if (zerop (cl-decf count))
12172 (setq continue nil)))
12173 (setq errs (cdr errs)))
12174 ;; Clear for `js2-echo-error'.
12175 (message nil)
12176 (if err
12177 (goto-char (cl-second err))
12178 ;; Wrap around to first error.
12179 (goto-char (cl-second (car all-errs)))
12180 ;; If we were already on it, echo msg again.
12181 (if (= (point) start)
12182 (js2-echo-error (point) (point)))))))
12183
12184 (defun js2-down-mouse-3 ()
12185 "Make right-click move the point to the click location.
12186 This makes right-click context menu operations a bit more intuitive.
12187 The point will not move if the region is active, however, to avoid
12188 destroying the region selection."
12189 (interactive)
12190 (when (and js2-move-point-on-right-click
12191 (not mark-active))
12192 (let ((e last-input-event))
12193 (ignore-errors
12194 (goto-char (cl-cadadr e))))))
12195
12196 (defun js2-mode-create-imenu-index ()
12197 "Return an alist for `imenu--index-alist'."
12198 ;; This is built up in `js2-parse-record-imenu' during parsing.
12199 (when js2-mode-ast
12200 ;; if we have an ast but no recorder, they're requesting a rescan
12201 (unless js2-imenu-recorder
12202 (js2-reparse 'force))
12203 (prog1
12204 (js2-build-imenu-index)
12205 (setq js2-imenu-recorder nil
12206 js2-imenu-function-map nil))))
12207
12208 (defun js2-mode-find-tag ()
12209 "Replacement for `find-tag-default'.
12210 `find-tag-default' returns a ridiculous answer inside comments."
12211 (let (beg end)
12212 (js2-with-underscore-as-word-syntax
12213 (save-excursion
12214 (if (and (not (looking-at "[[:alnum:]_$]"))
12215 (looking-back "[[:alnum:]_$]"))
12216 (setq beg (progn (forward-word -1) (point))
12217 end (progn (forward-word 1) (point)))
12218 (setq beg (progn (forward-word 1) (point))
12219 end (progn (forward-word -1) (point))))
12220 (replace-regexp-in-string
12221 "[\"']" ""
12222 (buffer-substring-no-properties beg end))))))
12223
12224 (defun js2-mode-forward-sibling ()
12225 "Move to the end of the sibling following point in parent.
12226 Returns non-nil if successful, or nil if there was no following sibling."
12227 (let* ((node (js2-node-at-point))
12228 (parent (js2-mode-find-enclosing-fn node))
12229 sib)
12230 (when (setq sib (js2-node-find-child-after (point) parent))
12231 (goto-char (+ (js2-node-abs-pos sib)
12232 (js2-node-len sib))))))
12233
12234 (defun js2-mode-backward-sibling ()
12235 "Move to the beginning of the sibling node preceding point in parent.
12236 Parent is defined as the enclosing script or function."
12237 (let* ((node (js2-node-at-point))
12238 (parent (js2-mode-find-enclosing-fn node))
12239 sib)
12240 (when (setq sib (js2-node-find-child-before (point) parent))
12241 (goto-char (js2-node-abs-pos sib)))))
12242
12243 (defun js2-beginning-of-defun (&optional arg)
12244 "Go to line on which current function starts, and return t on success.
12245 If we're not in a function or already at the beginning of one, go
12246 to beginning of previous script-level element.
12247 With ARG N, do that N times. If N is negative, move forward."
12248 (setq arg (or arg 1))
12249 (if (cl-plusp arg)
12250 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12251 (when (cond
12252 ((js2-function-node-p parent)
12253 (goto-char (js2-node-abs-pos parent)))
12254 (t
12255 (js2-mode-backward-sibling)))
12256 (if (> arg 1)
12257 (js2-beginning-of-defun (1- arg))
12258 t)))
12259 (when (js2-end-of-defun)
12260 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12261
12262 (defun js2-end-of-defun ()
12263 "Go to the char after the last position of the current function
12264 or script-level element."
12265 (let* ((node (js2-node-at-point))
12266 (parent (or (and (js2-function-node-p node) node)
12267 (js2-node-parent-script-or-fn node)))
12268 script)
12269 (unless (js2-function-node-p parent)
12270 ;; Use current script-level node, or, if none, the next one.
12271 (setq script (or parent node)
12272 parent (js2-node-find-child-before (point) script))
12273 (when (or (null parent)
12274 (>= (point) (+ (js2-node-abs-pos parent)
12275 (js2-node-len parent))))
12276 (setq parent (js2-node-find-child-after (point) script))))
12277 (when parent
12278 (goto-char (+ (js2-node-abs-pos parent)
12279 (js2-node-len parent))))))
12280
12281 (defun js2-mark-defun (&optional allow-extend)
12282 "Put mark at end of this function, point at beginning.
12283 The function marked is the one that contains point.
12284
12285 Interactively, if this command is repeated,
12286 or (in Transient Mark mode) if the mark is active,
12287 it marks the next defun after the ones already marked."
12288 (interactive "p")
12289 (let (extended)
12290 (when (and allow-extend
12291 (or (and (eq last-command this-command) (mark t))
12292 (and transient-mark-mode mark-active)))
12293 (let ((sib (save-excursion
12294 (goto-char (mark))
12295 (if (js2-mode-forward-sibling)
12296 (point)))))
12297 (if sib
12298 (progn
12299 (set-mark sib)
12300 (setq extended t))
12301 ;; no more siblings - try extending to enclosing node
12302 (goto-char (mark t)))))
12303 (when (not extended)
12304 (let ((node (js2-node-at-point (point) t)) ; skip comments
12305 ast fn stmt parent beg end)
12306 (when (js2-ast-root-p node)
12307 (setq ast node
12308 node (or (js2-node-find-child-after (point) node)
12309 (js2-node-find-child-before (point) node))))
12310 ;; only mark whole buffer if we can't find any children
12311 (if (null node)
12312 (setq node ast))
12313 (if (js2-function-node-p node)
12314 (setq parent node)
12315 (setq fn (js2-mode-find-enclosing-fn node)
12316 stmt (if (or (null fn)
12317 (js2-ast-root-p fn))
12318 (js2-mode-find-first-stmt node))
12319 parent (or stmt fn)))
12320 (setq beg (js2-node-abs-pos parent)
12321 end (+ beg (js2-node-len parent)))
12322 (push-mark beg)
12323 (goto-char end)
12324 (exchange-point-and-mark)))))
12325
12326 (defun js2-narrow-to-defun ()
12327 "Narrow to the function enclosing point."
12328 (interactive)
12329 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12330 (fn (if (js2-script-node-p node)
12331 node
12332 (js2-mode-find-enclosing-fn node)))
12333 (beg (js2-node-abs-pos fn)))
12334 (unless (js2-ast-root-p fn)
12335 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12336
12337 (provide 'js2-mode)
12338
12339 ;;; js2-mode.el ends here