]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Merge pull request #202 from brianloveswords/add-browser-externs
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2014 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: 20141118
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 (delta (make-symbol "--js2-time-end--")))
2079 `(let ((,beg (current-time))
2080 ,delta)
2081 ,form
2082 (/ (truncate (* (- (float-time (current-time))
2083 (float-time ,beg))
2084 10000))
2085 10000.0))))
2086
2087 (defsubst js2-same-line (pos)
2088 "Return t if POS is on the same line as current point."
2089 (and (>= pos (point-at-bol))
2090 (<= pos (point-at-eol))))
2091
2092 (defun js2-code-bug ()
2093 "Signal an error when we encounter an unexpected code path."
2094 (error "failed assertion"))
2095
2096 (defsubst js2-record-text-property (beg end prop value)
2097 "Record a text property to set when parsing finishes."
2098 (push (list beg end prop value) js2-mode-deferred-properties))
2099
2100 ;; I'd like to associate errors with nodes, but for now the
2101 ;; easiest thing to do is get the context info from the last token.
2102 (defun js2-record-parse-error (msg &optional arg pos len)
2103 (push (list (list msg arg)
2104 (or pos (js2-current-token-beg))
2105 (or len (js2-current-token-len)))
2106 js2-parsed-errors))
2107
2108 (defun js2-report-error (msg &optional msg-arg pos len)
2109 "Signal a syntax error or record a parse error."
2110 (if js2-recover-from-parse-errors
2111 (js2-record-parse-error msg msg-arg pos len)
2112 (signal 'js2-syntax-error
2113 (list msg
2114 js2-ts-lineno
2115 (save-excursion
2116 (goto-char js2-ts-cursor)
2117 (current-column))
2118 js2-ts-hit-eof))))
2119
2120 (defun js2-report-warning (msg &optional msg-arg pos len face)
2121 (if js2-compiler-report-warning-as-error
2122 (js2-report-error msg msg-arg pos len)
2123 (push (list (list msg msg-arg)
2124 (or pos (js2-current-token-beg))
2125 (or len (js2-current-token-len))
2126 face)
2127 js2-parsed-warnings)))
2128
2129 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2130 (if js2-compiler-strict-mode
2131 (js2-report-warning msg-id msg-arg beg
2132 (and beg end (- end beg)))))
2133
2134 (put 'js2-syntax-error 'error-conditions
2135 '(error syntax-error js2-syntax-error))
2136 (put 'js2-syntax-error 'error-message "Syntax error")
2137
2138 (put 'js2-parse-error 'error-conditions
2139 '(error parse-error js2-parse-error))
2140 (put 'js2-parse-error 'error-message "Parse error")
2141
2142 (defmacro js2-clear-flag (flags flag)
2143 `(setq ,flags (logand ,flags (lognot ,flag))))
2144
2145 (defmacro js2-set-flag (flags flag)
2146 "Logical-or FLAG into FLAGS."
2147 `(setq ,flags (logior ,flags ,flag)))
2148
2149 (defsubst js2-flag-set-p (flags flag)
2150 (/= 0 (logand flags flag)))
2151
2152 (defsubst js2-flag-not-set-p (flags flag)
2153 (zerop (logand flags flag)))
2154
2155 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2156 "Evaluate BODY with the _ character set to be word-syntax."
2157 (declare (indent 0) (debug t))
2158 (let ((old-syntax (make-symbol "old-syntax")))
2159 `(let ((,old-syntax (string (char-syntax ?_))))
2160 (unwind-protect
2161 (progn
2162 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2163 ,@body)
2164 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2165
2166 ;;; AST struct and function definitions
2167
2168 ;; flags for ast node property 'member-type (used for e4x operators)
2169 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2170 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2171 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2172
2173 (defsubst js2-relpos (pos anchor)
2174 "Convert POS to be relative to ANCHOR.
2175 If POS is nil, returns nil."
2176 (and pos (- pos anchor)))
2177
2178 (defun js2-make-pad (indent)
2179 (if (zerop indent)
2180 ""
2181 (make-string (* indent js2-basic-offset) ? )))
2182
2183 (defun js2-visit-ast (node callback)
2184 "Visit every node in ast NODE with visitor CALLBACK.
2185
2186 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2187 called twice: once to visit the node, and again after all the node's
2188 children have been processed. The END-P argument is nil on the first
2189 call and non-nil on the second call. The return value of the callback
2190 affects the traversal: if non-nil, the children of NODE are processed.
2191 If the callback returns nil, or if the node has no children, then the
2192 callback is called immediately with a non-nil END-P argument.
2193
2194 The node traversal is approximately lexical-order, although there
2195 are currently no guarantees around this."
2196 (when node
2197 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2198 ;; visit the node
2199 (when (funcall callback node nil)
2200 ;; visit the kids
2201 (cond
2202 ((eq vfunc 'js2-visit-none)
2203 nil) ; don't even bother calling it
2204 ;; Each AST node type has to define a `js2-visitor' function
2205 ;; that takes a node and a callback, and calls `js2-visit-ast'
2206 ;; on each child of the node.
2207 (vfunc
2208 (funcall vfunc node callback))
2209 (t
2210 (error "%s does not define a visitor-traversal function"
2211 (aref node 0)))))
2212 ;; call the end-visit
2213 (funcall callback node t))))
2214
2215 (cl-defstruct (js2-node
2216 (:constructor nil)) ; abstract
2217 "Base AST node type."
2218 (type -1) ; token type
2219 (pos -1) ; start position of this AST node in parsed input
2220 (len 1) ; num characters spanned by the node
2221 props ; optional node property list (an alist)
2222 parent) ; link to parent node; null for root
2223
2224 (defsubst js2-node-get-prop (node prop &optional default)
2225 (or (cadr (assoc prop (js2-node-props node))) default))
2226
2227 (defsubst js2-node-set-prop (node prop value)
2228 (setf (js2-node-props node)
2229 (cons (list prop value) (js2-node-props node))))
2230
2231 (defun js2-fixup-starts (n nodes)
2232 "Adjust the start positions of NODES to be relative to N.
2233 Any node in the list may be nil, for convenience."
2234 (dolist (node nodes)
2235 (when node
2236 (setf (js2-node-pos node) (- (js2-node-pos node)
2237 (js2-node-pos n))))))
2238
2239 (defun js2-node-add-children (parent &rest nodes)
2240 "Set parent node of NODES to PARENT, and return PARENT.
2241 Does nothing if we're not recording parent links.
2242 If any given node in NODES is nil, doesn't record that link."
2243 (js2-fixup-starts parent nodes)
2244 (dolist (node nodes)
2245 (and node
2246 (setf (js2-node-parent node) parent))))
2247
2248 ;; Non-recursive since it's called a frightening number of times.
2249 (defun js2-node-abs-pos (n)
2250 (let ((pos (js2-node-pos n)))
2251 (while (setq n (js2-node-parent n))
2252 (setq pos (+ pos (js2-node-pos n))))
2253 pos))
2254
2255 (defsubst js2-node-abs-end (n)
2256 "Return absolute buffer position of end of N."
2257 (+ (js2-node-abs-pos n) (js2-node-len n)))
2258
2259 ;; It's important to make sure block nodes have a Lisp list for the
2260 ;; child nodes, to limit printing recursion depth in an AST that
2261 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2262 ;; a sufficiently large vector tree.
2263
2264 (cl-defstruct (js2-block-node
2265 (:include js2-node)
2266 (:constructor nil)
2267 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2268 (pos (js2-current-token-beg))
2269 len
2270 props
2271 kids)))
2272 "A block of statements."
2273 kids) ; a Lisp list of the child statement nodes
2274
2275 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2276 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2277
2278 (defun js2-visit-block (ast callback)
2279 "Visit the `js2-block-node' children of AST."
2280 (dolist (kid (js2-block-node-kids ast))
2281 (js2-visit-ast kid callback)))
2282
2283 (defun js2-print-block (n i)
2284 (let ((pad (js2-make-pad i)))
2285 (insert pad "{\n")
2286 (dolist (kid (js2-block-node-kids n))
2287 (js2-print-ast kid (1+ i)))
2288 (insert pad "}")))
2289
2290 (cl-defstruct (js2-scope
2291 (:include js2-block-node)
2292 (:constructor nil)
2293 (:constructor make-js2-scope (&key (type js2-BLOCK)
2294 (pos (js2-current-token-beg))
2295 len
2296 kids)))
2297 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2298 ;; I don't have one of those handy, so I'll use an alist for now.
2299 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2300 ;; and is much lighter-weight to construct (both CPU and mem).
2301 ;; The keys are interned strings (symbols) for faster lookup.
2302 ;; Should switch to hybrid alist/hashtable eventually.
2303 symbol-table ; an alist of (symbol . js2-symbol)
2304 parent-scope ; a `js2-scope'
2305 top) ; top-level `js2-scope' (script/function)
2306
2307 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2308 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2309
2310 (defun js2-node-get-enclosing-scope (node)
2311 "Return the innermost `js2-scope' node surrounding NODE.
2312 Returns nil if there is no enclosing scope node."
2313 (let ((parent (js2-node-parent node)))
2314 (while (not (js2-scope-p parent))
2315 (setq parent (js2-node-parent parent)))
2316 parent))
2317
2318 (defun js2-get-defining-scope (scope name)
2319 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2320 Returns `js2-scope' in which NAME is defined, or nil if not found."
2321 (let ((sym (if (symbolp name)
2322 name
2323 (intern name)))
2324 table
2325 result
2326 (continue t))
2327 (while (and scope continue)
2328 (if (or
2329 (and (setq table (js2-scope-symbol-table scope))
2330 (assq sym table))
2331 (and (eq sym 'arguments)
2332 (js2-function-node-p scope)))
2333 (setq continue nil
2334 result scope)
2335 (setq scope (js2-scope-parent-scope scope))))
2336 result))
2337
2338 (defun js2-scope-get-symbol (scope name)
2339 "Return symbol table entry for NAME in SCOPE.
2340 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2341 (and (js2-scope-symbol-table scope)
2342 (cdr (assq (if (symbolp name)
2343 name
2344 (intern name))
2345 (js2-scope-symbol-table scope)))))
2346
2347 (defun js2-scope-put-symbol (scope name symbol)
2348 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2349 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2350 (let* ((table (js2-scope-symbol-table scope))
2351 (sym (if (symbolp name) name (intern name)))
2352 (entry (assq sym table)))
2353 (if entry
2354 (setcdr entry symbol)
2355 (push (cons sym symbol)
2356 (js2-scope-symbol-table scope)))))
2357
2358 (cl-defstruct (js2-symbol
2359 (:constructor nil)
2360 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2361 "A symbol table entry."
2362 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2363 ;; js2-LET, or js2-CONST
2364 decl-type
2365 name ; string
2366 ast-node) ; a `js2-node'
2367
2368 (cl-defstruct (js2-error-node
2369 (:include js2-node)
2370 (:constructor nil) ; silence emacs21 byte-compiler
2371 (:constructor make-js2-error-node (&key (type js2-ERROR)
2372 (pos (js2-current-token-beg))
2373 len)))
2374 "AST node representing a parse error.")
2375
2376 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2377 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2378
2379 (cl-defstruct (js2-script-node
2380 (:include js2-scope)
2381 (:constructor nil)
2382 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2383 (pos (js2-current-token-beg))
2384 len
2385 ;; FIXME: What are those?
2386 var-decls
2387 fun-decls)))
2388 functions ; Lisp list of nested functions
2389 regexps ; Lisp list of (string . flags)
2390 symbols ; alist (every symbol gets unique index)
2391 (param-count 0)
2392 var-names ; vector of string names
2393 consts ; bool-vector matching var-decls
2394 (temp-number 0)) ; for generating temp variables
2395
2396 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2397 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2398
2399 (defun js2-print-script (node indent)
2400 (dolist (kid (js2-block-node-kids node))
2401 (js2-print-ast kid indent)))
2402
2403 (cl-defstruct (js2-ast-root
2404 (:include js2-script-node)
2405 (:constructor nil)
2406 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2407 (pos (js2-current-token-beg))
2408 len
2409 buffer)))
2410 "The root node of a js2 AST."
2411 buffer ; the source buffer from which the code was parsed
2412 comments ; a Lisp list of comments, ordered by start position
2413 errors ; a Lisp list of errors found during parsing
2414 warnings ; a Lisp list of warnings found during parsing
2415 node-count) ; number of nodes in the tree, including the root
2416
2417 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2418 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2419
2420 (defun js2-visit-ast-root (ast callback)
2421 (dolist (kid (js2-ast-root-kids ast))
2422 (js2-visit-ast kid callback))
2423 (dolist (comment (js2-ast-root-comments ast))
2424 (js2-visit-ast comment callback)))
2425
2426 (cl-defstruct (js2-comment-node
2427 (:include js2-node)
2428 (:constructor nil)
2429 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2430 (pos (js2-current-token-beg))
2431 len
2432 format)))
2433 format) ; 'line, 'block, 'jsdoc or 'html
2434
2435 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2436 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2437
2438 (defun js2-print-comment (n i)
2439 ;; We really ought to link end-of-line comments to their nodes.
2440 ;; Or maybe we could add a new comment type, 'endline.
2441 (insert (js2-make-pad i)
2442 (js2-node-string n)))
2443
2444 (cl-defstruct (js2-expr-stmt-node
2445 (:include js2-node)
2446 (:constructor nil)
2447 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2448 (pos js2-ts-cursor)
2449 len
2450 expr)))
2451 "An expression statement."
2452 expr)
2453
2454 (defsubst js2-expr-stmt-node-set-has-result (node)
2455 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2456 (setf (js2-node-type node) js2-EXPR_RESULT))
2457
2458 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2459 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2460
2461 (defun js2-visit-expr-stmt-node (n v)
2462 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2463
2464 (defun js2-print-expr-stmt-node (n indent)
2465 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2466 (insert ";\n"))
2467
2468 (cl-defstruct (js2-loop-node
2469 (:include js2-scope)
2470 (:constructor nil))
2471 "Abstract supertype of loop nodes."
2472 body ; a `js2-block-node'
2473 lp ; position of left-paren, nil if omitted
2474 rp) ; position of right-paren, nil if omitted
2475
2476 (cl-defstruct (js2-do-node
2477 (:include js2-loop-node)
2478 (:constructor nil)
2479 (:constructor make-js2-do-node (&key (type js2-DO)
2480 (pos (js2-current-token-beg))
2481 len
2482 body
2483 condition
2484 while-pos
2485 lp
2486 rp)))
2487 "AST node for do-loop."
2488 condition ; while (expression)
2489 while-pos) ; buffer position of 'while' keyword
2490
2491 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2492 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2493
2494 (defun js2-visit-do-node (n v)
2495 (js2-visit-ast (js2-do-node-body n) v)
2496 (js2-visit-ast (js2-do-node-condition n) v))
2497
2498 (defun js2-print-do-node (n i)
2499 (let ((pad (js2-make-pad i)))
2500 (insert pad "do {\n")
2501 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2502 (js2-print-ast kid (1+ i)))
2503 (insert pad "} while (")
2504 (js2-print-ast (js2-do-node-condition n) 0)
2505 (insert ");\n")))
2506
2507 (cl-defstruct (js2-export-node
2508 (:include js2-node)
2509 (:constructor nil)
2510 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2511 (pos) (js2-current-token-beg)
2512 len
2513 exports-list
2514 from-clause
2515 declaration
2516 default)))
2517 "AST node for an export statement. There are many things that can be exported,
2518 so many of its properties will be nil.
2519 "
2520 exports-list ; lisp list of js2-export-binding-node to export
2521 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2522 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2523 default) ; js2-function-node or js2-assign-node
2524
2525 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2526 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2527
2528 (defun js2-visit-export-node (n v)
2529 (let ((exports-list (js2-export-node-exports-list n))
2530 (from (js2-export-node-from-clause n))
2531 (declaration (js2-export-node-declaration n))
2532 (default (js2-export-node-default n)))
2533 (when exports-list
2534 (dolist (export exports-list)
2535 (js2-visit-ast export v)))
2536 (when from
2537 (js2-visit-ast from v))
2538 (when declaration
2539 (js2-visit-ast declaration v))
2540 (when default
2541 (js2-visit-ast default v))))
2542
2543 (defun js2-print-export-node (n i)
2544 (let ((pad (js2-make-pad i))
2545 (exports-list (js2-export-node-exports-list n))
2546 (from (js2-export-node-from-clause n))
2547 (declaration (js2-export-node-declaration n))
2548 (default (js2-export-node-default n)))
2549 (insert pad "export ")
2550 (cond
2551 (default
2552 (insert "default ")
2553 (js2-print-ast default i))
2554 (declaration
2555 (js2-print-ast declaration i))
2556 ((and exports-list from)
2557 (js2-print-named-imports exports-list)
2558 (insert " ")
2559 (js2-print-from-clause from))
2560 (from
2561 (insert "* ")
2562 (js2-print-from-clause from))
2563 (exports-list
2564 (js2-print-named-imports exports-list)))
2565 (insert ";\n")))
2566
2567 (cl-defstruct (js2-while-node
2568 (:include js2-loop-node)
2569 (:constructor nil)
2570 (:constructor make-js2-while-node (&key (type js2-WHILE)
2571 (pos (js2-current-token-beg))
2572 len body
2573 condition lp
2574 rp)))
2575 "AST node for while-loop."
2576 condition) ; while-condition
2577
2578 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2579 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2580
2581 (defun js2-visit-while-node (n v)
2582 (js2-visit-ast (js2-while-node-condition n) v)
2583 (js2-visit-ast (js2-while-node-body n) v))
2584
2585 (defun js2-print-while-node (n i)
2586 (let ((pad (js2-make-pad i)))
2587 (insert pad "while (")
2588 (js2-print-ast (js2-while-node-condition n) 0)
2589 (insert ") {\n")
2590 (js2-print-body (js2-while-node-body n) (1+ i))
2591 (insert pad "}\n")))
2592
2593 (cl-defstruct (js2-for-node
2594 (:include js2-loop-node)
2595 (:constructor nil)
2596 (:constructor make-js2-for-node (&key (type js2-FOR)
2597 (pos js2-ts-cursor)
2598 len body init
2599 condition
2600 update lp rp)))
2601 "AST node for a C-style for-loop."
2602 init ; initialization expression
2603 condition ; loop condition
2604 update) ; update clause
2605
2606 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2607 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2608
2609 (defun js2-visit-for-node (n v)
2610 (js2-visit-ast (js2-for-node-init n) v)
2611 (js2-visit-ast (js2-for-node-condition n) v)
2612 (js2-visit-ast (js2-for-node-update n) v)
2613 (js2-visit-ast (js2-for-node-body n) v))
2614
2615 (defun js2-print-for-node (n i)
2616 (let ((pad (js2-make-pad i)))
2617 (insert pad "for (")
2618 (js2-print-ast (js2-for-node-init n) 0)
2619 (insert "; ")
2620 (js2-print-ast (js2-for-node-condition n) 0)
2621 (insert "; ")
2622 (js2-print-ast (js2-for-node-update n) 0)
2623 (insert ") {\n")
2624 (js2-print-body (js2-for-node-body n) (1+ i))
2625 (insert pad "}\n")))
2626
2627 (cl-defstruct (js2-for-in-node
2628 (:include js2-loop-node)
2629 (:constructor nil)
2630 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2631 (pos js2-ts-cursor)
2632 len body
2633 iterator
2634 object
2635 in-pos
2636 each-pos
2637 foreach-p forof-p
2638 lp rp)))
2639 "AST node for a for..in loop."
2640 iterator ; [var] foo in ...
2641 object ; object over which we're iterating
2642 in-pos ; buffer position of 'in' keyword
2643 each-pos ; buffer position of 'each' keyword, if foreach-p
2644 foreach-p ; t if it's a for-each loop
2645 forof-p) ; t if it's a for-of loop
2646
2647 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2648 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2649
2650 (defun js2-visit-for-in-node (n v)
2651 (js2-visit-ast (js2-for-in-node-iterator n) v)
2652 (js2-visit-ast (js2-for-in-node-object n) v)
2653 (js2-visit-ast (js2-for-in-node-body n) v))
2654
2655 (defun js2-print-for-in-node (n i)
2656 (let ((pad (js2-make-pad i))
2657 (foreach (js2-for-in-node-foreach-p n))
2658 (forof (js2-for-in-node-forof-p n)))
2659 (insert pad "for ")
2660 (if foreach
2661 (insert "each "))
2662 (insert "(")
2663 (js2-print-ast (js2-for-in-node-iterator n) 0)
2664 (insert (if forof " of " " in "))
2665 (js2-print-ast (js2-for-in-node-object n) 0)
2666 (insert ") {\n")
2667 (js2-print-body (js2-for-in-node-body n) (1+ i))
2668 (insert pad "}\n")))
2669
2670 (cl-defstruct (js2-return-node
2671 (:include js2-node)
2672 (:constructor nil)
2673 (:constructor make-js2-return-node (&key (type js2-RETURN)
2674 (pos js2-ts-cursor)
2675 len
2676 retval)))
2677 "AST node for a return statement."
2678 retval) ; expression to return, or 'undefined
2679
2680 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2681 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2682
2683 (defun js2-visit-return-node (n v)
2684 (js2-visit-ast (js2-return-node-retval n) v))
2685
2686 (defun js2-print-return-node (n i)
2687 (insert (js2-make-pad i) "return")
2688 (when (js2-return-node-retval n)
2689 (insert " ")
2690 (js2-print-ast (js2-return-node-retval n) 0))
2691 (insert ";\n"))
2692
2693 (cl-defstruct (js2-if-node
2694 (:include js2-node)
2695 (:constructor nil)
2696 (:constructor make-js2-if-node (&key (type js2-IF)
2697 (pos js2-ts-cursor)
2698 len condition
2699 then-part
2700 else-pos
2701 else-part lp
2702 rp)))
2703 "AST node for an if-statement."
2704 condition ; expression
2705 then-part ; statement or block
2706 else-pos ; optional buffer position of 'else' keyword
2707 else-part ; optional statement or block
2708 lp ; position of left-paren, nil if omitted
2709 rp) ; position of right-paren, nil if omitted
2710
2711 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2712 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2713
2714 (defun js2-visit-if-node (n v)
2715 (js2-visit-ast (js2-if-node-condition n) v)
2716 (js2-visit-ast (js2-if-node-then-part n) v)
2717 (js2-visit-ast (js2-if-node-else-part n) v))
2718
2719 (defun js2-print-if-node (n i)
2720 (let ((pad (js2-make-pad i))
2721 (then-part (js2-if-node-then-part n))
2722 (else-part (js2-if-node-else-part n)))
2723 (insert pad "if (")
2724 (js2-print-ast (js2-if-node-condition n) 0)
2725 (insert ") {\n")
2726 (js2-print-body then-part (1+ i))
2727 (insert pad "}")
2728 (cond
2729 ((not else-part)
2730 (insert "\n"))
2731 ((js2-if-node-p else-part)
2732 (insert " else ")
2733 (js2-print-body else-part i))
2734 (t
2735 (insert " else {\n")
2736 (js2-print-body else-part (1+ i))
2737 (insert pad "}\n")))))
2738
2739 (cl-defstruct (js2-export-binding-node
2740 (:include js2-node)
2741 (:constructor nil)
2742 (:constructor make-js2-export-binding-node (&key (type -1)
2743 pos
2744 len
2745 local-name
2746 extern-name)))
2747 "AST node for an external symbol binding.
2748 It contains a local-name node which is the name of the value in the
2749 current scope, and extern-name which is the name of the value in the
2750 imported or exported scope. By default these are the same, but if the
2751 name is aliased as in {foo as bar}, it would have an extern-name node
2752 containing 'foo' and a local-name node containing 'bar'."
2753 local-name ; js2-name-node with the variable name in this scope
2754 extern-name) ; js2-name-node with the value name in the exporting module
2755
2756 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2757 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2758
2759 (defun js2-visit-extern-binding (n v)
2760 "Visit an extern binding node. First visit the local-name, and, if
2761 different, visit the extern-name."
2762 (let ((local-name (js2-export-binding-node-local-name n))
2763 (extern-name (js2-export-binding-node-extern-name n)))
2764 (when local-name
2765 (js2-visit-ast local-name v))
2766 (when (not (equal local-name extern-name))
2767 (js2-visit-ast extern-name v))))
2768
2769 (defun js2-print-extern-binding (n i)
2770 "Print a representation of a single extern binding. E.g. 'foo' or
2771 'foo as bar'."
2772 (let ((local-name (js2-export-binding-node-local-name n))
2773 (extern-name (js2-export-binding-node-extern-name n)))
2774 (insert (js2-name-node-name extern-name))
2775 (when (not (equal local-name extern-name))
2776 (insert " as ")
2777 (insert (js2-name-node-name local-name)))))
2778
2779
2780 (cl-defstruct (js2-import-node
2781 (:include js2-node)
2782 (:constructor nil)
2783 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2784 (pos (js2-current-token-beg))
2785 len
2786 import
2787 from
2788 module-id)))
2789 "AST node for an import statement. It follows the form
2790
2791 import ModuleSpecifier;
2792 import ImportClause FromClause;"
2793 import ; js2-import-clause-node specifying which names are to imported.
2794 from ; js2-from-clause-node indicating the module from which to import.
2795 module-id) ; module-id of the import. E.g. 'src/mylib'.
2796
2797 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2798 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2799
2800 (defun js2-visit-import (n v)
2801 (let ((import-clause (js2-import-node-import n))
2802 (from-clause (js2-import-node-from n)))
2803 (when import-clause
2804 (js2-visit-ast import-clause v))
2805 (when from-clause
2806 (js2-visit-ast from-clause v))))
2807
2808 (defun js2-print-import (n i)
2809 "Prints a representation of the import node"
2810 (let ((pad (js2-make-pad i))
2811 (import-clause (js2-import-node-import n))
2812 (from-clause (js2-import-node-from n))
2813 (module-id (js2-import-node-module-id n)))
2814 (insert pad "import ")
2815 (if import-clause
2816 (progn
2817 (js2-print-import-clause import-clause)
2818 (insert " ")
2819 (js2-print-from-clause from-clause))
2820 (insert "'")
2821 (insert module-id)
2822 (insert "'"))
2823 (insert ";\n")))
2824
2825 (cl-defstruct (js2-import-clause-node
2826 (:include js2-node)
2827 (:constructor nil)
2828 (:constructor make-js2-import-clause-node (&key (type -1)
2829 pos
2830 len
2831 namespace-import
2832 named-imports
2833 default-binding)))
2834 "AST node corresponding to the import clause of an import statement. This is
2835 the portion of the import that bindings names from the external context to the
2836 local context."
2837 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2838 named-imports ; lisp list of js2-export-binding-node for all named imports.
2839 default-binding) ; js2-export-binding-node for the default import binding
2840
2841 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2842 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2843
2844 (defun js2-visit-import-clause (n v)
2845 (let ((ns-import (js2-import-clause-node-namespace-import n))
2846 (named-imports (js2-import-clause-node-named-imports n))
2847 (default (js2-import-clause-node-default-binding n)))
2848 (when ns-import
2849 (js2-visit-ast ns-import v))
2850 (when named-imports
2851 (dolist (import named-imports)
2852 (js2-visit-ast import v)))
2853 (when default
2854 (js2-visit-ast default v))))
2855
2856 (defun js2-print-import-clause (n)
2857 (let ((ns-import (js2-import-clause-node-namespace-import n))
2858 (named-imports (js2-import-clause-node-named-imports n))
2859 (default (js2-import-clause-node-default-binding n)))
2860 (cond
2861 ((and default ns-import)
2862 (js2-print-ast default)
2863 (insert ", ")
2864 (js2-print-namespace-import ns-import))
2865 ((and default named-imports)
2866 (js2-print-ast default)
2867 (insert ", ")
2868 (js2-print-named-imports named-imports))
2869 (default
2870 (js2-print-ast default))
2871 (ns-import
2872 (js2-print-namespace-import ns-import))
2873 (named-imports
2874 (js2-print-named-imports named-imports)))))
2875
2876 (defun js2-print-namespace-import (node)
2877 (insert "* as ")
2878 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2879
2880 (defun js2-print-named-imports (imports)
2881 (insert "{")
2882 (let ((len (length imports))
2883 (n 0))
2884 (while (< n len)
2885 (js2-print-extern-binding (nth n imports) 0)
2886 (unless (= n (- len 1))
2887 (insert ", "))
2888 (setq n (+ n 1))))
2889 (insert "}"))
2890
2891 (cl-defstruct (js2-namespace-import-node
2892 (:include js2-node)
2893 (:constructor nil)
2894 (:constructor make-js2-namespace-import-node (&key (type -1)
2895 pos
2896 len
2897 name)))
2898 "AST node for a complete namespace import.
2899 E.g. the '* as lib' expression in:
2900
2901 import * as lib from 'src/lib'
2902
2903 It contains a single name node referring to the bound name."
2904 name) ; js2-name-node of the bound name.
2905
2906 (defun js2-visit-namespace-import (n v)
2907 (js2-visit-ast (js2-namespace-import-node-name n) v))
2908
2909 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2910 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2911
2912 (cl-defstruct (js2-from-clause-node
2913 (:include js2-node)
2914 (:constructor nil)
2915 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2916 pos
2917 len
2918 module-id
2919 metadata-p)))
2920 "AST node for the from clause in an import or export statement.
2921 E.g. from 'my/module'. It can refere to either an external module, or to the
2922 modules metadata itself."
2923 module-id ; string containing the module specifier.
2924 metadata-p) ; true if this clause refers to the module's metadata
2925
2926 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2927 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2928
2929 (defun js2-print-from-clause (n)
2930 (insert "from ")
2931 (if (js2-from-clause-node-metadata-p n)
2932 (insert "this module")
2933 (insert "'")
2934 (insert (js2-from-clause-node-module-id n))
2935 (insert "'")))
2936
2937 (cl-defstruct (js2-try-node
2938 (:include js2-node)
2939 (:constructor nil)
2940 (:constructor make-js2-try-node (&key (type js2-TRY)
2941 (pos js2-ts-cursor)
2942 len
2943 try-block
2944 catch-clauses
2945 finally-block)))
2946 "AST node for a try-statement."
2947 try-block
2948 catch-clauses ; a Lisp list of `js2-catch-node'
2949 finally-block) ; a `js2-finally-node'
2950
2951 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2952 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2953
2954 (defun js2-visit-try-node (n v)
2955 (js2-visit-ast (js2-try-node-try-block n) v)
2956 (dolist (clause (js2-try-node-catch-clauses n))
2957 (js2-visit-ast clause v))
2958 (js2-visit-ast (js2-try-node-finally-block n) v))
2959
2960 (defun js2-print-try-node (n i)
2961 (let ((pad (js2-make-pad i))
2962 (catches (js2-try-node-catch-clauses n))
2963 (finally (js2-try-node-finally-block n)))
2964 (insert pad "try {\n")
2965 (js2-print-body (js2-try-node-try-block n) (1+ i))
2966 (insert pad "}")
2967 (when catches
2968 (dolist (catch catches)
2969 (js2-print-ast catch i)))
2970 (if finally
2971 (js2-print-ast finally i)
2972 (insert "\n"))))
2973
2974 (cl-defstruct (js2-catch-node
2975 (:include js2-scope)
2976 (:constructor nil)
2977 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2978 (pos js2-ts-cursor)
2979 len
2980 param
2981 guard-kwd
2982 guard-expr
2983 lp rp)))
2984 "AST node for a catch clause."
2985 param ; destructuring form or simple name node
2986 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2987 guard-expr ; catch condition, a `js2-node'
2988 lp ; buffer position of left-paren, nil if omitted
2989 rp) ; buffer position of right-paren, nil if omitted
2990
2991 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2992 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2993
2994 (defun js2-visit-catch-node (n v)
2995 (js2-visit-ast (js2-catch-node-param n) v)
2996 (when (js2-catch-node-guard-kwd n)
2997 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2998 (js2-visit-block n v))
2999
3000 (defun js2-print-catch-node (n i)
3001 (let ((pad (js2-make-pad i))
3002 (guard-kwd (js2-catch-node-guard-kwd n))
3003 (guard-expr (js2-catch-node-guard-expr n)))
3004 (insert " catch (")
3005 (js2-print-ast (js2-catch-node-param n) 0)
3006 (when guard-kwd
3007 (insert " if ")
3008 (js2-print-ast guard-expr 0))
3009 (insert ") {\n")
3010 (js2-print-body n (1+ i))
3011 (insert pad "}")))
3012
3013 (cl-defstruct (js2-finally-node
3014 (:include js2-node)
3015 (:constructor nil)
3016 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3017 (pos js2-ts-cursor)
3018 len body)))
3019 "AST node for a finally clause."
3020 body) ; a `js2-node', often but not always a block node
3021
3022 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3023 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3024
3025 (defun js2-visit-finally-node (n v)
3026 (js2-visit-ast (js2-finally-node-body n) v))
3027
3028 (defun js2-print-finally-node (n i)
3029 (let ((pad (js2-make-pad i)))
3030 (insert " finally {\n")
3031 (js2-print-body (js2-finally-node-body n) (1+ i))
3032 (insert pad "}\n")))
3033
3034 (cl-defstruct (js2-switch-node
3035 (:include js2-node)
3036 (:constructor nil)
3037 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3038 (pos js2-ts-cursor)
3039 len
3040 discriminant
3041 cases lp
3042 rp)))
3043 "AST node for a switch statement."
3044 discriminant ; a `js2-node' (switch expression)
3045 cases ; a Lisp list of `js2-case-node'
3046 lp ; position of open-paren for discriminant, nil if omitted
3047 rp) ; position of close-paren for discriminant, nil if omitted
3048
3049 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3050 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3051
3052 (defun js2-visit-switch-node (n v)
3053 (js2-visit-ast (js2-switch-node-discriminant n) v)
3054 (dolist (c (js2-switch-node-cases n))
3055 (js2-visit-ast c v)))
3056
3057 (defun js2-print-switch-node (n i)
3058 (let ((pad (js2-make-pad i))
3059 (cases (js2-switch-node-cases n)))
3060 (insert pad "switch (")
3061 (js2-print-ast (js2-switch-node-discriminant n) 0)
3062 (insert ") {\n")
3063 (dolist (case cases)
3064 (js2-print-ast case i))
3065 (insert pad "}\n")))
3066
3067 (cl-defstruct (js2-case-node
3068 (:include js2-block-node)
3069 (:constructor nil)
3070 (:constructor make-js2-case-node (&key (type js2-CASE)
3071 (pos js2-ts-cursor)
3072 len kids expr)))
3073 "AST node for a case clause of a switch statement."
3074 expr) ; the case expression (nil for default)
3075
3076 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3077 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3078
3079 (defun js2-visit-case-node (n v)
3080 (js2-visit-ast (js2-case-node-expr n) v)
3081 (js2-visit-block n v))
3082
3083 (defun js2-print-case-node (n i)
3084 (let ((pad (js2-make-pad i))
3085 (expr (js2-case-node-expr n)))
3086 (insert pad)
3087 (if (null expr)
3088 (insert "default:\n")
3089 (insert "case ")
3090 (js2-print-ast expr 0)
3091 (insert ":\n"))
3092 (dolist (kid (js2-case-node-kids n))
3093 (js2-print-ast kid (1+ i)))))
3094
3095 (cl-defstruct (js2-throw-node
3096 (:include js2-node)
3097 (:constructor nil)
3098 (:constructor make-js2-throw-node (&key (type js2-THROW)
3099 (pos js2-ts-cursor)
3100 len expr)))
3101 "AST node for a throw statement."
3102 expr) ; the expression to throw
3103
3104 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3105 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3106
3107 (defun js2-visit-throw-node (n v)
3108 (js2-visit-ast (js2-throw-node-expr n) v))
3109
3110 (defun js2-print-throw-node (n i)
3111 (insert (js2-make-pad i) "throw ")
3112 (js2-print-ast (js2-throw-node-expr n) 0)
3113 (insert ";\n"))
3114
3115 (cl-defstruct (js2-with-node
3116 (:include js2-node)
3117 (:constructor nil)
3118 (:constructor make-js2-with-node (&key (type js2-WITH)
3119 (pos js2-ts-cursor)
3120 len object
3121 body lp rp)))
3122 "AST node for a with-statement."
3123 object
3124 body
3125 lp ; buffer position of left-paren around object, nil if omitted
3126 rp) ; buffer position of right-paren around object, nil if omitted
3127
3128 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3129 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3130
3131 (defun js2-visit-with-node (n v)
3132 (js2-visit-ast (js2-with-node-object n) v)
3133 (js2-visit-ast (js2-with-node-body n) v))
3134
3135 (defun js2-print-with-node (n i)
3136 (let ((pad (js2-make-pad i)))
3137 (insert pad "with (")
3138 (js2-print-ast (js2-with-node-object n) 0)
3139 (insert ") {\n")
3140 (js2-print-body (js2-with-node-body n) (1+ i))
3141 (insert pad "}\n")))
3142
3143 (cl-defstruct (js2-label-node
3144 (:include js2-node)
3145 (:constructor nil)
3146 (:constructor make-js2-label-node (&key (type js2-LABEL)
3147 (pos js2-ts-cursor)
3148 len name)))
3149 "AST node for a statement label or case label."
3150 name ; a string
3151 loop) ; for validating and code-generating continue-to-label
3152
3153 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3154 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3155
3156 (defun js2-print-label (n i)
3157 (insert (js2-make-pad i)
3158 (js2-label-node-name n)
3159 ":\n"))
3160
3161 (cl-defstruct (js2-labeled-stmt-node
3162 (:include js2-node)
3163 (:constructor nil)
3164 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3165 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3166 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3167 (pos js2-ts-cursor)
3168 len labels stmt)))
3169 "AST node for a statement with one or more labels.
3170 Multiple labels for a statement are collapsed into the labels field."
3171 labels ; Lisp list of `js2-label-node'
3172 stmt) ; the statement these labels are for
3173
3174 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3175 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3176
3177 (defun js2-get-label-by-name (lbl-stmt name)
3178 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3179 Returns nil if no such label is in the list."
3180 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3181 result)
3182 (while (and label-list (not result))
3183 (if (string= (js2-label-node-name (car label-list)) name)
3184 (setq result (car label-list))
3185 (setq label-list (cdr label-list))))
3186 result))
3187
3188 (defun js2-visit-labeled-stmt (n v)
3189 (dolist (label (js2-labeled-stmt-node-labels n))
3190 (js2-visit-ast label v))
3191 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3192
3193 (defun js2-print-labeled-stmt (n i)
3194 (dolist (label (js2-labeled-stmt-node-labels n))
3195 (js2-print-ast label i))
3196 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3197
3198 (defun js2-labeled-stmt-node-contains (node label)
3199 "Return t if NODE contains LABEL in its label set.
3200 NODE is a `js2-labels-node'. LABEL is an identifier."
3201 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3202 if (string= label (js2-label-node-name nl))
3203 return t
3204 finally return nil))
3205
3206 (defsubst js2-labeled-stmt-node-add-label (node label)
3207 "Add a `js2-label-node' to the label set for this statement."
3208 (setf (js2-labeled-stmt-node-labels node)
3209 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3210
3211 (cl-defstruct (js2-jump-node
3212 (:include js2-node)
3213 (:constructor nil))
3214 "Abstract supertype of break and continue nodes."
3215 label ; `js2-name-node' for location of label identifier, if present
3216 target) ; target js2-labels-node or loop/switch statement
3217
3218 (defun js2-visit-jump-node (n v)
3219 ;; We don't visit the target, since it's a back-link.
3220 (js2-visit-ast (js2-jump-node-label n) v))
3221
3222 (cl-defstruct (js2-break-node
3223 (:include js2-jump-node)
3224 (:constructor nil)
3225 (:constructor make-js2-break-node (&key (type js2-BREAK)
3226 (pos js2-ts-cursor)
3227 len label target)))
3228 "AST node for a break statement.
3229 The label field is a `js2-name-node', possibly nil, for the named label
3230 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3231 is the target of the break - a label node or enclosing loop/switch statement.")
3232
3233 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3234 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3235
3236 (defun js2-print-break-node (n i)
3237 (insert (js2-make-pad i) "break")
3238 (when (js2-break-node-label n)
3239 (insert " ")
3240 (js2-print-ast (js2-break-node-label n) 0))
3241 (insert ";\n"))
3242
3243 (cl-defstruct (js2-continue-node
3244 (:include js2-jump-node)
3245 (:constructor nil)
3246 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3247 (pos js2-ts-cursor)
3248 len label target)))
3249 "AST node for a continue statement.
3250 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3251 It is nil if continue specifies no label. The target field is the jump target:
3252 a `js2-label-node' or the innermost enclosing loop.")
3253
3254 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3255 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3256
3257 (defun js2-print-continue-node (n i)
3258 (insert (js2-make-pad i) "continue")
3259 (when (js2-continue-node-label n)
3260 (insert " ")
3261 (js2-print-ast (js2-continue-node-label n) 0))
3262 (insert ";\n"))
3263
3264 (cl-defstruct (js2-function-node
3265 (:include js2-script-node)
3266 (:constructor nil)
3267 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3268 (pos js2-ts-cursor)
3269 len
3270 (ftype 'FUNCTION)
3271 (form 'FUNCTION_STATEMENT)
3272 (name "")
3273 params rest-p
3274 body
3275 generator-type
3276 lp rp)))
3277 "AST node for a function declaration.
3278 The `params' field is a Lisp list of nodes. Each node is either a simple
3279 `js2-name-node', or if it's a destructuring-assignment parameter, a
3280 `js2-array-node' or `js2-object-node'."
3281 ftype ; FUNCTION, GETTER or SETTER
3282 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3283 name ; function name (a `js2-name-node', or nil if anonymous)
3284 params ; a Lisp list of destructuring forms or simple name nodes
3285 rest-p ; if t, the last parameter is rest parameter
3286 body ; a `js2-block-node' or expression node (1.8 only)
3287 lp ; position of arg-list open-paren, or nil if omitted
3288 rp ; position of arg-list close-paren, or nil if omitted
3289 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3290 needs-activation ; t if we need an activation object for this frame
3291 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3292 member-expr) ; nonstandard Ecma extension from Rhino
3293
3294 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3295 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3296
3297 (defun js2-visit-function-node (n v)
3298 (js2-visit-ast (js2-function-node-name n) v)
3299 (dolist (p (js2-function-node-params n))
3300 (js2-visit-ast p v))
3301 (js2-visit-ast (js2-function-node-body n) v))
3302
3303 (defun js2-print-function-node (n i)
3304 (let* ((pad (js2-make-pad i))
3305 (getter (js2-node-get-prop n 'GETTER_SETTER))
3306 (name (or (js2-function-node-name n)
3307 (js2-function-node-member-expr n)))
3308 (params (js2-function-node-params n))
3309 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3310 (rest-p (js2-function-node-rest-p n))
3311 (body (js2-function-node-body n))
3312 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3313 (unless (or getter arrow)
3314 (insert pad "function")
3315 (when (eq (js2-function-node-generator-type n) 'STAR)
3316 (insert "*")))
3317 (when name
3318 (insert " ")
3319 (js2-print-ast name 0))
3320 (insert "(")
3321 (cl-loop with len = (length params)
3322 for param in params
3323 for count from 1
3324 do
3325 (when (and rest-p (= count len))
3326 (insert "..."))
3327 (js2-print-ast param 0)
3328 (when (< count len)
3329 (insert ", ")))
3330 (insert ") ")
3331 (when arrow
3332 (insert "=> "))
3333 (insert "{")
3334 ;; TODO: fix this to be smarter about indenting, etc.
3335 (unless expr
3336 (insert "\n"))
3337 (if (js2-block-node-p body)
3338 (js2-print-body body (1+ i))
3339 (js2-print-ast body 0))
3340 (insert pad "}")
3341 (unless expr
3342 (insert "\n"))))
3343
3344 (defun js2-function-name (node)
3345 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3346 (and (js2-function-node-name node)
3347 (js2-name-node-name (js2-function-node-name node))))
3348
3349 ;; Having this be an expression node makes it more flexible.
3350 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3351 ;; that work better if you assume it's an expression. Whenever we have
3352 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3353 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3354 (cl-defstruct (js2-var-decl-node
3355 (:include js2-node)
3356 (:constructor nil)
3357 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3358 (pos (js2-current-token-beg))
3359 len kids
3360 decl-type)))
3361 "AST node for a variable declaration list (VAR, CONST or LET).
3362 The node bounds differ depending on the declaration type. For VAR or
3363 CONST declarations, the bounds include the var/const keyword. For LET
3364 declarations, the node begins at the position of the first child."
3365 kids ; a Lisp list of `js2-var-init-node' structs.
3366 decl-type) ; js2-VAR, js2-CONST or js2-LET
3367
3368 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3369 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3370
3371 (defun js2-visit-var-decl (n v)
3372 (dolist (kid (js2-var-decl-node-kids n))
3373 (js2-visit-ast kid v)))
3374
3375 (defun js2-print-var-decl (n i)
3376 (let ((pad (js2-make-pad i))
3377 (tt (js2-var-decl-node-decl-type n)))
3378 (insert pad)
3379 (insert (cond
3380 ((= tt js2-VAR) "var ")
3381 ((= tt js2-LET) "let ")
3382 ((= tt js2-CONST) "const ")
3383 (t
3384 (error "malformed var-decl node"))))
3385 (cl-loop with kids = (js2-var-decl-node-kids n)
3386 with len = (length kids)
3387 for kid in kids
3388 for count from 1
3389 do
3390 (js2-print-ast kid 0)
3391 (if (< count len)
3392 (insert ", ")))))
3393
3394 (cl-defstruct (js2-var-init-node
3395 (:include js2-node)
3396 (:constructor nil)
3397 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3398 (pos js2-ts-cursor)
3399 len target
3400 initializer)))
3401 "AST node for a variable declaration.
3402 The type field will be js2-CONST for a const decl."
3403 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3404 initializer) ; initializer expression, a `js2-node'
3405
3406 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3407 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3408
3409 (defun js2-visit-var-init-node (n v)
3410 (js2-visit-ast (js2-var-init-node-target n) v)
3411 (js2-visit-ast (js2-var-init-node-initializer n) v))
3412
3413 (defun js2-print-var-init-node (n i)
3414 (let ((pad (js2-make-pad i))
3415 (name (js2-var-init-node-target n))
3416 (init (js2-var-init-node-initializer n)))
3417 (insert pad)
3418 (js2-print-ast name 0)
3419 (when init
3420 (insert " = ")
3421 (js2-print-ast init 0))))
3422
3423 (cl-defstruct (js2-cond-node
3424 (:include js2-node)
3425 (:constructor nil)
3426 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3427 (pos js2-ts-cursor)
3428 len
3429 test-expr
3430 true-expr
3431 false-expr
3432 q-pos c-pos)))
3433 "AST node for the ternary operator"
3434 test-expr
3435 true-expr
3436 false-expr
3437 q-pos ; buffer position of ?
3438 c-pos) ; buffer position of :
3439
3440 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3441 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3442
3443 (defun js2-visit-cond-node (n v)
3444 (js2-visit-ast (js2-cond-node-test-expr n) v)
3445 (js2-visit-ast (js2-cond-node-true-expr n) v)
3446 (js2-visit-ast (js2-cond-node-false-expr n) v))
3447
3448 (defun js2-print-cond-node (n i)
3449 (let ((pad (js2-make-pad i)))
3450 (insert pad)
3451 (js2-print-ast (js2-cond-node-test-expr n) 0)
3452 (insert " ? ")
3453 (js2-print-ast (js2-cond-node-true-expr n) 0)
3454 (insert " : ")
3455 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3456
3457 (cl-defstruct (js2-infix-node
3458 (:include js2-node)
3459 (:constructor nil)
3460 (:constructor make-js2-infix-node (&key type
3461 (pos js2-ts-cursor)
3462 len op-pos
3463 left right)))
3464 "Represents infix expressions.
3465 Includes assignment ops like `|=', and the comma operator.
3466 The type field inherited from `js2-node' holds the operator."
3467 op-pos ; buffer position where operator begins
3468 left ; any `js2-node'
3469 right) ; any `js2-node'
3470
3471 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3472 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3473
3474 (defun js2-visit-infix-node (n v)
3475 (js2-visit-ast (js2-infix-node-left n) v)
3476 (js2-visit-ast (js2-infix-node-right n) v))
3477
3478 (defconst js2-operator-tokens
3479 (let ((table (make-hash-table :test 'eq))
3480 (tokens
3481 (list (cons js2-IN "in")
3482 (cons js2-TYPEOF "typeof")
3483 (cons js2-INSTANCEOF "instanceof")
3484 (cons js2-DELPROP "delete")
3485 (cons js2-COMMA ",")
3486 (cons js2-COLON ":")
3487 (cons js2-OR "||")
3488 (cons js2-AND "&&")
3489 (cons js2-INC "++")
3490 (cons js2-DEC "--")
3491 (cons js2-BITOR "|")
3492 (cons js2-BITXOR "^")
3493 (cons js2-BITAND "&")
3494 (cons js2-EQ "==")
3495 (cons js2-NE "!=")
3496 (cons js2-LT "<")
3497 (cons js2-LE "<=")
3498 (cons js2-GT ">")
3499 (cons js2-GE ">=")
3500 (cons js2-LSH "<<")
3501 (cons js2-RSH ">>")
3502 (cons js2-URSH ">>>")
3503 (cons js2-ADD "+") ; infix plus
3504 (cons js2-SUB "-") ; infix minus
3505 (cons js2-MUL "*")
3506 (cons js2-DIV "/")
3507 (cons js2-MOD "%")
3508 (cons js2-NOT "!")
3509 (cons js2-BITNOT "~")
3510 (cons js2-POS "+") ; unary plus
3511 (cons js2-NEG "-") ; unary minus
3512 (cons js2-TRIPLEDOT "...")
3513 (cons js2-SHEQ "===") ; shallow equality
3514 (cons js2-SHNE "!==") ; shallow inequality
3515 (cons js2-ASSIGN "=")
3516 (cons js2-ASSIGN_BITOR "|=")
3517 (cons js2-ASSIGN_BITXOR "^=")
3518 (cons js2-ASSIGN_BITAND "&=")
3519 (cons js2-ASSIGN_LSH "<<=")
3520 (cons js2-ASSIGN_RSH ">>=")
3521 (cons js2-ASSIGN_URSH ">>>=")
3522 (cons js2-ASSIGN_ADD "+=")
3523 (cons js2-ASSIGN_SUB "-=")
3524 (cons js2-ASSIGN_MUL "*=")
3525 (cons js2-ASSIGN_DIV "/=")
3526 (cons js2-ASSIGN_MOD "%="))))
3527 (cl-loop for (k . v) in tokens do
3528 (puthash k v table))
3529 table))
3530
3531 (defun js2-print-infix-node (n i)
3532 (let* ((tt (js2-node-type n))
3533 (op (gethash tt js2-operator-tokens)))
3534 (unless op
3535 (error "unrecognized infix operator %s" (js2-node-type n)))
3536 (insert (js2-make-pad i))
3537 (js2-print-ast (js2-infix-node-left n) 0)
3538 (unless (= tt js2-COMMA)
3539 (insert " "))
3540 (insert op)
3541 (insert " ")
3542 (js2-print-ast (js2-infix-node-right n) 0)))
3543
3544 (cl-defstruct (js2-assign-node
3545 (:include js2-infix-node)
3546 (:constructor nil)
3547 (:constructor make-js2-assign-node (&key type
3548 (pos js2-ts-cursor)
3549 len op-pos
3550 left right)))
3551 "Represents any assignment.
3552 The type field holds the actual assignment operator.")
3553
3554 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3555 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3556
3557 (cl-defstruct (js2-unary-node
3558 (:include js2-node)
3559 (:constructor nil)
3560 (:constructor make-js2-unary-node (&key type ; required
3561 (pos js2-ts-cursor)
3562 len operand)))
3563 "AST node type for unary operator nodes.
3564 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3565 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3566 property is added if the operator follows the operand."
3567 operand) ; a `js2-node' expression
3568
3569 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3570 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3571
3572 (defun js2-visit-unary-node (n v)
3573 (js2-visit-ast (js2-unary-node-operand n) v))
3574
3575 (defun js2-print-unary-node (n i)
3576 (let* ((tt (js2-node-type n))
3577 (op (gethash tt js2-operator-tokens))
3578 (postfix (js2-node-get-prop n 'postfix)))
3579 (unless op
3580 (error "unrecognized unary operator %s" tt))
3581 (insert (js2-make-pad i))
3582 (unless postfix
3583 (insert op))
3584 (if (or (= tt js2-TYPEOF)
3585 (= tt js2-DELPROP))
3586 (insert " "))
3587 (js2-print-ast (js2-unary-node-operand n) 0)
3588 (when postfix
3589 (insert op))))
3590
3591 (cl-defstruct (js2-let-node
3592 (:include js2-scope)
3593 (:constructor nil)
3594 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3595 (pos (js2-current-token-beg))
3596 len vars body
3597 lp rp)))
3598 "AST node for a let expression or a let statement.
3599 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3600 vars ; a `js2-var-decl-node'
3601 body ; a `js2-node' representing the expression or body block
3602 lp
3603 rp)
3604
3605 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3606 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3607
3608 (defun js2-visit-let-node (n v)
3609 (js2-visit-ast (js2-let-node-vars n) v)
3610 (js2-visit-ast (js2-let-node-body n) v))
3611
3612 (defun js2-print-let-node (n i)
3613 (insert (js2-make-pad i) "let (")
3614 (let ((p (point)))
3615 (js2-print-ast (js2-let-node-vars n) 0)
3616 (delete-region p (+ p 4)))
3617 (insert ") ")
3618 (js2-print-ast (js2-let-node-body n) i))
3619
3620 (cl-defstruct (js2-keyword-node
3621 (:include js2-node)
3622 (:constructor nil)
3623 (:constructor make-js2-keyword-node (&key type
3624 (pos (js2-current-token-beg))
3625 (len (- js2-ts-cursor pos)))))
3626 "AST node representing a literal keyword such as `null'.
3627 Used for `null', `this', `true', `false' and `debugger'.
3628 The node type is set to js2-NULL, js2-THIS, etc.")
3629
3630 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3631 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3632
3633 (defun js2-print-keyword-node (n i)
3634 (insert (js2-make-pad i)
3635 (let ((tt (js2-node-type n)))
3636 (cond
3637 ((= tt js2-THIS) "this")
3638 ((= tt js2-SUPER) "super")
3639 ((= tt js2-NULL) "null")
3640 ((= tt js2-TRUE) "true")
3641 ((= tt js2-FALSE) "false")
3642 ((= tt js2-DEBUGGER) "debugger")
3643 (t (error "Invalid keyword literal type: %d" tt))))))
3644
3645 (defsubst js2-this-or-super-node-p (node)
3646 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3647 (let ((type (js2-node-type node)))
3648 (or (eq type js2-THIS) (eq type js2-SUPER))))
3649
3650 (cl-defstruct (js2-new-node
3651 (:include js2-node)
3652 (:constructor nil)
3653 (:constructor make-js2-new-node (&key (type js2-NEW)
3654 (pos (js2-current-token-beg))
3655 len target
3656 args initializer
3657 lp rp)))
3658 "AST node for new-expression such as new Foo()."
3659 target ; an identifier or reference
3660 args ; a Lisp list of argument nodes
3661 lp ; position of left-paren, nil if omitted
3662 rp ; position of right-paren, nil if omitted
3663 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3664
3665 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3666 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3667
3668 (defun js2-visit-new-node (n v)
3669 (js2-visit-ast (js2-new-node-target n) v)
3670 (dolist (arg (js2-new-node-args n))
3671 (js2-visit-ast arg v))
3672 (js2-visit-ast (js2-new-node-initializer n) v))
3673
3674 (defun js2-print-new-node (n i)
3675 (insert (js2-make-pad i) "new ")
3676 (js2-print-ast (js2-new-node-target n))
3677 (insert "(")
3678 (js2-print-list (js2-new-node-args n))
3679 (insert ")")
3680 (when (js2-new-node-initializer n)
3681 (insert " ")
3682 (js2-print-ast (js2-new-node-initializer n))))
3683
3684 (cl-defstruct (js2-name-node
3685 (:include js2-node)
3686 (:constructor nil)
3687 (:constructor make-js2-name-node (&key (type js2-NAME)
3688 (pos (js2-current-token-beg))
3689 (len (- js2-ts-cursor
3690 (js2-current-token-beg)))
3691 (name (js2-current-token-string)))))
3692 "AST node for a JavaScript identifier"
3693 name ; a string
3694 scope) ; a `js2-scope' (optional, used for codegen)
3695
3696 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3697 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3698
3699 (defun js2-print-name-node (n i)
3700 (insert (js2-make-pad i)
3701 (js2-name-node-name n)))
3702
3703 (defsubst js2-name-node-length (node)
3704 "Return identifier length of NODE, a `js2-name-node'.
3705 Returns 0 if NODE is nil or its identifier field is nil."
3706 (if node
3707 (length (js2-name-node-name node))
3708 0))
3709
3710 (cl-defstruct (js2-number-node
3711 (:include js2-node)
3712 (:constructor nil)
3713 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3714 (pos (js2-current-token-beg))
3715 (len (- js2-ts-cursor
3716 (js2-current-token-beg)))
3717 (value (js2-current-token-string))
3718 (num-value (js2-token-number
3719 (js2-current-token))))))
3720 "AST node for a number literal."
3721 value ; the original string, e.g. "6.02e23"
3722 num-value) ; the parsed number value
3723
3724 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3725 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3726
3727 (defun js2-print-number-node (n i)
3728 (insert (js2-make-pad i)
3729 (number-to-string (js2-number-node-num-value n))))
3730
3731 (cl-defstruct (js2-regexp-node
3732 (:include js2-node)
3733 (:constructor nil)
3734 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3735 (pos (js2-current-token-beg))
3736 (len (- js2-ts-cursor
3737 (js2-current-token-beg)))
3738 value flags)))
3739 "AST node for a regular expression literal."
3740 value ; the regexp string, without // delimiters
3741 flags) ; a string of flags, e.g. `mi'.
3742
3743 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3744 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3745
3746 (defun js2-print-regexp (n i)
3747 (insert (js2-make-pad i)
3748 "/"
3749 (js2-regexp-node-value n)
3750 "/")
3751 (if (js2-regexp-node-flags n)
3752 (insert (js2-regexp-node-flags n))))
3753
3754 (cl-defstruct (js2-string-node
3755 (:include js2-node)
3756 (:constructor nil)
3757 (:constructor make-js2-string-node (&key (type js2-STRING)
3758 (pos (js2-current-token-beg))
3759 (len (- js2-ts-cursor
3760 (js2-current-token-beg)))
3761 (value (js2-current-token-string)))))
3762 "String literal.
3763 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3764 You can tell the quote type by looking at the first character."
3765 value) ; the characters of the string, including the quotes
3766
3767 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3768 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3769
3770 (defun js2-print-string-node (n i)
3771 (insert (js2-make-pad i)
3772 (js2-node-string n)))
3773
3774 (cl-defstruct (js2-template-node
3775 (:include js2-node)
3776 (:constructor nil)
3777 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3778 beg len kids)))
3779 "Template literal."
3780 kids) ; `js2-string-node' is used for string segments, other nodes
3781 ; for substitutions inside.
3782
3783 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3784 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3785
3786 (defun js2-visit-template (n callback)
3787 (dolist (kid (js2-template-node-kids n))
3788 (js2-visit-ast kid callback)))
3789
3790 (defun js2-print-template (n i)
3791 (insert (js2-make-pad i))
3792 (dolist (kid (js2-template-node-kids n))
3793 (if (js2-string-node-p kid)
3794 (insert (js2-node-string kid))
3795 (js2-print-ast kid))))
3796
3797 (cl-defstruct (js2-tagged-template-node
3798 (:include js2-node)
3799 (:constructor nil)
3800 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3801 beg len tag template)))
3802 "Tagged template literal."
3803 tag ; `js2-node' with the tag expression.
3804 template) ; `js2-template-node' with the template.
3805
3806 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3807 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3808
3809 (defun js2-visit-tagged-template (n callback)
3810 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3811 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3812
3813 (defun js2-print-tagged-template (n i)
3814 (insert (js2-make-pad i))
3815 (js2-print-ast (js2-tagged-template-node-tag n))
3816 (js2-print-ast (js2-tagged-template-node-template n)))
3817
3818 (cl-defstruct (js2-array-node
3819 (:include js2-node)
3820 (:constructor nil)
3821 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3822 (pos js2-ts-cursor)
3823 len elems)))
3824 "AST node for an array literal."
3825 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3826
3827 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3828 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3829
3830 (defun js2-visit-array-node (n v)
3831 (dolist (e (js2-array-node-elems n))
3832 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3833
3834 (defun js2-print-array-node (n i)
3835 (insert (js2-make-pad i) "[")
3836 (let ((elems (js2-array-node-elems n)))
3837 (js2-print-list elems)
3838 (when (and elems (null (car (last elems))))
3839 (insert ",")))
3840 (insert "]"))
3841
3842 (cl-defstruct (js2-class-node
3843 (:include js2-node)
3844 (:constructor nil)
3845 (:constructor make-js2-class-node (&key (type js2-CLASS)
3846 (pos js2-ts-cursor)
3847 (form 'CLASS_STATEMENT)
3848 (name "")
3849 extends len elems)))
3850 "AST node for an class expression.
3851 `elems' is a list of `js2-object-prop-node', and `extends' is an
3852 optional `js2-expr-node'"
3853 form ; CLASS_{STATEMENT|EXPRESSION}
3854 name ; class name (a `js2-node-name', or nil if anonymous)
3855 extends ; class heritage (a `js2-expr-node', or nil if none)
3856 elems)
3857
3858 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3859 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3860
3861 (defun js2-visit-class-node (n v)
3862 (js2-visit-ast (js2-class-node-name n) v)
3863 (js2-visit-ast (js2-class-node-extends n) v)
3864 (dolist (e (js2-class-node-elems n))
3865 (js2-visit-ast e v)))
3866
3867 (defun js2-print-class-node (n i)
3868 (let* ((pad (js2-make-pad i))
3869 (name (js2-class-node-name n))
3870 (extends (js2-class-node-extends n))
3871 (elems (js2-class-node-elems n)))
3872 (insert pad "class")
3873 (when name
3874 (insert " ")
3875 (js2-print-ast name 0))
3876 (when extends
3877 (insert " extends ")
3878 (js2-print-ast extends))
3879 (insert " {")
3880 (dolist (elem elems)
3881 (insert "\n")
3882 (if (js2-node-get-prop elem 'STATIC)
3883 (progn (insert (js2-make-pad (1+ i)) "static ")
3884 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3885 (js2-print-ast elem (1+ i))))
3886 (insert "\n" pad "}")))
3887
3888 (cl-defstruct (js2-object-node
3889 (:include js2-node)
3890 (:constructor nil)
3891 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3892 (pos js2-ts-cursor)
3893 len
3894 elems)))
3895 "AST node for an object literal expression.
3896 `elems' is a list of `js2-object-prop-node'."
3897 elems)
3898
3899 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3900 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3901
3902 (defun js2-visit-object-node (n v)
3903 (dolist (e (js2-object-node-elems n))
3904 (js2-visit-ast e v)))
3905
3906 (defun js2-print-object-node (n i)
3907 (insert (js2-make-pad i) "{")
3908 (js2-print-list (js2-object-node-elems n))
3909 (insert "}"))
3910
3911 (cl-defstruct (js2-object-prop-node
3912 (:include js2-infix-node)
3913 (:constructor nil)
3914 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3915 (pos js2-ts-cursor)
3916 len left
3917 right op-pos)))
3918 "AST node for an object literal prop:value entry.
3919 The `left' field is the property: a name node, string node or number node.
3920 The `right' field is a `js2-node' representing the initializer value.
3921 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3922 and both fields have the same value.")
3923
3924 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3925 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3926
3927 (defun js2-print-object-prop-node (n i)
3928 (let* ((left (js2-object-prop-node-left n))
3929 (computed (not (or (js2-string-node-p left)
3930 (js2-number-node-p left)
3931 (js2-name-node-p left)))))
3932 (insert (js2-make-pad i))
3933 (if computed
3934 (insert "["))
3935 (js2-print-ast left 0)
3936 (if computed
3937 (insert "]"))
3938 (if (not (js2-node-get-prop n 'SHORTHAND))
3939 (progn
3940 (insert ": ")
3941 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3942
3943 (cl-defstruct (js2-getter-setter-node
3944 (:include js2-infix-node)
3945 (:constructor nil)
3946 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3947 (pos js2-ts-cursor)
3948 len left right)))
3949 "AST node for a getter/setter property in an object literal.
3950 The `left' field is the `js2-name-node' naming the getter/setter prop.
3951 The `right' field is always an anonymous `js2-function-node' with a node
3952 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3953
3954 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3955 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3956
3957 (defun js2-print-getter-setter (n i)
3958 (let ((pad (js2-make-pad i))
3959 (left (js2-getter-setter-node-left n))
3960 (right (js2-getter-setter-node-right n)))
3961 (insert pad)
3962 (if (/= (js2-node-type n) js2-FUNCTION)
3963 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3964 (js2-print-ast left 0)
3965 (js2-print-ast right 0)))
3966
3967 (cl-defstruct (js2-prop-get-node
3968 (:include js2-infix-node)
3969 (:constructor nil)
3970 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3971 (pos js2-ts-cursor)
3972 len left right)))
3973 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3974
3975 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3976 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3977
3978 (defun js2-visit-prop-get-node (n v)
3979 (js2-visit-ast (js2-prop-get-node-left n) v)
3980 (js2-visit-ast (js2-prop-get-node-right n) v))
3981
3982 (defun js2-print-prop-get-node (n i)
3983 (insert (js2-make-pad i))
3984 (js2-print-ast (js2-prop-get-node-left n) 0)
3985 (insert ".")
3986 (js2-print-ast (js2-prop-get-node-right n) 0))
3987
3988 (cl-defstruct (js2-elem-get-node
3989 (:include js2-node)
3990 (:constructor nil)
3991 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3992 (pos js2-ts-cursor)
3993 len target element
3994 lb rb)))
3995 "AST node for an array index expression such as foo[bar]."
3996 target ; a `js2-node' - the expression preceding the "."
3997 element ; a `js2-node' - the expression in brackets
3998 lb ; position of left-bracket, nil if omitted
3999 rb) ; position of right-bracket, nil if omitted
4000
4001 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4002 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4003
4004 (defun js2-visit-elem-get-node (n v)
4005 (js2-visit-ast (js2-elem-get-node-target n) v)
4006 (js2-visit-ast (js2-elem-get-node-element n) v))
4007
4008 (defun js2-print-elem-get-node (n i)
4009 (insert (js2-make-pad i))
4010 (js2-print-ast (js2-elem-get-node-target n) 0)
4011 (insert "[")
4012 (js2-print-ast (js2-elem-get-node-element n) 0)
4013 (insert "]"))
4014
4015 (cl-defstruct (js2-call-node
4016 (:include js2-node)
4017 (:constructor nil)
4018 (:constructor make-js2-call-node (&key (type js2-CALL)
4019 (pos js2-ts-cursor)
4020 len target args
4021 lp rp)))
4022 "AST node for a JavaScript function call."
4023 target ; a `js2-node' evaluating to the function to call
4024 args ; a Lisp list of `js2-node' arguments
4025 lp ; position of open-paren, or nil if missing
4026 rp) ; position of close-paren, or nil if missing
4027
4028 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4029 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4030
4031 (defun js2-visit-call-node (n v)
4032 (js2-visit-ast (js2-call-node-target n) v)
4033 (dolist (arg (js2-call-node-args n))
4034 (js2-visit-ast arg v)))
4035
4036 (defun js2-print-call-node (n i)
4037 (insert (js2-make-pad i))
4038 (js2-print-ast (js2-call-node-target n) 0)
4039 (insert "(")
4040 (js2-print-list (js2-call-node-args n))
4041 (insert ")"))
4042
4043 (cl-defstruct (js2-yield-node
4044 (:include js2-node)
4045 (:constructor nil)
4046 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4047 (pos js2-ts-cursor)
4048 len value star-p)))
4049 "AST node for yield statement or expression."
4050 star-p ; whether it's yield*
4051 value) ; optional: value to be yielded
4052
4053 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4054 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4055
4056 (defun js2-visit-yield-node (n v)
4057 (js2-visit-ast (js2-yield-node-value n) v))
4058
4059 (defun js2-print-yield-node (n i)
4060 (insert (js2-make-pad i))
4061 (insert "yield")
4062 (when (js2-yield-node-star-p n)
4063 (insert "*"))
4064 (when (js2-yield-node-value n)
4065 (insert " ")
4066 (js2-print-ast (js2-yield-node-value n) 0)))
4067
4068 (cl-defstruct (js2-paren-node
4069 (:include js2-node)
4070 (:constructor nil)
4071 (:constructor make-js2-paren-node (&key (type js2-LP)
4072 (pos js2-ts-cursor)
4073 len expr)))
4074 "AST node for a parenthesized expression.
4075 In particular, used when the parens are syntactically optional,
4076 as opposed to required parens such as those enclosing an if-conditional."
4077 expr) ; `js2-node'
4078
4079 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4080 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4081
4082 (defun js2-visit-paren-node (n v)
4083 (js2-visit-ast (js2-paren-node-expr n) v))
4084
4085 (defun js2-print-paren-node (n i)
4086 (insert (js2-make-pad i))
4087 (insert "(")
4088 (js2-print-ast (js2-paren-node-expr n) 0)
4089 (insert ")"))
4090
4091 (cl-defstruct (js2-comp-node
4092 (:include js2-scope)
4093 (:constructor nil)
4094 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4095 (pos js2-ts-cursor)
4096 len result
4097 loops filters
4098 form)))
4099 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4100 result ; result expression (just after left-bracket)
4101 loops ; a Lisp list of `js2-comp-loop-node'
4102 filters ; a Lisp list of guard/filter expressions
4103 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4104 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4105 )
4106
4107 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4108 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4109
4110 (defun js2-visit-comp-node (n v)
4111 (js2-visit-ast (js2-comp-node-result n) v)
4112 (dolist (l (js2-comp-node-loops n))
4113 (js2-visit-ast l v))
4114 (dolist (f (js2-comp-node-filters n))
4115 (js2-visit-ast f v)))
4116
4117 (defun js2-print-comp-node (n i)
4118 (let ((pad (js2-make-pad i))
4119 (result (js2-comp-node-result n))
4120 (loops (js2-comp-node-loops n))
4121 (filters (js2-comp-node-filters n))
4122 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4123 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4124 (insert pad (if gen-p "(" "["))
4125 (when legacy-p
4126 (js2-print-ast result 0))
4127 (dolist (l loops)
4128 (when legacy-p
4129 (insert " "))
4130 (js2-print-ast l 0)
4131 (unless legacy-p
4132 (insert " ")))
4133 (dolist (f filters)
4134 (when legacy-p
4135 (insert " "))
4136 (insert "if (")
4137 (js2-print-ast f 0)
4138 (insert ")")
4139 (unless legacy-p
4140 (insert " ")))
4141 (unless legacy-p
4142 (js2-print-ast result 0))
4143 (insert (if gen-p ")" "]"))))
4144
4145 (cl-defstruct (js2-comp-loop-node
4146 (:include js2-for-in-node)
4147 (:constructor nil)
4148 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4149 (pos js2-ts-cursor)
4150 len iterator
4151 object in-pos
4152 foreach-p
4153 each-pos
4154 forof-p
4155 lp rp)))
4156 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4157
4158 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4159 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4160
4161 (defun js2-visit-comp-loop (n v)
4162 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4163 (js2-visit-ast (js2-comp-loop-node-object n) v))
4164
4165 (defun js2-print-comp-loop (n _i)
4166 (insert "for ")
4167 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4168 (insert "(")
4169 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4170 (insert (if (js2-comp-loop-node-forof-p n)
4171 " of " " in "))
4172 (js2-print-ast (js2-comp-loop-node-object n) 0)
4173 (insert ")"))
4174
4175 (cl-defstruct (js2-empty-expr-node
4176 (:include js2-node)
4177 (:constructor nil)
4178 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4179 (pos (js2-current-token-beg))
4180 len)))
4181 "AST node for an empty expression.")
4182
4183 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4184 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4185
4186 (cl-defstruct (js2-xml-node
4187 (:include js2-block-node)
4188 (:constructor nil)
4189 (:constructor make-js2-xml-node (&key (type js2-XML)
4190 (pos (js2-current-token-beg))
4191 len kids)))
4192 "AST node for initial parse of E4X literals.
4193 The kids field is a list of XML fragments, each a `js2-string-node' or
4194 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4195
4196 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4197 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4198
4199 (defun js2-print-xml-node (n i)
4200 (dolist (kid (js2-xml-node-kids n))
4201 (js2-print-ast kid i)))
4202
4203 (cl-defstruct (js2-xml-js-expr-node
4204 (:include js2-xml-node)
4205 (:constructor nil)
4206 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4207 (pos js2-ts-cursor)
4208 len expr)))
4209 "AST node for an embedded JavaScript {expression} in an E4X literal.
4210 The start and end fields correspond to the curly-braces."
4211 expr) ; a `js2-expr-node' of some sort
4212
4213 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4214 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4215
4216 (defun js2-visit-xml-js-expr (n v)
4217 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4218
4219 (defun js2-print-xml-js-expr (n i)
4220 (insert (js2-make-pad i))
4221 (insert "{")
4222 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4223 (insert "}"))
4224
4225 (cl-defstruct (js2-xml-dot-query-node
4226 (:include js2-infix-node)
4227 (:constructor nil)
4228 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4229 (pos js2-ts-cursor)
4230 op-pos len left
4231 right rp)))
4232 "AST node for an E4X foo.(bar) filter expression.
4233 Note that the left-paren is automatically the character immediately
4234 following the dot (.) in the operator. No whitespace is permitted
4235 between the dot and the lp by the scanner."
4236 rp)
4237
4238 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4239 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4240
4241 (defun js2-print-xml-dot-query (n i)
4242 (insert (js2-make-pad i))
4243 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4244 (insert ".(")
4245 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4246 (insert ")"))
4247
4248 (cl-defstruct (js2-xml-ref-node
4249 (:include js2-node)
4250 (:constructor nil)) ; abstract
4251 "Base type for E4X XML attribute-access or property-get expressions.
4252 Such expressions can take a variety of forms. The general syntax has
4253 three parts:
4254
4255 - (optional) an @ (specifying an attribute access)
4256 - (optional) a namespace (a `js2-name-node') and double-colon
4257 - (required) either a `js2-name-node' or a bracketed [expression]
4258
4259 The property-name expressions (examples: ns::name, @name) are
4260 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4261 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4262
4263 This node type (or more specifically, its subclasses) will sometimes
4264 be the right-hand child of a `js2-prop-get-node' or a
4265 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4266 The `js2-xml-ref-node' may also be a standalone primary expression with
4267 no explicit target, which is valid in certain expression contexts such as
4268
4269 company..employee.(@id < 100)
4270
4271 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4272 expression whose parent is a `js2-xml-dot-query-node'."
4273 namespace
4274 at-pos
4275 colon-pos)
4276
4277 (defsubst js2-xml-ref-node-attr-access-p (node)
4278 "Return non-nil if this expression began with an @-token."
4279 (and (numberp (js2-xml-ref-node-at-pos node))
4280 (cl-plusp (js2-xml-ref-node-at-pos node))))
4281
4282 (cl-defstruct (js2-xml-prop-ref-node
4283 (:include js2-xml-ref-node)
4284 (:constructor nil)
4285 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4286 (pos (js2-current-token-beg))
4287 len propname
4288 namespace at-pos
4289 colon-pos)))
4290 "AST node for an E4X XML [expr] property-ref expression.
4291 The JavaScript syntax is an optional @, an optional ns::, and a name.
4292
4293 [ '@' ] [ name '::' ] name
4294
4295 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4296 @ns::*, @*::attr, @*::*, and @*.
4297
4298 The node starts at the @ token, if present. Otherwise it starts at the
4299 namespace name. The node bounds extend through the closing right-bracket,
4300 or if it is missing due to a syntax error, through the end of the index
4301 expression."
4302 propname)
4303
4304 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4305 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4306
4307 (defun js2-visit-xml-prop-ref-node (n v)
4308 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4309 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4310
4311 (defun js2-print-xml-prop-ref-node (n i)
4312 (insert (js2-make-pad i))
4313 (if (js2-xml-ref-node-attr-access-p n)
4314 (insert "@"))
4315 (when (js2-xml-prop-ref-node-namespace n)
4316 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4317 (insert "::"))
4318 (if (js2-xml-prop-ref-node-propname n)
4319 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4320
4321 (cl-defstruct (js2-xml-elem-ref-node
4322 (:include js2-xml-ref-node)
4323 (:constructor nil)
4324 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4325 (pos (js2-current-token-beg))
4326 len expr lb rb
4327 namespace at-pos
4328 colon-pos)))
4329 "AST node for an E4X XML [expr] member-ref expression.
4330 Syntax:
4331
4332 [ '@' ] [ name '::' ] '[' expr ']'
4333
4334 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4335
4336 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4337 is not a legal E4X XML element-ref expression, since it's already used
4338 for standard JavaScript element-get array indexing. Hence, a
4339 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4340 non-nil namespace node, or both.
4341
4342 The node starts at the @ token, if present. Otherwise it starts
4343 at the namespace name. The node bounds extend through the closing
4344 right-bracket, or if it is missing due to a syntax error, through the
4345 end of the index expression."
4346 expr ; the bracketed index expression
4347 lb
4348 rb)
4349
4350 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4351 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4352
4353 (defun js2-visit-xml-elem-ref-node (n v)
4354 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4355 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4356
4357 (defun js2-print-xml-elem-ref-node (n i)
4358 (insert (js2-make-pad i))
4359 (if (js2-xml-ref-node-attr-access-p n)
4360 (insert "@"))
4361 (when (js2-xml-elem-ref-node-namespace n)
4362 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4363 (insert "::"))
4364 (insert "[")
4365 (if (js2-xml-elem-ref-node-expr n)
4366 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4367 (insert "]"))
4368
4369 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4370
4371 (cl-defstruct (js2-xml-start-tag-node
4372 (:include js2-xml-node)
4373 (:constructor nil)
4374 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4375 (pos js2-ts-cursor)
4376 len name attrs kids
4377 empty-p)))
4378 "AST node for an XML start-tag. Not currently used.
4379 The `kids' field is a Lisp list of child content nodes."
4380 name ; a `js2-xml-name-node'
4381 attrs ; a Lisp list of `js2-xml-attr-node'
4382 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4383
4384 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4385 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4386
4387 (defun js2-visit-xml-start-tag (n v)
4388 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4389 (dolist (attr (js2-xml-start-tag-node-attrs n))
4390 (js2-visit-ast attr v))
4391 (js2-visit-block n v))
4392
4393 (defun js2-print-xml-start-tag (n i)
4394 (insert (js2-make-pad i) "<")
4395 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4396 (when (js2-xml-start-tag-node-attrs n)
4397 (insert " ")
4398 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4399 (insert ">"))
4400
4401 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4402 ;; and add the end-tag to the kids list of the parent as well.
4403 (cl-defstruct (js2-xml-end-tag-node
4404 (:include js2-xml-node)
4405 (:constructor nil)
4406 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4407 (pos js2-ts-cursor)
4408 len name)))
4409 "AST node for an XML end-tag. Not currently used."
4410 name) ; a `js2-xml-name-node'
4411
4412 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4413 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4414
4415 (defun js2-visit-xml-end-tag (n v)
4416 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4417
4418 (defun js2-print-xml-end-tag (n i)
4419 (insert (js2-make-pad i))
4420 (insert "</")
4421 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4422 (insert ">"))
4423
4424 (cl-defstruct (js2-xml-name-node
4425 (:include js2-xml-node)
4426 (:constructor nil)
4427 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4428 (pos js2-ts-cursor)
4429 len namespace kids)))
4430 "AST node for an E4X XML name. Not currently used.
4431 Any XML name can be qualified with a namespace, hence the namespace field.
4432 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4433 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4434 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4435 namespace) ; a `js2-string-node'
4436
4437 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4438 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4439
4440 (defun js2-visit-xml-name-node (n v)
4441 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4442
4443 (defun js2-print-xml-name-node (n i)
4444 (insert (js2-make-pad i))
4445 (when (js2-xml-name-node-namespace n)
4446 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4447 (insert "::"))
4448 (dolist (kid (js2-xml-name-node-kids n))
4449 (js2-print-ast kid 0)))
4450
4451 (cl-defstruct (js2-xml-pi-node
4452 (:include js2-xml-node)
4453 (:constructor nil)
4454 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4455 (pos js2-ts-cursor)
4456 len name attrs)))
4457 "AST node for an E4X XML processing instruction. Not currently used."
4458 name ; a `js2-xml-name-node'
4459 attrs) ; a list of `js2-xml-attr-node'
4460
4461 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4462 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4463
4464 (defun js2-visit-xml-pi-node (n v)
4465 (js2-visit-ast (js2-xml-pi-node-name n) v)
4466 (dolist (attr (js2-xml-pi-node-attrs n))
4467 (js2-visit-ast attr v)))
4468
4469 (defun js2-print-xml-pi-node (n i)
4470 (insert (js2-make-pad i) "<?")
4471 (js2-print-ast (js2-xml-pi-node-name n))
4472 (when (js2-xml-pi-node-attrs n)
4473 (insert " ")
4474 (js2-print-list (js2-xml-pi-node-attrs n)))
4475 (insert "?>"))
4476
4477 (cl-defstruct (js2-xml-cdata-node
4478 (:include js2-xml-node)
4479 (:constructor nil)
4480 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4481 (pos js2-ts-cursor)
4482 len content)))
4483 "AST node for a CDATA escape section. Not currently used."
4484 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4485
4486 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4487 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4488
4489 (defun js2-visit-xml-cdata-node (n v)
4490 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4491
4492 (defun js2-print-xml-cdata-node (n i)
4493 (insert (js2-make-pad i))
4494 (js2-print-ast (js2-xml-cdata-node-content n)))
4495
4496 (cl-defstruct (js2-xml-attr-node
4497 (:include js2-xml-node)
4498 (:constructor nil)
4499 (:constructor make-js2-attr-node (&key (type js2-XML)
4500 (pos js2-ts-cursor)
4501 len name value
4502 eq-pos quote-type)))
4503 "AST node representing a foo='bar' XML attribute value. Not yet used."
4504 name ; a `js2-xml-name-node'
4505 value ; a `js2-xml-name-node'
4506 eq-pos ; buffer position of "=" sign
4507 quote-type) ; 'single or 'double
4508
4509 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4510 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4511
4512 (defun js2-visit-xml-attr-node (n v)
4513 (js2-visit-ast (js2-xml-attr-node-name n) v)
4514 (js2-visit-ast (js2-xml-attr-node-value n) v))
4515
4516 (defun js2-print-xml-attr-node (n i)
4517 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4518 "'"
4519 "\"")))
4520 (insert (js2-make-pad i))
4521 (js2-print-ast (js2-xml-attr-node-name n) 0)
4522 (insert "=" quote)
4523 (js2-print-ast (js2-xml-attr-node-value n) 0)
4524 (insert quote)))
4525
4526 (cl-defstruct (js2-xml-text-node
4527 (:include js2-xml-node)
4528 (:constructor nil)
4529 (:constructor make-js2-text-node (&key (type js2-XML)
4530 (pos js2-ts-cursor)
4531 len content)))
4532 "AST node for an E4X XML text node. Not currently used."
4533 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4534
4535 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4536 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4537
4538 (defun js2-visit-xml-text-node (n v)
4539 (js2-visit-ast (js2-xml-text-node-content n) v))
4540
4541 (defun js2-print-xml-text-node (n i)
4542 (insert (js2-make-pad i))
4543 (dolist (kid (js2-xml-text-node-content n))
4544 (js2-print-ast kid)))
4545
4546 (cl-defstruct (js2-xml-comment-node
4547 (:include js2-xml-node)
4548 (:constructor nil)
4549 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4550 (pos js2-ts-cursor)
4551 len)))
4552 "AST node for E4X XML comment. Not currently used.")
4553
4554 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4555 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4556
4557 (defun js2-print-xml-comment (n i)
4558 (insert (js2-make-pad i)
4559 (js2-node-string n)))
4560
4561 ;;; Node utilities
4562
4563 (defsubst js2-node-line (n)
4564 "Fetch the source line number at the start of node N.
4565 This is O(n) in the length of the source buffer; use prudently."
4566 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4567
4568 (defsubst js2-block-node-kid (n i)
4569 "Return child I of node N, or nil if there aren't that many."
4570 (nth i (js2-block-node-kids n)))
4571
4572 (defsubst js2-block-node-first (n)
4573 "Return first child of block node N, or nil if there is none."
4574 (cl-first (js2-block-node-kids n)))
4575
4576 (defun js2-node-root (n)
4577 "Return the root of the AST containing N.
4578 If N has no parent pointer, returns N."
4579 (let ((parent (js2-node-parent n)))
4580 (if parent
4581 (js2-node-root parent)
4582 n)))
4583
4584 (defsubst js2-node-short-name (n)
4585 "Return the short name of node N as a string, e.g. `js2-if-node'."
4586 (substring (symbol-name (aref n 0))
4587 (length "cl-struct-")))
4588
4589 (defun js2-node-child-list (node)
4590 "Return the child list for NODE, a Lisp list of nodes.
4591 Works for block nodes, array nodes, obj literals, funarg lists,
4592 var decls and try nodes (for catch clauses). Note that you should call
4593 `js2-block-node-kids' on the function body for the body statements.
4594 Returns nil for zero-length child lists or unsupported nodes."
4595 (cond
4596 ((js2-function-node-p node)
4597 (js2-function-node-params node))
4598 ((js2-block-node-p node)
4599 (js2-block-node-kids node))
4600 ((js2-try-node-p node)
4601 (js2-try-node-catch-clauses node))
4602 ((js2-array-node-p node)
4603 (js2-array-node-elems node))
4604 ((js2-object-node-p node)
4605 (js2-object-node-elems node))
4606 ((js2-call-node-p node)
4607 (js2-call-node-args node))
4608 ((js2-new-node-p node)
4609 (js2-new-node-args node))
4610 ((js2-var-decl-node-p node)
4611 (js2-var-decl-node-kids node))
4612 (t
4613 nil)))
4614
4615 (defun js2-node-set-child-list (node kids)
4616 "Set the child list for NODE to KIDS."
4617 (cond
4618 ((js2-function-node-p node)
4619 (setf (js2-function-node-params node) kids))
4620 ((js2-block-node-p node)
4621 (setf (js2-block-node-kids node) kids))
4622 ((js2-try-node-p node)
4623 (setf (js2-try-node-catch-clauses node) kids))
4624 ((js2-array-node-p node)
4625 (setf (js2-array-node-elems node) kids))
4626 ((js2-object-node-p node)
4627 (setf (js2-object-node-elems node) kids))
4628 ((js2-call-node-p node)
4629 (setf (js2-call-node-args node) kids))
4630 ((js2-new-node-p node)
4631 (setf (js2-new-node-args node) kids))
4632 ((js2-var-decl-node-p node)
4633 (setf (js2-var-decl-node-kids node) kids))
4634 (t
4635 (error "Unsupported node type: %s" (js2-node-short-name node))))
4636 kids)
4637
4638 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4639 (defconst js2-paren-expr-nodes
4640 '(cl-struct-js2-comp-loop-node
4641 cl-struct-js2-comp-node
4642 cl-struct-js2-call-node
4643 cl-struct-js2-catch-node
4644 cl-struct-js2-do-node
4645 cl-struct-js2-elem-get-node
4646 cl-struct-js2-for-in-node
4647 cl-struct-js2-for-node
4648 cl-struct-js2-function-node
4649 cl-struct-js2-if-node
4650 cl-struct-js2-let-node
4651 cl-struct-js2-new-node
4652 cl-struct-js2-paren-node
4653 cl-struct-js2-switch-node
4654 cl-struct-js2-while-node
4655 cl-struct-js2-with-node
4656 cl-struct-js2-xml-dot-query-node)
4657 "Node types that can have a parenthesized child expression.
4658 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4659
4660 (defsubst js2-paren-expr-node-p (node)
4661 "Return t for nodes that typically have a parenthesized child expression.
4662 Useful for computing the indentation anchors for arg-lists and conditions.
4663 Note that it may return a false positive, for instance when NODE is
4664 a `js2-new-node' and there are no arguments or parentheses."
4665 (memq (aref node 0) js2-paren-expr-nodes))
4666
4667 ;; Fake polymorphism... yech.
4668 (defun js2-node-lp (node)
4669 "Return relative left-paren position for NODE, if applicable.
4670 For `js2-elem-get-node' structs, returns left-bracket position.
4671 Note that the position may be nil in the case of a parse error."
4672 (cond
4673 ((js2-elem-get-node-p node)
4674 (js2-elem-get-node-lb node))
4675 ((js2-loop-node-p node)
4676 (js2-loop-node-lp node))
4677 ((js2-function-node-p node)
4678 (js2-function-node-lp node))
4679 ((js2-if-node-p node)
4680 (js2-if-node-lp node))
4681 ((js2-new-node-p node)
4682 (js2-new-node-lp node))
4683 ((js2-call-node-p node)
4684 (js2-call-node-lp node))
4685 ((js2-paren-node-p node)
4686 0)
4687 ((js2-switch-node-p node)
4688 (js2-switch-node-lp node))
4689 ((js2-catch-node-p node)
4690 (js2-catch-node-lp node))
4691 ((js2-let-node-p node)
4692 (js2-let-node-lp node))
4693 ((js2-comp-node-p node)
4694 0)
4695 ((js2-with-node-p node)
4696 (js2-with-node-lp node))
4697 ((js2-xml-dot-query-node-p node)
4698 (1+ (js2-infix-node-op-pos node)))
4699 (t
4700 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4701
4702 ;; Fake polymorphism... blech.
4703 (defun js2-node-rp (node)
4704 "Return relative right-paren position for NODE, if applicable.
4705 For `js2-elem-get-node' structs, returns right-bracket position.
4706 Note that the position may be nil in the case of a parse error."
4707 (cond
4708 ((js2-elem-get-node-p node)
4709 (js2-elem-get-node-rb node))
4710 ((js2-loop-node-p node)
4711 (js2-loop-node-rp node))
4712 ((js2-function-node-p node)
4713 (js2-function-node-rp node))
4714 ((js2-if-node-p node)
4715 (js2-if-node-rp node))
4716 ((js2-new-node-p node)
4717 (js2-new-node-rp node))
4718 ((js2-call-node-p node)
4719 (js2-call-node-rp node))
4720 ((js2-paren-node-p node)
4721 (1- (js2-node-len node)))
4722 ((js2-switch-node-p node)
4723 (js2-switch-node-rp node))
4724 ((js2-catch-node-p node)
4725 (js2-catch-node-rp node))
4726 ((js2-let-node-p node)
4727 (js2-let-node-rp node))
4728 ((js2-comp-node-p node)
4729 (1- (js2-node-len node)))
4730 ((js2-with-node-p node)
4731 (js2-with-node-rp node))
4732 ((js2-xml-dot-query-node-p node)
4733 (1+ (js2-xml-dot-query-node-rp node)))
4734 (t
4735 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4736
4737 (defsubst js2-node-first-child (node)
4738 "Return the first element of `js2-node-child-list' for NODE."
4739 (car (js2-node-child-list node)))
4740
4741 (defsubst js2-node-last-child (node)
4742 "Return the last element of `js2-node-last-child' for NODE."
4743 (car (last (js2-node-child-list node))))
4744
4745 (defun js2-node-prev-sibling (node)
4746 "Return the previous statement in parent.
4747 Works for parents supported by `js2-node-child-list'.
4748 Returns nil if NODE is not in the parent, or PARENT is
4749 not a supported node, or if NODE is the first child."
4750 (let* ((p (js2-node-parent node))
4751 (kids (js2-node-child-list p))
4752 (sib (car kids)))
4753 (while (and kids
4754 (not (eq node (cadr kids))))
4755 (setq kids (cdr kids)
4756 sib (car kids)))
4757 sib))
4758
4759 (defun js2-node-next-sibling (node)
4760 "Return the next statement in parent block.
4761 Returns nil if NODE is not in the block, or PARENT is not
4762 a block node, or if NODE is the last statement."
4763 (let* ((p (js2-node-parent node))
4764 (kids (js2-node-child-list p)))
4765 (while (and kids
4766 (not (eq node (car kids))))
4767 (setq kids (cdr kids)))
4768 (cadr kids)))
4769
4770 (defun js2-node-find-child-before (pos parent &optional after)
4771 "Find the last child that starts before POS in parent.
4772 If AFTER is non-nil, returns first child starting after POS.
4773 POS is an absolute buffer position. PARENT is any node
4774 supported by `js2-node-child-list'.
4775 Returns nil if no applicable child is found."
4776 (let ((kids (if (js2-function-node-p parent)
4777 (js2-block-node-kids (js2-function-node-body parent))
4778 (js2-node-child-list parent)))
4779 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4780 (js2-function-node-body parent)
4781 parent)))
4782 kid result fn
4783 (continue t))
4784 (setq fn (if after '>= '<))
4785 (while (and kids continue)
4786 (setq kid (car kids))
4787 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4788 (setq result kid
4789 continue (not after))
4790 (setq continue after))
4791 (setq kids (cdr kids)))
4792 result))
4793
4794 (defun js2-node-find-child-after (pos parent)
4795 "Find first child that starts after POS in parent.
4796 POS is an absolute buffer position. PARENT is any node
4797 supported by `js2-node-child-list'.
4798 Returns nil if no applicable child is found."
4799 (js2-node-find-child-before pos parent 'after))
4800
4801 (defun js2-node-replace-child (pos parent new-node)
4802 "Replace node at index POS in PARENT with NEW-NODE.
4803 Only works for parents supported by `js2-node-child-list'."
4804 (let ((kids (js2-node-child-list parent))
4805 (i 0))
4806 (while (< i pos)
4807 (setq kids (cdr kids)
4808 i (1+ i)))
4809 (setcar kids new-node)
4810 (js2-node-add-children parent new-node)))
4811
4812 (defun js2-node-buffer (n)
4813 "Return the buffer associated with AST N.
4814 Returns nil if the buffer is not set as a property on the root
4815 node, or if parent links were not recorded during parsing."
4816 (let ((root (js2-node-root n)))
4817 (and root
4818 (js2-ast-root-p root)
4819 (js2-ast-root-buffer root))))
4820
4821 (defun js2-block-node-push (n kid)
4822 "Push js2-node KID onto the end of js2-block-node N's child list.
4823 KID is always added to the -end- of the kids list.
4824 Function also calls `js2-node-add-children' to add the parent link."
4825 (let ((kids (js2-node-child-list n)))
4826 (if kids
4827 (setcdr kids (nconc (cdr kids) (list kid)))
4828 (js2-node-set-child-list n (list kid)))
4829 (js2-node-add-children n kid)))
4830
4831 (defun js2-node-string (node)
4832 (with-current-buffer (or (js2-node-buffer node)
4833 (error "No buffer available for node %s" node))
4834 (let ((pos (js2-node-abs-pos node)))
4835 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4836
4837 ;; Container for storing the node we're looking for in a traversal.
4838 (js2-deflocal js2-discovered-node nil)
4839
4840 ;; Keep track of absolute node position during traversals.
4841 (js2-deflocal js2-visitor-offset nil)
4842
4843 (js2-deflocal js2-node-search-point nil)
4844
4845 (when js2-mode-dev-mode-p
4846 (defun js2-find-node-at-point ()
4847 (interactive)
4848 (let ((node (js2-node-at-point)))
4849 (message "%s" (or node "No node found at point"))))
4850 (defun js2-node-name-at-point ()
4851 (interactive)
4852 (let ((node (js2-node-at-point)))
4853 (message "%s" (if node
4854 (js2-node-short-name node)
4855 "No node found at point.")))))
4856
4857 (defun js2-node-at-point (&optional pos skip-comments)
4858 "Return AST node at POS, a buffer position, defaulting to current point.
4859 The `js2-mode-ast' variable must be set to the current parse tree.
4860 Signals an error if the AST (`js2-mode-ast') is nil.
4861 Always returns a node - if it can't find one, it returns the root.
4862 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4863 (let ((ast js2-mode-ast)
4864 result)
4865 (unless ast
4866 (error "No JavaScript AST available"))
4867 ;; Look through comments first, since they may be inside nodes that
4868 ;; would otherwise report a match.
4869 (setq pos (or pos (point))
4870 result (if (> pos (js2-node-abs-end ast))
4871 ast
4872 (if (not skip-comments)
4873 (js2-comment-at-point pos))))
4874 (unless result
4875 (setq js2-discovered-node nil
4876 js2-visitor-offset 0
4877 js2-node-search-point pos)
4878 (unwind-protect
4879 (catch 'js2-visit-done
4880 (js2-visit-ast ast #'js2-node-at-point-visitor))
4881 (setq js2-visitor-offset nil
4882 js2-node-search-point nil))
4883 (setq result js2-discovered-node))
4884 ;; may have found a comment beyond end of last child node,
4885 ;; since visiting the ast-root looks at the comment-list last.
4886 (if (and skip-comments
4887 (js2-comment-node-p result))
4888 (setq result nil))
4889 (or result js2-mode-ast)))
4890
4891 (defun js2-node-at-point-visitor (node end-p)
4892 (let ((rel-pos (js2-node-pos node))
4893 abs-pos
4894 abs-end
4895 (point js2-node-search-point))
4896 (cond
4897 (end-p
4898 ;; this evaluates to a non-nil return value, even if it's zero
4899 (cl-decf js2-visitor-offset rel-pos))
4900 ;; we already looked for comments before visiting, and don't want them now
4901 ((js2-comment-node-p node)
4902 nil)
4903 (t
4904 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4905 ;; we only want to use the node if the point is before
4906 ;; the last character position in the node, so we decrement
4907 ;; the absolute end by 1.
4908 abs-end (+ abs-pos (js2-node-len node) -1))
4909 (cond
4910 ;; If this node starts after search-point, stop the search.
4911 ((> abs-pos point)
4912 (throw 'js2-visit-done nil))
4913 ;; If this node ends before the search-point, don't check kids.
4914 ((> point abs-end)
4915 nil)
4916 (t
4917 ;; Otherwise point is within this node, possibly in a child.
4918 (setq js2-discovered-node node)
4919 t)))))) ; keep processing kids to look for more specific match
4920
4921 (defsubst js2-block-comment-p (node)
4922 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4923 (and (js2-comment-node-p node)
4924 (memq (js2-comment-node-format node) '(jsdoc block))))
4925
4926 ;; TODO: put the comments in a vector and binary-search them instead
4927 (defun js2-comment-at-point (&optional pos)
4928 "Look through scanned comment nodes for one containing POS.
4929 POS is a buffer position that defaults to current point.
4930 Function returns nil if POS was not in any comment node."
4931 (let ((ast js2-mode-ast)
4932 (x (or pos (point)))
4933 beg end)
4934 (unless ast
4935 (error "No JavaScript AST available"))
4936 (catch 'done
4937 ;; Comments are stored in lexical order.
4938 (dolist (comment (js2-ast-root-comments ast) nil)
4939 (setq beg (js2-node-abs-pos comment)
4940 end (+ beg (js2-node-len comment)))
4941 (if (and (>= x beg)
4942 (<= x end))
4943 (throw 'done comment))))))
4944
4945 (defun js2-mode-find-parent-fn (node)
4946 "Find function enclosing NODE.
4947 Returns nil if NODE is not inside a function."
4948 (setq node (js2-node-parent node))
4949 (while (and node (not (js2-function-node-p node)))
4950 (setq node (js2-node-parent node)))
4951 (and (js2-function-node-p node) node))
4952
4953 (defun js2-mode-find-enclosing-fn (node)
4954 "Find function or root enclosing NODE."
4955 (if (js2-ast-root-p node)
4956 node
4957 (setq node (js2-node-parent node))
4958 (while (not (or (js2-ast-root-p node)
4959 (js2-function-node-p node)))
4960 (setq node (js2-node-parent node)))
4961 node))
4962
4963 (defun js2-mode-find-enclosing-node (beg end)
4964 "Find node fully enclosing BEG and END."
4965 (let ((node (js2-node-at-point beg))
4966 pos
4967 (continue t))
4968 (while continue
4969 (if (or (js2-ast-root-p node)
4970 (and
4971 (<= (setq pos (js2-node-abs-pos node)) beg)
4972 (>= (+ pos (js2-node-len node)) end)))
4973 (setq continue nil)
4974 (setq node (js2-node-parent node))))
4975 node))
4976
4977 (defun js2-node-parent-script-or-fn (node)
4978 "Find script or function immediately enclosing NODE.
4979 If NODE is the ast-root, returns nil."
4980 (if (js2-ast-root-p node)
4981 nil
4982 (setq node (js2-node-parent node))
4983 (while (and node (not (or (js2-function-node-p node)
4984 (js2-script-node-p node))))
4985 (setq node (js2-node-parent node)))
4986 node))
4987
4988 (defun js2-node-is-descendant (node ancestor)
4989 "Return t if NODE is a descendant of ANCESTOR."
4990 (while (and node
4991 (not (eq node ancestor)))
4992 (setq node (js2-node-parent node)))
4993 node)
4994
4995 ;;; visitor infrastructure
4996
4997 (defun js2-visit-none (_node _callback)
4998 "Visitor for AST node that have no node children."
4999 nil)
5000
5001 (defun js2-print-none (_node _indent)
5002 "Visitor for AST node with no printed representation.")
5003
5004 (defun js2-print-body (node indent)
5005 "Print a statement, or a block without braces."
5006 (if (js2-block-node-p node)
5007 (dolist (kid (js2-block-node-kids node))
5008 (js2-print-ast kid indent))
5009 (js2-print-ast node indent)))
5010
5011 (defun js2-print-list (args &optional delimiter)
5012 (cl-loop with len = (length args)
5013 for arg in args
5014 for count from 1
5015 do
5016 (when arg (js2-print-ast arg 0))
5017 (if (< count len)
5018 (insert (or delimiter ", ")))))
5019
5020 (defun js2-print-tree (ast)
5021 "Prints an AST to the current buffer.
5022 Makes `js2-ast-parent-nodes' available to the printer functions."
5023 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5024 (js2-print-ast ast)))
5025
5026 (defun js2-print-ast (node &optional indent)
5027 "Helper function for printing AST nodes.
5028 Requires `js2-ast-parent-nodes' to be non-nil.
5029 You should use `js2-print-tree' instead of this function."
5030 (let ((printer (get (aref node 0) 'js2-printer))
5031 (i (or indent 0)))
5032 ;; TODO: wedge comments in here somewhere
5033 (if printer
5034 (funcall printer node i))))
5035
5036 (defconst js2-side-effecting-tokens
5037 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5038 (dolist (tt (list js2-ASSIGN
5039 js2-ASSIGN_ADD
5040 js2-ASSIGN_BITAND
5041 js2-ASSIGN_BITOR
5042 js2-ASSIGN_BITXOR
5043 js2-ASSIGN_DIV
5044 js2-ASSIGN_LSH
5045 js2-ASSIGN_MOD
5046 js2-ASSIGN_MUL
5047 js2-ASSIGN_RSH
5048 js2-ASSIGN_SUB
5049 js2-ASSIGN_URSH
5050 js2-BLOCK
5051 js2-BREAK
5052 js2-CALL
5053 js2-CATCH
5054 js2-CATCH_SCOPE
5055 js2-CLASS
5056 js2-CONST
5057 js2-CONTINUE
5058 js2-DEBUGGER
5059 js2-DEC
5060 js2-DELPROP
5061 js2-DEL_REF
5062 js2-DO
5063 js2-ELSE
5064 js2-EMPTY
5065 js2-ENTERWITH
5066 js2-EXPORT
5067 js2-EXPR_RESULT
5068 js2-FINALLY
5069 js2-FOR
5070 js2-FUNCTION
5071 js2-GOTO
5072 js2-IF
5073 js2-IFEQ
5074 js2-IFNE
5075 js2-IMPORT
5076 js2-INC
5077 js2-JSR
5078 js2-LABEL
5079 js2-LEAVEWITH
5080 js2-LET
5081 js2-LETEXPR
5082 js2-LOCAL_BLOCK
5083 js2-LOOP
5084 js2-NEW
5085 js2-REF_CALL
5086 js2-RETHROW
5087 js2-RETURN
5088 js2-RETURN_RESULT
5089 js2-SEMI
5090 js2-SETELEM
5091 js2-SETELEM_OP
5092 js2-SETNAME
5093 js2-SETPROP
5094 js2-SETPROP_OP
5095 js2-SETVAR
5096 js2-SET_REF
5097 js2-SET_REF_OP
5098 js2-SWITCH
5099 js2-TARGET
5100 js2-THROW
5101 js2-TRY
5102 js2-VAR
5103 js2-WHILE
5104 js2-WITH
5105 js2-WITHEXPR
5106 js2-YIELD))
5107 (aset tokens tt t))
5108 (if js2-instanceof-has-side-effects
5109 (aset tokens js2-INSTANCEOF t))
5110 tokens))
5111
5112 (defun js2-node-has-side-effects (node)
5113 "Return t if NODE has side effects."
5114 (when node ; makes it easier to handle malformed expressions
5115 (let ((tt (js2-node-type node)))
5116 (cond
5117 ;; This doubtless needs some work, since EXPR_VOID is used
5118 ;; in several ways in Rhino and I may not have caught them all.
5119 ;; I'll wait for people to notice incorrect warnings.
5120 ((and (= tt js2-EXPR_VOID)
5121 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5122 (let ((expr (js2-expr-stmt-node-expr node)))
5123 (or (js2-node-has-side-effects expr)
5124 (when (js2-string-node-p expr)
5125 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5126 ((= tt js2-COMMA)
5127 (js2-node-has-side-effects (js2-infix-node-right node)))
5128 ((or (= tt js2-AND)
5129 (= tt js2-OR))
5130 (or (js2-node-has-side-effects (js2-infix-node-right node))
5131 (js2-node-has-side-effects (js2-infix-node-left node))))
5132 ((= tt js2-HOOK)
5133 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5134 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5135 ((js2-paren-node-p node)
5136 (js2-node-has-side-effects (js2-paren-node-expr node)))
5137 ((= tt js2-ERROR) ; avoid cascaded error messages
5138 nil)
5139 (t
5140 (aref js2-side-effecting-tokens tt))))))
5141
5142 (defconst js2-stmt-node-types
5143 (list js2-BLOCK
5144 js2-BREAK
5145 js2-CONTINUE
5146 js2-DEFAULT ; e4x "default xml namespace" statement
5147 js2-DO
5148 js2-EXPORT
5149 js2-EXPR_RESULT
5150 js2-EXPR_VOID
5151 js2-FOR
5152 js2-IF
5153 js2-IMPORT
5154 js2-RETURN
5155 js2-SWITCH
5156 js2-THROW
5157 js2-TRY
5158 js2-WHILE
5159 js2-WITH)
5160 "Node types that only appear in statement contexts.
5161 The list does not include nodes that always appear as the child
5162 of another specific statement type, such as switch-cases,
5163 catch and finally blocks, and else-clauses. The list also excludes
5164 nodes like yield, let and var, which may appear in either expression
5165 or statement context, and in the latter context always have a
5166 `js2-expr-stmt-node' parent. Finally, the list does not include
5167 functions or scripts, which are treated separately from statements
5168 by the JavaScript parser and runtime.")
5169
5170 (defun js2-stmt-node-p (node)
5171 "Heuristic for figuring out if NODE is a statement.
5172 Some node types can appear in either an expression context or a
5173 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5174 For these node types in a statement context, the parent will be a
5175 `js2-expr-stmt-node'.
5176 Functions aren't included in the check."
5177 (memq (js2-node-type node) js2-stmt-node-types))
5178
5179 (defun js2-mode-find-first-stmt (node)
5180 "Search upward starting from NODE looking for a statement.
5181 For purposes of this function, a `js2-function-node' counts."
5182 (while (not (or (js2-stmt-node-p node)
5183 (js2-function-node-p node)))
5184 (setq node (js2-node-parent node)))
5185 node)
5186
5187 (defun js2-node-parent-stmt (node)
5188 "Return the node's first ancestor that is a statement.
5189 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5190 appearing in a statement context will have a parent that is a
5191 `js2-expr-stmt-node' that will be returned by this function."
5192 (let ((parent (js2-node-parent node)))
5193 (if (or (null parent)
5194 (js2-stmt-node-p parent)
5195 (and (js2-function-node-p parent)
5196 (not (eq (js2-function-node-form parent)
5197 'FUNCTION_EXPRESSION))))
5198 parent
5199 (js2-node-parent-stmt parent))))
5200
5201 ;; In the Mozilla Rhino sources, Roshan James writes:
5202 ;; Does consistent-return analysis on the function body when strict mode is
5203 ;; enabled.
5204 ;;
5205 ;; function (x) { return (x+1) }
5206 ;;
5207 ;; is ok, but
5208 ;;
5209 ;; function (x) { if (x < 0) return (x+1); }
5210 ;;
5211 ;; is not because the function can potentially return a value when the
5212 ;; condition is satisfied and if not, the function does not explicitly
5213 ;; return a value.
5214 ;;
5215 ;; This extends to checking mismatches such as "return" and "return <value>"
5216 ;; used in the same function. Warnings are not emitted if inconsistent
5217 ;; returns exist in code that can be statically shown to be unreachable.
5218 ;; Ex.
5219 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5220 ;;
5221 ;; emits no warning. However if the loop had a break statement, then a
5222 ;; warning would be emitted.
5223 ;;
5224 ;; The consistency analysis looks at control structures such as loops, ifs,
5225 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5226 ;; warns the user about an inconsistent set of termination possibilities.
5227 ;;
5228 ;; These flags enumerate the possible ways a statement/function can
5229 ;; terminate. These flags are used by endCheck() and by the Parser to
5230 ;; detect inconsistent return usage.
5231 ;;
5232 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5233 ;; able to execute (example: throw, continue)
5234 ;;
5235 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5236 ;; next one. Statement such as return dont. A compound statement may have
5237 ;; some branch that drops off control to the next statement.
5238 ;;
5239 ;; END_RETURNS indicates that the statement can return with no value.
5240 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5241 ;;
5242 ;; A compound statement such as
5243 ;; if (condition) {
5244 ;; return value;
5245 ;; }
5246 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5247
5248 (defconst js2-END_UNREACHED 0)
5249 (defconst js2-END_DROPS_OFF 1)
5250 (defconst js2-END_RETURNS 2)
5251 (defconst js2-END_RETURNS_VALUE 4)
5252 (defconst js2-END_YIELDS 8)
5253
5254 (defun js2-has-consistent-return-usage (node)
5255 "Check that every return usage in a function body is consistent.
5256 Returns t if the function satisfies strict mode requirement."
5257 (let ((n (js2-end-check node)))
5258 ;; either it doesn't return a value in any branch...
5259 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5260 ;; or it returns a value (or is unreached) at every branch
5261 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5262 js2-END_RETURNS
5263 js2-END_YIELDS)))))
5264
5265 (defun js2-end-check-if (node)
5266 "Ensure that return usage in then/else blocks is consistent.
5267 If there is no else block, then the return statement can fall through.
5268 Returns logical OR of END_* flags"
5269 (let ((th (js2-if-node-then-part node))
5270 (el (js2-if-node-else-part node)))
5271 (if (null th)
5272 js2-END_UNREACHED
5273 (logior (js2-end-check th) (if el
5274 (js2-end-check el)
5275 js2-END_DROPS_OFF)))))
5276
5277 (defun js2-end-check-switch (node)
5278 "Consistency of return statements is checked between the case statements.
5279 If there is no default, then the switch can fall through. If there is a
5280 default, we check to see if all code paths in the default return or if
5281 there is a code path that can fall through.
5282 Returns logical OR of END_* flags."
5283 (let ((rv js2-END_UNREACHED)
5284 default-case)
5285 ;; examine the cases
5286 (catch 'break
5287 (dolist (c (js2-switch-node-cases node))
5288 (if (js2-case-node-expr c)
5289 (js2-set-flag rv (js2-end-check-block c))
5290 (setq default-case c)
5291 (throw 'break nil))))
5292 ;; we don't care how the cases drop into each other
5293 (js2-clear-flag rv js2-END_DROPS_OFF)
5294 ;; examine the default
5295 (js2-set-flag rv (if default-case
5296 (js2-end-check default-case)
5297 js2-END_DROPS_OFF))
5298 rv))
5299
5300 (defun js2-end-check-try (node)
5301 "If the block has a finally, return consistency is checked in the
5302 finally block. If all code paths in the finally return, then the
5303 returns in the try-catch blocks don't matter. If there is a code path
5304 that does not return or if there is no finally block, the returns
5305 of the try and catch blocks are checked for mismatch.
5306 Returns logical OR of END_* flags."
5307 (let ((finally (js2-try-node-finally-block node))
5308 rv)
5309 ;; check the finally if it exists
5310 (setq rv (if finally
5311 (js2-end-check (js2-finally-node-body finally))
5312 js2-END_DROPS_OFF))
5313 ;; If the finally block always returns, then none of the returns
5314 ;; in the try or catch blocks matter.
5315 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5316 (js2-clear-flag rv js2-END_DROPS_OFF)
5317 ;; examine the try block
5318 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5319 ;; check each catch block
5320 (dolist (cb (js2-try-node-catch-clauses node))
5321 (js2-set-flag rv (js2-end-check cb))))
5322 rv))
5323
5324 (defun js2-end-check-loop (node)
5325 "Return statement in the loop body must be consistent.
5326 The default assumption for any kind of a loop is that it will eventually
5327 terminate. The only exception is a loop with a constant true condition.
5328 Code that follows such a loop is examined only if one can determine
5329 statically that there is a break out of the loop.
5330
5331 for(... ; ... ; ...) {}
5332 for(... in ... ) {}
5333 while(...) { }
5334 do { } while(...)
5335
5336 Returns logical OR of END_* flags."
5337 (let ((rv (js2-end-check (js2-loop-node-body node)))
5338 (condition (cond
5339 ((js2-while-node-p node)
5340 (js2-while-node-condition node))
5341 ((js2-do-node-p node)
5342 (js2-do-node-condition node))
5343 ((js2-for-node-p node)
5344 (js2-for-node-condition node)))))
5345
5346 ;; check to see if the loop condition is always true
5347 (if (and condition
5348 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5349 (js2-clear-flag rv js2-END_DROPS_OFF))
5350
5351 ;; look for effect of breaks
5352 (js2-set-flag rv (js2-node-get-prop node
5353 'CONTROL_BLOCK_PROP
5354 js2-END_UNREACHED))
5355 rv))
5356
5357 (defun js2-end-check-block (node)
5358 "A general block of code is examined statement by statement.
5359 If any statement (even a compound one) returns in all branches, then
5360 subsequent statements are not examined.
5361 Returns logical OR of END_* flags."
5362 (let* ((rv js2-END_DROPS_OFF)
5363 (kids (js2-block-node-kids node))
5364 (n (car kids)))
5365 ;; Check each statment. If the statement can continue onto the next
5366 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5367 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5368 (js2-clear-flag rv js2-END_DROPS_OFF)
5369 (js2-set-flag rv (js2-end-check n))
5370 (setq kids (cdr kids)
5371 n (car kids)))
5372 rv))
5373
5374 (defun js2-end-check-label (node)
5375 "A labeled statement implies that there may be a break to the label.
5376 The function processes the labeled statement and then checks the
5377 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5378 particular label.
5379 Returns logical OR of END_* flags."
5380 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5381 (logior rv (js2-node-get-prop node
5382 'CONTROL_BLOCK_PROP
5383 js2-END_UNREACHED))))
5384
5385 (defun js2-end-check-break (node)
5386 "When a break is encountered annotate the statement being broken
5387 out of by setting its CONTROL_BLOCK_PROP property.
5388 Returns logical OR of END_* flags."
5389 (and (js2-break-node-target node)
5390 (js2-node-set-prop (js2-break-node-target node)
5391 'CONTROL_BLOCK_PROP
5392 js2-END_DROPS_OFF))
5393 js2-END_UNREACHED)
5394
5395 (defun js2-end-check (node)
5396 "Examine the body of a function, doing a basic reachability analysis.
5397 Returns a combination of flags END_* flags that indicate
5398 how the function execution can terminate. These constitute only the
5399 pessimistic set of termination conditions. It is possible that at
5400 runtime certain code paths will never be actually taken. Hence this
5401 analysis will flag errors in cases where there may not be errors.
5402 Returns logical OR of END_* flags"
5403 (let (kid)
5404 (cond
5405 ((js2-break-node-p node)
5406 (js2-end-check-break node))
5407 ((js2-expr-stmt-node-p node)
5408 (if (setq kid (js2-expr-stmt-node-expr node))
5409 (js2-end-check kid)
5410 js2-END_DROPS_OFF))
5411 ((or (js2-continue-node-p node)
5412 (js2-throw-node-p node))
5413 js2-END_UNREACHED)
5414 ((js2-return-node-p node)
5415 (if (setq kid (js2-return-node-retval node))
5416 js2-END_RETURNS_VALUE
5417 js2-END_RETURNS))
5418 ((js2-loop-node-p node)
5419 (js2-end-check-loop node))
5420 ((js2-switch-node-p node)
5421 (js2-end-check-switch node))
5422 ((js2-labeled-stmt-node-p node)
5423 (js2-end-check-label node))
5424 ((js2-if-node-p node)
5425 (js2-end-check-if node))
5426 ((js2-try-node-p node)
5427 (js2-end-check-try node))
5428 ((js2-block-node-p node)
5429 (if (null (js2-block-node-kids node))
5430 js2-END_DROPS_OFF
5431 (js2-end-check-block node)))
5432 ((js2-yield-node-p node)
5433 js2-END_YIELDS)
5434 (t
5435 js2-END_DROPS_OFF))))
5436
5437 (defun js2-always-defined-boolean-p (node)
5438 "Check if NODE always evaluates to true or false in boolean context.
5439 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5440 nor always false."
5441 (let ((tt (js2-node-type node))
5442 num)
5443 (cond
5444 ((or (= tt js2-FALSE) (= tt js2-NULL))
5445 'ALWAYS_FALSE)
5446 ((= tt js2-TRUE)
5447 'ALWAYS_TRUE)
5448 ((= tt js2-NUMBER)
5449 (setq num (js2-number-node-num-value node))
5450 (if (and (not (eq num 0.0e+NaN))
5451 (not (zerop num)))
5452 'ALWAYS_TRUE
5453 'ALWAYS_FALSE))
5454 (t
5455 nil))))
5456
5457 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5458 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5459
5460 (defvar js2-tokens nil
5461 "List of all defined token names.") ; initialized in `js2-token-names'
5462
5463 (defconst js2-token-names
5464 (let* ((names (make-vector js2-num-tokens -1))
5465 (case-fold-search nil) ; only match js2-UPPER_CASE
5466 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5467 (cl-loop for sym in syms
5468 for i from 0
5469 do
5470 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5471 (not (boundp sym)))
5472 (aset names (symbol-value sym) ; code, e.g. 152
5473 (downcase
5474 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5475 (push sym js2-tokens)))
5476 names)
5477 "Vector mapping int values to token string names, sans `js2-' prefix.")
5478
5479 (defun js2-tt-name (tok)
5480 "Return a string name for TOK, a token symbol or code.
5481 Signals an error if it's not a recognized token."
5482 (let ((code tok))
5483 (if (symbolp tok)
5484 (setq code (symbol-value tok)))
5485 (if (eq code -1)
5486 "ERROR"
5487 (if (and (numberp code)
5488 (not (cl-minusp code))
5489 (< code js2-num-tokens))
5490 (aref js2-token-names code)
5491 (error "Invalid token: %s" code)))))
5492
5493 (defsubst js2-tt-sym (tok)
5494 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5495 (intern (js2-tt-name tok)))
5496
5497 (defconst js2-token-codes
5498 (let ((table (make-hash-table :test 'eq :size 256)))
5499 (cl-loop for name across js2-token-names
5500 for sym = (intern (concat "js2-" (upcase name)))
5501 do
5502 (puthash sym (symbol-value sym) table))
5503 ;; clean up a few that are "wrong" in Rhino's token codes
5504 (puthash 'js2-DELETE js2-DELPROP table)
5505 table)
5506 "Hashtable mapping token type symbols to their bytecodes.")
5507
5508 (defsubst js2-tt-code (sym)
5509 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5510 (or (gethash sym js2-token-codes)
5511 (error "Invalid token symbol: %s " sym))) ; signal code bug
5512
5513 (defun js2-report-scan-error (msg &optional no-throw beg len)
5514 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5515 (js2-report-error msg nil
5516 (or beg (js2-current-token-beg))
5517 (or len (js2-current-token-len)))
5518 (unless no-throw
5519 (throw 'return js2-ERROR)))
5520
5521 (defun js2-set-string-from-buffer (token)
5522 "Set `string' and `end' slots for TOKEN, return the string."
5523 (setf (js2-token-end token) js2-ts-cursor
5524 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5525
5526 ;; TODO: could potentially avoid a lot of consing by allocating a
5527 ;; char buffer the way Rhino does.
5528 (defsubst js2-add-to-string (c)
5529 (push c js2-ts-string-buffer))
5530
5531 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5532 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5533 ;; any other character: when it's not part of the current token, we
5534 ;; unget it, allowing it to be read again by the following call.
5535 (defsubst js2-unget-char ()
5536 (cl-decf js2-ts-cursor))
5537
5538 ;; Rhino distinguishes \r and \n line endings. We don't need to
5539 ;; because we only scan from Emacs buffers, which always use \n.
5540 (defun js2-get-char ()
5541 "Read and return the next character from the input buffer.
5542 Increments `js2-ts-lineno' if the return value is a newline char.
5543 Updates `js2-ts-cursor' to the point after the returned char.
5544 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5545 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5546 (let (c)
5547 ;; check for end of buffer
5548 (if (>= js2-ts-cursor (point-max))
5549 (setq js2-ts-hit-eof t
5550 js2-ts-cursor (1+ js2-ts-cursor)
5551 c js2-EOF_CHAR) ; return value
5552 ;; otherwise read next char
5553 (setq c (char-before (cl-incf js2-ts-cursor)))
5554 ;; if we read a newline, update counters
5555 (if (= c ?\n)
5556 (setq js2-ts-line-start js2-ts-cursor
5557 js2-ts-lineno (1+ js2-ts-lineno)))
5558 ;; TODO: skip over format characters
5559 c)))
5560
5561 (defun js2-read-unicode-escape ()
5562 "Read a \\uNNNN sequence from the input.
5563 Assumes the ?\ and ?u have already been read.
5564 Returns the unicode character, or nil if it wasn't a valid character.
5565 Doesn't change the values of any scanner variables."
5566 ;; I really wish I knew a better way to do this, but I can't
5567 ;; find the Emacs function that takes a 16-bit int and converts
5568 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5569 ;; Have to first check that it's 4 hex characters or it may stop
5570 ;; the read early.
5571 (ignore-errors
5572 (let ((s (buffer-substring-no-properties js2-ts-cursor
5573 (+ 4 js2-ts-cursor))))
5574 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5575 (read (concat "?\\u" s))))))
5576
5577 (defun js2-match-char (test)
5578 "Consume and return next character if it matches TEST, a character.
5579 Returns nil and consumes nothing if TEST is not the next character."
5580 (let ((c (js2-get-char)))
5581 (if (eq c test)
5582 t
5583 (js2-unget-char)
5584 nil)))
5585
5586 (defun js2-peek-char ()
5587 (prog1
5588 (js2-get-char)
5589 (js2-unget-char)))
5590
5591 (defun js2-identifier-start-p (c)
5592 "Is C a valid start to an ES5 Identifier?
5593 See http://es5.github.io/#x7.6"
5594 (or
5595 (memq c '(?$ ?_))
5596 (memq (get-char-code-property c 'general-category)
5597 ;; Letters
5598 '(Lu Ll Lt Lm Lo Nl))))
5599
5600 (defun js2-identifier-part-p (c)
5601 "Is C a valid part of an ES5 Identifier?
5602 See http://es5.github.io/#x7.6"
5603 (or
5604 (memq c '(?$ ?_ ?\u200c ?\u200d))
5605 (memq (get-char-code-property c 'general-category)
5606 '(;; Letters
5607 Lu Ll Lt Lm Lo Nl
5608 ;; Combining Marks
5609 Mn Mc
5610 ;; Digits
5611 Nd
5612 ;; Connector Punctuation
5613 Pc))))
5614
5615 (defun js2-alpha-p (c)
5616 (cond ((and (<= ?A c) (<= c ?Z)) t)
5617 ((and (<= ?a c) (<= c ?z)) t)
5618 (t nil)))
5619
5620 (defsubst js2-digit-p (c)
5621 (and (<= ?0 c) (<= c ?9)))
5622
5623 (defun js2-js-space-p (c)
5624 (if (<= c 127)
5625 (memq c '(#x20 #x9 #xB #xC #xD))
5626 (or
5627 (eq c #xA0)
5628 ;; TODO: change this nil to check for Unicode space character
5629 nil)))
5630
5631 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5632
5633 (defun js2-skip-line ()
5634 "Skip to end of line."
5635 (while (not (memq (js2-get-char) js2-eol-chars)))
5636 (js2-unget-char)
5637 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5638 (setq js2-token-end js2-ts-cursor))
5639
5640 (defun js2-init-scanner (&optional buf line)
5641 "Create token stream for BUF starting on LINE.
5642 BUF defaults to `current-buffer' and LINE defaults to 1.
5643
5644 A buffer can only have one scanner active at a time, which yields
5645 dramatically simpler code than using a defstruct. If you need to
5646 have simultaneous scanners in a buffer, copy the regions to scan
5647 into temp buffers."
5648 (with-current-buffer (or buf (current-buffer))
5649 (setq js2-ts-dirty-line nil
5650 js2-ts-hit-eof nil
5651 js2-ts-line-start 0
5652 js2-ts-lineno (or line 1)
5653 js2-ts-line-end-char -1
5654 js2-ts-cursor (point-min)
5655 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5656 js2-ti-tokens-cursor 0
5657 js2-ti-lookahead 0
5658 js2-ts-is-xml-attribute nil
5659 js2-ts-xml-is-tag-content nil
5660 js2-ts-xml-open-tags-count 0
5661 js2-ts-string-buffer nil)))
5662
5663 ;; This function uses the cached op, string and number fields in
5664 ;; TokenStream; if getToken has been called since the passed token
5665 ;; was scanned, the op or string printed may be incorrect.
5666 (defun js2-token-to-string (token)
5667 ;; Not sure where this function is used in Rhino. Not tested.
5668 (if (not js2-debug-print-trees)
5669 ""
5670 (let ((name (js2-tt-name token)))
5671 (cond
5672 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5673 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5674 (concat name " `" (js2-current-token-string) "'"))
5675 ((eq token js2-NUMBER)
5676 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5677 (t
5678 name)))))
5679
5680 (defconst js2-keywords
5681 '(break
5682 case catch class const continue
5683 debugger default delete do
5684 else extends export
5685 false finally for function
5686 if in instanceof import
5687 let
5688 new null
5689 return
5690 static super switch
5691 this throw true try typeof
5692 var void
5693 while with
5694 yield))
5695
5696 ;; Token names aren't exactly the same as the keywords, unfortunately.
5697 ;; E.g. delete is js2-DELPROP.
5698 (defconst js2-kwd-tokens
5699 (let ((table (make-vector js2-num-tokens nil))
5700 (tokens
5701 (list js2-BREAK
5702 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5703 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5704 js2-ELSE js2-EXPORT
5705 js2-ELSE js2-EXTENDS js2-EXPORT
5706 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5707 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5708 js2-LET
5709 js2-NEW js2-NULL
5710 js2-RETURN
5711 js2-STATIC js2-SUPER js2-SWITCH
5712 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5713 js2-VAR
5714 js2-WHILE js2-WITH
5715 js2-YIELD)))
5716 (dolist (i tokens)
5717 (aset table i 'font-lock-keyword-face))
5718 (aset table js2-STRING 'font-lock-string-face)
5719 (aset table js2-REGEXP 'font-lock-string-face)
5720 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5721 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5722 (aset table js2-COMMENT 'font-lock-comment-face)
5723 (aset table js2-THIS 'font-lock-builtin-face)
5724 (aset table js2-SUPER 'font-lock-builtin-face)
5725 (aset table js2-VOID 'font-lock-constant-face)
5726 (aset table js2-NULL 'font-lock-constant-face)
5727 (aset table js2-TRUE 'font-lock-constant-face)
5728 (aset table js2-FALSE 'font-lock-constant-face)
5729 (aset table js2-NOT 'font-lock-negation-char-face)
5730 table)
5731 "Vector whose values are non-nil for tokens that are keywords.
5732 The values are default faces to use for highlighting the keywords.")
5733
5734 ;; FIXME: Support strict mode-only future reserved words, after we know
5735 ;; which parts scopes are in strict mode, and which are not.
5736 (defconst js2-reserved-words '(class enum export extends import super)
5737 "Future reserved keywords in ECMAScript 5.1.")
5738
5739 (defconst js2-keyword-names
5740 (let ((table (make-hash-table :test 'equal)))
5741 (cl-loop for k in js2-keywords
5742 do (puthash
5743 (symbol-name k) ; instanceof
5744 (intern (concat "js2-"
5745 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5746 table))
5747 table)
5748 "JavaScript keywords by name, mapped to their symbols.")
5749
5750 (defconst js2-reserved-word-names
5751 (let ((table (make-hash-table :test 'equal)))
5752 (cl-loop for k in js2-reserved-words
5753 do
5754 (puthash (symbol-name k) 'js2-RESERVED table))
5755 table)
5756 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5757
5758 (defun js2-collect-string (buf)
5759 "Convert BUF, a list of chars, to a string.
5760 Reverses BUF before converting."
5761 (if buf
5762 (apply #'string (nreverse buf))
5763 ""))
5764
5765 (defun js2-string-to-keyword (s)
5766 "Return token for S, a string, if S is a keyword or reserved word.
5767 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5768 (or (gethash s js2-keyword-names)
5769 (gethash s js2-reserved-word-names)))
5770
5771 (defsubst js2-ts-set-char-token-bounds (token)
5772 "Used when next token is one character."
5773 (setf (js2-token-beg token) (1- js2-ts-cursor)
5774 (js2-token-end token) js2-ts-cursor))
5775
5776 (defsubst js2-ts-return (token type)
5777 "Update the `end' and `type' slots of TOKEN,
5778 then throw `return' with value TYPE."
5779 (setf (js2-token-end token) js2-ts-cursor
5780 (js2-token-type token) type)
5781 (throw 'return type))
5782
5783 (defun js2-x-digit-to-int (c accumulator)
5784 "Build up a hex number.
5785 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5786 corresponding number. Otherwise return -1."
5787 (catch 'return
5788 (catch 'check
5789 ;; Use 0..9 < A..Z < a..z
5790 (cond
5791 ((<= c ?9)
5792 (cl-decf c ?0)
5793 (if (<= 0 c)
5794 (throw 'check nil)))
5795 ((<= c ?F)
5796 (when (<= ?A c)
5797 (cl-decf c (- ?A 10))
5798 (throw 'check nil)))
5799 ((<= c ?f)
5800 (when (<= ?a c)
5801 (cl-decf c (- ?a 10))
5802 (throw 'check nil))))
5803 (throw 'return -1))
5804 (logior c (lsh accumulator 4))))
5805
5806 (defun js2-get-token (&optional modifier)
5807 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5808 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5809 next saved token.
5810
5811 This function will not return a newline (js2-EOL) - instead, it
5812 gobbles newlines until it finds a non-newline token. Call
5813 `js2-peek-token-or-eol' when you care about newlines.
5814
5815 This function will also not return a js2-COMMENT. Instead, it
5816 records comments found in `js2-scanned-comments'. If the token
5817 returned by this function immediately follows a jsdoc comment,
5818 the token is flagged as such."
5819 (if (zerop js2-ti-lookahead)
5820 (js2-get-token-internal modifier)
5821 (cl-decf js2-ti-lookahead)
5822 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5823 (let ((tt (js2-current-token-type)))
5824 (cl-assert (not (= tt js2-EOL)))
5825 tt)))
5826
5827 (defun js2-unget-token ()
5828 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5829 (cl-incf js2-ti-lookahead)
5830 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5831
5832 (defun js2-get-token-internal (modifier)
5833 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5834 (tt (js2-token-type token))
5835 saw-eol
5836 face)
5837 ;; process comments
5838 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5839 (if (= tt js2-EOL)
5840 (setq saw-eol t)
5841 (setq saw-eol nil)
5842 (when js2-record-comments
5843 (js2-record-comment token)))
5844 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5845 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5846 tt (js2-token-type token)))
5847
5848 (when saw-eol
5849 (setf (js2-token-follows-eol-p token) t))
5850
5851 ;; perform lexical fontification as soon as token is scanned
5852 (when js2-parse-ide-mode
5853 (cond
5854 ((cl-minusp tt)
5855 (js2-record-face 'js2-error token))
5856 ((setq face (aref js2-kwd-tokens tt))
5857 (js2-record-face face token))
5858 ((and (= tt js2-NAME)
5859 (equal (js2-token-string token) "undefined"))
5860 (js2-record-face 'font-lock-constant-face token))))
5861 tt))
5862
5863 (defsubst js2-string-to-number (str base)
5864 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5865 (condition-case nil
5866 (string-to-number str base)
5867 (overflow-error -1)))
5868
5869 (defun js2-get-token-internal-1 (modifier)
5870 "Return next JavaScript token type, an int such as js2-RETURN.
5871 During operation, creates an instance of `js2-token' struct, sets
5872 its relevant fields and puts it into `js2-ti-tokens'."
5873 (let (identifier-start
5874 is-unicode-escape-start c c1
5875 contains-escape escape-val str result base
5876 quote-char val look-for-slash continue tt
5877 (token (js2-new-token 0)))
5878 (setq
5879 tt
5880 (catch 'return
5881 (when (eq modifier 'TEMPLATE_TAIL)
5882 (setf (js2-token-beg token) (1- js2-ts-cursor))
5883 (throw 'return (js2-get-string-or-template-token ?` token)))
5884 (while t
5885 ;; Eat whitespace, possibly sensitive to newlines.
5886 (setq continue t)
5887 (while continue
5888 (setq c (js2-get-char))
5889 (cond
5890 ((eq c js2-EOF_CHAR)
5891 (js2-unget-char)
5892 (js2-ts-set-char-token-bounds token)
5893 (throw 'return js2-EOF))
5894 ((eq c ?\n)
5895 (js2-ts-set-char-token-bounds token)
5896 (setq js2-ts-dirty-line nil)
5897 (throw 'return js2-EOL))
5898 ((not (js2-js-space-p c))
5899 (if (/= c ?-) ; in case end of HTML comment
5900 (setq js2-ts-dirty-line t))
5901 (setq continue nil))))
5902 ;; Assume the token will be 1 char - fixed up below.
5903 (js2-ts-set-char-token-bounds token)
5904 (when (eq c ?@)
5905 (throw 'return js2-XMLATTR))
5906 ;; identifier/keyword/instanceof?
5907 ;; watch out for starting with a <backslash>
5908 (cond
5909 ((eq c ?\\)
5910 (setq c (js2-get-char))
5911 (if (eq c ?u)
5912 (setq identifier-start t
5913 is-unicode-escape-start t
5914 js2-ts-string-buffer nil)
5915 (setq identifier-start nil)
5916 (js2-unget-char)
5917 (setq c ?\\)))
5918 (t
5919 (when (setq identifier-start (js2-identifier-start-p c))
5920 (setq js2-ts-string-buffer nil)
5921 (js2-add-to-string c))))
5922 (when identifier-start
5923 (setq contains-escape is-unicode-escape-start)
5924 (catch 'break
5925 (while t
5926 (if is-unicode-escape-start
5927 ;; strictly speaking we should probably push-back
5928 ;; all the bad characters if the <backslash>uXXXX
5929 ;; sequence is malformed. But since there isn't a
5930 ;; correct context(is there?) for a bad Unicode
5931 ;; escape sequence in an identifier, we can report
5932 ;; an error here.
5933 (progn
5934 (setq escape-val 0)
5935 (dotimes (_ 4)
5936 (setq c (js2-get-char)
5937 escape-val (js2-x-digit-to-int c escape-val))
5938 ;; Next check takes care of c < 0 and bad escape
5939 (if (cl-minusp escape-val)
5940 (throw 'break nil)))
5941 (if (cl-minusp escape-val)
5942 (js2-report-scan-error "msg.invalid.escape" t))
5943 (js2-add-to-string escape-val)
5944 (setq is-unicode-escape-start nil))
5945 (setq c (js2-get-char))
5946 (cond
5947 ((eq c ?\\)
5948 (setq c (js2-get-char))
5949 (if (eq c ?u)
5950 (setq is-unicode-escape-start t
5951 contains-escape t)
5952 (js2-report-scan-error "msg.illegal.character" t)))
5953 (t
5954 (if (or (eq c js2-EOF_CHAR)
5955 (not (js2-identifier-part-p c)))
5956 (throw 'break nil))
5957 (js2-add-to-string c))))))
5958 (js2-unget-char)
5959 (setf str (js2-collect-string js2-ts-string-buffer)
5960 (js2-token-end token) js2-ts-cursor)
5961 ;; FIXME: Invalid in ES5 and ES6, see
5962 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5963 ;; Probably should just drop this conditional.
5964 (unless contains-escape
5965 ;; OPT we shouldn't have to make a string (object!) to
5966 ;; check if it's a keyword.
5967 ;; Return the corresponding token if it's a keyword
5968 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5969 (setq result (js2-string-to-keyword str)))
5970 (if (and (< js2-language-version 170)
5971 (memq result '(js2-LET js2-YIELD)))
5972 ;; LET and YIELD are tokens only in 1.7 and later
5973 (setq result 'js2-NAME))
5974 (when (eq result 'js2-RESERVED)
5975 (setf (js2-token-string token) str))
5976 (throw 'return (js2-tt-code result))))
5977 ;; If we want to intern these as Rhino does, just use (intern str)
5978 (setf (js2-token-string token) str)
5979 (throw 'return js2-NAME)) ; end identifier/kwd check
5980 ;; is it a number?
5981 (when (or (js2-digit-p c)
5982 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5983 (setq js2-ts-string-buffer nil
5984 base 10)
5985 (when (eq c ?0)
5986 (setq c (js2-get-char))
5987 (cond
5988 ((or (eq c ?x) (eq c ?X))
5989 (setq base 16)
5990 (setq c (js2-get-char)))
5991 ((and (or (eq c ?b) (eq c ?B))
5992 (>= js2-language-version 200))
5993 (setq base 2)
5994 (setq c (js2-get-char)))
5995 ((and (or (eq c ?o) (eq c ?O))
5996 (>= js2-language-version 200))
5997 (setq base 8)
5998 (setq c (js2-get-char)))
5999 ((js2-digit-p c)
6000 (setq base 'maybe-8))
6001 (t
6002 (js2-add-to-string ?0))))
6003 (cond
6004 ((eq base 16)
6005 (if (> 0 (js2-x-digit-to-int c 0))
6006 (js2-report-scan-error "msg.missing.hex.digits")
6007 (while (<= 0 (js2-x-digit-to-int c 0))
6008 (js2-add-to-string c)
6009 (setq c (js2-get-char)))))
6010 ((eq base 2)
6011 (if (not (memq c '(?0 ?1)))
6012 (js2-report-scan-error "msg.missing.binary.digits")
6013 (while (memq c '(?0 ?1))
6014 (js2-add-to-string c)
6015 (setq c (js2-get-char)))))
6016 ((eq base 8)
6017 (if (or (> ?0 c) (< ?7 c))
6018 (js2-report-scan-error "msg.missing.octal.digits")
6019 (while (and (<= ?0 c) (>= ?7 c))
6020 (js2-add-to-string c)
6021 (setq c (js2-get-char)))))
6022 (t
6023 (while (and (<= ?0 c) (<= c ?9))
6024 ;; We permit 08 and 09 as decimal numbers, which
6025 ;; makes our behavior a superset of the ECMA
6026 ;; numeric grammar. We might not always be so
6027 ;; permissive, so we warn about it.
6028 (when (and (eq base 'maybe-8) (>= c ?8))
6029 (js2-report-warning "msg.bad.octal.literal"
6030 (if (eq c ?8) "8" "9"))
6031 (setq base 10))
6032 (js2-add-to-string c)
6033 (setq c (js2-get-char)))
6034 (when (eq base 'maybe-8)
6035 (setq base 8))))
6036 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6037 (when (eq c ?.)
6038 (cl-loop do
6039 (js2-add-to-string c)
6040 (setq c (js2-get-char))
6041 while (js2-digit-p c)))
6042 (when (memq c '(?e ?E))
6043 (js2-add-to-string c)
6044 (setq c (js2-get-char))
6045 (when (memq c '(?+ ?-))
6046 (js2-add-to-string c)
6047 (setq c (js2-get-char)))
6048 (unless (js2-digit-p c)
6049 (js2-report-scan-error "msg.missing.exponent" t))
6050 (cl-loop do
6051 (js2-add-to-string c)
6052 (setq c (js2-get-char))
6053 while (js2-digit-p c))))
6054 (js2-unget-char)
6055 (let ((str (js2-set-string-from-buffer token)))
6056 (setf (js2-token-number token)
6057 (js2-string-to-number str base)))
6058 (throw 'return js2-NUMBER))
6059 ;; is it a string?
6060 (when (or (memq c '(?\" ?\'))
6061 (and (>= js2-language-version 200)
6062 (= c ?`)))
6063 (throw 'return
6064 (js2-get-string-or-template-token c token)))
6065 (js2-ts-return token
6066 (cl-case c
6067 (?\;
6068 (throw 'return js2-SEMI))
6069 (?\[
6070 (throw 'return js2-LB))
6071 (?\]
6072 (throw 'return js2-RB))
6073 (?{
6074 (throw 'return js2-LC))
6075 (?}
6076 (throw 'return js2-RC))
6077 (?\(
6078 (throw 'return js2-LP))
6079 (?\)
6080 (throw 'return js2-RP))
6081 (?,
6082 (throw 'return js2-COMMA))
6083 (??
6084 (throw 'return js2-HOOK))
6085 (?:
6086 (if (js2-match-char ?:)
6087 js2-COLONCOLON
6088 (throw 'return js2-COLON)))
6089 (?.
6090 (if (js2-match-char ?.)
6091 (if (js2-match-char ?.)
6092 js2-TRIPLEDOT js2-DOTDOT)
6093 (if (js2-match-char ?\()
6094 js2-DOTQUERY
6095 (throw 'return js2-DOT))))
6096 (?|
6097 (if (js2-match-char ?|)
6098 (throw 'return js2-OR)
6099 (if (js2-match-char ?=)
6100 js2-ASSIGN_BITOR
6101 (throw 'return js2-BITOR))))
6102 (?^
6103 (if (js2-match-char ?=)
6104 js2-ASSIGN_BITOR
6105 (throw 'return js2-BITXOR)))
6106 (?&
6107 (if (js2-match-char ?&)
6108 (throw 'return js2-AND)
6109 (if (js2-match-char ?=)
6110 js2-ASSIGN_BITAND
6111 (throw 'return js2-BITAND))))
6112 (?=
6113 (if (js2-match-char ?=)
6114 (if (js2-match-char ?=)
6115 js2-SHEQ
6116 (throw 'return js2-EQ))
6117 (if (js2-match-char ?>)
6118 (js2-ts-return token js2-ARROW)
6119 (throw 'return js2-ASSIGN))))
6120 (?!
6121 (if (js2-match-char ?=)
6122 (if (js2-match-char ?=)
6123 js2-SHNE
6124 js2-NE)
6125 (throw 'return js2-NOT)))
6126 (?<
6127 ;; NB:treat HTML begin-comment as comment-till-eol
6128 (when (js2-match-char ?!)
6129 (when (js2-match-char ?-)
6130 (when (js2-match-char ?-)
6131 (js2-skip-line)
6132 (setf (js2-token-comment-type (js2-current-token)) 'html)
6133 (throw 'return js2-COMMENT)))
6134 (js2-unget-char))
6135 (if (js2-match-char ?<)
6136 (if (js2-match-char ?=)
6137 js2-ASSIGN_LSH
6138 js2-LSH)
6139 (if (js2-match-char ?=)
6140 js2-LE
6141 (throw 'return js2-LT))))
6142 (?>
6143 (if (js2-match-char ?>)
6144 (if (js2-match-char ?>)
6145 (if (js2-match-char ?=)
6146 js2-ASSIGN_URSH
6147 js2-URSH)
6148 (if (js2-match-char ?=)
6149 js2-ASSIGN_RSH
6150 js2-RSH))
6151 (if (js2-match-char ?=)
6152 js2-GE
6153 (throw 'return js2-GT))))
6154 (?*
6155 (if (js2-match-char ?=)
6156 js2-ASSIGN_MUL
6157 (throw 'return js2-MUL)))
6158 (?/
6159 ;; is it a // comment?
6160 (when (js2-match-char ?/)
6161 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6162 (js2-skip-line)
6163 (setf (js2-token-comment-type token) 'line)
6164 ;; include newline so highlighting goes to end of window
6165 (cl-incf (js2-token-end token))
6166 (throw 'return js2-COMMENT))
6167 ;; is it a /* comment?
6168 (when (js2-match-char ?*)
6169 (setf look-for-slash nil
6170 (js2-token-beg token) (- js2-ts-cursor 2)
6171 (js2-token-comment-type token)
6172 (if (js2-match-char ?*)
6173 (progn
6174 (setq look-for-slash t)
6175 'jsdoc)
6176 'block))
6177 (while t
6178 (setq c (js2-get-char))
6179 (cond
6180 ((eq c js2-EOF_CHAR)
6181 (setf (js2-token-end token) (1- js2-ts-cursor))
6182 (js2-report-error "msg.unterminated.comment")
6183 (throw 'return js2-COMMENT))
6184 ((eq c ?*)
6185 (setq look-for-slash t))
6186 ((eq c ?/)
6187 (if look-for-slash
6188 (js2-ts-return token js2-COMMENT)))
6189 (t
6190 (setf look-for-slash nil
6191 (js2-token-end token) js2-ts-cursor)))))
6192 (if (js2-match-char ?=)
6193 js2-ASSIGN_DIV
6194 (throw 'return js2-DIV)))
6195 (?#
6196 (when js2-skip-preprocessor-directives
6197 (js2-skip-line)
6198 (setf (js2-token-comment-type token) 'preprocessor
6199 (js2-token-end token) js2-ts-cursor)
6200 (throw 'return js2-COMMENT))
6201 (throw 'return js2-ERROR))
6202 (?%
6203 (if (js2-match-char ?=)
6204 js2-ASSIGN_MOD
6205 (throw 'return js2-MOD)))
6206 (?~
6207 (throw 'return js2-BITNOT))
6208 (?+
6209 (if (js2-match-char ?=)
6210 js2-ASSIGN_ADD
6211 (if (js2-match-char ?+)
6212 js2-INC
6213 (throw 'return js2-ADD))))
6214 (?-
6215 (cond
6216 ((js2-match-char ?=)
6217 (setq c js2-ASSIGN_SUB))
6218 ((js2-match-char ?-)
6219 (unless js2-ts-dirty-line
6220 ;; treat HTML end-comment after possible whitespace
6221 ;; after line start as comment-until-eol
6222 (when (js2-match-char ?>)
6223 (js2-skip-line)
6224 (setf (js2-token-comment-type (js2-current-token)) 'html)
6225 (throw 'return js2-COMMENT)))
6226 (setq c js2-DEC))
6227 (t
6228 (setq c js2-SUB)))
6229 (setq js2-ts-dirty-line t)
6230 c)
6231 (otherwise
6232 (js2-report-scan-error "msg.illegal.character")))))))
6233 (setf (js2-token-type token) tt)
6234 token))
6235
6236 (defun js2-get-string-or-template-token (quote-char token)
6237 ;; We attempt to accumulate a string the fast way, by
6238 ;; building it directly out of the reader. But if there
6239 ;; are any escaped characters in the string, we revert to
6240 ;; building it out of a string buffer.
6241 (let ((c (js2-get-char))
6242 js2-ts-string-buffer
6243 nc)
6244 (catch 'break
6245 (while (/= c quote-char)
6246 (catch 'continue
6247 (when (eq c js2-EOF_CHAR)
6248 (js2-unget-char)
6249 (js2-report-error "msg.unterminated.string.lit")
6250 (throw 'break nil))
6251 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6252 (js2-unget-char)
6253 (js2-report-error "msg.unterminated.string.lit")
6254 (throw 'break nil))
6255 (when (eq c ?\\)
6256 ;; We've hit an escaped character
6257 (setq c (js2-get-char))
6258 (cl-case c
6259 (?b (setq c ?\b))
6260 (?f (setq c ?\f))
6261 (?n (setq c ?\n))
6262 (?r (setq c ?\r))
6263 (?t (setq c ?\t))
6264 (?v (setq c ?\v))
6265 (?u
6266 (setq c1 (js2-read-unicode-escape))
6267 (if js2-parse-ide-mode
6268 (if c1
6269 (progn
6270 ;; just copy the string in IDE-mode
6271 (js2-add-to-string ?\\)
6272 (js2-add-to-string ?u)
6273 (dotimes (_ 3)
6274 (js2-add-to-string (js2-get-char)))
6275 (setq c (js2-get-char))) ; added at end of loop
6276 ;; flag it as an invalid escape
6277 (js2-report-warning "msg.invalid.escape"
6278 nil (- js2-ts-cursor 2) 6))
6279 ;; Get 4 hex digits; if the u escape is not
6280 ;; followed by 4 hex digits, use 'u' + the
6281 ;; literal character sequence that follows.
6282 (js2-add-to-string ?u)
6283 (setq escape-val 0)
6284 (dotimes (_ 4)
6285 (setq c (js2-get-char)
6286 escape-val (js2-x-digit-to-int c escape-val))
6287 (if (cl-minusp escape-val)
6288 (throw 'continue nil))
6289 (js2-add-to-string c))
6290 ;; prepare for replace of stored 'u' sequence by escape value
6291 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6292 c escape-val)))
6293 (?x
6294 ;; Get 2 hex digits, defaulting to 'x'+literal
6295 ;; sequence, as above.
6296 (setq c (js2-get-char)
6297 escape-val (js2-x-digit-to-int c 0))
6298 (if (cl-minusp escape-val)
6299 (progn
6300 (js2-add-to-string ?x)
6301 (throw 'continue nil))
6302 (setq c1 c
6303 c (js2-get-char)
6304 escape-val (js2-x-digit-to-int c escape-val))
6305 (if (cl-minusp escape-val)
6306 (progn
6307 (js2-add-to-string ?x)
6308 (js2-add-to-string c1)
6309 (throw 'continue nil))
6310 ;; got 2 hex digits
6311 (setq c escape-val))))
6312 (?\n
6313 ;; Remove line terminator after escape to follow
6314 ;; SpiderMonkey and C/C++
6315 (setq c (js2-get-char))
6316 (throw 'continue nil))
6317 (t
6318 (when (and (<= ?0 c) (< c ?8))
6319 (setq val (- c ?0)
6320 c (js2-get-char))
6321 (when (and (<= ?0 c) (< c ?8))
6322 (setq val (- (+ (* 8 val) c) ?0)
6323 c (js2-get-char))
6324 (when (and (<= ?0 c)
6325 (< c ?8)
6326 (< val #o37))
6327 ;; c is 3rd char of octal sequence only
6328 ;; if the resulting val <= 0377
6329 (setq val (- (+ (* 8 val) c) ?0)
6330 c (js2-get-char))))
6331 (js2-unget-char)
6332 (setq c val)))))
6333 (when (and (eq quote-char ?`) (eq c ?$))
6334 (when (eq (setq nc (js2-get-char)) ?\{)
6335 (throw 'break nil))
6336 (js2-unget-char))
6337 (js2-add-to-string c)
6338 (setq c (js2-get-char)))))
6339 (js2-set-string-from-buffer token)
6340 (if (not (eq quote-char ?`))
6341 js2-STRING
6342 (if (and (eq c ?$) (eq nc ?\{))
6343 js2-TEMPLATE_HEAD
6344 js2-NO_SUBS_TEMPLATE))))
6345
6346 (defun js2-read-regexp (start-tt)
6347 "Called by parser when it gets / or /= in literal context."
6348 (let (c err
6349 in-class ; inside a '[' .. ']' character-class
6350 flags
6351 (continue t)
6352 (token (js2-new-token 0)))
6353 (setq js2-ts-string-buffer nil)
6354 (if (eq start-tt js2-ASSIGN_DIV)
6355 ;; mis-scanned /=
6356 (js2-add-to-string ?=)
6357 (if (not (eq start-tt js2-DIV))
6358 (error "failed assertion")))
6359 (while (and (not err)
6360 (or (/= (setq c (js2-get-char)) ?/)
6361 in-class))
6362 (cond
6363 ((or (= c ?\n)
6364 (= c js2-EOF_CHAR))
6365 (setf (js2-token-end token) (1- js2-ts-cursor)
6366 err t
6367 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6368 (js2-report-error "msg.unterminated.re.lit"))
6369 (t (cond
6370 ((= c ?\\)
6371 (js2-add-to-string c)
6372 (setq c (js2-get-char)))
6373 ((= c ?\[)
6374 (setq in-class t))
6375 ((= c ?\])
6376 (setq in-class nil)))
6377 (js2-add-to-string c))))
6378 (unless err
6379 (while continue
6380 (cond
6381 ((js2-match-char ?g)
6382 (push ?g flags))
6383 ((js2-match-char ?i)
6384 (push ?i flags))
6385 ((js2-match-char ?m)
6386 (push ?m flags))
6387 ((and (js2-match-char ?u)
6388 (>= js2-language-version 200))
6389 (push ?u flags))
6390 ((and (js2-match-char ?y)
6391 (>= js2-language-version 200))
6392 (push ?y flags))
6393 (t
6394 (setq continue nil))))
6395 (if (js2-alpha-p (js2-peek-char))
6396 (js2-report-scan-error "msg.invalid.re.flag" t
6397 js2-ts-cursor 1))
6398 (js2-set-string-from-buffer token))
6399 (js2-collect-string flags)))
6400
6401 (defun js2-get-first-xml-token ()
6402 (setq js2-ts-xml-open-tags-count 0
6403 js2-ts-is-xml-attribute nil
6404 js2-ts-xml-is-tag-content nil)
6405 (js2-unget-char)
6406 (js2-get-next-xml-token))
6407
6408 (defun js2-xml-discard-string (token)
6409 "Throw away the string in progress and flag an XML parse error."
6410 (setf js2-ts-string-buffer nil
6411 (js2-token-string token) nil)
6412 (js2-report-scan-error "msg.XML.bad.form" t))
6413
6414 (defun js2-get-next-xml-token ()
6415 (setq js2-ts-string-buffer nil) ; for recording the XML
6416 (let ((token (js2-new-token 0))
6417 c result)
6418 (setq result
6419 (catch 'return
6420 (while t
6421 (setq c (js2-get-char))
6422 (cond
6423 ((= c js2-EOF_CHAR)
6424 (throw 'return js2-ERROR))
6425 (js2-ts-xml-is-tag-content
6426 (cl-case c
6427 (?>
6428 (js2-add-to-string c)
6429 (setq js2-ts-xml-is-tag-content nil
6430 js2-ts-is-xml-attribute nil))
6431 (?/
6432 (js2-add-to-string c)
6433 (when (eq ?> (js2-peek-char))
6434 (setq c (js2-get-char))
6435 (js2-add-to-string c)
6436 (setq js2-ts-xml-is-tag-content nil)
6437 (cl-decf js2-ts-xml-open-tags-count)))
6438 (?{
6439 (js2-unget-char)
6440 (js2-set-string-from-buffer token)
6441 (throw 'return js2-XML))
6442 ((?\' ?\")
6443 (js2-add-to-string c)
6444 (unless (js2-read-quoted-string c token)
6445 (throw 'return js2-ERROR)))
6446 (?=
6447 (js2-add-to-string c)
6448 (setq js2-ts-is-xml-attribute t))
6449 ((? ?\t ?\r ?\n)
6450 (js2-add-to-string c))
6451 (t
6452 (js2-add-to-string c)
6453 (setq js2-ts-is-xml-attribute nil)))
6454 (when (and (not js2-ts-xml-is-tag-content)
6455 (zerop js2-ts-xml-open-tags-count))
6456 (js2-set-string-from-buffer token)
6457 (throw 'return js2-XMLEND)))
6458 (t
6459 ;; else not tag content
6460 (cl-case c
6461 (?<
6462 (js2-add-to-string c)
6463 (setq c (js2-peek-char))
6464 (cl-case c
6465 (?!
6466 (setq c (js2-get-char)) ;; skip !
6467 (js2-add-to-string c)
6468 (setq c (js2-peek-char))
6469 (cl-case c
6470 (?-
6471 (setq c (js2-get-char)) ;; skip -
6472 (js2-add-to-string c)
6473 (if (eq c ?-)
6474 (progn
6475 (js2-add-to-string c)
6476 (unless (js2-read-xml-comment token)
6477 (throw 'return js2-ERROR)))
6478 (js2-xml-discard-string token)
6479 (throw 'return js2-ERROR)))
6480 (?\[
6481 (setq c (js2-get-char)) ;; skip [
6482 (js2-add-to-string c)
6483 (if (and (= (js2-get-char) ?C)
6484 (= (js2-get-char) ?D)
6485 (= (js2-get-char) ?A)
6486 (= (js2-get-char) ?T)
6487 (= (js2-get-char) ?A)
6488 (= (js2-get-char) ?\[))
6489 (progn
6490 (js2-add-to-string ?C)
6491 (js2-add-to-string ?D)
6492 (js2-add-to-string ?A)
6493 (js2-add-to-string ?T)
6494 (js2-add-to-string ?A)
6495 (js2-add-to-string ?\[)
6496 (unless (js2-read-cdata token)
6497 (throw 'return js2-ERROR)))
6498 (js2-xml-discard-string token)
6499 (throw 'return js2-ERROR)))
6500 (t
6501 (unless (js2-read-entity token)
6502 (throw 'return js2-ERROR))))
6503 ;; Allow bare CDATA section, e.g.:
6504 ;; let xml = <![CDATA[ foo bar baz ]]>;
6505 (when (zerop js2-ts-xml-open-tags-count)
6506 (throw 'return js2-XMLEND)))
6507 (??
6508 (setq c (js2-get-char)) ;; skip ?
6509 (js2-add-to-string c)
6510 (unless (js2-read-PI token)
6511 (throw 'return js2-ERROR)))
6512 (?/
6513 ;; end tag
6514 (setq c (js2-get-char)) ;; skip /
6515 (js2-add-to-string c)
6516 (when (zerop js2-ts-xml-open-tags-count)
6517 (js2-xml-discard-string token)
6518 (throw 'return js2-ERROR))
6519 (setq js2-ts-xml-is-tag-content t)
6520 (cl-decf js2-ts-xml-open-tags-count))
6521 (t
6522 ;; start tag
6523 (setq js2-ts-xml-is-tag-content t)
6524 (cl-incf js2-ts-xml-open-tags-count))))
6525 (?{
6526 (js2-unget-char)
6527 (js2-set-string-from-buffer token)
6528 (throw 'return js2-XML))
6529 (t
6530 (js2-add-to-string c))))))))
6531 (setf (js2-token-end token) js2-ts-cursor)
6532 (setf (js2-token-type token) result)
6533 result))
6534
6535 (defun js2-read-quoted-string (quote token)
6536 (let (c)
6537 (catch 'return
6538 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6539 (js2-add-to-string c)
6540 (if (eq c quote)
6541 (throw 'return t)))
6542 (js2-xml-discard-string token) ;; throw away string in progress
6543 nil)))
6544
6545 (defun js2-read-xml-comment (token)
6546 (let ((c (js2-get-char)))
6547 (catch 'return
6548 (while (/= c js2-EOF_CHAR)
6549 (catch 'continue
6550 (js2-add-to-string c)
6551 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6552 (setq c (js2-get-char))
6553 (js2-add-to-string c)
6554 (if (eq (js2-peek-char) ?>)
6555 (progn
6556 (setq c (js2-get-char)) ;; skip >
6557 (js2-add-to-string c)
6558 (throw 'return t))
6559 (throw 'continue nil)))
6560 (setq c (js2-get-char))))
6561 (js2-xml-discard-string token)
6562 nil)))
6563
6564 (defun js2-read-cdata (token)
6565 (let ((c (js2-get-char)))
6566 (catch 'return
6567 (while (/= c js2-EOF_CHAR)
6568 (catch 'continue
6569 (js2-add-to-string c)
6570 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6571 (setq c (js2-get-char))
6572 (js2-add-to-string c)
6573 (if (eq (js2-peek-char) ?>)
6574 (progn
6575 (setq c (js2-get-char)) ;; Skip >
6576 (js2-add-to-string c)
6577 (throw 'return t))
6578 (throw 'continue nil)))
6579 (setq c (js2-get-char))))
6580 (js2-xml-discard-string token)
6581 nil)))
6582
6583 (defun js2-read-entity (token)
6584 (let ((decl-tags 1)
6585 c)
6586 (catch 'return
6587 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6588 (js2-add-to-string c)
6589 (cl-case c
6590 (?<
6591 (cl-incf decl-tags))
6592 (?>
6593 (cl-decf decl-tags)
6594 (if (zerop decl-tags)
6595 (throw 'return t)))))
6596 (js2-xml-discard-string token)
6597 nil)))
6598
6599 (defun js2-read-PI (token)
6600 "Scan an XML processing instruction."
6601 (let (c)
6602 (catch 'return
6603 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6604 (js2-add-to-string c)
6605 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6606 (setq c (js2-get-char)) ;; Skip >
6607 (js2-add-to-string c)
6608 (throw 'return t)))
6609 (js2-xml-discard-string token)
6610 nil)))
6611
6612 ;;; Highlighting
6613
6614 (defun js2-set-face (beg end face &optional record)
6615 "Fontify a region. If RECORD is non-nil, record for later."
6616 (when (cl-plusp js2-highlight-level)
6617 (setq beg (min (point-max) beg)
6618 beg (max (point-min) beg)
6619 end (min (point-max) end)
6620 end (max (point-min) end))
6621 (if record
6622 (push (list beg end face) js2-mode-fontifications)
6623 (put-text-property beg end 'font-lock-face face))))
6624
6625 (defsubst js2-clear-face (beg end)
6626 (remove-text-properties beg end '(font-lock-face nil
6627 help-echo nil
6628 point-entered nil
6629 c-in-sws nil)))
6630
6631 (defconst js2-ecma-global-props
6632 (concat "^"
6633 (regexp-opt
6634 '("Infinity" "NaN" "undefined" "arguments") t)
6635 "$")
6636 "Value properties of the Ecma-262 Global Object.
6637 Shown at or above `js2-highlight-level' 2.")
6638
6639 ;; might want to add the name "arguments" to this list?
6640 (defconst js2-ecma-object-props
6641 (concat "^"
6642 (regexp-opt
6643 '("prototype" "__proto__" "__parent__") t)
6644 "$")
6645 "Value properties of the Ecma-262 Object constructor.
6646 Shown at or above `js2-highlight-level' 2.")
6647
6648 (defconst js2-ecma-global-funcs
6649 (concat
6650 "^"
6651 (regexp-opt
6652 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6653 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6654 "$")
6655 "Function properties of the Ecma-262 Global object.
6656 Shown at or above `js2-highlight-level' 2.")
6657
6658 (defconst js2-ecma-number-props
6659 (concat "^"
6660 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6661 "NEGATIVE_INFINITY"
6662 "POSITIVE_INFINITY") t)
6663 "$")
6664 "Properties of the Ecma-262 Number constructor.
6665 Shown at or above `js2-highlight-level' 2.")
6666
6667 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6668 "Properties of the Ecma-262 Date constructor.
6669 Shown at or above `js2-highlight-level' 2.")
6670
6671 (defconst js2-ecma-math-props
6672 (concat "^"
6673 (regexp-opt
6674 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6675 t)
6676 "$")
6677 "Properties of the Ecma-262 Math object.
6678 Shown at or above `js2-highlight-level' 2.")
6679
6680 (defconst js2-ecma-math-funcs
6681 (concat "^"
6682 (regexp-opt
6683 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6684 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6685 "$")
6686 "Function properties of the Ecma-262 Math object.
6687 Shown at or above `js2-highlight-level' 2.")
6688
6689 (defconst js2-ecma-function-props
6690 (concat
6691 "^"
6692 (regexp-opt
6693 '(;; properties of the Object prototype object
6694 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6695 "toLocaleString" "toString" "valueOf"
6696 ;; properties of the Function prototype object
6697 "apply" "call"
6698 ;; properties of the Array prototype object
6699 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6700 "splice" "unshift"
6701 ;; properties of the String prototype object
6702 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6703 "localeCompare" "match" "replace" "search" "split" "substring"
6704 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6705 "toUpperCase"
6706 ;; properties of the Number prototype object
6707 "toExponential" "toFixed" "toPrecision"
6708 ;; properties of the Date prototype object
6709 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6710 "getMinutes" "getMonth" "getSeconds" "getTime"
6711 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6712 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6713 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6714 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6715 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6716 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6717 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6718 "toTimeString" "toUTCString"
6719 ;; properties of the RegExp prototype object
6720 "exec" "test"
6721 ;; properties of the JSON prototype object
6722 "parse" "stringify"
6723 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6724 "toSource" "__defineGetter__" "__defineSetter__"
6725 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6726 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6727 t)
6728 "$")
6729 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6730 Shown at or above `js2-highlight-level' 3.")
6731
6732 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6733 (let ((target-name (and target
6734 (js2-name-node-p target)
6735 (js2-name-node-name target)))
6736 (prop-name (if prop (js2-name-node-name prop)))
6737 (level2 (>= js2-highlight-level 2))
6738 (level3 (>= js2-highlight-level 3)))
6739 (when level2
6740 (let ((face
6741 (if call-p
6742 (cond
6743 ((and target prop)
6744 (cond
6745 ((and level3 (string-match js2-ecma-function-props prop-name))
6746 'font-lock-builtin-face)
6747 ((and target-name prop)
6748 (cond
6749 ((string= target-name "Date")
6750 (if (string-match js2-ecma-date-props prop-name)
6751 'font-lock-builtin-face))
6752 ((string= target-name "Math")
6753 (if (string-match js2-ecma-math-funcs prop-name)
6754 'font-lock-builtin-face))))))
6755 (prop
6756 (if (string-match js2-ecma-global-funcs prop-name)
6757 'font-lock-builtin-face)))
6758 (cond
6759 ((and target prop)
6760 (cond
6761 ((string= target-name "Number")
6762 (if (string-match js2-ecma-number-props prop-name)
6763 'font-lock-constant-face))
6764 ((string= target-name "Math")
6765 (if (string-match js2-ecma-math-props prop-name)
6766 'font-lock-constant-face))))
6767 (prop
6768 (if (string-match js2-ecma-object-props prop-name)
6769 'font-lock-constant-face))))))
6770 (when face
6771 (let ((pos (+ (js2-node-pos parent) ; absolute
6772 (js2-node-pos prop)))) ; relative
6773 (js2-set-face pos
6774 (+ pos (js2-node-len prop))
6775 face 'record)))))))
6776
6777 (defun js2-parse-highlight-member-expr-node (node)
6778 "Perform syntax highlighting of EcmaScript built-in properties.
6779 The variable `js2-highlight-level' governs this highighting."
6780 (let (face target prop name pos end parent call-p callee)
6781 (cond
6782 ;; case 1: simple name, e.g. foo
6783 ((js2-name-node-p node)
6784 (setq name (js2-name-node-name node))
6785 ;; possible for name to be nil in rare cases - saw it when
6786 ;; running js2-mode on an elisp buffer. Might as well try to
6787 ;; make it so js2-mode never barfs.
6788 (when name
6789 (setq face (if (string-match js2-ecma-global-props name)
6790 'font-lock-constant-face))
6791 (when face
6792 (setq pos (js2-node-pos node)
6793 end (+ pos (js2-node-len node)))
6794 (js2-set-face pos end face 'record))))
6795 ;; case 2: property access or function call
6796 ((or (js2-prop-get-node-p node)
6797 ;; highlight function call if expr is a prop-get node
6798 ;; or a plain name (i.e. unqualified function call)
6799 (and (setq call-p (js2-call-node-p node))
6800 (setq callee (js2-call-node-target node)) ; separate setq!
6801 (or (js2-prop-get-node-p callee)
6802 (js2-name-node-p callee))))
6803 (setq parent node
6804 node (if call-p callee node))
6805 (if (and call-p (js2-name-node-p callee))
6806 (setq prop callee)
6807 (setq target (js2-prop-get-node-left node)
6808 prop (js2-prop-get-node-right node)))
6809 (cond
6810 ((js2-name-node-p prop)
6811 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6812 (js2-parse-highlight-prop-get parent target prop call-p))
6813 ((js2-name-node-p target)
6814 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6815 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6816
6817 (defun js2-parse-highlight-member-expr-fn-name (expr)
6818 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6819 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6820 We currently only handle the case where the last component is a prop-get
6821 of a simple name. Called before EXPR has a parent node."
6822 (let (pos
6823 (name (and (js2-prop-get-node-p expr)
6824 (js2-prop-get-node-right expr))))
6825 (when (js2-name-node-p name)
6826 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6827 (js2-node-pos name)))
6828 (+ pos (js2-node-len name))
6829 'font-lock-function-name-face
6830 'record))))
6831
6832 ;; source: http://jsdoc.sourceforge.net/
6833 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6834 ;; allows type specifications, and needs work before entering the wild.
6835
6836 (defconst js2-jsdoc-param-tag-regexp
6837 (concat "^\\s-*\\*+\\s-*\\(@"
6838 "\\(?:param\\|argument\\)"
6839 "\\)"
6840 "\\s-*\\({[^}]+}\\)?" ; optional type
6841 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6842 "\\>")
6843 "Matches jsdoc tags with optional type and optional param name.")
6844
6845 (defconst js2-jsdoc-typed-tag-regexp
6846 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6847 (regexp-opt
6848 '("enum"
6849 "extends"
6850 "field"
6851 "id"
6852 "implements"
6853 "lends"
6854 "mods"
6855 "requires"
6856 "return"
6857 "returns"
6858 "throw"
6859 "throws"))
6860 "\\)\\)\\s-*\\({[^}]+}\\)?")
6861 "Matches jsdoc tags with optional type.")
6862
6863 (defconst js2-jsdoc-arg-tag-regexp
6864 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6865 (regexp-opt
6866 '("alias"
6867 "augments"
6868 "borrows"
6869 "bug"
6870 "base"
6871 "config"
6872 "default"
6873 "define"
6874 "exception"
6875 "function"
6876 "member"
6877 "memberOf"
6878 "name"
6879 "namespace"
6880 "property"
6881 "since"
6882 "suppress"
6883 "this"
6884 "throws"
6885 "type"
6886 "version"))
6887 "\\)\\)\\s-+\\([^ \t]+\\)")
6888 "Matches jsdoc tags with a single argument.")
6889
6890 (defconst js2-jsdoc-empty-tag-regexp
6891 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6892 (regexp-opt
6893 '("addon"
6894 "author"
6895 "class"
6896 "const"
6897 "constant"
6898 "constructor"
6899 "constructs"
6900 "deprecated"
6901 "desc"
6902 "description"
6903 "event"
6904 "example"
6905 "exec"
6906 "export"
6907 "fileoverview"
6908 "final"
6909 "function"
6910 "hidden"
6911 "ignore"
6912 "implicitCast"
6913 "inheritDoc"
6914 "inner"
6915 "interface"
6916 "license"
6917 "noalias"
6918 "noshadow"
6919 "notypecheck"
6920 "override"
6921 "owner"
6922 "preserve"
6923 "preserveTry"
6924 "private"
6925 "protected"
6926 "public"
6927 "static"
6928 "supported"
6929 ))
6930 "\\)\\)\\s-*")
6931 "Matches empty jsdoc tags.")
6932
6933 (defconst js2-jsdoc-link-tag-regexp
6934 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6935 "Matches a jsdoc link or code tag.")
6936
6937 (defconst js2-jsdoc-see-tag-regexp
6938 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6939 "Matches a jsdoc @see tag.")
6940
6941 (defconst js2-jsdoc-html-tag-regexp
6942 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6943 "Matches a simple (no attributes) html start- or end-tag.")
6944
6945 (defun js2-jsdoc-highlight-helper ()
6946 (js2-set-face (match-beginning 1)
6947 (match-end 1)
6948 'js2-jsdoc-tag)
6949 (if (match-beginning 2)
6950 (if (save-excursion
6951 (goto-char (match-beginning 2))
6952 (= (char-after) ?{))
6953 (js2-set-face (1+ (match-beginning 2))
6954 (1- (match-end 2))
6955 'js2-jsdoc-type)
6956 (js2-set-face (match-beginning 2)
6957 (match-end 2)
6958 'js2-jsdoc-value)))
6959 (if (match-beginning 3)
6960 (js2-set-face (match-beginning 3)
6961 (match-end 3)
6962 'js2-jsdoc-value)))
6963
6964 (defun js2-highlight-jsdoc (ast)
6965 "Highlight doc comment tags."
6966 (let ((comments (js2-ast-root-comments ast))
6967 beg end)
6968 (save-excursion
6969 (dolist (node comments)
6970 (when (eq (js2-comment-node-format node) 'jsdoc)
6971 (setq beg (js2-node-abs-pos node)
6972 end (+ beg (js2-node-len node)))
6973 (save-restriction
6974 (narrow-to-region beg end)
6975 (dolist (re (list js2-jsdoc-param-tag-regexp
6976 js2-jsdoc-typed-tag-regexp
6977 js2-jsdoc-arg-tag-regexp
6978 js2-jsdoc-link-tag-regexp
6979 js2-jsdoc-see-tag-regexp
6980 js2-jsdoc-empty-tag-regexp))
6981 (goto-char beg)
6982 (while (re-search-forward re nil t)
6983 (js2-jsdoc-highlight-helper)))
6984 ;; simple highlighting for html tags
6985 (goto-char beg)
6986 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6987 (js2-set-face (match-beginning 1)
6988 (match-end 1)
6989 'js2-jsdoc-html-tag-delimiter)
6990 (js2-set-face (match-beginning 2)
6991 (match-end 2)
6992 'js2-jsdoc-html-tag-name)
6993 (js2-set-face (match-beginning 3)
6994 (match-end 3)
6995 'js2-jsdoc-html-tag-delimiter))))))))
6996
6997 (defun js2-highlight-assign-targets (_node left right)
6998 "Highlight function properties and external variables."
6999 (let (leftpos name)
7000 ;; highlight vars and props assigned function values
7001 (when (or (js2-function-node-p right)
7002 (js2-class-node-p right))
7003 (cond
7004 ;; var foo = function() {...}
7005 ((js2-name-node-p left)
7006 (setq name left))
7007 ;; foo.bar.baz = function() {...}
7008 ((and (js2-prop-get-node-p left)
7009 (js2-name-node-p (js2-prop-get-node-right left)))
7010 (setq name (js2-prop-get-node-right left))))
7011 (when name
7012 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7013 (+ leftpos (js2-node-len name))
7014 'font-lock-function-name-face
7015 'record)))))
7016
7017 (defun js2-record-name-node (node)
7018 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7019 later. NODE must be a name node."
7020 (let ((leftpos (js2-node-abs-pos node)))
7021 (push (list node js2-current-scope
7022 leftpos
7023 (+ leftpos (js2-node-len node)))
7024 js2-recorded-identifiers)))
7025
7026 (defun js2-highlight-undeclared-vars ()
7027 "After entire parse is finished, look for undeclared variable references.
7028 We have to wait until entire buffer is parsed, since JavaScript permits var
7029 decls to occur after they're used.
7030
7031 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7032 it is considered declared."
7033 (let (name)
7034 (dolist (entry js2-recorded-identifiers)
7035 (cl-destructuring-bind (name-node scope pos end) entry
7036 (setq name (js2-name-node-name name-node))
7037 (unless (or (member name js2-global-externs)
7038 (member name js2-default-externs)
7039 (member name js2-additional-externs)
7040 (js2-get-defining-scope scope name))
7041 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7042 'js2-external-variable))))
7043 (setq js2-recorded-identifiers nil)))
7044
7045 (defun js2-set-default-externs ()
7046 "Set the value of `js2-default-externs' based on the various
7047 `js2-include-?-externs' variables."
7048 (setq js2-default-externs
7049 (append js2-ecma-262-externs
7050 (if js2-include-browser-externs js2-browser-externs)
7051 (if (and js2-include-browser-externs
7052 (>= js2-language-version 200)) js2-harmony-externs)
7053 (if js2-include-rhino-externs js2-rhino-externs)
7054 (if js2-include-node-externs js2-node-externs)
7055 (if (or js2-include-browser-externs js2-include-node-externs)
7056 js2-typed-array-externs))))
7057
7058 (defun js2-apply-jslint-globals ()
7059 (setq js2-additional-externs
7060 (nconc (js2-get-jslint-globals)
7061 js2-additional-externs)))
7062
7063 (defun js2-get-jslint-globals ()
7064 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7065 when (and (eq 'block (js2-comment-node-format node))
7066 (save-excursion
7067 (goto-char (js2-node-abs-pos node))
7068 (looking-at "/\\*global ")))
7069 append (js2-get-jslint-globals-in
7070 (match-end 0)
7071 (js2-node-abs-end node))))
7072
7073 (defun js2-get-jslint-globals-in (beg end)
7074 (let (res)
7075 (save-excursion
7076 (goto-char beg)
7077 (while (re-search-forward js2-mode-identifier-re end t)
7078 (let ((match (match-string 0)))
7079 (unless (member match '("true" "false"))
7080 (push match res)))))
7081 (nreverse res)))
7082
7083 ;;; IMenu support
7084
7085 ;; We currently only support imenu, but eventually should support speedbar and
7086 ;; possibly other browsing mechanisms.
7087
7088 ;; The basic strategy is to identify function assignment targets of the form
7089 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7090 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7091 ;; for imenu after parsing is finished.
7092
7093 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7094 ;; JavaScript, and the general problem is undecidable. However, several forms
7095 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7096 ;; include:
7097
7098 ;; function foo() -- function declaration
7099 ;; foo = function() -- function expression assigned to variable
7100 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7101 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7102 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7103 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7104 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7105 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7106 ;; function foo() {function bar() {...}} -- nested function
7107 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7108
7109 ;; This list boils down to a few forms that can be combined recursively.
7110 ;; Top-level named function declarations include both the left-hand (name)
7111 ;; and the right-hand (function value) expressions needed to produce an imenu
7112 ;; entry. The other "right-hand" forms we need to look for are:
7113 ;; - functions declared as props/getters/setters in object literals
7114 ;; - nested named function declarations
7115 ;; The "left-hand" expressions that functions can be assigned to include:
7116 ;; - local/global variables
7117 ;; - nested property-get expressions like a.b.c.d
7118 ;; - element gets like foo[10] or foo['bar'] where the index
7119 ;; expression can be trivially converted to a property name. They
7120 ;; effectively then become property gets.
7121
7122 ;; All the different definition types are canonicalized into the form
7123 ;; foo.bar.baz = position-of-function-keyword
7124
7125 ;; We need to build a trie-like structure for imenu. As an example,
7126 ;; consider the following JavaScript code:
7127
7128 ;; a = function() {...} // function at position 5
7129 ;; b = function() {...} // function at position 25
7130 ;; foo = function() {...} // function at position 100
7131 ;; foo.bar = function() {...} // function at position 200
7132 ;; foo.bar.baz = function() {...} // function at position 300
7133 ;; foo.bar.zab = function() {...} // function at position 400
7134
7135 ;; During parsing we accumulate an entry for each definition in
7136 ;; the variable `js2-imenu-recorder', like so:
7137
7138 ;; '((fn a 5)
7139 ;; (fn b 25)
7140 ;; (fn foo 100)
7141 ;; (fn foo bar 200)
7142 ;; (fn foo bar baz 300)
7143 ;; (fn foo bar zab 400))
7144
7145 ;; Where 'fn' is the respective function node.
7146 ;; After parsing these entries are merged into this alist-trie:
7147
7148 ;; '((a . 1)
7149 ;; (b . 2)
7150 ;; (foo (<definition> . 3)
7151 ;; (bar (<definition> . 6)
7152 ;; (baz . 100)
7153 ;; (zab . 200))))
7154
7155 ;; Note the wacky need for a <definition> name. The token can be anything
7156 ;; that isn't a valid JavaScript identifier, because you might make foo
7157 ;; a function and then start setting properties on it that are also functions.
7158
7159 (defun js2-prop-node-name (node)
7160 "Return the name of a node that may be a property-get/property-name.
7161 If NODE is not a valid name-node, string-node or integral number-node,
7162 returns nil. Otherwise returns the string name/value of the node."
7163 (cond
7164 ((js2-name-node-p node)
7165 (js2-name-node-name node))
7166 ((js2-string-node-p node)
7167 (js2-string-node-value node))
7168 ((and (js2-number-node-p node)
7169 (string-match "^[0-9]+$" (js2-number-node-value node)))
7170 (js2-number-node-value node))
7171 ((eq (js2-node-type node) js2-THIS)
7172 "this")
7173 ((eq (js2-node-type node) js2-SUPER)
7174 "super")))
7175
7176 (defun js2-node-qname-component (node)
7177 "Return the name of this node, if it contributes to a qname.
7178 Returns nil if the node doesn't contribute."
7179 (copy-sequence
7180 (or (js2-prop-node-name node)
7181 (if (and (js2-function-node-p node)
7182 (js2-function-node-name node))
7183 (js2-name-node-name (js2-function-node-name node))))))
7184
7185 (defun js2-record-imenu-entry (fn-node qname pos)
7186 "Add an entry to `js2-imenu-recorder'.
7187 FN-NODE should be the current item's function node.
7188
7189 Associate FN-NODE with its QNAME for later lookup.
7190 This is used in postprocessing the chain list. For each chain, we find
7191 the parent function, look up its qname, then prepend a copy of it to the chain."
7192 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7193 (unless js2-imenu-function-map
7194 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7195 (puthash fn-node qname js2-imenu-function-map))
7196
7197 (defun js2-record-imenu-functions (node &optional var)
7198 "Record function definitions for imenu.
7199 NODE is a function node or an object literal.
7200 VAR, if non-nil, is the expression that NODE is being assigned to.
7201 When passed arguments of wrong type, does nothing."
7202 (when js2-parse-ide-mode
7203 (let ((fun-p (js2-function-node-p node))
7204 qname fname-node)
7205 (cond
7206 ;; non-anonymous function declaration?
7207 ((and fun-p
7208 (not var)
7209 (setq fname-node (js2-function-node-name node)))
7210 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7211 ;; for remaining forms, compute left-side tree branch first
7212 ((and var (setq qname (js2-compute-nested-prop-get var)))
7213 (cond
7214 ;; foo.bar.baz = function
7215 (fun-p
7216 (js2-record-imenu-entry node qname (js2-node-pos node)))
7217 ;; foo.bar.baz = object-literal
7218 ;; look for nested functions: {a: {b: function() {...} }}
7219 ((js2-object-node-p node)
7220 ;; Node position here is still absolute, since the parser
7221 ;; passes the assignment target and value expressions
7222 ;; to us before they are added as children of the assignment node.
7223 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7224
7225 (defun js2-compute-nested-prop-get (node)
7226 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7227 component nodes as a list. Otherwise return nil. Element-gets are treated
7228 as property-gets if the index expression is a string, or a positive integer."
7229 (let (left right head)
7230 (cond
7231 ((or (js2-name-node-p node)
7232 (js2-this-or-super-node-p node))
7233 (list node))
7234 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7235 ((js2-prop-get-node-p node) ; foo.bar
7236 (setq left (js2-prop-get-node-left node)
7237 right (js2-prop-get-node-right node))
7238 (if (setq head (js2-compute-nested-prop-get left))
7239 (nconc head (list right))))
7240 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7241 (setq left (js2-elem-get-node-target node)
7242 right (js2-elem-get-node-element node))
7243 (if (or (js2-string-node-p right) ; ['bar']
7244 (and (js2-number-node-p right) ; [10]
7245 (string-match "^[0-9]+$"
7246 (js2-number-node-value right))))
7247 (if (setq head (js2-compute-nested-prop-get left))
7248 (nconc head (list right))))))))
7249
7250 (defun js2-record-object-literal (node qname pos)
7251 "Recursively process an object literal looking for functions.
7252 NODE is an object literal that is the right-hand child of an assignment
7253 expression. QNAME is a list of nodes representing the assignment target,
7254 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7255 POS is the absolute position of the node.
7256 We do a depth-first traversal of NODE. For any functions we find,
7257 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7258 (let (right)
7259 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7260 (let ((left (js2-infix-node-left e))
7261 ;; Element positions are relative to the parent position.
7262 (pos (+ pos (js2-node-pos e))))
7263 (cond
7264 ;; foo: function() {...}
7265 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7266 (when (js2-prop-node-name left)
7267 ;; As a policy decision, we record the position of the property,
7268 ;; not the position of the `function' keyword, since the property
7269 ;; is effectively the name of the function.
7270 (js2-record-imenu-entry right (append qname (list left)) pos)))
7271 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7272 ((js2-object-node-p right)
7273 (js2-record-object-literal right
7274 (append qname (list (js2-infix-node-left e)))
7275 (+ pos (js2-node-pos right)))))))))
7276
7277 (defun js2-node-top-level-decl-p (node)
7278 "Return t if NODE's name is defined in the top-level scope.
7279 Also returns t if NODE's name is not defined in any scope, since it implies
7280 that it's an external variable, which must also be in the top-level scope."
7281 (let* ((name (js2-prop-node-name node))
7282 (this-scope (js2-node-get-enclosing-scope node))
7283 defining-scope)
7284 (cond
7285 ((js2-this-or-super-node-p node)
7286 nil)
7287 ((null this-scope)
7288 t)
7289 ((setq defining-scope (js2-get-defining-scope this-scope name))
7290 (js2-ast-root-p defining-scope))
7291 (t t))))
7292
7293 (defun js2-wrapper-function-p (node)
7294 "Return t if NODE is a function expression that's immediately invoked.
7295 NODE must be `js2-function-node'."
7296 (let ((parent (js2-node-parent node)))
7297 (or
7298 ;; function(){...}();
7299 (and (js2-call-node-p parent)
7300 (eq node (js2-call-node-target parent)))
7301 (and (js2-paren-node-p parent)
7302 ;; (function(){...})();
7303 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7304 ;; (function(){...}).call(this);
7305 (and (js2-prop-get-node-p parent)
7306 (member (js2-name-node-name (js2-prop-get-node-right parent))
7307 '("call" "apply"))
7308 (js2-call-node-p (js2-node-parent parent))))))))
7309
7310 (defun js2-browse-postprocess-chains ()
7311 "Modify function-declaration name chains after parsing finishes.
7312 Some of the information is only available after the parse tree is complete.
7313 For instance, processing a nested scope requires a parent function node."
7314 (let (result fn parent-qname p elem)
7315 (dolist (entry js2-imenu-recorder)
7316 ;; function node goes first
7317 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7318 ;; Examine head's defining scope:
7319 ;; Pre-processed chain, or top-level/external, keep as-is.
7320 (if (or (stringp head) (js2-node-top-level-decl-p head))
7321 (push chain result)
7322 (when (js2-this-or-super-node-p head)
7323 (setq chain (cdr chain))) ; discard this-node
7324 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7325 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7326 (when (eq parent-qname 'not-found)
7327 ;; anonymous function expressions are not recorded
7328 ;; during the parse, so we need to handle this case here
7329 (setq parent-qname
7330 (if (js2-wrapper-function-p fn)
7331 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7332 (if (js2-ast-root-p grandparent)
7333 nil
7334 (gethash grandparent js2-imenu-function-map 'skip)))
7335 'skip))
7336 (puthash fn parent-qname js2-imenu-function-map))
7337 (if (eq parent-qname 'skip)
7338 ;; We don't show it, let's record that fact.
7339 (remhash current-fn js2-imenu-function-map)
7340 ;; Prepend parent fn qname to this chain.
7341 (let ((qname (append parent-qname chain)))
7342 (puthash current-fn (butlast qname) js2-imenu-function-map)
7343 (push qname result)))))))
7344 ;; Collect chains obtained by third-party code.
7345 (let (js2-imenu-recorder)
7346 (run-hooks 'js2-build-imenu-callbacks)
7347 (dolist (entry js2-imenu-recorder)
7348 (push (cdr entry) result)))
7349 ;; Finally replace each node in each chain with its name.
7350 (dolist (chain result)
7351 (setq p chain)
7352 (while p
7353 (if (js2-node-p (setq elem (car p)))
7354 (setcar p (js2-node-qname-component elem)))
7355 (setq p (cdr p))))
7356 result))
7357
7358 ;; Merge name chains into a trie-like tree structure of nested lists.
7359 ;; To simplify construction of the trie, we first build it out using the rule
7360 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7361 ;; [key, num-or-list]. The second element can be a number; if so, this key
7362 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7363 ;; associated with the key at this level.) Otherwise the second element is
7364 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7365 ;; a simple recursive formulation.
7366 ;;
7367 ;; js2-mode is building the data structure for imenu. The imenu documentation
7368 ;; claims that it's the structure above, but in practice it wants the children
7369 ;; at the same list level as the key for that level, which is how I've drawn
7370 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7371 ;; list wrapper around the children at each level.
7372 ;;
7373 ;; A completed nested imenu-alist entry looks like this:
7374 ;; '(("foo"
7375 ;; ("<definition>" . 7)
7376 ;; ("bar"
7377 ;; ("a" . 40)
7378 ;; ("b" . 60))))
7379 ;;
7380 ;; In particular, the documentation for `imenu--index-alist' says that
7381 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7382 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7383
7384 (defun js2-treeify (lst)
7385 "Convert (a b c d) to (a ((b ((c d)))))."
7386 (if (null (cddr lst)) ; list length <= 2
7387 lst
7388 (list (car lst) (list (js2-treeify (cdr lst))))))
7389
7390 (defun js2-build-alist-trie (chains trie)
7391 "Merge declaration name chains into a trie-like alist structure for imenu.
7392 CHAINS is the qname chain list produced during parsing. TRIE is a
7393 list of elements built up so far."
7394 (let (head tail pos branch kids)
7395 (dolist (chain chains)
7396 (setq head (car chain)
7397 tail (cdr chain)
7398 pos (if (numberp (car tail)) (car tail))
7399 branch (js2-find-if (lambda (n)
7400 (string= (car n) head))
7401 trie)
7402 kids (cl-second branch))
7403 (cond
7404 ;; case 1: this key isn't in the trie yet
7405 ((null branch)
7406 (if trie
7407 (setcdr (last trie) (list (js2-treeify chain)))
7408 (setq trie (list (js2-treeify chain)))))
7409 ;; case 2: key is present with a single number entry: replace w/ list
7410 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7411 ;; ("<definition>" 20)))
7412 ((numberp kids)
7413 (setcar (cdr branch)
7414 (list (list "<definition-1>" kids)
7415 (if pos
7416 (list "<definition-2>" pos)
7417 (js2-treeify tail)))))
7418 ;; case 3: key is there (with kids), and we're a number entry
7419 (pos
7420 (setcdr (last kids)
7421 (list
7422 (list (format "<definition-%d>"
7423 (1+ (cl-loop for kid in kids
7424 count (eq ?< (aref (car kid) 0)))))
7425 pos))))
7426 ;; case 4: key is there with kids, need to merge in our chain
7427 (t
7428 (js2-build-alist-trie (list tail) kids))))
7429 trie))
7430
7431 (defun js2-flatten-trie (trie)
7432 "Convert TRIE to imenu-format.
7433 Recurses through nodes, and for each one whose second element is a list,
7434 appends the list's flattened elements to the current element. Also
7435 changes the tails into conses. For instance, this pre-flattened trie
7436
7437 '(a ((b 20)
7438 (c ((d 30)
7439 (e 40)))))
7440
7441 becomes
7442
7443 '(a (b . 20)
7444 (c (d . 30)
7445 (e . 40)))
7446
7447 Note that the root of the trie has no key, just a list of chains.
7448 This is also true for the value of any key with multiple children,
7449 e.g. key 'c' in the example above."
7450 (cond
7451 ((listp (car trie))
7452 (mapcar #'js2-flatten-trie trie))
7453 (t
7454 (if (numberp (cl-second trie))
7455 (cons (car trie) (cl-second trie))
7456 ;; else pop list and append its kids
7457 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7458
7459 (defun js2-build-imenu-index ()
7460 "Turn `js2-imenu-recorder' into an imenu data structure."
7461 (when (eq js2-imenu-recorder 'empty)
7462 (setq js2-imenu-recorder nil))
7463 (let* ((chains (js2-browse-postprocess-chains))
7464 (result (js2-build-alist-trie chains nil)))
7465 (js2-flatten-trie result)))
7466
7467 (defun js2-test-print-chains (chains)
7468 "Print a list of qname chains.
7469 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7470 i.e. one or more nodes, and an integer position as the list tail."
7471 (mapconcat (lambda (chain)
7472 (concat "("
7473 (mapconcat (lambda (elem)
7474 (if (js2-node-p elem)
7475 (or (js2-node-qname-component elem)
7476 "nil")
7477 (number-to-string elem)))
7478 chain
7479 " ")
7480 ")"))
7481 chains
7482 "\n"))
7483
7484 ;;; Parser
7485
7486 (defconst js2-version "1.8.5"
7487 "Version of JavaScript supported.")
7488
7489 (defun js2-record-face (face &optional token)
7490 "Record a style run of FACE for TOKEN or the current token."
7491 (unless token (setq token (js2-current-token)))
7492 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7493
7494 (defsubst js2-node-end (n)
7495 "Computes the absolute end of node N.
7496 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7497 is only true until the node is added to its parent; i.e., while parsing."
7498 (+ (js2-node-pos n)
7499 (js2-node-len n)))
7500
7501 (defun js2-record-comment (token)
7502 "Record a comment in `js2-scanned-comments'."
7503 (let ((ct (js2-token-comment-type token))
7504 (beg (js2-token-beg token))
7505 (end (js2-token-end token)))
7506 (push (make-js2-comment-node :len (- end beg)
7507 :format ct)
7508 js2-scanned-comments)
7509 (when js2-parse-ide-mode
7510 (js2-record-face (if (eq ct 'jsdoc)
7511 'font-lock-doc-face
7512 'font-lock-comment-face)
7513 token)
7514 (when (memq ct '(html preprocessor))
7515 ;; Tell cc-engine the bounds of the comment.
7516 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7517
7518 (defun js2-peek-token ()
7519 "Return the next token type without consuming it.
7520 If `js2-ti-lookahead' is positive, return the type of next token
7521 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7522 (if (not (zerop js2-ti-lookahead))
7523 (js2-token-type
7524 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7525 (let ((tt (js2-get-token-internal nil)))
7526 (js2-unget-token)
7527 tt)))
7528
7529 (defalias 'js2-next-token 'js2-get-token)
7530
7531 (defun js2-match-token (match &optional dont-unget)
7532 "Get next token and return t if it matches MATCH, a bytecode.
7533 Returns nil and consumes nothing if MATCH is not the next token."
7534 (if (/= (js2-get-token) match)
7535 (ignore (unless dont-unget (js2-unget-token)))
7536 t))
7537
7538 (defun js2-match-contextual-kwd (name)
7539 "Consume and return t if next token is `js2-NAME', and its
7540 string is NAME. Returns nil and keeps current token otherwise."
7541 (if (or (/= (js2-get-token) js2-NAME)
7542 (not (string= (js2-current-token-string) name)))
7543 (progn
7544 (js2-unget-token)
7545 nil)
7546 (js2-record-face 'font-lock-keyword-face)
7547 t))
7548
7549 (defun js2-get-prop-name-token ()
7550 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7551
7552 (defun js2-match-prop-name ()
7553 "Consume token and return t if next token is a valid property name.
7554 If `js2-language-version' is >= 180, a keyword or reserved word
7555 is considered valid name as well."
7556 (if (eq js2-NAME (js2-get-prop-name-token))
7557 t
7558 (js2-unget-token)
7559 nil))
7560
7561 (defun js2-must-match-prop-name (msg-id &optional pos len)
7562 (if (js2-match-prop-name)
7563 t
7564 (js2-report-error msg-id nil pos len)
7565 nil))
7566
7567 (defun js2-peek-token-or-eol ()
7568 "Return js2-EOL if the next token immediately follows a newline.
7569 Else returns the next token. Used in situations where we don't
7570 consider certain token types valid if they are preceded by a newline.
7571 One example is the postfix ++ or -- operator, which has to be on the
7572 same line as its operand."
7573 (let ((tt (js2-get-token))
7574 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7575 (js2-unget-token)
7576 (if follows-eol
7577 js2-EOL
7578 tt)))
7579
7580 (defun js2-must-match (token msg-id &optional pos len)
7581 "Match next token to token code TOKEN, or record a syntax error.
7582 MSG-ID is the error message to report if the match fails.
7583 Returns t on match, nil if no match."
7584 (if (js2-match-token token t)
7585 t
7586 (js2-report-error msg-id nil pos len)
7587 (js2-unget-token)
7588 nil))
7589
7590 (defun js2-must-match-name (msg-id)
7591 (if (js2-match-token js2-NAME t)
7592 t
7593 (if (eq (js2-current-token-type) js2-RESERVED)
7594 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7595 (js2-report-error msg-id)
7596 (js2-unget-token))
7597 nil))
7598
7599 (defsubst js2-inside-function ()
7600 (cl-plusp js2-nesting-of-function))
7601
7602 (defun js2-set-requires-activation ()
7603 (if (js2-function-node-p js2-current-script-or-fn)
7604 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7605
7606 (defun js2-check-activation-name (name _token)
7607 (when (js2-inside-function)
7608 ;; skip language-version 1.2 check from Rhino
7609 (if (or (string= "arguments" name)
7610 (and js2-compiler-activation-names ; only used in codegen
7611 (gethash name js2-compiler-activation-names)))
7612 (js2-set-requires-activation))))
7613
7614 (defun js2-set-is-generator ()
7615 (let ((fn-node js2-current-script-or-fn))
7616 (when (and (js2-function-node-p fn-node)
7617 (not (js2-function-node-generator-type fn-node)))
7618 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7619
7620 (defun js2-must-have-xml ()
7621 (unless js2-compiler-xml-available
7622 (js2-report-error "msg.XML.not.available")))
7623
7624 (defun js2-push-scope (scope)
7625 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7626 (cl-assert (js2-scope-p scope))
7627 (cl-assert (null (js2-scope-parent-scope scope)))
7628 (cl-assert (not (eq js2-current-scope scope)))
7629 (setf (js2-scope-parent-scope scope) js2-current-scope
7630 js2-current-scope scope))
7631
7632 (defsubst js2-pop-scope ()
7633 (setq js2-current-scope
7634 (js2-scope-parent-scope js2-current-scope)))
7635
7636 (defun js2-enter-loop (loop-node)
7637 (push loop-node js2-loop-set)
7638 (push loop-node js2-loop-and-switch-set)
7639 (js2-push-scope loop-node)
7640 ;; Tell the current labeled statement (if any) its statement,
7641 ;; and set the jump target of the first label to the loop.
7642 ;; These are used in `js2-parse-continue' to verify that the
7643 ;; continue target is an actual labeled loop. (And for codegen.)
7644 (when js2-labeled-stmt
7645 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7646 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7647 js2-labeled-stmt))) loop-node)))
7648
7649 (defun js2-exit-loop ()
7650 (pop js2-loop-set)
7651 (pop js2-loop-and-switch-set)
7652 (js2-pop-scope))
7653
7654 (defsubst js2-enter-switch (switch-node)
7655 (push switch-node js2-loop-and-switch-set))
7656
7657 (defsubst js2-exit-switch ()
7658 (pop js2-loop-and-switch-set))
7659
7660 (defun js2-parse (&optional buf cb)
7661 "Tell the js2 parser to parse a region of JavaScript.
7662
7663 BUF is a buffer or buffer name containing the code to parse.
7664 Call `narrow-to-region' first to parse only part of the buffer.
7665
7666 The returned AST root node is given some additional properties:
7667 `node-count' - total number of nodes in the AST
7668 `buffer' - BUF. The buffer it refers to may change or be killed,
7669 so the value is not necessarily reliable.
7670
7671 An optional callback CB can be specified to report parsing
7672 progress. If `(functionp CB)' returns t, it will be called with
7673 the current line number once before parsing begins, then again
7674 each time the lexer reaches a new line number.
7675
7676 CB can also be a list of the form `(symbol cb ...)' to specify
7677 multiple callbacks with different criteria. Each symbol is a
7678 criterion keyword, and the following element is the callback to
7679 call
7680
7681 :line - called whenever the line number changes
7682 :token - called for each new token consumed
7683
7684 The list of criteria could be extended to include entering or
7685 leaving a statement, an expression, or a function definition."
7686 (if (and cb (not (functionp cb)))
7687 (error "criteria callbacks not yet implemented"))
7688 (let ((inhibit-point-motion-hooks t)
7689 (js2-compiler-xml-available (>= js2-language-version 160))
7690 ;; This is a recursive-descent parser, so give it a big stack.
7691 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7692 (max-specpdl-size (max max-specpdl-size 3000))
7693 (case-fold-search nil)
7694 ast)
7695 (with-current-buffer (or buf (current-buffer))
7696 (setq js2-scanned-comments nil
7697 js2-parsed-errors nil
7698 js2-parsed-warnings nil
7699 js2-imenu-recorder nil
7700 js2-imenu-function-map nil
7701 js2-label-set nil)
7702 (js2-init-scanner)
7703 (setq ast (js2-do-parse))
7704 (unless js2-ts-hit-eof
7705 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7706 (setf (js2-ast-root-errors ast) js2-parsed-errors
7707 (js2-ast-root-warnings ast) js2-parsed-warnings)
7708 ;; if we didn't find any declarations, put a dummy in this list so we
7709 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7710 (unless js2-imenu-recorder
7711 (setq js2-imenu-recorder 'empty))
7712 (run-hooks 'js2-parse-finished-hook)
7713 ast)))
7714
7715 ;; Corresponds to Rhino's Parser.parse() method.
7716 (defun js2-do-parse ()
7717 "Parse current buffer starting from current point.
7718 Scanner should be initialized."
7719 (let ((pos js2-ts-cursor)
7720 (end js2-ts-cursor) ; in case file is empty
7721 root n tt)
7722 ;; initialize buffer-local parsing vars
7723 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7724 js2-current-script-or-fn root
7725 js2-current-scope root
7726 js2-nesting-of-function 0
7727 js2-labeled-stmt nil
7728 js2-recorded-identifiers nil) ; for js2-highlight
7729 (while (/= (setq tt (js2-get-token)) js2-EOF)
7730 (if (= tt js2-FUNCTION)
7731 (progn
7732 (setq n (if js2-called-by-compile-function
7733 (js2-parse-function-expr)
7734 (js2-parse-function-stmt))))
7735 ;; not a function - parse a statement
7736 (js2-unget-token)
7737 (setq n (js2-parse-statement)))
7738 ;; add function or statement to script
7739 (setq end (js2-node-end n))
7740 (js2-block-node-push root n))
7741 ;; add comments to root in lexical order
7742 (when js2-scanned-comments
7743 ;; if we find a comment beyond end of normal kids, use its end
7744 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7745 (dolist (comment js2-scanned-comments)
7746 (push comment (js2-ast-root-comments root))
7747 (js2-node-add-children root comment)))
7748 (setf (js2-node-len root) (- end pos))
7749 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7750 ;; Give extensions a chance to muck with things before highlighting starts.
7751 (let ((js2-additional-externs js2-additional-externs))
7752 (save-excursion
7753 (run-hooks 'js2-post-parse-callbacks))
7754 (js2-highlight-undeclared-vars))
7755 root))
7756
7757 (defun js2-parse-function-closure-body (fn-node)
7758 "Parse a JavaScript 1.8 function closure body."
7759 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7760 (if js2-ts-hit-eof
7761 (js2-report-error "msg.no.brace.body" nil
7762 (js2-node-pos fn-node)
7763 (- js2-ts-cursor (js2-node-pos fn-node)))
7764 (js2-node-add-children fn-node
7765 (setf (js2-function-node-body fn-node)
7766 (js2-parse-expr t))))))
7767
7768 (defun js2-parse-function-body (fn-node)
7769 (js2-must-match js2-LC "msg.no.brace.body"
7770 (js2-node-pos fn-node)
7771 (- js2-ts-cursor (js2-node-pos fn-node)))
7772 (let ((pos (js2-current-token-beg)) ; LC position
7773 (pn (make-js2-block-node)) ; starts at LC position
7774 tt
7775 end)
7776 (cl-incf js2-nesting-of-function)
7777 (unwind-protect
7778 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7779 (= tt js2-EOF)
7780 (= tt js2-RC)))
7781 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7782 (js2-parse-statement)
7783 (js2-get-token)
7784 (js2-parse-function-stmt))))
7785 (cl-decf js2-nesting-of-function))
7786 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7787 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7788 (setq end (js2-current-token-end)))
7789 (setf (js2-node-pos pn) pos
7790 (js2-node-len pn) (- end pos))
7791 (setf (js2-function-node-body fn-node) pn)
7792 (js2-node-add-children fn-node pn)
7793 pn))
7794
7795 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7796 "Declare and fontify destructuring parameters inside NODE.
7797 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7798 (cond
7799 ((js2-name-node-p node)
7800 (let (leftpos)
7801 (js2-define-symbol decl-type (js2-name-node-name node)
7802 node ignore-not-in-block)
7803 (when face
7804 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7805 (+ leftpos (js2-node-len node))
7806 face 'record))))
7807 ((js2-object-node-p node)
7808 (dolist (elem (js2-object-node-elems node))
7809 (js2-define-destruct-symbols
7810 ;; In abbreviated destructuring {a, b}, right == left.
7811 (js2-object-prop-node-right elem)
7812 decl-type face ignore-not-in-block)))
7813 ((js2-array-node-p node)
7814 (dolist (elem (js2-array-node-elems node))
7815 (when elem
7816 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7817 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7818 (js2-node-len node)))))
7819
7820 (defun js2-parse-function-params (function-type fn-node pos)
7821 (if (js2-match-token js2-RP)
7822 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7823 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7824 (eq (js2-current-token-type) js2-NAME)))
7825 params param default-found rest-param-at)
7826 (when paren-free-arrow
7827 (js2-unget-token))
7828 (cl-loop for tt = (js2-peek-token)
7829 do
7830 (cond
7831 ;; destructuring param
7832 ((and (not paren-free-arrow)
7833 (or (= tt js2-LB) (= tt js2-LC)))
7834 (js2-get-token)
7835 (when default-found
7836 (js2-report-error "msg.no.default.after.default.param"))
7837 (setq param (js2-parse-destruct-primary-expr))
7838 (js2-define-destruct-symbols param
7839 js2-LP
7840 'js2-function-param)
7841 (push param params))
7842 ;; variable name
7843 (t
7844 (when (and (>= js2-language-version 200)
7845 (not paren-free-arrow)
7846 (js2-match-token js2-TRIPLEDOT)
7847 (not rest-param-at))
7848 ;; to report errors if there are more parameters
7849 (setq rest-param-at (length params)))
7850 (js2-must-match-name "msg.no.parm")
7851 (js2-record-face 'js2-function-param)
7852 (setq param (js2-create-name-node))
7853 (js2-define-symbol js2-LP (js2-current-token-string) param)
7854 ;; default parameter value
7855 (when (or (and default-found
7856 (not rest-param-at)
7857 (js2-must-match js2-ASSIGN
7858 "msg.no.default.after.default.param"
7859 (js2-node-pos param)
7860 (js2-node-len param)))
7861 (and (>= js2-language-version 200)
7862 (js2-match-token js2-ASSIGN)))
7863 (cl-assert (not paren-free-arrow))
7864 (let* ((pos (js2-node-pos param))
7865 (tt (js2-current-token-type))
7866 (op-pos (- (js2-current-token-beg) pos))
7867 (left param)
7868 (right (js2-parse-assign-expr))
7869 (len (- (js2-node-end right) pos)))
7870 (setq param (make-js2-assign-node
7871 :type tt :pos pos :len len :op-pos op-pos
7872 :left left :right right)
7873 default-found t)
7874 (js2-node-add-children param left right)))
7875 (push param params)))
7876 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7877 (js2-report-error "msg.param.after.rest" nil
7878 (js2-node-pos param) (js2-node-len param)))
7879 while
7880 (js2-match-token js2-COMMA))
7881 (when (and (not paren-free-arrow)
7882 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7883 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7884 (when rest-param-at
7885 (setf (js2-function-node-rest-p fn-node) t))
7886 (dolist (p params)
7887 (js2-node-add-children fn-node p)
7888 (push p (js2-function-node-params fn-node))))))
7889
7890 (defun js2-check-inconsistent-return-warning (fn-node name)
7891 "Possibly show inconsistent-return warning.
7892 Last token scanned is the close-curly for the function body."
7893 (when (and js2-mode-show-strict-warnings
7894 js2-strict-inconsistent-return-warning
7895 (not (js2-has-consistent-return-usage
7896 (js2-function-node-body fn-node))))
7897 ;; Have it extend from close-curly to bol or beginning of block.
7898 (let ((pos (save-excursion
7899 (goto-char (js2-current-token-end))
7900 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7901 (point-at-bol))))
7902 (end (js2-current-token-end)))
7903 (if (cl-plusp (js2-name-node-length name))
7904 (js2-add-strict-warning "msg.no.return.value"
7905 (js2-name-node-name name) pos end)
7906 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7907
7908 (defun js2-parse-function-stmt ()
7909 (let ((pos (js2-current-token-beg))
7910 (star-p (js2-match-token js2-MUL)))
7911 (js2-must-match-name "msg.unnamed.function.stmt")
7912 (let ((name (js2-create-name-node t))
7913 pn member-expr)
7914 (cond
7915 ((js2-match-token js2-LP)
7916 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7917 (js2-allow-member-expr-as-function-name
7918 (setq member-expr (js2-parse-member-expr-tail nil name))
7919 (js2-parse-highlight-member-expr-fn-name member-expr)
7920 (js2-must-match js2-LP "msg.no.paren.parms")
7921 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7922 (js2-function-node-member-expr pn) member-expr)
7923 pn)
7924 (t
7925 (js2-report-error "msg.no.paren.parms")
7926 (make-js2-error-node))))))
7927
7928 (defun js2-parse-function-expr ()
7929 (let ((pos (js2-current-token-beg))
7930 (star-p (js2-match-token js2-MUL))
7931 name)
7932 (when (js2-match-token js2-NAME)
7933 (setq name (js2-create-name-node t)))
7934 (js2-must-match js2-LP "msg.no.paren.parms")
7935 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7936
7937 (defun js2-parse-function (function-type pos star-p &optional name)
7938 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7939 beginning of the first token (function keyword, unless it's an
7940 arrow function), NAME is js2-name-node."
7941 (let (fn-node lp)
7942 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7943 (setq lp (js2-current-token-beg)))
7944 (setf fn-node (make-js2-function-node :pos pos
7945 :name name
7946 :form function-type
7947 :lp (if lp (- lp pos))
7948 :generator-type (and star-p 'STAR)))
7949 (when name
7950 (js2-set-face (js2-node-pos name) (js2-node-end name)
7951 'font-lock-function-name-face 'record)
7952 (when (and (eq function-type 'FUNCTION_STATEMENT)
7953 (cl-plusp (js2-name-node-length name)))
7954 ;; Function statements define a symbol in the enclosing scope
7955 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7956 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
7957 ;; 1. Nested functions are not affected by the dynamic scope flag
7958 ;; as dynamic scope is already a parent of their scope.
7959 ;; 2. Functions defined under the with statement also immune to
7960 ;; this setup, in which case dynamic scope is ignored in favor
7961 ;; of the with object.
7962 (setf (js2-function-node-ignore-dynamic fn-node) t))
7963 ;; dynamically bind all the per-function variables
7964 (let ((js2-current-script-or-fn fn-node)
7965 (js2-current-scope fn-node)
7966 (js2-nesting-of-with 0)
7967 (js2-end-flags 0)
7968 js2-label-set
7969 js2-loop-set
7970 js2-loop-and-switch-set)
7971 (js2-parse-function-params function-type fn-node pos)
7972 (when (eq function-type 'FUNCTION_ARROW)
7973 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7974 (if (and (>= js2-language-version 180)
7975 (/= (js2-peek-token) js2-LC))
7976 (js2-parse-function-closure-body fn-node)
7977 (js2-parse-function-body fn-node))
7978 (js2-check-inconsistent-return-warning fn-node name)
7979
7980 (when name
7981 (js2-node-add-children fn-node name)
7982 ;; Function expressions define a name only in the body of the
7983 ;; function, and only if not hidden by a parameter name
7984 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7985 (null (js2-scope-get-symbol js2-current-scope
7986 (js2-name-node-name name))))
7987 (js2-define-symbol js2-FUNCTION
7988 (js2-name-node-name name)
7989 fn-node))
7990 (when (eq function-type 'FUNCTION_STATEMENT)
7991 (js2-record-imenu-functions fn-node))))
7992
7993 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7994 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7995 ;; We wait until after parsing the function to set its parent scope,
7996 ;; since `js2-define-symbol' needs the defining-scope check to stop
7997 ;; at the function boundary when checking for redeclarations.
7998 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7999 fn-node))
8000
8001 (defun js2-parse-statements (&optional parent)
8002 "Parse a statement list. Last token consumed must be js2-LC.
8003
8004 PARENT can be a `js2-block-node', in which case the statements are
8005 appended to PARENT. Otherwise a new `js2-block-node' is created
8006 and returned.
8007
8008 This function does not match the closing js2-RC: the caller
8009 matches the RC so it can provide a suitable error message if not
8010 matched. This means it's up to the caller to set the length of
8011 the node to include the closing RC. The node start pos is set to
8012 the absolute buffer start position, and the caller should fix it
8013 up to be relative to the parent node. All children of this block
8014 node are given relative start positions and correct lengths."
8015 (let ((pn (or parent (make-js2-block-node)))
8016 tt)
8017 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8018 (/= tt js2-RC))
8019 (js2-block-node-push pn (js2-parse-statement)))
8020 pn))
8021
8022 (defun js2-parse-statement ()
8023 (let (pn beg end)
8024 ;; coarse-grained user-interrupt check - needs work
8025 (and js2-parse-interruptable-p
8026 (zerop (% (cl-incf js2-parse-stmt-count)
8027 js2-statements-per-pause))
8028 (input-pending-p)
8029 (throw 'interrupted t))
8030 (setq pn (js2-statement-helper))
8031 ;; no-side-effects warning check
8032 (unless (js2-node-has-side-effects pn)
8033 (setq end (js2-node-end pn))
8034 (save-excursion
8035 (goto-char end)
8036 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8037 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8038 pn))
8039
8040 ;; These correspond to the switch cases in Parser.statementHelper
8041 (defconst js2-parsers
8042 (let ((parsers (make-vector js2-num-tokens
8043 #'js2-parse-expr-stmt)))
8044 (aset parsers js2-BREAK #'js2-parse-break)
8045 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8046 (aset parsers js2-CONST #'js2-parse-const-var)
8047 (aset parsers js2-CONTINUE #'js2-parse-continue)
8048 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8049 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8050 (aset parsers js2-DO #'js2-parse-do)
8051 (aset parsers js2-EXPORT #'js2-parse-export)
8052 (aset parsers js2-FOR #'js2-parse-for)
8053 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8054 (aset parsers js2-IF #'js2-parse-if)
8055 (aset parsers js2-IMPORT #'js2-parse-import)
8056 (aset parsers js2-LC #'js2-parse-block)
8057 (aset parsers js2-LET #'js2-parse-let-stmt)
8058 (aset parsers js2-NAME #'js2-parse-name-or-label)
8059 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8060 (aset parsers js2-SEMI #'js2-parse-semi)
8061 (aset parsers js2-SWITCH #'js2-parse-switch)
8062 (aset parsers js2-THROW #'js2-parse-throw)
8063 (aset parsers js2-TRY #'js2-parse-try)
8064 (aset parsers js2-VAR #'js2-parse-const-var)
8065 (aset parsers js2-WHILE #'js2-parse-while)
8066 (aset parsers js2-WITH #'js2-parse-with)
8067 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8068 parsers)
8069 "A vector mapping token types to parser functions.")
8070
8071 (defun js2-parse-warn-missing-semi (beg end)
8072 (and js2-mode-show-strict-warnings
8073 js2-strict-missing-semi-warning
8074 (js2-add-strict-warning
8075 "msg.missing.semi" nil
8076 ;; back up to beginning of statement or line
8077 (max beg (save-excursion
8078 (goto-char end)
8079 (point-at-bol)))
8080 end)))
8081
8082 (defconst js2-no-semi-insertion
8083 (list js2-IF
8084 js2-SWITCH
8085 js2-WHILE
8086 js2-DO
8087 js2-FOR
8088 js2-TRY
8089 js2-WITH
8090 js2-LC
8091 js2-ERROR
8092 js2-SEMI
8093 js2-CLASS
8094 js2-FUNCTION)
8095 "List of tokens that don't do automatic semicolon insertion.")
8096
8097 (defconst js2-autoinsert-semi-and-warn
8098 (list js2-ERROR js2-EOF js2-RC))
8099
8100 (defun js2-statement-helper ()
8101 (let* ((tt (js2-get-token))
8102 (first-tt tt)
8103 (parser (if (= tt js2-ERROR)
8104 #'js2-parse-semi
8105 (aref js2-parsers tt)))
8106 pn)
8107 ;; If the statement is set, then it's been told its label by now.
8108 (and js2-labeled-stmt
8109 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8110 (setq js2-labeled-stmt nil))
8111 (setq pn (funcall parser))
8112 ;; Don't do auto semi insertion for certain statement types.
8113 (unless (or (memq first-tt js2-no-semi-insertion)
8114 (js2-labeled-stmt-node-p pn))
8115 (js2-auto-insert-semicolon pn))
8116 pn))
8117
8118 (defun js2-auto-insert-semicolon (pn)
8119 (let* ((tt (js2-get-token))
8120 (pos (js2-node-pos pn)))
8121 (cond
8122 ((= tt js2-SEMI)
8123 ;; extend the node bounds to include the semicolon.
8124 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8125 ((memq tt js2-autoinsert-semi-and-warn)
8126 (js2-unget-token) ; Not ';', do not consume.
8127 ;; Autoinsert ;
8128 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8129 (t
8130 (if (not (js2-token-follows-eol-p (js2-current-token)))
8131 ;; Report error if no EOL or autoinsert ';' otherwise
8132 (js2-report-error "msg.no.semi.stmt")
8133 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8134 (js2-unget-token) ; Not ';', do not consume.
8135 ))))
8136
8137 (defun js2-parse-condition ()
8138 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8139 The parens are discarded and the expression node is returned.
8140 The `pos' field of the return value is set to an absolute position
8141 that must be fixed up by the caller.
8142 Return value is a list (EXPR LP RP), with absolute paren positions."
8143 (let (pn lp rp)
8144 (if (js2-must-match js2-LP "msg.no.paren.cond")
8145 (setq lp (js2-current-token-beg)))
8146 (setq pn (js2-parse-expr))
8147 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8148 (setq rp (js2-current-token-beg)))
8149 ;; Report strict warning on code like "if (a = 7) ..."
8150 (if (and js2-strict-cond-assign-warning
8151 (js2-assign-node-p pn))
8152 (js2-add-strict-warning "msg.equal.as.assign" nil
8153 (js2-node-pos pn)
8154 (+ (js2-node-pos pn)
8155 (js2-node-len pn))))
8156 (list pn lp rp)))
8157
8158 (defun js2-parse-if ()
8159 "Parser for if-statement. Last matched token must be js2-IF."
8160 (let ((pos (js2-current-token-beg))
8161 cond if-true if-false else-pos end pn)
8162 (setq cond (js2-parse-condition)
8163 if-true (js2-parse-statement)
8164 if-false (if (js2-match-token js2-ELSE)
8165 (progn
8166 (setq else-pos (- (js2-current-token-beg) pos))
8167 (js2-parse-statement)))
8168 end (js2-node-end (or if-false if-true))
8169 pn (make-js2-if-node :pos pos
8170 :len (- end pos)
8171 :condition (car cond)
8172 :then-part if-true
8173 :else-part if-false
8174 :else-pos else-pos
8175 :lp (js2-relpos (cl-second cond) pos)
8176 :rp (js2-relpos (cl-third cond) pos)))
8177 (js2-node-add-children pn (car cond) if-true if-false)
8178 pn))
8179
8180 (defun js2-parse-import ()
8181 "Parse import statement. The current token must be js2-IMPORT."
8182 (unless (js2-ast-root-p js2-current-scope)
8183 (js2-report-error "msg.mod.import.decl.at.top.level"))
8184 (let ((beg (js2-current-token-beg)))
8185 (cond ((js2-match-token js2-STRING)
8186 (make-js2-import-node
8187 :pos beg
8188 :len (- (js2-current-token-end) beg)
8189 :module-id (js2-current-token-string)))
8190 (t
8191 (let* ((import-clause (js2-parse-import-clause))
8192 (from-clause (and import-clause (js2-parse-from-clause)))
8193 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8194 (node (make-js2-import-node
8195 :pos beg
8196 :len (- (js2-current-token-end) beg)
8197 :import import-clause
8198 :from from-clause
8199 :module-id module-id)))
8200 (when import-clause
8201 (js2-node-add-children node import-clause))
8202 (when from-clause
8203 (js2-node-add-children node from-clause))
8204 node)))))
8205
8206 (defun js2-parse-import-clause ()
8207 "Parse the bindings in an import statement.
8208 This can take many forms:
8209
8210 ImportedDefaultBinding -> 'foo'
8211 NameSpaceImport -> '* as lib'
8212 NamedImports -> '{foo as bar, bang}'
8213 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8214 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8215
8216 Try to match namespace imports and named imports first because nothing can
8217 come after them. If it is an imported default binding, then it could have named
8218 imports or a namespace import that follows it.
8219 "
8220 (let* ((beg (js2-current-token-beg))
8221 (clause (make-js2-import-clause-node
8222 :pos beg))
8223 (children (list)))
8224 (cond
8225 ((js2-match-token js2-MUL)
8226 (let ((ns-import (js2-parse-namespace-import)))
8227 (when ns-import
8228 (let ((name-node (js2-namespace-import-node-name ns-import)))
8229 (js2-define-symbol
8230 js2-LET (js2-name-node-name name-node) name-node t)))
8231 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8232 (push ns-import children)))
8233 ((js2-match-token js2-LC)
8234 (let ((imports (js2-parse-export-bindings t)))
8235 (setf (js2-import-clause-node-named-imports clause) imports)
8236 (dolist (import imports)
8237 (push import children)
8238 (let ((name-node (js2-export-binding-node-local-name import)))
8239 (when name-node
8240 (js2-define-symbol
8241 js2-LET (js2-name-node-name name-node) name-node t))))))
8242 ((= (js2-peek-token) js2-NAME)
8243 (let ((binding (js2-maybe-parse-export-binding)))
8244 (let ((node-name (js2-export-binding-node-local-name binding)))
8245 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8246 (setf (js2-import-clause-node-default-binding clause) binding)
8247 (push binding children))
8248 (when (js2-match-token js2-COMMA)
8249 (cond
8250 ((js2-match-token js2-MUL)
8251 (let ((ns-import (js2-parse-namespace-import)))
8252 (let ((name-node (js2-namespace-import-node-name ns-import)))
8253 (js2-define-symbol
8254 js2-LET (js2-name-node-name name-node) name-node t))
8255 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8256 (push ns-import children)))
8257 ((js2-match-token js2-LC)
8258 (let ((imports (js2-parse-export-bindings t)))
8259 (setf (js2-import-clause-node-named-imports clause) imports)
8260 (dolist (import imports)
8261 (push import children)
8262 (let ((name-node (js2-export-binding-node-local-name import)))
8263 (when name-node
8264 (js2-define-symbol
8265 js2-LET (js2-name-node-name name-node) name-node t))))))
8266 (t (js2-report-error "msg.syntax")))))
8267 (t (js2-report-error "msg.mod.declaration.after.import")))
8268 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8269 (apply #'js2-node-add-children clause children)
8270 clause))
8271
8272 (defun js2-parse-namespace-import ()
8273 "Parse a namespace import expression such as '* as bar'.
8274 The current token must be js2-MUL."
8275 (let ((beg (js2-current-token-beg)))
8276 (when (js2-must-match js2-NAME "msg.syntax")
8277 (if (equal "as" (js2-current-token-string))
8278 (when (js2-must-match-prop-name "msg.syntax")
8279 (let ((node (make-js2-namespace-import-node
8280 :pos beg
8281 :len (- (js2-current-token-end) beg)
8282 :name (make-js2-name-node
8283 :pos (js2-current-token-beg)
8284 :len (js2-current-token-end)
8285 :name (js2-current-token-string)))))
8286 (js2-node-add-children node (js2-namespace-import-node-name node))
8287 node))
8288 (js2-unget-token)
8289 (js2-report-error "msg.syntax")))))
8290
8291
8292 (defun js2-parse-from-clause ()
8293 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8294 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8295 (let ((beg (js2-current-token-beg)))
8296 (if (equal "from" (js2-current-token-string))
8297 (cond
8298 ((js2-match-token js2-STRING)
8299 (make-js2-from-clause-node
8300 :pos beg
8301 :len (- (js2-current-token-end) beg)
8302 :module-id (js2-current-token-string)
8303 :metadata-p nil))
8304 ((js2-match-token js2-THIS)
8305 (when (js2-must-match-name "msg.mod.spec.after.from")
8306 (if (equal "module" (js2-current-token-string))
8307 (make-js2-from-clause-node
8308 :pos beg
8309 :len (- (js2-current-token-end) beg)
8310 :module-id "this"
8311 :metadata-p t)
8312 (js2-unget-token)
8313 (js2-unget-token)
8314 (js2-report-error "msg.mod.spec.after.from")
8315 nil)))
8316 (t (js2-report-error "msg.mod.spec.after.from") nil))
8317 (js2-unget-token)
8318 (js2-report-error "msg.mod.from.after.import.spec.set")
8319 nil))))
8320
8321 (defun js2-parse-export-bindings (&optional import-p)
8322 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8323 {foo as bar, baz as bang}. The current token must be
8324 js2-LC. Return a lisp list of js2-export-binding-node"
8325 (let ((bindings (list)))
8326 (while
8327 (let ((binding (js2-maybe-parse-export-binding)))
8328 (when binding
8329 (push binding bindings))
8330 (js2-match-token js2-COMMA)))
8331 (when (js2-must-match js2-RC (if import-p
8332 "msg.mod.rc.after.import.spec.list"
8333 "msg.mod.rc.after.export.spec.list"))
8334 (reverse bindings))))
8335
8336 (defun js2-maybe-parse-export-binding ()
8337 "Attempt to parse a binding expression found inside an import/export statement.
8338 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8339 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8340 js2-export-binding-node and consume all the tokens. If it does not match, it
8341 consumes no tokens."
8342 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8343 (beg (js2-current-token-beg))
8344 (extern-name-len (js2-current-token-len))
8345 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8346 (aref js2-kwd-tokens (js2-current-token-type)))))
8347 (if extern-name
8348 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8349 (if (and as (equal "as" (js2-current-token-string)))
8350 (let ((name
8351 (or
8352 (and (js2-match-token js2-DEFAULT) "default")
8353 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8354 (if name
8355 (let ((node (make-js2-export-binding-node
8356 :pos beg
8357 :len (- (js2-current-token-end) beg)
8358 :local-name (make-js2-name-node
8359 :name name
8360 :pos (js2-current-token-beg)
8361 :len (js2-current-token-len))
8362 :extern-name (make-js2-name-node
8363 :name extern-name
8364 :pos beg
8365 :len extern-name-len))))
8366 (js2-node-add-children
8367 node
8368 (js2-export-binding-node-local-name node)
8369 (js2-export-binding-node-extern-name node))
8370 node)
8371 (js2-unget-token)
8372 nil))
8373 (when as (js2-unget-token))
8374 (let* ((name-node (make-js2-name-node
8375 :name (js2-current-token-string)
8376 :pos (js2-current-token-beg)
8377 :len (js2-current-token-len)))
8378 (node (make-js2-export-binding-node
8379 :pos (js2-current-token-beg)
8380 :len (js2-current-token-len)
8381 :local-name name-node
8382 :extern-name name-node)))
8383 (when is-reserved-name
8384 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8385 (js2-node-add-children node name-node)
8386 node)))
8387 nil)))
8388
8389 (defun js2-parse-switch ()
8390 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8391 (let ((pos (js2-current-token-beg))
8392 tt pn discriminant has-default case-expr case-node
8393 case-pos cases stmt lp)
8394 (if (js2-must-match js2-LP "msg.no.paren.switch")
8395 (setq lp (js2-current-token-beg)))
8396 (setq discriminant (js2-parse-expr)
8397 pn (make-js2-switch-node :discriminant discriminant
8398 :pos pos
8399 :lp (js2-relpos lp pos)))
8400 (js2-node-add-children pn discriminant)
8401 (js2-enter-switch pn)
8402 (unwind-protect
8403 (progn
8404 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8405 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8406 (js2-must-match js2-LC "msg.no.brace.switch")
8407 (catch 'break
8408 (while t
8409 (setq tt (js2-next-token)
8410 case-pos (js2-current-token-beg))
8411 (cond
8412 ((= tt js2-RC)
8413 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8414 (throw 'break nil)) ; done
8415 ((= tt js2-CASE)
8416 (setq case-expr (js2-parse-expr))
8417 (js2-must-match js2-COLON "msg.no.colon.case"))
8418 ((= tt js2-DEFAULT)
8419 (if has-default
8420 (js2-report-error "msg.double.switch.default"))
8421 (setq has-default t
8422 case-expr nil)
8423 (js2-must-match js2-COLON "msg.no.colon.case"))
8424 (t
8425 (js2-report-error "msg.bad.switch")
8426 (throw 'break nil)))
8427 (setq case-node (make-js2-case-node :pos case-pos
8428 :len (- (js2-current-token-end) case-pos)
8429 :expr case-expr))
8430 (js2-node-add-children case-node case-expr)
8431 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8432 (/= tt js2-CASE)
8433 (/= tt js2-DEFAULT)
8434 (/= tt js2-EOF))
8435 (setf stmt (js2-parse-statement)
8436 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8437 (js2-block-node-push case-node stmt))
8438 (push case-node cases)))
8439 ;; add cases last, as pushing reverses the order to be correct
8440 (dolist (kid cases)
8441 (js2-node-add-children pn kid)
8442 (push kid (js2-switch-node-cases pn)))
8443 pn) ; return value
8444 (js2-exit-switch))))
8445
8446 (defun js2-parse-while ()
8447 "Parser for while-statement. Last matched token must be js2-WHILE."
8448 (let ((pos (js2-current-token-beg))
8449 (pn (make-js2-while-node))
8450 cond body)
8451 (js2-enter-loop pn)
8452 (unwind-protect
8453 (progn
8454 (setf cond (js2-parse-condition)
8455 (js2-while-node-condition pn) (car cond)
8456 body (js2-parse-statement)
8457 (js2-while-node-body pn) body
8458 (js2-node-len pn) (- (js2-node-end body) pos)
8459 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8460 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8461 (js2-node-add-children pn body (car cond)))
8462 (js2-exit-loop))
8463 pn))
8464
8465 (defun js2-parse-do ()
8466 "Parser for do-statement. Last matched token must be js2-DO."
8467 (let ((pos (js2-current-token-beg))
8468 (pn (make-js2-do-node))
8469 cond body end)
8470 (js2-enter-loop pn)
8471 (unwind-protect
8472 (progn
8473 (setq body (js2-parse-statement))
8474 (js2-must-match js2-WHILE "msg.no.while.do")
8475 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8476 cond (js2-parse-condition)
8477 (js2-do-node-condition pn) (car cond)
8478 (js2-do-node-body pn) body
8479 end js2-ts-cursor
8480 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8481 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8482 (js2-node-add-children pn (car cond) body))
8483 (js2-exit-loop))
8484 ;; Always auto-insert semicolon to follow SpiderMonkey:
8485 ;; It is required by ECMAScript but is ignored by the rest of
8486 ;; world; see bug 238945
8487 (if (js2-match-token js2-SEMI)
8488 (setq end js2-ts-cursor))
8489 (setf (js2-node-len pn) (- end pos))
8490 pn))
8491
8492 (defun js2-parse-export ()
8493 "Parse an export statement.
8494 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8495 expressions should only be either hoistable expressions (function or generator)
8496 or assignment expressions, but there is no checking to enforce that and so it
8497 will parse without error a small subset of
8498 invalid export statements."
8499 (unless (js2-ast-root-p js2-current-scope)
8500 (js2-report-error "msg.mod.export.decl.at.top.level"))
8501 (let ((beg (js2-current-token-beg))
8502 (children (list))
8503 exports-list from-clause declaration default)
8504 (cond
8505 ((js2-match-token js2-MUL)
8506 (setq from-clause (js2-parse-from-clause))
8507 (when from-clause
8508 (push from-clause children)))
8509 ((js2-match-token js2-LC)
8510 (setq exports-list (js2-parse-export-bindings))
8511 (when exports-list
8512 (dolist (export exports-list)
8513 (push export children)))
8514 (when (js2-match-token js2-NAME)
8515 (if (equal "from" (js2-current-token-string))
8516 (progn
8517 (js2-unget-token)
8518 (setq from-clause (js2-parse-from-clause)))
8519 (js2-unget-token))))
8520 ((js2-match-token js2-DEFAULT)
8521 (setq default (js2-parse-expr)))
8522 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8523 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8524 (t
8525 (setq declaration (js2-parse-expr))))
8526 (when from-clause
8527 (push from-clause children))
8528 (when declaration
8529 (push declaration children))
8530 (when default
8531 (push default children))
8532 (let ((node (make-js2-export-node
8533 :pos beg
8534 :len (- (js2-current-token-end) beg)
8535 :exports-list exports-list
8536 :from-clause from-clause
8537 :declaration declaration
8538 :default default)))
8539 (apply #'js2-node-add-children node children)
8540 node)))
8541
8542 (defun js2-parse-for ()
8543 "Parse a for, for-in or for each-in statement.
8544 Last matched token must be js2-FOR."
8545 (let ((for-pos (js2-current-token-beg))
8546 pn is-for-each is-for-in-or-of is-for-of
8547 in-pos each-pos tmp-pos
8548 init ; Node init is also foo in 'foo in object'.
8549 cond ; Node cond is also object in 'foo in object'.
8550 incr ; 3rd section of for-loop initializer.
8551 body tt lp rp)
8552 ;; See if this is a for each () instead of just a for ()
8553 (when (js2-match-token js2-NAME)
8554 (if (string= "each" (js2-current-token-string))
8555 (progn
8556 (setq is-for-each t
8557 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8558 (js2-record-face 'font-lock-keyword-face))
8559 (js2-report-error "msg.no.paren.for")))
8560 (if (js2-must-match js2-LP "msg.no.paren.for")
8561 (setq lp (- (js2-current-token-beg) for-pos)))
8562 (setq tt (js2-get-token))
8563 ;; 'for' makes local scope
8564 (js2-push-scope (make-js2-scope))
8565 (unwind-protect
8566 ;; parse init clause
8567 (let ((js2-in-for-init t)) ; set as dynamic variable
8568 (cond
8569 ((= tt js2-SEMI)
8570 (js2-unget-token)
8571 (setq init (make-js2-empty-expr-node)))
8572 ((or (= tt js2-VAR) (= tt js2-LET))
8573 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8574 (t
8575 (js2-unget-token)
8576 (setq init (js2-parse-expr)))))
8577 (if (or (js2-match-token js2-IN)
8578 (and (>= js2-language-version 200)
8579 (js2-match-contextual-kwd "of")
8580 (setq is-for-of t)))
8581 (setq is-for-in-or-of t
8582 in-pos (- (js2-current-token-beg) for-pos)
8583 ;; scope of iteration target object is not the scope we've created above.
8584 ;; stash current scope temporary.
8585 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8586 (js2-parse-expr))) ; object over which we're iterating
8587 ;; else ordinary for loop - parse cond and incr
8588 (js2-must-match js2-SEMI "msg.no.semi.for")
8589 (setq cond (if (= (js2-peek-token) js2-SEMI)
8590 (make-js2-empty-expr-node) ; no loop condition
8591 (js2-parse-expr)))
8592 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8593 (setq tmp-pos (js2-current-token-end)
8594 incr (if (= (js2-peek-token) js2-RP)
8595 (make-js2-empty-expr-node :pos tmp-pos)
8596 (js2-parse-expr))))
8597 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8598 (setq rp (- (js2-current-token-beg) for-pos)))
8599 (if (not is-for-in-or-of)
8600 (setq pn (make-js2-for-node :init init
8601 :condition cond
8602 :update incr
8603 :lp lp
8604 :rp rp))
8605 ;; cond could be null if 'in obj' got eaten by the init node.
8606 (if (js2-infix-node-p init)
8607 ;; it was (foo in bar) instead of (var foo in bar)
8608 (setq cond (js2-infix-node-right init)
8609 init (js2-infix-node-left init))
8610 (if (and (js2-var-decl-node-p init)
8611 (> (length (js2-var-decl-node-kids init)) 1))
8612 (js2-report-error "msg.mult.index")))
8613 (setq pn (make-js2-for-in-node :iterator init
8614 :object cond
8615 :in-pos in-pos
8616 :foreach-p is-for-each
8617 :each-pos each-pos
8618 :forof-p is-for-of
8619 :lp lp
8620 :rp rp)))
8621 (unwind-protect
8622 (progn
8623 (js2-enter-loop pn)
8624 ;; We have to parse the body -after- creating the loop node,
8625 ;; so that the loop node appears in the js2-loop-set, allowing
8626 ;; break/continue statements to find the enclosing loop.
8627 (setf body (js2-parse-statement)
8628 (js2-loop-node-body pn) body
8629 (js2-node-pos pn) for-pos
8630 (js2-node-len pn) (- (js2-node-end body) for-pos))
8631 (js2-node-add-children pn init cond incr body))
8632 ;; finally
8633 (js2-exit-loop))
8634 (js2-pop-scope))
8635 pn))
8636
8637 (defun js2-parse-try ()
8638 "Parse a try statement. Last matched token must be js2-TRY."
8639 (let ((try-pos (js2-current-token-beg))
8640 try-end
8641 try-block
8642 catch-blocks
8643 finally-block
8644 saw-default-catch
8645 peek)
8646 (if (/= (js2-peek-token) js2-LC)
8647 (js2-report-error "msg.no.brace.try"))
8648 (setq try-block (js2-parse-statement)
8649 try-end (js2-node-end try-block)
8650 peek (js2-peek-token))
8651 (cond
8652 ((= peek js2-CATCH)
8653 (while (js2-match-token js2-CATCH)
8654 (let* ((catch-pos (js2-current-token-beg))
8655 (catch-node (make-js2-catch-node :pos catch-pos))
8656 param
8657 guard-kwd
8658 catch-cond
8659 lp rp)
8660 (if saw-default-catch
8661 (js2-report-error "msg.catch.unreachable"))
8662 (if (js2-must-match js2-LP "msg.no.paren.catch")
8663 (setq lp (- (js2-current-token-beg) catch-pos)))
8664 (js2-push-scope catch-node)
8665 (let ((tt (js2-peek-token)))
8666 (cond
8667 ;; Destructuring pattern:
8668 ;; catch ({ message, file }) { ... }
8669 ((or (= tt js2-LB) (= tt js2-LC))
8670 (js2-get-token)
8671 (setq param (js2-parse-destruct-primary-expr))
8672 (js2-define-destruct-symbols param js2-LET nil))
8673 ;; Simple name.
8674 (t
8675 (js2-must-match-name "msg.bad.catchcond")
8676 (setq param (js2-create-name-node))
8677 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8678 ;; Catch condition.
8679 (if (js2-match-token js2-IF)
8680 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8681 catch-cond (js2-parse-expr))
8682 (setq saw-default-catch t))
8683 (if (js2-must-match js2-RP "msg.bad.catchcond")
8684 (setq rp (- (js2-current-token-beg) catch-pos)))
8685 (js2-must-match js2-LC "msg.no.brace.catchblock")
8686 (js2-parse-statements catch-node)
8687 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8688 (setq try-end (js2-current-token-end)))
8689 (js2-pop-scope)
8690 (setf (js2-node-len catch-node) (- try-end catch-pos)
8691 (js2-catch-node-param catch-node) param
8692 (js2-catch-node-guard-expr catch-node) catch-cond
8693 (js2-catch-node-guard-kwd catch-node) guard-kwd
8694 (js2-catch-node-lp catch-node) lp
8695 (js2-catch-node-rp catch-node) rp)
8696 (js2-node-add-children catch-node param catch-cond)
8697 (push catch-node catch-blocks))))
8698 ((/= peek js2-FINALLY)
8699 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8700 (js2-node-pos try-block)
8701 (- (setq try-end (js2-node-end try-block))
8702 (js2-node-pos try-block)))))
8703 (when (js2-match-token js2-FINALLY)
8704 (let ((finally-pos (js2-current-token-beg))
8705 (block (js2-parse-statement)))
8706 (setq try-end (js2-node-end block)
8707 finally-block (make-js2-finally-node :pos finally-pos
8708 :len (- try-end finally-pos)
8709 :body block))
8710 (js2-node-add-children finally-block block)))
8711 (let ((pn (make-js2-try-node :pos try-pos
8712 :len (- try-end try-pos)
8713 :try-block try-block
8714 :finally-block finally-block)))
8715 (js2-node-add-children pn try-block finally-block)
8716 ;; Push them onto the try-node, which reverses and corrects their order.
8717 (dolist (cb catch-blocks)
8718 (js2-node-add-children pn cb)
8719 (push cb (js2-try-node-catch-clauses pn)))
8720 pn)))
8721
8722 (defun js2-parse-throw ()
8723 "Parser for throw-statement. Last matched token must be js2-THROW."
8724 (let ((pos (js2-current-token-beg))
8725 expr pn)
8726 (if (= (js2-peek-token-or-eol) js2-EOL)
8727 ;; ECMAScript does not allow new lines before throw expression,
8728 ;; see bug 256617
8729 (js2-report-error "msg.bad.throw.eol"))
8730 (setq expr (js2-parse-expr)
8731 pn (make-js2-throw-node :pos pos
8732 :len (- (js2-node-end expr) pos)
8733 :expr expr))
8734 (js2-node-add-children pn expr)
8735 pn))
8736
8737 (defun js2-match-jump-label-name (label-name)
8738 "If break/continue specified a label, return that label's labeled stmt.
8739 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8740 does not match an existing label, reports an error and returns nil."
8741 (let ((bundle (cdr (assoc label-name js2-label-set))))
8742 (if (null bundle)
8743 (js2-report-error "msg.undef.label"))
8744 bundle))
8745
8746 (defun js2-parse-break ()
8747 "Parser for break-statement. Last matched token must be js2-BREAK."
8748 (let ((pos (js2-current-token-beg))
8749 (end (js2-current-token-end))
8750 break-target ; statement to break from
8751 break-label ; in "break foo", name-node representing the foo
8752 labels ; matching labeled statement to break to
8753 pn)
8754 (when (eq (js2-peek-token-or-eol) js2-NAME)
8755 (js2-get-token)
8756 (setq break-label (js2-create-name-node)
8757 end (js2-node-end break-label)
8758 ;; matchJumpLabelName only matches if there is one
8759 labels (js2-match-jump-label-name (js2-current-token-string))
8760 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8761 (unless (or break-target break-label)
8762 ;; no break target specified - try for innermost enclosing loop/switch
8763 (if (null js2-loop-and-switch-set)
8764 (unless break-label
8765 (js2-report-error "msg.bad.break" nil pos (length "break")))
8766 (setq break-target (car js2-loop-and-switch-set))))
8767 (setq pn (make-js2-break-node :pos pos
8768 :len (- end pos)
8769 :label break-label
8770 :target break-target))
8771 (js2-node-add-children pn break-label) ; but not break-target
8772 pn))
8773
8774 (defun js2-parse-continue ()
8775 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8776 (let ((pos (js2-current-token-beg))
8777 (end (js2-current-token-end))
8778 label ; optional user-specified label, a `js2-name-node'
8779 labels ; current matching labeled stmt, if any
8780 target ; the `js2-loop-node' target of this continue stmt
8781 pn)
8782 (when (= (js2-peek-token-or-eol) js2-NAME)
8783 (js2-get-token)
8784 (setq label (js2-create-name-node)
8785 end (js2-node-end label)
8786 ;; matchJumpLabelName only matches if there is one
8787 labels (js2-match-jump-label-name (js2-current-token-string))))
8788 (cond
8789 ((null labels) ; no current label to go to
8790 (if (null js2-loop-set) ; no loop to continue to
8791 (js2-report-error "msg.continue.outside" nil pos
8792 (length "continue"))
8793 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8794 (t
8795 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8796 (setq target (js2-labeled-stmt-node-stmt labels))
8797 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8798 (setq pn (make-js2-continue-node :pos pos
8799 :len (- end pos)
8800 :label label
8801 :target target))
8802 (js2-node-add-children pn label) ; but not target - it's not our child
8803 pn))
8804
8805 (defun js2-parse-with ()
8806 "Parser for with-statement. Last matched token must be js2-WITH."
8807 (let ((pos (js2-current-token-beg))
8808 obj body pn lp rp)
8809 (if (js2-must-match js2-LP "msg.no.paren.with")
8810 (setq lp (js2-current-token-beg)))
8811 (setq obj (js2-parse-expr))
8812 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8813 (setq rp (js2-current-token-beg)))
8814 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8815 (setq body (js2-parse-statement)))
8816 (setq pn (make-js2-with-node :pos pos
8817 :len (- (js2-node-end body) pos)
8818 :object obj
8819 :body body
8820 :lp (js2-relpos lp pos)
8821 :rp (js2-relpos rp pos)))
8822 (js2-node-add-children pn obj body)
8823 pn))
8824
8825 (defun js2-parse-const-var ()
8826 "Parser for var- or const-statement.
8827 Last matched token must be js2-CONST or js2-VAR."
8828 (let ((tt (js2-current-token-type))
8829 (pos (js2-current-token-beg))
8830 expr pn)
8831 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8832 pn (make-js2-expr-stmt-node :pos pos
8833 :len (- (js2-node-end expr) pos)
8834 :expr expr))
8835 (js2-node-add-children pn expr)
8836 pn))
8837
8838 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8839 (let ((pn (make-js2-expr-stmt-node :pos pos
8840 :len (js2-node-len expr)
8841 :type (if (js2-inside-function)
8842 js2-EXPR_VOID
8843 js2-EXPR_RESULT)
8844 :expr expr)))
8845 (if add-child
8846 (js2-node-add-children pn expr))
8847 pn))
8848
8849 (defun js2-parse-let-stmt ()
8850 "Parser for let-statement. Last matched token must be js2-LET."
8851 (let ((pos (js2-current-token-beg))
8852 expr pn)
8853 (if (= (js2-peek-token) js2-LP)
8854 ;; let expression in statement context
8855 (setq expr (js2-parse-let pos 'statement)
8856 pn (js2-wrap-with-expr-stmt pos expr t))
8857 ;; else we're looking at a statement like let x=6, y=7;
8858 (setf expr (js2-parse-variables js2-LET pos)
8859 pn (js2-wrap-with-expr-stmt pos expr t)
8860 (js2-node-type pn) js2-EXPR_RESULT))
8861 pn))
8862
8863 (defun js2-parse-ret-yield ()
8864 (js2-parse-return-or-yield (js2-current-token-type) nil))
8865
8866 (defconst js2-parse-return-stmt-enders
8867 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8868
8869 (defsubst js2-now-all-set (before after mask)
8870 "Return whether or not the bits in the mask have changed to all set.
8871 BEFORE is bits before change, AFTER is bits after change, and MASK is
8872 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8873 but not BEFORE."
8874 (and (/= (logand before mask) mask)
8875 (= (logand after mask) mask)))
8876
8877 (defun js2-parse-return-or-yield (tt expr-context)
8878 (let* ((pos (js2-current-token-beg))
8879 (end (js2-current-token-end))
8880 (before js2-end-flags)
8881 (inside-function (js2-inside-function))
8882 (gen-type (and inside-function (js2-function-node-generator-type
8883 js2-current-script-or-fn)))
8884 e ret name yield-star-p)
8885 (unless inside-function
8886 (js2-report-error (if (eq tt js2-RETURN)
8887 "msg.bad.return"
8888 "msg.bad.yield")))
8889 (when (and inside-function
8890 (eq gen-type 'STAR)
8891 (js2-match-token js2-MUL))
8892 (setq yield-star-p t))
8893 ;; This is ugly, but we don't want to require a semicolon.
8894 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8895 (setq e (js2-parse-expr)
8896 end (js2-node-end e)))
8897 (cond
8898 ((eq tt js2-RETURN)
8899 (js2-set-flag js2-end-flags (if (null e)
8900 js2-end-returns
8901 js2-end-returns-value))
8902 (setq ret (make-js2-return-node :pos pos
8903 :len (- end pos)
8904 :retval e))
8905 (js2-node-add-children ret e)
8906 ;; See if we need a strict mode warning.
8907 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8908 ;; more thorough and accurate than this before/after flag check.
8909 ;; E.g. if there's a finally-block that always returns, we shouldn't
8910 ;; show a warning generated by inconsistent returns in the catch blocks.
8911 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8912 ;; so we know which returns/yields to highlight, and we should get rid of
8913 ;; all the checking in `js2-parse-return-or-yield'.
8914 (if (and js2-strict-inconsistent-return-warning
8915 (js2-now-all-set before js2-end-flags
8916 (logior js2-end-returns js2-end-returns-value)))
8917 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8918 ((eq gen-type 'COMPREHENSION)
8919 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8920 ;; like SpiderMonkey does.
8921 (js2-report-error "msg.syntax" nil pos 5))
8922 (t
8923 (setq ret (make-js2-yield-node :pos pos
8924 :len (- end pos)
8925 :value e
8926 :star-p yield-star-p))
8927 (js2-node-add-children ret e)
8928 (unless expr-context
8929 (setq e ret
8930 ret (js2-wrap-with-expr-stmt pos e t))
8931 (js2-set-requires-activation)
8932 (js2-set-is-generator))))
8933 ;; see if we are mixing yields and value returns.
8934 (when (and inside-function
8935 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8936 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8937 'LEGACY))
8938 (setq name (js2-function-name js2-current-script-or-fn))
8939 (if (zerop (length name))
8940 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8941 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8942 ret))
8943
8944 (defun js2-parse-debugger ()
8945 (make-js2-keyword-node :type js2-DEBUGGER))
8946
8947 (defun js2-parse-block ()
8948 "Parser for a curly-delimited statement block.
8949 Last token matched must be `js2-LC'."
8950 (let ((pos (js2-current-token-beg))
8951 (pn (make-js2-scope)))
8952 (js2-push-scope pn)
8953 (unwind-protect
8954 (progn
8955 (js2-parse-statements pn)
8956 (js2-must-match js2-RC "msg.no.brace.block")
8957 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8958 (js2-pop-scope))
8959 pn))
8960
8961 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8962 (defun js2-parse-semi ()
8963 "Parse a statement or handle an error.
8964 Current token type is `js2-SEMI' or `js2-ERROR'."
8965 (let ((tt (js2-current-token-type)) pos len)
8966 (if (eq tt js2-SEMI)
8967 (make-js2-empty-expr-node :len 1)
8968 (setq pos (js2-current-token-beg)
8969 len (- (js2-current-token-end) pos))
8970 (js2-report-error "msg.syntax" nil pos len)
8971 (make-js2-error-node :pos pos :len len))))
8972
8973 (defun js2-parse-default-xml-namespace ()
8974 "Parse a `default xml namespace = <expr>' e4x statement."
8975 (let ((pos (js2-current-token-beg))
8976 end len expr unary)
8977 (js2-must-have-xml)
8978 (js2-set-requires-activation)
8979 (setq len (- js2-ts-cursor pos))
8980 (unless (and (js2-match-token js2-NAME)
8981 (string= (js2-current-token-string) "xml"))
8982 (js2-report-error "msg.bad.namespace" nil pos len))
8983 (unless (and (js2-match-token js2-NAME)
8984 (string= (js2-current-token-string) "namespace"))
8985 (js2-report-error "msg.bad.namespace" nil pos len))
8986 (unless (js2-match-token js2-ASSIGN)
8987 (js2-report-error "msg.bad.namespace" nil pos len))
8988 (setq expr (js2-parse-expr)
8989 end (js2-node-end expr)
8990 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8991 :pos pos
8992 :len (- end pos)
8993 :operand expr))
8994 (js2-node-add-children unary expr)
8995 (make-js2-expr-stmt-node :pos pos
8996 :len (- end pos)
8997 :expr unary)))
8998
8999 (defun js2-record-label (label bundle)
9000 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9001 (js2-get-token)
9002 (let ((name (js2-label-node-name label))
9003 labeled-stmt
9004 dup)
9005 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9006 ;; flag both labels if possible when used in editing mode
9007 (if (and js2-parse-ide-mode
9008 (setq dup (js2-get-label-by-name labeled-stmt name)))
9009 (js2-report-error "msg.dup.label" nil
9010 (js2-node-abs-pos dup) (js2-node-len dup)))
9011 (js2-report-error "msg.dup.label" nil
9012 (js2-node-pos label) (js2-node-len label)))
9013 (js2-labeled-stmt-node-add-label bundle label)
9014 (js2-node-add-children bundle label)
9015 ;; Add one reference to the bundle per label in `js2-label-set'
9016 (push (cons name bundle) js2-label-set)))
9017
9018 (defun js2-parse-name-or-label ()
9019 "Parser for identifier or label. Last token matched must be js2-NAME.
9020 Called when we found a name in a statement context. If it's a label, we gather
9021 up any following labels and the next non-label statement into a
9022 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9023 expression and return it wrapped in a `js2-expr-stmt-node'."
9024 (let ((pos (js2-current-token-beg))
9025 expr stmt bundle
9026 (continue t))
9027 ;; set check for label and call down to `js2-parse-primary-expr'
9028 (setq expr (js2-maybe-parse-label))
9029 (if (null expr)
9030 ;; Parse the non-label expression and wrap with expression stmt.
9031 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9032 ;; else parsed a label
9033 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9034 (js2-record-label expr bundle)
9035 ;; look for more labels
9036 (while (and continue (= (js2-get-token) js2-NAME))
9037 (if (setq expr (js2-maybe-parse-label))
9038 (js2-record-label expr bundle)
9039 (setq expr (js2-parse-expr)
9040 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9041 continue nil)
9042 (js2-auto-insert-semicolon stmt)))
9043 ;; no more labels; now parse the labeled statement
9044 (unwind-protect
9045 (unless stmt
9046 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9047 (js2-unget-token)
9048 (setq stmt (js2-statement-helper))))
9049 ;; remove the labels for this statement from the global set
9050 (dolist (label (js2-labeled-stmt-node-labels bundle))
9051 (setq js2-label-set (remove label js2-label-set))))
9052 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9053 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9054 (js2-node-add-children bundle stmt)
9055 bundle)))
9056
9057 (defun js2-maybe-parse-label ()
9058 (cl-assert (= (js2-current-token-type) js2-NAME))
9059 (let (label-pos
9060 (next-tt (js2-get-token))
9061 (label-end (js2-current-token-end)))
9062 ;; Do not consume colon, it is used as unwind indicator
9063 ;; to return to statementHelper.
9064 (js2-unget-token)
9065 (if (= next-tt js2-COLON)
9066 (prog2
9067 (setq label-pos (js2-current-token-beg))
9068 (make-js2-label-node :pos label-pos
9069 :len (- label-end label-pos)
9070 :name (js2-current-token-string))
9071 (js2-set-face label-pos
9072 label-end
9073 'font-lock-variable-name-face 'record))
9074 ;; Backtrack from the name token, too.
9075 (js2-unget-token)
9076 nil)))
9077
9078 (defun js2-parse-expr-stmt ()
9079 "Default parser in statement context, if no recognized statement found."
9080 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9081 (progn
9082 (js2-unget-token)
9083 (js2-parse-expr)) t))
9084
9085 (defun js2-parse-variables (decl-type pos)
9086 "Parse a comma-separated list of variable declarations.
9087 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9088
9089 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9090 For 'var' or 'const', the keyword should be the token last scanned.
9091
9092 POS is the position where the node should start. It's sometimes the
9093 var/const/let keyword, and other times the beginning of the first token
9094 in the first variable declaration.
9095
9096 Returns the parsed `js2-var-decl-node' expression node."
9097 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9098 :pos pos))
9099 destructuring kid-pos tt init name end nbeg nend vi
9100 (continue t))
9101 ;; Example:
9102 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9103 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9104 ;; var {a, b} = baz;
9105 (while continue
9106 (setq destructuring nil
9107 name nil
9108 tt (js2-get-token)
9109 kid-pos (js2-current-token-beg)
9110 end (js2-current-token-end)
9111 init nil)
9112 (if (or (= tt js2-LB) (= tt js2-LC))
9113 ;; Destructuring assignment, e.g., var [a, b] = ...
9114 (setq destructuring (js2-parse-destruct-primary-expr)
9115 end (js2-node-end destructuring))
9116 ;; Simple variable name
9117 (js2-unget-token)
9118 (when (js2-must-match-name "msg.bad.var")
9119 (setq name (js2-create-name-node)
9120 nbeg (js2-current-token-beg)
9121 nend (js2-current-token-end)
9122 end nend)
9123 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9124 (when (js2-match-token js2-ASSIGN)
9125 (setq init (js2-parse-assign-expr)
9126 end (js2-node-end init))
9127 (js2-record-imenu-functions init name))
9128 (when name
9129 (js2-set-face nbeg nend (if (js2-function-node-p init)
9130 'font-lock-function-name-face
9131 'font-lock-variable-name-face)
9132 'record))
9133 (setq vi (make-js2-var-init-node :pos kid-pos
9134 :len (- end kid-pos)
9135 :type decl-type))
9136 (if destructuring
9137 (progn
9138 (if (and (null init) (not js2-in-for-init))
9139 (js2-report-error "msg.destruct.assign.no.init"))
9140 (js2-define-destruct-symbols destructuring
9141 decl-type
9142 'font-lock-variable-name-face)
9143 (setf (js2-var-init-node-target vi) destructuring))
9144 (setf (js2-var-init-node-target vi) name))
9145 (setf (js2-var-init-node-initializer vi) init)
9146 (js2-node-add-children vi name destructuring init)
9147 (js2-block-node-push result vi)
9148 (unless (js2-match-token js2-COMMA)
9149 (setq continue nil)))
9150 (setf (js2-node-len result) (- end pos))
9151 result))
9152
9153 (defun js2-parse-let (pos &optional stmt-p)
9154 "Parse a let expression or statement.
9155 A let-expression is of the form `let (vars) expr'.
9156 A let-statment is of the form `let (vars) {statements}'.
9157 The third form of let is a variable declaration list, handled
9158 by `js2-parse-variables'."
9159 (let ((pn (make-js2-let-node :pos pos))
9160 beg vars body)
9161 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9162 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9163 (js2-push-scope pn)
9164 (unwind-protect
9165 (progn
9166 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9167 (if (js2-must-match js2-RP "msg.no.paren.let")
9168 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9169 (if (and stmt-p (js2-match-token js2-LC))
9170 ;; let statement
9171 (progn
9172 (setf beg (js2-current-token-beg) ; position stmt at LC
9173 body (js2-parse-statements))
9174 (js2-must-match js2-RC "msg.no.curly.let")
9175 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9176 (js2-node-len pn) (- (js2-current-token-end) pos)
9177 (js2-let-node-body pn) body
9178 (js2-node-type pn) js2-LET))
9179 ;; let expression
9180 (setf body (js2-parse-expr)
9181 (js2-node-len pn) (- (js2-node-end body) pos)
9182 (js2-let-node-body pn) body))
9183 (setf (js2-let-node-vars pn) vars)
9184 (js2-node-add-children pn vars body))
9185 (js2-pop-scope))
9186 pn))
9187
9188 (defun js2-define-new-symbol (decl-type name node &optional scope)
9189 (js2-scope-put-symbol (or scope js2-current-scope)
9190 name
9191 (make-js2-symbol decl-type name node)))
9192
9193 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9194 "Define a symbol in the current scope.
9195 If NODE is non-nil, it is the AST node associated with the symbol."
9196 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9197 (symbol (if defining-scope
9198 (js2-scope-get-symbol defining-scope name)))
9199 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9200 (pos (if node (js2-node-abs-pos node)))
9201 (len (if node (js2-node-len node))))
9202 (cond
9203 ((and symbol ; already defined
9204 (or (= sdt js2-CONST) ; old version is const
9205 (= decl-type js2-CONST) ; new version is const
9206 ;; two let-bound vars in this block have same name
9207 (and (= sdt js2-LET)
9208 (eq defining-scope js2-current-scope))))
9209 (js2-report-error
9210 (cond
9211 ((= sdt js2-CONST) "msg.const.redecl")
9212 ((= sdt js2-LET) "msg.let.redecl")
9213 ((= sdt js2-VAR) "msg.var.redecl")
9214 ((= sdt js2-FUNCTION) "msg.function.redecl")
9215 (t "msg.parm.redecl"))
9216 name pos len))
9217 ((= decl-type js2-LET)
9218 (if (and (not ignore-not-in-block)
9219 (or (= (js2-node-type js2-current-scope) js2-IF)
9220 (js2-loop-node-p js2-current-scope)))
9221 (js2-report-error "msg.let.decl.not.in.block")
9222 (js2-define-new-symbol decl-type name node)))
9223 ((or (= decl-type js2-VAR)
9224 (= decl-type js2-CONST)
9225 (= decl-type js2-FUNCTION))
9226 (if symbol
9227 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9228 (js2-add-strict-warning "msg.var.redecl" name)
9229 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9230 (js2-add-strict-warning "msg.var.hides.arg" name)))
9231 (js2-define-new-symbol decl-type name node
9232 js2-current-script-or-fn)))
9233 ((= decl-type js2-LP)
9234 (if symbol
9235 ;; must be duplicate parameter. Second parameter hides the
9236 ;; first, so go ahead and add the second pararameter
9237 (js2-report-warning "msg.dup.parms" name))
9238 (js2-define-new-symbol decl-type name node))
9239 (t (js2-code-bug)))))
9240
9241 (defun js2-parse-paren-expr-or-generator-comp ()
9242 (let ((px-pos (js2-current-token-beg)))
9243 (if (and (>= js2-language-version 200)
9244 (js2-match-token js2-FOR))
9245 (js2-parse-generator-comp px-pos)
9246 (let* ((js2-in-for-init nil)
9247 (expr (js2-parse-expr))
9248 (pn (make-js2-paren-node :pos px-pos
9249 :expr expr
9250 :len (- (js2-current-token-end)
9251 px-pos))))
9252 (js2-node-add-children pn (js2-paren-node-expr pn))
9253 (js2-must-match js2-RP "msg.no.paren")
9254 pn))))
9255
9256 (defun js2-parse-expr (&optional oneshot)
9257 (let* ((pn (js2-parse-assign-expr))
9258 (pos (js2-node-pos pn))
9259 left
9260 right
9261 op-pos)
9262 (while (and (not oneshot)
9263 (js2-match-token js2-COMMA))
9264 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9265 (if (= (js2-peek-token) js2-YIELD)
9266 (js2-report-error "msg.yield.parenthesized"))
9267 (setq right (js2-parse-assign-expr)
9268 left pn
9269 pn (make-js2-infix-node :type js2-COMMA
9270 :pos pos
9271 :len (- js2-ts-cursor pos)
9272 :op-pos op-pos
9273 :left left
9274 :right right))
9275 (js2-node-add-children pn left right))
9276 pn))
9277
9278 (defun js2-parse-assign-expr ()
9279 (let ((tt (js2-get-token))
9280 (pos (js2-current-token-beg))
9281 pn left right op-pos
9282 ts-state recorded-identifiers parsed-errors)
9283 (if (= tt js2-YIELD)
9284 (js2-parse-return-or-yield tt t)
9285 ;; Save the tokenizer state in case we find an arrow function
9286 ;; and have to rewind.
9287 (setq ts-state (make-js2-ts-state)
9288 recorded-identifiers js2-recorded-identifiers
9289 parsed-errors js2-parsed-errors)
9290 ;; not yield - parse assignment expression
9291 (setq pn (js2-parse-cond-expr)
9292 tt (js2-get-token))
9293 (cond
9294 ((and (<= js2-first-assign tt)
9295 (<= tt js2-last-assign))
9296 ;; tt express assignment (=, |=, ^=, ..., %=)
9297 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9298 left pn)
9299 (setq right (js2-parse-assign-expr)
9300 pn (make-js2-assign-node :type tt
9301 :pos pos
9302 :len (- (js2-node-end right) pos)
9303 :op-pos op-pos
9304 :left left
9305 :right right))
9306 (when js2-parse-ide-mode
9307 (js2-highlight-assign-targets pn left right)
9308 (js2-record-imenu-functions right left))
9309 ;; do this last so ide checks above can use absolute positions
9310 (js2-node-add-children pn left right))
9311 ((and (= tt js2-ARROW)
9312 (>= js2-language-version 200))
9313 (js2-ts-seek ts-state)
9314 (setq js2-recorded-identifiers recorded-identifiers
9315 js2-parsed-errors parsed-errors)
9316 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9317 (t
9318 (js2-unget-token)))
9319 pn)))
9320
9321 (defun js2-parse-cond-expr ()
9322 (let ((pos (js2-current-token-beg))
9323 (pn (js2-parse-or-expr))
9324 test-expr
9325 if-true
9326 if-false
9327 q-pos
9328 c-pos)
9329 (when (js2-match-token js2-HOOK)
9330 (setq q-pos (- (js2-current-token-beg) pos)
9331 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9332 (js2-must-match js2-COLON "msg.no.colon.cond")
9333 (setq c-pos (- (js2-current-token-beg) pos)
9334 if-false (js2-parse-assign-expr)
9335 test-expr pn
9336 pn (make-js2-cond-node :pos pos
9337 :len (- (js2-node-end if-false) pos)
9338 :test-expr test-expr
9339 :true-expr if-true
9340 :false-expr if-false
9341 :q-pos q-pos
9342 :c-pos c-pos))
9343 (js2-node-add-children pn test-expr if-true if-false))
9344 pn))
9345
9346 (defun js2-make-binary (type left parser)
9347 "Helper for constructing a binary-operator AST node.
9348 LEFT is the left-side-expression, already parsed, and the
9349 binary operator should have just been matched.
9350 PARSER is a function to call to parse the right operand,
9351 or a `js2-node' struct if it has already been parsed.
9352 FIXME: The latter option is unused?"
9353 (let* ((pos (js2-node-pos left))
9354 (op-pos (- (js2-current-token-beg) pos))
9355 (right (if (js2-node-p parser)
9356 parser
9357 (js2-get-token)
9358 (funcall parser)))
9359 (pn (make-js2-infix-node :type type
9360 :pos pos
9361 :len (- (js2-node-end right) pos)
9362 :op-pos op-pos
9363 :left left
9364 :right right)))
9365 (js2-node-add-children pn left right)
9366 pn))
9367
9368 (defun js2-parse-or-expr ()
9369 (let ((pn (js2-parse-and-expr)))
9370 (when (js2-match-token js2-OR)
9371 (setq pn (js2-make-binary js2-OR
9372 pn
9373 'js2-parse-or-expr)))
9374 pn))
9375
9376 (defun js2-parse-and-expr ()
9377 (let ((pn (js2-parse-bit-or-expr)))
9378 (when (js2-match-token js2-AND)
9379 (setq pn (js2-make-binary js2-AND
9380 pn
9381 'js2-parse-and-expr)))
9382 pn))
9383
9384 (defun js2-parse-bit-or-expr ()
9385 (let ((pn (js2-parse-bit-xor-expr)))
9386 (while (js2-match-token js2-BITOR)
9387 (setq pn (js2-make-binary js2-BITOR
9388 pn
9389 'js2-parse-bit-xor-expr)))
9390 pn))
9391
9392 (defun js2-parse-bit-xor-expr ()
9393 (let ((pn (js2-parse-bit-and-expr)))
9394 (while (js2-match-token js2-BITXOR)
9395 (setq pn (js2-make-binary js2-BITXOR
9396 pn
9397 'js2-parse-bit-and-expr)))
9398 pn))
9399
9400 (defun js2-parse-bit-and-expr ()
9401 (let ((pn (js2-parse-eq-expr)))
9402 (while (js2-match-token js2-BITAND)
9403 (setq pn (js2-make-binary js2-BITAND
9404 pn
9405 'js2-parse-eq-expr)))
9406 pn))
9407
9408 (defconst js2-parse-eq-ops
9409 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9410
9411 (defun js2-parse-eq-expr ()
9412 (let ((pn (js2-parse-rel-expr))
9413 tt)
9414 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9415 (setq pn (js2-make-binary tt
9416 pn
9417 'js2-parse-rel-expr)))
9418 (js2-unget-token)
9419 pn))
9420
9421 (defconst js2-parse-rel-ops
9422 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9423
9424 (defun js2-parse-rel-expr ()
9425 (let ((pn (js2-parse-shift-expr))
9426 (continue t)
9427 tt)
9428 (while continue
9429 (setq tt (js2-get-token))
9430 (cond
9431 ((and js2-in-for-init (= tt js2-IN))
9432 (js2-unget-token)
9433 (setq continue nil))
9434 ((memq tt js2-parse-rel-ops)
9435 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9436 (t
9437 (js2-unget-token)
9438 (setq continue nil))))
9439 pn))
9440
9441 (defconst js2-parse-shift-ops
9442 (list js2-LSH js2-URSH js2-RSH))
9443
9444 (defun js2-parse-shift-expr ()
9445 (let ((pn (js2-parse-add-expr))
9446 tt
9447 (continue t))
9448 (while continue
9449 (setq tt (js2-get-token))
9450 (if (memq tt js2-parse-shift-ops)
9451 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9452 (js2-unget-token)
9453 (setq continue nil)))
9454 pn))
9455
9456 (defun js2-parse-add-expr ()
9457 (let ((pn (js2-parse-mul-expr))
9458 tt
9459 (continue t))
9460 (while continue
9461 (setq tt (js2-get-token))
9462 (if (or (= tt js2-ADD) (= tt js2-SUB))
9463 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9464 (js2-unget-token)
9465 (setq continue nil)))
9466 pn))
9467
9468 (defconst js2-parse-mul-ops
9469 (list js2-MUL js2-DIV js2-MOD))
9470
9471 (defun js2-parse-mul-expr ()
9472 (let ((pn (js2-parse-unary-expr))
9473 tt
9474 (continue t))
9475 (while continue
9476 (setq tt (js2-get-token))
9477 (if (memq tt js2-parse-mul-ops)
9478 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9479 (js2-unget-token)
9480 (setq continue nil)))
9481 pn))
9482
9483 (defun js2-make-unary (type parser &rest args)
9484 "Make a unary node of type TYPE.
9485 PARSER is either a node (for postfix operators) or a function to call
9486 to parse the operand (for prefix operators)."
9487 (let* ((pos (js2-current-token-beg))
9488 (postfix (js2-node-p parser))
9489 (expr (if postfix
9490 parser
9491 (apply parser args)))
9492 end
9493 pn)
9494 (if postfix ; e.g. i++
9495 (setq pos (js2-node-pos expr)
9496 end (js2-current-token-end))
9497 (setq end (js2-node-end expr)))
9498 (setq pn (make-js2-unary-node :type type
9499 :pos pos
9500 :len (- end pos)
9501 :operand expr))
9502 (js2-node-add-children pn expr)
9503 pn))
9504
9505 (defconst js2-incrementable-node-types
9506 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9507 "Node types that can be the operand of a ++ or -- operator.")
9508
9509 (defun js2-check-bad-inc-dec (tt beg end unary)
9510 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9511 js2-incrementable-node-types)
9512 (js2-report-error (if (= tt js2-INC)
9513 "msg.bad.incr"
9514 "msg.bad.decr")
9515 nil beg (- end beg))))
9516
9517 (defun js2-parse-unary-expr ()
9518 (let ((tt (js2-current-token-type))
9519 pn expr beg end)
9520 (cond
9521 ((or (= tt js2-VOID)
9522 (= tt js2-NOT)
9523 (= tt js2-BITNOT)
9524 (= tt js2-TYPEOF))
9525 (js2-get-token)
9526 (js2-make-unary tt 'js2-parse-unary-expr))
9527 ((= tt js2-ADD)
9528 (js2-get-token)
9529 ;; Convert to special POS token in decompiler and parse tree
9530 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9531 ((= tt js2-SUB)
9532 (js2-get-token)
9533 ;; Convert to special NEG token in decompiler and parse tree
9534 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9535 ((or (= tt js2-INC)
9536 (= tt js2-DEC))
9537 (js2-get-token)
9538 (prog1
9539 (setq beg (js2-current-token-beg)
9540 end (js2-current-token-end)
9541 expr (js2-make-unary tt 'js2-parse-member-expr t))
9542 (js2-check-bad-inc-dec tt beg end expr)))
9543 ((= tt js2-DELPROP)
9544 (js2-get-token)
9545 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9546 ((= tt js2-ERROR)
9547 (js2-get-token)
9548 (make-js2-error-node)) ; try to continue
9549 ((and (= tt js2-LT)
9550 js2-compiler-xml-available)
9551 ;; XML stream encountered in expression.
9552 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9553 (t
9554 (setq pn (js2-parse-member-expr t)
9555 ;; Don't look across a newline boundary for a postfix incop.
9556 tt (js2-peek-token-or-eol))
9557 (when (or (= tt js2-INC) (= tt js2-DEC))
9558 (js2-get-token)
9559 (setf expr pn
9560 pn (js2-make-unary tt expr))
9561 (js2-node-set-prop pn 'postfix t)
9562 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9563 pn))))
9564
9565 (defun js2-parse-xml-initializer ()
9566 "Parse an E4X XML initializer.
9567 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9568 Then I'll postprocess the result, depending on whether we're in IDE
9569 mode or codegen mode, and generate the appropriate rewritten AST.
9570 IDE mode uses a rich AST that models the XML structure. Codegen mode
9571 just concatenates everything and makes a new XML or XMLList out of it."
9572 (let ((tt (js2-get-first-xml-token))
9573 pn-xml pn expr kids expr-pos
9574 (continue t)
9575 (first-token t))
9576 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9577 (js2-report-error "msg.syntax"))
9578 (setq pn-xml (make-js2-xml-node))
9579 (while continue
9580 (if first-token
9581 (setq first-token nil)
9582 (setq tt (js2-get-next-xml-token)))
9583 (cond
9584 ;; js2-XML means we found a {expr} in the XML stream.
9585 ;; The token string is the XML up to the left-curly.
9586 ((= tt js2-XML)
9587 (push (make-js2-string-node :pos (js2-current-token-beg)
9588 :len (- js2-ts-cursor (js2-current-token-beg)))
9589 kids)
9590 (js2-must-match js2-LC "msg.syntax")
9591 (setq expr-pos js2-ts-cursor
9592 expr (if (eq (js2-peek-token) js2-RC)
9593 (make-js2-empty-expr-node :pos expr-pos)
9594 (js2-parse-expr)))
9595 (js2-must-match js2-RC "msg.syntax")
9596 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9597 :len (js2-node-len expr)
9598 :expr expr))
9599 (js2-node-add-children pn expr)
9600 (push pn kids))
9601 ;; a js2-XMLEND token means we hit the final close-tag.
9602 ((= tt js2-XMLEND)
9603 (push (make-js2-string-node :pos (js2-current-token-beg)
9604 :len (- js2-ts-cursor (js2-current-token-beg)))
9605 kids)
9606 (dolist (kid (nreverse kids))
9607 (js2-block-node-push pn-xml kid))
9608 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9609 (js2-node-pos pn-xml))
9610 continue nil))
9611 (t
9612 (js2-report-error "msg.syntax")
9613 (setq continue nil))))
9614 pn-xml))
9615
9616
9617 (defun js2-parse-argument-list ()
9618 "Parse an argument list and return it as a Lisp list of nodes.
9619 Returns the list in reverse order. Consumes the right-paren token."
9620 (let (result)
9621 (unless (js2-match-token js2-RP)
9622 (cl-loop do
9623 (let ((tt (js2-get-token)))
9624 (if (= tt js2-YIELD)
9625 (js2-report-error "msg.yield.parenthesized"))
9626 (if (and (= tt js2-TRIPLEDOT)
9627 (>= js2-language-version 200))
9628 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9629 (js2-unget-token)
9630 (push (js2-parse-assign-expr) result)))
9631 while
9632 (js2-match-token js2-COMMA))
9633 (js2-must-match js2-RP "msg.no.paren.arg")
9634 result)))
9635
9636 (defun js2-parse-member-expr (&optional allow-call-syntax)
9637 (let ((tt (js2-current-token-type))
9638 pn pos target args beg end init)
9639 (if (/= tt js2-NEW)
9640 (setq pn (js2-parse-primary-expr))
9641 ;; parse a 'new' expression
9642 (js2-get-token)
9643 (setq pos (js2-current-token-beg)
9644 beg pos
9645 target (js2-parse-member-expr)
9646 end (js2-node-end target)
9647 pn (make-js2-new-node :pos pos
9648 :target target
9649 :len (- end pos)))
9650 (js2-highlight-function-call (js2-current-token))
9651 (js2-node-add-children pn target)
9652 (when (js2-match-token js2-LP)
9653 ;; Add the arguments to pn, if any are supplied.
9654 (setf beg pos ; start of "new" keyword
9655 pos (js2-current-token-beg)
9656 args (nreverse (js2-parse-argument-list))
9657 (js2-new-node-args pn) args
9658 end (js2-current-token-end)
9659 (js2-new-node-lp pn) (- pos beg)
9660 (js2-new-node-rp pn) (- end 1 beg))
9661 (apply #'js2-node-add-children pn args))
9662 (when (and js2-allow-rhino-new-expr-initializer
9663 (js2-match-token js2-LC))
9664 (setf init (js2-parse-object-literal)
9665 end (js2-node-end init)
9666 (js2-new-node-initializer pn) init)
9667 (js2-node-add-children pn init))
9668 (setf (js2-node-len pn) (- end beg))) ; end outer if
9669 (js2-parse-member-expr-tail allow-call-syntax pn)))
9670
9671 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9672 "Parse a chain of property/array accesses or function calls.
9673 Includes parsing for E4X operators like `..' and `.@'.
9674 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9675 Returns an expression tree that includes PN, the parent node."
9676 (let (tt
9677 (continue t))
9678 (while continue
9679 (setq tt (js2-get-token))
9680 (cond
9681 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9682 (setq pn (js2-parse-property-access tt pn)))
9683 ((= tt js2-DOTQUERY)
9684 (setq pn (js2-parse-dot-query pn)))
9685 ((= tt js2-LB)
9686 (setq pn (js2-parse-element-get pn)))
9687 ((= tt js2-LP)
9688 (js2-unget-token)
9689 (if allow-call-syntax
9690 (setq pn (js2-parse-function-call pn))
9691 (setq continue nil)))
9692 ((= tt js2-TEMPLATE_HEAD)
9693 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9694 ((= tt js2-NO_SUBS_TEMPLATE)
9695 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9696 (t
9697 (js2-unget-token)
9698 (setq continue nil))))
9699 (if (>= js2-highlight-level 2)
9700 (js2-parse-highlight-member-expr-node pn))
9701 pn))
9702
9703 (defun js2-parse-tagged-template (tag-node tpl-node)
9704 "Parse tagged template expression."
9705 (let* ((beg (js2-node-pos tag-node))
9706 (pn (make-js2-tagged-template-node :beg beg
9707 :len (- (js2-current-token-end) beg)
9708 :tag tag-node
9709 :template tpl-node)))
9710 (js2-node-add-children pn tag-node tpl-node)
9711 pn))
9712
9713 (defun js2-parse-dot-query (pn)
9714 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9715 Last token parsed must be `js2-DOTQUERY'."
9716 (let ((pos (js2-node-pos pn))
9717 op-pos expr end)
9718 (js2-must-have-xml)
9719 (js2-set-requires-activation)
9720 (setq op-pos (js2-current-token-beg)
9721 expr (js2-parse-expr)
9722 end (js2-node-end expr)
9723 pn (make-js2-xml-dot-query-node :left pn
9724 :pos pos
9725 :op-pos op-pos
9726 :right expr))
9727 (js2-node-add-children pn
9728 (js2-xml-dot-query-node-left pn)
9729 (js2-xml-dot-query-node-right pn))
9730 (if (js2-must-match js2-RP "msg.no.paren")
9731 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9732 end (js2-current-token-end)))
9733 (setf (js2-node-len pn) (- end pos))
9734 pn))
9735
9736 (defun js2-parse-element-get (pn)
9737 "Parse an element-get expression, e.g. foo[bar].
9738 Last token parsed must be `js2-RB'."
9739 (let ((lb (js2-current-token-beg))
9740 (pos (js2-node-pos pn))
9741 rb expr)
9742 (setq expr (js2-parse-expr))
9743 (if (js2-must-match js2-RB "msg.no.bracket.index")
9744 (setq rb (js2-current-token-beg)))
9745 (setq pn (make-js2-elem-get-node :target pn
9746 :pos pos
9747 :element expr
9748 :lb (js2-relpos lb pos)
9749 :rb (js2-relpos rb pos)
9750 :len (- (js2-current-token-end) pos)))
9751 (js2-node-add-children pn
9752 (js2-elem-get-node-target pn)
9753 (js2-elem-get-node-element pn))
9754 pn))
9755
9756 (defun js2-highlight-function-call (token)
9757 (when (eq (js2-token-type token) js2-NAME)
9758 (js2-record-face 'js2-function-call token)))
9759
9760 (defun js2-parse-function-call (pn)
9761 (js2-highlight-function-call (js2-current-token))
9762 (js2-get-token)
9763 (let (args
9764 (pos (js2-node-pos pn)))
9765 (setq pn (make-js2-call-node :pos pos
9766 :target pn
9767 :lp (- (js2-current-token-beg) pos)))
9768 (js2-node-add-children pn (js2-call-node-target pn))
9769 ;; Add the arguments to pn, if any are supplied.
9770 (setf args (nreverse (js2-parse-argument-list))
9771 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9772 (js2-call-node-args pn) args)
9773 (apply #'js2-node-add-children pn args)
9774 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9775 pn))
9776
9777 (defun js2-parse-property-access (tt pn)
9778 "Parse a property access, XML descendants access, or XML attr access."
9779 (let ((member-type-flags 0)
9780 (dot-pos (js2-current-token-beg))
9781 (dot-len (if (= tt js2-DOTDOT) 2 1))
9782 name
9783 ref ; right side of . or .. operator
9784 result)
9785 (when (= tt js2-DOTDOT)
9786 (js2-must-have-xml)
9787 (setq member-type-flags js2-descendants-flag))
9788 (if (not js2-compiler-xml-available)
9789 (progn
9790 (js2-must-match-prop-name "msg.no.name.after.dot")
9791 (setq name (js2-create-name-node t js2-GETPROP)
9792 result (make-js2-prop-get-node :left pn
9793 :pos (js2-current-token-beg)
9794 :right name
9795 :len (js2-current-token-len)))
9796 (js2-node-add-children result pn name)
9797 result)
9798 ;; otherwise look for XML operators
9799 (setf result (if (= tt js2-DOT)
9800 (make-js2-prop-get-node)
9801 (make-js2-infix-node :type js2-DOTDOT))
9802 (js2-node-pos result) (js2-node-pos pn)
9803 (js2-infix-node-op-pos result) dot-pos
9804 (js2-infix-node-left result) pn ; do this after setting position
9805 tt (js2-get-prop-name-token))
9806 (cond
9807 ;; handles: name, ns::name, ns::*, ns::[expr]
9808 ((= tt js2-NAME)
9809 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9810 ;; handles: *, *::name, *::*, *::[expr]
9811 ((= tt js2-MUL)
9812 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9813 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9814 ((= tt js2-XMLATTR)
9815 (setq result (js2-parse-attribute-access)))
9816 (t
9817 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9818 (if ref
9819 (setf (js2-node-len result) (- (js2-node-end ref)
9820 (js2-node-pos result))
9821 (js2-infix-node-right result) ref))
9822 (if (js2-infix-node-p result)
9823 (js2-node-add-children result
9824 (js2-infix-node-left result)
9825 (js2-infix-node-right result)))
9826 result)))
9827
9828 (defun js2-parse-attribute-access ()
9829 "Parse an E4X XML attribute expression.
9830 This includes expressions of the forms:
9831
9832 @attr @ns::attr @ns::*
9833 @* @*::attr @*::*
9834 @[expr] @*::[expr] @ns::[expr]
9835
9836 Called if we peeked an '@' token."
9837 (let ((tt (js2-get-prop-name-token))
9838 (at-pos (js2-current-token-beg)))
9839 (cond
9840 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9841 ((= tt js2-NAME)
9842 (js2-parse-property-name at-pos nil 0))
9843 ;; handles: @*, @*::name, @*::*, @*::[expr]
9844 ((= tt js2-MUL)
9845 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9846 ;; handles @[expr]
9847 ((= tt js2-LB)
9848 (js2-parse-xml-elem-ref at-pos))
9849 (t
9850 (js2-report-error "msg.no.name.after.xmlAttr")
9851 ;; Avoid cascaded errors that happen if we make an error node here.
9852 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9853
9854 (defun js2-parse-property-name (at-pos s member-type-flags)
9855 "Check if :: follows name in which case it becomes qualified name.
9856
9857 AT-POS is a natural number if we just read an '@' token, else nil.
9858 S is the name or string that was matched: an identifier, 'throw' or '*'.
9859 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9860
9861 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9862 operator, or the name is followed by ::. For a plain name, returns a
9863 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9864 (let ((pos (or at-pos (js2-current-token-beg)))
9865 colon-pos
9866 (name (js2-create-name-node t (js2-current-token-type) s))
9867 ns tt pn)
9868 (catch 'return
9869 (when (js2-match-token js2-COLONCOLON)
9870 (setq ns name
9871 colon-pos (js2-current-token-beg)
9872 tt (js2-get-prop-name-token))
9873 (cond
9874 ;; handles name::name
9875 ((= tt js2-NAME)
9876 (setq name (js2-create-name-node)))
9877 ;; handles name::*
9878 ((= tt js2-MUL)
9879 (setq name (js2-create-name-node nil nil "*")))
9880 ;; handles name::[expr]
9881 ((= tt js2-LB)
9882 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9883 (t
9884 (js2-report-error "msg.no.name.after.coloncolon"))))
9885 (if (and (null ns) (zerop member-type-flags))
9886 name
9887 (prog1
9888 (setq pn
9889 (make-js2-xml-prop-ref-node :pos pos
9890 :len (- (js2-node-end name) pos)
9891 :at-pos at-pos
9892 :colon-pos colon-pos
9893 :propname name))
9894 (js2-node-add-children pn name))))))
9895
9896 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9897 "Parse the [expr] portion of an xml element reference.
9898 For instance, @[expr], @*::[expr], or ns::[expr]."
9899 (let* ((lb (js2-current-token-beg))
9900 (pos (or at-pos lb))
9901 rb
9902 (expr (js2-parse-expr))
9903 (end (js2-node-end expr))
9904 pn)
9905 (if (js2-must-match js2-RB "msg.no.bracket.index")
9906 (setq rb (js2-current-token-beg)
9907 end (js2-current-token-end)))
9908 (prog1
9909 (setq pn
9910 (make-js2-xml-elem-ref-node :pos pos
9911 :len (- end pos)
9912 :namespace namespace
9913 :colon-pos colon-pos
9914 :at-pos at-pos
9915 :expr expr
9916 :lb (js2-relpos lb pos)
9917 :rb (js2-relpos rb pos)))
9918 (js2-node-add-children pn namespace expr))))
9919
9920 (defun js2-parse-destruct-primary-expr ()
9921 (let ((js2-is-in-destructuring t))
9922 (js2-parse-primary-expr)))
9923
9924 (defun js2-parse-primary-expr ()
9925 "Parse a literal (leaf) expression of some sort.
9926 Includes complex literals such as functions, object-literals,
9927 array-literals, array comprehensions and regular expressions."
9928 (let (pn ; parent node (usually return value)
9929 tt)
9930 (setq tt (js2-current-token-type))
9931 (cond
9932 ((= tt js2-CLASS)
9933 (js2-parse-class-expr))
9934 ((= tt js2-FUNCTION)
9935 (js2-parse-function-expr))
9936 ((= tt js2-LB)
9937 (js2-parse-array-comp-or-literal))
9938 ((= tt js2-LC)
9939 (js2-parse-object-literal))
9940 ((= tt js2-LET)
9941 (js2-parse-let (js2-current-token-beg)))
9942 ((= tt js2-LP)
9943 (js2-parse-paren-expr-or-generator-comp))
9944 ((= tt js2-XMLATTR)
9945 (js2-must-have-xml)
9946 (js2-parse-attribute-access))
9947 ((= tt js2-NAME)
9948 (js2-parse-name tt))
9949 ((= tt js2-NUMBER)
9950 (make-js2-number-node))
9951 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9952 (make-js2-string-node :type tt))
9953 ((= tt js2-TEMPLATE_HEAD)
9954 (js2-parse-template-literal))
9955 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9956 ;; Got / or /= which in this context means a regexp literal
9957 (let ((px-pos (js2-current-token-beg))
9958 (flags (js2-read-regexp tt))
9959 (end (js2-current-token-end)))
9960 (prog1
9961 (make-js2-regexp-node :pos px-pos
9962 :len (- end px-pos)
9963 :value (js2-current-token-string)
9964 :flags flags)
9965 (js2-set-face px-pos end 'font-lock-string-face 'record)
9966 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9967 ((or (= tt js2-NULL)
9968 (= tt js2-THIS)
9969 (= tt js2-SUPER)
9970 (= tt js2-FALSE)
9971 (= tt js2-TRUE))
9972 (make-js2-keyword-node :type tt))
9973 ((= tt js2-RP)
9974 ;; Not valid expression syntax, but this is valid in an arrow
9975 ;; function with no params: () => body.
9976 (if (eq (js2-peek-token) js2-ARROW)
9977 (progn
9978 (js2-unget-token) ; Put back the right paren.
9979 ;; Return whatever, it will hopefully be rewinded and
9980 ;; reparsed when we reach the =>.
9981 (make-js2-keyword-node :type js2-NULL))
9982 (js2-report-error "msg.syntax")
9983 (make-js2-error-node)))
9984 ((= tt js2-TRIPLEDOT)
9985 ;; Likewise, only valid in an arrow function with a rest param.
9986 (if (and (js2-match-token js2-NAME)
9987 (js2-match-token js2-RP)
9988 (eq (js2-peek-token) js2-ARROW))
9989 (progn
9990 (js2-unget-token) ; Put back the right paren.
9991 ;; See the previous case.
9992 (make-js2-keyword-node :type js2-NULL))
9993 (js2-report-error "msg.syntax")
9994 (make-js2-error-node)))
9995 ((= tt js2-RESERVED)
9996 (js2-report-error "msg.reserved.id")
9997 (make-js2-name-node))
9998 ((= tt js2-ERROR)
9999 ;; the scanner or one of its subroutines reported the error.
10000 (make-js2-error-node))
10001 ((= tt js2-EOF)
10002 (let* ((px-pos (point-at-bol))
10003 (len (- js2-ts-cursor px-pos)))
10004 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10005 (make-js2-error-node :pos (1- js2-ts-cursor)))
10006 (t
10007 (js2-report-error "msg.syntax")
10008 (make-js2-error-node)))))
10009
10010 (defun js2-parse-template-literal ()
10011 (let ((beg (js2-current-token-beg))
10012 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10013 (tt js2-TEMPLATE_HEAD))
10014 (while (eq tt js2-TEMPLATE_HEAD)
10015 (push (js2-parse-expr) kids)
10016 (js2-must-match js2-RC "msg.syntax")
10017 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10018 (push (make-js2-string-node :type tt) kids))
10019 (setq kids (nreverse kids))
10020 (let ((tpl (make-js2-template-node :beg beg
10021 :len (- (js2-current-token-end) beg)
10022 :kids kids)))
10023 (apply #'js2-node-add-children tpl kids)
10024 tpl)))
10025
10026 (defun js2-parse-name (_tt)
10027 (let ((name (js2-current-token-string))
10028 node)
10029 (setq node (if js2-compiler-xml-available
10030 (js2-parse-property-name nil name 0)
10031 (js2-create-name-node 'check-activation nil name)))
10032 (if js2-highlight-external-variables
10033 (js2-record-name-node node))
10034 node))
10035
10036 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10037 (js2-add-strict-warning
10038 msg nil
10039 ;; back up from comma to beginning of line or array/objlit
10040 (max (if elems
10041 (js2-node-pos (car elems))
10042 pos)
10043 (save-excursion
10044 (goto-char comma-pos)
10045 (back-to-indentation)
10046 (point)))
10047 comma-pos))
10048
10049 (defun js2-parse-array-comp-or-literal ()
10050 (let ((pos (js2-current-token-beg)))
10051 (if (and (>= js2-language-version 200)
10052 (js2-match-token js2-FOR))
10053 (js2-parse-array-comp pos)
10054 (js2-parse-array-literal pos))))
10055
10056 (defun js2-parse-array-literal (pos)
10057 (let ((after-lb-or-comma t)
10058 after-comma tt elems pn
10059 (continue t))
10060 (unless js2-is-in-destructuring
10061 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10062 (while continue
10063 (setq tt (js2-get-token))
10064 (cond
10065 ;; comma
10066 ((= tt js2-COMMA)
10067 (setq after-comma (js2-current-token-end))
10068 (if (not after-lb-or-comma)
10069 (setq after-lb-or-comma t)
10070 (push nil elems)))
10071 ;; end of array
10072 ((or (= tt js2-RB)
10073 (= tt js2-EOF)) ; prevent infinite loop
10074 (if (= tt js2-EOF)
10075 (js2-report-error "msg.no.bracket.arg" nil pos))
10076 (when (and after-comma (< js2-language-version 170))
10077 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10078 pos (remove nil elems) after-comma))
10079 (setq continue nil
10080 pn (make-js2-array-node :pos pos
10081 :len (- js2-ts-cursor pos)
10082 :elems (nreverse elems)))
10083 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10084 ;; destructuring binding
10085 (js2-is-in-destructuring
10086 (push (if (or (= tt js2-LC)
10087 (= tt js2-LB)
10088 (= tt js2-NAME))
10089 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10090 (js2-parse-destruct-primary-expr)
10091 ;; invalid pattern
10092 (js2-report-error "msg.bad.var")
10093 (make-js2-error-node))
10094 elems)
10095 (setq after-lb-or-comma nil
10096 after-comma nil))
10097 ;; array comp
10098 ((and (>= js2-language-version 170)
10099 (= tt js2-FOR) ; check for array comprehension
10100 (not after-lb-or-comma) ; "for" can't follow a comma
10101 elems ; must have at least 1 element
10102 (not (cdr elems))) ; but no 2nd element
10103 (js2-unget-token)
10104 (setf continue nil
10105 pn (js2-parse-legacy-array-comp (car elems) pos)))
10106 ;; another element
10107 (t
10108 (unless after-lb-or-comma
10109 (js2-report-error "msg.no.bracket.arg"))
10110 (if (and (= tt js2-TRIPLEDOT)
10111 (>= js2-language-version 200))
10112 ;; spread operator
10113 (push (js2-make-unary tt 'js2-parse-assign-expr)
10114 elems)
10115 (js2-unget-token)
10116 (push (js2-parse-assign-expr) elems))
10117 (setq after-lb-or-comma nil
10118 after-comma nil))))
10119 (unless js2-is-in-destructuring
10120 (js2-pop-scope))
10121 pn))
10122
10123 (defun js2-parse-legacy-array-comp (expr pos)
10124 "Parse a legacy array comprehension (JavaScript 1.7).
10125 EXPR is the first expression after the opening left-bracket.
10126 POS is the beginning of the LB token preceding EXPR.
10127 We should have just parsed the 'for' keyword before calling this function."
10128 (let ((current-scope js2-current-scope)
10129 loops first filter result)
10130 (unwind-protect
10131 (progn
10132 (while (js2-match-token js2-FOR)
10133 (let ((loop (make-js2-comp-loop-node)))
10134 (js2-push-scope loop)
10135 (push loop loops)
10136 (js2-parse-comp-loop loop)))
10137 ;; First loop takes expr scope's parent.
10138 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10139 (js2-scope-parent-scope current-scope))
10140 ;; Set expr scope's parent to the last loop.
10141 (setf (js2-scope-parent-scope current-scope) (car loops))
10142 (if (/= (js2-get-token) js2-IF)
10143 (js2-unget-token)
10144 (setq filter (js2-parse-condition))))
10145 (dotimes (_ (1- (length loops)))
10146 (js2-pop-scope)))
10147 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10148 (setq result (make-js2-comp-node :pos pos
10149 :len (- js2-ts-cursor pos)
10150 :result expr
10151 :loops (nreverse loops)
10152 :filters (and filter (list (car filter)))
10153 :form 'LEGACY_ARRAY))
10154 (apply #'js2-node-add-children result expr (car filter)
10155 (js2-comp-node-loops result))
10156 result))
10157
10158 (defun js2-parse-array-comp (pos)
10159 "Parse an ES6 array comprehension.
10160 POS is the beginning of the LB token.
10161 We should have just parsed the 'for' keyword before calling this function."
10162 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10163 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10164 pn))
10165
10166 (defun js2-parse-generator-comp (pos)
10167 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10168 (js2-current-script-or-fn
10169 (make-js2-function-node :generator-type 'COMPREHENSION))
10170 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10171 (js2-must-match js2-RP "msg.no.paren" pos)
10172 pn))
10173
10174 (defun js2-parse-comprehension (pos form)
10175 (let (loops filters expr result)
10176 (unwind-protect
10177 (progn
10178 (js2-unget-token)
10179 (while (js2-match-token js2-FOR)
10180 (let ((loop (make-js2-comp-loop-node)))
10181 (js2-push-scope loop)
10182 (push loop loops)
10183 (js2-parse-comp-loop loop)))
10184 (while (js2-match-token js2-IF)
10185 (push (car (js2-parse-condition)) filters))
10186 (setq expr (js2-parse-assign-expr)))
10187 (dolist (_ loops)
10188 (js2-pop-scope)))
10189 (setq result (make-js2-comp-node :pos pos
10190 :len (- js2-ts-cursor pos)
10191 :result expr
10192 :loops (nreverse loops)
10193 :filters (nreverse filters)
10194 :form form))
10195 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10196 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10197 result))
10198
10199 (defun js2-parse-comp-loop (pn &optional only-of-p)
10200 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10201 The current token should be the initial FOR.
10202 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10203 (let ((pos (js2-comp-loop-node-pos pn))
10204 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10205 (when (and (not only-of-p) (js2-match-token js2-NAME))
10206 (if (string= (js2-current-token-string) "each")
10207 (progn
10208 (setq foreach-p t
10209 each-pos (- (js2-current-token-beg) pos)) ; relative
10210 (js2-record-face 'font-lock-keyword-face))
10211 (js2-report-error "msg.no.paren.for")))
10212 (if (js2-must-match js2-LP "msg.no.paren.for")
10213 (setq lp (- (js2-current-token-beg) pos)))
10214 (setq tt (js2-peek-token))
10215 (cond
10216 ((or (= tt js2-LB)
10217 (= tt js2-LC))
10218 (js2-get-token)
10219 (setq iter (js2-parse-destruct-primary-expr))
10220 (js2-define-destruct-symbols iter js2-LET
10221 'font-lock-variable-name-face t))
10222 ((js2-match-token js2-NAME)
10223 (setq iter (js2-create-name-node)))
10224 (t
10225 (js2-report-error "msg.bad.var")))
10226 ;; Define as a let since we want the scope of the variable to
10227 ;; be restricted to the array comprehension
10228 (if (js2-name-node-p iter)
10229 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10230 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10231 (and (>= js2-language-version 200)
10232 (js2-match-contextual-kwd "of")
10233 (setq forof-p t)))
10234 (setq in-pos (- (js2-current-token-beg) pos))
10235 (js2-report-error "msg.in.after.for.name"))
10236 (setq obj (js2-parse-expr))
10237 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10238 (setq rp (- (js2-current-token-beg) pos)))
10239 (setf (js2-node-pos pn) pos
10240 (js2-node-len pn) (- js2-ts-cursor pos)
10241 (js2-comp-loop-node-iterator pn) iter
10242 (js2-comp-loop-node-object pn) obj
10243 (js2-comp-loop-node-in-pos pn) in-pos
10244 (js2-comp-loop-node-each-pos pn) each-pos
10245 (js2-comp-loop-node-foreach-p pn) foreach-p
10246 (js2-comp-loop-node-forof-p pn) forof-p
10247 (js2-comp-loop-node-lp pn) lp
10248 (js2-comp-loop-node-rp pn) rp)
10249 (js2-node-add-children pn iter obj)
10250 pn))
10251
10252 (defun js2-parse-class-stmt ()
10253 (let ((pos (js2-current-token-beg)))
10254 (js2-must-match-name "msg.unnamed.class.stmt")
10255 (js2-parse-class pos 'CLASS_STATEMENT (js2-create-name-node t))))
10256
10257 (defun js2-parse-class-expr ()
10258 (let ((pos (js2-current-token-beg))
10259 name)
10260 (when (js2-match-token js2-NAME)
10261 (setq name (js2-create-name-node t)))
10262 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10263
10264 (defun js2-parse-class (pos form name)
10265 ;; class X [extends ...] {
10266 (let (pn elems extends)
10267 (when name
10268 (js2-set-face (js2-node-pos name) (js2-node-end name)
10269 'font-lock-function-name-face 'record))
10270 (if (js2-match-token js2-EXTENDS)
10271 (if (= (js2-peek-token) js2-LC)
10272 (js2-report-error "msg.missing.extends")
10273 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10274 (setq extends (js2-parse-assign-expr))
10275 (if (not extends)
10276 (js2-report-error "msg.bad.extends"))))
10277 (js2-must-match js2-LC "msg.no.brace.class")
10278 (setq elems (js2-parse-object-literal-elems t)
10279 pn (make-js2-class-node :pos pos
10280 :len (- js2-ts-cursor pos)
10281 :form form
10282 :name name
10283 :extends extends
10284 :elems elems))
10285 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10286 pn))
10287
10288 (defun js2-parse-object-literal ()
10289 (let* ((pos (js2-current-token-beg))
10290 (elems (js2-parse-object-literal-elems))
10291 (result (make-js2-object-node :pos pos
10292 :len (- js2-ts-cursor pos)
10293 :elems elems)))
10294 (apply #'js2-node-add-children result (js2-object-node-elems result))
10295 result))
10296
10297 (defun js2-parse-object-literal-elems (&optional class-p)
10298 (let ((pos (js2-current-token-beg))
10299 (static nil)
10300 (continue t)
10301 tt elems elem after-comma)
10302 (while continue
10303 (setq static (and class-p (js2-match-token js2-STATIC))
10304 tt (js2-get-prop-name-token)
10305 elem nil)
10306 (cond
10307 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
10308 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
10309 ;; TODO(sdh): support *foo() {...}
10310 ((or (= js2-NAME tt)
10311 (= tt js2-STRING))
10312 (setq after-comma nil
10313 elem (js2-parse-named-prop tt))
10314 (if (and (null elem)
10315 (not js2-recover-from-parse-errors))
10316 (setq continue nil)))
10317 ;; {[Symbol.iterator]: ...}
10318 ((and (= tt js2-LB)
10319 (>= js2-language-version 200))
10320 (let ((expr (js2-parse-expr)))
10321 (js2-must-match js2-RB "msg.missing.computed.rb")
10322 (setq after-comma nil
10323 elem (js2-parse-plain-property expr))))
10324 ;; {12: x} or {10.7: x}
10325 ((= tt js2-NUMBER)
10326 (setq after-comma nil
10327 elem (js2-parse-plain-property (make-js2-number-node))))
10328 ;; Break out of loop, and handle trailing commas.
10329 ((or (= tt js2-RC)
10330 (= tt js2-EOF))
10331 (js2-unget-token)
10332 (setq continue nil)
10333 (if after-comma
10334 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10335 pos elems after-comma)))
10336 (t
10337 (js2-report-error "msg.bad.prop")
10338 (unless js2-recover-from-parse-errors
10339 (setq continue nil)))) ; end switch
10340 ;; Handle static for classes' codegen.
10341 (if static
10342 (if elem (js2-node-set-prop elem 'STATIC t)
10343 (js2-report-error "msg.unexpected.static")))
10344 ;; Handle commas, depending on class-p.
10345 (let ((comma (js2-match-token js2-COMMA)))
10346 (if class-p
10347 (if comma
10348 (js2-report-error "msg.class.unexpected.comma"))
10349 (if comma
10350 (setq after-comma (js2-current-token-end))
10351 (setq continue nil))))
10352 ;; Append any parsed element.
10353 (if elem (push elem elems))) ; end loop
10354 (js2-must-match js2-RC "msg.no.brace.prop")
10355 (nreverse elems)))
10356
10357 (defun js2-parse-named-prop (tt)
10358 "Parse a name, string, or getter/setter object property.
10359 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10360 (let ((string-prop (and (= tt js2-STRING)
10361 (make-js2-string-node)))
10362 expr
10363 (ppos (js2-current-token-beg))
10364 (pend (js2-current-token-end))
10365 (name (js2-create-name-node))
10366 (prop (js2-current-token-string)))
10367 (cond
10368 ;; getter/setter prop
10369 ((and (= tt js2-NAME)
10370 (= (js2-peek-token) js2-NAME)
10371 (or (string= prop "get")
10372 (string= prop "set")))
10373 (js2-get-token)
10374 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
10375 (js2-record-face 'font-lock-function-name-face) ; for peeked name
10376 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
10377 (js2-parse-getter-setter-prop ppos name prop))
10378 ;; method definition: {f() {...}}
10379 ((and (= (js2-peek-token) js2-LP)
10380 (>= js2-language-version 200))
10381 (js2-record-face 'font-lock-function-name-face) ; name
10382 (js2-parse-getter-setter-prop ppos name ""))
10383 ;; regular prop
10384 (t
10385 (prog1
10386 (setq expr (js2-parse-plain-property (or string-prop name)))
10387 (when (and (not string-prop)
10388 (not js2-is-in-destructuring)
10389 js2-highlight-external-variables
10390 (js2-node-get-prop expr 'SHORTHAND))
10391 (js2-record-name-node name))
10392 (js2-set-face ppos pend
10393 (if (js2-function-node-p
10394 (js2-object-prop-node-right expr))
10395 'font-lock-function-name-face
10396 'font-lock-variable-name-face)
10397 'record))))))
10398
10399 (defun js2-parse-plain-property (prop)
10400 "Parse a non-getter/setter property in an object literal.
10401 PROP is the node representing the property: a number, name or string."
10402 (let* ((tt (js2-get-token))
10403 (pos (js2-node-pos prop))
10404 colon expr result)
10405 (cond
10406 ;; Abbreviated property, as in {foo, bar}
10407 ((and (>= js2-language-version 200)
10408 (or (= tt js2-COMMA)
10409 (= tt js2-RC))
10410 (not (js2-number-node-p prop)))
10411 (js2-unget-token)
10412 (setq result (make-js2-object-prop-node
10413 :pos pos
10414 :left prop
10415 :right prop
10416 :op-pos (js2-current-token-len)))
10417 (js2-node-add-children result prop)
10418 (js2-node-set-prop result 'SHORTHAND t)
10419 result)
10420 ;; Normal property
10421 (t
10422 (if (= tt js2-COLON)
10423 (setq colon (- (js2-current-token-beg) pos)
10424 expr (js2-parse-assign-expr))
10425 (js2-report-error "msg.no.colon.prop")
10426 (setq expr (make-js2-error-node)))
10427 (setq result (make-js2-object-prop-node
10428 :pos pos
10429 ;; don't include last consumed token in length
10430 :len (- (+ (js2-node-pos expr)
10431 (js2-node-len expr))
10432 pos)
10433 :left prop
10434 :right expr
10435 :op-pos colon))
10436 (js2-node-add-children result prop expr)
10437 result))))
10438
10439 (defun js2-parse-getter-setter-prop (pos prop type-string)
10440 "Parse getter or setter property in an object literal.
10441 JavaScript syntax is:
10442
10443 { get foo() {...}, set foo(x) {...} }
10444
10445 and expression closure style is also supported
10446
10447 { get foo() x, set foo(x) _x = x }
10448
10449 POS is the start position of the `get' or `set' keyword.
10450 PROP is the `js2-name-node' representing the property name.
10451 GET-P is non-nil if the keyword was `get'."
10452 (let ((type (cond
10453 ((string= "get" type-string) js2-GET)
10454 ((string= "set" type-string) js2-SET)
10455 (t js2-FUNCTION)))
10456 result end
10457 (fn (js2-parse-function-expr)))
10458 ;; it has to be an anonymous function, as we already parsed the name
10459 (if (/= (js2-node-type fn) js2-FUNCTION)
10460 (js2-report-error "msg.bad.prop")
10461 (if (cl-plusp (length (js2-function-name fn)))
10462 (js2-report-error "msg.bad.prop")))
10463 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10464 (setq end (js2-node-end fn)
10465 result (make-js2-getter-setter-node :type type
10466 :pos pos
10467 :len (- end pos)
10468 :left prop
10469 :right fn))
10470 (js2-node-add-children result prop fn)
10471 result))
10472
10473 (defun js2-create-name-node (&optional check-activation-p token string)
10474 "Create a name node using the current token and, optionally, STRING.
10475 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10476 (let* ((beg (js2-current-token-beg))
10477 (tt (js2-current-token-type))
10478 (s (or string
10479 (if (= js2-NAME tt)
10480 (js2-current-token-string)
10481 (js2-tt-name tt))))
10482 name)
10483 (setq name (make-js2-name-node :pos beg
10484 :name s
10485 :len (length s)))
10486 (if check-activation-p
10487 (js2-check-activation-name s (or token js2-NAME)))
10488 name))
10489
10490 ;;; Indentation support
10491
10492 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10493 ;; Karl cleverly deduces that the desired indentation level is often a
10494 ;; function of paren/bracket/brace nesting depth, which can be determined
10495 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10496 ;; then does some equally clever checks to see if we're in the context of a
10497 ;; substatement of a possibly braceless statement keyword such as if, while,
10498 ;; or finally. This approach yields pretty good results.
10499
10500 ;; The indenter is often "wrong", however, and needs to be overridden.
10501 ;; The right long-term solution is probably to emulate (or integrate
10502 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10503 ;; parse tree from `js2-parse' is present, which is not true at the
10504 ;; moment the user is typing, computing indentation is still thousands
10505 ;; of lines of code to handle every possible syntactic edge case.
10506
10507 ;; In the meantime, the compromise solution is that we offer a "bounce
10508 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10509 ;; current line indent among various likely guess points. This approach
10510 ;; is far from perfect, but should at least make it slightly easier to
10511 ;; move the line towards its desired indentation when manually
10512 ;; overriding Karl's heuristic nesting guesser.
10513
10514 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10515 ;; extensions such as `let' and Array comprehensions. Major kudos to
10516 ;; Karl for coming up with the initial approach, which packs a lot of
10517 ;; punch for so little code.
10518
10519 (defconst js2-possibly-braceless-keywords-re
10520 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10521 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10522 "try" "while" "with" "let")))
10523 "Regular expression matching keywords that are optionally
10524 followed by an opening brace.")
10525
10526 (defconst js2-indent-operator-re
10527 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10528 (regexp-opt '("in" "instanceof") 'words))
10529 "Regular expression matching operators that affect indentation
10530 of continued expressions.")
10531
10532 (defconst js2-declaration-keyword-re
10533 (regexp-opt '("var" "let" "const") 'words)
10534 "Regular expression matching variable declaration keywords.")
10535
10536 (defun js2-re-search-forward-inner (regexp &optional bound count)
10537 "Auxiliary function for `js2-re-search-forward'."
10538 (let (parse saved-point)
10539 (while (> count 0)
10540 (re-search-forward regexp bound)
10541 (setq parse (if saved-point
10542 (parse-partial-sexp saved-point (point))
10543 (syntax-ppss (point))))
10544 (cond ((nth 3 parse)
10545 (re-search-forward
10546 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10547 (save-excursion (end-of-line) (point)) t))
10548 ((nth 7 parse)
10549 (forward-line))
10550 ((or (nth 4 parse)
10551 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10552 (re-search-forward "\\*/"))
10553 (t
10554 (setq count (1- count))))
10555 (setq saved-point (point))))
10556 (point))
10557
10558 (defun js2-re-search-forward (regexp &optional bound noerror count)
10559 "Search forward but ignore strings and comments.
10560 Invokes `re-search-forward' but treats the buffer as if strings
10561 and comments have been removed."
10562 (let ((saved-point (point)))
10563 (condition-case err
10564 (cond ((null count)
10565 (js2-re-search-forward-inner regexp bound 1))
10566 ((< count 0)
10567 (js2-re-search-backward-inner regexp bound (- count)))
10568 ((> count 0)
10569 (js2-re-search-forward-inner regexp bound count)))
10570 (search-failed
10571 (goto-char saved-point)
10572 (unless noerror
10573 (error (error-message-string err)))))))
10574
10575 (defun js2-re-search-backward-inner (regexp &optional bound count)
10576 "Auxiliary function for `js2-re-search-backward'."
10577 (let (parse)
10578 (while (> count 0)
10579 (re-search-backward regexp bound)
10580 (setq parse (syntax-ppss (point)))
10581 (cond ((nth 3 parse)
10582 (re-search-backward
10583 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10584 (line-beginning-position) t))
10585 ((nth 7 parse)
10586 (goto-char (nth 8 parse)))
10587 ((or (nth 4 parse)
10588 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10589 (re-search-backward "/\\*"))
10590 (t
10591 (setq count (1- count))))))
10592 (point))
10593
10594 (defun js2-re-search-backward (regexp &optional bound noerror count)
10595 "Search backward but ignore strings and comments.
10596 Invokes `re-search-backward' but treats the buffer as if strings
10597 and comments have been removed."
10598 (let ((saved-point (point)))
10599 (condition-case err
10600 (cond ((null count)
10601 (js2-re-search-backward-inner regexp bound 1))
10602 ((< count 0)
10603 (js2-re-search-forward-inner regexp bound (- count)))
10604 ((> count 0)
10605 (js2-re-search-backward-inner regexp bound count)))
10606 (search-failed
10607 (goto-char saved-point)
10608 (unless noerror
10609 (error (error-message-string err)))))))
10610
10611 (defun js2-looking-at-operator-p ()
10612 "Return non-nil if text after point is a non-comma operator."
10613 (and (looking-at js2-indent-operator-re)
10614 (or (not (looking-at ":"))
10615 (save-excursion
10616 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10617 (looking-at "?"))))))
10618
10619 (defun js2-continued-expression-p ()
10620 "Return non-nil if the current line continues an expression."
10621 (save-excursion
10622 (back-to-indentation)
10623 (or (js2-looking-at-operator-p)
10624 (when (catch 'found
10625 (while (and (re-search-backward "\n" nil t)
10626 (let ((state (syntax-ppss)))
10627 (when (nth 4 state)
10628 (goto-char (nth 8 state))) ;; skip comments
10629 (skip-chars-backward " \t")
10630 (if (bolp)
10631 t
10632 (throw 'found t))))))
10633 (backward-char)
10634 (when (js2-looking-at-operator-p)
10635 (backward-char)
10636 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10637
10638 (defun js2-end-of-do-while-loop-p ()
10639 "Return non-nil if word after point is `while' of a do-while
10640 statement, else returns nil. A braceless do-while statement
10641 spanning several lines requires that the start of the loop is
10642 indented to the same column as the current line."
10643 (interactive)
10644 (save-excursion
10645 (when (looking-at "\\s-*\\<while\\>")
10646 (if (save-excursion
10647 (skip-chars-backward "[ \t\n]*}")
10648 (looking-at "[ \t\n]*}"))
10649 (save-excursion
10650 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10651 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10652 (or (looking-at "\\<do\\>")
10653 (let ((saved-indent (current-indentation)))
10654 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10655 (/= (current-indentation) saved-indent)))
10656 (and (looking-at "[ \t]*\\<do\\>")
10657 (not (js2-re-search-forward
10658 "\\<while\\>" (point-at-eol) t))
10659 (= (current-indentation) saved-indent))))))))
10660
10661 (defun js2-multiline-decl-indentation ()
10662 "Return the declaration indentation column if the current line belongs
10663 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10664 (let (forward-sexp-function ; use Lisp version
10665 at-opening-bracket)
10666 (save-excursion
10667 (back-to-indentation)
10668 (when (not (looking-at js2-declaration-keyword-re))
10669 (when (looking-at js2-indent-operator-re)
10670 (goto-char (match-end 0))) ; continued expressions are ok
10671 (while (and (not at-opening-bracket)
10672 (not (bobp))
10673 (let ((pos (point)))
10674 (save-excursion
10675 (js2-backward-sws)
10676 (or (eq (char-before) ?,)
10677 (and (not (eq (char-before) ?\;))
10678 (prog2 (skip-syntax-backward ".")
10679 (looking-at js2-indent-operator-re)
10680 (js2-backward-sws))
10681 (not (eq (char-before) ?\;)))
10682 (js2-same-line pos)))))
10683 (condition-case _
10684 (backward-sexp)
10685 (scan-error (setq at-opening-bracket t))))
10686 (when (looking-at js2-declaration-keyword-re)
10687 (goto-char (match-end 0))
10688 (1+ (current-column)))))))
10689
10690 (defun js2-ctrl-statement-indentation ()
10691 "Return the proper indentation of current line if it is a control statement.
10692 Returns an indentation if this line starts the body of a control
10693 statement without braces, else returns nil."
10694 (let (forward-sexp-function)
10695 (save-excursion
10696 (back-to-indentation)
10697 (when (and (not (js2-same-line (point-min)))
10698 (not (looking-at "{"))
10699 (js2-re-search-backward "[[:graph:]]" nil t)
10700 (not (looking-at "[{([]"))
10701 (progn
10702 (forward-char)
10703 (when (= (char-before) ?\))
10704 ;; scan-sexps sometimes throws an error
10705 (ignore-errors (backward-sexp))
10706 (skip-chars-backward " \t" (point-at-bol)))
10707 (let ((pt (point)))
10708 (back-to-indentation)
10709 (when (looking-at "}[ \t]*")
10710 (goto-char (match-end 0)))
10711 (and (looking-at js2-possibly-braceless-keywords-re)
10712 (= (match-end 0) pt)
10713 (not (js2-end-of-do-while-loop-p))))))
10714 (+ (current-indentation) js2-basic-offset)))))
10715
10716 (defun js2-indent-in-array-comp (parse-status)
10717 "Return non-nil if we think we're in an array comprehension.
10718 In particular, return the buffer position of the first `for' kwd."
10719 (let ((bracket (nth 1 parse-status))
10720 (end (point)))
10721 (when bracket
10722 (save-excursion
10723 (goto-char bracket)
10724 (when (looking-at "\\[")
10725 (forward-char 1)
10726 (js2-forward-sws)
10727 (if (looking-at "[[{]")
10728 (let (forward-sexp-function) ; use Lisp version
10729 (forward-sexp) ; skip destructuring form
10730 (js2-forward-sws)
10731 (if (and (/= (char-after) ?,) ; regular array
10732 (looking-at "for"))
10733 (match-beginning 0)))
10734 ;; to skip arbitrary expressions we need the parser,
10735 ;; so we'll just guess at it.
10736 (if (and (> end (point)) ; not empty literal
10737 (re-search-forward "[^,]]* \\(for\\) " end t)
10738 ;; not inside comment or string literal
10739 (let ((state (parse-partial-sexp bracket (point))))
10740 (not (or (nth 3 state) (nth 4 state)))))
10741 (match-beginning 1))))))))
10742
10743 (defun js2-array-comp-indentation (parse-status for-kwd)
10744 (if (js2-same-line for-kwd)
10745 ;; first continuation line
10746 (save-excursion
10747 (goto-char (nth 1 parse-status))
10748 (forward-char 1)
10749 (skip-chars-forward " \t")
10750 (current-column))
10751 (save-excursion
10752 (goto-char for-kwd)
10753 (current-column))))
10754
10755 (defun js2-proper-indentation (parse-status)
10756 "Return the proper indentation for the current line."
10757 (save-excursion
10758 (back-to-indentation)
10759 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10760 (at-closing-bracket (looking-at "[]})]"))
10761 (same-indent-p (or at-closing-bracket
10762 (looking-at "\\<case\\>[^:]")
10763 (and (looking-at "\\<default:")
10764 (save-excursion
10765 (js2-backward-sws)
10766 (not (memq (char-before) '(?, ?{)))))))
10767 (continued-expr-p (js2-continued-expression-p))
10768 (declaration-indent (and js2-pretty-multiline-declarations
10769 (js2-multiline-decl-indentation)))
10770 (bracket (nth 1 parse-status))
10771 beg indent)
10772 (cond
10773 ;; indent array comprehension continuation lines specially
10774 ((and bracket
10775 (>= js2-language-version 170)
10776 (not (js2-same-line bracket))
10777 (setq beg (js2-indent-in-array-comp parse-status))
10778 (>= (point) (save-excursion
10779 (goto-char beg)
10780 (point-at-bol)))) ; at or after first loop?
10781 (js2-array-comp-indentation parse-status beg))
10782
10783 (ctrl-stmt-indent)
10784
10785 ((and declaration-indent continued-expr-p)
10786 (+ declaration-indent js2-basic-offset))
10787
10788 (declaration-indent)
10789
10790 (bracket
10791 (goto-char bracket)
10792 (cond
10793 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10794 (when (save-excursion (skip-chars-backward " \t)")
10795 (looking-at ")"))
10796 (backward-list))
10797 (back-to-indentation)
10798 (and (eq js2-pretty-multiline-declarations 'all)
10799 (looking-at js2-declaration-keyword-re)
10800 (goto-char (1+ (match-end 0))))
10801 (setq indent
10802 (cond (same-indent-p
10803 (current-column))
10804 (continued-expr-p
10805 (+ (current-column) (* 2 js2-basic-offset)))
10806 (t
10807 (+ (current-column) js2-basic-offset))))
10808 (if (and js2-indent-switch-body
10809 (not at-closing-bracket)
10810 (looking-at "\\_<switch\\_>"))
10811 (+ indent js2-basic-offset)
10812 indent))
10813 (t
10814 (unless same-indent-p
10815 (forward-char)
10816 (skip-chars-forward " \t"))
10817 (current-column))))
10818
10819 (continued-expr-p js2-basic-offset)
10820
10821 (t 0)))))
10822
10823 (defun js2-lineup-comment (parse-status)
10824 "Indent a multi-line block comment continuation line."
10825 (let* ((beg (nth 8 parse-status))
10826 (first-line (js2-same-line beg))
10827 (offset (save-excursion
10828 (goto-char beg)
10829 (if (looking-at "/\\*")
10830 (+ 1 (current-column))
10831 0))))
10832 (unless first-line
10833 (indent-line-to offset))))
10834
10835 (defun js2-backward-sws ()
10836 "Move backward through whitespace and comments."
10837 (interactive)
10838 (while (forward-comment -1)))
10839
10840 (defun js2-forward-sws ()
10841 "Move forward through whitespace and comments."
10842 (interactive)
10843 (while (forward-comment 1)))
10844
10845 (defun js2-current-indent (&optional pos)
10846 "Return column of indentation on current line.
10847 If POS is non-nil, go to that point and return indentation for that line."
10848 (save-excursion
10849 (if pos
10850 (goto-char pos))
10851 (back-to-indentation)
10852 (current-column)))
10853
10854 (defun js2-arglist-close ()
10855 "Return non-nil if we're on a line beginning with a close-paren/brace."
10856 (save-excursion
10857 (goto-char (point-at-bol))
10858 (js2-forward-sws)
10859 (looking-at "[])}]")))
10860
10861 (defun js2-indent-looks-like-label-p ()
10862 (goto-char (point-at-bol))
10863 (js2-forward-sws)
10864 (looking-at (concat js2-mode-identifier-re ":")))
10865
10866 (defun js2-indent-in-objlit-p (parse-status)
10867 "Return non-nil if this looks like an object-literal entry."
10868 (let ((start (nth 1 parse-status)))
10869 (and
10870 start
10871 (save-excursion
10872 (and (zerop (forward-line -1))
10873 (not (< (point) start)) ; crossed a {} boundary
10874 (js2-indent-looks-like-label-p)))
10875 (save-excursion
10876 (js2-indent-looks-like-label-p)))))
10877
10878 ;; If prev line looks like foobar({ then we're passing an object
10879 ;; literal to a function call, and people pretty much always want to
10880 ;; de-dent back to the previous line, so move the 'basic-offset'
10881 ;; position to the front.
10882 (defun js2-indent-objlit-arg-p (parse-status)
10883 (save-excursion
10884 (back-to-indentation)
10885 (js2-backward-sws)
10886 (and (eq (1- (point)) (nth 1 parse-status))
10887 (eq (char-before) ?{)
10888 (progn
10889 (forward-char -1)
10890 (skip-chars-backward " \t")
10891 (eq (char-before) ?\()))))
10892
10893 (defun js2-indent-case-block-p ()
10894 (save-excursion
10895 (back-to-indentation)
10896 (js2-backward-sws)
10897 (goto-char (point-at-bol))
10898 (skip-chars-forward " \t")
10899 (looking-at "case\\s-.+:")))
10900
10901 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10902 "Cycle among alternate computed indentation positions.
10903 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10904 of the buffer to the current point. NORMAL-COL is the indentation
10905 column computed by the heuristic guesser based on current paren,
10906 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10907 in reverse."
10908 (let ((cur-indent (js2-current-indent))
10909 (old-buffer-undo-list buffer-undo-list)
10910 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10911 (current-line (save-excursion
10912 (forward-line 0) ; move to bol
10913 (1+ (count-lines (point-min) (point)))))
10914 positions pos main-pos anchor arglist-cont same-indent
10915 basic-offset computed-pos)
10916 ;; temporarily don't record undo info, if user requested this
10917 (when js2-mode-indent-inhibit-undo
10918 (setq buffer-undo-list t))
10919 (unwind-protect
10920 (progn
10921 ;; First likely point: indent from beginning of previous code line
10922 (push (setq basic-offset
10923 (+ (save-excursion
10924 (back-to-indentation)
10925 (js2-backward-sws)
10926 (back-to-indentation)
10927 (current-column))
10928 js2-basic-offset))
10929 positions)
10930
10931 ;; (First + epsilon) likely point: indent 2x from beginning of
10932 ;; previous code line. Google does it this way.
10933 (push (setq basic-offset
10934 (+ (save-excursion
10935 (back-to-indentation)
10936 (js2-backward-sws)
10937 (back-to-indentation)
10938 (current-column))
10939 (* 2 js2-basic-offset)))
10940 positions)
10941
10942 ;; Second likely point: indent from assign-expr RHS. This
10943 ;; is just a crude guess based on finding " = " on the previous
10944 ;; line containing actual code.
10945 (setq pos (save-excursion
10946 (forward-line -1)
10947 (goto-char (point-at-bol))
10948 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10949 (point-at-eol) t)
10950 (goto-char (match-end 1))
10951 (skip-chars-forward " \t\r\n")
10952 (current-column))))
10953 (when pos
10954 (cl-incf pos js2-basic-offset)
10955 (push pos positions))
10956
10957 ;; Third likely point: same indent as previous line of code.
10958 ;; Make it the first likely point if we're not on an
10959 ;; arglist-close line and previous line ends in a comma, or
10960 ;; both this line and prev line look like object-literal
10961 ;; elements.
10962 (setq pos (save-excursion
10963 (goto-char (point-at-bol))
10964 (js2-backward-sws)
10965 (back-to-indentation)
10966 (prog1
10967 (current-column)
10968 ;; while we're here, look for trailing comma
10969 (if (save-excursion
10970 (goto-char (point-at-eol))
10971 (js2-backward-sws)
10972 (eq (char-before) ?,))
10973 (setq arglist-cont (1- (point)))))))
10974 (when pos
10975 (if (and (or arglist-cont
10976 (js2-indent-in-objlit-p parse-status))
10977 (not (js2-arglist-close)))
10978 (setq same-indent pos))
10979 (push pos positions))
10980
10981 ;; Fourth likely point: first preceding code with less indentation.
10982 ;; than the immediately preceding code line.
10983 (setq pos (save-excursion
10984 (back-to-indentation)
10985 (js2-backward-sws)
10986 (back-to-indentation)
10987 (setq anchor (current-column))
10988 (while (and (zerop (forward-line -1))
10989 (>= (progn
10990 (back-to-indentation)
10991 (current-column))
10992 anchor)))
10993 (setq pos (current-column))))
10994 (push pos positions)
10995
10996 ;; nesting-heuristic position, main by default
10997 (push (setq main-pos normal-col) positions)
10998
10999 ;; delete duplicates and sort positions list
11000 (setq positions (sort (delete-dups positions) '<))
11001
11002 ;; comma-list continuation lines: prev line indent takes precedence
11003 (if same-indent
11004 (setq main-pos same-indent))
11005
11006 ;; common special cases where we want to indent in from previous line
11007 (if (or (js2-indent-case-block-p)
11008 (js2-indent-objlit-arg-p parse-status))
11009 (setq main-pos basic-offset))
11010
11011 ;; if bouncing backwards, reverse positions list
11012 (if backwards
11013 (setq positions (reverse positions)))
11014
11015 ;; record whether we're already sitting on one of the alternatives
11016 (setq pos (member cur-indent positions))
11017
11018 (cond
11019 ;; case 0: we're one one of the alternatives and this is the
11020 ;; first time they've pressed TAB on this line (best-guess).
11021 ((and js2-mode-indent-ignore-first-tab
11022 pos
11023 ;; first time pressing TAB on this line?
11024 (not (eq js2-mode-last-indented-line current-line)))
11025 ;; do nothing
11026 (setq computed-pos nil))
11027 ;; case 1: only one computed position => use it
11028 ((null (cdr positions))
11029 (setq computed-pos 0))
11030 ;; case 2: not on any of the computed spots => use main spot
11031 ((not pos)
11032 (setq computed-pos (js2-position main-pos positions)))
11033 ;; case 3: on last position: cycle to first position
11034 ((null (cdr pos))
11035 (setq computed-pos 0))
11036 ;; case 4: on intermediate position: cycle to next position
11037 (t
11038 (setq computed-pos (js2-position (cl-second pos) positions))))
11039
11040 ;; see if any hooks want to indent; otherwise we do it
11041 (cl-loop with result = nil
11042 for hook in js2-indent-hook
11043 while (null result)
11044 do
11045 (setq result (funcall hook positions computed-pos))
11046 finally do
11047 (unless (or result (null computed-pos))
11048 (indent-line-to (nth computed-pos positions)))))
11049
11050 ;; finally
11051 (if js2-mode-indent-inhibit-undo
11052 (setq buffer-undo-list old-buffer-undo-list))
11053 ;; see commentary for `js2-mode-last-indented-line'
11054 (setq js2-mode-last-indented-line current-line))))
11055
11056 (defun js2-indent-bounce-backwards ()
11057 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11058 cycles between the computed indentation positions in reverse order."
11059 (interactive)
11060 (js2-indent-line t))
11061
11062 (defun js2-1-line-comment-continuation-p ()
11063 "Return t if we're in a 1-line comment continuation.
11064 If so, we don't ever want to use bounce-indent."
11065 (save-excursion
11066 (and (progn
11067 (forward-line 0)
11068 (looking-at "\\s-*//"))
11069 (progn
11070 (forward-line -1)
11071 (forward-line 0)
11072 (when (looking-at "\\s-*$")
11073 (js2-backward-sws)
11074 (forward-line 0))
11075 (looking-at "\\s-*//")))))
11076
11077 (defun js2-indent-line (&optional bounce-backwards)
11078 "Indent the current line as JavaScript source text."
11079 (interactive)
11080 (let (parse-status offset indent-col
11081 ;; Don't whine about errors/warnings when we're indenting.
11082 ;; This has to be set before calling parse-partial-sexp below.
11083 (inhibit-point-motion-hooks t))
11084 (setq parse-status (save-excursion
11085 (syntax-ppss (point-at-bol)))
11086 offset (- (point) (save-excursion
11087 (back-to-indentation)
11088 (point))))
11089 (js2-with-underscore-as-word-syntax
11090 (if (nth 4 parse-status)
11091 (js2-lineup-comment parse-status)
11092 (setq indent-col (js2-proper-indentation parse-status))
11093 ;; See comments below about `js2-mode-last-indented-line'.
11094 (cond
11095 ;; bounce-indenting is disabled during electric-key indent.
11096 ;; It doesn't work well on first line of buffer.
11097 ((and js2-bounce-indent-p
11098 (not (js2-same-line (point-min)))
11099 (not (js2-1-line-comment-continuation-p)))
11100 (js2-bounce-indent indent-col parse-status bounce-backwards))
11101 ;; just indent to the guesser's likely spot
11102 (t (indent-line-to indent-col))))
11103 (when (cl-plusp offset)
11104 (forward-char offset)))))
11105
11106 (defun js2-indent-region (start end)
11107 "Indent the region, but don't use bounce indenting."
11108 (let ((js2-bounce-indent-p nil)
11109 (indent-region-function nil)
11110 (after-change-functions (remq 'js2-mode-edit
11111 after-change-functions)))
11112 (indent-region start end nil) ; nil for byte-compiler
11113 (js2-mode-edit start end (- end start))))
11114
11115 (defvar js2-minor-mode-map
11116 (let ((map (make-sparse-keymap)))
11117 (define-key map (kbd "C-c C-`") #'js2-next-error)
11118 (define-key map [mouse-1] #'js2-mode-show-node)
11119 map)
11120 "Keymap used when `js2-minor-mode' is active.")
11121
11122 ;;;###autoload
11123 (define-minor-mode js2-minor-mode
11124 "Minor mode for running js2 as a background linter.
11125 This allows you to use a different major mode for JavaScript editing,
11126 such as `js-mode', while retaining the asynchronous error/warning
11127 highlighting features of `js2-mode'."
11128 :group 'js2-mode
11129 :lighter " js-lint"
11130 (if js2-minor-mode
11131 (js2-minor-mode-enter)
11132 (js2-minor-mode-exit)))
11133
11134 (defun js2-minor-mode-enter ()
11135 "Initialization for `js2-minor-mode'."
11136 (set (make-local-variable 'max-lisp-eval-depth)
11137 (max max-lisp-eval-depth 3000))
11138 (setq next-error-function #'js2-next-error)
11139 (js2-set-default-externs)
11140 ;; Experiment: make reparse-delay longer for longer files.
11141 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11142 (setq js2-idle-timer-delay
11143 (* js2-idle-timer-delay
11144 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11145 (setq js2-mode-buffer-dirty-p t
11146 js2-mode-parsing nil)
11147 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11148 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11149 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11150 (when js2-include-jslint-globals
11151 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11152 (run-hooks 'js2-init-hook)
11153 (js2-reparse))
11154
11155 (defun js2-minor-mode-exit ()
11156 "Turn off `js2-minor-mode'."
11157 (setq next-error-function nil)
11158 (remove-hook 'after-change-functions #'js2-mode-edit t)
11159 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11160 (when js2-mode-node-overlay
11161 (delete-overlay js2-mode-node-overlay)
11162 (setq js2-mode-node-overlay nil))
11163 (js2-remove-overlays)
11164 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11165 (setq js2-mode-ast nil))
11166
11167 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11168 (make-variable-buffer-local 'js2-source-buffer)
11169
11170 (cl-defun js2-display-error-list ()
11171 "Display a navigable buffer listing parse errors/warnings."
11172 (interactive)
11173 (unless (js2-have-errors-p)
11174 (message "No errors")
11175 (cl-return-from js2-display-error-list))
11176 (cl-labels ((annotate-list
11177 (lst type)
11178 "Add diagnostic TYPE and line number to errs list"
11179 (mapcar (lambda (err)
11180 (list err type (line-number-at-pos (nth 1 err))))
11181 lst)))
11182 (let* ((srcbuf (current-buffer))
11183 (errbuf (get-buffer-create "*js-lint*"))
11184 (errors (annotate-list
11185 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11186 'js2-error)) ; must be a valid face name
11187 (warnings (annotate-list
11188 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11189 'js2-warning)) ; must be a valid face name
11190 (all-errs (sort (append errors warnings)
11191 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11192 (with-current-buffer errbuf
11193 (let ((inhibit-read-only t))
11194 (erase-buffer)
11195 (dolist (err all-errs)
11196 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11197 (insert-text-button
11198 (format "line %d: %s" line (js2-get-msg msg-key))
11199 'face type
11200 'follow-link "\C-m"
11201 'action 'js2-error-buffer-jump
11202 'js2-msg (js2-get-msg msg-key)
11203 'js2-pos beg)
11204 (insert "\n"))))
11205 (js2-error-buffer-mode)
11206 (setq js2-source-buffer srcbuf)
11207 (pop-to-buffer errbuf)
11208 (goto-char (point-min))
11209 (unless (eobp)
11210 (js2-error-buffer-view))))))
11211
11212 (defvar js2-error-buffer-mode-map
11213 (let ((map (make-sparse-keymap)))
11214 (define-key map "n" #'js2-error-buffer-next)
11215 (define-key map "p" #'js2-error-buffer-prev)
11216 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11217 (define-key map "o" #'js2-error-buffer-view)
11218 (define-key map "q" #'js2-error-buffer-quit)
11219 map)
11220 "Keymap used for js2 diagnostics buffers.")
11221
11222 (defun js2-error-buffer-mode ()
11223 "Major mode for js2 diagnostics buffers.
11224 Selecting an error will jump it to the corresponding source-buffer error.
11225 \\{js2-error-buffer-mode-map}"
11226 (interactive)
11227 (setq major-mode 'js2-error-buffer-mode
11228 mode-name "JS Lint Diagnostics")
11229 (use-local-map js2-error-buffer-mode-map)
11230 (setq truncate-lines t)
11231 (set-buffer-modified-p nil)
11232 (setq buffer-read-only t)
11233 (run-hooks 'js2-error-buffer-mode-hook))
11234
11235 (defun js2-error-buffer-next ()
11236 "Move to next error and view it."
11237 (interactive)
11238 (when (zerop (forward-line 1))
11239 (js2-error-buffer-view)))
11240
11241 (defun js2-error-buffer-prev ()
11242 "Move to previous error and view it."
11243 (interactive)
11244 (when (zerop (forward-line -1))
11245 (js2-error-buffer-view)))
11246
11247 (defun js2-error-buffer-quit ()
11248 "Kill the current buffer."
11249 (interactive)
11250 (kill-buffer))
11251
11252 (defun js2-error-buffer-jump (&rest ignored)
11253 "Jump cursor to current error in source buffer."
11254 (interactive)
11255 (when (js2-error-buffer-view)
11256 (pop-to-buffer js2-source-buffer)))
11257
11258 (defun js2-error-buffer-view ()
11259 "Scroll source buffer to show error at current line."
11260 (interactive)
11261 (cond
11262 ((not (eq major-mode 'js2-error-buffer-mode))
11263 (message "Not in a js2 errors buffer"))
11264 ((not (buffer-live-p js2-source-buffer))
11265 (message "Source buffer has been killed"))
11266 ((not (wholenump (get-text-property (point) 'js2-pos)))
11267 (message "There does not seem to be an error here"))
11268 (t
11269 (let ((pos (get-text-property (point) 'js2-pos))
11270 (msg (get-text-property (point) 'js2-msg)))
11271 (save-selected-window
11272 (pop-to-buffer js2-source-buffer)
11273 (goto-char pos)
11274 (message msg))))))
11275
11276 ;;;###autoload
11277 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11278 ;; FIXME: Should derive from js-mode.
11279 "Major mode for editing JavaScript code."
11280 ;; Used by comment-region; don't change it.
11281 (set (make-local-variable 'comment-start) "//")
11282 (set (make-local-variable 'comment-end) "")
11283 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11284 (set (make-local-variable 'max-lisp-eval-depth)
11285 (max max-lisp-eval-depth 3000))
11286 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11287 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11288 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11289 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11290 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11291 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11292 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11293 ;; for characters inside regexp literals.
11294 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11295 ;; this is necessary to make `show-paren-function' work properly
11296 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11297 ;; needed for M-x rgrep, among other things
11298 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11299
11300 (set (make-local-variable 'electric-indent-chars)
11301 (append "{}()[]:;,*." electric-indent-chars))
11302 (set (make-local-variable 'electric-layout-rules)
11303 '((?\; . after) (?\{ . after) (?\} . before)))
11304
11305 ;; some variables needed by cc-engine for paragraph-fill, etc.
11306 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11307 c-comment-start-regexp "/[*/]\\|\\s|"
11308 c-line-comment-starter "//"
11309 c-paragraph-start js2-paragraph-start
11310 c-paragraph-separate "$"
11311 c-syntactic-ws-start js2-syntactic-ws-start
11312 c-syntactic-ws-end js2-syntactic-ws-end
11313 c-syntactic-eol js2-syntactic-eol)
11314
11315 (let ((c-buffer-is-cc-mode t))
11316 ;; Copied from `js-mode'. Also see Bug#6071.
11317 (make-local-variable 'paragraph-start)
11318 (make-local-variable 'paragraph-separate)
11319 (make-local-variable 'paragraph-ignore-fill-prefix)
11320 (make-local-variable 'adaptive-fill-mode)
11321 (make-local-variable 'adaptive-fill-regexp)
11322 (c-setup-paragraph-variables))
11323
11324 (setq font-lock-defaults '(nil t))
11325
11326 ;; Experiment: make reparse-delay longer for longer files.
11327 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11328 (setq js2-idle-timer-delay
11329 (* js2-idle-timer-delay
11330 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11331
11332 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11333 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11334 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11335 (setq next-error-function #'js2-next-error)
11336 (imenu-add-to-menubar (concat "IM-" mode-name))
11337 (add-to-invisibility-spec '(js2-outline . t))
11338 (set (make-local-variable 'line-move-ignore-invisible) t)
11339 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11340
11341 (setq js2-mode-functions-hidden nil
11342 js2-mode-comments-hidden nil
11343 js2-mode-buffer-dirty-p t
11344 js2-mode-parsing nil)
11345
11346 (js2-set-default-externs)
11347
11348 (when js2-include-jslint-globals
11349 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11350
11351 (run-hooks 'js2-init-hook)
11352
11353 (js2-reparse))
11354
11355 (defun js2-mode-exit ()
11356 "Exit `js2-mode' and clean up."
11357 (interactive)
11358 (when js2-mode-node-overlay
11359 (delete-overlay js2-mode-node-overlay)
11360 (setq js2-mode-node-overlay nil))
11361 (js2-remove-overlays)
11362 (setq js2-mode-ast nil)
11363 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11364 (remove-from-invisibility-spec '(js2-outline . t))
11365 (js2-mode-show-all)
11366 (with-silent-modifications
11367 (js2-clear-face (point-min) (point-max))))
11368
11369 (defun js2-mode-reset-timer ()
11370 "Cancel any existing parse timer and schedule a new one."
11371 (if js2-mode-parse-timer
11372 (cancel-timer js2-mode-parse-timer))
11373 (setq js2-mode-parsing nil)
11374 (let ((timer (timer-create)))
11375 (setq js2-mode-parse-timer timer)
11376 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11377 (timer-set-idle-time timer js2-idle-timer-delay)
11378 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11379 (timer-activate-when-idle timer nil)))
11380
11381 (defun js2-mode-idle-reparse (buffer)
11382 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11383 it to be reparsed when the buffer is selected."
11384 (cond ((eq buffer (current-buffer))
11385 (js2-reparse))
11386 ((buffer-live-p buffer)
11387 ;; reparse when the buffer is selected again
11388 (with-current-buffer buffer
11389 (add-hook 'window-configuration-change-hook
11390 #'js2-mode-idle-reparse-inner
11391 nil t)))))
11392
11393 (defun js2-mode-idle-reparse-inner ()
11394 (remove-hook 'window-configuration-change-hook
11395 #'js2-mode-idle-reparse-inner
11396 t)
11397 (js2-reparse))
11398
11399 (defun js2-mode-edit (_beg _end _len)
11400 "Schedule a new parse after buffer is edited.
11401 Buffer edit spans from BEG to END and is of length LEN."
11402 (setq js2-mode-buffer-dirty-p t)
11403 (js2-mode-hide-overlay)
11404 (js2-mode-reset-timer))
11405
11406 (defun js2-minor-mode-edit (_beg _end _len)
11407 "Callback for buffer edits in `js2-mode'.
11408 Schedules 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-reparse (&optional force)
11415 "Re-parse current buffer after user finishes some data entry.
11416 If we get any user input while parsing, including cursor motion,
11417 we discard the parse and reschedule it. If FORCE is nil, then the
11418 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11419 (let (time
11420 interrupted-p
11421 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11422 (unless js2-mode-parsing
11423 (setq js2-mode-parsing t)
11424 (unwind-protect
11425 (when (or js2-mode-buffer-dirty-p force)
11426 (js2-remove-overlays)
11427 (setq js2-mode-buffer-dirty-p nil
11428 js2-mode-fontifications nil
11429 js2-mode-deferred-properties nil)
11430 (if js2-mode-verbose-parse-p
11431 (message "parsing..."))
11432 (setq time
11433 (js2-time
11434 (setq interrupted-p
11435 (catch 'interrupted
11436 (js2-parse)
11437 (with-silent-modifications
11438 ;; if parsing is interrupted, comments and regex
11439 ;; literals stay ignored by `parse-partial-sexp'
11440 (remove-text-properties (point-min) (point-max)
11441 '(syntax-table))
11442 (js2-mode-apply-deferred-properties)
11443 (js2-mode-remove-suppressed-warnings)
11444 (js2-mode-show-warnings)
11445 (js2-mode-show-errors)
11446 (if (>= js2-highlight-level 1)
11447 (js2-highlight-jsdoc js2-mode-ast)))
11448 nil))))
11449 (if interrupted-p
11450 (progn
11451 ;; unfinished parse => try again
11452 (setq js2-mode-buffer-dirty-p t)
11453 (js2-mode-reset-timer))
11454 (if js2-mode-verbose-parse-p
11455 (message "Parse time: %s" time))))
11456 (setq js2-mode-parsing nil)
11457 (unless interrupted-p
11458 (setq js2-mode-parse-timer nil))))))
11459
11460 (defun js2-mode-show-node (event)
11461 "Debugging aid: highlight selected AST node on mouse click."
11462 (interactive "e")
11463 (mouse-set-point event)
11464 (setq deactivate-mark t)
11465 (when js2-mode-show-overlay
11466 (let ((node (js2-node-at-point))
11467 beg end)
11468 (if (null node)
11469 (message "No node found at location %s" (point))
11470 (setq beg (js2-node-abs-pos node)
11471 end (+ beg (js2-node-len node)))
11472 (if js2-mode-node-overlay
11473 (move-overlay js2-mode-node-overlay beg end)
11474 (setq js2-mode-node-overlay (make-overlay beg end))
11475 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11476 (with-silent-modifications
11477 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
11478 (message "%s, parent: %s"
11479 (js2-node-short-name node)
11480 (if (js2-node-parent node)
11481 (js2-node-short-name (js2-node-parent node))
11482 "nil"))))))
11483
11484 (defun js2-mode-hide-overlay (&optional _p1 p2)
11485 "Remove the debugging overlay when the point moves.
11486 P1 and P2 are the old and new values of point, respectively."
11487 (when js2-mode-node-overlay
11488 (let ((beg (overlay-start js2-mode-node-overlay))
11489 (end (overlay-end js2-mode-node-overlay)))
11490 ;; Sometimes we're called spuriously.
11491 (unless (and p2
11492 (>= p2 beg)
11493 (<= p2 end))
11494 (with-silent-modifications
11495 (remove-text-properties beg end '(point-left nil)))
11496 (delete-overlay js2-mode-node-overlay)
11497 (setq js2-mode-node-overlay nil)))))
11498
11499 (defun js2-mode-reset ()
11500 "Debugging helper: reset everything."
11501 (interactive)
11502 (js2-mode-exit)
11503 (js2-mode))
11504
11505 (defun js2-mode-show-warn-or-err (e face)
11506 "Highlight a warning or error E with FACE.
11507 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11508 The last element is optional. When present, use instead of FACE."
11509 (let* ((key (cl-first e))
11510 (beg (cl-second e))
11511 (end (+ beg (cl-third e)))
11512 ;; Don't inadvertently go out of bounds.
11513 (beg (max (point-min) (min beg (point-max))))
11514 (end (max (point-min) (min end (point-max))))
11515 (ovl (make-overlay beg end)))
11516 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11517 (overlay-put ovl 'js2-error t)
11518 (put-text-property beg end 'help-echo (js2-get-msg key))
11519 (put-text-property beg end 'point-entered #'js2-echo-error)))
11520
11521 (defun js2-remove-overlays ()
11522 "Remove overlays from buffer that have a `js2-error' property."
11523 (let ((beg (point-min))
11524 (end (point-max)))
11525 (save-excursion
11526 (dolist (o (overlays-in beg end))
11527 (when (overlay-get o 'js2-error)
11528 (delete-overlay o))))))
11529
11530 (defun js2-error-at-point (&optional pos)
11531 "Return non-nil if there's an error overlay at POS.
11532 Defaults to point."
11533 (cl-loop with pos = (or pos (point))
11534 for o in (overlays-at pos)
11535 thereis (overlay-get o 'js2-error)))
11536
11537 (defun js2-mode-apply-deferred-properties ()
11538 "Apply fontifications and other text properties recorded during parsing."
11539 (when (cl-plusp js2-highlight-level)
11540 ;; We defer clearing faces as long as possible to eliminate flashing.
11541 (js2-clear-face (point-min) (point-max))
11542 ;; Have to reverse the recorded fontifications list so that errors
11543 ;; and warnings overwrite the normal fontifications.
11544 (dolist (f (nreverse js2-mode-fontifications))
11545 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11546 (setq js2-mode-fontifications nil))
11547 (dolist (p js2-mode-deferred-properties)
11548 (apply #'put-text-property p))
11549 (setq js2-mode-deferred-properties nil))
11550
11551 (defun js2-mode-show-errors ()
11552 "Highlight syntax errors."
11553 (when js2-mode-show-parse-errors
11554 (dolist (e (js2-ast-root-errors js2-mode-ast))
11555 (js2-mode-show-warn-or-err e 'js2-error))))
11556
11557 (defun js2-mode-remove-suppressed-warnings ()
11558 "Take suppressed warnings out of the AST warnings list.
11559 This ensures that the counts and `next-error' are correct."
11560 (setf (js2-ast-root-warnings js2-mode-ast)
11561 (js2-delete-if
11562 (lambda (e)
11563 (let ((key (caar e)))
11564 (or
11565 (and (not js2-strict-trailing-comma-warning)
11566 (string-match "trailing\\.comma" key))
11567 (and (not js2-strict-cond-assign-warning)
11568 (string= key "msg.equal.as.assign"))
11569 (and js2-missing-semi-one-line-override
11570 (string= key "msg.missing.semi")
11571 (let* ((beg (cl-second e))
11572 (node (js2-node-at-point beg))
11573 (fn (js2-mode-find-parent-fn node))
11574 (body (and fn (js2-function-node-body fn)))
11575 (lc (and body (js2-node-abs-pos body)))
11576 (rc (and lc (+ lc (js2-node-len body)))))
11577 (and fn
11578 (or (null body)
11579 (save-excursion
11580 (goto-char beg)
11581 (and (js2-same-line lc)
11582 (js2-same-line rc))))))))))
11583 (js2-ast-root-warnings js2-mode-ast))))
11584
11585 (defun js2-mode-show-warnings ()
11586 "Highlight strict-mode warnings."
11587 (when js2-mode-show-strict-warnings
11588 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11589 (js2-mode-show-warn-or-err e 'js2-warning))))
11590
11591 (defun js2-echo-error (_old-point new-point)
11592 "Called by point-motion hooks."
11593 (let ((msg (get-text-property new-point 'help-echo)))
11594 (when (and (stringp msg)
11595 (not (active-minibuffer-window))
11596 (not (current-message)))
11597 (message msg))))
11598
11599 (defalias 'js2-echo-help #'js2-echo-error)
11600
11601 (defun js2-line-break (&optional _soft)
11602 "Break line at point and indent, continuing comment if within one.
11603 If inside a string, and `js2-concat-multiline-strings' is not
11604 nil, turn it into concatenation."
11605 (interactive)
11606 (let ((parse-status (syntax-ppss)))
11607 (cond
11608 ;; Check if we're inside a string.
11609 ((nth 3 parse-status)
11610 (if js2-concat-multiline-strings
11611 (js2-mode-split-string parse-status)
11612 (insert "\n")))
11613 ;; Check if inside a block comment.
11614 ((nth 4 parse-status)
11615 (js2-mode-extend-comment (nth 8 parse-status)))
11616 (t
11617 (newline-and-indent)))))
11618
11619 (defun js2-mode-split-string (parse-status)
11620 "Turn a newline in mid-string into a string concatenation.
11621 PARSE-STATUS is as documented in `parse-partial-sexp'."
11622 (let* ((quote-char (nth 3 parse-status))
11623 (at-eol (eq js2-concat-multiline-strings 'eol)))
11624 (insert quote-char)
11625 (insert (if at-eol " +\n" "\n"))
11626 (unless at-eol
11627 (insert "+ "))
11628 (js2-indent-line)
11629 (insert quote-char)
11630 (when (eolp)
11631 (insert quote-char)
11632 (backward-char 1))))
11633
11634 (defun js2-mode-extend-comment (start-pos)
11635 "Indent the line and, when inside a comment block, add comment prefix."
11636 (let (star single col first-line needs-close)
11637 (save-excursion
11638 (back-to-indentation)
11639 (when (< (point) start-pos)
11640 (goto-char start-pos))
11641 (cond
11642 ((looking-at "\\*[^/]")
11643 (setq star t
11644 col (current-column)))
11645 ((looking-at "/\\*")
11646 (setq star t
11647 first-line t
11648 col (1+ (current-column))))
11649 ((looking-at "//")
11650 (setq single t
11651 col (current-column)))))
11652 ;; Heuristic for whether we need to close the comment:
11653 ;; if we've got a parse error here, assume it's an unterminated
11654 ;; comment.
11655 (setq needs-close
11656 (or
11657 (eq (get-text-property (1- (point)) 'point-entered)
11658 'js2-echo-error)
11659 ;; The heuristic above doesn't work well when we're
11660 ;; creating a comment and there's another one downstream,
11661 ;; as our parser thinks this one ends at the end of the
11662 ;; next one. (You can have a /* inside a js block comment.)
11663 ;; So just close it if the next non-ws char isn't a *.
11664 (and first-line
11665 (eolp)
11666 (save-excursion
11667 (skip-chars-forward " \t\r\n")
11668 (not (eq (char-after) ?*))))))
11669 (delete-horizontal-space)
11670 (insert "\n")
11671 (cond
11672 (star
11673 (indent-to col)
11674 (insert "* ")
11675 (if (and first-line needs-close)
11676 (save-excursion
11677 (insert "\n")
11678 (indent-to col)
11679 (insert "*/"))))
11680 ((and single
11681 (save-excursion
11682 (and (zerop (forward-line 1))
11683 (looking-at "\\s-*//"))))
11684 (indent-to col)
11685 (insert "// ")))
11686 ;; Don't need to extend the comment after all.
11687 (js2-indent-line)))
11688
11689 (defun js2-beginning-of-line ()
11690 "Toggle point between bol and first non-whitespace char in line.
11691 Also moves past comment delimiters when inside comments."
11692 (interactive)
11693 (let (node)
11694 (cond
11695 ((bolp)
11696 (back-to-indentation))
11697 ((looking-at "//")
11698 (skip-chars-forward "/ \t"))
11699 ((and (eq (char-after) ?*)
11700 (setq node (js2-comment-at-point))
11701 (memq (js2-comment-node-format node) '(jsdoc block))
11702 (save-excursion
11703 (skip-chars-backward " \t")
11704 (bolp)))
11705 (skip-chars-forward "\* \t"))
11706 (t
11707 (goto-char (point-at-bol))))))
11708
11709 (defun js2-end-of-line ()
11710 "Toggle point between eol and last non-whitespace char in line."
11711 (interactive)
11712 (if (eolp)
11713 (skip-chars-backward " \t")
11714 (goto-char (point-at-eol))))
11715
11716 (defun js2-mode-wait-for-parse (callback)
11717 "Invoke CALLBACK when parsing is finished.
11718 If parsing is already finished, calls CALLBACK immediately."
11719 (if (not js2-mode-buffer-dirty-p)
11720 (funcall callback)
11721 (push callback js2-mode-pending-parse-callbacks)
11722 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11723
11724 (defun js2-mode-parse-finished ()
11725 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11726 ;; We can't let errors propagate up, since it prevents the
11727 ;; `js2-parse' method from completing normally and returning
11728 ;; the ast, which makes things mysteriously not work right.
11729 (unwind-protect
11730 (dolist (cb js2-mode-pending-parse-callbacks)
11731 (condition-case err
11732 (funcall cb)
11733 (error (message "%s" err))))
11734 (setq js2-mode-pending-parse-callbacks nil)))
11735
11736 (defun js2-mode-flag-region (from to flag)
11737 "Hide or show text from FROM to TO, according to FLAG.
11738 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11739 Returns the created overlay if FLAG is non-nil."
11740 (remove-overlays from to 'invisible 'js2-outline)
11741 (when flag
11742 (let ((o (make-overlay from to)))
11743 (overlay-put o 'invisible 'js2-outline)
11744 (overlay-put o 'isearch-open-invisible
11745 'js2-isearch-open-invisible)
11746 o)))
11747
11748 ;; Function to be set as an outline-isearch-open-invisible' property
11749 ;; to the overlay that makes the outline invisible (see
11750 ;; `js2-mode-flag-region').
11751 (defun js2-isearch-open-invisible (_overlay)
11752 ;; We rely on the fact that isearch places point on the matched text.
11753 (js2-mode-show-element))
11754
11755 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11756 "Return cons cell of bounds of folding overlay at POS.
11757 Returns nil if not found."
11758 (let ((overlays (overlays-at (or pos (point))))
11759 o)
11760 (while (and overlays
11761 (not o))
11762 (if (overlay-get (car overlays) 'invisible)
11763 (setq o (car overlays))
11764 (setq overlays (cdr overlays))))
11765 (if o
11766 (cons (overlay-start o) (overlay-end o)))))
11767
11768 (defun js2-mode-function-at-point (&optional pos)
11769 "Return the innermost function node enclosing current point.
11770 Returns nil if point is not in a function."
11771 (let ((node (js2-node-at-point pos)))
11772 (while (and node (not (js2-function-node-p node)))
11773 (setq node (js2-node-parent node)))
11774 (if (js2-function-node-p node)
11775 node)))
11776
11777 (defun js2-mode-toggle-element ()
11778 "Hide or show the foldable element at the point."
11779 (interactive)
11780 (let (comment fn pos)
11781 (save-excursion
11782 (cond
11783 ;; /* ... */ comment?
11784 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11785 (if (js2-mode-invisible-overlay-bounds
11786 (setq pos (+ 3 (js2-node-abs-pos comment))))
11787 (progn
11788 (goto-char pos)
11789 (js2-mode-show-element))
11790 (js2-mode-hide-element)))
11791 ;; //-comment?
11792 ((save-excursion
11793 (back-to-indentation)
11794 (looking-at js2-mode-//-comment-re))
11795 (js2-mode-toggle-//-comment))
11796 ;; function?
11797 ((setq fn (js2-mode-function-at-point))
11798 (setq pos (and (js2-function-node-body fn)
11799 (js2-node-abs-pos (js2-function-node-body fn))))
11800 (goto-char (1+ pos))
11801 (if (js2-mode-invisible-overlay-bounds)
11802 (js2-mode-show-element)
11803 (js2-mode-hide-element)))
11804 (t
11805 (message "Nothing at point to hide or show"))))))
11806
11807 (defun js2-mode-hide-element ()
11808 "Fold/hide contents of a block, showing ellipses.
11809 Show the hidden text with \\[js2-mode-show-element]."
11810 (interactive)
11811 (if js2-mode-buffer-dirty-p
11812 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11813 (let (node body beg end)
11814 (cond
11815 ((js2-mode-invisible-overlay-bounds)
11816 (message "already hidden"))
11817 (t
11818 (setq node (js2-node-at-point))
11819 (cond
11820 ((js2-block-comment-p node)
11821 (js2-mode-hide-comment node))
11822 (t
11823 (while (and node (not (js2-function-node-p node)))
11824 (setq node (js2-node-parent node)))
11825 (if (and node
11826 (setq body (js2-function-node-body node)))
11827 (progn
11828 (setq beg (js2-node-abs-pos body)
11829 end (+ beg (js2-node-len body)))
11830 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11831 (message "No collapsable element found at point"))))))))
11832
11833 (defun js2-mode-show-element ()
11834 "Show the hidden element at current point."
11835 (interactive)
11836 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11837 (if bounds
11838 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11839 (message "Nothing to un-hide"))))
11840
11841 (defun js2-mode-show-all ()
11842 "Show all of the text in the buffer."
11843 (interactive)
11844 (js2-mode-flag-region (point-min) (point-max) nil))
11845
11846 (defun js2-mode-toggle-hide-functions ()
11847 (interactive)
11848 (if js2-mode-functions-hidden
11849 (js2-mode-show-functions)
11850 (js2-mode-hide-functions)))
11851
11852 (defun js2-mode-hide-functions ()
11853 "Hides all non-nested function bodies in the buffer.
11854 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11855 to open an individual entry."
11856 (interactive)
11857 (if js2-mode-buffer-dirty-p
11858 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11859 (if (null js2-mode-ast)
11860 (message "Oops - parsing failed")
11861 (setq js2-mode-functions-hidden t)
11862 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11863
11864 (defun js2-mode-function-hider (n endp)
11865 (when (not endp)
11866 (let ((tt (js2-node-type n))
11867 body beg end)
11868 (cond
11869 ((and (= tt js2-FUNCTION)
11870 (setq body (js2-function-node-body n)))
11871 (setq beg (js2-node-abs-pos body)
11872 end (+ beg (js2-node-len body)))
11873 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11874 nil) ; don't process children of function
11875 (t
11876 t))))) ; keep processing other AST nodes
11877
11878 (defun js2-mode-show-functions ()
11879 "Un-hide any folded function bodies in the buffer."
11880 (interactive)
11881 (setq js2-mode-functions-hidden nil)
11882 (save-excursion
11883 (goto-char (point-min))
11884 (while (/= (goto-char (next-overlay-change (point)))
11885 (point-max))
11886 (dolist (o (overlays-at (point)))
11887 (when (and (overlay-get o 'invisible)
11888 (not (overlay-get o 'comment)))
11889 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11890
11891 (defun js2-mode-hide-comment (n)
11892 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11893 3 ; /**
11894 2)) ; /*
11895 (beg (+ (js2-node-abs-pos n) head))
11896 (end (- (+ beg (js2-node-len n)) head 2))
11897 (o (js2-mode-flag-region beg end 'hide)))
11898 (overlay-put o 'comment t)))
11899
11900 (defun js2-mode-toggle-hide-comments ()
11901 "Folds all block comments in the buffer.
11902 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11903 to open an individual entry."
11904 (interactive)
11905 (if js2-mode-comments-hidden
11906 (js2-mode-show-comments)
11907 (js2-mode-hide-comments)))
11908
11909 (defun js2-mode-hide-comments ()
11910 (interactive)
11911 (if js2-mode-buffer-dirty-p
11912 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11913 (if (null js2-mode-ast)
11914 (message "Oops - parsing failed")
11915 (setq js2-mode-comments-hidden t)
11916 (dolist (n (js2-ast-root-comments js2-mode-ast))
11917 (when (js2-block-comment-p n)
11918 (js2-mode-hide-comment n)))
11919 (js2-mode-hide-//-comments)))
11920
11921 (defun js2-mode-extend-//-comment (direction)
11922 "Find start or end of a block of similar //-comment lines.
11923 DIRECTION is -1 to look back, 1 to look forward.
11924 INDENT is the indentation level to match.
11925 Returns the end-of-line position of the furthest adjacent
11926 //-comment line with the same indentation as the current line.
11927 If there is no such matching line, returns current end of line."
11928 (let ((pos (point-at-eol))
11929 (indent (current-indentation)))
11930 (save-excursion
11931 (while (and (zerop (forward-line direction))
11932 (looking-at js2-mode-//-comment-re)
11933 (eq indent (length (match-string 1))))
11934 (setq pos (point-at-eol)))
11935 pos)))
11936
11937 (defun js2-mode-hide-//-comments ()
11938 "Fold adjacent 1-line comments, showing only snippet of first one."
11939 (let (beg end)
11940 (save-excursion
11941 (goto-char (point-min))
11942 (while (re-search-forward js2-mode-//-comment-re nil t)
11943 (setq beg (point)
11944 end (js2-mode-extend-//-comment 1))
11945 (unless (eq beg end)
11946 (overlay-put (js2-mode-flag-region beg end 'hide)
11947 'comment t))
11948 (goto-char end)
11949 (forward-char 1)))))
11950
11951 (defun js2-mode-toggle-//-comment ()
11952 "Fold or un-fold any multi-line //-comment at point.
11953 Caller should have determined that this line starts with a //-comment."
11954 (let* ((beg (point-at-eol))
11955 (end beg))
11956 (save-excursion
11957 (goto-char end)
11958 (if (js2-mode-invisible-overlay-bounds)
11959 (js2-mode-show-element)
11960 ;; else hide the comment
11961 (setq beg (js2-mode-extend-//-comment -1)
11962 end (js2-mode-extend-//-comment 1))
11963 (unless (eq beg end)
11964 (overlay-put (js2-mode-flag-region beg end 'hide)
11965 'comment t))))))
11966
11967 (defun js2-mode-show-comments ()
11968 "Un-hide any hidden comments, leaving other hidden elements alone."
11969 (interactive)
11970 (setq js2-mode-comments-hidden nil)
11971 (save-excursion
11972 (goto-char (point-min))
11973 (while (/= (goto-char (next-overlay-change (point)))
11974 (point-max))
11975 (dolist (o (overlays-at (point)))
11976 (when (overlay-get o 'comment)
11977 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11978
11979 (defun js2-mode-display-warnings-and-errors ()
11980 "Turn on display of warnings and errors."
11981 (interactive)
11982 (setq js2-mode-show-parse-errors t
11983 js2-mode-show-strict-warnings t)
11984 (js2-reparse 'force))
11985
11986 (defun js2-mode-hide-warnings-and-errors ()
11987 "Turn off display of warnings and errors."
11988 (interactive)
11989 (setq js2-mode-show-parse-errors nil
11990 js2-mode-show-strict-warnings nil)
11991 (js2-reparse 'force))
11992
11993 (defun js2-mode-toggle-warnings-and-errors ()
11994 "Toggle the display of warnings and errors.
11995 Some users don't like having warnings/errors reported while they type."
11996 (interactive)
11997 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11998 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11999 (if (called-interactively-p 'any)
12000 (message "warnings and errors %s"
12001 (if js2-mode-show-parse-errors
12002 "enabled"
12003 "disabled")))
12004 (js2-reparse 'force))
12005
12006 (defun js2-mode-customize ()
12007 (interactive)
12008 (customize-group 'js2-mode))
12009
12010 (defun js2-mode-forward-sexp (&optional arg)
12011 "Move forward across one statement or balanced expression.
12012 With ARG, do it that many times. Negative arg -N means
12013 move backward across N balanced expressions."
12014 (interactive "p")
12015 (setq arg (or arg 1))
12016 (save-restriction
12017 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12018 (js2-reparse)
12019 (let (forward-sexp-function
12020 node (start (point)) pos lp rp child)
12021 (cond
12022 ;; backward-sexp
12023 ;; could probably make this better for some cases:
12024 ;; - if in statement block (e.g. function body), go to parent
12025 ;; - infix exprs like (foo in bar) - maybe go to beginning
12026 ;; of infix expr if in the right-side expression?
12027 ((and arg (cl-minusp arg))
12028 (dotimes (_ (- arg))
12029 (js2-backward-sws)
12030 (forward-char -1) ; Enter the node we backed up to.
12031 (when (setq node (js2-node-at-point (point) t))
12032 (setq pos (js2-node-abs-pos node))
12033 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12034 (setq lp (car parens)
12035 rp (cdr parens)))
12036 (when (and lp (> start lp))
12037 (if (and rp (<= start rp))
12038 ;; Between parens, check if there's a child node we can jump.
12039 (when (setq child (js2-node-closest-child node (point) lp t))
12040 (setq pos (js2-node-abs-pos child)))
12041 ;; Before both parens.
12042 (setq pos lp)))
12043 (let ((state (parse-partial-sexp start pos)))
12044 (goto-char (if (not (zerop (car state)))
12045 ;; Stumble at the unbalanced paren if < 0, or
12046 ;; jump a bit further if > 0.
12047 (scan-sexps start -1)
12048 pos))))
12049 (unless pos (goto-char (point-min)))))
12050 (t
12051 ;; forward-sexp
12052 (dotimes (_ arg)
12053 (js2-forward-sws)
12054 (when (setq node (js2-node-at-point (point) t))
12055 (setq pos (js2-node-abs-pos node))
12056 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12057 (setq lp (car parens)
12058 rp (cdr parens)))
12059 (or
12060 (when (and rp (<= start rp))
12061 (if (> start lp)
12062 (when (setq child (js2-node-closest-child node (point) rp))
12063 (setq pos (js2-node-abs-end child)))
12064 (setq pos (1+ rp))))
12065 ;; No parens or child nodes, looks for the end of the curren node.
12066 (cl-incf pos (js2-node-len
12067 (if (js2-expr-stmt-node-p (js2-node-parent node))
12068 ;; Stop after the semicolon.
12069 (js2-node-parent node)
12070 node))))
12071 (let ((state (save-excursion (parse-partial-sexp start pos))))
12072 (goto-char (if (not (zerop (car state)))
12073 (scan-sexps start 1)
12074 pos))))
12075 (unless pos (goto-char (point-max)))))))))
12076
12077 (defun js2-mode-forward-sexp-parens (node abs-pos)
12078 "Return a cons cell with positions of main parens in NODE."
12079 (cond
12080 ((or (js2-array-node-p node)
12081 (js2-object-node-p node)
12082 (js2-comp-node-p node)
12083 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12084 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12085 ((js2-paren-expr-node-p node)
12086 (let ((lp (js2-node-lp node))
12087 (rp (js2-node-rp node)))
12088 (cons (when lp (+ abs-pos lp))
12089 (when rp (+ abs-pos rp)))))))
12090
12091 (defun js2-node-closest-child (parent point limit &optional before)
12092 (let* ((parent-pos (js2-node-abs-pos parent))
12093 (rpoint (- point parent-pos))
12094 (rlimit (- limit parent-pos))
12095 (min (min rpoint rlimit))
12096 (max (max rpoint rlimit))
12097 found)
12098 (catch 'done
12099 (js2-visit-ast
12100 parent
12101 (lambda (node _end-p)
12102 (if (eq node parent)
12103 t
12104 (let ((pos (js2-node-pos node)) ;; Both relative values.
12105 (end (+ (js2-node-pos node) (js2-node-len node))))
12106 (when (and (>= pos min) (<= end max)
12107 (if before (< pos rpoint) (> end rpoint)))
12108 (setq found node))
12109 (when (> end rpoint)
12110 (throw 'done nil)))
12111 nil))))
12112 found))
12113
12114 (defun js2-errors ()
12115 "Return a list of errors found."
12116 (and js2-mode-ast
12117 (js2-ast-root-errors js2-mode-ast)))
12118
12119 (defun js2-warnings ()
12120 "Return a list of warnings found."
12121 (and js2-mode-ast
12122 (js2-ast-root-warnings js2-mode-ast)))
12123
12124 (defun js2-have-errors-p ()
12125 "Return non-nil if any parse errors or warnings were found."
12126 (or (js2-errors) (js2-warnings)))
12127
12128 (defun js2-errors-and-warnings ()
12129 "Return a copy of the concatenated errors and warnings lists.
12130 They are appended: first the errors, then the warnings.
12131 Entries are of the form (MSG BEG END)."
12132 (when js2-mode-ast
12133 (append (js2-ast-root-errors js2-mode-ast)
12134 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12135
12136 (defun js2-next-error (&optional arg reset)
12137 "Move to next parse error.
12138 Typically invoked via \\[next-error].
12139 ARG is the number of errors, forward or backward, to move.
12140 RESET means start over from the beginning."
12141 (interactive "p")
12142 (if (not (or (js2-errors) (js2-warnings)))
12143 (message "No errors")
12144 (when reset
12145 (goto-char (point-min)))
12146 (let* ((errs (js2-errors-and-warnings))
12147 (continue t)
12148 (start (point))
12149 (count (or arg 1))
12150 (backward (cl-minusp count))
12151 (sorter (if backward '> '<))
12152 (stopper (if backward '< '>))
12153 (count (abs count))
12154 all-errs err)
12155 ;; Sort by start position.
12156 (setq errs (sort errs (lambda (e1 e2)
12157 (funcall sorter (cl-second e1) (cl-second e2))))
12158 all-errs errs)
12159 ;; Find nth error with pos > start.
12160 (while (and errs continue)
12161 (when (funcall stopper (cl-cadar errs) start)
12162 (setq err (car errs))
12163 (if (zerop (cl-decf count))
12164 (setq continue nil)))
12165 (setq errs (cdr errs)))
12166 ;; Clear for `js2-echo-error'.
12167 (message nil)
12168 (if err
12169 (goto-char (cl-second err))
12170 ;; Wrap around to first error.
12171 (goto-char (cl-second (car all-errs)))
12172 ;; If we were already on it, echo msg again.
12173 (if (= (point) start)
12174 (js2-echo-error (point) (point)))))))
12175
12176 (defun js2-down-mouse-3 ()
12177 "Make right-click move the point to the click location.
12178 This makes right-click context menu operations a bit more intuitive.
12179 The point will not move if the region is active, however, to avoid
12180 destroying the region selection."
12181 (interactive)
12182 (when (and js2-move-point-on-right-click
12183 (not mark-active))
12184 (let ((e last-input-event))
12185 (ignore-errors
12186 (goto-char (cl-cadadr e))))))
12187
12188 (defun js2-mode-create-imenu-index ()
12189 "Return an alist for `imenu--index-alist'."
12190 ;; This is built up in `js2-parse-record-imenu' during parsing.
12191 (when js2-mode-ast
12192 ;; if we have an ast but no recorder, they're requesting a rescan
12193 (unless js2-imenu-recorder
12194 (js2-reparse 'force))
12195 (prog1
12196 (js2-build-imenu-index)
12197 (setq js2-imenu-recorder nil
12198 js2-imenu-function-map nil))))
12199
12200 (defun js2-mode-find-tag ()
12201 "Replacement for `find-tag-default'.
12202 `find-tag-default' returns a ridiculous answer inside comments."
12203 (let (beg end)
12204 (js2-with-underscore-as-word-syntax
12205 (save-excursion
12206 (if (and (not (looking-at "[[:alnum:]_$]"))
12207 (looking-back "[[:alnum:]_$]"))
12208 (setq beg (progn (forward-word -1) (point))
12209 end (progn (forward-word 1) (point)))
12210 (setq beg (progn (forward-word 1) (point))
12211 end (progn (forward-word -1) (point))))
12212 (replace-regexp-in-string
12213 "[\"']" ""
12214 (buffer-substring-no-properties beg end))))))
12215
12216 (defun js2-mode-forward-sibling ()
12217 "Move to the end of the sibling following point in parent.
12218 Returns non-nil if successful, or nil if there was no following sibling."
12219 (let* ((node (js2-node-at-point))
12220 (parent (js2-mode-find-enclosing-fn node))
12221 sib)
12222 (when (setq sib (js2-node-find-child-after (point) parent))
12223 (goto-char (+ (js2-node-abs-pos sib)
12224 (js2-node-len sib))))))
12225
12226 (defun js2-mode-backward-sibling ()
12227 "Move to the beginning of the sibling node preceding point in parent.
12228 Parent is defined as the enclosing script or function."
12229 (let* ((node (js2-node-at-point))
12230 (parent (js2-mode-find-enclosing-fn node))
12231 sib)
12232 (when (setq sib (js2-node-find-child-before (point) parent))
12233 (goto-char (js2-node-abs-pos sib)))))
12234
12235 (defun js2-beginning-of-defun (&optional arg)
12236 "Go to line on which current function starts, and return t on success.
12237 If we're not in a function or already at the beginning of one, go
12238 to beginning of previous script-level element.
12239 With ARG N, do that N times. If N is negative, move forward."
12240 (setq arg (or arg 1))
12241 (if (cl-plusp arg)
12242 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12243 (when (cond
12244 ((js2-function-node-p parent)
12245 (goto-char (js2-node-abs-pos parent)))
12246 (t
12247 (js2-mode-backward-sibling)))
12248 (if (> arg 1)
12249 (js2-beginning-of-defun (1- arg))
12250 t)))
12251 (when (js2-end-of-defun)
12252 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12253
12254 (defun js2-end-of-defun ()
12255 "Go to the char after the last position of the current function
12256 or script-level element."
12257 (let* ((node (js2-node-at-point))
12258 (parent (or (and (js2-function-node-p node) node)
12259 (js2-node-parent-script-or-fn node)))
12260 script)
12261 (unless (js2-function-node-p parent)
12262 ;; Use current script-level node, or, if none, the next one.
12263 (setq script (or parent node)
12264 parent (js2-node-find-child-before (point) script))
12265 (when (or (null parent)
12266 (>= (point) (+ (js2-node-abs-pos parent)
12267 (js2-node-len parent))))
12268 (setq parent (js2-node-find-child-after (point) script))))
12269 (when parent
12270 (goto-char (+ (js2-node-abs-pos parent)
12271 (js2-node-len parent))))))
12272
12273 (defun js2-mark-defun (&optional allow-extend)
12274 "Put mark at end of this function, point at beginning.
12275 The function marked is the one that contains point.
12276
12277 Interactively, if this command is repeated,
12278 or (in Transient Mark mode) if the mark is active,
12279 it marks the next defun after the ones already marked."
12280 (interactive "p")
12281 (let (extended)
12282 (when (and allow-extend
12283 (or (and (eq last-command this-command) (mark t))
12284 (and transient-mark-mode mark-active)))
12285 (let ((sib (save-excursion
12286 (goto-char (mark))
12287 (if (js2-mode-forward-sibling)
12288 (point)))))
12289 (if sib
12290 (progn
12291 (set-mark sib)
12292 (setq extended t))
12293 ;; no more siblings - try extending to enclosing node
12294 (goto-char (mark t)))))
12295 (when (not extended)
12296 (let ((node (js2-node-at-point (point) t)) ; skip comments
12297 ast fn stmt parent beg end)
12298 (when (js2-ast-root-p node)
12299 (setq ast node
12300 node (or (js2-node-find-child-after (point) node)
12301 (js2-node-find-child-before (point) node))))
12302 ;; only mark whole buffer if we can't find any children
12303 (if (null node)
12304 (setq node ast))
12305 (if (js2-function-node-p node)
12306 (setq parent node)
12307 (setq fn (js2-mode-find-enclosing-fn node)
12308 stmt (if (or (null fn)
12309 (js2-ast-root-p fn))
12310 (js2-mode-find-first-stmt node))
12311 parent (or stmt fn)))
12312 (setq beg (js2-node-abs-pos parent)
12313 end (+ beg (js2-node-len parent)))
12314 (push-mark beg)
12315 (goto-char end)
12316 (exchange-point-and-mark)))))
12317
12318 (defun js2-narrow-to-defun ()
12319 "Narrow to the function enclosing point."
12320 (interactive)
12321 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12322 (fn (if (js2-script-node-p node)
12323 node
12324 (js2-mode-find-enclosing-fn node)))
12325 (beg (js2-node-abs-pos fn)))
12326 (unless (js2-ast-root-p fn)
12327 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12328
12329 (provide 'js2-mode)
12330
12331 ;;; js2-mode.el ends here