]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Bump the version and update NEWS
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2015 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20150202
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (require 'cl-lib)
89 (require 'imenu)
90 (require 'cc-cmds) ; for `c-fill-paragraph'
91
92 (eval-and-compile
93 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
94 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
95
96 (defvar electric-layout-rules)
97
98 ;;; Externs (variables presumed to be defined by the host system)
99
100 (defvar js2-ecma-262-externs
101 (mapcar 'symbol-name
102 '(Array Boolean Date Error EvalError Function Infinity JSON
103 Math NaN Number Object RangeError ReferenceError RegExp
104 String SyntaxError TypeError URIError
105 decodeURI decodeURIComponent encodeURI
106 encodeURIComponent escape eval isFinite isNaN
107 parseFloat parseInt undefined unescape))
108 "Ecma-262 externs. Included in `js2-externs' by default.")
109
110 (defvar js2-browser-externs
111 (mapcar 'symbol-name
112 '(;; DOM level 1
113 Attr CDATASection CharacterData Comment DOMException
114 DOMImplementation Document DocumentFragment
115 DocumentType Element Entity EntityReference
116 ExceptionCode NamedNodeMap Node NodeList Notation
117 ProcessingInstruction Text
118
119 ;; DOM level 2
120 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
121 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
122 HTMLBodyElement HTMLButtonElement HTMLCollection
123 HTMLDListElement HTMLDirectoryElement HTMLDivElement
124 HTMLDocument HTMLElement HTMLFieldSetElement
125 HTMLFontElement HTMLFormElement HTMLFrameElement
126 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
127 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
128 HTMLImageElement HTMLInputElement HTMLIsIndexElement
129 HTMLLIElement HTMLLabelElement HTMLLegendElement
130 HTMLLinkElement HTMLMapElement HTMLMenuElement
131 HTMLMetaElement HTMLModElement HTMLOListElement
132 HTMLObjectElement HTMLOptGroupElement
133 HTMLOptionElement HTMLOptionsCollection
134 HTMLParagraphElement HTMLParamElement HTMLPreElement
135 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
136 HTMLStyleElement HTMLTableCaptionElement
137 HTMLTableCellElement HTMLTableColElement
138 HTMLTableElement HTMLTableRowElement
139 HTMLTableSectionElement HTMLTextAreaElement
140 HTMLTitleElement HTMLUListElement
141
142 ;; DOM level 3
143 DOMConfiguration DOMError DOMException
144 DOMImplementationList DOMImplementationSource
145 DOMLocator DOMStringList NameList TypeInfo
146 UserDataHandler
147
148 ;; Window
149 window alert confirm document java navigator prompt screen
150 self top requestAnimationFrame cancelAnimationFrame
151
152 ;; W3C CSS
153 CSSCharsetRule CSSFontFace CSSFontFaceRule
154 CSSImportRule CSSMediaRule CSSPageRule
155 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
156 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
157 CSSValue CSSValueList Counter DOMImplementationCSS
158 DocumentCSS DocumentStyle ElementCSSInlineStyle
159 LinkStyle MediaList RGBColor Rect StyleSheet
160 StyleSheetList ViewCSS
161
162 ;; W3C Event
163 EventListener EventTarget Event DocumentEvent UIEvent
164 MouseEvent MutationEvent KeyboardEvent
165
166 ;; W3C Range
167 DocumentRange Range RangeException
168
169 ;; W3C XML
170 XPathResult XMLHttpRequest
171
172 ;; console object. Provided by at least Chrome and Firefox.
173 console))
174 "Browser externs.
175 You can cause these to be included or excluded with the custom
176 variable `js2-include-browser-externs'.")
177
178 (defvar js2-rhino-externs
179 (mapcar 'symbol-name
180 '(Packages importClass importPackage com org java
181 ;; Global object (shell) externs.
182 defineClass deserialize doctest gc help load
183 loadClass print quit readFile readUrl runCommand seal
184 serialize spawn sync toint32 version))
185 "Mozilla Rhino externs.
186 Set `js2-include-rhino-externs' to t to include them.")
187
188 (defvar js2-node-externs
189 (mapcar 'symbol-name
190 '(__dirname __filename Buffer clearInterval clearTimeout require
191 console exports global module process setInterval setTimeout))
192 "Node.js externs.
193 Set `js2-include-node-externs' to t to include them.")
194
195 (defvar js2-typed-array-externs
196 (mapcar 'symbol-name
197 '(ArrayBuffer Uint8ClampedArray DataView
198 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
199 Float32Array Float64Array))
200 "Khronos typed array externs. Available in most modern browsers and
201 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
202 are enabled, these will also be included.")
203
204 (defvar js2-harmony-externs
205 (mapcar 'symbol-name
206 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
207 "ES6 externs. If `js2-include-browser-externs' is enabled and
208 `js2-language-version' is sufficiently high, these will be included.")
209
210 ;;; Variables
211
212 (defun js2-mark-safe-local (name pred)
213 "Make the variable NAME buffer-local and mark it as safe file-local
214 variable with predicate PRED."
215 (make-variable-buffer-local name)
216 (put name 'safe-local-variable pred))
217
218 (defcustom js2-highlight-level 2
219 "Amount of syntax highlighting to perform.
220 0 or a negative value means none.
221 1 adds basic syntax highlighting.
222 2 adds highlighting of some Ecma built-in properties.
223 3 adds highlighting of many Ecma built-in functions."
224 :group 'js2-mode
225 :type '(choice (const :tag "None" 0)
226 (const :tag "Basic" 1)
227 (const :tag "Include Properties" 2)
228 (const :tag "Include Functions" 3)))
229
230 (defvar js2-mode-dev-mode-p nil
231 "Non-nil if running in development mode. Normally nil.")
232
233 (defgroup js2-mode nil
234 "An improved JavaScript mode."
235 :group 'languages)
236
237 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
238 (numberp c-basic-offset))
239 c-basic-offset
240 4)
241 "Number of spaces to indent nested statements.
242 Similar to `c-basic-offset'."
243 :group 'js2-mode
244 :type 'integer)
245 (js2-mark-safe-local 'js2-basic-offset 'integerp)
246
247 (defcustom js2-bounce-indent-p nil
248 "Non-nil to have indent-line function choose among alternatives.
249 If nil, the indent-line function will indent to a predetermined column
250 based on heuristic guessing. If non-nil, then if the current line is
251 already indented to that predetermined column, indenting will choose
252 another likely column and indent to that spot. Repeated invocation of
253 the indent-line function will cycle among the computed alternatives.
254 See the function `js2-bounce-indent' for details. When it is non-nil,
255 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
256 :type 'boolean
257 :group 'js2-mode)
258
259 (defcustom js2-pretty-multiline-declarations t
260 "Non-nil to line up multiline declarations vertically:
261
262 var a = 10,
263 b = 20,
264 c = 30;
265
266 If the value is not `all', and the first assigned value in
267 declaration is a function/array/object literal spanning several
268 lines, it won't be indented additionally:
269
270 var o = { var bar = 2,
271 foo: 3 vs. o = {
272 }, foo: 3
273 bar = 2; };"
274 :group 'js2-mode
275 :type 'symbol)
276 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
277
278 (defcustom js2-indent-switch-body nil
279 "When nil, case labels are indented on the same level as the
280 containing switch statement. Otherwise, all lines inside
281 switch statement body are indented one additional level."
282 :type 'boolean
283 :group 'js2-mode)
284 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
285
286 (defcustom js2-idle-timer-delay 0.2
287 "Delay in secs before re-parsing after user makes changes.
288 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
289 :type 'number
290 :group 'js2-mode)
291 (make-variable-buffer-local 'js2-idle-timer-delay)
292
293 (defcustom js2-dynamic-idle-timer-adjust 0
294 "Positive to adjust `js2-idle-timer-delay' based on file size.
295 The idea is that for short files, parsing is faster so we can be
296 more responsive to user edits without interfering with editing.
297 The buffer length in characters (typically bytes) is divided by
298 this value and used to multiply `js2-idle-timer-delay' for the
299 buffer. For example, a 21k file and 10k adjust yields 21k/10k
300 == 2, so js2-idle-timer-delay is multiplied by 2.
301 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
302 `js2-idle-timer-delay' is not dependent on the file size."
303 :type 'number
304 :group 'js2-mode)
305
306 (defcustom js2-concat-multiline-strings t
307 "When non-nil, `js2-line-break' in mid-string will make it a
308 string concatenation. When `eol', the '+' will be inserted at the
309 end of the line, otherwise, at the beginning of the next line."
310 :type '(choice (const t) (const eol) (const nil))
311 :group 'js2-mode)
312
313 (defcustom js2-mode-show-parse-errors t
314 "True to highlight parse errors."
315 :type 'boolean
316 :group 'js2-mode)
317
318 (defcustom js2-mode-show-strict-warnings t
319 "Non-nil to emit Ecma strict-mode warnings.
320 Some of the warnings can be individually disabled by other flags,
321 even if this flag is non-nil."
322 :type 'boolean
323 :group 'js2-mode)
324
325 (defcustom js2-strict-trailing-comma-warning t
326 "Non-nil to warn about trailing commas in array literals.
327 Ecma-262-5.1 allows them, but older versions of IE raise an error."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-strict-missing-semi-warning t
332 "Non-nil to warn about semicolon auto-insertion after statement.
333 Technically this is legal per Ecma-262, but some style guides disallow
334 depending on it."
335 :type 'boolean
336 :group 'js2-mode)
337
338 (defcustom js2-missing-semi-one-line-override nil
339 "Non-nil to permit missing semicolons in one-line functions.
340 In one-liner functions such as `function identity(x) {return x}'
341 people often omit the semicolon for a cleaner look. If you are
342 such a person, you can suppress the missing-semicolon warning
343 by setting this variable to t."
344 :type 'boolean
345 :group 'js2-mode)
346
347 (defcustom js2-strict-inconsistent-return-warning t
348 "Non-nil to warn about mixing returns with value-returns.
349 It's perfectly legal to have a `return' and a `return foo' in the
350 same function, but it's often an indicator of a bug, and it also
351 interferes with type inference (in systems that support it.)"
352 :type 'boolean
353 :group 'js2-mode)
354
355 (defcustom js2-strict-cond-assign-warning t
356 "Non-nil to warn about expressions like if (a = b).
357 This often should have been '==' instead of '='. If the warning
358 is enabled, you can suppress it on a per-expression basis by
359 parenthesizing the expression, e.g. if ((a = b)) ..."
360 :type 'boolean
361 :group 'js2-mode)
362
363 (defcustom js2-strict-var-redeclaration-warning t
364 "Non-nil to warn about redeclaring variables in a script or function."
365 :type 'boolean
366 :group 'js2-mode)
367
368 (defcustom js2-strict-var-hides-function-arg-warning t
369 "Non-nil to warn about a var decl hiding a function argument."
370 :type 'boolean
371 :group 'js2-mode)
372
373 (defcustom js2-skip-preprocessor-directives nil
374 "Non-nil to treat lines beginning with # as comments.
375 Useful for viewing Mozilla JavaScript source code."
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-language-version 200
380 "Configures what JavaScript language version to recognize.
381 Currently versions 150, 160, 170, 180 and 200 are supported,
382 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
383 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
384 yield, and Array comprehensions, and 1.8 adds function closures."
385 :type 'integer
386 :group 'js2-mode)
387
388 (defcustom js2-instanceof-has-side-effects nil
389 "If non-nil, treats the instanceof operator as having side effects.
390 This is useful for xulrunner apps."
391 :type 'boolean
392 :group 'js2-mode)
393
394 (defcustom js2-move-point-on-right-click t
395 "Non-nil to move insertion point when you right-click.
396 This makes right-click context menu behavior a bit more intuitive,
397 since menu operations generally apply to the point. The exception
398 is if there is a region selection, in which case the point does -not-
399 move, so cut/copy/paste can work properly.
400
401 Note that IntelliJ moves the point, and Eclipse leaves it alone,
402 so this behavior is customizable."
403 :group 'js2-mode
404 :type 'boolean)
405
406 (defcustom js2-allow-rhino-new-expr-initializer t
407 "Non-nil to support a Rhino's experimental syntactic construct.
408
409 Rhino supports the ability to follow a `new' expression with an object
410 literal, which is used to set additional properties on the new object
411 after calling its constructor. Syntax:
412
413 new <expr> [ ( arglist ) ] [initializer]
414
415 Hence, this expression:
416
417 new Object {a: 1, b: 2}
418
419 results in an Object with properties a=1 and b=2. This syntax is
420 apparently not configurable in Rhino - it's currently always enabled,
421 as of Rhino version 1.7R2."
422 :type 'boolean
423 :group 'js2-mode)
424
425 (defcustom js2-allow-member-expr-as-function-name nil
426 "Non-nil to support experimental Rhino syntax for function names.
427
428 Rhino supports an experimental syntax configured via the Rhino Context
429 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
430
431 function <member-expr> ( [ arg-list ] ) { <body> }
432
433 Where member-expr is a non-parenthesized 'member expression', which
434 is anything at the grammar level of a new-expression or lower, meaning
435 any expression that does not involve infix or unary operators.
436
437 When <member-expr> is not a simple identifier, then it is syntactic
438 sugar for assigning the anonymous function to the <member-expr>. Hence,
439 this code:
440
441 function a.b().c[2] (x, y) { ... }
442
443 is rewritten as:
444
445 a.b().c[2] = function(x, y) {...}
446
447 which doesn't seem particularly useful, but Rhino permits it."
448 :type 'boolean
449 :group 'js2-mode)
450
451 ;; scanner variables
452
453 (defmacro js2-deflocal (name value &optional comment)
454 "Define a buffer-local variable NAME with VALUE and COMMENT."
455 (declare (debug defvar) (doc-string 3))
456 `(progn
457 (defvar ,name ,value ,comment)
458 (make-variable-buffer-local ',name)))
459
460 (defvar js2-EOF_CHAR -1
461 "Represents end of stream. Distinct from js2-EOF token type.")
462
463 ;; I originally used symbols to represent tokens, but Rhino uses
464 ;; ints and then sets various flag bits in them, so ints it is.
465 ;; The upshot is that we need a `js2-' prefix in front of each name.
466 (defvar js2-ERROR -1)
467 (defvar js2-EOF 0)
468 (defvar js2-EOL 1)
469 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
470 (defvar js2-LEAVEWITH 3)
471 (defvar js2-RETURN 4)
472 (defvar js2-GOTO 5)
473 (defvar js2-IFEQ 6)
474 (defvar js2-IFNE 7)
475 (defvar js2-SETNAME 8)
476 (defvar js2-BITOR 9)
477 (defvar js2-BITXOR 10)
478 (defvar js2-BITAND 11)
479 (defvar js2-EQ 12)
480 (defvar js2-NE 13)
481 (defvar js2-LT 14)
482 (defvar js2-LE 15)
483 (defvar js2-GT 16)
484 (defvar js2-GE 17)
485 (defvar js2-LSH 18)
486 (defvar js2-RSH 19)
487 (defvar js2-URSH 20)
488 (defvar js2-ADD 21) ; infix plus
489 (defvar js2-SUB 22) ; infix minus
490 (defvar js2-MUL 23)
491 (defvar js2-DIV 24)
492 (defvar js2-MOD 25)
493 (defvar js2-NOT 26)
494 (defvar js2-BITNOT 27)
495 (defvar js2-POS 28) ; unary plus
496 (defvar js2-NEG 29) ; unary minus
497 (defvar js2-NEW 30)
498 (defvar js2-DELPROP 31)
499 (defvar js2-TYPEOF 32)
500 (defvar js2-GETPROP 33)
501 (defvar js2-GETPROPNOWARN 34)
502 (defvar js2-SETPROP 35)
503 (defvar js2-GETELEM 36)
504 (defvar js2-SETELEM 37)
505 (defvar js2-CALL 38)
506 (defvar js2-NAME 39) ; an identifier
507 (defvar js2-NUMBER 40)
508 (defvar js2-STRING 41)
509 (defvar js2-NULL 42)
510 (defvar js2-THIS 43)
511 (defvar js2-FALSE 44)
512 (defvar js2-TRUE 45)
513 (defvar js2-SHEQ 46) ; shallow equality (===)
514 (defvar js2-SHNE 47) ; shallow inequality (!==)
515 (defvar js2-REGEXP 48)
516 (defvar js2-BINDNAME 49)
517 (defvar js2-THROW 50)
518 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
519 (defvar js2-IN 52)
520 (defvar js2-INSTANCEOF 53)
521 (defvar js2-LOCAL_LOAD 54)
522 (defvar js2-GETVAR 55)
523 (defvar js2-SETVAR 56)
524 (defvar js2-CATCH_SCOPE 57)
525 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
526 (defvar js2-ENUM_INIT_VALUES 59)
527 (defvar js2-ENUM_INIT_ARRAY 60)
528 (defvar js2-ENUM_NEXT 61)
529 (defvar js2-ENUM_ID 62)
530 (defvar js2-THISFN 63)
531 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
532 (defvar js2-ARRAYLIT 65) ; array literal
533 (defvar js2-OBJECTLIT 66) ; object literal
534 (defvar js2-GET_REF 67) ; *reference
535 (defvar js2-SET_REF 68) ; *reference = something
536 (defvar js2-DEL_REF 69) ; delete reference
537 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
538 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
539 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
540
541 ;; XML support
542 (defvar js2-DEFAULTNAMESPACE 73)
543 (defvar js2-ESCXMLATTR 74)
544 (defvar js2-ESCXMLTEXT 75)
545 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
546 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
547 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
548 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
549
550 (defvar js2-first-bytecode js2-ENTERWITH)
551 (defvar js2-last-bytecode js2-REF_NS_NAME)
552
553 (defvar js2-TRY 80)
554 (defvar js2-SEMI 81) ; semicolon
555 (defvar js2-LB 82) ; left and right brackets
556 (defvar js2-RB 83)
557 (defvar js2-LC 84) ; left and right curly-braces
558 (defvar js2-RC 85)
559 (defvar js2-LP 86) ; left and right parens
560 (defvar js2-RP 87)
561 (defvar js2-COMMA 88) ; comma operator
562
563 (defvar js2-ASSIGN 89) ; simple assignment (=)
564 (defvar js2-ASSIGN_BITOR 90) ; |=
565 (defvar js2-ASSIGN_BITXOR 91) ; ^=
566 (defvar js2-ASSIGN_BITAND 92) ; &=
567 (defvar js2-ASSIGN_LSH 93) ; <<=
568 (defvar js2-ASSIGN_RSH 94) ; >>=
569 (defvar js2-ASSIGN_URSH 95) ; >>>=
570 (defvar js2-ASSIGN_ADD 96) ; +=
571 (defvar js2-ASSIGN_SUB 97) ; -=
572 (defvar js2-ASSIGN_MUL 98) ; *=
573 (defvar js2-ASSIGN_DIV 99) ; /=
574 (defvar js2-ASSIGN_MOD 100) ; %=
575
576 (defvar js2-first-assign js2-ASSIGN)
577 (defvar js2-last-assign js2-ASSIGN_MOD)
578
579 (defvar js2-HOOK 101) ; conditional (?:)
580 (defvar js2-COLON 102)
581 (defvar js2-OR 103) ; logical or (||)
582 (defvar js2-AND 104) ; logical and (&&)
583 (defvar js2-INC 105) ; increment/decrement (++ --)
584 (defvar js2-DEC 106)
585 (defvar js2-DOT 107) ; member operator (.)
586 (defvar js2-FUNCTION 108) ; function keyword
587 (defvar js2-EXPORT 109) ; export keyword
588 (defvar js2-IMPORT 110) ; import keyword
589 (defvar js2-IF 111) ; if keyword
590 (defvar js2-ELSE 112) ; else keyword
591 (defvar js2-SWITCH 113) ; switch keyword
592 (defvar js2-CASE 114) ; case keyword
593 (defvar js2-DEFAULT 115) ; default keyword
594 (defvar js2-WHILE 116) ; while keyword
595 (defvar js2-DO 117) ; do keyword
596 (defvar js2-FOR 118) ; for keyword
597 (defvar js2-BREAK 119) ; break keyword
598 (defvar js2-CONTINUE 120) ; continue keyword
599 (defvar js2-VAR 121) ; var keyword
600 (defvar js2-WITH 122) ; with keyword
601 (defvar js2-CATCH 123) ; catch keyword
602 (defvar js2-FINALLY 124) ; finally keyword
603 (defvar js2-VOID 125) ; void keyword
604 (defvar js2-RESERVED 126) ; reserved keywords
605
606 (defvar js2-EMPTY 127)
607
608 ;; Types used for the parse tree - never returned by scanner.
609
610 (defvar js2-BLOCK 128) ; statement block
611 (defvar js2-LABEL 129) ; label
612 (defvar js2-TARGET 130)
613 (defvar js2-LOOP 131)
614 (defvar js2-EXPR_VOID 132) ; expression statement in functions
615 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
616 (defvar js2-JSR 134)
617 (defvar js2-SCRIPT 135) ; top-level node for entire script
618 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
619 (defvar js2-USE_STACK 137)
620 (defvar js2-SETPROP_OP 138) ; x.y op= something
621 (defvar js2-SETELEM_OP 139) ; x[y] op= something
622 (defvar js2-LOCAL_BLOCK 140)
623 (defvar js2-SET_REF_OP 141) ; *reference op= something
624
625 ;; For XML support:
626 (defvar js2-DOTDOT 142) ; member operator (..)
627 (defvar js2-COLONCOLON 143) ; namespace::name
628 (defvar js2-XML 144) ; XML type
629 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
630 (defvar js2-XMLATTR 146) ; @
631 (defvar js2-XMLEND 147)
632
633 ;; Optimizer-only tokens
634 (defvar js2-TO_OBJECT 148)
635 (defvar js2-TO_DOUBLE 149)
636
637 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
638 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
639 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
640 (defvar js2-CONST 153)
641 (defvar js2-SETCONST 154)
642 (defvar js2-SETCONSTVAR 155)
643 (defvar js2-ARRAYCOMP 156)
644 (defvar js2-LETEXPR 157)
645 (defvar js2-WITHEXPR 158)
646 (defvar js2-DEBUGGER 159)
647
648 (defvar js2-COMMENT 160)
649 (defvar js2-TRIPLEDOT 161) ; for rest parameter
650 (defvar js2-ARROW 162) ; function arrow (=>)
651 (defvar js2-CLASS 163)
652 (defvar js2-EXTENDS 164)
653 (defvar js2-STATIC 165)
654 (defvar js2-SUPER 166)
655 (defvar js2-TEMPLATE_HEAD 167) ; part of template literal before substitution
656 (defvar js2-NO_SUBS_TEMPLATE 168) ; template literal without substitutions
657 (defvar js2-TAGGED_TEMPLATE 169) ; tagged template literal
658
659 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
660
661 (defconst js2-debug-print-trees nil)
662
663 ;; Rhino accepts any string or stream as input. Emacs character
664 ;; processing works best in buffers, so we'll assume the input is a
665 ;; buffer. JavaScript strings can be copied into temp buffers before
666 ;; scanning them.
667
668 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
669 ;; They're the Emacs equivalent of instance variables, more or less.
670
671 (js2-deflocal js2-ts-dirty-line nil
672 "Token stream buffer-local variable.
673 Indicates stuff other than whitespace since start of line.")
674
675 (js2-deflocal js2-ts-hit-eof nil
676 "Token stream buffer-local variable.")
677
678 ;; FIXME: Unused.
679 (js2-deflocal js2-ts-line-start 0
680 "Token stream buffer-local variable.")
681
682 (js2-deflocal js2-ts-lineno 1
683 "Token stream buffer-local variable.")
684
685 ;; FIXME: Unused.
686 (js2-deflocal js2-ts-line-end-char -1
687 "Token stream buffer-local variable.")
688
689 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
690 "Token stream buffer-local variable.
691 Current scan position.")
692
693 ;; FIXME: Unused.
694 (js2-deflocal js2-ts-is-xml-attribute nil
695 "Token stream buffer-local variable.")
696
697 (js2-deflocal js2-ts-xml-is-tag-content nil
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-xml-open-tags-count 0
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-string-buffer nil
704 "Token stream buffer-local variable.
705 List of chars built up while scanning various tokens.")
706
707 (cl-defstruct (js2-token
708 (:constructor nil)
709 (:constructor make-js2-token (beg)))
710 "Value returned from the token stream."
711 (type js2-EOF)
712 (beg 1)
713 (end -1)
714 (string "")
715 number
716 regexp-flags
717 comment-type
718 follows-eol-p)
719
720 ;; Have to call `js2-init-scanner' to initialize the values.
721 (js2-deflocal js2-ti-tokens nil)
722 (js2-deflocal js2-ti-tokens-cursor nil)
723 (js2-deflocal js2-ti-lookahead nil)
724
725 (cl-defstruct (js2-ts-state
726 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
727 (cursor js2-ts-cursor)
728 (tokens (copy-sequence js2-ti-tokens))
729 (tokens-cursor js2-ti-tokens-cursor)
730 (lookahead js2-ti-lookahead))))
731 lineno
732 cursor
733 tokens
734 tokens-cursor
735 lookahead)
736
737 ;;; Parser variables
738
739 (js2-deflocal js2-parsed-errors nil
740 "List of errors produced during scanning/parsing.")
741
742 (js2-deflocal js2-parsed-warnings nil
743 "List of warnings produced during scanning/parsing.")
744
745 (js2-deflocal js2-recover-from-parse-errors t
746 "Non-nil to continue parsing after a syntax error.
747
748 In recovery mode, the AST will be built in full, and any error
749 nodes will be flagged with appropriate error information. If
750 this flag is nil, a syntax error will result in an error being
751 signaled.
752
753 The variable is automatically buffer-local, because different
754 modes that use the parser will need different settings.")
755
756 (js2-deflocal js2-parse-hook nil
757 "List of callbacks for receiving parsing progress.")
758
759 (defvar js2-parse-finished-hook nil
760 "List of callbacks to notify when parsing finishes.
761 Not called if parsing was interrupted.")
762
763 (js2-deflocal js2-is-eval-code nil
764 "True if we're evaluating code in a string.
765 If non-nil, the tokenizer will record the token text, and the AST nodes
766 will record their source text. Off by default for IDE modes, since the
767 text is available in the buffer.")
768
769 (defvar js2-parse-ide-mode t
770 "Non-nil if the parser is being used for `js2-mode'.
771 If non-nil, the parser will set text properties for fontification
772 and the syntax table. The value should be nil when using the
773 parser as a frontend to an interpreter or byte compiler.")
774
775 ;;; Parser instance variables (buffer-local vars for js2-parse)
776
777 (defconst js2-ti-after-eol (lsh 1 16)
778 "Flag: first token of the source line.")
779
780 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
781
782 (js2-deflocal js2-compiler-generate-debug-info t)
783 (js2-deflocal js2-compiler-use-dynamic-scope nil)
784 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
785 (js2-deflocal js2-compiler-xml-available t)
786 (js2-deflocal js2-compiler-optimization-level 0)
787 (js2-deflocal js2-compiler-generating-source t)
788 (js2-deflocal js2-compiler-strict-mode nil)
789 (js2-deflocal js2-compiler-report-warning-as-error nil)
790 (js2-deflocal js2-compiler-generate-observer-count nil)
791 (js2-deflocal js2-compiler-activation-names nil)
792
793 ;; SKIP: sourceURI
794
795 ;; There's a compileFunction method in Context.java - may need it.
796 (js2-deflocal js2-called-by-compile-function nil
797 "True if `js2-parse' was called by `js2-compile-function'.
798 Will only be used when we finish implementing the interpreter.")
799
800 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
801
802 ;; SKIP: node factory - we're going to just call functions directly,
803 ;; and eventually go to a unified AST format.
804
805 (js2-deflocal js2-nesting-of-function 0)
806
807 (js2-deflocal js2-recorded-identifiers nil
808 "Tracks identifiers found during parsing.")
809
810 (js2-deflocal js2-is-in-destructuring nil
811 "True while parsing destructuring expression.")
812
813 (defcustom js2-global-externs nil
814 "A list of any extern names you'd like to consider always declared.
815 This list is global and is used by all `js2-mode' files.
816 You can create buffer-local externs list using `js2-additional-externs'.
817
818 There is also a buffer-local variable `js2-default-externs',
819 which is initialized by default to include the Ecma-262 externs
820 and the standard browser externs. The three lists are all
821 checked during highlighting."
822 :type 'list
823 :group 'js2-mode)
824
825 (js2-deflocal js2-default-externs nil
826 "Default external declarations.
827
828 These are currently only used for highlighting undeclared variables,
829 which only worries about top-level (unqualified) references.
830 As js2-mode's processing improves, we will flesh out this list.
831
832 The initial value is set to `js2-ecma-262-externs', unless some
833 of the `js2-include-?-externs' variables are set to t, in which
834 case the browser, Rhino and/or Node.js externs are also included.
835
836 See `js2-additional-externs' for more information.")
837
838 (defcustom js2-include-browser-externs t
839 "Non-nil to include browser externs in the master externs list.
840 If you work on JavaScript files that are not intended for browsers,
841 such as Mozilla Rhino server-side JavaScript, set this to nil.
842 See `js2-additional-externs' for more information about externs."
843 :type 'boolean
844 :group 'js2-mode)
845
846 (defcustom js2-include-rhino-externs nil
847 "Non-nil to include Mozilla Rhino externs in the master externs list.
848 See `js2-additional-externs' for more information about externs."
849 :type 'boolean
850 :group 'js2-mode)
851
852 (defcustom js2-include-node-externs nil
853 "Non-nil to include Node.js externs in the master externs list.
854 See `js2-additional-externs' for more information about externs."
855 :type 'boolean
856 :group 'js2-mode)
857
858 (js2-deflocal js2-additional-externs nil
859 "A buffer-local list of additional external declarations.
860 It is used to decide whether variables are considered undeclared
861 for purposes of highlighting.
862
863 Each entry is a Lisp string. The string should be the fully qualified
864 name of an external entity. All externs should be added to this list,
865 so that as js2-mode's processing improves it can take advantage of them.
866
867 You may want to declare your externs in three ways.
868 First, you can add externs that are valid for all your JavaScript files.
869 You should probably do this by adding them to `js2-global-externs', which
870 is a global list used for all js2-mode files.
871
872 Next, you can add a function to `js2-init-hook' that adds additional
873 externs appropriate for the specific file, perhaps based on its path.
874 These should go in `js2-additional-externs', which is buffer-local.
875
876 Third, you can use JSLint's global declaration, as long as
877 `js2-include-jslint-globals' is non-nil, which see.
878
879 Finally, you can add a function to `js2-post-parse-callbacks',
880 which is called after parsing completes, and `js2-mode-ast' is bound to
881 the root of the parse tree. At this stage you can set up an AST
882 node visitor using `js2-visit-ast' and examine the parse tree
883 for specific import patterns that may imply the existence of
884 other externs, possibly tied to your build system. These should also
885 be added to `js2-additional-externs'.
886
887 Your post-parse callback may of course also use the simpler and
888 faster (but perhaps less robust) approach of simply scanning the
889 buffer text for your imports, using regular expressions.")
890
891 ;; SKIP: decompiler
892 ;; SKIP: encoded-source
893
894 ;;; The following variables are per-function and should be saved/restored
895 ;;; during function parsing...
896
897 (js2-deflocal js2-current-script-or-fn nil)
898 (js2-deflocal js2-current-scope nil)
899 (js2-deflocal js2-nesting-of-with 0)
900 (js2-deflocal js2-label-set nil
901 "An alist mapping label names to nodes.")
902
903 (js2-deflocal js2-loop-set nil)
904 (js2-deflocal js2-loop-and-switch-set nil)
905 (js2-deflocal js2-has-return-value nil)
906 (js2-deflocal js2-end-flags 0)
907
908 ;;; ...end of per function variables
909
910 ;; These flags enumerate the possible ways a statement/function can
911 ;; terminate. These flags are used by endCheck() and by the Parser to
912 ;; detect inconsistent return usage.
913 ;;
914 ;; END_UNREACHED is reserved for code paths that are assumed to always be
915 ;; able to execute (example: throw, continue)
916 ;;
917 ;; END_DROPS_OFF indicates if the statement can transfer control to the
918 ;; next one. Statement such as return dont. A compound statement may have
919 ;; some branch that drops off control to the next statement.
920 ;;
921 ;; END_RETURNS indicates that the statement can return (without arguments)
922 ;; END_RETURNS_VALUE indicates that the statement can return a value.
923 ;;
924 ;; A compound statement such as
925 ;; if (condition) {
926 ;; return value;
927 ;; }
928 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
929
930 (defconst js2-end-unreached #x0)
931 (defconst js2-end-drops-off #x1)
932 (defconst js2-end-returns #x2)
933 (defconst js2-end-returns-value #x4)
934
935 ;; Rhino awkwardly passes a statementLabel parameter to the
936 ;; statementHelper() function, the main statement parser, which
937 ;; is then used by quite a few of the sub-parsers. We just make
938 ;; it a buffer-local variable and make sure it's cleaned up properly.
939 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
940
941 ;; Similarly, Rhino passes an inForInit boolean through about half
942 ;; the expression parsers. We use a dynamically-scoped variable,
943 ;; which makes it easier to funcall the parsers individually without
944 ;; worrying about whether they take the parameter or not.
945 (js2-deflocal js2-in-for-init nil)
946 (js2-deflocal js2-temp-name-counter 0)
947 (js2-deflocal js2-parse-stmt-count 0)
948
949 (defsubst js2-get-next-temp-name ()
950 (format "$%d" (cl-incf js2-temp-name-counter)))
951
952 (defvar js2-parse-interruptable-p t
953 "Set this to nil to force parse to continue until finished.
954 This will mostly be useful for interpreters.")
955
956 (defvar js2-statements-per-pause 50
957 "Pause after this many statements to check for user input.
958 If user input is pending, stop the parse and discard the tree.
959 This makes for a smoother user experience for large files.
960 You may have to wait a second or two before the highlighting
961 and error-reporting appear, but you can always type ahead if
962 you wish. This appears to be more or less how Eclipse, IntelliJ
963 and other editors work.")
964
965 (js2-deflocal js2-record-comments t
966 "Instructs the scanner to record comments in `js2-scanned-comments'.")
967
968 (js2-deflocal js2-scanned-comments nil
969 "List of all comments from the current parse.")
970
971 (defcustom js2-mode-indent-inhibit-undo nil
972 "Non-nil to disable collection of Undo information when indenting lines.
973 Some users have requested this behavior. It's nil by default because
974 other Emacs modes don't work this way."
975 :type 'boolean
976 :group 'js2-mode)
977
978 (defcustom js2-mode-indent-ignore-first-tab nil
979 "If non-nil, ignore first TAB keypress if we look indented properly.
980 It's fairly common for users to navigate to an already-indented line
981 and press TAB for reassurance that it's been indented. For this class
982 of users, we want the first TAB press on a line to be ignored if the
983 line is already indented to one of the precomputed alternatives.
984
985 This behavior is only partly implemented. If you TAB-indent a line,
986 navigate to another line, and then navigate back, it fails to clear
987 the last-indented variable, so it thinks you've already hit TAB once,
988 and performs the indent. A full solution would involve getting on the
989 point-motion hooks for the entire buffer. If we come across another
990 use cases that requires watching point motion, I'll consider doing it.
991
992 If you set this variable to nil, then the TAB key will always change
993 the indentation of the current line, if more than one alternative
994 indentation spot exists."
995 :type 'boolean
996 :group 'js2-mode)
997
998 (defvar js2-indent-hook nil
999 "A hook for user-defined indentation rules.
1000
1001 Functions on this hook should expect two arguments: (LIST INDEX)
1002 The LIST argument is the list of computed indentation points for
1003 the current line. INDEX is the list index of the indentation point
1004 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1005 indent function is not going to change the current line indentation.
1006
1007 If a hook function on this list returns a non-nil value, then
1008 `js2-bounce-indent' assumes the hook function has performed its own
1009 indentation, and will do nothing. If all hook functions on the list
1010 return nil, then `js2-bounce-indent' will use its computed indentation
1011 and reindent the line.
1012
1013 When hook functions on this hook list are called, the variable
1014 `js2-mode-ast' may or may not be set, depending on whether the
1015 parse tree is available. If the variable is nil, you can pass a
1016 callback to `js2-mode-wait-for-parse', and your callback will be
1017 called after the new parse tree is built. This can take some time
1018 in large files.")
1019
1020 (defface js2-warning
1021 `((((class color) (background light))
1022 (:underline "orange"))
1023 (((class color) (background dark))
1024 (:underline "orange"))
1025 (t (:underline t)))
1026 "Face for JavaScript warnings."
1027 :group 'js2-mode)
1028
1029 (defface js2-error
1030 `((((class color) (background light))
1031 (:foreground "red"))
1032 (((class color) (background dark))
1033 (:foreground "red"))
1034 (t (:foreground "red")))
1035 "Face for JavaScript errors."
1036 :group 'js2-mode)
1037
1038 (defface js2-jsdoc-tag
1039 '((t :foreground "SlateGray"))
1040 "Face used to highlight @whatever tags in jsdoc comments."
1041 :group 'js2-mode)
1042
1043 (defface js2-jsdoc-type
1044 '((t :foreground "SteelBlue"))
1045 "Face used to highlight {FooBar} types in jsdoc comments."
1046 :group 'js2-mode)
1047
1048 (defface js2-jsdoc-value
1049 '((t :foreground "PeachPuff3"))
1050 "Face used to highlight tag values in jsdoc comments."
1051 :group 'js2-mode)
1052
1053 (defface js2-function-param
1054 '((t :foreground "SeaGreen"))
1055 "Face used to highlight function parameters in javascript."
1056 :group 'js2-mode)
1057
1058 (defface js2-function-call
1059 '((t :inherit default))
1060 "Face used to highlight function name in calls."
1061 :group 'js2-mode)
1062
1063 (defface js2-instance-member
1064 '((t :foreground "DarkOrchid"))
1065 "Face used to highlight instance variables in javascript.
1066 Not currently used."
1067 :group 'js2-mode)
1068
1069 (defface js2-private-member
1070 '((t :foreground "PeachPuff3"))
1071 "Face used to highlight calls to private methods in javascript.
1072 Not currently used."
1073 :group 'js2-mode)
1074
1075 (defface js2-private-function-call
1076 '((t :foreground "goldenrod"))
1077 "Face used to highlight calls to private functions in javascript.
1078 Not currently used."
1079 :group 'js2-mode)
1080
1081 (defface js2-jsdoc-html-tag-name
1082 '((((class color) (min-colors 88) (background light))
1083 (:foreground "rosybrown"))
1084 (((class color) (min-colors 8) (background dark))
1085 (:foreground "yellow"))
1086 (((class color) (min-colors 8) (background light))
1087 (:foreground "magenta")))
1088 "Face used to highlight jsdoc html tag names"
1089 :group 'js2-mode)
1090
1091 (defface js2-jsdoc-html-tag-delimiter
1092 '((((class color) (min-colors 88) (background light))
1093 (:foreground "dark khaki"))
1094 (((class color) (min-colors 8) (background dark))
1095 (:foreground "green"))
1096 (((class color) (min-colors 8) (background light))
1097 (:foreground "green")))
1098 "Face used to highlight brackets in jsdoc html tags."
1099 :group 'js2-mode)
1100
1101 (defface js2-external-variable
1102 '((t :foreground "orange"))
1103 "Face used to highlight undeclared variable identifiers.")
1104
1105 (defcustom js2-init-hook nil
1106 "List of functions to be called after `js2-mode' or
1107 `js2-minor-mode' has initialized all variables, before parsing
1108 the buffer for the first time."
1109 :type 'hook
1110 :group 'js2-mode
1111 :version "20130608")
1112
1113 (defcustom js2-post-parse-callbacks nil
1114 "List of callback functions invoked after parsing finishes.
1115 Currently, the main use for this function is to add synthetic
1116 declarations to `js2-recorded-identifiers', which see."
1117 :type 'hook
1118 :group 'js2-mode)
1119
1120 (defcustom js2-build-imenu-callbacks nil
1121 "List of functions called during Imenu index generation.
1122 It's a good place to add additional entries to it, using
1123 `js2-record-imenu-entry'."
1124 :type 'hook
1125 :group 'js2-mode)
1126
1127 (defcustom js2-highlight-external-variables t
1128 "Non-nil to highlight undeclared variable identifiers.
1129 An undeclared variable is any variable not declared with var or let
1130 in the current scope or any lexically enclosing scope. If you use
1131 such a variable, then you are either expecting it to originate from
1132 another file, or you've got a potential bug."
1133 :type 'boolean
1134 :group 'js2-mode)
1135
1136 (defcustom js2-include-jslint-globals t
1137 "Non-nil to include the identifiers from JSLint global
1138 declaration (see http://www.jslint.com/lint.html#global) in the
1139 buffer-local externs list. See `js2-additional-externs' for more
1140 information."
1141 :type 'boolean
1142 :group 'js2-mode)
1143
1144 (defvar js2-mode-map
1145 (let ((map (make-sparse-keymap)))
1146 (define-key map [mouse-1] #'js2-mode-show-node)
1147 (define-key map (kbd "M-j") #'js2-line-break)
1148 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1149 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1150 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1151 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1152 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1153 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1154 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1155 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1156 (when js2-bounce-indent-p
1157 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1158
1159 (define-key map [menu-bar javascript]
1160 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1161
1162 (define-key map [menu-bar javascript customize-js2-mode]
1163 '(menu-item "Customize js2-mode" js2-mode-customize
1164 :help "Customize the behavior of this mode"))
1165
1166 (define-key map [menu-bar javascript js2-force-refresh]
1167 '(menu-item "Force buffer refresh" js2-mode-reset
1168 :help "Re-parse the buffer from scratch"))
1169
1170 (define-key map [menu-bar javascript separator-2]
1171 '("--"))
1172
1173 (define-key map [menu-bar javascript next-error]
1174 '(menu-item "Next warning or error" next-error
1175 :enabled (and js2-mode-ast
1176 (or (js2-ast-root-errors js2-mode-ast)
1177 (js2-ast-root-warnings js2-mode-ast)))
1178 :help "Move to next warning or error"))
1179
1180 (define-key map [menu-bar javascript display-errors]
1181 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1182 :visible (not js2-mode-show-parse-errors)
1183 :help "Turn on display of warnings and errors"))
1184
1185 (define-key map [menu-bar javascript hide-errors]
1186 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1187 :visible js2-mode-show-parse-errors
1188 :help "Turn off display of warnings and errors"))
1189
1190 (define-key map [menu-bar javascript separator-1]
1191 '("--"))
1192
1193 (define-key map [menu-bar javascript js2-toggle-function]
1194 '(menu-item "Show/collapse element" js2-mode-toggle-element
1195 :help "Hide or show function body or comment"))
1196
1197 (define-key map [menu-bar javascript show-comments]
1198 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1199 :visible js2-mode-comments-hidden
1200 :help "Expand all hidden block comments"))
1201
1202 (define-key map [menu-bar javascript hide-comments]
1203 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1204 :visible (not js2-mode-comments-hidden)
1205 :help "Show block comments as /*...*/"))
1206
1207 (define-key map [menu-bar javascript show-all-functions]
1208 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1209 :visible js2-mode-functions-hidden
1210 :help "Expand all hidden function bodies"))
1211
1212 (define-key map [menu-bar javascript hide-all-functions]
1213 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1214 :visible (not js2-mode-functions-hidden)
1215 :help "Show {...} for all top-level function bodies"))
1216
1217 map)
1218 "Keymap used in `js2-mode' buffers.")
1219
1220 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1221
1222 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1223 "Matches a //-comment line. Must be first non-whitespace on line.
1224 First match-group is the leading whitespace.")
1225
1226 (defvar js2-mode-hook nil)
1227
1228 (js2-deflocal js2-mode-ast nil "Private variable.")
1229 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1230 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1231 (js2-deflocal js2-mode-parsing nil "Private variable.")
1232 (js2-deflocal js2-mode-node-overlay nil)
1233
1234 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1235 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1236
1237 (js2-deflocal js2-mode-fontifications nil "Private variable")
1238 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1239 (js2-deflocal js2-imenu-recorder nil "Private variable")
1240 (js2-deflocal js2-imenu-function-map nil "Private variable")
1241
1242 (defvar js2-paragraph-start
1243 "\\(@[[:alpha:]]+\\>\\|$\\)")
1244
1245 ;; Note that we also set a 'c-in-sws text property in html comments,
1246 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1247 (defvar js2-syntactic-ws-start
1248 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1249
1250 (defvar js2-syntactic-ws-end
1251 "\\s \\|[\n\r/]\\|\\s!")
1252
1253 (defvar js2-syntactic-eol
1254 (concat "\\s *\\(/\\*[^*\n\r]*"
1255 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1256 "\\*+/\\s *\\)*"
1257 "\\(//\\|/\\*[^*\n\r]*"
1258 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1259 "\\|\\\\$\\|$\\)")
1260 "Copied from `java-mode'. Needed for some cc-engine functions.")
1261
1262 (defvar js2-comment-prefix-regexp
1263 "//+\\|\\**")
1264
1265 (defvar js2-comment-start-skip
1266 "\\(//+\\|/\\*+\\)\\s *")
1267
1268 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1269 "Non-nil to emit status messages during parsing.")
1270
1271 (defvar js2-mode-functions-hidden nil "Private variable.")
1272 (defvar js2-mode-comments-hidden nil "Private variable.")
1273
1274 (defvar js2-mode-syntax-table
1275 (let ((table (make-syntax-table)))
1276 (c-populate-syntax-table table)
1277 table)
1278 "Syntax table used in `js2-mode' buffers.")
1279
1280 (defvar js2-mode-abbrev-table nil
1281 "Abbrev table in use in `js2-mode' buffers.")
1282 (define-abbrev-table 'js2-mode-abbrev-table ())
1283
1284 (defvar js2-mode-pending-parse-callbacks nil
1285 "List of functions waiting to be notified that parse is finished.")
1286
1287 (defvar js2-mode-last-indented-line -1)
1288
1289 ;;; Localizable error and warning messages
1290
1291 ;; Messages are copied from Rhino's Messages.properties.
1292 ;; Many of the Java-specific messages have been elided.
1293 ;; Add any js2-specific ones at the end, so we can keep
1294 ;; this file synced with changes to Rhino's.
1295
1296 (defvar js2-message-table
1297 (make-hash-table :test 'equal :size 250)
1298 "Contains localized messages for `js2-mode'.")
1299
1300 ;; TODO(stevey): construct this table at compile-time.
1301 (defmacro js2-msg (key &rest strings)
1302 `(puthash ,key (concat ,@strings)
1303 js2-message-table))
1304
1305 (defun js2-get-msg (msg-key)
1306 "Look up a localized message.
1307 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1308 the correct number of ARGS must be provided."
1309 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1310 (args (if (listp msg-key) (cdr msg-key)))
1311 (msg (gethash key js2-message-table)))
1312 (if msg
1313 (apply #'format msg args)
1314 key))) ; default to showing the key
1315
1316 (js2-msg "msg.dup.parms"
1317 "Duplicate parameter name '%s'.")
1318
1319 (js2-msg "msg.too.big.jump"
1320 "Program too complex: jump offset too big.")
1321
1322 (js2-msg "msg.too.big.index"
1323 "Program too complex: internal index exceeds 64K limit.")
1324
1325 (js2-msg "msg.while.compiling.fn"
1326 "Encountered code generation error while compiling function '%s': %s")
1327
1328 (js2-msg "msg.while.compiling.script"
1329 "Encountered code generation error while compiling script: %s")
1330
1331 ;; Context
1332 (js2-msg "msg.ctor.not.found"
1333 "Constructor for '%s' not found.")
1334
1335 (js2-msg "msg.not.ctor"
1336 "'%s' is not a constructor.")
1337
1338 ;; FunctionObject
1339 (js2-msg "msg.varargs.ctor"
1340 "Method or constructor '%s' must be static "
1341 "with the signature (Context cx, Object[] args, "
1342 "Function ctorObj, boolean inNewExpr) "
1343 "to define a variable arguments constructor.")
1344
1345 (js2-msg "msg.varargs.fun"
1346 "Method '%s' must be static with the signature "
1347 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1348 "to define a variable arguments function.")
1349
1350 (js2-msg "msg.incompat.call"
1351 "Method '%s' called on incompatible object.")
1352
1353 (js2-msg "msg.bad.parms"
1354 "Unsupported parameter type '%s' in method '%s'.")
1355
1356 (js2-msg "msg.bad.method.return"
1357 "Unsupported return type '%s' in method '%s'.")
1358
1359 (js2-msg "msg.bad.ctor.return"
1360 "Construction of objects of type '%s' is not supported.")
1361
1362 (js2-msg "msg.no.overload"
1363 "Method '%s' occurs multiple times in class '%s'.")
1364
1365 (js2-msg "msg.method.not.found"
1366 "Method '%s' not found in '%s'.")
1367
1368 ;; IRFactory
1369
1370 (js2-msg "msg.bad.for.in.lhs"
1371 "Invalid left-hand side of for..in loop.")
1372
1373 (js2-msg "msg.mult.index"
1374 "Only one variable allowed in for..in loop.")
1375
1376 (js2-msg "msg.bad.for.in.destruct"
1377 "Left hand side of for..in loop must be an array of "
1378 "length 2 to accept key/value pair.")
1379
1380 (js2-msg "msg.cant.convert"
1381 "Can't convert to type '%s'.")
1382
1383 (js2-msg "msg.bad.assign.left"
1384 "Invalid assignment left-hand side.")
1385
1386 (js2-msg "msg.bad.decr"
1387 "Invalid decerement operand.")
1388
1389 (js2-msg "msg.bad.incr"
1390 "Invalid increment operand.")
1391
1392 (js2-msg "msg.bad.yield"
1393 "yield must be in a function.")
1394
1395 (js2-msg "msg.yield.parenthesized"
1396 "yield expression must be parenthesized.")
1397
1398 ;; NativeGlobal
1399 (js2-msg "msg.cant.call.indirect"
1400 "Function '%s' must be called directly, and not by way of a "
1401 "function of another name.")
1402
1403 (js2-msg "msg.eval.nonstring"
1404 "Calling eval() with anything other than a primitive "
1405 "string value will simply return the value. "
1406 "Is this what you intended?")
1407
1408 (js2-msg "msg.eval.nonstring.strict"
1409 "Calling eval() with anything other than a primitive "
1410 "string value is not allowed in strict mode.")
1411
1412 (js2-msg "msg.bad.destruct.op"
1413 "Invalid destructuring assignment operator")
1414
1415 ;; NativeCall
1416 (js2-msg "msg.only.from.new"
1417 "'%s' may only be invoked from a `new' expression.")
1418
1419 (js2-msg "msg.deprec.ctor"
1420 "The '%s' constructor is deprecated.")
1421
1422 ;; NativeFunction
1423 (js2-msg "msg.no.function.ref.found"
1424 "no source found to decompile function reference %s")
1425
1426 (js2-msg "msg.arg.isnt.array"
1427 "second argument to Function.prototype.apply must be an array")
1428
1429 ;; NativeGlobal
1430 (js2-msg "msg.bad.esc.mask"
1431 "invalid string escape mask")
1432
1433 ;; NativeRegExp
1434 (js2-msg "msg.bad.quant"
1435 "Invalid quantifier %s")
1436
1437 (js2-msg "msg.overlarge.backref"
1438 "Overly large back reference %s")
1439
1440 (js2-msg "msg.overlarge.min"
1441 "Overly large minimum %s")
1442
1443 (js2-msg "msg.overlarge.max"
1444 "Overly large maximum %s")
1445
1446 (js2-msg "msg.zero.quant"
1447 "Zero quantifier %s")
1448
1449 (js2-msg "msg.max.lt.min"
1450 "Maximum %s less than minimum")
1451
1452 (js2-msg "msg.unterm.quant"
1453 "Unterminated quantifier %s")
1454
1455 (js2-msg "msg.unterm.paren"
1456 "Unterminated parenthetical %s")
1457
1458 (js2-msg "msg.unterm.class"
1459 "Unterminated character class %s")
1460
1461 (js2-msg "msg.bad.range"
1462 "Invalid range in character class.")
1463
1464 (js2-msg "msg.trail.backslash"
1465 "Trailing \\ in regular expression.")
1466
1467 (js2-msg "msg.re.unmatched.right.paren"
1468 "unmatched ) in regular expression.")
1469
1470 (js2-msg "msg.no.regexp"
1471 "Regular expressions are not available.")
1472
1473 (js2-msg "msg.bad.backref"
1474 "back-reference exceeds number of capturing parentheses.")
1475
1476 (js2-msg "msg.bad.regexp.compile"
1477 "Only one argument may be specified if the first "
1478 "argument to RegExp.prototype.compile is a RegExp object.")
1479
1480 ;; Parser
1481 (js2-msg "msg.got.syntax.errors"
1482 "Compilation produced %s syntax errors.")
1483
1484 (js2-msg "msg.var.redecl"
1485 "TypeError: redeclaration of var %s.")
1486
1487 (js2-msg "msg.const.redecl"
1488 "TypeError: redeclaration of const %s.")
1489
1490 (js2-msg "msg.let.redecl"
1491 "TypeError: redeclaration of variable %s.")
1492
1493 (js2-msg "msg.parm.redecl"
1494 "TypeError: redeclaration of formal parameter %s.")
1495
1496 (js2-msg "msg.fn.redecl"
1497 "TypeError: redeclaration of function %s.")
1498
1499 (js2-msg "msg.let.decl.not.in.block"
1500 "SyntaxError: let declaration not directly within block")
1501
1502 (js2-msg "msg.mod.import.decl.at.top.level"
1503 "SyntaxError: import declarations may only appear at the top level")
1504
1505 (js2-msg "msg.mod.as.after.reserved.word"
1506 "SyntaxError: missing keyword 'as' after reserved word %s")
1507
1508 (js2-msg "msg.mod.rc.after.import.spec.list"
1509 "SyntaxError: missing '}' after module specifier list")
1510
1511 (js2-msg "msg.mod.from.after.import.spec.set"
1512 "SyntaxError: missing keyword 'from' after import specifier set")
1513
1514 (js2-msg "msg.mod.declaration.after.import"
1515 "SyntaxError: missing declaration after 'import' keyword")
1516
1517 (js2-msg "msg.mod.spec.after.from"
1518 "SyntaxError: missing module specifier after 'from' keyword")
1519
1520 (js2-msg "msg.mod.export.decl.at.top.level"
1521 "SyntaxError: export declarations may only appear at top level")
1522
1523 (js2-msg "msg.mod.rc.after.export.spec.list"
1524 "SyntaxError: missing '}' after export specifier list")
1525
1526 ;; NodeTransformer
1527 (js2-msg "msg.dup.label"
1528 "duplicated label")
1529
1530 (js2-msg "msg.undef.label"
1531 "undefined label")
1532
1533 (js2-msg "msg.bad.break"
1534 "unlabelled break must be inside loop or switch")
1535
1536 (js2-msg "msg.continue.outside"
1537 "continue must be inside loop")
1538
1539 (js2-msg "msg.continue.nonloop"
1540 "continue can only use labels of iteration statements")
1541
1542 (js2-msg "msg.bad.throw.eol"
1543 "Line terminator is not allowed between the throw "
1544 "keyword and throw expression.")
1545
1546 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1547 "function statement requires a name")
1548
1549 (js2-msg "msg.no.paren.parms"
1550 "missing ( before function parameters.")
1551
1552 (js2-msg "msg.no.parm"
1553 "missing formal parameter")
1554
1555 (js2-msg "msg.no.paren.after.parms"
1556 "missing ) after formal parameters")
1557
1558 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1559 "parameter without default follows parameter with default")
1560
1561 (js2-msg "msg.param.after.rest" ; added by js2-mode
1562 "parameter after rest parameter")
1563
1564 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1565 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1566
1567 (js2-msg "msg.no.brace.body"
1568 "missing '{' before function body")
1569
1570 (js2-msg "msg.no.brace.after.body"
1571 "missing } after function body")
1572
1573 (js2-msg "msg.no.paren.cond"
1574 "missing ( before condition")
1575
1576 (js2-msg "msg.no.paren.after.cond"
1577 "missing ) after condition")
1578
1579 (js2-msg "msg.no.semi.stmt"
1580 "missing ; before statement")
1581
1582 (js2-msg "msg.missing.semi"
1583 "missing ; after statement")
1584
1585 (js2-msg "msg.no.name.after.dot"
1586 "missing name after . operator")
1587
1588 (js2-msg "msg.no.name.after.coloncolon"
1589 "missing name after :: operator")
1590
1591 (js2-msg "msg.no.name.after.dotdot"
1592 "missing name after .. operator")
1593
1594 (js2-msg "msg.no.name.after.xmlAttr"
1595 "missing name after .@")
1596
1597 (js2-msg "msg.no.bracket.index"
1598 "missing ] in index expression")
1599
1600 (js2-msg "msg.no.paren.switch"
1601 "missing ( before switch expression")
1602
1603 (js2-msg "msg.no.paren.after.switch"
1604 "missing ) after switch expression")
1605
1606 (js2-msg "msg.no.brace.switch"
1607 "missing '{' before switch body")
1608
1609 (js2-msg "msg.bad.switch"
1610 "invalid switch statement")
1611
1612 (js2-msg "msg.no.colon.case"
1613 "missing : after case expression")
1614
1615 (js2-msg "msg.double.switch.default"
1616 "double default label in the switch statement")
1617
1618 (js2-msg "msg.no.while.do"
1619 "missing while after do-loop body")
1620
1621 (js2-msg "msg.no.paren.for"
1622 "missing ( after for")
1623
1624 (js2-msg "msg.no.semi.for"
1625 "missing ; after for-loop initializer")
1626
1627 (js2-msg "msg.no.semi.for.cond"
1628 "missing ; after for-loop condition")
1629
1630 (js2-msg "msg.in.after.for.name"
1631 "missing in or of after for")
1632
1633 (js2-msg "msg.no.paren.for.ctrl"
1634 "missing ) after for-loop control")
1635
1636 (js2-msg "msg.no.paren.with"
1637 "missing ( before with-statement object")
1638
1639 (js2-msg "msg.no.paren.after.with"
1640 "missing ) after with-statement object")
1641
1642 (js2-msg "msg.no.paren.after.let"
1643 "missing ( after let")
1644
1645 (js2-msg "msg.no.paren.let"
1646 "missing ) after variable list")
1647
1648 (js2-msg "msg.no.curly.let"
1649 "missing } after let statement")
1650
1651 (js2-msg "msg.bad.return"
1652 "invalid return")
1653
1654 (js2-msg "msg.no.brace.block"
1655 "missing } in compound statement")
1656
1657 (js2-msg "msg.bad.label"
1658 "invalid label")
1659
1660 (js2-msg "msg.bad.var"
1661 "missing variable name")
1662
1663 (js2-msg "msg.bad.var.init"
1664 "invalid variable initialization")
1665
1666 (js2-msg "msg.no.colon.cond"
1667 "missing : in conditional expression")
1668
1669 (js2-msg "msg.no.paren.arg"
1670 "missing ) after argument list")
1671
1672 (js2-msg "msg.no.bracket.arg"
1673 "missing ] after element list")
1674
1675 (js2-msg "msg.bad.prop"
1676 "invalid property id")
1677
1678 (js2-msg "msg.no.colon.prop"
1679 "missing : after property id")
1680
1681 (js2-msg "msg.no.brace.prop"
1682 "missing } after property list")
1683
1684 (js2-msg "msg.no.paren"
1685 "missing ) in parenthetical")
1686
1687 (js2-msg "msg.reserved.id"
1688 "'%s' is a reserved identifier")
1689
1690 (js2-msg "msg.no.paren.catch"
1691 "missing ( before catch-block condition")
1692
1693 (js2-msg "msg.bad.catchcond"
1694 "invalid catch block condition")
1695
1696 (js2-msg "msg.catch.unreachable"
1697 "any catch clauses following an unqualified catch are unreachable")
1698
1699 (js2-msg "msg.no.brace.try"
1700 "missing '{' before try block")
1701
1702 (js2-msg "msg.no.brace.catchblock"
1703 "missing '{' before catch-block body")
1704
1705 (js2-msg "msg.try.no.catchfinally"
1706 "'try' without 'catch' or 'finally'")
1707
1708 (js2-msg "msg.no.return.value"
1709 "function %s does not always return a value")
1710
1711 (js2-msg "msg.anon.no.return.value"
1712 "anonymous function does not always return a value")
1713
1714 (js2-msg "msg.return.inconsistent"
1715 "return statement is inconsistent with previous usage")
1716
1717 (js2-msg "msg.generator.returns"
1718 "TypeError: legacy generator function '%s' returns a value")
1719
1720 (js2-msg "msg.anon.generator.returns"
1721 "TypeError: anonymous legacy generator function returns a value")
1722
1723 (js2-msg "msg.syntax"
1724 "syntax error")
1725
1726 (js2-msg "msg.unexpected.eof"
1727 "Unexpected end of file")
1728
1729 (js2-msg "msg.XML.bad.form"
1730 "illegally formed XML syntax")
1731
1732 (js2-msg "msg.XML.not.available"
1733 "XML runtime not available")
1734
1735 (js2-msg "msg.too.deep.parser.recursion"
1736 "Too deep recursion while parsing")
1737
1738 (js2-msg "msg.no.side.effects"
1739 "Code has no side effects")
1740
1741 (js2-msg "msg.extra.trailing.comma"
1742 "Trailing comma is not supported in some browsers")
1743
1744 (js2-msg "msg.array.trailing.comma"
1745 "Trailing comma yields different behavior across browsers")
1746
1747 (js2-msg "msg.equal.as.assign"
1748 (concat "Test for equality (==) mistyped as assignment (=)?"
1749 " (parenthesize to suppress warning)"))
1750
1751 (js2-msg "msg.var.hides.arg"
1752 "Variable %s hides argument")
1753
1754 (js2-msg "msg.destruct.assign.no.init"
1755 "Missing = in destructuring declaration")
1756
1757 ;; ScriptRuntime
1758 (js2-msg "msg.no.properties"
1759 "%s has no properties.")
1760
1761 (js2-msg "msg.invalid.iterator"
1762 "Invalid iterator value")
1763
1764 (js2-msg "msg.iterator.primitive"
1765 "__iterator__ returned a primitive value")
1766
1767 (js2-msg "msg.assn.create.strict"
1768 "Assignment to undeclared variable %s")
1769
1770 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1771 "Undeclared variable or function '%s'")
1772
1773 (js2-msg "msg.ref.undefined.prop"
1774 "Reference to undefined property '%s'")
1775
1776 (js2-msg "msg.prop.not.found"
1777 "Property %s not found.")
1778
1779 (js2-msg "msg.invalid.type"
1780 "Invalid JavaScript value of type %s")
1781
1782 (js2-msg "msg.primitive.expected"
1783 "Primitive type expected (had %s instead)")
1784
1785 (js2-msg "msg.namespace.expected"
1786 "Namespace object expected to left of :: (found %s instead)")
1787
1788 (js2-msg "msg.null.to.object"
1789 "Cannot convert null to an object.")
1790
1791 (js2-msg "msg.undef.to.object"
1792 "Cannot convert undefined to an object.")
1793
1794 (js2-msg "msg.cyclic.value"
1795 "Cyclic %s value not allowed.")
1796
1797 (js2-msg "msg.is.not.defined"
1798 "'%s' is not defined.")
1799
1800 (js2-msg "msg.undef.prop.read"
1801 "Cannot read property '%s' from %s")
1802
1803 (js2-msg "msg.undef.prop.write"
1804 "Cannot set property '%s' of %s to '%s'")
1805
1806 (js2-msg "msg.undef.prop.delete"
1807 "Cannot delete property '%s' of %s")
1808
1809 (js2-msg "msg.undef.method.call"
1810 "Cannot call method '%s' of %s")
1811
1812 (js2-msg "msg.undef.with"
1813 "Cannot apply 'with' to %s")
1814
1815 (js2-msg "msg.isnt.function"
1816 "%s is not a function, it is %s.")
1817
1818 (js2-msg "msg.isnt.function.in"
1819 "Cannot call property %s in object %s. "
1820 "It is not a function, it is '%s'.")
1821
1822 (js2-msg "msg.function.not.found"
1823 "Cannot find function %s.")
1824
1825 (js2-msg "msg.function.not.found.in"
1826 "Cannot find function %s in object %s.")
1827
1828 (js2-msg "msg.isnt.xml.object"
1829 "%s is not an xml object.")
1830
1831 (js2-msg "msg.no.ref.to.get"
1832 "%s is not a reference to read reference value.")
1833
1834 (js2-msg "msg.no.ref.to.set"
1835 "%s is not a reference to set reference value to %s.")
1836
1837 (js2-msg "msg.no.ref.from.function"
1838 "Function %s can not be used as the left-hand "
1839 "side of assignment or as an operand of ++ or -- operator.")
1840
1841 (js2-msg "msg.bad.default.value"
1842 "Object's getDefaultValue() method returned an object.")
1843
1844 (js2-msg "msg.instanceof.not.object"
1845 "Can't use instanceof on a non-object.")
1846
1847 (js2-msg "msg.instanceof.bad.prototype"
1848 "'prototype' property of %s is not an object.")
1849
1850 (js2-msg "msg.bad.radix"
1851 "illegal radix %s.")
1852
1853 ;; ScriptableObject
1854 (js2-msg "msg.default.value"
1855 "Cannot find default value for object.")
1856
1857 (js2-msg "msg.zero.arg.ctor"
1858 "Cannot load class '%s' which has no zero-parameter constructor.")
1859
1860 (js2-msg "msg.ctor.multiple.parms"
1861 "Can't define constructor or class %s since more than "
1862 "one constructor has multiple parameters.")
1863
1864 (js2-msg "msg.extend.scriptable"
1865 "%s must extend ScriptableObject in order to define property %s.")
1866
1867 (js2-msg "msg.bad.getter.parms"
1868 "In order to define a property, getter %s must have zero "
1869 "parameters or a single ScriptableObject parameter.")
1870
1871 (js2-msg "msg.obj.getter.parms"
1872 "Expected static or delegated getter %s to take "
1873 "a ScriptableObject parameter.")
1874
1875 (js2-msg "msg.getter.static"
1876 "Getter and setter must both be static or neither be static.")
1877
1878 (js2-msg "msg.setter.return"
1879 "Setter must have void return type: %s")
1880
1881 (js2-msg "msg.setter2.parms"
1882 "Two-parameter setter must take a ScriptableObject as "
1883 "its first parameter.")
1884
1885 (js2-msg "msg.setter1.parms"
1886 "Expected single parameter setter for %s")
1887
1888 (js2-msg "msg.setter2.expected"
1889 "Expected static or delegated setter %s to take two parameters.")
1890
1891 (js2-msg "msg.setter.parms"
1892 "Expected either one or two parameters for setter.")
1893
1894 (js2-msg "msg.setter.bad.type"
1895 "Unsupported parameter type '%s' in setter '%s'.")
1896
1897 (js2-msg "msg.add.sealed"
1898 "Cannot add a property to a sealed object: %s.")
1899
1900 (js2-msg "msg.remove.sealed"
1901 "Cannot remove a property from a sealed object: %s.")
1902
1903 (js2-msg "msg.modify.sealed"
1904 "Cannot modify a property of a sealed object: %s.")
1905
1906 (js2-msg "msg.modify.readonly"
1907 "Cannot modify readonly property: %s.")
1908
1909 ;; TokenStream
1910 (js2-msg "msg.missing.exponent"
1911 "missing exponent")
1912
1913 (js2-msg "msg.caught.nfe"
1914 "number format error")
1915
1916 (js2-msg "msg.unterminated.string.lit"
1917 "unterminated string literal")
1918
1919 (js2-msg "msg.unterminated.comment"
1920 "unterminated comment")
1921
1922 (js2-msg "msg.unterminated.re.lit"
1923 "unterminated regular expression literal")
1924
1925 (js2-msg "msg.invalid.re.flag"
1926 "invalid flag after regular expression")
1927
1928 (js2-msg "msg.no.re.input.for"
1929 "no input for %s")
1930
1931 (js2-msg "msg.illegal.character"
1932 "illegal character")
1933
1934 (js2-msg "msg.invalid.escape"
1935 "invalid Unicode escape sequence")
1936
1937 (js2-msg "msg.bad.namespace"
1938 "not a valid default namespace statement. "
1939 "Syntax is: default xml namespace = EXPRESSION;")
1940
1941 ;; TokensStream warnings
1942 (js2-msg "msg.bad.octal.literal"
1943 "illegal octal literal digit %s; "
1944 "interpreting it as a decimal digit")
1945
1946 (js2-msg "msg.missing.hex.digits"
1947 "missing hexadecimal digits after '0x'")
1948
1949 (js2-msg "msg.missing.binary.digits"
1950 "missing binary digits after '0b'")
1951
1952 (js2-msg "msg.missing.octal.digits"
1953 "missing octal digits after '0o'")
1954
1955 (js2-msg "msg.script.is.not.constructor"
1956 "Script objects are not constructors.")
1957
1958 ;; Arrays
1959 (js2-msg "msg.arraylength.bad"
1960 "Inappropriate array length.")
1961
1962 ;; Arrays
1963 (js2-msg "msg.arraylength.too.big"
1964 "Array length %s exceeds supported capacity limit.")
1965
1966 ;; URI
1967 (js2-msg "msg.bad.uri"
1968 "Malformed URI sequence.")
1969
1970 ;; Number
1971 (js2-msg "msg.bad.precision"
1972 "Precision %s out of range.")
1973
1974 ;; NativeGenerator
1975 (js2-msg "msg.send.newborn"
1976 "Attempt to send value to newborn generator")
1977
1978 (js2-msg "msg.already.exec.gen"
1979 "Already executing generator")
1980
1981 (js2-msg "msg.StopIteration.invalid"
1982 "StopIteration may not be changed to an arbitrary object.")
1983
1984 ;; Interpreter
1985 (js2-msg "msg.yield.closing"
1986 "Yield from closing generator")
1987
1988 ;; Classes
1989 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1990 "class statement requires a name")
1991
1992 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1993 "unexpected ',' between class properties")
1994
1995 (js2-msg "msg.unexpected.static" ; added by js2-mode
1996 "unexpected 'static'")
1997
1998 (js2-msg "msg.missing.extends" ; added by js2-mode
1999 "name is required after extends")
2000
2001 (js2-msg "msg.no.brace.class" ; added by js2-mode
2002 "missing '{' before class body")
2003
2004 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2005 "missing ']' after computed property expression")
2006
2007 ;;; Tokens Buffer
2008
2009 (defconst js2-ti-max-lookahead 2)
2010 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2011
2012 (defun js2-new-token (offset)
2013 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2014 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2015 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2016 token))
2017
2018 (defsubst js2-current-token ()
2019 (aref js2-ti-tokens js2-ti-tokens-cursor))
2020
2021 (defsubst js2-current-token-string ()
2022 (js2-token-string (js2-current-token)))
2023
2024 (defsubst js2-current-token-type ()
2025 (js2-token-type (js2-current-token)))
2026
2027 (defsubst js2-current-token-beg ()
2028 (js2-token-beg (js2-current-token)))
2029
2030 (defsubst js2-current-token-end ()
2031 (js2-token-end (js2-current-token)))
2032
2033 (defun js2-current-token-len ()
2034 (let ((token (js2-current-token)))
2035 (- (js2-token-end token)
2036 (js2-token-beg token))))
2037
2038 (defun js2-ts-seek (state)
2039 (setq js2-ts-lineno (js2-ts-state-lineno state)
2040 js2-ts-cursor (js2-ts-state-cursor state)
2041 js2-ti-tokens (js2-ts-state-tokens state)
2042 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2043 js2-ti-lookahead (js2-ts-state-lookahead state)))
2044
2045 ;;; Utilities
2046
2047 (defun js2-delete-if (predicate list)
2048 "Remove all items satisfying PREDICATE in LIST."
2049 (cl-loop for item in list
2050 if (not (funcall predicate item))
2051 collect item))
2052
2053 (defun js2-position (element list)
2054 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2055 Returns nil if element is not found in the list."
2056 (let ((count 0)
2057 found)
2058 (while (and list (not found))
2059 (if (eq element (car list))
2060 (setq found t)
2061 (setq count (1+ count)
2062 list (cdr list))))
2063 (if found count)))
2064
2065 (defun js2-find-if (predicate list)
2066 "Find first item satisfying PREDICATE in LIST."
2067 (let (result)
2068 (while (and list (not result))
2069 (if (funcall predicate (car list))
2070 (setq result (car list)))
2071 (setq list (cdr list)))
2072 result))
2073
2074 (defmacro js2-time (form)
2075 "Evaluate FORM, discard result, and return elapsed time in sec."
2076 (declare (debug t))
2077 (let ((beg (make-symbol "--js2-time-beg--")))
2078 `(let ((,beg (current-time)))
2079 ,form
2080 (/ (truncate (* (- (float-time (current-time))
2081 (float-time ,beg))
2082 10000))
2083 10000.0))))
2084
2085 (defsubst js2-same-line (pos)
2086 "Return t if POS is on the same line as current point."
2087 (and (>= pos (point-at-bol))
2088 (<= pos (point-at-eol))))
2089
2090 (defun js2-code-bug ()
2091 "Signal an error when we encounter an unexpected code path."
2092 (error "failed assertion"))
2093
2094 (defsubst js2-record-text-property (beg end prop value)
2095 "Record a text property to set when parsing finishes."
2096 (push (list beg end prop value) js2-mode-deferred-properties))
2097
2098 ;; I'd like to associate errors with nodes, but for now the
2099 ;; easiest thing to do is get the context info from the last token.
2100 (defun js2-record-parse-error (msg &optional arg pos len)
2101 (push (list (list msg arg)
2102 (or pos (js2-current-token-beg))
2103 (or len (js2-current-token-len)))
2104 js2-parsed-errors))
2105
2106 (defun js2-report-error (msg &optional msg-arg pos len)
2107 "Signal a syntax error or record a parse error."
2108 (if js2-recover-from-parse-errors
2109 (js2-record-parse-error msg msg-arg pos len)
2110 (signal 'js2-syntax-error
2111 (list msg
2112 js2-ts-lineno
2113 (save-excursion
2114 (goto-char js2-ts-cursor)
2115 (current-column))
2116 js2-ts-hit-eof))))
2117
2118 (defun js2-report-warning (msg &optional msg-arg pos len face)
2119 (if js2-compiler-report-warning-as-error
2120 (js2-report-error msg msg-arg pos len)
2121 (push (list (list msg msg-arg)
2122 (or pos (js2-current-token-beg))
2123 (or len (js2-current-token-len))
2124 face)
2125 js2-parsed-warnings)))
2126
2127 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2128 (if js2-compiler-strict-mode
2129 (js2-report-warning msg-id msg-arg beg
2130 (and beg end (- end beg)))))
2131
2132 (put 'js2-syntax-error 'error-conditions
2133 '(error syntax-error js2-syntax-error))
2134 (put 'js2-syntax-error 'error-message "Syntax error")
2135
2136 (put 'js2-parse-error 'error-conditions
2137 '(error parse-error js2-parse-error))
2138 (put 'js2-parse-error 'error-message "Parse error")
2139
2140 (defmacro js2-clear-flag (flags flag)
2141 `(setq ,flags (logand ,flags (lognot ,flag))))
2142
2143 (defmacro js2-set-flag (flags flag)
2144 "Logical-or FLAG into FLAGS."
2145 `(setq ,flags (logior ,flags ,flag)))
2146
2147 (defsubst js2-flag-set-p (flags flag)
2148 (/= 0 (logand flags flag)))
2149
2150 (defsubst js2-flag-not-set-p (flags flag)
2151 (zerop (logand flags flag)))
2152
2153 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2154 "Evaluate BODY with the _ character set to be word-syntax."
2155 (declare (indent 0) (debug t))
2156 (let ((old-syntax (make-symbol "old-syntax")))
2157 `(let ((,old-syntax (string (char-syntax ?_))))
2158 (unwind-protect
2159 (progn
2160 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2161 ,@body)
2162 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2163
2164 ;;; AST struct and function definitions
2165
2166 ;; flags for ast node property 'member-type (used for e4x operators)
2167 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2168 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2169 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2170
2171 (defsubst js2-relpos (pos anchor)
2172 "Convert POS to be relative to ANCHOR.
2173 If POS is nil, returns nil."
2174 (and pos (- pos anchor)))
2175
2176 (defun js2-make-pad (indent)
2177 (if (zerop indent)
2178 ""
2179 (make-string (* indent js2-basic-offset) ? )))
2180
2181 (defun js2-visit-ast (node callback)
2182 "Visit every node in ast NODE with visitor CALLBACK.
2183
2184 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2185 called twice: once to visit the node, and again after all the node's
2186 children have been processed. The END-P argument is nil on the first
2187 call and non-nil on the second call. The return value of the callback
2188 affects the traversal: if non-nil, the children of NODE are processed.
2189 If the callback returns nil, or if the node has no children, then the
2190 callback is called immediately with a non-nil END-P argument.
2191
2192 The node traversal is approximately lexical-order, although there
2193 are currently no guarantees around this."
2194 (when node
2195 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2196 ;; visit the node
2197 (when (funcall callback node nil)
2198 ;; visit the kids
2199 (cond
2200 ((eq vfunc 'js2-visit-none)
2201 nil) ; don't even bother calling it
2202 ;; Each AST node type has to define a `js2-visitor' function
2203 ;; that takes a node and a callback, and calls `js2-visit-ast'
2204 ;; on each child of the node.
2205 (vfunc
2206 (funcall vfunc node callback))
2207 (t
2208 (error "%s does not define a visitor-traversal function"
2209 (aref node 0)))))
2210 ;; call the end-visit
2211 (funcall callback node t))))
2212
2213 (cl-defstruct (js2-node
2214 (:constructor nil)) ; abstract
2215 "Base AST node type."
2216 (type -1) ; token type
2217 (pos -1) ; start position of this AST node in parsed input
2218 (len 1) ; num characters spanned by the node
2219 props ; optional node property list (an alist)
2220 parent) ; link to parent node; null for root
2221
2222 (defsubst js2-node-get-prop (node prop &optional default)
2223 (or (cadr (assoc prop (js2-node-props node))) default))
2224
2225 (defsubst js2-node-set-prop (node prop value)
2226 (setf (js2-node-props node)
2227 (cons (list prop value) (js2-node-props node))))
2228
2229 (defun js2-fixup-starts (n nodes)
2230 "Adjust the start positions of NODES to be relative to N.
2231 Any node in the list may be nil, for convenience."
2232 (dolist (node nodes)
2233 (when node
2234 (setf (js2-node-pos node) (- (js2-node-pos node)
2235 (js2-node-pos n))))))
2236
2237 (defun js2-node-add-children (parent &rest nodes)
2238 "Set parent node of NODES to PARENT, and return PARENT.
2239 Does nothing if we're not recording parent links.
2240 If any given node in NODES is nil, doesn't record that link."
2241 (js2-fixup-starts parent nodes)
2242 (dolist (node nodes)
2243 (and node
2244 (setf (js2-node-parent node) parent))))
2245
2246 ;; Non-recursive since it's called a frightening number of times.
2247 (defun js2-node-abs-pos (n)
2248 (let ((pos (js2-node-pos n)))
2249 (while (setq n (js2-node-parent n))
2250 (setq pos (+ pos (js2-node-pos n))))
2251 pos))
2252
2253 (defsubst js2-node-abs-end (n)
2254 "Return absolute buffer position of end of N."
2255 (+ (js2-node-abs-pos n) (js2-node-len n)))
2256
2257 ;; It's important to make sure block nodes have a Lisp list for the
2258 ;; child nodes, to limit printing recursion depth in an AST that
2259 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2260 ;; a sufficiently large vector tree.
2261
2262 (cl-defstruct (js2-block-node
2263 (:include js2-node)
2264 (:constructor nil)
2265 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2266 (pos (js2-current-token-beg))
2267 len
2268 props
2269 kids)))
2270 "A block of statements."
2271 kids) ; a Lisp list of the child statement nodes
2272
2273 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2274 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2275
2276 (defun js2-visit-block (ast callback)
2277 "Visit the `js2-block-node' children of AST."
2278 (dolist (kid (js2-block-node-kids ast))
2279 (js2-visit-ast kid callback)))
2280
2281 (defun js2-print-block (n i)
2282 (let ((pad (js2-make-pad i)))
2283 (insert pad "{\n")
2284 (dolist (kid (js2-block-node-kids n))
2285 (js2-print-ast kid (1+ i)))
2286 (insert pad "}")))
2287
2288 (cl-defstruct (js2-scope
2289 (:include js2-block-node)
2290 (:constructor nil)
2291 (:constructor make-js2-scope (&key (type js2-BLOCK)
2292 (pos (js2-current-token-beg))
2293 len
2294 kids)))
2295 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2296 ;; I don't have one of those handy, so I'll use an alist for now.
2297 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2298 ;; and is much lighter-weight to construct (both CPU and mem).
2299 ;; The keys are interned strings (symbols) for faster lookup.
2300 ;; Should switch to hybrid alist/hashtable eventually.
2301 symbol-table ; an alist of (symbol . js2-symbol)
2302 parent-scope ; a `js2-scope'
2303 top) ; top-level `js2-scope' (script/function)
2304
2305 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2306 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2307
2308 (defun js2-node-get-enclosing-scope (node)
2309 "Return the innermost `js2-scope' node surrounding NODE.
2310 Returns nil if there is no enclosing scope node."
2311 (let ((parent (js2-node-parent node)))
2312 (while (not (js2-scope-p parent))
2313 (setq parent (js2-node-parent parent)))
2314 parent))
2315
2316 (defun js2-get-defining-scope (scope name)
2317 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2318 Returns `js2-scope' in which NAME is defined, or nil if not found."
2319 (let ((sym (if (symbolp name)
2320 name
2321 (intern name)))
2322 table
2323 result
2324 (continue t))
2325 (while (and scope continue)
2326 (if (or
2327 (and (setq table (js2-scope-symbol-table scope))
2328 (assq sym table))
2329 (and (eq sym 'arguments)
2330 (js2-function-node-p scope)))
2331 (setq continue nil
2332 result scope)
2333 (setq scope (js2-scope-parent-scope scope))))
2334 result))
2335
2336 (defun js2-scope-get-symbol (scope name)
2337 "Return symbol table entry for NAME in SCOPE.
2338 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2339 (and (js2-scope-symbol-table scope)
2340 (cdr (assq (if (symbolp name)
2341 name
2342 (intern name))
2343 (js2-scope-symbol-table scope)))))
2344
2345 (defun js2-scope-put-symbol (scope name symbol)
2346 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2347 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2348 (let* ((table (js2-scope-symbol-table scope))
2349 (sym (if (symbolp name) name (intern name)))
2350 (entry (assq sym table)))
2351 (if entry
2352 (setcdr entry symbol)
2353 (push (cons sym symbol)
2354 (js2-scope-symbol-table scope)))))
2355
2356 (cl-defstruct (js2-symbol
2357 (:constructor nil)
2358 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2359 "A symbol table entry."
2360 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2361 ;; js2-LET, or js2-CONST
2362 decl-type
2363 name ; string
2364 ast-node) ; a `js2-node'
2365
2366 (cl-defstruct (js2-error-node
2367 (:include js2-node)
2368 (:constructor nil) ; silence emacs21 byte-compiler
2369 (:constructor make-js2-error-node (&key (type js2-ERROR)
2370 (pos (js2-current-token-beg))
2371 len)))
2372 "AST node representing a parse error.")
2373
2374 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2375 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2376
2377 (cl-defstruct (js2-script-node
2378 (:include js2-scope)
2379 (:constructor nil)
2380 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2381 (pos (js2-current-token-beg))
2382 len
2383 ;; FIXME: What are those?
2384 var-decls
2385 fun-decls)))
2386 functions ; Lisp list of nested functions
2387 regexps ; Lisp list of (string . flags)
2388 symbols ; alist (every symbol gets unique index)
2389 (param-count 0)
2390 var-names ; vector of string names
2391 consts ; bool-vector matching var-decls
2392 (temp-number 0)) ; for generating temp variables
2393
2394 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2395 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2396
2397 (defun js2-print-script (node indent)
2398 (dolist (kid (js2-block-node-kids node))
2399 (js2-print-ast kid indent)))
2400
2401 (cl-defstruct (js2-ast-root
2402 (:include js2-script-node)
2403 (:constructor nil)
2404 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2405 (pos (js2-current-token-beg))
2406 len
2407 buffer)))
2408 "The root node of a js2 AST."
2409 buffer ; the source buffer from which the code was parsed
2410 comments ; a Lisp list of comments, ordered by start position
2411 errors ; a Lisp list of errors found during parsing
2412 warnings ; a Lisp list of warnings found during parsing
2413 node-count) ; number of nodes in the tree, including the root
2414
2415 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2416 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2417
2418 (defun js2-visit-ast-root (ast callback)
2419 (dolist (kid (js2-ast-root-kids ast))
2420 (js2-visit-ast kid callback))
2421 (dolist (comment (js2-ast-root-comments ast))
2422 (js2-visit-ast comment callback)))
2423
2424 (cl-defstruct (js2-comment-node
2425 (:include js2-node)
2426 (:constructor nil)
2427 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2428 (pos (js2-current-token-beg))
2429 len
2430 format)))
2431 format) ; 'line, 'block, 'jsdoc or 'html
2432
2433 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2434 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2435
2436 (defun js2-print-comment (n i)
2437 ;; We really ought to link end-of-line comments to their nodes.
2438 ;; Or maybe we could add a new comment type, 'endline.
2439 (insert (js2-make-pad i)
2440 (js2-node-string n)))
2441
2442 (cl-defstruct (js2-expr-stmt-node
2443 (:include js2-node)
2444 (:constructor nil)
2445 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2446 (pos js2-ts-cursor)
2447 len
2448 expr)))
2449 "An expression statement."
2450 expr)
2451
2452 (defsubst js2-expr-stmt-node-set-has-result (node)
2453 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2454 (setf (js2-node-type node) js2-EXPR_RESULT))
2455
2456 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2457 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2458
2459 (defun js2-visit-expr-stmt-node (n v)
2460 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2461
2462 (defun js2-print-expr-stmt-node (n indent)
2463 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2464 (insert ";\n"))
2465
2466 (cl-defstruct (js2-loop-node
2467 (:include js2-scope)
2468 (:constructor nil))
2469 "Abstract supertype of loop nodes."
2470 body ; a `js2-block-node'
2471 lp ; position of left-paren, nil if omitted
2472 rp) ; position of right-paren, nil if omitted
2473
2474 (cl-defstruct (js2-do-node
2475 (:include js2-loop-node)
2476 (:constructor nil)
2477 (:constructor make-js2-do-node (&key (type js2-DO)
2478 (pos (js2-current-token-beg))
2479 len
2480 body
2481 condition
2482 while-pos
2483 lp
2484 rp)))
2485 "AST node for do-loop."
2486 condition ; while (expression)
2487 while-pos) ; buffer position of 'while' keyword
2488
2489 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2490 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2491
2492 (defun js2-visit-do-node (n v)
2493 (js2-visit-ast (js2-do-node-body n) v)
2494 (js2-visit-ast (js2-do-node-condition n) v))
2495
2496 (defun js2-print-do-node (n i)
2497 (let ((pad (js2-make-pad i)))
2498 (insert pad "do {\n")
2499 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2500 (js2-print-ast kid (1+ i)))
2501 (insert pad "} while (")
2502 (js2-print-ast (js2-do-node-condition n) 0)
2503 (insert ");\n")))
2504
2505 (cl-defstruct (js2-export-node
2506 (:include js2-node)
2507 (:constructor nil)
2508 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2509 (pos) (js2-current-token-beg)
2510 len
2511 exports-list
2512 from-clause
2513 declaration
2514 default)))
2515 "AST node for an export statement. There are many things that can be exported,
2516 so many of its properties will be nil.
2517 "
2518 exports-list ; lisp list of js2-export-binding-node to export
2519 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2520 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2521 default) ; js2-function-node or js2-assign-node
2522
2523 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2524 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2525
2526 (defun js2-visit-export-node (n v)
2527 (let ((exports-list (js2-export-node-exports-list n))
2528 (from (js2-export-node-from-clause n))
2529 (declaration (js2-export-node-declaration n))
2530 (default (js2-export-node-default n)))
2531 (when exports-list
2532 (dolist (export exports-list)
2533 (js2-visit-ast export v)))
2534 (when from
2535 (js2-visit-ast from v))
2536 (when declaration
2537 (js2-visit-ast declaration v))
2538 (when default
2539 (js2-visit-ast default v))))
2540
2541 (defun js2-print-export-node (n i)
2542 (let ((pad (js2-make-pad i))
2543 (exports-list (js2-export-node-exports-list n))
2544 (from (js2-export-node-from-clause n))
2545 (declaration (js2-export-node-declaration n))
2546 (default (js2-export-node-default n)))
2547 (insert pad "export ")
2548 (cond
2549 (default
2550 (insert "default ")
2551 (js2-print-ast default i))
2552 (declaration
2553 (js2-print-ast declaration i))
2554 ((and exports-list from)
2555 (js2-print-named-imports exports-list)
2556 (insert " ")
2557 (js2-print-from-clause from))
2558 (from
2559 (insert "* ")
2560 (js2-print-from-clause from))
2561 (exports-list
2562 (js2-print-named-imports exports-list)))
2563 (insert ";\n")))
2564
2565 (cl-defstruct (js2-while-node
2566 (:include js2-loop-node)
2567 (:constructor nil)
2568 (:constructor make-js2-while-node (&key (type js2-WHILE)
2569 (pos (js2-current-token-beg))
2570 len body
2571 condition lp
2572 rp)))
2573 "AST node for while-loop."
2574 condition) ; while-condition
2575
2576 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2577 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2578
2579 (defun js2-visit-while-node (n v)
2580 (js2-visit-ast (js2-while-node-condition n) v)
2581 (js2-visit-ast (js2-while-node-body n) v))
2582
2583 (defun js2-print-while-node (n i)
2584 (let ((pad (js2-make-pad i)))
2585 (insert pad "while (")
2586 (js2-print-ast (js2-while-node-condition n) 0)
2587 (insert ") {\n")
2588 (js2-print-body (js2-while-node-body n) (1+ i))
2589 (insert pad "}\n")))
2590
2591 (cl-defstruct (js2-for-node
2592 (:include js2-loop-node)
2593 (:constructor nil)
2594 (:constructor make-js2-for-node (&key (type js2-FOR)
2595 (pos js2-ts-cursor)
2596 len body init
2597 condition
2598 update lp rp)))
2599 "AST node for a C-style for-loop."
2600 init ; initialization expression
2601 condition ; loop condition
2602 update) ; update clause
2603
2604 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2605 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2606
2607 (defun js2-visit-for-node (n v)
2608 (js2-visit-ast (js2-for-node-init n) v)
2609 (js2-visit-ast (js2-for-node-condition n) v)
2610 (js2-visit-ast (js2-for-node-update n) v)
2611 (js2-visit-ast (js2-for-node-body n) v))
2612
2613 (defun js2-print-for-node (n i)
2614 (let ((pad (js2-make-pad i)))
2615 (insert pad "for (")
2616 (js2-print-ast (js2-for-node-init n) 0)
2617 (insert "; ")
2618 (js2-print-ast (js2-for-node-condition n) 0)
2619 (insert "; ")
2620 (js2-print-ast (js2-for-node-update n) 0)
2621 (insert ") {\n")
2622 (js2-print-body (js2-for-node-body n) (1+ i))
2623 (insert pad "}\n")))
2624
2625 (cl-defstruct (js2-for-in-node
2626 (:include js2-loop-node)
2627 (:constructor nil)
2628 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2629 (pos js2-ts-cursor)
2630 len body
2631 iterator
2632 object
2633 in-pos
2634 each-pos
2635 foreach-p forof-p
2636 lp rp)))
2637 "AST node for a for..in loop."
2638 iterator ; [var] foo in ...
2639 object ; object over which we're iterating
2640 in-pos ; buffer position of 'in' keyword
2641 each-pos ; buffer position of 'each' keyword, if foreach-p
2642 foreach-p ; t if it's a for-each loop
2643 forof-p) ; t if it's a for-of loop
2644
2645 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2646 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2647
2648 (defun js2-visit-for-in-node (n v)
2649 (js2-visit-ast (js2-for-in-node-iterator n) v)
2650 (js2-visit-ast (js2-for-in-node-object n) v)
2651 (js2-visit-ast (js2-for-in-node-body n) v))
2652
2653 (defun js2-print-for-in-node (n i)
2654 (let ((pad (js2-make-pad i))
2655 (foreach (js2-for-in-node-foreach-p n))
2656 (forof (js2-for-in-node-forof-p n)))
2657 (insert pad "for ")
2658 (if foreach
2659 (insert "each "))
2660 (insert "(")
2661 (js2-print-ast (js2-for-in-node-iterator n) 0)
2662 (insert (if forof " of " " in "))
2663 (js2-print-ast (js2-for-in-node-object n) 0)
2664 (insert ") {\n")
2665 (js2-print-body (js2-for-in-node-body n) (1+ i))
2666 (insert pad "}\n")))
2667
2668 (cl-defstruct (js2-return-node
2669 (:include js2-node)
2670 (:constructor nil)
2671 (:constructor make-js2-return-node (&key (type js2-RETURN)
2672 (pos js2-ts-cursor)
2673 len
2674 retval)))
2675 "AST node for a return statement."
2676 retval) ; expression to return, or 'undefined
2677
2678 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2679 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2680
2681 (defun js2-visit-return-node (n v)
2682 (js2-visit-ast (js2-return-node-retval n) v))
2683
2684 (defun js2-print-return-node (n i)
2685 (insert (js2-make-pad i) "return")
2686 (when (js2-return-node-retval n)
2687 (insert " ")
2688 (js2-print-ast (js2-return-node-retval n) 0))
2689 (insert ";\n"))
2690
2691 (cl-defstruct (js2-if-node
2692 (:include js2-node)
2693 (:constructor nil)
2694 (:constructor make-js2-if-node (&key (type js2-IF)
2695 (pos js2-ts-cursor)
2696 len condition
2697 then-part
2698 else-pos
2699 else-part lp
2700 rp)))
2701 "AST node for an if-statement."
2702 condition ; expression
2703 then-part ; statement or block
2704 else-pos ; optional buffer position of 'else' keyword
2705 else-part ; optional statement or block
2706 lp ; position of left-paren, nil if omitted
2707 rp) ; position of right-paren, nil if omitted
2708
2709 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2710 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2711
2712 (defun js2-visit-if-node (n v)
2713 (js2-visit-ast (js2-if-node-condition n) v)
2714 (js2-visit-ast (js2-if-node-then-part n) v)
2715 (js2-visit-ast (js2-if-node-else-part n) v))
2716
2717 (defun js2-print-if-node (n i)
2718 (let ((pad (js2-make-pad i))
2719 (then-part (js2-if-node-then-part n))
2720 (else-part (js2-if-node-else-part n)))
2721 (insert pad "if (")
2722 (js2-print-ast (js2-if-node-condition n) 0)
2723 (insert ") {\n")
2724 (js2-print-body then-part (1+ i))
2725 (insert pad "}")
2726 (cond
2727 ((not else-part)
2728 (insert "\n"))
2729 ((js2-if-node-p else-part)
2730 (insert " else ")
2731 (js2-print-body else-part i))
2732 (t
2733 (insert " else {\n")
2734 (js2-print-body else-part (1+ i))
2735 (insert pad "}\n")))))
2736
2737 (cl-defstruct (js2-export-binding-node
2738 (:include js2-node)
2739 (:constructor nil)
2740 (:constructor make-js2-export-binding-node (&key (type -1)
2741 pos
2742 len
2743 local-name
2744 extern-name)))
2745 "AST node for an external symbol binding.
2746 It contains a local-name node which is the name of the value in the
2747 current scope, and extern-name which is the name of the value in the
2748 imported or exported scope. By default these are the same, but if the
2749 name is aliased as in {foo as bar}, it would have an extern-name node
2750 containing 'foo' and a local-name node containing 'bar'."
2751 local-name ; js2-name-node with the variable name in this scope
2752 extern-name) ; js2-name-node with the value name in the exporting module
2753
2754 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2755 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2756
2757 (defun js2-visit-extern-binding (n v)
2758 "Visit an extern binding node. First visit the local-name, and, if
2759 different, visit the extern-name."
2760 (let ((local-name (js2-export-binding-node-local-name n))
2761 (extern-name (js2-export-binding-node-extern-name n)))
2762 (when local-name
2763 (js2-visit-ast local-name v))
2764 (when (not (equal local-name extern-name))
2765 (js2-visit-ast extern-name v))))
2766
2767 (defun js2-print-extern-binding (n i)
2768 "Print a representation of a single extern binding. E.g. 'foo' or
2769 'foo as bar'."
2770 (let ((local-name (js2-export-binding-node-local-name n))
2771 (extern-name (js2-export-binding-node-extern-name n)))
2772 (insert (js2-name-node-name extern-name))
2773 (when (not (equal local-name extern-name))
2774 (insert " as ")
2775 (insert (js2-name-node-name local-name)))))
2776
2777
2778 (cl-defstruct (js2-import-node
2779 (:include js2-node)
2780 (:constructor nil)
2781 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2782 (pos (js2-current-token-beg))
2783 len
2784 import
2785 from
2786 module-id)))
2787 "AST node for an import statement. It follows the form
2788
2789 import ModuleSpecifier;
2790 import ImportClause FromClause;"
2791 import ; js2-import-clause-node specifying which names are to imported.
2792 from ; js2-from-clause-node indicating the module from which to import.
2793 module-id) ; module-id of the import. E.g. 'src/mylib'.
2794
2795 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2796 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2797
2798 (defun js2-visit-import (n v)
2799 (let ((import-clause (js2-import-node-import n))
2800 (from-clause (js2-import-node-from n)))
2801 (when import-clause
2802 (js2-visit-ast import-clause v))
2803 (when from-clause
2804 (js2-visit-ast from-clause v))))
2805
2806 (defun js2-print-import (n i)
2807 "Prints a representation of the import node"
2808 (let ((pad (js2-make-pad i))
2809 (import-clause (js2-import-node-import n))
2810 (from-clause (js2-import-node-from n))
2811 (module-id (js2-import-node-module-id n)))
2812 (insert pad "import ")
2813 (if import-clause
2814 (progn
2815 (js2-print-import-clause import-clause)
2816 (insert " ")
2817 (js2-print-from-clause from-clause))
2818 (insert "'")
2819 (insert module-id)
2820 (insert "'"))
2821 (insert ";\n")))
2822
2823 (cl-defstruct (js2-import-clause-node
2824 (:include js2-node)
2825 (:constructor nil)
2826 (:constructor make-js2-import-clause-node (&key (type -1)
2827 pos
2828 len
2829 namespace-import
2830 named-imports
2831 default-binding)))
2832 "AST node corresponding to the import clause of an import statement. This is
2833 the portion of the import that bindings names from the external context to the
2834 local context."
2835 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2836 named-imports ; lisp list of js2-export-binding-node for all named imports.
2837 default-binding) ; js2-export-binding-node for the default import binding
2838
2839 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2840 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2841
2842 (defun js2-visit-import-clause (n v)
2843 (let ((ns-import (js2-import-clause-node-namespace-import n))
2844 (named-imports (js2-import-clause-node-named-imports n))
2845 (default (js2-import-clause-node-default-binding n)))
2846 (when ns-import
2847 (js2-visit-ast ns-import v))
2848 (when named-imports
2849 (dolist (import named-imports)
2850 (js2-visit-ast import v)))
2851 (when default
2852 (js2-visit-ast default v))))
2853
2854 (defun js2-print-import-clause (n)
2855 (let ((ns-import (js2-import-clause-node-namespace-import n))
2856 (named-imports (js2-import-clause-node-named-imports n))
2857 (default (js2-import-clause-node-default-binding n)))
2858 (cond
2859 ((and default ns-import)
2860 (js2-print-ast default)
2861 (insert ", ")
2862 (js2-print-namespace-import ns-import))
2863 ((and default named-imports)
2864 (js2-print-ast default)
2865 (insert ", ")
2866 (js2-print-named-imports named-imports))
2867 (default
2868 (js2-print-ast default))
2869 (ns-import
2870 (js2-print-namespace-import ns-import))
2871 (named-imports
2872 (js2-print-named-imports named-imports)))))
2873
2874 (defun js2-print-namespace-import (node)
2875 (insert "* as ")
2876 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2877
2878 (defun js2-print-named-imports (imports)
2879 (insert "{")
2880 (let ((len (length imports))
2881 (n 0))
2882 (while (< n len)
2883 (js2-print-extern-binding (nth n imports) 0)
2884 (unless (= n (- len 1))
2885 (insert ", "))
2886 (setq n (+ n 1))))
2887 (insert "}"))
2888
2889 (cl-defstruct (js2-namespace-import-node
2890 (:include js2-node)
2891 (:constructor nil)
2892 (:constructor make-js2-namespace-import-node (&key (type -1)
2893 pos
2894 len
2895 name)))
2896 "AST node for a complete namespace import.
2897 E.g. the '* as lib' expression in:
2898
2899 import * as lib from 'src/lib'
2900
2901 It contains a single name node referring to the bound name."
2902 name) ; js2-name-node of the bound name.
2903
2904 (defun js2-visit-namespace-import (n v)
2905 (js2-visit-ast (js2-namespace-import-node-name n) v))
2906
2907 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2908 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2909
2910 (cl-defstruct (js2-from-clause-node
2911 (:include js2-node)
2912 (:constructor nil)
2913 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2914 pos
2915 len
2916 module-id
2917 metadata-p)))
2918 "AST node for the from clause in an import or export statement.
2919 E.g. from 'my/module'. It can refere to either an external module, or to the
2920 modules metadata itself."
2921 module-id ; string containing the module specifier.
2922 metadata-p) ; true if this clause refers to the module's metadata
2923
2924 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2925 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2926
2927 (defun js2-print-from-clause (n)
2928 (insert "from ")
2929 (if (js2-from-clause-node-metadata-p n)
2930 (insert "this module")
2931 (insert "'")
2932 (insert (js2-from-clause-node-module-id n))
2933 (insert "'")))
2934
2935 (cl-defstruct (js2-try-node
2936 (:include js2-node)
2937 (:constructor nil)
2938 (:constructor make-js2-try-node (&key (type js2-TRY)
2939 (pos js2-ts-cursor)
2940 len
2941 try-block
2942 catch-clauses
2943 finally-block)))
2944 "AST node for a try-statement."
2945 try-block
2946 catch-clauses ; a Lisp list of `js2-catch-node'
2947 finally-block) ; a `js2-finally-node'
2948
2949 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2950 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2951
2952 (defun js2-visit-try-node (n v)
2953 (js2-visit-ast (js2-try-node-try-block n) v)
2954 (dolist (clause (js2-try-node-catch-clauses n))
2955 (js2-visit-ast clause v))
2956 (js2-visit-ast (js2-try-node-finally-block n) v))
2957
2958 (defun js2-print-try-node (n i)
2959 (let ((pad (js2-make-pad i))
2960 (catches (js2-try-node-catch-clauses n))
2961 (finally (js2-try-node-finally-block n)))
2962 (insert pad "try {\n")
2963 (js2-print-body (js2-try-node-try-block n) (1+ i))
2964 (insert pad "}")
2965 (when catches
2966 (dolist (catch catches)
2967 (js2-print-ast catch i)))
2968 (if finally
2969 (js2-print-ast finally i)
2970 (insert "\n"))))
2971
2972 (cl-defstruct (js2-catch-node
2973 (:include js2-scope)
2974 (:constructor nil)
2975 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2976 (pos js2-ts-cursor)
2977 len
2978 param
2979 guard-kwd
2980 guard-expr
2981 lp rp)))
2982 "AST node for a catch clause."
2983 param ; destructuring form or simple name node
2984 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2985 guard-expr ; catch condition, a `js2-node'
2986 lp ; buffer position of left-paren, nil if omitted
2987 rp) ; buffer position of right-paren, nil if omitted
2988
2989 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2990 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2991
2992 (defun js2-visit-catch-node (n v)
2993 (js2-visit-ast (js2-catch-node-param n) v)
2994 (when (js2-catch-node-guard-kwd n)
2995 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2996 (js2-visit-block n v))
2997
2998 (defun js2-print-catch-node (n i)
2999 (let ((pad (js2-make-pad i))
3000 (guard-kwd (js2-catch-node-guard-kwd n))
3001 (guard-expr (js2-catch-node-guard-expr n)))
3002 (insert " catch (")
3003 (js2-print-ast (js2-catch-node-param n) 0)
3004 (when guard-kwd
3005 (insert " if ")
3006 (js2-print-ast guard-expr 0))
3007 (insert ") {\n")
3008 (js2-print-body n (1+ i))
3009 (insert pad "}")))
3010
3011 (cl-defstruct (js2-finally-node
3012 (:include js2-node)
3013 (:constructor nil)
3014 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3015 (pos js2-ts-cursor)
3016 len body)))
3017 "AST node for a finally clause."
3018 body) ; a `js2-node', often but not always a block node
3019
3020 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3021 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3022
3023 (defun js2-visit-finally-node (n v)
3024 (js2-visit-ast (js2-finally-node-body n) v))
3025
3026 (defun js2-print-finally-node (n i)
3027 (let ((pad (js2-make-pad i)))
3028 (insert " finally {\n")
3029 (js2-print-body (js2-finally-node-body n) (1+ i))
3030 (insert pad "}\n")))
3031
3032 (cl-defstruct (js2-switch-node
3033 (:include js2-node)
3034 (:constructor nil)
3035 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3036 (pos js2-ts-cursor)
3037 len
3038 discriminant
3039 cases lp
3040 rp)))
3041 "AST node for a switch statement."
3042 discriminant ; a `js2-node' (switch expression)
3043 cases ; a Lisp list of `js2-case-node'
3044 lp ; position of open-paren for discriminant, nil if omitted
3045 rp) ; position of close-paren for discriminant, nil if omitted
3046
3047 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3048 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3049
3050 (defun js2-visit-switch-node (n v)
3051 (js2-visit-ast (js2-switch-node-discriminant n) v)
3052 (dolist (c (js2-switch-node-cases n))
3053 (js2-visit-ast c v)))
3054
3055 (defun js2-print-switch-node (n i)
3056 (let ((pad (js2-make-pad i))
3057 (cases (js2-switch-node-cases n)))
3058 (insert pad "switch (")
3059 (js2-print-ast (js2-switch-node-discriminant n) 0)
3060 (insert ") {\n")
3061 (dolist (case cases)
3062 (js2-print-ast case i))
3063 (insert pad "}\n")))
3064
3065 (cl-defstruct (js2-case-node
3066 (:include js2-block-node)
3067 (:constructor nil)
3068 (:constructor make-js2-case-node (&key (type js2-CASE)
3069 (pos js2-ts-cursor)
3070 len kids expr)))
3071 "AST node for a case clause of a switch statement."
3072 expr) ; the case expression (nil for default)
3073
3074 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3075 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3076
3077 (defun js2-visit-case-node (n v)
3078 (js2-visit-ast (js2-case-node-expr n) v)
3079 (js2-visit-block n v))
3080
3081 (defun js2-print-case-node (n i)
3082 (let ((pad (js2-make-pad i))
3083 (expr (js2-case-node-expr n)))
3084 (insert pad)
3085 (if (null expr)
3086 (insert "default:\n")
3087 (insert "case ")
3088 (js2-print-ast expr 0)
3089 (insert ":\n"))
3090 (dolist (kid (js2-case-node-kids n))
3091 (js2-print-ast kid (1+ i)))))
3092
3093 (cl-defstruct (js2-throw-node
3094 (:include js2-node)
3095 (:constructor nil)
3096 (:constructor make-js2-throw-node (&key (type js2-THROW)
3097 (pos js2-ts-cursor)
3098 len expr)))
3099 "AST node for a throw statement."
3100 expr) ; the expression to throw
3101
3102 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3103 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3104
3105 (defun js2-visit-throw-node (n v)
3106 (js2-visit-ast (js2-throw-node-expr n) v))
3107
3108 (defun js2-print-throw-node (n i)
3109 (insert (js2-make-pad i) "throw ")
3110 (js2-print-ast (js2-throw-node-expr n) 0)
3111 (insert ";\n"))
3112
3113 (cl-defstruct (js2-with-node
3114 (:include js2-node)
3115 (:constructor nil)
3116 (:constructor make-js2-with-node (&key (type js2-WITH)
3117 (pos js2-ts-cursor)
3118 len object
3119 body lp rp)))
3120 "AST node for a with-statement."
3121 object
3122 body
3123 lp ; buffer position of left-paren around object, nil if omitted
3124 rp) ; buffer position of right-paren around object, nil if omitted
3125
3126 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3127 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3128
3129 (defun js2-visit-with-node (n v)
3130 (js2-visit-ast (js2-with-node-object n) v)
3131 (js2-visit-ast (js2-with-node-body n) v))
3132
3133 (defun js2-print-with-node (n i)
3134 (let ((pad (js2-make-pad i)))
3135 (insert pad "with (")
3136 (js2-print-ast (js2-with-node-object n) 0)
3137 (insert ") {\n")
3138 (js2-print-body (js2-with-node-body n) (1+ i))
3139 (insert pad "}\n")))
3140
3141 (cl-defstruct (js2-label-node
3142 (:include js2-node)
3143 (:constructor nil)
3144 (:constructor make-js2-label-node (&key (type js2-LABEL)
3145 (pos js2-ts-cursor)
3146 len name)))
3147 "AST node for a statement label or case label."
3148 name ; a string
3149 loop) ; for validating and code-generating continue-to-label
3150
3151 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3152 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3153
3154 (defun js2-print-label (n i)
3155 (insert (js2-make-pad i)
3156 (js2-label-node-name n)
3157 ":\n"))
3158
3159 (cl-defstruct (js2-labeled-stmt-node
3160 (:include js2-node)
3161 (:constructor nil)
3162 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3163 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3164 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3165 (pos js2-ts-cursor)
3166 len labels stmt)))
3167 "AST node for a statement with one or more labels.
3168 Multiple labels for a statement are collapsed into the labels field."
3169 labels ; Lisp list of `js2-label-node'
3170 stmt) ; the statement these labels are for
3171
3172 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3173 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3174
3175 (defun js2-get-label-by-name (lbl-stmt name)
3176 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3177 Returns nil if no such label is in the list."
3178 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3179 result)
3180 (while (and label-list (not result))
3181 (if (string= (js2-label-node-name (car label-list)) name)
3182 (setq result (car label-list))
3183 (setq label-list (cdr label-list))))
3184 result))
3185
3186 (defun js2-visit-labeled-stmt (n v)
3187 (dolist (label (js2-labeled-stmt-node-labels n))
3188 (js2-visit-ast label v))
3189 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3190
3191 (defun js2-print-labeled-stmt (n i)
3192 (dolist (label (js2-labeled-stmt-node-labels n))
3193 (js2-print-ast label i))
3194 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3195
3196 (defun js2-labeled-stmt-node-contains (node label)
3197 "Return t if NODE contains LABEL in its label set.
3198 NODE is a `js2-labels-node'. LABEL is an identifier."
3199 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3200 if (string= label (js2-label-node-name nl))
3201 return t
3202 finally return nil))
3203
3204 (defsubst js2-labeled-stmt-node-add-label (node label)
3205 "Add a `js2-label-node' to the label set for this statement."
3206 (setf (js2-labeled-stmt-node-labels node)
3207 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3208
3209 (cl-defstruct (js2-jump-node
3210 (:include js2-node)
3211 (:constructor nil))
3212 "Abstract supertype of break and continue nodes."
3213 label ; `js2-name-node' for location of label identifier, if present
3214 target) ; target js2-labels-node or loop/switch statement
3215
3216 (defun js2-visit-jump-node (n v)
3217 ;; We don't visit the target, since it's a back-link.
3218 (js2-visit-ast (js2-jump-node-label n) v))
3219
3220 (cl-defstruct (js2-break-node
3221 (:include js2-jump-node)
3222 (:constructor nil)
3223 (:constructor make-js2-break-node (&key (type js2-BREAK)
3224 (pos js2-ts-cursor)
3225 len label target)))
3226 "AST node for a break statement.
3227 The label field is a `js2-name-node', possibly nil, for the named label
3228 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3229 is the target of the break - a label node or enclosing loop/switch statement.")
3230
3231 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3232 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3233
3234 (defun js2-print-break-node (n i)
3235 (insert (js2-make-pad i) "break")
3236 (when (js2-break-node-label n)
3237 (insert " ")
3238 (js2-print-ast (js2-break-node-label n) 0))
3239 (insert ";\n"))
3240
3241 (cl-defstruct (js2-continue-node
3242 (:include js2-jump-node)
3243 (:constructor nil)
3244 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3245 (pos js2-ts-cursor)
3246 len label target)))
3247 "AST node for a continue statement.
3248 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3249 It is nil if continue specifies no label. The target field is the jump target:
3250 a `js2-label-node' or the innermost enclosing loop.")
3251
3252 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3253 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3254
3255 (defun js2-print-continue-node (n i)
3256 (insert (js2-make-pad i) "continue")
3257 (when (js2-continue-node-label n)
3258 (insert " ")
3259 (js2-print-ast (js2-continue-node-label n) 0))
3260 (insert ";\n"))
3261
3262 (cl-defstruct (js2-function-node
3263 (:include js2-script-node)
3264 (:constructor nil)
3265 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3266 (pos js2-ts-cursor)
3267 len
3268 (ftype 'FUNCTION)
3269 (form 'FUNCTION_STATEMENT)
3270 (name "")
3271 params rest-p
3272 body
3273 generator-type
3274 lp rp)))
3275 "AST node for a function declaration.
3276 The `params' field is a Lisp list of nodes. Each node is either a simple
3277 `js2-name-node', or if it's a destructuring-assignment parameter, a
3278 `js2-array-node' or `js2-object-node'."
3279 ftype ; FUNCTION, GETTER or SETTER
3280 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3281 name ; function name (a `js2-name-node', or nil if anonymous)
3282 params ; a Lisp list of destructuring forms or simple name nodes
3283 rest-p ; if t, the last parameter is rest parameter
3284 body ; a `js2-block-node' or expression node (1.8 only)
3285 lp ; position of arg-list open-paren, or nil if omitted
3286 rp ; position of arg-list close-paren, or nil if omitted
3287 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3288 needs-activation ; t if we need an activation object for this frame
3289 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3290 member-expr) ; nonstandard Ecma extension from Rhino
3291
3292 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3293 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3294
3295 (defun js2-visit-function-node (n v)
3296 (js2-visit-ast (js2-function-node-name n) v)
3297 (dolist (p (js2-function-node-params n))
3298 (js2-visit-ast p v))
3299 (js2-visit-ast (js2-function-node-body n) v))
3300
3301 (defun js2-print-function-node (n i)
3302 (let* ((pad (js2-make-pad i))
3303 (getter (js2-node-get-prop n 'GETTER_SETTER))
3304 (name (or (js2-function-node-name n)
3305 (js2-function-node-member-expr n)))
3306 (params (js2-function-node-params n))
3307 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3308 (rest-p (js2-function-node-rest-p n))
3309 (body (js2-function-node-body n))
3310 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3311 (unless (or getter arrow)
3312 (insert pad "function")
3313 (when (eq (js2-function-node-generator-type n) 'STAR)
3314 (insert "*")))
3315 (when name
3316 (insert " ")
3317 (js2-print-ast name 0))
3318 (insert "(")
3319 (cl-loop with len = (length params)
3320 for param in params
3321 for count from 1
3322 do
3323 (when (and rest-p (= count len))
3324 (insert "..."))
3325 (js2-print-ast param 0)
3326 (when (< count len)
3327 (insert ", ")))
3328 (insert ") ")
3329 (when arrow
3330 (insert "=> "))
3331 (insert "{")
3332 ;; TODO: fix this to be smarter about indenting, etc.
3333 (unless expr
3334 (insert "\n"))
3335 (if (js2-block-node-p body)
3336 (js2-print-body body (1+ i))
3337 (js2-print-ast body 0))
3338 (insert pad "}")
3339 (unless expr
3340 (insert "\n"))))
3341
3342 (defun js2-function-name (node)
3343 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3344 (and (js2-function-node-name node)
3345 (js2-name-node-name (js2-function-node-name node))))
3346
3347 ;; Having this be an expression node makes it more flexible.
3348 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3349 ;; that work better if you assume it's an expression. Whenever we have
3350 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3351 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3352 (cl-defstruct (js2-var-decl-node
3353 (:include js2-node)
3354 (:constructor nil)
3355 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3356 (pos (js2-current-token-beg))
3357 len kids
3358 decl-type)))
3359 "AST node for a variable declaration list (VAR, CONST or LET).
3360 The node bounds differ depending on the declaration type. For VAR or
3361 CONST declarations, the bounds include the var/const keyword. For LET
3362 declarations, the node begins at the position of the first child."
3363 kids ; a Lisp list of `js2-var-init-node' structs.
3364 decl-type) ; js2-VAR, js2-CONST or js2-LET
3365
3366 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3367 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3368
3369 (defun js2-visit-var-decl (n v)
3370 (dolist (kid (js2-var-decl-node-kids n))
3371 (js2-visit-ast kid v)))
3372
3373 (defun js2-print-var-decl (n i)
3374 (let ((pad (js2-make-pad i))
3375 (tt (js2-var-decl-node-decl-type n)))
3376 (insert pad)
3377 (insert (cond
3378 ((= tt js2-VAR) "var ")
3379 ((= tt js2-LET) "let ")
3380 ((= tt js2-CONST) "const ")
3381 (t
3382 (error "malformed var-decl node"))))
3383 (cl-loop with kids = (js2-var-decl-node-kids n)
3384 with len = (length kids)
3385 for kid in kids
3386 for count from 1
3387 do
3388 (js2-print-ast kid 0)
3389 (if (< count len)
3390 (insert ", ")))))
3391
3392 (cl-defstruct (js2-var-init-node
3393 (:include js2-node)
3394 (:constructor nil)
3395 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3396 (pos js2-ts-cursor)
3397 len target
3398 initializer)))
3399 "AST node for a variable declaration.
3400 The type field will be js2-CONST for a const decl."
3401 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3402 initializer) ; initializer expression, a `js2-node'
3403
3404 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3405 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3406
3407 (defun js2-visit-var-init-node (n v)
3408 (js2-visit-ast (js2-var-init-node-target n) v)
3409 (js2-visit-ast (js2-var-init-node-initializer n) v))
3410
3411 (defun js2-print-var-init-node (n i)
3412 (let ((pad (js2-make-pad i))
3413 (name (js2-var-init-node-target n))
3414 (init (js2-var-init-node-initializer n)))
3415 (insert pad)
3416 (js2-print-ast name 0)
3417 (when init
3418 (insert " = ")
3419 (js2-print-ast init 0))))
3420
3421 (cl-defstruct (js2-cond-node
3422 (:include js2-node)
3423 (:constructor nil)
3424 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3425 (pos js2-ts-cursor)
3426 len
3427 test-expr
3428 true-expr
3429 false-expr
3430 q-pos c-pos)))
3431 "AST node for the ternary operator"
3432 test-expr
3433 true-expr
3434 false-expr
3435 q-pos ; buffer position of ?
3436 c-pos) ; buffer position of :
3437
3438 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3439 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3440
3441 (defun js2-visit-cond-node (n v)
3442 (js2-visit-ast (js2-cond-node-test-expr n) v)
3443 (js2-visit-ast (js2-cond-node-true-expr n) v)
3444 (js2-visit-ast (js2-cond-node-false-expr n) v))
3445
3446 (defun js2-print-cond-node (n i)
3447 (let ((pad (js2-make-pad i)))
3448 (insert pad)
3449 (js2-print-ast (js2-cond-node-test-expr n) 0)
3450 (insert " ? ")
3451 (js2-print-ast (js2-cond-node-true-expr n) 0)
3452 (insert " : ")
3453 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3454
3455 (cl-defstruct (js2-infix-node
3456 (:include js2-node)
3457 (:constructor nil)
3458 (:constructor make-js2-infix-node (&key type
3459 (pos js2-ts-cursor)
3460 len op-pos
3461 left right)))
3462 "Represents infix expressions.
3463 Includes assignment ops like `|=', and the comma operator.
3464 The type field inherited from `js2-node' holds the operator."
3465 op-pos ; buffer position where operator begins
3466 left ; any `js2-node'
3467 right) ; any `js2-node'
3468
3469 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3470 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3471
3472 (defun js2-visit-infix-node (n v)
3473 (js2-visit-ast (js2-infix-node-left n) v)
3474 (js2-visit-ast (js2-infix-node-right n) v))
3475
3476 (defconst js2-operator-tokens
3477 (let ((table (make-hash-table :test 'eq))
3478 (tokens
3479 (list (cons js2-IN "in")
3480 (cons js2-TYPEOF "typeof")
3481 (cons js2-INSTANCEOF "instanceof")
3482 (cons js2-DELPROP "delete")
3483 (cons js2-COMMA ",")
3484 (cons js2-COLON ":")
3485 (cons js2-OR "||")
3486 (cons js2-AND "&&")
3487 (cons js2-INC "++")
3488 (cons js2-DEC "--")
3489 (cons js2-BITOR "|")
3490 (cons js2-BITXOR "^")
3491 (cons js2-BITAND "&")
3492 (cons js2-EQ "==")
3493 (cons js2-NE "!=")
3494 (cons js2-LT "<")
3495 (cons js2-LE "<=")
3496 (cons js2-GT ">")
3497 (cons js2-GE ">=")
3498 (cons js2-LSH "<<")
3499 (cons js2-RSH ">>")
3500 (cons js2-URSH ">>>")
3501 (cons js2-ADD "+") ; infix plus
3502 (cons js2-SUB "-") ; infix minus
3503 (cons js2-MUL "*")
3504 (cons js2-DIV "/")
3505 (cons js2-MOD "%")
3506 (cons js2-NOT "!")
3507 (cons js2-BITNOT "~")
3508 (cons js2-POS "+") ; unary plus
3509 (cons js2-NEG "-") ; unary minus
3510 (cons js2-TRIPLEDOT "...")
3511 (cons js2-SHEQ "===") ; shallow equality
3512 (cons js2-SHNE "!==") ; shallow inequality
3513 (cons js2-ASSIGN "=")
3514 (cons js2-ASSIGN_BITOR "|=")
3515 (cons js2-ASSIGN_BITXOR "^=")
3516 (cons js2-ASSIGN_BITAND "&=")
3517 (cons js2-ASSIGN_LSH "<<=")
3518 (cons js2-ASSIGN_RSH ">>=")
3519 (cons js2-ASSIGN_URSH ">>>=")
3520 (cons js2-ASSIGN_ADD "+=")
3521 (cons js2-ASSIGN_SUB "-=")
3522 (cons js2-ASSIGN_MUL "*=")
3523 (cons js2-ASSIGN_DIV "/=")
3524 (cons js2-ASSIGN_MOD "%="))))
3525 (cl-loop for (k . v) in tokens do
3526 (puthash k v table))
3527 table))
3528
3529 (defun js2-print-infix-node (n i)
3530 (let* ((tt (js2-node-type n))
3531 (op (gethash tt js2-operator-tokens)))
3532 (unless op
3533 (error "unrecognized infix operator %s" (js2-node-type n)))
3534 (insert (js2-make-pad i))
3535 (js2-print-ast (js2-infix-node-left n) 0)
3536 (unless (= tt js2-COMMA)
3537 (insert " "))
3538 (insert op)
3539 (insert " ")
3540 (js2-print-ast (js2-infix-node-right n) 0)))
3541
3542 (cl-defstruct (js2-assign-node
3543 (:include js2-infix-node)
3544 (:constructor nil)
3545 (:constructor make-js2-assign-node (&key type
3546 (pos js2-ts-cursor)
3547 len op-pos
3548 left right)))
3549 "Represents any assignment.
3550 The type field holds the actual assignment operator.")
3551
3552 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3553 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3554
3555 (cl-defstruct (js2-unary-node
3556 (:include js2-node)
3557 (:constructor nil)
3558 (:constructor make-js2-unary-node (&key type ; required
3559 (pos js2-ts-cursor)
3560 len operand)))
3561 "AST node type for unary operator nodes.
3562 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3563 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3564 property is added if the operator follows the operand."
3565 operand) ; a `js2-node' expression
3566
3567 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3568 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3569
3570 (defun js2-visit-unary-node (n v)
3571 (js2-visit-ast (js2-unary-node-operand n) v))
3572
3573 (defun js2-print-unary-node (n i)
3574 (let* ((tt (js2-node-type n))
3575 (op (gethash tt js2-operator-tokens))
3576 (postfix (js2-node-get-prop n 'postfix)))
3577 (unless op
3578 (error "unrecognized unary operator %s" tt))
3579 (insert (js2-make-pad i))
3580 (unless postfix
3581 (insert op))
3582 (if (or (= tt js2-TYPEOF)
3583 (= tt js2-DELPROP))
3584 (insert " "))
3585 (js2-print-ast (js2-unary-node-operand n) 0)
3586 (when postfix
3587 (insert op))))
3588
3589 (cl-defstruct (js2-let-node
3590 (:include js2-scope)
3591 (:constructor nil)
3592 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3593 (pos (js2-current-token-beg))
3594 len vars body
3595 lp rp)))
3596 "AST node for a let expression or a let statement.
3597 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3598 vars ; a `js2-var-decl-node'
3599 body ; a `js2-node' representing the expression or body block
3600 lp
3601 rp)
3602
3603 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3604 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3605
3606 (defun js2-visit-let-node (n v)
3607 (js2-visit-ast (js2-let-node-vars n) v)
3608 (js2-visit-ast (js2-let-node-body n) v))
3609
3610 (defun js2-print-let-node (n i)
3611 (insert (js2-make-pad i) "let (")
3612 (let ((p (point)))
3613 (js2-print-ast (js2-let-node-vars n) 0)
3614 (delete-region p (+ p 4)))
3615 (insert ") ")
3616 (js2-print-ast (js2-let-node-body n) i))
3617
3618 (cl-defstruct (js2-keyword-node
3619 (:include js2-node)
3620 (:constructor nil)
3621 (:constructor make-js2-keyword-node (&key type
3622 (pos (js2-current-token-beg))
3623 (len (- js2-ts-cursor pos)))))
3624 "AST node representing a literal keyword such as `null'.
3625 Used for `null', `this', `true', `false' and `debugger'.
3626 The node type is set to js2-NULL, js2-THIS, etc.")
3627
3628 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3629 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3630
3631 (defun js2-print-keyword-node (n i)
3632 (insert (js2-make-pad i)
3633 (let ((tt (js2-node-type n)))
3634 (cond
3635 ((= tt js2-THIS) "this")
3636 ((= tt js2-SUPER) "super")
3637 ((= tt js2-NULL) "null")
3638 ((= tt js2-TRUE) "true")
3639 ((= tt js2-FALSE) "false")
3640 ((= tt js2-DEBUGGER) "debugger")
3641 (t (error "Invalid keyword literal type: %d" tt))))))
3642
3643 (defsubst js2-this-or-super-node-p (node)
3644 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3645 (let ((type (js2-node-type node)))
3646 (or (eq type js2-THIS) (eq type js2-SUPER))))
3647
3648 (cl-defstruct (js2-new-node
3649 (:include js2-node)
3650 (:constructor nil)
3651 (:constructor make-js2-new-node (&key (type js2-NEW)
3652 (pos (js2-current-token-beg))
3653 len target
3654 args initializer
3655 lp rp)))
3656 "AST node for new-expression such as new Foo()."
3657 target ; an identifier or reference
3658 args ; a Lisp list of argument nodes
3659 lp ; position of left-paren, nil if omitted
3660 rp ; position of right-paren, nil if omitted
3661 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3662
3663 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3664 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3665
3666 (defun js2-visit-new-node (n v)
3667 (js2-visit-ast (js2-new-node-target n) v)
3668 (dolist (arg (js2-new-node-args n))
3669 (js2-visit-ast arg v))
3670 (js2-visit-ast (js2-new-node-initializer n) v))
3671
3672 (defun js2-print-new-node (n i)
3673 (insert (js2-make-pad i) "new ")
3674 (js2-print-ast (js2-new-node-target n))
3675 (insert "(")
3676 (js2-print-list (js2-new-node-args n))
3677 (insert ")")
3678 (when (js2-new-node-initializer n)
3679 (insert " ")
3680 (js2-print-ast (js2-new-node-initializer n))))
3681
3682 (cl-defstruct (js2-name-node
3683 (:include js2-node)
3684 (:constructor nil)
3685 (:constructor make-js2-name-node (&key (type js2-NAME)
3686 (pos (js2-current-token-beg))
3687 (len (- js2-ts-cursor
3688 (js2-current-token-beg)))
3689 (name (js2-current-token-string)))))
3690 "AST node for a JavaScript identifier"
3691 name ; a string
3692 scope) ; a `js2-scope' (optional, used for codegen)
3693
3694 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3695 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3696
3697 (defun js2-print-name-node (n i)
3698 (insert (js2-make-pad i)
3699 (js2-name-node-name n)))
3700
3701 (defsubst js2-name-node-length (node)
3702 "Return identifier length of NODE, a `js2-name-node'.
3703 Returns 0 if NODE is nil or its identifier field is nil."
3704 (if node
3705 (length (js2-name-node-name node))
3706 0))
3707
3708 (cl-defstruct (js2-number-node
3709 (:include js2-node)
3710 (:constructor nil)
3711 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3712 (pos (js2-current-token-beg))
3713 (len (- js2-ts-cursor
3714 (js2-current-token-beg)))
3715 (value (js2-current-token-string))
3716 (num-value (js2-token-number
3717 (js2-current-token))))))
3718 "AST node for a number literal."
3719 value ; the original string, e.g. "6.02e23"
3720 num-value) ; the parsed number value
3721
3722 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3723 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3724
3725 (defun js2-print-number-node (n i)
3726 (insert (js2-make-pad i)
3727 (number-to-string (js2-number-node-num-value n))))
3728
3729 (cl-defstruct (js2-regexp-node
3730 (:include js2-node)
3731 (:constructor nil)
3732 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3733 (pos (js2-current-token-beg))
3734 (len (- js2-ts-cursor
3735 (js2-current-token-beg)))
3736 value flags)))
3737 "AST node for a regular expression literal."
3738 value ; the regexp string, without // delimiters
3739 flags) ; a string of flags, e.g. `mi'.
3740
3741 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3742 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3743
3744 (defun js2-print-regexp (n i)
3745 (insert (js2-make-pad i)
3746 "/"
3747 (js2-regexp-node-value n)
3748 "/")
3749 (if (js2-regexp-node-flags n)
3750 (insert (js2-regexp-node-flags n))))
3751
3752 (cl-defstruct (js2-string-node
3753 (:include js2-node)
3754 (:constructor nil)
3755 (:constructor make-js2-string-node (&key (type js2-STRING)
3756 (pos (js2-current-token-beg))
3757 (len (- js2-ts-cursor
3758 (js2-current-token-beg)))
3759 (value (js2-current-token-string)))))
3760 "String literal.
3761 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3762 You can tell the quote type by looking at the first character."
3763 value) ; the characters of the string, including the quotes
3764
3765 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3766 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3767
3768 (defun js2-print-string-node (n i)
3769 (insert (js2-make-pad i)
3770 (js2-node-string n)))
3771
3772 (cl-defstruct (js2-template-node
3773 (:include js2-node)
3774 (:constructor nil)
3775 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3776 beg len kids)))
3777 "Template literal."
3778 kids) ; `js2-string-node' is used for string segments, other nodes
3779 ; for substitutions inside.
3780
3781 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3782 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3783
3784 (defun js2-visit-template (n callback)
3785 (dolist (kid (js2-template-node-kids n))
3786 (js2-visit-ast kid callback)))
3787
3788 (defun js2-print-template (n i)
3789 (insert (js2-make-pad i))
3790 (dolist (kid (js2-template-node-kids n))
3791 (if (js2-string-node-p kid)
3792 (insert (js2-node-string kid))
3793 (js2-print-ast kid))))
3794
3795 (cl-defstruct (js2-tagged-template-node
3796 (:include js2-node)
3797 (:constructor nil)
3798 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3799 beg len tag template)))
3800 "Tagged template literal."
3801 tag ; `js2-node' with the tag expression.
3802 template) ; `js2-template-node' with the template.
3803
3804 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3805 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3806
3807 (defun js2-visit-tagged-template (n callback)
3808 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3809 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3810
3811 (defun js2-print-tagged-template (n i)
3812 (insert (js2-make-pad i))
3813 (js2-print-ast (js2-tagged-template-node-tag n))
3814 (js2-print-ast (js2-tagged-template-node-template n)))
3815
3816 (cl-defstruct (js2-array-node
3817 (:include js2-node)
3818 (:constructor nil)
3819 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3820 (pos js2-ts-cursor)
3821 len elems)))
3822 "AST node for an array literal."
3823 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3824
3825 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3826 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3827
3828 (defun js2-visit-array-node (n v)
3829 (dolist (e (js2-array-node-elems n))
3830 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3831
3832 (defun js2-print-array-node (n i)
3833 (insert (js2-make-pad i) "[")
3834 (let ((elems (js2-array-node-elems n)))
3835 (js2-print-list elems)
3836 (when (and elems (null (car (last elems))))
3837 (insert ",")))
3838 (insert "]"))
3839
3840 (cl-defstruct (js2-class-node
3841 (:include js2-node)
3842 (:constructor nil)
3843 (:constructor make-js2-class-node (&key (type js2-CLASS)
3844 (pos js2-ts-cursor)
3845 (form 'CLASS_STATEMENT)
3846 (name "")
3847 extends len elems)))
3848 "AST node for an class expression.
3849 `elems' is a list of `js2-object-prop-node', and `extends' is an
3850 optional `js2-expr-node'"
3851 form ; CLASS_{STATEMENT|EXPRESSION}
3852 name ; class name (a `js2-node-name', or nil if anonymous)
3853 extends ; class heritage (a `js2-expr-node', or nil if none)
3854 elems)
3855
3856 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3857 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3858
3859 (defun js2-visit-class-node (n v)
3860 (js2-visit-ast (js2-class-node-name n) v)
3861 (js2-visit-ast (js2-class-node-extends n) v)
3862 (dolist (e (js2-class-node-elems n))
3863 (js2-visit-ast e v)))
3864
3865 (defun js2-print-class-node (n i)
3866 (let* ((pad (js2-make-pad i))
3867 (name (js2-class-node-name n))
3868 (extends (js2-class-node-extends n))
3869 (elems (js2-class-node-elems n)))
3870 (insert pad "class")
3871 (when name
3872 (insert " ")
3873 (js2-print-ast name 0))
3874 (when extends
3875 (insert " extends ")
3876 (js2-print-ast extends))
3877 (insert " {")
3878 (dolist (elem elems)
3879 (insert "\n")
3880 (if (js2-node-get-prop elem 'STATIC)
3881 (progn (insert (js2-make-pad (1+ i)) "static ")
3882 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3883 (js2-print-ast elem (1+ i))))
3884 (insert "\n" pad "}")))
3885
3886 (cl-defstruct (js2-object-node
3887 (:include js2-node)
3888 (:constructor nil)
3889 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3890 (pos js2-ts-cursor)
3891 len
3892 elems)))
3893 "AST node for an object literal expression.
3894 `elems' is a list of `js2-object-prop-node'."
3895 elems)
3896
3897 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3898 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3899
3900 (defun js2-visit-object-node (n v)
3901 (dolist (e (js2-object-node-elems n))
3902 (js2-visit-ast e v)))
3903
3904 (defun js2-print-object-node (n i)
3905 (insert (js2-make-pad i) "{")
3906 (js2-print-list (js2-object-node-elems n))
3907 (insert "}"))
3908
3909 (cl-defstruct (js2-object-prop-node
3910 (:include js2-infix-node)
3911 (:constructor nil)
3912 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3913 (pos js2-ts-cursor)
3914 len left
3915 right op-pos)))
3916 "AST node for an object literal prop:value entry.
3917 The `left' field is the property: a name node, string node or number node.
3918 The `right' field is a `js2-node' representing the initializer value.
3919 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3920 and both fields have the same value.")
3921
3922 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3923 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3924
3925 (defun js2-print-object-prop-node (n i)
3926 (let* ((left (js2-object-prop-node-left n))
3927 (computed (not (or (js2-string-node-p left)
3928 (js2-number-node-p left)
3929 (js2-name-node-p left)))))
3930 (insert (js2-make-pad i))
3931 (if computed
3932 (insert "["))
3933 (js2-print-ast left 0)
3934 (if computed
3935 (insert "]"))
3936 (if (not (js2-node-get-prop n 'SHORTHAND))
3937 (progn
3938 (insert ": ")
3939 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3940
3941 (cl-defstruct (js2-getter-setter-node
3942 (:include js2-infix-node)
3943 (:constructor nil)
3944 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3945 (pos js2-ts-cursor)
3946 len left right)))
3947 "AST node for a getter/setter property in an object literal.
3948 The `left' field is the `js2-name-node' naming the getter/setter prop.
3949 The `right' field is always an anonymous `js2-function-node' with a node
3950 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3951
3952 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3953 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3954
3955 (defun js2-print-getter-setter (n i)
3956 (let ((pad (js2-make-pad i))
3957 (left (js2-getter-setter-node-left n))
3958 (right (js2-getter-setter-node-right n)))
3959 (insert pad)
3960 (if (/= (js2-node-type n) js2-FUNCTION)
3961 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3962 (js2-print-ast left 0)
3963 (js2-print-ast right 0)))
3964
3965 (cl-defstruct (js2-prop-get-node
3966 (:include js2-infix-node)
3967 (:constructor nil)
3968 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3969 (pos js2-ts-cursor)
3970 len left right)))
3971 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3972
3973 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3974 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3975
3976 (defun js2-visit-prop-get-node (n v)
3977 (js2-visit-ast (js2-prop-get-node-left n) v)
3978 (js2-visit-ast (js2-prop-get-node-right n) v))
3979
3980 (defun js2-print-prop-get-node (n i)
3981 (insert (js2-make-pad i))
3982 (js2-print-ast (js2-prop-get-node-left n) 0)
3983 (insert ".")
3984 (js2-print-ast (js2-prop-get-node-right n) 0))
3985
3986 (cl-defstruct (js2-elem-get-node
3987 (:include js2-node)
3988 (:constructor nil)
3989 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3990 (pos js2-ts-cursor)
3991 len target element
3992 lb rb)))
3993 "AST node for an array index expression such as foo[bar]."
3994 target ; a `js2-node' - the expression preceding the "."
3995 element ; a `js2-node' - the expression in brackets
3996 lb ; position of left-bracket, nil if omitted
3997 rb) ; position of right-bracket, nil if omitted
3998
3999 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4000 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4001
4002 (defun js2-visit-elem-get-node (n v)
4003 (js2-visit-ast (js2-elem-get-node-target n) v)
4004 (js2-visit-ast (js2-elem-get-node-element n) v))
4005
4006 (defun js2-print-elem-get-node (n i)
4007 (insert (js2-make-pad i))
4008 (js2-print-ast (js2-elem-get-node-target n) 0)
4009 (insert "[")
4010 (js2-print-ast (js2-elem-get-node-element n) 0)
4011 (insert "]"))
4012
4013 (cl-defstruct (js2-call-node
4014 (:include js2-node)
4015 (:constructor nil)
4016 (:constructor make-js2-call-node (&key (type js2-CALL)
4017 (pos js2-ts-cursor)
4018 len target args
4019 lp rp)))
4020 "AST node for a JavaScript function call."
4021 target ; a `js2-node' evaluating to the function to call
4022 args ; a Lisp list of `js2-node' arguments
4023 lp ; position of open-paren, or nil if missing
4024 rp) ; position of close-paren, or nil if missing
4025
4026 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4027 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4028
4029 (defun js2-visit-call-node (n v)
4030 (js2-visit-ast (js2-call-node-target n) v)
4031 (dolist (arg (js2-call-node-args n))
4032 (js2-visit-ast arg v)))
4033
4034 (defun js2-print-call-node (n i)
4035 (insert (js2-make-pad i))
4036 (js2-print-ast (js2-call-node-target n) 0)
4037 (insert "(")
4038 (js2-print-list (js2-call-node-args n))
4039 (insert ")"))
4040
4041 (cl-defstruct (js2-yield-node
4042 (:include js2-node)
4043 (:constructor nil)
4044 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4045 (pos js2-ts-cursor)
4046 len value star-p)))
4047 "AST node for yield statement or expression."
4048 star-p ; whether it's yield*
4049 value) ; optional: value to be yielded
4050
4051 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4052 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4053
4054 (defun js2-visit-yield-node (n v)
4055 (js2-visit-ast (js2-yield-node-value n) v))
4056
4057 (defun js2-print-yield-node (n i)
4058 (insert (js2-make-pad i))
4059 (insert "yield")
4060 (when (js2-yield-node-star-p n)
4061 (insert "*"))
4062 (when (js2-yield-node-value n)
4063 (insert " ")
4064 (js2-print-ast (js2-yield-node-value n) 0)))
4065
4066 (cl-defstruct (js2-paren-node
4067 (:include js2-node)
4068 (:constructor nil)
4069 (:constructor make-js2-paren-node (&key (type js2-LP)
4070 (pos js2-ts-cursor)
4071 len expr)))
4072 "AST node for a parenthesized expression.
4073 In particular, used when the parens are syntactically optional,
4074 as opposed to required parens such as those enclosing an if-conditional."
4075 expr) ; `js2-node'
4076
4077 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4078 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4079
4080 (defun js2-visit-paren-node (n v)
4081 (js2-visit-ast (js2-paren-node-expr n) v))
4082
4083 (defun js2-print-paren-node (n i)
4084 (insert (js2-make-pad i))
4085 (insert "(")
4086 (js2-print-ast (js2-paren-node-expr n) 0)
4087 (insert ")"))
4088
4089 (cl-defstruct (js2-comp-node
4090 (:include js2-scope)
4091 (:constructor nil)
4092 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4093 (pos js2-ts-cursor)
4094 len result
4095 loops filters
4096 form)))
4097 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4098 result ; result expression (just after left-bracket)
4099 loops ; a Lisp list of `js2-comp-loop-node'
4100 filters ; a Lisp list of guard/filter expressions
4101 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4102 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4103 )
4104
4105 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4106 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4107
4108 (defun js2-visit-comp-node (n v)
4109 (js2-visit-ast (js2-comp-node-result n) v)
4110 (dolist (l (js2-comp-node-loops n))
4111 (js2-visit-ast l v))
4112 (dolist (f (js2-comp-node-filters n))
4113 (js2-visit-ast f v)))
4114
4115 (defun js2-print-comp-node (n i)
4116 (let ((pad (js2-make-pad i))
4117 (result (js2-comp-node-result n))
4118 (loops (js2-comp-node-loops n))
4119 (filters (js2-comp-node-filters n))
4120 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4121 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4122 (insert pad (if gen-p "(" "["))
4123 (when legacy-p
4124 (js2-print-ast result 0))
4125 (dolist (l loops)
4126 (when legacy-p
4127 (insert " "))
4128 (js2-print-ast l 0)
4129 (unless legacy-p
4130 (insert " ")))
4131 (dolist (f filters)
4132 (when legacy-p
4133 (insert " "))
4134 (insert "if (")
4135 (js2-print-ast f 0)
4136 (insert ")")
4137 (unless legacy-p
4138 (insert " ")))
4139 (unless legacy-p
4140 (js2-print-ast result 0))
4141 (insert (if gen-p ")" "]"))))
4142
4143 (cl-defstruct (js2-comp-loop-node
4144 (:include js2-for-in-node)
4145 (:constructor nil)
4146 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4147 (pos js2-ts-cursor)
4148 len iterator
4149 object in-pos
4150 foreach-p
4151 each-pos
4152 forof-p
4153 lp rp)))
4154 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4155
4156 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4157 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4158
4159 (defun js2-visit-comp-loop (n v)
4160 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4161 (js2-visit-ast (js2-comp-loop-node-object n) v))
4162
4163 (defun js2-print-comp-loop (n _i)
4164 (insert "for ")
4165 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4166 (insert "(")
4167 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4168 (insert (if (js2-comp-loop-node-forof-p n)
4169 " of " " in "))
4170 (js2-print-ast (js2-comp-loop-node-object n) 0)
4171 (insert ")"))
4172
4173 (cl-defstruct (js2-empty-expr-node
4174 (:include js2-node)
4175 (:constructor nil)
4176 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4177 (pos (js2-current-token-beg))
4178 len)))
4179 "AST node for an empty expression.")
4180
4181 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4182 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4183
4184 (cl-defstruct (js2-xml-node
4185 (:include js2-block-node)
4186 (:constructor nil)
4187 (:constructor make-js2-xml-node (&key (type js2-XML)
4188 (pos (js2-current-token-beg))
4189 len kids)))
4190 "AST node for initial parse of E4X literals.
4191 The kids field is a list of XML fragments, each a `js2-string-node' or
4192 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4193
4194 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4195 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4196
4197 (defun js2-print-xml-node (n i)
4198 (dolist (kid (js2-xml-node-kids n))
4199 (js2-print-ast kid i)))
4200
4201 (cl-defstruct (js2-xml-js-expr-node
4202 (:include js2-xml-node)
4203 (:constructor nil)
4204 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4205 (pos js2-ts-cursor)
4206 len expr)))
4207 "AST node for an embedded JavaScript {expression} in an E4X literal.
4208 The start and end fields correspond to the curly-braces."
4209 expr) ; a `js2-expr-node' of some sort
4210
4211 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4212 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4213
4214 (defun js2-visit-xml-js-expr (n v)
4215 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4216
4217 (defun js2-print-xml-js-expr (n i)
4218 (insert (js2-make-pad i))
4219 (insert "{")
4220 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4221 (insert "}"))
4222
4223 (cl-defstruct (js2-xml-dot-query-node
4224 (:include js2-infix-node)
4225 (:constructor nil)
4226 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4227 (pos js2-ts-cursor)
4228 op-pos len left
4229 right rp)))
4230 "AST node for an E4X foo.(bar) filter expression.
4231 Note that the left-paren is automatically the character immediately
4232 following the dot (.) in the operator. No whitespace is permitted
4233 between the dot and the lp by the scanner."
4234 rp)
4235
4236 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4237 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4238
4239 (defun js2-print-xml-dot-query (n i)
4240 (insert (js2-make-pad i))
4241 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4242 (insert ".(")
4243 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4244 (insert ")"))
4245
4246 (cl-defstruct (js2-xml-ref-node
4247 (:include js2-node)
4248 (:constructor nil)) ; abstract
4249 "Base type for E4X XML attribute-access or property-get expressions.
4250 Such expressions can take a variety of forms. The general syntax has
4251 three parts:
4252
4253 - (optional) an @ (specifying an attribute access)
4254 - (optional) a namespace (a `js2-name-node') and double-colon
4255 - (required) either a `js2-name-node' or a bracketed [expression]
4256
4257 The property-name expressions (examples: ns::name, @name) are
4258 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4259 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4260
4261 This node type (or more specifically, its subclasses) will sometimes
4262 be the right-hand child of a `js2-prop-get-node' or a
4263 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4264 The `js2-xml-ref-node' may also be a standalone primary expression with
4265 no explicit target, which is valid in certain expression contexts such as
4266
4267 company..employee.(@id < 100)
4268
4269 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4270 expression whose parent is a `js2-xml-dot-query-node'."
4271 namespace
4272 at-pos
4273 colon-pos)
4274
4275 (defsubst js2-xml-ref-node-attr-access-p (node)
4276 "Return non-nil if this expression began with an @-token."
4277 (and (numberp (js2-xml-ref-node-at-pos node))
4278 (cl-plusp (js2-xml-ref-node-at-pos node))))
4279
4280 (cl-defstruct (js2-xml-prop-ref-node
4281 (:include js2-xml-ref-node)
4282 (:constructor nil)
4283 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4284 (pos (js2-current-token-beg))
4285 len propname
4286 namespace at-pos
4287 colon-pos)))
4288 "AST node for an E4X XML [expr] property-ref expression.
4289 The JavaScript syntax is an optional @, an optional ns::, and a name.
4290
4291 [ '@' ] [ name '::' ] name
4292
4293 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4294 @ns::*, @*::attr, @*::*, and @*.
4295
4296 The node starts at the @ token, if present. Otherwise it starts at the
4297 namespace name. The node bounds extend through the closing right-bracket,
4298 or if it is missing due to a syntax error, through the end of the index
4299 expression."
4300 propname)
4301
4302 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4303 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4304
4305 (defun js2-visit-xml-prop-ref-node (n v)
4306 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4307 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4308
4309 (defun js2-print-xml-prop-ref-node (n i)
4310 (insert (js2-make-pad i))
4311 (if (js2-xml-ref-node-attr-access-p n)
4312 (insert "@"))
4313 (when (js2-xml-prop-ref-node-namespace n)
4314 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4315 (insert "::"))
4316 (if (js2-xml-prop-ref-node-propname n)
4317 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4318
4319 (cl-defstruct (js2-xml-elem-ref-node
4320 (:include js2-xml-ref-node)
4321 (:constructor nil)
4322 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4323 (pos (js2-current-token-beg))
4324 len expr lb rb
4325 namespace at-pos
4326 colon-pos)))
4327 "AST node for an E4X XML [expr] member-ref expression.
4328 Syntax:
4329
4330 [ '@' ] [ name '::' ] '[' expr ']'
4331
4332 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4333
4334 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4335 is not a legal E4X XML element-ref expression, since it's already used
4336 for standard JavaScript element-get array indexing. Hence, a
4337 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4338 non-nil namespace node, or both.
4339
4340 The node starts at the @ token, if present. Otherwise it starts
4341 at the namespace name. The node bounds extend through the closing
4342 right-bracket, or if it is missing due to a syntax error, through the
4343 end of the index expression."
4344 expr ; the bracketed index expression
4345 lb
4346 rb)
4347
4348 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4349 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4350
4351 (defun js2-visit-xml-elem-ref-node (n v)
4352 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4353 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4354
4355 (defun js2-print-xml-elem-ref-node (n i)
4356 (insert (js2-make-pad i))
4357 (if (js2-xml-ref-node-attr-access-p n)
4358 (insert "@"))
4359 (when (js2-xml-elem-ref-node-namespace n)
4360 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4361 (insert "::"))
4362 (insert "[")
4363 (if (js2-xml-elem-ref-node-expr n)
4364 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4365 (insert "]"))
4366
4367 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4368
4369 (cl-defstruct (js2-xml-start-tag-node
4370 (:include js2-xml-node)
4371 (:constructor nil)
4372 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4373 (pos js2-ts-cursor)
4374 len name attrs kids
4375 empty-p)))
4376 "AST node for an XML start-tag. Not currently used.
4377 The `kids' field is a Lisp list of child content nodes."
4378 name ; a `js2-xml-name-node'
4379 attrs ; a Lisp list of `js2-xml-attr-node'
4380 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4381
4382 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4383 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4384
4385 (defun js2-visit-xml-start-tag (n v)
4386 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4387 (dolist (attr (js2-xml-start-tag-node-attrs n))
4388 (js2-visit-ast attr v))
4389 (js2-visit-block n v))
4390
4391 (defun js2-print-xml-start-tag (n i)
4392 (insert (js2-make-pad i) "<")
4393 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4394 (when (js2-xml-start-tag-node-attrs n)
4395 (insert " ")
4396 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4397 (insert ">"))
4398
4399 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4400 ;; and add the end-tag to the kids list of the parent as well.
4401 (cl-defstruct (js2-xml-end-tag-node
4402 (:include js2-xml-node)
4403 (:constructor nil)
4404 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4405 (pos js2-ts-cursor)
4406 len name)))
4407 "AST node for an XML end-tag. Not currently used."
4408 name) ; a `js2-xml-name-node'
4409
4410 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4411 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4412
4413 (defun js2-visit-xml-end-tag (n v)
4414 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4415
4416 (defun js2-print-xml-end-tag (n i)
4417 (insert (js2-make-pad i))
4418 (insert "</")
4419 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4420 (insert ">"))
4421
4422 (cl-defstruct (js2-xml-name-node
4423 (:include js2-xml-node)
4424 (:constructor nil)
4425 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4426 (pos js2-ts-cursor)
4427 len namespace kids)))
4428 "AST node for an E4X XML name. Not currently used.
4429 Any XML name can be qualified with a namespace, hence the namespace field.
4430 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4431 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4432 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4433 namespace) ; a `js2-string-node'
4434
4435 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4436 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4437
4438 (defun js2-visit-xml-name-node (n v)
4439 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4440
4441 (defun js2-print-xml-name-node (n i)
4442 (insert (js2-make-pad i))
4443 (when (js2-xml-name-node-namespace n)
4444 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4445 (insert "::"))
4446 (dolist (kid (js2-xml-name-node-kids n))
4447 (js2-print-ast kid 0)))
4448
4449 (cl-defstruct (js2-xml-pi-node
4450 (:include js2-xml-node)
4451 (:constructor nil)
4452 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4453 (pos js2-ts-cursor)
4454 len name attrs)))
4455 "AST node for an E4X XML processing instruction. Not currently used."
4456 name ; a `js2-xml-name-node'
4457 attrs) ; a list of `js2-xml-attr-node'
4458
4459 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4460 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4461
4462 (defun js2-visit-xml-pi-node (n v)
4463 (js2-visit-ast (js2-xml-pi-node-name n) v)
4464 (dolist (attr (js2-xml-pi-node-attrs n))
4465 (js2-visit-ast attr v)))
4466
4467 (defun js2-print-xml-pi-node (n i)
4468 (insert (js2-make-pad i) "<?")
4469 (js2-print-ast (js2-xml-pi-node-name n))
4470 (when (js2-xml-pi-node-attrs n)
4471 (insert " ")
4472 (js2-print-list (js2-xml-pi-node-attrs n)))
4473 (insert "?>"))
4474
4475 (cl-defstruct (js2-xml-cdata-node
4476 (:include js2-xml-node)
4477 (:constructor nil)
4478 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4479 (pos js2-ts-cursor)
4480 len content)))
4481 "AST node for a CDATA escape section. Not currently used."
4482 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4483
4484 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4485 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4486
4487 (defun js2-visit-xml-cdata-node (n v)
4488 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4489
4490 (defun js2-print-xml-cdata-node (n i)
4491 (insert (js2-make-pad i))
4492 (js2-print-ast (js2-xml-cdata-node-content n)))
4493
4494 (cl-defstruct (js2-xml-attr-node
4495 (:include js2-xml-node)
4496 (:constructor nil)
4497 (:constructor make-js2-attr-node (&key (type js2-XML)
4498 (pos js2-ts-cursor)
4499 len name value
4500 eq-pos quote-type)))
4501 "AST node representing a foo='bar' XML attribute value. Not yet used."
4502 name ; a `js2-xml-name-node'
4503 value ; a `js2-xml-name-node'
4504 eq-pos ; buffer position of "=" sign
4505 quote-type) ; 'single or 'double
4506
4507 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4508 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4509
4510 (defun js2-visit-xml-attr-node (n v)
4511 (js2-visit-ast (js2-xml-attr-node-name n) v)
4512 (js2-visit-ast (js2-xml-attr-node-value n) v))
4513
4514 (defun js2-print-xml-attr-node (n i)
4515 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4516 "'"
4517 "\"")))
4518 (insert (js2-make-pad i))
4519 (js2-print-ast (js2-xml-attr-node-name n) 0)
4520 (insert "=" quote)
4521 (js2-print-ast (js2-xml-attr-node-value n) 0)
4522 (insert quote)))
4523
4524 (cl-defstruct (js2-xml-text-node
4525 (:include js2-xml-node)
4526 (:constructor nil)
4527 (:constructor make-js2-text-node (&key (type js2-XML)
4528 (pos js2-ts-cursor)
4529 len content)))
4530 "AST node for an E4X XML text node. Not currently used."
4531 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4532
4533 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4534 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4535
4536 (defun js2-visit-xml-text-node (n v)
4537 (js2-visit-ast (js2-xml-text-node-content n) v))
4538
4539 (defun js2-print-xml-text-node (n i)
4540 (insert (js2-make-pad i))
4541 (dolist (kid (js2-xml-text-node-content n))
4542 (js2-print-ast kid)))
4543
4544 (cl-defstruct (js2-xml-comment-node
4545 (:include js2-xml-node)
4546 (:constructor nil)
4547 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4548 (pos js2-ts-cursor)
4549 len)))
4550 "AST node for E4X XML comment. Not currently used.")
4551
4552 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4553 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4554
4555 (defun js2-print-xml-comment (n i)
4556 (insert (js2-make-pad i)
4557 (js2-node-string n)))
4558
4559 ;;; Node utilities
4560
4561 (defsubst js2-node-line (n)
4562 "Fetch the source line number at the start of node N.
4563 This is O(n) in the length of the source buffer; use prudently."
4564 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4565
4566 (defsubst js2-block-node-kid (n i)
4567 "Return child I of node N, or nil if there aren't that many."
4568 (nth i (js2-block-node-kids n)))
4569
4570 (defsubst js2-block-node-first (n)
4571 "Return first child of block node N, or nil if there is none."
4572 (cl-first (js2-block-node-kids n)))
4573
4574 (defun js2-node-root (n)
4575 "Return the root of the AST containing N.
4576 If N has no parent pointer, returns N."
4577 (let ((parent (js2-node-parent n)))
4578 (if parent
4579 (js2-node-root parent)
4580 n)))
4581
4582 (defsubst js2-node-short-name (n)
4583 "Return the short name of node N as a string, e.g. `js2-if-node'."
4584 (substring (symbol-name (aref n 0))
4585 (length "cl-struct-")))
4586
4587 (defun js2-node-child-list (node)
4588 "Return the child list for NODE, a Lisp list of nodes.
4589 Works for block nodes, array nodes, obj literals, funarg lists,
4590 var decls and try nodes (for catch clauses). Note that you should call
4591 `js2-block-node-kids' on the function body for the body statements.
4592 Returns nil for zero-length child lists or unsupported nodes."
4593 (cond
4594 ((js2-function-node-p node)
4595 (js2-function-node-params node))
4596 ((js2-block-node-p node)
4597 (js2-block-node-kids node))
4598 ((js2-try-node-p node)
4599 (js2-try-node-catch-clauses node))
4600 ((js2-array-node-p node)
4601 (js2-array-node-elems node))
4602 ((js2-object-node-p node)
4603 (js2-object-node-elems node))
4604 ((js2-call-node-p node)
4605 (js2-call-node-args node))
4606 ((js2-new-node-p node)
4607 (js2-new-node-args node))
4608 ((js2-var-decl-node-p node)
4609 (js2-var-decl-node-kids node))
4610 (t
4611 nil)))
4612
4613 (defun js2-node-set-child-list (node kids)
4614 "Set the child list for NODE to KIDS."
4615 (cond
4616 ((js2-function-node-p node)
4617 (setf (js2-function-node-params node) kids))
4618 ((js2-block-node-p node)
4619 (setf (js2-block-node-kids node) kids))
4620 ((js2-try-node-p node)
4621 (setf (js2-try-node-catch-clauses node) kids))
4622 ((js2-array-node-p node)
4623 (setf (js2-array-node-elems node) kids))
4624 ((js2-object-node-p node)
4625 (setf (js2-object-node-elems node) kids))
4626 ((js2-call-node-p node)
4627 (setf (js2-call-node-args node) kids))
4628 ((js2-new-node-p node)
4629 (setf (js2-new-node-args node) kids))
4630 ((js2-var-decl-node-p node)
4631 (setf (js2-var-decl-node-kids node) kids))
4632 (t
4633 (error "Unsupported node type: %s" (js2-node-short-name node))))
4634 kids)
4635
4636 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4637 (defconst js2-paren-expr-nodes
4638 '(cl-struct-js2-comp-loop-node
4639 cl-struct-js2-comp-node
4640 cl-struct-js2-call-node
4641 cl-struct-js2-catch-node
4642 cl-struct-js2-do-node
4643 cl-struct-js2-elem-get-node
4644 cl-struct-js2-for-in-node
4645 cl-struct-js2-for-node
4646 cl-struct-js2-function-node
4647 cl-struct-js2-if-node
4648 cl-struct-js2-let-node
4649 cl-struct-js2-new-node
4650 cl-struct-js2-paren-node
4651 cl-struct-js2-switch-node
4652 cl-struct-js2-while-node
4653 cl-struct-js2-with-node
4654 cl-struct-js2-xml-dot-query-node)
4655 "Node types that can have a parenthesized child expression.
4656 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4657
4658 (defsubst js2-paren-expr-node-p (node)
4659 "Return t for nodes that typically have a parenthesized child expression.
4660 Useful for computing the indentation anchors for arg-lists and conditions.
4661 Note that it may return a false positive, for instance when NODE is
4662 a `js2-new-node' and there are no arguments or parentheses."
4663 (memq (aref node 0) js2-paren-expr-nodes))
4664
4665 ;; Fake polymorphism... yech.
4666 (defun js2-node-lp (node)
4667 "Return relative left-paren position for NODE, if applicable.
4668 For `js2-elem-get-node' structs, returns left-bracket position.
4669 Note that the position may be nil in the case of a parse error."
4670 (cond
4671 ((js2-elem-get-node-p node)
4672 (js2-elem-get-node-lb node))
4673 ((js2-loop-node-p node)
4674 (js2-loop-node-lp node))
4675 ((js2-function-node-p node)
4676 (js2-function-node-lp node))
4677 ((js2-if-node-p node)
4678 (js2-if-node-lp node))
4679 ((js2-new-node-p node)
4680 (js2-new-node-lp node))
4681 ((js2-call-node-p node)
4682 (js2-call-node-lp node))
4683 ((js2-paren-node-p node)
4684 0)
4685 ((js2-switch-node-p node)
4686 (js2-switch-node-lp node))
4687 ((js2-catch-node-p node)
4688 (js2-catch-node-lp node))
4689 ((js2-let-node-p node)
4690 (js2-let-node-lp node))
4691 ((js2-comp-node-p node)
4692 0)
4693 ((js2-with-node-p node)
4694 (js2-with-node-lp node))
4695 ((js2-xml-dot-query-node-p node)
4696 (1+ (js2-infix-node-op-pos node)))
4697 (t
4698 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4699
4700 ;; Fake polymorphism... blech.
4701 (defun js2-node-rp (node)
4702 "Return relative right-paren position for NODE, if applicable.
4703 For `js2-elem-get-node' structs, returns right-bracket position.
4704 Note that the position may be nil in the case of a parse error."
4705 (cond
4706 ((js2-elem-get-node-p node)
4707 (js2-elem-get-node-rb node))
4708 ((js2-loop-node-p node)
4709 (js2-loop-node-rp node))
4710 ((js2-function-node-p node)
4711 (js2-function-node-rp node))
4712 ((js2-if-node-p node)
4713 (js2-if-node-rp node))
4714 ((js2-new-node-p node)
4715 (js2-new-node-rp node))
4716 ((js2-call-node-p node)
4717 (js2-call-node-rp node))
4718 ((js2-paren-node-p node)
4719 (1- (js2-node-len node)))
4720 ((js2-switch-node-p node)
4721 (js2-switch-node-rp node))
4722 ((js2-catch-node-p node)
4723 (js2-catch-node-rp node))
4724 ((js2-let-node-p node)
4725 (js2-let-node-rp node))
4726 ((js2-comp-node-p node)
4727 (1- (js2-node-len node)))
4728 ((js2-with-node-p node)
4729 (js2-with-node-rp node))
4730 ((js2-xml-dot-query-node-p node)
4731 (1+ (js2-xml-dot-query-node-rp node)))
4732 (t
4733 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4734
4735 (defsubst js2-node-first-child (node)
4736 "Return the first element of `js2-node-child-list' for NODE."
4737 (car (js2-node-child-list node)))
4738
4739 (defsubst js2-node-last-child (node)
4740 "Return the last element of `js2-node-last-child' for NODE."
4741 (car (last (js2-node-child-list node))))
4742
4743 (defun js2-node-prev-sibling (node)
4744 "Return the previous statement in parent.
4745 Works for parents supported by `js2-node-child-list'.
4746 Returns nil if NODE is not in the parent, or PARENT is
4747 not a supported node, or if NODE is the first child."
4748 (let* ((p (js2-node-parent node))
4749 (kids (js2-node-child-list p))
4750 (sib (car kids)))
4751 (while (and kids
4752 (not (eq node (cadr kids))))
4753 (setq kids (cdr kids)
4754 sib (car kids)))
4755 sib))
4756
4757 (defun js2-node-next-sibling (node)
4758 "Return the next statement in parent block.
4759 Returns nil if NODE is not in the block, or PARENT is not
4760 a block node, or if NODE is the last statement."
4761 (let* ((p (js2-node-parent node))
4762 (kids (js2-node-child-list p)))
4763 (while (and kids
4764 (not (eq node (car kids))))
4765 (setq kids (cdr kids)))
4766 (cadr kids)))
4767
4768 (defun js2-node-find-child-before (pos parent &optional after)
4769 "Find the last child that starts before POS in parent.
4770 If AFTER is non-nil, returns first child starting after POS.
4771 POS is an absolute buffer position. PARENT is any node
4772 supported by `js2-node-child-list'.
4773 Returns nil if no applicable child is found."
4774 (let ((kids (if (js2-function-node-p parent)
4775 (js2-block-node-kids (js2-function-node-body parent))
4776 (js2-node-child-list parent)))
4777 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4778 (js2-function-node-body parent)
4779 parent)))
4780 kid result fn
4781 (continue t))
4782 (setq fn (if after '>= '<))
4783 (while (and kids continue)
4784 (setq kid (car kids))
4785 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4786 (setq result kid
4787 continue (not after))
4788 (setq continue after))
4789 (setq kids (cdr kids)))
4790 result))
4791
4792 (defun js2-node-find-child-after (pos parent)
4793 "Find first child that starts after POS in parent.
4794 POS is an absolute buffer position. PARENT is any node
4795 supported by `js2-node-child-list'.
4796 Returns nil if no applicable child is found."
4797 (js2-node-find-child-before pos parent 'after))
4798
4799 (defun js2-node-replace-child (pos parent new-node)
4800 "Replace node at index POS in PARENT with NEW-NODE.
4801 Only works for parents supported by `js2-node-child-list'."
4802 (let ((kids (js2-node-child-list parent))
4803 (i 0))
4804 (while (< i pos)
4805 (setq kids (cdr kids)
4806 i (1+ i)))
4807 (setcar kids new-node)
4808 (js2-node-add-children parent new-node)))
4809
4810 (defun js2-node-buffer (n)
4811 "Return the buffer associated with AST N.
4812 Returns nil if the buffer is not set as a property on the root
4813 node, or if parent links were not recorded during parsing."
4814 (let ((root (js2-node-root n)))
4815 (and root
4816 (js2-ast-root-p root)
4817 (js2-ast-root-buffer root))))
4818
4819 (defun js2-block-node-push (n kid)
4820 "Push js2-node KID onto the end of js2-block-node N's child list.
4821 KID is always added to the -end- of the kids list.
4822 Function also calls `js2-node-add-children' to add the parent link."
4823 (let ((kids (js2-node-child-list n)))
4824 (if kids
4825 (setcdr kids (nconc (cdr kids) (list kid)))
4826 (js2-node-set-child-list n (list kid)))
4827 (js2-node-add-children n kid)))
4828
4829 (defun js2-node-string (node)
4830 (with-current-buffer (or (js2-node-buffer node)
4831 (error "No buffer available for node %s" node))
4832 (let ((pos (js2-node-abs-pos node)))
4833 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4834
4835 ;; Container for storing the node we're looking for in a traversal.
4836 (js2-deflocal js2-discovered-node nil)
4837
4838 ;; Keep track of absolute node position during traversals.
4839 (js2-deflocal js2-visitor-offset nil)
4840
4841 (js2-deflocal js2-node-search-point nil)
4842
4843 (when js2-mode-dev-mode-p
4844 (defun js2-find-node-at-point ()
4845 (interactive)
4846 (let ((node (js2-node-at-point)))
4847 (message "%s" (or node "No node found at point"))))
4848 (defun js2-node-name-at-point ()
4849 (interactive)
4850 (let ((node (js2-node-at-point)))
4851 (message "%s" (if node
4852 (js2-node-short-name node)
4853 "No node found at point.")))))
4854
4855 (defun js2-node-at-point (&optional pos skip-comments)
4856 "Return AST node at POS, a buffer position, defaulting to current point.
4857 The `js2-mode-ast' variable must be set to the current parse tree.
4858 Signals an error if the AST (`js2-mode-ast') is nil.
4859 Always returns a node - if it can't find one, it returns the root.
4860 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4861 (let ((ast js2-mode-ast)
4862 result)
4863 (unless ast
4864 (error "No JavaScript AST available"))
4865 ;; Look through comments first, since they may be inside nodes that
4866 ;; would otherwise report a match.
4867 (setq pos (or pos (point))
4868 result (if (> pos (js2-node-abs-end ast))
4869 ast
4870 (if (not skip-comments)
4871 (js2-comment-at-point pos))))
4872 (unless result
4873 (setq js2-discovered-node nil
4874 js2-visitor-offset 0
4875 js2-node-search-point pos)
4876 (unwind-protect
4877 (catch 'js2-visit-done
4878 (js2-visit-ast ast #'js2-node-at-point-visitor))
4879 (setq js2-visitor-offset nil
4880 js2-node-search-point nil))
4881 (setq result js2-discovered-node))
4882 ;; may have found a comment beyond end of last child node,
4883 ;; since visiting the ast-root looks at the comment-list last.
4884 (if (and skip-comments
4885 (js2-comment-node-p result))
4886 (setq result nil))
4887 (or result js2-mode-ast)))
4888
4889 (defun js2-node-at-point-visitor (node end-p)
4890 (let ((rel-pos (js2-node-pos node))
4891 abs-pos
4892 abs-end
4893 (point js2-node-search-point))
4894 (cond
4895 (end-p
4896 ;; this evaluates to a non-nil return value, even if it's zero
4897 (cl-decf js2-visitor-offset rel-pos))
4898 ;; we already looked for comments before visiting, and don't want them now
4899 ((js2-comment-node-p node)
4900 nil)
4901 (t
4902 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4903 ;; we only want to use the node if the point is before
4904 ;; the last character position in the node, so we decrement
4905 ;; the absolute end by 1.
4906 abs-end (+ abs-pos (js2-node-len node) -1))
4907 (cond
4908 ;; If this node starts after search-point, stop the search.
4909 ((> abs-pos point)
4910 (throw 'js2-visit-done nil))
4911 ;; If this node ends before the search-point, don't check kids.
4912 ((> point abs-end)
4913 nil)
4914 (t
4915 ;; Otherwise point is within this node, possibly in a child.
4916 (setq js2-discovered-node node)
4917 t)))))) ; keep processing kids to look for more specific match
4918
4919 (defsubst js2-block-comment-p (node)
4920 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4921 (and (js2-comment-node-p node)
4922 (memq (js2-comment-node-format node) '(jsdoc block))))
4923
4924 ;; TODO: put the comments in a vector and binary-search them instead
4925 (defun js2-comment-at-point (&optional pos)
4926 "Look through scanned comment nodes for one containing POS.
4927 POS is a buffer position that defaults to current point.
4928 Function returns nil if POS was not in any comment node."
4929 (let ((ast js2-mode-ast)
4930 (x (or pos (point)))
4931 beg end)
4932 (unless ast
4933 (error "No JavaScript AST available"))
4934 (catch 'done
4935 ;; Comments are stored in lexical order.
4936 (dolist (comment (js2-ast-root-comments ast) nil)
4937 (setq beg (js2-node-abs-pos comment)
4938 end (+ beg (js2-node-len comment)))
4939 (if (and (>= x beg)
4940 (<= x end))
4941 (throw 'done comment))))))
4942
4943 (defun js2-mode-find-parent-fn (node)
4944 "Find function enclosing NODE.
4945 Returns nil if NODE is not inside a function."
4946 (setq node (js2-node-parent node))
4947 (while (and node (not (js2-function-node-p node)))
4948 (setq node (js2-node-parent node)))
4949 (and (js2-function-node-p node) node))
4950
4951 (defun js2-mode-find-enclosing-fn (node)
4952 "Find function or root enclosing NODE."
4953 (if (js2-ast-root-p node)
4954 node
4955 (setq node (js2-node-parent node))
4956 (while (not (or (js2-ast-root-p node)
4957 (js2-function-node-p node)))
4958 (setq node (js2-node-parent node)))
4959 node))
4960
4961 (defun js2-mode-find-enclosing-node (beg end)
4962 "Find node fully enclosing BEG and END."
4963 (let ((node (js2-node-at-point beg))
4964 pos
4965 (continue t))
4966 (while continue
4967 (if (or (js2-ast-root-p node)
4968 (and
4969 (<= (setq pos (js2-node-abs-pos node)) beg)
4970 (>= (+ pos (js2-node-len node)) end)))
4971 (setq continue nil)
4972 (setq node (js2-node-parent node))))
4973 node))
4974
4975 (defun js2-node-parent-script-or-fn (node)
4976 "Find script or function immediately enclosing NODE.
4977 If NODE is the ast-root, returns nil."
4978 (if (js2-ast-root-p node)
4979 nil
4980 (setq node (js2-node-parent node))
4981 (while (and node (not (or (js2-function-node-p node)
4982 (js2-script-node-p node))))
4983 (setq node (js2-node-parent node)))
4984 node))
4985
4986 (defun js2-node-is-descendant (node ancestor)
4987 "Return t if NODE is a descendant of ANCESTOR."
4988 (while (and node
4989 (not (eq node ancestor)))
4990 (setq node (js2-node-parent node)))
4991 node)
4992
4993 ;;; visitor infrastructure
4994
4995 (defun js2-visit-none (_node _callback)
4996 "Visitor for AST node that have no node children."
4997 nil)
4998
4999 (defun js2-print-none (_node _indent)
5000 "Visitor for AST node with no printed representation.")
5001
5002 (defun js2-print-body (node indent)
5003 "Print a statement, or a block without braces."
5004 (if (js2-block-node-p node)
5005 (dolist (kid (js2-block-node-kids node))
5006 (js2-print-ast kid indent))
5007 (js2-print-ast node indent)))
5008
5009 (defun js2-print-list (args &optional delimiter)
5010 (cl-loop with len = (length args)
5011 for arg in args
5012 for count from 1
5013 do
5014 (when arg (js2-print-ast arg 0))
5015 (if (< count len)
5016 (insert (or delimiter ", ")))))
5017
5018 (defun js2-print-tree (ast)
5019 "Prints an AST to the current buffer.
5020 Makes `js2-ast-parent-nodes' available to the printer functions."
5021 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5022 (js2-print-ast ast)))
5023
5024 (defun js2-print-ast (node &optional indent)
5025 "Helper function for printing AST nodes.
5026 Requires `js2-ast-parent-nodes' to be non-nil.
5027 You should use `js2-print-tree' instead of this function."
5028 (let ((printer (get (aref node 0) 'js2-printer))
5029 (i (or indent 0)))
5030 ;; TODO: wedge comments in here somewhere
5031 (if printer
5032 (funcall printer node i))))
5033
5034 (defconst js2-side-effecting-tokens
5035 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5036 (dolist (tt (list js2-ASSIGN
5037 js2-ASSIGN_ADD
5038 js2-ASSIGN_BITAND
5039 js2-ASSIGN_BITOR
5040 js2-ASSIGN_BITXOR
5041 js2-ASSIGN_DIV
5042 js2-ASSIGN_LSH
5043 js2-ASSIGN_MOD
5044 js2-ASSIGN_MUL
5045 js2-ASSIGN_RSH
5046 js2-ASSIGN_SUB
5047 js2-ASSIGN_URSH
5048 js2-BLOCK
5049 js2-BREAK
5050 js2-CALL
5051 js2-CATCH
5052 js2-CATCH_SCOPE
5053 js2-CLASS
5054 js2-CONST
5055 js2-CONTINUE
5056 js2-DEBUGGER
5057 js2-DEC
5058 js2-DELPROP
5059 js2-DEL_REF
5060 js2-DO
5061 js2-ELSE
5062 js2-EMPTY
5063 js2-ENTERWITH
5064 js2-EXPORT
5065 js2-EXPR_RESULT
5066 js2-FINALLY
5067 js2-FOR
5068 js2-FUNCTION
5069 js2-GOTO
5070 js2-IF
5071 js2-IFEQ
5072 js2-IFNE
5073 js2-IMPORT
5074 js2-INC
5075 js2-JSR
5076 js2-LABEL
5077 js2-LEAVEWITH
5078 js2-LET
5079 js2-LETEXPR
5080 js2-LOCAL_BLOCK
5081 js2-LOOP
5082 js2-NEW
5083 js2-REF_CALL
5084 js2-RETHROW
5085 js2-RETURN
5086 js2-RETURN_RESULT
5087 js2-SEMI
5088 js2-SETELEM
5089 js2-SETELEM_OP
5090 js2-SETNAME
5091 js2-SETPROP
5092 js2-SETPROP_OP
5093 js2-SETVAR
5094 js2-SET_REF
5095 js2-SET_REF_OP
5096 js2-SWITCH
5097 js2-TARGET
5098 js2-THROW
5099 js2-TRY
5100 js2-VAR
5101 js2-WHILE
5102 js2-WITH
5103 js2-WITHEXPR
5104 js2-YIELD))
5105 (aset tokens tt t))
5106 (if js2-instanceof-has-side-effects
5107 (aset tokens js2-INSTANCEOF t))
5108 tokens))
5109
5110 (defun js2-node-has-side-effects (node)
5111 "Return t if NODE has side effects."
5112 (when node ; makes it easier to handle malformed expressions
5113 (let ((tt (js2-node-type node)))
5114 (cond
5115 ;; This doubtless needs some work, since EXPR_VOID is used
5116 ;; in several ways in Rhino and I may not have caught them all.
5117 ;; I'll wait for people to notice incorrect warnings.
5118 ((and (= tt js2-EXPR_VOID)
5119 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5120 (let ((expr (js2-expr-stmt-node-expr node)))
5121 (or (js2-node-has-side-effects expr)
5122 (when (js2-string-node-p expr)
5123 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5124 ((= tt js2-COMMA)
5125 (js2-node-has-side-effects (js2-infix-node-right node)))
5126 ((or (= tt js2-AND)
5127 (= tt js2-OR))
5128 (or (js2-node-has-side-effects (js2-infix-node-right node))
5129 (js2-node-has-side-effects (js2-infix-node-left node))))
5130 ((= tt js2-HOOK)
5131 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5132 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5133 ((js2-paren-node-p node)
5134 (js2-node-has-side-effects (js2-paren-node-expr node)))
5135 ((= tt js2-ERROR) ; avoid cascaded error messages
5136 nil)
5137 (t
5138 (aref js2-side-effecting-tokens tt))))))
5139
5140 (defconst js2-stmt-node-types
5141 (list js2-BLOCK
5142 js2-BREAK
5143 js2-CONTINUE
5144 js2-DEFAULT ; e4x "default xml namespace" statement
5145 js2-DO
5146 js2-EXPORT
5147 js2-EXPR_RESULT
5148 js2-EXPR_VOID
5149 js2-FOR
5150 js2-IF
5151 js2-IMPORT
5152 js2-RETURN
5153 js2-SWITCH
5154 js2-THROW
5155 js2-TRY
5156 js2-WHILE
5157 js2-WITH)
5158 "Node types that only appear in statement contexts.
5159 The list does not include nodes that always appear as the child
5160 of another specific statement type, such as switch-cases,
5161 catch and finally blocks, and else-clauses. The list also excludes
5162 nodes like yield, let and var, which may appear in either expression
5163 or statement context, and in the latter context always have a
5164 `js2-expr-stmt-node' parent. Finally, the list does not include
5165 functions or scripts, which are treated separately from statements
5166 by the JavaScript parser and runtime.")
5167
5168 (defun js2-stmt-node-p (node)
5169 "Heuristic for figuring out if NODE is a statement.
5170 Some node types can appear in either an expression context or a
5171 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5172 For these node types in a statement context, the parent will be a
5173 `js2-expr-stmt-node'.
5174 Functions aren't included in the check."
5175 (memq (js2-node-type node) js2-stmt-node-types))
5176
5177 (defun js2-mode-find-first-stmt (node)
5178 "Search upward starting from NODE looking for a statement.
5179 For purposes of this function, a `js2-function-node' counts."
5180 (while (not (or (js2-stmt-node-p node)
5181 (js2-function-node-p node)))
5182 (setq node (js2-node-parent node)))
5183 node)
5184
5185 (defun js2-node-parent-stmt (node)
5186 "Return the node's first ancestor that is a statement.
5187 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5188 appearing in a statement context will have a parent that is a
5189 `js2-expr-stmt-node' that will be returned by this function."
5190 (let ((parent (js2-node-parent node)))
5191 (if (or (null parent)
5192 (js2-stmt-node-p parent)
5193 (and (js2-function-node-p parent)
5194 (not (eq (js2-function-node-form parent)
5195 'FUNCTION_EXPRESSION))))
5196 parent
5197 (js2-node-parent-stmt parent))))
5198
5199 ;; In the Mozilla Rhino sources, Roshan James writes:
5200 ;; Does consistent-return analysis on the function body when strict mode is
5201 ;; enabled.
5202 ;;
5203 ;; function (x) { return (x+1) }
5204 ;;
5205 ;; is ok, but
5206 ;;
5207 ;; function (x) { if (x < 0) return (x+1); }
5208 ;;
5209 ;; is not because the function can potentially return a value when the
5210 ;; condition is satisfied and if not, the function does not explicitly
5211 ;; return a value.
5212 ;;
5213 ;; This extends to checking mismatches such as "return" and "return <value>"
5214 ;; used in the same function. Warnings are not emitted if inconsistent
5215 ;; returns exist in code that can be statically shown to be unreachable.
5216 ;; Ex.
5217 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5218 ;;
5219 ;; emits no warning. However if the loop had a break statement, then a
5220 ;; warning would be emitted.
5221 ;;
5222 ;; The consistency analysis looks at control structures such as loops, ifs,
5223 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5224 ;; warns the user about an inconsistent set of termination possibilities.
5225 ;;
5226 ;; These flags enumerate the possible ways a statement/function can
5227 ;; terminate. These flags are used by endCheck() and by the Parser to
5228 ;; detect inconsistent return usage.
5229 ;;
5230 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5231 ;; able to execute (example: throw, continue)
5232 ;;
5233 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5234 ;; next one. Statement such as return dont. A compound statement may have
5235 ;; some branch that drops off control to the next statement.
5236 ;;
5237 ;; END_RETURNS indicates that the statement can return with no value.
5238 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5239 ;;
5240 ;; A compound statement such as
5241 ;; if (condition) {
5242 ;; return value;
5243 ;; }
5244 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5245
5246 (defconst js2-END_UNREACHED 0)
5247 (defconst js2-END_DROPS_OFF 1)
5248 (defconst js2-END_RETURNS 2)
5249 (defconst js2-END_RETURNS_VALUE 4)
5250 (defconst js2-END_YIELDS 8)
5251
5252 (defun js2-has-consistent-return-usage (node)
5253 "Check that every return usage in a function body is consistent.
5254 Returns t if the function satisfies strict mode requirement."
5255 (let ((n (js2-end-check node)))
5256 ;; either it doesn't return a value in any branch...
5257 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5258 ;; or it returns a value (or is unreached) at every branch
5259 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5260 js2-END_RETURNS
5261 js2-END_YIELDS)))))
5262
5263 (defun js2-end-check-if (node)
5264 "Ensure that return usage in then/else blocks is consistent.
5265 If there is no else block, then the return statement can fall through.
5266 Returns logical OR of END_* flags"
5267 (let ((th (js2-if-node-then-part node))
5268 (el (js2-if-node-else-part node)))
5269 (if (null th)
5270 js2-END_UNREACHED
5271 (logior (js2-end-check th) (if el
5272 (js2-end-check el)
5273 js2-END_DROPS_OFF)))))
5274
5275 (defun js2-end-check-switch (node)
5276 "Consistency of return statements is checked between the case statements.
5277 If there is no default, then the switch can fall through. If there is a
5278 default, we check to see if all code paths in the default return or if
5279 there is a code path that can fall through.
5280 Returns logical OR of END_* flags."
5281 (let ((rv js2-END_UNREACHED)
5282 default-case)
5283 ;; examine the cases
5284 (catch 'break
5285 (dolist (c (js2-switch-node-cases node))
5286 (if (js2-case-node-expr c)
5287 (js2-set-flag rv (js2-end-check-block c))
5288 (setq default-case c)
5289 (throw 'break nil))))
5290 ;; we don't care how the cases drop into each other
5291 (js2-clear-flag rv js2-END_DROPS_OFF)
5292 ;; examine the default
5293 (js2-set-flag rv (if default-case
5294 (js2-end-check default-case)
5295 js2-END_DROPS_OFF))
5296 rv))
5297
5298 (defun js2-end-check-try (node)
5299 "If the block has a finally, return consistency is checked in the
5300 finally block. If all code paths in the finally return, then the
5301 returns in the try-catch blocks don't matter. If there is a code path
5302 that does not return or if there is no finally block, the returns
5303 of the try and catch blocks are checked for mismatch.
5304 Returns logical OR of END_* flags."
5305 (let ((finally (js2-try-node-finally-block node))
5306 rv)
5307 ;; check the finally if it exists
5308 (setq rv (if finally
5309 (js2-end-check (js2-finally-node-body finally))
5310 js2-END_DROPS_OFF))
5311 ;; If the finally block always returns, then none of the returns
5312 ;; in the try or catch blocks matter.
5313 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5314 (js2-clear-flag rv js2-END_DROPS_OFF)
5315 ;; examine the try block
5316 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5317 ;; check each catch block
5318 (dolist (cb (js2-try-node-catch-clauses node))
5319 (js2-set-flag rv (js2-end-check cb))))
5320 rv))
5321
5322 (defun js2-end-check-loop (node)
5323 "Return statement in the loop body must be consistent.
5324 The default assumption for any kind of a loop is that it will eventually
5325 terminate. The only exception is a loop with a constant true condition.
5326 Code that follows such a loop is examined only if one can determine
5327 statically that there is a break out of the loop.
5328
5329 for(... ; ... ; ...) {}
5330 for(... in ... ) {}
5331 while(...) { }
5332 do { } while(...)
5333
5334 Returns logical OR of END_* flags."
5335 (let ((rv (js2-end-check (js2-loop-node-body node)))
5336 (condition (cond
5337 ((js2-while-node-p node)
5338 (js2-while-node-condition node))
5339 ((js2-do-node-p node)
5340 (js2-do-node-condition node))
5341 ((js2-for-node-p node)
5342 (js2-for-node-condition node)))))
5343
5344 ;; check to see if the loop condition is always true
5345 (if (and condition
5346 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5347 (js2-clear-flag rv js2-END_DROPS_OFF))
5348
5349 ;; look for effect of breaks
5350 (js2-set-flag rv (js2-node-get-prop node
5351 'CONTROL_BLOCK_PROP
5352 js2-END_UNREACHED))
5353 rv))
5354
5355 (defun js2-end-check-block (node)
5356 "A general block of code is examined statement by statement.
5357 If any statement (even a compound one) returns in all branches, then
5358 subsequent statements are not examined.
5359 Returns logical OR of END_* flags."
5360 (let* ((rv js2-END_DROPS_OFF)
5361 (kids (js2-block-node-kids node))
5362 (n (car kids)))
5363 ;; Check each statment. If the statement can continue onto the next
5364 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5365 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5366 (js2-clear-flag rv js2-END_DROPS_OFF)
5367 (js2-set-flag rv (js2-end-check n))
5368 (setq kids (cdr kids)
5369 n (car kids)))
5370 rv))
5371
5372 (defun js2-end-check-label (node)
5373 "A labeled statement implies that there may be a break to the label.
5374 The function processes the labeled statement and then checks the
5375 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5376 particular label.
5377 Returns logical OR of END_* flags."
5378 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5379 (logior rv (js2-node-get-prop node
5380 'CONTROL_BLOCK_PROP
5381 js2-END_UNREACHED))))
5382
5383 (defun js2-end-check-break (node)
5384 "When a break is encountered annotate the statement being broken
5385 out of by setting its CONTROL_BLOCK_PROP property.
5386 Returns logical OR of END_* flags."
5387 (and (js2-break-node-target node)
5388 (js2-node-set-prop (js2-break-node-target node)
5389 'CONTROL_BLOCK_PROP
5390 js2-END_DROPS_OFF))
5391 js2-END_UNREACHED)
5392
5393 (defun js2-end-check (node)
5394 "Examine the body of a function, doing a basic reachability analysis.
5395 Returns a combination of flags END_* flags that indicate
5396 how the function execution can terminate. These constitute only the
5397 pessimistic set of termination conditions. It is possible that at
5398 runtime certain code paths will never be actually taken. Hence this
5399 analysis will flag errors in cases where there may not be errors.
5400 Returns logical OR of END_* flags"
5401 (let (kid)
5402 (cond
5403 ((js2-break-node-p node)
5404 (js2-end-check-break node))
5405 ((js2-expr-stmt-node-p node)
5406 (if (setq kid (js2-expr-stmt-node-expr node))
5407 (js2-end-check kid)
5408 js2-END_DROPS_OFF))
5409 ((or (js2-continue-node-p node)
5410 (js2-throw-node-p node))
5411 js2-END_UNREACHED)
5412 ((js2-return-node-p node)
5413 (if (setq kid (js2-return-node-retval node))
5414 js2-END_RETURNS_VALUE
5415 js2-END_RETURNS))
5416 ((js2-loop-node-p node)
5417 (js2-end-check-loop node))
5418 ((js2-switch-node-p node)
5419 (js2-end-check-switch node))
5420 ((js2-labeled-stmt-node-p node)
5421 (js2-end-check-label node))
5422 ((js2-if-node-p node)
5423 (js2-end-check-if node))
5424 ((js2-try-node-p node)
5425 (js2-end-check-try node))
5426 ((js2-block-node-p node)
5427 (if (null (js2-block-node-kids node))
5428 js2-END_DROPS_OFF
5429 (js2-end-check-block node)))
5430 ((js2-yield-node-p node)
5431 js2-END_YIELDS)
5432 (t
5433 js2-END_DROPS_OFF))))
5434
5435 (defun js2-always-defined-boolean-p (node)
5436 "Check if NODE always evaluates to true or false in boolean context.
5437 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5438 nor always false."
5439 (let ((tt (js2-node-type node))
5440 num)
5441 (cond
5442 ((or (= tt js2-FALSE) (= tt js2-NULL))
5443 'ALWAYS_FALSE)
5444 ((= tt js2-TRUE)
5445 'ALWAYS_TRUE)
5446 ((= tt js2-NUMBER)
5447 (setq num (js2-number-node-num-value node))
5448 (if (and (not (eq num 0.0e+NaN))
5449 (not (zerop num)))
5450 'ALWAYS_TRUE
5451 'ALWAYS_FALSE))
5452 (t
5453 nil))))
5454
5455 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5456 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5457
5458 (defvar js2-tokens nil
5459 "List of all defined token names.") ; initialized in `js2-token-names'
5460
5461 (defconst js2-token-names
5462 (let* ((names (make-vector js2-num-tokens -1))
5463 (case-fold-search nil) ; only match js2-UPPER_CASE
5464 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5465 (cl-loop for sym in syms
5466 for i from 0
5467 do
5468 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5469 (not (boundp sym)))
5470 (aset names (symbol-value sym) ; code, e.g. 152
5471 (downcase
5472 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5473 (push sym js2-tokens)))
5474 names)
5475 "Vector mapping int values to token string names, sans `js2-' prefix.")
5476
5477 (defun js2-tt-name (tok)
5478 "Return a string name for TOK, a token symbol or code.
5479 Signals an error if it's not a recognized token."
5480 (let ((code tok))
5481 (if (symbolp tok)
5482 (setq code (symbol-value tok)))
5483 (if (eq code -1)
5484 "ERROR"
5485 (if (and (numberp code)
5486 (not (cl-minusp code))
5487 (< code js2-num-tokens))
5488 (aref js2-token-names code)
5489 (error "Invalid token: %s" code)))))
5490
5491 (defsubst js2-tt-sym (tok)
5492 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5493 (intern (js2-tt-name tok)))
5494
5495 (defconst js2-token-codes
5496 (let ((table (make-hash-table :test 'eq :size 256)))
5497 (cl-loop for name across js2-token-names
5498 for sym = (intern (concat "js2-" (upcase name)))
5499 do
5500 (puthash sym (symbol-value sym) table))
5501 ;; clean up a few that are "wrong" in Rhino's token codes
5502 (puthash 'js2-DELETE js2-DELPROP table)
5503 table)
5504 "Hashtable mapping token type symbols to their bytecodes.")
5505
5506 (defsubst js2-tt-code (sym)
5507 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5508 (or (gethash sym js2-token-codes)
5509 (error "Invalid token symbol: %s " sym))) ; signal code bug
5510
5511 (defun js2-report-scan-error (msg &optional no-throw beg len)
5512 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5513 (js2-report-error msg nil
5514 (or beg (js2-current-token-beg))
5515 (or len (js2-current-token-len)))
5516 (unless no-throw
5517 (throw 'return js2-ERROR)))
5518
5519 (defun js2-set-string-from-buffer (token)
5520 "Set `string' and `end' slots for TOKEN, return the string."
5521 (setf (js2-token-end token) js2-ts-cursor
5522 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5523
5524 ;; TODO: could potentially avoid a lot of consing by allocating a
5525 ;; char buffer the way Rhino does.
5526 (defsubst js2-add-to-string (c)
5527 (push c js2-ts-string-buffer))
5528
5529 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5530 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5531 ;; any other character: when it's not part of the current token, we
5532 ;; unget it, allowing it to be read again by the following call.
5533 (defsubst js2-unget-char ()
5534 (cl-decf js2-ts-cursor))
5535
5536 ;; Rhino distinguishes \r and \n line endings. We don't need to
5537 ;; because we only scan from Emacs buffers, which always use \n.
5538 (defun js2-get-char ()
5539 "Read and return the next character from the input buffer.
5540 Increments `js2-ts-lineno' if the return value is a newline char.
5541 Updates `js2-ts-cursor' to the point after the returned char.
5542 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5543 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5544 (let (c)
5545 ;; check for end of buffer
5546 (if (>= js2-ts-cursor (point-max))
5547 (setq js2-ts-hit-eof t
5548 js2-ts-cursor (1+ js2-ts-cursor)
5549 c js2-EOF_CHAR) ; return value
5550 ;; otherwise read next char
5551 (setq c (char-before (cl-incf js2-ts-cursor)))
5552 ;; if we read a newline, update counters
5553 (if (= c ?\n)
5554 (setq js2-ts-line-start js2-ts-cursor
5555 js2-ts-lineno (1+ js2-ts-lineno)))
5556 ;; TODO: skip over format characters
5557 c)))
5558
5559 (defun js2-read-unicode-escape ()
5560 "Read a \\uNNNN sequence from the input.
5561 Assumes the ?\ and ?u have already been read.
5562 Returns the unicode character, or nil if it wasn't a valid character.
5563 Doesn't change the values of any scanner variables."
5564 ;; I really wish I knew a better way to do this, but I can't
5565 ;; find the Emacs function that takes a 16-bit int and converts
5566 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5567 ;; Have to first check that it's 4 hex characters or it may stop
5568 ;; the read early.
5569 (ignore-errors
5570 (let ((s (buffer-substring-no-properties js2-ts-cursor
5571 (+ 4 js2-ts-cursor))))
5572 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5573 (read (concat "?\\u" s))))))
5574
5575 (defun js2-match-char (test)
5576 "Consume and return next character if it matches TEST, a character.
5577 Returns nil and consumes nothing if TEST is not the next character."
5578 (let ((c (js2-get-char)))
5579 (if (eq c test)
5580 t
5581 (js2-unget-char)
5582 nil)))
5583
5584 (defun js2-peek-char ()
5585 (prog1
5586 (js2-get-char)
5587 (js2-unget-char)))
5588
5589 (defun js2-identifier-start-p (c)
5590 "Is C a valid start to an ES5 Identifier?
5591 See http://es5.github.io/#x7.6"
5592 (or
5593 (memq c '(?$ ?_))
5594 (memq (get-char-code-property c 'general-category)
5595 ;; Letters
5596 '(Lu Ll Lt Lm Lo Nl))))
5597
5598 (defun js2-identifier-part-p (c)
5599 "Is C a valid part of an ES5 Identifier?
5600 See http://es5.github.io/#x7.6"
5601 (or
5602 (memq c '(?$ ?_ ?\u200c ?\u200d))
5603 (memq (get-char-code-property c 'general-category)
5604 '(;; Letters
5605 Lu Ll Lt Lm Lo Nl
5606 ;; Combining Marks
5607 Mn Mc
5608 ;; Digits
5609 Nd
5610 ;; Connector Punctuation
5611 Pc))))
5612
5613 (defun js2-alpha-p (c)
5614 (cond ((and (<= ?A c) (<= c ?Z)) t)
5615 ((and (<= ?a c) (<= c ?z)) t)
5616 (t nil)))
5617
5618 (defsubst js2-digit-p (c)
5619 (and (<= ?0 c) (<= c ?9)))
5620
5621 (defun js2-js-space-p (c)
5622 (if (<= c 127)
5623 (memq c '(#x20 #x9 #xB #xC #xD))
5624 (or
5625 (eq c #xA0)
5626 ;; TODO: change this nil to check for Unicode space character
5627 nil)))
5628
5629 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5630
5631 (defun js2-skip-line ()
5632 "Skip to end of line."
5633 (while (not (memq (js2-get-char) js2-eol-chars)))
5634 (js2-unget-char)
5635 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5636
5637 (defun js2-init-scanner (&optional buf line)
5638 "Create token stream for BUF starting on LINE.
5639 BUF defaults to `current-buffer' and LINE defaults to 1.
5640
5641 A buffer can only have one scanner active at a time, which yields
5642 dramatically simpler code than using a defstruct. If you need to
5643 have simultaneous scanners in a buffer, copy the regions to scan
5644 into temp buffers."
5645 (with-current-buffer (or buf (current-buffer))
5646 (setq js2-ts-dirty-line nil
5647 js2-ts-hit-eof nil
5648 js2-ts-line-start 0
5649 js2-ts-lineno (or line 1)
5650 js2-ts-line-end-char -1
5651 js2-ts-cursor (point-min)
5652 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5653 js2-ti-tokens-cursor 0
5654 js2-ti-lookahead 0
5655 js2-ts-is-xml-attribute nil
5656 js2-ts-xml-is-tag-content nil
5657 js2-ts-xml-open-tags-count 0
5658 js2-ts-string-buffer nil)))
5659
5660 ;; This function uses the cached op, string and number fields in
5661 ;; TokenStream; if getToken has been called since the passed token
5662 ;; was scanned, the op or string printed may be incorrect.
5663 (defun js2-token-to-string (token)
5664 ;; Not sure where this function is used in Rhino. Not tested.
5665 (if (not js2-debug-print-trees)
5666 ""
5667 (let ((name (js2-tt-name token)))
5668 (cond
5669 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5670 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5671 (concat name " `" (js2-current-token-string) "'"))
5672 ((eq token js2-NUMBER)
5673 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5674 (t
5675 name)))))
5676
5677 (defconst js2-keywords
5678 '(break
5679 case catch class const continue
5680 debugger default delete do
5681 else extends export
5682 false finally for function
5683 if in instanceof import
5684 let
5685 new null
5686 return
5687 static super switch
5688 this throw true try typeof
5689 var void
5690 while with
5691 yield))
5692
5693 ;; Token names aren't exactly the same as the keywords, unfortunately.
5694 ;; E.g. delete is js2-DELPROP.
5695 (defconst js2-kwd-tokens
5696 (let ((table (make-vector js2-num-tokens nil))
5697 (tokens
5698 (list js2-BREAK
5699 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5700 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5701 js2-ELSE js2-EXPORT
5702 js2-ELSE js2-EXTENDS js2-EXPORT
5703 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5704 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5705 js2-LET
5706 js2-NEW js2-NULL
5707 js2-RETURN
5708 js2-STATIC js2-SUPER js2-SWITCH
5709 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5710 js2-VAR
5711 js2-WHILE js2-WITH
5712 js2-YIELD)))
5713 (dolist (i tokens)
5714 (aset table i 'font-lock-keyword-face))
5715 (aset table js2-STRING 'font-lock-string-face)
5716 (aset table js2-REGEXP 'font-lock-string-face)
5717 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5718 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5719 (aset table js2-COMMENT 'font-lock-comment-face)
5720 (aset table js2-THIS 'font-lock-builtin-face)
5721 (aset table js2-SUPER 'font-lock-builtin-face)
5722 (aset table js2-VOID 'font-lock-constant-face)
5723 (aset table js2-NULL 'font-lock-constant-face)
5724 (aset table js2-TRUE 'font-lock-constant-face)
5725 (aset table js2-FALSE 'font-lock-constant-face)
5726 (aset table js2-NOT 'font-lock-negation-char-face)
5727 table)
5728 "Vector whose values are non-nil for tokens that are keywords.
5729 The values are default faces to use for highlighting the keywords.")
5730
5731 ;; FIXME: Support strict mode-only future reserved words, after we know
5732 ;; which parts scopes are in strict mode, and which are not.
5733 (defconst js2-reserved-words '(class enum export extends import super)
5734 "Future reserved keywords in ECMAScript 5.1.")
5735
5736 (defconst js2-keyword-names
5737 (let ((table (make-hash-table :test 'equal)))
5738 (cl-loop for k in js2-keywords
5739 do (puthash
5740 (symbol-name k) ; instanceof
5741 (intern (concat "js2-"
5742 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5743 table))
5744 table)
5745 "JavaScript keywords by name, mapped to their symbols.")
5746
5747 (defconst js2-reserved-word-names
5748 (let ((table (make-hash-table :test 'equal)))
5749 (cl-loop for k in js2-reserved-words
5750 do
5751 (puthash (symbol-name k) 'js2-RESERVED table))
5752 table)
5753 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5754
5755 (defun js2-collect-string (buf)
5756 "Convert BUF, a list of chars, to a string.
5757 Reverses BUF before converting."
5758 (if buf
5759 (apply #'string (nreverse buf))
5760 ""))
5761
5762 (defun js2-string-to-keyword (s)
5763 "Return token for S, a string, if S is a keyword or reserved word.
5764 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5765 (or (gethash s js2-keyword-names)
5766 (gethash s js2-reserved-word-names)))
5767
5768 (defsubst js2-ts-set-char-token-bounds (token)
5769 "Used when next token is one character."
5770 (setf (js2-token-beg token) (1- js2-ts-cursor)
5771 (js2-token-end token) js2-ts-cursor))
5772
5773 (defsubst js2-ts-return (token type)
5774 "Update the `end' and `type' slots of TOKEN,
5775 then throw `return' with value TYPE."
5776 (setf (js2-token-end token) js2-ts-cursor
5777 (js2-token-type token) type)
5778 (throw 'return type))
5779
5780 (defun js2-x-digit-to-int (c accumulator)
5781 "Build up a hex number.
5782 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5783 corresponding number. Otherwise return -1."
5784 (catch 'return
5785 (catch 'check
5786 ;; Use 0..9 < A..Z < a..z
5787 (cond
5788 ((<= c ?9)
5789 (cl-decf c ?0)
5790 (if (<= 0 c)
5791 (throw 'check nil)))
5792 ((<= c ?F)
5793 (when (<= ?A c)
5794 (cl-decf c (- ?A 10))
5795 (throw 'check nil)))
5796 ((<= c ?f)
5797 (when (<= ?a c)
5798 (cl-decf c (- ?a 10))
5799 (throw 'check nil))))
5800 (throw 'return -1))
5801 (logior c (lsh accumulator 4))))
5802
5803 (defun js2-get-token (&optional modifier)
5804 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5805 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5806 next saved token.
5807
5808 This function will not return a newline (js2-EOL) - instead, it
5809 gobbles newlines until it finds a non-newline token. Call
5810 `js2-peek-token-or-eol' when you care about newlines.
5811
5812 This function will also not return a js2-COMMENT. Instead, it
5813 records comments found in `js2-scanned-comments'. If the token
5814 returned by this function immediately follows a jsdoc comment,
5815 the token is flagged as such."
5816 (if (zerop js2-ti-lookahead)
5817 (js2-get-token-internal modifier)
5818 (cl-decf js2-ti-lookahead)
5819 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5820 (let ((tt (js2-current-token-type)))
5821 (cl-assert (not (= tt js2-EOL)))
5822 tt)))
5823
5824 (defun js2-unget-token ()
5825 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5826 (cl-incf js2-ti-lookahead)
5827 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5828
5829 (defun js2-get-token-internal (modifier)
5830 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5831 (tt (js2-token-type token))
5832 saw-eol
5833 face)
5834 ;; process comments
5835 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5836 (if (= tt js2-EOL)
5837 (setq saw-eol t)
5838 (setq saw-eol nil)
5839 (when js2-record-comments
5840 (js2-record-comment token)))
5841 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5842 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5843 tt (js2-token-type token)))
5844
5845 (when saw-eol
5846 (setf (js2-token-follows-eol-p token) t))
5847
5848 ;; perform lexical fontification as soon as token is scanned
5849 (when js2-parse-ide-mode
5850 (cond
5851 ((cl-minusp tt)
5852 (js2-record-face 'js2-error token))
5853 ((setq face (aref js2-kwd-tokens tt))
5854 (js2-record-face face token))
5855 ((and (= tt js2-NAME)
5856 (equal (js2-token-string token) "undefined"))
5857 (js2-record-face 'font-lock-constant-face token))))
5858 tt))
5859
5860 (defsubst js2-string-to-number (str base)
5861 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5862 (condition-case nil
5863 (string-to-number str base)
5864 (overflow-error -1)))
5865
5866 (defun js2-get-token-internal-1 (modifier)
5867 "Return next JavaScript token type, an int such as js2-RETURN.
5868 During operation, creates an instance of `js2-token' struct, sets
5869 its relevant fields and puts it into `js2-ti-tokens'."
5870 (let (identifier-start
5871 is-unicode-escape-start c
5872 contains-escape escape-val str result base
5873 quote-char look-for-slash continue tt
5874 (token (js2-new-token 0)))
5875 (setq
5876 tt
5877 (catch 'return
5878 (when (eq modifier 'TEMPLATE_TAIL)
5879 (setf (js2-token-beg token) (1- js2-ts-cursor))
5880 (throw 'return (js2-get-string-or-template-token ?` token)))
5881 (while t
5882 ;; Eat whitespace, possibly sensitive to newlines.
5883 (setq continue t)
5884 (while continue
5885 (setq c (js2-get-char))
5886 (cond
5887 ((eq c js2-EOF_CHAR)
5888 (js2-unget-char)
5889 (js2-ts-set-char-token-bounds token)
5890 (throw 'return js2-EOF))
5891 ((eq c ?\n)
5892 (js2-ts-set-char-token-bounds token)
5893 (setq js2-ts-dirty-line nil)
5894 (throw 'return js2-EOL))
5895 ((not (js2-js-space-p c))
5896 (if (/= c ?-) ; in case end of HTML comment
5897 (setq js2-ts-dirty-line t))
5898 (setq continue nil))))
5899 ;; Assume the token will be 1 char - fixed up below.
5900 (js2-ts-set-char-token-bounds token)
5901 (when (eq c ?@)
5902 (throw 'return js2-XMLATTR))
5903 ;; identifier/keyword/instanceof?
5904 ;; watch out for starting with a <backslash>
5905 (cond
5906 ((eq c ?\\)
5907 (setq c (js2-get-char))
5908 (if (eq c ?u)
5909 (setq identifier-start t
5910 is-unicode-escape-start t
5911 js2-ts-string-buffer nil)
5912 (setq identifier-start nil)
5913 (js2-unget-char)
5914 (setq c ?\\)))
5915 (t
5916 (when (setq identifier-start (js2-identifier-start-p c))
5917 (setq js2-ts-string-buffer nil)
5918 (js2-add-to-string c))))
5919 (when identifier-start
5920 (setq contains-escape is-unicode-escape-start)
5921 (catch 'break
5922 (while t
5923 (if is-unicode-escape-start
5924 ;; strictly speaking we should probably push-back
5925 ;; all the bad characters if the <backslash>uXXXX
5926 ;; sequence is malformed. But since there isn't a
5927 ;; correct context(is there?) for a bad Unicode
5928 ;; escape sequence in an identifier, we can report
5929 ;; an error here.
5930 (progn
5931 (setq escape-val 0)
5932 (dotimes (_ 4)
5933 (setq c (js2-get-char)
5934 escape-val (js2-x-digit-to-int c escape-val))
5935 ;; Next check takes care of c < 0 and bad escape
5936 (if (cl-minusp escape-val)
5937 (throw 'break nil)))
5938 (if (cl-minusp escape-val)
5939 (js2-report-scan-error "msg.invalid.escape" t))
5940 (js2-add-to-string escape-val)
5941 (setq is-unicode-escape-start nil))
5942 (setq c (js2-get-char))
5943 (cond
5944 ((eq c ?\\)
5945 (setq c (js2-get-char))
5946 (if (eq c ?u)
5947 (setq is-unicode-escape-start t
5948 contains-escape t)
5949 (js2-report-scan-error "msg.illegal.character" t)))
5950 (t
5951 (if (or (eq c js2-EOF_CHAR)
5952 (not (js2-identifier-part-p c)))
5953 (throw 'break nil))
5954 (js2-add-to-string c))))))
5955 (js2-unget-char)
5956 (setf str (js2-collect-string js2-ts-string-buffer)
5957 (js2-token-end token) js2-ts-cursor)
5958 ;; FIXME: Invalid in ES5 and ES6, see
5959 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5960 ;; Probably should just drop this conditional.
5961 (unless contains-escape
5962 ;; OPT we shouldn't have to make a string (object!) to
5963 ;; check if it's a keyword.
5964 ;; Return the corresponding token if it's a keyword
5965 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5966 (setq result (js2-string-to-keyword str)))
5967 (if (and (< js2-language-version 170)
5968 (memq result '(js2-LET js2-YIELD)))
5969 ;; LET and YIELD are tokens only in 1.7 and later
5970 (setq result 'js2-NAME))
5971 (when (eq result 'js2-RESERVED)
5972 (setf (js2-token-string token) str))
5973 (throw 'return (js2-tt-code result))))
5974 ;; If we want to intern these as Rhino does, just use (intern str)
5975 (setf (js2-token-string token) str)
5976 (throw 'return js2-NAME)) ; end identifier/kwd check
5977 ;; is it a number?
5978 (when (or (js2-digit-p c)
5979 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5980 (setq js2-ts-string-buffer nil
5981 base 10)
5982 (when (eq c ?0)
5983 (setq c (js2-get-char))
5984 (cond
5985 ((or (eq c ?x) (eq c ?X))
5986 (setq base 16)
5987 (setq c (js2-get-char)))
5988 ((and (or (eq c ?b) (eq c ?B))
5989 (>= js2-language-version 200))
5990 (setq base 2)
5991 (setq c (js2-get-char)))
5992 ((and (or (eq c ?o) (eq c ?O))
5993 (>= js2-language-version 200))
5994 (setq base 8)
5995 (setq c (js2-get-char)))
5996 ((js2-digit-p c)
5997 (setq base 'maybe-8))
5998 (t
5999 (js2-add-to-string ?0))))
6000 (cond
6001 ((eq base 16)
6002 (if (> 0 (js2-x-digit-to-int c 0))
6003 (js2-report-scan-error "msg.missing.hex.digits")
6004 (while (<= 0 (js2-x-digit-to-int c 0))
6005 (js2-add-to-string c)
6006 (setq c (js2-get-char)))))
6007 ((eq base 2)
6008 (if (not (memq c '(?0 ?1)))
6009 (js2-report-scan-error "msg.missing.binary.digits")
6010 (while (memq c '(?0 ?1))
6011 (js2-add-to-string c)
6012 (setq c (js2-get-char)))))
6013 ((eq base 8)
6014 (if (or (> ?0 c) (< ?7 c))
6015 (js2-report-scan-error "msg.missing.octal.digits")
6016 (while (and (<= ?0 c) (>= ?7 c))
6017 (js2-add-to-string c)
6018 (setq c (js2-get-char)))))
6019 (t
6020 (while (and (<= ?0 c) (<= c ?9))
6021 ;; We permit 08 and 09 as decimal numbers, which
6022 ;; makes our behavior a superset of the ECMA
6023 ;; numeric grammar. We might not always be so
6024 ;; permissive, so we warn about it.
6025 (when (and (eq base 'maybe-8) (>= c ?8))
6026 (js2-report-warning "msg.bad.octal.literal"
6027 (if (eq c ?8) "8" "9"))
6028 (setq base 10))
6029 (js2-add-to-string c)
6030 (setq c (js2-get-char)))
6031 (when (eq base 'maybe-8)
6032 (setq base 8))))
6033 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6034 (when (eq c ?.)
6035 (cl-loop do
6036 (js2-add-to-string c)
6037 (setq c (js2-get-char))
6038 while (js2-digit-p c)))
6039 (when (memq c '(?e ?E))
6040 (js2-add-to-string c)
6041 (setq c (js2-get-char))
6042 (when (memq c '(?+ ?-))
6043 (js2-add-to-string c)
6044 (setq c (js2-get-char)))
6045 (unless (js2-digit-p c)
6046 (js2-report-scan-error "msg.missing.exponent" t))
6047 (cl-loop do
6048 (js2-add-to-string c)
6049 (setq c (js2-get-char))
6050 while (js2-digit-p c))))
6051 (js2-unget-char)
6052 (let ((str (js2-set-string-from-buffer token)))
6053 (setf (js2-token-number token)
6054 (js2-string-to-number str base)))
6055 (throw 'return js2-NUMBER))
6056 ;; is it a string?
6057 (when (or (memq c '(?\" ?\'))
6058 (and (>= js2-language-version 200)
6059 (= c ?`)))
6060 (throw 'return
6061 (js2-get-string-or-template-token c token)))
6062 (js2-ts-return token
6063 (cl-case c
6064 (?\;
6065 (throw 'return js2-SEMI))
6066 (?\[
6067 (throw 'return js2-LB))
6068 (?\]
6069 (throw 'return js2-RB))
6070 (?{
6071 (throw 'return js2-LC))
6072 (?}
6073 (throw 'return js2-RC))
6074 (?\(
6075 (throw 'return js2-LP))
6076 (?\)
6077 (throw 'return js2-RP))
6078 (?,
6079 (throw 'return js2-COMMA))
6080 (??
6081 (throw 'return js2-HOOK))
6082 (?:
6083 (if (js2-match-char ?:)
6084 js2-COLONCOLON
6085 (throw 'return js2-COLON)))
6086 (?.
6087 (if (js2-match-char ?.)
6088 (if (js2-match-char ?.)
6089 js2-TRIPLEDOT js2-DOTDOT)
6090 (if (js2-match-char ?\()
6091 js2-DOTQUERY
6092 (throw 'return js2-DOT))))
6093 (?|
6094 (if (js2-match-char ?|)
6095 (throw 'return js2-OR)
6096 (if (js2-match-char ?=)
6097 js2-ASSIGN_BITOR
6098 (throw 'return js2-BITOR))))
6099 (?^
6100 (if (js2-match-char ?=)
6101 js2-ASSIGN_BITOR
6102 (throw 'return js2-BITXOR)))
6103 (?&
6104 (if (js2-match-char ?&)
6105 (throw 'return js2-AND)
6106 (if (js2-match-char ?=)
6107 js2-ASSIGN_BITAND
6108 (throw 'return js2-BITAND))))
6109 (?=
6110 (if (js2-match-char ?=)
6111 (if (js2-match-char ?=)
6112 js2-SHEQ
6113 (throw 'return js2-EQ))
6114 (if (js2-match-char ?>)
6115 (js2-ts-return token js2-ARROW)
6116 (throw 'return js2-ASSIGN))))
6117 (?!
6118 (if (js2-match-char ?=)
6119 (if (js2-match-char ?=)
6120 js2-SHNE
6121 js2-NE)
6122 (throw 'return js2-NOT)))
6123 (?<
6124 ;; NB:treat HTML begin-comment as comment-till-eol
6125 (when (js2-match-char ?!)
6126 (when (js2-match-char ?-)
6127 (when (js2-match-char ?-)
6128 (js2-skip-line)
6129 (setf (js2-token-comment-type (js2-current-token)) 'html)
6130 (throw 'return js2-COMMENT)))
6131 (js2-unget-char))
6132 (if (js2-match-char ?<)
6133 (if (js2-match-char ?=)
6134 js2-ASSIGN_LSH
6135 js2-LSH)
6136 (if (js2-match-char ?=)
6137 js2-LE
6138 (throw 'return js2-LT))))
6139 (?>
6140 (if (js2-match-char ?>)
6141 (if (js2-match-char ?>)
6142 (if (js2-match-char ?=)
6143 js2-ASSIGN_URSH
6144 js2-URSH)
6145 (if (js2-match-char ?=)
6146 js2-ASSIGN_RSH
6147 js2-RSH))
6148 (if (js2-match-char ?=)
6149 js2-GE
6150 (throw 'return js2-GT))))
6151 (?*
6152 (if (js2-match-char ?=)
6153 js2-ASSIGN_MUL
6154 (throw 'return js2-MUL)))
6155 (?/
6156 ;; is it a // comment?
6157 (when (js2-match-char ?/)
6158 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6159 (js2-skip-line)
6160 (setf (js2-token-comment-type token) 'line)
6161 ;; include newline so highlighting goes to end of window
6162 (cl-incf (js2-token-end token))
6163 (throw 'return js2-COMMENT))
6164 ;; is it a /* comment?
6165 (when (js2-match-char ?*)
6166 (setf look-for-slash nil
6167 (js2-token-beg token) (- js2-ts-cursor 2)
6168 (js2-token-comment-type token)
6169 (if (js2-match-char ?*)
6170 (progn
6171 (setq look-for-slash t)
6172 'jsdoc)
6173 'block))
6174 (while t
6175 (setq c (js2-get-char))
6176 (cond
6177 ((eq c js2-EOF_CHAR)
6178 (setf (js2-token-end token) (1- js2-ts-cursor))
6179 (js2-report-error "msg.unterminated.comment")
6180 (throw 'return js2-COMMENT))
6181 ((eq c ?*)
6182 (setq look-for-slash t))
6183 ((eq c ?/)
6184 (if look-for-slash
6185 (js2-ts-return token js2-COMMENT)))
6186 (t
6187 (setf look-for-slash nil
6188 (js2-token-end token) js2-ts-cursor)))))
6189 (if (js2-match-char ?=)
6190 js2-ASSIGN_DIV
6191 (throw 'return js2-DIV)))
6192 (?#
6193 (when js2-skip-preprocessor-directives
6194 (js2-skip-line)
6195 (setf (js2-token-comment-type token) 'preprocessor
6196 (js2-token-end token) js2-ts-cursor)
6197 (throw 'return js2-COMMENT))
6198 (throw 'return js2-ERROR))
6199 (?%
6200 (if (js2-match-char ?=)
6201 js2-ASSIGN_MOD
6202 (throw 'return js2-MOD)))
6203 (?~
6204 (throw 'return js2-BITNOT))
6205 (?+
6206 (if (js2-match-char ?=)
6207 js2-ASSIGN_ADD
6208 (if (js2-match-char ?+)
6209 js2-INC
6210 (throw 'return js2-ADD))))
6211 (?-
6212 (cond
6213 ((js2-match-char ?=)
6214 (setq c js2-ASSIGN_SUB))
6215 ((js2-match-char ?-)
6216 (unless js2-ts-dirty-line
6217 ;; treat HTML end-comment after possible whitespace
6218 ;; after line start as comment-until-eol
6219 (when (js2-match-char ?>)
6220 (js2-skip-line)
6221 (setf (js2-token-comment-type (js2-current-token)) 'html)
6222 (throw 'return js2-COMMENT)))
6223 (setq c js2-DEC))
6224 (t
6225 (setq c js2-SUB)))
6226 (setq js2-ts-dirty-line t)
6227 c)
6228 (otherwise
6229 (js2-report-scan-error "msg.illegal.character")))))))
6230 (setf (js2-token-type token) tt)
6231 token))
6232
6233 (defun js2-get-string-or-template-token (quote-char token)
6234 ;; We attempt to accumulate a string the fast way, by
6235 ;; building it directly out of the reader. But if there
6236 ;; are any escaped characters in the string, we revert to
6237 ;; building it out of a string buffer.
6238 (let ((c (js2-get-char))
6239 js2-ts-string-buffer
6240 nc c1 val escape-val)
6241 (catch 'break
6242 (while (/= c quote-char)
6243 (catch 'continue
6244 (when (eq c js2-EOF_CHAR)
6245 (js2-unget-char)
6246 (js2-report-error "msg.unterminated.string.lit")
6247 (throw 'break nil))
6248 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6249 (js2-unget-char)
6250 (js2-report-error "msg.unterminated.string.lit")
6251 (throw 'break nil))
6252 (when (eq c ?\\)
6253 ;; We've hit an escaped character
6254 (setq c (js2-get-char))
6255 (cl-case c
6256 (?b (setq c ?\b))
6257 (?f (setq c ?\f))
6258 (?n (setq c ?\n))
6259 (?r (setq c ?\r))
6260 (?t (setq c ?\t))
6261 (?v (setq c ?\v))
6262 (?u
6263 (setq c1 (js2-read-unicode-escape))
6264 (if js2-parse-ide-mode
6265 (if c1
6266 (progn
6267 ;; just copy the string in IDE-mode
6268 (js2-add-to-string ?\\)
6269 (js2-add-to-string ?u)
6270 (dotimes (_ 3)
6271 (js2-add-to-string (js2-get-char)))
6272 (setq c (js2-get-char))) ; added at end of loop
6273 ;; flag it as an invalid escape
6274 (js2-report-warning "msg.invalid.escape"
6275 nil (- js2-ts-cursor 2) 6))
6276 ;; Get 4 hex digits; if the u escape is not
6277 ;; followed by 4 hex digits, use 'u' + the
6278 ;; literal character sequence that follows.
6279 (js2-add-to-string ?u)
6280 (setq escape-val 0)
6281 (dotimes (_ 4)
6282 (setq c (js2-get-char)
6283 escape-val (js2-x-digit-to-int c escape-val))
6284 (if (cl-minusp escape-val)
6285 (throw 'continue nil))
6286 (js2-add-to-string c))
6287 ;; prepare for replace of stored 'u' sequence by escape value
6288 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6289 c escape-val)))
6290 (?x
6291 ;; Get 2 hex digits, defaulting to 'x'+literal
6292 ;; sequence, as above.
6293 (setq c (js2-get-char)
6294 escape-val (js2-x-digit-to-int c 0))
6295 (if (cl-minusp escape-val)
6296 (progn
6297 (js2-add-to-string ?x)
6298 (throw 'continue nil))
6299 (setq c1 c
6300 c (js2-get-char)
6301 escape-val (js2-x-digit-to-int c escape-val))
6302 (if (cl-minusp escape-val)
6303 (progn
6304 (js2-add-to-string ?x)
6305 (js2-add-to-string c1)
6306 (throw 'continue nil))
6307 ;; got 2 hex digits
6308 (setq c escape-val))))
6309 (?\n
6310 ;; Remove line terminator after escape to follow
6311 ;; SpiderMonkey and C/C++
6312 (setq c (js2-get-char))
6313 (throw 'continue nil))
6314 (t
6315 (when (and (<= ?0 c) (< c ?8))
6316 (setq val (- c ?0)
6317 c (js2-get-char))
6318 (when (and (<= ?0 c) (< c ?8))
6319 (setq val (- (+ (* 8 val) c) ?0)
6320 c (js2-get-char))
6321 (when (and (<= ?0 c)
6322 (< c ?8)
6323 (< val #o37))
6324 ;; c is 3rd char of octal sequence only
6325 ;; if the resulting val <= 0377
6326 (setq val (- (+ (* 8 val) c) ?0)
6327 c (js2-get-char))))
6328 (js2-unget-char)
6329 (setq c val)))))
6330 (when (and (eq quote-char ?`) (eq c ?$))
6331 (when (eq (setq nc (js2-get-char)) ?\{)
6332 (throw 'break nil))
6333 (js2-unget-char))
6334 (js2-add-to-string c)
6335 (setq c (js2-get-char)))))
6336 (js2-set-string-from-buffer token)
6337 (if (not (eq quote-char ?`))
6338 js2-STRING
6339 (if (and (eq c ?$) (eq nc ?\{))
6340 js2-TEMPLATE_HEAD
6341 js2-NO_SUBS_TEMPLATE))))
6342
6343 (defun js2-read-regexp (start-tt)
6344 "Called by parser when it gets / or /= in literal context."
6345 (let (c err
6346 in-class ; inside a '[' .. ']' character-class
6347 flags
6348 (continue t)
6349 (token (js2-new-token 0)))
6350 (setq js2-ts-string-buffer nil)
6351 (if (eq start-tt js2-ASSIGN_DIV)
6352 ;; mis-scanned /=
6353 (js2-add-to-string ?=)
6354 (if (not (eq start-tt js2-DIV))
6355 (error "failed assertion")))
6356 (while (and (not err)
6357 (or (/= (setq c (js2-get-char)) ?/)
6358 in-class))
6359 (cond
6360 ((or (= c ?\n)
6361 (= c js2-EOF_CHAR))
6362 (setf (js2-token-end token) (1- js2-ts-cursor)
6363 err t
6364 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6365 (js2-report-error "msg.unterminated.re.lit"))
6366 (t (cond
6367 ((= c ?\\)
6368 (js2-add-to-string c)
6369 (setq c (js2-get-char)))
6370 ((= c ?\[)
6371 (setq in-class t))
6372 ((= c ?\])
6373 (setq in-class nil)))
6374 (js2-add-to-string c))))
6375 (unless err
6376 (while continue
6377 (cond
6378 ((js2-match-char ?g)
6379 (push ?g flags))
6380 ((js2-match-char ?i)
6381 (push ?i flags))
6382 ((js2-match-char ?m)
6383 (push ?m flags))
6384 ((and (js2-match-char ?u)
6385 (>= js2-language-version 200))
6386 (push ?u flags))
6387 ((and (js2-match-char ?y)
6388 (>= js2-language-version 200))
6389 (push ?y flags))
6390 (t
6391 (setq continue nil))))
6392 (if (js2-alpha-p (js2-peek-char))
6393 (js2-report-scan-error "msg.invalid.re.flag" t
6394 js2-ts-cursor 1))
6395 (js2-set-string-from-buffer token))
6396 (js2-collect-string flags)))
6397
6398 (defun js2-get-first-xml-token ()
6399 (setq js2-ts-xml-open-tags-count 0
6400 js2-ts-is-xml-attribute nil
6401 js2-ts-xml-is-tag-content nil)
6402 (js2-unget-char)
6403 (js2-get-next-xml-token))
6404
6405 (defun js2-xml-discard-string (token)
6406 "Throw away the string in progress and flag an XML parse error."
6407 (setf js2-ts-string-buffer nil
6408 (js2-token-string token) nil)
6409 (js2-report-scan-error "msg.XML.bad.form" t))
6410
6411 (defun js2-get-next-xml-token ()
6412 (setq js2-ts-string-buffer nil) ; for recording the XML
6413 (let ((token (js2-new-token 0))
6414 c result)
6415 (setq result
6416 (catch 'return
6417 (while t
6418 (setq c (js2-get-char))
6419 (cond
6420 ((= c js2-EOF_CHAR)
6421 (throw 'return js2-ERROR))
6422 (js2-ts-xml-is-tag-content
6423 (cl-case c
6424 (?>
6425 (js2-add-to-string c)
6426 (setq js2-ts-xml-is-tag-content nil
6427 js2-ts-is-xml-attribute nil))
6428 (?/
6429 (js2-add-to-string c)
6430 (when (eq ?> (js2-peek-char))
6431 (setq c (js2-get-char))
6432 (js2-add-to-string c)
6433 (setq js2-ts-xml-is-tag-content nil)
6434 (cl-decf js2-ts-xml-open-tags-count)))
6435 (?{
6436 (js2-unget-char)
6437 (js2-set-string-from-buffer token)
6438 (throw 'return js2-XML))
6439 ((?\' ?\")
6440 (js2-add-to-string c)
6441 (unless (js2-read-quoted-string c token)
6442 (throw 'return js2-ERROR)))
6443 (?=
6444 (js2-add-to-string c)
6445 (setq js2-ts-is-xml-attribute t))
6446 ((? ?\t ?\r ?\n)
6447 (js2-add-to-string c))
6448 (t
6449 (js2-add-to-string c)
6450 (setq js2-ts-is-xml-attribute nil)))
6451 (when (and (not js2-ts-xml-is-tag-content)
6452 (zerop js2-ts-xml-open-tags-count))
6453 (js2-set-string-from-buffer token)
6454 (throw 'return js2-XMLEND)))
6455 (t
6456 ;; else not tag content
6457 (cl-case c
6458 (?<
6459 (js2-add-to-string c)
6460 (setq c (js2-peek-char))
6461 (cl-case c
6462 (?!
6463 (setq c (js2-get-char)) ;; skip !
6464 (js2-add-to-string c)
6465 (setq c (js2-peek-char))
6466 (cl-case c
6467 (?-
6468 (setq c (js2-get-char)) ;; skip -
6469 (js2-add-to-string c)
6470 (if (eq c ?-)
6471 (progn
6472 (js2-add-to-string c)
6473 (unless (js2-read-xml-comment token)
6474 (throw 'return js2-ERROR)))
6475 (js2-xml-discard-string token)
6476 (throw 'return js2-ERROR)))
6477 (?\[
6478 (setq c (js2-get-char)) ;; skip [
6479 (js2-add-to-string c)
6480 (if (and (= (js2-get-char) ?C)
6481 (= (js2-get-char) ?D)
6482 (= (js2-get-char) ?A)
6483 (= (js2-get-char) ?T)
6484 (= (js2-get-char) ?A)
6485 (= (js2-get-char) ?\[))
6486 (progn
6487 (js2-add-to-string ?C)
6488 (js2-add-to-string ?D)
6489 (js2-add-to-string ?A)
6490 (js2-add-to-string ?T)
6491 (js2-add-to-string ?A)
6492 (js2-add-to-string ?\[)
6493 (unless (js2-read-cdata token)
6494 (throw 'return js2-ERROR)))
6495 (js2-xml-discard-string token)
6496 (throw 'return js2-ERROR)))
6497 (t
6498 (unless (js2-read-entity token)
6499 (throw 'return js2-ERROR))))
6500 ;; Allow bare CDATA section, e.g.:
6501 ;; let xml = <![CDATA[ foo bar baz ]]>;
6502 (when (zerop js2-ts-xml-open-tags-count)
6503 (throw 'return js2-XMLEND)))
6504 (??
6505 (setq c (js2-get-char)) ;; skip ?
6506 (js2-add-to-string c)
6507 (unless (js2-read-PI token)
6508 (throw 'return js2-ERROR)))
6509 (?/
6510 ;; end tag
6511 (setq c (js2-get-char)) ;; skip /
6512 (js2-add-to-string c)
6513 (when (zerop js2-ts-xml-open-tags-count)
6514 (js2-xml-discard-string token)
6515 (throw 'return js2-ERROR))
6516 (setq js2-ts-xml-is-tag-content t)
6517 (cl-decf js2-ts-xml-open-tags-count))
6518 (t
6519 ;; start tag
6520 (setq js2-ts-xml-is-tag-content t)
6521 (cl-incf js2-ts-xml-open-tags-count))))
6522 (?{
6523 (js2-unget-char)
6524 (js2-set-string-from-buffer token)
6525 (throw 'return js2-XML))
6526 (t
6527 (js2-add-to-string c))))))))
6528 (setf (js2-token-end token) js2-ts-cursor)
6529 (setf (js2-token-type token) result)
6530 result))
6531
6532 (defun js2-read-quoted-string (quote token)
6533 (let (c)
6534 (catch 'return
6535 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6536 (js2-add-to-string c)
6537 (if (eq c quote)
6538 (throw 'return t)))
6539 (js2-xml-discard-string token) ;; throw away string in progress
6540 nil)))
6541
6542 (defun js2-read-xml-comment (token)
6543 (let ((c (js2-get-char)))
6544 (catch 'return
6545 (while (/= c js2-EOF_CHAR)
6546 (catch 'continue
6547 (js2-add-to-string c)
6548 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6549 (setq c (js2-get-char))
6550 (js2-add-to-string c)
6551 (if (eq (js2-peek-char) ?>)
6552 (progn
6553 (setq c (js2-get-char)) ;; skip >
6554 (js2-add-to-string c)
6555 (throw 'return t))
6556 (throw 'continue nil)))
6557 (setq c (js2-get-char))))
6558 (js2-xml-discard-string token)
6559 nil)))
6560
6561 (defun js2-read-cdata (token)
6562 (let ((c (js2-get-char)))
6563 (catch 'return
6564 (while (/= c js2-EOF_CHAR)
6565 (catch 'continue
6566 (js2-add-to-string c)
6567 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6568 (setq c (js2-get-char))
6569 (js2-add-to-string c)
6570 (if (eq (js2-peek-char) ?>)
6571 (progn
6572 (setq c (js2-get-char)) ;; Skip >
6573 (js2-add-to-string c)
6574 (throw 'return t))
6575 (throw 'continue nil)))
6576 (setq c (js2-get-char))))
6577 (js2-xml-discard-string token)
6578 nil)))
6579
6580 (defun js2-read-entity (token)
6581 (let ((decl-tags 1)
6582 c)
6583 (catch 'return
6584 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6585 (js2-add-to-string c)
6586 (cl-case c
6587 (?<
6588 (cl-incf decl-tags))
6589 (?>
6590 (cl-decf decl-tags)
6591 (if (zerop decl-tags)
6592 (throw 'return t)))))
6593 (js2-xml-discard-string token)
6594 nil)))
6595
6596 (defun js2-read-PI (token)
6597 "Scan an XML processing instruction."
6598 (let (c)
6599 (catch 'return
6600 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6601 (js2-add-to-string c)
6602 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6603 (setq c (js2-get-char)) ;; Skip >
6604 (js2-add-to-string c)
6605 (throw 'return t)))
6606 (js2-xml-discard-string token)
6607 nil)))
6608
6609 ;;; Highlighting
6610
6611 (defun js2-set-face (beg end face &optional record)
6612 "Fontify a region. If RECORD is non-nil, record for later."
6613 (when (cl-plusp js2-highlight-level)
6614 (setq beg (min (point-max) beg)
6615 beg (max (point-min) beg)
6616 end (min (point-max) end)
6617 end (max (point-min) end))
6618 (if record
6619 (push (list beg end face) js2-mode-fontifications)
6620 (put-text-property beg end 'font-lock-face face))))
6621
6622 (defsubst js2-clear-face (beg end)
6623 (remove-text-properties beg end '(font-lock-face nil
6624 help-echo nil
6625 point-entered nil
6626 c-in-sws nil)))
6627
6628 (defconst js2-ecma-global-props
6629 (concat "^"
6630 (regexp-opt
6631 '("Infinity" "NaN" "undefined" "arguments") t)
6632 "$")
6633 "Value properties of the Ecma-262 Global Object.
6634 Shown at or above `js2-highlight-level' 2.")
6635
6636 ;; might want to add the name "arguments" to this list?
6637 (defconst js2-ecma-object-props
6638 (concat "^"
6639 (regexp-opt
6640 '("prototype" "__proto__" "__parent__") t)
6641 "$")
6642 "Value properties of the Ecma-262 Object constructor.
6643 Shown at or above `js2-highlight-level' 2.")
6644
6645 (defconst js2-ecma-global-funcs
6646 (concat
6647 "^"
6648 (regexp-opt
6649 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6650 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6651 "$")
6652 "Function properties of the Ecma-262 Global object.
6653 Shown at or above `js2-highlight-level' 2.")
6654
6655 (defconst js2-ecma-number-props
6656 (concat "^"
6657 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6658 "NEGATIVE_INFINITY"
6659 "POSITIVE_INFINITY") t)
6660 "$")
6661 "Properties of the Ecma-262 Number constructor.
6662 Shown at or above `js2-highlight-level' 2.")
6663
6664 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6665 "Properties of the Ecma-262 Date constructor.
6666 Shown at or above `js2-highlight-level' 2.")
6667
6668 (defconst js2-ecma-math-props
6669 (concat "^"
6670 (regexp-opt
6671 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6672 t)
6673 "$")
6674 "Properties of the Ecma-262 Math object.
6675 Shown at or above `js2-highlight-level' 2.")
6676
6677 (defconst js2-ecma-math-funcs
6678 (concat "^"
6679 (regexp-opt
6680 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6681 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6682 "$")
6683 "Function properties of the Ecma-262 Math object.
6684 Shown at or above `js2-highlight-level' 2.")
6685
6686 (defconst js2-ecma-function-props
6687 (concat
6688 "^"
6689 (regexp-opt
6690 '(;; properties of the Object prototype object
6691 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6692 "toLocaleString" "toString" "valueOf"
6693 ;; properties of the Function prototype object
6694 "apply" "call"
6695 ;; properties of the Array prototype object
6696 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6697 "splice" "unshift"
6698 ;; properties of the String prototype object
6699 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6700 "localeCompare" "match" "replace" "search" "split" "substring"
6701 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6702 "toUpperCase"
6703 ;; properties of the Number prototype object
6704 "toExponential" "toFixed" "toPrecision"
6705 ;; properties of the Date prototype object
6706 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6707 "getMinutes" "getMonth" "getSeconds" "getTime"
6708 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6709 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6710 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6711 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6712 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6713 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6714 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6715 "toTimeString" "toUTCString"
6716 ;; properties of the RegExp prototype object
6717 "exec" "test"
6718 ;; properties of the JSON prototype object
6719 "parse" "stringify"
6720 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6721 "toSource" "__defineGetter__" "__defineSetter__"
6722 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6723 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6724 t)
6725 "$")
6726 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6727 Shown at or above `js2-highlight-level' 3.")
6728
6729 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6730 (let ((target-name (and target
6731 (js2-name-node-p target)
6732 (js2-name-node-name target)))
6733 (prop-name (if prop (js2-name-node-name prop)))
6734 (level2 (>= js2-highlight-level 2))
6735 (level3 (>= js2-highlight-level 3)))
6736 (when level2
6737 (let ((face
6738 (if call-p
6739 (cond
6740 ((and target prop)
6741 (cond
6742 ((and level3 (string-match js2-ecma-function-props prop-name))
6743 'font-lock-builtin-face)
6744 ((and target-name prop)
6745 (cond
6746 ((string= target-name "Date")
6747 (if (string-match js2-ecma-date-props prop-name)
6748 'font-lock-builtin-face))
6749 ((string= target-name "Math")
6750 (if (string-match js2-ecma-math-funcs prop-name)
6751 'font-lock-builtin-face))))))
6752 (prop
6753 (if (string-match js2-ecma-global-funcs prop-name)
6754 'font-lock-builtin-face)))
6755 (cond
6756 ((and target prop)
6757 (cond
6758 ((string= target-name "Number")
6759 (if (string-match js2-ecma-number-props prop-name)
6760 'font-lock-constant-face))
6761 ((string= target-name "Math")
6762 (if (string-match js2-ecma-math-props prop-name)
6763 'font-lock-constant-face))))
6764 (prop
6765 (if (string-match js2-ecma-object-props prop-name)
6766 'font-lock-constant-face))))))
6767 (when face
6768 (let ((pos (+ (js2-node-pos parent) ; absolute
6769 (js2-node-pos prop)))) ; relative
6770 (js2-set-face pos
6771 (+ pos (js2-node-len prop))
6772 face 'record)))))))
6773
6774 (defun js2-parse-highlight-member-expr-node (node)
6775 "Perform syntax highlighting of EcmaScript built-in properties.
6776 The variable `js2-highlight-level' governs this highighting."
6777 (let (face target prop name pos end parent call-p callee)
6778 (cond
6779 ;; case 1: simple name, e.g. foo
6780 ((js2-name-node-p node)
6781 (setq name (js2-name-node-name node))
6782 ;; possible for name to be nil in rare cases - saw it when
6783 ;; running js2-mode on an elisp buffer. Might as well try to
6784 ;; make it so js2-mode never barfs.
6785 (when name
6786 (setq face (if (string-match js2-ecma-global-props name)
6787 'font-lock-constant-face))
6788 (when face
6789 (setq pos (js2-node-pos node)
6790 end (+ pos (js2-node-len node)))
6791 (js2-set-face pos end face 'record))))
6792 ;; case 2: property access or function call
6793 ((or (js2-prop-get-node-p node)
6794 ;; highlight function call if expr is a prop-get node
6795 ;; or a plain name (i.e. unqualified function call)
6796 (and (setq call-p (js2-call-node-p node))
6797 (setq callee (js2-call-node-target node)) ; separate setq!
6798 (or (js2-prop-get-node-p callee)
6799 (js2-name-node-p callee))))
6800 (setq parent node
6801 node (if call-p callee node))
6802 (if (and call-p (js2-name-node-p callee))
6803 (setq prop callee)
6804 (setq target (js2-prop-get-node-left node)
6805 prop (js2-prop-get-node-right node)))
6806 (cond
6807 ((js2-name-node-p prop)
6808 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6809 (js2-parse-highlight-prop-get parent target prop call-p))
6810 ((js2-name-node-p target)
6811 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6812 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6813
6814 (defun js2-parse-highlight-member-expr-fn-name (expr)
6815 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6816 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6817 We currently only handle the case where the last component is a prop-get
6818 of a simple name. Called before EXPR has a parent node."
6819 (let (pos
6820 (name (and (js2-prop-get-node-p expr)
6821 (js2-prop-get-node-right expr))))
6822 (when (js2-name-node-p name)
6823 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6824 (js2-node-pos name)))
6825 (+ pos (js2-node-len name))
6826 'font-lock-function-name-face
6827 'record))))
6828
6829 ;; source: http://jsdoc.sourceforge.net/
6830 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6831 ;; allows type specifications, and needs work before entering the wild.
6832
6833 (defconst js2-jsdoc-param-tag-regexp
6834 (concat "^\\s-*\\*+\\s-*\\(@"
6835 "\\(?:param\\|argument\\)"
6836 "\\)"
6837 "\\s-*\\({[^}]+}\\)?" ; optional type
6838 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6839 "\\>")
6840 "Matches jsdoc tags with optional type and optional param name.")
6841
6842 (defconst js2-jsdoc-typed-tag-regexp
6843 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6844 (regexp-opt
6845 '("enum"
6846 "extends"
6847 "field"
6848 "id"
6849 "implements"
6850 "lends"
6851 "mods"
6852 "requires"
6853 "return"
6854 "returns"
6855 "throw"
6856 "throws"))
6857 "\\)\\)\\s-*\\({[^}]+}\\)?")
6858 "Matches jsdoc tags with optional type.")
6859
6860 (defconst js2-jsdoc-arg-tag-regexp
6861 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6862 (regexp-opt
6863 '("alias"
6864 "augments"
6865 "borrows"
6866 "bug"
6867 "base"
6868 "config"
6869 "default"
6870 "define"
6871 "exception"
6872 "function"
6873 "member"
6874 "memberOf"
6875 "name"
6876 "namespace"
6877 "property"
6878 "since"
6879 "suppress"
6880 "this"
6881 "throws"
6882 "type"
6883 "version"))
6884 "\\)\\)\\s-+\\([^ \t]+\\)")
6885 "Matches jsdoc tags with a single argument.")
6886
6887 (defconst js2-jsdoc-empty-tag-regexp
6888 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6889 (regexp-opt
6890 '("addon"
6891 "author"
6892 "class"
6893 "const"
6894 "constant"
6895 "constructor"
6896 "constructs"
6897 "deprecated"
6898 "desc"
6899 "description"
6900 "event"
6901 "example"
6902 "exec"
6903 "export"
6904 "fileoverview"
6905 "final"
6906 "function"
6907 "hidden"
6908 "ignore"
6909 "implicitCast"
6910 "inheritDoc"
6911 "inner"
6912 "interface"
6913 "license"
6914 "noalias"
6915 "noshadow"
6916 "notypecheck"
6917 "override"
6918 "owner"
6919 "preserve"
6920 "preserveTry"
6921 "private"
6922 "protected"
6923 "public"
6924 "static"
6925 "supported"
6926 ))
6927 "\\)\\)\\s-*")
6928 "Matches empty jsdoc tags.")
6929
6930 (defconst js2-jsdoc-link-tag-regexp
6931 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6932 "Matches a jsdoc link or code tag.")
6933
6934 (defconst js2-jsdoc-see-tag-regexp
6935 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6936 "Matches a jsdoc @see tag.")
6937
6938 (defconst js2-jsdoc-html-tag-regexp
6939 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6940 "Matches a simple (no attributes) html start- or end-tag.")
6941
6942 (defun js2-jsdoc-highlight-helper ()
6943 (js2-set-face (match-beginning 1)
6944 (match-end 1)
6945 'js2-jsdoc-tag)
6946 (if (match-beginning 2)
6947 (if (save-excursion
6948 (goto-char (match-beginning 2))
6949 (= (char-after) ?{))
6950 (js2-set-face (1+ (match-beginning 2))
6951 (1- (match-end 2))
6952 'js2-jsdoc-type)
6953 (js2-set-face (match-beginning 2)
6954 (match-end 2)
6955 'js2-jsdoc-value)))
6956 (if (match-beginning 3)
6957 (js2-set-face (match-beginning 3)
6958 (match-end 3)
6959 'js2-jsdoc-value)))
6960
6961 (defun js2-highlight-jsdoc (ast)
6962 "Highlight doc comment tags."
6963 (let ((comments (js2-ast-root-comments ast))
6964 beg end)
6965 (save-excursion
6966 (dolist (node comments)
6967 (when (eq (js2-comment-node-format node) 'jsdoc)
6968 (setq beg (js2-node-abs-pos node)
6969 end (+ beg (js2-node-len node)))
6970 (save-restriction
6971 (narrow-to-region beg end)
6972 (dolist (re (list js2-jsdoc-param-tag-regexp
6973 js2-jsdoc-typed-tag-regexp
6974 js2-jsdoc-arg-tag-regexp
6975 js2-jsdoc-link-tag-regexp
6976 js2-jsdoc-see-tag-regexp
6977 js2-jsdoc-empty-tag-regexp))
6978 (goto-char beg)
6979 (while (re-search-forward re nil t)
6980 (js2-jsdoc-highlight-helper)))
6981 ;; simple highlighting for html tags
6982 (goto-char beg)
6983 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6984 (js2-set-face (match-beginning 1)
6985 (match-end 1)
6986 'js2-jsdoc-html-tag-delimiter)
6987 (js2-set-face (match-beginning 2)
6988 (match-end 2)
6989 'js2-jsdoc-html-tag-name)
6990 (js2-set-face (match-beginning 3)
6991 (match-end 3)
6992 'js2-jsdoc-html-tag-delimiter))))))))
6993
6994 (defun js2-highlight-assign-targets (_node left right)
6995 "Highlight function properties and external variables."
6996 (let (leftpos name)
6997 ;; highlight vars and props assigned function values
6998 (when (or (js2-function-node-p right)
6999 (js2-class-node-p right))
7000 (cond
7001 ;; var foo = function() {...}
7002 ((js2-name-node-p left)
7003 (setq name left))
7004 ;; foo.bar.baz = function() {...}
7005 ((and (js2-prop-get-node-p left)
7006 (js2-name-node-p (js2-prop-get-node-right left)))
7007 (setq name (js2-prop-get-node-right left))))
7008 (when name
7009 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7010 (+ leftpos (js2-node-len name))
7011 'font-lock-function-name-face
7012 'record)))))
7013
7014 (defun js2-record-name-node (node)
7015 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7016 later. NODE must be a name node."
7017 (let ((leftpos (js2-node-abs-pos node)))
7018 (push (list node js2-current-scope
7019 leftpos
7020 (+ leftpos (js2-node-len node)))
7021 js2-recorded-identifiers)))
7022
7023 (defun js2-highlight-undeclared-vars ()
7024 "After entire parse is finished, look for undeclared variable references.
7025 We have to wait until entire buffer is parsed, since JavaScript permits var
7026 decls to occur after they're used.
7027
7028 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7029 it is considered declared."
7030 (let (name)
7031 (dolist (entry js2-recorded-identifiers)
7032 (cl-destructuring-bind (name-node scope pos end) entry
7033 (setq name (js2-name-node-name name-node))
7034 (unless (or (member name js2-global-externs)
7035 (member name js2-default-externs)
7036 (member name js2-additional-externs)
7037 (js2-get-defining-scope scope name))
7038 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7039 'js2-external-variable))))
7040 (setq js2-recorded-identifiers nil)))
7041
7042 (defun js2-set-default-externs ()
7043 "Set the value of `js2-default-externs' based on the various
7044 `js2-include-?-externs' variables."
7045 (setq js2-default-externs
7046 (append js2-ecma-262-externs
7047 (if js2-include-browser-externs js2-browser-externs)
7048 (if (and js2-include-browser-externs
7049 (>= js2-language-version 200)) js2-harmony-externs)
7050 (if js2-include-rhino-externs js2-rhino-externs)
7051 (if js2-include-node-externs js2-node-externs)
7052 (if (or js2-include-browser-externs js2-include-node-externs)
7053 js2-typed-array-externs))))
7054
7055 (defun js2-apply-jslint-globals ()
7056 (setq js2-additional-externs
7057 (nconc (js2-get-jslint-globals)
7058 js2-additional-externs)))
7059
7060 (defun js2-get-jslint-globals ()
7061 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7062 when (and (eq 'block (js2-comment-node-format node))
7063 (save-excursion
7064 (goto-char (js2-node-abs-pos node))
7065 (looking-at "/\\*global ")))
7066 append (js2-get-jslint-globals-in
7067 (match-end 0)
7068 (js2-node-abs-end node))))
7069
7070 (defun js2-get-jslint-globals-in (beg end)
7071 (let (res)
7072 (save-excursion
7073 (goto-char beg)
7074 (while (re-search-forward js2-mode-identifier-re end t)
7075 (let ((match (match-string 0)))
7076 (unless (member match '("true" "false"))
7077 (push match res)))))
7078 (nreverse res)))
7079
7080 ;;; IMenu support
7081
7082 ;; We currently only support imenu, but eventually should support speedbar and
7083 ;; possibly other browsing mechanisms.
7084
7085 ;; The basic strategy is to identify function assignment targets of the form
7086 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7087 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7088 ;; for imenu after parsing is finished.
7089
7090 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7091 ;; JavaScript, and the general problem is undecidable. However, several forms
7092 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7093 ;; include:
7094
7095 ;; function foo() -- function declaration
7096 ;; foo = function() -- function expression assigned to variable
7097 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7098 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7099 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7100 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7101 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7102 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7103 ;; function foo() {function bar() {...}} -- nested function
7104 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7105
7106 ;; This list boils down to a few forms that can be combined recursively.
7107 ;; Top-level named function declarations include both the left-hand (name)
7108 ;; and the right-hand (function value) expressions needed to produce an imenu
7109 ;; entry. The other "right-hand" forms we need to look for are:
7110 ;; - functions declared as props/getters/setters in object literals
7111 ;; - nested named function declarations
7112 ;; The "left-hand" expressions that functions can be assigned to include:
7113 ;; - local/global variables
7114 ;; - nested property-get expressions like a.b.c.d
7115 ;; - element gets like foo[10] or foo['bar'] where the index
7116 ;; expression can be trivially converted to a property name. They
7117 ;; effectively then become property gets.
7118
7119 ;; All the different definition types are canonicalized into the form
7120 ;; foo.bar.baz = position-of-function-keyword
7121
7122 ;; We need to build a trie-like structure for imenu. As an example,
7123 ;; consider the following JavaScript code:
7124
7125 ;; a = function() {...} // function at position 5
7126 ;; b = function() {...} // function at position 25
7127 ;; foo = function() {...} // function at position 100
7128 ;; foo.bar = function() {...} // function at position 200
7129 ;; foo.bar.baz = function() {...} // function at position 300
7130 ;; foo.bar.zab = function() {...} // function at position 400
7131
7132 ;; During parsing we accumulate an entry for each definition in
7133 ;; the variable `js2-imenu-recorder', like so:
7134
7135 ;; '((fn a 5)
7136 ;; (fn b 25)
7137 ;; (fn foo 100)
7138 ;; (fn foo bar 200)
7139 ;; (fn foo bar baz 300)
7140 ;; (fn foo bar zab 400))
7141
7142 ;; Where 'fn' is the respective function node.
7143 ;; After parsing these entries are merged into this alist-trie:
7144
7145 ;; '((a . 1)
7146 ;; (b . 2)
7147 ;; (foo (<definition> . 3)
7148 ;; (bar (<definition> . 6)
7149 ;; (baz . 100)
7150 ;; (zab . 200))))
7151
7152 ;; Note the wacky need for a <definition> name. The token can be anything
7153 ;; that isn't a valid JavaScript identifier, because you might make foo
7154 ;; a function and then start setting properties on it that are also functions.
7155
7156 (defun js2-prop-node-name (node)
7157 "Return the name of a node that may be a property-get/property-name.
7158 If NODE is not a valid name-node, string-node or integral number-node,
7159 returns nil. Otherwise returns the string name/value of the node."
7160 (cond
7161 ((js2-name-node-p node)
7162 (js2-name-node-name node))
7163 ((js2-string-node-p node)
7164 (js2-string-node-value node))
7165 ((and (js2-number-node-p node)
7166 (string-match "^[0-9]+$" (js2-number-node-value node)))
7167 (js2-number-node-value node))
7168 ((eq (js2-node-type node) js2-THIS)
7169 "this")
7170 ((eq (js2-node-type node) js2-SUPER)
7171 "super")))
7172
7173 (defun js2-node-qname-component (node)
7174 "Return the name of this node, if it contributes to a qname.
7175 Returns nil if the node doesn't contribute."
7176 (copy-sequence
7177 (or (js2-prop-node-name node)
7178 (if (and (js2-function-node-p node)
7179 (js2-function-node-name node))
7180 (js2-name-node-name (js2-function-node-name node))))))
7181
7182 (defun js2-record-imenu-entry (fn-node qname pos)
7183 "Add an entry to `js2-imenu-recorder'.
7184 FN-NODE should be the current item's function node.
7185
7186 Associate FN-NODE with its QNAME for later lookup.
7187 This is used in postprocessing the chain list. For each chain, we find
7188 the parent function, look up its qname, then prepend a copy of it to the chain."
7189 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7190 (unless js2-imenu-function-map
7191 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7192 (puthash fn-node qname js2-imenu-function-map))
7193
7194 (defun js2-record-imenu-functions (node &optional var)
7195 "Record function definitions for imenu.
7196 NODE is a function node or an object literal.
7197 VAR, if non-nil, is the expression that NODE is being assigned to.
7198 When passed arguments of wrong type, does nothing."
7199 (when js2-parse-ide-mode
7200 (let ((fun-p (js2-function-node-p node))
7201 qname fname-node)
7202 (cond
7203 ;; non-anonymous function declaration?
7204 ((and fun-p
7205 (not var)
7206 (setq fname-node (js2-function-node-name node)))
7207 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7208 ;; for remaining forms, compute left-side tree branch first
7209 ((and var (setq qname (js2-compute-nested-prop-get var)))
7210 (cond
7211 ;; foo.bar.baz = function
7212 (fun-p
7213 (js2-record-imenu-entry node qname (js2-node-pos node)))
7214 ;; foo.bar.baz = object-literal
7215 ;; look for nested functions: {a: {b: function() {...} }}
7216 ((js2-object-node-p node)
7217 ;; Node position here is still absolute, since the parser
7218 ;; passes the assignment target and value expressions
7219 ;; to us before they are added as children of the assignment node.
7220 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7221
7222 (defun js2-compute-nested-prop-get (node)
7223 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7224 component nodes as a list. Otherwise return nil. Element-gets are treated
7225 as property-gets if the index expression is a string, or a positive integer."
7226 (let (left right head)
7227 (cond
7228 ((or (js2-name-node-p node)
7229 (js2-this-or-super-node-p node))
7230 (list node))
7231 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7232 ((js2-prop-get-node-p node) ; foo.bar
7233 (setq left (js2-prop-get-node-left node)
7234 right (js2-prop-get-node-right node))
7235 (if (setq head (js2-compute-nested-prop-get left))
7236 (nconc head (list right))))
7237 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7238 (setq left (js2-elem-get-node-target node)
7239 right (js2-elem-get-node-element node))
7240 (if (or (js2-string-node-p right) ; ['bar']
7241 (and (js2-number-node-p right) ; [10]
7242 (string-match "^[0-9]+$"
7243 (js2-number-node-value right))))
7244 (if (setq head (js2-compute-nested-prop-get left))
7245 (nconc head (list right))))))))
7246
7247 (defun js2-record-object-literal (node qname pos)
7248 "Recursively process an object literal looking for functions.
7249 NODE is an object literal that is the right-hand child of an assignment
7250 expression. QNAME is a list of nodes representing the assignment target,
7251 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7252 POS is the absolute position of the node.
7253 We do a depth-first traversal of NODE. For any functions we find,
7254 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7255 (let (right)
7256 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7257 (let ((left (js2-infix-node-left e))
7258 ;; Element positions are relative to the parent position.
7259 (pos (+ pos (js2-node-pos e))))
7260 (cond
7261 ;; foo: function() {...}
7262 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7263 (when (js2-prop-node-name left)
7264 ;; As a policy decision, we record the position of the property,
7265 ;; not the position of the `function' keyword, since the property
7266 ;; is effectively the name of the function.
7267 (js2-record-imenu-entry right (append qname (list left)) pos)))
7268 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7269 ((js2-object-node-p right)
7270 (js2-record-object-literal right
7271 (append qname (list (js2-infix-node-left e)))
7272 (+ pos (js2-node-pos right)))))))))
7273
7274 (defun js2-node-top-level-decl-p (node)
7275 "Return t if NODE's name is defined in the top-level scope.
7276 Also returns t if NODE's name is not defined in any scope, since it implies
7277 that it's an external variable, which must also be in the top-level scope."
7278 (let* ((name (js2-prop-node-name node))
7279 (this-scope (js2-node-get-enclosing-scope node))
7280 defining-scope)
7281 (cond
7282 ((js2-this-or-super-node-p node)
7283 nil)
7284 ((null this-scope)
7285 t)
7286 ((setq defining-scope (js2-get-defining-scope this-scope name))
7287 (js2-ast-root-p defining-scope))
7288 (t t))))
7289
7290 (defun js2-wrapper-function-p (node)
7291 "Return t if NODE is a function expression that's immediately invoked.
7292 NODE must be `js2-function-node'."
7293 (let ((parent (js2-node-parent node)))
7294 (or
7295 ;; function(){...}();
7296 (and (js2-call-node-p parent)
7297 (eq node (js2-call-node-target parent)))
7298 (and (js2-paren-node-p parent)
7299 ;; (function(){...})();
7300 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7301 ;; (function(){...}).call(this);
7302 (and (js2-prop-get-node-p parent)
7303 (member (js2-name-node-name (js2-prop-get-node-right parent))
7304 '("call" "apply"))
7305 (js2-call-node-p (js2-node-parent parent))))))))
7306
7307 (defun js2-browse-postprocess-chains ()
7308 "Modify function-declaration name chains after parsing finishes.
7309 Some of the information is only available after the parse tree is complete.
7310 For instance, processing a nested scope requires a parent function node."
7311 (let (result fn parent-qname p elem)
7312 (dolist (entry js2-imenu-recorder)
7313 ;; function node goes first
7314 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7315 ;; Examine head's defining scope:
7316 ;; Pre-processed chain, or top-level/external, keep as-is.
7317 (if (or (stringp head) (js2-node-top-level-decl-p head))
7318 (push chain result)
7319 (when (js2-this-or-super-node-p head)
7320 (setq chain (cdr chain))) ; discard this-node
7321 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7322 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7323 (when (eq parent-qname 'not-found)
7324 ;; anonymous function expressions are not recorded
7325 ;; during the parse, so we need to handle this case here
7326 (setq parent-qname
7327 (if (js2-wrapper-function-p fn)
7328 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7329 (if (js2-ast-root-p grandparent)
7330 nil
7331 (gethash grandparent js2-imenu-function-map 'skip)))
7332 'skip))
7333 (puthash fn parent-qname js2-imenu-function-map))
7334 (if (eq parent-qname 'skip)
7335 ;; We don't show it, let's record that fact.
7336 (remhash current-fn js2-imenu-function-map)
7337 ;; Prepend parent fn qname to this chain.
7338 (let ((qname (append parent-qname chain)))
7339 (puthash current-fn (butlast qname) js2-imenu-function-map)
7340 (push qname result)))))))
7341 ;; Collect chains obtained by third-party code.
7342 (let (js2-imenu-recorder)
7343 (run-hooks 'js2-build-imenu-callbacks)
7344 (dolist (entry js2-imenu-recorder)
7345 (push (cdr entry) result)))
7346 ;; Finally replace each node in each chain with its name.
7347 (dolist (chain result)
7348 (setq p chain)
7349 (while p
7350 (if (js2-node-p (setq elem (car p)))
7351 (setcar p (js2-node-qname-component elem)))
7352 (setq p (cdr p))))
7353 result))
7354
7355 ;; Merge name chains into a trie-like tree structure of nested lists.
7356 ;; To simplify construction of the trie, we first build it out using the rule
7357 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7358 ;; [key, num-or-list]. The second element can be a number; if so, this key
7359 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7360 ;; associated with the key at this level.) Otherwise the second element is
7361 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7362 ;; a simple recursive formulation.
7363 ;;
7364 ;; js2-mode is building the data structure for imenu. The imenu documentation
7365 ;; claims that it's the structure above, but in practice it wants the children
7366 ;; at the same list level as the key for that level, which is how I've drawn
7367 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7368 ;; list wrapper around the children at each level.
7369 ;;
7370 ;; A completed nested imenu-alist entry looks like this:
7371 ;; '(("foo"
7372 ;; ("<definition>" . 7)
7373 ;; ("bar"
7374 ;; ("a" . 40)
7375 ;; ("b" . 60))))
7376 ;;
7377 ;; In particular, the documentation for `imenu--index-alist' says that
7378 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7379 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7380
7381 (defun js2-treeify (lst)
7382 "Convert (a b c d) to (a ((b ((c d)))))."
7383 (if (null (cddr lst)) ; list length <= 2
7384 lst
7385 (list (car lst) (list (js2-treeify (cdr lst))))))
7386
7387 (defun js2-build-alist-trie (chains trie)
7388 "Merge declaration name chains into a trie-like alist structure for imenu.
7389 CHAINS is the qname chain list produced during parsing. TRIE is a
7390 list of elements built up so far."
7391 (let (head tail pos branch kids)
7392 (dolist (chain chains)
7393 (setq head (car chain)
7394 tail (cdr chain)
7395 pos (if (numberp (car tail)) (car tail))
7396 branch (js2-find-if (lambda (n)
7397 (string= (car n) head))
7398 trie)
7399 kids (cl-second branch))
7400 (cond
7401 ;; case 1: this key isn't in the trie yet
7402 ((null branch)
7403 (if trie
7404 (setcdr (last trie) (list (js2-treeify chain)))
7405 (setq trie (list (js2-treeify chain)))))
7406 ;; case 2: key is present with a single number entry: replace w/ list
7407 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7408 ;; ("<definition>" 20)))
7409 ((numberp kids)
7410 (setcar (cdr branch)
7411 (list (list "<definition-1>" kids)
7412 (if pos
7413 (list "<definition-2>" pos)
7414 (js2-treeify tail)))))
7415 ;; case 3: key is there (with kids), and we're a number entry
7416 (pos
7417 (setcdr (last kids)
7418 (list
7419 (list (format "<definition-%d>"
7420 (1+ (cl-loop for kid in kids
7421 count (eq ?< (aref (car kid) 0)))))
7422 pos))))
7423 ;; case 4: key is there with kids, need to merge in our chain
7424 (t
7425 (js2-build-alist-trie (list tail) kids))))
7426 trie))
7427
7428 (defun js2-flatten-trie (trie)
7429 "Convert TRIE to imenu-format.
7430 Recurses through nodes, and for each one whose second element is a list,
7431 appends the list's flattened elements to the current element. Also
7432 changes the tails into conses. For instance, this pre-flattened trie
7433
7434 '(a ((b 20)
7435 (c ((d 30)
7436 (e 40)))))
7437
7438 becomes
7439
7440 '(a (b . 20)
7441 (c (d . 30)
7442 (e . 40)))
7443
7444 Note that the root of the trie has no key, just a list of chains.
7445 This is also true for the value of any key with multiple children,
7446 e.g. key 'c' in the example above."
7447 (cond
7448 ((listp (car trie))
7449 (mapcar #'js2-flatten-trie trie))
7450 (t
7451 (if (numberp (cl-second trie))
7452 (cons (car trie) (cl-second trie))
7453 ;; else pop list and append its kids
7454 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7455
7456 (defun js2-build-imenu-index ()
7457 "Turn `js2-imenu-recorder' into an imenu data structure."
7458 (when (eq js2-imenu-recorder 'empty)
7459 (setq js2-imenu-recorder nil))
7460 (let* ((chains (js2-browse-postprocess-chains))
7461 (result (js2-build-alist-trie chains nil)))
7462 (js2-flatten-trie result)))
7463
7464 (defun js2-test-print-chains (chains)
7465 "Print a list of qname chains.
7466 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7467 i.e. one or more nodes, and an integer position as the list tail."
7468 (mapconcat (lambda (chain)
7469 (concat "("
7470 (mapconcat (lambda (elem)
7471 (if (js2-node-p elem)
7472 (or (js2-node-qname-component elem)
7473 "nil")
7474 (number-to-string elem)))
7475 chain
7476 " ")
7477 ")"))
7478 chains
7479 "\n"))
7480
7481 ;;; Parser
7482
7483 (defconst js2-version "1.8.5"
7484 "Version of JavaScript supported.")
7485
7486 (defun js2-record-face (face &optional token)
7487 "Record a style run of FACE for TOKEN or the current token."
7488 (unless token (setq token (js2-current-token)))
7489 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7490
7491 (defsubst js2-node-end (n)
7492 "Computes the absolute end of node N.
7493 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7494 is only true until the node is added to its parent; i.e., while parsing."
7495 (+ (js2-node-pos n)
7496 (js2-node-len n)))
7497
7498 (defun js2-record-comment (token)
7499 "Record a comment in `js2-scanned-comments'."
7500 (let ((ct (js2-token-comment-type token))
7501 (beg (js2-token-beg token))
7502 (end (js2-token-end token)))
7503 (push (make-js2-comment-node :len (- end beg)
7504 :format ct)
7505 js2-scanned-comments)
7506 (when js2-parse-ide-mode
7507 (js2-record-face (if (eq ct 'jsdoc)
7508 'font-lock-doc-face
7509 'font-lock-comment-face)
7510 token)
7511 (when (memq ct '(html preprocessor))
7512 ;; Tell cc-engine the bounds of the comment.
7513 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7514
7515 (defun js2-peek-token ()
7516 "Return the next token type without consuming it.
7517 If `js2-ti-lookahead' is positive, return the type of next token
7518 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7519 (if (not (zerop js2-ti-lookahead))
7520 (js2-token-type
7521 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7522 (let ((tt (js2-get-token-internal nil)))
7523 (js2-unget-token)
7524 tt)))
7525
7526 (defalias 'js2-next-token 'js2-get-token)
7527
7528 (defun js2-match-token (match &optional dont-unget)
7529 "Get next token and return t if it matches MATCH, a bytecode.
7530 Returns nil and consumes nothing if MATCH is not the next token."
7531 (if (/= (js2-get-token) match)
7532 (ignore (unless dont-unget (js2-unget-token)))
7533 t))
7534
7535 (defun js2-match-contextual-kwd (name)
7536 "Consume and return t if next token is `js2-NAME', and its
7537 string is NAME. Returns nil and keeps current token otherwise."
7538 (if (or (/= (js2-get-token) js2-NAME)
7539 (not (string= (js2-current-token-string) name)))
7540 (progn
7541 (js2-unget-token)
7542 nil)
7543 (js2-record-face 'font-lock-keyword-face)
7544 t))
7545
7546 (defun js2-get-prop-name-token ()
7547 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7548
7549 (defun js2-match-prop-name ()
7550 "Consume token and return t if next token is a valid property name.
7551 If `js2-language-version' is >= 180, a keyword or reserved word
7552 is considered valid name as well."
7553 (if (eq js2-NAME (js2-get-prop-name-token))
7554 t
7555 (js2-unget-token)
7556 nil))
7557
7558 (defun js2-must-match-prop-name (msg-id &optional pos len)
7559 (if (js2-match-prop-name)
7560 t
7561 (js2-report-error msg-id nil pos len)
7562 nil))
7563
7564 (defun js2-peek-token-or-eol ()
7565 "Return js2-EOL if the next token immediately follows a newline.
7566 Else returns the next token. Used in situations where we don't
7567 consider certain token types valid if they are preceded by a newline.
7568 One example is the postfix ++ or -- operator, which has to be on the
7569 same line as its operand."
7570 (let ((tt (js2-get-token))
7571 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7572 (js2-unget-token)
7573 (if follows-eol
7574 js2-EOL
7575 tt)))
7576
7577 (defun js2-must-match (token msg-id &optional pos len)
7578 "Match next token to token code TOKEN, or record a syntax error.
7579 MSG-ID is the error message to report if the match fails.
7580 Returns t on match, nil if no match."
7581 (if (js2-match-token token t)
7582 t
7583 (js2-report-error msg-id nil pos len)
7584 (js2-unget-token)
7585 nil))
7586
7587 (defun js2-must-match-name (msg-id)
7588 (if (js2-match-token js2-NAME t)
7589 t
7590 (if (eq (js2-current-token-type) js2-RESERVED)
7591 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7592 (js2-report-error msg-id)
7593 (js2-unget-token))
7594 nil))
7595
7596 (defsubst js2-inside-function ()
7597 (cl-plusp js2-nesting-of-function))
7598
7599 (defun js2-set-requires-activation ()
7600 (if (js2-function-node-p js2-current-script-or-fn)
7601 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7602
7603 (defun js2-check-activation-name (name _token)
7604 (when (js2-inside-function)
7605 ;; skip language-version 1.2 check from Rhino
7606 (if (or (string= "arguments" name)
7607 (and js2-compiler-activation-names ; only used in codegen
7608 (gethash name js2-compiler-activation-names)))
7609 (js2-set-requires-activation))))
7610
7611 (defun js2-set-is-generator ()
7612 (let ((fn-node js2-current-script-or-fn))
7613 (when (and (js2-function-node-p fn-node)
7614 (not (js2-function-node-generator-type fn-node)))
7615 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7616
7617 (defun js2-must-have-xml ()
7618 (unless js2-compiler-xml-available
7619 (js2-report-error "msg.XML.not.available")))
7620
7621 (defun js2-push-scope (scope)
7622 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7623 (cl-assert (js2-scope-p scope))
7624 (cl-assert (null (js2-scope-parent-scope scope)))
7625 (cl-assert (not (eq js2-current-scope scope)))
7626 (setf (js2-scope-parent-scope scope) js2-current-scope
7627 js2-current-scope scope))
7628
7629 (defsubst js2-pop-scope ()
7630 (setq js2-current-scope
7631 (js2-scope-parent-scope js2-current-scope)))
7632
7633 (defun js2-enter-loop (loop-node)
7634 (push loop-node js2-loop-set)
7635 (push loop-node js2-loop-and-switch-set)
7636 (js2-push-scope loop-node)
7637 ;; Tell the current labeled statement (if any) its statement,
7638 ;; and set the jump target of the first label to the loop.
7639 ;; These are used in `js2-parse-continue' to verify that the
7640 ;; continue target is an actual labeled loop. (And for codegen.)
7641 (when js2-labeled-stmt
7642 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7643 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7644 js2-labeled-stmt))) loop-node)))
7645
7646 (defun js2-exit-loop ()
7647 (pop js2-loop-set)
7648 (pop js2-loop-and-switch-set)
7649 (js2-pop-scope))
7650
7651 (defsubst js2-enter-switch (switch-node)
7652 (push switch-node js2-loop-and-switch-set))
7653
7654 (defsubst js2-exit-switch ()
7655 (pop js2-loop-and-switch-set))
7656
7657 (defun js2-parse (&optional buf cb)
7658 "Tell the js2 parser to parse a region of JavaScript.
7659
7660 BUF is a buffer or buffer name containing the code to parse.
7661 Call `narrow-to-region' first to parse only part of the buffer.
7662
7663 The returned AST root node is given some additional properties:
7664 `node-count' - total number of nodes in the AST
7665 `buffer' - BUF. The buffer it refers to may change or be killed,
7666 so the value is not necessarily reliable.
7667
7668 An optional callback CB can be specified to report parsing
7669 progress. If `(functionp CB)' returns t, it will be called with
7670 the current line number once before parsing begins, then again
7671 each time the lexer reaches a new line number.
7672
7673 CB can also be a list of the form `(symbol cb ...)' to specify
7674 multiple callbacks with different criteria. Each symbol is a
7675 criterion keyword, and the following element is the callback to
7676 call
7677
7678 :line - called whenever the line number changes
7679 :token - called for each new token consumed
7680
7681 The list of criteria could be extended to include entering or
7682 leaving a statement, an expression, or a function definition."
7683 (if (and cb (not (functionp cb)))
7684 (error "criteria callbacks not yet implemented"))
7685 (let ((inhibit-point-motion-hooks t)
7686 (js2-compiler-xml-available (>= js2-language-version 160))
7687 ;; This is a recursive-descent parser, so give it a big stack.
7688 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7689 (max-specpdl-size (max max-specpdl-size 3000))
7690 (case-fold-search nil)
7691 ast)
7692 (with-current-buffer (or buf (current-buffer))
7693 (setq js2-scanned-comments nil
7694 js2-parsed-errors nil
7695 js2-parsed-warnings nil
7696 js2-imenu-recorder nil
7697 js2-imenu-function-map nil
7698 js2-label-set nil)
7699 (js2-init-scanner)
7700 (setq ast (js2-do-parse))
7701 (unless js2-ts-hit-eof
7702 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7703 (setf (js2-ast-root-errors ast) js2-parsed-errors
7704 (js2-ast-root-warnings ast) js2-parsed-warnings)
7705 ;; if we didn't find any declarations, put a dummy in this list so we
7706 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7707 (unless js2-imenu-recorder
7708 (setq js2-imenu-recorder 'empty))
7709 (run-hooks 'js2-parse-finished-hook)
7710 ast)))
7711
7712 ;; Corresponds to Rhino's Parser.parse() method.
7713 (defun js2-do-parse ()
7714 "Parse current buffer starting from current point.
7715 Scanner should be initialized."
7716 (let ((pos js2-ts-cursor)
7717 (end js2-ts-cursor) ; in case file is empty
7718 root n tt)
7719 ;; initialize buffer-local parsing vars
7720 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7721 js2-current-script-or-fn root
7722 js2-current-scope root
7723 js2-nesting-of-function 0
7724 js2-labeled-stmt nil
7725 js2-recorded-identifiers nil) ; for js2-highlight
7726 (while (/= (setq tt (js2-get-token)) js2-EOF)
7727 (if (= tt js2-FUNCTION)
7728 (progn
7729 (setq n (if js2-called-by-compile-function
7730 (js2-parse-function-expr)
7731 (js2-parse-function-stmt))))
7732 ;; not a function - parse a statement
7733 (js2-unget-token)
7734 (setq n (js2-parse-statement)))
7735 ;; add function or statement to script
7736 (setq end (js2-node-end n))
7737 (js2-block-node-push root n))
7738 ;; add comments to root in lexical order
7739 (when js2-scanned-comments
7740 ;; if we find a comment beyond end of normal kids, use its end
7741 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7742 (dolist (comment js2-scanned-comments)
7743 (push comment (js2-ast-root-comments root))
7744 (js2-node-add-children root comment)))
7745 (setf (js2-node-len root) (- end pos))
7746 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7747 ;; Give extensions a chance to muck with things before highlighting starts.
7748 (let ((js2-additional-externs js2-additional-externs))
7749 (save-excursion
7750 (run-hooks 'js2-post-parse-callbacks))
7751 (js2-highlight-undeclared-vars))
7752 root))
7753
7754 (defun js2-parse-function-closure-body (fn-node)
7755 "Parse a JavaScript 1.8 function closure body."
7756 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7757 (if js2-ts-hit-eof
7758 (js2-report-error "msg.no.brace.body" nil
7759 (js2-node-pos fn-node)
7760 (- js2-ts-cursor (js2-node-pos fn-node)))
7761 (js2-node-add-children fn-node
7762 (setf (js2-function-node-body fn-node)
7763 (js2-parse-expr t))))))
7764
7765 (defun js2-parse-function-body (fn-node)
7766 (js2-must-match js2-LC "msg.no.brace.body"
7767 (js2-node-pos fn-node)
7768 (- js2-ts-cursor (js2-node-pos fn-node)))
7769 (let ((pos (js2-current-token-beg)) ; LC position
7770 (pn (make-js2-block-node)) ; starts at LC position
7771 tt
7772 end)
7773 (cl-incf js2-nesting-of-function)
7774 (unwind-protect
7775 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7776 (= tt js2-EOF)
7777 (= tt js2-RC)))
7778 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7779 (js2-parse-statement)
7780 (js2-get-token)
7781 (js2-parse-function-stmt))))
7782 (cl-decf js2-nesting-of-function))
7783 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7784 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7785 (setq end (js2-current-token-end)))
7786 (setf (js2-node-pos pn) pos
7787 (js2-node-len pn) (- end pos))
7788 (setf (js2-function-node-body fn-node) pn)
7789 (js2-node-add-children fn-node pn)
7790 pn))
7791
7792 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7793 "Declare and fontify destructuring parameters inside NODE.
7794 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7795 (cond
7796 ((js2-name-node-p node)
7797 (let (leftpos)
7798 (js2-define-symbol decl-type (js2-name-node-name node)
7799 node ignore-not-in-block)
7800 (when face
7801 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7802 (+ leftpos (js2-node-len node))
7803 face 'record))))
7804 ((js2-object-node-p node)
7805 (dolist (elem (js2-object-node-elems node))
7806 (js2-define-destruct-symbols
7807 ;; In abbreviated destructuring {a, b}, right == left.
7808 (js2-object-prop-node-right elem)
7809 decl-type face ignore-not-in-block)))
7810 ((js2-array-node-p node)
7811 (dolist (elem (js2-array-node-elems node))
7812 (when elem
7813 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7814 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7815 (js2-node-len node)))))
7816
7817 (defun js2-parse-function-params (function-type fn-node pos)
7818 (if (js2-match-token js2-RP)
7819 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7820 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7821 (eq (js2-current-token-type) js2-NAME)))
7822 params param default-found rest-param-at)
7823 (when paren-free-arrow
7824 (js2-unget-token))
7825 (cl-loop for tt = (js2-peek-token)
7826 do
7827 (cond
7828 ;; destructuring param
7829 ((and (not paren-free-arrow)
7830 (or (= tt js2-LB) (= tt js2-LC)))
7831 (js2-get-token)
7832 (when default-found
7833 (js2-report-error "msg.no.default.after.default.param"))
7834 (setq param (js2-parse-destruct-primary-expr))
7835 (js2-define-destruct-symbols param
7836 js2-LP
7837 'js2-function-param)
7838 (push param params))
7839 ;; variable name
7840 (t
7841 (when (and (>= js2-language-version 200)
7842 (not paren-free-arrow)
7843 (js2-match-token js2-TRIPLEDOT)
7844 (not rest-param-at))
7845 ;; to report errors if there are more parameters
7846 (setq rest-param-at (length params)))
7847 (js2-must-match-name "msg.no.parm")
7848 (js2-record-face 'js2-function-param)
7849 (setq param (js2-create-name-node))
7850 (js2-define-symbol js2-LP (js2-current-token-string) param)
7851 ;; default parameter value
7852 (when (or (and default-found
7853 (not rest-param-at)
7854 (js2-must-match js2-ASSIGN
7855 "msg.no.default.after.default.param"
7856 (js2-node-pos param)
7857 (js2-node-len param)))
7858 (and (>= js2-language-version 200)
7859 (js2-match-token js2-ASSIGN)))
7860 (cl-assert (not paren-free-arrow))
7861 (let* ((pos (js2-node-pos param))
7862 (tt (js2-current-token-type))
7863 (op-pos (- (js2-current-token-beg) pos))
7864 (left param)
7865 (right (js2-parse-assign-expr))
7866 (len (- (js2-node-end right) pos)))
7867 (setq param (make-js2-assign-node
7868 :type tt :pos pos :len len :op-pos op-pos
7869 :left left :right right)
7870 default-found t)
7871 (js2-node-add-children param left right)))
7872 (push param params)))
7873 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7874 (js2-report-error "msg.param.after.rest" nil
7875 (js2-node-pos param) (js2-node-len param)))
7876 while
7877 (js2-match-token js2-COMMA))
7878 (when (and (not paren-free-arrow)
7879 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7880 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7881 (when rest-param-at
7882 (setf (js2-function-node-rest-p fn-node) t))
7883 (dolist (p params)
7884 (js2-node-add-children fn-node p)
7885 (push p (js2-function-node-params fn-node))))))
7886
7887 (defun js2-check-inconsistent-return-warning (fn-node name)
7888 "Possibly show inconsistent-return warning.
7889 Last token scanned is the close-curly for the function body."
7890 (when (and js2-mode-show-strict-warnings
7891 js2-strict-inconsistent-return-warning
7892 (not (js2-has-consistent-return-usage
7893 (js2-function-node-body fn-node))))
7894 ;; Have it extend from close-curly to bol or beginning of block.
7895 (let ((pos (save-excursion
7896 (goto-char (js2-current-token-end))
7897 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7898 (point-at-bol))))
7899 (end (js2-current-token-end)))
7900 (if (cl-plusp (js2-name-node-length name))
7901 (js2-add-strict-warning "msg.no.return.value"
7902 (js2-name-node-name name) pos end)
7903 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7904
7905 (defun js2-parse-function-stmt ()
7906 (let ((pos (js2-current-token-beg))
7907 (star-p (js2-match-token js2-MUL)))
7908 (js2-must-match-name "msg.unnamed.function.stmt")
7909 (let ((name (js2-create-name-node t))
7910 pn member-expr)
7911 (cond
7912 ((js2-match-token js2-LP)
7913 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7914 (js2-allow-member-expr-as-function-name
7915 (setq member-expr (js2-parse-member-expr-tail nil name))
7916 (js2-parse-highlight-member-expr-fn-name member-expr)
7917 (js2-must-match js2-LP "msg.no.paren.parms")
7918 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7919 (js2-function-node-member-expr pn) member-expr)
7920 pn)
7921 (t
7922 (js2-report-error "msg.no.paren.parms")
7923 (make-js2-error-node))))))
7924
7925 (defun js2-parse-function-expr ()
7926 (let ((pos (js2-current-token-beg))
7927 (star-p (js2-match-token js2-MUL))
7928 name)
7929 (when (js2-match-token js2-NAME)
7930 (setq name (js2-create-name-node t)))
7931 (js2-must-match js2-LP "msg.no.paren.parms")
7932 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7933
7934 (defun js2-parse-function (function-type pos star-p &optional name)
7935 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7936 beginning of the first token (function keyword, unless it's an
7937 arrow function), NAME is js2-name-node."
7938 (let (fn-node lp)
7939 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7940 (setq lp (js2-current-token-beg)))
7941 (setf fn-node (make-js2-function-node :pos pos
7942 :name name
7943 :form function-type
7944 :lp (if lp (- lp pos))
7945 :generator-type (and star-p 'STAR)))
7946 (when name
7947 (js2-set-face (js2-node-pos name) (js2-node-end name)
7948 'font-lock-function-name-face 'record)
7949 (when (and (eq function-type 'FUNCTION_STATEMENT)
7950 (cl-plusp (js2-name-node-length name)))
7951 ;; Function statements define a symbol in the enclosing scope
7952 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7953 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
7954 ;; 1. Nested functions are not affected by the dynamic scope flag
7955 ;; as dynamic scope is already a parent of their scope.
7956 ;; 2. Functions defined under the with statement also immune to
7957 ;; this setup, in which case dynamic scope is ignored in favor
7958 ;; of the with object.
7959 (setf (js2-function-node-ignore-dynamic fn-node) t))
7960 ;; dynamically bind all the per-function variables
7961 (let ((js2-current-script-or-fn fn-node)
7962 (js2-current-scope fn-node)
7963 (js2-nesting-of-with 0)
7964 (js2-end-flags 0)
7965 js2-label-set
7966 js2-loop-set
7967 js2-loop-and-switch-set)
7968 (js2-parse-function-params function-type fn-node pos)
7969 (when (eq function-type 'FUNCTION_ARROW)
7970 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7971 (if (and (>= js2-language-version 180)
7972 (/= (js2-peek-token) js2-LC))
7973 (js2-parse-function-closure-body fn-node)
7974 (js2-parse-function-body fn-node))
7975 (js2-check-inconsistent-return-warning fn-node name)
7976
7977 (when name
7978 (js2-node-add-children fn-node name)
7979 ;; Function expressions define a name only in the body of the
7980 ;; function, and only if not hidden by a parameter name
7981 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7982 (null (js2-scope-get-symbol js2-current-scope
7983 (js2-name-node-name name))))
7984 (js2-define-symbol js2-FUNCTION
7985 (js2-name-node-name name)
7986 fn-node))
7987 (when (eq function-type 'FUNCTION_STATEMENT)
7988 (js2-record-imenu-functions fn-node))))
7989
7990 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7991 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7992 ;; We wait until after parsing the function to set its parent scope,
7993 ;; since `js2-define-symbol' needs the defining-scope check to stop
7994 ;; at the function boundary when checking for redeclarations.
7995 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7996 fn-node))
7997
7998 (defun js2-parse-statements (&optional parent)
7999 "Parse a statement list. Last token consumed must be js2-LC.
8000
8001 PARENT can be a `js2-block-node', in which case the statements are
8002 appended to PARENT. Otherwise a new `js2-block-node' is created
8003 and returned.
8004
8005 This function does not match the closing js2-RC: the caller
8006 matches the RC so it can provide a suitable error message if not
8007 matched. This means it's up to the caller to set the length of
8008 the node to include the closing RC. The node start pos is set to
8009 the absolute buffer start position, and the caller should fix it
8010 up to be relative to the parent node. All children of this block
8011 node are given relative start positions and correct lengths."
8012 (let ((pn (or parent (make-js2-block-node)))
8013 tt)
8014 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8015 (/= tt js2-RC))
8016 (js2-block-node-push pn (js2-parse-statement)))
8017 pn))
8018
8019 (defun js2-parse-statement ()
8020 (let (pn beg end)
8021 ;; coarse-grained user-interrupt check - needs work
8022 (and js2-parse-interruptable-p
8023 (zerop (% (cl-incf js2-parse-stmt-count)
8024 js2-statements-per-pause))
8025 (input-pending-p)
8026 (throw 'interrupted t))
8027 (setq pn (js2-statement-helper))
8028 ;; no-side-effects warning check
8029 (unless (js2-node-has-side-effects pn)
8030 (setq end (js2-node-end pn))
8031 (save-excursion
8032 (goto-char end)
8033 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8034 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8035 pn))
8036
8037 ;; These correspond to the switch cases in Parser.statementHelper
8038 (defconst js2-parsers
8039 (let ((parsers (make-vector js2-num-tokens
8040 #'js2-parse-expr-stmt)))
8041 (aset parsers js2-BREAK #'js2-parse-break)
8042 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8043 (aset parsers js2-CONST #'js2-parse-const-var)
8044 (aset parsers js2-CONTINUE #'js2-parse-continue)
8045 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8046 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8047 (aset parsers js2-DO #'js2-parse-do)
8048 (aset parsers js2-EXPORT #'js2-parse-export)
8049 (aset parsers js2-FOR #'js2-parse-for)
8050 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8051 (aset parsers js2-IF #'js2-parse-if)
8052 (aset parsers js2-IMPORT #'js2-parse-import)
8053 (aset parsers js2-LC #'js2-parse-block)
8054 (aset parsers js2-LET #'js2-parse-let-stmt)
8055 (aset parsers js2-NAME #'js2-parse-name-or-label)
8056 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8057 (aset parsers js2-SEMI #'js2-parse-semi)
8058 (aset parsers js2-SWITCH #'js2-parse-switch)
8059 (aset parsers js2-THROW #'js2-parse-throw)
8060 (aset parsers js2-TRY #'js2-parse-try)
8061 (aset parsers js2-VAR #'js2-parse-const-var)
8062 (aset parsers js2-WHILE #'js2-parse-while)
8063 (aset parsers js2-WITH #'js2-parse-with)
8064 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8065 parsers)
8066 "A vector mapping token types to parser functions.")
8067
8068 (defun js2-parse-warn-missing-semi (beg end)
8069 (and js2-mode-show-strict-warnings
8070 js2-strict-missing-semi-warning
8071 (js2-add-strict-warning
8072 "msg.missing.semi" nil
8073 ;; back up to beginning of statement or line
8074 (max beg (save-excursion
8075 (goto-char end)
8076 (point-at-bol)))
8077 end)))
8078
8079 (defconst js2-no-semi-insertion
8080 (list js2-IF
8081 js2-SWITCH
8082 js2-WHILE
8083 js2-DO
8084 js2-FOR
8085 js2-TRY
8086 js2-WITH
8087 js2-LC
8088 js2-ERROR
8089 js2-SEMI
8090 js2-CLASS
8091 js2-FUNCTION)
8092 "List of tokens that don't do automatic semicolon insertion.")
8093
8094 (defconst js2-autoinsert-semi-and-warn
8095 (list js2-ERROR js2-EOF js2-RC))
8096
8097 (defun js2-statement-helper ()
8098 (let* ((tt (js2-get-token))
8099 (first-tt tt)
8100 (parser (if (= tt js2-ERROR)
8101 #'js2-parse-semi
8102 (aref js2-parsers tt)))
8103 pn)
8104 ;; If the statement is set, then it's been told its label by now.
8105 (and js2-labeled-stmt
8106 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8107 (setq js2-labeled-stmt nil))
8108 (setq pn (funcall parser))
8109 ;; Don't do auto semi insertion for certain statement types.
8110 (unless (or (memq first-tt js2-no-semi-insertion)
8111 (js2-labeled-stmt-node-p pn))
8112 (js2-auto-insert-semicolon pn))
8113 pn))
8114
8115 (defun js2-auto-insert-semicolon (pn)
8116 (let* ((tt (js2-get-token))
8117 (pos (js2-node-pos pn)))
8118 (cond
8119 ((= tt js2-SEMI)
8120 ;; extend the node bounds to include the semicolon.
8121 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8122 ((memq tt js2-autoinsert-semi-and-warn)
8123 (js2-unget-token) ; Not ';', do not consume.
8124 ;; Autoinsert ;
8125 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8126 (t
8127 (if (not (js2-token-follows-eol-p (js2-current-token)))
8128 ;; Report error if no EOL or autoinsert ';' otherwise
8129 (js2-report-error "msg.no.semi.stmt")
8130 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8131 (js2-unget-token) ; Not ';', do not consume.
8132 ))))
8133
8134 (defun js2-parse-condition ()
8135 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8136 The parens are discarded and the expression node is returned.
8137 The `pos' field of the return value is set to an absolute position
8138 that must be fixed up by the caller.
8139 Return value is a list (EXPR LP RP), with absolute paren positions."
8140 (let (pn lp rp)
8141 (if (js2-must-match js2-LP "msg.no.paren.cond")
8142 (setq lp (js2-current-token-beg)))
8143 (setq pn (js2-parse-expr))
8144 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8145 (setq rp (js2-current-token-beg)))
8146 ;; Report strict warning on code like "if (a = 7) ..."
8147 (if (and js2-strict-cond-assign-warning
8148 (js2-assign-node-p pn))
8149 (js2-add-strict-warning "msg.equal.as.assign" nil
8150 (js2-node-pos pn)
8151 (+ (js2-node-pos pn)
8152 (js2-node-len pn))))
8153 (list pn lp rp)))
8154
8155 (defun js2-parse-if ()
8156 "Parser for if-statement. Last matched token must be js2-IF."
8157 (let ((pos (js2-current-token-beg))
8158 cond if-true if-false else-pos end pn)
8159 (setq cond (js2-parse-condition)
8160 if-true (js2-parse-statement)
8161 if-false (if (js2-match-token js2-ELSE)
8162 (progn
8163 (setq else-pos (- (js2-current-token-beg) pos))
8164 (js2-parse-statement)))
8165 end (js2-node-end (or if-false if-true))
8166 pn (make-js2-if-node :pos pos
8167 :len (- end pos)
8168 :condition (car cond)
8169 :then-part if-true
8170 :else-part if-false
8171 :else-pos else-pos
8172 :lp (js2-relpos (cl-second cond) pos)
8173 :rp (js2-relpos (cl-third cond) pos)))
8174 (js2-node-add-children pn (car cond) if-true if-false)
8175 pn))
8176
8177 (defun js2-parse-import ()
8178 "Parse import statement. The current token must be js2-IMPORT."
8179 (unless (js2-ast-root-p js2-current-scope)
8180 (js2-report-error "msg.mod.import.decl.at.top.level"))
8181 (let ((beg (js2-current-token-beg)))
8182 (cond ((js2-match-token js2-STRING)
8183 (make-js2-import-node
8184 :pos beg
8185 :len (- (js2-current-token-end) beg)
8186 :module-id (js2-current-token-string)))
8187 (t
8188 (let* ((import-clause (js2-parse-import-clause))
8189 (from-clause (and import-clause (js2-parse-from-clause)))
8190 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8191 (node (make-js2-import-node
8192 :pos beg
8193 :len (- (js2-current-token-end) beg)
8194 :import import-clause
8195 :from from-clause
8196 :module-id module-id)))
8197 (when import-clause
8198 (js2-node-add-children node import-clause))
8199 (when from-clause
8200 (js2-node-add-children node from-clause))
8201 node)))))
8202
8203 (defun js2-parse-import-clause ()
8204 "Parse the bindings in an import statement.
8205 This can take many forms:
8206
8207 ImportedDefaultBinding -> 'foo'
8208 NameSpaceImport -> '* as lib'
8209 NamedImports -> '{foo as bar, bang}'
8210 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8211 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8212
8213 Try to match namespace imports and named imports first because nothing can
8214 come after them. If it is an imported default binding, then it could have named
8215 imports or a namespace import that follows it.
8216 "
8217 (let* ((beg (js2-current-token-beg))
8218 (clause (make-js2-import-clause-node
8219 :pos beg))
8220 (children (list)))
8221 (cond
8222 ((js2-match-token js2-MUL)
8223 (let ((ns-import (js2-parse-namespace-import)))
8224 (when ns-import
8225 (let ((name-node (js2-namespace-import-node-name ns-import)))
8226 (js2-define-symbol
8227 js2-LET (js2-name-node-name name-node) name-node t)))
8228 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8229 (push ns-import children)))
8230 ((js2-match-token js2-LC)
8231 (let ((imports (js2-parse-export-bindings t)))
8232 (setf (js2-import-clause-node-named-imports clause) imports)
8233 (dolist (import imports)
8234 (push import children)
8235 (let ((name-node (js2-export-binding-node-local-name import)))
8236 (when name-node
8237 (js2-define-symbol
8238 js2-LET (js2-name-node-name name-node) name-node t))))))
8239 ((= (js2-peek-token) js2-NAME)
8240 (let ((binding (js2-maybe-parse-export-binding)))
8241 (let ((node-name (js2-export-binding-node-local-name binding)))
8242 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8243 (setf (js2-import-clause-node-default-binding clause) binding)
8244 (push binding children))
8245 (when (js2-match-token js2-COMMA)
8246 (cond
8247 ((js2-match-token js2-MUL)
8248 (let ((ns-import (js2-parse-namespace-import)))
8249 (let ((name-node (js2-namespace-import-node-name ns-import)))
8250 (js2-define-symbol
8251 js2-LET (js2-name-node-name name-node) name-node t))
8252 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8253 (push ns-import children)))
8254 ((js2-match-token js2-LC)
8255 (let ((imports (js2-parse-export-bindings t)))
8256 (setf (js2-import-clause-node-named-imports clause) imports)
8257 (dolist (import imports)
8258 (push import children)
8259 (let ((name-node (js2-export-binding-node-local-name import)))
8260 (when name-node
8261 (js2-define-symbol
8262 js2-LET (js2-name-node-name name-node) name-node t))))))
8263 (t (js2-report-error "msg.syntax")))))
8264 (t (js2-report-error "msg.mod.declaration.after.import")))
8265 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8266 (apply #'js2-node-add-children clause children)
8267 clause))
8268
8269 (defun js2-parse-namespace-import ()
8270 "Parse a namespace import expression such as '* as bar'.
8271 The current token must be js2-MUL."
8272 (let ((beg (js2-current-token-beg)))
8273 (when (js2-must-match js2-NAME "msg.syntax")
8274 (if (equal "as" (js2-current-token-string))
8275 (when (js2-must-match-prop-name "msg.syntax")
8276 (let ((node (make-js2-namespace-import-node
8277 :pos beg
8278 :len (- (js2-current-token-end) beg)
8279 :name (make-js2-name-node
8280 :pos (js2-current-token-beg)
8281 :len (js2-current-token-end)
8282 :name (js2-current-token-string)))))
8283 (js2-node-add-children node (js2-namespace-import-node-name node))
8284 node))
8285 (js2-unget-token)
8286 (js2-report-error "msg.syntax")))))
8287
8288
8289 (defun js2-parse-from-clause ()
8290 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8291 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8292 (let ((beg (js2-current-token-beg)))
8293 (if (equal "from" (js2-current-token-string))
8294 (cond
8295 ((js2-match-token js2-STRING)
8296 (make-js2-from-clause-node
8297 :pos beg
8298 :len (- (js2-current-token-end) beg)
8299 :module-id (js2-current-token-string)
8300 :metadata-p nil))
8301 ((js2-match-token js2-THIS)
8302 (when (js2-must-match-name "msg.mod.spec.after.from")
8303 (if (equal "module" (js2-current-token-string))
8304 (make-js2-from-clause-node
8305 :pos beg
8306 :len (- (js2-current-token-end) beg)
8307 :module-id "this"
8308 :metadata-p t)
8309 (js2-unget-token)
8310 (js2-unget-token)
8311 (js2-report-error "msg.mod.spec.after.from")
8312 nil)))
8313 (t (js2-report-error "msg.mod.spec.after.from") nil))
8314 (js2-unget-token)
8315 (js2-report-error "msg.mod.from.after.import.spec.set")
8316 nil))))
8317
8318 (defun js2-parse-export-bindings (&optional import-p)
8319 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8320 {foo as bar, baz as bang}. The current token must be
8321 js2-LC. Return a lisp list of js2-export-binding-node"
8322 (let ((bindings (list)))
8323 (while
8324 (let ((binding (js2-maybe-parse-export-binding)))
8325 (when binding
8326 (push binding bindings))
8327 (js2-match-token js2-COMMA)))
8328 (when (js2-must-match js2-RC (if import-p
8329 "msg.mod.rc.after.import.spec.list"
8330 "msg.mod.rc.after.export.spec.list"))
8331 (reverse bindings))))
8332
8333 (defun js2-maybe-parse-export-binding ()
8334 "Attempt to parse a binding expression found inside an import/export statement.
8335 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8336 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8337 js2-export-binding-node and consume all the tokens. If it does not match, it
8338 consumes no tokens."
8339 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8340 (beg (js2-current-token-beg))
8341 (extern-name-len (js2-current-token-len))
8342 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8343 (aref js2-kwd-tokens (js2-current-token-type)))))
8344 (if extern-name
8345 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8346 (if (and as (equal "as" (js2-current-token-string)))
8347 (let ((name
8348 (or
8349 (and (js2-match-token js2-DEFAULT) "default")
8350 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8351 (if name
8352 (let ((node (make-js2-export-binding-node
8353 :pos beg
8354 :len (- (js2-current-token-end) beg)
8355 :local-name (make-js2-name-node
8356 :name name
8357 :pos (js2-current-token-beg)
8358 :len (js2-current-token-len))
8359 :extern-name (make-js2-name-node
8360 :name extern-name
8361 :pos beg
8362 :len extern-name-len))))
8363 (js2-node-add-children
8364 node
8365 (js2-export-binding-node-local-name node)
8366 (js2-export-binding-node-extern-name node))
8367 node)
8368 (js2-unget-token)
8369 nil))
8370 (when as (js2-unget-token))
8371 (let* ((name-node (make-js2-name-node
8372 :name (js2-current-token-string)
8373 :pos (js2-current-token-beg)
8374 :len (js2-current-token-len)))
8375 (node (make-js2-export-binding-node
8376 :pos (js2-current-token-beg)
8377 :len (js2-current-token-len)
8378 :local-name name-node
8379 :extern-name name-node)))
8380 (when is-reserved-name
8381 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8382 (js2-node-add-children node name-node)
8383 node)))
8384 nil)))
8385
8386 (defun js2-parse-switch ()
8387 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8388 (let ((pos (js2-current-token-beg))
8389 tt pn discriminant has-default case-expr case-node
8390 case-pos cases stmt lp)
8391 (if (js2-must-match js2-LP "msg.no.paren.switch")
8392 (setq lp (js2-current-token-beg)))
8393 (setq discriminant (js2-parse-expr)
8394 pn (make-js2-switch-node :discriminant discriminant
8395 :pos pos
8396 :lp (js2-relpos lp pos)))
8397 (js2-node-add-children pn discriminant)
8398 (js2-enter-switch pn)
8399 (unwind-protect
8400 (progn
8401 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8402 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8403 (js2-must-match js2-LC "msg.no.brace.switch")
8404 (catch 'break
8405 (while t
8406 (setq tt (js2-next-token)
8407 case-pos (js2-current-token-beg))
8408 (cond
8409 ((= tt js2-RC)
8410 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8411 (throw 'break nil)) ; done
8412 ((= tt js2-CASE)
8413 (setq case-expr (js2-parse-expr))
8414 (js2-must-match js2-COLON "msg.no.colon.case"))
8415 ((= tt js2-DEFAULT)
8416 (if has-default
8417 (js2-report-error "msg.double.switch.default"))
8418 (setq has-default t
8419 case-expr nil)
8420 (js2-must-match js2-COLON "msg.no.colon.case"))
8421 (t
8422 (js2-report-error "msg.bad.switch")
8423 (throw 'break nil)))
8424 (setq case-node (make-js2-case-node :pos case-pos
8425 :len (- (js2-current-token-end) case-pos)
8426 :expr case-expr))
8427 (js2-node-add-children case-node case-expr)
8428 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8429 (/= tt js2-CASE)
8430 (/= tt js2-DEFAULT)
8431 (/= tt js2-EOF))
8432 (setf stmt (js2-parse-statement)
8433 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8434 (js2-block-node-push case-node stmt))
8435 (push case-node cases)))
8436 ;; add cases last, as pushing reverses the order to be correct
8437 (dolist (kid cases)
8438 (js2-node-add-children pn kid)
8439 (push kid (js2-switch-node-cases pn)))
8440 pn) ; return value
8441 (js2-exit-switch))))
8442
8443 (defun js2-parse-while ()
8444 "Parser for while-statement. Last matched token must be js2-WHILE."
8445 (let ((pos (js2-current-token-beg))
8446 (pn (make-js2-while-node))
8447 cond body)
8448 (js2-enter-loop pn)
8449 (unwind-protect
8450 (progn
8451 (setf cond (js2-parse-condition)
8452 (js2-while-node-condition pn) (car cond)
8453 body (js2-parse-statement)
8454 (js2-while-node-body pn) body
8455 (js2-node-len pn) (- (js2-node-end body) pos)
8456 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8457 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8458 (js2-node-add-children pn body (car cond)))
8459 (js2-exit-loop))
8460 pn))
8461
8462 (defun js2-parse-do ()
8463 "Parser for do-statement. Last matched token must be js2-DO."
8464 (let ((pos (js2-current-token-beg))
8465 (pn (make-js2-do-node))
8466 cond body end)
8467 (js2-enter-loop pn)
8468 (unwind-protect
8469 (progn
8470 (setq body (js2-parse-statement))
8471 (js2-must-match js2-WHILE "msg.no.while.do")
8472 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8473 cond (js2-parse-condition)
8474 (js2-do-node-condition pn) (car cond)
8475 (js2-do-node-body pn) body
8476 end js2-ts-cursor
8477 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8478 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8479 (js2-node-add-children pn (car cond) body))
8480 (js2-exit-loop))
8481 ;; Always auto-insert semicolon to follow SpiderMonkey:
8482 ;; It is required by ECMAScript but is ignored by the rest of
8483 ;; world; see bug 238945
8484 (if (js2-match-token js2-SEMI)
8485 (setq end js2-ts-cursor))
8486 (setf (js2-node-len pn) (- end pos))
8487 pn))
8488
8489 (defun js2-parse-export ()
8490 "Parse an export statement.
8491 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8492 expressions should only be either hoistable expressions (function or generator)
8493 or assignment expressions, but there is no checking to enforce that and so it
8494 will parse without error a small subset of
8495 invalid export statements."
8496 (unless (js2-ast-root-p js2-current-scope)
8497 (js2-report-error "msg.mod.export.decl.at.top.level"))
8498 (let ((beg (js2-current-token-beg))
8499 (children (list))
8500 exports-list from-clause declaration default)
8501 (cond
8502 ((js2-match-token js2-MUL)
8503 (setq from-clause (js2-parse-from-clause))
8504 (when from-clause
8505 (push from-clause children)))
8506 ((js2-match-token js2-LC)
8507 (setq exports-list (js2-parse-export-bindings))
8508 (when exports-list
8509 (dolist (export exports-list)
8510 (push export children)))
8511 (when (js2-match-token js2-NAME)
8512 (if (equal "from" (js2-current-token-string))
8513 (progn
8514 (js2-unget-token)
8515 (setq from-clause (js2-parse-from-clause)))
8516 (js2-unget-token))))
8517 ((js2-match-token js2-DEFAULT)
8518 (setq default (js2-parse-expr)))
8519 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8520 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8521 (t
8522 (setq declaration (js2-parse-expr))))
8523 (when from-clause
8524 (push from-clause children))
8525 (when declaration
8526 (push declaration children))
8527 (when default
8528 (push default children))
8529 (let ((node (make-js2-export-node
8530 :pos beg
8531 :len (- (js2-current-token-end) beg)
8532 :exports-list exports-list
8533 :from-clause from-clause
8534 :declaration declaration
8535 :default default)))
8536 (apply #'js2-node-add-children node children)
8537 node)))
8538
8539 (defun js2-parse-for ()
8540 "Parse a for, for-in or for each-in statement.
8541 Last matched token must be js2-FOR."
8542 (let ((for-pos (js2-current-token-beg))
8543 pn is-for-each is-for-in-or-of is-for-of
8544 in-pos each-pos tmp-pos
8545 init ; Node init is also foo in 'foo in object'.
8546 cond ; Node cond is also object in 'foo in object'.
8547 incr ; 3rd section of for-loop initializer.
8548 body tt lp rp)
8549 ;; See if this is a for each () instead of just a for ()
8550 (when (js2-match-token js2-NAME)
8551 (if (string= "each" (js2-current-token-string))
8552 (progn
8553 (setq is-for-each t
8554 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8555 (js2-record-face 'font-lock-keyword-face))
8556 (js2-report-error "msg.no.paren.for")))
8557 (if (js2-must-match js2-LP "msg.no.paren.for")
8558 (setq lp (- (js2-current-token-beg) for-pos)))
8559 (setq tt (js2-get-token))
8560 ;; 'for' makes local scope
8561 (js2-push-scope (make-js2-scope))
8562 (unwind-protect
8563 ;; parse init clause
8564 (let ((js2-in-for-init t)) ; set as dynamic variable
8565 (cond
8566 ((= tt js2-SEMI)
8567 (js2-unget-token)
8568 (setq init (make-js2-empty-expr-node)))
8569 ((or (= tt js2-VAR) (= tt js2-LET))
8570 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8571 (t
8572 (js2-unget-token)
8573 (setq init (js2-parse-expr)))))
8574 (if (or (js2-match-token js2-IN)
8575 (and (>= js2-language-version 200)
8576 (js2-match-contextual-kwd "of")
8577 (setq is-for-of t)))
8578 (setq is-for-in-or-of t
8579 in-pos (- (js2-current-token-beg) for-pos)
8580 ;; scope of iteration target object is not the scope we've created above.
8581 ;; stash current scope temporary.
8582 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8583 (js2-parse-expr))) ; object over which we're iterating
8584 ;; else ordinary for loop - parse cond and incr
8585 (js2-must-match js2-SEMI "msg.no.semi.for")
8586 (setq cond (if (= (js2-peek-token) js2-SEMI)
8587 (make-js2-empty-expr-node) ; no loop condition
8588 (js2-parse-expr)))
8589 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8590 (setq tmp-pos (js2-current-token-end)
8591 incr (if (= (js2-peek-token) js2-RP)
8592 (make-js2-empty-expr-node :pos tmp-pos)
8593 (js2-parse-expr))))
8594 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8595 (setq rp (- (js2-current-token-beg) for-pos)))
8596 (if (not is-for-in-or-of)
8597 (setq pn (make-js2-for-node :init init
8598 :condition cond
8599 :update incr
8600 :lp lp
8601 :rp rp))
8602 ;; cond could be null if 'in obj' got eaten by the init node.
8603 (if (js2-infix-node-p init)
8604 ;; it was (foo in bar) instead of (var foo in bar)
8605 (setq cond (js2-infix-node-right init)
8606 init (js2-infix-node-left init))
8607 (if (and (js2-var-decl-node-p init)
8608 (> (length (js2-var-decl-node-kids init)) 1))
8609 (js2-report-error "msg.mult.index")))
8610 (setq pn (make-js2-for-in-node :iterator init
8611 :object cond
8612 :in-pos in-pos
8613 :foreach-p is-for-each
8614 :each-pos each-pos
8615 :forof-p is-for-of
8616 :lp lp
8617 :rp rp)))
8618 (unwind-protect
8619 (progn
8620 (js2-enter-loop pn)
8621 ;; We have to parse the body -after- creating the loop node,
8622 ;; so that the loop node appears in the js2-loop-set, allowing
8623 ;; break/continue statements to find the enclosing loop.
8624 (setf body (js2-parse-statement)
8625 (js2-loop-node-body pn) body
8626 (js2-node-pos pn) for-pos
8627 (js2-node-len pn) (- (js2-node-end body) for-pos))
8628 (js2-node-add-children pn init cond incr body))
8629 ;; finally
8630 (js2-exit-loop))
8631 (js2-pop-scope))
8632 pn))
8633
8634 (defun js2-parse-try ()
8635 "Parse a try statement. Last matched token must be js2-TRY."
8636 (let ((try-pos (js2-current-token-beg))
8637 try-end
8638 try-block
8639 catch-blocks
8640 finally-block
8641 saw-default-catch
8642 peek)
8643 (if (/= (js2-peek-token) js2-LC)
8644 (js2-report-error "msg.no.brace.try"))
8645 (setq try-block (js2-parse-statement)
8646 try-end (js2-node-end try-block)
8647 peek (js2-peek-token))
8648 (cond
8649 ((= peek js2-CATCH)
8650 (while (js2-match-token js2-CATCH)
8651 (let* ((catch-pos (js2-current-token-beg))
8652 (catch-node (make-js2-catch-node :pos catch-pos))
8653 param
8654 guard-kwd
8655 catch-cond
8656 lp rp)
8657 (if saw-default-catch
8658 (js2-report-error "msg.catch.unreachable"))
8659 (if (js2-must-match js2-LP "msg.no.paren.catch")
8660 (setq lp (- (js2-current-token-beg) catch-pos)))
8661 (js2-push-scope catch-node)
8662 (let ((tt (js2-peek-token)))
8663 (cond
8664 ;; Destructuring pattern:
8665 ;; catch ({ message, file }) { ... }
8666 ((or (= tt js2-LB) (= tt js2-LC))
8667 (js2-get-token)
8668 (setq param (js2-parse-destruct-primary-expr))
8669 (js2-define-destruct-symbols param js2-LET nil))
8670 ;; Simple name.
8671 (t
8672 (js2-must-match-name "msg.bad.catchcond")
8673 (setq param (js2-create-name-node))
8674 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8675 ;; Catch condition.
8676 (if (js2-match-token js2-IF)
8677 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8678 catch-cond (js2-parse-expr))
8679 (setq saw-default-catch t))
8680 (if (js2-must-match js2-RP "msg.bad.catchcond")
8681 (setq rp (- (js2-current-token-beg) catch-pos)))
8682 (js2-must-match js2-LC "msg.no.brace.catchblock")
8683 (js2-parse-statements catch-node)
8684 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8685 (setq try-end (js2-current-token-end)))
8686 (js2-pop-scope)
8687 (setf (js2-node-len catch-node) (- try-end catch-pos)
8688 (js2-catch-node-param catch-node) param
8689 (js2-catch-node-guard-expr catch-node) catch-cond
8690 (js2-catch-node-guard-kwd catch-node) guard-kwd
8691 (js2-catch-node-lp catch-node) lp
8692 (js2-catch-node-rp catch-node) rp)
8693 (js2-node-add-children catch-node param catch-cond)
8694 (push catch-node catch-blocks))))
8695 ((/= peek js2-FINALLY)
8696 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8697 (js2-node-pos try-block)
8698 (- (setq try-end (js2-node-end try-block))
8699 (js2-node-pos try-block)))))
8700 (when (js2-match-token js2-FINALLY)
8701 (let ((finally-pos (js2-current-token-beg))
8702 (block (js2-parse-statement)))
8703 (setq try-end (js2-node-end block)
8704 finally-block (make-js2-finally-node :pos finally-pos
8705 :len (- try-end finally-pos)
8706 :body block))
8707 (js2-node-add-children finally-block block)))
8708 (let ((pn (make-js2-try-node :pos try-pos
8709 :len (- try-end try-pos)
8710 :try-block try-block
8711 :finally-block finally-block)))
8712 (js2-node-add-children pn try-block finally-block)
8713 ;; Push them onto the try-node, which reverses and corrects their order.
8714 (dolist (cb catch-blocks)
8715 (js2-node-add-children pn cb)
8716 (push cb (js2-try-node-catch-clauses pn)))
8717 pn)))
8718
8719 (defun js2-parse-throw ()
8720 "Parser for throw-statement. Last matched token must be js2-THROW."
8721 (let ((pos (js2-current-token-beg))
8722 expr pn)
8723 (if (= (js2-peek-token-or-eol) js2-EOL)
8724 ;; ECMAScript does not allow new lines before throw expression,
8725 ;; see bug 256617
8726 (js2-report-error "msg.bad.throw.eol"))
8727 (setq expr (js2-parse-expr)
8728 pn (make-js2-throw-node :pos pos
8729 :len (- (js2-node-end expr) pos)
8730 :expr expr))
8731 (js2-node-add-children pn expr)
8732 pn))
8733
8734 (defun js2-match-jump-label-name (label-name)
8735 "If break/continue specified a label, return that label's labeled stmt.
8736 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8737 does not match an existing label, reports an error and returns nil."
8738 (let ((bundle (cdr (assoc label-name js2-label-set))))
8739 (if (null bundle)
8740 (js2-report-error "msg.undef.label"))
8741 bundle))
8742
8743 (defun js2-parse-break ()
8744 "Parser for break-statement. Last matched token must be js2-BREAK."
8745 (let ((pos (js2-current-token-beg))
8746 (end (js2-current-token-end))
8747 break-target ; statement to break from
8748 break-label ; in "break foo", name-node representing the foo
8749 labels ; matching labeled statement to break to
8750 pn)
8751 (when (eq (js2-peek-token-or-eol) js2-NAME)
8752 (js2-get-token)
8753 (setq break-label (js2-create-name-node)
8754 end (js2-node-end break-label)
8755 ;; matchJumpLabelName only matches if there is one
8756 labels (js2-match-jump-label-name (js2-current-token-string))
8757 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8758 (unless (or break-target break-label)
8759 ;; no break target specified - try for innermost enclosing loop/switch
8760 (if (null js2-loop-and-switch-set)
8761 (unless break-label
8762 (js2-report-error "msg.bad.break" nil pos (length "break")))
8763 (setq break-target (car js2-loop-and-switch-set))))
8764 (setq pn (make-js2-break-node :pos pos
8765 :len (- end pos)
8766 :label break-label
8767 :target break-target))
8768 (js2-node-add-children pn break-label) ; but not break-target
8769 pn))
8770
8771 (defun js2-parse-continue ()
8772 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8773 (let ((pos (js2-current-token-beg))
8774 (end (js2-current-token-end))
8775 label ; optional user-specified label, a `js2-name-node'
8776 labels ; current matching labeled stmt, if any
8777 target ; the `js2-loop-node' target of this continue stmt
8778 pn)
8779 (when (= (js2-peek-token-or-eol) js2-NAME)
8780 (js2-get-token)
8781 (setq label (js2-create-name-node)
8782 end (js2-node-end label)
8783 ;; matchJumpLabelName only matches if there is one
8784 labels (js2-match-jump-label-name (js2-current-token-string))))
8785 (cond
8786 ((null labels) ; no current label to go to
8787 (if (null js2-loop-set) ; no loop to continue to
8788 (js2-report-error "msg.continue.outside" nil pos
8789 (length "continue"))
8790 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8791 (t
8792 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8793 (setq target (js2-labeled-stmt-node-stmt labels))
8794 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8795 (setq pn (make-js2-continue-node :pos pos
8796 :len (- end pos)
8797 :label label
8798 :target target))
8799 (js2-node-add-children pn label) ; but not target - it's not our child
8800 pn))
8801
8802 (defun js2-parse-with ()
8803 "Parser for with-statement. Last matched token must be js2-WITH."
8804 (let ((pos (js2-current-token-beg))
8805 obj body pn lp rp)
8806 (if (js2-must-match js2-LP "msg.no.paren.with")
8807 (setq lp (js2-current-token-beg)))
8808 (setq obj (js2-parse-expr))
8809 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8810 (setq rp (js2-current-token-beg)))
8811 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8812 (setq body (js2-parse-statement)))
8813 (setq pn (make-js2-with-node :pos pos
8814 :len (- (js2-node-end body) pos)
8815 :object obj
8816 :body body
8817 :lp (js2-relpos lp pos)
8818 :rp (js2-relpos rp pos)))
8819 (js2-node-add-children pn obj body)
8820 pn))
8821
8822 (defun js2-parse-const-var ()
8823 "Parser for var- or const-statement.
8824 Last matched token must be js2-CONST or js2-VAR."
8825 (let ((tt (js2-current-token-type))
8826 (pos (js2-current-token-beg))
8827 expr pn)
8828 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8829 pn (make-js2-expr-stmt-node :pos pos
8830 :len (- (js2-node-end expr) pos)
8831 :expr expr))
8832 (js2-node-add-children pn expr)
8833 pn))
8834
8835 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8836 (let ((pn (make-js2-expr-stmt-node :pos pos
8837 :len (js2-node-len expr)
8838 :type (if (js2-inside-function)
8839 js2-EXPR_VOID
8840 js2-EXPR_RESULT)
8841 :expr expr)))
8842 (if add-child
8843 (js2-node-add-children pn expr))
8844 pn))
8845
8846 (defun js2-parse-let-stmt ()
8847 "Parser for let-statement. Last matched token must be js2-LET."
8848 (let ((pos (js2-current-token-beg))
8849 expr pn)
8850 (if (= (js2-peek-token) js2-LP)
8851 ;; let expression in statement context
8852 (setq expr (js2-parse-let pos 'statement)
8853 pn (js2-wrap-with-expr-stmt pos expr t))
8854 ;; else we're looking at a statement like let x=6, y=7;
8855 (setf expr (js2-parse-variables js2-LET pos)
8856 pn (js2-wrap-with-expr-stmt pos expr t)
8857 (js2-node-type pn) js2-EXPR_RESULT))
8858 pn))
8859
8860 (defun js2-parse-ret-yield ()
8861 (js2-parse-return-or-yield (js2-current-token-type) nil))
8862
8863 (defconst js2-parse-return-stmt-enders
8864 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8865
8866 (defsubst js2-now-all-set (before after mask)
8867 "Return whether or not the bits in the mask have changed to all set.
8868 BEFORE is bits before change, AFTER is bits after change, and MASK is
8869 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8870 but not BEFORE."
8871 (and (/= (logand before mask) mask)
8872 (= (logand after mask) mask)))
8873
8874 (defun js2-parse-return-or-yield (tt expr-context)
8875 (let* ((pos (js2-current-token-beg))
8876 (end (js2-current-token-end))
8877 (before js2-end-flags)
8878 (inside-function (js2-inside-function))
8879 (gen-type (and inside-function (js2-function-node-generator-type
8880 js2-current-script-or-fn)))
8881 e ret name yield-star-p)
8882 (unless inside-function
8883 (js2-report-error (if (eq tt js2-RETURN)
8884 "msg.bad.return"
8885 "msg.bad.yield")))
8886 (when (and inside-function
8887 (eq gen-type 'STAR)
8888 (js2-match-token js2-MUL))
8889 (setq yield-star-p t))
8890 ;; This is ugly, but we don't want to require a semicolon.
8891 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8892 (setq e (js2-parse-expr)
8893 end (js2-node-end e)))
8894 (cond
8895 ((eq tt js2-RETURN)
8896 (js2-set-flag js2-end-flags (if (null e)
8897 js2-end-returns
8898 js2-end-returns-value))
8899 (setq ret (make-js2-return-node :pos pos
8900 :len (- end pos)
8901 :retval e))
8902 (js2-node-add-children ret e)
8903 ;; See if we need a strict mode warning.
8904 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8905 ;; more thorough and accurate than this before/after flag check.
8906 ;; E.g. if there's a finally-block that always returns, we shouldn't
8907 ;; show a warning generated by inconsistent returns in the catch blocks.
8908 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8909 ;; so we know which returns/yields to highlight, and we should get rid of
8910 ;; all the checking in `js2-parse-return-or-yield'.
8911 (if (and js2-strict-inconsistent-return-warning
8912 (js2-now-all-set before js2-end-flags
8913 (logior js2-end-returns js2-end-returns-value)))
8914 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8915 ((eq gen-type 'COMPREHENSION)
8916 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8917 ;; like SpiderMonkey does.
8918 (js2-report-error "msg.syntax" nil pos 5))
8919 (t
8920 (setq ret (make-js2-yield-node :pos pos
8921 :len (- end pos)
8922 :value e
8923 :star-p yield-star-p))
8924 (js2-node-add-children ret e)
8925 (unless expr-context
8926 (setq e ret
8927 ret (js2-wrap-with-expr-stmt pos e t))
8928 (js2-set-requires-activation)
8929 (js2-set-is-generator))))
8930 ;; see if we are mixing yields and value returns.
8931 (when (and inside-function
8932 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8933 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8934 'LEGACY))
8935 (setq name (js2-function-name js2-current-script-or-fn))
8936 (if (zerop (length name))
8937 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8938 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8939 ret))
8940
8941 (defun js2-parse-debugger ()
8942 (make-js2-keyword-node :type js2-DEBUGGER))
8943
8944 (defun js2-parse-block ()
8945 "Parser for a curly-delimited statement block.
8946 Last token matched must be `js2-LC'."
8947 (let ((pos (js2-current-token-beg))
8948 (pn (make-js2-scope)))
8949 (js2-push-scope pn)
8950 (unwind-protect
8951 (progn
8952 (js2-parse-statements pn)
8953 (js2-must-match js2-RC "msg.no.brace.block")
8954 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8955 (js2-pop-scope))
8956 pn))
8957
8958 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8959 (defun js2-parse-semi ()
8960 "Parse a statement or handle an error.
8961 Current token type is `js2-SEMI' or `js2-ERROR'."
8962 (let ((tt (js2-current-token-type)) pos len)
8963 (if (eq tt js2-SEMI)
8964 (make-js2-empty-expr-node :len 1)
8965 (setq pos (js2-current-token-beg)
8966 len (- (js2-current-token-end) pos))
8967 (js2-report-error "msg.syntax" nil pos len)
8968 (make-js2-error-node :pos pos :len len))))
8969
8970 (defun js2-parse-default-xml-namespace ()
8971 "Parse a `default xml namespace = <expr>' e4x statement."
8972 (let ((pos (js2-current-token-beg))
8973 end len expr unary)
8974 (js2-must-have-xml)
8975 (js2-set-requires-activation)
8976 (setq len (- js2-ts-cursor pos))
8977 (unless (and (js2-match-token js2-NAME)
8978 (string= (js2-current-token-string) "xml"))
8979 (js2-report-error "msg.bad.namespace" nil pos len))
8980 (unless (and (js2-match-token js2-NAME)
8981 (string= (js2-current-token-string) "namespace"))
8982 (js2-report-error "msg.bad.namespace" nil pos len))
8983 (unless (js2-match-token js2-ASSIGN)
8984 (js2-report-error "msg.bad.namespace" nil pos len))
8985 (setq expr (js2-parse-expr)
8986 end (js2-node-end expr)
8987 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8988 :pos pos
8989 :len (- end pos)
8990 :operand expr))
8991 (js2-node-add-children unary expr)
8992 (make-js2-expr-stmt-node :pos pos
8993 :len (- end pos)
8994 :expr unary)))
8995
8996 (defun js2-record-label (label bundle)
8997 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8998 (js2-get-token)
8999 (let ((name (js2-label-node-name label))
9000 labeled-stmt
9001 dup)
9002 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9003 ;; flag both labels if possible when used in editing mode
9004 (if (and js2-parse-ide-mode
9005 (setq dup (js2-get-label-by-name labeled-stmt name)))
9006 (js2-report-error "msg.dup.label" nil
9007 (js2-node-abs-pos dup) (js2-node-len dup)))
9008 (js2-report-error "msg.dup.label" nil
9009 (js2-node-pos label) (js2-node-len label)))
9010 (js2-labeled-stmt-node-add-label bundle label)
9011 (js2-node-add-children bundle label)
9012 ;; Add one reference to the bundle per label in `js2-label-set'
9013 (push (cons name bundle) js2-label-set)))
9014
9015 (defun js2-parse-name-or-label ()
9016 "Parser for identifier or label. Last token matched must be js2-NAME.
9017 Called when we found a name in a statement context. If it's a label, we gather
9018 up any following labels and the next non-label statement into a
9019 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9020 expression and return it wrapped in a `js2-expr-stmt-node'."
9021 (let ((pos (js2-current-token-beg))
9022 expr stmt bundle
9023 (continue t))
9024 ;; set check for label and call down to `js2-parse-primary-expr'
9025 (setq expr (js2-maybe-parse-label))
9026 (if (null expr)
9027 ;; Parse the non-label expression and wrap with expression stmt.
9028 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9029 ;; else parsed a label
9030 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9031 (js2-record-label expr bundle)
9032 ;; look for more labels
9033 (while (and continue (= (js2-get-token) js2-NAME))
9034 (if (setq expr (js2-maybe-parse-label))
9035 (js2-record-label expr bundle)
9036 (setq expr (js2-parse-expr)
9037 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9038 continue nil)
9039 (js2-auto-insert-semicolon stmt)))
9040 ;; no more labels; now parse the labeled statement
9041 (unwind-protect
9042 (unless stmt
9043 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9044 (js2-unget-token)
9045 (setq stmt (js2-statement-helper))))
9046 ;; remove the labels for this statement from the global set
9047 (dolist (label (js2-labeled-stmt-node-labels bundle))
9048 (setq js2-label-set (remove label js2-label-set))))
9049 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9050 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9051 (js2-node-add-children bundle stmt)
9052 bundle)))
9053
9054 (defun js2-maybe-parse-label ()
9055 (cl-assert (= (js2-current-token-type) js2-NAME))
9056 (let (label-pos
9057 (next-tt (js2-get-token))
9058 (label-end (js2-current-token-end)))
9059 ;; Do not consume colon, it is used as unwind indicator
9060 ;; to return to statementHelper.
9061 (js2-unget-token)
9062 (if (= next-tt js2-COLON)
9063 (prog2
9064 (setq label-pos (js2-current-token-beg))
9065 (make-js2-label-node :pos label-pos
9066 :len (- label-end label-pos)
9067 :name (js2-current-token-string))
9068 (js2-set-face label-pos
9069 label-end
9070 'font-lock-variable-name-face 'record))
9071 ;; Backtrack from the name token, too.
9072 (js2-unget-token)
9073 nil)))
9074
9075 (defun js2-parse-expr-stmt ()
9076 "Default parser in statement context, if no recognized statement found."
9077 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9078 (progn
9079 (js2-unget-token)
9080 (js2-parse-expr)) t))
9081
9082 (defun js2-parse-variables (decl-type pos)
9083 "Parse a comma-separated list of variable declarations.
9084 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9085
9086 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9087 For 'var' or 'const', the keyword should be the token last scanned.
9088
9089 POS is the position where the node should start. It's sometimes the
9090 var/const/let keyword, and other times the beginning of the first token
9091 in the first variable declaration.
9092
9093 Returns the parsed `js2-var-decl-node' expression node."
9094 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9095 :pos pos))
9096 destructuring kid-pos tt init name end nbeg nend vi
9097 (continue t))
9098 ;; Example:
9099 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9100 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9101 ;; var {a, b} = baz;
9102 (while continue
9103 (setq destructuring nil
9104 name nil
9105 tt (js2-get-token)
9106 kid-pos (js2-current-token-beg)
9107 end (js2-current-token-end)
9108 init nil)
9109 (if (or (= tt js2-LB) (= tt js2-LC))
9110 ;; Destructuring assignment, e.g., var [a, b] = ...
9111 (setq destructuring (js2-parse-destruct-primary-expr)
9112 end (js2-node-end destructuring))
9113 ;; Simple variable name
9114 (js2-unget-token)
9115 (when (js2-must-match-name "msg.bad.var")
9116 (setq name (js2-create-name-node)
9117 nbeg (js2-current-token-beg)
9118 nend (js2-current-token-end)
9119 end nend)
9120 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9121 (when (js2-match-token js2-ASSIGN)
9122 (setq init (js2-parse-assign-expr)
9123 end (js2-node-end init))
9124 (js2-record-imenu-functions init name))
9125 (when name
9126 (js2-set-face nbeg nend (if (js2-function-node-p init)
9127 'font-lock-function-name-face
9128 'font-lock-variable-name-face)
9129 'record))
9130 (setq vi (make-js2-var-init-node :pos kid-pos
9131 :len (- end kid-pos)
9132 :type decl-type))
9133 (if destructuring
9134 (progn
9135 (if (and (null init) (not js2-in-for-init))
9136 (js2-report-error "msg.destruct.assign.no.init"))
9137 (js2-define-destruct-symbols destructuring
9138 decl-type
9139 'font-lock-variable-name-face)
9140 (setf (js2-var-init-node-target vi) destructuring))
9141 (setf (js2-var-init-node-target vi) name))
9142 (setf (js2-var-init-node-initializer vi) init)
9143 (js2-node-add-children vi name destructuring init)
9144 (js2-block-node-push result vi)
9145 (unless (js2-match-token js2-COMMA)
9146 (setq continue nil)))
9147 (setf (js2-node-len result) (- end pos))
9148 result))
9149
9150 (defun js2-parse-let (pos &optional stmt-p)
9151 "Parse a let expression or statement.
9152 A let-expression is of the form `let (vars) expr'.
9153 A let-statment is of the form `let (vars) {statements}'.
9154 The third form of let is a variable declaration list, handled
9155 by `js2-parse-variables'."
9156 (let ((pn (make-js2-let-node :pos pos))
9157 beg vars body)
9158 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9159 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9160 (js2-push-scope pn)
9161 (unwind-protect
9162 (progn
9163 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9164 (if (js2-must-match js2-RP "msg.no.paren.let")
9165 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9166 (if (and stmt-p (js2-match-token js2-LC))
9167 ;; let statement
9168 (progn
9169 (setf beg (js2-current-token-beg) ; position stmt at LC
9170 body (js2-parse-statements))
9171 (js2-must-match js2-RC "msg.no.curly.let")
9172 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9173 (js2-node-len pn) (- (js2-current-token-end) pos)
9174 (js2-let-node-body pn) body
9175 (js2-node-type pn) js2-LET))
9176 ;; let expression
9177 (setf body (js2-parse-expr)
9178 (js2-node-len pn) (- (js2-node-end body) pos)
9179 (js2-let-node-body pn) body))
9180 (setf (js2-let-node-vars pn) vars)
9181 (js2-node-add-children pn vars body))
9182 (js2-pop-scope))
9183 pn))
9184
9185 (defun js2-define-new-symbol (decl-type name node &optional scope)
9186 (js2-scope-put-symbol (or scope js2-current-scope)
9187 name
9188 (make-js2-symbol decl-type name node)))
9189
9190 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9191 "Define a symbol in the current scope.
9192 If NODE is non-nil, it is the AST node associated with the symbol."
9193 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9194 (symbol (if defining-scope
9195 (js2-scope-get-symbol defining-scope name)))
9196 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9197 (pos (if node (js2-node-abs-pos node)))
9198 (len (if node (js2-node-len node))))
9199 (cond
9200 ((and symbol ; already defined
9201 (or (= sdt js2-CONST) ; old version is const
9202 (= decl-type js2-CONST) ; new version is const
9203 ;; two let-bound vars in this block have same name
9204 (and (= sdt js2-LET)
9205 (eq defining-scope js2-current-scope))))
9206 (js2-report-error
9207 (cond
9208 ((= sdt js2-CONST) "msg.const.redecl")
9209 ((= sdt js2-LET) "msg.let.redecl")
9210 ((= sdt js2-VAR) "msg.var.redecl")
9211 ((= sdt js2-FUNCTION) "msg.function.redecl")
9212 (t "msg.parm.redecl"))
9213 name pos len))
9214 ((= decl-type js2-LET)
9215 (if (and (not ignore-not-in-block)
9216 (or (= (js2-node-type js2-current-scope) js2-IF)
9217 (js2-loop-node-p js2-current-scope)))
9218 (js2-report-error "msg.let.decl.not.in.block")
9219 (js2-define-new-symbol decl-type name node)))
9220 ((or (= decl-type js2-VAR)
9221 (= decl-type js2-CONST)
9222 (= decl-type js2-FUNCTION))
9223 (if symbol
9224 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9225 (js2-add-strict-warning "msg.var.redecl" name)
9226 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9227 (js2-add-strict-warning "msg.var.hides.arg" name)))
9228 (js2-define-new-symbol decl-type name node
9229 js2-current-script-or-fn)))
9230 ((= decl-type js2-LP)
9231 (if symbol
9232 ;; must be duplicate parameter. Second parameter hides the
9233 ;; first, so go ahead and add the second pararameter
9234 (js2-report-warning "msg.dup.parms" name))
9235 (js2-define-new-symbol decl-type name node))
9236 (t (js2-code-bug)))))
9237
9238 (defun js2-parse-paren-expr-or-generator-comp ()
9239 (let ((px-pos (js2-current-token-beg)))
9240 (cond
9241 ((and (>= js2-language-version 200)
9242 (js2-match-token js2-FOR))
9243 (js2-parse-generator-comp px-pos))
9244 ((and (>= js2-language-version 200)
9245 (js2-match-token js2-RP))
9246 ;; Not valid expression syntax, but this is valid in an arrow
9247 ;; function with no params: () => body.
9248 (if (eq (js2-peek-token) js2-ARROW)
9249 ;; Return whatever, it will hopefully be rewinded and
9250 ;; reparsed when we reach the =>.
9251 (make-js2-keyword-node :type js2-NULL)
9252 (js2-report-error "msg.syntax")
9253 (make-js2-error-node)))
9254 (t
9255 (let* ((js2-in-for-init nil)
9256 (expr (js2-parse-expr))
9257 (pn (make-js2-paren-node :pos px-pos
9258 :expr expr
9259 :len (- (js2-current-token-end)
9260 px-pos))))
9261 (js2-node-add-children pn (js2-paren-node-expr pn))
9262 (js2-must-match js2-RP "msg.no.paren")
9263 pn)))))
9264
9265 (defun js2-parse-expr (&optional oneshot)
9266 (let* ((pn (js2-parse-assign-expr))
9267 (pos (js2-node-pos pn))
9268 left
9269 right
9270 op-pos)
9271 (while (and (not oneshot)
9272 (js2-match-token js2-COMMA))
9273 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9274 (if (= (js2-peek-token) js2-YIELD)
9275 (js2-report-error "msg.yield.parenthesized"))
9276 (setq right (js2-parse-assign-expr)
9277 left pn
9278 pn (make-js2-infix-node :type js2-COMMA
9279 :pos pos
9280 :len (- js2-ts-cursor pos)
9281 :op-pos op-pos
9282 :left left
9283 :right right))
9284 (js2-node-add-children pn left right))
9285 pn))
9286
9287 (defun js2-parse-assign-expr ()
9288 (let ((tt (js2-get-token))
9289 (pos (js2-current-token-beg))
9290 pn left right op-pos
9291 ts-state recorded-identifiers parsed-errors)
9292 (if (= tt js2-YIELD)
9293 (js2-parse-return-or-yield tt t)
9294 ;; Save the tokenizer state in case we find an arrow function
9295 ;; and have to rewind.
9296 (setq ts-state (make-js2-ts-state)
9297 recorded-identifiers js2-recorded-identifiers
9298 parsed-errors js2-parsed-errors)
9299 ;; not yield - parse assignment expression
9300 (setq pn (js2-parse-cond-expr)
9301 tt (js2-get-token))
9302 (cond
9303 ((and (<= js2-first-assign tt)
9304 (<= tt js2-last-assign))
9305 ;; tt express assignment (=, |=, ^=, ..., %=)
9306 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9307 left pn)
9308 (setq right (js2-parse-assign-expr)
9309 pn (make-js2-assign-node :type tt
9310 :pos pos
9311 :len (- (js2-node-end right) pos)
9312 :op-pos op-pos
9313 :left left
9314 :right right))
9315 (when js2-parse-ide-mode
9316 (js2-highlight-assign-targets pn left right)
9317 (js2-record-imenu-functions right left))
9318 ;; do this last so ide checks above can use absolute positions
9319 (js2-node-add-children pn left right))
9320 ((and (= tt js2-ARROW)
9321 (>= js2-language-version 200))
9322 (js2-ts-seek ts-state)
9323 (setq js2-recorded-identifiers recorded-identifiers
9324 js2-parsed-errors parsed-errors)
9325 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9326 (t
9327 (js2-unget-token)))
9328 pn)))
9329
9330 (defun js2-parse-cond-expr ()
9331 (let ((pos (js2-current-token-beg))
9332 (pn (js2-parse-or-expr))
9333 test-expr
9334 if-true
9335 if-false
9336 q-pos
9337 c-pos)
9338 (when (js2-match-token js2-HOOK)
9339 (setq q-pos (- (js2-current-token-beg) pos)
9340 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9341 (js2-must-match js2-COLON "msg.no.colon.cond")
9342 (setq c-pos (- (js2-current-token-beg) pos)
9343 if-false (js2-parse-assign-expr)
9344 test-expr pn
9345 pn (make-js2-cond-node :pos pos
9346 :len (- (js2-node-end if-false) pos)
9347 :test-expr test-expr
9348 :true-expr if-true
9349 :false-expr if-false
9350 :q-pos q-pos
9351 :c-pos c-pos))
9352 (js2-node-add-children pn test-expr if-true if-false))
9353 pn))
9354
9355 (defun js2-make-binary (type left parser)
9356 "Helper for constructing a binary-operator AST node.
9357 LEFT is the left-side-expression, already parsed, and the
9358 binary operator should have just been matched.
9359 PARSER is a function to call to parse the right operand,
9360 or a `js2-node' struct if it has already been parsed.
9361 FIXME: The latter option is unused?"
9362 (let* ((pos (js2-node-pos left))
9363 (op-pos (- (js2-current-token-beg) pos))
9364 (right (if (js2-node-p parser)
9365 parser
9366 (js2-get-token)
9367 (funcall parser)))
9368 (pn (make-js2-infix-node :type type
9369 :pos pos
9370 :len (- (js2-node-end right) pos)
9371 :op-pos op-pos
9372 :left left
9373 :right right)))
9374 (js2-node-add-children pn left right)
9375 pn))
9376
9377 (defun js2-parse-or-expr ()
9378 (let ((pn (js2-parse-and-expr)))
9379 (when (js2-match-token js2-OR)
9380 (setq pn (js2-make-binary js2-OR
9381 pn
9382 'js2-parse-or-expr)))
9383 pn))
9384
9385 (defun js2-parse-and-expr ()
9386 (let ((pn (js2-parse-bit-or-expr)))
9387 (when (js2-match-token js2-AND)
9388 (setq pn (js2-make-binary js2-AND
9389 pn
9390 'js2-parse-and-expr)))
9391 pn))
9392
9393 (defun js2-parse-bit-or-expr ()
9394 (let ((pn (js2-parse-bit-xor-expr)))
9395 (while (js2-match-token js2-BITOR)
9396 (setq pn (js2-make-binary js2-BITOR
9397 pn
9398 'js2-parse-bit-xor-expr)))
9399 pn))
9400
9401 (defun js2-parse-bit-xor-expr ()
9402 (let ((pn (js2-parse-bit-and-expr)))
9403 (while (js2-match-token js2-BITXOR)
9404 (setq pn (js2-make-binary js2-BITXOR
9405 pn
9406 'js2-parse-bit-and-expr)))
9407 pn))
9408
9409 (defun js2-parse-bit-and-expr ()
9410 (let ((pn (js2-parse-eq-expr)))
9411 (while (js2-match-token js2-BITAND)
9412 (setq pn (js2-make-binary js2-BITAND
9413 pn
9414 'js2-parse-eq-expr)))
9415 pn))
9416
9417 (defconst js2-parse-eq-ops
9418 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9419
9420 (defun js2-parse-eq-expr ()
9421 (let ((pn (js2-parse-rel-expr))
9422 tt)
9423 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9424 (setq pn (js2-make-binary tt
9425 pn
9426 'js2-parse-rel-expr)))
9427 (js2-unget-token)
9428 pn))
9429
9430 (defconst js2-parse-rel-ops
9431 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9432
9433 (defun js2-parse-rel-expr ()
9434 (let ((pn (js2-parse-shift-expr))
9435 (continue t)
9436 tt)
9437 (while continue
9438 (setq tt (js2-get-token))
9439 (cond
9440 ((and js2-in-for-init (= tt js2-IN))
9441 (js2-unget-token)
9442 (setq continue nil))
9443 ((memq tt js2-parse-rel-ops)
9444 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9445 (t
9446 (js2-unget-token)
9447 (setq continue nil))))
9448 pn))
9449
9450 (defconst js2-parse-shift-ops
9451 (list js2-LSH js2-URSH js2-RSH))
9452
9453 (defun js2-parse-shift-expr ()
9454 (let ((pn (js2-parse-add-expr))
9455 tt
9456 (continue t))
9457 (while continue
9458 (setq tt (js2-get-token))
9459 (if (memq tt js2-parse-shift-ops)
9460 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9461 (js2-unget-token)
9462 (setq continue nil)))
9463 pn))
9464
9465 (defun js2-parse-add-expr ()
9466 (let ((pn (js2-parse-mul-expr))
9467 tt
9468 (continue t))
9469 (while continue
9470 (setq tt (js2-get-token))
9471 (if (or (= tt js2-ADD) (= tt js2-SUB))
9472 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9473 (js2-unget-token)
9474 (setq continue nil)))
9475 pn))
9476
9477 (defconst js2-parse-mul-ops
9478 (list js2-MUL js2-DIV js2-MOD))
9479
9480 (defun js2-parse-mul-expr ()
9481 (let ((pn (js2-parse-unary-expr))
9482 tt
9483 (continue t))
9484 (while continue
9485 (setq tt (js2-get-token))
9486 (if (memq tt js2-parse-mul-ops)
9487 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9488 (js2-unget-token)
9489 (setq continue nil)))
9490 pn))
9491
9492 (defun js2-make-unary (type parser &rest args)
9493 "Make a unary node of type TYPE.
9494 PARSER is either a node (for postfix operators) or a function to call
9495 to parse the operand (for prefix operators)."
9496 (let* ((pos (js2-current-token-beg))
9497 (postfix (js2-node-p parser))
9498 (expr (if postfix
9499 parser
9500 (apply parser args)))
9501 end
9502 pn)
9503 (if postfix ; e.g. i++
9504 (setq pos (js2-node-pos expr)
9505 end (js2-current-token-end))
9506 (setq end (js2-node-end expr)))
9507 (setq pn (make-js2-unary-node :type type
9508 :pos pos
9509 :len (- end pos)
9510 :operand expr))
9511 (js2-node-add-children pn expr)
9512 pn))
9513
9514 (defconst js2-incrementable-node-types
9515 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9516 "Node types that can be the operand of a ++ or -- operator.")
9517
9518 (defun js2-check-bad-inc-dec (tt beg end unary)
9519 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9520 js2-incrementable-node-types)
9521 (js2-report-error (if (= tt js2-INC)
9522 "msg.bad.incr"
9523 "msg.bad.decr")
9524 nil beg (- end beg))))
9525
9526 (defun js2-parse-unary-expr ()
9527 (let ((tt (js2-current-token-type))
9528 pn expr beg end)
9529 (cond
9530 ((or (= tt js2-VOID)
9531 (= tt js2-NOT)
9532 (= tt js2-BITNOT)
9533 (= tt js2-TYPEOF))
9534 (js2-get-token)
9535 (js2-make-unary tt 'js2-parse-unary-expr))
9536 ((= tt js2-ADD)
9537 (js2-get-token)
9538 ;; Convert to special POS token in decompiler and parse tree
9539 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9540 ((= tt js2-SUB)
9541 (js2-get-token)
9542 ;; Convert to special NEG token in decompiler and parse tree
9543 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9544 ((or (= tt js2-INC)
9545 (= tt js2-DEC))
9546 (js2-get-token)
9547 (prog1
9548 (setq beg (js2-current-token-beg)
9549 end (js2-current-token-end)
9550 expr (js2-make-unary tt 'js2-parse-member-expr t))
9551 (js2-check-bad-inc-dec tt beg end expr)))
9552 ((= tt js2-DELPROP)
9553 (js2-get-token)
9554 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9555 ((= tt js2-ERROR)
9556 (js2-get-token)
9557 (make-js2-error-node)) ; try to continue
9558 ((and (= tt js2-LT)
9559 js2-compiler-xml-available)
9560 ;; XML stream encountered in expression.
9561 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9562 (t
9563 (setq pn (js2-parse-member-expr t)
9564 ;; Don't look across a newline boundary for a postfix incop.
9565 tt (js2-peek-token-or-eol))
9566 (when (or (= tt js2-INC) (= tt js2-DEC))
9567 (js2-get-token)
9568 (setf expr pn
9569 pn (js2-make-unary tt expr))
9570 (js2-node-set-prop pn 'postfix t)
9571 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9572 pn))))
9573
9574 (defun js2-parse-xml-initializer ()
9575 "Parse an E4X XML initializer.
9576 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9577 Then I'll postprocess the result, depending on whether we're in IDE
9578 mode or codegen mode, and generate the appropriate rewritten AST.
9579 IDE mode uses a rich AST that models the XML structure. Codegen mode
9580 just concatenates everything and makes a new XML or XMLList out of it."
9581 (let ((tt (js2-get-first-xml-token))
9582 pn-xml pn expr kids expr-pos
9583 (continue t)
9584 (first-token t))
9585 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9586 (js2-report-error "msg.syntax"))
9587 (setq pn-xml (make-js2-xml-node))
9588 (while continue
9589 (if first-token
9590 (setq first-token nil)
9591 (setq tt (js2-get-next-xml-token)))
9592 (cond
9593 ;; js2-XML means we found a {expr} in the XML stream.
9594 ;; The token string is the XML up to the left-curly.
9595 ((= tt js2-XML)
9596 (push (make-js2-string-node :pos (js2-current-token-beg)
9597 :len (- js2-ts-cursor (js2-current-token-beg)))
9598 kids)
9599 (js2-must-match js2-LC "msg.syntax")
9600 (setq expr-pos js2-ts-cursor
9601 expr (if (eq (js2-peek-token) js2-RC)
9602 (make-js2-empty-expr-node :pos expr-pos)
9603 (js2-parse-expr)))
9604 (js2-must-match js2-RC "msg.syntax")
9605 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9606 :len (js2-node-len expr)
9607 :expr expr))
9608 (js2-node-add-children pn expr)
9609 (push pn kids))
9610 ;; a js2-XMLEND token means we hit the final close-tag.
9611 ((= tt js2-XMLEND)
9612 (push (make-js2-string-node :pos (js2-current-token-beg)
9613 :len (- js2-ts-cursor (js2-current-token-beg)))
9614 kids)
9615 (dolist (kid (nreverse kids))
9616 (js2-block-node-push pn-xml kid))
9617 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9618 (js2-node-pos pn-xml))
9619 continue nil))
9620 (t
9621 (js2-report-error "msg.syntax")
9622 (setq continue nil))))
9623 pn-xml))
9624
9625
9626 (defun js2-parse-argument-list ()
9627 "Parse an argument list and return it as a Lisp list of nodes.
9628 Returns the list in reverse order. Consumes the right-paren token."
9629 (let (result)
9630 (unless (js2-match-token js2-RP)
9631 (cl-loop do
9632 (let ((tt (js2-get-token)))
9633 (if (= tt js2-YIELD)
9634 (js2-report-error "msg.yield.parenthesized"))
9635 (if (and (= tt js2-TRIPLEDOT)
9636 (>= js2-language-version 200))
9637 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9638 (js2-unget-token)
9639 (push (js2-parse-assign-expr) result)))
9640 while
9641 (js2-match-token js2-COMMA))
9642 (js2-must-match js2-RP "msg.no.paren.arg")
9643 result)))
9644
9645 (defun js2-parse-member-expr (&optional allow-call-syntax)
9646 (let ((tt (js2-current-token-type))
9647 pn pos target args beg end init)
9648 (if (/= tt js2-NEW)
9649 (setq pn (js2-parse-primary-expr))
9650 ;; parse a 'new' expression
9651 (js2-get-token)
9652 (setq pos (js2-current-token-beg)
9653 beg pos
9654 target (js2-parse-member-expr)
9655 end (js2-node-end target)
9656 pn (make-js2-new-node :pos pos
9657 :target target
9658 :len (- end pos)))
9659 (js2-highlight-function-call (js2-current-token))
9660 (js2-node-add-children pn target)
9661 (when (js2-match-token js2-LP)
9662 ;; Add the arguments to pn, if any are supplied.
9663 (setf beg pos ; start of "new" keyword
9664 pos (js2-current-token-beg)
9665 args (nreverse (js2-parse-argument-list))
9666 (js2-new-node-args pn) args
9667 end (js2-current-token-end)
9668 (js2-new-node-lp pn) (- pos beg)
9669 (js2-new-node-rp pn) (- end 1 beg))
9670 (apply #'js2-node-add-children pn args))
9671 (when (and js2-allow-rhino-new-expr-initializer
9672 (js2-match-token js2-LC))
9673 (setf init (js2-parse-object-literal)
9674 end (js2-node-end init)
9675 (js2-new-node-initializer pn) init)
9676 (js2-node-add-children pn init))
9677 (setf (js2-node-len pn) (- end beg))) ; end outer if
9678 (js2-parse-member-expr-tail allow-call-syntax pn)))
9679
9680 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9681 "Parse a chain of property/array accesses or function calls.
9682 Includes parsing for E4X operators like `..' and `.@'.
9683 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9684 Returns an expression tree that includes PN, the parent node."
9685 (let (tt
9686 (continue t))
9687 (while continue
9688 (setq tt (js2-get-token))
9689 (cond
9690 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9691 (setq pn (js2-parse-property-access tt pn)))
9692 ((= tt js2-DOTQUERY)
9693 (setq pn (js2-parse-dot-query pn)))
9694 ((= tt js2-LB)
9695 (setq pn (js2-parse-element-get pn)))
9696 ((= tt js2-LP)
9697 (js2-unget-token)
9698 (if allow-call-syntax
9699 (setq pn (js2-parse-function-call pn))
9700 (setq continue nil)))
9701 ((= tt js2-TEMPLATE_HEAD)
9702 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9703 ((= tt js2-NO_SUBS_TEMPLATE)
9704 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9705 (t
9706 (js2-unget-token)
9707 (setq continue nil))))
9708 (if (>= js2-highlight-level 2)
9709 (js2-parse-highlight-member-expr-node pn))
9710 pn))
9711
9712 (defun js2-parse-tagged-template (tag-node tpl-node)
9713 "Parse tagged template expression."
9714 (let* ((beg (js2-node-pos tag-node))
9715 (pn (make-js2-tagged-template-node :beg beg
9716 :len (- (js2-current-token-end) beg)
9717 :tag tag-node
9718 :template tpl-node)))
9719 (js2-node-add-children pn tag-node tpl-node)
9720 pn))
9721
9722 (defun js2-parse-dot-query (pn)
9723 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9724 Last token parsed must be `js2-DOTQUERY'."
9725 (let ((pos (js2-node-pos pn))
9726 op-pos expr end)
9727 (js2-must-have-xml)
9728 (js2-set-requires-activation)
9729 (setq op-pos (js2-current-token-beg)
9730 expr (js2-parse-expr)
9731 end (js2-node-end expr)
9732 pn (make-js2-xml-dot-query-node :left pn
9733 :pos pos
9734 :op-pos op-pos
9735 :right expr))
9736 (js2-node-add-children pn
9737 (js2-xml-dot-query-node-left pn)
9738 (js2-xml-dot-query-node-right pn))
9739 (if (js2-must-match js2-RP "msg.no.paren")
9740 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9741 end (js2-current-token-end)))
9742 (setf (js2-node-len pn) (- end pos))
9743 pn))
9744
9745 (defun js2-parse-element-get (pn)
9746 "Parse an element-get expression, e.g. foo[bar].
9747 Last token parsed must be `js2-RB'."
9748 (let ((lb (js2-current-token-beg))
9749 (pos (js2-node-pos pn))
9750 rb expr)
9751 (setq expr (js2-parse-expr))
9752 (if (js2-must-match js2-RB "msg.no.bracket.index")
9753 (setq rb (js2-current-token-beg)))
9754 (setq pn (make-js2-elem-get-node :target pn
9755 :pos pos
9756 :element expr
9757 :lb (js2-relpos lb pos)
9758 :rb (js2-relpos rb pos)
9759 :len (- (js2-current-token-end) pos)))
9760 (js2-node-add-children pn
9761 (js2-elem-get-node-target pn)
9762 (js2-elem-get-node-element pn))
9763 pn))
9764
9765 (defun js2-highlight-function-call (token)
9766 (when (eq (js2-token-type token) js2-NAME)
9767 (js2-record-face 'js2-function-call token)))
9768
9769 (defun js2-parse-function-call (pn)
9770 (js2-highlight-function-call (js2-current-token))
9771 (js2-get-token)
9772 (let (args
9773 (pos (js2-node-pos pn)))
9774 (setq pn (make-js2-call-node :pos pos
9775 :target pn
9776 :lp (- (js2-current-token-beg) pos)))
9777 (js2-node-add-children pn (js2-call-node-target pn))
9778 ;; Add the arguments to pn, if any are supplied.
9779 (setf args (nreverse (js2-parse-argument-list))
9780 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9781 (js2-call-node-args pn) args)
9782 (apply #'js2-node-add-children pn args)
9783 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9784 pn))
9785
9786 (defun js2-parse-property-access (tt pn)
9787 "Parse a property access, XML descendants access, or XML attr access."
9788 (let ((member-type-flags 0)
9789 (dot-pos (js2-current-token-beg))
9790 (dot-len (if (= tt js2-DOTDOT) 2 1))
9791 name
9792 ref ; right side of . or .. operator
9793 result)
9794 (when (= tt js2-DOTDOT)
9795 (js2-must-have-xml)
9796 (setq member-type-flags js2-descendants-flag))
9797 (if (not js2-compiler-xml-available)
9798 (progn
9799 (js2-must-match-prop-name "msg.no.name.after.dot")
9800 (setq name (js2-create-name-node t js2-GETPROP)
9801 result (make-js2-prop-get-node :left pn
9802 :pos (js2-current-token-beg)
9803 :right name
9804 :len (js2-current-token-len)))
9805 (js2-node-add-children result pn name)
9806 result)
9807 ;; otherwise look for XML operators
9808 (setf result (if (= tt js2-DOT)
9809 (make-js2-prop-get-node)
9810 (make-js2-infix-node :type js2-DOTDOT))
9811 (js2-node-pos result) (js2-node-pos pn)
9812 (js2-infix-node-op-pos result) dot-pos
9813 (js2-infix-node-left result) pn ; do this after setting position
9814 tt (js2-get-prop-name-token))
9815 (cond
9816 ;; handles: name, ns::name, ns::*, ns::[expr]
9817 ((= tt js2-NAME)
9818 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9819 ;; handles: *, *::name, *::*, *::[expr]
9820 ((= tt js2-MUL)
9821 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9822 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9823 ((= tt js2-XMLATTR)
9824 (setq result (js2-parse-attribute-access)))
9825 (t
9826 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9827 (if ref
9828 (setf (js2-node-len result) (- (js2-node-end ref)
9829 (js2-node-pos result))
9830 (js2-infix-node-right result) ref))
9831 (if (js2-infix-node-p result)
9832 (js2-node-add-children result
9833 (js2-infix-node-left result)
9834 (js2-infix-node-right result)))
9835 result)))
9836
9837 (defun js2-parse-attribute-access ()
9838 "Parse an E4X XML attribute expression.
9839 This includes expressions of the forms:
9840
9841 @attr @ns::attr @ns::*
9842 @* @*::attr @*::*
9843 @[expr] @*::[expr] @ns::[expr]
9844
9845 Called if we peeked an '@' token."
9846 (let ((tt (js2-get-prop-name-token))
9847 (at-pos (js2-current-token-beg)))
9848 (cond
9849 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9850 ((= tt js2-NAME)
9851 (js2-parse-property-name at-pos nil 0))
9852 ;; handles: @*, @*::name, @*::*, @*::[expr]
9853 ((= tt js2-MUL)
9854 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9855 ;; handles @[expr]
9856 ((= tt js2-LB)
9857 (js2-parse-xml-elem-ref at-pos))
9858 (t
9859 (js2-report-error "msg.no.name.after.xmlAttr")
9860 ;; Avoid cascaded errors that happen if we make an error node here.
9861 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9862
9863 (defun js2-parse-property-name (at-pos s member-type-flags)
9864 "Check if :: follows name in which case it becomes qualified name.
9865
9866 AT-POS is a natural number if we just read an '@' token, else nil.
9867 S is the name or string that was matched: an identifier, 'throw' or '*'.
9868 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9869
9870 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9871 operator, or the name is followed by ::. For a plain name, returns a
9872 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9873 (let ((pos (or at-pos (js2-current-token-beg)))
9874 colon-pos
9875 (name (js2-create-name-node t (js2-current-token-type) s))
9876 ns tt pn)
9877 (catch 'return
9878 (when (js2-match-token js2-COLONCOLON)
9879 (setq ns name
9880 colon-pos (js2-current-token-beg)
9881 tt (js2-get-prop-name-token))
9882 (cond
9883 ;; handles name::name
9884 ((= tt js2-NAME)
9885 (setq name (js2-create-name-node)))
9886 ;; handles name::*
9887 ((= tt js2-MUL)
9888 (setq name (js2-create-name-node nil nil "*")))
9889 ;; handles name::[expr]
9890 ((= tt js2-LB)
9891 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9892 (t
9893 (js2-report-error "msg.no.name.after.coloncolon"))))
9894 (if (and (null ns) (zerop member-type-flags))
9895 name
9896 (prog1
9897 (setq pn
9898 (make-js2-xml-prop-ref-node :pos pos
9899 :len (- (js2-node-end name) pos)
9900 :at-pos at-pos
9901 :colon-pos colon-pos
9902 :propname name))
9903 (js2-node-add-children pn name))))))
9904
9905 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9906 "Parse the [expr] portion of an xml element reference.
9907 For instance, @[expr], @*::[expr], or ns::[expr]."
9908 (let* ((lb (js2-current-token-beg))
9909 (pos (or at-pos lb))
9910 rb
9911 (expr (js2-parse-expr))
9912 (end (js2-node-end expr))
9913 pn)
9914 (if (js2-must-match js2-RB "msg.no.bracket.index")
9915 (setq rb (js2-current-token-beg)
9916 end (js2-current-token-end)))
9917 (prog1
9918 (setq pn
9919 (make-js2-xml-elem-ref-node :pos pos
9920 :len (- end pos)
9921 :namespace namespace
9922 :colon-pos colon-pos
9923 :at-pos at-pos
9924 :expr expr
9925 :lb (js2-relpos lb pos)
9926 :rb (js2-relpos rb pos)))
9927 (js2-node-add-children pn namespace expr))))
9928
9929 (defun js2-parse-destruct-primary-expr ()
9930 (let ((js2-is-in-destructuring t))
9931 (js2-parse-primary-expr)))
9932
9933 (defun js2-parse-primary-expr ()
9934 "Parse a literal (leaf) expression of some sort.
9935 Includes complex literals such as functions, object-literals,
9936 array-literals, array comprehensions and regular expressions."
9937 (let (pn ; parent node (usually return value)
9938 tt)
9939 (setq tt (js2-current-token-type))
9940 (cond
9941 ((= tt js2-CLASS)
9942 (js2-parse-class-expr))
9943 ((= tt js2-FUNCTION)
9944 (js2-parse-function-expr))
9945 ((= tt js2-LB)
9946 (js2-parse-array-comp-or-literal))
9947 ((= tt js2-LC)
9948 (js2-parse-object-literal))
9949 ((= tt js2-LET)
9950 (js2-parse-let (js2-current-token-beg)))
9951 ((= tt js2-LP)
9952 (js2-parse-paren-expr-or-generator-comp))
9953 ((= tt js2-XMLATTR)
9954 (js2-must-have-xml)
9955 (js2-parse-attribute-access))
9956 ((= tt js2-NAME)
9957 (js2-parse-name tt))
9958 ((= tt js2-NUMBER)
9959 (make-js2-number-node))
9960 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9961 (make-js2-string-node :type tt))
9962 ((= tt js2-TEMPLATE_HEAD)
9963 (js2-parse-template-literal))
9964 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9965 ;; Got / or /= which in this context means a regexp literal
9966 (let ((px-pos (js2-current-token-beg))
9967 (flags (js2-read-regexp tt))
9968 (end (js2-current-token-end)))
9969 (prog1
9970 (make-js2-regexp-node :pos px-pos
9971 :len (- end px-pos)
9972 :value (js2-current-token-string)
9973 :flags flags)
9974 (js2-set-face px-pos end 'font-lock-string-face 'record)
9975 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9976 ((or (= tt js2-NULL)
9977 (= tt js2-THIS)
9978 (= tt js2-SUPER)
9979 (= tt js2-FALSE)
9980 (= tt js2-TRUE))
9981 (make-js2-keyword-node :type tt))
9982 ((= tt js2-TRIPLEDOT)
9983 ;; Likewise, only valid in an arrow function with a rest param.
9984 (if (and (js2-match-token js2-NAME)
9985 (js2-match-token js2-RP)
9986 (eq (js2-peek-token) js2-ARROW))
9987 (progn
9988 (js2-unget-token) ; Put back the right paren.
9989 ;; See the previous case.
9990 (make-js2-keyword-node :type js2-NULL))
9991 (js2-report-error "msg.syntax")
9992 (make-js2-error-node)))
9993 ((= tt js2-RESERVED)
9994 (js2-report-error "msg.reserved.id")
9995 (make-js2-name-node))
9996 ((= tt js2-ERROR)
9997 ;; the scanner or one of its subroutines reported the error.
9998 (make-js2-error-node))
9999 ((= tt js2-EOF)
10000 (let* ((px-pos (point-at-bol))
10001 (len (- js2-ts-cursor px-pos)))
10002 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10003 (make-js2-error-node :pos (1- js2-ts-cursor)))
10004 (t
10005 (js2-report-error "msg.syntax")
10006 (make-js2-error-node)))))
10007
10008 (defun js2-parse-template-literal ()
10009 (let ((beg (js2-current-token-beg))
10010 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10011 (tt js2-TEMPLATE_HEAD))
10012 (while (eq tt js2-TEMPLATE_HEAD)
10013 (push (js2-parse-expr) kids)
10014 (js2-must-match js2-RC "msg.syntax")
10015 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10016 (push (make-js2-string-node :type tt) kids))
10017 (setq kids (nreverse kids))
10018 (let ((tpl (make-js2-template-node :beg beg
10019 :len (- (js2-current-token-end) beg)
10020 :kids kids)))
10021 (apply #'js2-node-add-children tpl kids)
10022 tpl)))
10023
10024 (defun js2-parse-name (_tt)
10025 (let ((name (js2-current-token-string))
10026 node)
10027 (setq node (if js2-compiler-xml-available
10028 (js2-parse-property-name nil name 0)
10029 (js2-create-name-node 'check-activation nil name)))
10030 (if js2-highlight-external-variables
10031 (js2-record-name-node node))
10032 node))
10033
10034 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10035 (js2-add-strict-warning
10036 msg nil
10037 ;; back up from comma to beginning of line or array/objlit
10038 (max (if elems
10039 (js2-node-pos (car elems))
10040 pos)
10041 (save-excursion
10042 (goto-char comma-pos)
10043 (back-to-indentation)
10044 (point)))
10045 comma-pos))
10046
10047 (defun js2-parse-array-comp-or-literal ()
10048 (let ((pos (js2-current-token-beg)))
10049 (if (and (>= js2-language-version 200)
10050 (js2-match-token js2-FOR))
10051 (js2-parse-array-comp pos)
10052 (js2-parse-array-literal pos))))
10053
10054 (defun js2-parse-array-literal (pos)
10055 (let ((after-lb-or-comma t)
10056 after-comma tt elems pn
10057 (continue t))
10058 (unless js2-is-in-destructuring
10059 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10060 (while continue
10061 (setq tt (js2-get-token))
10062 (cond
10063 ;; comma
10064 ((= tt js2-COMMA)
10065 (setq after-comma (js2-current-token-end))
10066 (if (not after-lb-or-comma)
10067 (setq after-lb-or-comma t)
10068 (push nil elems)))
10069 ;; end of array
10070 ((or (= tt js2-RB)
10071 (= tt js2-EOF)) ; prevent infinite loop
10072 (if (= tt js2-EOF)
10073 (js2-report-error "msg.no.bracket.arg" nil pos))
10074 (when (and after-comma (< js2-language-version 170))
10075 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10076 pos (remove nil elems) after-comma))
10077 (setq continue nil
10078 pn (make-js2-array-node :pos pos
10079 :len (- js2-ts-cursor pos)
10080 :elems (nreverse elems)))
10081 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10082 ;; destructuring binding
10083 (js2-is-in-destructuring
10084 (push (if (or (= tt js2-LC)
10085 (= tt js2-LB)
10086 (= tt js2-NAME))
10087 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10088 (js2-parse-destruct-primary-expr)
10089 ;; invalid pattern
10090 (js2-report-error "msg.bad.var")
10091 (make-js2-error-node))
10092 elems)
10093 (setq after-lb-or-comma nil
10094 after-comma nil))
10095 ;; array comp
10096 ((and (>= js2-language-version 170)
10097 (= tt js2-FOR) ; check for array comprehension
10098 (not after-lb-or-comma) ; "for" can't follow a comma
10099 elems ; must have at least 1 element
10100 (not (cdr elems))) ; but no 2nd element
10101 (js2-unget-token)
10102 (setf continue nil
10103 pn (js2-parse-legacy-array-comp (car elems) pos)))
10104 ;; another element
10105 (t
10106 (unless after-lb-or-comma
10107 (js2-report-error "msg.no.bracket.arg"))
10108 (if (and (= tt js2-TRIPLEDOT)
10109 (>= js2-language-version 200))
10110 ;; spread operator
10111 (push (js2-make-unary tt 'js2-parse-assign-expr)
10112 elems)
10113 (js2-unget-token)
10114 (push (js2-parse-assign-expr) elems))
10115 (setq after-lb-or-comma nil
10116 after-comma nil))))
10117 (unless js2-is-in-destructuring
10118 (js2-pop-scope))
10119 pn))
10120
10121 (defun js2-parse-legacy-array-comp (expr pos)
10122 "Parse a legacy array comprehension (JavaScript 1.7).
10123 EXPR is the first expression after the opening left-bracket.
10124 POS is the beginning of the LB token preceding EXPR.
10125 We should have just parsed the 'for' keyword before calling this function."
10126 (let ((current-scope js2-current-scope)
10127 loops first filter result)
10128 (unwind-protect
10129 (progn
10130 (while (js2-match-token js2-FOR)
10131 (let ((loop (make-js2-comp-loop-node)))
10132 (js2-push-scope loop)
10133 (push loop loops)
10134 (js2-parse-comp-loop loop)))
10135 ;; First loop takes expr scope's parent.
10136 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10137 (js2-scope-parent-scope current-scope))
10138 ;; Set expr scope's parent to the last loop.
10139 (setf (js2-scope-parent-scope current-scope) (car loops))
10140 (if (/= (js2-get-token) js2-IF)
10141 (js2-unget-token)
10142 (setq filter (js2-parse-condition))))
10143 (dotimes (_ (1- (length loops)))
10144 (js2-pop-scope)))
10145 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10146 (setq result (make-js2-comp-node :pos pos
10147 :len (- js2-ts-cursor pos)
10148 :result expr
10149 :loops (nreverse loops)
10150 :filters (and filter (list (car filter)))
10151 :form 'LEGACY_ARRAY))
10152 (apply #'js2-node-add-children result expr (car filter)
10153 (js2-comp-node-loops result))
10154 result))
10155
10156 (defun js2-parse-array-comp (pos)
10157 "Parse an ES6 array comprehension.
10158 POS is the beginning of the LB token.
10159 We should have just parsed the 'for' keyword before calling this function."
10160 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10161 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10162 pn))
10163
10164 (defun js2-parse-generator-comp (pos)
10165 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10166 (js2-current-script-or-fn
10167 (make-js2-function-node :generator-type 'COMPREHENSION))
10168 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10169 (js2-must-match js2-RP "msg.no.paren" pos)
10170 pn))
10171
10172 (defun js2-parse-comprehension (pos form)
10173 (let (loops filters expr result)
10174 (unwind-protect
10175 (progn
10176 (js2-unget-token)
10177 (while (js2-match-token js2-FOR)
10178 (let ((loop (make-js2-comp-loop-node)))
10179 (js2-push-scope loop)
10180 (push loop loops)
10181 (js2-parse-comp-loop loop)))
10182 (while (js2-match-token js2-IF)
10183 (push (car (js2-parse-condition)) filters))
10184 (setq expr (js2-parse-assign-expr)))
10185 (dolist (_ loops)
10186 (js2-pop-scope)))
10187 (setq result (make-js2-comp-node :pos pos
10188 :len (- js2-ts-cursor pos)
10189 :result expr
10190 :loops (nreverse loops)
10191 :filters (nreverse filters)
10192 :form form))
10193 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10194 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10195 result))
10196
10197 (defun js2-parse-comp-loop (pn &optional only-of-p)
10198 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10199 The current token should be the initial FOR.
10200 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10201 (let ((pos (js2-comp-loop-node-pos pn))
10202 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10203 (when (and (not only-of-p) (js2-match-token js2-NAME))
10204 (if (string= (js2-current-token-string) "each")
10205 (progn
10206 (setq foreach-p t
10207 each-pos (- (js2-current-token-beg) pos)) ; relative
10208 (js2-record-face 'font-lock-keyword-face))
10209 (js2-report-error "msg.no.paren.for")))
10210 (if (js2-must-match js2-LP "msg.no.paren.for")
10211 (setq lp (- (js2-current-token-beg) pos)))
10212 (setq tt (js2-peek-token))
10213 (cond
10214 ((or (= tt js2-LB)
10215 (= tt js2-LC))
10216 (js2-get-token)
10217 (setq iter (js2-parse-destruct-primary-expr))
10218 (js2-define-destruct-symbols iter js2-LET
10219 'font-lock-variable-name-face t))
10220 ((js2-match-token js2-NAME)
10221 (setq iter (js2-create-name-node)))
10222 (t
10223 (js2-report-error "msg.bad.var")))
10224 ;; Define as a let since we want the scope of the variable to
10225 ;; be restricted to the array comprehension
10226 (if (js2-name-node-p iter)
10227 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10228 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10229 (and (>= js2-language-version 200)
10230 (js2-match-contextual-kwd "of")
10231 (setq forof-p t)))
10232 (setq in-pos (- (js2-current-token-beg) pos))
10233 (js2-report-error "msg.in.after.for.name"))
10234 (setq obj (js2-parse-expr))
10235 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10236 (setq rp (- (js2-current-token-beg) pos)))
10237 (setf (js2-node-pos pn) pos
10238 (js2-node-len pn) (- js2-ts-cursor pos)
10239 (js2-comp-loop-node-iterator pn) iter
10240 (js2-comp-loop-node-object pn) obj
10241 (js2-comp-loop-node-in-pos pn) in-pos
10242 (js2-comp-loop-node-each-pos pn) each-pos
10243 (js2-comp-loop-node-foreach-p pn) foreach-p
10244 (js2-comp-loop-node-forof-p pn) forof-p
10245 (js2-comp-loop-node-lp pn) lp
10246 (js2-comp-loop-node-rp pn) rp)
10247 (js2-node-add-children pn iter obj)
10248 pn))
10249
10250 (defun js2-parse-class-stmt ()
10251 (let ((pos (js2-current-token-beg))
10252 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10253 (name (js2-create-name-node t)))
10254 (js2-set-face (js2-node-pos name) (js2-node-end name)
10255 'font-lock-function-name-face 'record)
10256 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10257 (js2-define-symbol js2-FUNCTION
10258 (js2-name-node-name name)
10259 node)
10260 node)))
10261
10262 (defun js2-parse-class-expr ()
10263 (let ((pos (js2-current-token-beg))
10264 name)
10265 (when (js2-match-token js2-NAME)
10266 (setq name (js2-create-name-node t)))
10267 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10268
10269 (defun js2-parse-class (pos form name)
10270 ;; class X [extends ...] {
10271 (let (pn elems extends)
10272 (if (js2-match-token js2-EXTENDS)
10273 (if (= (js2-peek-token) js2-LC)
10274 (js2-report-error "msg.missing.extends")
10275 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10276 (setq extends (js2-parse-assign-expr))
10277 (if (not extends)
10278 (js2-report-error "msg.bad.extends"))))
10279 (js2-must-match js2-LC "msg.no.brace.class")
10280 (setq elems (js2-parse-object-literal-elems t)
10281 pn (make-js2-class-node :pos pos
10282 :len (- js2-ts-cursor pos)
10283 :form form
10284 :name name
10285 :extends extends
10286 :elems elems))
10287 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10288 pn))
10289
10290 (defun js2-parse-object-literal ()
10291 (let* ((pos (js2-current-token-beg))
10292 (elems (js2-parse-object-literal-elems))
10293 (result (make-js2-object-node :pos pos
10294 :len (- js2-ts-cursor pos)
10295 :elems elems)))
10296 (apply #'js2-node-add-children result (js2-object-node-elems result))
10297 result))
10298
10299 (defun js2-parse-object-literal-elems (&optional class-p)
10300 (let ((pos (js2-current-token-beg))
10301 (static nil)
10302 (continue t)
10303 tt elems elem after-comma)
10304 (while continue
10305 (setq static (and class-p (js2-match-token js2-STATIC))
10306 tt (js2-get-prop-name-token)
10307 elem nil)
10308 (cond
10309 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
10310 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
10311 ;; TODO(sdh): support *foo() {...}
10312 ((or (= js2-NAME tt)
10313 (= tt js2-STRING))
10314 (setq after-comma nil
10315 elem (js2-parse-named-prop tt))
10316 (if (and (null elem)
10317 (not js2-recover-from-parse-errors))
10318 (setq continue nil)))
10319 ;; {[Symbol.iterator]: ...}
10320 ((and (= tt js2-LB)
10321 (>= js2-language-version 200))
10322 (let ((expr (js2-parse-expr)))
10323 (js2-must-match js2-RB "msg.missing.computed.rb")
10324 (setq after-comma nil
10325 elem (js2-parse-plain-property expr))))
10326 ;; {12: x} or {10.7: x}
10327 ((= tt js2-NUMBER)
10328 (setq after-comma nil
10329 elem (js2-parse-plain-property (make-js2-number-node))))
10330 ;; Break out of loop, and handle trailing commas.
10331 ((or (= tt js2-RC)
10332 (= tt js2-EOF))
10333 (js2-unget-token)
10334 (setq continue nil)
10335 (if after-comma
10336 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10337 pos elems after-comma)))
10338 (t
10339 (js2-report-error "msg.bad.prop")
10340 (unless js2-recover-from-parse-errors
10341 (setq continue nil)))) ; end switch
10342 ;; Handle static for classes' codegen.
10343 (if static
10344 (if elem (js2-node-set-prop elem 'STATIC t)
10345 (js2-report-error "msg.unexpected.static")))
10346 ;; Handle commas, depending on class-p.
10347 (let ((comma (js2-match-token js2-COMMA)))
10348 (if class-p
10349 (if comma
10350 (js2-report-error "msg.class.unexpected.comma"))
10351 (if comma
10352 (setq after-comma (js2-current-token-end))
10353 (setq continue nil))))
10354 ;; Append any parsed element.
10355 (if elem (push elem elems))) ; end loop
10356 (js2-must-match js2-RC "msg.no.brace.prop")
10357 (nreverse elems)))
10358
10359 (defun js2-parse-named-prop (tt)
10360 "Parse a name, string, or getter/setter object property.
10361 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10362 (let ((string-prop (and (= tt js2-STRING)
10363 (make-js2-string-node)))
10364 expr
10365 (ppos (js2-current-token-beg))
10366 (pend (js2-current-token-end))
10367 (name (js2-create-name-node))
10368 (prop (js2-current-token-string)))
10369 (cond
10370 ;; getter/setter prop
10371 ((and (= tt js2-NAME)
10372 (= (js2-peek-token) js2-NAME)
10373 (or (string= prop "get")
10374 (string= prop "set")))
10375 (js2-get-token)
10376 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
10377 (js2-record-face 'font-lock-function-name-face) ; for peeked name
10378 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
10379 (js2-parse-getter-setter-prop ppos name prop))
10380 ;; method definition: {f() {...}}
10381 ((and (= (js2-peek-token) js2-LP)
10382 (>= js2-language-version 200))
10383 (js2-record-face 'font-lock-function-name-face) ; name
10384 (js2-parse-getter-setter-prop ppos name ""))
10385 ;; regular prop
10386 (t
10387 (prog1
10388 (setq expr (js2-parse-plain-property (or string-prop name)))
10389 (when (and (not string-prop)
10390 (not js2-is-in-destructuring)
10391 js2-highlight-external-variables
10392 (js2-node-get-prop expr 'SHORTHAND))
10393 (js2-record-name-node name))
10394 (js2-set-face ppos pend
10395 (if (js2-function-node-p
10396 (js2-object-prop-node-right expr))
10397 'font-lock-function-name-face
10398 'font-lock-variable-name-face)
10399 'record))))))
10400
10401 (defun js2-parse-plain-property (prop)
10402 "Parse a non-getter/setter property in an object literal.
10403 PROP is the node representing the property: a number, name or string."
10404 (let* ((tt (js2-get-token))
10405 (pos (js2-node-pos prop))
10406 colon expr result)
10407 (cond
10408 ;; Abbreviated property, as in {foo, bar}
10409 ((and (>= js2-language-version 200)
10410 (or (= tt js2-COMMA)
10411 (= tt js2-RC))
10412 (not (js2-number-node-p prop)))
10413 (js2-unget-token)
10414 (setq result (make-js2-object-prop-node
10415 :pos pos
10416 :left prop
10417 :right prop
10418 :op-pos (js2-current-token-len)))
10419 (js2-node-add-children result prop)
10420 (js2-node-set-prop result 'SHORTHAND t)
10421 result)
10422 ;; Normal property
10423 (t
10424 (if (= tt js2-COLON)
10425 (setq colon (- (js2-current-token-beg) pos)
10426 expr (js2-parse-assign-expr))
10427 (js2-report-error "msg.no.colon.prop")
10428 (setq expr (make-js2-error-node)))
10429 (setq result (make-js2-object-prop-node
10430 :pos pos
10431 ;; don't include last consumed token in length
10432 :len (- (+ (js2-node-pos expr)
10433 (js2-node-len expr))
10434 pos)
10435 :left prop
10436 :right expr
10437 :op-pos colon))
10438 (js2-node-add-children result prop expr)
10439 result))))
10440
10441 (defun js2-parse-getter-setter-prop (pos prop type-string)
10442 "Parse getter or setter property in an object literal.
10443 JavaScript syntax is:
10444
10445 { get foo() {...}, set foo(x) {...} }
10446
10447 and expression closure style is also supported
10448
10449 { get foo() x, set foo(x) _x = x }
10450
10451 POS is the start position of the `get' or `set' keyword.
10452 PROP is the `js2-name-node' representing the property name.
10453 GET-P is non-nil if the keyword was `get'."
10454 (let ((type (cond
10455 ((string= "get" type-string) js2-GET)
10456 ((string= "set" type-string) js2-SET)
10457 (t js2-FUNCTION)))
10458 result end
10459 (fn (js2-parse-function-expr)))
10460 ;; it has to be an anonymous function, as we already parsed the name
10461 (if (/= (js2-node-type fn) js2-FUNCTION)
10462 (js2-report-error "msg.bad.prop")
10463 (if (cl-plusp (length (js2-function-name fn)))
10464 (js2-report-error "msg.bad.prop")))
10465 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10466 (setq end (js2-node-end fn)
10467 result (make-js2-getter-setter-node :type type
10468 :pos pos
10469 :len (- end pos)
10470 :left prop
10471 :right fn))
10472 (js2-node-add-children result prop fn)
10473 result))
10474
10475 (defun js2-create-name-node (&optional check-activation-p token string)
10476 "Create a name node using the current token and, optionally, STRING.
10477 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10478 (let* ((beg (js2-current-token-beg))
10479 (tt (js2-current-token-type))
10480 (s (or string
10481 (if (= js2-NAME tt)
10482 (js2-current-token-string)
10483 (js2-tt-name tt))))
10484 name)
10485 (setq name (make-js2-name-node :pos beg
10486 :name s
10487 :len (length s)))
10488 (if check-activation-p
10489 (js2-check-activation-name s (or token js2-NAME)))
10490 name))
10491
10492 ;;; Indentation support
10493
10494 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10495 ;; Karl cleverly deduces that the desired indentation level is often a
10496 ;; function of paren/bracket/brace nesting depth, which can be determined
10497 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10498 ;; then does some equally clever checks to see if we're in the context of a
10499 ;; substatement of a possibly braceless statement keyword such as if, while,
10500 ;; or finally. This approach yields pretty good results.
10501
10502 ;; The indenter is often "wrong", however, and needs to be overridden.
10503 ;; The right long-term solution is probably to emulate (or integrate
10504 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10505 ;; parse tree from `js2-parse' is present, which is not true at the
10506 ;; moment the user is typing, computing indentation is still thousands
10507 ;; of lines of code to handle every possible syntactic edge case.
10508
10509 ;; In the meantime, the compromise solution is that we offer a "bounce
10510 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10511 ;; current line indent among various likely guess points. This approach
10512 ;; is far from perfect, but should at least make it slightly easier to
10513 ;; move the line towards its desired indentation when manually
10514 ;; overriding Karl's heuristic nesting guesser.
10515
10516 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10517 ;; extensions such as `let' and Array comprehensions. Major kudos to
10518 ;; Karl for coming up with the initial approach, which packs a lot of
10519 ;; punch for so little code.
10520
10521 (defconst js2-possibly-braceless-keywords-re
10522 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10523 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10524 "try" "while" "with" "let")))
10525 "Regular expression matching keywords that are optionally
10526 followed by an opening brace.")
10527
10528 (defconst js2-indent-operator-re
10529 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10530 (regexp-opt '("in" "instanceof") 'words))
10531 "Regular expression matching operators that affect indentation
10532 of continued expressions.")
10533
10534 (defconst js2-declaration-keyword-re
10535 (regexp-opt '("var" "let" "const") 'words)
10536 "Regular expression matching variable declaration keywords.")
10537
10538 (defun js2-re-search-forward-inner (regexp &optional bound count)
10539 "Auxiliary function for `js2-re-search-forward'."
10540 (let (parse saved-point)
10541 (while (> count 0)
10542 (re-search-forward regexp bound)
10543 (setq parse (if saved-point
10544 (parse-partial-sexp saved-point (point))
10545 (syntax-ppss (point))))
10546 (cond ((nth 3 parse)
10547 (re-search-forward
10548 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10549 (save-excursion (end-of-line) (point)) t))
10550 ((nth 7 parse)
10551 (forward-line))
10552 ((or (nth 4 parse)
10553 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10554 (re-search-forward "\\*/"))
10555 (t
10556 (setq count (1- count))))
10557 (setq saved-point (point))))
10558 (point))
10559
10560 (defun js2-re-search-forward (regexp &optional bound noerror count)
10561 "Search forward but ignore strings and comments.
10562 Invokes `re-search-forward' but treats the buffer as if strings
10563 and comments have been removed."
10564 (let ((saved-point (point)))
10565 (condition-case err
10566 (cond ((null count)
10567 (js2-re-search-forward-inner regexp bound 1))
10568 ((< count 0)
10569 (js2-re-search-backward-inner regexp bound (- count)))
10570 ((> count 0)
10571 (js2-re-search-forward-inner regexp bound count)))
10572 (search-failed
10573 (goto-char saved-point)
10574 (unless noerror
10575 (error (error-message-string err)))))))
10576
10577 (defun js2-re-search-backward-inner (regexp &optional bound count)
10578 "Auxiliary function for `js2-re-search-backward'."
10579 (let (parse)
10580 (while (> count 0)
10581 (re-search-backward regexp bound)
10582 (setq parse (syntax-ppss (point)))
10583 (cond ((nth 3 parse)
10584 (re-search-backward
10585 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10586 (line-beginning-position) t))
10587 ((nth 7 parse)
10588 (goto-char (nth 8 parse)))
10589 ((or (nth 4 parse)
10590 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10591 (re-search-backward "/\\*"))
10592 (t
10593 (setq count (1- count))))))
10594 (point))
10595
10596 (defun js2-re-search-backward (regexp &optional bound noerror count)
10597 "Search backward but ignore strings and comments.
10598 Invokes `re-search-backward' but treats the buffer as if strings
10599 and comments have been removed."
10600 (let ((saved-point (point)))
10601 (condition-case err
10602 (cond ((null count)
10603 (js2-re-search-backward-inner regexp bound 1))
10604 ((< count 0)
10605 (js2-re-search-forward-inner regexp bound (- count)))
10606 ((> count 0)
10607 (js2-re-search-backward-inner regexp bound count)))
10608 (search-failed
10609 (goto-char saved-point)
10610 (unless noerror
10611 (error (error-message-string err)))))))
10612
10613 (defun js2-looking-at-operator-p ()
10614 "Return non-nil if text after point is a non-comma operator."
10615 (and (looking-at js2-indent-operator-re)
10616 (or (not (looking-at ":"))
10617 (save-excursion
10618 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10619 (looking-at "?"))))))
10620
10621 (defun js2-continued-expression-p ()
10622 "Return non-nil if the current line continues an expression."
10623 (save-excursion
10624 (back-to-indentation)
10625 (or (js2-looking-at-operator-p)
10626 (when (catch 'found
10627 (while (and (re-search-backward "\n" nil t)
10628 (let ((state (syntax-ppss)))
10629 (when (nth 4 state)
10630 (goto-char (nth 8 state))) ;; skip comments
10631 (skip-chars-backward " \t")
10632 (if (bolp)
10633 t
10634 (throw 'found t))))))
10635 (backward-char)
10636 (when (js2-looking-at-operator-p)
10637 (backward-char)
10638 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10639
10640 (defun js2-end-of-do-while-loop-p ()
10641 "Return non-nil if word after point is `while' of a do-while
10642 statement, else returns nil. A braceless do-while statement
10643 spanning several lines requires that the start of the loop is
10644 indented to the same column as the current line."
10645 (interactive)
10646 (save-excursion
10647 (when (looking-at "\\s-*\\<while\\>")
10648 (if (save-excursion
10649 (skip-chars-backward "[ \t\n]*}")
10650 (looking-at "[ \t\n]*}"))
10651 (save-excursion
10652 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10653 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10654 (or (looking-at "\\<do\\>")
10655 (let ((saved-indent (current-indentation)))
10656 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10657 (/= (current-indentation) saved-indent)))
10658 (and (looking-at "[ \t]*\\<do\\>")
10659 (not (js2-re-search-forward
10660 "\\<while\\>" (point-at-eol) t))
10661 (= (current-indentation) saved-indent))))))))
10662
10663 (defun js2-multiline-decl-indentation ()
10664 "Return the declaration indentation column if the current line belongs
10665 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10666 (let (forward-sexp-function ; use Lisp version
10667 at-opening-bracket)
10668 (save-excursion
10669 (back-to-indentation)
10670 (when (not (looking-at js2-declaration-keyword-re))
10671 (when (looking-at js2-indent-operator-re)
10672 (goto-char (match-end 0))) ; continued expressions are ok
10673 (while (and (not at-opening-bracket)
10674 (not (bobp))
10675 (let ((pos (point)))
10676 (save-excursion
10677 (js2-backward-sws)
10678 (or (eq (char-before) ?,)
10679 (and (not (eq (char-before) ?\;))
10680 (prog2 (skip-syntax-backward ".")
10681 (looking-at js2-indent-operator-re)
10682 (js2-backward-sws))
10683 (not (eq (char-before) ?\;)))
10684 (js2-same-line pos)))))
10685 (condition-case _
10686 (backward-sexp)
10687 (scan-error (setq at-opening-bracket t))))
10688 (when (looking-at js2-declaration-keyword-re)
10689 (goto-char (match-end 0))
10690 (1+ (current-column)))))))
10691
10692 (defun js2-ctrl-statement-indentation ()
10693 "Return the proper indentation of current line if it is a control statement.
10694 Returns an indentation if this line starts the body of a control
10695 statement without braces, else returns nil."
10696 (let (forward-sexp-function)
10697 (save-excursion
10698 (back-to-indentation)
10699 (when (and (not (js2-same-line (point-min)))
10700 (not (looking-at "{"))
10701 (js2-re-search-backward "[[:graph:]]" nil t)
10702 (not (looking-at "[{([]"))
10703 (progn
10704 (forward-char)
10705 (when (= (char-before) ?\))
10706 ;; scan-sexps sometimes throws an error
10707 (ignore-errors (backward-sexp))
10708 (skip-chars-backward " \t" (point-at-bol)))
10709 (let ((pt (point)))
10710 (back-to-indentation)
10711 (when (looking-at "}[ \t]*")
10712 (goto-char (match-end 0)))
10713 (and (looking-at js2-possibly-braceless-keywords-re)
10714 (= (match-end 0) pt)
10715 (not (js2-end-of-do-while-loop-p))))))
10716 (+ (current-indentation) js2-basic-offset)))))
10717
10718 (defun js2-indent-in-array-comp (parse-status)
10719 "Return non-nil if we think we're in an array comprehension.
10720 In particular, return the buffer position of the first `for' kwd."
10721 (let ((bracket (nth 1 parse-status))
10722 (end (point)))
10723 (when bracket
10724 (save-excursion
10725 (goto-char bracket)
10726 (when (looking-at "\\[")
10727 (forward-char 1)
10728 (js2-forward-sws)
10729 (if (looking-at "[[{]")
10730 (let (forward-sexp-function) ; use Lisp version
10731 (forward-sexp) ; skip destructuring form
10732 (js2-forward-sws)
10733 (if (and (/= (char-after) ?,) ; regular array
10734 (looking-at "for"))
10735 (match-beginning 0)))
10736 ;; to skip arbitrary expressions we need the parser,
10737 ;; so we'll just guess at it.
10738 (if (and (> end (point)) ; not empty literal
10739 (re-search-forward "[^,]]* \\(for\\) " end t)
10740 ;; not inside comment or string literal
10741 (let ((state (parse-partial-sexp bracket (point))))
10742 (not (or (nth 3 state) (nth 4 state)))))
10743 (match-beginning 1))))))))
10744
10745 (defun js2-array-comp-indentation (parse-status for-kwd)
10746 (if (js2-same-line for-kwd)
10747 ;; first continuation line
10748 (save-excursion
10749 (goto-char (nth 1 parse-status))
10750 (forward-char 1)
10751 (skip-chars-forward " \t")
10752 (current-column))
10753 (save-excursion
10754 (goto-char for-kwd)
10755 (current-column))))
10756
10757 (defun js2-proper-indentation (parse-status)
10758 "Return the proper indentation for the current line."
10759 (save-excursion
10760 (back-to-indentation)
10761 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10762 (at-closing-bracket (looking-at "[]})]"))
10763 (same-indent-p (or at-closing-bracket
10764 (looking-at "\\<case\\>[^:]")
10765 (and (looking-at "\\<default:")
10766 (save-excursion
10767 (js2-backward-sws)
10768 (not (memq (char-before) '(?, ?{)))))))
10769 (continued-expr-p (js2-continued-expression-p))
10770 (declaration-indent (and js2-pretty-multiline-declarations
10771 (js2-multiline-decl-indentation)))
10772 (bracket (nth 1 parse-status))
10773 beg indent)
10774 (cond
10775 ;; indent array comprehension continuation lines specially
10776 ((and bracket
10777 (>= js2-language-version 170)
10778 (not (js2-same-line bracket))
10779 (setq beg (js2-indent-in-array-comp parse-status))
10780 (>= (point) (save-excursion
10781 (goto-char beg)
10782 (point-at-bol)))) ; at or after first loop?
10783 (js2-array-comp-indentation parse-status beg))
10784
10785 (ctrl-stmt-indent)
10786
10787 ((and declaration-indent continued-expr-p)
10788 (+ declaration-indent js2-basic-offset))
10789
10790 (declaration-indent)
10791
10792 (bracket
10793 (goto-char bracket)
10794 (cond
10795 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10796 (when (save-excursion (skip-chars-backward " \t)")
10797 (looking-at ")"))
10798 (backward-list))
10799 (back-to-indentation)
10800 (and (eq js2-pretty-multiline-declarations 'all)
10801 (looking-at js2-declaration-keyword-re)
10802 (goto-char (1+ (match-end 0))))
10803 (setq indent
10804 (cond (same-indent-p
10805 (current-column))
10806 (continued-expr-p
10807 (+ (current-column) (* 2 js2-basic-offset)))
10808 (t
10809 (+ (current-column) js2-basic-offset))))
10810 (if (and js2-indent-switch-body
10811 (not at-closing-bracket)
10812 (looking-at "\\_<switch\\_>"))
10813 (+ indent js2-basic-offset)
10814 indent))
10815 (t
10816 (unless same-indent-p
10817 (forward-char)
10818 (skip-chars-forward " \t"))
10819 (current-column))))
10820
10821 (continued-expr-p js2-basic-offset)
10822
10823 (t 0)))))
10824
10825 (defun js2-lineup-comment (parse-status)
10826 "Indent a multi-line block comment continuation line."
10827 (let* ((beg (nth 8 parse-status))
10828 (first-line (js2-same-line beg))
10829 (offset (save-excursion
10830 (goto-char beg)
10831 (if (looking-at "/\\*")
10832 (+ 1 (current-column))
10833 0))))
10834 (unless first-line
10835 (indent-line-to offset))))
10836
10837 (defun js2-backward-sws ()
10838 "Move backward through whitespace and comments."
10839 (interactive)
10840 (while (forward-comment -1)))
10841
10842 (defun js2-forward-sws ()
10843 "Move forward through whitespace and comments."
10844 (interactive)
10845 (while (forward-comment 1)))
10846
10847 (defun js2-current-indent (&optional pos)
10848 "Return column of indentation on current line.
10849 If POS is non-nil, go to that point and return indentation for that line."
10850 (save-excursion
10851 (if pos
10852 (goto-char pos))
10853 (back-to-indentation)
10854 (current-column)))
10855
10856 (defun js2-arglist-close ()
10857 "Return non-nil if we're on a line beginning with a close-paren/brace."
10858 (save-excursion
10859 (goto-char (point-at-bol))
10860 (js2-forward-sws)
10861 (looking-at "[])}]")))
10862
10863 (defun js2-indent-looks-like-label-p ()
10864 (goto-char (point-at-bol))
10865 (js2-forward-sws)
10866 (looking-at (concat js2-mode-identifier-re ":")))
10867
10868 (defun js2-indent-in-objlit-p (parse-status)
10869 "Return non-nil if this looks like an object-literal entry."
10870 (let ((start (nth 1 parse-status)))
10871 (and
10872 start
10873 (save-excursion
10874 (and (zerop (forward-line -1))
10875 (not (< (point) start)) ; crossed a {} boundary
10876 (js2-indent-looks-like-label-p)))
10877 (save-excursion
10878 (js2-indent-looks-like-label-p)))))
10879
10880 ;; If prev line looks like foobar({ then we're passing an object
10881 ;; literal to a function call, and people pretty much always want to
10882 ;; de-dent back to the previous line, so move the 'basic-offset'
10883 ;; position to the front.
10884 (defun js2-indent-objlit-arg-p (parse-status)
10885 (save-excursion
10886 (back-to-indentation)
10887 (js2-backward-sws)
10888 (and (eq (1- (point)) (nth 1 parse-status))
10889 (eq (char-before) ?{)
10890 (progn
10891 (forward-char -1)
10892 (skip-chars-backward " \t")
10893 (eq (char-before) ?\()))))
10894
10895 (defun js2-indent-case-block-p ()
10896 (save-excursion
10897 (back-to-indentation)
10898 (js2-backward-sws)
10899 (goto-char (point-at-bol))
10900 (skip-chars-forward " \t")
10901 (looking-at "case\\s-.+:")))
10902
10903 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10904 "Cycle among alternate computed indentation positions.
10905 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10906 of the buffer to the current point. NORMAL-COL is the indentation
10907 column computed by the heuristic guesser based on current paren,
10908 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10909 in reverse."
10910 (let ((cur-indent (js2-current-indent))
10911 (old-buffer-undo-list buffer-undo-list)
10912 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10913 (current-line (save-excursion
10914 (forward-line 0) ; move to bol
10915 (1+ (count-lines (point-min) (point)))))
10916 positions pos main-pos anchor arglist-cont same-indent
10917 basic-offset computed-pos)
10918 ;; temporarily don't record undo info, if user requested this
10919 (when js2-mode-indent-inhibit-undo
10920 (setq buffer-undo-list t))
10921 (unwind-protect
10922 (progn
10923 ;; First likely point: indent from beginning of previous code line
10924 (push (setq basic-offset
10925 (+ (save-excursion
10926 (back-to-indentation)
10927 (js2-backward-sws)
10928 (back-to-indentation)
10929 (current-column))
10930 js2-basic-offset))
10931 positions)
10932
10933 ;; (First + epsilon) likely point: indent 2x from beginning of
10934 ;; previous code line. Google does it this way.
10935 (push (setq basic-offset
10936 (+ (save-excursion
10937 (back-to-indentation)
10938 (js2-backward-sws)
10939 (back-to-indentation)
10940 (current-column))
10941 (* 2 js2-basic-offset)))
10942 positions)
10943
10944 ;; Second likely point: indent from assign-expr RHS. This
10945 ;; is just a crude guess based on finding " = " on the previous
10946 ;; line containing actual code.
10947 (setq pos (save-excursion
10948 (forward-line -1)
10949 (goto-char (point-at-bol))
10950 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10951 (point-at-eol) t)
10952 (goto-char (match-end 1))
10953 (skip-chars-forward " \t\r\n")
10954 (current-column))))
10955 (when pos
10956 (cl-incf pos js2-basic-offset)
10957 (push pos positions))
10958
10959 ;; Third likely point: same indent as previous line of code.
10960 ;; Make it the first likely point if we're not on an
10961 ;; arglist-close line and previous line ends in a comma, or
10962 ;; both this line and prev line look like object-literal
10963 ;; elements.
10964 (setq pos (save-excursion
10965 (goto-char (point-at-bol))
10966 (js2-backward-sws)
10967 (back-to-indentation)
10968 (prog1
10969 (current-column)
10970 ;; while we're here, look for trailing comma
10971 (if (save-excursion
10972 (goto-char (point-at-eol))
10973 (js2-backward-sws)
10974 (eq (char-before) ?,))
10975 (setq arglist-cont (1- (point)))))))
10976 (when pos
10977 (if (and (or arglist-cont
10978 (js2-indent-in-objlit-p parse-status))
10979 (not (js2-arglist-close)))
10980 (setq same-indent pos))
10981 (push pos positions))
10982
10983 ;; Fourth likely point: first preceding code with less indentation.
10984 ;; than the immediately preceding code line.
10985 (setq pos (save-excursion
10986 (back-to-indentation)
10987 (js2-backward-sws)
10988 (back-to-indentation)
10989 (setq anchor (current-column))
10990 (while (and (zerop (forward-line -1))
10991 (>= (progn
10992 (back-to-indentation)
10993 (current-column))
10994 anchor)))
10995 (setq pos (current-column))))
10996 (push pos positions)
10997
10998 ;; nesting-heuristic position, main by default
10999 (push (setq main-pos normal-col) positions)
11000
11001 ;; delete duplicates and sort positions list
11002 (setq positions (sort (delete-dups positions) '<))
11003
11004 ;; comma-list continuation lines: prev line indent takes precedence
11005 (if same-indent
11006 (setq main-pos same-indent))
11007
11008 ;; common special cases where we want to indent in from previous line
11009 (if (or (js2-indent-case-block-p)
11010 (js2-indent-objlit-arg-p parse-status))
11011 (setq main-pos basic-offset))
11012
11013 ;; if bouncing backwards, reverse positions list
11014 (if backwards
11015 (setq positions (reverse positions)))
11016
11017 ;; record whether we're already sitting on one of the alternatives
11018 (setq pos (member cur-indent positions))
11019
11020 (cond
11021 ;; case 0: we're one one of the alternatives and this is the
11022 ;; first time they've pressed TAB on this line (best-guess).
11023 ((and js2-mode-indent-ignore-first-tab
11024 pos
11025 ;; first time pressing TAB on this line?
11026 (not (eq js2-mode-last-indented-line current-line)))
11027 ;; do nothing
11028 (setq computed-pos nil))
11029 ;; case 1: only one computed position => use it
11030 ((null (cdr positions))
11031 (setq computed-pos 0))
11032 ;; case 2: not on any of the computed spots => use main spot
11033 ((not pos)
11034 (setq computed-pos (js2-position main-pos positions)))
11035 ;; case 3: on last position: cycle to first position
11036 ((null (cdr pos))
11037 (setq computed-pos 0))
11038 ;; case 4: on intermediate position: cycle to next position
11039 (t
11040 (setq computed-pos (js2-position (cl-second pos) positions))))
11041
11042 ;; see if any hooks want to indent; otherwise we do it
11043 (cl-loop with result = nil
11044 for hook in js2-indent-hook
11045 while (null result)
11046 do
11047 (setq result (funcall hook positions computed-pos))
11048 finally do
11049 (unless (or result (null computed-pos))
11050 (indent-line-to (nth computed-pos positions)))))
11051
11052 ;; finally
11053 (if js2-mode-indent-inhibit-undo
11054 (setq buffer-undo-list old-buffer-undo-list))
11055 ;; see commentary for `js2-mode-last-indented-line'
11056 (setq js2-mode-last-indented-line current-line))))
11057
11058 (defun js2-indent-bounce-backwards ()
11059 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11060 cycles between the computed indentation positions in reverse order."
11061 (interactive)
11062 (js2-indent-line t))
11063
11064 (defun js2-1-line-comment-continuation-p ()
11065 "Return t if we're in a 1-line comment continuation.
11066 If so, we don't ever want to use bounce-indent."
11067 (save-excursion
11068 (and (progn
11069 (forward-line 0)
11070 (looking-at "\\s-*//"))
11071 (progn
11072 (forward-line -1)
11073 (forward-line 0)
11074 (when (looking-at "\\s-*$")
11075 (js2-backward-sws)
11076 (forward-line 0))
11077 (looking-at "\\s-*//")))))
11078
11079 (defun js2-indent-line (&optional bounce-backwards)
11080 "Indent the current line as JavaScript source text."
11081 (interactive)
11082 (let (parse-status offset indent-col
11083 ;; Don't whine about errors/warnings when we're indenting.
11084 ;; This has to be set before calling parse-partial-sexp below.
11085 (inhibit-point-motion-hooks t))
11086 (setq parse-status (save-excursion
11087 (syntax-ppss (point-at-bol)))
11088 offset (- (point) (save-excursion
11089 (back-to-indentation)
11090 (point))))
11091 (js2-with-underscore-as-word-syntax
11092 (if (nth 4 parse-status)
11093 (js2-lineup-comment parse-status)
11094 (setq indent-col (js2-proper-indentation parse-status))
11095 ;; See comments below about `js2-mode-last-indented-line'.
11096 (cond
11097 ;; bounce-indenting is disabled during electric-key indent.
11098 ;; It doesn't work well on first line of buffer.
11099 ((and js2-bounce-indent-p
11100 (not (js2-same-line (point-min)))
11101 (not (js2-1-line-comment-continuation-p)))
11102 (js2-bounce-indent indent-col parse-status bounce-backwards))
11103 ;; just indent to the guesser's likely spot
11104 (t (indent-line-to indent-col))))
11105 (when (cl-plusp offset)
11106 (forward-char offset)))))
11107
11108 (defun js2-indent-region (start end)
11109 "Indent the region, but don't use bounce indenting."
11110 (let ((js2-bounce-indent-p nil)
11111 (indent-region-function nil)
11112 (after-change-functions (remq 'js2-mode-edit
11113 after-change-functions)))
11114 (indent-region start end nil) ; nil for byte-compiler
11115 (js2-mode-edit start end (- end start))))
11116
11117 (defvar js2-minor-mode-map
11118 (let ((map (make-sparse-keymap)))
11119 (define-key map (kbd "C-c C-`") #'js2-next-error)
11120 (define-key map [mouse-1] #'js2-mode-show-node)
11121 map)
11122 "Keymap used when `js2-minor-mode' is active.")
11123
11124 ;;;###autoload
11125 (define-minor-mode js2-minor-mode
11126 "Minor mode for running js2 as a background linter.
11127 This allows you to use a different major mode for JavaScript editing,
11128 such as `js-mode', while retaining the asynchronous error/warning
11129 highlighting features of `js2-mode'."
11130 :group 'js2-mode
11131 :lighter " js-lint"
11132 (if js2-minor-mode
11133 (js2-minor-mode-enter)
11134 (js2-minor-mode-exit)))
11135
11136 (defun js2-minor-mode-enter ()
11137 "Initialization for `js2-minor-mode'."
11138 (set (make-local-variable 'max-lisp-eval-depth)
11139 (max max-lisp-eval-depth 3000))
11140 (setq next-error-function #'js2-next-error)
11141 (js2-set-default-externs)
11142 ;; Experiment: make reparse-delay longer for longer files.
11143 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11144 (setq js2-idle-timer-delay
11145 (* js2-idle-timer-delay
11146 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11147 (setq js2-mode-buffer-dirty-p t
11148 js2-mode-parsing nil)
11149 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11150 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11151 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11152 (when js2-include-jslint-globals
11153 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11154 (run-hooks 'js2-init-hook)
11155 (js2-reparse))
11156
11157 (defun js2-minor-mode-exit ()
11158 "Turn off `js2-minor-mode'."
11159 (setq next-error-function nil)
11160 (remove-hook 'after-change-functions #'js2-mode-edit t)
11161 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11162 (when js2-mode-node-overlay
11163 (delete-overlay js2-mode-node-overlay)
11164 (setq js2-mode-node-overlay nil))
11165 (js2-remove-overlays)
11166 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11167 (setq js2-mode-ast nil))
11168
11169 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11170 (make-variable-buffer-local 'js2-source-buffer)
11171
11172 (cl-defun js2-display-error-list ()
11173 "Display a navigable buffer listing parse errors/warnings."
11174 (interactive)
11175 (unless (js2-have-errors-p)
11176 (message "No errors")
11177 (cl-return-from js2-display-error-list))
11178 (cl-labels ((annotate-list
11179 (lst type)
11180 "Add diagnostic TYPE and line number to errs list"
11181 (mapcar (lambda (err)
11182 (list err type (line-number-at-pos (nth 1 err))))
11183 lst)))
11184 (let* ((srcbuf (current-buffer))
11185 (errbuf (get-buffer-create "*js-lint*"))
11186 (errors (annotate-list
11187 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11188 'js2-error)) ; must be a valid face name
11189 (warnings (annotate-list
11190 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11191 'js2-warning)) ; must be a valid face name
11192 (all-errs (sort (append errors warnings)
11193 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11194 (with-current-buffer errbuf
11195 (let ((inhibit-read-only t))
11196 (erase-buffer)
11197 (dolist (err all-errs)
11198 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11199 (insert-text-button
11200 (format "line %d: %s" line (js2-get-msg msg-key))
11201 'face type
11202 'follow-link "\C-m"
11203 'action 'js2-error-buffer-jump
11204 'js2-msg (js2-get-msg msg-key)
11205 'js2-pos beg)
11206 (insert "\n"))))
11207 (js2-error-buffer-mode)
11208 (setq js2-source-buffer srcbuf)
11209 (pop-to-buffer errbuf)
11210 (goto-char (point-min))
11211 (unless (eobp)
11212 (js2-error-buffer-view))))))
11213
11214 (defvar js2-error-buffer-mode-map
11215 (let ((map (make-sparse-keymap)))
11216 (define-key map "n" #'js2-error-buffer-next)
11217 (define-key map "p" #'js2-error-buffer-prev)
11218 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11219 (define-key map "o" #'js2-error-buffer-view)
11220 (define-key map "q" #'js2-error-buffer-quit)
11221 map)
11222 "Keymap used for js2 diagnostics buffers.")
11223
11224 (defun js2-error-buffer-mode ()
11225 "Major mode for js2 diagnostics buffers.
11226 Selecting an error will jump it to the corresponding source-buffer error.
11227 \\{js2-error-buffer-mode-map}"
11228 (interactive)
11229 (setq major-mode 'js2-error-buffer-mode
11230 mode-name "JS Lint Diagnostics")
11231 (use-local-map js2-error-buffer-mode-map)
11232 (setq truncate-lines t)
11233 (set-buffer-modified-p nil)
11234 (setq buffer-read-only t)
11235 (run-hooks 'js2-error-buffer-mode-hook))
11236
11237 (defun js2-error-buffer-next ()
11238 "Move to next error and view it."
11239 (interactive)
11240 (when (zerop (forward-line 1))
11241 (js2-error-buffer-view)))
11242
11243 (defun js2-error-buffer-prev ()
11244 "Move to previous error and view it."
11245 (interactive)
11246 (when (zerop (forward-line -1))
11247 (js2-error-buffer-view)))
11248
11249 (defun js2-error-buffer-quit ()
11250 "Kill the current buffer."
11251 (interactive)
11252 (kill-buffer))
11253
11254 (defun js2-error-buffer-jump (&rest ignored)
11255 "Jump cursor to current error in source buffer."
11256 (interactive)
11257 (when (js2-error-buffer-view)
11258 (pop-to-buffer js2-source-buffer)))
11259
11260 (defun js2-error-buffer-view ()
11261 "Scroll source buffer to show error at current line."
11262 (interactive)
11263 (cond
11264 ((not (eq major-mode 'js2-error-buffer-mode))
11265 (message "Not in a js2 errors buffer"))
11266 ((not (buffer-live-p js2-source-buffer))
11267 (message "Source buffer has been killed"))
11268 ((not (wholenump (get-text-property (point) 'js2-pos)))
11269 (message "There does not seem to be an error here"))
11270 (t
11271 (let ((pos (get-text-property (point) 'js2-pos))
11272 (msg (get-text-property (point) 'js2-msg)))
11273 (save-selected-window
11274 (pop-to-buffer js2-source-buffer)
11275 (goto-char pos)
11276 (message msg))))))
11277
11278 ;;;###autoload
11279 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11280 ;; FIXME: Should derive from js-mode.
11281 "Major mode for editing JavaScript code."
11282 ;; Used by comment-region; don't change it.
11283 (set (make-local-variable 'comment-start) "//")
11284 (set (make-local-variable 'comment-end) "")
11285 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11286 (set (make-local-variable 'max-lisp-eval-depth)
11287 (max max-lisp-eval-depth 3000))
11288 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11289 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11290 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11291 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11292 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11293 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11294 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11295 ;; for characters inside regexp literals.
11296 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11297 ;; this is necessary to make `show-paren-function' work properly
11298 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11299 ;; needed for M-x rgrep, among other things
11300 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11301
11302 (set (make-local-variable 'electric-indent-chars)
11303 (append "{}()[]:;,*." electric-indent-chars))
11304 (set (make-local-variable 'electric-layout-rules)
11305 '((?\; . after) (?\{ . after) (?\} . before)))
11306
11307 ;; some variables needed by cc-engine for paragraph-fill, etc.
11308 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11309 c-comment-start-regexp "/[*/]\\|\\s|"
11310 c-line-comment-starter "//"
11311 c-paragraph-start js2-paragraph-start
11312 c-paragraph-separate "$"
11313 c-syntactic-ws-start js2-syntactic-ws-start
11314 c-syntactic-ws-end js2-syntactic-ws-end
11315 c-syntactic-eol js2-syntactic-eol)
11316
11317 (let ((c-buffer-is-cc-mode t))
11318 ;; Copied from `js-mode'. Also see Bug#6071.
11319 (make-local-variable 'paragraph-start)
11320 (make-local-variable 'paragraph-separate)
11321 (make-local-variable 'paragraph-ignore-fill-prefix)
11322 (make-local-variable 'adaptive-fill-mode)
11323 (make-local-variable 'adaptive-fill-regexp)
11324 (c-setup-paragraph-variables))
11325
11326 (setq font-lock-defaults '(nil t))
11327
11328 ;; Experiment: make reparse-delay longer for longer files.
11329 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11330 (setq js2-idle-timer-delay
11331 (* js2-idle-timer-delay
11332 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11333
11334 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11335 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11336 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11337 (setq next-error-function #'js2-next-error)
11338 (imenu-add-to-menubar (concat "IM-" mode-name))
11339 (add-to-invisibility-spec '(js2-outline . t))
11340 (set (make-local-variable 'line-move-ignore-invisible) t)
11341 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11342
11343 (setq js2-mode-functions-hidden nil
11344 js2-mode-comments-hidden nil
11345 js2-mode-buffer-dirty-p t
11346 js2-mode-parsing nil)
11347
11348 (js2-set-default-externs)
11349
11350 (when js2-include-jslint-globals
11351 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11352
11353 (run-hooks 'js2-init-hook)
11354
11355 (js2-reparse))
11356
11357 (defun js2-mode-exit ()
11358 "Exit `js2-mode' and clean up."
11359 (interactive)
11360 (when js2-mode-node-overlay
11361 (delete-overlay js2-mode-node-overlay)
11362 (setq js2-mode-node-overlay nil))
11363 (js2-remove-overlays)
11364 (setq js2-mode-ast nil)
11365 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11366 (remove-from-invisibility-spec '(js2-outline . t))
11367 (js2-mode-show-all)
11368 (with-silent-modifications
11369 (js2-clear-face (point-min) (point-max))))
11370
11371 (defun js2-mode-reset-timer ()
11372 "Cancel any existing parse timer and schedule a new one."
11373 (if js2-mode-parse-timer
11374 (cancel-timer js2-mode-parse-timer))
11375 (setq js2-mode-parsing nil)
11376 (let ((timer (timer-create)))
11377 (setq js2-mode-parse-timer timer)
11378 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11379 (timer-set-idle-time timer js2-idle-timer-delay)
11380 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11381 (timer-activate-when-idle timer nil)))
11382
11383 (defun js2-mode-idle-reparse (buffer)
11384 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11385 it to be reparsed when the buffer is selected."
11386 (cond ((eq buffer (current-buffer))
11387 (js2-reparse))
11388 ((buffer-live-p buffer)
11389 ;; reparse when the buffer is selected again
11390 (with-current-buffer buffer
11391 (add-hook 'window-configuration-change-hook
11392 #'js2-mode-idle-reparse-inner
11393 nil t)))))
11394
11395 (defun js2-mode-idle-reparse-inner ()
11396 (remove-hook 'window-configuration-change-hook
11397 #'js2-mode-idle-reparse-inner
11398 t)
11399 (js2-reparse))
11400
11401 (defun js2-mode-edit (_beg _end _len)
11402 "Schedule a new parse after buffer is edited.
11403 Buffer edit spans from BEG to END and is of length LEN."
11404 (setq js2-mode-buffer-dirty-p t)
11405 (js2-mode-hide-overlay)
11406 (js2-mode-reset-timer))
11407
11408 (defun js2-minor-mode-edit (_beg _end _len)
11409 "Callback for buffer edits in `js2-mode'.
11410 Schedules a new parse after buffer is edited.
11411 Buffer edit spans from BEG to END and is of length LEN."
11412 (setq js2-mode-buffer-dirty-p t)
11413 (js2-mode-hide-overlay)
11414 (js2-mode-reset-timer))
11415
11416 (defun js2-reparse (&optional force)
11417 "Re-parse current buffer after user finishes some data entry.
11418 If we get any user input while parsing, including cursor motion,
11419 we discard the parse and reschedule it. If FORCE is nil, then the
11420 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11421 (let (time
11422 interrupted-p
11423 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11424 (unless js2-mode-parsing
11425 (setq js2-mode-parsing t)
11426 (unwind-protect
11427 (when (or js2-mode-buffer-dirty-p force)
11428 (js2-remove-overlays)
11429 (setq js2-mode-buffer-dirty-p nil
11430 js2-mode-fontifications nil
11431 js2-mode-deferred-properties nil)
11432 (if js2-mode-verbose-parse-p
11433 (message "parsing..."))
11434 (setq time
11435 (js2-time
11436 (setq interrupted-p
11437 (catch 'interrupted
11438 (js2-parse)
11439 (with-silent-modifications
11440 ;; if parsing is interrupted, comments and regex
11441 ;; literals stay ignored by `parse-partial-sexp'
11442 (remove-text-properties (point-min) (point-max)
11443 '(syntax-table))
11444 (js2-mode-apply-deferred-properties)
11445 (js2-mode-remove-suppressed-warnings)
11446 (js2-mode-show-warnings)
11447 (js2-mode-show-errors)
11448 (if (>= js2-highlight-level 1)
11449 (js2-highlight-jsdoc js2-mode-ast)))
11450 nil))))
11451 (if interrupted-p
11452 (progn
11453 ;; unfinished parse => try again
11454 (setq js2-mode-buffer-dirty-p t)
11455 (js2-mode-reset-timer))
11456 (if js2-mode-verbose-parse-p
11457 (message "Parse time: %s" time))))
11458 (setq js2-mode-parsing nil)
11459 (unless interrupted-p
11460 (setq js2-mode-parse-timer nil))))))
11461
11462 (defun js2-mode-show-node (event)
11463 "Debugging aid: highlight selected AST node on mouse click."
11464 (interactive "e")
11465 (mouse-set-point event)
11466 (setq deactivate-mark t)
11467 (when js2-mode-show-overlay
11468 (let ((node (js2-node-at-point))
11469 beg end)
11470 (if (null node)
11471 (message "No node found at location %s" (point))
11472 (setq beg (js2-node-abs-pos node)
11473 end (+ beg (js2-node-len node)))
11474 (if js2-mode-node-overlay
11475 (move-overlay js2-mode-node-overlay beg end)
11476 (setq js2-mode-node-overlay (make-overlay beg end))
11477 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11478 (with-silent-modifications
11479 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
11480 (message "%s, parent: %s"
11481 (js2-node-short-name node)
11482 (if (js2-node-parent node)
11483 (js2-node-short-name (js2-node-parent node))
11484 "nil"))))))
11485
11486 (defun js2-mode-hide-overlay (&optional _p1 p2)
11487 "Remove the debugging overlay when the point moves.
11488 P1 and P2 are the old and new values of point, respectively."
11489 (when js2-mode-node-overlay
11490 (let ((beg (overlay-start js2-mode-node-overlay))
11491 (end (overlay-end js2-mode-node-overlay)))
11492 ;; Sometimes we're called spuriously.
11493 (unless (and p2
11494 (>= p2 beg)
11495 (<= p2 end))
11496 (with-silent-modifications
11497 (remove-text-properties beg end '(point-left nil)))
11498 (delete-overlay js2-mode-node-overlay)
11499 (setq js2-mode-node-overlay nil)))))
11500
11501 (defun js2-mode-reset ()
11502 "Debugging helper: reset everything."
11503 (interactive)
11504 (js2-mode-exit)
11505 (js2-mode))
11506
11507 (defun js2-mode-show-warn-or-err (e face)
11508 "Highlight a warning or error E with FACE.
11509 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11510 The last element is optional. When present, use instead of FACE."
11511 (let* ((key (cl-first e))
11512 (beg (cl-second e))
11513 (end (+ beg (cl-third e)))
11514 ;; Don't inadvertently go out of bounds.
11515 (beg (max (point-min) (min beg (point-max))))
11516 (end (max (point-min) (min end (point-max))))
11517 (ovl (make-overlay beg end)))
11518 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11519 (overlay-put ovl 'js2-error t)
11520 (put-text-property beg end 'help-echo (js2-get-msg key))
11521 (put-text-property beg end 'point-entered #'js2-echo-error)))
11522
11523 (defun js2-remove-overlays ()
11524 "Remove overlays from buffer that have a `js2-error' property."
11525 (let ((beg (point-min))
11526 (end (point-max)))
11527 (save-excursion
11528 (dolist (o (overlays-in beg end))
11529 (when (overlay-get o 'js2-error)
11530 (delete-overlay o))))))
11531
11532 (defun js2-error-at-point (&optional pos)
11533 "Return non-nil if there's an error overlay at POS.
11534 Defaults to point."
11535 (cl-loop with pos = (or pos (point))
11536 for o in (overlays-at pos)
11537 thereis (overlay-get o 'js2-error)))
11538
11539 (defun js2-mode-apply-deferred-properties ()
11540 "Apply fontifications and other text properties recorded during parsing."
11541 (when (cl-plusp js2-highlight-level)
11542 ;; We defer clearing faces as long as possible to eliminate flashing.
11543 (js2-clear-face (point-min) (point-max))
11544 ;; Have to reverse the recorded fontifications list so that errors
11545 ;; and warnings overwrite the normal fontifications.
11546 (dolist (f (nreverse js2-mode-fontifications))
11547 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11548 (setq js2-mode-fontifications nil))
11549 (dolist (p js2-mode-deferred-properties)
11550 (apply #'put-text-property p))
11551 (setq js2-mode-deferred-properties nil))
11552
11553 (defun js2-mode-show-errors ()
11554 "Highlight syntax errors."
11555 (when js2-mode-show-parse-errors
11556 (dolist (e (js2-ast-root-errors js2-mode-ast))
11557 (js2-mode-show-warn-or-err e 'js2-error))))
11558
11559 (defun js2-mode-remove-suppressed-warnings ()
11560 "Take suppressed warnings out of the AST warnings list.
11561 This ensures that the counts and `next-error' are correct."
11562 (setf (js2-ast-root-warnings js2-mode-ast)
11563 (js2-delete-if
11564 (lambda (e)
11565 (let ((key (caar e)))
11566 (or
11567 (and (not js2-strict-trailing-comma-warning)
11568 (string-match "trailing\\.comma" key))
11569 (and (not js2-strict-cond-assign-warning)
11570 (string= key "msg.equal.as.assign"))
11571 (and js2-missing-semi-one-line-override
11572 (string= key "msg.missing.semi")
11573 (let* ((beg (cl-second e))
11574 (node (js2-node-at-point beg))
11575 (fn (js2-mode-find-parent-fn node))
11576 (body (and fn (js2-function-node-body fn)))
11577 (lc (and body (js2-node-abs-pos body)))
11578 (rc (and lc (+ lc (js2-node-len body)))))
11579 (and fn
11580 (or (null body)
11581 (save-excursion
11582 (goto-char beg)
11583 (and (js2-same-line lc)
11584 (js2-same-line rc))))))))))
11585 (js2-ast-root-warnings js2-mode-ast))))
11586
11587 (defun js2-mode-show-warnings ()
11588 "Highlight strict-mode warnings."
11589 (when js2-mode-show-strict-warnings
11590 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11591 (js2-mode-show-warn-or-err e 'js2-warning))))
11592
11593 (defun js2-echo-error (_old-point new-point)
11594 "Called by point-motion hooks."
11595 (let ((msg (get-text-property new-point 'help-echo)))
11596 (when (and (stringp msg)
11597 (not (active-minibuffer-window))
11598 (not (current-message)))
11599 (message msg))))
11600
11601 (defalias 'js2-echo-help #'js2-echo-error)
11602
11603 (defun js2-line-break (&optional _soft)
11604 "Break line at point and indent, continuing comment if within one.
11605 If inside a string, and `js2-concat-multiline-strings' is not
11606 nil, turn it into concatenation."
11607 (interactive)
11608 (let ((parse-status (syntax-ppss)))
11609 (cond
11610 ;; Check if we're inside a string.
11611 ((nth 3 parse-status)
11612 (if js2-concat-multiline-strings
11613 (js2-mode-split-string parse-status)
11614 (insert "\n")))
11615 ;; Check if inside a block comment.
11616 ((nth 4 parse-status)
11617 (js2-mode-extend-comment (nth 8 parse-status)))
11618 (t
11619 (newline-and-indent)))))
11620
11621 (defun js2-mode-split-string (parse-status)
11622 "Turn a newline in mid-string into a string concatenation.
11623 PARSE-STATUS is as documented in `parse-partial-sexp'."
11624 (let* ((quote-char (nth 3 parse-status))
11625 (at-eol (eq js2-concat-multiline-strings 'eol)))
11626 (insert quote-char)
11627 (insert (if at-eol " +\n" "\n"))
11628 (unless at-eol
11629 (insert "+ "))
11630 (js2-indent-line)
11631 (insert quote-char)
11632 (when (eolp)
11633 (insert quote-char)
11634 (backward-char 1))))
11635
11636 (defun js2-mode-extend-comment (start-pos)
11637 "Indent the line and, when inside a comment block, add comment prefix."
11638 (let (star single col first-line needs-close)
11639 (save-excursion
11640 (back-to-indentation)
11641 (when (< (point) start-pos)
11642 (goto-char start-pos))
11643 (cond
11644 ((looking-at "\\*[^/]")
11645 (setq star t
11646 col (current-column)))
11647 ((looking-at "/\\*")
11648 (setq star t
11649 first-line t
11650 col (1+ (current-column))))
11651 ((looking-at "//")
11652 (setq single t
11653 col (current-column)))))
11654 ;; Heuristic for whether we need to close the comment:
11655 ;; if we've got a parse error here, assume it's an unterminated
11656 ;; comment.
11657 (setq needs-close
11658 (or
11659 (eq (get-text-property (1- (point)) 'point-entered)
11660 'js2-echo-error)
11661 ;; The heuristic above doesn't work well when we're
11662 ;; creating a comment and there's another one downstream,
11663 ;; as our parser thinks this one ends at the end of the
11664 ;; next one. (You can have a /* inside a js block comment.)
11665 ;; So just close it if the next non-ws char isn't a *.
11666 (and first-line
11667 (eolp)
11668 (save-excursion
11669 (skip-chars-forward " \t\r\n")
11670 (not (eq (char-after) ?*))))))
11671 (delete-horizontal-space)
11672 (insert "\n")
11673 (cond
11674 (star
11675 (indent-to col)
11676 (insert "* ")
11677 (if (and first-line needs-close)
11678 (save-excursion
11679 (insert "\n")
11680 (indent-to col)
11681 (insert "*/"))))
11682 ((and single
11683 (save-excursion
11684 (and (zerop (forward-line 1))
11685 (looking-at "\\s-*//"))))
11686 (indent-to col)
11687 (insert "// ")))
11688 ;; Don't need to extend the comment after all.
11689 (js2-indent-line)))
11690
11691 (defun js2-beginning-of-line ()
11692 "Toggle point between bol and first non-whitespace char in line.
11693 Also moves past comment delimiters when inside comments."
11694 (interactive)
11695 (let (node)
11696 (cond
11697 ((bolp)
11698 (back-to-indentation))
11699 ((looking-at "//")
11700 (skip-chars-forward "/ \t"))
11701 ((and (eq (char-after) ?*)
11702 (setq node (js2-comment-at-point))
11703 (memq (js2-comment-node-format node) '(jsdoc block))
11704 (save-excursion
11705 (skip-chars-backward " \t")
11706 (bolp)))
11707 (skip-chars-forward "\* \t"))
11708 (t
11709 (goto-char (point-at-bol))))))
11710
11711 (defun js2-end-of-line ()
11712 "Toggle point between eol and last non-whitespace char in line."
11713 (interactive)
11714 (if (eolp)
11715 (skip-chars-backward " \t")
11716 (goto-char (point-at-eol))))
11717
11718 (defun js2-mode-wait-for-parse (callback)
11719 "Invoke CALLBACK when parsing is finished.
11720 If parsing is already finished, calls CALLBACK immediately."
11721 (if (not js2-mode-buffer-dirty-p)
11722 (funcall callback)
11723 (push callback js2-mode-pending-parse-callbacks)
11724 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11725
11726 (defun js2-mode-parse-finished ()
11727 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11728 ;; We can't let errors propagate up, since it prevents the
11729 ;; `js2-parse' method from completing normally and returning
11730 ;; the ast, which makes things mysteriously not work right.
11731 (unwind-protect
11732 (dolist (cb js2-mode-pending-parse-callbacks)
11733 (condition-case err
11734 (funcall cb)
11735 (error (message "%s" err))))
11736 (setq js2-mode-pending-parse-callbacks nil)))
11737
11738 (defun js2-mode-flag-region (from to flag)
11739 "Hide or show text from FROM to TO, according to FLAG.
11740 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11741 Returns the created overlay if FLAG is non-nil."
11742 (remove-overlays from to 'invisible 'js2-outline)
11743 (when flag
11744 (let ((o (make-overlay from to)))
11745 (overlay-put o 'invisible 'js2-outline)
11746 (overlay-put o 'isearch-open-invisible
11747 'js2-isearch-open-invisible)
11748 o)))
11749
11750 ;; Function to be set as an outline-isearch-open-invisible' property
11751 ;; to the overlay that makes the outline invisible (see
11752 ;; `js2-mode-flag-region').
11753 (defun js2-isearch-open-invisible (_overlay)
11754 ;; We rely on the fact that isearch places point on the matched text.
11755 (js2-mode-show-element))
11756
11757 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11758 "Return cons cell of bounds of folding overlay at POS.
11759 Returns nil if not found."
11760 (let ((overlays (overlays-at (or pos (point))))
11761 o)
11762 (while (and overlays
11763 (not o))
11764 (if (overlay-get (car overlays) 'invisible)
11765 (setq o (car overlays))
11766 (setq overlays (cdr overlays))))
11767 (if o
11768 (cons (overlay-start o) (overlay-end o)))))
11769
11770 (defun js2-mode-function-at-point (&optional pos)
11771 "Return the innermost function node enclosing current point.
11772 Returns nil if point is not in a function."
11773 (let ((node (js2-node-at-point pos)))
11774 (while (and node (not (js2-function-node-p node)))
11775 (setq node (js2-node-parent node)))
11776 (if (js2-function-node-p node)
11777 node)))
11778
11779 (defun js2-mode-toggle-element ()
11780 "Hide or show the foldable element at the point."
11781 (interactive)
11782 (let (comment fn pos)
11783 (save-excursion
11784 (cond
11785 ;; /* ... */ comment?
11786 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11787 (if (js2-mode-invisible-overlay-bounds
11788 (setq pos (+ 3 (js2-node-abs-pos comment))))
11789 (progn
11790 (goto-char pos)
11791 (js2-mode-show-element))
11792 (js2-mode-hide-element)))
11793 ;; //-comment?
11794 ((save-excursion
11795 (back-to-indentation)
11796 (looking-at js2-mode-//-comment-re))
11797 (js2-mode-toggle-//-comment))
11798 ;; function?
11799 ((setq fn (js2-mode-function-at-point))
11800 (setq pos (and (js2-function-node-body fn)
11801 (js2-node-abs-pos (js2-function-node-body fn))))
11802 (goto-char (1+ pos))
11803 (if (js2-mode-invisible-overlay-bounds)
11804 (js2-mode-show-element)
11805 (js2-mode-hide-element)))
11806 (t
11807 (message "Nothing at point to hide or show"))))))
11808
11809 (defun js2-mode-hide-element ()
11810 "Fold/hide contents of a block, showing ellipses.
11811 Show the hidden text with \\[js2-mode-show-element]."
11812 (interactive)
11813 (if js2-mode-buffer-dirty-p
11814 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11815 (let (node body beg end)
11816 (cond
11817 ((js2-mode-invisible-overlay-bounds)
11818 (message "already hidden"))
11819 (t
11820 (setq node (js2-node-at-point))
11821 (cond
11822 ((js2-block-comment-p node)
11823 (js2-mode-hide-comment node))
11824 (t
11825 (while (and node (not (js2-function-node-p node)))
11826 (setq node (js2-node-parent node)))
11827 (if (and node
11828 (setq body (js2-function-node-body node)))
11829 (progn
11830 (setq beg (js2-node-abs-pos body)
11831 end (+ beg (js2-node-len body)))
11832 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11833 (message "No collapsable element found at point"))))))))
11834
11835 (defun js2-mode-show-element ()
11836 "Show the hidden element at current point."
11837 (interactive)
11838 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11839 (if bounds
11840 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11841 (message "Nothing to un-hide"))))
11842
11843 (defun js2-mode-show-all ()
11844 "Show all of the text in the buffer."
11845 (interactive)
11846 (js2-mode-flag-region (point-min) (point-max) nil))
11847
11848 (defun js2-mode-toggle-hide-functions ()
11849 (interactive)
11850 (if js2-mode-functions-hidden
11851 (js2-mode-show-functions)
11852 (js2-mode-hide-functions)))
11853
11854 (defun js2-mode-hide-functions ()
11855 "Hides all non-nested function bodies in the buffer.
11856 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11857 to open an individual entry."
11858 (interactive)
11859 (if js2-mode-buffer-dirty-p
11860 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11861 (if (null js2-mode-ast)
11862 (message "Oops - parsing failed")
11863 (setq js2-mode-functions-hidden t)
11864 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11865
11866 (defun js2-mode-function-hider (n endp)
11867 (when (not endp)
11868 (let ((tt (js2-node-type n))
11869 body beg end)
11870 (cond
11871 ((and (= tt js2-FUNCTION)
11872 (setq body (js2-function-node-body n)))
11873 (setq beg (js2-node-abs-pos body)
11874 end (+ beg (js2-node-len body)))
11875 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11876 nil) ; don't process children of function
11877 (t
11878 t))))) ; keep processing other AST nodes
11879
11880 (defun js2-mode-show-functions ()
11881 "Un-hide any folded function bodies in the buffer."
11882 (interactive)
11883 (setq js2-mode-functions-hidden nil)
11884 (save-excursion
11885 (goto-char (point-min))
11886 (while (/= (goto-char (next-overlay-change (point)))
11887 (point-max))
11888 (dolist (o (overlays-at (point)))
11889 (when (and (overlay-get o 'invisible)
11890 (not (overlay-get o 'comment)))
11891 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11892
11893 (defun js2-mode-hide-comment (n)
11894 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11895 3 ; /**
11896 2)) ; /*
11897 (beg (+ (js2-node-abs-pos n) head))
11898 (end (- (+ beg (js2-node-len n)) head 2))
11899 (o (js2-mode-flag-region beg end 'hide)))
11900 (overlay-put o 'comment t)))
11901
11902 (defun js2-mode-toggle-hide-comments ()
11903 "Folds all block comments in the buffer.
11904 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11905 to open an individual entry."
11906 (interactive)
11907 (if js2-mode-comments-hidden
11908 (js2-mode-show-comments)
11909 (js2-mode-hide-comments)))
11910
11911 (defun js2-mode-hide-comments ()
11912 (interactive)
11913 (if js2-mode-buffer-dirty-p
11914 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11915 (if (null js2-mode-ast)
11916 (message "Oops - parsing failed")
11917 (setq js2-mode-comments-hidden t)
11918 (dolist (n (js2-ast-root-comments js2-mode-ast))
11919 (when (js2-block-comment-p n)
11920 (js2-mode-hide-comment n)))
11921 (js2-mode-hide-//-comments)))
11922
11923 (defun js2-mode-extend-//-comment (direction)
11924 "Find start or end of a block of similar //-comment lines.
11925 DIRECTION is -1 to look back, 1 to look forward.
11926 INDENT is the indentation level to match.
11927 Returns the end-of-line position of the furthest adjacent
11928 //-comment line with the same indentation as the current line.
11929 If there is no such matching line, returns current end of line."
11930 (let ((pos (point-at-eol))
11931 (indent (current-indentation)))
11932 (save-excursion
11933 (while (and (zerop (forward-line direction))
11934 (looking-at js2-mode-//-comment-re)
11935 (eq indent (length (match-string 1))))
11936 (setq pos (point-at-eol)))
11937 pos)))
11938
11939 (defun js2-mode-hide-//-comments ()
11940 "Fold adjacent 1-line comments, showing only snippet of first one."
11941 (let (beg end)
11942 (save-excursion
11943 (goto-char (point-min))
11944 (while (re-search-forward js2-mode-//-comment-re nil t)
11945 (setq beg (point)
11946 end (js2-mode-extend-//-comment 1))
11947 (unless (eq beg end)
11948 (overlay-put (js2-mode-flag-region beg end 'hide)
11949 'comment t))
11950 (goto-char end)
11951 (forward-char 1)))))
11952
11953 (defun js2-mode-toggle-//-comment ()
11954 "Fold or un-fold any multi-line //-comment at point.
11955 Caller should have determined that this line starts with a //-comment."
11956 (let* ((beg (point-at-eol))
11957 (end beg))
11958 (save-excursion
11959 (goto-char end)
11960 (if (js2-mode-invisible-overlay-bounds)
11961 (js2-mode-show-element)
11962 ;; else hide the comment
11963 (setq beg (js2-mode-extend-//-comment -1)
11964 end (js2-mode-extend-//-comment 1))
11965 (unless (eq beg end)
11966 (overlay-put (js2-mode-flag-region beg end 'hide)
11967 'comment t))))))
11968
11969 (defun js2-mode-show-comments ()
11970 "Un-hide any hidden comments, leaving other hidden elements alone."
11971 (interactive)
11972 (setq js2-mode-comments-hidden nil)
11973 (save-excursion
11974 (goto-char (point-min))
11975 (while (/= (goto-char (next-overlay-change (point)))
11976 (point-max))
11977 (dolist (o (overlays-at (point)))
11978 (when (overlay-get o 'comment)
11979 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11980
11981 (defun js2-mode-display-warnings-and-errors ()
11982 "Turn on display of warnings and errors."
11983 (interactive)
11984 (setq js2-mode-show-parse-errors t
11985 js2-mode-show-strict-warnings t)
11986 (js2-reparse 'force))
11987
11988 (defun js2-mode-hide-warnings-and-errors ()
11989 "Turn off display of warnings and errors."
11990 (interactive)
11991 (setq js2-mode-show-parse-errors nil
11992 js2-mode-show-strict-warnings nil)
11993 (js2-reparse 'force))
11994
11995 (defun js2-mode-toggle-warnings-and-errors ()
11996 "Toggle the display of warnings and errors.
11997 Some users don't like having warnings/errors reported while they type."
11998 (interactive)
11999 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12000 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12001 (if (called-interactively-p 'any)
12002 (message "warnings and errors %s"
12003 (if js2-mode-show-parse-errors
12004 "enabled"
12005 "disabled")))
12006 (js2-reparse 'force))
12007
12008 (defun js2-mode-customize ()
12009 (interactive)
12010 (customize-group 'js2-mode))
12011
12012 (defun js2-mode-forward-sexp (&optional arg)
12013 "Move forward across one statement or balanced expression.
12014 With ARG, do it that many times. Negative arg -N means
12015 move backward across N balanced expressions."
12016 (interactive "p")
12017 (setq arg (or arg 1))
12018 (save-restriction
12019 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12020 (js2-reparse)
12021 (let (forward-sexp-function
12022 node (start (point)) pos lp rp child)
12023 (cond
12024 ;; backward-sexp
12025 ;; could probably make this better for some cases:
12026 ;; - if in statement block (e.g. function body), go to parent
12027 ;; - infix exprs like (foo in bar) - maybe go to beginning
12028 ;; of infix expr if in the right-side expression?
12029 ((and arg (cl-minusp arg))
12030 (dotimes (_ (- arg))
12031 (js2-backward-sws)
12032 (forward-char -1) ; Enter the node we backed up to.
12033 (when (setq node (js2-node-at-point (point) t))
12034 (setq pos (js2-node-abs-pos node))
12035 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12036 (setq lp (car parens)
12037 rp (cdr parens)))
12038 (when (and lp (> start lp))
12039 (if (and rp (<= start rp))
12040 ;; Between parens, check if there's a child node we can jump.
12041 (when (setq child (js2-node-closest-child node (point) lp t))
12042 (setq pos (js2-node-abs-pos child)))
12043 ;; Before both parens.
12044 (setq pos lp)))
12045 (let ((state (parse-partial-sexp start pos)))
12046 (goto-char (if (not (zerop (car state)))
12047 ;; Stumble at the unbalanced paren if < 0, or
12048 ;; jump a bit further if > 0.
12049 (scan-sexps start -1)
12050 pos))))
12051 (unless pos (goto-char (point-min)))))
12052 (t
12053 ;; forward-sexp
12054 (dotimes (_ arg)
12055 (js2-forward-sws)
12056 (when (setq node (js2-node-at-point (point) t))
12057 (setq pos (js2-node-abs-pos node))
12058 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12059 (setq lp (car parens)
12060 rp (cdr parens)))
12061 (or
12062 (when (and rp (<= start rp))
12063 (if (> start lp)
12064 (when (setq child (js2-node-closest-child node (point) rp))
12065 (setq pos (js2-node-abs-end child)))
12066 (setq pos (1+ rp))))
12067 ;; No parens or child nodes, looks for the end of the curren node.
12068 (cl-incf pos (js2-node-len
12069 (if (js2-expr-stmt-node-p (js2-node-parent node))
12070 ;; Stop after the semicolon.
12071 (js2-node-parent node)
12072 node))))
12073 (let ((state (save-excursion (parse-partial-sexp start pos))))
12074 (goto-char (if (not (zerop (car state)))
12075 (scan-sexps start 1)
12076 pos))))
12077 (unless pos (goto-char (point-max)))))))))
12078
12079 (defun js2-mode-forward-sexp-parens (node abs-pos)
12080 "Return a cons cell with positions of main parens in NODE."
12081 (cond
12082 ((or (js2-array-node-p node)
12083 (js2-object-node-p node)
12084 (js2-comp-node-p node)
12085 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12086 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12087 ((js2-paren-expr-node-p node)
12088 (let ((lp (js2-node-lp node))
12089 (rp (js2-node-rp node)))
12090 (cons (when lp (+ abs-pos lp))
12091 (when rp (+ abs-pos rp)))))))
12092
12093 (defun js2-node-closest-child (parent point limit &optional before)
12094 (let* ((parent-pos (js2-node-abs-pos parent))
12095 (rpoint (- point parent-pos))
12096 (rlimit (- limit parent-pos))
12097 (min (min rpoint rlimit))
12098 (max (max rpoint rlimit))
12099 found)
12100 (catch 'done
12101 (js2-visit-ast
12102 parent
12103 (lambda (node _end-p)
12104 (if (eq node parent)
12105 t
12106 (let ((pos (js2-node-pos node)) ;; Both relative values.
12107 (end (+ (js2-node-pos node) (js2-node-len node))))
12108 (when (and (>= pos min) (<= end max)
12109 (if before (< pos rpoint) (> end rpoint)))
12110 (setq found node))
12111 (when (> end rpoint)
12112 (throw 'done nil)))
12113 nil))))
12114 found))
12115
12116 (defun js2-errors ()
12117 "Return a list of errors found."
12118 (and js2-mode-ast
12119 (js2-ast-root-errors js2-mode-ast)))
12120
12121 (defun js2-warnings ()
12122 "Return a list of warnings found."
12123 (and js2-mode-ast
12124 (js2-ast-root-warnings js2-mode-ast)))
12125
12126 (defun js2-have-errors-p ()
12127 "Return non-nil if any parse errors or warnings were found."
12128 (or (js2-errors) (js2-warnings)))
12129
12130 (defun js2-errors-and-warnings ()
12131 "Return a copy of the concatenated errors and warnings lists.
12132 They are appended: first the errors, then the warnings.
12133 Entries are of the form (MSG BEG END)."
12134 (when js2-mode-ast
12135 (append (js2-ast-root-errors js2-mode-ast)
12136 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12137
12138 (defun js2-next-error (&optional arg reset)
12139 "Move to next parse error.
12140 Typically invoked via \\[next-error].
12141 ARG is the number of errors, forward or backward, to move.
12142 RESET means start over from the beginning."
12143 (interactive "p")
12144 (if (not (or (js2-errors) (js2-warnings)))
12145 (message "No errors")
12146 (when reset
12147 (goto-char (point-min)))
12148 (let* ((errs (js2-errors-and-warnings))
12149 (continue t)
12150 (start (point))
12151 (count (or arg 1))
12152 (backward (cl-minusp count))
12153 (sorter (if backward '> '<))
12154 (stopper (if backward '< '>))
12155 (count (abs count))
12156 all-errs err)
12157 ;; Sort by start position.
12158 (setq errs (sort errs (lambda (e1 e2)
12159 (funcall sorter (cl-second e1) (cl-second e2))))
12160 all-errs errs)
12161 ;; Find nth error with pos > start.
12162 (while (and errs continue)
12163 (when (funcall stopper (cl-cadar errs) start)
12164 (setq err (car errs))
12165 (if (zerop (cl-decf count))
12166 (setq continue nil)))
12167 (setq errs (cdr errs)))
12168 ;; Clear for `js2-echo-error'.
12169 (message nil)
12170 (if err
12171 (goto-char (cl-second err))
12172 ;; Wrap around to first error.
12173 (goto-char (cl-second (car all-errs)))
12174 ;; If we were already on it, echo msg again.
12175 (if (= (point) start)
12176 (js2-echo-error (point) (point)))))))
12177
12178 (defun js2-down-mouse-3 ()
12179 "Make right-click move the point to the click location.
12180 This makes right-click context menu operations a bit more intuitive.
12181 The point will not move if the region is active, however, to avoid
12182 destroying the region selection."
12183 (interactive)
12184 (when (and js2-move-point-on-right-click
12185 (not mark-active))
12186 (let ((e last-input-event))
12187 (ignore-errors
12188 (goto-char (cl-cadadr e))))))
12189
12190 (defun js2-mode-create-imenu-index ()
12191 "Return an alist for `imenu--index-alist'."
12192 ;; This is built up in `js2-parse-record-imenu' during parsing.
12193 (when js2-mode-ast
12194 ;; if we have an ast but no recorder, they're requesting a rescan
12195 (unless js2-imenu-recorder
12196 (js2-reparse 'force))
12197 (prog1
12198 (js2-build-imenu-index)
12199 (setq js2-imenu-recorder nil
12200 js2-imenu-function-map nil))))
12201
12202 (defun js2-mode-find-tag ()
12203 "Replacement for `find-tag-default'.
12204 `find-tag-default' returns a ridiculous answer inside comments."
12205 (let (beg end)
12206 (js2-with-underscore-as-word-syntax
12207 (save-excursion
12208 (if (and (not (looking-at "[[:alnum:]_$]"))
12209 (looking-back "[[:alnum:]_$]"))
12210 (setq beg (progn (forward-word -1) (point))
12211 end (progn (forward-word 1) (point)))
12212 (setq beg (progn (forward-word 1) (point))
12213 end (progn (forward-word -1) (point))))
12214 (replace-regexp-in-string
12215 "[\"']" ""
12216 (buffer-substring-no-properties beg end))))))
12217
12218 (defun js2-mode-forward-sibling ()
12219 "Move to the end of the sibling following point in parent.
12220 Returns non-nil if successful, or nil if there was no following sibling."
12221 (let* ((node (js2-node-at-point))
12222 (parent (js2-mode-find-enclosing-fn node))
12223 sib)
12224 (when (setq sib (js2-node-find-child-after (point) parent))
12225 (goto-char (+ (js2-node-abs-pos sib)
12226 (js2-node-len sib))))))
12227
12228 (defun js2-mode-backward-sibling ()
12229 "Move to the beginning of the sibling node preceding point in parent.
12230 Parent is defined as the enclosing script or function."
12231 (let* ((node (js2-node-at-point))
12232 (parent (js2-mode-find-enclosing-fn node))
12233 sib)
12234 (when (setq sib (js2-node-find-child-before (point) parent))
12235 (goto-char (js2-node-abs-pos sib)))))
12236
12237 (defun js2-beginning-of-defun (&optional arg)
12238 "Go to line on which current function starts, and return t on success.
12239 If we're not in a function or already at the beginning of one, go
12240 to beginning of previous script-level element.
12241 With ARG N, do that N times. If N is negative, move forward."
12242 (setq arg (or arg 1))
12243 (if (cl-plusp arg)
12244 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12245 (when (cond
12246 ((js2-function-node-p parent)
12247 (goto-char (js2-node-abs-pos parent)))
12248 (t
12249 (js2-mode-backward-sibling)))
12250 (if (> arg 1)
12251 (js2-beginning-of-defun (1- arg))
12252 t)))
12253 (when (js2-end-of-defun)
12254 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12255
12256 (defun js2-end-of-defun ()
12257 "Go to the char after the last position of the current function
12258 or script-level element."
12259 (let* ((node (js2-node-at-point))
12260 (parent (or (and (js2-function-node-p node) node)
12261 (js2-node-parent-script-or-fn node)))
12262 script)
12263 (unless (js2-function-node-p parent)
12264 ;; Use current script-level node, or, if none, the next one.
12265 (setq script (or parent node)
12266 parent (js2-node-find-child-before (point) script))
12267 (when (or (null parent)
12268 (>= (point) (+ (js2-node-abs-pos parent)
12269 (js2-node-len parent))))
12270 (setq parent (js2-node-find-child-after (point) script))))
12271 (when parent
12272 (goto-char (+ (js2-node-abs-pos parent)
12273 (js2-node-len parent))))))
12274
12275 (defun js2-mark-defun (&optional allow-extend)
12276 "Put mark at end of this function, point at beginning.
12277 The function marked is the one that contains point.
12278
12279 Interactively, if this command is repeated,
12280 or (in Transient Mark mode) if the mark is active,
12281 it marks the next defun after the ones already marked."
12282 (interactive "p")
12283 (let (extended)
12284 (when (and allow-extend
12285 (or (and (eq last-command this-command) (mark t))
12286 (and transient-mark-mode mark-active)))
12287 (let ((sib (save-excursion
12288 (goto-char (mark))
12289 (if (js2-mode-forward-sibling)
12290 (point)))))
12291 (if sib
12292 (progn
12293 (set-mark sib)
12294 (setq extended t))
12295 ;; no more siblings - try extending to enclosing node
12296 (goto-char (mark t)))))
12297 (when (not extended)
12298 (let ((node (js2-node-at-point (point) t)) ; skip comments
12299 ast fn stmt parent beg end)
12300 (when (js2-ast-root-p node)
12301 (setq ast node
12302 node (or (js2-node-find-child-after (point) node)
12303 (js2-node-find-child-before (point) node))))
12304 ;; only mark whole buffer if we can't find any children
12305 (if (null node)
12306 (setq node ast))
12307 (if (js2-function-node-p node)
12308 (setq parent node)
12309 (setq fn (js2-mode-find-enclosing-fn node)
12310 stmt (if (or (null fn)
12311 (js2-ast-root-p fn))
12312 (js2-mode-find-first-stmt node))
12313 parent (or stmt fn)))
12314 (setq beg (js2-node-abs-pos parent)
12315 end (+ beg (js2-node-len parent)))
12316 (push-mark beg)
12317 (goto-char end)
12318 (exchange-point-and-mark)))))
12319
12320 (defun js2-narrow-to-defun ()
12321 "Narrow to the function enclosing point."
12322 (interactive)
12323 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12324 (fn (if (js2-script-node-p node)
12325 node
12326 (js2-mode-find-enclosing-fn node)))
12327 (beg (js2-node-abs-pos fn)))
12328 (unless (js2-ast-root-p fn)
12329 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12330
12331 (provide 'js2-mode)
12332
12333 ;;; js2-mode.el ends here