]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Fix off-by-one error for comment node length
[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-SUPER 165)
654 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
655 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
656 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
657
658 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
659
660 (defconst js2-debug-print-trees nil)
661
662 ;; Rhino accepts any string or stream as input. Emacs character
663 ;; processing works best in buffers, so we'll assume the input is a
664 ;; buffer. JavaScript strings can be copied into temp buffers before
665 ;; scanning them.
666
667 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
668 ;; They're the Emacs equivalent of instance variables, more or less.
669
670 (js2-deflocal js2-ts-dirty-line nil
671 "Token stream buffer-local variable.
672 Indicates stuff other than whitespace since start of line.")
673
674 (js2-deflocal js2-ts-hit-eof nil
675 "Token stream buffer-local variable.")
676
677 ;; FIXME: Unused.
678 (js2-deflocal js2-ts-line-start 0
679 "Token stream buffer-local variable.")
680
681 (js2-deflocal js2-ts-lineno 1
682 "Token stream buffer-local variable.")
683
684 ;; FIXME: Unused.
685 (js2-deflocal js2-ts-line-end-char -1
686 "Token stream buffer-local variable.")
687
688 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
689 "Token stream buffer-local variable.
690 Current scan position.")
691
692 ;; FIXME: Unused.
693 (js2-deflocal js2-ts-is-xml-attribute nil
694 "Token stream buffer-local variable.")
695
696 (js2-deflocal js2-ts-xml-is-tag-content nil
697 "Token stream buffer-local variable.")
698
699 (js2-deflocal js2-ts-xml-open-tags-count 0
700 "Token stream buffer-local variable.")
701
702 (js2-deflocal js2-ts-string-buffer nil
703 "Token stream buffer-local variable.
704 List of chars built up while scanning various tokens.")
705
706 (cl-defstruct (js2-token
707 (:constructor nil)
708 (:constructor make-js2-token (beg)))
709 "Value returned from the token stream."
710 (type js2-EOF)
711 (beg 1)
712 (end -1)
713 (string "")
714 number
715 regexp-flags
716 comment-type
717 follows-eol-p)
718
719 ;; Have to call `js2-init-scanner' to initialize the values.
720 (js2-deflocal js2-ti-tokens nil)
721 (js2-deflocal js2-ti-tokens-cursor nil)
722 (js2-deflocal js2-ti-lookahead nil)
723
724 (cl-defstruct (js2-ts-state
725 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
726 (cursor js2-ts-cursor)
727 (tokens (copy-sequence js2-ti-tokens))
728 (tokens-cursor js2-ti-tokens-cursor)
729 (lookahead js2-ti-lookahead))))
730 lineno
731 cursor
732 tokens
733 tokens-cursor
734 lookahead)
735
736 ;;; Parser variables
737
738 (js2-deflocal js2-parsed-errors nil
739 "List of errors produced during scanning/parsing.")
740
741 (js2-deflocal js2-parsed-warnings nil
742 "List of warnings produced during scanning/parsing.")
743
744 (js2-deflocal js2-recover-from-parse-errors t
745 "Non-nil to continue parsing after a syntax error.
746
747 In recovery mode, the AST will be built in full, and any error
748 nodes will be flagged with appropriate error information. If
749 this flag is nil, a syntax error will result in an error being
750 signaled.
751
752 The variable is automatically buffer-local, because different
753 modes that use the parser will need different settings.")
754
755 (js2-deflocal js2-parse-hook nil
756 "List of callbacks for receiving parsing progress.")
757
758 (defvar js2-parse-finished-hook nil
759 "List of callbacks to notify when parsing finishes.
760 Not called if parsing was interrupted.")
761
762 (js2-deflocal js2-is-eval-code nil
763 "True if we're evaluating code in a string.
764 If non-nil, the tokenizer will record the token text, and the AST nodes
765 will record their source text. Off by default for IDE modes, since the
766 text is available in the buffer.")
767
768 (defvar js2-parse-ide-mode t
769 "Non-nil if the parser is being used for `js2-mode'.
770 If non-nil, the parser will set text properties for fontification
771 and the syntax table. The value should be nil when using the
772 parser as a frontend to an interpreter or byte compiler.")
773
774 ;;; Parser instance variables (buffer-local vars for js2-parse)
775
776 (defconst js2-ti-after-eol (lsh 1 16)
777 "Flag: first token of the source line.")
778
779 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
780
781 (js2-deflocal js2-compiler-generate-debug-info t)
782 (js2-deflocal js2-compiler-use-dynamic-scope nil)
783 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
784 (js2-deflocal js2-compiler-xml-available t)
785 (js2-deflocal js2-compiler-optimization-level 0)
786 (js2-deflocal js2-compiler-generating-source t)
787 (js2-deflocal js2-compiler-strict-mode nil)
788 (js2-deflocal js2-compiler-report-warning-as-error nil)
789 (js2-deflocal js2-compiler-generate-observer-count nil)
790 (js2-deflocal js2-compiler-activation-names nil)
791
792 ;; SKIP: sourceURI
793
794 ;; There's a compileFunction method in Context.java - may need it.
795 (js2-deflocal js2-called-by-compile-function nil
796 "True if `js2-parse' was called by `js2-compile-function'.
797 Will only be used when we finish implementing the interpreter.")
798
799 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
800
801 ;; SKIP: node factory - we're going to just call functions directly,
802 ;; and eventually go to a unified AST format.
803
804 (js2-deflocal js2-nesting-of-function 0)
805
806 (js2-deflocal js2-recorded-identifiers nil
807 "Tracks identifiers found during parsing.")
808
809 (js2-deflocal js2-is-in-destructuring nil
810 "True while parsing destructuring expression.")
811
812 (defcustom js2-global-externs nil
813 "A list of any extern names you'd like to consider always declared.
814 This list is global and is used by all `js2-mode' files.
815 You can create buffer-local externs list using `js2-additional-externs'.
816
817 There is also a buffer-local variable `js2-default-externs',
818 which is initialized by default to include the Ecma-262 externs
819 and the standard browser externs. The three lists are all
820 checked during highlighting."
821 :type 'list
822 :group 'js2-mode)
823
824 (js2-deflocal js2-default-externs nil
825 "Default external declarations.
826
827 These are currently only used for highlighting undeclared variables,
828 which only worries about top-level (unqualified) references.
829 As js2-mode's processing improves, we will flesh out this list.
830
831 The initial value is set to `js2-ecma-262-externs', unless some
832 of the `js2-include-?-externs' variables are set to t, in which
833 case the browser, Rhino and/or Node.js externs are also included.
834
835 See `js2-additional-externs' for more information.")
836
837 (defcustom js2-include-browser-externs t
838 "Non-nil to include browser externs in the master externs list.
839 If you work on JavaScript files that are not intended for browsers,
840 such as Mozilla Rhino server-side JavaScript, set this to nil.
841 See `js2-additional-externs' for more information about externs."
842 :type 'boolean
843 :group 'js2-mode)
844
845 (defcustom js2-include-rhino-externs nil
846 "Non-nil to include Mozilla Rhino externs in the master externs list.
847 See `js2-additional-externs' for more information about externs."
848 :type 'boolean
849 :group 'js2-mode)
850
851 (defcustom js2-include-node-externs nil
852 "Non-nil to include Node.js externs in the master externs list.
853 See `js2-additional-externs' for more information about externs."
854 :type 'boolean
855 :group 'js2-mode)
856
857 (js2-deflocal js2-additional-externs nil
858 "A buffer-local list of additional external declarations.
859 It is used to decide whether variables are considered undeclared
860 for purposes of highlighting.
861
862 Each entry is a Lisp string. The string should be the fully qualified
863 name of an external entity. All externs should be added to this list,
864 so that as js2-mode's processing improves it can take advantage of them.
865
866 You may want to declare your externs in three ways.
867 First, you can add externs that are valid for all your JavaScript files.
868 You should probably do this by adding them to `js2-global-externs', which
869 is a global list used for all js2-mode files.
870
871 Next, you can add a function to `js2-init-hook' that adds additional
872 externs appropriate for the specific file, perhaps based on its path.
873 These should go in `js2-additional-externs', which is buffer-local.
874
875 Third, you can use JSLint's global declaration, as long as
876 `js2-include-jslint-globals' is non-nil, which see.
877
878 Finally, you can add a function to `js2-post-parse-callbacks',
879 which is called after parsing completes, and `js2-mode-ast' is bound to
880 the root of the parse tree. At this stage you can set up an AST
881 node visitor using `js2-visit-ast' and examine the parse tree
882 for specific import patterns that may imply the existence of
883 other externs, possibly tied to your build system. These should also
884 be added to `js2-additional-externs'.
885
886 Your post-parse callback may of course also use the simpler and
887 faster (but perhaps less robust) approach of simply scanning the
888 buffer text for your imports, using regular expressions.")
889
890 ;; SKIP: decompiler
891 ;; SKIP: encoded-source
892
893 ;;; The following variables are per-function and should be saved/restored
894 ;;; during function parsing...
895
896 (js2-deflocal js2-current-script-or-fn nil)
897 (js2-deflocal js2-current-scope nil)
898 (js2-deflocal js2-nesting-of-with 0)
899 (js2-deflocal js2-label-set nil
900 "An alist mapping label names to nodes.")
901
902 (js2-deflocal js2-loop-set nil)
903 (js2-deflocal js2-loop-and-switch-set nil)
904 (js2-deflocal js2-has-return-value nil)
905 (js2-deflocal js2-end-flags 0)
906
907 ;;; ...end of per function variables
908
909 ;; These flags enumerate the possible ways a statement/function can
910 ;; terminate. These flags are used by endCheck() and by the Parser to
911 ;; detect inconsistent return usage.
912 ;;
913 ;; END_UNREACHED is reserved for code paths that are assumed to always be
914 ;; able to execute (example: throw, continue)
915 ;;
916 ;; END_DROPS_OFF indicates if the statement can transfer control to the
917 ;; next one. Statement such as return dont. A compound statement may have
918 ;; some branch that drops off control to the next statement.
919 ;;
920 ;; END_RETURNS indicates that the statement can return (without arguments)
921 ;; END_RETURNS_VALUE indicates that the statement can return a value.
922 ;;
923 ;; A compound statement such as
924 ;; if (condition) {
925 ;; return value;
926 ;; }
927 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
928
929 (defconst js2-end-unreached #x0)
930 (defconst js2-end-drops-off #x1)
931 (defconst js2-end-returns #x2)
932 (defconst js2-end-returns-value #x4)
933
934 ;; Rhino awkwardly passes a statementLabel parameter to the
935 ;; statementHelper() function, the main statement parser, which
936 ;; is then used by quite a few of the sub-parsers. We just make
937 ;; it a buffer-local variable and make sure it's cleaned up properly.
938 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
939
940 ;; Similarly, Rhino passes an inForInit boolean through about half
941 ;; the expression parsers. We use a dynamically-scoped variable,
942 ;; which makes it easier to funcall the parsers individually without
943 ;; worrying about whether they take the parameter or not.
944 (js2-deflocal js2-in-for-init nil)
945 (js2-deflocal js2-temp-name-counter 0)
946 (js2-deflocal js2-parse-stmt-count 0)
947
948 (defsubst js2-get-next-temp-name ()
949 (format "$%d" (cl-incf js2-temp-name-counter)))
950
951 (defvar js2-parse-interruptable-p t
952 "Set this to nil to force parse to continue until finished.
953 This will mostly be useful for interpreters.")
954
955 (defvar js2-statements-per-pause 50
956 "Pause after this many statements to check for user input.
957 If user input is pending, stop the parse and discard the tree.
958 This makes for a smoother user experience for large files.
959 You may have to wait a second or two before the highlighting
960 and error-reporting appear, but you can always type ahead if
961 you wish. This appears to be more or less how Eclipse, IntelliJ
962 and other editors work.")
963
964 (js2-deflocal js2-record-comments t
965 "Instructs the scanner to record comments in `js2-scanned-comments'.")
966
967 (js2-deflocal js2-scanned-comments nil
968 "List of all comments from the current parse.")
969
970 (defcustom js2-mode-indent-inhibit-undo nil
971 "Non-nil to disable collection of Undo information when indenting lines.
972 Some users have requested this behavior. It's nil by default because
973 other Emacs modes don't work this way."
974 :type 'boolean
975 :group 'js2-mode)
976
977 (defcustom js2-mode-indent-ignore-first-tab nil
978 "If non-nil, ignore first TAB keypress if we look indented properly.
979 It's fairly common for users to navigate to an already-indented line
980 and press TAB for reassurance that it's been indented. For this class
981 of users, we want the first TAB press on a line to be ignored if the
982 line is already indented to one of the precomputed alternatives.
983
984 This behavior is only partly implemented. If you TAB-indent a line,
985 navigate to another line, and then navigate back, it fails to clear
986 the last-indented variable, so it thinks you've already hit TAB once,
987 and performs the indent. A full solution would involve getting on the
988 point-motion hooks for the entire buffer. If we come across another
989 use cases that requires watching point motion, I'll consider doing it.
990
991 If you set this variable to nil, then the TAB key will always change
992 the indentation of the current line, if more than one alternative
993 indentation spot exists."
994 :type 'boolean
995 :group 'js2-mode)
996
997 (defvar js2-indent-hook nil
998 "A hook for user-defined indentation rules.
999
1000 Functions on this hook should expect two arguments: (LIST INDEX)
1001 The LIST argument is the list of computed indentation points for
1002 the current line. INDEX is the list index of the indentation point
1003 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1004 indent function is not going to change the current line indentation.
1005
1006 If a hook function on this list returns a non-nil value, then
1007 `js2-bounce-indent' assumes the hook function has performed its own
1008 indentation, and will do nothing. If all hook functions on the list
1009 return nil, then `js2-bounce-indent' will use its computed indentation
1010 and reindent the line.
1011
1012 When hook functions on this hook list are called, the variable
1013 `js2-mode-ast' may or may not be set, depending on whether the
1014 parse tree is available. If the variable is nil, you can pass a
1015 callback to `js2-mode-wait-for-parse', and your callback will be
1016 called after the new parse tree is built. This can take some time
1017 in large files.")
1018
1019 (defface js2-warning
1020 `((((class color) (background light))
1021 (:underline "orange"))
1022 (((class color) (background dark))
1023 (:underline "orange"))
1024 (t (:underline t)))
1025 "Face for JavaScript warnings."
1026 :group 'js2-mode)
1027
1028 (defface js2-error
1029 `((((class color) (background light))
1030 (:foreground "red"))
1031 (((class color) (background dark))
1032 (:foreground "red"))
1033 (t (:foreground "red")))
1034 "Face for JavaScript errors."
1035 :group 'js2-mode)
1036
1037 (defface js2-jsdoc-tag
1038 '((t :foreground "SlateGray"))
1039 "Face used to highlight @whatever tags in jsdoc comments."
1040 :group 'js2-mode)
1041
1042 (defface js2-jsdoc-type
1043 '((t :foreground "SteelBlue"))
1044 "Face used to highlight {FooBar} types in jsdoc comments."
1045 :group 'js2-mode)
1046
1047 (defface js2-jsdoc-value
1048 '((t :foreground "PeachPuff3"))
1049 "Face used to highlight tag values in jsdoc comments."
1050 :group 'js2-mode)
1051
1052 (defface js2-function-param
1053 '((t :foreground "SeaGreen"))
1054 "Face used to highlight function parameters in javascript."
1055 :group 'js2-mode)
1056
1057 (defface js2-function-call
1058 '((t :inherit default))
1059 "Face used to highlight function name in calls."
1060 :group 'js2-mode)
1061
1062 (defface js2-instance-member
1063 '((t :foreground "DarkOrchid"))
1064 "Face used to highlight instance variables in javascript.
1065 Not currently used."
1066 :group 'js2-mode)
1067
1068 (defface js2-private-member
1069 '((t :foreground "PeachPuff3"))
1070 "Face used to highlight calls to private methods in javascript.
1071 Not currently used."
1072 :group 'js2-mode)
1073
1074 (defface js2-private-function-call
1075 '((t :foreground "goldenrod"))
1076 "Face used to highlight calls to private functions in javascript.
1077 Not currently used."
1078 :group 'js2-mode)
1079
1080 (defface js2-jsdoc-html-tag-name
1081 '((((class color) (min-colors 88) (background light))
1082 (:foreground "rosybrown"))
1083 (((class color) (min-colors 8) (background dark))
1084 (:foreground "yellow"))
1085 (((class color) (min-colors 8) (background light))
1086 (:foreground "magenta")))
1087 "Face used to highlight jsdoc html tag names"
1088 :group 'js2-mode)
1089
1090 (defface js2-jsdoc-html-tag-delimiter
1091 '((((class color) (min-colors 88) (background light))
1092 (:foreground "dark khaki"))
1093 (((class color) (min-colors 8) (background dark))
1094 (:foreground "green"))
1095 (((class color) (min-colors 8) (background light))
1096 (:foreground "green")))
1097 "Face used to highlight brackets in jsdoc html tags."
1098 :group 'js2-mode)
1099
1100 (defface js2-external-variable
1101 '((t :foreground "orange"))
1102 "Face used to highlight undeclared variable identifiers.")
1103
1104 (defcustom js2-init-hook nil
1105 "List of functions to be called after `js2-mode' or
1106 `js2-minor-mode' has initialized all variables, before parsing
1107 the buffer for the first time."
1108 :type 'hook
1109 :group 'js2-mode
1110 :version "20130608")
1111
1112 (defcustom js2-post-parse-callbacks nil
1113 "List of callback functions invoked after parsing finishes.
1114 Currently, the main use for this function is to add synthetic
1115 declarations to `js2-recorded-identifiers', which see."
1116 :type 'hook
1117 :group 'js2-mode)
1118
1119 (defcustom js2-build-imenu-callbacks nil
1120 "List of functions called during Imenu index generation.
1121 It's a good place to add additional entries to it, using
1122 `js2-record-imenu-entry'."
1123 :type 'hook
1124 :group 'js2-mode)
1125
1126 (defcustom js2-highlight-external-variables t
1127 "Non-nil to highlight undeclared variable identifiers.
1128 An undeclared variable is any variable not declared with var or let
1129 in the current scope or any lexically enclosing scope. If you use
1130 such a variable, then you are either expecting it to originate from
1131 another file, or you've got a potential bug."
1132 :type 'boolean
1133 :group 'js2-mode)
1134
1135 (defcustom js2-include-jslint-globals t
1136 "Non-nil to include the identifiers from JSLint global
1137 declaration (see http://www.jslint.com/lint.html#global) in the
1138 buffer-local externs list. See `js2-additional-externs' for more
1139 information."
1140 :type 'boolean
1141 :group 'js2-mode)
1142
1143 (defvar js2-mode-map
1144 (let ((map (make-sparse-keymap)))
1145 (define-key map [mouse-1] #'js2-mode-show-node)
1146 (define-key map (kbd "M-j") #'js2-line-break)
1147 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1148 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1149 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1150 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1151 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1152 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1153 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1154 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1155 (when js2-bounce-indent-p
1156 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1157
1158 (define-key map [menu-bar javascript]
1159 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1160
1161 (define-key map [menu-bar javascript customize-js2-mode]
1162 '(menu-item "Customize js2-mode" js2-mode-customize
1163 :help "Customize the behavior of this mode"))
1164
1165 (define-key map [menu-bar javascript js2-force-refresh]
1166 '(menu-item "Force buffer refresh" js2-mode-reset
1167 :help "Re-parse the buffer from scratch"))
1168
1169 (define-key map [menu-bar javascript separator-2]
1170 '("--"))
1171
1172 (define-key map [menu-bar javascript next-error]
1173 '(menu-item "Next warning or error" next-error
1174 :enabled (and js2-mode-ast
1175 (or (js2-ast-root-errors js2-mode-ast)
1176 (js2-ast-root-warnings js2-mode-ast)))
1177 :help "Move to next warning or error"))
1178
1179 (define-key map [menu-bar javascript display-errors]
1180 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1181 :visible (not js2-mode-show-parse-errors)
1182 :help "Turn on display of warnings and errors"))
1183
1184 (define-key map [menu-bar javascript hide-errors]
1185 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1186 :visible js2-mode-show-parse-errors
1187 :help "Turn off display of warnings and errors"))
1188
1189 (define-key map [menu-bar javascript separator-1]
1190 '("--"))
1191
1192 (define-key map [menu-bar javascript js2-toggle-function]
1193 '(menu-item "Show/collapse element" js2-mode-toggle-element
1194 :help "Hide or show function body or comment"))
1195
1196 (define-key map [menu-bar javascript show-comments]
1197 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1198 :visible js2-mode-comments-hidden
1199 :help "Expand all hidden block comments"))
1200
1201 (define-key map [menu-bar javascript hide-comments]
1202 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1203 :visible (not js2-mode-comments-hidden)
1204 :help "Show block comments as /*...*/"))
1205
1206 (define-key map [menu-bar javascript show-all-functions]
1207 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1208 :visible js2-mode-functions-hidden
1209 :help "Expand all hidden function bodies"))
1210
1211 (define-key map [menu-bar javascript hide-all-functions]
1212 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1213 :visible (not js2-mode-functions-hidden)
1214 :help "Show {...} for all top-level function bodies"))
1215
1216 map)
1217 "Keymap used in `js2-mode' buffers.")
1218
1219 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1220
1221 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1222 "Matches a //-comment line. Must be first non-whitespace on line.
1223 First match-group is the leading whitespace.")
1224
1225 (defvar js2-mode-hook nil)
1226
1227 (js2-deflocal js2-mode-ast nil "Private variable.")
1228 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1229 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1230 (js2-deflocal js2-mode-parsing nil "Private variable.")
1231 (js2-deflocal js2-mode-node-overlay nil)
1232
1233 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1234 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1235
1236 (js2-deflocal js2-mode-fontifications nil "Private variable")
1237 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1238 (js2-deflocal js2-imenu-recorder nil "Private variable")
1239 (js2-deflocal js2-imenu-function-map nil "Private variable")
1240
1241 (defvar js2-paragraph-start
1242 "\\(@[[:alpha:]]+\\>\\|$\\)")
1243
1244 ;; Note that we also set a 'c-in-sws text property in html comments,
1245 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1246 (defvar js2-syntactic-ws-start
1247 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1248
1249 (defvar js2-syntactic-ws-end
1250 "\\s \\|[\n\r/]\\|\\s!")
1251
1252 (defvar js2-syntactic-eol
1253 (concat "\\s *\\(/\\*[^*\n\r]*"
1254 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1255 "\\*+/\\s *\\)*"
1256 "\\(//\\|/\\*[^*\n\r]*"
1257 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1258 "\\|\\\\$\\|$\\)")
1259 "Copied from `java-mode'. Needed for some cc-engine functions.")
1260
1261 (defvar js2-comment-prefix-regexp
1262 "//+\\|\\**")
1263
1264 (defvar js2-comment-start-skip
1265 "\\(//+\\|/\\*+\\)\\s *")
1266
1267 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1268 "Non-nil to emit status messages during parsing.")
1269
1270 (defvar js2-mode-functions-hidden nil "Private variable.")
1271 (defvar js2-mode-comments-hidden nil "Private variable.")
1272
1273 (defvar js2-mode-syntax-table
1274 (let ((table (make-syntax-table)))
1275 (c-populate-syntax-table table)
1276 table)
1277 "Syntax table used in `js2-mode' buffers.")
1278
1279 (defvar js2-mode-abbrev-table nil
1280 "Abbrev table in use in `js2-mode' buffers.")
1281 (define-abbrev-table 'js2-mode-abbrev-table ())
1282
1283 (defvar js2-mode-pending-parse-callbacks nil
1284 "List of functions waiting to be notified that parse is finished.")
1285
1286 (defvar js2-mode-last-indented-line -1)
1287
1288 ;;; Localizable error and warning messages
1289
1290 ;; Messages are copied from Rhino's Messages.properties.
1291 ;; Many of the Java-specific messages have been elided.
1292 ;; Add any js2-specific ones at the end, so we can keep
1293 ;; this file synced with changes to Rhino's.
1294
1295 (defvar js2-message-table
1296 (make-hash-table :test 'equal :size 250)
1297 "Contains localized messages for `js2-mode'.")
1298
1299 ;; TODO(stevey): construct this table at compile-time.
1300 (defmacro js2-msg (key &rest strings)
1301 `(puthash ,key (concat ,@strings)
1302 js2-message-table))
1303
1304 (defun js2-get-msg (msg-key)
1305 "Look up a localized message.
1306 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1307 the correct number of ARGS must be provided."
1308 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1309 (args (if (listp msg-key) (cdr msg-key)))
1310 (msg (gethash key js2-message-table)))
1311 (if msg
1312 (apply #'format msg args)
1313 key))) ; default to showing the key
1314
1315 (js2-msg "msg.dup.parms"
1316 "Duplicate parameter name '%s'.")
1317
1318 (js2-msg "msg.too.big.jump"
1319 "Program too complex: jump offset too big.")
1320
1321 (js2-msg "msg.too.big.index"
1322 "Program too complex: internal index exceeds 64K limit.")
1323
1324 (js2-msg "msg.while.compiling.fn"
1325 "Encountered code generation error while compiling function '%s': %s")
1326
1327 (js2-msg "msg.while.compiling.script"
1328 "Encountered code generation error while compiling script: %s")
1329
1330 ;; Context
1331 (js2-msg "msg.ctor.not.found"
1332 "Constructor for '%s' not found.")
1333
1334 (js2-msg "msg.not.ctor"
1335 "'%s' is not a constructor.")
1336
1337 ;; FunctionObject
1338 (js2-msg "msg.varargs.ctor"
1339 "Method or constructor '%s' must be static "
1340 "with the signature (Context cx, Object[] args, "
1341 "Function ctorObj, boolean inNewExpr) "
1342 "to define a variable arguments constructor.")
1343
1344 (js2-msg "msg.varargs.fun"
1345 "Method '%s' must be static with the signature "
1346 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1347 "to define a variable arguments function.")
1348
1349 (js2-msg "msg.incompat.call"
1350 "Method '%s' called on incompatible object.")
1351
1352 (js2-msg "msg.bad.parms"
1353 "Unsupported parameter type '%s' in method '%s'.")
1354
1355 (js2-msg "msg.bad.method.return"
1356 "Unsupported return type '%s' in method '%s'.")
1357
1358 (js2-msg "msg.bad.ctor.return"
1359 "Construction of objects of type '%s' is not supported.")
1360
1361 (js2-msg "msg.no.overload"
1362 "Method '%s' occurs multiple times in class '%s'.")
1363
1364 (js2-msg "msg.method.not.found"
1365 "Method '%s' not found in '%s'.")
1366
1367 ;; IRFactory
1368
1369 (js2-msg "msg.bad.for.in.lhs"
1370 "Invalid left-hand side of for..in loop.")
1371
1372 (js2-msg "msg.mult.index"
1373 "Only one variable allowed in for..in loop.")
1374
1375 (js2-msg "msg.bad.for.in.destruct"
1376 "Left hand side of for..in loop must be an array of "
1377 "length 2 to accept key/value pair.")
1378
1379 (js2-msg "msg.cant.convert"
1380 "Can't convert to type '%s'.")
1381
1382 (js2-msg "msg.bad.assign.left"
1383 "Invalid assignment left-hand side.")
1384
1385 (js2-msg "msg.bad.decr"
1386 "Invalid decrement operand.")
1387
1388 (js2-msg "msg.bad.incr"
1389 "Invalid increment operand.")
1390
1391 (js2-msg "msg.bad.yield"
1392 "yield must be in a function.")
1393
1394 (js2-msg "msg.yield.parenthesized"
1395 "yield expression must be parenthesized.")
1396
1397 ;; NativeGlobal
1398 (js2-msg "msg.cant.call.indirect"
1399 "Function '%s' must be called directly, and not by way of a "
1400 "function of another name.")
1401
1402 (js2-msg "msg.eval.nonstring"
1403 "Calling eval() with anything other than a primitive "
1404 "string value will simply return the value. "
1405 "Is this what you intended?")
1406
1407 (js2-msg "msg.eval.nonstring.strict"
1408 "Calling eval() with anything other than a primitive "
1409 "string value is not allowed in strict mode.")
1410
1411 (js2-msg "msg.bad.destruct.op"
1412 "Invalid destructuring assignment operator")
1413
1414 ;; NativeCall
1415 (js2-msg "msg.only.from.new"
1416 "'%s' may only be invoked from a `new' expression.")
1417
1418 (js2-msg "msg.deprec.ctor"
1419 "The '%s' constructor is deprecated.")
1420
1421 ;; NativeFunction
1422 (js2-msg "msg.no.function.ref.found"
1423 "no source found to decompile function reference %s")
1424
1425 (js2-msg "msg.arg.isnt.array"
1426 "second argument to Function.prototype.apply must be an array")
1427
1428 ;; NativeGlobal
1429 (js2-msg "msg.bad.esc.mask"
1430 "invalid string escape mask")
1431
1432 ;; NativeRegExp
1433 (js2-msg "msg.bad.quant"
1434 "Invalid quantifier %s")
1435
1436 (js2-msg "msg.overlarge.backref"
1437 "Overly large back reference %s")
1438
1439 (js2-msg "msg.overlarge.min"
1440 "Overly large minimum %s")
1441
1442 (js2-msg "msg.overlarge.max"
1443 "Overly large maximum %s")
1444
1445 (js2-msg "msg.zero.quant"
1446 "Zero quantifier %s")
1447
1448 (js2-msg "msg.max.lt.min"
1449 "Maximum %s less than minimum")
1450
1451 (js2-msg "msg.unterm.quant"
1452 "Unterminated quantifier %s")
1453
1454 (js2-msg "msg.unterm.paren"
1455 "Unterminated parenthetical %s")
1456
1457 (js2-msg "msg.unterm.class"
1458 "Unterminated character class %s")
1459
1460 (js2-msg "msg.bad.range"
1461 "Invalid range in character class.")
1462
1463 (js2-msg "msg.trail.backslash"
1464 "Trailing \\ in regular expression.")
1465
1466 (js2-msg "msg.re.unmatched.right.paren"
1467 "unmatched ) in regular expression.")
1468
1469 (js2-msg "msg.no.regexp"
1470 "Regular expressions are not available.")
1471
1472 (js2-msg "msg.bad.backref"
1473 "back-reference exceeds number of capturing parentheses.")
1474
1475 (js2-msg "msg.bad.regexp.compile"
1476 "Only one argument may be specified if the first "
1477 "argument to RegExp.prototype.compile is a RegExp object.")
1478
1479 ;; Parser
1480 (js2-msg "msg.got.syntax.errors"
1481 "Compilation produced %s syntax errors.")
1482
1483 (js2-msg "msg.var.redecl"
1484 "TypeError: redeclaration of var %s.")
1485
1486 (js2-msg "msg.const.redecl"
1487 "TypeError: redeclaration of const %s.")
1488
1489 (js2-msg "msg.let.redecl"
1490 "TypeError: redeclaration of variable %s.")
1491
1492 (js2-msg "msg.parm.redecl"
1493 "TypeError: redeclaration of formal parameter %s.")
1494
1495 (js2-msg "msg.fn.redecl"
1496 "TypeError: redeclaration of function %s.")
1497
1498 (js2-msg "msg.let.decl.not.in.block"
1499 "SyntaxError: let declaration not directly within block")
1500
1501 (js2-msg "msg.mod.import.decl.at.top.level"
1502 "SyntaxError: import declarations may only appear at the top level")
1503
1504 (js2-msg "msg.mod.as.after.reserved.word"
1505 "SyntaxError: missing keyword 'as' after reserved word %s")
1506
1507 (js2-msg "msg.mod.rc.after.import.spec.list"
1508 "SyntaxError: missing '}' after module specifier list")
1509
1510 (js2-msg "msg.mod.from.after.import.spec.set"
1511 "SyntaxError: missing keyword 'from' after import specifier set")
1512
1513 (js2-msg "msg.mod.declaration.after.import"
1514 "SyntaxError: missing declaration after 'import' keyword")
1515
1516 (js2-msg "msg.mod.spec.after.from"
1517 "SyntaxError: missing module specifier after 'from' keyword")
1518
1519 (js2-msg "msg.mod.export.decl.at.top.level"
1520 "SyntaxError: export declarations may only appear at top level")
1521
1522 (js2-msg "msg.mod.rc.after.export.spec.list"
1523 "SyntaxError: missing '}' after export specifier list")
1524
1525 ;; NodeTransformer
1526 (js2-msg "msg.dup.label"
1527 "duplicated label")
1528
1529 (js2-msg "msg.undef.label"
1530 "undefined label")
1531
1532 (js2-msg "msg.bad.break"
1533 "unlabelled break must be inside loop or switch")
1534
1535 (js2-msg "msg.continue.outside"
1536 "continue must be inside loop")
1537
1538 (js2-msg "msg.continue.nonloop"
1539 "continue can only use labels of iteration statements")
1540
1541 (js2-msg "msg.bad.throw.eol"
1542 "Line terminator is not allowed between the throw "
1543 "keyword and throw expression.")
1544
1545 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1546 "function statement requires a name")
1547
1548 (js2-msg "msg.no.paren.parms"
1549 "missing ( before function parameters.")
1550
1551 (js2-msg "msg.no.parm"
1552 "missing formal parameter")
1553
1554 (js2-msg "msg.no.paren.after.parms"
1555 "missing ) after formal parameters")
1556
1557 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1558 "parameter without default follows parameter with default")
1559
1560 (js2-msg "msg.param.after.rest" ; added by js2-mode
1561 "parameter after rest parameter")
1562
1563 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1564 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1565
1566 (js2-msg "msg.no.brace.body"
1567 "missing '{' before function body")
1568
1569 (js2-msg "msg.no.brace.after.body"
1570 "missing } after function body")
1571
1572 (js2-msg "msg.no.paren.cond"
1573 "missing ( before condition")
1574
1575 (js2-msg "msg.no.paren.after.cond"
1576 "missing ) after condition")
1577
1578 (js2-msg "msg.no.semi.stmt"
1579 "missing ; before statement")
1580
1581 (js2-msg "msg.missing.semi"
1582 "missing ; after statement")
1583
1584 (js2-msg "msg.no.name.after.dot"
1585 "missing name after . operator")
1586
1587 (js2-msg "msg.no.name.after.coloncolon"
1588 "missing name after :: operator")
1589
1590 (js2-msg "msg.no.name.after.dotdot"
1591 "missing name after .. operator")
1592
1593 (js2-msg "msg.no.name.after.xmlAttr"
1594 "missing name after .@")
1595
1596 (js2-msg "msg.no.bracket.index"
1597 "missing ] in index expression")
1598
1599 (js2-msg "msg.no.paren.switch"
1600 "missing ( before switch expression")
1601
1602 (js2-msg "msg.no.paren.after.switch"
1603 "missing ) after switch expression")
1604
1605 (js2-msg "msg.no.brace.switch"
1606 "missing '{' before switch body")
1607
1608 (js2-msg "msg.bad.switch"
1609 "invalid switch statement")
1610
1611 (js2-msg "msg.no.colon.case"
1612 "missing : after case expression")
1613
1614 (js2-msg "msg.double.switch.default"
1615 "double default label in the switch statement")
1616
1617 (js2-msg "msg.no.while.do"
1618 "missing while after do-loop body")
1619
1620 (js2-msg "msg.no.paren.for"
1621 "missing ( after for")
1622
1623 (js2-msg "msg.no.semi.for"
1624 "missing ; after for-loop initializer")
1625
1626 (js2-msg "msg.no.semi.for.cond"
1627 "missing ; after for-loop condition")
1628
1629 (js2-msg "msg.in.after.for.name"
1630 "missing in or of after for")
1631
1632 (js2-msg "msg.no.paren.for.ctrl"
1633 "missing ) after for-loop control")
1634
1635 (js2-msg "msg.no.paren.with"
1636 "missing ( before with-statement object")
1637
1638 (js2-msg "msg.no.paren.after.with"
1639 "missing ) after with-statement object")
1640
1641 (js2-msg "msg.no.paren.after.let"
1642 "missing ( after let")
1643
1644 (js2-msg "msg.no.paren.let"
1645 "missing ) after variable list")
1646
1647 (js2-msg "msg.no.curly.let"
1648 "missing } after let statement")
1649
1650 (js2-msg "msg.bad.return"
1651 "invalid return")
1652
1653 (js2-msg "msg.no.brace.block"
1654 "missing } in compound statement")
1655
1656 (js2-msg "msg.bad.label"
1657 "invalid label")
1658
1659 (js2-msg "msg.bad.var"
1660 "missing variable name")
1661
1662 (js2-msg "msg.bad.var.init"
1663 "invalid variable initialization")
1664
1665 (js2-msg "msg.no.colon.cond"
1666 "missing : in conditional expression")
1667
1668 (js2-msg "msg.no.paren.arg"
1669 "missing ) after argument list")
1670
1671 (js2-msg "msg.no.bracket.arg"
1672 "missing ] after element list")
1673
1674 (js2-msg "msg.bad.prop"
1675 "invalid property id")
1676
1677 (js2-msg "msg.no.colon.prop"
1678 "missing : after property id")
1679
1680 (js2-msg "msg.no.brace.prop"
1681 "missing } after property list")
1682
1683 (js2-msg "msg.no.paren"
1684 "missing ) in parenthetical")
1685
1686 (js2-msg "msg.reserved.id"
1687 "'%s' is a reserved identifier")
1688
1689 (js2-msg "msg.no.paren.catch"
1690 "missing ( before catch-block condition")
1691
1692 (js2-msg "msg.bad.catchcond"
1693 "invalid catch block condition")
1694
1695 (js2-msg "msg.catch.unreachable"
1696 "any catch clauses following an unqualified catch are unreachable")
1697
1698 (js2-msg "msg.no.brace.try"
1699 "missing '{' before try block")
1700
1701 (js2-msg "msg.no.brace.catchblock"
1702 "missing '{' before catch-block body")
1703
1704 (js2-msg "msg.try.no.catchfinally"
1705 "'try' without 'catch' or 'finally'")
1706
1707 (js2-msg "msg.no.return.value"
1708 "function %s does not always return a value")
1709
1710 (js2-msg "msg.anon.no.return.value"
1711 "anonymous function does not always return a value")
1712
1713 (js2-msg "msg.return.inconsistent"
1714 "return statement is inconsistent with previous usage")
1715
1716 (js2-msg "msg.generator.returns"
1717 "TypeError: legacy generator function '%s' returns a value")
1718
1719 (js2-msg "msg.anon.generator.returns"
1720 "TypeError: anonymous legacy generator function returns a value")
1721
1722 (js2-msg "msg.syntax"
1723 "syntax error")
1724
1725 (js2-msg "msg.unexpected.eof"
1726 "Unexpected end of file")
1727
1728 (js2-msg "msg.XML.bad.form"
1729 "illegally formed XML syntax")
1730
1731 (js2-msg "msg.XML.not.available"
1732 "XML runtime not available")
1733
1734 (js2-msg "msg.too.deep.parser.recursion"
1735 "Too deep recursion while parsing")
1736
1737 (js2-msg "msg.no.side.effects"
1738 "Code has no side effects")
1739
1740 (js2-msg "msg.extra.trailing.comma"
1741 "Trailing comma is not supported in some browsers")
1742
1743 (js2-msg "msg.array.trailing.comma"
1744 "Trailing comma yields different behavior across browsers")
1745
1746 (js2-msg "msg.equal.as.assign"
1747 (concat "Test for equality (==) mistyped as assignment (=)?"
1748 " (parenthesize to suppress warning)"))
1749
1750 (js2-msg "msg.var.hides.arg"
1751 "Variable %s hides argument")
1752
1753 (js2-msg "msg.destruct.assign.no.init"
1754 "Missing = in destructuring declaration")
1755
1756 ;; ScriptRuntime
1757 (js2-msg "msg.no.properties"
1758 "%s has no properties.")
1759
1760 (js2-msg "msg.invalid.iterator"
1761 "Invalid iterator value")
1762
1763 (js2-msg "msg.iterator.primitive"
1764 "__iterator__ returned a primitive value")
1765
1766 (js2-msg "msg.assn.create.strict"
1767 "Assignment to undeclared variable %s")
1768
1769 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1770 "Undeclared variable or function '%s'")
1771
1772 (js2-msg "msg.ref.undefined.prop"
1773 "Reference to undefined property '%s'")
1774
1775 (js2-msg "msg.prop.not.found"
1776 "Property %s not found.")
1777
1778 (js2-msg "msg.invalid.type"
1779 "Invalid JavaScript value of type %s")
1780
1781 (js2-msg "msg.primitive.expected"
1782 "Primitive type expected (had %s instead)")
1783
1784 (js2-msg "msg.namespace.expected"
1785 "Namespace object expected to left of :: (found %s instead)")
1786
1787 (js2-msg "msg.null.to.object"
1788 "Cannot convert null to an object.")
1789
1790 (js2-msg "msg.undef.to.object"
1791 "Cannot convert undefined to an object.")
1792
1793 (js2-msg "msg.cyclic.value"
1794 "Cyclic %s value not allowed.")
1795
1796 (js2-msg "msg.is.not.defined"
1797 "'%s' is not defined.")
1798
1799 (js2-msg "msg.undef.prop.read"
1800 "Cannot read property '%s' from %s")
1801
1802 (js2-msg "msg.undef.prop.write"
1803 "Cannot set property '%s' of %s to '%s'")
1804
1805 (js2-msg "msg.undef.prop.delete"
1806 "Cannot delete property '%s' of %s")
1807
1808 (js2-msg "msg.undef.method.call"
1809 "Cannot call method '%s' of %s")
1810
1811 (js2-msg "msg.undef.with"
1812 "Cannot apply 'with' to %s")
1813
1814 (js2-msg "msg.isnt.function"
1815 "%s is not a function, it is %s.")
1816
1817 (js2-msg "msg.isnt.function.in"
1818 "Cannot call property %s in object %s. "
1819 "It is not a function, it is '%s'.")
1820
1821 (js2-msg "msg.function.not.found"
1822 "Cannot find function %s.")
1823
1824 (js2-msg "msg.function.not.found.in"
1825 "Cannot find function %s in object %s.")
1826
1827 (js2-msg "msg.isnt.xml.object"
1828 "%s is not an xml object.")
1829
1830 (js2-msg "msg.no.ref.to.get"
1831 "%s is not a reference to read reference value.")
1832
1833 (js2-msg "msg.no.ref.to.set"
1834 "%s is not a reference to set reference value to %s.")
1835
1836 (js2-msg "msg.no.ref.from.function"
1837 "Function %s can not be used as the left-hand "
1838 "side of assignment or as an operand of ++ or -- operator.")
1839
1840 (js2-msg "msg.bad.default.value"
1841 "Object's getDefaultValue() method returned an object.")
1842
1843 (js2-msg "msg.instanceof.not.object"
1844 "Can't use instanceof on a non-object.")
1845
1846 (js2-msg "msg.instanceof.bad.prototype"
1847 "'prototype' property of %s is not an object.")
1848
1849 (js2-msg "msg.bad.radix"
1850 "illegal radix %s.")
1851
1852 ;; ScriptableObject
1853 (js2-msg "msg.default.value"
1854 "Cannot find default value for object.")
1855
1856 (js2-msg "msg.zero.arg.ctor"
1857 "Cannot load class '%s' which has no zero-parameter constructor.")
1858
1859 (js2-msg "msg.ctor.multiple.parms"
1860 "Can't define constructor or class %s since more than "
1861 "one constructor has multiple parameters.")
1862
1863 (js2-msg "msg.extend.scriptable"
1864 "%s must extend ScriptableObject in order to define property %s.")
1865
1866 (js2-msg "msg.bad.getter.parms"
1867 "In order to define a property, getter %s must have zero "
1868 "parameters or a single ScriptableObject parameter.")
1869
1870 (js2-msg "msg.obj.getter.parms"
1871 "Expected static or delegated getter %s to take "
1872 "a ScriptableObject parameter.")
1873
1874 (js2-msg "msg.getter.static"
1875 "Getter and setter must both be static or neither be static.")
1876
1877 (js2-msg "msg.setter.return"
1878 "Setter must have void return type: %s")
1879
1880 (js2-msg "msg.setter2.parms"
1881 "Two-parameter setter must take a ScriptableObject as "
1882 "its first parameter.")
1883
1884 (js2-msg "msg.setter1.parms"
1885 "Expected single parameter setter for %s")
1886
1887 (js2-msg "msg.setter2.expected"
1888 "Expected static or delegated setter %s to take two parameters.")
1889
1890 (js2-msg "msg.setter.parms"
1891 "Expected either one or two parameters for setter.")
1892
1893 (js2-msg "msg.setter.bad.type"
1894 "Unsupported parameter type '%s' in setter '%s'.")
1895
1896 (js2-msg "msg.add.sealed"
1897 "Cannot add a property to a sealed object: %s.")
1898
1899 (js2-msg "msg.remove.sealed"
1900 "Cannot remove a property from a sealed object: %s.")
1901
1902 (js2-msg "msg.modify.sealed"
1903 "Cannot modify a property of a sealed object: %s.")
1904
1905 (js2-msg "msg.modify.readonly"
1906 "Cannot modify readonly property: %s.")
1907
1908 ;; TokenStream
1909 (js2-msg "msg.missing.exponent"
1910 "missing exponent")
1911
1912 (js2-msg "msg.caught.nfe"
1913 "number format error")
1914
1915 (js2-msg "msg.unterminated.string.lit"
1916 "unterminated string literal")
1917
1918 (js2-msg "msg.unterminated.comment"
1919 "unterminated comment")
1920
1921 (js2-msg "msg.unterminated.re.lit"
1922 "unterminated regular expression literal")
1923
1924 (js2-msg "msg.invalid.re.flag"
1925 "invalid flag after regular expression")
1926
1927 (js2-msg "msg.no.re.input.for"
1928 "no input for %s")
1929
1930 (js2-msg "msg.illegal.character"
1931 "illegal character")
1932
1933 (js2-msg "msg.invalid.escape"
1934 "invalid Unicode escape sequence")
1935
1936 (js2-msg "msg.bad.namespace"
1937 "not a valid default namespace statement. "
1938 "Syntax is: default xml namespace = EXPRESSION;")
1939
1940 ;; TokensStream warnings
1941 (js2-msg "msg.bad.octal.literal"
1942 "illegal octal literal digit %s; "
1943 "interpreting it as a decimal digit")
1944
1945 (js2-msg "msg.missing.hex.digits"
1946 "missing hexadecimal digits after '0x'")
1947
1948 (js2-msg "msg.missing.binary.digits"
1949 "missing binary digits after '0b'")
1950
1951 (js2-msg "msg.missing.octal.digits"
1952 "missing octal digits after '0o'")
1953
1954 (js2-msg "msg.script.is.not.constructor"
1955 "Script objects are not constructors.")
1956
1957 ;; Arrays
1958 (js2-msg "msg.arraylength.bad"
1959 "Inappropriate array length.")
1960
1961 ;; Arrays
1962 (js2-msg "msg.arraylength.too.big"
1963 "Array length %s exceeds supported capacity limit.")
1964
1965 ;; URI
1966 (js2-msg "msg.bad.uri"
1967 "Malformed URI sequence.")
1968
1969 ;; Number
1970 (js2-msg "msg.bad.precision"
1971 "Precision %s out of range.")
1972
1973 ;; NativeGenerator
1974 (js2-msg "msg.send.newborn"
1975 "Attempt to send value to newborn generator")
1976
1977 (js2-msg "msg.already.exec.gen"
1978 "Already executing generator")
1979
1980 (js2-msg "msg.StopIteration.invalid"
1981 "StopIteration may not be changed to an arbitrary object.")
1982
1983 ;; Interpreter
1984 (js2-msg "msg.yield.closing"
1985 "Yield from closing generator")
1986
1987 ;; Classes
1988 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1989 "class statement requires a name")
1990
1991 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1992 "unexpected ',' between class properties")
1993
1994 (js2-msg "msg.unexpected.static" ; added by js2-mode
1995 "unexpected 'static'")
1996
1997 (js2-msg "msg.missing.extends" ; added by js2-mode
1998 "name is required after extends")
1999
2000 (js2-msg "msg.no.brace.class" ; added by js2-mode
2001 "missing '{' before class body")
2002
2003 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2004 "missing ']' after computed property expression")
2005
2006 ;;; Tokens Buffer
2007
2008 (defconst js2-ti-max-lookahead 2)
2009 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2010
2011 (defun js2-new-token (offset)
2012 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2013 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2014 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2015 token))
2016
2017 (defsubst js2-current-token ()
2018 (aref js2-ti-tokens js2-ti-tokens-cursor))
2019
2020 (defsubst js2-current-token-string ()
2021 (js2-token-string (js2-current-token)))
2022
2023 (defsubst js2-current-token-type ()
2024 (js2-token-type (js2-current-token)))
2025
2026 (defsubst js2-current-token-beg ()
2027 (js2-token-beg (js2-current-token)))
2028
2029 (defsubst js2-current-token-end ()
2030 (js2-token-end (js2-current-token)))
2031
2032 (defun js2-current-token-len ()
2033 (let ((token (js2-current-token)))
2034 (- (js2-token-end token)
2035 (js2-token-beg token))))
2036
2037 (defun js2-ts-seek (state)
2038 (setq js2-ts-lineno (js2-ts-state-lineno state)
2039 js2-ts-cursor (js2-ts-state-cursor state)
2040 js2-ti-tokens (js2-ts-state-tokens state)
2041 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2042 js2-ti-lookahead (js2-ts-state-lookahead state)))
2043
2044 ;;; Utilities
2045
2046 (defun js2-delete-if (predicate list)
2047 "Remove all items satisfying PREDICATE in LIST."
2048 (cl-loop for item in list
2049 if (not (funcall predicate item))
2050 collect item))
2051
2052 (defun js2-position (element list)
2053 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2054 Returns nil if element is not found in the list."
2055 (let ((count 0)
2056 found)
2057 (while (and list (not found))
2058 (if (eq element (car list))
2059 (setq found t)
2060 (setq count (1+ count)
2061 list (cdr list))))
2062 (if found count)))
2063
2064 (defun js2-find-if (predicate list)
2065 "Find first item satisfying PREDICATE in LIST."
2066 (let (result)
2067 (while (and list (not result))
2068 (if (funcall predicate (car list))
2069 (setq result (car list)))
2070 (setq list (cdr list)))
2071 result))
2072
2073 (defmacro js2-time (form)
2074 "Evaluate FORM, discard result, and return elapsed time in sec."
2075 (declare (debug t))
2076 (let ((beg (make-symbol "--js2-time-beg--")))
2077 `(let ((,beg (current-time)))
2078 ,form
2079 (/ (truncate (* (- (float-time (current-time))
2080 (float-time ,beg))
2081 10000))
2082 10000.0))))
2083
2084 (defsubst js2-same-line (pos)
2085 "Return t if POS is on the same line as current point."
2086 (and (>= pos (point-at-bol))
2087 (<= pos (point-at-eol))))
2088
2089 (defun js2-code-bug ()
2090 "Signal an error when we encounter an unexpected code path."
2091 (error "failed assertion"))
2092
2093 (defsubst js2-record-text-property (beg end prop value)
2094 "Record a text property to set when parsing finishes."
2095 (push (list beg end prop value) js2-mode-deferred-properties))
2096
2097 ;; I'd like to associate errors with nodes, but for now the
2098 ;; easiest thing to do is get the context info from the last token.
2099 (defun js2-record-parse-error (msg &optional arg pos len)
2100 (push (list (list msg arg)
2101 (or pos (js2-current-token-beg))
2102 (or len (js2-current-token-len)))
2103 js2-parsed-errors))
2104
2105 (defun js2-report-error (msg &optional msg-arg pos len)
2106 "Signal a syntax error or record a parse error."
2107 (if js2-recover-from-parse-errors
2108 (js2-record-parse-error msg msg-arg pos len)
2109 (signal 'js2-syntax-error
2110 (list msg
2111 js2-ts-lineno
2112 (save-excursion
2113 (goto-char js2-ts-cursor)
2114 (current-column))
2115 js2-ts-hit-eof))))
2116
2117 (defun js2-report-warning (msg &optional msg-arg pos len face)
2118 (if js2-compiler-report-warning-as-error
2119 (js2-report-error msg msg-arg pos len)
2120 (push (list (list msg msg-arg)
2121 (or pos (js2-current-token-beg))
2122 (or len (js2-current-token-len))
2123 face)
2124 js2-parsed-warnings)))
2125
2126 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2127 (if js2-compiler-strict-mode
2128 (js2-report-warning msg-id msg-arg beg
2129 (and beg end (- end beg)))))
2130
2131 (put 'js2-syntax-error 'error-conditions
2132 '(error syntax-error js2-syntax-error))
2133 (put 'js2-syntax-error 'error-message "Syntax error")
2134
2135 (put 'js2-parse-error 'error-conditions
2136 '(error parse-error js2-parse-error))
2137 (put 'js2-parse-error 'error-message "Parse error")
2138
2139 (defmacro js2-clear-flag (flags flag)
2140 `(setq ,flags (logand ,flags (lognot ,flag))))
2141
2142 (defmacro js2-set-flag (flags flag)
2143 "Logical-or FLAG into FLAGS."
2144 `(setq ,flags (logior ,flags ,flag)))
2145
2146 (defsubst js2-flag-set-p (flags flag)
2147 (/= 0 (logand flags flag)))
2148
2149 (defsubst js2-flag-not-set-p (flags flag)
2150 (zerop (logand flags flag)))
2151
2152 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2153 "Evaluate BODY with the _ character set to be word-syntax."
2154 (declare (indent 0) (debug t))
2155 (let ((old-syntax (make-symbol "old-syntax")))
2156 `(let ((,old-syntax (string (char-syntax ?_))))
2157 (unwind-protect
2158 (progn
2159 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2160 ,@body)
2161 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2162
2163 ;;; AST struct and function definitions
2164
2165 ;; flags for ast node property 'member-type (used for e4x operators)
2166 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2167 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2168 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2169
2170 (defsubst js2-relpos (pos anchor)
2171 "Convert POS to be relative to ANCHOR.
2172 If POS is nil, returns nil."
2173 (and pos (- pos anchor)))
2174
2175 (defun js2-make-pad (indent)
2176 (if (zerop indent)
2177 ""
2178 (make-string (* indent js2-basic-offset) ? )))
2179
2180 (defun js2-visit-ast (node callback)
2181 "Visit every node in ast NODE with visitor CALLBACK.
2182
2183 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2184 called twice: once to visit the node, and again after all the node's
2185 children have been processed. The END-P argument is nil on the first
2186 call and non-nil on the second call. The return value of the callback
2187 affects the traversal: if non-nil, the children of NODE are processed.
2188 If the callback returns nil, or if the node has no children, then the
2189 callback is called immediately with a non-nil END-P argument.
2190
2191 The node traversal is approximately lexical-order, although there
2192 are currently no guarantees around this."
2193 (when node
2194 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2195 ;; visit the node
2196 (when (funcall callback node nil)
2197 ;; visit the kids
2198 (cond
2199 ((eq vfunc 'js2-visit-none)
2200 nil) ; don't even bother calling it
2201 ;; Each AST node type has to define a `js2-visitor' function
2202 ;; that takes a node and a callback, and calls `js2-visit-ast'
2203 ;; on each child of the node.
2204 (vfunc
2205 (funcall vfunc node callback))
2206 (t
2207 (error "%s does not define a visitor-traversal function"
2208 (aref node 0)))))
2209 ;; call the end-visit
2210 (funcall callback node t))))
2211
2212 (cl-defstruct (js2-node
2213 (:constructor nil)) ; abstract
2214 "Base AST node type."
2215 (type -1) ; token type
2216 (pos -1) ; start position of this AST node in parsed input
2217 (len 1) ; num characters spanned by the node
2218 props ; optional node property list (an alist)
2219 parent) ; link to parent node; null for root
2220
2221 (defsubst js2-node-get-prop (node prop &optional default)
2222 (or (cadr (assoc prop (js2-node-props node))) default))
2223
2224 (defsubst js2-node-set-prop (node prop value)
2225 (setf (js2-node-props node)
2226 (cons (list prop value) (js2-node-props node))))
2227
2228 (defun js2-fixup-starts (n nodes)
2229 "Adjust the start positions of NODES to be relative to N.
2230 Any node in the list may be nil, for convenience."
2231 (dolist (node nodes)
2232 (when node
2233 (setf (js2-node-pos node) (- (js2-node-pos node)
2234 (js2-node-pos n))))))
2235
2236 (defun js2-node-add-children (parent &rest nodes)
2237 "Set parent node of NODES to PARENT, and return PARENT.
2238 Does nothing if we're not recording parent links.
2239 If any given node in NODES is nil, doesn't record that link."
2240 (js2-fixup-starts parent nodes)
2241 (dolist (node nodes)
2242 (and node
2243 (setf (js2-node-parent node) parent))))
2244
2245 ;; Non-recursive since it's called a frightening number of times.
2246 (defun js2-node-abs-pos (n)
2247 (let ((pos (js2-node-pos n)))
2248 (while (setq n (js2-node-parent n))
2249 (setq pos (+ pos (js2-node-pos n))))
2250 pos))
2251
2252 (defsubst js2-node-abs-end (n)
2253 "Return absolute buffer position of end of N."
2254 (+ (js2-node-abs-pos n) (js2-node-len n)))
2255
2256 ;; It's important to make sure block nodes have a Lisp list for the
2257 ;; child nodes, to limit printing recursion depth in an AST that
2258 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2259 ;; a sufficiently large vector tree.
2260
2261 (cl-defstruct (js2-block-node
2262 (:include js2-node)
2263 (:constructor nil)
2264 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2265 (pos (js2-current-token-beg))
2266 len
2267 props
2268 kids)))
2269 "A block of statements."
2270 kids) ; a Lisp list of the child statement nodes
2271
2272 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2273 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2274
2275 (defun js2-visit-block (ast callback)
2276 "Visit the `js2-block-node' children of AST."
2277 (dolist (kid (js2-block-node-kids ast))
2278 (js2-visit-ast kid callback)))
2279
2280 (defun js2-print-block (n i)
2281 (let ((pad (js2-make-pad i)))
2282 (insert pad "{\n")
2283 (dolist (kid (js2-block-node-kids n))
2284 (js2-print-ast kid (1+ i)))
2285 (insert pad "}")))
2286
2287 (cl-defstruct (js2-scope
2288 (:include js2-block-node)
2289 (:constructor nil)
2290 (:constructor make-js2-scope (&key (type js2-BLOCK)
2291 (pos (js2-current-token-beg))
2292 len
2293 kids)))
2294 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2295 ;; I don't have one of those handy, so I'll use an alist for now.
2296 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2297 ;; and is much lighter-weight to construct (both CPU and mem).
2298 ;; The keys are interned strings (symbols) for faster lookup.
2299 ;; Should switch to hybrid alist/hashtable eventually.
2300 symbol-table ; an alist of (symbol . js2-symbol)
2301 parent-scope ; a `js2-scope'
2302 top) ; top-level `js2-scope' (script/function)
2303
2304 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2305 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2306
2307 (defun js2-node-get-enclosing-scope (node)
2308 "Return the innermost `js2-scope' node surrounding NODE.
2309 Returns nil if there is no enclosing scope node."
2310 (let ((parent (js2-node-parent node)))
2311 (while (not (js2-scope-p parent))
2312 (setq parent (js2-node-parent parent)))
2313 parent))
2314
2315 (defun js2-get-defining-scope (scope name &optional point)
2316 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2317 Returns `js2-scope' in which NAME is defined, or nil if not found.
2318
2319 If POINT is non-nil, and if the found declaration type is
2320 `js2-LET', also check that the declaration node is before POINT."
2321 (let ((sym (if (symbolp name)
2322 name
2323 (intern name)))
2324 result
2325 (continue t))
2326 (while (and scope continue)
2327 (if (or
2328 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2329 (and entry
2330 (or (not point)
2331 (not (eq js2-LET (js2-symbol-decl-type entry)))
2332 (>= point
2333 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2334 (and (eq sym 'arguments)
2335 (js2-function-node-p scope)))
2336 (setq continue nil
2337 result scope)
2338 (setq scope (js2-scope-parent-scope scope))))
2339 result))
2340
2341 (defun js2-scope-get-symbol (scope name)
2342 "Return symbol table entry for NAME in SCOPE.
2343 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2344 (and (js2-scope-symbol-table scope)
2345 (cdr (assq (if (symbolp name)
2346 name
2347 (intern name))
2348 (js2-scope-symbol-table scope)))))
2349
2350 (defun js2-scope-put-symbol (scope name symbol)
2351 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2352 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2353 (let* ((table (js2-scope-symbol-table scope))
2354 (sym (if (symbolp name) name (intern name)))
2355 (entry (assq sym table)))
2356 (if entry
2357 (setcdr entry symbol)
2358 (push (cons sym symbol)
2359 (js2-scope-symbol-table scope)))))
2360
2361 (cl-defstruct (js2-symbol
2362 (:constructor nil)
2363 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2364 "A symbol table entry."
2365 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2366 ;; js2-LET, or js2-CONST
2367 decl-type
2368 name ; string
2369 ast-node) ; a `js2-node'
2370
2371 (cl-defstruct (js2-error-node
2372 (:include js2-node)
2373 (:constructor nil) ; silence emacs21 byte-compiler
2374 (:constructor make-js2-error-node (&key (type js2-ERROR)
2375 (pos (js2-current-token-beg))
2376 len)))
2377 "AST node representing a parse error.")
2378
2379 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2380 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2381
2382 (cl-defstruct (js2-script-node
2383 (:include js2-scope)
2384 (:constructor nil)
2385 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2386 (pos (js2-current-token-beg))
2387 len
2388 ;; FIXME: What are those?
2389 var-decls
2390 fun-decls)))
2391 functions ; Lisp list of nested functions
2392 regexps ; Lisp list of (string . flags)
2393 symbols ; alist (every symbol gets unique index)
2394 (param-count 0)
2395 var-names ; vector of string names
2396 consts ; bool-vector matching var-decls
2397 (temp-number 0)) ; for generating temp variables
2398
2399 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2400 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2401
2402 (defun js2-print-script (node indent)
2403 (dolist (kid (js2-block-node-kids node))
2404 (js2-print-ast kid indent)))
2405
2406 (cl-defstruct (js2-ast-root
2407 (:include js2-script-node)
2408 (:constructor nil)
2409 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2410 (pos (js2-current-token-beg))
2411 len
2412 buffer)))
2413 "The root node of a js2 AST."
2414 buffer ; the source buffer from which the code was parsed
2415 comments ; a Lisp list of comments, ordered by start position
2416 errors ; a Lisp list of errors found during parsing
2417 warnings ; a Lisp list of warnings found during parsing
2418 node-count) ; number of nodes in the tree, including the root
2419
2420 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2421 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2422
2423 (defun js2-visit-ast-root (ast callback)
2424 (dolist (kid (js2-ast-root-kids ast))
2425 (js2-visit-ast kid callback))
2426 (dolist (comment (js2-ast-root-comments ast))
2427 (js2-visit-ast comment callback)))
2428
2429 (cl-defstruct (js2-comment-node
2430 (:include js2-node)
2431 (:constructor nil)
2432 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2433 (pos (js2-current-token-beg))
2434 len
2435 format)))
2436 format) ; 'line, 'block, 'jsdoc or 'html
2437
2438 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2439 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2440
2441 (defun js2-print-comment (n i)
2442 ;; We really ought to link end-of-line comments to their nodes.
2443 ;; Or maybe we could add a new comment type, 'endline.
2444 (insert (js2-make-pad i)
2445 (js2-node-string n)))
2446
2447 (cl-defstruct (js2-expr-stmt-node
2448 (:include js2-node)
2449 (:constructor nil)
2450 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2451 (pos js2-ts-cursor)
2452 len
2453 expr)))
2454 "An expression statement."
2455 expr)
2456
2457 (defsubst js2-expr-stmt-node-set-has-result (node)
2458 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2459 (setf (js2-node-type node) js2-EXPR_RESULT))
2460
2461 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2462 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2463
2464 (defun js2-visit-expr-stmt-node (n v)
2465 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2466
2467 (defun js2-print-expr-stmt-node (n indent)
2468 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2469 (insert ";\n"))
2470
2471 (cl-defstruct (js2-loop-node
2472 (:include js2-scope)
2473 (:constructor nil))
2474 "Abstract supertype of loop nodes."
2475 body ; a `js2-block-node'
2476 lp ; position of left-paren, nil if omitted
2477 rp) ; position of right-paren, nil if omitted
2478
2479 (cl-defstruct (js2-do-node
2480 (:include js2-loop-node)
2481 (:constructor nil)
2482 (:constructor make-js2-do-node (&key (type js2-DO)
2483 (pos (js2-current-token-beg))
2484 len
2485 body
2486 condition
2487 while-pos
2488 lp
2489 rp)))
2490 "AST node for do-loop."
2491 condition ; while (expression)
2492 while-pos) ; buffer position of 'while' keyword
2493
2494 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2495 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2496
2497 (defun js2-visit-do-node (n v)
2498 (js2-visit-ast (js2-do-node-body n) v)
2499 (js2-visit-ast (js2-do-node-condition n) v))
2500
2501 (defun js2-print-do-node (n i)
2502 (let ((pad (js2-make-pad i)))
2503 (insert pad "do {\n")
2504 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2505 (js2-print-ast kid (1+ i)))
2506 (insert pad "} while (")
2507 (js2-print-ast (js2-do-node-condition n) 0)
2508 (insert ");\n")))
2509
2510 (cl-defstruct (js2-export-node
2511 (:include js2-node)
2512 (:constructor nil)
2513 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2514 (pos) (js2-current-token-beg)
2515 len
2516 exports-list
2517 from-clause
2518 declaration
2519 default)))
2520 "AST node for an export statement. There are many things that can be exported,
2521 so many of its properties will be nil.
2522 "
2523 exports-list ; lisp list of js2-export-binding-node to export
2524 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2525 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2526 default) ; js2-function-node or js2-assign-node
2527
2528 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2529 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2530
2531 (defun js2-visit-export-node (n v)
2532 (let ((exports-list (js2-export-node-exports-list n))
2533 (from (js2-export-node-from-clause n))
2534 (declaration (js2-export-node-declaration n))
2535 (default (js2-export-node-default n)))
2536 (when exports-list
2537 (dolist (export exports-list)
2538 (js2-visit-ast export v)))
2539 (when from
2540 (js2-visit-ast from v))
2541 (when declaration
2542 (js2-visit-ast declaration v))
2543 (when default
2544 (js2-visit-ast default v))))
2545
2546 (defun js2-print-export-node (n i)
2547 (let ((pad (js2-make-pad i))
2548 (exports-list (js2-export-node-exports-list n))
2549 (from (js2-export-node-from-clause n))
2550 (declaration (js2-export-node-declaration n))
2551 (default (js2-export-node-default n)))
2552 (insert pad "export ")
2553 (cond
2554 (default
2555 (insert "default ")
2556 (js2-print-ast default i))
2557 (declaration
2558 (js2-print-ast declaration i))
2559 ((and exports-list from)
2560 (js2-print-named-imports exports-list)
2561 (insert " ")
2562 (js2-print-from-clause from))
2563 (from
2564 (insert "* ")
2565 (js2-print-from-clause from))
2566 (exports-list
2567 (js2-print-named-imports exports-list)))
2568 (insert ";\n")))
2569
2570 (cl-defstruct (js2-while-node
2571 (:include js2-loop-node)
2572 (:constructor nil)
2573 (:constructor make-js2-while-node (&key (type js2-WHILE)
2574 (pos (js2-current-token-beg))
2575 len body
2576 condition lp
2577 rp)))
2578 "AST node for while-loop."
2579 condition) ; while-condition
2580
2581 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2582 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2583
2584 (defun js2-visit-while-node (n v)
2585 (js2-visit-ast (js2-while-node-condition n) v)
2586 (js2-visit-ast (js2-while-node-body n) v))
2587
2588 (defun js2-print-while-node (n i)
2589 (let ((pad (js2-make-pad i)))
2590 (insert pad "while (")
2591 (js2-print-ast (js2-while-node-condition n) 0)
2592 (insert ") {\n")
2593 (js2-print-body (js2-while-node-body n) (1+ i))
2594 (insert pad "}\n")))
2595
2596 (cl-defstruct (js2-for-node
2597 (:include js2-loop-node)
2598 (:constructor nil)
2599 (:constructor make-js2-for-node (&key (type js2-FOR)
2600 (pos js2-ts-cursor)
2601 len body init
2602 condition
2603 update lp rp)))
2604 "AST node for a C-style for-loop."
2605 init ; initialization expression
2606 condition ; loop condition
2607 update) ; update clause
2608
2609 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2610 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2611
2612 (defun js2-visit-for-node (n v)
2613 (js2-visit-ast (js2-for-node-init n) v)
2614 (js2-visit-ast (js2-for-node-condition n) v)
2615 (js2-visit-ast (js2-for-node-update n) v)
2616 (js2-visit-ast (js2-for-node-body n) v))
2617
2618 (defun js2-print-for-node (n i)
2619 (let ((pad (js2-make-pad i)))
2620 (insert pad "for (")
2621 (js2-print-ast (js2-for-node-init n) 0)
2622 (insert "; ")
2623 (js2-print-ast (js2-for-node-condition n) 0)
2624 (insert "; ")
2625 (js2-print-ast (js2-for-node-update n) 0)
2626 (insert ") {\n")
2627 (js2-print-body (js2-for-node-body n) (1+ i))
2628 (insert pad "}\n")))
2629
2630 (cl-defstruct (js2-for-in-node
2631 (:include js2-loop-node)
2632 (:constructor nil)
2633 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2634 (pos js2-ts-cursor)
2635 len body
2636 iterator
2637 object
2638 in-pos
2639 each-pos
2640 foreach-p forof-p
2641 lp rp)))
2642 "AST node for a for..in loop."
2643 iterator ; [var] foo in ...
2644 object ; object over which we're iterating
2645 in-pos ; buffer position of 'in' keyword
2646 each-pos ; buffer position of 'each' keyword, if foreach-p
2647 foreach-p ; t if it's a for-each loop
2648 forof-p) ; t if it's a for-of loop
2649
2650 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2651 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2652
2653 (defun js2-visit-for-in-node (n v)
2654 (js2-visit-ast (js2-for-in-node-iterator n) v)
2655 (js2-visit-ast (js2-for-in-node-object n) v)
2656 (js2-visit-ast (js2-for-in-node-body n) v))
2657
2658 (defun js2-print-for-in-node (n i)
2659 (let ((pad (js2-make-pad i))
2660 (foreach (js2-for-in-node-foreach-p n))
2661 (forof (js2-for-in-node-forof-p n)))
2662 (insert pad "for ")
2663 (if foreach
2664 (insert "each "))
2665 (insert "(")
2666 (js2-print-ast (js2-for-in-node-iterator n) 0)
2667 (insert (if forof " of " " in "))
2668 (js2-print-ast (js2-for-in-node-object n) 0)
2669 (insert ") {\n")
2670 (js2-print-body (js2-for-in-node-body n) (1+ i))
2671 (insert pad "}\n")))
2672
2673 (cl-defstruct (js2-return-node
2674 (:include js2-node)
2675 (:constructor nil)
2676 (:constructor make-js2-return-node (&key (type js2-RETURN)
2677 (pos js2-ts-cursor)
2678 len
2679 retval)))
2680 "AST node for a return statement."
2681 retval) ; expression to return, or 'undefined
2682
2683 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2684 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2685
2686 (defun js2-visit-return-node (n v)
2687 (js2-visit-ast (js2-return-node-retval n) v))
2688
2689 (defun js2-print-return-node (n i)
2690 (insert (js2-make-pad i) "return")
2691 (when (js2-return-node-retval n)
2692 (insert " ")
2693 (js2-print-ast (js2-return-node-retval n) 0))
2694 (insert ";\n"))
2695
2696 (cl-defstruct (js2-if-node
2697 (:include js2-node)
2698 (:constructor nil)
2699 (:constructor make-js2-if-node (&key (type js2-IF)
2700 (pos js2-ts-cursor)
2701 len condition
2702 then-part
2703 else-pos
2704 else-part lp
2705 rp)))
2706 "AST node for an if-statement."
2707 condition ; expression
2708 then-part ; statement or block
2709 else-pos ; optional buffer position of 'else' keyword
2710 else-part ; optional statement or block
2711 lp ; position of left-paren, nil if omitted
2712 rp) ; position of right-paren, nil if omitted
2713
2714 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2715 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2716
2717 (defun js2-visit-if-node (n v)
2718 (js2-visit-ast (js2-if-node-condition n) v)
2719 (js2-visit-ast (js2-if-node-then-part n) v)
2720 (js2-visit-ast (js2-if-node-else-part n) v))
2721
2722 (defun js2-print-if-node (n i)
2723 (let ((pad (js2-make-pad i))
2724 (then-part (js2-if-node-then-part n))
2725 (else-part (js2-if-node-else-part n)))
2726 (insert pad "if (")
2727 (js2-print-ast (js2-if-node-condition n) 0)
2728 (insert ") {\n")
2729 (js2-print-body then-part (1+ i))
2730 (insert pad "}")
2731 (cond
2732 ((not else-part)
2733 (insert "\n"))
2734 ((js2-if-node-p else-part)
2735 (insert " else ")
2736 (js2-print-body else-part i))
2737 (t
2738 (insert " else {\n")
2739 (js2-print-body else-part (1+ i))
2740 (insert pad "}\n")))))
2741
2742 (cl-defstruct (js2-export-binding-node
2743 (:include js2-node)
2744 (:constructor nil)
2745 (:constructor make-js2-export-binding-node (&key (type -1)
2746 pos
2747 len
2748 local-name
2749 extern-name)))
2750 "AST node for an external symbol binding.
2751 It contains a local-name node which is the name of the value in the
2752 current scope, and extern-name which is the name of the value in the
2753 imported or exported scope. By default these are the same, but if the
2754 name is aliased as in {foo as bar}, it would have an extern-name node
2755 containing 'foo' and a local-name node containing 'bar'."
2756 local-name ; js2-name-node with the variable name in this scope
2757 extern-name) ; js2-name-node with the value name in the exporting module
2758
2759 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2760 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2761
2762 (defun js2-visit-extern-binding (n v)
2763 "Visit an extern binding node. First visit the local-name, and, if
2764 different, visit the extern-name."
2765 (let ((local-name (js2-export-binding-node-local-name n))
2766 (extern-name (js2-export-binding-node-extern-name n)))
2767 (when local-name
2768 (js2-visit-ast local-name v))
2769 (when (not (equal local-name extern-name))
2770 (js2-visit-ast extern-name v))))
2771
2772 (defun js2-print-extern-binding (n i)
2773 "Print a representation of a single extern binding. E.g. 'foo' or
2774 'foo as bar'."
2775 (let ((local-name (js2-export-binding-node-local-name n))
2776 (extern-name (js2-export-binding-node-extern-name n)))
2777 (insert (js2-name-node-name extern-name))
2778 (when (not (equal local-name extern-name))
2779 (insert " as ")
2780 (insert (js2-name-node-name local-name)))))
2781
2782
2783 (cl-defstruct (js2-import-node
2784 (:include js2-node)
2785 (:constructor nil)
2786 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2787 (pos (js2-current-token-beg))
2788 len
2789 import
2790 from
2791 module-id)))
2792 "AST node for an import statement. It follows the form
2793
2794 import ModuleSpecifier;
2795 import ImportClause FromClause;"
2796 import ; js2-import-clause-node specifying which names are to imported.
2797 from ; js2-from-clause-node indicating the module from which to import.
2798 module-id) ; module-id of the import. E.g. 'src/mylib'.
2799
2800 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2801 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2802
2803 (defun js2-visit-import (n v)
2804 (let ((import-clause (js2-import-node-import n))
2805 (from-clause (js2-import-node-from n)))
2806 (when import-clause
2807 (js2-visit-ast import-clause v))
2808 (when from-clause
2809 (js2-visit-ast from-clause v))))
2810
2811 (defun js2-print-import (n i)
2812 "Prints a representation of the import node"
2813 (let ((pad (js2-make-pad i))
2814 (import-clause (js2-import-node-import n))
2815 (from-clause (js2-import-node-from n))
2816 (module-id (js2-import-node-module-id n)))
2817 (insert pad "import ")
2818 (if import-clause
2819 (progn
2820 (js2-print-import-clause import-clause)
2821 (insert " ")
2822 (js2-print-from-clause from-clause))
2823 (insert "'")
2824 (insert module-id)
2825 (insert "'"))
2826 (insert ";\n")))
2827
2828 (cl-defstruct (js2-import-clause-node
2829 (:include js2-node)
2830 (:constructor nil)
2831 (:constructor make-js2-import-clause-node (&key (type -1)
2832 pos
2833 len
2834 namespace-import
2835 named-imports
2836 default-binding)))
2837 "AST node corresponding to the import clause of an import statement. This is
2838 the portion of the import that bindings names from the external context to the
2839 local context."
2840 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2841 named-imports ; lisp list of js2-export-binding-node for all named imports.
2842 default-binding) ; js2-export-binding-node for the default import binding
2843
2844 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2845 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2846
2847 (defun js2-visit-import-clause (n v)
2848 (let ((ns-import (js2-import-clause-node-namespace-import n))
2849 (named-imports (js2-import-clause-node-named-imports n))
2850 (default (js2-import-clause-node-default-binding n)))
2851 (when ns-import
2852 (js2-visit-ast ns-import v))
2853 (when named-imports
2854 (dolist (import named-imports)
2855 (js2-visit-ast import v)))
2856 (when default
2857 (js2-visit-ast default v))))
2858
2859 (defun js2-print-import-clause (n)
2860 (let ((ns-import (js2-import-clause-node-namespace-import n))
2861 (named-imports (js2-import-clause-node-named-imports n))
2862 (default (js2-import-clause-node-default-binding n)))
2863 (cond
2864 ((and default ns-import)
2865 (js2-print-ast default)
2866 (insert ", ")
2867 (js2-print-namespace-import ns-import))
2868 ((and default named-imports)
2869 (js2-print-ast default)
2870 (insert ", ")
2871 (js2-print-named-imports named-imports))
2872 (default
2873 (js2-print-ast default))
2874 (ns-import
2875 (js2-print-namespace-import ns-import))
2876 (named-imports
2877 (js2-print-named-imports named-imports)))))
2878
2879 (defun js2-print-namespace-import (node)
2880 (insert "* as ")
2881 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2882
2883 (defun js2-print-named-imports (imports)
2884 (insert "{")
2885 (let ((len (length imports))
2886 (n 0))
2887 (while (< n len)
2888 (js2-print-extern-binding (nth n imports) 0)
2889 (unless (= n (- len 1))
2890 (insert ", "))
2891 (setq n (+ n 1))))
2892 (insert "}"))
2893
2894 (cl-defstruct (js2-namespace-import-node
2895 (:include js2-node)
2896 (:constructor nil)
2897 (:constructor make-js2-namespace-import-node (&key (type -1)
2898 pos
2899 len
2900 name)))
2901 "AST node for a complete namespace import.
2902 E.g. the '* as lib' expression in:
2903
2904 import * as lib from 'src/lib'
2905
2906 It contains a single name node referring to the bound name."
2907 name) ; js2-name-node of the bound name.
2908
2909 (defun js2-visit-namespace-import (n v)
2910 (js2-visit-ast (js2-namespace-import-node-name n) v))
2911
2912 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2913 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2914
2915 (cl-defstruct (js2-from-clause-node
2916 (:include js2-node)
2917 (:constructor nil)
2918 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2919 pos
2920 len
2921 module-id
2922 metadata-p)))
2923 "AST node for the from clause in an import or export statement.
2924 E.g. from 'my/module'. It can refere to either an external module, or to the
2925 modules metadata itself."
2926 module-id ; string containing the module specifier.
2927 metadata-p) ; true if this clause refers to the module's metadata
2928
2929 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2930 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2931
2932 (defun js2-print-from-clause (n)
2933 (insert "from ")
2934 (if (js2-from-clause-node-metadata-p n)
2935 (insert "this module")
2936 (insert "'")
2937 (insert (js2-from-clause-node-module-id n))
2938 (insert "'")))
2939
2940 (cl-defstruct (js2-try-node
2941 (:include js2-node)
2942 (:constructor nil)
2943 (:constructor make-js2-try-node (&key (type js2-TRY)
2944 (pos js2-ts-cursor)
2945 len
2946 try-block
2947 catch-clauses
2948 finally-block)))
2949 "AST node for a try-statement."
2950 try-block
2951 catch-clauses ; a Lisp list of `js2-catch-node'
2952 finally-block) ; a `js2-finally-node'
2953
2954 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2955 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2956
2957 (defun js2-visit-try-node (n v)
2958 (js2-visit-ast (js2-try-node-try-block n) v)
2959 (dolist (clause (js2-try-node-catch-clauses n))
2960 (js2-visit-ast clause v))
2961 (js2-visit-ast (js2-try-node-finally-block n) v))
2962
2963 (defun js2-print-try-node (n i)
2964 (let ((pad (js2-make-pad i))
2965 (catches (js2-try-node-catch-clauses n))
2966 (finally (js2-try-node-finally-block n)))
2967 (insert pad "try {\n")
2968 (js2-print-body (js2-try-node-try-block n) (1+ i))
2969 (insert pad "}")
2970 (when catches
2971 (dolist (catch catches)
2972 (js2-print-ast catch i)))
2973 (if finally
2974 (js2-print-ast finally i)
2975 (insert "\n"))))
2976
2977 (cl-defstruct (js2-catch-node
2978 (:include js2-scope)
2979 (:constructor nil)
2980 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2981 (pos js2-ts-cursor)
2982 len
2983 param
2984 guard-kwd
2985 guard-expr
2986 lp rp)))
2987 "AST node for a catch clause."
2988 param ; destructuring form or simple name node
2989 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2990 guard-expr ; catch condition, a `js2-node'
2991 lp ; buffer position of left-paren, nil if omitted
2992 rp) ; buffer position of right-paren, nil if omitted
2993
2994 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2995 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2996
2997 (defun js2-visit-catch-node (n v)
2998 (js2-visit-ast (js2-catch-node-param n) v)
2999 (when (js2-catch-node-guard-kwd n)
3000 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3001 (js2-visit-block n v))
3002
3003 (defun js2-print-catch-node (n i)
3004 (let ((pad (js2-make-pad i))
3005 (guard-kwd (js2-catch-node-guard-kwd n))
3006 (guard-expr (js2-catch-node-guard-expr n)))
3007 (insert " catch (")
3008 (js2-print-ast (js2-catch-node-param n) 0)
3009 (when guard-kwd
3010 (insert " if ")
3011 (js2-print-ast guard-expr 0))
3012 (insert ") {\n")
3013 (js2-print-body n (1+ i))
3014 (insert pad "}")))
3015
3016 (cl-defstruct (js2-finally-node
3017 (:include js2-node)
3018 (:constructor nil)
3019 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3020 (pos js2-ts-cursor)
3021 len body)))
3022 "AST node for a finally clause."
3023 body) ; a `js2-node', often but not always a block node
3024
3025 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3026 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3027
3028 (defun js2-visit-finally-node (n v)
3029 (js2-visit-ast (js2-finally-node-body n) v))
3030
3031 (defun js2-print-finally-node (n i)
3032 (let ((pad (js2-make-pad i)))
3033 (insert " finally {\n")
3034 (js2-print-body (js2-finally-node-body n) (1+ i))
3035 (insert pad "}\n")))
3036
3037 (cl-defstruct (js2-switch-node
3038 (:include js2-node)
3039 (:constructor nil)
3040 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3041 (pos js2-ts-cursor)
3042 len
3043 discriminant
3044 cases lp
3045 rp)))
3046 "AST node for a switch statement."
3047 discriminant ; a `js2-node' (switch expression)
3048 cases ; a Lisp list of `js2-case-node'
3049 lp ; position of open-paren for discriminant, nil if omitted
3050 rp) ; position of close-paren for discriminant, nil if omitted
3051
3052 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3053 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3054
3055 (defun js2-visit-switch-node (n v)
3056 (js2-visit-ast (js2-switch-node-discriminant n) v)
3057 (dolist (c (js2-switch-node-cases n))
3058 (js2-visit-ast c v)))
3059
3060 (defun js2-print-switch-node (n i)
3061 (let ((pad (js2-make-pad i))
3062 (cases (js2-switch-node-cases n)))
3063 (insert pad "switch (")
3064 (js2-print-ast (js2-switch-node-discriminant n) 0)
3065 (insert ") {\n")
3066 (dolist (case cases)
3067 (js2-print-ast case i))
3068 (insert pad "}\n")))
3069
3070 (cl-defstruct (js2-case-node
3071 (:include js2-block-node)
3072 (:constructor nil)
3073 (:constructor make-js2-case-node (&key (type js2-CASE)
3074 (pos js2-ts-cursor)
3075 len kids expr)))
3076 "AST node for a case clause of a switch statement."
3077 expr) ; the case expression (nil for default)
3078
3079 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3080 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3081
3082 (defun js2-visit-case-node (n v)
3083 (js2-visit-ast (js2-case-node-expr n) v)
3084 (js2-visit-block n v))
3085
3086 (defun js2-print-case-node (n i)
3087 (let ((pad (js2-make-pad i))
3088 (expr (js2-case-node-expr n)))
3089 (insert pad)
3090 (if (null expr)
3091 (insert "default:\n")
3092 (insert "case ")
3093 (js2-print-ast expr 0)
3094 (insert ":\n"))
3095 (dolist (kid (js2-case-node-kids n))
3096 (js2-print-ast kid (1+ i)))))
3097
3098 (cl-defstruct (js2-throw-node
3099 (:include js2-node)
3100 (:constructor nil)
3101 (:constructor make-js2-throw-node (&key (type js2-THROW)
3102 (pos js2-ts-cursor)
3103 len expr)))
3104 "AST node for a throw statement."
3105 expr) ; the expression to throw
3106
3107 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3108 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3109
3110 (defun js2-visit-throw-node (n v)
3111 (js2-visit-ast (js2-throw-node-expr n) v))
3112
3113 (defun js2-print-throw-node (n i)
3114 (insert (js2-make-pad i) "throw ")
3115 (js2-print-ast (js2-throw-node-expr n) 0)
3116 (insert ";\n"))
3117
3118 (cl-defstruct (js2-with-node
3119 (:include js2-node)
3120 (:constructor nil)
3121 (:constructor make-js2-with-node (&key (type js2-WITH)
3122 (pos js2-ts-cursor)
3123 len object
3124 body lp rp)))
3125 "AST node for a with-statement."
3126 object
3127 body
3128 lp ; buffer position of left-paren around object, nil if omitted
3129 rp) ; buffer position of right-paren around object, nil if omitted
3130
3131 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3132 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3133
3134 (defun js2-visit-with-node (n v)
3135 (js2-visit-ast (js2-with-node-object n) v)
3136 (js2-visit-ast (js2-with-node-body n) v))
3137
3138 (defun js2-print-with-node (n i)
3139 (let ((pad (js2-make-pad i)))
3140 (insert pad "with (")
3141 (js2-print-ast (js2-with-node-object n) 0)
3142 (insert ") {\n")
3143 (js2-print-body (js2-with-node-body n) (1+ i))
3144 (insert pad "}\n")))
3145
3146 (cl-defstruct (js2-label-node
3147 (:include js2-node)
3148 (:constructor nil)
3149 (:constructor make-js2-label-node (&key (type js2-LABEL)
3150 (pos js2-ts-cursor)
3151 len name)))
3152 "AST node for a statement label or case label."
3153 name ; a string
3154 loop) ; for validating and code-generating continue-to-label
3155
3156 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3157 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3158
3159 (defun js2-print-label (n i)
3160 (insert (js2-make-pad i)
3161 (js2-label-node-name n)
3162 ":\n"))
3163
3164 (cl-defstruct (js2-labeled-stmt-node
3165 (:include js2-node)
3166 (:constructor nil)
3167 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3168 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3169 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3170 (pos js2-ts-cursor)
3171 len labels stmt)))
3172 "AST node for a statement with one or more labels.
3173 Multiple labels for a statement are collapsed into the labels field."
3174 labels ; Lisp list of `js2-label-node'
3175 stmt) ; the statement these labels are for
3176
3177 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3178 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3179
3180 (defun js2-get-label-by-name (lbl-stmt name)
3181 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3182 Returns nil if no such label is in the list."
3183 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3184 result)
3185 (while (and label-list (not result))
3186 (if (string= (js2-label-node-name (car label-list)) name)
3187 (setq result (car label-list))
3188 (setq label-list (cdr label-list))))
3189 result))
3190
3191 (defun js2-visit-labeled-stmt (n v)
3192 (dolist (label (js2-labeled-stmt-node-labels n))
3193 (js2-visit-ast label v))
3194 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3195
3196 (defun js2-print-labeled-stmt (n i)
3197 (dolist (label (js2-labeled-stmt-node-labels n))
3198 (js2-print-ast label i))
3199 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3200
3201 (defun js2-labeled-stmt-node-contains (node label)
3202 "Return t if NODE contains LABEL in its label set.
3203 NODE is a `js2-labels-node'. LABEL is an identifier."
3204 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3205 if (string= label (js2-label-node-name nl))
3206 return t
3207 finally return nil))
3208
3209 (defsubst js2-labeled-stmt-node-add-label (node label)
3210 "Add a `js2-label-node' to the label set for this statement."
3211 (setf (js2-labeled-stmt-node-labels node)
3212 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3213
3214 (cl-defstruct (js2-jump-node
3215 (:include js2-node)
3216 (:constructor nil))
3217 "Abstract supertype of break and continue nodes."
3218 label ; `js2-name-node' for location of label identifier, if present
3219 target) ; target js2-labels-node or loop/switch statement
3220
3221 (defun js2-visit-jump-node (n v)
3222 ;; We don't visit the target, since it's a back-link.
3223 (js2-visit-ast (js2-jump-node-label n) v))
3224
3225 (cl-defstruct (js2-break-node
3226 (:include js2-jump-node)
3227 (:constructor nil)
3228 (:constructor make-js2-break-node (&key (type js2-BREAK)
3229 (pos js2-ts-cursor)
3230 len label target)))
3231 "AST node for a break statement.
3232 The label field is a `js2-name-node', possibly nil, for the named label
3233 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3234 is the target of the break - a label node or enclosing loop/switch statement.")
3235
3236 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3237 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3238
3239 (defun js2-print-break-node (n i)
3240 (insert (js2-make-pad i) "break")
3241 (when (js2-break-node-label n)
3242 (insert " ")
3243 (js2-print-ast (js2-break-node-label n) 0))
3244 (insert ";\n"))
3245
3246 (cl-defstruct (js2-continue-node
3247 (:include js2-jump-node)
3248 (:constructor nil)
3249 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3250 (pos js2-ts-cursor)
3251 len label target)))
3252 "AST node for a continue statement.
3253 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3254 It is nil if continue specifies no label. The target field is the jump target:
3255 a `js2-label-node' or the innermost enclosing loop.")
3256
3257 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3258 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3259
3260 (defun js2-print-continue-node (n i)
3261 (insert (js2-make-pad i) "continue")
3262 (when (js2-continue-node-label n)
3263 (insert " ")
3264 (js2-print-ast (js2-continue-node-label n) 0))
3265 (insert ";\n"))
3266
3267 (cl-defstruct (js2-function-node
3268 (:include js2-script-node)
3269 (:constructor nil)
3270 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3271 (pos js2-ts-cursor)
3272 len
3273 (ftype 'FUNCTION)
3274 (form 'FUNCTION_STATEMENT)
3275 (name "")
3276 params rest-p
3277 body
3278 generator-type
3279 lp rp)))
3280 "AST node for a function declaration.
3281 The `params' field is a Lisp list of nodes. Each node is either a simple
3282 `js2-name-node', or if it's a destructuring-assignment parameter, a
3283 `js2-array-node' or `js2-object-node'."
3284 ftype ; FUNCTION, GETTER or SETTER
3285 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3286 name ; function name (a `js2-name-node', or nil if anonymous)
3287 params ; a Lisp list of destructuring forms or simple name nodes
3288 rest-p ; if t, the last parameter is rest parameter
3289 body ; a `js2-block-node' or expression node (1.8 only)
3290 lp ; position of arg-list open-paren, or nil if omitted
3291 rp ; position of arg-list close-paren, or nil if omitted
3292 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3293 needs-activation ; t if we need an activation object for this frame
3294 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3295 member-expr) ; nonstandard Ecma extension from Rhino
3296
3297 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3298 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3299
3300 (defun js2-visit-function-node (n v)
3301 (js2-visit-ast (js2-function-node-name n) v)
3302 (dolist (p (js2-function-node-params n))
3303 (js2-visit-ast p v))
3304 (js2-visit-ast (js2-function-node-body n) v))
3305
3306 (defun js2-print-function-node (n i)
3307 (let* ((pad (js2-make-pad i))
3308 (getter (js2-node-get-prop n 'GETTER_SETTER))
3309 (name (or (js2-function-node-name n)
3310 (js2-function-node-member-expr n)))
3311 (params (js2-function-node-params n))
3312 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3313 (rest-p (js2-function-node-rest-p n))
3314 (body (js2-function-node-body n))
3315 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3316 (unless (or getter arrow)
3317 (insert pad "function")
3318 (when (eq (js2-function-node-generator-type n) 'STAR)
3319 (insert "*")))
3320 (when name
3321 (insert " ")
3322 (js2-print-ast name 0))
3323 (insert "(")
3324 (cl-loop with len = (length params)
3325 for param in params
3326 for count from 1
3327 do
3328 (when (and rest-p (= count len))
3329 (insert "..."))
3330 (js2-print-ast param 0)
3331 (when (< count len)
3332 (insert ", ")))
3333 (insert ") ")
3334 (when arrow
3335 (insert "=> "))
3336 (insert "{")
3337 ;; TODO: fix this to be smarter about indenting, etc.
3338 (unless expr
3339 (insert "\n"))
3340 (if (js2-block-node-p body)
3341 (js2-print-body body (1+ i))
3342 (js2-print-ast body 0))
3343 (insert pad "}")
3344 (unless expr
3345 (insert "\n"))))
3346
3347 (defun js2-function-name (node)
3348 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3349 (and (js2-function-node-name node)
3350 (js2-name-node-name (js2-function-node-name node))))
3351
3352 ;; Having this be an expression node makes it more flexible.
3353 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3354 ;; that work better if you assume it's an expression. Whenever we have
3355 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3356 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3357 (cl-defstruct (js2-var-decl-node
3358 (:include js2-node)
3359 (:constructor nil)
3360 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3361 (pos (js2-current-token-beg))
3362 len kids
3363 decl-type)))
3364 "AST node for a variable declaration list (VAR, CONST or LET).
3365 The node bounds differ depending on the declaration type. For VAR or
3366 CONST declarations, the bounds include the var/const keyword. For LET
3367 declarations, the node begins at the position of the first child."
3368 kids ; a Lisp list of `js2-var-init-node' structs.
3369 decl-type) ; js2-VAR, js2-CONST or js2-LET
3370
3371 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3372 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3373
3374 (defun js2-visit-var-decl (n v)
3375 (dolist (kid (js2-var-decl-node-kids n))
3376 (js2-visit-ast kid v)))
3377
3378 (defun js2-print-var-decl (n i)
3379 (let ((pad (js2-make-pad i))
3380 (tt (js2-var-decl-node-decl-type n)))
3381 (insert pad)
3382 (insert (cond
3383 ((= tt js2-VAR) "var ")
3384 ((= tt js2-LET) "let ")
3385 ((= tt js2-CONST) "const ")
3386 (t
3387 (error "malformed var-decl node"))))
3388 (cl-loop with kids = (js2-var-decl-node-kids n)
3389 with len = (length kids)
3390 for kid in kids
3391 for count from 1
3392 do
3393 (js2-print-ast kid 0)
3394 (if (< count len)
3395 (insert ", ")))))
3396
3397 (cl-defstruct (js2-var-init-node
3398 (:include js2-node)
3399 (:constructor nil)
3400 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3401 (pos js2-ts-cursor)
3402 len target
3403 initializer)))
3404 "AST node for a variable declaration.
3405 The type field will be js2-CONST for a const decl."
3406 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3407 initializer) ; initializer expression, a `js2-node'
3408
3409 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3410 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3411
3412 (defun js2-visit-var-init-node (n v)
3413 (js2-visit-ast (js2-var-init-node-target n) v)
3414 (js2-visit-ast (js2-var-init-node-initializer n) v))
3415
3416 (defun js2-print-var-init-node (n i)
3417 (let ((pad (js2-make-pad i))
3418 (name (js2-var-init-node-target n))
3419 (init (js2-var-init-node-initializer n)))
3420 (insert pad)
3421 (js2-print-ast name 0)
3422 (when init
3423 (insert " = ")
3424 (js2-print-ast init 0))))
3425
3426 (cl-defstruct (js2-cond-node
3427 (:include js2-node)
3428 (:constructor nil)
3429 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3430 (pos js2-ts-cursor)
3431 len
3432 test-expr
3433 true-expr
3434 false-expr
3435 q-pos c-pos)))
3436 "AST node for the ternary operator"
3437 test-expr
3438 true-expr
3439 false-expr
3440 q-pos ; buffer position of ?
3441 c-pos) ; buffer position of :
3442
3443 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3444 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3445
3446 (defun js2-visit-cond-node (n v)
3447 (js2-visit-ast (js2-cond-node-test-expr n) v)
3448 (js2-visit-ast (js2-cond-node-true-expr n) v)
3449 (js2-visit-ast (js2-cond-node-false-expr n) v))
3450
3451 (defun js2-print-cond-node (n i)
3452 (let ((pad (js2-make-pad i)))
3453 (insert pad)
3454 (js2-print-ast (js2-cond-node-test-expr n) 0)
3455 (insert " ? ")
3456 (js2-print-ast (js2-cond-node-true-expr n) 0)
3457 (insert " : ")
3458 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3459
3460 (cl-defstruct (js2-infix-node
3461 (:include js2-node)
3462 (:constructor nil)
3463 (:constructor make-js2-infix-node (&key type
3464 (pos js2-ts-cursor)
3465 len op-pos
3466 left right)))
3467 "Represents infix expressions.
3468 Includes assignment ops like `|=', and the comma operator.
3469 The type field inherited from `js2-node' holds the operator."
3470 op-pos ; buffer position where operator begins
3471 left ; any `js2-node'
3472 right) ; any `js2-node'
3473
3474 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3475 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3476
3477 (defun js2-visit-infix-node (n v)
3478 (js2-visit-ast (js2-infix-node-left n) v)
3479 (js2-visit-ast (js2-infix-node-right n) v))
3480
3481 (defconst js2-operator-tokens
3482 (let ((table (make-hash-table :test 'eq))
3483 (tokens
3484 (list (cons js2-IN "in")
3485 (cons js2-TYPEOF "typeof")
3486 (cons js2-INSTANCEOF "instanceof")
3487 (cons js2-DELPROP "delete")
3488 (cons js2-COMMA ",")
3489 (cons js2-COLON ":")
3490 (cons js2-OR "||")
3491 (cons js2-AND "&&")
3492 (cons js2-INC "++")
3493 (cons js2-DEC "--")
3494 (cons js2-BITOR "|")
3495 (cons js2-BITXOR "^")
3496 (cons js2-BITAND "&")
3497 (cons js2-EQ "==")
3498 (cons js2-NE "!=")
3499 (cons js2-LT "<")
3500 (cons js2-LE "<=")
3501 (cons js2-GT ">")
3502 (cons js2-GE ">=")
3503 (cons js2-LSH "<<")
3504 (cons js2-RSH ">>")
3505 (cons js2-URSH ">>>")
3506 (cons js2-ADD "+") ; infix plus
3507 (cons js2-SUB "-") ; infix minus
3508 (cons js2-MUL "*")
3509 (cons js2-DIV "/")
3510 (cons js2-MOD "%")
3511 (cons js2-NOT "!")
3512 (cons js2-BITNOT "~")
3513 (cons js2-POS "+") ; unary plus
3514 (cons js2-NEG "-") ; unary minus
3515 (cons js2-TRIPLEDOT "...")
3516 (cons js2-SHEQ "===") ; shallow equality
3517 (cons js2-SHNE "!==") ; shallow inequality
3518 (cons js2-ASSIGN "=")
3519 (cons js2-ASSIGN_BITOR "|=")
3520 (cons js2-ASSIGN_BITXOR "^=")
3521 (cons js2-ASSIGN_BITAND "&=")
3522 (cons js2-ASSIGN_LSH "<<=")
3523 (cons js2-ASSIGN_RSH ">>=")
3524 (cons js2-ASSIGN_URSH ">>>=")
3525 (cons js2-ASSIGN_ADD "+=")
3526 (cons js2-ASSIGN_SUB "-=")
3527 (cons js2-ASSIGN_MUL "*=")
3528 (cons js2-ASSIGN_DIV "/=")
3529 (cons js2-ASSIGN_MOD "%="))))
3530 (cl-loop for (k . v) in tokens do
3531 (puthash k v table))
3532 table))
3533
3534 (defun js2-print-infix-node (n i)
3535 (let* ((tt (js2-node-type n))
3536 (op (gethash tt js2-operator-tokens)))
3537 (unless op
3538 (error "unrecognized infix operator %s" (js2-node-type n)))
3539 (insert (js2-make-pad i))
3540 (js2-print-ast (js2-infix-node-left n) 0)
3541 (unless (= tt js2-COMMA)
3542 (insert " "))
3543 (insert op)
3544 (insert " ")
3545 (js2-print-ast (js2-infix-node-right n) 0)))
3546
3547 (cl-defstruct (js2-assign-node
3548 (:include js2-infix-node)
3549 (:constructor nil)
3550 (:constructor make-js2-assign-node (&key type
3551 (pos js2-ts-cursor)
3552 len op-pos
3553 left right)))
3554 "Represents any assignment.
3555 The type field holds the actual assignment operator.")
3556
3557 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3558 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3559
3560 (cl-defstruct (js2-unary-node
3561 (:include js2-node)
3562 (:constructor nil)
3563 (:constructor make-js2-unary-node (&key type ; required
3564 (pos js2-ts-cursor)
3565 len operand)))
3566 "AST node type for unary operator nodes.
3567 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3568 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3569 property is added if the operator follows the operand."
3570 operand) ; a `js2-node' expression
3571
3572 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3573 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3574
3575 (defun js2-visit-unary-node (n v)
3576 (js2-visit-ast (js2-unary-node-operand n) v))
3577
3578 (defun js2-print-unary-node (n i)
3579 (let* ((tt (js2-node-type n))
3580 (op (gethash tt js2-operator-tokens))
3581 (postfix (js2-node-get-prop n 'postfix)))
3582 (unless op
3583 (error "unrecognized unary operator %s" tt))
3584 (insert (js2-make-pad i))
3585 (unless postfix
3586 (insert op))
3587 (if (or (= tt js2-TYPEOF)
3588 (= tt js2-DELPROP))
3589 (insert " "))
3590 (js2-print-ast (js2-unary-node-operand n) 0)
3591 (when postfix
3592 (insert op))))
3593
3594 (cl-defstruct (js2-let-node
3595 (:include js2-scope)
3596 (:constructor nil)
3597 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3598 (pos (js2-current-token-beg))
3599 len vars body
3600 lp rp)))
3601 "AST node for a let expression or a let statement.
3602 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3603 vars ; a `js2-var-decl-node'
3604 body ; a `js2-node' representing the expression or body block
3605 lp
3606 rp)
3607
3608 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3609 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3610
3611 (defun js2-visit-let-node (n v)
3612 (js2-visit-ast (js2-let-node-vars n) v)
3613 (js2-visit-ast (js2-let-node-body n) v))
3614
3615 (defun js2-print-let-node (n i)
3616 (insert (js2-make-pad i) "let (")
3617 (let ((p (point)))
3618 (js2-print-ast (js2-let-node-vars n) 0)
3619 (delete-region p (+ p 4)))
3620 (insert ") ")
3621 (js2-print-ast (js2-let-node-body n) i))
3622
3623 (cl-defstruct (js2-keyword-node
3624 (:include js2-node)
3625 (:constructor nil)
3626 (:constructor make-js2-keyword-node (&key type
3627 (pos (js2-current-token-beg))
3628 (len (- js2-ts-cursor pos)))))
3629 "AST node representing a literal keyword such as `null'.
3630 Used for `null', `this', `true', `false' and `debugger'.
3631 The node type is set to js2-NULL, js2-THIS, etc.")
3632
3633 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3634 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3635
3636 (defun js2-print-keyword-node (n i)
3637 (insert (js2-make-pad i)
3638 (let ((tt (js2-node-type n)))
3639 (cond
3640 ((= tt js2-THIS) "this")
3641 ((= tt js2-SUPER) "super")
3642 ((= tt js2-NULL) "null")
3643 ((= tt js2-TRUE) "true")
3644 ((= tt js2-FALSE) "false")
3645 ((= tt js2-DEBUGGER) "debugger")
3646 (t (error "Invalid keyword literal type: %d" tt))))))
3647
3648 (defsubst js2-this-or-super-node-p (node)
3649 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3650 (let ((type (js2-node-type node)))
3651 (or (eq type js2-THIS) (eq type js2-SUPER))))
3652
3653 (cl-defstruct (js2-new-node
3654 (:include js2-node)
3655 (:constructor nil)
3656 (:constructor make-js2-new-node (&key (type js2-NEW)
3657 (pos (js2-current-token-beg))
3658 len target
3659 args initializer
3660 lp rp)))
3661 "AST node for new-expression such as new Foo()."
3662 target ; an identifier or reference
3663 args ; a Lisp list of argument nodes
3664 lp ; position of left-paren, nil if omitted
3665 rp ; position of right-paren, nil if omitted
3666 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3667
3668 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3669 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3670
3671 (defun js2-visit-new-node (n v)
3672 (js2-visit-ast (js2-new-node-target n) v)
3673 (dolist (arg (js2-new-node-args n))
3674 (js2-visit-ast arg v))
3675 (js2-visit-ast (js2-new-node-initializer n) v))
3676
3677 (defun js2-print-new-node (n i)
3678 (insert (js2-make-pad i) "new ")
3679 (js2-print-ast (js2-new-node-target n))
3680 (insert "(")
3681 (js2-print-list (js2-new-node-args n))
3682 (insert ")")
3683 (when (js2-new-node-initializer n)
3684 (insert " ")
3685 (js2-print-ast (js2-new-node-initializer n))))
3686
3687 (cl-defstruct (js2-name-node
3688 (:include js2-node)
3689 (:constructor nil)
3690 (:constructor make-js2-name-node (&key (type js2-NAME)
3691 (pos (js2-current-token-beg))
3692 (len (- js2-ts-cursor
3693 (js2-current-token-beg)))
3694 (name (js2-current-token-string)))))
3695 "AST node for a JavaScript identifier"
3696 name ; a string
3697 scope) ; a `js2-scope' (optional, used for codegen)
3698
3699 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3700 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3701
3702 (defun js2-print-name-node (n i)
3703 (insert (js2-make-pad i)
3704 (js2-name-node-name n)))
3705
3706 (defsubst js2-name-node-length (node)
3707 "Return identifier length of NODE, a `js2-name-node'.
3708 Returns 0 if NODE is nil or its identifier field is nil."
3709 (if node
3710 (length (js2-name-node-name node))
3711 0))
3712
3713 (cl-defstruct (js2-number-node
3714 (:include js2-node)
3715 (:constructor nil)
3716 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3717 (pos (js2-current-token-beg))
3718 (len (- js2-ts-cursor
3719 (js2-current-token-beg)))
3720 (value (js2-current-token-string))
3721 (num-value (js2-token-number
3722 (js2-current-token))))))
3723 "AST node for a number literal."
3724 value ; the original string, e.g. "6.02e23"
3725 num-value) ; the parsed number value
3726
3727 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3728 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3729
3730 (defun js2-print-number-node (n i)
3731 (insert (js2-make-pad i)
3732 (number-to-string (js2-number-node-num-value n))))
3733
3734 (cl-defstruct (js2-regexp-node
3735 (:include js2-node)
3736 (:constructor nil)
3737 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3738 (pos (js2-current-token-beg))
3739 (len (- js2-ts-cursor
3740 (js2-current-token-beg)))
3741 value flags)))
3742 "AST node for a regular expression literal."
3743 value ; the regexp string, without // delimiters
3744 flags) ; a string of flags, e.g. `mi'.
3745
3746 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3747 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3748
3749 (defun js2-print-regexp (n i)
3750 (insert (js2-make-pad i)
3751 "/"
3752 (js2-regexp-node-value n)
3753 "/")
3754 (if (js2-regexp-node-flags n)
3755 (insert (js2-regexp-node-flags n))))
3756
3757 (cl-defstruct (js2-string-node
3758 (:include js2-node)
3759 (:constructor nil)
3760 (:constructor make-js2-string-node (&key (type js2-STRING)
3761 (pos (js2-current-token-beg))
3762 (len (- js2-ts-cursor
3763 (js2-current-token-beg)))
3764 (value (js2-current-token-string)))))
3765 "String literal.
3766 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3767 You can tell the quote type by looking at the first character."
3768 value) ; the characters of the string, including the quotes
3769
3770 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3771 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3772
3773 (defun js2-print-string-node (n i)
3774 (insert (js2-make-pad i)
3775 (js2-node-string n)))
3776
3777 (cl-defstruct (js2-template-node
3778 (:include js2-node)
3779 (:constructor nil)
3780 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3781 beg len kids)))
3782 "Template literal."
3783 kids) ; `js2-string-node' is used for string segments, other nodes
3784 ; for substitutions inside.
3785
3786 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3787 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3788
3789 (defun js2-visit-template (n callback)
3790 (dolist (kid (js2-template-node-kids n))
3791 (js2-visit-ast kid callback)))
3792
3793 (defun js2-print-template (n i)
3794 (insert (js2-make-pad i))
3795 (dolist (kid (js2-template-node-kids n))
3796 (if (js2-string-node-p kid)
3797 (insert (js2-node-string kid))
3798 (js2-print-ast kid))))
3799
3800 (cl-defstruct (js2-tagged-template-node
3801 (:include js2-node)
3802 (:constructor nil)
3803 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3804 beg len tag template)))
3805 "Tagged template literal."
3806 tag ; `js2-node' with the tag expression.
3807 template) ; `js2-template-node' with the template.
3808
3809 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3810 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3811
3812 (defun js2-visit-tagged-template (n callback)
3813 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3814 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3815
3816 (defun js2-print-tagged-template (n i)
3817 (insert (js2-make-pad i))
3818 (js2-print-ast (js2-tagged-template-node-tag n))
3819 (js2-print-ast (js2-tagged-template-node-template n)))
3820
3821 (cl-defstruct (js2-array-node
3822 (:include js2-node)
3823 (:constructor nil)
3824 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3825 (pos js2-ts-cursor)
3826 len elems)))
3827 "AST node for an array literal."
3828 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3829
3830 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3831 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3832
3833 (defun js2-visit-array-node (n v)
3834 (dolist (e (js2-array-node-elems n))
3835 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3836
3837 (defun js2-print-array-node (n i)
3838 (insert (js2-make-pad i) "[")
3839 (let ((elems (js2-array-node-elems n)))
3840 (js2-print-list elems)
3841 (when (and elems (null (car (last elems))))
3842 (insert ",")))
3843 (insert "]"))
3844
3845 (cl-defstruct (js2-class-node
3846 (:include js2-node)
3847 (:constructor nil)
3848 (:constructor make-js2-class-node (&key (type js2-CLASS)
3849 (pos js2-ts-cursor)
3850 (form 'CLASS_STATEMENT)
3851 (name "")
3852 extends len elems)))
3853 "AST node for an class expression.
3854 `elems' is a list of `js2-object-prop-node', and `extends' is an
3855 optional `js2-expr-node'"
3856 form ; CLASS_{STATEMENT|EXPRESSION}
3857 name ; class name (a `js2-node-name', or nil if anonymous)
3858 extends ; class heritage (a `js2-expr-node', or nil if none)
3859 elems)
3860
3861 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3862 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3863
3864 (defun js2-visit-class-node (n v)
3865 (js2-visit-ast (js2-class-node-name n) v)
3866 (js2-visit-ast (js2-class-node-extends n) v)
3867 (dolist (e (js2-class-node-elems n))
3868 (js2-visit-ast e v)))
3869
3870 (defun js2-print-class-node (n i)
3871 (let* ((pad (js2-make-pad i))
3872 (name (js2-class-node-name n))
3873 (extends (js2-class-node-extends n))
3874 (elems (js2-class-node-elems n)))
3875 (insert pad "class")
3876 (when name
3877 (insert " ")
3878 (js2-print-ast name 0))
3879 (when extends
3880 (insert " extends ")
3881 (js2-print-ast extends))
3882 (insert " {")
3883 (dolist (elem elems)
3884 (insert "\n")
3885 (if (js2-node-get-prop elem 'STATIC)
3886 (progn (insert (js2-make-pad (1+ i)) "static ")
3887 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3888 (js2-print-ast elem (1+ i))))
3889 (insert "\n" pad "}")))
3890
3891 (cl-defstruct (js2-object-node
3892 (:include js2-node)
3893 (:constructor nil)
3894 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3895 (pos js2-ts-cursor)
3896 len
3897 elems)))
3898 "AST node for an object literal expression.
3899 `elems' is a list of `js2-object-prop-node'."
3900 elems)
3901
3902 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3903 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3904
3905 (defun js2-visit-object-node (n v)
3906 (dolist (e (js2-object-node-elems n))
3907 (js2-visit-ast e v)))
3908
3909 (defun js2-print-object-node (n i)
3910 (insert (js2-make-pad i) "{")
3911 (js2-print-list (js2-object-node-elems n))
3912 (insert "}"))
3913
3914 (cl-defstruct (js2-object-prop-node
3915 (:include js2-infix-node)
3916 (:constructor nil)
3917 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3918 (pos js2-ts-cursor)
3919 len left
3920 right op-pos)))
3921 "AST node for an object literal prop:value entry.
3922 The `left' field is the property: a name node, string node or number node.
3923 The `right' field is a `js2-node' representing the initializer value.
3924 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3925 and both fields have the same value.")
3926
3927 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3928 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3929
3930 (defun js2-print-object-prop-node (n i)
3931 (let* ((left (js2-object-prop-node-left n))
3932 (computed (not (or (js2-string-node-p left)
3933 (js2-number-node-p left)
3934 (js2-name-node-p left)))))
3935 (insert (js2-make-pad i))
3936 (if computed
3937 (insert "["))
3938 (js2-print-ast left 0)
3939 (if computed
3940 (insert "]"))
3941 (if (not (js2-node-get-prop n 'SHORTHAND))
3942 (progn
3943 (insert ": ")
3944 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3945
3946 (cl-defstruct (js2-getter-setter-node
3947 (:include js2-infix-node)
3948 (:constructor nil)
3949 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3950 (pos js2-ts-cursor)
3951 len left right)))
3952 "AST node for a getter/setter property in an object literal.
3953 The `left' field is the `js2-name-node' naming the getter/setter prop.
3954 The `right' field is always an anonymous `js2-function-node' with a node
3955 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3956
3957 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3958 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3959
3960 (defun js2-print-getter-setter (n i)
3961 (let ((pad (js2-make-pad i))
3962 (left (js2-getter-setter-node-left n))
3963 (right (js2-getter-setter-node-right n)))
3964 (insert pad)
3965 (if (/= (js2-node-type n) js2-FUNCTION)
3966 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3967 (js2-print-ast left 0)
3968 (js2-print-ast right 0)))
3969
3970 (cl-defstruct (js2-prop-get-node
3971 (:include js2-infix-node)
3972 (:constructor nil)
3973 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3974 (pos js2-ts-cursor)
3975 len left right)))
3976 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3977
3978 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3979 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3980
3981 (defun js2-visit-prop-get-node (n v)
3982 (js2-visit-ast (js2-prop-get-node-left n) v)
3983 (js2-visit-ast (js2-prop-get-node-right n) v))
3984
3985 (defun js2-print-prop-get-node (n i)
3986 (insert (js2-make-pad i))
3987 (js2-print-ast (js2-prop-get-node-left n) 0)
3988 (insert ".")
3989 (js2-print-ast (js2-prop-get-node-right n) 0))
3990
3991 (cl-defstruct (js2-elem-get-node
3992 (:include js2-node)
3993 (:constructor nil)
3994 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3995 (pos js2-ts-cursor)
3996 len target element
3997 lb rb)))
3998 "AST node for an array index expression such as foo[bar]."
3999 target ; a `js2-node' - the expression preceding the "."
4000 element ; a `js2-node' - the expression in brackets
4001 lb ; position of left-bracket, nil if omitted
4002 rb) ; position of right-bracket, nil if omitted
4003
4004 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4005 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4006
4007 (defun js2-visit-elem-get-node (n v)
4008 (js2-visit-ast (js2-elem-get-node-target n) v)
4009 (js2-visit-ast (js2-elem-get-node-element n) v))
4010
4011 (defun js2-print-elem-get-node (n i)
4012 (insert (js2-make-pad i))
4013 (js2-print-ast (js2-elem-get-node-target n) 0)
4014 (insert "[")
4015 (js2-print-ast (js2-elem-get-node-element n) 0)
4016 (insert "]"))
4017
4018 (cl-defstruct (js2-call-node
4019 (:include js2-node)
4020 (:constructor nil)
4021 (:constructor make-js2-call-node (&key (type js2-CALL)
4022 (pos js2-ts-cursor)
4023 len target args
4024 lp rp)))
4025 "AST node for a JavaScript function call."
4026 target ; a `js2-node' evaluating to the function to call
4027 args ; a Lisp list of `js2-node' arguments
4028 lp ; position of open-paren, or nil if missing
4029 rp) ; position of close-paren, or nil if missing
4030
4031 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4032 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4033
4034 (defun js2-visit-call-node (n v)
4035 (js2-visit-ast (js2-call-node-target n) v)
4036 (dolist (arg (js2-call-node-args n))
4037 (js2-visit-ast arg v)))
4038
4039 (defun js2-print-call-node (n i)
4040 (insert (js2-make-pad i))
4041 (js2-print-ast (js2-call-node-target n) 0)
4042 (insert "(")
4043 (js2-print-list (js2-call-node-args n))
4044 (insert ")"))
4045
4046 (cl-defstruct (js2-yield-node
4047 (:include js2-node)
4048 (:constructor nil)
4049 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4050 (pos js2-ts-cursor)
4051 len value star-p)))
4052 "AST node for yield statement or expression."
4053 star-p ; whether it's yield*
4054 value) ; optional: value to be yielded
4055
4056 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4057 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4058
4059 (defun js2-visit-yield-node (n v)
4060 (js2-visit-ast (js2-yield-node-value n) v))
4061
4062 (defun js2-print-yield-node (n i)
4063 (insert (js2-make-pad i))
4064 (insert "yield")
4065 (when (js2-yield-node-star-p n)
4066 (insert "*"))
4067 (when (js2-yield-node-value n)
4068 (insert " ")
4069 (js2-print-ast (js2-yield-node-value n) 0)))
4070
4071 (cl-defstruct (js2-paren-node
4072 (:include js2-node)
4073 (:constructor nil)
4074 (:constructor make-js2-paren-node (&key (type js2-LP)
4075 (pos js2-ts-cursor)
4076 len expr)))
4077 "AST node for a parenthesized expression.
4078 In particular, used when the parens are syntactically optional,
4079 as opposed to required parens such as those enclosing an if-conditional."
4080 expr) ; `js2-node'
4081
4082 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4083 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4084
4085 (defun js2-visit-paren-node (n v)
4086 (js2-visit-ast (js2-paren-node-expr n) v))
4087
4088 (defun js2-print-paren-node (n i)
4089 (insert (js2-make-pad i))
4090 (insert "(")
4091 (js2-print-ast (js2-paren-node-expr n) 0)
4092 (insert ")"))
4093
4094 (cl-defstruct (js2-comp-node
4095 (:include js2-scope)
4096 (:constructor nil)
4097 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4098 (pos js2-ts-cursor)
4099 len result
4100 loops filters
4101 form)))
4102 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4103 result ; result expression (just after left-bracket)
4104 loops ; a Lisp list of `js2-comp-loop-node'
4105 filters ; a Lisp list of guard/filter expressions
4106 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4107 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4108 )
4109
4110 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4111 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4112
4113 (defun js2-visit-comp-node (n v)
4114 (js2-visit-ast (js2-comp-node-result n) v)
4115 (dolist (l (js2-comp-node-loops n))
4116 (js2-visit-ast l v))
4117 (dolist (f (js2-comp-node-filters n))
4118 (js2-visit-ast f v)))
4119
4120 (defun js2-print-comp-node (n i)
4121 (let ((pad (js2-make-pad i))
4122 (result (js2-comp-node-result n))
4123 (loops (js2-comp-node-loops n))
4124 (filters (js2-comp-node-filters n))
4125 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4126 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4127 (insert pad (if gen-p "(" "["))
4128 (when legacy-p
4129 (js2-print-ast result 0))
4130 (dolist (l loops)
4131 (when legacy-p
4132 (insert " "))
4133 (js2-print-ast l 0)
4134 (unless legacy-p
4135 (insert " ")))
4136 (dolist (f filters)
4137 (when legacy-p
4138 (insert " "))
4139 (insert "if (")
4140 (js2-print-ast f 0)
4141 (insert ")")
4142 (unless legacy-p
4143 (insert " ")))
4144 (unless legacy-p
4145 (js2-print-ast result 0))
4146 (insert (if gen-p ")" "]"))))
4147
4148 (cl-defstruct (js2-comp-loop-node
4149 (:include js2-for-in-node)
4150 (:constructor nil)
4151 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4152 (pos js2-ts-cursor)
4153 len iterator
4154 object in-pos
4155 foreach-p
4156 each-pos
4157 forof-p
4158 lp rp)))
4159 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4160
4161 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4162 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4163
4164 (defun js2-visit-comp-loop (n v)
4165 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4166 (js2-visit-ast (js2-comp-loop-node-object n) v))
4167
4168 (defun js2-print-comp-loop (n _i)
4169 (insert "for ")
4170 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4171 (insert "(")
4172 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4173 (insert (if (js2-comp-loop-node-forof-p n)
4174 " of " " in "))
4175 (js2-print-ast (js2-comp-loop-node-object n) 0)
4176 (insert ")"))
4177
4178 (cl-defstruct (js2-empty-expr-node
4179 (:include js2-node)
4180 (:constructor nil)
4181 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4182 (pos (js2-current-token-beg))
4183 len)))
4184 "AST node for an empty expression.")
4185
4186 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4187 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4188
4189 (cl-defstruct (js2-xml-node
4190 (:include js2-block-node)
4191 (:constructor nil)
4192 (:constructor make-js2-xml-node (&key (type js2-XML)
4193 (pos (js2-current-token-beg))
4194 len kids)))
4195 "AST node for initial parse of E4X literals.
4196 The kids field is a list of XML fragments, each a `js2-string-node' or
4197 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4198
4199 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4200 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4201
4202 (defun js2-print-xml-node (n i)
4203 (dolist (kid (js2-xml-node-kids n))
4204 (js2-print-ast kid i)))
4205
4206 (cl-defstruct (js2-xml-js-expr-node
4207 (:include js2-xml-node)
4208 (:constructor nil)
4209 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4210 (pos js2-ts-cursor)
4211 len expr)))
4212 "AST node for an embedded JavaScript {expression} in an E4X literal.
4213 The start and end fields correspond to the curly-braces."
4214 expr) ; a `js2-expr-node' of some sort
4215
4216 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4217 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4218
4219 (defun js2-visit-xml-js-expr (n v)
4220 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4221
4222 (defun js2-print-xml-js-expr (n i)
4223 (insert (js2-make-pad i))
4224 (insert "{")
4225 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4226 (insert "}"))
4227
4228 (cl-defstruct (js2-xml-dot-query-node
4229 (:include js2-infix-node)
4230 (:constructor nil)
4231 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4232 (pos js2-ts-cursor)
4233 op-pos len left
4234 right rp)))
4235 "AST node for an E4X foo.(bar) filter expression.
4236 Note that the left-paren is automatically the character immediately
4237 following the dot (.) in the operator. No whitespace is permitted
4238 between the dot and the lp by the scanner."
4239 rp)
4240
4241 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4242 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4243
4244 (defun js2-print-xml-dot-query (n i)
4245 (insert (js2-make-pad i))
4246 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4247 (insert ".(")
4248 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4249 (insert ")"))
4250
4251 (cl-defstruct (js2-xml-ref-node
4252 (:include js2-node)
4253 (:constructor nil)) ; abstract
4254 "Base type for E4X XML attribute-access or property-get expressions.
4255 Such expressions can take a variety of forms. The general syntax has
4256 three parts:
4257
4258 - (optional) an @ (specifying an attribute access)
4259 - (optional) a namespace (a `js2-name-node') and double-colon
4260 - (required) either a `js2-name-node' or a bracketed [expression]
4261
4262 The property-name expressions (examples: ns::name, @name) are
4263 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4264 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4265
4266 This node type (or more specifically, its subclasses) will sometimes
4267 be the right-hand child of a `js2-prop-get-node' or a
4268 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4269 The `js2-xml-ref-node' may also be a standalone primary expression with
4270 no explicit target, which is valid in certain expression contexts such as
4271
4272 company..employee.(@id < 100)
4273
4274 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4275 expression whose parent is a `js2-xml-dot-query-node'."
4276 namespace
4277 at-pos
4278 colon-pos)
4279
4280 (defsubst js2-xml-ref-node-attr-access-p (node)
4281 "Return non-nil if this expression began with an @-token."
4282 (and (numberp (js2-xml-ref-node-at-pos node))
4283 (cl-plusp (js2-xml-ref-node-at-pos node))))
4284
4285 (cl-defstruct (js2-xml-prop-ref-node
4286 (:include js2-xml-ref-node)
4287 (:constructor nil)
4288 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4289 (pos (js2-current-token-beg))
4290 len propname
4291 namespace at-pos
4292 colon-pos)))
4293 "AST node for an E4X XML [expr] property-ref expression.
4294 The JavaScript syntax is an optional @, an optional ns::, and a name.
4295
4296 [ '@' ] [ name '::' ] name
4297
4298 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4299 @ns::*, @*::attr, @*::*, and @*.
4300
4301 The node starts at the @ token, if present. Otherwise it starts at the
4302 namespace name. The node bounds extend through the closing right-bracket,
4303 or if it is missing due to a syntax error, through the end of the index
4304 expression."
4305 propname)
4306
4307 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4308 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4309
4310 (defun js2-visit-xml-prop-ref-node (n v)
4311 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4312 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4313
4314 (defun js2-print-xml-prop-ref-node (n i)
4315 (insert (js2-make-pad i))
4316 (if (js2-xml-ref-node-attr-access-p n)
4317 (insert "@"))
4318 (when (js2-xml-prop-ref-node-namespace n)
4319 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4320 (insert "::"))
4321 (if (js2-xml-prop-ref-node-propname n)
4322 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4323
4324 (cl-defstruct (js2-xml-elem-ref-node
4325 (:include js2-xml-ref-node)
4326 (:constructor nil)
4327 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4328 (pos (js2-current-token-beg))
4329 len expr lb rb
4330 namespace at-pos
4331 colon-pos)))
4332 "AST node for an E4X XML [expr] member-ref expression.
4333 Syntax:
4334
4335 [ '@' ] [ name '::' ] '[' expr ']'
4336
4337 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4338
4339 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4340 is not a legal E4X XML element-ref expression, since it's already used
4341 for standard JavaScript element-get array indexing. Hence, a
4342 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4343 non-nil namespace node, or both.
4344
4345 The node starts at the @ token, if present. Otherwise it starts
4346 at the namespace name. The node bounds extend through the closing
4347 right-bracket, or if it is missing due to a syntax error, through the
4348 end of the index expression."
4349 expr ; the bracketed index expression
4350 lb
4351 rb)
4352
4353 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4354 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4355
4356 (defun js2-visit-xml-elem-ref-node (n v)
4357 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4358 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4359
4360 (defun js2-print-xml-elem-ref-node (n i)
4361 (insert (js2-make-pad i))
4362 (if (js2-xml-ref-node-attr-access-p n)
4363 (insert "@"))
4364 (when (js2-xml-elem-ref-node-namespace n)
4365 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4366 (insert "::"))
4367 (insert "[")
4368 (if (js2-xml-elem-ref-node-expr n)
4369 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4370 (insert "]"))
4371
4372 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4373
4374 (cl-defstruct (js2-xml-start-tag-node
4375 (:include js2-xml-node)
4376 (:constructor nil)
4377 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4378 (pos js2-ts-cursor)
4379 len name attrs kids
4380 empty-p)))
4381 "AST node for an XML start-tag. Not currently used.
4382 The `kids' field is a Lisp list of child content nodes."
4383 name ; a `js2-xml-name-node'
4384 attrs ; a Lisp list of `js2-xml-attr-node'
4385 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4386
4387 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4388 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4389
4390 (defun js2-visit-xml-start-tag (n v)
4391 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4392 (dolist (attr (js2-xml-start-tag-node-attrs n))
4393 (js2-visit-ast attr v))
4394 (js2-visit-block n v))
4395
4396 (defun js2-print-xml-start-tag (n i)
4397 (insert (js2-make-pad i) "<")
4398 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4399 (when (js2-xml-start-tag-node-attrs n)
4400 (insert " ")
4401 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4402 (insert ">"))
4403
4404 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4405 ;; and add the end-tag to the kids list of the parent as well.
4406 (cl-defstruct (js2-xml-end-tag-node
4407 (:include js2-xml-node)
4408 (:constructor nil)
4409 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4410 (pos js2-ts-cursor)
4411 len name)))
4412 "AST node for an XML end-tag. Not currently used."
4413 name) ; a `js2-xml-name-node'
4414
4415 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4416 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4417
4418 (defun js2-visit-xml-end-tag (n v)
4419 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4420
4421 (defun js2-print-xml-end-tag (n i)
4422 (insert (js2-make-pad i))
4423 (insert "</")
4424 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4425 (insert ">"))
4426
4427 (cl-defstruct (js2-xml-name-node
4428 (:include js2-xml-node)
4429 (:constructor nil)
4430 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4431 (pos js2-ts-cursor)
4432 len namespace kids)))
4433 "AST node for an E4X XML name. Not currently used.
4434 Any XML name can be qualified with a namespace, hence the namespace field.
4435 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4436 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4437 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4438 namespace) ; a `js2-string-node'
4439
4440 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4441 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4442
4443 (defun js2-visit-xml-name-node (n v)
4444 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4445
4446 (defun js2-print-xml-name-node (n i)
4447 (insert (js2-make-pad i))
4448 (when (js2-xml-name-node-namespace n)
4449 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4450 (insert "::"))
4451 (dolist (kid (js2-xml-name-node-kids n))
4452 (js2-print-ast kid 0)))
4453
4454 (cl-defstruct (js2-xml-pi-node
4455 (:include js2-xml-node)
4456 (:constructor nil)
4457 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4458 (pos js2-ts-cursor)
4459 len name attrs)))
4460 "AST node for an E4X XML processing instruction. Not currently used."
4461 name ; a `js2-xml-name-node'
4462 attrs) ; a list of `js2-xml-attr-node'
4463
4464 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4465 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4466
4467 (defun js2-visit-xml-pi-node (n v)
4468 (js2-visit-ast (js2-xml-pi-node-name n) v)
4469 (dolist (attr (js2-xml-pi-node-attrs n))
4470 (js2-visit-ast attr v)))
4471
4472 (defun js2-print-xml-pi-node (n i)
4473 (insert (js2-make-pad i) "<?")
4474 (js2-print-ast (js2-xml-pi-node-name n))
4475 (when (js2-xml-pi-node-attrs n)
4476 (insert " ")
4477 (js2-print-list (js2-xml-pi-node-attrs n)))
4478 (insert "?>"))
4479
4480 (cl-defstruct (js2-xml-cdata-node
4481 (:include js2-xml-node)
4482 (:constructor nil)
4483 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4484 (pos js2-ts-cursor)
4485 len content)))
4486 "AST node for a CDATA escape section. Not currently used."
4487 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4488
4489 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4490 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4491
4492 (defun js2-visit-xml-cdata-node (n v)
4493 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4494
4495 (defun js2-print-xml-cdata-node (n i)
4496 (insert (js2-make-pad i))
4497 (js2-print-ast (js2-xml-cdata-node-content n)))
4498
4499 (cl-defstruct (js2-xml-attr-node
4500 (:include js2-xml-node)
4501 (:constructor nil)
4502 (:constructor make-js2-attr-node (&key (type js2-XML)
4503 (pos js2-ts-cursor)
4504 len name value
4505 eq-pos quote-type)))
4506 "AST node representing a foo='bar' XML attribute value. Not yet used."
4507 name ; a `js2-xml-name-node'
4508 value ; a `js2-xml-name-node'
4509 eq-pos ; buffer position of "=" sign
4510 quote-type) ; 'single or 'double
4511
4512 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4513 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4514
4515 (defun js2-visit-xml-attr-node (n v)
4516 (js2-visit-ast (js2-xml-attr-node-name n) v)
4517 (js2-visit-ast (js2-xml-attr-node-value n) v))
4518
4519 (defun js2-print-xml-attr-node (n i)
4520 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4521 "'"
4522 "\"")))
4523 (insert (js2-make-pad i))
4524 (js2-print-ast (js2-xml-attr-node-name n) 0)
4525 (insert "=" quote)
4526 (js2-print-ast (js2-xml-attr-node-value n) 0)
4527 (insert quote)))
4528
4529 (cl-defstruct (js2-xml-text-node
4530 (:include js2-xml-node)
4531 (:constructor nil)
4532 (:constructor make-js2-text-node (&key (type js2-XML)
4533 (pos js2-ts-cursor)
4534 len content)))
4535 "AST node for an E4X XML text node. Not currently used."
4536 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4537
4538 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4539 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4540
4541 (defun js2-visit-xml-text-node (n v)
4542 (js2-visit-ast (js2-xml-text-node-content n) v))
4543
4544 (defun js2-print-xml-text-node (n i)
4545 (insert (js2-make-pad i))
4546 (dolist (kid (js2-xml-text-node-content n))
4547 (js2-print-ast kid)))
4548
4549 (cl-defstruct (js2-xml-comment-node
4550 (:include js2-xml-node)
4551 (:constructor nil)
4552 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4553 (pos js2-ts-cursor)
4554 len)))
4555 "AST node for E4X XML comment. Not currently used.")
4556
4557 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4558 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4559
4560 (defun js2-print-xml-comment (n i)
4561 (insert (js2-make-pad i)
4562 (js2-node-string n)))
4563
4564 ;;; Node utilities
4565
4566 (defsubst js2-node-line (n)
4567 "Fetch the source line number at the start of node N.
4568 This is O(n) in the length of the source buffer; use prudently."
4569 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4570
4571 (defsubst js2-block-node-kid (n i)
4572 "Return child I of node N, or nil if there aren't that many."
4573 (nth i (js2-block-node-kids n)))
4574
4575 (defsubst js2-block-node-first (n)
4576 "Return first child of block node N, or nil if there is none."
4577 (cl-first (js2-block-node-kids n)))
4578
4579 (defun js2-node-root (n)
4580 "Return the root of the AST containing N.
4581 If N has no parent pointer, returns N."
4582 (let ((parent (js2-node-parent n)))
4583 (if parent
4584 (js2-node-root parent)
4585 n)))
4586
4587 (defsubst js2-node-short-name (n)
4588 "Return the short name of node N as a string, e.g. `js2-if-node'."
4589 (substring (symbol-name (aref n 0))
4590 (length "cl-struct-")))
4591
4592 (defun js2-node-child-list (node)
4593 "Return the child list for NODE, a Lisp list of nodes.
4594 Works for block nodes, array nodes, obj literals, funarg lists,
4595 var decls and try nodes (for catch clauses). Note that you should call
4596 `js2-block-node-kids' on the function body for the body statements.
4597 Returns nil for zero-length child lists or unsupported nodes."
4598 (cond
4599 ((js2-function-node-p node)
4600 (js2-function-node-params node))
4601 ((js2-block-node-p node)
4602 (js2-block-node-kids node))
4603 ((js2-try-node-p node)
4604 (js2-try-node-catch-clauses node))
4605 ((js2-array-node-p node)
4606 (js2-array-node-elems node))
4607 ((js2-object-node-p node)
4608 (js2-object-node-elems node))
4609 ((js2-call-node-p node)
4610 (js2-call-node-args node))
4611 ((js2-new-node-p node)
4612 (js2-new-node-args node))
4613 ((js2-var-decl-node-p node)
4614 (js2-var-decl-node-kids node))
4615 (t
4616 nil)))
4617
4618 (defun js2-node-set-child-list (node kids)
4619 "Set the child list for NODE to KIDS."
4620 (cond
4621 ((js2-function-node-p node)
4622 (setf (js2-function-node-params node) kids))
4623 ((js2-block-node-p node)
4624 (setf (js2-block-node-kids node) kids))
4625 ((js2-try-node-p node)
4626 (setf (js2-try-node-catch-clauses node) kids))
4627 ((js2-array-node-p node)
4628 (setf (js2-array-node-elems node) kids))
4629 ((js2-object-node-p node)
4630 (setf (js2-object-node-elems node) kids))
4631 ((js2-call-node-p node)
4632 (setf (js2-call-node-args node) kids))
4633 ((js2-new-node-p node)
4634 (setf (js2-new-node-args node) kids))
4635 ((js2-var-decl-node-p node)
4636 (setf (js2-var-decl-node-kids node) kids))
4637 (t
4638 (error "Unsupported node type: %s" (js2-node-short-name node))))
4639 kids)
4640
4641 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4642 (defconst js2-paren-expr-nodes
4643 '(cl-struct-js2-comp-loop-node
4644 cl-struct-js2-comp-node
4645 cl-struct-js2-call-node
4646 cl-struct-js2-catch-node
4647 cl-struct-js2-do-node
4648 cl-struct-js2-elem-get-node
4649 cl-struct-js2-for-in-node
4650 cl-struct-js2-for-node
4651 cl-struct-js2-function-node
4652 cl-struct-js2-if-node
4653 cl-struct-js2-let-node
4654 cl-struct-js2-new-node
4655 cl-struct-js2-paren-node
4656 cl-struct-js2-switch-node
4657 cl-struct-js2-while-node
4658 cl-struct-js2-with-node
4659 cl-struct-js2-xml-dot-query-node)
4660 "Node types that can have a parenthesized child expression.
4661 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4662
4663 (defsubst js2-paren-expr-node-p (node)
4664 "Return t for nodes that typically have a parenthesized child expression.
4665 Useful for computing the indentation anchors for arg-lists and conditions.
4666 Note that it may return a false positive, for instance when NODE is
4667 a `js2-new-node' and there are no arguments or parentheses."
4668 (memq (aref node 0) js2-paren-expr-nodes))
4669
4670 ;; Fake polymorphism... yech.
4671 (defun js2-node-lp (node)
4672 "Return relative left-paren position for NODE, if applicable.
4673 For `js2-elem-get-node' structs, returns left-bracket position.
4674 Note that the position may be nil in the case of a parse error."
4675 (cond
4676 ((js2-elem-get-node-p node)
4677 (js2-elem-get-node-lb node))
4678 ((js2-loop-node-p node)
4679 (js2-loop-node-lp node))
4680 ((js2-function-node-p node)
4681 (js2-function-node-lp node))
4682 ((js2-if-node-p node)
4683 (js2-if-node-lp node))
4684 ((js2-new-node-p node)
4685 (js2-new-node-lp node))
4686 ((js2-call-node-p node)
4687 (js2-call-node-lp node))
4688 ((js2-paren-node-p node)
4689 0)
4690 ((js2-switch-node-p node)
4691 (js2-switch-node-lp node))
4692 ((js2-catch-node-p node)
4693 (js2-catch-node-lp node))
4694 ((js2-let-node-p node)
4695 (js2-let-node-lp node))
4696 ((js2-comp-node-p node)
4697 0)
4698 ((js2-with-node-p node)
4699 (js2-with-node-lp node))
4700 ((js2-xml-dot-query-node-p node)
4701 (1+ (js2-infix-node-op-pos node)))
4702 (t
4703 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4704
4705 ;; Fake polymorphism... blech.
4706 (defun js2-node-rp (node)
4707 "Return relative right-paren position for NODE, if applicable.
4708 For `js2-elem-get-node' structs, returns right-bracket position.
4709 Note that the position may be nil in the case of a parse error."
4710 (cond
4711 ((js2-elem-get-node-p node)
4712 (js2-elem-get-node-rb node))
4713 ((js2-loop-node-p node)
4714 (js2-loop-node-rp node))
4715 ((js2-function-node-p node)
4716 (js2-function-node-rp node))
4717 ((js2-if-node-p node)
4718 (js2-if-node-rp node))
4719 ((js2-new-node-p node)
4720 (js2-new-node-rp node))
4721 ((js2-call-node-p node)
4722 (js2-call-node-rp node))
4723 ((js2-paren-node-p node)
4724 (1- (js2-node-len node)))
4725 ((js2-switch-node-p node)
4726 (js2-switch-node-rp node))
4727 ((js2-catch-node-p node)
4728 (js2-catch-node-rp node))
4729 ((js2-let-node-p node)
4730 (js2-let-node-rp node))
4731 ((js2-comp-node-p node)
4732 (1- (js2-node-len node)))
4733 ((js2-with-node-p node)
4734 (js2-with-node-rp node))
4735 ((js2-xml-dot-query-node-p node)
4736 (1+ (js2-xml-dot-query-node-rp node)))
4737 (t
4738 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4739
4740 (defsubst js2-node-first-child (node)
4741 "Return the first element of `js2-node-child-list' for NODE."
4742 (car (js2-node-child-list node)))
4743
4744 (defsubst js2-node-last-child (node)
4745 "Return the last element of `js2-node-last-child' for NODE."
4746 (car (last (js2-node-child-list node))))
4747
4748 (defun js2-node-prev-sibling (node)
4749 "Return the previous statement in parent.
4750 Works for parents supported by `js2-node-child-list'.
4751 Returns nil if NODE is not in the parent, or PARENT is
4752 not a supported node, or if NODE is the first child."
4753 (let* ((p (js2-node-parent node))
4754 (kids (js2-node-child-list p))
4755 (sib (car kids)))
4756 (while (and kids
4757 (not (eq node (cadr kids))))
4758 (setq kids (cdr kids)
4759 sib (car kids)))
4760 sib))
4761
4762 (defun js2-node-next-sibling (node)
4763 "Return the next statement in parent block.
4764 Returns nil if NODE is not in the block, or PARENT is not
4765 a block node, or if NODE is the last statement."
4766 (let* ((p (js2-node-parent node))
4767 (kids (js2-node-child-list p)))
4768 (while (and kids
4769 (not (eq node (car kids))))
4770 (setq kids (cdr kids)))
4771 (cadr kids)))
4772
4773 (defun js2-node-find-child-before (pos parent &optional after)
4774 "Find the last child that starts before POS in parent.
4775 If AFTER is non-nil, returns first child starting after POS.
4776 POS is an absolute buffer position. PARENT is any node
4777 supported by `js2-node-child-list'.
4778 Returns nil if no applicable child is found."
4779 (let ((kids (if (js2-function-node-p parent)
4780 (js2-block-node-kids (js2-function-node-body parent))
4781 (js2-node-child-list parent)))
4782 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4783 (js2-function-node-body parent)
4784 parent)))
4785 kid result fn
4786 (continue t))
4787 (setq fn (if after '>= '<))
4788 (while (and kids continue)
4789 (setq kid (car kids))
4790 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4791 (setq result kid
4792 continue (not after))
4793 (setq continue after))
4794 (setq kids (cdr kids)))
4795 result))
4796
4797 (defun js2-node-find-child-after (pos parent)
4798 "Find first child that starts after POS in parent.
4799 POS is an absolute buffer position. PARENT is any node
4800 supported by `js2-node-child-list'.
4801 Returns nil if no applicable child is found."
4802 (js2-node-find-child-before pos parent 'after))
4803
4804 (defun js2-node-replace-child (pos parent new-node)
4805 "Replace node at index POS in PARENT with NEW-NODE.
4806 Only works for parents supported by `js2-node-child-list'."
4807 (let ((kids (js2-node-child-list parent))
4808 (i 0))
4809 (while (< i pos)
4810 (setq kids (cdr kids)
4811 i (1+ i)))
4812 (setcar kids new-node)
4813 (js2-node-add-children parent new-node)))
4814
4815 (defun js2-node-buffer (n)
4816 "Return the buffer associated with AST N.
4817 Returns nil if the buffer is not set as a property on the root
4818 node, or if parent links were not recorded during parsing."
4819 (let ((root (js2-node-root n)))
4820 (and root
4821 (js2-ast-root-p root)
4822 (js2-ast-root-buffer root))))
4823
4824 (defun js2-block-node-push (n kid)
4825 "Push js2-node KID onto the end of js2-block-node N's child list.
4826 KID is always added to the -end- of the kids list.
4827 Function also calls `js2-node-add-children' to add the parent link."
4828 (let ((kids (js2-node-child-list n)))
4829 (if kids
4830 (setcdr kids (nconc (cdr kids) (list kid)))
4831 (js2-node-set-child-list n (list kid)))
4832 (js2-node-add-children n kid)))
4833
4834 (defun js2-node-string (node)
4835 (with-current-buffer (or (js2-node-buffer node)
4836 (error "No buffer available for node %s" node))
4837 (let ((pos (js2-node-abs-pos node)))
4838 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4839
4840 ;; Container for storing the node we're looking for in a traversal.
4841 (js2-deflocal js2-discovered-node nil)
4842
4843 ;; Keep track of absolute node position during traversals.
4844 (js2-deflocal js2-visitor-offset nil)
4845
4846 (js2-deflocal js2-node-search-point nil)
4847
4848 (when js2-mode-dev-mode-p
4849 (defun js2-find-node-at-point ()
4850 (interactive)
4851 (let ((node (js2-node-at-point)))
4852 (message "%s" (or node "No node found at point"))))
4853 (defun js2-node-name-at-point ()
4854 (interactive)
4855 (let ((node (js2-node-at-point)))
4856 (message "%s" (if node
4857 (js2-node-short-name node)
4858 "No node found at point.")))))
4859
4860 (defun js2-node-at-point (&optional pos skip-comments)
4861 "Return AST node at POS, a buffer position, defaulting to current point.
4862 The `js2-mode-ast' variable must be set to the current parse tree.
4863 Signals an error if the AST (`js2-mode-ast') is nil.
4864 Always returns a node - if it can't find one, it returns the root.
4865 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4866 (let ((ast js2-mode-ast)
4867 result)
4868 (unless ast
4869 (error "No JavaScript AST available"))
4870 ;; Look through comments first, since they may be inside nodes that
4871 ;; would otherwise report a match.
4872 (setq pos (or pos (point))
4873 result (if (> pos (js2-node-abs-end ast))
4874 ast
4875 (if (not skip-comments)
4876 (js2-comment-at-point pos))))
4877 (unless result
4878 (setq js2-discovered-node nil
4879 js2-visitor-offset 0
4880 js2-node-search-point pos)
4881 (unwind-protect
4882 (catch 'js2-visit-done
4883 (js2-visit-ast ast #'js2-node-at-point-visitor))
4884 (setq js2-visitor-offset nil
4885 js2-node-search-point nil))
4886 (setq result js2-discovered-node))
4887 ;; may have found a comment beyond end of last child node,
4888 ;; since visiting the ast-root looks at the comment-list last.
4889 (if (and skip-comments
4890 (js2-comment-node-p result))
4891 (setq result nil))
4892 (or result js2-mode-ast)))
4893
4894 (defun js2-node-at-point-visitor (node end-p)
4895 (let ((rel-pos (js2-node-pos node))
4896 abs-pos
4897 abs-end
4898 (point js2-node-search-point))
4899 (cond
4900 (end-p
4901 ;; this evaluates to a non-nil return value, even if it's zero
4902 (cl-decf js2-visitor-offset rel-pos))
4903 ;; we already looked for comments before visiting, and don't want them now
4904 ((js2-comment-node-p node)
4905 nil)
4906 (t
4907 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4908 ;; we only want to use the node if the point is before
4909 ;; the last character position in the node, so we decrement
4910 ;; the absolute end by 1.
4911 abs-end (+ abs-pos (js2-node-len node) -1))
4912 (cond
4913 ;; If this node starts after search-point, stop the search.
4914 ((> abs-pos point)
4915 (throw 'js2-visit-done nil))
4916 ;; If this node ends before the search-point, don't check kids.
4917 ((> point abs-end)
4918 nil)
4919 (t
4920 ;; Otherwise point is within this node, possibly in a child.
4921 (setq js2-discovered-node node)
4922 t)))))) ; keep processing kids to look for more specific match
4923
4924 (defsubst js2-block-comment-p (node)
4925 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4926 (and (js2-comment-node-p node)
4927 (memq (js2-comment-node-format node) '(jsdoc block))))
4928
4929 ;; TODO: put the comments in a vector and binary-search them instead
4930 (defun js2-comment-at-point (&optional pos)
4931 "Look through scanned comment nodes for one containing POS.
4932 POS is a buffer position that defaults to current point.
4933 Function returns nil if POS was not in any comment node."
4934 (let ((ast js2-mode-ast)
4935 (x (or pos (point)))
4936 beg end)
4937 (unless ast
4938 (error "No JavaScript AST available"))
4939 (catch 'done
4940 ;; Comments are stored in lexical order.
4941 (dolist (comment (js2-ast-root-comments ast) nil)
4942 (setq beg (js2-node-abs-pos comment)
4943 end (+ beg (js2-node-len comment)))
4944 (if (and (>= x beg)
4945 (<= x end))
4946 (throw 'done comment))))))
4947
4948 (defun js2-mode-find-parent-fn (node)
4949 "Find function enclosing NODE.
4950 Returns nil if NODE is not inside a function."
4951 (setq node (js2-node-parent node))
4952 (while (and node (not (js2-function-node-p node)))
4953 (setq node (js2-node-parent node)))
4954 (and (js2-function-node-p node) node))
4955
4956 (defun js2-mode-find-enclosing-fn (node)
4957 "Find function or root enclosing NODE."
4958 (if (js2-ast-root-p node)
4959 node
4960 (setq node (js2-node-parent node))
4961 (while (not (or (js2-ast-root-p node)
4962 (js2-function-node-p node)))
4963 (setq node (js2-node-parent node)))
4964 node))
4965
4966 (defun js2-mode-find-enclosing-node (beg end)
4967 "Find node fully enclosing BEG and END."
4968 (let ((node (js2-node-at-point beg))
4969 pos
4970 (continue t))
4971 (while continue
4972 (if (or (js2-ast-root-p node)
4973 (and
4974 (<= (setq pos (js2-node-abs-pos node)) beg)
4975 (>= (+ pos (js2-node-len node)) end)))
4976 (setq continue nil)
4977 (setq node (js2-node-parent node))))
4978 node))
4979
4980 (defun js2-node-parent-script-or-fn (node)
4981 "Find script or function immediately enclosing NODE.
4982 If NODE is the ast-root, returns nil."
4983 (if (js2-ast-root-p node)
4984 nil
4985 (setq node (js2-node-parent node))
4986 (while (and node (not (or (js2-function-node-p node)
4987 (js2-script-node-p node))))
4988 (setq node (js2-node-parent node)))
4989 node))
4990
4991 (defun js2-node-is-descendant (node ancestor)
4992 "Return t if NODE is a descendant of ANCESTOR."
4993 (while (and node
4994 (not (eq node ancestor)))
4995 (setq node (js2-node-parent node)))
4996 node)
4997
4998 ;;; visitor infrastructure
4999
5000 (defun js2-visit-none (_node _callback)
5001 "Visitor for AST node that have no node children."
5002 nil)
5003
5004 (defun js2-print-none (_node _indent)
5005 "Visitor for AST node with no printed representation.")
5006
5007 (defun js2-print-body (node indent)
5008 "Print a statement, or a block without braces."
5009 (if (js2-block-node-p node)
5010 (dolist (kid (js2-block-node-kids node))
5011 (js2-print-ast kid indent))
5012 (js2-print-ast node indent)))
5013
5014 (defun js2-print-list (args &optional delimiter)
5015 (cl-loop with len = (length args)
5016 for arg in args
5017 for count from 1
5018 do
5019 (when arg (js2-print-ast arg 0))
5020 (if (< count len)
5021 (insert (or delimiter ", ")))))
5022
5023 (defun js2-print-tree (ast)
5024 "Prints an AST to the current buffer.
5025 Makes `js2-ast-parent-nodes' available to the printer functions."
5026 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5027 (js2-print-ast ast)))
5028
5029 (defun js2-print-ast (node &optional indent)
5030 "Helper function for printing AST nodes.
5031 Requires `js2-ast-parent-nodes' to be non-nil.
5032 You should use `js2-print-tree' instead of this function."
5033 (let ((printer (get (aref node 0) 'js2-printer))
5034 (i (or indent 0)))
5035 ;; TODO: wedge comments in here somewhere
5036 (if printer
5037 (funcall printer node i))))
5038
5039 (defconst js2-side-effecting-tokens
5040 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5041 (dolist (tt (list js2-ASSIGN
5042 js2-ASSIGN_ADD
5043 js2-ASSIGN_BITAND
5044 js2-ASSIGN_BITOR
5045 js2-ASSIGN_BITXOR
5046 js2-ASSIGN_DIV
5047 js2-ASSIGN_LSH
5048 js2-ASSIGN_MOD
5049 js2-ASSIGN_MUL
5050 js2-ASSIGN_RSH
5051 js2-ASSIGN_SUB
5052 js2-ASSIGN_URSH
5053 js2-BLOCK
5054 js2-BREAK
5055 js2-CALL
5056 js2-CATCH
5057 js2-CATCH_SCOPE
5058 js2-CLASS
5059 js2-CONST
5060 js2-CONTINUE
5061 js2-DEBUGGER
5062 js2-DEC
5063 js2-DELPROP
5064 js2-DEL_REF
5065 js2-DO
5066 js2-ELSE
5067 js2-EMPTY
5068 js2-ENTERWITH
5069 js2-EXPORT
5070 js2-EXPR_RESULT
5071 js2-FINALLY
5072 js2-FOR
5073 js2-FUNCTION
5074 js2-GOTO
5075 js2-IF
5076 js2-IFEQ
5077 js2-IFNE
5078 js2-IMPORT
5079 js2-INC
5080 js2-JSR
5081 js2-LABEL
5082 js2-LEAVEWITH
5083 js2-LET
5084 js2-LETEXPR
5085 js2-LOCAL_BLOCK
5086 js2-LOOP
5087 js2-NEW
5088 js2-REF_CALL
5089 js2-RETHROW
5090 js2-RETURN
5091 js2-RETURN_RESULT
5092 js2-SEMI
5093 js2-SETELEM
5094 js2-SETELEM_OP
5095 js2-SETNAME
5096 js2-SETPROP
5097 js2-SETPROP_OP
5098 js2-SETVAR
5099 js2-SET_REF
5100 js2-SET_REF_OP
5101 js2-SWITCH
5102 js2-TARGET
5103 js2-THROW
5104 js2-TRY
5105 js2-VAR
5106 js2-WHILE
5107 js2-WITH
5108 js2-WITHEXPR
5109 js2-YIELD))
5110 (aset tokens tt t))
5111 (if js2-instanceof-has-side-effects
5112 (aset tokens js2-INSTANCEOF t))
5113 tokens))
5114
5115 (defun js2-node-has-side-effects (node)
5116 "Return t if NODE has side effects."
5117 (when node ; makes it easier to handle malformed expressions
5118 (let ((tt (js2-node-type node)))
5119 (cond
5120 ;; This doubtless needs some work, since EXPR_VOID is used
5121 ;; in several ways in Rhino and I may not have caught them all.
5122 ;; I'll wait for people to notice incorrect warnings.
5123 ((and (= tt js2-EXPR_VOID)
5124 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5125 (let ((expr (js2-expr-stmt-node-expr node)))
5126 (or (js2-node-has-side-effects expr)
5127 (when (js2-string-node-p expr)
5128 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5129 ((= tt js2-COMMA)
5130 (js2-node-has-side-effects (js2-infix-node-right node)))
5131 ((or (= tt js2-AND)
5132 (= tt js2-OR))
5133 (or (js2-node-has-side-effects (js2-infix-node-right node))
5134 (js2-node-has-side-effects (js2-infix-node-left node))))
5135 ((= tt js2-HOOK)
5136 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5137 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5138 ((js2-paren-node-p node)
5139 (js2-node-has-side-effects (js2-paren-node-expr node)))
5140 ((= tt js2-ERROR) ; avoid cascaded error messages
5141 nil)
5142 (t
5143 (aref js2-side-effecting-tokens tt))))))
5144
5145 (defconst js2-stmt-node-types
5146 (list js2-BLOCK
5147 js2-BREAK
5148 js2-CONTINUE
5149 js2-DEFAULT ; e4x "default xml namespace" statement
5150 js2-DO
5151 js2-EXPORT
5152 js2-EXPR_RESULT
5153 js2-EXPR_VOID
5154 js2-FOR
5155 js2-IF
5156 js2-IMPORT
5157 js2-RETURN
5158 js2-SWITCH
5159 js2-THROW
5160 js2-TRY
5161 js2-WHILE
5162 js2-WITH)
5163 "Node types that only appear in statement contexts.
5164 The list does not include nodes that always appear as the child
5165 of another specific statement type, such as switch-cases,
5166 catch and finally blocks, and else-clauses. The list also excludes
5167 nodes like yield, let and var, which may appear in either expression
5168 or statement context, and in the latter context always have a
5169 `js2-expr-stmt-node' parent. Finally, the list does not include
5170 functions or scripts, which are treated separately from statements
5171 by the JavaScript parser and runtime.")
5172
5173 (defun js2-stmt-node-p (node)
5174 "Heuristic for figuring out if NODE is a statement.
5175 Some node types can appear in either an expression context or a
5176 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5177 For these node types in a statement context, the parent will be a
5178 `js2-expr-stmt-node'.
5179 Functions aren't included in the check."
5180 (memq (js2-node-type node) js2-stmt-node-types))
5181
5182 (defun js2-mode-find-first-stmt (node)
5183 "Search upward starting from NODE looking for a statement.
5184 For purposes of this function, a `js2-function-node' counts."
5185 (while (not (or (js2-stmt-node-p node)
5186 (js2-function-node-p node)))
5187 (setq node (js2-node-parent node)))
5188 node)
5189
5190 (defun js2-node-parent-stmt (node)
5191 "Return the node's first ancestor that is a statement.
5192 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5193 appearing in a statement context will have a parent that is a
5194 `js2-expr-stmt-node' that will be returned by this function."
5195 (let ((parent (js2-node-parent node)))
5196 (if (or (null parent)
5197 (js2-stmt-node-p parent)
5198 (and (js2-function-node-p parent)
5199 (not (eq (js2-function-node-form parent)
5200 'FUNCTION_EXPRESSION))))
5201 parent
5202 (js2-node-parent-stmt parent))))
5203
5204 ;; In the Mozilla Rhino sources, Roshan James writes:
5205 ;; Does consistent-return analysis on the function body when strict mode is
5206 ;; enabled.
5207 ;;
5208 ;; function (x) { return (x+1) }
5209 ;;
5210 ;; is ok, but
5211 ;;
5212 ;; function (x) { if (x < 0) return (x+1); }
5213 ;;
5214 ;; is not because the function can potentially return a value when the
5215 ;; condition is satisfied and if not, the function does not explicitly
5216 ;; return a value.
5217 ;;
5218 ;; This extends to checking mismatches such as "return" and "return <value>"
5219 ;; used in the same function. Warnings are not emitted if inconsistent
5220 ;; returns exist in code that can be statically shown to be unreachable.
5221 ;; Ex.
5222 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5223 ;;
5224 ;; emits no warning. However if the loop had a break statement, then a
5225 ;; warning would be emitted.
5226 ;;
5227 ;; The consistency analysis looks at control structures such as loops, ifs,
5228 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5229 ;; warns the user about an inconsistent set of termination possibilities.
5230 ;;
5231 ;; These flags enumerate the possible ways a statement/function can
5232 ;; terminate. These flags are used by endCheck() and by the Parser to
5233 ;; detect inconsistent return usage.
5234 ;;
5235 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5236 ;; able to execute (example: throw, continue)
5237 ;;
5238 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5239 ;; next one. Statement such as return dont. A compound statement may have
5240 ;; some branch that drops off control to the next statement.
5241 ;;
5242 ;; END_RETURNS indicates that the statement can return with no value.
5243 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5244 ;;
5245 ;; A compound statement such as
5246 ;; if (condition) {
5247 ;; return value;
5248 ;; }
5249 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5250
5251 (defconst js2-END_UNREACHED 0)
5252 (defconst js2-END_DROPS_OFF 1)
5253 (defconst js2-END_RETURNS 2)
5254 (defconst js2-END_RETURNS_VALUE 4)
5255 (defconst js2-END_YIELDS 8)
5256
5257 (defun js2-has-consistent-return-usage (node)
5258 "Check that every return usage in a function body is consistent.
5259 Returns t if the function satisfies strict mode requirement."
5260 (let ((n (js2-end-check node)))
5261 ;; either it doesn't return a value in any branch...
5262 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5263 ;; or it returns a value (or is unreached) at every branch
5264 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5265 js2-END_RETURNS
5266 js2-END_YIELDS)))))
5267
5268 (defun js2-end-check-if (node)
5269 "Ensure that return usage in then/else blocks is consistent.
5270 If there is no else block, then the return statement can fall through.
5271 Returns logical OR of END_* flags"
5272 (let ((th (js2-if-node-then-part node))
5273 (el (js2-if-node-else-part node)))
5274 (if (null th)
5275 js2-END_UNREACHED
5276 (logior (js2-end-check th) (if el
5277 (js2-end-check el)
5278 js2-END_DROPS_OFF)))))
5279
5280 (defun js2-end-check-switch (node)
5281 "Consistency of return statements is checked between the case statements.
5282 If there is no default, then the switch can fall through. If there is a
5283 default, we check to see if all code paths in the default return or if
5284 there is a code path that can fall through.
5285 Returns logical OR of END_* flags."
5286 (let ((rv js2-END_UNREACHED)
5287 default-case)
5288 ;; examine the cases
5289 (catch 'break
5290 (dolist (c (js2-switch-node-cases node))
5291 (if (js2-case-node-expr c)
5292 (js2-set-flag rv (js2-end-check-block c))
5293 (setq default-case c)
5294 (throw 'break nil))))
5295 ;; we don't care how the cases drop into each other
5296 (js2-clear-flag rv js2-END_DROPS_OFF)
5297 ;; examine the default
5298 (js2-set-flag rv (if default-case
5299 (js2-end-check default-case)
5300 js2-END_DROPS_OFF))
5301 rv))
5302
5303 (defun js2-end-check-try (node)
5304 "If the block has a finally, return consistency is checked in the
5305 finally block. If all code paths in the finally return, then the
5306 returns in the try-catch blocks don't matter. If there is a code path
5307 that does not return or if there is no finally block, the returns
5308 of the try and catch blocks are checked for mismatch.
5309 Returns logical OR of END_* flags."
5310 (let ((finally (js2-try-node-finally-block node))
5311 rv)
5312 ;; check the finally if it exists
5313 (setq rv (if finally
5314 (js2-end-check (js2-finally-node-body finally))
5315 js2-END_DROPS_OFF))
5316 ;; If the finally block always returns, then none of the returns
5317 ;; in the try or catch blocks matter.
5318 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5319 (js2-clear-flag rv js2-END_DROPS_OFF)
5320 ;; examine the try block
5321 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5322 ;; check each catch block
5323 (dolist (cb (js2-try-node-catch-clauses node))
5324 (js2-set-flag rv (js2-end-check cb))))
5325 rv))
5326
5327 (defun js2-end-check-loop (node)
5328 "Return statement in the loop body must be consistent.
5329 The default assumption for any kind of a loop is that it will eventually
5330 terminate. The only exception is a loop with a constant true condition.
5331 Code that follows such a loop is examined only if one can determine
5332 statically that there is a break out of the loop.
5333
5334 for(... ; ... ; ...) {}
5335 for(... in ... ) {}
5336 while(...) { }
5337 do { } while(...)
5338
5339 Returns logical OR of END_* flags."
5340 (let ((rv (js2-end-check (js2-loop-node-body node)))
5341 (condition (cond
5342 ((js2-while-node-p node)
5343 (js2-while-node-condition node))
5344 ((js2-do-node-p node)
5345 (js2-do-node-condition node))
5346 ((js2-for-node-p node)
5347 (js2-for-node-condition node)))))
5348
5349 ;; check to see if the loop condition is always true
5350 (if (and condition
5351 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5352 (js2-clear-flag rv js2-END_DROPS_OFF))
5353
5354 ;; look for effect of breaks
5355 (js2-set-flag rv (js2-node-get-prop node
5356 'CONTROL_BLOCK_PROP
5357 js2-END_UNREACHED))
5358 rv))
5359
5360 (defun js2-end-check-block (node)
5361 "A general block of code is examined statement by statement.
5362 If any statement (even a compound one) returns in all branches, then
5363 subsequent statements are not examined.
5364 Returns logical OR of END_* flags."
5365 (let* ((rv js2-END_DROPS_OFF)
5366 (kids (js2-block-node-kids node))
5367 (n (car kids)))
5368 ;; Check each statement. If the statement can continue onto the next
5369 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5370 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5371 (js2-clear-flag rv js2-END_DROPS_OFF)
5372 (js2-set-flag rv (js2-end-check n))
5373 (setq kids (cdr kids)
5374 n (car kids)))
5375 rv))
5376
5377 (defun js2-end-check-label (node)
5378 "A labeled statement implies that there may be a break to the label.
5379 The function processes the labeled statement and then checks the
5380 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5381 particular label.
5382 Returns logical OR of END_* flags."
5383 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5384 (logior rv (js2-node-get-prop node
5385 'CONTROL_BLOCK_PROP
5386 js2-END_UNREACHED))))
5387
5388 (defun js2-end-check-break (node)
5389 "When a break is encountered annotate the statement being broken
5390 out of by setting its CONTROL_BLOCK_PROP property.
5391 Returns logical OR of END_* flags."
5392 (and (js2-break-node-target node)
5393 (js2-node-set-prop (js2-break-node-target node)
5394 'CONTROL_BLOCK_PROP
5395 js2-END_DROPS_OFF))
5396 js2-END_UNREACHED)
5397
5398 (defun js2-end-check (node)
5399 "Examine the body of a function, doing a basic reachability analysis.
5400 Returns a combination of flags END_* flags that indicate
5401 how the function execution can terminate. These constitute only the
5402 pessimistic set of termination conditions. It is possible that at
5403 runtime certain code paths will never be actually taken. Hence this
5404 analysis will flag errors in cases where there may not be errors.
5405 Returns logical OR of END_* flags"
5406 (let (kid)
5407 (cond
5408 ((js2-break-node-p node)
5409 (js2-end-check-break node))
5410 ((js2-expr-stmt-node-p node)
5411 (if (setq kid (js2-expr-stmt-node-expr node))
5412 (js2-end-check kid)
5413 js2-END_DROPS_OFF))
5414 ((or (js2-continue-node-p node)
5415 (js2-throw-node-p node))
5416 js2-END_UNREACHED)
5417 ((js2-return-node-p node)
5418 (if (setq kid (js2-return-node-retval node))
5419 js2-END_RETURNS_VALUE
5420 js2-END_RETURNS))
5421 ((js2-loop-node-p node)
5422 (js2-end-check-loop node))
5423 ((js2-switch-node-p node)
5424 (js2-end-check-switch node))
5425 ((js2-labeled-stmt-node-p node)
5426 (js2-end-check-label node))
5427 ((js2-if-node-p node)
5428 (js2-end-check-if node))
5429 ((js2-try-node-p node)
5430 (js2-end-check-try node))
5431 ((js2-block-node-p node)
5432 (if (null (js2-block-node-kids node))
5433 js2-END_DROPS_OFF
5434 (js2-end-check-block node)))
5435 ((js2-yield-node-p node)
5436 js2-END_YIELDS)
5437 (t
5438 js2-END_DROPS_OFF))))
5439
5440 (defun js2-always-defined-boolean-p (node)
5441 "Check if NODE always evaluates to true or false in boolean context.
5442 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5443 nor always false."
5444 (let ((tt (js2-node-type node))
5445 num)
5446 (cond
5447 ((or (= tt js2-FALSE) (= tt js2-NULL))
5448 'ALWAYS_FALSE)
5449 ((= tt js2-TRUE)
5450 'ALWAYS_TRUE)
5451 ((= tt js2-NUMBER)
5452 (setq num (js2-number-node-num-value node))
5453 (if (and (not (eq num 0.0e+NaN))
5454 (not (zerop num)))
5455 'ALWAYS_TRUE
5456 'ALWAYS_FALSE))
5457 (t
5458 nil))))
5459
5460 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5461 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5462
5463 (defvar js2-tokens nil
5464 "List of all defined token names.") ; initialized in `js2-token-names'
5465
5466 (defconst js2-token-names
5467 (let* ((names (make-vector js2-num-tokens -1))
5468 (case-fold-search nil) ; only match js2-UPPER_CASE
5469 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5470 (cl-loop for sym in syms
5471 for i from 0
5472 do
5473 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5474 (not (boundp sym)))
5475 (aset names (symbol-value sym) ; code, e.g. 152
5476 (downcase
5477 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5478 (push sym js2-tokens)))
5479 names)
5480 "Vector mapping int values to token string names, sans `js2-' prefix.")
5481
5482 (defun js2-tt-name (tok)
5483 "Return a string name for TOK, a token symbol or code.
5484 Signals an error if it's not a recognized token."
5485 (let ((code tok))
5486 (if (symbolp tok)
5487 (setq code (symbol-value tok)))
5488 (if (eq code -1)
5489 "ERROR"
5490 (if (and (numberp code)
5491 (not (cl-minusp code))
5492 (< code js2-num-tokens))
5493 (aref js2-token-names code)
5494 (error "Invalid token: %s" code)))))
5495
5496 (defsubst js2-tt-sym (tok)
5497 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5498 (intern (js2-tt-name tok)))
5499
5500 (defconst js2-token-codes
5501 (let ((table (make-hash-table :test 'eq :size 256)))
5502 (cl-loop for name across js2-token-names
5503 for sym = (intern (concat "js2-" (upcase name)))
5504 do
5505 (puthash sym (symbol-value sym) table))
5506 ;; clean up a few that are "wrong" in Rhino's token codes
5507 (puthash 'js2-DELETE js2-DELPROP table)
5508 table)
5509 "Hashtable mapping token type symbols to their bytecodes.")
5510
5511 (defsubst js2-tt-code (sym)
5512 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5513 (or (gethash sym js2-token-codes)
5514 (error "Invalid token symbol: %s " sym))) ; signal code bug
5515
5516 (defun js2-report-scan-error (msg &optional no-throw beg len)
5517 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5518 (js2-report-error msg nil
5519 (or beg (js2-current-token-beg))
5520 (or len (js2-current-token-len)))
5521 (unless no-throw
5522 (throw 'return js2-ERROR)))
5523
5524 (defun js2-set-string-from-buffer (token)
5525 "Set `string' and `end' slots for TOKEN, return the string."
5526 (setf (js2-token-end token) js2-ts-cursor
5527 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5528
5529 ;; TODO: could potentially avoid a lot of consing by allocating a
5530 ;; char buffer the way Rhino does.
5531 (defsubst js2-add-to-string (c)
5532 (push c js2-ts-string-buffer))
5533
5534 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5535 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5536 ;; any other character: when it's not part of the current token, we
5537 ;; unget it, allowing it to be read again by the following call.
5538 (defsubst js2-unget-char ()
5539 (cl-decf js2-ts-cursor))
5540
5541 ;; Rhino distinguishes \r and \n line endings. We don't need to
5542 ;; because we only scan from Emacs buffers, which always use \n.
5543 (defun js2-get-char ()
5544 "Read and return the next character from the input buffer.
5545 Increments `js2-ts-lineno' if the return value is a newline char.
5546 Updates `js2-ts-cursor' to the point after the returned char.
5547 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5548 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5549 (let (c)
5550 ;; check for end of buffer
5551 (if (>= js2-ts-cursor (point-max))
5552 (setq js2-ts-hit-eof t
5553 js2-ts-cursor (1+ js2-ts-cursor)
5554 c js2-EOF_CHAR) ; return value
5555 ;; otherwise read next char
5556 (setq c (char-before (cl-incf js2-ts-cursor)))
5557 ;; if we read a newline, update counters
5558 (if (= c ?\n)
5559 (setq js2-ts-line-start js2-ts-cursor
5560 js2-ts-lineno (1+ js2-ts-lineno)))
5561 ;; TODO: skip over format characters
5562 c)))
5563
5564 (defun js2-read-unicode-escape ()
5565 "Read a \\uNNNN sequence from the input.
5566 Assumes the ?\ and ?u have already been read.
5567 Returns the unicode character, or nil if it wasn't a valid character.
5568 Doesn't change the values of any scanner variables."
5569 ;; I really wish I knew a better way to do this, but I can't
5570 ;; find the Emacs function that takes a 16-bit int and converts
5571 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5572 ;; Have to first check that it's 4 hex characters or it may stop
5573 ;; the read early.
5574 (ignore-errors
5575 (let ((s (buffer-substring-no-properties js2-ts-cursor
5576 (+ 4 js2-ts-cursor))))
5577 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5578 (read (concat "?\\u" s))))))
5579
5580 (defun js2-match-char (test)
5581 "Consume and return next character if it matches TEST, a character.
5582 Returns nil and consumes nothing if TEST is not the next character."
5583 (let ((c (js2-get-char)))
5584 (if (eq c test)
5585 t
5586 (js2-unget-char)
5587 nil)))
5588
5589 (defun js2-peek-char ()
5590 (prog1
5591 (js2-get-char)
5592 (js2-unget-char)))
5593
5594 (defun js2-identifier-start-p (c)
5595 "Is C a valid start to an ES5 Identifier?
5596 See http://es5.github.io/#x7.6"
5597 (or
5598 (memq c '(?$ ?_))
5599 (memq (get-char-code-property c 'general-category)
5600 ;; Letters
5601 '(Lu Ll Lt Lm Lo Nl))))
5602
5603 (defun js2-identifier-part-p (c)
5604 "Is C a valid part of an ES5 Identifier?
5605 See http://es5.github.io/#x7.6"
5606 (or
5607 (memq c '(?$ ?_ ?\u200c ?\u200d))
5608 (memq (get-char-code-property c 'general-category)
5609 '(;; Letters
5610 Lu Ll Lt Lm Lo Nl
5611 ;; Combining Marks
5612 Mn Mc
5613 ;; Digits
5614 Nd
5615 ;; Connector Punctuation
5616 Pc))))
5617
5618 (defun js2-alpha-p (c)
5619 (cond ((and (<= ?A c) (<= c ?Z)) t)
5620 ((and (<= ?a c) (<= c ?z)) t)
5621 (t nil)))
5622
5623 (defsubst js2-digit-p (c)
5624 (and (<= ?0 c) (<= c ?9)))
5625
5626 (defun js2-js-space-p (c)
5627 (if (<= c 127)
5628 (memq c '(#x20 #x9 #xB #xC #xD))
5629 (or
5630 (eq c #xA0)
5631 ;; TODO: change this nil to check for Unicode space character
5632 nil)))
5633
5634 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5635
5636 (defun js2-skip-line ()
5637 "Skip to end of line."
5638 (while (not (memq (js2-get-char) js2-eol-chars)))
5639 (js2-unget-char)
5640 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5641
5642 (defun js2-init-scanner (&optional buf line)
5643 "Create token stream for BUF starting on LINE.
5644 BUF defaults to `current-buffer' and LINE defaults to 1.
5645
5646 A buffer can only have one scanner active at a time, which yields
5647 dramatically simpler code than using a defstruct. If you need to
5648 have simultaneous scanners in a buffer, copy the regions to scan
5649 into temp buffers."
5650 (with-current-buffer (or buf (current-buffer))
5651 (setq js2-ts-dirty-line nil
5652 js2-ts-hit-eof nil
5653 js2-ts-line-start 0
5654 js2-ts-lineno (or line 1)
5655 js2-ts-line-end-char -1
5656 js2-ts-cursor (point-min)
5657 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5658 js2-ti-tokens-cursor 0
5659 js2-ti-lookahead 0
5660 js2-ts-is-xml-attribute nil
5661 js2-ts-xml-is-tag-content nil
5662 js2-ts-xml-open-tags-count 0
5663 js2-ts-string-buffer nil)))
5664
5665 ;; This function uses the cached op, string and number fields in
5666 ;; TokenStream; if getToken has been called since the passed token
5667 ;; was scanned, the op or string printed may be incorrect.
5668 (defun js2-token-to-string (token)
5669 ;; Not sure where this function is used in Rhino. Not tested.
5670 (if (not js2-debug-print-trees)
5671 ""
5672 (let ((name (js2-tt-name token)))
5673 (cond
5674 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5675 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5676 (concat name " `" (js2-current-token-string) "'"))
5677 ((eq token js2-NUMBER)
5678 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5679 (t
5680 name)))))
5681
5682 (defconst js2-keywords
5683 '(break
5684 case catch class const continue
5685 debugger default delete do
5686 else extends export
5687 false finally for function
5688 if in instanceof import
5689 let
5690 new null
5691 return
5692 super switch
5693 this throw true try typeof
5694 var void
5695 while with
5696 yield))
5697
5698 ;; Token names aren't exactly the same as the keywords, unfortunately.
5699 ;; E.g. delete is js2-DELPROP.
5700 (defconst js2-kwd-tokens
5701 (let ((table (make-vector js2-num-tokens nil))
5702 (tokens
5703 (list js2-BREAK
5704 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5705 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5706 js2-ELSE js2-EXPORT
5707 js2-ELSE js2-EXTENDS js2-EXPORT
5708 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5709 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5710 js2-LET
5711 js2-NEW js2-NULL
5712 js2-RETURN
5713 js2-SUPER js2-SWITCH
5714 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5715 js2-VAR
5716 js2-WHILE js2-WITH
5717 js2-YIELD)))
5718 (dolist (i tokens)
5719 (aset table i 'font-lock-keyword-face))
5720 (aset table js2-STRING 'font-lock-string-face)
5721 (aset table js2-REGEXP 'font-lock-string-face)
5722 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5723 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5724 (aset table js2-COMMENT 'font-lock-comment-face)
5725 (aset table js2-THIS 'font-lock-builtin-face)
5726 (aset table js2-SUPER 'font-lock-builtin-face)
5727 (aset table js2-VOID 'font-lock-constant-face)
5728 (aset table js2-NULL 'font-lock-constant-face)
5729 (aset table js2-TRUE 'font-lock-constant-face)
5730 (aset table js2-FALSE 'font-lock-constant-face)
5731 (aset table js2-NOT 'font-lock-negation-char-face)
5732 table)
5733 "Vector whose values are non-nil for tokens that are keywords.
5734 The values are default faces to use for highlighting the keywords.")
5735
5736 ;; FIXME: Support strict mode-only future reserved words, after we know
5737 ;; which parts scopes are in strict mode, and which are not.
5738 (defconst js2-reserved-words '(class enum export extends import static super)
5739 "Future reserved keywords in ECMAScript 5.1.")
5740
5741 (defconst js2-keyword-names
5742 (let ((table (make-hash-table :test 'equal)))
5743 (cl-loop for k in js2-keywords
5744 do (puthash
5745 (symbol-name k) ; instanceof
5746 (intern (concat "js2-"
5747 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5748 table))
5749 table)
5750 "JavaScript keywords by name, mapped to their symbols.")
5751
5752 (defconst js2-reserved-word-names
5753 (let ((table (make-hash-table :test 'equal)))
5754 (cl-loop for k in js2-reserved-words
5755 do
5756 (puthash (symbol-name k) 'js2-RESERVED table))
5757 table)
5758 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5759
5760 (defun js2-collect-string (buf)
5761 "Convert BUF, a list of chars, to a string.
5762 Reverses BUF before converting."
5763 (if buf
5764 (apply #'string (nreverse buf))
5765 ""))
5766
5767 (defun js2-string-to-keyword (s)
5768 "Return token for S, a string, if S is a keyword or reserved word.
5769 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5770 (or (gethash s js2-keyword-names)
5771 (gethash s js2-reserved-word-names)))
5772
5773 (defsubst js2-ts-set-char-token-bounds (token)
5774 "Used when next token is one character."
5775 (setf (js2-token-beg token) (1- js2-ts-cursor)
5776 (js2-token-end token) js2-ts-cursor))
5777
5778 (defsubst js2-ts-return (token type)
5779 "Update the `end' and `type' slots of TOKEN,
5780 then throw `return' with value TYPE."
5781 (setf (js2-token-end token) js2-ts-cursor
5782 (js2-token-type token) type)
5783 (throw 'return type))
5784
5785 (defun js2-x-digit-to-int (c accumulator)
5786 "Build up a hex number.
5787 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5788 corresponding number. Otherwise return -1."
5789 (catch 'return
5790 (catch 'check
5791 ;; Use 0..9 < A..Z < a..z
5792 (cond
5793 ((<= c ?9)
5794 (cl-decf c ?0)
5795 (if (<= 0 c)
5796 (throw 'check nil)))
5797 ((<= c ?F)
5798 (when (<= ?A c)
5799 (cl-decf c (- ?A 10))
5800 (throw 'check nil)))
5801 ((<= c ?f)
5802 (when (<= ?a c)
5803 (cl-decf c (- ?a 10))
5804 (throw 'check nil))))
5805 (throw 'return -1))
5806 (logior c (lsh accumulator 4))))
5807
5808 (defun js2-get-token (&optional modifier)
5809 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5810 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5811 next saved token.
5812
5813 This function will not return a newline (js2-EOL) - instead, it
5814 gobbles newlines until it finds a non-newline token. Call
5815 `js2-peek-token-or-eol' when you care about newlines.
5816
5817 This function will also not return a js2-COMMENT. Instead, it
5818 records comments found in `js2-scanned-comments'. If the token
5819 returned by this function immediately follows a jsdoc comment,
5820 the token is flagged as such."
5821 (if (zerop js2-ti-lookahead)
5822 (js2-get-token-internal modifier)
5823 (cl-decf js2-ti-lookahead)
5824 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5825 (let ((tt (js2-current-token-type)))
5826 (cl-assert (not (= tt js2-EOL)))
5827 tt)))
5828
5829 (defun js2-unget-token ()
5830 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5831 (cl-incf js2-ti-lookahead)
5832 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5833
5834 (defun js2-get-token-internal (modifier)
5835 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5836 (tt (js2-token-type token))
5837 saw-eol
5838 face)
5839 ;; process comments
5840 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5841 (if (= tt js2-EOL)
5842 (setq saw-eol t)
5843 (setq saw-eol nil)
5844 (when js2-record-comments
5845 (js2-record-comment token)))
5846 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5847 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5848 tt (js2-token-type token)))
5849
5850 (when saw-eol
5851 (setf (js2-token-follows-eol-p token) t))
5852
5853 ;; perform lexical fontification as soon as token is scanned
5854 (when js2-parse-ide-mode
5855 (cond
5856 ((cl-minusp tt)
5857 (js2-record-face 'js2-error token))
5858 ((setq face (aref js2-kwd-tokens tt))
5859 (js2-record-face face token))
5860 ((and (= tt js2-NAME)
5861 (equal (js2-token-string token) "undefined"))
5862 (js2-record-face 'font-lock-constant-face token))))
5863 tt))
5864
5865 (defsubst js2-string-to-number (str base)
5866 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5867 (condition-case nil
5868 (string-to-number str base)
5869 (overflow-error -1)))
5870
5871 (defun js2-get-token-internal-1 (modifier)
5872 "Return next JavaScript token type, an int such as js2-RETURN.
5873 During operation, creates an instance of `js2-token' struct, sets
5874 its relevant fields and puts it into `js2-ti-tokens'."
5875 (let (identifier-start
5876 is-unicode-escape-start c
5877 contains-escape escape-val str result base
5878 quote-char look-for-slash continue tt
5879 (token (js2-new-token 0)))
5880 (setq
5881 tt
5882 (catch 'return
5883 (when (eq modifier 'TEMPLATE_TAIL)
5884 (setf (js2-token-beg token) (1- js2-ts-cursor))
5885 (throw 'return (js2-get-string-or-template-token ?` token)))
5886 (while t
5887 ;; Eat whitespace, possibly sensitive to newlines.
5888 (setq continue t)
5889 (while continue
5890 (setq c (js2-get-char))
5891 (cond
5892 ((eq c js2-EOF_CHAR)
5893 (js2-unget-char)
5894 (js2-ts-set-char-token-bounds token)
5895 (throw 'return js2-EOF))
5896 ((eq c ?\n)
5897 (js2-ts-set-char-token-bounds token)
5898 (setq js2-ts-dirty-line nil)
5899 (throw 'return js2-EOL))
5900 ((not (js2-js-space-p c))
5901 (if (/= c ?-) ; in case end of HTML comment
5902 (setq js2-ts-dirty-line t))
5903 (setq continue nil))))
5904 ;; Assume the token will be 1 char - fixed up below.
5905 (js2-ts-set-char-token-bounds token)
5906 (when (eq c ?@)
5907 (throw 'return js2-XMLATTR))
5908 ;; identifier/keyword/instanceof?
5909 ;; watch out for starting with a <backslash>
5910 (cond
5911 ((eq c ?\\)
5912 (setq c (js2-get-char))
5913 (if (eq c ?u)
5914 (setq identifier-start t
5915 is-unicode-escape-start t
5916 js2-ts-string-buffer nil)
5917 (setq identifier-start nil)
5918 (js2-unget-char)
5919 (setq c ?\\)))
5920 (t
5921 (when (setq identifier-start (js2-identifier-start-p c))
5922 (setq js2-ts-string-buffer nil)
5923 (js2-add-to-string c))))
5924 (when identifier-start
5925 (setq contains-escape is-unicode-escape-start)
5926 (catch 'break
5927 (while t
5928 (if is-unicode-escape-start
5929 ;; strictly speaking we should probably push-back
5930 ;; all the bad characters if the <backslash>uXXXX
5931 ;; sequence is malformed. But since there isn't a
5932 ;; correct context(is there?) for a bad Unicode
5933 ;; escape sequence in an identifier, we can report
5934 ;; an error here.
5935 (progn
5936 (setq escape-val 0)
5937 (dotimes (_ 4)
5938 (setq c (js2-get-char)
5939 escape-val (js2-x-digit-to-int c escape-val))
5940 ;; Next check takes care of c < 0 and bad escape
5941 (if (cl-minusp escape-val)
5942 (throw 'break nil)))
5943 (if (cl-minusp escape-val)
5944 (js2-report-scan-error "msg.invalid.escape" t))
5945 (js2-add-to-string escape-val)
5946 (setq is-unicode-escape-start nil))
5947 (setq c (js2-get-char))
5948 (cond
5949 ((eq c ?\\)
5950 (setq c (js2-get-char))
5951 (if (eq c ?u)
5952 (setq is-unicode-escape-start t
5953 contains-escape t)
5954 (js2-report-scan-error "msg.illegal.character" t)))
5955 (t
5956 (if (or (eq c js2-EOF_CHAR)
5957 (not (js2-identifier-part-p c)))
5958 (throw 'break nil))
5959 (js2-add-to-string c))))))
5960 (js2-unget-char)
5961 (setf str (js2-collect-string js2-ts-string-buffer)
5962 (js2-token-end token) js2-ts-cursor)
5963 ;; FIXME: Invalid in ES5 and ES6, see
5964 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5965 ;; Probably should just drop this conditional.
5966 (unless contains-escape
5967 ;; OPT we shouldn't have to make a string (object!) to
5968 ;; check if it's a keyword.
5969 ;; Return the corresponding token if it's a keyword
5970 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5971 (setq result (js2-string-to-keyword str)))
5972 (if (and (< js2-language-version 170)
5973 (memq result '(js2-LET js2-YIELD)))
5974 ;; LET and YIELD are tokens only in 1.7 and later
5975 (setq result 'js2-NAME))
5976 (when (eq result 'js2-RESERVED)
5977 (setf (js2-token-string token) str))
5978 (throw 'return (js2-tt-code result))))
5979 ;; If we want to intern these as Rhino does, just use (intern str)
5980 (setf (js2-token-string token) str)
5981 (throw 'return js2-NAME)) ; end identifier/kwd check
5982 ;; is it a number?
5983 (when (or (js2-digit-p c)
5984 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5985 (setq js2-ts-string-buffer nil
5986 base 10)
5987 (when (eq c ?0)
5988 (setq c (js2-get-char))
5989 (cond
5990 ((or (eq c ?x) (eq c ?X))
5991 (setq base 16)
5992 (setq c (js2-get-char)))
5993 ((and (or (eq c ?b) (eq c ?B))
5994 (>= js2-language-version 200))
5995 (setq base 2)
5996 (setq c (js2-get-char)))
5997 ((and (or (eq c ?o) (eq c ?O))
5998 (>= js2-language-version 200))
5999 (setq base 8)
6000 (setq c (js2-get-char)))
6001 ((js2-digit-p c)
6002 (setq base 'maybe-8))
6003 (t
6004 (js2-add-to-string ?0))))
6005 (cond
6006 ((eq base 16)
6007 (if (> 0 (js2-x-digit-to-int c 0))
6008 (js2-report-scan-error "msg.missing.hex.digits")
6009 (while (<= 0 (js2-x-digit-to-int c 0))
6010 (js2-add-to-string c)
6011 (setq c (js2-get-char)))))
6012 ((eq base 2)
6013 (if (not (memq c '(?0 ?1)))
6014 (js2-report-scan-error "msg.missing.binary.digits")
6015 (while (memq c '(?0 ?1))
6016 (js2-add-to-string c)
6017 (setq c (js2-get-char)))))
6018 ((eq base 8)
6019 (if (or (> ?0 c) (< ?7 c))
6020 (js2-report-scan-error "msg.missing.octal.digits")
6021 (while (and (<= ?0 c) (>= ?7 c))
6022 (js2-add-to-string c)
6023 (setq c (js2-get-char)))))
6024 (t
6025 (while (and (<= ?0 c) (<= c ?9))
6026 ;; We permit 08 and 09 as decimal numbers, which
6027 ;; makes our behavior a superset of the ECMA
6028 ;; numeric grammar. We might not always be so
6029 ;; permissive, so we warn about it.
6030 (when (and (eq base 'maybe-8) (>= c ?8))
6031 (js2-report-warning "msg.bad.octal.literal"
6032 (if (eq c ?8) "8" "9"))
6033 (setq base 10))
6034 (js2-add-to-string c)
6035 (setq c (js2-get-char)))
6036 (when (eq base 'maybe-8)
6037 (setq base 8))))
6038 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6039 (when (eq c ?.)
6040 (cl-loop do
6041 (js2-add-to-string c)
6042 (setq c (js2-get-char))
6043 while (js2-digit-p c)))
6044 (when (memq c '(?e ?E))
6045 (js2-add-to-string c)
6046 (setq c (js2-get-char))
6047 (when (memq c '(?+ ?-))
6048 (js2-add-to-string c)
6049 (setq c (js2-get-char)))
6050 (unless (js2-digit-p c)
6051 (js2-report-scan-error "msg.missing.exponent" t))
6052 (cl-loop do
6053 (js2-add-to-string c)
6054 (setq c (js2-get-char))
6055 while (js2-digit-p c))))
6056 (js2-unget-char)
6057 (let ((str (js2-set-string-from-buffer token)))
6058 (setf (js2-token-number token)
6059 (js2-string-to-number str base)))
6060 (throw 'return js2-NUMBER))
6061 ;; is it a string?
6062 (when (or (memq c '(?\" ?\'))
6063 (and (>= js2-language-version 200)
6064 (= c ?`)))
6065 (throw 'return
6066 (js2-get-string-or-template-token c token)))
6067 (js2-ts-return token
6068 (cl-case c
6069 (?\;
6070 (throw 'return js2-SEMI))
6071 (?\[
6072 (throw 'return js2-LB))
6073 (?\]
6074 (throw 'return js2-RB))
6075 (?{
6076 (throw 'return js2-LC))
6077 (?}
6078 (throw 'return js2-RC))
6079 (?\(
6080 (throw 'return js2-LP))
6081 (?\)
6082 (throw 'return js2-RP))
6083 (?,
6084 (throw 'return js2-COMMA))
6085 (??
6086 (throw 'return js2-HOOK))
6087 (?:
6088 (if (js2-match-char ?:)
6089 js2-COLONCOLON
6090 (throw 'return js2-COLON)))
6091 (?.
6092 (if (js2-match-char ?.)
6093 (if (js2-match-char ?.)
6094 js2-TRIPLEDOT js2-DOTDOT)
6095 (if (js2-match-char ?\()
6096 js2-DOTQUERY
6097 (throw 'return js2-DOT))))
6098 (?|
6099 (if (js2-match-char ?|)
6100 (throw 'return js2-OR)
6101 (if (js2-match-char ?=)
6102 js2-ASSIGN_BITOR
6103 (throw 'return js2-BITOR))))
6104 (?^
6105 (if (js2-match-char ?=)
6106 js2-ASSIGN_BITOR
6107 (throw 'return js2-BITXOR)))
6108 (?&
6109 (if (js2-match-char ?&)
6110 (throw 'return js2-AND)
6111 (if (js2-match-char ?=)
6112 js2-ASSIGN_BITAND
6113 (throw 'return js2-BITAND))))
6114 (?=
6115 (if (js2-match-char ?=)
6116 (if (js2-match-char ?=)
6117 js2-SHEQ
6118 (throw 'return js2-EQ))
6119 (if (js2-match-char ?>)
6120 (js2-ts-return token js2-ARROW)
6121 (throw 'return js2-ASSIGN))))
6122 (?!
6123 (if (js2-match-char ?=)
6124 (if (js2-match-char ?=)
6125 js2-SHNE
6126 js2-NE)
6127 (throw 'return js2-NOT)))
6128 (?<
6129 ;; NB:treat HTML begin-comment as comment-till-eol
6130 (when (js2-match-char ?!)
6131 (when (js2-match-char ?-)
6132 (when (js2-match-char ?-)
6133 (js2-skip-line)
6134 (setf (js2-token-comment-type (js2-current-token)) 'html)
6135 (throw 'return js2-COMMENT)))
6136 (js2-unget-char))
6137 (if (js2-match-char ?<)
6138 (if (js2-match-char ?=)
6139 js2-ASSIGN_LSH
6140 js2-LSH)
6141 (if (js2-match-char ?=)
6142 js2-LE
6143 (throw 'return js2-LT))))
6144 (?>
6145 (if (js2-match-char ?>)
6146 (if (js2-match-char ?>)
6147 (if (js2-match-char ?=)
6148 js2-ASSIGN_URSH
6149 js2-URSH)
6150 (if (js2-match-char ?=)
6151 js2-ASSIGN_RSH
6152 js2-RSH))
6153 (if (js2-match-char ?=)
6154 js2-GE
6155 (throw 'return js2-GT))))
6156 (?*
6157 (if (js2-match-char ?=)
6158 js2-ASSIGN_MUL
6159 (throw 'return js2-MUL)))
6160 (?/
6161 ;; is it a // comment?
6162 (when (js2-match-char ?/)
6163 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6164 (js2-skip-line)
6165 (setf (js2-token-comment-type token) 'line)
6166 ;; include newline so highlighting goes to end of
6167 ;; window, if there actually is a newline; if we
6168 ;; hit eof, then implicitly there isn't
6169 (unless js2-ts-hit-eof
6170 (cl-incf (js2-token-end token)))
6171 (throw 'return js2-COMMENT))
6172 ;; is it a /* comment?
6173 (when (js2-match-char ?*)
6174 (setf look-for-slash nil
6175 (js2-token-beg token) (- js2-ts-cursor 2)
6176 (js2-token-comment-type token)
6177 (if (js2-match-char ?*)
6178 (progn
6179 (setq look-for-slash t)
6180 'jsdoc)
6181 'block))
6182 (while t
6183 (setq c (js2-get-char))
6184 (cond
6185 ((eq c js2-EOF_CHAR)
6186 (setf (js2-token-end token) (1- js2-ts-cursor))
6187 (js2-report-error "msg.unterminated.comment")
6188 (throw 'return js2-COMMENT))
6189 ((eq c ?*)
6190 (setq look-for-slash t))
6191 ((eq c ?/)
6192 (if look-for-slash
6193 (js2-ts-return token js2-COMMENT)))
6194 (t
6195 (setf look-for-slash nil
6196 (js2-token-end token) js2-ts-cursor)))))
6197 (if (js2-match-char ?=)
6198 js2-ASSIGN_DIV
6199 (throw 'return js2-DIV)))
6200 (?#
6201 (when js2-skip-preprocessor-directives
6202 (js2-skip-line)
6203 (setf (js2-token-comment-type token) 'preprocessor
6204 (js2-token-end token) js2-ts-cursor)
6205 (throw 'return js2-COMMENT))
6206 (throw 'return js2-ERROR))
6207 (?%
6208 (if (js2-match-char ?=)
6209 js2-ASSIGN_MOD
6210 (throw 'return js2-MOD)))
6211 (?~
6212 (throw 'return js2-BITNOT))
6213 (?+
6214 (if (js2-match-char ?=)
6215 js2-ASSIGN_ADD
6216 (if (js2-match-char ?+)
6217 js2-INC
6218 (throw 'return js2-ADD))))
6219 (?-
6220 (cond
6221 ((js2-match-char ?=)
6222 (setq c js2-ASSIGN_SUB))
6223 ((js2-match-char ?-)
6224 (unless js2-ts-dirty-line
6225 ;; treat HTML end-comment after possible whitespace
6226 ;; after line start as comment-until-eol
6227 (when (js2-match-char ?>)
6228 (js2-skip-line)
6229 (setf (js2-token-comment-type (js2-current-token)) 'html)
6230 (throw 'return js2-COMMENT)))
6231 (setq c js2-DEC))
6232 (t
6233 (setq c js2-SUB)))
6234 (setq js2-ts-dirty-line t)
6235 c)
6236 (otherwise
6237 (js2-report-scan-error "msg.illegal.character")))))))
6238 (setf (js2-token-type token) tt)
6239 token))
6240
6241 (defun js2-get-string-or-template-token (quote-char token)
6242 ;; We attempt to accumulate a string the fast way, by
6243 ;; building it directly out of the reader. But if there
6244 ;; are any escaped characters in the string, we revert to
6245 ;; building it out of a string buffer.
6246 (let ((c (js2-get-char))
6247 js2-ts-string-buffer
6248 nc c1 val escape-val)
6249 (catch 'break
6250 (while (/= c quote-char)
6251 (catch 'continue
6252 (when (eq c js2-EOF_CHAR)
6253 (js2-unget-char)
6254 (js2-report-error "msg.unterminated.string.lit")
6255 (throw 'break nil))
6256 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6257 (js2-unget-char)
6258 (js2-report-error "msg.unterminated.string.lit")
6259 (throw 'break nil))
6260 (when (eq c ?\\)
6261 ;; We've hit an escaped character
6262 (setq c (js2-get-char))
6263 (cl-case c
6264 (?b (setq c ?\b))
6265 (?f (setq c ?\f))
6266 (?n (setq c ?\n))
6267 (?r (setq c ?\r))
6268 (?t (setq c ?\t))
6269 (?v (setq c ?\v))
6270 (?u
6271 (setq c1 (js2-read-unicode-escape))
6272 (if js2-parse-ide-mode
6273 (if c1
6274 (progn
6275 ;; just copy the string in IDE-mode
6276 (js2-add-to-string ?\\)
6277 (js2-add-to-string ?u)
6278 (dotimes (_ 3)
6279 (js2-add-to-string (js2-get-char)))
6280 (setq c (js2-get-char))) ; added at end of loop
6281 ;; flag it as an invalid escape
6282 (js2-report-warning "msg.invalid.escape"
6283 nil (- js2-ts-cursor 2) 6))
6284 ;; Get 4 hex digits; if the u escape is not
6285 ;; followed by 4 hex digits, use 'u' + the
6286 ;; literal character sequence that follows.
6287 (js2-add-to-string ?u)
6288 (setq escape-val 0)
6289 (dotimes (_ 4)
6290 (setq c (js2-get-char)
6291 escape-val (js2-x-digit-to-int c escape-val))
6292 (if (cl-minusp escape-val)
6293 (throw 'continue nil))
6294 (js2-add-to-string c))
6295 ;; prepare for replace of stored 'u' sequence by escape value
6296 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6297 c escape-val)))
6298 (?x
6299 ;; Get 2 hex digits, defaulting to 'x'+literal
6300 ;; sequence, as above.
6301 (setq c (js2-get-char)
6302 escape-val (js2-x-digit-to-int c 0))
6303 (if (cl-minusp escape-val)
6304 (progn
6305 (js2-add-to-string ?x)
6306 (throw 'continue nil))
6307 (setq c1 c
6308 c (js2-get-char)
6309 escape-val (js2-x-digit-to-int c escape-val))
6310 (if (cl-minusp escape-val)
6311 (progn
6312 (js2-add-to-string ?x)
6313 (js2-add-to-string c1)
6314 (throw 'continue nil))
6315 ;; got 2 hex digits
6316 (setq c escape-val))))
6317 (?\n
6318 ;; Remove line terminator after escape to follow
6319 ;; SpiderMonkey and C/C++
6320 (setq c (js2-get-char))
6321 (throw 'continue nil))
6322 (t
6323 (when (and (<= ?0 c) (< c ?8))
6324 (setq val (- c ?0)
6325 c (js2-get-char))
6326 (when (and (<= ?0 c) (< c ?8))
6327 (setq val (- (+ (* 8 val) c) ?0)
6328 c (js2-get-char))
6329 (when (and (<= ?0 c)
6330 (< c ?8)
6331 (< val #o37))
6332 ;; c is 3rd char of octal sequence only
6333 ;; if the resulting val <= 0377
6334 (setq val (- (+ (* 8 val) c) ?0)
6335 c (js2-get-char))))
6336 (js2-unget-char)
6337 (setq c val)))))
6338 (when (and (eq quote-char ?`) (eq c ?$))
6339 (when (eq (setq nc (js2-get-char)) ?\{)
6340 (throw 'break nil))
6341 (js2-unget-char))
6342 (js2-add-to-string c)
6343 (setq c (js2-get-char)))))
6344 (js2-set-string-from-buffer token)
6345 (if (not (eq quote-char ?`))
6346 js2-STRING
6347 (if (and (eq c ?$) (eq nc ?\{))
6348 js2-TEMPLATE_HEAD
6349 js2-NO_SUBS_TEMPLATE))))
6350
6351 (defun js2-read-regexp (start-tt)
6352 "Called by parser when it gets / or /= in literal context."
6353 (let (c err
6354 in-class ; inside a '[' .. ']' character-class
6355 flags
6356 (continue t)
6357 (token (js2-new-token 0)))
6358 (setq js2-ts-string-buffer nil)
6359 (if (eq start-tt js2-ASSIGN_DIV)
6360 ;; mis-scanned /=
6361 (js2-add-to-string ?=)
6362 (if (not (eq start-tt js2-DIV))
6363 (error "failed assertion")))
6364 (while (and (not err)
6365 (or (/= (setq c (js2-get-char)) ?/)
6366 in-class))
6367 (cond
6368 ((or (= c ?\n)
6369 (= c js2-EOF_CHAR))
6370 (setf (js2-token-end token) (1- js2-ts-cursor)
6371 err t
6372 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6373 (js2-report-error "msg.unterminated.re.lit"))
6374 (t (cond
6375 ((= c ?\\)
6376 (js2-add-to-string c)
6377 (setq c (js2-get-char)))
6378 ((= c ?\[)
6379 (setq in-class t))
6380 ((= c ?\])
6381 (setq in-class nil)))
6382 (js2-add-to-string c))))
6383 (unless err
6384 (while continue
6385 (cond
6386 ((js2-match-char ?g)
6387 (push ?g flags))
6388 ((js2-match-char ?i)
6389 (push ?i flags))
6390 ((js2-match-char ?m)
6391 (push ?m flags))
6392 ((and (js2-match-char ?u)
6393 (>= js2-language-version 200))
6394 (push ?u flags))
6395 ((and (js2-match-char ?y)
6396 (>= js2-language-version 200))
6397 (push ?y flags))
6398 (t
6399 (setq continue nil))))
6400 (if (js2-alpha-p (js2-peek-char))
6401 (js2-report-scan-error "msg.invalid.re.flag" t
6402 js2-ts-cursor 1))
6403 (js2-set-string-from-buffer token))
6404 (js2-collect-string flags)))
6405
6406 (defun js2-get-first-xml-token ()
6407 (setq js2-ts-xml-open-tags-count 0
6408 js2-ts-is-xml-attribute nil
6409 js2-ts-xml-is-tag-content nil)
6410 (js2-unget-char)
6411 (js2-get-next-xml-token))
6412
6413 (defun js2-xml-discard-string (token)
6414 "Throw away the string in progress and flag an XML parse error."
6415 (setf js2-ts-string-buffer nil
6416 (js2-token-string token) nil)
6417 (js2-report-scan-error "msg.XML.bad.form" t))
6418
6419 (defun js2-get-next-xml-token ()
6420 (setq js2-ts-string-buffer nil) ; for recording the XML
6421 (let ((token (js2-new-token 0))
6422 c result)
6423 (setq result
6424 (catch 'return
6425 (while t
6426 (setq c (js2-get-char))
6427 (cond
6428 ((= c js2-EOF_CHAR)
6429 (throw 'return js2-ERROR))
6430 (js2-ts-xml-is-tag-content
6431 (cl-case c
6432 (?>
6433 (js2-add-to-string c)
6434 (setq js2-ts-xml-is-tag-content nil
6435 js2-ts-is-xml-attribute nil))
6436 (?/
6437 (js2-add-to-string c)
6438 (when (eq ?> (js2-peek-char))
6439 (setq c (js2-get-char))
6440 (js2-add-to-string c)
6441 (setq js2-ts-xml-is-tag-content nil)
6442 (cl-decf js2-ts-xml-open-tags-count)))
6443 (?{
6444 (js2-unget-char)
6445 (js2-set-string-from-buffer token)
6446 (throw 'return js2-XML))
6447 ((?\' ?\")
6448 (js2-add-to-string c)
6449 (unless (js2-read-quoted-string c token)
6450 (throw 'return js2-ERROR)))
6451 (?=
6452 (js2-add-to-string c)
6453 (setq js2-ts-is-xml-attribute t))
6454 ((? ?\t ?\r ?\n)
6455 (js2-add-to-string c))
6456 (t
6457 (js2-add-to-string c)
6458 (setq js2-ts-is-xml-attribute nil)))
6459 (when (and (not js2-ts-xml-is-tag-content)
6460 (zerop js2-ts-xml-open-tags-count))
6461 (js2-set-string-from-buffer token)
6462 (throw 'return js2-XMLEND)))
6463 (t
6464 ;; else not tag content
6465 (cl-case c
6466 (?<
6467 (js2-add-to-string c)
6468 (setq c (js2-peek-char))
6469 (cl-case c
6470 (?!
6471 (setq c (js2-get-char)) ;; skip !
6472 (js2-add-to-string c)
6473 (setq c (js2-peek-char))
6474 (cl-case c
6475 (?-
6476 (setq c (js2-get-char)) ;; skip -
6477 (js2-add-to-string c)
6478 (if (eq c ?-)
6479 (progn
6480 (js2-add-to-string c)
6481 (unless (js2-read-xml-comment token)
6482 (throw 'return js2-ERROR)))
6483 (js2-xml-discard-string token)
6484 (throw 'return js2-ERROR)))
6485 (?\[
6486 (setq c (js2-get-char)) ;; skip [
6487 (js2-add-to-string c)
6488 (if (and (= (js2-get-char) ?C)
6489 (= (js2-get-char) ?D)
6490 (= (js2-get-char) ?A)
6491 (= (js2-get-char) ?T)
6492 (= (js2-get-char) ?A)
6493 (= (js2-get-char) ?\[))
6494 (progn
6495 (js2-add-to-string ?C)
6496 (js2-add-to-string ?D)
6497 (js2-add-to-string ?A)
6498 (js2-add-to-string ?T)
6499 (js2-add-to-string ?A)
6500 (js2-add-to-string ?\[)
6501 (unless (js2-read-cdata token)
6502 (throw 'return js2-ERROR)))
6503 (js2-xml-discard-string token)
6504 (throw 'return js2-ERROR)))
6505 (t
6506 (unless (js2-read-entity token)
6507 (throw 'return js2-ERROR))))
6508 ;; Allow bare CDATA section, e.g.:
6509 ;; let xml = <![CDATA[ foo bar baz ]]>;
6510 (when (zerop js2-ts-xml-open-tags-count)
6511 (throw 'return js2-XMLEND)))
6512 (??
6513 (setq c (js2-get-char)) ;; skip ?
6514 (js2-add-to-string c)
6515 (unless (js2-read-PI token)
6516 (throw 'return js2-ERROR)))
6517 (?/
6518 ;; end tag
6519 (setq c (js2-get-char)) ;; skip /
6520 (js2-add-to-string c)
6521 (when (zerop js2-ts-xml-open-tags-count)
6522 (js2-xml-discard-string token)
6523 (throw 'return js2-ERROR))
6524 (setq js2-ts-xml-is-tag-content t)
6525 (cl-decf js2-ts-xml-open-tags-count))
6526 (t
6527 ;; start tag
6528 (setq js2-ts-xml-is-tag-content t)
6529 (cl-incf js2-ts-xml-open-tags-count))))
6530 (?{
6531 (js2-unget-char)
6532 (js2-set-string-from-buffer token)
6533 (throw 'return js2-XML))
6534 (t
6535 (js2-add-to-string c))))))))
6536 (setf (js2-token-end token) js2-ts-cursor)
6537 (setf (js2-token-type token) result)
6538 result))
6539
6540 (defun js2-read-quoted-string (quote token)
6541 (let (c)
6542 (catch 'return
6543 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6544 (js2-add-to-string c)
6545 (if (eq c quote)
6546 (throw 'return t)))
6547 (js2-xml-discard-string token) ;; throw away string in progress
6548 nil)))
6549
6550 (defun js2-read-xml-comment (token)
6551 (let ((c (js2-get-char)))
6552 (catch 'return
6553 (while (/= c js2-EOF_CHAR)
6554 (catch 'continue
6555 (js2-add-to-string c)
6556 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6557 (setq c (js2-get-char))
6558 (js2-add-to-string c)
6559 (if (eq (js2-peek-char) ?>)
6560 (progn
6561 (setq c (js2-get-char)) ;; skip >
6562 (js2-add-to-string c)
6563 (throw 'return t))
6564 (throw 'continue nil)))
6565 (setq c (js2-get-char))))
6566 (js2-xml-discard-string token)
6567 nil)))
6568
6569 (defun js2-read-cdata (token)
6570 (let ((c (js2-get-char)))
6571 (catch 'return
6572 (while (/= c js2-EOF_CHAR)
6573 (catch 'continue
6574 (js2-add-to-string c)
6575 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6576 (setq c (js2-get-char))
6577 (js2-add-to-string c)
6578 (if (eq (js2-peek-char) ?>)
6579 (progn
6580 (setq c (js2-get-char)) ;; Skip >
6581 (js2-add-to-string c)
6582 (throw 'return t))
6583 (throw 'continue nil)))
6584 (setq c (js2-get-char))))
6585 (js2-xml-discard-string token)
6586 nil)))
6587
6588 (defun js2-read-entity (token)
6589 (let ((decl-tags 1)
6590 c)
6591 (catch 'return
6592 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6593 (js2-add-to-string c)
6594 (cl-case c
6595 (?<
6596 (cl-incf decl-tags))
6597 (?>
6598 (cl-decf decl-tags)
6599 (if (zerop decl-tags)
6600 (throw 'return t)))))
6601 (js2-xml-discard-string token)
6602 nil)))
6603
6604 (defun js2-read-PI (token)
6605 "Scan an XML processing instruction."
6606 (let (c)
6607 (catch 'return
6608 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6609 (js2-add-to-string c)
6610 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6611 (setq c (js2-get-char)) ;; Skip >
6612 (js2-add-to-string c)
6613 (throw 'return t)))
6614 (js2-xml-discard-string token)
6615 nil)))
6616
6617 ;;; Highlighting
6618
6619 (defun js2-set-face (beg end face &optional record)
6620 "Fontify a region. If RECORD is non-nil, record for later."
6621 (when (cl-plusp js2-highlight-level)
6622 (setq beg (min (point-max) beg)
6623 beg (max (point-min) beg)
6624 end (min (point-max) end)
6625 end (max (point-min) end))
6626 (if record
6627 (push (list beg end face) js2-mode-fontifications)
6628 (put-text-property beg end 'font-lock-face face))))
6629
6630 (defsubst js2-clear-face (beg end)
6631 (remove-text-properties beg end '(font-lock-face nil
6632 help-echo nil
6633 point-entered nil
6634 c-in-sws nil)))
6635
6636 (defconst js2-ecma-global-props
6637 (concat "^"
6638 (regexp-opt
6639 '("Infinity" "NaN" "undefined" "arguments") t)
6640 "$")
6641 "Value properties of the Ecma-262 Global Object.
6642 Shown at or above `js2-highlight-level' 2.")
6643
6644 ;; might want to add the name "arguments" to this list?
6645 (defconst js2-ecma-object-props
6646 (concat "^"
6647 (regexp-opt
6648 '("prototype" "__proto__" "__parent__") t)
6649 "$")
6650 "Value properties of the Ecma-262 Object constructor.
6651 Shown at or above `js2-highlight-level' 2.")
6652
6653 (defconst js2-ecma-global-funcs
6654 (concat
6655 "^"
6656 (regexp-opt
6657 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6658 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6659 "$")
6660 "Function properties of the Ecma-262 Global object.
6661 Shown at or above `js2-highlight-level' 2.")
6662
6663 (defconst js2-ecma-number-props
6664 (concat "^"
6665 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6666 "NEGATIVE_INFINITY"
6667 "POSITIVE_INFINITY") t)
6668 "$")
6669 "Properties of the Ecma-262 Number constructor.
6670 Shown at or above `js2-highlight-level' 2.")
6671
6672 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6673 "Properties of the Ecma-262 Date constructor.
6674 Shown at or above `js2-highlight-level' 2.")
6675
6676 (defconst js2-ecma-math-props
6677 (concat "^"
6678 (regexp-opt
6679 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6680 t)
6681 "$")
6682 "Properties of the Ecma-262 Math object.
6683 Shown at or above `js2-highlight-level' 2.")
6684
6685 (defconst js2-ecma-math-funcs
6686 (concat "^"
6687 (regexp-opt
6688 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6689 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6690 "$")
6691 "Function properties of the Ecma-262 Math object.
6692 Shown at or above `js2-highlight-level' 2.")
6693
6694 (defconst js2-ecma-function-props
6695 (concat
6696 "^"
6697 (regexp-opt
6698 '(;; properties of the Object prototype object
6699 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6700 "toLocaleString" "toString" "valueOf"
6701 ;; properties of the Function prototype object
6702 "apply" "call"
6703 ;; properties of the Array prototype object
6704 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6705 "splice" "unshift"
6706 ;; properties of the String prototype object
6707 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6708 "localeCompare" "match" "replace" "search" "split" "substring"
6709 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6710 "toUpperCase"
6711 ;; properties of the Number prototype object
6712 "toExponential" "toFixed" "toPrecision"
6713 ;; properties of the Date prototype object
6714 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6715 "getMinutes" "getMonth" "getSeconds" "getTime"
6716 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6717 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6718 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6719 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6720 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6721 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6722 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6723 "toTimeString" "toUTCString"
6724 ;; properties of the RegExp prototype object
6725 "exec" "test"
6726 ;; properties of the JSON prototype object
6727 "parse" "stringify"
6728 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6729 "toSource" "__defineGetter__" "__defineSetter__"
6730 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6731 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6732 t)
6733 "$")
6734 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6735 Shown at or above `js2-highlight-level' 3.")
6736
6737 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6738 (let ((target-name (and target
6739 (js2-name-node-p target)
6740 (js2-name-node-name target)))
6741 (prop-name (if prop (js2-name-node-name prop)))
6742 (level2 (>= js2-highlight-level 2))
6743 (level3 (>= js2-highlight-level 3)))
6744 (when level2
6745 (let ((face
6746 (if call-p
6747 (cond
6748 ((and target prop)
6749 (cond
6750 ((and level3 (string-match js2-ecma-function-props prop-name))
6751 'font-lock-builtin-face)
6752 ((and target-name prop)
6753 (cond
6754 ((string= target-name "Date")
6755 (if (string-match js2-ecma-date-props prop-name)
6756 'font-lock-builtin-face))
6757 ((string= target-name "Math")
6758 (if (string-match js2-ecma-math-funcs prop-name)
6759 'font-lock-builtin-face))))))
6760 (prop
6761 (if (string-match js2-ecma-global-funcs prop-name)
6762 'font-lock-builtin-face)))
6763 (cond
6764 ((and target prop)
6765 (cond
6766 ((string= target-name "Number")
6767 (if (string-match js2-ecma-number-props prop-name)
6768 'font-lock-constant-face))
6769 ((string= target-name "Math")
6770 (if (string-match js2-ecma-math-props prop-name)
6771 'font-lock-constant-face))))
6772 (prop
6773 (if (string-match js2-ecma-object-props prop-name)
6774 'font-lock-constant-face))))))
6775 (when face
6776 (let ((pos (+ (js2-node-pos parent) ; absolute
6777 (js2-node-pos prop)))) ; relative
6778 (js2-set-face pos
6779 (+ pos (js2-node-len prop))
6780 face 'record)))))))
6781
6782 (defun js2-parse-highlight-member-expr-node (node)
6783 "Perform syntax highlighting of EcmaScript built-in properties.
6784 The variable `js2-highlight-level' governs this highlighting."
6785 (let (face target prop name pos end parent call-p callee)
6786 (cond
6787 ;; case 1: simple name, e.g. foo
6788 ((js2-name-node-p node)
6789 (setq name (js2-name-node-name node))
6790 ;; possible for name to be nil in rare cases - saw it when
6791 ;; running js2-mode on an elisp buffer. Might as well try to
6792 ;; make it so js2-mode never barfs.
6793 (when name
6794 (setq face (if (string-match js2-ecma-global-props name)
6795 'font-lock-constant-face))
6796 (when face
6797 (setq pos (js2-node-pos node)
6798 end (+ pos (js2-node-len node)))
6799 (js2-set-face pos end face 'record))))
6800 ;; case 2: property access or function call
6801 ((or (js2-prop-get-node-p node)
6802 ;; highlight function call if expr is a prop-get node
6803 ;; or a plain name (i.e. unqualified function call)
6804 (and (setq call-p (js2-call-node-p node))
6805 (setq callee (js2-call-node-target node)) ; separate setq!
6806 (or (js2-prop-get-node-p callee)
6807 (js2-name-node-p callee))))
6808 (setq parent node
6809 node (if call-p callee node))
6810 (if (and call-p (js2-name-node-p callee))
6811 (setq prop callee)
6812 (setq target (js2-prop-get-node-left node)
6813 prop (js2-prop-get-node-right node)))
6814 (cond
6815 ((js2-name-node-p prop)
6816 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6817 (js2-parse-highlight-prop-get parent target prop call-p))
6818 ((js2-name-node-p target)
6819 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6820 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6821
6822 (defun js2-parse-highlight-member-expr-fn-name (expr)
6823 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6824 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6825 We currently only handle the case where the last component is a prop-get
6826 of a simple name. Called before EXPR has a parent node."
6827 (let (pos
6828 (name (and (js2-prop-get-node-p expr)
6829 (js2-prop-get-node-right expr))))
6830 (when (js2-name-node-p name)
6831 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6832 (js2-node-pos name)))
6833 (+ pos (js2-node-len name))
6834 'font-lock-function-name-face
6835 'record))))
6836
6837 ;; source: http://jsdoc.sourceforge.net/
6838 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6839 ;; allows type specifications, and needs work before entering the wild.
6840
6841 (defconst js2-jsdoc-param-tag-regexp
6842 (concat "^\\s-*\\*+\\s-*\\(@"
6843 "\\(?:param\\|argument\\)"
6844 "\\)"
6845 "\\s-*\\({[^}]+}\\)?" ; optional type
6846 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6847 "\\>")
6848 "Matches jsdoc tags with optional type and optional param name.")
6849
6850 (defconst js2-jsdoc-typed-tag-regexp
6851 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6852 (regexp-opt
6853 '("enum"
6854 "extends"
6855 "field"
6856 "id"
6857 "implements"
6858 "lends"
6859 "mods"
6860 "requires"
6861 "return"
6862 "returns"
6863 "throw"
6864 "throws"))
6865 "\\)\\)\\s-*\\({[^}]+}\\)?")
6866 "Matches jsdoc tags with optional type.")
6867
6868 (defconst js2-jsdoc-arg-tag-regexp
6869 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6870 (regexp-opt
6871 '("alias"
6872 "augments"
6873 "borrows"
6874 "bug"
6875 "base"
6876 "config"
6877 "default"
6878 "define"
6879 "exception"
6880 "function"
6881 "member"
6882 "memberOf"
6883 "name"
6884 "namespace"
6885 "property"
6886 "since"
6887 "suppress"
6888 "this"
6889 "throws"
6890 "type"
6891 "version"))
6892 "\\)\\)\\s-+\\([^ \t]+\\)")
6893 "Matches jsdoc tags with a single argument.")
6894
6895 (defconst js2-jsdoc-empty-tag-regexp
6896 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6897 (regexp-opt
6898 '("addon"
6899 "author"
6900 "class"
6901 "const"
6902 "constant"
6903 "constructor"
6904 "constructs"
6905 "deprecated"
6906 "desc"
6907 "description"
6908 "event"
6909 "example"
6910 "exec"
6911 "export"
6912 "fileoverview"
6913 "final"
6914 "function"
6915 "hidden"
6916 "ignore"
6917 "implicitCast"
6918 "inheritDoc"
6919 "inner"
6920 "interface"
6921 "license"
6922 "noalias"
6923 "noshadow"
6924 "notypecheck"
6925 "override"
6926 "owner"
6927 "preserve"
6928 "preserveTry"
6929 "private"
6930 "protected"
6931 "public"
6932 "static"
6933 "supported"
6934 ))
6935 "\\)\\)\\s-*")
6936 "Matches empty jsdoc tags.")
6937
6938 (defconst js2-jsdoc-link-tag-regexp
6939 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6940 "Matches a jsdoc link or code tag.")
6941
6942 (defconst js2-jsdoc-see-tag-regexp
6943 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6944 "Matches a jsdoc @see tag.")
6945
6946 (defconst js2-jsdoc-html-tag-regexp
6947 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6948 "Matches a simple (no attributes) html start- or end-tag.")
6949
6950 (defun js2-jsdoc-highlight-helper ()
6951 (js2-set-face (match-beginning 1)
6952 (match-end 1)
6953 'js2-jsdoc-tag)
6954 (if (match-beginning 2)
6955 (if (save-excursion
6956 (goto-char (match-beginning 2))
6957 (= (char-after) ?{))
6958 (js2-set-face (1+ (match-beginning 2))
6959 (1- (match-end 2))
6960 'js2-jsdoc-type)
6961 (js2-set-face (match-beginning 2)
6962 (match-end 2)
6963 'js2-jsdoc-value)))
6964 (if (match-beginning 3)
6965 (js2-set-face (match-beginning 3)
6966 (match-end 3)
6967 'js2-jsdoc-value)))
6968
6969 (defun js2-highlight-jsdoc (ast)
6970 "Highlight doc comment tags."
6971 (let ((comments (js2-ast-root-comments ast))
6972 beg end)
6973 (save-excursion
6974 (dolist (node comments)
6975 (when (eq (js2-comment-node-format node) 'jsdoc)
6976 (setq beg (js2-node-abs-pos node)
6977 end (+ beg (js2-node-len node)))
6978 (save-restriction
6979 (narrow-to-region beg end)
6980 (dolist (re (list js2-jsdoc-param-tag-regexp
6981 js2-jsdoc-typed-tag-regexp
6982 js2-jsdoc-arg-tag-regexp
6983 js2-jsdoc-link-tag-regexp
6984 js2-jsdoc-see-tag-regexp
6985 js2-jsdoc-empty-tag-regexp))
6986 (goto-char beg)
6987 (while (re-search-forward re nil t)
6988 (js2-jsdoc-highlight-helper)))
6989 ;; simple highlighting for html tags
6990 (goto-char beg)
6991 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6992 (js2-set-face (match-beginning 1)
6993 (match-end 1)
6994 'js2-jsdoc-html-tag-delimiter)
6995 (js2-set-face (match-beginning 2)
6996 (match-end 2)
6997 'js2-jsdoc-html-tag-name)
6998 (js2-set-face (match-beginning 3)
6999 (match-end 3)
7000 'js2-jsdoc-html-tag-delimiter))))))))
7001
7002 (defun js2-highlight-assign-targets (_node left right)
7003 "Highlight function properties and external variables."
7004 (let (leftpos name)
7005 ;; highlight vars and props assigned function values
7006 (when (or (js2-function-node-p right)
7007 (js2-class-node-p right))
7008 (cond
7009 ;; var foo = function() {...}
7010 ((js2-name-node-p left)
7011 (setq name left))
7012 ;; foo.bar.baz = function() {...}
7013 ((and (js2-prop-get-node-p left)
7014 (js2-name-node-p (js2-prop-get-node-right left)))
7015 (setq name (js2-prop-get-node-right left))))
7016 (when name
7017 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7018 (+ leftpos (js2-node-len name))
7019 'font-lock-function-name-face
7020 'record)))))
7021
7022 (defun js2-record-name-node (node)
7023 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7024 later. NODE must be a name node."
7025 (let ((leftpos (js2-node-abs-pos node)))
7026 (push (list node js2-current-scope
7027 leftpos
7028 (+ leftpos (js2-node-len node)))
7029 js2-recorded-identifiers)))
7030
7031 (defun js2-highlight-undeclared-vars ()
7032 "After entire parse is finished, look for undeclared variable references.
7033 We have to wait until entire buffer is parsed, since JavaScript permits var
7034 decls to occur after they're used.
7035
7036 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7037 it is considered declared."
7038 (let (name)
7039 (dolist (entry js2-recorded-identifiers)
7040 (cl-destructuring-bind (name-node scope pos end) entry
7041 (setq name (js2-name-node-name name-node))
7042 (unless (or (member name js2-global-externs)
7043 (member name js2-default-externs)
7044 (member name js2-additional-externs)
7045 (js2-get-defining-scope scope name pos))
7046 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7047 'js2-external-variable))))
7048 (setq js2-recorded-identifiers nil)))
7049
7050 (defun js2-set-default-externs ()
7051 "Set the value of `js2-default-externs' based on the various
7052 `js2-include-?-externs' variables."
7053 (setq js2-default-externs
7054 (append js2-ecma-262-externs
7055 (if js2-include-browser-externs js2-browser-externs)
7056 (if (and js2-include-browser-externs
7057 (>= js2-language-version 200)) js2-harmony-externs)
7058 (if js2-include-rhino-externs js2-rhino-externs)
7059 (if js2-include-node-externs js2-node-externs)
7060 (if (or js2-include-browser-externs js2-include-node-externs)
7061 js2-typed-array-externs))))
7062
7063 (defun js2-apply-jslint-globals ()
7064 (setq js2-additional-externs
7065 (nconc (js2-get-jslint-globals)
7066 js2-additional-externs)))
7067
7068 (defun js2-get-jslint-globals ()
7069 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7070 when (and (eq 'block (js2-comment-node-format node))
7071 (save-excursion
7072 (goto-char (js2-node-abs-pos node))
7073 (looking-at "/\\*global ")))
7074 append (js2-get-jslint-globals-in
7075 (match-end 0)
7076 (js2-node-abs-end node))))
7077
7078 (defun js2-get-jslint-globals-in (beg end)
7079 (let (res)
7080 (save-excursion
7081 (goto-char beg)
7082 (while (re-search-forward js2-mode-identifier-re end t)
7083 (let ((match (match-string 0)))
7084 (unless (member match '("true" "false"))
7085 (push match res)))))
7086 (nreverse res)))
7087
7088 ;;; IMenu support
7089
7090 ;; We currently only support imenu, but eventually should support speedbar and
7091 ;; possibly other browsing mechanisms.
7092
7093 ;; The basic strategy is to identify function assignment targets of the form
7094 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7095 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7096 ;; for imenu after parsing is finished.
7097
7098 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7099 ;; JavaScript, and the general problem is undecidable. However, several forms
7100 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7101 ;; include:
7102
7103 ;; function foo() -- function declaration
7104 ;; foo = function() -- function expression assigned to variable
7105 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7106 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7107 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7108 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7109 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7110 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7111 ;; function foo() {function bar() {...}} -- nested function
7112 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7113
7114 ;; This list boils down to a few forms that can be combined recursively.
7115 ;; Top-level named function declarations include both the left-hand (name)
7116 ;; and the right-hand (function value) expressions needed to produce an imenu
7117 ;; entry. The other "right-hand" forms we need to look for are:
7118 ;; - functions declared as props/getters/setters in object literals
7119 ;; - nested named function declarations
7120 ;; The "left-hand" expressions that functions can be assigned to include:
7121 ;; - local/global variables
7122 ;; - nested property-get expressions like a.b.c.d
7123 ;; - element gets like foo[10] or foo['bar'] where the index
7124 ;; expression can be trivially converted to a property name. They
7125 ;; effectively then become property gets.
7126
7127 ;; All the different definition types are canonicalized into the form
7128 ;; foo.bar.baz = position-of-function-keyword
7129
7130 ;; We need to build a trie-like structure for imenu. As an example,
7131 ;; consider the following JavaScript code:
7132
7133 ;; a = function() {...} // function at position 5
7134 ;; b = function() {...} // function at position 25
7135 ;; foo = function() {...} // function at position 100
7136 ;; foo.bar = function() {...} // function at position 200
7137 ;; foo.bar.baz = function() {...} // function at position 300
7138 ;; foo.bar.zab = function() {...} // function at position 400
7139
7140 ;; During parsing we accumulate an entry for each definition in
7141 ;; the variable `js2-imenu-recorder', like so:
7142
7143 ;; '((fn a 5)
7144 ;; (fn b 25)
7145 ;; (fn foo 100)
7146 ;; (fn foo bar 200)
7147 ;; (fn foo bar baz 300)
7148 ;; (fn foo bar zab 400))
7149
7150 ;; Where 'fn' is the respective function node.
7151 ;; After parsing these entries are merged into this alist-trie:
7152
7153 ;; '((a . 1)
7154 ;; (b . 2)
7155 ;; (foo (<definition> . 3)
7156 ;; (bar (<definition> . 6)
7157 ;; (baz . 100)
7158 ;; (zab . 200))))
7159
7160 ;; Note the wacky need for a <definition> name. The token can be anything
7161 ;; that isn't a valid JavaScript identifier, because you might make foo
7162 ;; a function and then start setting properties on it that are also functions.
7163
7164 (defun js2-prop-node-name (node)
7165 "Return the name of a node that may be a property-get/property-name.
7166 If NODE is not a valid name-node, string-node or integral number-node,
7167 returns nil. Otherwise returns the string name/value of the node."
7168 (cond
7169 ((js2-name-node-p node)
7170 (js2-name-node-name node))
7171 ((js2-string-node-p node)
7172 (js2-string-node-value node))
7173 ((and (js2-number-node-p node)
7174 (string-match "^[0-9]+$" (js2-number-node-value node)))
7175 (js2-number-node-value node))
7176 ((eq (js2-node-type node) js2-THIS)
7177 "this")
7178 ((eq (js2-node-type node) js2-SUPER)
7179 "super")))
7180
7181 (defun js2-node-qname-component (node)
7182 "Return the name of this node, if it contributes to a qname.
7183 Returns nil if the node doesn't contribute."
7184 (copy-sequence
7185 (or (js2-prop-node-name node)
7186 (if (and (js2-function-node-p node)
7187 (js2-function-node-name node))
7188 (js2-name-node-name (js2-function-node-name node))))))
7189
7190 (defun js2-record-imenu-entry (fn-node qname pos)
7191 "Add an entry to `js2-imenu-recorder'.
7192 FN-NODE should be the current item's function node.
7193
7194 Associate FN-NODE with its QNAME for later lookup.
7195 This is used in postprocessing the chain list. For each chain, we find
7196 the parent function, look up its qname, then prepend a copy of it to the chain."
7197 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7198 (unless js2-imenu-function-map
7199 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7200 (puthash fn-node qname js2-imenu-function-map))
7201
7202 (defun js2-record-imenu-functions (node &optional var)
7203 "Record function definitions for imenu.
7204 NODE is a function node or an object literal.
7205 VAR, if non-nil, is the expression that NODE is being assigned to.
7206 When passed arguments of wrong type, does nothing."
7207 (when js2-parse-ide-mode
7208 (let ((fun-p (js2-function-node-p node))
7209 qname fname-node)
7210 (cond
7211 ;; non-anonymous function declaration?
7212 ((and fun-p
7213 (not var)
7214 (setq fname-node (js2-function-node-name node)))
7215 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7216 ;; for remaining forms, compute left-side tree branch first
7217 ((and var (setq qname (js2-compute-nested-prop-get var)))
7218 (cond
7219 ;; foo.bar.baz = function
7220 (fun-p
7221 (js2-record-imenu-entry node qname (js2-node-pos node)))
7222 ;; foo.bar.baz = object-literal
7223 ;; look for nested functions: {a: {b: function() {...} }}
7224 ((js2-object-node-p node)
7225 ;; Node position here is still absolute, since the parser
7226 ;; passes the assignment target and value expressions
7227 ;; to us before they are added as children of the assignment node.
7228 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7229
7230 (defun js2-compute-nested-prop-get (node)
7231 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7232 component nodes as a list. Otherwise return nil. Element-gets are treated
7233 as property-gets if the index expression is a string, or a positive integer."
7234 (let (left right head)
7235 (cond
7236 ((or (js2-name-node-p node)
7237 (js2-this-or-super-node-p node))
7238 (list node))
7239 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7240 ((js2-prop-get-node-p node) ; foo.bar
7241 (setq left (js2-prop-get-node-left node)
7242 right (js2-prop-get-node-right node))
7243 (if (setq head (js2-compute-nested-prop-get left))
7244 (nconc head (list right))))
7245 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7246 (setq left (js2-elem-get-node-target node)
7247 right (js2-elem-get-node-element node))
7248 (if (or (js2-string-node-p right) ; ['bar']
7249 (and (js2-number-node-p right) ; [10]
7250 (string-match "^[0-9]+$"
7251 (js2-number-node-value right))))
7252 (if (setq head (js2-compute-nested-prop-get left))
7253 (nconc head (list right))))))))
7254
7255 (defun js2-record-object-literal (node qname pos)
7256 "Recursively process an object literal looking for functions.
7257 NODE is an object literal that is the right-hand child of an assignment
7258 expression. QNAME is a list of nodes representing the assignment target,
7259 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7260 POS is the absolute position of the node.
7261 We do a depth-first traversal of NODE. For any functions we find,
7262 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7263 (let (right)
7264 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7265 (let ((left (js2-infix-node-left e))
7266 ;; Element positions are relative to the parent position.
7267 (pos (+ pos (js2-node-pos e))))
7268 (cond
7269 ;; foo: function() {...}
7270 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7271 (when (js2-prop-node-name left)
7272 ;; As a policy decision, we record the position of the property,
7273 ;; not the position of the `function' keyword, since the property
7274 ;; is effectively the name of the function.
7275 (js2-record-imenu-entry right (append qname (list left)) pos)))
7276 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7277 ((js2-object-node-p right)
7278 (js2-record-object-literal right
7279 (append qname (list (js2-infix-node-left e)))
7280 (+ pos (js2-node-pos right)))))))))
7281
7282 (defun js2-node-top-level-decl-p (node)
7283 "Return t if NODE's name is defined in the top-level scope.
7284 Also returns t if NODE's name is not defined in any scope, since it implies
7285 that it's an external variable, which must also be in the top-level scope."
7286 (let* ((name (js2-prop-node-name node))
7287 (this-scope (js2-node-get-enclosing-scope node))
7288 defining-scope)
7289 (cond
7290 ((js2-this-or-super-node-p node)
7291 nil)
7292 ((null this-scope)
7293 t)
7294 ((setq defining-scope (js2-get-defining-scope this-scope name))
7295 (js2-ast-root-p defining-scope))
7296 (t t))))
7297
7298 (defun js2-wrapper-function-p (node)
7299 "Return t if NODE is a function expression that's immediately invoked.
7300 NODE must be `js2-function-node'."
7301 (let ((parent (js2-node-parent node)))
7302 (or
7303 ;; function(){...}();
7304 (and (js2-call-node-p parent)
7305 (eq node (js2-call-node-target parent)))
7306 (and (js2-paren-node-p parent)
7307 ;; (function(){...})();
7308 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7309 ;; (function(){...}).call(this);
7310 (and (js2-prop-get-node-p parent)
7311 (member (js2-name-node-name (js2-prop-get-node-right parent))
7312 '("call" "apply"))
7313 (js2-call-node-p (js2-node-parent parent))))))))
7314
7315 (defun js2-browse-postprocess-chains ()
7316 "Modify function-declaration name chains after parsing finishes.
7317 Some of the information is only available after the parse tree is complete.
7318 For instance, processing a nested scope requires a parent function node."
7319 (let (result fn parent-qname p elem)
7320 (dolist (entry js2-imenu-recorder)
7321 ;; function node goes first
7322 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7323 ;; Examine head's defining scope:
7324 ;; Pre-processed chain, or top-level/external, keep as-is.
7325 (if (or (stringp head) (js2-node-top-level-decl-p head))
7326 (push chain result)
7327 (when (js2-this-or-super-node-p head)
7328 (setq chain (cdr chain))) ; discard this-node
7329 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7330 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7331 (when (eq parent-qname 'not-found)
7332 ;; anonymous function expressions are not recorded
7333 ;; during the parse, so we need to handle this case here
7334 (setq parent-qname
7335 (if (js2-wrapper-function-p fn)
7336 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7337 (if (js2-ast-root-p grandparent)
7338 nil
7339 (gethash grandparent js2-imenu-function-map 'skip)))
7340 'skip))
7341 (puthash fn parent-qname js2-imenu-function-map))
7342 (if (eq parent-qname 'skip)
7343 ;; We don't show it, let's record that fact.
7344 (remhash current-fn js2-imenu-function-map)
7345 ;; Prepend parent fn qname to this chain.
7346 (let ((qname (append parent-qname chain)))
7347 (puthash current-fn (butlast qname) js2-imenu-function-map)
7348 (push qname result)))))))
7349 ;; Collect chains obtained by third-party code.
7350 (let (js2-imenu-recorder)
7351 (run-hooks 'js2-build-imenu-callbacks)
7352 (dolist (entry js2-imenu-recorder)
7353 (push (cdr entry) result)))
7354 ;; Finally replace each node in each chain with its name.
7355 (dolist (chain result)
7356 (setq p chain)
7357 (while p
7358 (if (js2-node-p (setq elem (car p)))
7359 (setcar p (js2-node-qname-component elem)))
7360 (setq p (cdr p))))
7361 result))
7362
7363 ;; Merge name chains into a trie-like tree structure of nested lists.
7364 ;; To simplify construction of the trie, we first build it out using the rule
7365 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7366 ;; [key, num-or-list]. The second element can be a number; if so, this key
7367 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7368 ;; associated with the key at this level.) Otherwise the second element is
7369 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7370 ;; a simple recursive formulation.
7371 ;;
7372 ;; js2-mode is building the data structure for imenu. The imenu documentation
7373 ;; claims that it's the structure above, but in practice it wants the children
7374 ;; at the same list level as the key for that level, which is how I've drawn
7375 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7376 ;; list wrapper around the children at each level.
7377 ;;
7378 ;; A completed nested imenu-alist entry looks like this:
7379 ;; '(("foo"
7380 ;; ("<definition>" . 7)
7381 ;; ("bar"
7382 ;; ("a" . 40)
7383 ;; ("b" . 60))))
7384 ;;
7385 ;; In particular, the documentation for `imenu--index-alist' says that
7386 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7387 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7388
7389 (defun js2-treeify (lst)
7390 "Convert (a b c d) to (a ((b ((c d)))))."
7391 (if (null (cddr lst)) ; list length <= 2
7392 lst
7393 (list (car lst) (list (js2-treeify (cdr lst))))))
7394
7395 (defun js2-build-alist-trie (chains trie)
7396 "Merge declaration name chains into a trie-like alist structure for imenu.
7397 CHAINS is the qname chain list produced during parsing. TRIE is a
7398 list of elements built up so far."
7399 (let (head tail pos branch kids)
7400 (dolist (chain chains)
7401 (setq head (car chain)
7402 tail (cdr chain)
7403 pos (if (numberp (car tail)) (car tail))
7404 branch (js2-find-if (lambda (n)
7405 (string= (car n) head))
7406 trie)
7407 kids (cl-second branch))
7408 (cond
7409 ;; case 1: this key isn't in the trie yet
7410 ((null branch)
7411 (if trie
7412 (setcdr (last trie) (list (js2-treeify chain)))
7413 (setq trie (list (js2-treeify chain)))))
7414 ;; case 2: key is present with a single number entry: replace w/ list
7415 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7416 ;; ("<definition>" 20)))
7417 ((numberp kids)
7418 (setcar (cdr branch)
7419 (list (list "<definition-1>" kids)
7420 (if pos
7421 (list "<definition-2>" pos)
7422 (js2-treeify tail)))))
7423 ;; case 3: key is there (with kids), and we're a number entry
7424 (pos
7425 (setcdr (last kids)
7426 (list
7427 (list (format "<definition-%d>"
7428 (1+ (cl-loop for kid in kids
7429 count (eq ?< (aref (car kid) 0)))))
7430 pos))))
7431 ;; case 4: key is there with kids, need to merge in our chain
7432 (t
7433 (js2-build-alist-trie (list tail) kids))))
7434 trie))
7435
7436 (defun js2-flatten-trie (trie)
7437 "Convert TRIE to imenu-format.
7438 Recurses through nodes, and for each one whose second element is a list,
7439 appends the list's flattened elements to the current element. Also
7440 changes the tails into conses. For instance, this pre-flattened trie
7441
7442 '(a ((b 20)
7443 (c ((d 30)
7444 (e 40)))))
7445
7446 becomes
7447
7448 '(a (b . 20)
7449 (c (d . 30)
7450 (e . 40)))
7451
7452 Note that the root of the trie has no key, just a list of chains.
7453 This is also true for the value of any key with multiple children,
7454 e.g. key 'c' in the example above."
7455 (cond
7456 ((listp (car trie))
7457 (mapcar #'js2-flatten-trie trie))
7458 (t
7459 (if (numberp (cl-second trie))
7460 (cons (car trie) (cl-second trie))
7461 ;; else pop list and append its kids
7462 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7463
7464 (defun js2-build-imenu-index ()
7465 "Turn `js2-imenu-recorder' into an imenu data structure."
7466 (when (eq js2-imenu-recorder 'empty)
7467 (setq js2-imenu-recorder nil))
7468 (let* ((chains (js2-browse-postprocess-chains))
7469 (result (js2-build-alist-trie chains nil)))
7470 (js2-flatten-trie result)))
7471
7472 (defun js2-test-print-chains (chains)
7473 "Print a list of qname chains.
7474 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7475 i.e. one or more nodes, and an integer position as the list tail."
7476 (mapconcat (lambda (chain)
7477 (concat "("
7478 (mapconcat (lambda (elem)
7479 (if (js2-node-p elem)
7480 (or (js2-node-qname-component elem)
7481 "nil")
7482 (number-to-string elem)))
7483 chain
7484 " ")
7485 ")"))
7486 chains
7487 "\n"))
7488
7489 ;;; Parser
7490
7491 (defconst js2-version "1.8.5"
7492 "Version of JavaScript supported.")
7493
7494 (defun js2-record-face (face &optional token)
7495 "Record a style run of FACE for TOKEN or the current token."
7496 (unless token (setq token (js2-current-token)))
7497 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7498
7499 (defsubst js2-node-end (n)
7500 "Computes the absolute end of node N.
7501 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7502 is only true until the node is added to its parent; i.e., while parsing."
7503 (+ (js2-node-pos n)
7504 (js2-node-len n)))
7505
7506 (defun js2-record-comment (token)
7507 "Record a comment in `js2-scanned-comments'."
7508 (let ((ct (js2-token-comment-type token))
7509 (beg (js2-token-beg token))
7510 (end (js2-token-end token)))
7511 (push (make-js2-comment-node :len (- end beg)
7512 :format ct)
7513 js2-scanned-comments)
7514 (when js2-parse-ide-mode
7515 (js2-record-face (if (eq ct 'jsdoc)
7516 'font-lock-doc-face
7517 'font-lock-comment-face)
7518 token)
7519 (when (memq ct '(html preprocessor))
7520 ;; Tell cc-engine the bounds of the comment.
7521 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7522
7523 (defun js2-peek-token ()
7524 "Return the next token type without consuming it.
7525 If `js2-ti-lookahead' is positive, return the type of next token
7526 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7527 (if (not (zerop js2-ti-lookahead))
7528 (js2-token-type
7529 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7530 (let ((tt (js2-get-token-internal nil)))
7531 (js2-unget-token)
7532 tt)))
7533
7534 (defalias 'js2-next-token 'js2-get-token)
7535
7536 (defun js2-match-token (match &optional dont-unget)
7537 "Get next token and return t if it matches MATCH, a bytecode.
7538 Returns nil and consumes nothing if MATCH is not the next token."
7539 (if (/= (js2-get-token) match)
7540 (ignore (unless dont-unget (js2-unget-token)))
7541 t))
7542
7543 (defun js2-match-contextual-kwd (name)
7544 "Consume and return t if next token is `js2-NAME', and its
7545 string is NAME. Returns nil and keeps current token otherwise."
7546 (if (or (/= (js2-get-token) js2-NAME)
7547 (not (string= (js2-current-token-string) name)))
7548 (progn
7549 (js2-unget-token)
7550 nil)
7551 (js2-record-face 'font-lock-keyword-face)
7552 t))
7553
7554 (defun js2-get-prop-name-token ()
7555 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7556
7557 (defun js2-match-prop-name ()
7558 "Consume token and return t if next token is a valid property name.
7559 If `js2-language-version' is >= 180, a keyword or reserved word
7560 is considered valid name as well."
7561 (if (eq js2-NAME (js2-get-prop-name-token))
7562 t
7563 (js2-unget-token)
7564 nil))
7565
7566 (defun js2-must-match-prop-name (msg-id &optional pos len)
7567 (if (js2-match-prop-name)
7568 t
7569 (js2-report-error msg-id nil pos len)
7570 nil))
7571
7572 (defun js2-peek-token-or-eol ()
7573 "Return js2-EOL if the next token immediately follows a newline.
7574 Else returns the next token. Used in situations where we don't
7575 consider certain token types valid if they are preceded by a newline.
7576 One example is the postfix ++ or -- operator, which has to be on the
7577 same line as its operand."
7578 (let ((tt (js2-get-token))
7579 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7580 (js2-unget-token)
7581 (if follows-eol
7582 js2-EOL
7583 tt)))
7584
7585 (defun js2-must-match (token msg-id &optional pos len)
7586 "Match next token to token code TOKEN, or record a syntax error.
7587 MSG-ID is the error message to report if the match fails.
7588 Returns t on match, nil if no match."
7589 (if (js2-match-token token t)
7590 t
7591 (js2-report-error msg-id nil pos len)
7592 (js2-unget-token)
7593 nil))
7594
7595 (defun js2-must-match-name (msg-id)
7596 (if (js2-match-token js2-NAME t)
7597 t
7598 (if (eq (js2-current-token-type) js2-RESERVED)
7599 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7600 (js2-report-error msg-id)
7601 (js2-unget-token))
7602 nil))
7603
7604 (defsubst js2-inside-function ()
7605 (cl-plusp js2-nesting-of-function))
7606
7607 (defun js2-set-requires-activation ()
7608 (if (js2-function-node-p js2-current-script-or-fn)
7609 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7610
7611 (defun js2-check-activation-name (name _token)
7612 (when (js2-inside-function)
7613 ;; skip language-version 1.2 check from Rhino
7614 (if (or (string= "arguments" name)
7615 (and js2-compiler-activation-names ; only used in codegen
7616 (gethash name js2-compiler-activation-names)))
7617 (js2-set-requires-activation))))
7618
7619 (defun js2-set-is-generator ()
7620 (let ((fn-node js2-current-script-or-fn))
7621 (when (and (js2-function-node-p fn-node)
7622 (not (js2-function-node-generator-type fn-node)))
7623 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7624
7625 (defun js2-must-have-xml ()
7626 (unless js2-compiler-xml-available
7627 (js2-report-error "msg.XML.not.available")))
7628
7629 (defun js2-push-scope (scope)
7630 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7631 (cl-assert (js2-scope-p scope))
7632 (cl-assert (null (js2-scope-parent-scope scope)))
7633 (cl-assert (not (eq js2-current-scope scope)))
7634 (setf (js2-scope-parent-scope scope) js2-current-scope
7635 js2-current-scope scope))
7636
7637 (defsubst js2-pop-scope ()
7638 (setq js2-current-scope
7639 (js2-scope-parent-scope js2-current-scope)))
7640
7641 (defun js2-enter-loop (loop-node)
7642 (push loop-node js2-loop-set)
7643 (push loop-node js2-loop-and-switch-set)
7644 (js2-push-scope loop-node)
7645 ;; Tell the current labeled statement (if any) its statement,
7646 ;; and set the jump target of the first label to the loop.
7647 ;; These are used in `js2-parse-continue' to verify that the
7648 ;; continue target is an actual labeled loop. (And for codegen.)
7649 (when js2-labeled-stmt
7650 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7651 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7652 js2-labeled-stmt))) loop-node)))
7653
7654 (defun js2-exit-loop ()
7655 (pop js2-loop-set)
7656 (pop js2-loop-and-switch-set)
7657 (js2-pop-scope))
7658
7659 (defsubst js2-enter-switch (switch-node)
7660 (push switch-node js2-loop-and-switch-set))
7661
7662 (defsubst js2-exit-switch ()
7663 (pop js2-loop-and-switch-set))
7664
7665 (defun js2-parse (&optional buf cb)
7666 "Tell the js2 parser to parse a region of JavaScript.
7667
7668 BUF is a buffer or buffer name containing the code to parse.
7669 Call `narrow-to-region' first to parse only part of the buffer.
7670
7671 The returned AST root node is given some additional properties:
7672 `node-count' - total number of nodes in the AST
7673 `buffer' - BUF. The buffer it refers to may change or be killed,
7674 so the value is not necessarily reliable.
7675
7676 An optional callback CB can be specified to report parsing
7677 progress. If `(functionp CB)' returns t, it will be called with
7678 the current line number once before parsing begins, then again
7679 each time the lexer reaches a new line number.
7680
7681 CB can also be a list of the form `(symbol cb ...)' to specify
7682 multiple callbacks with different criteria. Each symbol is a
7683 criterion keyword, and the following element is the callback to
7684 call
7685
7686 :line - called whenever the line number changes
7687 :token - called for each new token consumed
7688
7689 The list of criteria could be extended to include entering or
7690 leaving a statement, an expression, or a function definition."
7691 (if (and cb (not (functionp cb)))
7692 (error "criteria callbacks not yet implemented"))
7693 (let ((inhibit-point-motion-hooks t)
7694 (js2-compiler-xml-available (>= js2-language-version 160))
7695 ;; This is a recursive-descent parser, so give it a big stack.
7696 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7697 (max-specpdl-size (max max-specpdl-size 3000))
7698 (case-fold-search nil)
7699 ast)
7700 (with-current-buffer (or buf (current-buffer))
7701 (setq js2-scanned-comments nil
7702 js2-parsed-errors nil
7703 js2-parsed-warnings nil
7704 js2-imenu-recorder nil
7705 js2-imenu-function-map nil
7706 js2-label-set nil)
7707 (js2-init-scanner)
7708 (setq ast (js2-do-parse))
7709 (unless js2-ts-hit-eof
7710 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7711 (setf (js2-ast-root-errors ast) js2-parsed-errors
7712 (js2-ast-root-warnings ast) js2-parsed-warnings)
7713 ;; if we didn't find any declarations, put a dummy in this list so we
7714 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7715 (unless js2-imenu-recorder
7716 (setq js2-imenu-recorder 'empty))
7717 (run-hooks 'js2-parse-finished-hook)
7718 ast)))
7719
7720 ;; Corresponds to Rhino's Parser.parse() method.
7721 (defun js2-do-parse ()
7722 "Parse current buffer starting from current point.
7723 Scanner should be initialized."
7724 (let ((pos js2-ts-cursor)
7725 (end js2-ts-cursor) ; in case file is empty
7726 root n tt)
7727 ;; initialize buffer-local parsing vars
7728 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7729 js2-current-script-or-fn root
7730 js2-current-scope root
7731 js2-nesting-of-function 0
7732 js2-labeled-stmt nil
7733 js2-recorded-identifiers nil) ; for js2-highlight
7734 (while (/= (setq tt (js2-get-token)) js2-EOF)
7735 (if (= tt js2-FUNCTION)
7736 (progn
7737 (setq n (if js2-called-by-compile-function
7738 (js2-parse-function-expr)
7739 (js2-parse-function-stmt))))
7740 ;; not a function - parse a statement
7741 (js2-unget-token)
7742 (setq n (js2-parse-statement)))
7743 ;; add function or statement to script
7744 (setq end (js2-node-end n))
7745 (js2-block-node-push root n))
7746 ;; add comments to root in lexical order
7747 (when js2-scanned-comments
7748 ;; if we find a comment beyond end of normal kids, use its end
7749 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7750 (dolist (comment js2-scanned-comments)
7751 (push comment (js2-ast-root-comments root))
7752 (js2-node-add-children root comment)))
7753 (setf (js2-node-len root) (- end pos))
7754 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7755 ;; Give extensions a chance to muck with things before highlighting starts.
7756 (let ((js2-additional-externs js2-additional-externs))
7757 (save-excursion
7758 (run-hooks 'js2-post-parse-callbacks))
7759 (js2-highlight-undeclared-vars))
7760 root))
7761
7762 (defun js2-parse-function-closure-body (fn-node)
7763 "Parse a JavaScript 1.8 function closure body."
7764 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7765 (if js2-ts-hit-eof
7766 (js2-report-error "msg.no.brace.body" nil
7767 (js2-node-pos fn-node)
7768 (- js2-ts-cursor (js2-node-pos fn-node)))
7769 (js2-node-add-children fn-node
7770 (setf (js2-function-node-body fn-node)
7771 (js2-parse-expr t))))))
7772
7773 (defun js2-parse-function-body (fn-node)
7774 (js2-must-match js2-LC "msg.no.brace.body"
7775 (js2-node-pos fn-node)
7776 (- js2-ts-cursor (js2-node-pos fn-node)))
7777 (let ((pos (js2-current-token-beg)) ; LC position
7778 (pn (make-js2-block-node)) ; starts at LC position
7779 tt
7780 end)
7781 (cl-incf js2-nesting-of-function)
7782 (unwind-protect
7783 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7784 (= tt js2-EOF)
7785 (= tt js2-RC)))
7786 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7787 (js2-parse-statement)
7788 (js2-get-token)
7789 (js2-parse-function-stmt))))
7790 (cl-decf js2-nesting-of-function))
7791 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7792 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7793 (setq end (js2-current-token-end)))
7794 (setf (js2-node-pos pn) pos
7795 (js2-node-len pn) (- end pos))
7796 (setf (js2-function-node-body fn-node) pn)
7797 (js2-node-add-children fn-node pn)
7798 pn))
7799
7800 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7801 "Declare and fontify destructuring parameters inside NODE.
7802 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7803 (cond
7804 ((js2-name-node-p node)
7805 (let (leftpos)
7806 (js2-define-symbol decl-type (js2-name-node-name node)
7807 node ignore-not-in-block)
7808 (when face
7809 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7810 (+ leftpos (js2-node-len node))
7811 face 'record))))
7812 ((js2-object-node-p node)
7813 (dolist (elem (js2-object-node-elems node))
7814 (js2-define-destruct-symbols
7815 ;; In abbreviated destructuring {a, b}, right == left.
7816 (js2-object-prop-node-right elem)
7817 decl-type face ignore-not-in-block)))
7818 ((js2-array-node-p node)
7819 (dolist (elem (js2-array-node-elems node))
7820 (when elem
7821 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7822 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7823 (js2-node-len node)))))
7824
7825 (defun js2-parse-function-params (function-type fn-node pos)
7826 (if (js2-match-token js2-RP)
7827 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7828 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7829 (eq (js2-current-token-type) js2-NAME)))
7830 params param default-found rest-param-at)
7831 (when paren-free-arrow
7832 (js2-unget-token))
7833 (cl-loop for tt = (js2-peek-token)
7834 do
7835 (cond
7836 ;; destructuring param
7837 ((and (not paren-free-arrow)
7838 (or (= tt js2-LB) (= tt js2-LC)))
7839 (js2-get-token)
7840 (when default-found
7841 (js2-report-error "msg.no.default.after.default.param"))
7842 (setq param (js2-parse-destruct-primary-expr))
7843 (js2-define-destruct-symbols param
7844 js2-LP
7845 'js2-function-param)
7846 (push param params))
7847 ;; variable name
7848 (t
7849 (when (and (>= js2-language-version 200)
7850 (not paren-free-arrow)
7851 (js2-match-token js2-TRIPLEDOT)
7852 (not rest-param-at))
7853 ;; to report errors if there are more parameters
7854 (setq rest-param-at (length params)))
7855 (js2-must-match-name "msg.no.parm")
7856 (js2-record-face 'js2-function-param)
7857 (setq param (js2-create-name-node))
7858 (js2-define-symbol js2-LP (js2-current-token-string) param)
7859 ;; default parameter value
7860 (when (or (and default-found
7861 (not rest-param-at)
7862 (js2-must-match js2-ASSIGN
7863 "msg.no.default.after.default.param"
7864 (js2-node-pos param)
7865 (js2-node-len param)))
7866 (and (>= js2-language-version 200)
7867 (js2-match-token js2-ASSIGN)))
7868 (cl-assert (not paren-free-arrow))
7869 (let* ((pos (js2-node-pos param))
7870 (tt (js2-current-token-type))
7871 (op-pos (- (js2-current-token-beg) pos))
7872 (left param)
7873 (right (js2-parse-assign-expr))
7874 (len (- (js2-node-end right) pos)))
7875 (setq param (make-js2-assign-node
7876 :type tt :pos pos :len len :op-pos op-pos
7877 :left left :right right)
7878 default-found t)
7879 (js2-node-add-children param left right)))
7880 (push param params)))
7881 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7882 (js2-report-error "msg.param.after.rest" nil
7883 (js2-node-pos param) (js2-node-len param)))
7884 while
7885 (js2-match-token js2-COMMA))
7886 (when (and (not paren-free-arrow)
7887 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7888 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7889 (when rest-param-at
7890 (setf (js2-function-node-rest-p fn-node) t))
7891 (dolist (p params)
7892 (js2-node-add-children fn-node p)
7893 (push p (js2-function-node-params fn-node))))))
7894
7895 (defun js2-check-inconsistent-return-warning (fn-node name)
7896 "Possibly show inconsistent-return warning.
7897 Last token scanned is the close-curly for the function body."
7898 (when (and js2-mode-show-strict-warnings
7899 js2-strict-inconsistent-return-warning
7900 (not (js2-has-consistent-return-usage
7901 (js2-function-node-body fn-node))))
7902 ;; Have it extend from close-curly to bol or beginning of block.
7903 (let ((pos (save-excursion
7904 (goto-char (js2-current-token-end))
7905 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7906 (point-at-bol))))
7907 (end (js2-current-token-end)))
7908 (if (cl-plusp (js2-name-node-length name))
7909 (js2-add-strict-warning "msg.no.return.value"
7910 (js2-name-node-name name) pos end)
7911 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7912
7913 (defun js2-parse-function-stmt ()
7914 (let ((pos (js2-current-token-beg))
7915 (star-p (js2-match-token js2-MUL)))
7916 (js2-must-match-name "msg.unnamed.function.stmt")
7917 (let ((name (js2-create-name-node t))
7918 pn member-expr)
7919 (cond
7920 ((js2-match-token js2-LP)
7921 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7922 (js2-allow-member-expr-as-function-name
7923 (setq member-expr (js2-parse-member-expr-tail nil name))
7924 (js2-parse-highlight-member-expr-fn-name member-expr)
7925 (js2-must-match js2-LP "msg.no.paren.parms")
7926 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7927 (js2-function-node-member-expr pn) member-expr)
7928 pn)
7929 (t
7930 (js2-report-error "msg.no.paren.parms")
7931 (make-js2-error-node))))))
7932
7933 (defun js2-parse-function-expr ()
7934 (let ((pos (js2-current-token-beg))
7935 (star-p (js2-match-token js2-MUL))
7936 name)
7937 (when (js2-match-token js2-NAME)
7938 (setq name (js2-create-name-node t)))
7939 (js2-must-match js2-LP "msg.no.paren.parms")
7940 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7941
7942 (defun js2-parse-function (function-type pos star-p &optional name)
7943 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7944 beginning of the first token (function keyword, unless it's an
7945 arrow function), NAME is js2-name-node."
7946 (let (fn-node lp)
7947 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7948 (setq lp (js2-current-token-beg)))
7949 (setf fn-node (make-js2-function-node :pos pos
7950 :name name
7951 :form function-type
7952 :lp (if lp (- lp pos))
7953 :generator-type (and star-p 'STAR)))
7954 (when name
7955 (js2-set-face (js2-node-pos name) (js2-node-end name)
7956 'font-lock-function-name-face 'record)
7957 (when (and (eq function-type 'FUNCTION_STATEMENT)
7958 (cl-plusp (js2-name-node-length name)))
7959 ;; Function statements define a symbol in the enclosing scope
7960 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7961 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
7962 ;; 1. Nested functions are not affected by the dynamic scope flag
7963 ;; as dynamic scope is already a parent of their scope.
7964 ;; 2. Functions defined under the with statement also immune to
7965 ;; this setup, in which case dynamic scope is ignored in favor
7966 ;; of the with object.
7967 (setf (js2-function-node-ignore-dynamic fn-node) t))
7968 ;; dynamically bind all the per-function variables
7969 (let ((js2-current-script-or-fn fn-node)
7970 (js2-current-scope fn-node)
7971 (js2-nesting-of-with 0)
7972 (js2-end-flags 0)
7973 js2-label-set
7974 js2-loop-set
7975 js2-loop-and-switch-set)
7976 (js2-parse-function-params function-type fn-node pos)
7977 (when (eq function-type 'FUNCTION_ARROW)
7978 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7979 (if (and (>= js2-language-version 180)
7980 (/= (js2-peek-token) js2-LC))
7981 (js2-parse-function-closure-body fn-node)
7982 (js2-parse-function-body fn-node))
7983 (js2-check-inconsistent-return-warning fn-node name)
7984
7985 (when name
7986 (js2-node-add-children fn-node name)
7987 ;; Function expressions define a name only in the body of the
7988 ;; function, and only if not hidden by a parameter name
7989 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7990 (null (js2-scope-get-symbol js2-current-scope
7991 (js2-name-node-name name))))
7992 (js2-define-symbol js2-FUNCTION
7993 (js2-name-node-name name)
7994 fn-node))
7995 (when (eq function-type 'FUNCTION_STATEMENT)
7996 (js2-record-imenu-functions fn-node))))
7997
7998 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7999 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8000 ;; We wait until after parsing the function to set its parent scope,
8001 ;; since `js2-define-symbol' needs the defining-scope check to stop
8002 ;; at the function boundary when checking for redeclarations.
8003 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8004 fn-node))
8005
8006 (defun js2-parse-statements (&optional parent)
8007 "Parse a statement list. Last token consumed must be js2-LC.
8008
8009 PARENT can be a `js2-block-node', in which case the statements are
8010 appended to PARENT. Otherwise a new `js2-block-node' is created
8011 and returned.
8012
8013 This function does not match the closing js2-RC: the caller
8014 matches the RC so it can provide a suitable error message if not
8015 matched. This means it's up to the caller to set the length of
8016 the node to include the closing RC. The node start pos is set to
8017 the absolute buffer start position, and the caller should fix it
8018 up to be relative to the parent node. All children of this block
8019 node are given relative start positions and correct lengths."
8020 (let ((pn (or parent (make-js2-block-node)))
8021 tt)
8022 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8023 (/= tt js2-RC))
8024 (js2-block-node-push pn (js2-parse-statement)))
8025 pn))
8026
8027 (defun js2-parse-statement ()
8028 (let (pn beg end)
8029 ;; coarse-grained user-interrupt check - needs work
8030 (and js2-parse-interruptable-p
8031 (zerop (% (cl-incf js2-parse-stmt-count)
8032 js2-statements-per-pause))
8033 (input-pending-p)
8034 (throw 'interrupted t))
8035 (setq pn (js2-statement-helper))
8036 ;; no-side-effects warning check
8037 (unless (js2-node-has-side-effects pn)
8038 (setq end (js2-node-end pn))
8039 (save-excursion
8040 (goto-char end)
8041 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8042 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8043 pn))
8044
8045 ;; These correspond to the switch cases in Parser.statementHelper
8046 (defconst js2-parsers
8047 (let ((parsers (make-vector js2-num-tokens
8048 #'js2-parse-expr-stmt)))
8049 (aset parsers js2-BREAK #'js2-parse-break)
8050 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8051 (aset parsers js2-CONST #'js2-parse-const-var)
8052 (aset parsers js2-CONTINUE #'js2-parse-continue)
8053 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8054 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8055 (aset parsers js2-DO #'js2-parse-do)
8056 (aset parsers js2-EXPORT #'js2-parse-export)
8057 (aset parsers js2-FOR #'js2-parse-for)
8058 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8059 (aset parsers js2-IF #'js2-parse-if)
8060 (aset parsers js2-IMPORT #'js2-parse-import)
8061 (aset parsers js2-LC #'js2-parse-block)
8062 (aset parsers js2-LET #'js2-parse-let-stmt)
8063 (aset parsers js2-NAME #'js2-parse-name-or-label)
8064 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8065 (aset parsers js2-SEMI #'js2-parse-semi)
8066 (aset parsers js2-SWITCH #'js2-parse-switch)
8067 (aset parsers js2-THROW #'js2-parse-throw)
8068 (aset parsers js2-TRY #'js2-parse-try)
8069 (aset parsers js2-VAR #'js2-parse-const-var)
8070 (aset parsers js2-WHILE #'js2-parse-while)
8071 (aset parsers js2-WITH #'js2-parse-with)
8072 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8073 parsers)
8074 "A vector mapping token types to parser functions.")
8075
8076 (defun js2-parse-warn-missing-semi (beg end)
8077 (and js2-mode-show-strict-warnings
8078 js2-strict-missing-semi-warning
8079 (js2-add-strict-warning
8080 "msg.missing.semi" nil
8081 ;; back up to beginning of statement or line
8082 (max beg (save-excursion
8083 (goto-char end)
8084 (point-at-bol)))
8085 end)))
8086
8087 (defconst js2-no-semi-insertion
8088 (list js2-IF
8089 js2-SWITCH
8090 js2-WHILE
8091 js2-DO
8092 js2-FOR
8093 js2-TRY
8094 js2-WITH
8095 js2-LC
8096 js2-ERROR
8097 js2-SEMI
8098 js2-CLASS
8099 js2-FUNCTION
8100 js2-EXPORT)
8101 "List of tokens that don't do automatic semicolon insertion.")
8102
8103 (defconst js2-autoinsert-semi-and-warn
8104 (list js2-ERROR js2-EOF js2-RC))
8105
8106 (defun js2-statement-helper ()
8107 (let* ((tt (js2-get-token))
8108 (first-tt tt)
8109 (parser (if (= tt js2-ERROR)
8110 #'js2-parse-semi
8111 (aref js2-parsers tt)))
8112 pn)
8113 ;; If the statement is set, then it's been told its label by now.
8114 (and js2-labeled-stmt
8115 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8116 (setq js2-labeled-stmt nil))
8117 (setq pn (funcall parser))
8118 ;; Don't do auto semi insertion for certain statement types.
8119 (unless (or (memq first-tt js2-no-semi-insertion)
8120 (js2-labeled-stmt-node-p pn))
8121 (js2-auto-insert-semicolon pn))
8122 pn))
8123
8124 (defun js2-auto-insert-semicolon (pn)
8125 (let* ((tt (js2-get-token))
8126 (pos (js2-node-pos pn)))
8127 (cond
8128 ((= tt js2-SEMI)
8129 ;; extend the node bounds to include the semicolon.
8130 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8131 ((memq tt js2-autoinsert-semi-and-warn)
8132 (js2-unget-token) ; Not ';', do not consume.
8133 ;; Autoinsert ;
8134 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8135 (t
8136 (if (not (js2-token-follows-eol-p (js2-current-token)))
8137 ;; Report error if no EOL or autoinsert ';' otherwise
8138 (js2-report-error "msg.no.semi.stmt")
8139 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8140 (js2-unget-token) ; Not ';', do not consume.
8141 ))))
8142
8143 (defun js2-parse-condition ()
8144 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8145 The parens are discarded and the expression node is returned.
8146 The `pos' field of the return value is set to an absolute position
8147 that must be fixed up by the caller.
8148 Return value is a list (EXPR LP RP), with absolute paren positions."
8149 (let (pn lp rp)
8150 (if (js2-must-match js2-LP "msg.no.paren.cond")
8151 (setq lp (js2-current-token-beg)))
8152 (setq pn (js2-parse-expr))
8153 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8154 (setq rp (js2-current-token-beg)))
8155 ;; Report strict warning on code like "if (a = 7) ..."
8156 (if (and js2-strict-cond-assign-warning
8157 (js2-assign-node-p pn))
8158 (js2-add-strict-warning "msg.equal.as.assign" nil
8159 (js2-node-pos pn)
8160 (+ (js2-node-pos pn)
8161 (js2-node-len pn))))
8162 (list pn lp rp)))
8163
8164 (defun js2-parse-if ()
8165 "Parser for if-statement. Last matched token must be js2-IF."
8166 (let ((pos (js2-current-token-beg))
8167 cond if-true if-false else-pos end pn)
8168 (setq cond (js2-parse-condition)
8169 if-true (js2-parse-statement)
8170 if-false (if (js2-match-token js2-ELSE)
8171 (progn
8172 (setq else-pos (- (js2-current-token-beg) pos))
8173 (js2-parse-statement)))
8174 end (js2-node-end (or if-false if-true))
8175 pn (make-js2-if-node :pos pos
8176 :len (- end pos)
8177 :condition (car cond)
8178 :then-part if-true
8179 :else-part if-false
8180 :else-pos else-pos
8181 :lp (js2-relpos (cl-second cond) pos)
8182 :rp (js2-relpos (cl-third cond) pos)))
8183 (js2-node-add-children pn (car cond) if-true if-false)
8184 pn))
8185
8186 (defun js2-parse-import ()
8187 "Parse import statement. The current token must be js2-IMPORT."
8188 (unless (js2-ast-root-p js2-current-scope)
8189 (js2-report-error "msg.mod.import.decl.at.top.level"))
8190 (let ((beg (js2-current-token-beg)))
8191 (cond ((js2-match-token js2-STRING)
8192 (make-js2-import-node
8193 :pos beg
8194 :len (- (js2-current-token-end) beg)
8195 :module-id (js2-current-token-string)))
8196 (t
8197 (let* ((import-clause (js2-parse-import-clause))
8198 (from-clause (and import-clause (js2-parse-from-clause)))
8199 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8200 (node (make-js2-import-node
8201 :pos beg
8202 :len (- (js2-current-token-end) beg)
8203 :import import-clause
8204 :from from-clause
8205 :module-id module-id)))
8206 (when import-clause
8207 (js2-node-add-children node import-clause))
8208 (when from-clause
8209 (js2-node-add-children node from-clause))
8210 node)))))
8211
8212 (defun js2-parse-import-clause ()
8213 "Parse the bindings in an import statement.
8214 This can take many forms:
8215
8216 ImportedDefaultBinding -> 'foo'
8217 NameSpaceImport -> '* as lib'
8218 NamedImports -> '{foo as bar, bang}'
8219 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8220 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8221
8222 Try to match namespace imports and named imports first because nothing can
8223 come after them. If it is an imported default binding, then it could have named
8224 imports or a namespace import that follows it.
8225 "
8226 (let* ((beg (js2-current-token-beg))
8227 (clause (make-js2-import-clause-node
8228 :pos beg))
8229 (children (list)))
8230 (cond
8231 ((js2-match-token js2-MUL)
8232 (let ((ns-import (js2-parse-namespace-import)))
8233 (when ns-import
8234 (let ((name-node (js2-namespace-import-node-name ns-import)))
8235 (js2-define-symbol
8236 js2-LET (js2-name-node-name name-node) name-node t)))
8237 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8238 (push ns-import children)))
8239 ((js2-match-token js2-LC)
8240 (let ((imports (js2-parse-export-bindings t)))
8241 (setf (js2-import-clause-node-named-imports clause) imports)
8242 (dolist (import imports)
8243 (push import children)
8244 (let ((name-node (js2-export-binding-node-local-name import)))
8245 (when name-node
8246 (js2-define-symbol
8247 js2-LET (js2-name-node-name name-node) name-node t))))))
8248 ((= (js2-peek-token) js2-NAME)
8249 (let ((binding (js2-maybe-parse-export-binding)))
8250 (let ((node-name (js2-export-binding-node-local-name binding)))
8251 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8252 (setf (js2-import-clause-node-default-binding clause) binding)
8253 (push binding children))
8254 (when (js2-match-token js2-COMMA)
8255 (cond
8256 ((js2-match-token js2-MUL)
8257 (let ((ns-import (js2-parse-namespace-import)))
8258 (let ((name-node (js2-namespace-import-node-name ns-import)))
8259 (js2-define-symbol
8260 js2-LET (js2-name-node-name name-node) name-node t))
8261 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8262 (push ns-import children)))
8263 ((js2-match-token js2-LC)
8264 (let ((imports (js2-parse-export-bindings t)))
8265 (setf (js2-import-clause-node-named-imports clause) imports)
8266 (dolist (import imports)
8267 (push import children)
8268 (let ((name-node (js2-export-binding-node-local-name import)))
8269 (when name-node
8270 (js2-define-symbol
8271 js2-LET (js2-name-node-name name-node) name-node t))))))
8272 (t (js2-report-error "msg.syntax")))))
8273 (t (js2-report-error "msg.mod.declaration.after.import")))
8274 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8275 (apply #'js2-node-add-children clause children)
8276 clause))
8277
8278 (defun js2-parse-namespace-import ()
8279 "Parse a namespace import expression such as '* as bar'.
8280 The current token must be js2-MUL."
8281 (let ((beg (js2-current-token-beg)))
8282 (when (js2-must-match js2-NAME "msg.syntax")
8283 (if (equal "as" (js2-current-token-string))
8284 (when (js2-must-match-prop-name "msg.syntax")
8285 (let ((node (make-js2-namespace-import-node
8286 :pos beg
8287 :len (- (js2-current-token-end) beg)
8288 :name (make-js2-name-node
8289 :pos (js2-current-token-beg)
8290 :len (js2-current-token-end)
8291 :name (js2-current-token-string)))))
8292 (js2-node-add-children node (js2-namespace-import-node-name node))
8293 node))
8294 (js2-unget-token)
8295 (js2-report-error "msg.syntax")))))
8296
8297
8298 (defun js2-parse-from-clause ()
8299 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8300 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8301 (let ((beg (js2-current-token-beg)))
8302 (if (equal "from" (js2-current-token-string))
8303 (cond
8304 ((js2-match-token js2-STRING)
8305 (make-js2-from-clause-node
8306 :pos beg
8307 :len (- (js2-current-token-end) beg)
8308 :module-id (js2-current-token-string)
8309 :metadata-p nil))
8310 ((js2-match-token js2-THIS)
8311 (when (js2-must-match-name "msg.mod.spec.after.from")
8312 (if (equal "module" (js2-current-token-string))
8313 (make-js2-from-clause-node
8314 :pos beg
8315 :len (- (js2-current-token-end) beg)
8316 :module-id "this"
8317 :metadata-p t)
8318 (js2-unget-token)
8319 (js2-unget-token)
8320 (js2-report-error "msg.mod.spec.after.from")
8321 nil)))
8322 (t (js2-report-error "msg.mod.spec.after.from") nil))
8323 (js2-unget-token)
8324 (js2-report-error "msg.mod.from.after.import.spec.set")
8325 nil))))
8326
8327 (defun js2-parse-export-bindings (&optional import-p)
8328 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8329 {foo as bar, baz as bang}. The current token must be
8330 js2-LC. Return a lisp list of js2-export-binding-node"
8331 (let ((bindings (list)))
8332 (while
8333 (let ((binding (js2-maybe-parse-export-binding)))
8334 (when binding
8335 (push binding bindings))
8336 (js2-match-token js2-COMMA)))
8337 (when (js2-must-match js2-RC (if import-p
8338 "msg.mod.rc.after.import.spec.list"
8339 "msg.mod.rc.after.export.spec.list"))
8340 (reverse bindings))))
8341
8342 (defun js2-maybe-parse-export-binding ()
8343 "Attempt to parse a binding expression found inside an import/export statement.
8344 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8345 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8346 js2-export-binding-node and consume all the tokens. If it does not match, it
8347 consumes no tokens."
8348 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8349 (beg (js2-current-token-beg))
8350 (extern-name-len (js2-current-token-len))
8351 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8352 (aref js2-kwd-tokens (js2-current-token-type)))))
8353 (if extern-name
8354 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8355 (if (and as (equal "as" (js2-current-token-string)))
8356 (let ((name
8357 (or
8358 (and (js2-match-token js2-DEFAULT) "default")
8359 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8360 (if name
8361 (let ((node (make-js2-export-binding-node
8362 :pos beg
8363 :len (- (js2-current-token-end) beg)
8364 :local-name (make-js2-name-node
8365 :name name
8366 :pos (js2-current-token-beg)
8367 :len (js2-current-token-len))
8368 :extern-name (make-js2-name-node
8369 :name extern-name
8370 :pos beg
8371 :len extern-name-len))))
8372 (js2-node-add-children
8373 node
8374 (js2-export-binding-node-local-name node)
8375 (js2-export-binding-node-extern-name node))
8376 node)
8377 (js2-unget-token)
8378 nil))
8379 (when as (js2-unget-token))
8380 (let* ((name-node (make-js2-name-node
8381 :name (js2-current-token-string)
8382 :pos (js2-current-token-beg)
8383 :len (js2-current-token-len)))
8384 (node (make-js2-export-binding-node
8385 :pos (js2-current-token-beg)
8386 :len (js2-current-token-len)
8387 :local-name name-node
8388 :extern-name name-node)))
8389 (when is-reserved-name
8390 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8391 (js2-node-add-children node name-node)
8392 node)))
8393 nil)))
8394
8395 (defun js2-parse-switch ()
8396 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8397 (let ((pos (js2-current-token-beg))
8398 tt pn discriminant has-default case-expr case-node
8399 case-pos cases stmt lp)
8400 (if (js2-must-match js2-LP "msg.no.paren.switch")
8401 (setq lp (js2-current-token-beg)))
8402 (setq discriminant (js2-parse-expr)
8403 pn (make-js2-switch-node :discriminant discriminant
8404 :pos pos
8405 :lp (js2-relpos lp pos)))
8406 (js2-node-add-children pn discriminant)
8407 (js2-enter-switch pn)
8408 (unwind-protect
8409 (progn
8410 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8411 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8412 (js2-must-match js2-LC "msg.no.brace.switch")
8413 (catch 'break
8414 (while t
8415 (setq tt (js2-next-token)
8416 case-pos (js2-current-token-beg))
8417 (cond
8418 ((= tt js2-RC)
8419 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8420 (throw 'break nil)) ; done
8421 ((= tt js2-CASE)
8422 (setq case-expr (js2-parse-expr))
8423 (js2-must-match js2-COLON "msg.no.colon.case"))
8424 ((= tt js2-DEFAULT)
8425 (if has-default
8426 (js2-report-error "msg.double.switch.default"))
8427 (setq has-default t
8428 case-expr nil)
8429 (js2-must-match js2-COLON "msg.no.colon.case"))
8430 (t
8431 (js2-report-error "msg.bad.switch")
8432 (throw 'break nil)))
8433 (setq case-node (make-js2-case-node :pos case-pos
8434 :len (- (js2-current-token-end) case-pos)
8435 :expr case-expr))
8436 (js2-node-add-children case-node case-expr)
8437 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8438 (/= tt js2-CASE)
8439 (/= tt js2-DEFAULT)
8440 (/= tt js2-EOF))
8441 (setf stmt (js2-parse-statement)
8442 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8443 (js2-block-node-push case-node stmt))
8444 (push case-node cases)))
8445 ;; add cases last, as pushing reverses the order to be correct
8446 (dolist (kid cases)
8447 (js2-node-add-children pn kid)
8448 (push kid (js2-switch-node-cases pn)))
8449 pn) ; return value
8450 (js2-exit-switch))))
8451
8452 (defun js2-parse-while ()
8453 "Parser for while-statement. Last matched token must be js2-WHILE."
8454 (let ((pos (js2-current-token-beg))
8455 (pn (make-js2-while-node))
8456 cond body)
8457 (js2-enter-loop pn)
8458 (unwind-protect
8459 (progn
8460 (setf cond (js2-parse-condition)
8461 (js2-while-node-condition pn) (car cond)
8462 body (js2-parse-statement)
8463 (js2-while-node-body pn) body
8464 (js2-node-len pn) (- (js2-node-end body) pos)
8465 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8466 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8467 (js2-node-add-children pn body (car cond)))
8468 (js2-exit-loop))
8469 pn))
8470
8471 (defun js2-parse-do ()
8472 "Parser for do-statement. Last matched token must be js2-DO."
8473 (let ((pos (js2-current-token-beg))
8474 (pn (make-js2-do-node))
8475 cond body end)
8476 (js2-enter-loop pn)
8477 (unwind-protect
8478 (progn
8479 (setq body (js2-parse-statement))
8480 (js2-must-match js2-WHILE "msg.no.while.do")
8481 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8482 cond (js2-parse-condition)
8483 (js2-do-node-condition pn) (car cond)
8484 (js2-do-node-body pn) body
8485 end js2-ts-cursor
8486 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8487 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8488 (js2-node-add-children pn (car cond) body))
8489 (js2-exit-loop))
8490 ;; Always auto-insert semicolon to follow SpiderMonkey:
8491 ;; It is required by ECMAScript but is ignored by the rest of
8492 ;; world; see bug 238945
8493 (if (js2-match-token js2-SEMI)
8494 (setq end js2-ts-cursor))
8495 (setf (js2-node-len pn) (- end pos))
8496 pn))
8497
8498 (defun js2-parse-export ()
8499 "Parse an export statement.
8500 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8501 expressions should only be either hoistable expressions (function or generator)
8502 or assignment expressions, but there is no checking to enforce that and so it
8503 will parse without error a small subset of
8504 invalid export statements."
8505 (unless (js2-ast-root-p js2-current-scope)
8506 (js2-report-error "msg.mod.export.decl.at.top.level"))
8507 (let ((beg (js2-current-token-beg))
8508 (children (list))
8509 exports-list from-clause declaration default)
8510 (cond
8511 ((js2-match-token js2-MUL)
8512 (setq from-clause (js2-parse-from-clause))
8513 (when from-clause
8514 (push from-clause children)))
8515 ((js2-match-token js2-LC)
8516 (setq exports-list (js2-parse-export-bindings))
8517 (when exports-list
8518 (dolist (export exports-list)
8519 (push export children)))
8520 (when (js2-match-token js2-NAME)
8521 (if (equal "from" (js2-current-token-string))
8522 (progn
8523 (js2-unget-token)
8524 (setq from-clause (js2-parse-from-clause)))
8525 (js2-unget-token))))
8526 ((js2-match-token js2-DEFAULT)
8527 (setq default (js2-parse-expr)))
8528 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8529 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8530 (t
8531 (setq declaration (js2-parse-expr))))
8532 (when from-clause
8533 (push from-clause children))
8534 (when declaration
8535 (push declaration children)
8536 (when (not (js2-function-node-p declaration))
8537 (js2-auto-insert-semicolon declaration)))
8538 (when default
8539 (push default children)
8540 (when (not (js2-function-node-p default))
8541 (js2-auto-insert-semicolon default)))
8542 (let ((node (make-js2-export-node
8543 :pos beg
8544 :len (- (js2-current-token-end) beg)
8545 :exports-list exports-list
8546 :from-clause from-clause
8547 :declaration declaration
8548 :default default)))
8549 (apply #'js2-node-add-children node children)
8550 node)))
8551
8552 (defun js2-parse-for ()
8553 "Parse a for, for-in or for each-in statement.
8554 Last matched token must be js2-FOR."
8555 (let ((for-pos (js2-current-token-beg))
8556 (tmp-scope (make-js2-scope))
8557 pn is-for-each is-for-in-or-of is-for-of
8558 in-pos each-pos tmp-pos
8559 init ; Node init is also foo in 'foo in object'.
8560 cond ; Node cond is also object in 'foo in object'.
8561 incr ; 3rd section of for-loop initializer.
8562 body tt lp rp)
8563 ;; See if this is a for each () instead of just a for ()
8564 (when (js2-match-token js2-NAME)
8565 (if (string= "each" (js2-current-token-string))
8566 (progn
8567 (setq is-for-each t
8568 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8569 (js2-record-face 'font-lock-keyword-face))
8570 (js2-report-error "msg.no.paren.for")))
8571 (if (js2-must-match js2-LP "msg.no.paren.for")
8572 (setq lp (- (js2-current-token-beg) for-pos)))
8573 (setq tt (js2-get-token))
8574 ;; Capture identifiers inside parens. We can't create the node
8575 ;; (and use it as the current scope) until we know its type.
8576 (js2-push-scope tmp-scope)
8577 (unwind-protect
8578 (progn
8579 ;; parse init clause
8580 (let ((js2-in-for-init t)) ; set as dynamic variable
8581 (cond
8582 ((= tt js2-SEMI)
8583 (js2-unget-token)
8584 (setq init (make-js2-empty-expr-node)))
8585 ((or (= tt js2-VAR) (= tt js2-LET))
8586 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8587 (t
8588 (js2-unget-token)
8589 (setq init (js2-parse-expr)))))
8590 (if (or (js2-match-token js2-IN)
8591 (and (>= js2-language-version 200)
8592 (js2-match-contextual-kwd "of")
8593 (setq is-for-of t)))
8594 (setq is-for-in-or-of t
8595 in-pos (- (js2-current-token-beg) for-pos)
8596 ;; scope of iteration target object is not the scope we've created above.
8597 ;; stash current scope temporary.
8598 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8599 (js2-parse-expr))) ; object over which we're iterating
8600 ;; else ordinary for loop - parse cond and incr
8601 (js2-must-match js2-SEMI "msg.no.semi.for")
8602 (setq cond (if (= (js2-peek-token) js2-SEMI)
8603 (make-js2-empty-expr-node) ; no loop condition
8604 (js2-parse-expr)))
8605 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8606 (setq tmp-pos (js2-current-token-end)
8607 incr (if (= (js2-peek-token) js2-RP)
8608 (make-js2-empty-expr-node :pos tmp-pos)
8609 (js2-parse-expr)))))
8610 (js2-pop-scope))
8611 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8612 (setq rp (- (js2-current-token-beg) for-pos)))
8613 (if (not is-for-in-or-of)
8614 (setq pn (make-js2-for-node :init init
8615 :condition cond
8616 :update incr
8617 :lp lp
8618 :rp rp))
8619 ;; cond could be null if 'in obj' got eaten by the init node.
8620 (if (js2-infix-node-p init)
8621 ;; it was (foo in bar) instead of (var foo in bar)
8622 (setq cond (js2-infix-node-right init)
8623 init (js2-infix-node-left init))
8624 (if (and (js2-var-decl-node-p init)
8625 (> (length (js2-var-decl-node-kids init)) 1))
8626 (js2-report-error "msg.mult.index")))
8627 (setq pn (make-js2-for-in-node :iterator init
8628 :object cond
8629 :in-pos in-pos
8630 :foreach-p is-for-each
8631 :each-pos each-pos
8632 :forof-p is-for-of
8633 :lp lp
8634 :rp rp)))
8635 ;; Transplant the declarations.
8636 (setf (js2-scope-symbol-table pn)
8637 (js2-scope-symbol-table tmp-scope))
8638 (unwind-protect
8639 (progn
8640 (js2-enter-loop pn)
8641 ;; We have to parse the body -after- creating the loop node,
8642 ;; so that the loop node appears in the js2-loop-set, allowing
8643 ;; break/continue statements to find the enclosing loop.
8644 (setf body (js2-parse-statement)
8645 (js2-loop-node-body pn) body
8646 (js2-node-pos pn) for-pos
8647 (js2-node-len pn) (- (js2-node-end body) for-pos))
8648 (js2-node-add-children pn init cond incr body))
8649 ;; finally
8650 (js2-exit-loop))
8651 pn))
8652
8653 (defun js2-parse-try ()
8654 "Parse a try statement. Last matched token must be js2-TRY."
8655 (let ((try-pos (js2-current-token-beg))
8656 try-end
8657 try-block
8658 catch-blocks
8659 finally-block
8660 saw-default-catch
8661 peek)
8662 (if (/= (js2-peek-token) js2-LC)
8663 (js2-report-error "msg.no.brace.try"))
8664 (setq try-block (js2-parse-statement)
8665 try-end (js2-node-end try-block)
8666 peek (js2-peek-token))
8667 (cond
8668 ((= peek js2-CATCH)
8669 (while (js2-match-token js2-CATCH)
8670 (let* ((catch-pos (js2-current-token-beg))
8671 (catch-node (make-js2-catch-node :pos catch-pos))
8672 param
8673 guard-kwd
8674 catch-cond
8675 lp rp)
8676 (if saw-default-catch
8677 (js2-report-error "msg.catch.unreachable"))
8678 (if (js2-must-match js2-LP "msg.no.paren.catch")
8679 (setq lp (- (js2-current-token-beg) catch-pos)))
8680 (js2-push-scope catch-node)
8681 (let ((tt (js2-peek-token)))
8682 (cond
8683 ;; Destructuring pattern:
8684 ;; catch ({ message, file }) { ... }
8685 ((or (= tt js2-LB) (= tt js2-LC))
8686 (js2-get-token)
8687 (setq param (js2-parse-destruct-primary-expr))
8688 (js2-define-destruct-symbols param js2-LET nil))
8689 ;; Simple name.
8690 (t
8691 (js2-must-match-name "msg.bad.catchcond")
8692 (setq param (js2-create-name-node))
8693 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8694 ;; Catch condition.
8695 (if (js2-match-token js2-IF)
8696 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8697 catch-cond (js2-parse-expr))
8698 (setq saw-default-catch t))
8699 (if (js2-must-match js2-RP "msg.bad.catchcond")
8700 (setq rp (- (js2-current-token-beg) catch-pos)))
8701 (js2-must-match js2-LC "msg.no.brace.catchblock")
8702 (js2-parse-statements catch-node)
8703 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8704 (setq try-end (js2-current-token-end)))
8705 (js2-pop-scope)
8706 (setf (js2-node-len catch-node) (- try-end catch-pos)
8707 (js2-catch-node-param catch-node) param
8708 (js2-catch-node-guard-expr catch-node) catch-cond
8709 (js2-catch-node-guard-kwd catch-node) guard-kwd
8710 (js2-catch-node-lp catch-node) lp
8711 (js2-catch-node-rp catch-node) rp)
8712 (js2-node-add-children catch-node param catch-cond)
8713 (push catch-node catch-blocks))))
8714 ((/= peek js2-FINALLY)
8715 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8716 (js2-node-pos try-block)
8717 (- (setq try-end (js2-node-end try-block))
8718 (js2-node-pos try-block)))))
8719 (when (js2-match-token js2-FINALLY)
8720 (let ((finally-pos (js2-current-token-beg))
8721 (block (js2-parse-statement)))
8722 (setq try-end (js2-node-end block)
8723 finally-block (make-js2-finally-node :pos finally-pos
8724 :len (- try-end finally-pos)
8725 :body block))
8726 (js2-node-add-children finally-block block)))
8727 (let ((pn (make-js2-try-node :pos try-pos
8728 :len (- try-end try-pos)
8729 :try-block try-block
8730 :finally-block finally-block)))
8731 (js2-node-add-children pn try-block finally-block)
8732 ;; Push them onto the try-node, which reverses and corrects their order.
8733 (dolist (cb catch-blocks)
8734 (js2-node-add-children pn cb)
8735 (push cb (js2-try-node-catch-clauses pn)))
8736 pn)))
8737
8738 (defun js2-parse-throw ()
8739 "Parser for throw-statement. Last matched token must be js2-THROW."
8740 (let ((pos (js2-current-token-beg))
8741 expr pn)
8742 (if (= (js2-peek-token-or-eol) js2-EOL)
8743 ;; ECMAScript does not allow new lines before throw expression,
8744 ;; see bug 256617
8745 (js2-report-error "msg.bad.throw.eol"))
8746 (setq expr (js2-parse-expr)
8747 pn (make-js2-throw-node :pos pos
8748 :len (- (js2-node-end expr) pos)
8749 :expr expr))
8750 (js2-node-add-children pn expr)
8751 pn))
8752
8753 (defun js2-match-jump-label-name (label-name)
8754 "If break/continue specified a label, return that label's labeled stmt.
8755 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8756 does not match an existing label, reports an error and returns nil."
8757 (let ((bundle (cdr (assoc label-name js2-label-set))))
8758 (if (null bundle)
8759 (js2-report-error "msg.undef.label"))
8760 bundle))
8761
8762 (defun js2-parse-break ()
8763 "Parser for break-statement. Last matched token must be js2-BREAK."
8764 (let ((pos (js2-current-token-beg))
8765 (end (js2-current-token-end))
8766 break-target ; statement to break from
8767 break-label ; in "break foo", name-node representing the foo
8768 labels ; matching labeled statement to break to
8769 pn)
8770 (when (eq (js2-peek-token-or-eol) js2-NAME)
8771 (js2-get-token)
8772 (setq break-label (js2-create-name-node)
8773 end (js2-node-end break-label)
8774 ;; matchJumpLabelName only matches if there is one
8775 labels (js2-match-jump-label-name (js2-current-token-string))
8776 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8777 (unless (or break-target break-label)
8778 ;; no break target specified - try for innermost enclosing loop/switch
8779 (if (null js2-loop-and-switch-set)
8780 (unless break-label
8781 (js2-report-error "msg.bad.break" nil pos (length "break")))
8782 (setq break-target (car js2-loop-and-switch-set))))
8783 (setq pn (make-js2-break-node :pos pos
8784 :len (- end pos)
8785 :label break-label
8786 :target break-target))
8787 (js2-node-add-children pn break-label) ; but not break-target
8788 pn))
8789
8790 (defun js2-parse-continue ()
8791 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8792 (let ((pos (js2-current-token-beg))
8793 (end (js2-current-token-end))
8794 label ; optional user-specified label, a `js2-name-node'
8795 labels ; current matching labeled stmt, if any
8796 target ; the `js2-loop-node' target of this continue stmt
8797 pn)
8798 (when (= (js2-peek-token-or-eol) js2-NAME)
8799 (js2-get-token)
8800 (setq label (js2-create-name-node)
8801 end (js2-node-end label)
8802 ;; matchJumpLabelName only matches if there is one
8803 labels (js2-match-jump-label-name (js2-current-token-string))))
8804 (cond
8805 ((null labels) ; no current label to go to
8806 (if (null js2-loop-set) ; no loop to continue to
8807 (js2-report-error "msg.continue.outside" nil pos
8808 (length "continue"))
8809 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8810 (t
8811 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8812 (setq target (js2-labeled-stmt-node-stmt labels))
8813 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8814 (setq pn (make-js2-continue-node :pos pos
8815 :len (- end pos)
8816 :label label
8817 :target target))
8818 (js2-node-add-children pn label) ; but not target - it's not our child
8819 pn))
8820
8821 (defun js2-parse-with ()
8822 "Parser for with-statement. Last matched token must be js2-WITH."
8823 (let ((pos (js2-current-token-beg))
8824 obj body pn lp rp)
8825 (if (js2-must-match js2-LP "msg.no.paren.with")
8826 (setq lp (js2-current-token-beg)))
8827 (setq obj (js2-parse-expr))
8828 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8829 (setq rp (js2-current-token-beg)))
8830 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8831 (setq body (js2-parse-statement)))
8832 (setq pn (make-js2-with-node :pos pos
8833 :len (- (js2-node-end body) pos)
8834 :object obj
8835 :body body
8836 :lp (js2-relpos lp pos)
8837 :rp (js2-relpos rp pos)))
8838 (js2-node-add-children pn obj body)
8839 pn))
8840
8841 (defun js2-parse-const-var ()
8842 "Parser for var- or const-statement.
8843 Last matched token must be js2-CONST or js2-VAR."
8844 (let ((tt (js2-current-token-type))
8845 (pos (js2-current-token-beg))
8846 expr pn)
8847 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8848 pn (make-js2-expr-stmt-node :pos pos
8849 :len (- (js2-node-end expr) pos)
8850 :expr expr))
8851 (js2-node-add-children pn expr)
8852 pn))
8853
8854 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8855 (let ((pn (make-js2-expr-stmt-node :pos pos
8856 :len (js2-node-len expr)
8857 :type (if (js2-inside-function)
8858 js2-EXPR_VOID
8859 js2-EXPR_RESULT)
8860 :expr expr)))
8861 (if add-child
8862 (js2-node-add-children pn expr))
8863 pn))
8864
8865 (defun js2-parse-let-stmt ()
8866 "Parser for let-statement. Last matched token must be js2-LET."
8867 (let ((pos (js2-current-token-beg))
8868 expr pn)
8869 (if (= (js2-peek-token) js2-LP)
8870 ;; let expression in statement context
8871 (setq expr (js2-parse-let pos 'statement)
8872 pn (js2-wrap-with-expr-stmt pos expr t))
8873 ;; else we're looking at a statement like let x=6, y=7;
8874 (setf expr (js2-parse-variables js2-LET pos)
8875 pn (js2-wrap-with-expr-stmt pos expr t)
8876 (js2-node-type pn) js2-EXPR_RESULT))
8877 pn))
8878
8879 (defun js2-parse-ret-yield ()
8880 (js2-parse-return-or-yield (js2-current-token-type) nil))
8881
8882 (defconst js2-parse-return-stmt-enders
8883 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8884
8885 (defsubst js2-now-all-set (before after mask)
8886 "Return whether or not the bits in the mask have changed to all set.
8887 BEFORE is bits before change, AFTER is bits after change, and MASK is
8888 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8889 but not BEFORE."
8890 (and (/= (logand before mask) mask)
8891 (= (logand after mask) mask)))
8892
8893 (defun js2-parse-return-or-yield (tt expr-context)
8894 (let* ((pos (js2-current-token-beg))
8895 (end (js2-current-token-end))
8896 (before js2-end-flags)
8897 (inside-function (js2-inside-function))
8898 (gen-type (and inside-function (js2-function-node-generator-type
8899 js2-current-script-or-fn)))
8900 e ret name yield-star-p)
8901 (unless inside-function
8902 (js2-report-error (if (eq tt js2-RETURN)
8903 "msg.bad.return"
8904 "msg.bad.yield")))
8905 (when (and inside-function
8906 (eq gen-type 'STAR)
8907 (js2-match-token js2-MUL))
8908 (setq yield-star-p t))
8909 ;; This is ugly, but we don't want to require a semicolon.
8910 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8911 (setq e (js2-parse-expr)
8912 end (js2-node-end e)))
8913 (cond
8914 ((eq tt js2-RETURN)
8915 (js2-set-flag js2-end-flags (if (null e)
8916 js2-end-returns
8917 js2-end-returns-value))
8918 (setq ret (make-js2-return-node :pos pos
8919 :len (- end pos)
8920 :retval e))
8921 (js2-node-add-children ret e)
8922 ;; See if we need a strict mode warning.
8923 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8924 ;; more thorough and accurate than this before/after flag check.
8925 ;; E.g. if there's a finally-block that always returns, we shouldn't
8926 ;; show a warning generated by inconsistent returns in the catch blocks.
8927 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8928 ;; so we know which returns/yields to highlight, and we should get rid of
8929 ;; all the checking in `js2-parse-return-or-yield'.
8930 (if (and js2-strict-inconsistent-return-warning
8931 (js2-now-all-set before js2-end-flags
8932 (logior js2-end-returns js2-end-returns-value)))
8933 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8934 ((eq gen-type 'COMPREHENSION)
8935 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8936 ;; like SpiderMonkey does.
8937 (js2-report-error "msg.syntax" nil pos 5))
8938 (t
8939 (setq ret (make-js2-yield-node :pos pos
8940 :len (- end pos)
8941 :value e
8942 :star-p yield-star-p))
8943 (js2-node-add-children ret e)
8944 (unless expr-context
8945 (setq e ret
8946 ret (js2-wrap-with-expr-stmt pos e t))
8947 (js2-set-requires-activation)
8948 (js2-set-is-generator))))
8949 ;; see if we are mixing yields and value returns.
8950 (when (and inside-function
8951 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8952 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8953 'LEGACY))
8954 (setq name (js2-function-name js2-current-script-or-fn))
8955 (if (zerop (length name))
8956 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8957 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8958 ret))
8959
8960 (defun js2-parse-debugger ()
8961 (make-js2-keyword-node :type js2-DEBUGGER))
8962
8963 (defun js2-parse-block ()
8964 "Parser for a curly-delimited statement block.
8965 Last token matched must be `js2-LC'."
8966 (let ((pos (js2-current-token-beg))
8967 (pn (make-js2-scope)))
8968 (js2-push-scope pn)
8969 (unwind-protect
8970 (progn
8971 (js2-parse-statements pn)
8972 (js2-must-match js2-RC "msg.no.brace.block")
8973 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8974 (js2-pop-scope))
8975 pn))
8976
8977 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8978 (defun js2-parse-semi ()
8979 "Parse a statement or handle an error.
8980 Current token type is `js2-SEMI' or `js2-ERROR'."
8981 (let ((tt (js2-current-token-type)) pos len)
8982 (if (eq tt js2-SEMI)
8983 (make-js2-empty-expr-node :len 1)
8984 (setq pos (js2-current-token-beg)
8985 len (- (js2-current-token-end) pos))
8986 (js2-report-error "msg.syntax" nil pos len)
8987 (make-js2-error-node :pos pos :len len))))
8988
8989 (defun js2-parse-default-xml-namespace ()
8990 "Parse a `default xml namespace = <expr>' e4x statement."
8991 (let ((pos (js2-current-token-beg))
8992 end len expr unary)
8993 (js2-must-have-xml)
8994 (js2-set-requires-activation)
8995 (setq len (- js2-ts-cursor pos))
8996 (unless (and (js2-match-token js2-NAME)
8997 (string= (js2-current-token-string) "xml"))
8998 (js2-report-error "msg.bad.namespace" nil pos len))
8999 (unless (and (js2-match-token js2-NAME)
9000 (string= (js2-current-token-string) "namespace"))
9001 (js2-report-error "msg.bad.namespace" nil pos len))
9002 (unless (js2-match-token js2-ASSIGN)
9003 (js2-report-error "msg.bad.namespace" nil pos len))
9004 (setq expr (js2-parse-expr)
9005 end (js2-node-end expr)
9006 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9007 :pos pos
9008 :len (- end pos)
9009 :operand expr))
9010 (js2-node-add-children unary expr)
9011 (make-js2-expr-stmt-node :pos pos
9012 :len (- end pos)
9013 :expr unary)))
9014
9015 (defun js2-record-label (label bundle)
9016 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9017 (js2-get-token)
9018 (let ((name (js2-label-node-name label))
9019 labeled-stmt
9020 dup)
9021 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9022 ;; flag both labels if possible when used in editing mode
9023 (if (and js2-parse-ide-mode
9024 (setq dup (js2-get-label-by-name labeled-stmt name)))
9025 (js2-report-error "msg.dup.label" nil
9026 (js2-node-abs-pos dup) (js2-node-len dup)))
9027 (js2-report-error "msg.dup.label" nil
9028 (js2-node-pos label) (js2-node-len label)))
9029 (js2-labeled-stmt-node-add-label bundle label)
9030 (js2-node-add-children bundle label)
9031 ;; Add one reference to the bundle per label in `js2-label-set'
9032 (push (cons name bundle) js2-label-set)))
9033
9034 (defun js2-parse-name-or-label ()
9035 "Parser for identifier or label. Last token matched must be js2-NAME.
9036 Called when we found a name in a statement context. If it's a label, we gather
9037 up any following labels and the next non-label statement into a
9038 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9039 expression and return it wrapped in a `js2-expr-stmt-node'."
9040 (let ((pos (js2-current-token-beg))
9041 expr stmt bundle
9042 (continue t))
9043 ;; set check for label and call down to `js2-parse-primary-expr'
9044 (setq expr (js2-maybe-parse-label))
9045 (if (null expr)
9046 ;; Parse the non-label expression and wrap with expression stmt.
9047 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9048 ;; else parsed a label
9049 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9050 (js2-record-label expr bundle)
9051 ;; look for more labels
9052 (while (and continue (= (js2-get-token) js2-NAME))
9053 (if (setq expr (js2-maybe-parse-label))
9054 (js2-record-label expr bundle)
9055 (setq expr (js2-parse-expr)
9056 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9057 continue nil)
9058 (js2-auto-insert-semicolon stmt)))
9059 ;; no more labels; now parse the labeled statement
9060 (unwind-protect
9061 (unless stmt
9062 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9063 (js2-unget-token)
9064 (setq stmt (js2-statement-helper))))
9065 ;; remove the labels for this statement from the global set
9066 (dolist (label (js2-labeled-stmt-node-labels bundle))
9067 (setq js2-label-set (remove label js2-label-set))))
9068 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9069 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9070 (js2-node-add-children bundle stmt)
9071 bundle)))
9072
9073 (defun js2-maybe-parse-label ()
9074 (cl-assert (= (js2-current-token-type) js2-NAME))
9075 (let (label-pos
9076 (next-tt (js2-get-token))
9077 (label-end (js2-current-token-end)))
9078 ;; Do not consume colon, it is used as unwind indicator
9079 ;; to return to statementHelper.
9080 (js2-unget-token)
9081 (if (= next-tt js2-COLON)
9082 (prog2
9083 (setq label-pos (js2-current-token-beg))
9084 (make-js2-label-node :pos label-pos
9085 :len (- label-end label-pos)
9086 :name (js2-current-token-string))
9087 (js2-set-face label-pos
9088 label-end
9089 'font-lock-variable-name-face 'record))
9090 ;; Backtrack from the name token, too.
9091 (js2-unget-token)
9092 nil)))
9093
9094 (defun js2-parse-expr-stmt ()
9095 "Default parser in statement context, if no recognized statement found."
9096 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9097 (progn
9098 (js2-unget-token)
9099 (js2-parse-expr)) t))
9100
9101 (defun js2-parse-variables (decl-type pos)
9102 "Parse a comma-separated list of variable declarations.
9103 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9104
9105 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9106 For 'var' or 'const', the keyword should be the token last scanned.
9107
9108 POS is the position where the node should start. It's sometimes the
9109 var/const/let keyword, and other times the beginning of the first token
9110 in the first variable declaration.
9111
9112 Returns the parsed `js2-var-decl-node' expression node."
9113 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9114 :pos pos))
9115 destructuring kid-pos tt init name end nbeg nend vi
9116 (continue t))
9117 ;; Example:
9118 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9119 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9120 ;; var {a, b} = baz;
9121 (while continue
9122 (setq destructuring nil
9123 name nil
9124 tt (js2-get-token)
9125 kid-pos (js2-current-token-beg)
9126 end (js2-current-token-end)
9127 init nil)
9128 (if (or (= tt js2-LB) (= tt js2-LC))
9129 ;; Destructuring assignment, e.g., var [a, b] = ...
9130 (setq destructuring (js2-parse-destruct-primary-expr)
9131 end (js2-node-end destructuring))
9132 ;; Simple variable name
9133 (js2-unget-token)
9134 (when (js2-must-match-name "msg.bad.var")
9135 (setq name (js2-create-name-node)
9136 nbeg (js2-current-token-beg)
9137 nend (js2-current-token-end)
9138 end nend)
9139 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9140 (when (js2-match-token js2-ASSIGN)
9141 (setq init (js2-parse-assign-expr)
9142 end (js2-node-end init))
9143 (js2-record-imenu-functions init name))
9144 (when name
9145 (js2-set-face nbeg nend (if (js2-function-node-p init)
9146 'font-lock-function-name-face
9147 'font-lock-variable-name-face)
9148 'record))
9149 (setq vi (make-js2-var-init-node :pos kid-pos
9150 :len (- end kid-pos)
9151 :type decl-type))
9152 (if destructuring
9153 (progn
9154 (if (and (null init) (not js2-in-for-init))
9155 (js2-report-error "msg.destruct.assign.no.init"))
9156 (js2-define-destruct-symbols destructuring
9157 decl-type
9158 'font-lock-variable-name-face)
9159 (setf (js2-var-init-node-target vi) destructuring))
9160 (setf (js2-var-init-node-target vi) name))
9161 (setf (js2-var-init-node-initializer vi) init)
9162 (js2-node-add-children vi name destructuring init)
9163 (js2-block-node-push result vi)
9164 (unless (js2-match-token js2-COMMA)
9165 (setq continue nil)))
9166 (setf (js2-node-len result) (- end pos))
9167 result))
9168
9169 (defun js2-parse-let (pos &optional stmt-p)
9170 "Parse a let expression or statement.
9171 A let-expression is of the form `let (vars) expr'.
9172 A let-statement is of the form `let (vars) {statements}'.
9173 The third form of let is a variable declaration list, handled
9174 by `js2-parse-variables'."
9175 (let ((pn (make-js2-let-node :pos pos))
9176 beg vars body)
9177 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9178 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9179 (js2-push-scope pn)
9180 (unwind-protect
9181 (progn
9182 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9183 (if (js2-must-match js2-RP "msg.no.paren.let")
9184 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9185 (if (and stmt-p (js2-match-token js2-LC))
9186 ;; let statement
9187 (progn
9188 (setf beg (js2-current-token-beg) ; position stmt at LC
9189 body (js2-parse-statements))
9190 (js2-must-match js2-RC "msg.no.curly.let")
9191 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9192 (js2-node-len pn) (- (js2-current-token-end) pos)
9193 (js2-let-node-body pn) body
9194 (js2-node-type pn) js2-LET))
9195 ;; let expression
9196 (setf body (js2-parse-expr)
9197 (js2-node-len pn) (- (js2-node-end body) pos)
9198 (js2-let-node-body pn) body))
9199 (setf (js2-let-node-vars pn) vars)
9200 (js2-node-add-children pn vars body))
9201 (js2-pop-scope))
9202 pn))
9203
9204 (defun js2-define-new-symbol (decl-type name node &optional scope)
9205 (js2-scope-put-symbol (or scope js2-current-scope)
9206 name
9207 (make-js2-symbol decl-type name node)))
9208
9209 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9210 "Define a symbol in the current scope.
9211 If NODE is non-nil, it is the AST node associated with the symbol."
9212 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9213 (symbol (if defining-scope
9214 (js2-scope-get-symbol defining-scope name)))
9215 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9216 (pos (if node (js2-node-abs-pos node)))
9217 (len (if node (js2-node-len node))))
9218 (cond
9219 ((and symbol ; already defined
9220 (or (= sdt js2-CONST) ; old version is const
9221 (= decl-type js2-CONST) ; new version is const
9222 ;; two let-bound vars in this block have same name
9223 (and (= sdt js2-LET)
9224 (eq defining-scope js2-current-scope))))
9225 (js2-report-error
9226 (cond
9227 ((= sdt js2-CONST) "msg.const.redecl")
9228 ((= sdt js2-LET) "msg.let.redecl")
9229 ((= sdt js2-VAR) "msg.var.redecl")
9230 ((= sdt js2-FUNCTION) "msg.function.redecl")
9231 (t "msg.parm.redecl"))
9232 name pos len))
9233 ((= decl-type js2-LET)
9234 (if (and (not ignore-not-in-block)
9235 (or (= (js2-node-type js2-current-scope) js2-IF)
9236 (js2-loop-node-p js2-current-scope)))
9237 (js2-report-error "msg.let.decl.not.in.block")
9238 (js2-define-new-symbol decl-type name node)))
9239 ((or (= decl-type js2-VAR)
9240 (= decl-type js2-CONST)
9241 (= decl-type js2-FUNCTION))
9242 (if symbol
9243 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9244 (js2-add-strict-warning "msg.var.redecl" name)
9245 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9246 (js2-add-strict-warning "msg.var.hides.arg" name)))
9247 (js2-define-new-symbol decl-type name node
9248 js2-current-script-or-fn)))
9249 ((= decl-type js2-LP)
9250 (if symbol
9251 ;; must be duplicate parameter. Second parameter hides the
9252 ;; first, so go ahead and add the second pararameter
9253 (js2-report-warning "msg.dup.parms" name))
9254 (js2-define-new-symbol decl-type name node))
9255 (t (js2-code-bug)))))
9256
9257 (defun js2-parse-paren-expr-or-generator-comp ()
9258 (let ((px-pos (js2-current-token-beg)))
9259 (cond
9260 ((and (>= js2-language-version 200)
9261 (js2-match-token js2-FOR))
9262 (js2-parse-generator-comp px-pos))
9263 ((and (>= js2-language-version 200)
9264 (js2-match-token js2-RP))
9265 ;; Not valid expression syntax, but this is valid in an arrow
9266 ;; function with no params: () => body.
9267 (if (eq (js2-peek-token) js2-ARROW)
9268 ;; Return whatever, it will hopefully be rewinded and
9269 ;; reparsed when we reach the =>.
9270 (make-js2-keyword-node :type js2-NULL)
9271 (js2-report-error "msg.syntax")
9272 (make-js2-error-node)))
9273 (t
9274 (let* ((js2-in-for-init nil)
9275 (expr (js2-parse-expr))
9276 (pn (make-js2-paren-node :pos px-pos
9277 :expr expr)))
9278 (js2-node-add-children pn (js2-paren-node-expr pn))
9279 (js2-must-match js2-RP "msg.no.paren")
9280 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9281 pn)))))
9282
9283 (defun js2-parse-expr (&optional oneshot)
9284 (let* ((pn (js2-parse-assign-expr))
9285 (pos (js2-node-pos pn))
9286 left
9287 right
9288 op-pos)
9289 (while (and (not oneshot)
9290 (js2-match-token js2-COMMA))
9291 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9292 (if (= (js2-peek-token) js2-YIELD)
9293 (js2-report-error "msg.yield.parenthesized"))
9294 (setq right (js2-parse-assign-expr)
9295 left pn
9296 pn (make-js2-infix-node :type js2-COMMA
9297 :pos pos
9298 :len (- js2-ts-cursor pos)
9299 :op-pos op-pos
9300 :left left
9301 :right right))
9302 (js2-node-add-children pn left right))
9303 pn))
9304
9305 (defun js2-parse-assign-expr ()
9306 (let ((tt (js2-get-token))
9307 (pos (js2-current-token-beg))
9308 pn left right op-pos
9309 ts-state recorded-identifiers parsed-errors)
9310 (if (= tt js2-YIELD)
9311 (js2-parse-return-or-yield tt t)
9312 ;; Save the tokenizer state in case we find an arrow function
9313 ;; and have to rewind.
9314 (setq ts-state (make-js2-ts-state)
9315 recorded-identifiers js2-recorded-identifiers
9316 parsed-errors js2-parsed-errors)
9317 ;; not yield - parse assignment expression
9318 (setq pn (js2-parse-cond-expr)
9319 tt (js2-get-token))
9320 (cond
9321 ((and (<= js2-first-assign tt)
9322 (<= tt js2-last-assign))
9323 ;; tt express assignment (=, |=, ^=, ..., %=)
9324 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9325 left pn)
9326 (setq right (js2-parse-assign-expr)
9327 pn (make-js2-assign-node :type tt
9328 :pos pos
9329 :len (- (js2-node-end right) pos)
9330 :op-pos op-pos
9331 :left left
9332 :right right))
9333 (when js2-parse-ide-mode
9334 (js2-highlight-assign-targets pn left right)
9335 (js2-record-imenu-functions right left))
9336 ;; do this last so ide checks above can use absolute positions
9337 (js2-node-add-children pn left right))
9338 ((and (= tt js2-ARROW)
9339 (>= js2-language-version 200))
9340 (js2-ts-seek ts-state)
9341 (setq js2-recorded-identifiers recorded-identifiers
9342 js2-parsed-errors parsed-errors)
9343 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9344 (t
9345 (js2-unget-token)))
9346 pn)))
9347
9348 (defun js2-parse-cond-expr ()
9349 (let ((pos (js2-current-token-beg))
9350 (pn (js2-parse-or-expr))
9351 test-expr
9352 if-true
9353 if-false
9354 q-pos
9355 c-pos)
9356 (when (js2-match-token js2-HOOK)
9357 (setq q-pos (- (js2-current-token-beg) pos)
9358 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9359 (js2-must-match js2-COLON "msg.no.colon.cond")
9360 (setq c-pos (- (js2-current-token-beg) pos)
9361 if-false (js2-parse-assign-expr)
9362 test-expr pn
9363 pn (make-js2-cond-node :pos pos
9364 :len (- (js2-node-end if-false) pos)
9365 :test-expr test-expr
9366 :true-expr if-true
9367 :false-expr if-false
9368 :q-pos q-pos
9369 :c-pos c-pos))
9370 (js2-node-add-children pn test-expr if-true if-false))
9371 pn))
9372
9373 (defun js2-make-binary (type left parser)
9374 "Helper for constructing a binary-operator AST node.
9375 LEFT is the left-side-expression, already parsed, and the
9376 binary operator should have just been matched.
9377 PARSER is a function to call to parse the right operand,
9378 or a `js2-node' struct if it has already been parsed.
9379 FIXME: The latter option is unused?"
9380 (let* ((pos (js2-node-pos left))
9381 (op-pos (- (js2-current-token-beg) pos))
9382 (right (if (js2-node-p parser)
9383 parser
9384 (js2-get-token)
9385 (funcall parser)))
9386 (pn (make-js2-infix-node :type type
9387 :pos pos
9388 :len (- (js2-node-end right) pos)
9389 :op-pos op-pos
9390 :left left
9391 :right right)))
9392 (js2-node-add-children pn left right)
9393 pn))
9394
9395 (defun js2-parse-or-expr ()
9396 (let ((pn (js2-parse-and-expr)))
9397 (when (js2-match-token js2-OR)
9398 (setq pn (js2-make-binary js2-OR
9399 pn
9400 'js2-parse-or-expr)))
9401 pn))
9402
9403 (defun js2-parse-and-expr ()
9404 (let ((pn (js2-parse-bit-or-expr)))
9405 (when (js2-match-token js2-AND)
9406 (setq pn (js2-make-binary js2-AND
9407 pn
9408 'js2-parse-and-expr)))
9409 pn))
9410
9411 (defun js2-parse-bit-or-expr ()
9412 (let ((pn (js2-parse-bit-xor-expr)))
9413 (while (js2-match-token js2-BITOR)
9414 (setq pn (js2-make-binary js2-BITOR
9415 pn
9416 'js2-parse-bit-xor-expr)))
9417 pn))
9418
9419 (defun js2-parse-bit-xor-expr ()
9420 (let ((pn (js2-parse-bit-and-expr)))
9421 (while (js2-match-token js2-BITXOR)
9422 (setq pn (js2-make-binary js2-BITXOR
9423 pn
9424 'js2-parse-bit-and-expr)))
9425 pn))
9426
9427 (defun js2-parse-bit-and-expr ()
9428 (let ((pn (js2-parse-eq-expr)))
9429 (while (js2-match-token js2-BITAND)
9430 (setq pn (js2-make-binary js2-BITAND
9431 pn
9432 'js2-parse-eq-expr)))
9433 pn))
9434
9435 (defconst js2-parse-eq-ops
9436 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9437
9438 (defun js2-parse-eq-expr ()
9439 (let ((pn (js2-parse-rel-expr))
9440 tt)
9441 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9442 (setq pn (js2-make-binary tt
9443 pn
9444 'js2-parse-rel-expr)))
9445 (js2-unget-token)
9446 pn))
9447
9448 (defconst js2-parse-rel-ops
9449 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9450
9451 (defun js2-parse-rel-expr ()
9452 (let ((pn (js2-parse-shift-expr))
9453 (continue t)
9454 tt)
9455 (while continue
9456 (setq tt (js2-get-token))
9457 (cond
9458 ((and js2-in-for-init (= tt js2-IN))
9459 (js2-unget-token)
9460 (setq continue nil))
9461 ((memq tt js2-parse-rel-ops)
9462 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9463 (t
9464 (js2-unget-token)
9465 (setq continue nil))))
9466 pn))
9467
9468 (defconst js2-parse-shift-ops
9469 (list js2-LSH js2-URSH js2-RSH))
9470
9471 (defun js2-parse-shift-expr ()
9472 (let ((pn (js2-parse-add-expr))
9473 tt
9474 (continue t))
9475 (while continue
9476 (setq tt (js2-get-token))
9477 (if (memq tt js2-parse-shift-ops)
9478 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9479 (js2-unget-token)
9480 (setq continue nil)))
9481 pn))
9482
9483 (defun js2-parse-add-expr ()
9484 (let ((pn (js2-parse-mul-expr))
9485 tt
9486 (continue t))
9487 (while continue
9488 (setq tt (js2-get-token))
9489 (if (or (= tt js2-ADD) (= tt js2-SUB))
9490 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9491 (js2-unget-token)
9492 (setq continue nil)))
9493 pn))
9494
9495 (defconst js2-parse-mul-ops
9496 (list js2-MUL js2-DIV js2-MOD))
9497
9498 (defun js2-parse-mul-expr ()
9499 (let ((pn (js2-parse-unary-expr))
9500 tt
9501 (continue t))
9502 (while continue
9503 (setq tt (js2-get-token))
9504 (if (memq tt js2-parse-mul-ops)
9505 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9506 (js2-unget-token)
9507 (setq continue nil)))
9508 pn))
9509
9510 (defun js2-make-unary (type parser &rest args)
9511 "Make a unary node of type TYPE.
9512 PARSER is either a node (for postfix operators) or a function to call
9513 to parse the operand (for prefix operators)."
9514 (let* ((pos (js2-current-token-beg))
9515 (postfix (js2-node-p parser))
9516 (expr (if postfix
9517 parser
9518 (apply parser args)))
9519 end
9520 pn)
9521 (if postfix ; e.g. i++
9522 (setq pos (js2-node-pos expr)
9523 end (js2-current-token-end))
9524 (setq end (js2-node-end expr)))
9525 (setq pn (make-js2-unary-node :type type
9526 :pos pos
9527 :len (- end pos)
9528 :operand expr))
9529 (js2-node-add-children pn expr)
9530 pn))
9531
9532 (defconst js2-incrementable-node-types
9533 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9534 "Node types that can be the operand of a ++ or -- operator.")
9535
9536 (defun js2-check-bad-inc-dec (tt beg end unary)
9537 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9538 js2-incrementable-node-types)
9539 (js2-report-error (if (= tt js2-INC)
9540 "msg.bad.incr"
9541 "msg.bad.decr")
9542 nil beg (- end beg))))
9543
9544 (defun js2-parse-unary-expr ()
9545 (let ((tt (js2-current-token-type))
9546 pn expr beg end)
9547 (cond
9548 ((or (= tt js2-VOID)
9549 (= tt js2-NOT)
9550 (= tt js2-BITNOT)
9551 (= tt js2-TYPEOF))
9552 (js2-get-token)
9553 (js2-make-unary tt 'js2-parse-unary-expr))
9554 ((= tt js2-ADD)
9555 (js2-get-token)
9556 ;; Convert to special POS token in decompiler and parse tree
9557 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9558 ((= tt js2-SUB)
9559 (js2-get-token)
9560 ;; Convert to special NEG token in decompiler and parse tree
9561 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9562 ((or (= tt js2-INC)
9563 (= tt js2-DEC))
9564 (js2-get-token)
9565 (prog1
9566 (setq beg (js2-current-token-beg)
9567 end (js2-current-token-end)
9568 expr (js2-make-unary tt 'js2-parse-member-expr t))
9569 (js2-check-bad-inc-dec tt beg end expr)))
9570 ((= tt js2-DELPROP)
9571 (js2-get-token)
9572 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9573 ((= tt js2-ERROR)
9574 (js2-get-token)
9575 (make-js2-error-node)) ; try to continue
9576 ((and (= tt js2-LT)
9577 js2-compiler-xml-available)
9578 ;; XML stream encountered in expression.
9579 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9580 (t
9581 (setq pn (js2-parse-member-expr t)
9582 ;; Don't look across a newline boundary for a postfix incop.
9583 tt (js2-peek-token-or-eol))
9584 (when (or (= tt js2-INC) (= tt js2-DEC))
9585 (js2-get-token)
9586 (setf expr pn
9587 pn (js2-make-unary tt expr))
9588 (js2-node-set-prop pn 'postfix t)
9589 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9590 pn))))
9591
9592 (defun js2-parse-xml-initializer ()
9593 "Parse an E4X XML initializer.
9594 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9595 Then I'll postprocess the result, depending on whether we're in IDE
9596 mode or codegen mode, and generate the appropriate rewritten AST.
9597 IDE mode uses a rich AST that models the XML structure. Codegen mode
9598 just concatenates everything and makes a new XML or XMLList out of it."
9599 (let ((tt (js2-get-first-xml-token))
9600 pn-xml pn expr kids expr-pos
9601 (continue t)
9602 (first-token t))
9603 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9604 (js2-report-error "msg.syntax"))
9605 (setq pn-xml (make-js2-xml-node))
9606 (while continue
9607 (if first-token
9608 (setq first-token nil)
9609 (setq tt (js2-get-next-xml-token)))
9610 (cond
9611 ;; js2-XML means we found a {expr} in the XML stream.
9612 ;; The token string is the XML up to the left-curly.
9613 ((= tt js2-XML)
9614 (push (make-js2-string-node :pos (js2-current-token-beg)
9615 :len (- js2-ts-cursor (js2-current-token-beg)))
9616 kids)
9617 (js2-must-match js2-LC "msg.syntax")
9618 (setq expr-pos js2-ts-cursor
9619 expr (if (eq (js2-peek-token) js2-RC)
9620 (make-js2-empty-expr-node :pos expr-pos)
9621 (js2-parse-expr)))
9622 (js2-must-match js2-RC "msg.syntax")
9623 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9624 :len (js2-node-len expr)
9625 :expr expr))
9626 (js2-node-add-children pn expr)
9627 (push pn kids))
9628 ;; a js2-XMLEND token means we hit the final close-tag.
9629 ((= tt js2-XMLEND)
9630 (push (make-js2-string-node :pos (js2-current-token-beg)
9631 :len (- js2-ts-cursor (js2-current-token-beg)))
9632 kids)
9633 (dolist (kid (nreverse kids))
9634 (js2-block-node-push pn-xml kid))
9635 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9636 (js2-node-pos pn-xml))
9637 continue nil))
9638 (t
9639 (js2-report-error "msg.syntax")
9640 (setq continue nil))))
9641 pn-xml))
9642
9643
9644 (defun js2-parse-argument-list ()
9645 "Parse an argument list and return it as a Lisp list of nodes.
9646 Returns the list in reverse order. Consumes the right-paren token."
9647 (let (result)
9648 (unless (js2-match-token js2-RP)
9649 (cl-loop do
9650 (let ((tt (js2-get-token)))
9651 (if (= tt js2-YIELD)
9652 (js2-report-error "msg.yield.parenthesized"))
9653 (if (and (= tt js2-TRIPLEDOT)
9654 (>= js2-language-version 200))
9655 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9656 (js2-unget-token)
9657 (push (js2-parse-assign-expr) result)))
9658 while
9659 (js2-match-token js2-COMMA))
9660 (js2-must-match js2-RP "msg.no.paren.arg")
9661 result)))
9662
9663 (defun js2-parse-member-expr (&optional allow-call-syntax)
9664 (let ((tt (js2-current-token-type))
9665 pn pos target args beg end init)
9666 (if (/= tt js2-NEW)
9667 (setq pn (js2-parse-primary-expr))
9668 ;; parse a 'new' expression
9669 (js2-get-token)
9670 (setq pos (js2-current-token-beg)
9671 beg pos
9672 target (js2-parse-member-expr)
9673 end (js2-node-end target)
9674 pn (make-js2-new-node :pos pos
9675 :target target
9676 :len (- end pos)))
9677 (js2-highlight-function-call (js2-current-token))
9678 (js2-node-add-children pn target)
9679 (when (js2-match-token js2-LP)
9680 ;; Add the arguments to pn, if any are supplied.
9681 (setf beg pos ; start of "new" keyword
9682 pos (js2-current-token-beg)
9683 args (nreverse (js2-parse-argument-list))
9684 (js2-new-node-args pn) args
9685 end (js2-current-token-end)
9686 (js2-new-node-lp pn) (- pos beg)
9687 (js2-new-node-rp pn) (- end 1 beg))
9688 (apply #'js2-node-add-children pn args))
9689 (when (and js2-allow-rhino-new-expr-initializer
9690 (js2-match-token js2-LC))
9691 (setf init (js2-parse-object-literal)
9692 end (js2-node-end init)
9693 (js2-new-node-initializer pn) init)
9694 (js2-node-add-children pn init))
9695 (setf (js2-node-len pn) (- end beg))) ; end outer if
9696 (js2-parse-member-expr-tail allow-call-syntax pn)))
9697
9698 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9699 "Parse a chain of property/array accesses or function calls.
9700 Includes parsing for E4X operators like `..' and `.@'.
9701 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9702 Returns an expression tree that includes PN, the parent node."
9703 (let (tt
9704 (continue t))
9705 (while continue
9706 (setq tt (js2-get-token))
9707 (cond
9708 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9709 (setq pn (js2-parse-property-access tt pn)))
9710 ((= tt js2-DOTQUERY)
9711 (setq pn (js2-parse-dot-query pn)))
9712 ((= tt js2-LB)
9713 (setq pn (js2-parse-element-get pn)))
9714 ((= tt js2-LP)
9715 (js2-unget-token)
9716 (if allow-call-syntax
9717 (setq pn (js2-parse-function-call pn))
9718 (setq continue nil)))
9719 ((= tt js2-TEMPLATE_HEAD)
9720 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9721 ((= tt js2-NO_SUBS_TEMPLATE)
9722 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9723 (t
9724 (js2-unget-token)
9725 (setq continue nil))))
9726 (if (>= js2-highlight-level 2)
9727 (js2-parse-highlight-member-expr-node pn))
9728 pn))
9729
9730 (defun js2-parse-tagged-template (tag-node tpl-node)
9731 "Parse tagged template expression."
9732 (let* ((beg (js2-node-pos tag-node))
9733 (pn (make-js2-tagged-template-node :beg beg
9734 :len (- (js2-current-token-end) beg)
9735 :tag tag-node
9736 :template tpl-node)))
9737 (js2-node-add-children pn tag-node tpl-node)
9738 pn))
9739
9740 (defun js2-parse-dot-query (pn)
9741 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9742 Last token parsed must be `js2-DOTQUERY'."
9743 (let ((pos (js2-node-pos pn))
9744 op-pos expr end)
9745 (js2-must-have-xml)
9746 (js2-set-requires-activation)
9747 (setq op-pos (js2-current-token-beg)
9748 expr (js2-parse-expr)
9749 end (js2-node-end expr)
9750 pn (make-js2-xml-dot-query-node :left pn
9751 :pos pos
9752 :op-pos op-pos
9753 :right expr))
9754 (js2-node-add-children pn
9755 (js2-xml-dot-query-node-left pn)
9756 (js2-xml-dot-query-node-right pn))
9757 (if (js2-must-match js2-RP "msg.no.paren")
9758 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9759 end (js2-current-token-end)))
9760 (setf (js2-node-len pn) (- end pos))
9761 pn))
9762
9763 (defun js2-parse-element-get (pn)
9764 "Parse an element-get expression, e.g. foo[bar].
9765 Last token parsed must be `js2-RB'."
9766 (let ((lb (js2-current-token-beg))
9767 (pos (js2-node-pos pn))
9768 rb expr)
9769 (setq expr (js2-parse-expr))
9770 (if (js2-must-match js2-RB "msg.no.bracket.index")
9771 (setq rb (js2-current-token-beg)))
9772 (setq pn (make-js2-elem-get-node :target pn
9773 :pos pos
9774 :element expr
9775 :lb (js2-relpos lb pos)
9776 :rb (js2-relpos rb pos)
9777 :len (- (js2-current-token-end) pos)))
9778 (js2-node-add-children pn
9779 (js2-elem-get-node-target pn)
9780 (js2-elem-get-node-element pn))
9781 pn))
9782
9783 (defun js2-highlight-function-call (token)
9784 (when (eq (js2-token-type token) js2-NAME)
9785 (js2-record-face 'js2-function-call token)))
9786
9787 (defun js2-parse-function-call (pn)
9788 (js2-highlight-function-call (js2-current-token))
9789 (js2-get-token)
9790 (let (args
9791 (pos (js2-node-pos pn)))
9792 (setq pn (make-js2-call-node :pos pos
9793 :target pn
9794 :lp (- (js2-current-token-beg) pos)))
9795 (js2-node-add-children pn (js2-call-node-target pn))
9796 ;; Add the arguments to pn, if any are supplied.
9797 (setf args (nreverse (js2-parse-argument-list))
9798 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9799 (js2-call-node-args pn) args)
9800 (apply #'js2-node-add-children pn args)
9801 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9802 pn))
9803
9804 (defun js2-parse-property-access (tt pn)
9805 "Parse a property access, XML descendants access, or XML attr access."
9806 (let ((member-type-flags 0)
9807 (dot-pos (js2-current-token-beg))
9808 (dot-len (if (= tt js2-DOTDOT) 2 1))
9809 name
9810 ref ; right side of . or .. operator
9811 result)
9812 (when (= tt js2-DOTDOT)
9813 (js2-must-have-xml)
9814 (setq member-type-flags js2-descendants-flag))
9815 (if (not js2-compiler-xml-available)
9816 (progn
9817 (js2-must-match-prop-name "msg.no.name.after.dot")
9818 (setq name (js2-create-name-node t js2-GETPROP)
9819 result (make-js2-prop-get-node :left pn
9820 :pos (js2-current-token-beg)
9821 :right name
9822 :len (js2-current-token-len)))
9823 (js2-node-add-children result pn name)
9824 result)
9825 ;; otherwise look for XML operators
9826 (setf result (if (= tt js2-DOT)
9827 (make-js2-prop-get-node)
9828 (make-js2-infix-node :type js2-DOTDOT))
9829 (js2-node-pos result) (js2-node-pos pn)
9830 (js2-infix-node-op-pos result) dot-pos
9831 (js2-infix-node-left result) pn ; do this after setting position
9832 tt (js2-get-prop-name-token))
9833 (cond
9834 ;; handles: name, ns::name, ns::*, ns::[expr]
9835 ((= tt js2-NAME)
9836 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9837 ;; handles: *, *::name, *::*, *::[expr]
9838 ((= tt js2-MUL)
9839 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9840 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9841 ((= tt js2-XMLATTR)
9842 (setq result (js2-parse-attribute-access)))
9843 (t
9844 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9845 (if ref
9846 (setf (js2-node-len result) (- (js2-node-end ref)
9847 (js2-node-pos result))
9848 (js2-infix-node-right result) ref))
9849 (if (js2-infix-node-p result)
9850 (js2-node-add-children result
9851 (js2-infix-node-left result)
9852 (js2-infix-node-right result)))
9853 result)))
9854
9855 (defun js2-parse-attribute-access ()
9856 "Parse an E4X XML attribute expression.
9857 This includes expressions of the forms:
9858
9859 @attr @ns::attr @ns::*
9860 @* @*::attr @*::*
9861 @[expr] @*::[expr] @ns::[expr]
9862
9863 Called if we peeked an '@' token."
9864 (let ((tt (js2-get-prop-name-token))
9865 (at-pos (js2-current-token-beg)))
9866 (cond
9867 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9868 ((= tt js2-NAME)
9869 (js2-parse-property-name at-pos nil 0))
9870 ;; handles: @*, @*::name, @*::*, @*::[expr]
9871 ((= tt js2-MUL)
9872 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9873 ;; handles @[expr]
9874 ((= tt js2-LB)
9875 (js2-parse-xml-elem-ref at-pos))
9876 (t
9877 (js2-report-error "msg.no.name.after.xmlAttr")
9878 ;; Avoid cascaded errors that happen if we make an error node here.
9879 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9880
9881 (defun js2-parse-property-name (at-pos s member-type-flags)
9882 "Check if :: follows name in which case it becomes qualified name.
9883
9884 AT-POS is a natural number if we just read an '@' token, else nil.
9885 S is the name or string that was matched: an identifier, 'throw' or '*'.
9886 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9887
9888 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9889 operator, or the name is followed by ::. For a plain name, returns a
9890 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9891 (let ((pos (or at-pos (js2-current-token-beg)))
9892 colon-pos
9893 (name (js2-create-name-node t (js2-current-token-type) s))
9894 ns tt pn)
9895 (catch 'return
9896 (when (js2-match-token js2-COLONCOLON)
9897 (setq ns name
9898 colon-pos (js2-current-token-beg)
9899 tt (js2-get-prop-name-token))
9900 (cond
9901 ;; handles name::name
9902 ((= tt js2-NAME)
9903 (setq name (js2-create-name-node)))
9904 ;; handles name::*
9905 ((= tt js2-MUL)
9906 (setq name (js2-create-name-node nil nil "*")))
9907 ;; handles name::[expr]
9908 ((= tt js2-LB)
9909 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9910 (t
9911 (js2-report-error "msg.no.name.after.coloncolon"))))
9912 (if (and (null ns) (zerop member-type-flags))
9913 name
9914 (prog1
9915 (setq pn
9916 (make-js2-xml-prop-ref-node :pos pos
9917 :len (- (js2-node-end name) pos)
9918 :at-pos at-pos
9919 :colon-pos colon-pos
9920 :propname name))
9921 (js2-node-add-children pn name))))))
9922
9923 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9924 "Parse the [expr] portion of an xml element reference.
9925 For instance, @[expr], @*::[expr], or ns::[expr]."
9926 (let* ((lb (js2-current-token-beg))
9927 (pos (or at-pos lb))
9928 rb
9929 (expr (js2-parse-expr))
9930 (end (js2-node-end expr))
9931 pn)
9932 (if (js2-must-match js2-RB "msg.no.bracket.index")
9933 (setq rb (js2-current-token-beg)
9934 end (js2-current-token-end)))
9935 (prog1
9936 (setq pn
9937 (make-js2-xml-elem-ref-node :pos pos
9938 :len (- end pos)
9939 :namespace namespace
9940 :colon-pos colon-pos
9941 :at-pos at-pos
9942 :expr expr
9943 :lb (js2-relpos lb pos)
9944 :rb (js2-relpos rb pos)))
9945 (js2-node-add-children pn namespace expr))))
9946
9947 (defun js2-parse-destruct-primary-expr ()
9948 (let ((js2-is-in-destructuring t))
9949 (js2-parse-primary-expr)))
9950
9951 (defun js2-parse-primary-expr ()
9952 "Parse a literal (leaf) expression of some sort.
9953 Includes complex literals such as functions, object-literals,
9954 array-literals, array comprehensions and regular expressions."
9955 (let (pn ; parent node (usually return value)
9956 tt)
9957 (setq tt (js2-current-token-type))
9958 (cond
9959 ((= tt js2-CLASS)
9960 (js2-parse-class-expr))
9961 ((= tt js2-FUNCTION)
9962 (js2-parse-function-expr))
9963 ((= tt js2-LB)
9964 (js2-parse-array-comp-or-literal))
9965 ((= tt js2-LC)
9966 (js2-parse-object-literal))
9967 ((= tt js2-LET)
9968 (js2-parse-let (js2-current-token-beg)))
9969 ((= tt js2-LP)
9970 (js2-parse-paren-expr-or-generator-comp))
9971 ((= tt js2-XMLATTR)
9972 (js2-must-have-xml)
9973 (js2-parse-attribute-access))
9974 ((= tt js2-NAME)
9975 (js2-parse-name tt))
9976 ((= tt js2-NUMBER)
9977 (make-js2-number-node))
9978 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9979 (make-js2-string-node :type tt))
9980 ((= tt js2-TEMPLATE_HEAD)
9981 (js2-parse-template-literal))
9982 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9983 ;; Got / or /= which in this context means a regexp literal
9984 (let ((px-pos (js2-current-token-beg))
9985 (flags (js2-read-regexp tt))
9986 (end (js2-current-token-end)))
9987 (prog1
9988 (make-js2-regexp-node :pos px-pos
9989 :len (- end px-pos)
9990 :value (js2-current-token-string)
9991 :flags flags)
9992 (js2-set-face px-pos end 'font-lock-string-face 'record)
9993 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9994 ((or (= tt js2-NULL)
9995 (= tt js2-THIS)
9996 (= tt js2-SUPER)
9997 (= tt js2-FALSE)
9998 (= tt js2-TRUE))
9999 (make-js2-keyword-node :type tt))
10000 ((= tt js2-TRIPLEDOT)
10001 ;; Likewise, only valid in an arrow function with a rest param.
10002 (if (and (js2-match-token js2-NAME)
10003 (js2-match-token js2-RP)
10004 (eq (js2-peek-token) js2-ARROW))
10005 (progn
10006 (js2-unget-token) ; Put back the right paren.
10007 ;; See the previous case.
10008 (make-js2-keyword-node :type js2-NULL))
10009 (js2-report-error "msg.syntax")
10010 (make-js2-error-node)))
10011 ((= tt js2-RESERVED)
10012 (js2-report-error "msg.reserved.id")
10013 (make-js2-name-node))
10014 ((= tt js2-ERROR)
10015 ;; the scanner or one of its subroutines reported the error.
10016 (make-js2-error-node))
10017 ((= tt js2-EOF)
10018 (let* ((px-pos (point-at-bol))
10019 (len (- js2-ts-cursor px-pos)))
10020 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10021 (make-js2-error-node :pos (1- js2-ts-cursor)))
10022 (t
10023 (js2-report-error "msg.syntax")
10024 (make-js2-error-node)))))
10025
10026 (defun js2-parse-template-literal ()
10027 (let ((beg (js2-current-token-beg))
10028 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10029 (tt js2-TEMPLATE_HEAD))
10030 (while (eq tt js2-TEMPLATE_HEAD)
10031 (push (js2-parse-expr) kids)
10032 (js2-must-match js2-RC "msg.syntax")
10033 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10034 (push (make-js2-string-node :type tt) kids))
10035 (setq kids (nreverse kids))
10036 (let ((tpl (make-js2-template-node :beg beg
10037 :len (- (js2-current-token-end) beg)
10038 :kids kids)))
10039 (apply #'js2-node-add-children tpl kids)
10040 tpl)))
10041
10042 (defun js2-parse-name (_tt)
10043 (let ((name (js2-current-token-string))
10044 node)
10045 (setq node (if js2-compiler-xml-available
10046 (js2-parse-property-name nil name 0)
10047 (js2-create-name-node 'check-activation nil name)))
10048 (if js2-highlight-external-variables
10049 (js2-record-name-node node))
10050 node))
10051
10052 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10053 (js2-add-strict-warning
10054 msg nil
10055 ;; back up from comma to beginning of line or array/objlit
10056 (max (if elems
10057 (js2-node-pos (car elems))
10058 pos)
10059 (save-excursion
10060 (goto-char comma-pos)
10061 (back-to-indentation)
10062 (point)))
10063 comma-pos))
10064
10065 (defun js2-parse-array-comp-or-literal ()
10066 (let ((pos (js2-current-token-beg)))
10067 (if (and (>= js2-language-version 200)
10068 (js2-match-token js2-FOR))
10069 (js2-parse-array-comp pos)
10070 (js2-parse-array-literal pos))))
10071
10072 (defun js2-parse-array-literal (pos)
10073 (let ((after-lb-or-comma t)
10074 after-comma tt elems pn
10075 (continue t))
10076 (unless js2-is-in-destructuring
10077 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10078 (while continue
10079 (setq tt (js2-get-token))
10080 (cond
10081 ;; comma
10082 ((= tt js2-COMMA)
10083 (setq after-comma (js2-current-token-end))
10084 (if (not after-lb-or-comma)
10085 (setq after-lb-or-comma t)
10086 (push nil elems)))
10087 ;; end of array
10088 ((or (= tt js2-RB)
10089 (= tt js2-EOF)) ; prevent infinite loop
10090 (if (= tt js2-EOF)
10091 (js2-report-error "msg.no.bracket.arg" nil pos))
10092 (when (and after-comma (< js2-language-version 170))
10093 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10094 pos (remove nil elems) after-comma))
10095 (setq continue nil
10096 pn (make-js2-array-node :pos pos
10097 :len (- js2-ts-cursor pos)
10098 :elems (nreverse elems)))
10099 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10100 ;; destructuring binding
10101 (js2-is-in-destructuring
10102 (push (if (or (= tt js2-LC)
10103 (= tt js2-LB)
10104 (= tt js2-NAME))
10105 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10106 (js2-parse-destruct-primary-expr)
10107 ;; invalid pattern
10108 (js2-report-error "msg.bad.var")
10109 (make-js2-error-node))
10110 elems)
10111 (setq after-lb-or-comma nil
10112 after-comma nil))
10113 ;; array comp
10114 ((and (>= js2-language-version 170)
10115 (= tt js2-FOR) ; check for array comprehension
10116 (not after-lb-or-comma) ; "for" can't follow a comma
10117 elems ; must have at least 1 element
10118 (not (cdr elems))) ; but no 2nd element
10119 (js2-unget-token)
10120 (setf continue nil
10121 pn (js2-parse-legacy-array-comp (car elems) pos)))
10122 ;; another element
10123 (t
10124 (unless after-lb-or-comma
10125 (js2-report-error "msg.no.bracket.arg"))
10126 (if (and (= tt js2-TRIPLEDOT)
10127 (>= js2-language-version 200))
10128 ;; spread operator
10129 (push (js2-make-unary tt 'js2-parse-assign-expr)
10130 elems)
10131 (js2-unget-token)
10132 (push (js2-parse-assign-expr) elems))
10133 (setq after-lb-or-comma nil
10134 after-comma nil))))
10135 (unless js2-is-in-destructuring
10136 (js2-pop-scope))
10137 pn))
10138
10139 (defun js2-parse-legacy-array-comp (expr pos)
10140 "Parse a legacy array comprehension (JavaScript 1.7).
10141 EXPR is the first expression after the opening left-bracket.
10142 POS is the beginning of the LB token preceding EXPR.
10143 We should have just parsed the 'for' keyword before calling this function."
10144 (let ((current-scope js2-current-scope)
10145 loops first filter result)
10146 (unwind-protect
10147 (progn
10148 (while (js2-match-token js2-FOR)
10149 (let ((loop (make-js2-comp-loop-node)))
10150 (js2-push-scope loop)
10151 (push loop loops)
10152 (js2-parse-comp-loop loop)))
10153 ;; First loop takes expr scope's parent.
10154 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10155 (js2-scope-parent-scope current-scope))
10156 ;; Set expr scope's parent to the last loop.
10157 (setf (js2-scope-parent-scope current-scope) (car loops))
10158 (if (/= (js2-get-token) js2-IF)
10159 (js2-unget-token)
10160 (setq filter (js2-parse-condition))))
10161 (dotimes (_ (1- (length loops)))
10162 (js2-pop-scope)))
10163 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10164 (setq result (make-js2-comp-node :pos pos
10165 :len (- js2-ts-cursor pos)
10166 :result expr
10167 :loops (nreverse loops)
10168 :filters (and filter (list (car filter)))
10169 :form 'LEGACY_ARRAY))
10170 ;; Set comp loop's parent to the last loop.
10171 ;; TODO: Get rid of the bogus expr scope.
10172 (setf (js2-scope-parent-scope result) first)
10173 (apply #'js2-node-add-children result expr (car filter)
10174 (js2-comp-node-loops result))
10175 result))
10176
10177 (defun js2-parse-array-comp (pos)
10178 "Parse an ES6 array comprehension.
10179 POS is the beginning of the LB token.
10180 We should have just parsed the 'for' keyword before calling this function."
10181 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10182 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10183 pn))
10184
10185 (defun js2-parse-generator-comp (pos)
10186 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10187 (js2-current-script-or-fn
10188 (make-js2-function-node :generator-type 'COMPREHENSION))
10189 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10190 (js2-must-match js2-RP "msg.no.paren" pos)
10191 pn))
10192
10193 (defun js2-parse-comprehension (pos form)
10194 (let (loops filters expr result)
10195 (unwind-protect
10196 (progn
10197 (js2-unget-token)
10198 (while (js2-match-token js2-FOR)
10199 (let ((loop (make-js2-comp-loop-node)))
10200 (js2-push-scope loop)
10201 (push loop loops)
10202 (js2-parse-comp-loop loop)))
10203 (while (js2-match-token js2-IF)
10204 (push (car (js2-parse-condition)) filters))
10205 (setq expr (js2-parse-assign-expr)))
10206 (dolist (_ loops)
10207 (js2-pop-scope)))
10208 (setq result (make-js2-comp-node :pos pos
10209 :len (- js2-ts-cursor pos)
10210 :result expr
10211 :loops (nreverse loops)
10212 :filters (nreverse filters)
10213 :form form))
10214 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10215 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10216 result))
10217
10218 (defun js2-parse-comp-loop (pn &optional only-of-p)
10219 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10220 The current token should be the initial FOR.
10221 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10222 (let ((pos (js2-comp-loop-node-pos pn))
10223 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10224 (when (and (not only-of-p) (js2-match-token js2-NAME))
10225 (if (string= (js2-current-token-string) "each")
10226 (progn
10227 (setq foreach-p t
10228 each-pos (- (js2-current-token-beg) pos)) ; relative
10229 (js2-record-face 'font-lock-keyword-face))
10230 (js2-report-error "msg.no.paren.for")))
10231 (if (js2-must-match js2-LP "msg.no.paren.for")
10232 (setq lp (- (js2-current-token-beg) pos)))
10233 (setq tt (js2-peek-token))
10234 (cond
10235 ((or (= tt js2-LB)
10236 (= tt js2-LC))
10237 (js2-get-token)
10238 (setq iter (js2-parse-destruct-primary-expr))
10239 (js2-define-destruct-symbols iter js2-LET
10240 'font-lock-variable-name-face t))
10241 ((js2-match-token js2-NAME)
10242 (setq iter (js2-create-name-node)))
10243 (t
10244 (js2-report-error "msg.bad.var")))
10245 ;; Define as a let since we want the scope of the variable to
10246 ;; be restricted to the array comprehension
10247 (if (js2-name-node-p iter)
10248 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10249 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10250 (and (>= js2-language-version 200)
10251 (js2-match-contextual-kwd "of")
10252 (setq forof-p t)))
10253 (setq in-pos (- (js2-current-token-beg) pos))
10254 (js2-report-error "msg.in.after.for.name"))
10255 (setq obj (js2-parse-expr))
10256 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10257 (setq rp (- (js2-current-token-beg) pos)))
10258 (setf (js2-node-pos pn) pos
10259 (js2-node-len pn) (- js2-ts-cursor pos)
10260 (js2-comp-loop-node-iterator pn) iter
10261 (js2-comp-loop-node-object pn) obj
10262 (js2-comp-loop-node-in-pos pn) in-pos
10263 (js2-comp-loop-node-each-pos pn) each-pos
10264 (js2-comp-loop-node-foreach-p pn) foreach-p
10265 (js2-comp-loop-node-forof-p pn) forof-p
10266 (js2-comp-loop-node-lp pn) lp
10267 (js2-comp-loop-node-rp pn) rp)
10268 (js2-node-add-children pn iter obj)
10269 pn))
10270
10271 (defun js2-parse-class-stmt ()
10272 (let ((pos (js2-current-token-beg))
10273 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10274 (name (js2-create-name-node t)))
10275 (js2-set-face (js2-node-pos name) (js2-node-end name)
10276 'font-lock-function-name-face 'record)
10277 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10278 (js2-define-symbol js2-FUNCTION
10279 (js2-name-node-name name)
10280 node)
10281 node)))
10282
10283 (defun js2-parse-class-expr ()
10284 (let ((pos (js2-current-token-beg))
10285 name)
10286 (when (js2-match-token js2-NAME)
10287 (setq name (js2-create-name-node t)))
10288 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10289
10290 (defun js2-parse-class (pos form name)
10291 ;; class X [extends ...] {
10292 (let (pn elems extends)
10293 (if (js2-match-token js2-EXTENDS)
10294 (if (= (js2-peek-token) js2-LC)
10295 (js2-report-error "msg.missing.extends")
10296 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10297 (setq extends (js2-parse-assign-expr))
10298 (if (not extends)
10299 (js2-report-error "msg.bad.extends"))))
10300 (js2-must-match js2-LC "msg.no.brace.class")
10301 (setq elems (js2-parse-object-literal-elems t)
10302 pn (make-js2-class-node :pos pos
10303 :len (- js2-ts-cursor pos)
10304 :form form
10305 :name name
10306 :extends extends
10307 :elems elems))
10308 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10309 pn))
10310
10311 (defun js2-parse-object-literal ()
10312 (let* ((pos (js2-current-token-beg))
10313 (elems (js2-parse-object-literal-elems))
10314 (result (make-js2-object-node :pos pos
10315 :len (- js2-ts-cursor pos)
10316 :elems elems)))
10317 (apply #'js2-node-add-children result (js2-object-node-elems result))
10318 result))
10319
10320 (defun js2-parse-object-literal-elems (&optional class-p)
10321 (let ((pos (js2-current-token-beg))
10322 (static nil)
10323 (continue t)
10324 tt elems elem after-comma)
10325 (while continue
10326 (setq tt (js2-get-prop-name-token)
10327 static nil
10328 elem nil)
10329 (when (and class-p (= js2-NAME tt)
10330 (string= "static" (js2-current-token-string)))
10331 (js2-record-face 'font-lock-keyword-face)
10332 (setq static t
10333 tt (js2-get-prop-name-token)))
10334 (cond
10335 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
10336 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
10337 ;; TODO(sdh): support *foo() {...}
10338 ((or (= js2-NAME tt)
10339 (= tt js2-STRING))
10340 (setq after-comma nil
10341 elem (js2-parse-named-prop tt))
10342 (if (and (null elem)
10343 (not js2-recover-from-parse-errors))
10344 (setq continue nil)))
10345 ;; {[Symbol.iterator]: ...}
10346 ((and (= tt js2-LB)
10347 (>= js2-language-version 200))
10348 (let ((expr (js2-parse-expr)))
10349 (js2-must-match js2-RB "msg.missing.computed.rb")
10350 (setq after-comma nil
10351 elem (js2-parse-plain-property expr))))
10352 ;; {12: x} or {10.7: x}
10353 ((= tt js2-NUMBER)
10354 (setq after-comma nil
10355 elem (js2-parse-plain-property (make-js2-number-node))))
10356 ;; Break out of loop, and handle trailing commas.
10357 ((or (= tt js2-RC)
10358 (= tt js2-EOF))
10359 (js2-unget-token)
10360 (setq continue nil)
10361 (if after-comma
10362 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10363 pos elems after-comma)))
10364 (t
10365 (js2-report-error "msg.bad.prop")
10366 (unless js2-recover-from-parse-errors
10367 (setq continue nil)))) ; end switch
10368 ;; Handle static for classes' codegen.
10369 (if static
10370 (if elem (js2-node-set-prop elem 'STATIC t)
10371 (js2-report-error "msg.unexpected.static")))
10372 ;; Handle commas, depending on class-p.
10373 (let ((tok (js2-get-prop-name-token)))
10374 (if (eq tok js2-COMMA)
10375 (if class-p
10376 (js2-report-error "msg.class.unexpected.comma")
10377 (setq after-comma (js2-current-token-end)))
10378 (js2-unget-token)
10379 (unless class-p (setq continue nil))))
10380 ;; Append any parsed element.
10381 (if elem (push elem elems))) ; end loop
10382 (js2-must-match js2-RC "msg.no.brace.prop")
10383 (nreverse elems)))
10384
10385 (defun js2-parse-named-prop (tt)
10386 "Parse a name, string, or getter/setter object property.
10387 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10388 (let ((string-prop (and (= tt js2-STRING)
10389 (make-js2-string-node)))
10390 expr
10391 (ppos (js2-current-token-beg))
10392 (pend (js2-current-token-end))
10393 (name (js2-create-name-node))
10394 (prop (js2-current-token-string)))
10395 (cond
10396 ;; getter/setter prop
10397 ((and (= tt js2-NAME)
10398 (= (js2-peek-token) js2-NAME)
10399 (or (string= prop "get")
10400 (string= prop "set")))
10401 (js2-get-token)
10402 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
10403 (js2-record-face 'font-lock-function-name-face) ; for peeked name
10404 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
10405 (js2-parse-getter-setter-prop ppos name prop))
10406 ;; method definition: {f() {...}}
10407 ((and (= (js2-peek-token) js2-LP)
10408 (>= js2-language-version 200))
10409 (js2-record-face 'font-lock-function-name-face) ; name
10410 (js2-parse-getter-setter-prop ppos name ""))
10411 ;; regular prop
10412 (t
10413 (prog1
10414 (setq expr (js2-parse-plain-property (or string-prop name)))
10415 (when (and (not string-prop)
10416 (not js2-is-in-destructuring)
10417 js2-highlight-external-variables
10418 (js2-node-get-prop expr 'SHORTHAND))
10419 (js2-record-name-node name))
10420 (js2-set-face ppos pend
10421 (if (js2-function-node-p
10422 (js2-object-prop-node-right expr))
10423 'font-lock-function-name-face
10424 'font-lock-variable-name-face)
10425 'record))))))
10426
10427 (defun js2-parse-plain-property (prop)
10428 "Parse a non-getter/setter property in an object literal.
10429 PROP is the node representing the property: a number, name or string."
10430 (let* ((tt (js2-get-token))
10431 (pos (js2-node-pos prop))
10432 colon expr result)
10433 (cond
10434 ;; Abbreviated property, as in {foo, bar}
10435 ((and (>= js2-language-version 200)
10436 (or (= tt js2-COMMA)
10437 (= tt js2-RC))
10438 (not (js2-number-node-p prop)))
10439 (js2-unget-token)
10440 (setq result (make-js2-object-prop-node
10441 :pos pos
10442 :left prop
10443 :right prop
10444 :op-pos (js2-current-token-len)))
10445 (js2-node-add-children result prop)
10446 (js2-node-set-prop result 'SHORTHAND t)
10447 result)
10448 ;; Normal property
10449 (t
10450 (if (= tt js2-COLON)
10451 (setq colon (- (js2-current-token-beg) pos)
10452 expr (js2-parse-assign-expr))
10453 (js2-report-error "msg.no.colon.prop")
10454 (setq expr (make-js2-error-node)))
10455 (setq result (make-js2-object-prop-node
10456 :pos pos
10457 ;; don't include last consumed token in length
10458 :len (- (+ (js2-node-pos expr)
10459 (js2-node-len expr))
10460 pos)
10461 :left prop
10462 :right expr
10463 :op-pos colon))
10464 (js2-node-add-children result prop expr)
10465 result))))
10466
10467 (defun js2-parse-getter-setter-prop (pos prop type-string)
10468 "Parse getter or setter property in an object literal.
10469 JavaScript syntax is:
10470
10471 { get foo() {...}, set foo(x) {...} }
10472
10473 and expression closure style is also supported
10474
10475 { get foo() x, set foo(x) _x = x }
10476
10477 POS is the start position of the `get' or `set' keyword.
10478 PROP is the `js2-name-node' representing the property name.
10479 GET-P is non-nil if the keyword was `get'."
10480 (let ((type (cond
10481 ((string= "get" type-string) js2-GET)
10482 ((string= "set" type-string) js2-SET)
10483 (t js2-FUNCTION)))
10484 result end
10485 (fn (js2-parse-function-expr)))
10486 ;; it has to be an anonymous function, as we already parsed the name
10487 (if (/= (js2-node-type fn) js2-FUNCTION)
10488 (js2-report-error "msg.bad.prop")
10489 (if (cl-plusp (length (js2-function-name fn)))
10490 (js2-report-error "msg.bad.prop")))
10491 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10492 (setq end (js2-node-end fn)
10493 result (make-js2-getter-setter-node :type type
10494 :pos pos
10495 :len (- end pos)
10496 :left prop
10497 :right fn))
10498 (js2-node-add-children result prop fn)
10499 result))
10500
10501 (defun js2-create-name-node (&optional check-activation-p token string)
10502 "Create a name node using the current token and, optionally, STRING.
10503 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10504 (let* ((beg (js2-current-token-beg))
10505 (tt (js2-current-token-type))
10506 (s (or string
10507 (if (= js2-NAME tt)
10508 (js2-current-token-string)
10509 (js2-tt-name tt))))
10510 name)
10511 (setq name (make-js2-name-node :pos beg
10512 :name s
10513 :len (length s)))
10514 (if check-activation-p
10515 (js2-check-activation-name s (or token js2-NAME)))
10516 name))
10517
10518 ;;; Indentation support
10519
10520 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10521 ;; Karl cleverly deduces that the desired indentation level is often a
10522 ;; function of paren/bracket/brace nesting depth, which can be determined
10523 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10524 ;; then does some equally clever checks to see if we're in the context of a
10525 ;; substatement of a possibly braceless statement keyword such as if, while,
10526 ;; or finally. This approach yields pretty good results.
10527
10528 ;; The indenter is often "wrong", however, and needs to be overridden.
10529 ;; The right long-term solution is probably to emulate (or integrate
10530 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10531 ;; parse tree from `js2-parse' is present, which is not true at the
10532 ;; moment the user is typing, computing indentation is still thousands
10533 ;; of lines of code to handle every possible syntactic edge case.
10534
10535 ;; In the meantime, the compromise solution is that we offer a "bounce
10536 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10537 ;; current line indent among various likely guess points. This approach
10538 ;; is far from perfect, but should at least make it slightly easier to
10539 ;; move the line towards its desired indentation when manually
10540 ;; overriding Karl's heuristic nesting guesser.
10541
10542 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10543 ;; extensions such as `let' and Array comprehensions. Major kudos to
10544 ;; Karl for coming up with the initial approach, which packs a lot of
10545 ;; punch for so little code.
10546
10547 (defconst js2-possibly-braceless-keywords-re
10548 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10549 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10550 "try" "while" "with" "let")))
10551 "Regular expression matching keywords that are optionally
10552 followed by an opening brace.")
10553
10554 (defconst js2-indent-operator-re
10555 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10556 (regexp-opt '("in" "instanceof") 'words))
10557 "Regular expression matching operators that affect indentation
10558 of continued expressions.")
10559
10560 (defconst js2-declaration-keyword-re
10561 (regexp-opt '("var" "let" "const") 'words)
10562 "Regular expression matching variable declaration keywords.")
10563
10564 (defun js2-re-search-forward-inner (regexp &optional bound count)
10565 "Auxiliary function for `js2-re-search-forward'."
10566 (let (parse saved-point)
10567 (while (> count 0)
10568 (re-search-forward regexp bound)
10569 (setq parse (if saved-point
10570 (parse-partial-sexp saved-point (point))
10571 (syntax-ppss (point))))
10572 (cond ((nth 3 parse)
10573 (re-search-forward
10574 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10575 (save-excursion (end-of-line) (point)) t))
10576 ((nth 7 parse)
10577 (forward-line))
10578 ((or (nth 4 parse)
10579 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10580 (re-search-forward "\\*/"))
10581 (t
10582 (setq count (1- count))))
10583 (setq saved-point (point))))
10584 (point))
10585
10586 (defun js2-re-search-forward (regexp &optional bound noerror count)
10587 "Search forward but ignore strings and comments.
10588 Invokes `re-search-forward' but treats the buffer as if strings
10589 and comments have been removed."
10590 (let ((saved-point (point)))
10591 (condition-case err
10592 (cond ((null count)
10593 (js2-re-search-forward-inner regexp bound 1))
10594 ((< count 0)
10595 (js2-re-search-backward-inner regexp bound (- count)))
10596 ((> count 0)
10597 (js2-re-search-forward-inner regexp bound count)))
10598 (search-failed
10599 (goto-char saved-point)
10600 (unless noerror
10601 (error (error-message-string err)))))))
10602
10603 (defun js2-re-search-backward-inner (regexp &optional bound count)
10604 "Auxiliary function for `js2-re-search-backward'."
10605 (let (parse)
10606 (while (> count 0)
10607 (re-search-backward regexp bound)
10608 (setq parse (syntax-ppss (point)))
10609 (cond ((nth 3 parse)
10610 (re-search-backward
10611 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10612 (line-beginning-position) t))
10613 ((nth 7 parse)
10614 (goto-char (nth 8 parse)))
10615 ((or (nth 4 parse)
10616 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10617 (re-search-backward "/\\*"))
10618 (t
10619 (setq count (1- count))))))
10620 (point))
10621
10622 (defun js2-re-search-backward (regexp &optional bound noerror count)
10623 "Search backward but ignore strings and comments.
10624 Invokes `re-search-backward' but treats the buffer as if strings
10625 and comments have been removed."
10626 (let ((saved-point (point)))
10627 (condition-case err
10628 (cond ((null count)
10629 (js2-re-search-backward-inner regexp bound 1))
10630 ((< count 0)
10631 (js2-re-search-forward-inner regexp bound (- count)))
10632 ((> count 0)
10633 (js2-re-search-backward-inner regexp bound count)))
10634 (search-failed
10635 (goto-char saved-point)
10636 (unless noerror
10637 (error (error-message-string err)))))))
10638
10639 (defun js2-looking-at-operator-p ()
10640 "Return non-nil if text after point is a non-comma operator."
10641 (and (looking-at js2-indent-operator-re)
10642 (or (not (looking-at ":"))
10643 (save-excursion
10644 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10645 (looking-at "?"))))))
10646
10647 (defun js2-continued-expression-p ()
10648 "Return non-nil if the current line continues an expression."
10649 (save-excursion
10650 (back-to-indentation)
10651 (or (js2-looking-at-operator-p)
10652 (when (catch 'found
10653 (while (and (re-search-backward "\n" nil t)
10654 (let ((state (syntax-ppss)))
10655 (when (nth 4 state)
10656 (goto-char (nth 8 state))) ;; skip comments
10657 (skip-chars-backward " \t")
10658 (if (bolp)
10659 t
10660 (throw 'found t))))))
10661 (backward-char)
10662 (when (js2-looking-at-operator-p)
10663 (backward-char)
10664 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10665
10666 (defun js2-end-of-do-while-loop-p ()
10667 "Return non-nil if word after point is `while' of a do-while
10668 statement, else returns nil. A braceless do-while statement
10669 spanning several lines requires that the start of the loop is
10670 indented to the same column as the current line."
10671 (interactive)
10672 (save-excursion
10673 (when (looking-at "\\s-*\\<while\\>")
10674 (if (save-excursion
10675 (skip-chars-backward "[ \t\n]*}")
10676 (looking-at "[ \t\n]*}"))
10677 (save-excursion
10678 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10679 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10680 (or (looking-at "\\<do\\>")
10681 (let ((saved-indent (current-indentation)))
10682 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10683 (/= (current-indentation) saved-indent)))
10684 (and (looking-at "[ \t]*\\<do\\>")
10685 (not (js2-re-search-forward
10686 "\\<while\\>" (point-at-eol) t))
10687 (= (current-indentation) saved-indent))))))))
10688
10689 (defun js2-multiline-decl-indentation ()
10690 "Return the declaration indentation column if the current line belongs
10691 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10692 (let (forward-sexp-function ; use Lisp version
10693 at-opening-bracket)
10694 (save-excursion
10695 (back-to-indentation)
10696 (when (not (looking-at js2-declaration-keyword-re))
10697 (when (looking-at js2-indent-operator-re)
10698 (goto-char (match-end 0))) ; continued expressions are ok
10699 (while (and (not at-opening-bracket)
10700 (not (bobp))
10701 (let ((pos (point)))
10702 (save-excursion
10703 (js2-backward-sws)
10704 (or (eq (char-before) ?,)
10705 (and (not (eq (char-before) ?\;))
10706 (prog2 (skip-syntax-backward ".")
10707 (looking-at js2-indent-operator-re)
10708 (js2-backward-sws))
10709 (not (eq (char-before) ?\;)))
10710 (js2-same-line pos)))))
10711 (condition-case _
10712 (backward-sexp)
10713 (scan-error (setq at-opening-bracket t))))
10714 (when (looking-at js2-declaration-keyword-re)
10715 (goto-char (match-end 0))
10716 (1+ (current-column)))))))
10717
10718 (defun js2-ctrl-statement-indentation ()
10719 "Return the proper indentation of current line if it is a control statement.
10720 Returns an indentation if this line starts the body of a control
10721 statement without braces, else returns nil."
10722 (let (forward-sexp-function)
10723 (save-excursion
10724 (back-to-indentation)
10725 (when (and (not (js2-same-line (point-min)))
10726 (not (looking-at "{"))
10727 (js2-re-search-backward "[[:graph:]]" nil t)
10728 (not (looking-at "[{([]"))
10729 (progn
10730 (forward-char)
10731 (when (= (char-before) ?\))
10732 ;; scan-sexps sometimes throws an error
10733 (ignore-errors (backward-sexp))
10734 (skip-chars-backward " \t" (point-at-bol)))
10735 (let ((pt (point)))
10736 (back-to-indentation)
10737 (when (looking-at "}[ \t]*")
10738 (goto-char (match-end 0)))
10739 (and (looking-at js2-possibly-braceless-keywords-re)
10740 (= (match-end 0) pt)
10741 (not (js2-end-of-do-while-loop-p))))))
10742 (+ (current-indentation) js2-basic-offset)))))
10743
10744 (defun js2-indent-in-array-comp (parse-status)
10745 "Return non-nil if we think we're in an array comprehension.
10746 In particular, return the buffer position of the first `for' kwd."
10747 (let ((bracket (nth 1 parse-status))
10748 (end (point)))
10749 (when bracket
10750 (save-excursion
10751 (goto-char bracket)
10752 (when (looking-at "\\[")
10753 (forward-char 1)
10754 (js2-forward-sws)
10755 (if (looking-at "[[{]")
10756 (let (forward-sexp-function) ; use Lisp version
10757 (forward-sexp) ; skip destructuring form
10758 (js2-forward-sws)
10759 (if (and (/= (char-after) ?,) ; regular array
10760 (looking-at "for"))
10761 (match-beginning 0)))
10762 ;; to skip arbitrary expressions we need the parser,
10763 ;; so we'll just guess at it.
10764 (if (and (> end (point)) ; not empty literal
10765 (re-search-forward "[^,]]* \\(for\\) " end t)
10766 ;; not inside comment or string literal
10767 (let ((state (parse-partial-sexp bracket (point))))
10768 (not (or (nth 3 state) (nth 4 state)))))
10769 (match-beginning 1))))))))
10770
10771 (defun js2-array-comp-indentation (parse-status for-kwd)
10772 (if (js2-same-line for-kwd)
10773 ;; first continuation line
10774 (save-excursion
10775 (goto-char (nth 1 parse-status))
10776 (forward-char 1)
10777 (skip-chars-forward " \t")
10778 (current-column))
10779 (save-excursion
10780 (goto-char for-kwd)
10781 (current-column))))
10782
10783 (defun js2-proper-indentation (parse-status)
10784 "Return the proper indentation for the current line."
10785 (save-excursion
10786 (back-to-indentation)
10787 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10788 (at-closing-bracket (looking-at "[]})]"))
10789 (same-indent-p (or at-closing-bracket
10790 (looking-at "\\<case\\>[^:]")
10791 (and (looking-at "\\<default:")
10792 (save-excursion
10793 (js2-backward-sws)
10794 (not (memq (char-before) '(?, ?{)))))))
10795 (continued-expr-p (js2-continued-expression-p))
10796 (declaration-indent (and js2-pretty-multiline-declarations
10797 (js2-multiline-decl-indentation)))
10798 (bracket (nth 1 parse-status))
10799 beg indent)
10800 (cond
10801 ;; indent array comprehension continuation lines specially
10802 ((and bracket
10803 (>= js2-language-version 170)
10804 (not (js2-same-line bracket))
10805 (setq beg (js2-indent-in-array-comp parse-status))
10806 (>= (point) (save-excursion
10807 (goto-char beg)
10808 (point-at-bol)))) ; at or after first loop?
10809 (js2-array-comp-indentation parse-status beg))
10810
10811 (ctrl-stmt-indent)
10812
10813 ((and declaration-indent continued-expr-p)
10814 (+ declaration-indent js2-basic-offset))
10815
10816 (declaration-indent)
10817
10818 (bracket
10819 (goto-char bracket)
10820 (cond
10821 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10822 (when (save-excursion (skip-chars-backward " \t)")
10823 (looking-at ")"))
10824 (backward-list))
10825 (back-to-indentation)
10826 (and (eq js2-pretty-multiline-declarations 'all)
10827 (looking-at js2-declaration-keyword-re)
10828 (goto-char (1+ (match-end 0))))
10829 (setq indent
10830 (cond (same-indent-p
10831 (current-column))
10832 (continued-expr-p
10833 (+ (current-column) (* 2 js2-basic-offset)))
10834 (t
10835 (+ (current-column) js2-basic-offset))))
10836 (if (and js2-indent-switch-body
10837 (not at-closing-bracket)
10838 (looking-at "\\_<switch\\_>"))
10839 (+ indent js2-basic-offset)
10840 indent))
10841 (t
10842 (unless same-indent-p
10843 (forward-char)
10844 (skip-chars-forward " \t"))
10845 (current-column))))
10846
10847 (continued-expr-p js2-basic-offset)
10848
10849 (t 0)))))
10850
10851 (defun js2-lineup-comment (parse-status)
10852 "Indent a multi-line block comment continuation line."
10853 (let* ((beg (nth 8 parse-status))
10854 (first-line (js2-same-line beg))
10855 (offset (save-excursion
10856 (goto-char beg)
10857 (if (looking-at "/\\*")
10858 (+ 1 (current-column))
10859 0))))
10860 (unless first-line
10861 (indent-line-to offset))))
10862
10863 (defun js2-backward-sws ()
10864 "Move backward through whitespace and comments."
10865 (interactive)
10866 (while (forward-comment -1)))
10867
10868 (defun js2-forward-sws ()
10869 "Move forward through whitespace and comments."
10870 (interactive)
10871 (while (forward-comment 1)))
10872
10873 (defun js2-current-indent (&optional pos)
10874 "Return column of indentation on current line.
10875 If POS is non-nil, go to that point and return indentation for that line."
10876 (save-excursion
10877 (if pos
10878 (goto-char pos))
10879 (back-to-indentation)
10880 (current-column)))
10881
10882 (defun js2-arglist-close ()
10883 "Return non-nil if we're on a line beginning with a close-paren/brace."
10884 (save-excursion
10885 (goto-char (point-at-bol))
10886 (js2-forward-sws)
10887 (looking-at "[])}]")))
10888
10889 (defun js2-indent-looks-like-label-p ()
10890 (goto-char (point-at-bol))
10891 (js2-forward-sws)
10892 (looking-at (concat js2-mode-identifier-re ":")))
10893
10894 (defun js2-indent-in-objlit-p (parse-status)
10895 "Return non-nil if this looks like an object-literal entry."
10896 (let ((start (nth 1 parse-status)))
10897 (and
10898 start
10899 (save-excursion
10900 (and (zerop (forward-line -1))
10901 (not (< (point) start)) ; crossed a {} boundary
10902 (js2-indent-looks-like-label-p)))
10903 (save-excursion
10904 (js2-indent-looks-like-label-p)))))
10905
10906 ;; If prev line looks like foobar({ then we're passing an object
10907 ;; literal to a function call, and people pretty much always want to
10908 ;; de-dent back to the previous line, so move the 'basic-offset'
10909 ;; position to the front.
10910 (defun js2-indent-objlit-arg-p (parse-status)
10911 (save-excursion
10912 (back-to-indentation)
10913 (js2-backward-sws)
10914 (and (eq (1- (point)) (nth 1 parse-status))
10915 (eq (char-before) ?{)
10916 (progn
10917 (forward-char -1)
10918 (skip-chars-backward " \t")
10919 (eq (char-before) ?\()))))
10920
10921 (defun js2-indent-case-block-p ()
10922 (save-excursion
10923 (back-to-indentation)
10924 (js2-backward-sws)
10925 (goto-char (point-at-bol))
10926 (skip-chars-forward " \t")
10927 (looking-at "case\\s-.+:")))
10928
10929 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10930 "Cycle among alternate computed indentation positions.
10931 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10932 of the buffer to the current point. NORMAL-COL is the indentation
10933 column computed by the heuristic guesser based on current paren,
10934 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10935 in reverse."
10936 (let ((cur-indent (js2-current-indent))
10937 (old-buffer-undo-list buffer-undo-list)
10938 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10939 (current-line (save-excursion
10940 (forward-line 0) ; move to bol
10941 (1+ (count-lines (point-min) (point)))))
10942 positions pos main-pos anchor arglist-cont same-indent
10943 basic-offset computed-pos)
10944 ;; temporarily don't record undo info, if user requested this
10945 (when js2-mode-indent-inhibit-undo
10946 (setq buffer-undo-list t))
10947 (unwind-protect
10948 (progn
10949 ;; First likely point: indent from beginning of previous code line
10950 (push (setq basic-offset
10951 (+ (save-excursion
10952 (back-to-indentation)
10953 (js2-backward-sws)
10954 (back-to-indentation)
10955 (current-column))
10956 js2-basic-offset))
10957 positions)
10958
10959 ;; (First + epsilon) likely point: indent 2x from beginning of
10960 ;; previous code line. Google does it this way.
10961 (push (setq basic-offset
10962 (+ (save-excursion
10963 (back-to-indentation)
10964 (js2-backward-sws)
10965 (back-to-indentation)
10966 (current-column))
10967 (* 2 js2-basic-offset)))
10968 positions)
10969
10970 ;; Second likely point: indent from assign-expr RHS. This
10971 ;; is just a crude guess based on finding " = " on the previous
10972 ;; line containing actual code.
10973 (setq pos (save-excursion
10974 (forward-line -1)
10975 (goto-char (point-at-bol))
10976 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10977 (point-at-eol) t)
10978 (goto-char (match-end 1))
10979 (skip-chars-forward " \t\r\n")
10980 (current-column))))
10981 (when pos
10982 (cl-incf pos js2-basic-offset)
10983 (push pos positions))
10984
10985 ;; Third likely point: same indent as previous line of code.
10986 ;; Make it the first likely point if we're not on an
10987 ;; arglist-close line and previous line ends in a comma, or
10988 ;; both this line and prev line look like object-literal
10989 ;; elements.
10990 (setq pos (save-excursion
10991 (goto-char (point-at-bol))
10992 (js2-backward-sws)
10993 (back-to-indentation)
10994 (prog1
10995 (current-column)
10996 ;; while we're here, look for trailing comma
10997 (if (save-excursion
10998 (goto-char (point-at-eol))
10999 (js2-backward-sws)
11000 (eq (char-before) ?,))
11001 (setq arglist-cont (1- (point)))))))
11002 (when pos
11003 (if (and (or arglist-cont
11004 (js2-indent-in-objlit-p parse-status))
11005 (not (js2-arglist-close)))
11006 (setq same-indent pos))
11007 (push pos positions))
11008
11009 ;; Fourth likely point: first preceding code with less indentation.
11010 ;; than the immediately preceding code line.
11011 (setq pos (save-excursion
11012 (back-to-indentation)
11013 (js2-backward-sws)
11014 (back-to-indentation)
11015 (setq anchor (current-column))
11016 (while (and (zerop (forward-line -1))
11017 (>= (progn
11018 (back-to-indentation)
11019 (current-column))
11020 anchor)))
11021 (setq pos (current-column))))
11022 (push pos positions)
11023
11024 ;; nesting-heuristic position, main by default
11025 (push (setq main-pos normal-col) positions)
11026
11027 ;; delete duplicates and sort positions list
11028 (setq positions (sort (delete-dups positions) '<))
11029
11030 ;; comma-list continuation lines: prev line indent takes precedence
11031 (if same-indent
11032 (setq main-pos same-indent))
11033
11034 ;; common special cases where we want to indent in from previous line
11035 (if (or (js2-indent-case-block-p)
11036 (js2-indent-objlit-arg-p parse-status))
11037 (setq main-pos basic-offset))
11038
11039 ;; if bouncing backwards, reverse positions list
11040 (if backwards
11041 (setq positions (reverse positions)))
11042
11043 ;; record whether we're already sitting on one of the alternatives
11044 (setq pos (member cur-indent positions))
11045
11046 (cond
11047 ;; case 0: we're one one of the alternatives and this is the
11048 ;; first time they've pressed TAB on this line (best-guess).
11049 ((and js2-mode-indent-ignore-first-tab
11050 pos
11051 ;; first time pressing TAB on this line?
11052 (not (eq js2-mode-last-indented-line current-line)))
11053 ;; do nothing
11054 (setq computed-pos nil))
11055 ;; case 1: only one computed position => use it
11056 ((null (cdr positions))
11057 (setq computed-pos 0))
11058 ;; case 2: not on any of the computed spots => use main spot
11059 ((not pos)
11060 (setq computed-pos (js2-position main-pos positions)))
11061 ;; case 3: on last position: cycle to first position
11062 ((null (cdr pos))
11063 (setq computed-pos 0))
11064 ;; case 4: on intermediate position: cycle to next position
11065 (t
11066 (setq computed-pos (js2-position (cl-second pos) positions))))
11067
11068 ;; see if any hooks want to indent; otherwise we do it
11069 (cl-loop with result = nil
11070 for hook in js2-indent-hook
11071 while (null result)
11072 do
11073 (setq result (funcall hook positions computed-pos))
11074 finally do
11075 (unless (or result (null computed-pos))
11076 (indent-line-to (nth computed-pos positions)))))
11077
11078 ;; finally
11079 (if js2-mode-indent-inhibit-undo
11080 (setq buffer-undo-list old-buffer-undo-list))
11081 ;; see commentary for `js2-mode-last-indented-line'
11082 (setq js2-mode-last-indented-line current-line))))
11083
11084 (defun js2-indent-bounce-backwards ()
11085 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11086 cycles between the computed indentation positions in reverse order."
11087 (interactive)
11088 (js2-indent-line t))
11089
11090 (defun js2-1-line-comment-continuation-p ()
11091 "Return t if we're in a 1-line comment continuation.
11092 If so, we don't ever want to use bounce-indent."
11093 (save-excursion
11094 (and (progn
11095 (forward-line 0)
11096 (looking-at "\\s-*//"))
11097 (progn
11098 (forward-line -1)
11099 (forward-line 0)
11100 (when (looking-at "\\s-*$")
11101 (js2-backward-sws)
11102 (forward-line 0))
11103 (looking-at "\\s-*//")))))
11104
11105 (defun js2-indent-line (&optional bounce-backwards)
11106 "Indent the current line as JavaScript source text."
11107 (interactive)
11108 (let (parse-status offset indent-col
11109 ;; Don't whine about errors/warnings when we're indenting.
11110 ;; This has to be set before calling parse-partial-sexp below.
11111 (inhibit-point-motion-hooks t))
11112 (setq parse-status (save-excursion
11113 (syntax-ppss (point-at-bol)))
11114 offset (- (point) (save-excursion
11115 (back-to-indentation)
11116 (point))))
11117 (js2-with-underscore-as-word-syntax
11118 (if (nth 4 parse-status)
11119 (js2-lineup-comment parse-status)
11120 (setq indent-col (js2-proper-indentation parse-status))
11121 ;; See comments below about `js2-mode-last-indented-line'.
11122 (cond
11123 ;; bounce-indenting is disabled during electric-key indent.
11124 ;; It doesn't work well on first line of buffer.
11125 ((and js2-bounce-indent-p
11126 (not (js2-same-line (point-min)))
11127 (not (js2-1-line-comment-continuation-p)))
11128 (js2-bounce-indent indent-col parse-status bounce-backwards))
11129 ;; just indent to the guesser's likely spot
11130 (t (indent-line-to indent-col))))
11131 (when (cl-plusp offset)
11132 (forward-char offset)))))
11133
11134 (defun js2-indent-region (start end)
11135 "Indent the region, but don't use bounce indenting."
11136 (let ((js2-bounce-indent-p nil)
11137 (indent-region-function nil)
11138 (after-change-functions (remq 'js2-mode-edit
11139 after-change-functions)))
11140 (indent-region start end nil) ; nil for byte-compiler
11141 (js2-mode-edit start end (- end start))))
11142
11143 (defvar js2-minor-mode-map
11144 (let ((map (make-sparse-keymap)))
11145 (define-key map (kbd "C-c C-`") #'js2-next-error)
11146 (define-key map [mouse-1] #'js2-mode-show-node)
11147 map)
11148 "Keymap used when `js2-minor-mode' is active.")
11149
11150 ;;;###autoload
11151 (define-minor-mode js2-minor-mode
11152 "Minor mode for running js2 as a background linter.
11153 This allows you to use a different major mode for JavaScript editing,
11154 such as `js-mode', while retaining the asynchronous error/warning
11155 highlighting features of `js2-mode'."
11156 :group 'js2-mode
11157 :lighter " js-lint"
11158 (if js2-minor-mode
11159 (js2-minor-mode-enter)
11160 (js2-minor-mode-exit)))
11161
11162 (defun js2-minor-mode-enter ()
11163 "Initialization for `js2-minor-mode'."
11164 (set (make-local-variable 'max-lisp-eval-depth)
11165 (max max-lisp-eval-depth 3000))
11166 (setq next-error-function #'js2-next-error)
11167 (js2-set-default-externs)
11168 ;; Experiment: make reparse-delay longer for longer files.
11169 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11170 (setq js2-idle-timer-delay
11171 (* js2-idle-timer-delay
11172 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11173 (setq js2-mode-buffer-dirty-p t
11174 js2-mode-parsing nil)
11175 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11176 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11177 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11178 (when js2-include-jslint-globals
11179 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11180 (run-hooks 'js2-init-hook)
11181 (js2-reparse))
11182
11183 (defun js2-minor-mode-exit ()
11184 "Turn off `js2-minor-mode'."
11185 (setq next-error-function nil)
11186 (remove-hook 'after-change-functions #'js2-mode-edit t)
11187 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11188 (when js2-mode-node-overlay
11189 (delete-overlay js2-mode-node-overlay)
11190 (setq js2-mode-node-overlay nil))
11191 (js2-remove-overlays)
11192 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11193 (setq js2-mode-ast nil))
11194
11195 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11196 (make-variable-buffer-local 'js2-source-buffer)
11197
11198 (cl-defun js2-display-error-list ()
11199 "Display a navigable buffer listing parse errors/warnings."
11200 (interactive)
11201 (unless (js2-have-errors-p)
11202 (message "No errors")
11203 (cl-return-from js2-display-error-list))
11204 (cl-labels ((annotate-list
11205 (lst type)
11206 "Add diagnostic TYPE and line number to errs list"
11207 (mapcar (lambda (err)
11208 (list err type (line-number-at-pos (nth 1 err))))
11209 lst)))
11210 (let* ((srcbuf (current-buffer))
11211 (errbuf (get-buffer-create "*js-lint*"))
11212 (errors (annotate-list
11213 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11214 'js2-error)) ; must be a valid face name
11215 (warnings (annotate-list
11216 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11217 'js2-warning)) ; must be a valid face name
11218 (all-errs (sort (append errors warnings)
11219 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11220 (with-current-buffer errbuf
11221 (let ((inhibit-read-only t))
11222 (erase-buffer)
11223 (dolist (err all-errs)
11224 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11225 (insert-text-button
11226 (format "line %d: %s" line (js2-get-msg msg-key))
11227 'face type
11228 'follow-link "\C-m"
11229 'action 'js2-error-buffer-jump
11230 'js2-msg (js2-get-msg msg-key)
11231 'js2-pos beg)
11232 (insert "\n"))))
11233 (js2-error-buffer-mode)
11234 (setq js2-source-buffer srcbuf)
11235 (pop-to-buffer errbuf)
11236 (goto-char (point-min))
11237 (unless (eobp)
11238 (js2-error-buffer-view))))))
11239
11240 (defvar js2-error-buffer-mode-map
11241 (let ((map (make-sparse-keymap)))
11242 (define-key map "n" #'js2-error-buffer-next)
11243 (define-key map "p" #'js2-error-buffer-prev)
11244 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11245 (define-key map "o" #'js2-error-buffer-view)
11246 (define-key map "q" #'js2-error-buffer-quit)
11247 map)
11248 "Keymap used for js2 diagnostics buffers.")
11249
11250 (defun js2-error-buffer-mode ()
11251 "Major mode for js2 diagnostics buffers.
11252 Selecting an error will jump it to the corresponding source-buffer error.
11253 \\{js2-error-buffer-mode-map}"
11254 (interactive)
11255 (setq major-mode 'js2-error-buffer-mode
11256 mode-name "JS Lint Diagnostics")
11257 (use-local-map js2-error-buffer-mode-map)
11258 (setq truncate-lines t)
11259 (set-buffer-modified-p nil)
11260 (setq buffer-read-only t)
11261 (run-hooks 'js2-error-buffer-mode-hook))
11262
11263 (defun js2-error-buffer-next ()
11264 "Move to next error and view it."
11265 (interactive)
11266 (when (zerop (forward-line 1))
11267 (js2-error-buffer-view)))
11268
11269 (defun js2-error-buffer-prev ()
11270 "Move to previous error and view it."
11271 (interactive)
11272 (when (zerop (forward-line -1))
11273 (js2-error-buffer-view)))
11274
11275 (defun js2-error-buffer-quit ()
11276 "Kill the current buffer."
11277 (interactive)
11278 (kill-buffer))
11279
11280 (defun js2-error-buffer-jump (&rest ignored)
11281 "Jump cursor to current error in source buffer."
11282 (interactive)
11283 (when (js2-error-buffer-view)
11284 (pop-to-buffer js2-source-buffer)))
11285
11286 (defun js2-error-buffer-view ()
11287 "Scroll source buffer to show error at current line."
11288 (interactive)
11289 (cond
11290 ((not (eq major-mode 'js2-error-buffer-mode))
11291 (message "Not in a js2 errors buffer"))
11292 ((not (buffer-live-p js2-source-buffer))
11293 (message "Source buffer has been killed"))
11294 ((not (wholenump (get-text-property (point) 'js2-pos)))
11295 (message "There does not seem to be an error here"))
11296 (t
11297 (let ((pos (get-text-property (point) 'js2-pos))
11298 (msg (get-text-property (point) 'js2-msg)))
11299 (save-selected-window
11300 (pop-to-buffer js2-source-buffer)
11301 (goto-char pos)
11302 (message msg))))))
11303
11304 ;;;###autoload
11305 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11306 ;; FIXME: Should derive from js-mode.
11307 "Major mode for editing JavaScript code."
11308 ;; Used by comment-region; don't change it.
11309 (set (make-local-variable 'comment-start) "//")
11310 (set (make-local-variable 'comment-end) "")
11311 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11312 (set (make-local-variable 'max-lisp-eval-depth)
11313 (max max-lisp-eval-depth 3000))
11314 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11315 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11316 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11317 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11318 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11319 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11320 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11321 ;; for characters inside regexp literals.
11322 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11323 ;; this is necessary to make `show-paren-function' work properly
11324 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11325 ;; needed for M-x rgrep, among other things
11326 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11327
11328 (set (make-local-variable 'electric-indent-chars)
11329 (append "{}()[]:;,*." electric-indent-chars))
11330 (set (make-local-variable 'electric-layout-rules)
11331 '((?\; . after) (?\{ . after) (?\} . before)))
11332
11333 ;; some variables needed by cc-engine for paragraph-fill, etc.
11334 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11335 c-comment-start-regexp "/[*/]\\|\\s|"
11336 c-line-comment-starter "//"
11337 c-paragraph-start js2-paragraph-start
11338 c-paragraph-separate "$"
11339 c-syntactic-ws-start js2-syntactic-ws-start
11340 c-syntactic-ws-end js2-syntactic-ws-end
11341 c-syntactic-eol js2-syntactic-eol)
11342
11343 (let ((c-buffer-is-cc-mode t))
11344 ;; Copied from `js-mode'. Also see Bug#6071.
11345 (make-local-variable 'paragraph-start)
11346 (make-local-variable 'paragraph-separate)
11347 (make-local-variable 'paragraph-ignore-fill-prefix)
11348 (make-local-variable 'adaptive-fill-mode)
11349 (make-local-variable 'adaptive-fill-regexp)
11350 (c-setup-paragraph-variables))
11351
11352 (setq font-lock-defaults '(nil t))
11353
11354 ;; Experiment: make reparse-delay longer for longer files.
11355 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11356 (setq js2-idle-timer-delay
11357 (* js2-idle-timer-delay
11358 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11359
11360 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11361 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11362 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11363 (setq next-error-function #'js2-next-error)
11364 (imenu-add-to-menubar (concat "IM-" mode-name))
11365 (add-to-invisibility-spec '(js2-outline . t))
11366 (set (make-local-variable 'line-move-ignore-invisible) t)
11367 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11368
11369 (setq js2-mode-functions-hidden nil
11370 js2-mode-comments-hidden nil
11371 js2-mode-buffer-dirty-p t
11372 js2-mode-parsing nil)
11373
11374 (js2-set-default-externs)
11375
11376 (when js2-include-jslint-globals
11377 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11378
11379 (run-hooks 'js2-init-hook)
11380
11381 (js2-reparse))
11382
11383 (defun js2-mode-exit ()
11384 "Exit `js2-mode' and clean up."
11385 (interactive)
11386 (when js2-mode-node-overlay
11387 (delete-overlay js2-mode-node-overlay)
11388 (setq js2-mode-node-overlay nil))
11389 (js2-remove-overlays)
11390 (setq js2-mode-ast nil)
11391 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11392 (remove-from-invisibility-spec '(js2-outline . t))
11393 (js2-mode-show-all)
11394 (with-silent-modifications
11395 (js2-clear-face (point-min) (point-max))))
11396
11397 (defun js2-mode-reset-timer ()
11398 "Cancel any existing parse timer and schedule a new one."
11399 (if js2-mode-parse-timer
11400 (cancel-timer js2-mode-parse-timer))
11401 (setq js2-mode-parsing nil)
11402 (let ((timer (timer-create)))
11403 (setq js2-mode-parse-timer timer)
11404 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11405 (timer-set-idle-time timer js2-idle-timer-delay)
11406 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11407 (timer-activate-when-idle timer nil)))
11408
11409 (defun js2-mode-idle-reparse (buffer)
11410 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11411 it to be reparsed when the buffer is selected."
11412 (cond ((eq buffer (current-buffer))
11413 (js2-reparse))
11414 ((buffer-live-p buffer)
11415 ;; reparse when the buffer is selected again
11416 (with-current-buffer buffer
11417 (add-hook 'window-configuration-change-hook
11418 #'js2-mode-idle-reparse-inner
11419 nil t)))))
11420
11421 (defun js2-mode-idle-reparse-inner ()
11422 (remove-hook 'window-configuration-change-hook
11423 #'js2-mode-idle-reparse-inner
11424 t)
11425 (js2-reparse))
11426
11427 (defun js2-mode-edit (_beg _end _len)
11428 "Schedule a new parse after buffer is edited.
11429 Buffer edit spans from BEG to END and is of length LEN."
11430 (setq js2-mode-buffer-dirty-p t)
11431 (js2-mode-hide-overlay)
11432 (js2-mode-reset-timer))
11433
11434 (defun js2-minor-mode-edit (_beg _end _len)
11435 "Callback for buffer edits in `js2-mode'.
11436 Schedules a new parse after buffer is edited.
11437 Buffer edit spans from BEG to END and is of length LEN."
11438 (setq js2-mode-buffer-dirty-p t)
11439 (js2-mode-hide-overlay)
11440 (js2-mode-reset-timer))
11441
11442 (defun js2-reparse (&optional force)
11443 "Re-parse current buffer after user finishes some data entry.
11444 If we get any user input while parsing, including cursor motion,
11445 we discard the parse and reschedule it. If FORCE is nil, then the
11446 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11447 (let (time
11448 interrupted-p
11449 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11450 (unless js2-mode-parsing
11451 (setq js2-mode-parsing t)
11452 (unwind-protect
11453 (when (or js2-mode-buffer-dirty-p force)
11454 (js2-remove-overlays)
11455 (setq js2-mode-buffer-dirty-p nil
11456 js2-mode-fontifications nil
11457 js2-mode-deferred-properties nil)
11458 (if js2-mode-verbose-parse-p
11459 (message "parsing..."))
11460 (setq time
11461 (js2-time
11462 (setq interrupted-p
11463 (catch 'interrupted
11464 (js2-parse)
11465 (with-silent-modifications
11466 ;; if parsing is interrupted, comments and regex
11467 ;; literals stay ignored by `parse-partial-sexp'
11468 (remove-text-properties (point-min) (point-max)
11469 '(syntax-table))
11470 (js2-mode-apply-deferred-properties)
11471 (js2-mode-remove-suppressed-warnings)
11472 (js2-mode-show-warnings)
11473 (js2-mode-show-errors)
11474 (if (>= js2-highlight-level 1)
11475 (js2-highlight-jsdoc js2-mode-ast)))
11476 nil))))
11477 (if interrupted-p
11478 (progn
11479 ;; unfinished parse => try again
11480 (setq js2-mode-buffer-dirty-p t)
11481 (js2-mode-reset-timer))
11482 (if js2-mode-verbose-parse-p
11483 (message "Parse time: %s" time))))
11484 (setq js2-mode-parsing nil)
11485 (unless interrupted-p
11486 (setq js2-mode-parse-timer nil))))))
11487
11488 (defun js2-mode-show-node (event)
11489 "Debugging aid: highlight selected AST node on mouse click."
11490 (interactive "e")
11491 (mouse-set-point event)
11492 (setq deactivate-mark t)
11493 (when js2-mode-show-overlay
11494 (let ((node (js2-node-at-point))
11495 beg end)
11496 (if (null node)
11497 (message "No node found at location %s" (point))
11498 (setq beg (js2-node-abs-pos node)
11499 end (+ beg (js2-node-len node)))
11500 (if js2-mode-node-overlay
11501 (move-overlay js2-mode-node-overlay beg end)
11502 (setq js2-mode-node-overlay (make-overlay beg end))
11503 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11504 (with-silent-modifications
11505 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
11506 (message "%s, parent: %s"
11507 (js2-node-short-name node)
11508 (if (js2-node-parent node)
11509 (js2-node-short-name (js2-node-parent node))
11510 "nil"))))))
11511
11512 (defun js2-mode-hide-overlay (&optional _p1 p2)
11513 "Remove the debugging overlay when the point moves.
11514 P1 and P2 are the old and new values of point, respectively."
11515 (when js2-mode-node-overlay
11516 (let ((beg (overlay-start js2-mode-node-overlay))
11517 (end (overlay-end js2-mode-node-overlay)))
11518 ;; Sometimes we're called spuriously.
11519 (unless (and p2
11520 (>= p2 beg)
11521 (<= p2 end))
11522 (with-silent-modifications
11523 (remove-text-properties beg end '(point-left nil)))
11524 (delete-overlay js2-mode-node-overlay)
11525 (setq js2-mode-node-overlay nil)))))
11526
11527 (defun js2-mode-reset ()
11528 "Debugging helper: reset everything."
11529 (interactive)
11530 (js2-mode-exit)
11531 (js2-mode))
11532
11533 (defun js2-mode-show-warn-or-err (e face)
11534 "Highlight a warning or error E with FACE.
11535 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11536 The last element is optional. When present, use instead of FACE."
11537 (let* ((key (cl-first e))
11538 (beg (cl-second e))
11539 (end (+ beg (cl-third e)))
11540 ;; Don't inadvertently go out of bounds.
11541 (beg (max (point-min) (min beg (point-max))))
11542 (end (max (point-min) (min end (point-max))))
11543 (ovl (make-overlay beg end)))
11544 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11545 (overlay-put ovl 'js2-error t)
11546 (put-text-property beg end 'help-echo (js2-get-msg key))
11547 (put-text-property beg end 'point-entered #'js2-echo-error)))
11548
11549 (defun js2-remove-overlays ()
11550 "Remove overlays from buffer that have a `js2-error' property."
11551 (let ((beg (point-min))
11552 (end (point-max)))
11553 (save-excursion
11554 (dolist (o (overlays-in beg end))
11555 (when (overlay-get o 'js2-error)
11556 (delete-overlay o))))))
11557
11558 (defun js2-error-at-point (&optional pos)
11559 "Return non-nil if there's an error overlay at POS.
11560 Defaults to point."
11561 (cl-loop with pos = (or pos (point))
11562 for o in (overlays-at pos)
11563 thereis (overlay-get o 'js2-error)))
11564
11565 (defun js2-mode-apply-deferred-properties ()
11566 "Apply fontifications and other text properties recorded during parsing."
11567 (when (cl-plusp js2-highlight-level)
11568 ;; We defer clearing faces as long as possible to eliminate flashing.
11569 (js2-clear-face (point-min) (point-max))
11570 ;; Have to reverse the recorded fontifications list so that errors
11571 ;; and warnings overwrite the normal fontifications.
11572 (dolist (f (nreverse js2-mode-fontifications))
11573 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11574 (setq js2-mode-fontifications nil))
11575 (dolist (p js2-mode-deferred-properties)
11576 (apply #'put-text-property p))
11577 (setq js2-mode-deferred-properties nil))
11578
11579 (defun js2-mode-show-errors ()
11580 "Highlight syntax errors."
11581 (when js2-mode-show-parse-errors
11582 (dolist (e (js2-ast-root-errors js2-mode-ast))
11583 (js2-mode-show-warn-or-err e 'js2-error))))
11584
11585 (defun js2-mode-remove-suppressed-warnings ()
11586 "Take suppressed warnings out of the AST warnings list.
11587 This ensures that the counts and `next-error' are correct."
11588 (setf (js2-ast-root-warnings js2-mode-ast)
11589 (js2-delete-if
11590 (lambda (e)
11591 (let ((key (caar e)))
11592 (or
11593 (and (not js2-strict-trailing-comma-warning)
11594 (string-match "trailing\\.comma" key))
11595 (and (not js2-strict-cond-assign-warning)
11596 (string= key "msg.equal.as.assign"))
11597 (and js2-missing-semi-one-line-override
11598 (string= key "msg.missing.semi")
11599 (let* ((beg (cl-second e))
11600 (node (js2-node-at-point beg))
11601 (fn (js2-mode-find-parent-fn node))
11602 (body (and fn (js2-function-node-body fn)))
11603 (lc (and body (js2-node-abs-pos body)))
11604 (rc (and lc (+ lc (js2-node-len body)))))
11605 (and fn
11606 (or (null body)
11607 (save-excursion
11608 (goto-char beg)
11609 (and (js2-same-line lc)
11610 (js2-same-line rc))))))))))
11611 (js2-ast-root-warnings js2-mode-ast))))
11612
11613 (defun js2-mode-show-warnings ()
11614 "Highlight strict-mode warnings."
11615 (when js2-mode-show-strict-warnings
11616 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11617 (js2-mode-show-warn-or-err e 'js2-warning))))
11618
11619 (defun js2-echo-error (_old-point new-point)
11620 "Called by point-motion hooks."
11621 (let ((msg (get-text-property new-point 'help-echo)))
11622 (when (and (stringp msg)
11623 (not (active-minibuffer-window))
11624 (not (current-message)))
11625 (message msg))))
11626
11627 (defalias 'js2-echo-help #'js2-echo-error)
11628
11629 (defun js2-line-break (&optional _soft)
11630 "Break line at point and indent, continuing comment if within one.
11631 If inside a string, and `js2-concat-multiline-strings' is not
11632 nil, turn it into concatenation."
11633 (interactive)
11634 (let ((parse-status (syntax-ppss)))
11635 (cond
11636 ;; Check if we're inside a string.
11637 ((nth 3 parse-status)
11638 (if js2-concat-multiline-strings
11639 (js2-mode-split-string parse-status)
11640 (insert "\n")))
11641 ;; Check if inside a block comment.
11642 ((nth 4 parse-status)
11643 (js2-mode-extend-comment (nth 8 parse-status)))
11644 (t
11645 (newline-and-indent)))))
11646
11647 (defun js2-mode-split-string (parse-status)
11648 "Turn a newline in mid-string into a string concatenation.
11649 PARSE-STATUS is as documented in `parse-partial-sexp'."
11650 (let* ((quote-char (nth 3 parse-status))
11651 (at-eol (eq js2-concat-multiline-strings 'eol)))
11652 (insert quote-char)
11653 (insert (if at-eol " +\n" "\n"))
11654 (unless at-eol
11655 (insert "+ "))
11656 (js2-indent-line)
11657 (insert quote-char)
11658 (when (eolp)
11659 (insert quote-char)
11660 (backward-char 1))))
11661
11662 (defun js2-mode-extend-comment (start-pos)
11663 "Indent the line and, when inside a comment block, add comment prefix."
11664 (let (star single col first-line needs-close)
11665 (save-excursion
11666 (back-to-indentation)
11667 (when (< (point) start-pos)
11668 (goto-char start-pos))
11669 (cond
11670 ((looking-at "\\*[^/]")
11671 (setq star t
11672 col (current-column)))
11673 ((looking-at "/\\*")
11674 (setq star t
11675 first-line t
11676 col (1+ (current-column))))
11677 ((looking-at "//")
11678 (setq single t
11679 col (current-column)))))
11680 ;; Heuristic for whether we need to close the comment:
11681 ;; if we've got a parse error here, assume it's an unterminated
11682 ;; comment.
11683 (setq needs-close
11684 (or
11685 (eq (get-text-property (1- (point)) 'point-entered)
11686 'js2-echo-error)
11687 ;; The heuristic above doesn't work well when we're
11688 ;; creating a comment and there's another one downstream,
11689 ;; as our parser thinks this one ends at the end of the
11690 ;; next one. (You can have a /* inside a js block comment.)
11691 ;; So just close it if the next non-ws char isn't a *.
11692 (and first-line
11693 (eolp)
11694 (save-excursion
11695 (skip-chars-forward " \t\r\n")
11696 (not (eq (char-after) ?*))))))
11697 (delete-horizontal-space)
11698 (insert "\n")
11699 (cond
11700 (star
11701 (indent-to col)
11702 (insert "* ")
11703 (if (and first-line needs-close)
11704 (save-excursion
11705 (insert "\n")
11706 (indent-to col)
11707 (insert "*/"))))
11708 ((and single
11709 (save-excursion
11710 (and (zerop (forward-line 1))
11711 (looking-at "\\s-*//"))))
11712 (indent-to col)
11713 (insert "// ")))
11714 ;; Don't need to extend the comment after all.
11715 (js2-indent-line)))
11716
11717 (defun js2-beginning-of-line ()
11718 "Toggle point between bol and first non-whitespace char in line.
11719 Also moves past comment delimiters when inside comments."
11720 (interactive)
11721 (let (node)
11722 (cond
11723 ((bolp)
11724 (back-to-indentation))
11725 ((looking-at "//")
11726 (skip-chars-forward "/ \t"))
11727 ((and (eq (char-after) ?*)
11728 (setq node (js2-comment-at-point))
11729 (memq (js2-comment-node-format node) '(jsdoc block))
11730 (save-excursion
11731 (skip-chars-backward " \t")
11732 (bolp)))
11733 (skip-chars-forward "\* \t"))
11734 (t
11735 (goto-char (point-at-bol))))))
11736
11737 (defun js2-end-of-line ()
11738 "Toggle point between eol and last non-whitespace char in line."
11739 (interactive)
11740 (if (eolp)
11741 (skip-chars-backward " \t")
11742 (goto-char (point-at-eol))))
11743
11744 (defun js2-mode-wait-for-parse (callback)
11745 "Invoke CALLBACK when parsing is finished.
11746 If parsing is already finished, calls CALLBACK immediately."
11747 (if (not js2-mode-buffer-dirty-p)
11748 (funcall callback)
11749 (push callback js2-mode-pending-parse-callbacks)
11750 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11751
11752 (defun js2-mode-parse-finished ()
11753 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11754 ;; We can't let errors propagate up, since it prevents the
11755 ;; `js2-parse' method from completing normally and returning
11756 ;; the ast, which makes things mysteriously not work right.
11757 (unwind-protect
11758 (dolist (cb js2-mode-pending-parse-callbacks)
11759 (condition-case err
11760 (funcall cb)
11761 (error (message "%s" err))))
11762 (setq js2-mode-pending-parse-callbacks nil)))
11763
11764 (defun js2-mode-flag-region (from to flag)
11765 "Hide or show text from FROM to TO, according to FLAG.
11766 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11767 Returns the created overlay if FLAG is non-nil."
11768 (remove-overlays from to 'invisible 'js2-outline)
11769 (when flag
11770 (let ((o (make-overlay from to)))
11771 (overlay-put o 'invisible 'js2-outline)
11772 (overlay-put o 'isearch-open-invisible
11773 'js2-isearch-open-invisible)
11774 o)))
11775
11776 ;; Function to be set as an outline-isearch-open-invisible' property
11777 ;; to the overlay that makes the outline invisible (see
11778 ;; `js2-mode-flag-region').
11779 (defun js2-isearch-open-invisible (_overlay)
11780 ;; We rely on the fact that isearch places point on the matched text.
11781 (js2-mode-show-element))
11782
11783 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11784 "Return cons cell of bounds of folding overlay at POS.
11785 Returns nil if not found."
11786 (let ((overlays (overlays-at (or pos (point))))
11787 o)
11788 (while (and overlays
11789 (not o))
11790 (if (overlay-get (car overlays) 'invisible)
11791 (setq o (car overlays))
11792 (setq overlays (cdr overlays))))
11793 (if o
11794 (cons (overlay-start o) (overlay-end o)))))
11795
11796 (defun js2-mode-function-at-point (&optional pos)
11797 "Return the innermost function node enclosing current point.
11798 Returns nil if point is not in a function."
11799 (let ((node (js2-node-at-point pos)))
11800 (while (and node (not (js2-function-node-p node)))
11801 (setq node (js2-node-parent node)))
11802 (if (js2-function-node-p node)
11803 node)))
11804
11805 (defun js2-mode-toggle-element ()
11806 "Hide or show the foldable element at the point."
11807 (interactive)
11808 (let (comment fn pos)
11809 (save-excursion
11810 (cond
11811 ;; /* ... */ comment?
11812 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11813 (if (js2-mode-invisible-overlay-bounds
11814 (setq pos (+ 3 (js2-node-abs-pos comment))))
11815 (progn
11816 (goto-char pos)
11817 (js2-mode-show-element))
11818 (js2-mode-hide-element)))
11819 ;; //-comment?
11820 ((save-excursion
11821 (back-to-indentation)
11822 (looking-at js2-mode-//-comment-re))
11823 (js2-mode-toggle-//-comment))
11824 ;; function?
11825 ((setq fn (js2-mode-function-at-point))
11826 (setq pos (and (js2-function-node-body fn)
11827 (js2-node-abs-pos (js2-function-node-body fn))))
11828 (goto-char (1+ pos))
11829 (if (js2-mode-invisible-overlay-bounds)
11830 (js2-mode-show-element)
11831 (js2-mode-hide-element)))
11832 (t
11833 (message "Nothing at point to hide or show"))))))
11834
11835 (defun js2-mode-hide-element ()
11836 "Fold/hide contents of a block, showing ellipses.
11837 Show the hidden text with \\[js2-mode-show-element]."
11838 (interactive)
11839 (if js2-mode-buffer-dirty-p
11840 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11841 (let (node body beg end)
11842 (cond
11843 ((js2-mode-invisible-overlay-bounds)
11844 (message "already hidden"))
11845 (t
11846 (setq node (js2-node-at-point))
11847 (cond
11848 ((js2-block-comment-p node)
11849 (js2-mode-hide-comment node))
11850 (t
11851 (while (and node (not (js2-function-node-p node)))
11852 (setq node (js2-node-parent node)))
11853 (if (and node
11854 (setq body (js2-function-node-body node)))
11855 (progn
11856 (setq beg (js2-node-abs-pos body)
11857 end (+ beg (js2-node-len body)))
11858 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11859 (message "No collapsable element found at point"))))))))
11860
11861 (defun js2-mode-show-element ()
11862 "Show the hidden element at current point."
11863 (interactive)
11864 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11865 (if bounds
11866 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11867 (message "Nothing to un-hide"))))
11868
11869 (defun js2-mode-show-all ()
11870 "Show all of the text in the buffer."
11871 (interactive)
11872 (js2-mode-flag-region (point-min) (point-max) nil))
11873
11874 (defun js2-mode-toggle-hide-functions ()
11875 (interactive)
11876 (if js2-mode-functions-hidden
11877 (js2-mode-show-functions)
11878 (js2-mode-hide-functions)))
11879
11880 (defun js2-mode-hide-functions ()
11881 "Hides all non-nested function bodies in the buffer.
11882 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11883 to open an individual entry."
11884 (interactive)
11885 (if js2-mode-buffer-dirty-p
11886 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11887 (if (null js2-mode-ast)
11888 (message "Oops - parsing failed")
11889 (setq js2-mode-functions-hidden t)
11890 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11891
11892 (defun js2-mode-function-hider (n endp)
11893 (when (not endp)
11894 (let ((tt (js2-node-type n))
11895 body beg end)
11896 (cond
11897 ((and (= tt js2-FUNCTION)
11898 (setq body (js2-function-node-body n)))
11899 (setq beg (js2-node-abs-pos body)
11900 end (+ beg (js2-node-len body)))
11901 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11902 nil) ; don't process children of function
11903 (t
11904 t))))) ; keep processing other AST nodes
11905
11906 (defun js2-mode-show-functions ()
11907 "Un-hide any folded function bodies in the buffer."
11908 (interactive)
11909 (setq js2-mode-functions-hidden nil)
11910 (save-excursion
11911 (goto-char (point-min))
11912 (while (/= (goto-char (next-overlay-change (point)))
11913 (point-max))
11914 (dolist (o (overlays-at (point)))
11915 (when (and (overlay-get o 'invisible)
11916 (not (overlay-get o 'comment)))
11917 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11918
11919 (defun js2-mode-hide-comment (n)
11920 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11921 3 ; /**
11922 2)) ; /*
11923 (beg (+ (js2-node-abs-pos n) head))
11924 (end (- (+ beg (js2-node-len n)) head 2))
11925 (o (js2-mode-flag-region beg end 'hide)))
11926 (overlay-put o 'comment t)))
11927
11928 (defun js2-mode-toggle-hide-comments ()
11929 "Folds all block comments in the buffer.
11930 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11931 to open an individual entry."
11932 (interactive)
11933 (if js2-mode-comments-hidden
11934 (js2-mode-show-comments)
11935 (js2-mode-hide-comments)))
11936
11937 (defun js2-mode-hide-comments ()
11938 (interactive)
11939 (if js2-mode-buffer-dirty-p
11940 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11941 (if (null js2-mode-ast)
11942 (message "Oops - parsing failed")
11943 (setq js2-mode-comments-hidden t)
11944 (dolist (n (js2-ast-root-comments js2-mode-ast))
11945 (when (js2-block-comment-p n)
11946 (js2-mode-hide-comment n)))
11947 (js2-mode-hide-//-comments)))
11948
11949 (defun js2-mode-extend-//-comment (direction)
11950 "Find start or end of a block of similar //-comment lines.
11951 DIRECTION is -1 to look back, 1 to look forward.
11952 INDENT is the indentation level to match.
11953 Returns the end-of-line position of the furthest adjacent
11954 //-comment line with the same indentation as the current line.
11955 If there is no such matching line, returns current end of line."
11956 (let ((pos (point-at-eol))
11957 (indent (current-indentation)))
11958 (save-excursion
11959 (while (and (zerop (forward-line direction))
11960 (looking-at js2-mode-//-comment-re)
11961 (eq indent (length (match-string 1))))
11962 (setq pos (point-at-eol)))
11963 pos)))
11964
11965 (defun js2-mode-hide-//-comments ()
11966 "Fold adjacent 1-line comments, showing only snippet of first one."
11967 (let (beg end)
11968 (save-excursion
11969 (goto-char (point-min))
11970 (while (re-search-forward js2-mode-//-comment-re nil t)
11971 (setq beg (point)
11972 end (js2-mode-extend-//-comment 1))
11973 (unless (eq beg end)
11974 (overlay-put (js2-mode-flag-region beg end 'hide)
11975 'comment t))
11976 (goto-char end)
11977 (forward-char 1)))))
11978
11979 (defun js2-mode-toggle-//-comment ()
11980 "Fold or un-fold any multi-line //-comment at point.
11981 Caller should have determined that this line starts with a //-comment."
11982 (let* ((beg (point-at-eol))
11983 (end beg))
11984 (save-excursion
11985 (goto-char end)
11986 (if (js2-mode-invisible-overlay-bounds)
11987 (js2-mode-show-element)
11988 ;; else hide the comment
11989 (setq beg (js2-mode-extend-//-comment -1)
11990 end (js2-mode-extend-//-comment 1))
11991 (unless (eq beg end)
11992 (overlay-put (js2-mode-flag-region beg end 'hide)
11993 'comment t))))))
11994
11995 (defun js2-mode-show-comments ()
11996 "Un-hide any hidden comments, leaving other hidden elements alone."
11997 (interactive)
11998 (setq js2-mode-comments-hidden nil)
11999 (save-excursion
12000 (goto-char (point-min))
12001 (while (/= (goto-char (next-overlay-change (point)))
12002 (point-max))
12003 (dolist (o (overlays-at (point)))
12004 (when (overlay-get o 'comment)
12005 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12006
12007 (defun js2-mode-display-warnings-and-errors ()
12008 "Turn on display of warnings and errors."
12009 (interactive)
12010 (setq js2-mode-show-parse-errors t
12011 js2-mode-show-strict-warnings t)
12012 (js2-reparse 'force))
12013
12014 (defun js2-mode-hide-warnings-and-errors ()
12015 "Turn off display of warnings and errors."
12016 (interactive)
12017 (setq js2-mode-show-parse-errors nil
12018 js2-mode-show-strict-warnings nil)
12019 (js2-reparse 'force))
12020
12021 (defun js2-mode-toggle-warnings-and-errors ()
12022 "Toggle the display of warnings and errors.
12023 Some users don't like having warnings/errors reported while they type."
12024 (interactive)
12025 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12026 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12027 (if (called-interactively-p 'any)
12028 (message "warnings and errors %s"
12029 (if js2-mode-show-parse-errors
12030 "enabled"
12031 "disabled")))
12032 (js2-reparse 'force))
12033
12034 (defun js2-mode-customize ()
12035 (interactive)
12036 (customize-group 'js2-mode))
12037
12038 (defun js2-mode-forward-sexp (&optional arg)
12039 "Move forward across one statement or balanced expression.
12040 With ARG, do it that many times. Negative arg -N means
12041 move backward across N balanced expressions."
12042 (interactive "p")
12043 (setq arg (or arg 1))
12044 (save-restriction
12045 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12046 (js2-reparse)
12047 (let (forward-sexp-function
12048 node (start (point)) pos lp rp child)
12049 (cond
12050 ;; backward-sexp
12051 ;; could probably make this better for some cases:
12052 ;; - if in statement block (e.g. function body), go to parent
12053 ;; - infix exprs like (foo in bar) - maybe go to beginning
12054 ;; of infix expr if in the right-side expression?
12055 ((and arg (cl-minusp arg))
12056 (dotimes (_ (- arg))
12057 (js2-backward-sws)
12058 (forward-char -1) ; Enter the node we backed up to.
12059 (when (setq node (js2-node-at-point (point) t))
12060 (setq pos (js2-node-abs-pos node))
12061 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12062 (setq lp (car parens)
12063 rp (cdr parens)))
12064 (when (and lp (> start lp))
12065 (if (and rp (<= start rp))
12066 ;; Between parens, check if there's a child node we can jump.
12067 (when (setq child (js2-node-closest-child node (point) lp t))
12068 (setq pos (js2-node-abs-pos child)))
12069 ;; Before both parens.
12070 (setq pos lp)))
12071 (let ((state (parse-partial-sexp start pos)))
12072 (goto-char (if (not (zerop (car state)))
12073 ;; Stumble at the unbalanced paren if < 0, or
12074 ;; jump a bit further if > 0.
12075 (scan-sexps start -1)
12076 pos))))
12077 (unless pos (goto-char (point-min)))))
12078 (t
12079 ;; forward-sexp
12080 (dotimes (_ arg)
12081 (js2-forward-sws)
12082 (when (setq node (js2-node-at-point (point) t))
12083 (setq pos (js2-node-abs-pos node))
12084 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12085 (setq lp (car parens)
12086 rp (cdr parens)))
12087 (or
12088 (when (and rp (<= start rp))
12089 (if (> start lp)
12090 (when (setq child (js2-node-closest-child node (point) rp))
12091 (setq pos (js2-node-abs-end child)))
12092 (setq pos (1+ rp))))
12093 ;; No parens or child nodes, looks for the end of the current node.
12094 (cl-incf pos (js2-node-len
12095 (if (js2-expr-stmt-node-p (js2-node-parent node))
12096 ;; Stop after the semicolon.
12097 (js2-node-parent node)
12098 node))))
12099 (let ((state (save-excursion (parse-partial-sexp start pos))))
12100 (goto-char (if (not (zerop (car state)))
12101 (scan-sexps start 1)
12102 pos))))
12103 (unless pos (goto-char (point-max)))))))))
12104
12105 (defun js2-mode-forward-sexp-parens (node abs-pos)
12106 "Return a cons cell with positions of main parens in NODE."
12107 (cond
12108 ((or (js2-array-node-p node)
12109 (js2-object-node-p node)
12110 (js2-comp-node-p node)
12111 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12112 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12113 ((js2-paren-expr-node-p node)
12114 (let ((lp (js2-node-lp node))
12115 (rp (js2-node-rp node)))
12116 (cons (when lp (+ abs-pos lp))
12117 (when rp (+ abs-pos rp)))))))
12118
12119 (defun js2-node-closest-child (parent point limit &optional before)
12120 (let* ((parent-pos (js2-node-abs-pos parent))
12121 (rpoint (- point parent-pos))
12122 (rlimit (- limit parent-pos))
12123 (min (min rpoint rlimit))
12124 (max (max rpoint rlimit))
12125 found)
12126 (catch 'done
12127 (js2-visit-ast
12128 parent
12129 (lambda (node _end-p)
12130 (if (eq node parent)
12131 t
12132 (let ((pos (js2-node-pos node)) ;; Both relative values.
12133 (end (+ (js2-node-pos node) (js2-node-len node))))
12134 (when (and (>= pos min) (<= end max)
12135 (if before (< pos rpoint) (> end rpoint)))
12136 (setq found node))
12137 (when (> end rpoint)
12138 (throw 'done nil)))
12139 nil))))
12140 found))
12141
12142 (defun js2-errors ()
12143 "Return a list of errors found."
12144 (and js2-mode-ast
12145 (js2-ast-root-errors js2-mode-ast)))
12146
12147 (defun js2-warnings ()
12148 "Return a list of warnings found."
12149 (and js2-mode-ast
12150 (js2-ast-root-warnings js2-mode-ast)))
12151
12152 (defun js2-have-errors-p ()
12153 "Return non-nil if any parse errors or warnings were found."
12154 (or (js2-errors) (js2-warnings)))
12155
12156 (defun js2-errors-and-warnings ()
12157 "Return a copy of the concatenated errors and warnings lists.
12158 They are appended: first the errors, then the warnings.
12159 Entries are of the form (MSG BEG END)."
12160 (when js2-mode-ast
12161 (append (js2-ast-root-errors js2-mode-ast)
12162 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12163
12164 (defun js2-next-error (&optional arg reset)
12165 "Move to next parse error.
12166 Typically invoked via \\[next-error].
12167 ARG is the number of errors, forward or backward, to move.
12168 RESET means start over from the beginning."
12169 (interactive "p")
12170 (if (not (or (js2-errors) (js2-warnings)))
12171 (message "No errors")
12172 (when reset
12173 (goto-char (point-min)))
12174 (let* ((errs (js2-errors-and-warnings))
12175 (continue t)
12176 (start (point))
12177 (count (or arg 1))
12178 (backward (cl-minusp count))
12179 (sorter (if backward '> '<))
12180 (stopper (if backward '< '>))
12181 (count (abs count))
12182 all-errs err)
12183 ;; Sort by start position.
12184 (setq errs (sort errs (lambda (e1 e2)
12185 (funcall sorter (cl-second e1) (cl-second e2))))
12186 all-errs errs)
12187 ;; Find nth error with pos > start.
12188 (while (and errs continue)
12189 (when (funcall stopper (cl-cadar errs) start)
12190 (setq err (car errs))
12191 (if (zerop (cl-decf count))
12192 (setq continue nil)))
12193 (setq errs (cdr errs)))
12194 ;; Clear for `js2-echo-error'.
12195 (message nil)
12196 (if err
12197 (goto-char (cl-second err))
12198 ;; Wrap around to first error.
12199 (goto-char (cl-second (car all-errs)))
12200 ;; If we were already on it, echo msg again.
12201 (if (= (point) start)
12202 (js2-echo-error (point) (point)))))))
12203
12204 (defun js2-down-mouse-3 ()
12205 "Make right-click move the point to the click location.
12206 This makes right-click context menu operations a bit more intuitive.
12207 The point will not move if the region is active, however, to avoid
12208 destroying the region selection."
12209 (interactive)
12210 (when (and js2-move-point-on-right-click
12211 (not mark-active))
12212 (let ((e last-input-event))
12213 (ignore-errors
12214 (goto-char (cl-cadadr e))))))
12215
12216 (defun js2-mode-create-imenu-index ()
12217 "Return an alist for `imenu--index-alist'."
12218 ;; This is built up in `js2-parse-record-imenu' during parsing.
12219 (when js2-mode-ast
12220 ;; if we have an ast but no recorder, they're requesting a rescan
12221 (unless js2-imenu-recorder
12222 (js2-reparse 'force))
12223 (prog1
12224 (js2-build-imenu-index)
12225 (setq js2-imenu-recorder nil
12226 js2-imenu-function-map nil))))
12227
12228 (defun js2-mode-find-tag ()
12229 "Replacement for `find-tag-default'.
12230 `find-tag-default' returns a ridiculous answer inside comments."
12231 (let (beg end)
12232 (js2-with-underscore-as-word-syntax
12233 (save-excursion
12234 (if (and (not (looking-at "[[:alnum:]_$]"))
12235 (looking-back "[[:alnum:]_$]"))
12236 (setq beg (progn (forward-word -1) (point))
12237 end (progn (forward-word 1) (point)))
12238 (setq beg (progn (forward-word 1) (point))
12239 end (progn (forward-word -1) (point))))
12240 (replace-regexp-in-string
12241 "[\"']" ""
12242 (buffer-substring-no-properties beg end))))))
12243
12244 (defun js2-mode-forward-sibling ()
12245 "Move to the end of the sibling following point in parent.
12246 Returns non-nil if successful, or nil if there was no following sibling."
12247 (let* ((node (js2-node-at-point))
12248 (parent (js2-mode-find-enclosing-fn node))
12249 sib)
12250 (when (setq sib (js2-node-find-child-after (point) parent))
12251 (goto-char (+ (js2-node-abs-pos sib)
12252 (js2-node-len sib))))))
12253
12254 (defun js2-mode-backward-sibling ()
12255 "Move to the beginning of the sibling node preceding point in parent.
12256 Parent is defined as the enclosing script or function."
12257 (let* ((node (js2-node-at-point))
12258 (parent (js2-mode-find-enclosing-fn node))
12259 sib)
12260 (when (setq sib (js2-node-find-child-before (point) parent))
12261 (goto-char (js2-node-abs-pos sib)))))
12262
12263 (defun js2-beginning-of-defun (&optional arg)
12264 "Go to line on which current function starts, and return t on success.
12265 If we're not in a function or already at the beginning of one, go
12266 to beginning of previous script-level element.
12267 With ARG N, do that N times. If N is negative, move forward."
12268 (setq arg (or arg 1))
12269 (if (cl-plusp arg)
12270 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12271 (when (cond
12272 ((js2-function-node-p parent)
12273 (goto-char (js2-node-abs-pos parent)))
12274 (t
12275 (js2-mode-backward-sibling)))
12276 (if (> arg 1)
12277 (js2-beginning-of-defun (1- arg))
12278 t)))
12279 (when (js2-end-of-defun)
12280 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12281
12282 (defun js2-end-of-defun ()
12283 "Go to the char after the last position of the current function
12284 or script-level element."
12285 (let* ((node (js2-node-at-point))
12286 (parent (or (and (js2-function-node-p node) node)
12287 (js2-node-parent-script-or-fn node)))
12288 script)
12289 (unless (js2-function-node-p parent)
12290 ;; Use current script-level node, or, if none, the next one.
12291 (setq script (or parent node)
12292 parent (js2-node-find-child-before (point) script))
12293 (when (or (null parent)
12294 (>= (point) (+ (js2-node-abs-pos parent)
12295 (js2-node-len parent))))
12296 (setq parent (js2-node-find-child-after (point) script))))
12297 (when parent
12298 (goto-char (+ (js2-node-abs-pos parent)
12299 (js2-node-len parent))))))
12300
12301 (defun js2-mark-defun (&optional allow-extend)
12302 "Put mark at end of this function, point at beginning.
12303 The function marked is the one that contains point.
12304
12305 Interactively, if this command is repeated,
12306 or (in Transient Mark mode) if the mark is active,
12307 it marks the next defun after the ones already marked."
12308 (interactive "p")
12309 (let (extended)
12310 (when (and allow-extend
12311 (or (and (eq last-command this-command) (mark t))
12312 (and transient-mark-mode mark-active)))
12313 (let ((sib (save-excursion
12314 (goto-char (mark))
12315 (if (js2-mode-forward-sibling)
12316 (point)))))
12317 (if sib
12318 (progn
12319 (set-mark sib)
12320 (setq extended t))
12321 ;; no more siblings - try extending to enclosing node
12322 (goto-char (mark t)))))
12323 (when (not extended)
12324 (let ((node (js2-node-at-point (point) t)) ; skip comments
12325 ast fn stmt parent beg end)
12326 (when (js2-ast-root-p node)
12327 (setq ast node
12328 node (or (js2-node-find-child-after (point) node)
12329 (js2-node-find-child-before (point) node))))
12330 ;; only mark whole buffer if we can't find any children
12331 (if (null node)
12332 (setq node ast))
12333 (if (js2-function-node-p node)
12334 (setq parent node)
12335 (setq fn (js2-mode-find-enclosing-fn node)
12336 stmt (if (or (null fn)
12337 (js2-ast-root-p fn))
12338 (js2-mode-find-first-stmt node))
12339 parent (or stmt fn)))
12340 (setq beg (js2-node-abs-pos parent)
12341 end (+ beg (js2-node-len parent)))
12342 (push-mark beg)
12343 (goto-char end)
12344 (exchange-point-and-mark)))))
12345
12346 (defun js2-narrow-to-defun ()
12347 "Narrow to the function enclosing point."
12348 (interactive)
12349 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12350 (fn (if (js2-script-node-p node)
12351 node
12352 (js2-mode-find-enclosing-fn node)))
12353 (beg (js2-node-abs-pos fn)))
12354 (unless (js2-ast-root-p fn)
12355 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12356
12357 (provide 'js2-mode)
12358
12359 ;;; js2-mode.el ends here