]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Merge pull request #221 from jacksonrayhamilton/enclosing-scope
[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 (while (and (setq node (js2-node-parent node))
2311 (not (js2-scope-p node))))
2312 node)
2313
2314 (defun js2-get-defining-scope (scope name &optional point)
2315 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2316 Returns `js2-scope' in which NAME is defined, or nil if not found.
2317
2318 If POINT is non-nil, and if the found declaration type is
2319 `js2-LET', also check that the declaration node is before POINT."
2320 (let ((sym (if (symbolp name)
2321 name
2322 (intern name)))
2323 result
2324 (continue t))
2325 (while (and scope continue)
2326 (if (or
2327 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2328 (and entry
2329 (or (not point)
2330 (not (eq js2-LET (js2-symbol-decl-type entry)))
2331 (>= point
2332 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2333 (and (eq sym 'arguments)
2334 (js2-function-node-p scope)))
2335 (setq continue nil
2336 result scope)
2337 (setq scope (js2-scope-parent-scope scope))))
2338 result))
2339
2340 (defun js2-scope-get-symbol (scope name)
2341 "Return symbol table entry for NAME in SCOPE.
2342 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2343 (and (js2-scope-symbol-table scope)
2344 (cdr (assq (if (symbolp name)
2345 name
2346 (intern name))
2347 (js2-scope-symbol-table scope)))))
2348
2349 (defun js2-scope-put-symbol (scope name symbol)
2350 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2351 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2352 (let* ((table (js2-scope-symbol-table scope))
2353 (sym (if (symbolp name) name (intern name)))
2354 (entry (assq sym table)))
2355 (if entry
2356 (setcdr entry symbol)
2357 (push (cons sym symbol)
2358 (js2-scope-symbol-table scope)))))
2359
2360 (cl-defstruct (js2-symbol
2361 (:constructor nil)
2362 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2363 "A symbol table entry."
2364 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2365 ;; js2-LET, or js2-CONST
2366 decl-type
2367 name ; string
2368 ast-node) ; a `js2-node'
2369
2370 (cl-defstruct (js2-error-node
2371 (:include js2-node)
2372 (:constructor nil) ; silence emacs21 byte-compiler
2373 (:constructor make-js2-error-node (&key (type js2-ERROR)
2374 (pos (js2-current-token-beg))
2375 len)))
2376 "AST node representing a parse error.")
2377
2378 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2379 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2380
2381 (cl-defstruct (js2-script-node
2382 (:include js2-scope)
2383 (:constructor nil)
2384 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2385 (pos (js2-current-token-beg))
2386 len
2387 ;; FIXME: What are those?
2388 var-decls
2389 fun-decls)))
2390 functions ; Lisp list of nested functions
2391 regexps ; Lisp list of (string . flags)
2392 symbols ; alist (every symbol gets unique index)
2393 (param-count 0)
2394 var-names ; vector of string names
2395 consts ; bool-vector matching var-decls
2396 (temp-number 0)) ; for generating temp variables
2397
2398 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2399 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2400
2401 (defun js2-print-script (node indent)
2402 (dolist (kid (js2-block-node-kids node))
2403 (js2-print-ast kid indent)))
2404
2405 (cl-defstruct (js2-ast-root
2406 (:include js2-script-node)
2407 (:constructor nil)
2408 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2409 (pos (js2-current-token-beg))
2410 len
2411 buffer)))
2412 "The root node of a js2 AST."
2413 buffer ; the source buffer from which the code was parsed
2414 comments ; a Lisp list of comments, ordered by start position
2415 errors ; a Lisp list of errors found during parsing
2416 warnings ; a Lisp list of warnings found during parsing
2417 node-count) ; number of nodes in the tree, including the root
2418
2419 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2420 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2421
2422 (defun js2-visit-ast-root (ast callback)
2423 (dolist (kid (js2-ast-root-kids ast))
2424 (js2-visit-ast kid callback))
2425 (dolist (comment (js2-ast-root-comments ast))
2426 (js2-visit-ast comment callback)))
2427
2428 (cl-defstruct (js2-comment-node
2429 (:include js2-node)
2430 (:constructor nil)
2431 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2432 (pos (js2-current-token-beg))
2433 len
2434 format)))
2435 format) ; 'line, 'block, 'jsdoc or 'html
2436
2437 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2438 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2439
2440 (defun js2-print-comment (n i)
2441 ;; We really ought to link end-of-line comments to their nodes.
2442 ;; Or maybe we could add a new comment type, 'endline.
2443 (insert (js2-make-pad i)
2444 (js2-node-string n)))
2445
2446 (cl-defstruct (js2-expr-stmt-node
2447 (:include js2-node)
2448 (:constructor nil)
2449 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2450 (pos js2-ts-cursor)
2451 len
2452 expr)))
2453 "An expression statement."
2454 expr)
2455
2456 (defsubst js2-expr-stmt-node-set-has-result (node)
2457 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2458 (setf (js2-node-type node) js2-EXPR_RESULT))
2459
2460 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2461 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2462
2463 (defun js2-visit-expr-stmt-node (n v)
2464 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2465
2466 (defun js2-print-expr-stmt-node (n indent)
2467 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2468 (insert ";\n"))
2469
2470 (cl-defstruct (js2-loop-node
2471 (:include js2-scope)
2472 (:constructor nil))
2473 "Abstract supertype of loop nodes."
2474 body ; a `js2-block-node'
2475 lp ; position of left-paren, nil if omitted
2476 rp) ; position of right-paren, nil if omitted
2477
2478 (cl-defstruct (js2-do-node
2479 (:include js2-loop-node)
2480 (:constructor nil)
2481 (:constructor make-js2-do-node (&key (type js2-DO)
2482 (pos (js2-current-token-beg))
2483 len
2484 body
2485 condition
2486 while-pos
2487 lp
2488 rp)))
2489 "AST node for do-loop."
2490 condition ; while (expression)
2491 while-pos) ; buffer position of 'while' keyword
2492
2493 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2494 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2495
2496 (defun js2-visit-do-node (n v)
2497 (js2-visit-ast (js2-do-node-body n) v)
2498 (js2-visit-ast (js2-do-node-condition n) v))
2499
2500 (defun js2-print-do-node (n i)
2501 (let ((pad (js2-make-pad i)))
2502 (insert pad "do {\n")
2503 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2504 (js2-print-ast kid (1+ i)))
2505 (insert pad "} while (")
2506 (js2-print-ast (js2-do-node-condition n) 0)
2507 (insert ");\n")))
2508
2509 (cl-defstruct (js2-export-node
2510 (:include js2-node)
2511 (:constructor nil)
2512 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2513 (pos) (js2-current-token-beg)
2514 len
2515 exports-list
2516 from-clause
2517 declaration
2518 default)))
2519 "AST node for an export statement. There are many things that can be exported,
2520 so many of its properties will be nil.
2521 "
2522 exports-list ; lisp list of js2-export-binding-node to export
2523 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2524 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2525 default) ; js2-function-node or js2-assign-node
2526
2527 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2528 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2529
2530 (defun js2-visit-export-node (n v)
2531 (let ((exports-list (js2-export-node-exports-list n))
2532 (from (js2-export-node-from-clause n))
2533 (declaration (js2-export-node-declaration n))
2534 (default (js2-export-node-default n)))
2535 (when exports-list
2536 (dolist (export exports-list)
2537 (js2-visit-ast export v)))
2538 (when from
2539 (js2-visit-ast from v))
2540 (when declaration
2541 (js2-visit-ast declaration v))
2542 (when default
2543 (js2-visit-ast default v))))
2544
2545 (defun js2-print-export-node (n i)
2546 (let ((pad (js2-make-pad i))
2547 (exports-list (js2-export-node-exports-list n))
2548 (from (js2-export-node-from-clause n))
2549 (declaration (js2-export-node-declaration n))
2550 (default (js2-export-node-default n)))
2551 (insert pad "export ")
2552 (cond
2553 (default
2554 (insert "default ")
2555 (js2-print-ast default i))
2556 (declaration
2557 (js2-print-ast declaration i))
2558 ((and exports-list from)
2559 (js2-print-named-imports exports-list)
2560 (insert " ")
2561 (js2-print-from-clause from))
2562 (from
2563 (insert "* ")
2564 (js2-print-from-clause from))
2565 (exports-list
2566 (js2-print-named-imports exports-list)))
2567 (insert ";\n")))
2568
2569 (cl-defstruct (js2-while-node
2570 (:include js2-loop-node)
2571 (:constructor nil)
2572 (:constructor make-js2-while-node (&key (type js2-WHILE)
2573 (pos (js2-current-token-beg))
2574 len body
2575 condition lp
2576 rp)))
2577 "AST node for while-loop."
2578 condition) ; while-condition
2579
2580 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2581 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2582
2583 (defun js2-visit-while-node (n v)
2584 (js2-visit-ast (js2-while-node-condition n) v)
2585 (js2-visit-ast (js2-while-node-body n) v))
2586
2587 (defun js2-print-while-node (n i)
2588 (let ((pad (js2-make-pad i)))
2589 (insert pad "while (")
2590 (js2-print-ast (js2-while-node-condition n) 0)
2591 (insert ") {\n")
2592 (js2-print-body (js2-while-node-body n) (1+ i))
2593 (insert pad "}\n")))
2594
2595 (cl-defstruct (js2-for-node
2596 (:include js2-loop-node)
2597 (:constructor nil)
2598 (:constructor make-js2-for-node (&key (type js2-FOR)
2599 (pos js2-ts-cursor)
2600 len body init
2601 condition
2602 update lp rp)))
2603 "AST node for a C-style for-loop."
2604 init ; initialization expression
2605 condition ; loop condition
2606 update) ; update clause
2607
2608 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2609 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2610
2611 (defun js2-visit-for-node (n v)
2612 (js2-visit-ast (js2-for-node-init n) v)
2613 (js2-visit-ast (js2-for-node-condition n) v)
2614 (js2-visit-ast (js2-for-node-update n) v)
2615 (js2-visit-ast (js2-for-node-body n) v))
2616
2617 (defun js2-print-for-node (n i)
2618 (let ((pad (js2-make-pad i)))
2619 (insert pad "for (")
2620 (js2-print-ast (js2-for-node-init n) 0)
2621 (insert "; ")
2622 (js2-print-ast (js2-for-node-condition n) 0)
2623 (insert "; ")
2624 (js2-print-ast (js2-for-node-update n) 0)
2625 (insert ") {\n")
2626 (js2-print-body (js2-for-node-body n) (1+ i))
2627 (insert pad "}\n")))
2628
2629 (cl-defstruct (js2-for-in-node
2630 (:include js2-loop-node)
2631 (:constructor nil)
2632 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2633 (pos js2-ts-cursor)
2634 len body
2635 iterator
2636 object
2637 in-pos
2638 each-pos
2639 foreach-p forof-p
2640 lp rp)))
2641 "AST node for a for..in loop."
2642 iterator ; [var] foo in ...
2643 object ; object over which we're iterating
2644 in-pos ; buffer position of 'in' keyword
2645 each-pos ; buffer position of 'each' keyword, if foreach-p
2646 foreach-p ; t if it's a for-each loop
2647 forof-p) ; t if it's a for-of loop
2648
2649 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2650 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2651
2652 (defun js2-visit-for-in-node (n v)
2653 (js2-visit-ast (js2-for-in-node-iterator n) v)
2654 (js2-visit-ast (js2-for-in-node-object n) v)
2655 (js2-visit-ast (js2-for-in-node-body n) v))
2656
2657 (defun js2-print-for-in-node (n i)
2658 (let ((pad (js2-make-pad i))
2659 (foreach (js2-for-in-node-foreach-p n))
2660 (forof (js2-for-in-node-forof-p n)))
2661 (insert pad "for ")
2662 (if foreach
2663 (insert "each "))
2664 (insert "(")
2665 (js2-print-ast (js2-for-in-node-iterator n) 0)
2666 (insert (if forof " of " " in "))
2667 (js2-print-ast (js2-for-in-node-object n) 0)
2668 (insert ") {\n")
2669 (js2-print-body (js2-for-in-node-body n) (1+ i))
2670 (insert pad "}\n")))
2671
2672 (cl-defstruct (js2-return-node
2673 (:include js2-node)
2674 (:constructor nil)
2675 (:constructor make-js2-return-node (&key (type js2-RETURN)
2676 (pos js2-ts-cursor)
2677 len
2678 retval)))
2679 "AST node for a return statement."
2680 retval) ; expression to return, or 'undefined
2681
2682 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2683 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2684
2685 (defun js2-visit-return-node (n v)
2686 (js2-visit-ast (js2-return-node-retval n) v))
2687
2688 (defun js2-print-return-node (n i)
2689 (insert (js2-make-pad i) "return")
2690 (when (js2-return-node-retval n)
2691 (insert " ")
2692 (js2-print-ast (js2-return-node-retval n) 0))
2693 (insert ";\n"))
2694
2695 (cl-defstruct (js2-if-node
2696 (:include js2-node)
2697 (:constructor nil)
2698 (:constructor make-js2-if-node (&key (type js2-IF)
2699 (pos js2-ts-cursor)
2700 len condition
2701 then-part
2702 else-pos
2703 else-part lp
2704 rp)))
2705 "AST node for an if-statement."
2706 condition ; expression
2707 then-part ; statement or block
2708 else-pos ; optional buffer position of 'else' keyword
2709 else-part ; optional statement or block
2710 lp ; position of left-paren, nil if omitted
2711 rp) ; position of right-paren, nil if omitted
2712
2713 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2714 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2715
2716 (defun js2-visit-if-node (n v)
2717 (js2-visit-ast (js2-if-node-condition n) v)
2718 (js2-visit-ast (js2-if-node-then-part n) v)
2719 (js2-visit-ast (js2-if-node-else-part n) v))
2720
2721 (defun js2-print-if-node (n i)
2722 (let ((pad (js2-make-pad i))
2723 (then-part (js2-if-node-then-part n))
2724 (else-part (js2-if-node-else-part n)))
2725 (insert pad "if (")
2726 (js2-print-ast (js2-if-node-condition n) 0)
2727 (insert ") {\n")
2728 (js2-print-body then-part (1+ i))
2729 (insert pad "}")
2730 (cond
2731 ((not else-part)
2732 (insert "\n"))
2733 ((js2-if-node-p else-part)
2734 (insert " else ")
2735 (js2-print-body else-part i))
2736 (t
2737 (insert " else {\n")
2738 (js2-print-body else-part (1+ i))
2739 (insert pad "}\n")))))
2740
2741 (cl-defstruct (js2-export-binding-node
2742 (:include js2-node)
2743 (:constructor nil)
2744 (:constructor make-js2-export-binding-node (&key (type -1)
2745 pos
2746 len
2747 local-name
2748 extern-name)))
2749 "AST node for an external symbol binding.
2750 It contains a local-name node which is the name of the value in the
2751 current scope, and extern-name which is the name of the value in the
2752 imported or exported scope. By default these are the same, but if the
2753 name is aliased as in {foo as bar}, it would have an extern-name node
2754 containing 'foo' and a local-name node containing 'bar'."
2755 local-name ; js2-name-node with the variable name in this scope
2756 extern-name) ; js2-name-node with the value name in the exporting module
2757
2758 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2759 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2760
2761 (defun js2-visit-extern-binding (n v)
2762 "Visit an extern binding node. First visit the local-name, and, if
2763 different, visit the extern-name."
2764 (let ((local-name (js2-export-binding-node-local-name n))
2765 (extern-name (js2-export-binding-node-extern-name n)))
2766 (when local-name
2767 (js2-visit-ast local-name v))
2768 (when (not (equal local-name extern-name))
2769 (js2-visit-ast extern-name v))))
2770
2771 (defun js2-print-extern-binding (n i)
2772 "Print a representation of a single extern binding. E.g. 'foo' or
2773 'foo as bar'."
2774 (let ((local-name (js2-export-binding-node-local-name n))
2775 (extern-name (js2-export-binding-node-extern-name n)))
2776 (insert (js2-name-node-name extern-name))
2777 (when (not (equal local-name extern-name))
2778 (insert " as ")
2779 (insert (js2-name-node-name local-name)))))
2780
2781
2782 (cl-defstruct (js2-import-node
2783 (:include js2-node)
2784 (:constructor nil)
2785 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2786 (pos (js2-current-token-beg))
2787 len
2788 import
2789 from
2790 module-id)))
2791 "AST node for an import statement. It follows the form
2792
2793 import ModuleSpecifier;
2794 import ImportClause FromClause;"
2795 import ; js2-import-clause-node specifying which names are to imported.
2796 from ; js2-from-clause-node indicating the module from which to import.
2797 module-id) ; module-id of the import. E.g. 'src/mylib'.
2798
2799 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2800 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2801
2802 (defun js2-visit-import (n v)
2803 (let ((import-clause (js2-import-node-import n))
2804 (from-clause (js2-import-node-from n)))
2805 (when import-clause
2806 (js2-visit-ast import-clause v))
2807 (when from-clause
2808 (js2-visit-ast from-clause v))))
2809
2810 (defun js2-print-import (n i)
2811 "Prints a representation of the import node"
2812 (let ((pad (js2-make-pad i))
2813 (import-clause (js2-import-node-import n))
2814 (from-clause (js2-import-node-from n))
2815 (module-id (js2-import-node-module-id n)))
2816 (insert pad "import ")
2817 (if import-clause
2818 (progn
2819 (js2-print-import-clause import-clause)
2820 (insert " ")
2821 (js2-print-from-clause from-clause))
2822 (insert "'")
2823 (insert module-id)
2824 (insert "'"))
2825 (insert ";\n")))
2826
2827 (cl-defstruct (js2-import-clause-node
2828 (:include js2-node)
2829 (:constructor nil)
2830 (:constructor make-js2-import-clause-node (&key (type -1)
2831 pos
2832 len
2833 namespace-import
2834 named-imports
2835 default-binding)))
2836 "AST node corresponding to the import clause of an import statement. This is
2837 the portion of the import that bindings names from the external context to the
2838 local context."
2839 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2840 named-imports ; lisp list of js2-export-binding-node for all named imports.
2841 default-binding) ; js2-export-binding-node for the default import binding
2842
2843 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2844 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2845
2846 (defun js2-visit-import-clause (n v)
2847 (let ((ns-import (js2-import-clause-node-namespace-import n))
2848 (named-imports (js2-import-clause-node-named-imports n))
2849 (default (js2-import-clause-node-default-binding n)))
2850 (when ns-import
2851 (js2-visit-ast ns-import v))
2852 (when named-imports
2853 (dolist (import named-imports)
2854 (js2-visit-ast import v)))
2855 (when default
2856 (js2-visit-ast default v))))
2857
2858 (defun js2-print-import-clause (n)
2859 (let ((ns-import (js2-import-clause-node-namespace-import n))
2860 (named-imports (js2-import-clause-node-named-imports n))
2861 (default (js2-import-clause-node-default-binding n)))
2862 (cond
2863 ((and default ns-import)
2864 (js2-print-ast default)
2865 (insert ", ")
2866 (js2-print-namespace-import ns-import))
2867 ((and default named-imports)
2868 (js2-print-ast default)
2869 (insert ", ")
2870 (js2-print-named-imports named-imports))
2871 (default
2872 (js2-print-ast default))
2873 (ns-import
2874 (js2-print-namespace-import ns-import))
2875 (named-imports
2876 (js2-print-named-imports named-imports)))))
2877
2878 (defun js2-print-namespace-import (node)
2879 (insert "* as ")
2880 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2881
2882 (defun js2-print-named-imports (imports)
2883 (insert "{")
2884 (let ((len (length imports))
2885 (n 0))
2886 (while (< n len)
2887 (js2-print-extern-binding (nth n imports) 0)
2888 (unless (= n (- len 1))
2889 (insert ", "))
2890 (setq n (+ n 1))))
2891 (insert "}"))
2892
2893 (cl-defstruct (js2-namespace-import-node
2894 (:include js2-node)
2895 (:constructor nil)
2896 (:constructor make-js2-namespace-import-node (&key (type -1)
2897 pos
2898 len
2899 name)))
2900 "AST node for a complete namespace import.
2901 E.g. the '* as lib' expression in:
2902
2903 import * as lib from 'src/lib'
2904
2905 It contains a single name node referring to the bound name."
2906 name) ; js2-name-node of the bound name.
2907
2908 (defun js2-visit-namespace-import (n v)
2909 (js2-visit-ast (js2-namespace-import-node-name n) v))
2910
2911 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2912 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2913
2914 (cl-defstruct (js2-from-clause-node
2915 (:include js2-node)
2916 (:constructor nil)
2917 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2918 pos
2919 len
2920 module-id
2921 metadata-p)))
2922 "AST node for the from clause in an import or export statement.
2923 E.g. from 'my/module'. It can refere to either an external module, or to the
2924 modules metadata itself."
2925 module-id ; string containing the module specifier.
2926 metadata-p) ; true if this clause refers to the module's metadata
2927
2928 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2929 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2930
2931 (defun js2-print-from-clause (n)
2932 (insert "from ")
2933 (if (js2-from-clause-node-metadata-p n)
2934 (insert "this module")
2935 (insert "'")
2936 (insert (js2-from-clause-node-module-id n))
2937 (insert "'")))
2938
2939 (cl-defstruct (js2-try-node
2940 (:include js2-node)
2941 (:constructor nil)
2942 (:constructor make-js2-try-node (&key (type js2-TRY)
2943 (pos js2-ts-cursor)
2944 len
2945 try-block
2946 catch-clauses
2947 finally-block)))
2948 "AST node for a try-statement."
2949 try-block
2950 catch-clauses ; a Lisp list of `js2-catch-node'
2951 finally-block) ; a `js2-finally-node'
2952
2953 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2954 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2955
2956 (defun js2-visit-try-node (n v)
2957 (js2-visit-ast (js2-try-node-try-block n) v)
2958 (dolist (clause (js2-try-node-catch-clauses n))
2959 (js2-visit-ast clause v))
2960 (js2-visit-ast (js2-try-node-finally-block n) v))
2961
2962 (defun js2-print-try-node (n i)
2963 (let ((pad (js2-make-pad i))
2964 (catches (js2-try-node-catch-clauses n))
2965 (finally (js2-try-node-finally-block n)))
2966 (insert pad "try {\n")
2967 (js2-print-body (js2-try-node-try-block n) (1+ i))
2968 (insert pad "}")
2969 (when catches
2970 (dolist (catch catches)
2971 (js2-print-ast catch i)))
2972 (if finally
2973 (js2-print-ast finally i)
2974 (insert "\n"))))
2975
2976 (cl-defstruct (js2-catch-node
2977 (:include js2-scope)
2978 (:constructor nil)
2979 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2980 (pos js2-ts-cursor)
2981 len
2982 param
2983 guard-kwd
2984 guard-expr
2985 lp rp)))
2986 "AST node for a catch clause."
2987 param ; destructuring form or simple name node
2988 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2989 guard-expr ; catch condition, a `js2-node'
2990 lp ; buffer position of left-paren, nil if omitted
2991 rp) ; buffer position of right-paren, nil if omitted
2992
2993 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2994 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2995
2996 (defun js2-visit-catch-node (n v)
2997 (js2-visit-ast (js2-catch-node-param n) v)
2998 (when (js2-catch-node-guard-kwd n)
2999 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3000 (js2-visit-block n v))
3001
3002 (defun js2-print-catch-node (n i)
3003 (let ((pad (js2-make-pad i))
3004 (guard-kwd (js2-catch-node-guard-kwd n))
3005 (guard-expr (js2-catch-node-guard-expr n)))
3006 (insert " catch (")
3007 (js2-print-ast (js2-catch-node-param n) 0)
3008 (when guard-kwd
3009 (insert " if ")
3010 (js2-print-ast guard-expr 0))
3011 (insert ") {\n")
3012 (js2-print-body n (1+ i))
3013 (insert pad "}")))
3014
3015 (cl-defstruct (js2-finally-node
3016 (:include js2-node)
3017 (:constructor nil)
3018 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3019 (pos js2-ts-cursor)
3020 len body)))
3021 "AST node for a finally clause."
3022 body) ; a `js2-node', often but not always a block node
3023
3024 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3025 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3026
3027 (defun js2-visit-finally-node (n v)
3028 (js2-visit-ast (js2-finally-node-body n) v))
3029
3030 (defun js2-print-finally-node (n i)
3031 (let ((pad (js2-make-pad i)))
3032 (insert " finally {\n")
3033 (js2-print-body (js2-finally-node-body n) (1+ i))
3034 (insert pad "}\n")))
3035
3036 (cl-defstruct (js2-switch-node
3037 (:include js2-node)
3038 (:constructor nil)
3039 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3040 (pos js2-ts-cursor)
3041 len
3042 discriminant
3043 cases lp
3044 rp)))
3045 "AST node for a switch statement."
3046 discriminant ; a `js2-node' (switch expression)
3047 cases ; a Lisp list of `js2-case-node'
3048 lp ; position of open-paren for discriminant, nil if omitted
3049 rp) ; position of close-paren for discriminant, nil if omitted
3050
3051 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3052 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3053
3054 (defun js2-visit-switch-node (n v)
3055 (js2-visit-ast (js2-switch-node-discriminant n) v)
3056 (dolist (c (js2-switch-node-cases n))
3057 (js2-visit-ast c v)))
3058
3059 (defun js2-print-switch-node (n i)
3060 (let ((pad (js2-make-pad i))
3061 (cases (js2-switch-node-cases n)))
3062 (insert pad "switch (")
3063 (js2-print-ast (js2-switch-node-discriminant n) 0)
3064 (insert ") {\n")
3065 (dolist (case cases)
3066 (js2-print-ast case i))
3067 (insert pad "}\n")))
3068
3069 (cl-defstruct (js2-case-node
3070 (:include js2-block-node)
3071 (:constructor nil)
3072 (:constructor make-js2-case-node (&key (type js2-CASE)
3073 (pos js2-ts-cursor)
3074 len kids expr)))
3075 "AST node for a case clause of a switch statement."
3076 expr) ; the case expression (nil for default)
3077
3078 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3079 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3080
3081 (defun js2-visit-case-node (n v)
3082 (js2-visit-ast (js2-case-node-expr n) v)
3083 (js2-visit-block n v))
3084
3085 (defun js2-print-case-node (n i)
3086 (let ((pad (js2-make-pad i))
3087 (expr (js2-case-node-expr n)))
3088 (insert pad)
3089 (if (null expr)
3090 (insert "default:\n")
3091 (insert "case ")
3092 (js2-print-ast expr 0)
3093 (insert ":\n"))
3094 (dolist (kid (js2-case-node-kids n))
3095 (js2-print-ast kid (1+ i)))))
3096
3097 (cl-defstruct (js2-throw-node
3098 (:include js2-node)
3099 (:constructor nil)
3100 (:constructor make-js2-throw-node (&key (type js2-THROW)
3101 (pos js2-ts-cursor)
3102 len expr)))
3103 "AST node for a throw statement."
3104 expr) ; the expression to throw
3105
3106 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3107 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3108
3109 (defun js2-visit-throw-node (n v)
3110 (js2-visit-ast (js2-throw-node-expr n) v))
3111
3112 (defun js2-print-throw-node (n i)
3113 (insert (js2-make-pad i) "throw ")
3114 (js2-print-ast (js2-throw-node-expr n) 0)
3115 (insert ";\n"))
3116
3117 (cl-defstruct (js2-with-node
3118 (:include js2-node)
3119 (:constructor nil)
3120 (:constructor make-js2-with-node (&key (type js2-WITH)
3121 (pos js2-ts-cursor)
3122 len object
3123 body lp rp)))
3124 "AST node for a with-statement."
3125 object
3126 body
3127 lp ; buffer position of left-paren around object, nil if omitted
3128 rp) ; buffer position of right-paren around object, nil if omitted
3129
3130 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3131 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3132
3133 (defun js2-visit-with-node (n v)
3134 (js2-visit-ast (js2-with-node-object n) v)
3135 (js2-visit-ast (js2-with-node-body n) v))
3136
3137 (defun js2-print-with-node (n i)
3138 (let ((pad (js2-make-pad i)))
3139 (insert pad "with (")
3140 (js2-print-ast (js2-with-node-object n) 0)
3141 (insert ") {\n")
3142 (js2-print-body (js2-with-node-body n) (1+ i))
3143 (insert pad "}\n")))
3144
3145 (cl-defstruct (js2-label-node
3146 (:include js2-node)
3147 (:constructor nil)
3148 (:constructor make-js2-label-node (&key (type js2-LABEL)
3149 (pos js2-ts-cursor)
3150 len name)))
3151 "AST node for a statement label or case label."
3152 name ; a string
3153 loop) ; for validating and code-generating continue-to-label
3154
3155 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3156 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3157
3158 (defun js2-print-label (n i)
3159 (insert (js2-make-pad i)
3160 (js2-label-node-name n)
3161 ":\n"))
3162
3163 (cl-defstruct (js2-labeled-stmt-node
3164 (:include js2-node)
3165 (:constructor nil)
3166 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3167 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3168 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3169 (pos js2-ts-cursor)
3170 len labels stmt)))
3171 "AST node for a statement with one or more labels.
3172 Multiple labels for a statement are collapsed into the labels field."
3173 labels ; Lisp list of `js2-label-node'
3174 stmt) ; the statement these labels are for
3175
3176 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3177 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3178
3179 (defun js2-get-label-by-name (lbl-stmt name)
3180 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3181 Returns nil if no such label is in the list."
3182 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3183 result)
3184 (while (and label-list (not result))
3185 (if (string= (js2-label-node-name (car label-list)) name)
3186 (setq result (car label-list))
3187 (setq label-list (cdr label-list))))
3188 result))
3189
3190 (defun js2-visit-labeled-stmt (n v)
3191 (dolist (label (js2-labeled-stmt-node-labels n))
3192 (js2-visit-ast label v))
3193 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3194
3195 (defun js2-print-labeled-stmt (n i)
3196 (dolist (label (js2-labeled-stmt-node-labels n))
3197 (js2-print-ast label i))
3198 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3199
3200 (defun js2-labeled-stmt-node-contains (node label)
3201 "Return t if NODE contains LABEL in its label set.
3202 NODE is a `js2-labels-node'. LABEL is an identifier."
3203 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3204 if (string= label (js2-label-node-name nl))
3205 return t
3206 finally return nil))
3207
3208 (defsubst js2-labeled-stmt-node-add-label (node label)
3209 "Add a `js2-label-node' to the label set for this statement."
3210 (setf (js2-labeled-stmt-node-labels node)
3211 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3212
3213 (cl-defstruct (js2-jump-node
3214 (:include js2-node)
3215 (:constructor nil))
3216 "Abstract supertype of break and continue nodes."
3217 label ; `js2-name-node' for location of label identifier, if present
3218 target) ; target js2-labels-node or loop/switch statement
3219
3220 (defun js2-visit-jump-node (n v)
3221 ;; We don't visit the target, since it's a back-link.
3222 (js2-visit-ast (js2-jump-node-label n) v))
3223
3224 (cl-defstruct (js2-break-node
3225 (:include js2-jump-node)
3226 (:constructor nil)
3227 (:constructor make-js2-break-node (&key (type js2-BREAK)
3228 (pos js2-ts-cursor)
3229 len label target)))
3230 "AST node for a break statement.
3231 The label field is a `js2-name-node', possibly nil, for the named label
3232 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3233 is the target of the break - a label node or enclosing loop/switch statement.")
3234
3235 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3236 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3237
3238 (defun js2-print-break-node (n i)
3239 (insert (js2-make-pad i) "break")
3240 (when (js2-break-node-label n)
3241 (insert " ")
3242 (js2-print-ast (js2-break-node-label n) 0))
3243 (insert ";\n"))
3244
3245 (cl-defstruct (js2-continue-node
3246 (:include js2-jump-node)
3247 (:constructor nil)
3248 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3249 (pos js2-ts-cursor)
3250 len label target)))
3251 "AST node for a continue statement.
3252 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3253 It is nil if continue specifies no label. The target field is the jump target:
3254 a `js2-label-node' or the innermost enclosing loop.")
3255
3256 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3257 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3258
3259 (defun js2-print-continue-node (n i)
3260 (insert (js2-make-pad i) "continue")
3261 (when (js2-continue-node-label n)
3262 (insert " ")
3263 (js2-print-ast (js2-continue-node-label n) 0))
3264 (insert ";\n"))
3265
3266 (cl-defstruct (js2-function-node
3267 (:include js2-script-node)
3268 (:constructor nil)
3269 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3270 (pos js2-ts-cursor)
3271 len
3272 (ftype 'FUNCTION)
3273 (form 'FUNCTION_STATEMENT)
3274 (name "")
3275 params rest-p
3276 body
3277 generator-type
3278 lp rp)))
3279 "AST node for a function declaration.
3280 The `params' field is a Lisp list of nodes. Each node is either a simple
3281 `js2-name-node', or if it's a destructuring-assignment parameter, a
3282 `js2-array-node' or `js2-object-node'."
3283 ftype ; FUNCTION, GETTER or SETTER
3284 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3285 name ; function name (a `js2-name-node', or nil if anonymous)
3286 params ; a Lisp list of destructuring forms or simple name nodes
3287 rest-p ; if t, the last parameter is rest parameter
3288 body ; a `js2-block-node' or expression node (1.8 only)
3289 lp ; position of arg-list open-paren, or nil if omitted
3290 rp ; position of arg-list close-paren, or nil if omitted
3291 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3292 needs-activation ; t if we need an activation object for this frame
3293 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3294 member-expr) ; nonstandard Ecma extension from Rhino
3295
3296 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3297 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3298
3299 (defun js2-visit-function-node (n v)
3300 (js2-visit-ast (js2-function-node-name n) v)
3301 (dolist (p (js2-function-node-params n))
3302 (js2-visit-ast p v))
3303 (js2-visit-ast (js2-function-node-body n) v))
3304
3305 (defun js2-print-function-node (n i)
3306 (let* ((pad (js2-make-pad i))
3307 (getter (js2-node-get-prop n 'GETTER_SETTER))
3308 (name (or (js2-function-node-name n)
3309 (js2-function-node-member-expr n)))
3310 (params (js2-function-node-params n))
3311 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3312 (rest-p (js2-function-node-rest-p n))
3313 (body (js2-function-node-body n))
3314 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3315 (unless (or getter arrow)
3316 (insert pad "function")
3317 (when (eq (js2-function-node-generator-type n) 'STAR)
3318 (insert "*")))
3319 (when name
3320 (insert " ")
3321 (js2-print-ast name 0))
3322 (insert "(")
3323 (cl-loop with len = (length params)
3324 for param in params
3325 for count from 1
3326 do
3327 (when (and rest-p (= count len))
3328 (insert "..."))
3329 (js2-print-ast param 0)
3330 (when (< count len)
3331 (insert ", ")))
3332 (insert ") ")
3333 (when arrow
3334 (insert "=> "))
3335 (insert "{")
3336 ;; TODO: fix this to be smarter about indenting, etc.
3337 (unless expr
3338 (insert "\n"))
3339 (if (js2-block-node-p body)
3340 (js2-print-body body (1+ i))
3341 (js2-print-ast body 0))
3342 (insert pad "}")
3343 (unless expr
3344 (insert "\n"))))
3345
3346 (defun js2-function-name (node)
3347 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3348 (and (js2-function-node-name node)
3349 (js2-name-node-name (js2-function-node-name node))))
3350
3351 ;; Having this be an expression node makes it more flexible.
3352 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3353 ;; that work better if you assume it's an expression. Whenever we have
3354 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3355 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3356 (cl-defstruct (js2-var-decl-node
3357 (:include js2-node)
3358 (:constructor nil)
3359 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3360 (pos (js2-current-token-beg))
3361 len kids
3362 decl-type)))
3363 "AST node for a variable declaration list (VAR, CONST or LET).
3364 The node bounds differ depending on the declaration type. For VAR or
3365 CONST declarations, the bounds include the var/const keyword. For LET
3366 declarations, the node begins at the position of the first child."
3367 kids ; a Lisp list of `js2-var-init-node' structs.
3368 decl-type) ; js2-VAR, js2-CONST or js2-LET
3369
3370 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3371 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3372
3373 (defun js2-visit-var-decl (n v)
3374 (dolist (kid (js2-var-decl-node-kids n))
3375 (js2-visit-ast kid v)))
3376
3377 (defun js2-print-var-decl (n i)
3378 (let ((pad (js2-make-pad i))
3379 (tt (js2-var-decl-node-decl-type n)))
3380 (insert pad)
3381 (insert (cond
3382 ((= tt js2-VAR) "var ")
3383 ((= tt js2-LET) "let ")
3384 ((= tt js2-CONST) "const ")
3385 (t
3386 (error "malformed var-decl node"))))
3387 (cl-loop with kids = (js2-var-decl-node-kids n)
3388 with len = (length kids)
3389 for kid in kids
3390 for count from 1
3391 do
3392 (js2-print-ast kid 0)
3393 (if (< count len)
3394 (insert ", ")))))
3395
3396 (cl-defstruct (js2-var-init-node
3397 (:include js2-node)
3398 (:constructor nil)
3399 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3400 (pos js2-ts-cursor)
3401 len target
3402 initializer)))
3403 "AST node for a variable declaration.
3404 The type field will be js2-CONST for a const decl."
3405 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3406 initializer) ; initializer expression, a `js2-node'
3407
3408 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3409 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3410
3411 (defun js2-visit-var-init-node (n v)
3412 (js2-visit-ast (js2-var-init-node-target n) v)
3413 (js2-visit-ast (js2-var-init-node-initializer n) v))
3414
3415 (defun js2-print-var-init-node (n i)
3416 (let ((pad (js2-make-pad i))
3417 (name (js2-var-init-node-target n))
3418 (init (js2-var-init-node-initializer n)))
3419 (insert pad)
3420 (js2-print-ast name 0)
3421 (when init
3422 (insert " = ")
3423 (js2-print-ast init 0))))
3424
3425 (cl-defstruct (js2-cond-node
3426 (:include js2-node)
3427 (:constructor nil)
3428 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3429 (pos js2-ts-cursor)
3430 len
3431 test-expr
3432 true-expr
3433 false-expr
3434 q-pos c-pos)))
3435 "AST node for the ternary operator"
3436 test-expr
3437 true-expr
3438 false-expr
3439 q-pos ; buffer position of ?
3440 c-pos) ; buffer position of :
3441
3442 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3443 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3444
3445 (defun js2-visit-cond-node (n v)
3446 (js2-visit-ast (js2-cond-node-test-expr n) v)
3447 (js2-visit-ast (js2-cond-node-true-expr n) v)
3448 (js2-visit-ast (js2-cond-node-false-expr n) v))
3449
3450 (defun js2-print-cond-node (n i)
3451 (let ((pad (js2-make-pad i)))
3452 (insert pad)
3453 (js2-print-ast (js2-cond-node-test-expr n) 0)
3454 (insert " ? ")
3455 (js2-print-ast (js2-cond-node-true-expr n) 0)
3456 (insert " : ")
3457 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3458
3459 (cl-defstruct (js2-infix-node
3460 (:include js2-node)
3461 (:constructor nil)
3462 (:constructor make-js2-infix-node (&key type
3463 (pos js2-ts-cursor)
3464 len op-pos
3465 left right)))
3466 "Represents infix expressions.
3467 Includes assignment ops like `|=', and the comma operator.
3468 The type field inherited from `js2-node' holds the operator."
3469 op-pos ; buffer position where operator begins
3470 left ; any `js2-node'
3471 right) ; any `js2-node'
3472
3473 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3474 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3475
3476 (defun js2-visit-infix-node (n v)
3477 (js2-visit-ast (js2-infix-node-left n) v)
3478 (js2-visit-ast (js2-infix-node-right n) v))
3479
3480 (defconst js2-operator-tokens
3481 (let ((table (make-hash-table :test 'eq))
3482 (tokens
3483 (list (cons js2-IN "in")
3484 (cons js2-TYPEOF "typeof")
3485 (cons js2-INSTANCEOF "instanceof")
3486 (cons js2-DELPROP "delete")
3487 (cons js2-COMMA ",")
3488 (cons js2-COLON ":")
3489 (cons js2-OR "||")
3490 (cons js2-AND "&&")
3491 (cons js2-INC "++")
3492 (cons js2-DEC "--")
3493 (cons js2-BITOR "|")
3494 (cons js2-BITXOR "^")
3495 (cons js2-BITAND "&")
3496 (cons js2-EQ "==")
3497 (cons js2-NE "!=")
3498 (cons js2-LT "<")
3499 (cons js2-LE "<=")
3500 (cons js2-GT ">")
3501 (cons js2-GE ">=")
3502 (cons js2-LSH "<<")
3503 (cons js2-RSH ">>")
3504 (cons js2-URSH ">>>")
3505 (cons js2-ADD "+") ; infix plus
3506 (cons js2-SUB "-") ; infix minus
3507 (cons js2-MUL "*")
3508 (cons js2-DIV "/")
3509 (cons js2-MOD "%")
3510 (cons js2-NOT "!")
3511 (cons js2-BITNOT "~")
3512 (cons js2-POS "+") ; unary plus
3513 (cons js2-NEG "-") ; unary minus
3514 (cons js2-TRIPLEDOT "...")
3515 (cons js2-SHEQ "===") ; shallow equality
3516 (cons js2-SHNE "!==") ; shallow inequality
3517 (cons js2-ASSIGN "=")
3518 (cons js2-ASSIGN_BITOR "|=")
3519 (cons js2-ASSIGN_BITXOR "^=")
3520 (cons js2-ASSIGN_BITAND "&=")
3521 (cons js2-ASSIGN_LSH "<<=")
3522 (cons js2-ASSIGN_RSH ">>=")
3523 (cons js2-ASSIGN_URSH ">>>=")
3524 (cons js2-ASSIGN_ADD "+=")
3525 (cons js2-ASSIGN_SUB "-=")
3526 (cons js2-ASSIGN_MUL "*=")
3527 (cons js2-ASSIGN_DIV "/=")
3528 (cons js2-ASSIGN_MOD "%="))))
3529 (cl-loop for (k . v) in tokens do
3530 (puthash k v table))
3531 table))
3532
3533 (defun js2-print-infix-node (n i)
3534 (let* ((tt (js2-node-type n))
3535 (op (gethash tt js2-operator-tokens)))
3536 (unless op
3537 (error "unrecognized infix operator %s" (js2-node-type n)))
3538 (insert (js2-make-pad i))
3539 (js2-print-ast (js2-infix-node-left n) 0)
3540 (unless (= tt js2-COMMA)
3541 (insert " "))
3542 (insert op)
3543 (insert " ")
3544 (js2-print-ast (js2-infix-node-right n) 0)))
3545
3546 (cl-defstruct (js2-assign-node
3547 (:include js2-infix-node)
3548 (:constructor nil)
3549 (:constructor make-js2-assign-node (&key type
3550 (pos js2-ts-cursor)
3551 len op-pos
3552 left right)))
3553 "Represents any assignment.
3554 The type field holds the actual assignment operator.")
3555
3556 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3557 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3558
3559 (cl-defstruct (js2-unary-node
3560 (:include js2-node)
3561 (:constructor nil)
3562 (:constructor make-js2-unary-node (&key type ; required
3563 (pos js2-ts-cursor)
3564 len operand)))
3565 "AST node type for unary operator nodes.
3566 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3567 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3568 property is added if the operator follows the operand."
3569 operand) ; a `js2-node' expression
3570
3571 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3572 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3573
3574 (defun js2-visit-unary-node (n v)
3575 (js2-visit-ast (js2-unary-node-operand n) v))
3576
3577 (defun js2-print-unary-node (n i)
3578 (let* ((tt (js2-node-type n))
3579 (op (gethash tt js2-operator-tokens))
3580 (postfix (js2-node-get-prop n 'postfix)))
3581 (unless op
3582 (error "unrecognized unary operator %s" tt))
3583 (insert (js2-make-pad i))
3584 (unless postfix
3585 (insert op))
3586 (if (or (= tt js2-TYPEOF)
3587 (= tt js2-DELPROP))
3588 (insert " "))
3589 (js2-print-ast (js2-unary-node-operand n) 0)
3590 (when postfix
3591 (insert op))))
3592
3593 (cl-defstruct (js2-let-node
3594 (:include js2-scope)
3595 (:constructor nil)
3596 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3597 (pos (js2-current-token-beg))
3598 len vars body
3599 lp rp)))
3600 "AST node for a let expression or a let statement.
3601 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3602 vars ; a `js2-var-decl-node'
3603 body ; a `js2-node' representing the expression or body block
3604 lp
3605 rp)
3606
3607 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3608 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3609
3610 (defun js2-visit-let-node (n v)
3611 (js2-visit-ast (js2-let-node-vars n) v)
3612 (js2-visit-ast (js2-let-node-body n) v))
3613
3614 (defun js2-print-let-node (n i)
3615 (insert (js2-make-pad i) "let (")
3616 (let ((p (point)))
3617 (js2-print-ast (js2-let-node-vars n) 0)
3618 (delete-region p (+ p 4)))
3619 (insert ") ")
3620 (js2-print-ast (js2-let-node-body n) i))
3621
3622 (cl-defstruct (js2-keyword-node
3623 (:include js2-node)
3624 (:constructor nil)
3625 (:constructor make-js2-keyword-node (&key type
3626 (pos (js2-current-token-beg))
3627 (len (- js2-ts-cursor pos)))))
3628 "AST node representing a literal keyword such as `null'.
3629 Used for `null', `this', `true', `false' and `debugger'.
3630 The node type is set to js2-NULL, js2-THIS, etc.")
3631
3632 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3633 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3634
3635 (defun js2-print-keyword-node (n i)
3636 (insert (js2-make-pad i)
3637 (let ((tt (js2-node-type n)))
3638 (cond
3639 ((= tt js2-THIS) "this")
3640 ((= tt js2-SUPER) "super")
3641 ((= tt js2-NULL) "null")
3642 ((= tt js2-TRUE) "true")
3643 ((= tt js2-FALSE) "false")
3644 ((= tt js2-DEBUGGER) "debugger")
3645 (t (error "Invalid keyword literal type: %d" tt))))))
3646
3647 (defsubst js2-this-or-super-node-p (node)
3648 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3649 (let ((type (js2-node-type node)))
3650 (or (eq type js2-THIS) (eq type js2-SUPER))))
3651
3652 (cl-defstruct (js2-new-node
3653 (:include js2-node)
3654 (:constructor nil)
3655 (:constructor make-js2-new-node (&key (type js2-NEW)
3656 (pos (js2-current-token-beg))
3657 len target
3658 args initializer
3659 lp rp)))
3660 "AST node for new-expression such as new Foo()."
3661 target ; an identifier or reference
3662 args ; a Lisp list of argument nodes
3663 lp ; position of left-paren, nil if omitted
3664 rp ; position of right-paren, nil if omitted
3665 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3666
3667 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3668 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3669
3670 (defun js2-visit-new-node (n v)
3671 (js2-visit-ast (js2-new-node-target n) v)
3672 (dolist (arg (js2-new-node-args n))
3673 (js2-visit-ast arg v))
3674 (js2-visit-ast (js2-new-node-initializer n) v))
3675
3676 (defun js2-print-new-node (n i)
3677 (insert (js2-make-pad i) "new ")
3678 (js2-print-ast (js2-new-node-target n))
3679 (insert "(")
3680 (js2-print-list (js2-new-node-args n))
3681 (insert ")")
3682 (when (js2-new-node-initializer n)
3683 (insert " ")
3684 (js2-print-ast (js2-new-node-initializer n))))
3685
3686 (cl-defstruct (js2-name-node
3687 (:include js2-node)
3688 (:constructor nil)
3689 (:constructor make-js2-name-node (&key (type js2-NAME)
3690 (pos (js2-current-token-beg))
3691 (len (- js2-ts-cursor
3692 (js2-current-token-beg)))
3693 (name (js2-current-token-string)))))
3694 "AST node for a JavaScript identifier"
3695 name ; a string
3696 scope) ; a `js2-scope' (optional, used for codegen)
3697
3698 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3699 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3700
3701 (defun js2-print-name-node (n i)
3702 (insert (js2-make-pad i)
3703 (js2-name-node-name n)))
3704
3705 (defsubst js2-name-node-length (node)
3706 "Return identifier length of NODE, a `js2-name-node'.
3707 Returns 0 if NODE is nil or its identifier field is nil."
3708 (if node
3709 (length (js2-name-node-name node))
3710 0))
3711
3712 (cl-defstruct (js2-number-node
3713 (:include js2-node)
3714 (:constructor nil)
3715 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3716 (pos (js2-current-token-beg))
3717 (len (- js2-ts-cursor
3718 (js2-current-token-beg)))
3719 (value (js2-current-token-string))
3720 (num-value (js2-token-number
3721 (js2-current-token))))))
3722 "AST node for a number literal."
3723 value ; the original string, e.g. "6.02e23"
3724 num-value) ; the parsed number value
3725
3726 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3727 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3728
3729 (defun js2-print-number-node (n i)
3730 (insert (js2-make-pad i)
3731 (number-to-string (js2-number-node-num-value n))))
3732
3733 (cl-defstruct (js2-regexp-node
3734 (:include js2-node)
3735 (:constructor nil)
3736 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3737 (pos (js2-current-token-beg))
3738 (len (- js2-ts-cursor
3739 (js2-current-token-beg)))
3740 value flags)))
3741 "AST node for a regular expression literal."
3742 value ; the regexp string, without // delimiters
3743 flags) ; a string of flags, e.g. `mi'.
3744
3745 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3746 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3747
3748 (defun js2-print-regexp (n i)
3749 (insert (js2-make-pad i)
3750 "/"
3751 (js2-regexp-node-value n)
3752 "/")
3753 (if (js2-regexp-node-flags n)
3754 (insert (js2-regexp-node-flags n))))
3755
3756 (cl-defstruct (js2-string-node
3757 (:include js2-node)
3758 (:constructor nil)
3759 (:constructor make-js2-string-node (&key (type js2-STRING)
3760 (pos (js2-current-token-beg))
3761 (len (- js2-ts-cursor
3762 (js2-current-token-beg)))
3763 (value (js2-current-token-string)))))
3764 "String literal.
3765 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3766 You can tell the quote type by looking at the first character."
3767 value) ; the characters of the string, including the quotes
3768
3769 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3770 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3771
3772 (defun js2-print-string-node (n i)
3773 (insert (js2-make-pad i)
3774 (js2-node-string n)))
3775
3776 (cl-defstruct (js2-template-node
3777 (:include js2-node)
3778 (:constructor nil)
3779 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3780 beg len kids)))
3781 "Template literal."
3782 kids) ; `js2-string-node' is used for string segments, other nodes
3783 ; for substitutions inside.
3784
3785 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3786 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3787
3788 (defun js2-visit-template (n callback)
3789 (dolist (kid (js2-template-node-kids n))
3790 (js2-visit-ast kid callback)))
3791
3792 (defun js2-print-template (n i)
3793 (insert (js2-make-pad i))
3794 (dolist (kid (js2-template-node-kids n))
3795 (if (js2-string-node-p kid)
3796 (insert (js2-node-string kid))
3797 (js2-print-ast kid))))
3798
3799 (cl-defstruct (js2-tagged-template-node
3800 (:include js2-node)
3801 (:constructor nil)
3802 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3803 beg len tag template)))
3804 "Tagged template literal."
3805 tag ; `js2-node' with the tag expression.
3806 template) ; `js2-template-node' with the template.
3807
3808 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3809 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3810
3811 (defun js2-visit-tagged-template (n callback)
3812 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3813 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3814
3815 (defun js2-print-tagged-template (n i)
3816 (insert (js2-make-pad i))
3817 (js2-print-ast (js2-tagged-template-node-tag n))
3818 (js2-print-ast (js2-tagged-template-node-template n)))
3819
3820 (cl-defstruct (js2-array-node
3821 (:include js2-node)
3822 (:constructor nil)
3823 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3824 (pos js2-ts-cursor)
3825 len elems)))
3826 "AST node for an array literal."
3827 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3828
3829 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3830 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3831
3832 (defun js2-visit-array-node (n v)
3833 (dolist (e (js2-array-node-elems n))
3834 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3835
3836 (defun js2-print-array-node (n i)
3837 (insert (js2-make-pad i) "[")
3838 (let ((elems (js2-array-node-elems n)))
3839 (js2-print-list elems)
3840 (when (and elems (null (car (last elems))))
3841 (insert ",")))
3842 (insert "]"))
3843
3844 (cl-defstruct (js2-class-node
3845 (:include js2-node)
3846 (:constructor nil)
3847 (:constructor make-js2-class-node (&key (type js2-CLASS)
3848 (pos js2-ts-cursor)
3849 (form 'CLASS_STATEMENT)
3850 (name "")
3851 extends len elems)))
3852 "AST node for an class expression.
3853 `elems' is a list of `js2-object-prop-node', and `extends' is an
3854 optional `js2-expr-node'"
3855 form ; CLASS_{STATEMENT|EXPRESSION}
3856 name ; class name (a `js2-node-name', or nil if anonymous)
3857 extends ; class heritage (a `js2-expr-node', or nil if none)
3858 elems)
3859
3860 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3861 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3862
3863 (defun js2-visit-class-node (n v)
3864 (js2-visit-ast (js2-class-node-name n) v)
3865 (js2-visit-ast (js2-class-node-extends n) v)
3866 (dolist (e (js2-class-node-elems n))
3867 (js2-visit-ast e v)))
3868
3869 (defun js2-print-class-node (n i)
3870 (let* ((pad (js2-make-pad i))
3871 (name (js2-class-node-name n))
3872 (extends (js2-class-node-extends n))
3873 (elems (js2-class-node-elems n)))
3874 (insert pad "class")
3875 (when name
3876 (insert " ")
3877 (js2-print-ast name 0))
3878 (when extends
3879 (insert " extends ")
3880 (js2-print-ast extends))
3881 (insert " {")
3882 (dolist (elem elems)
3883 (insert "\n")
3884 (if (js2-node-get-prop elem 'STATIC)
3885 (progn (insert (js2-make-pad (1+ i)) "static ")
3886 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3887 (js2-print-ast elem (1+ i))))
3888 (insert "\n" pad "}")))
3889
3890 (cl-defstruct (js2-object-node
3891 (:include js2-node)
3892 (:constructor nil)
3893 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3894 (pos js2-ts-cursor)
3895 len
3896 elems)))
3897 "AST node for an object literal expression.
3898 `elems' is a list of `js2-object-prop-node'."
3899 elems)
3900
3901 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3902 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3903
3904 (defun js2-visit-object-node (n v)
3905 (dolist (e (js2-object-node-elems n))
3906 (js2-visit-ast e v)))
3907
3908 (defun js2-print-object-node (n i)
3909 (insert (js2-make-pad i) "{")
3910 (js2-print-list (js2-object-node-elems n))
3911 (insert "}"))
3912
3913 (cl-defstruct (js2-object-prop-node
3914 (:include js2-infix-node)
3915 (:constructor nil)
3916 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3917 (pos js2-ts-cursor)
3918 len left
3919 right op-pos)))
3920 "AST node for an object literal prop:value entry.
3921 The `left' field is the property: a name node, string node or number node.
3922 The `right' field is a `js2-node' representing the initializer value.
3923 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3924 and both fields have the same value.")
3925
3926 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3927 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3928
3929 (defun js2-print-object-prop-node (n i)
3930 (let* ((left (js2-object-prop-node-left n))
3931 (computed (not (or (js2-string-node-p left)
3932 (js2-number-node-p left)
3933 (js2-name-node-p left)))))
3934 (insert (js2-make-pad i))
3935 (if computed
3936 (insert "["))
3937 (js2-print-ast left 0)
3938 (if computed
3939 (insert "]"))
3940 (if (not (js2-node-get-prop n 'SHORTHAND))
3941 (progn
3942 (insert ": ")
3943 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3944
3945 (cl-defstruct (js2-getter-setter-node
3946 (:include js2-infix-node)
3947 (:constructor nil)
3948 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3949 (pos js2-ts-cursor)
3950 len left right)))
3951 "AST node for a getter/setter property in an object literal.
3952 The `left' field is the `js2-name-node' naming the getter/setter prop.
3953 The `right' field is always an anonymous `js2-function-node' with a node
3954 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3955
3956 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3957 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3958
3959 (defun js2-print-getter-setter (n i)
3960 (let ((pad (js2-make-pad i))
3961 (left (js2-getter-setter-node-left n))
3962 (right (js2-getter-setter-node-right n)))
3963 (insert pad)
3964 (if (/= (js2-node-type n) js2-FUNCTION)
3965 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3966 (js2-print-ast left 0)
3967 (js2-print-ast right 0)))
3968
3969 (cl-defstruct (js2-prop-get-node
3970 (:include js2-infix-node)
3971 (:constructor nil)
3972 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3973 (pos js2-ts-cursor)
3974 len left right)))
3975 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3976
3977 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3978 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3979
3980 (defun js2-visit-prop-get-node (n v)
3981 (js2-visit-ast (js2-prop-get-node-left n) v)
3982 (js2-visit-ast (js2-prop-get-node-right n) v))
3983
3984 (defun js2-print-prop-get-node (n i)
3985 (insert (js2-make-pad i))
3986 (js2-print-ast (js2-prop-get-node-left n) 0)
3987 (insert ".")
3988 (js2-print-ast (js2-prop-get-node-right n) 0))
3989
3990 (cl-defstruct (js2-elem-get-node
3991 (:include js2-node)
3992 (:constructor nil)
3993 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3994 (pos js2-ts-cursor)
3995 len target element
3996 lb rb)))
3997 "AST node for an array index expression such as foo[bar]."
3998 target ; a `js2-node' - the expression preceding the "."
3999 element ; a `js2-node' - the expression in brackets
4000 lb ; position of left-bracket, nil if omitted
4001 rb) ; position of right-bracket, nil if omitted
4002
4003 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4004 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4005
4006 (defun js2-visit-elem-get-node (n v)
4007 (js2-visit-ast (js2-elem-get-node-target n) v)
4008 (js2-visit-ast (js2-elem-get-node-element n) v))
4009
4010 (defun js2-print-elem-get-node (n i)
4011 (insert (js2-make-pad i))
4012 (js2-print-ast (js2-elem-get-node-target n) 0)
4013 (insert "[")
4014 (js2-print-ast (js2-elem-get-node-element n) 0)
4015 (insert "]"))
4016
4017 (cl-defstruct (js2-call-node
4018 (:include js2-node)
4019 (:constructor nil)
4020 (:constructor make-js2-call-node (&key (type js2-CALL)
4021 (pos js2-ts-cursor)
4022 len target args
4023 lp rp)))
4024 "AST node for a JavaScript function call."
4025 target ; a `js2-node' evaluating to the function to call
4026 args ; a Lisp list of `js2-node' arguments
4027 lp ; position of open-paren, or nil if missing
4028 rp) ; position of close-paren, or nil if missing
4029
4030 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4031 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4032
4033 (defun js2-visit-call-node (n v)
4034 (js2-visit-ast (js2-call-node-target n) v)
4035 (dolist (arg (js2-call-node-args n))
4036 (js2-visit-ast arg v)))
4037
4038 (defun js2-print-call-node (n i)
4039 (insert (js2-make-pad i))
4040 (js2-print-ast (js2-call-node-target n) 0)
4041 (insert "(")
4042 (js2-print-list (js2-call-node-args n))
4043 (insert ")"))
4044
4045 (cl-defstruct (js2-yield-node
4046 (:include js2-node)
4047 (:constructor nil)
4048 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4049 (pos js2-ts-cursor)
4050 len value star-p)))
4051 "AST node for yield statement or expression."
4052 star-p ; whether it's yield*
4053 value) ; optional: value to be yielded
4054
4055 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4056 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4057
4058 (defun js2-visit-yield-node (n v)
4059 (js2-visit-ast (js2-yield-node-value n) v))
4060
4061 (defun js2-print-yield-node (n i)
4062 (insert (js2-make-pad i))
4063 (insert "yield")
4064 (when (js2-yield-node-star-p n)
4065 (insert "*"))
4066 (when (js2-yield-node-value n)
4067 (insert " ")
4068 (js2-print-ast (js2-yield-node-value n) 0)))
4069
4070 (cl-defstruct (js2-paren-node
4071 (:include js2-node)
4072 (:constructor nil)
4073 (:constructor make-js2-paren-node (&key (type js2-LP)
4074 (pos js2-ts-cursor)
4075 len expr)))
4076 "AST node for a parenthesized expression.
4077 In particular, used when the parens are syntactically optional,
4078 as opposed to required parens such as those enclosing an if-conditional."
4079 expr) ; `js2-node'
4080
4081 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4082 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4083
4084 (defun js2-visit-paren-node (n v)
4085 (js2-visit-ast (js2-paren-node-expr n) v))
4086
4087 (defun js2-print-paren-node (n i)
4088 (insert (js2-make-pad i))
4089 (insert "(")
4090 (js2-print-ast (js2-paren-node-expr n) 0)
4091 (insert ")"))
4092
4093 (cl-defstruct (js2-comp-node
4094 (:include js2-scope)
4095 (:constructor nil)
4096 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4097 (pos js2-ts-cursor)
4098 len result
4099 loops filters
4100 form)))
4101 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4102 result ; result expression (just after left-bracket)
4103 loops ; a Lisp list of `js2-comp-loop-node'
4104 filters ; a Lisp list of guard/filter expressions
4105 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4106 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4107 )
4108
4109 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4110 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4111
4112 (defun js2-visit-comp-node (n v)
4113 (js2-visit-ast (js2-comp-node-result n) v)
4114 (dolist (l (js2-comp-node-loops n))
4115 (js2-visit-ast l v))
4116 (dolist (f (js2-comp-node-filters n))
4117 (js2-visit-ast f v)))
4118
4119 (defun js2-print-comp-node (n i)
4120 (let ((pad (js2-make-pad i))
4121 (result (js2-comp-node-result n))
4122 (loops (js2-comp-node-loops n))
4123 (filters (js2-comp-node-filters n))
4124 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4125 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4126 (insert pad (if gen-p "(" "["))
4127 (when legacy-p
4128 (js2-print-ast result 0))
4129 (dolist (l loops)
4130 (when legacy-p
4131 (insert " "))
4132 (js2-print-ast l 0)
4133 (unless legacy-p
4134 (insert " ")))
4135 (dolist (f filters)
4136 (when legacy-p
4137 (insert " "))
4138 (insert "if (")
4139 (js2-print-ast f 0)
4140 (insert ")")
4141 (unless legacy-p
4142 (insert " ")))
4143 (unless legacy-p
4144 (js2-print-ast result 0))
4145 (insert (if gen-p ")" "]"))))
4146
4147 (cl-defstruct (js2-comp-loop-node
4148 (:include js2-for-in-node)
4149 (:constructor nil)
4150 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4151 (pos js2-ts-cursor)
4152 len iterator
4153 object in-pos
4154 foreach-p
4155 each-pos
4156 forof-p
4157 lp rp)))
4158 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4159
4160 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4161 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4162
4163 (defun js2-visit-comp-loop (n v)
4164 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4165 (js2-visit-ast (js2-comp-loop-node-object n) v))
4166
4167 (defun js2-print-comp-loop (n _i)
4168 (insert "for ")
4169 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4170 (insert "(")
4171 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4172 (insert (if (js2-comp-loop-node-forof-p n)
4173 " of " " in "))
4174 (js2-print-ast (js2-comp-loop-node-object n) 0)
4175 (insert ")"))
4176
4177 (cl-defstruct (js2-empty-expr-node
4178 (:include js2-node)
4179 (:constructor nil)
4180 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4181 (pos (js2-current-token-beg))
4182 len)))
4183 "AST node for an empty expression.")
4184
4185 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4186 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4187
4188 (cl-defstruct (js2-xml-node
4189 (:include js2-block-node)
4190 (:constructor nil)
4191 (:constructor make-js2-xml-node (&key (type js2-XML)
4192 (pos (js2-current-token-beg))
4193 len kids)))
4194 "AST node for initial parse of E4X literals.
4195 The kids field is a list of XML fragments, each a `js2-string-node' or
4196 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4197
4198 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4199 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4200
4201 (defun js2-print-xml-node (n i)
4202 (dolist (kid (js2-xml-node-kids n))
4203 (js2-print-ast kid i)))
4204
4205 (cl-defstruct (js2-xml-js-expr-node
4206 (:include js2-xml-node)
4207 (:constructor nil)
4208 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4209 (pos js2-ts-cursor)
4210 len expr)))
4211 "AST node for an embedded JavaScript {expression} in an E4X literal.
4212 The start and end fields correspond to the curly-braces."
4213 expr) ; a `js2-expr-node' of some sort
4214
4215 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4216 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4217
4218 (defun js2-visit-xml-js-expr (n v)
4219 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4220
4221 (defun js2-print-xml-js-expr (n i)
4222 (insert (js2-make-pad i))
4223 (insert "{")
4224 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4225 (insert "}"))
4226
4227 (cl-defstruct (js2-xml-dot-query-node
4228 (:include js2-infix-node)
4229 (:constructor nil)
4230 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4231 (pos js2-ts-cursor)
4232 op-pos len left
4233 right rp)))
4234 "AST node for an E4X foo.(bar) filter expression.
4235 Note that the left-paren is automatically the character immediately
4236 following the dot (.) in the operator. No whitespace is permitted
4237 between the dot and the lp by the scanner."
4238 rp)
4239
4240 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4241 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4242
4243 (defun js2-print-xml-dot-query (n i)
4244 (insert (js2-make-pad i))
4245 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4246 (insert ".(")
4247 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4248 (insert ")"))
4249
4250 (cl-defstruct (js2-xml-ref-node
4251 (:include js2-node)
4252 (:constructor nil)) ; abstract
4253 "Base type for E4X XML attribute-access or property-get expressions.
4254 Such expressions can take a variety of forms. The general syntax has
4255 three parts:
4256
4257 - (optional) an @ (specifying an attribute access)
4258 - (optional) a namespace (a `js2-name-node') and double-colon
4259 - (required) either a `js2-name-node' or a bracketed [expression]
4260
4261 The property-name expressions (examples: ns::name, @name) are
4262 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4263 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4264
4265 This node type (or more specifically, its subclasses) will sometimes
4266 be the right-hand child of a `js2-prop-get-node' or a
4267 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4268 The `js2-xml-ref-node' may also be a standalone primary expression with
4269 no explicit target, which is valid in certain expression contexts such as
4270
4271 company..employee.(@id < 100)
4272
4273 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4274 expression whose parent is a `js2-xml-dot-query-node'."
4275 namespace
4276 at-pos
4277 colon-pos)
4278
4279 (defsubst js2-xml-ref-node-attr-access-p (node)
4280 "Return non-nil if this expression began with an @-token."
4281 (and (numberp (js2-xml-ref-node-at-pos node))
4282 (cl-plusp (js2-xml-ref-node-at-pos node))))
4283
4284 (cl-defstruct (js2-xml-prop-ref-node
4285 (:include js2-xml-ref-node)
4286 (:constructor nil)
4287 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4288 (pos (js2-current-token-beg))
4289 len propname
4290 namespace at-pos
4291 colon-pos)))
4292 "AST node for an E4X XML [expr] property-ref expression.
4293 The JavaScript syntax is an optional @, an optional ns::, and a name.
4294
4295 [ '@' ] [ name '::' ] name
4296
4297 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4298 @ns::*, @*::attr, @*::*, and @*.
4299
4300 The node starts at the @ token, if present. Otherwise it starts at the
4301 namespace name. The node bounds extend through the closing right-bracket,
4302 or if it is missing due to a syntax error, through the end of the index
4303 expression."
4304 propname)
4305
4306 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4307 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4308
4309 (defun js2-visit-xml-prop-ref-node (n v)
4310 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4311 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4312
4313 (defun js2-print-xml-prop-ref-node (n i)
4314 (insert (js2-make-pad i))
4315 (if (js2-xml-ref-node-attr-access-p n)
4316 (insert "@"))
4317 (when (js2-xml-prop-ref-node-namespace n)
4318 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4319 (insert "::"))
4320 (if (js2-xml-prop-ref-node-propname n)
4321 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4322
4323 (cl-defstruct (js2-xml-elem-ref-node
4324 (:include js2-xml-ref-node)
4325 (:constructor nil)
4326 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4327 (pos (js2-current-token-beg))
4328 len expr lb rb
4329 namespace at-pos
4330 colon-pos)))
4331 "AST node for an E4X XML [expr] member-ref expression.
4332 Syntax:
4333
4334 [ '@' ] [ name '::' ] '[' expr ']'
4335
4336 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4337
4338 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4339 is not a legal E4X XML element-ref expression, since it's already used
4340 for standard JavaScript element-get array indexing. Hence, a
4341 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4342 non-nil namespace node, or both.
4343
4344 The node starts at the @ token, if present. Otherwise it starts
4345 at the namespace name. The node bounds extend through the closing
4346 right-bracket, or if it is missing due to a syntax error, through the
4347 end of the index expression."
4348 expr ; the bracketed index expression
4349 lb
4350 rb)
4351
4352 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4353 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4354
4355 (defun js2-visit-xml-elem-ref-node (n v)
4356 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4357 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4358
4359 (defun js2-print-xml-elem-ref-node (n i)
4360 (insert (js2-make-pad i))
4361 (if (js2-xml-ref-node-attr-access-p n)
4362 (insert "@"))
4363 (when (js2-xml-elem-ref-node-namespace n)
4364 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4365 (insert "::"))
4366 (insert "[")
4367 (if (js2-xml-elem-ref-node-expr n)
4368 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4369 (insert "]"))
4370
4371 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4372
4373 (cl-defstruct (js2-xml-start-tag-node
4374 (:include js2-xml-node)
4375 (:constructor nil)
4376 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4377 (pos js2-ts-cursor)
4378 len name attrs kids
4379 empty-p)))
4380 "AST node for an XML start-tag. Not currently used.
4381 The `kids' field is a Lisp list of child content nodes."
4382 name ; a `js2-xml-name-node'
4383 attrs ; a Lisp list of `js2-xml-attr-node'
4384 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4385
4386 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4387 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4388
4389 (defun js2-visit-xml-start-tag (n v)
4390 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4391 (dolist (attr (js2-xml-start-tag-node-attrs n))
4392 (js2-visit-ast attr v))
4393 (js2-visit-block n v))
4394
4395 (defun js2-print-xml-start-tag (n i)
4396 (insert (js2-make-pad i) "<")
4397 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4398 (when (js2-xml-start-tag-node-attrs n)
4399 (insert " ")
4400 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4401 (insert ">"))
4402
4403 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4404 ;; and add the end-tag to the kids list of the parent as well.
4405 (cl-defstruct (js2-xml-end-tag-node
4406 (:include js2-xml-node)
4407 (:constructor nil)
4408 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4409 (pos js2-ts-cursor)
4410 len name)))
4411 "AST node for an XML end-tag. Not currently used."
4412 name) ; a `js2-xml-name-node'
4413
4414 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4415 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4416
4417 (defun js2-visit-xml-end-tag (n v)
4418 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4419
4420 (defun js2-print-xml-end-tag (n i)
4421 (insert (js2-make-pad i))
4422 (insert "</")
4423 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4424 (insert ">"))
4425
4426 (cl-defstruct (js2-xml-name-node
4427 (:include js2-xml-node)
4428 (:constructor nil)
4429 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4430 (pos js2-ts-cursor)
4431 len namespace kids)))
4432 "AST node for an E4X XML name. Not currently used.
4433 Any XML name can be qualified with a namespace, hence the namespace field.
4434 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4435 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4436 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4437 namespace) ; a `js2-string-node'
4438
4439 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4440 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4441
4442 (defun js2-visit-xml-name-node (n v)
4443 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4444
4445 (defun js2-print-xml-name-node (n i)
4446 (insert (js2-make-pad i))
4447 (when (js2-xml-name-node-namespace n)
4448 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4449 (insert "::"))
4450 (dolist (kid (js2-xml-name-node-kids n))
4451 (js2-print-ast kid 0)))
4452
4453 (cl-defstruct (js2-xml-pi-node
4454 (:include js2-xml-node)
4455 (:constructor nil)
4456 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4457 (pos js2-ts-cursor)
4458 len name attrs)))
4459 "AST node for an E4X XML processing instruction. Not currently used."
4460 name ; a `js2-xml-name-node'
4461 attrs) ; a list of `js2-xml-attr-node'
4462
4463 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4464 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4465
4466 (defun js2-visit-xml-pi-node (n v)
4467 (js2-visit-ast (js2-xml-pi-node-name n) v)
4468 (dolist (attr (js2-xml-pi-node-attrs n))
4469 (js2-visit-ast attr v)))
4470
4471 (defun js2-print-xml-pi-node (n i)
4472 (insert (js2-make-pad i) "<?")
4473 (js2-print-ast (js2-xml-pi-node-name n))
4474 (when (js2-xml-pi-node-attrs n)
4475 (insert " ")
4476 (js2-print-list (js2-xml-pi-node-attrs n)))
4477 (insert "?>"))
4478
4479 (cl-defstruct (js2-xml-cdata-node
4480 (:include js2-xml-node)
4481 (:constructor nil)
4482 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4483 (pos js2-ts-cursor)
4484 len content)))
4485 "AST node for a CDATA escape section. Not currently used."
4486 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4487
4488 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4489 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4490
4491 (defun js2-visit-xml-cdata-node (n v)
4492 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4493
4494 (defun js2-print-xml-cdata-node (n i)
4495 (insert (js2-make-pad i))
4496 (js2-print-ast (js2-xml-cdata-node-content n)))
4497
4498 (cl-defstruct (js2-xml-attr-node
4499 (:include js2-xml-node)
4500 (:constructor nil)
4501 (:constructor make-js2-attr-node (&key (type js2-XML)
4502 (pos js2-ts-cursor)
4503 len name value
4504 eq-pos quote-type)))
4505 "AST node representing a foo='bar' XML attribute value. Not yet used."
4506 name ; a `js2-xml-name-node'
4507 value ; a `js2-xml-name-node'
4508 eq-pos ; buffer position of "=" sign
4509 quote-type) ; 'single or 'double
4510
4511 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4512 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4513
4514 (defun js2-visit-xml-attr-node (n v)
4515 (js2-visit-ast (js2-xml-attr-node-name n) v)
4516 (js2-visit-ast (js2-xml-attr-node-value n) v))
4517
4518 (defun js2-print-xml-attr-node (n i)
4519 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4520 "'"
4521 "\"")))
4522 (insert (js2-make-pad i))
4523 (js2-print-ast (js2-xml-attr-node-name n) 0)
4524 (insert "=" quote)
4525 (js2-print-ast (js2-xml-attr-node-value n) 0)
4526 (insert quote)))
4527
4528 (cl-defstruct (js2-xml-text-node
4529 (:include js2-xml-node)
4530 (:constructor nil)
4531 (:constructor make-js2-text-node (&key (type js2-XML)
4532 (pos js2-ts-cursor)
4533 len content)))
4534 "AST node for an E4X XML text node. Not currently used."
4535 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4536
4537 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4538 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4539
4540 (defun js2-visit-xml-text-node (n v)
4541 (js2-visit-ast (js2-xml-text-node-content n) v))
4542
4543 (defun js2-print-xml-text-node (n i)
4544 (insert (js2-make-pad i))
4545 (dolist (kid (js2-xml-text-node-content n))
4546 (js2-print-ast kid)))
4547
4548 (cl-defstruct (js2-xml-comment-node
4549 (:include js2-xml-node)
4550 (:constructor nil)
4551 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4552 (pos js2-ts-cursor)
4553 len)))
4554 "AST node for E4X XML comment. Not currently used.")
4555
4556 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4557 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4558
4559 (defun js2-print-xml-comment (n i)
4560 (insert (js2-make-pad i)
4561 (js2-node-string n)))
4562
4563 ;;; Node utilities
4564
4565 (defsubst js2-node-line (n)
4566 "Fetch the source line number at the start of node N.
4567 This is O(n) in the length of the source buffer; use prudently."
4568 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4569
4570 (defsubst js2-block-node-kid (n i)
4571 "Return child I of node N, or nil if there aren't that many."
4572 (nth i (js2-block-node-kids n)))
4573
4574 (defsubst js2-block-node-first (n)
4575 "Return first child of block node N, or nil if there is none."
4576 (cl-first (js2-block-node-kids n)))
4577
4578 (defun js2-node-root (n)
4579 "Return the root of the AST containing N.
4580 If N has no parent pointer, returns N."
4581 (let ((parent (js2-node-parent n)))
4582 (if parent
4583 (js2-node-root parent)
4584 n)))
4585
4586 (defsubst js2-node-short-name (n)
4587 "Return the short name of node N as a string, e.g. `js2-if-node'."
4588 (substring (symbol-name (aref n 0))
4589 (length "cl-struct-")))
4590
4591 (defun js2-node-child-list (node)
4592 "Return the child list for NODE, a Lisp list of nodes.
4593 Works for block nodes, array nodes, obj literals, funarg lists,
4594 var decls and try nodes (for catch clauses). Note that you should call
4595 `js2-block-node-kids' on the function body for the body statements.
4596 Returns nil for zero-length child lists or unsupported nodes."
4597 (cond
4598 ((js2-function-node-p node)
4599 (js2-function-node-params node))
4600 ((js2-block-node-p node)
4601 (js2-block-node-kids node))
4602 ((js2-try-node-p node)
4603 (js2-try-node-catch-clauses node))
4604 ((js2-array-node-p node)
4605 (js2-array-node-elems node))
4606 ((js2-object-node-p node)
4607 (js2-object-node-elems node))
4608 ((js2-call-node-p node)
4609 (js2-call-node-args node))
4610 ((js2-new-node-p node)
4611 (js2-new-node-args node))
4612 ((js2-var-decl-node-p node)
4613 (js2-var-decl-node-kids node))
4614 (t
4615 nil)))
4616
4617 (defun js2-node-set-child-list (node kids)
4618 "Set the child list for NODE to KIDS."
4619 (cond
4620 ((js2-function-node-p node)
4621 (setf (js2-function-node-params node) kids))
4622 ((js2-block-node-p node)
4623 (setf (js2-block-node-kids node) kids))
4624 ((js2-try-node-p node)
4625 (setf (js2-try-node-catch-clauses node) kids))
4626 ((js2-array-node-p node)
4627 (setf (js2-array-node-elems node) kids))
4628 ((js2-object-node-p node)
4629 (setf (js2-object-node-elems node) kids))
4630 ((js2-call-node-p node)
4631 (setf (js2-call-node-args node) kids))
4632 ((js2-new-node-p node)
4633 (setf (js2-new-node-args node) kids))
4634 ((js2-var-decl-node-p node)
4635 (setf (js2-var-decl-node-kids node) kids))
4636 (t
4637 (error "Unsupported node type: %s" (js2-node-short-name node))))
4638 kids)
4639
4640 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4641 (defconst js2-paren-expr-nodes
4642 '(cl-struct-js2-comp-loop-node
4643 cl-struct-js2-comp-node
4644 cl-struct-js2-call-node
4645 cl-struct-js2-catch-node
4646 cl-struct-js2-do-node
4647 cl-struct-js2-elem-get-node
4648 cl-struct-js2-for-in-node
4649 cl-struct-js2-for-node
4650 cl-struct-js2-function-node
4651 cl-struct-js2-if-node
4652 cl-struct-js2-let-node
4653 cl-struct-js2-new-node
4654 cl-struct-js2-paren-node
4655 cl-struct-js2-switch-node
4656 cl-struct-js2-while-node
4657 cl-struct-js2-with-node
4658 cl-struct-js2-xml-dot-query-node)
4659 "Node types that can have a parenthesized child expression.
4660 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4661
4662 (defsubst js2-paren-expr-node-p (node)
4663 "Return t for nodes that typically have a parenthesized child expression.
4664 Useful for computing the indentation anchors for arg-lists and conditions.
4665 Note that it may return a false positive, for instance when NODE is
4666 a `js2-new-node' and there are no arguments or parentheses."
4667 (memq (aref node 0) js2-paren-expr-nodes))
4668
4669 ;; Fake polymorphism... yech.
4670 (defun js2-node-lp (node)
4671 "Return relative left-paren position for NODE, if applicable.
4672 For `js2-elem-get-node' structs, returns left-bracket position.
4673 Note that the position may be nil in the case of a parse error."
4674 (cond
4675 ((js2-elem-get-node-p node)
4676 (js2-elem-get-node-lb node))
4677 ((js2-loop-node-p node)
4678 (js2-loop-node-lp node))
4679 ((js2-function-node-p node)
4680 (js2-function-node-lp node))
4681 ((js2-if-node-p node)
4682 (js2-if-node-lp node))
4683 ((js2-new-node-p node)
4684 (js2-new-node-lp node))
4685 ((js2-call-node-p node)
4686 (js2-call-node-lp node))
4687 ((js2-paren-node-p node)
4688 0)
4689 ((js2-switch-node-p node)
4690 (js2-switch-node-lp node))
4691 ((js2-catch-node-p node)
4692 (js2-catch-node-lp node))
4693 ((js2-let-node-p node)
4694 (js2-let-node-lp node))
4695 ((js2-comp-node-p node)
4696 0)
4697 ((js2-with-node-p node)
4698 (js2-with-node-lp node))
4699 ((js2-xml-dot-query-node-p node)
4700 (1+ (js2-infix-node-op-pos node)))
4701 (t
4702 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4703
4704 ;; Fake polymorphism... blech.
4705 (defun js2-node-rp (node)
4706 "Return relative right-paren position for NODE, if applicable.
4707 For `js2-elem-get-node' structs, returns right-bracket position.
4708 Note that the position may be nil in the case of a parse error."
4709 (cond
4710 ((js2-elem-get-node-p node)
4711 (js2-elem-get-node-rb node))
4712 ((js2-loop-node-p node)
4713 (js2-loop-node-rp node))
4714 ((js2-function-node-p node)
4715 (js2-function-node-rp node))
4716 ((js2-if-node-p node)
4717 (js2-if-node-rp node))
4718 ((js2-new-node-p node)
4719 (js2-new-node-rp node))
4720 ((js2-call-node-p node)
4721 (js2-call-node-rp node))
4722 ((js2-paren-node-p node)
4723 (1- (js2-node-len node)))
4724 ((js2-switch-node-p node)
4725 (js2-switch-node-rp node))
4726 ((js2-catch-node-p node)
4727 (js2-catch-node-rp node))
4728 ((js2-let-node-p node)
4729 (js2-let-node-rp node))
4730 ((js2-comp-node-p node)
4731 (1- (js2-node-len node)))
4732 ((js2-with-node-p node)
4733 (js2-with-node-rp node))
4734 ((js2-xml-dot-query-node-p node)
4735 (1+ (js2-xml-dot-query-node-rp node)))
4736 (t
4737 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4738
4739 (defsubst js2-node-first-child (node)
4740 "Return the first element of `js2-node-child-list' for NODE."
4741 (car (js2-node-child-list node)))
4742
4743 (defsubst js2-node-last-child (node)
4744 "Return the last element of `js2-node-last-child' for NODE."
4745 (car (last (js2-node-child-list node))))
4746
4747 (defun js2-node-prev-sibling (node)
4748 "Return the previous statement in parent.
4749 Works for parents supported by `js2-node-child-list'.
4750 Returns nil if NODE is not in the parent, or PARENT is
4751 not a supported node, or if NODE is the first child."
4752 (let* ((p (js2-node-parent node))
4753 (kids (js2-node-child-list p))
4754 (sib (car kids)))
4755 (while (and kids
4756 (not (eq node (cadr kids))))
4757 (setq kids (cdr kids)
4758 sib (car kids)))
4759 sib))
4760
4761 (defun js2-node-next-sibling (node)
4762 "Return the next statement in parent block.
4763 Returns nil if NODE is not in the block, or PARENT is not
4764 a block node, or if NODE is the last statement."
4765 (let* ((p (js2-node-parent node))
4766 (kids (js2-node-child-list p)))
4767 (while (and kids
4768 (not (eq node (car kids))))
4769 (setq kids (cdr kids)))
4770 (cadr kids)))
4771
4772 (defun js2-node-find-child-before (pos parent &optional after)
4773 "Find the last child that starts before POS in parent.
4774 If AFTER is non-nil, returns first child starting after POS.
4775 POS is an absolute buffer position. PARENT is any node
4776 supported by `js2-node-child-list'.
4777 Returns nil if no applicable child is found."
4778 (let ((kids (if (js2-function-node-p parent)
4779 (js2-block-node-kids (js2-function-node-body parent))
4780 (js2-node-child-list parent)))
4781 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4782 (js2-function-node-body parent)
4783 parent)))
4784 kid result fn
4785 (continue t))
4786 (setq fn (if after '>= '<))
4787 (while (and kids continue)
4788 (setq kid (car kids))
4789 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4790 (setq result kid
4791 continue (not after))
4792 (setq continue after))
4793 (setq kids (cdr kids)))
4794 result))
4795
4796 (defun js2-node-find-child-after (pos parent)
4797 "Find first child that starts after POS in parent.
4798 POS is an absolute buffer position. PARENT is any node
4799 supported by `js2-node-child-list'.
4800 Returns nil if no applicable child is found."
4801 (js2-node-find-child-before pos parent 'after))
4802
4803 (defun js2-node-replace-child (pos parent new-node)
4804 "Replace node at index POS in PARENT with NEW-NODE.
4805 Only works for parents supported by `js2-node-child-list'."
4806 (let ((kids (js2-node-child-list parent))
4807 (i 0))
4808 (while (< i pos)
4809 (setq kids (cdr kids)
4810 i (1+ i)))
4811 (setcar kids new-node)
4812 (js2-node-add-children parent new-node)))
4813
4814 (defun js2-node-buffer (n)
4815 "Return the buffer associated with AST N.
4816 Returns nil if the buffer is not set as a property on the root
4817 node, or if parent links were not recorded during parsing."
4818 (let ((root (js2-node-root n)))
4819 (and root
4820 (js2-ast-root-p root)
4821 (js2-ast-root-buffer root))))
4822
4823 (defun js2-block-node-push (n kid)
4824 "Push js2-node KID onto the end of js2-block-node N's child list.
4825 KID is always added to the -end- of the kids list.
4826 Function also calls `js2-node-add-children' to add the parent link."
4827 (let ((kids (js2-node-child-list n)))
4828 (if kids
4829 (setcdr kids (nconc (cdr kids) (list kid)))
4830 (js2-node-set-child-list n (list kid)))
4831 (js2-node-add-children n kid)))
4832
4833 (defun js2-node-string (node)
4834 (with-current-buffer (or (js2-node-buffer node)
4835 (error "No buffer available for node %s" node))
4836 (let ((pos (js2-node-abs-pos node)))
4837 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4838
4839 ;; Container for storing the node we're looking for in a traversal.
4840 (js2-deflocal js2-discovered-node nil)
4841
4842 ;; Keep track of absolute node position during traversals.
4843 (js2-deflocal js2-visitor-offset nil)
4844
4845 (js2-deflocal js2-node-search-point nil)
4846
4847 (when js2-mode-dev-mode-p
4848 (defun js2-find-node-at-point ()
4849 (interactive)
4850 (let ((node (js2-node-at-point)))
4851 (message "%s" (or node "No node found at point"))))
4852 (defun js2-node-name-at-point ()
4853 (interactive)
4854 (let ((node (js2-node-at-point)))
4855 (message "%s" (if node
4856 (js2-node-short-name node)
4857 "No node found at point.")))))
4858
4859 (defun js2-node-at-point (&optional pos skip-comments)
4860 "Return AST node at POS, a buffer position, defaulting to current point.
4861 The `js2-mode-ast' variable must be set to the current parse tree.
4862 Signals an error if the AST (`js2-mode-ast') is nil.
4863 Always returns a node - if it can't find one, it returns the root.
4864 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4865 (let ((ast js2-mode-ast)
4866 result)
4867 (unless ast
4868 (error "No JavaScript AST available"))
4869 ;; Look through comments first, since they may be inside nodes that
4870 ;; would otherwise report a match.
4871 (setq pos (or pos (point))
4872 result (if (> pos (js2-node-abs-end ast))
4873 ast
4874 (if (not skip-comments)
4875 (js2-comment-at-point pos))))
4876 (unless result
4877 (setq js2-discovered-node nil
4878 js2-visitor-offset 0
4879 js2-node-search-point pos)
4880 (unwind-protect
4881 (catch 'js2-visit-done
4882 (js2-visit-ast ast #'js2-node-at-point-visitor))
4883 (setq js2-visitor-offset nil
4884 js2-node-search-point nil))
4885 (setq result js2-discovered-node))
4886 ;; may have found a comment beyond end of last child node,
4887 ;; since visiting the ast-root looks at the comment-list last.
4888 (if (and skip-comments
4889 (js2-comment-node-p result))
4890 (setq result nil))
4891 (or result js2-mode-ast)))
4892
4893 (defun js2-node-at-point-visitor (node end-p)
4894 (let ((rel-pos (js2-node-pos node))
4895 abs-pos
4896 abs-end
4897 (point js2-node-search-point))
4898 (cond
4899 (end-p
4900 ;; this evaluates to a non-nil return value, even if it's zero
4901 (cl-decf js2-visitor-offset rel-pos))
4902 ;; we already looked for comments before visiting, and don't want them now
4903 ((js2-comment-node-p node)
4904 nil)
4905 (t
4906 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4907 ;; we only want to use the node if the point is before
4908 ;; the last character position in the node, so we decrement
4909 ;; the absolute end by 1.
4910 abs-end (+ abs-pos (js2-node-len node) -1))
4911 (cond
4912 ;; If this node starts after search-point, stop the search.
4913 ((> abs-pos point)
4914 (throw 'js2-visit-done nil))
4915 ;; If this node ends before the search-point, don't check kids.
4916 ((> point abs-end)
4917 nil)
4918 (t
4919 ;; Otherwise point is within this node, possibly in a child.
4920 (setq js2-discovered-node node)
4921 t)))))) ; keep processing kids to look for more specific match
4922
4923 (defsubst js2-block-comment-p (node)
4924 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4925 (and (js2-comment-node-p node)
4926 (memq (js2-comment-node-format node) '(jsdoc block))))
4927
4928 ;; TODO: put the comments in a vector and binary-search them instead
4929 (defun js2-comment-at-point (&optional pos)
4930 "Look through scanned comment nodes for one containing POS.
4931 POS is a buffer position that defaults to current point.
4932 Function returns nil if POS was not in any comment node."
4933 (let ((ast js2-mode-ast)
4934 (x (or pos (point)))
4935 beg end)
4936 (unless ast
4937 (error "No JavaScript AST available"))
4938 (catch 'done
4939 ;; Comments are stored in lexical order.
4940 (dolist (comment (js2-ast-root-comments ast) nil)
4941 (setq beg (js2-node-abs-pos comment)
4942 end (+ beg (js2-node-len comment)))
4943 (if (and (>= x beg)
4944 (<= x end))
4945 (throw 'done comment))))))
4946
4947 (defun js2-mode-find-parent-fn (node)
4948 "Find function enclosing NODE.
4949 Returns nil if NODE is not inside a function."
4950 (setq node (js2-node-parent node))
4951 (while (and node (not (js2-function-node-p node)))
4952 (setq node (js2-node-parent node)))
4953 (and (js2-function-node-p node) node))
4954
4955 (defun js2-mode-find-enclosing-fn (node)
4956 "Find function or root enclosing NODE."
4957 (if (js2-ast-root-p node)
4958 node
4959 (setq node (js2-node-parent node))
4960 (while (not (or (js2-ast-root-p node)
4961 (js2-function-node-p node)))
4962 (setq node (js2-node-parent node)))
4963 node))
4964
4965 (defun js2-mode-find-enclosing-node (beg end)
4966 "Find node fully enclosing BEG and END."
4967 (let ((node (js2-node-at-point beg))
4968 pos
4969 (continue t))
4970 (while continue
4971 (if (or (js2-ast-root-p node)
4972 (and
4973 (<= (setq pos (js2-node-abs-pos node)) beg)
4974 (>= (+ pos (js2-node-len node)) end)))
4975 (setq continue nil)
4976 (setq node (js2-node-parent node))))
4977 node))
4978
4979 (defun js2-node-parent-script-or-fn (node)
4980 "Find script or function immediately enclosing NODE.
4981 If NODE is the ast-root, returns nil."
4982 (if (js2-ast-root-p node)
4983 nil
4984 (setq node (js2-node-parent node))
4985 (while (and node (not (or (js2-function-node-p node)
4986 (js2-script-node-p node))))
4987 (setq node (js2-node-parent node)))
4988 node))
4989
4990 (defun js2-node-is-descendant (node ancestor)
4991 "Return t if NODE is a descendant of ANCESTOR."
4992 (while (and node
4993 (not (eq node ancestor)))
4994 (setq node (js2-node-parent node)))
4995 node)
4996
4997 ;;; visitor infrastructure
4998
4999 (defun js2-visit-none (_node _callback)
5000 "Visitor for AST node that have no node children."
5001 nil)
5002
5003 (defun js2-print-none (_node _indent)
5004 "Visitor for AST node with no printed representation.")
5005
5006 (defun js2-print-body (node indent)
5007 "Print a statement, or a block without braces."
5008 (if (js2-block-node-p node)
5009 (dolist (kid (js2-block-node-kids node))
5010 (js2-print-ast kid indent))
5011 (js2-print-ast node indent)))
5012
5013 (defun js2-print-list (args &optional delimiter)
5014 (cl-loop with len = (length args)
5015 for arg in args
5016 for count from 1
5017 do
5018 (when arg (js2-print-ast arg 0))
5019 (if (< count len)
5020 (insert (or delimiter ", ")))))
5021
5022 (defun js2-print-tree (ast)
5023 "Prints an AST to the current buffer.
5024 Makes `js2-ast-parent-nodes' available to the printer functions."
5025 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5026 (js2-print-ast ast)))
5027
5028 (defun js2-print-ast (node &optional indent)
5029 "Helper function for printing AST nodes.
5030 Requires `js2-ast-parent-nodes' to be non-nil.
5031 You should use `js2-print-tree' instead of this function."
5032 (let ((printer (get (aref node 0) 'js2-printer))
5033 (i (or indent 0)))
5034 ;; TODO: wedge comments in here somewhere
5035 (if printer
5036 (funcall printer node i))))
5037
5038 (defconst js2-side-effecting-tokens
5039 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5040 (dolist (tt (list js2-ASSIGN
5041 js2-ASSIGN_ADD
5042 js2-ASSIGN_BITAND
5043 js2-ASSIGN_BITOR
5044 js2-ASSIGN_BITXOR
5045 js2-ASSIGN_DIV
5046 js2-ASSIGN_LSH
5047 js2-ASSIGN_MOD
5048 js2-ASSIGN_MUL
5049 js2-ASSIGN_RSH
5050 js2-ASSIGN_SUB
5051 js2-ASSIGN_URSH
5052 js2-BLOCK
5053 js2-BREAK
5054 js2-CALL
5055 js2-CATCH
5056 js2-CATCH_SCOPE
5057 js2-CLASS
5058 js2-CONST
5059 js2-CONTINUE
5060 js2-DEBUGGER
5061 js2-DEC
5062 js2-DELPROP
5063 js2-DEL_REF
5064 js2-DO
5065 js2-ELSE
5066 js2-EMPTY
5067 js2-ENTERWITH
5068 js2-EXPORT
5069 js2-EXPR_RESULT
5070 js2-FINALLY
5071 js2-FOR
5072 js2-FUNCTION
5073 js2-GOTO
5074 js2-IF
5075 js2-IFEQ
5076 js2-IFNE
5077 js2-IMPORT
5078 js2-INC
5079 js2-JSR
5080 js2-LABEL
5081 js2-LEAVEWITH
5082 js2-LET
5083 js2-LETEXPR
5084 js2-LOCAL_BLOCK
5085 js2-LOOP
5086 js2-NEW
5087 js2-REF_CALL
5088 js2-RETHROW
5089 js2-RETURN
5090 js2-RETURN_RESULT
5091 js2-SEMI
5092 js2-SETELEM
5093 js2-SETELEM_OP
5094 js2-SETNAME
5095 js2-SETPROP
5096 js2-SETPROP_OP
5097 js2-SETVAR
5098 js2-SET_REF
5099 js2-SET_REF_OP
5100 js2-SWITCH
5101 js2-TARGET
5102 js2-THROW
5103 js2-TRY
5104 js2-VAR
5105 js2-WHILE
5106 js2-WITH
5107 js2-WITHEXPR
5108 js2-YIELD))
5109 (aset tokens tt t))
5110 (if js2-instanceof-has-side-effects
5111 (aset tokens js2-INSTANCEOF t))
5112 tokens))
5113
5114 (defun js2-node-has-side-effects (node)
5115 "Return t if NODE has side effects."
5116 (when node ; makes it easier to handle malformed expressions
5117 (let ((tt (js2-node-type node)))
5118 (cond
5119 ;; This doubtless needs some work, since EXPR_VOID is used
5120 ;; in several ways in Rhino and I may not have caught them all.
5121 ;; I'll wait for people to notice incorrect warnings.
5122 ((and (= tt js2-EXPR_VOID)
5123 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5124 (let ((expr (js2-expr-stmt-node-expr node)))
5125 (or (js2-node-has-side-effects expr)
5126 (when (js2-string-node-p expr)
5127 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5128 ((= tt js2-COMMA)
5129 (js2-node-has-side-effects (js2-infix-node-right node)))
5130 ((or (= tt js2-AND)
5131 (= tt js2-OR))
5132 (or (js2-node-has-side-effects (js2-infix-node-right node))
5133 (js2-node-has-side-effects (js2-infix-node-left node))))
5134 ((= tt js2-HOOK)
5135 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5136 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5137 ((js2-paren-node-p node)
5138 (js2-node-has-side-effects (js2-paren-node-expr node)))
5139 ((= tt js2-ERROR) ; avoid cascaded error messages
5140 nil)
5141 (t
5142 (aref js2-side-effecting-tokens tt))))))
5143
5144 (defconst js2-stmt-node-types
5145 (list js2-BLOCK
5146 js2-BREAK
5147 js2-CONTINUE
5148 js2-DEFAULT ; e4x "default xml namespace" statement
5149 js2-DO
5150 js2-EXPORT
5151 js2-EXPR_RESULT
5152 js2-EXPR_VOID
5153 js2-FOR
5154 js2-IF
5155 js2-IMPORT
5156 js2-RETURN
5157 js2-SWITCH
5158 js2-THROW
5159 js2-TRY
5160 js2-WHILE
5161 js2-WITH)
5162 "Node types that only appear in statement contexts.
5163 The list does not include nodes that always appear as the child
5164 of another specific statement type, such as switch-cases,
5165 catch and finally blocks, and else-clauses. The list also excludes
5166 nodes like yield, let and var, which may appear in either expression
5167 or statement context, and in the latter context always have a
5168 `js2-expr-stmt-node' parent. Finally, the list does not include
5169 functions or scripts, which are treated separately from statements
5170 by the JavaScript parser and runtime.")
5171
5172 (defun js2-stmt-node-p (node)
5173 "Heuristic for figuring out if NODE is a statement.
5174 Some node types can appear in either an expression context or a
5175 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5176 For these node types in a statement context, the parent will be a
5177 `js2-expr-stmt-node'.
5178 Functions aren't included in the check."
5179 (memq (js2-node-type node) js2-stmt-node-types))
5180
5181 (defun js2-mode-find-first-stmt (node)
5182 "Search upward starting from NODE looking for a statement.
5183 For purposes of this function, a `js2-function-node' counts."
5184 (while (not (or (js2-stmt-node-p node)
5185 (js2-function-node-p node)))
5186 (setq node (js2-node-parent node)))
5187 node)
5188
5189 (defun js2-node-parent-stmt (node)
5190 "Return the node's first ancestor that is a statement.
5191 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5192 appearing in a statement context will have a parent that is a
5193 `js2-expr-stmt-node' that will be returned by this function."
5194 (let ((parent (js2-node-parent node)))
5195 (if (or (null parent)
5196 (js2-stmt-node-p parent)
5197 (and (js2-function-node-p parent)
5198 (not (eq (js2-function-node-form parent)
5199 'FUNCTION_EXPRESSION))))
5200 parent
5201 (js2-node-parent-stmt parent))))
5202
5203 ;; In the Mozilla Rhino sources, Roshan James writes:
5204 ;; Does consistent-return analysis on the function body when strict mode is
5205 ;; enabled.
5206 ;;
5207 ;; function (x) { return (x+1) }
5208 ;;
5209 ;; is ok, but
5210 ;;
5211 ;; function (x) { if (x < 0) return (x+1); }
5212 ;;
5213 ;; is not because the function can potentially return a value when the
5214 ;; condition is satisfied and if not, the function does not explicitly
5215 ;; return a value.
5216 ;;
5217 ;; This extends to checking mismatches such as "return" and "return <value>"
5218 ;; used in the same function. Warnings are not emitted if inconsistent
5219 ;; returns exist in code that can be statically shown to be unreachable.
5220 ;; Ex.
5221 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5222 ;;
5223 ;; emits no warning. However if the loop had a break statement, then a
5224 ;; warning would be emitted.
5225 ;;
5226 ;; The consistency analysis looks at control structures such as loops, ifs,
5227 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5228 ;; warns the user about an inconsistent set of termination possibilities.
5229 ;;
5230 ;; These flags enumerate the possible ways a statement/function can
5231 ;; terminate. These flags are used by endCheck() and by the Parser to
5232 ;; detect inconsistent return usage.
5233 ;;
5234 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5235 ;; able to execute (example: throw, continue)
5236 ;;
5237 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5238 ;; next one. Statement such as return dont. A compound statement may have
5239 ;; some branch that drops off control to the next statement.
5240 ;;
5241 ;; END_RETURNS indicates that the statement can return with no value.
5242 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5243 ;;
5244 ;; A compound statement such as
5245 ;; if (condition) {
5246 ;; return value;
5247 ;; }
5248 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5249
5250 (defconst js2-END_UNREACHED 0)
5251 (defconst js2-END_DROPS_OFF 1)
5252 (defconst js2-END_RETURNS 2)
5253 (defconst js2-END_RETURNS_VALUE 4)
5254 (defconst js2-END_YIELDS 8)
5255
5256 (defun js2-has-consistent-return-usage (node)
5257 "Check that every return usage in a function body is consistent.
5258 Returns t if the function satisfies strict mode requirement."
5259 (let ((n (js2-end-check node)))
5260 ;; either it doesn't return a value in any branch...
5261 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5262 ;; or it returns a value (or is unreached) at every branch
5263 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5264 js2-END_RETURNS
5265 js2-END_YIELDS)))))
5266
5267 (defun js2-end-check-if (node)
5268 "Ensure that return usage in then/else blocks is consistent.
5269 If there is no else block, then the return statement can fall through.
5270 Returns logical OR of END_* flags"
5271 (let ((th (js2-if-node-then-part node))
5272 (el (js2-if-node-else-part node)))
5273 (if (null th)
5274 js2-END_UNREACHED
5275 (logior (js2-end-check th) (if el
5276 (js2-end-check el)
5277 js2-END_DROPS_OFF)))))
5278
5279 (defun js2-end-check-switch (node)
5280 "Consistency of return statements is checked between the case statements.
5281 If there is no default, then the switch can fall through. If there is a
5282 default, we check to see if all code paths in the default return or if
5283 there is a code path that can fall through.
5284 Returns logical OR of END_* flags."
5285 (let ((rv js2-END_UNREACHED)
5286 default-case)
5287 ;; examine the cases
5288 (catch 'break
5289 (dolist (c (js2-switch-node-cases node))
5290 (if (js2-case-node-expr c)
5291 (js2-set-flag rv (js2-end-check-block c))
5292 (setq default-case c)
5293 (throw 'break nil))))
5294 ;; we don't care how the cases drop into each other
5295 (js2-clear-flag rv js2-END_DROPS_OFF)
5296 ;; examine the default
5297 (js2-set-flag rv (if default-case
5298 (js2-end-check default-case)
5299 js2-END_DROPS_OFF))
5300 rv))
5301
5302 (defun js2-end-check-try (node)
5303 "If the block has a finally, return consistency is checked in the
5304 finally block. If all code paths in the finally return, then the
5305 returns in the try-catch blocks don't matter. If there is a code path
5306 that does not return or if there is no finally block, the returns
5307 of the try and catch blocks are checked for mismatch.
5308 Returns logical OR of END_* flags."
5309 (let ((finally (js2-try-node-finally-block node))
5310 rv)
5311 ;; check the finally if it exists
5312 (setq rv (if finally
5313 (js2-end-check (js2-finally-node-body finally))
5314 js2-END_DROPS_OFF))
5315 ;; If the finally block always returns, then none of the returns
5316 ;; in the try or catch blocks matter.
5317 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5318 (js2-clear-flag rv js2-END_DROPS_OFF)
5319 ;; examine the try block
5320 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5321 ;; check each catch block
5322 (dolist (cb (js2-try-node-catch-clauses node))
5323 (js2-set-flag rv (js2-end-check cb))))
5324 rv))
5325
5326 (defun js2-end-check-loop (node)
5327 "Return statement in the loop body must be consistent.
5328 The default assumption for any kind of a loop is that it will eventually
5329 terminate. The only exception is a loop with a constant true condition.
5330 Code that follows such a loop is examined only if one can determine
5331 statically that there is a break out of the loop.
5332
5333 for(... ; ... ; ...) {}
5334 for(... in ... ) {}
5335 while(...) { }
5336 do { } while(...)
5337
5338 Returns logical OR of END_* flags."
5339 (let ((rv (js2-end-check (js2-loop-node-body node)))
5340 (condition (cond
5341 ((js2-while-node-p node)
5342 (js2-while-node-condition node))
5343 ((js2-do-node-p node)
5344 (js2-do-node-condition node))
5345 ((js2-for-node-p node)
5346 (js2-for-node-condition node)))))
5347
5348 ;; check to see if the loop condition is always true
5349 (if (and condition
5350 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5351 (js2-clear-flag rv js2-END_DROPS_OFF))
5352
5353 ;; look for effect of breaks
5354 (js2-set-flag rv (js2-node-get-prop node
5355 'CONTROL_BLOCK_PROP
5356 js2-END_UNREACHED))
5357 rv))
5358
5359 (defun js2-end-check-block (node)
5360 "A general block of code is examined statement by statement.
5361 If any statement (even a compound one) returns in all branches, then
5362 subsequent statements are not examined.
5363 Returns logical OR of END_* flags."
5364 (let* ((rv js2-END_DROPS_OFF)
5365 (kids (js2-block-node-kids node))
5366 (n (car kids)))
5367 ;; Check each statement. If the statement can continue onto the next
5368 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5369 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5370 (js2-clear-flag rv js2-END_DROPS_OFF)
5371 (js2-set-flag rv (js2-end-check n))
5372 (setq kids (cdr kids)
5373 n (car kids)))
5374 rv))
5375
5376 (defun js2-end-check-label (node)
5377 "A labeled statement implies that there may be a break to the label.
5378 The function processes the labeled statement and then checks the
5379 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5380 particular label.
5381 Returns logical OR of END_* flags."
5382 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5383 (logior rv (js2-node-get-prop node
5384 'CONTROL_BLOCK_PROP
5385 js2-END_UNREACHED))))
5386
5387 (defun js2-end-check-break (node)
5388 "When a break is encountered annotate the statement being broken
5389 out of by setting its CONTROL_BLOCK_PROP property.
5390 Returns logical OR of END_* flags."
5391 (and (js2-break-node-target node)
5392 (js2-node-set-prop (js2-break-node-target node)
5393 'CONTROL_BLOCK_PROP
5394 js2-END_DROPS_OFF))
5395 js2-END_UNREACHED)
5396
5397 (defun js2-end-check (node)
5398 "Examine the body of a function, doing a basic reachability analysis.
5399 Returns a combination of flags END_* flags that indicate
5400 how the function execution can terminate. These constitute only the
5401 pessimistic set of termination conditions. It is possible that at
5402 runtime certain code paths will never be actually taken. Hence this
5403 analysis will flag errors in cases where there may not be errors.
5404 Returns logical OR of END_* flags"
5405 (let (kid)
5406 (cond
5407 ((js2-break-node-p node)
5408 (js2-end-check-break node))
5409 ((js2-expr-stmt-node-p node)
5410 (if (setq kid (js2-expr-stmt-node-expr node))
5411 (js2-end-check kid)
5412 js2-END_DROPS_OFF))
5413 ((or (js2-continue-node-p node)
5414 (js2-throw-node-p node))
5415 js2-END_UNREACHED)
5416 ((js2-return-node-p node)
5417 (if (setq kid (js2-return-node-retval node))
5418 js2-END_RETURNS_VALUE
5419 js2-END_RETURNS))
5420 ((js2-loop-node-p node)
5421 (js2-end-check-loop node))
5422 ((js2-switch-node-p node)
5423 (js2-end-check-switch node))
5424 ((js2-labeled-stmt-node-p node)
5425 (js2-end-check-label node))
5426 ((js2-if-node-p node)
5427 (js2-end-check-if node))
5428 ((js2-try-node-p node)
5429 (js2-end-check-try node))
5430 ((js2-block-node-p node)
5431 (if (null (js2-block-node-kids node))
5432 js2-END_DROPS_OFF
5433 (js2-end-check-block node)))
5434 ((js2-yield-node-p node)
5435 js2-END_YIELDS)
5436 (t
5437 js2-END_DROPS_OFF))))
5438
5439 (defun js2-always-defined-boolean-p (node)
5440 "Check if NODE always evaluates to true or false in boolean context.
5441 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5442 nor always false."
5443 (let ((tt (js2-node-type node))
5444 num)
5445 (cond
5446 ((or (= tt js2-FALSE) (= tt js2-NULL))
5447 'ALWAYS_FALSE)
5448 ((= tt js2-TRUE)
5449 'ALWAYS_TRUE)
5450 ((= tt js2-NUMBER)
5451 (setq num (js2-number-node-num-value node))
5452 (if (and (not (eq num 0.0e+NaN))
5453 (not (zerop num)))
5454 'ALWAYS_TRUE
5455 'ALWAYS_FALSE))
5456 (t
5457 nil))))
5458
5459 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5460 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5461
5462 (defvar js2-tokens nil
5463 "List of all defined token names.") ; initialized in `js2-token-names'
5464
5465 (defconst js2-token-names
5466 (let* ((names (make-vector js2-num-tokens -1))
5467 (case-fold-search nil) ; only match js2-UPPER_CASE
5468 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5469 (cl-loop for sym in syms
5470 for i from 0
5471 do
5472 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5473 (not (boundp sym)))
5474 (aset names (symbol-value sym) ; code, e.g. 152
5475 (downcase
5476 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5477 (push sym js2-tokens)))
5478 names)
5479 "Vector mapping int values to token string names, sans `js2-' prefix.")
5480
5481 (defun js2-tt-name (tok)
5482 "Return a string name for TOK, a token symbol or code.
5483 Signals an error if it's not a recognized token."
5484 (let ((code tok))
5485 (if (symbolp tok)
5486 (setq code (symbol-value tok)))
5487 (if (eq code -1)
5488 "ERROR"
5489 (if (and (numberp code)
5490 (not (cl-minusp code))
5491 (< code js2-num-tokens))
5492 (aref js2-token-names code)
5493 (error "Invalid token: %s" code)))))
5494
5495 (defsubst js2-tt-sym (tok)
5496 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5497 (intern (js2-tt-name tok)))
5498
5499 (defconst js2-token-codes
5500 (let ((table (make-hash-table :test 'eq :size 256)))
5501 (cl-loop for name across js2-token-names
5502 for sym = (intern (concat "js2-" (upcase name)))
5503 do
5504 (puthash sym (symbol-value sym) table))
5505 ;; clean up a few that are "wrong" in Rhino's token codes
5506 (puthash 'js2-DELETE js2-DELPROP table)
5507 table)
5508 "Hashtable mapping token type symbols to their bytecodes.")
5509
5510 (defsubst js2-tt-code (sym)
5511 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5512 (or (gethash sym js2-token-codes)
5513 (error "Invalid token symbol: %s " sym))) ; signal code bug
5514
5515 (defun js2-report-scan-error (msg &optional no-throw beg len)
5516 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5517 (js2-report-error msg nil
5518 (or beg (js2-current-token-beg))
5519 (or len (js2-current-token-len)))
5520 (unless no-throw
5521 (throw 'return js2-ERROR)))
5522
5523 (defun js2-set-string-from-buffer (token)
5524 "Set `string' and `end' slots for TOKEN, return the string."
5525 (setf (js2-token-end token) js2-ts-cursor
5526 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5527
5528 ;; TODO: could potentially avoid a lot of consing by allocating a
5529 ;; char buffer the way Rhino does.
5530 (defsubst js2-add-to-string (c)
5531 (push c js2-ts-string-buffer))
5532
5533 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5534 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5535 ;; any other character: when it's not part of the current token, we
5536 ;; unget it, allowing it to be read again by the following call.
5537 (defsubst js2-unget-char ()
5538 (cl-decf js2-ts-cursor))
5539
5540 ;; Rhino distinguishes \r and \n line endings. We don't need to
5541 ;; because we only scan from Emacs buffers, which always use \n.
5542 (defun js2-get-char ()
5543 "Read and return the next character from the input buffer.
5544 Increments `js2-ts-lineno' if the return value is a newline char.
5545 Updates `js2-ts-cursor' to the point after the returned char.
5546 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5547 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5548 (let (c)
5549 ;; check for end of buffer
5550 (if (>= js2-ts-cursor (point-max))
5551 (setq js2-ts-hit-eof t
5552 js2-ts-cursor (1+ js2-ts-cursor)
5553 c js2-EOF_CHAR) ; return value
5554 ;; otherwise read next char
5555 (setq c (char-before (cl-incf js2-ts-cursor)))
5556 ;; if we read a newline, update counters
5557 (if (= c ?\n)
5558 (setq js2-ts-line-start js2-ts-cursor
5559 js2-ts-lineno (1+ js2-ts-lineno)))
5560 ;; TODO: skip over format characters
5561 c)))
5562
5563 (defun js2-read-unicode-escape ()
5564 "Read a \\uNNNN sequence from the input.
5565 Assumes the ?\ and ?u have already been read.
5566 Returns the unicode character, or nil if it wasn't a valid character.
5567 Doesn't change the values of any scanner variables."
5568 ;; I really wish I knew a better way to do this, but I can't
5569 ;; find the Emacs function that takes a 16-bit int and converts
5570 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5571 ;; Have to first check that it's 4 hex characters or it may stop
5572 ;; the read early.
5573 (ignore-errors
5574 (let ((s (buffer-substring-no-properties js2-ts-cursor
5575 (+ 4 js2-ts-cursor))))
5576 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5577 (read (concat "?\\u" s))))))
5578
5579 (defun js2-match-char (test)
5580 "Consume and return next character if it matches TEST, a character.
5581 Returns nil and consumes nothing if TEST is not the next character."
5582 (let ((c (js2-get-char)))
5583 (if (eq c test)
5584 t
5585 (js2-unget-char)
5586 nil)))
5587
5588 (defun js2-peek-char ()
5589 (prog1
5590 (js2-get-char)
5591 (js2-unget-char)))
5592
5593 (defun js2-identifier-start-p (c)
5594 "Is C a valid start to an ES5 Identifier?
5595 See http://es5.github.io/#x7.6"
5596 (or
5597 (memq c '(?$ ?_))
5598 (memq (get-char-code-property c 'general-category)
5599 ;; Letters
5600 '(Lu Ll Lt Lm Lo Nl))))
5601
5602 (defun js2-identifier-part-p (c)
5603 "Is C a valid part of an ES5 Identifier?
5604 See http://es5.github.io/#x7.6"
5605 (or
5606 (memq c '(?$ ?_ ?\u200c ?\u200d))
5607 (memq (get-char-code-property c 'general-category)
5608 '(;; Letters
5609 Lu Ll Lt Lm Lo Nl
5610 ;; Combining Marks
5611 Mn Mc
5612 ;; Digits
5613 Nd
5614 ;; Connector Punctuation
5615 Pc))))
5616
5617 (defun js2-alpha-p (c)
5618 (cond ((and (<= ?A c) (<= c ?Z)) t)
5619 ((and (<= ?a c) (<= c ?z)) t)
5620 (t nil)))
5621
5622 (defsubst js2-digit-p (c)
5623 (and (<= ?0 c) (<= c ?9)))
5624
5625 (defun js2-js-space-p (c)
5626 (if (<= c 127)
5627 (memq c '(#x20 #x9 #xB #xC #xD))
5628 (or
5629 (eq c #xA0)
5630 ;; TODO: change this nil to check for Unicode space character
5631 nil)))
5632
5633 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5634
5635 (defun js2-skip-line ()
5636 "Skip to end of line."
5637 (while (not (memq (js2-get-char) js2-eol-chars)))
5638 (js2-unget-char)
5639 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5640
5641 (defun js2-init-scanner (&optional buf line)
5642 "Create token stream for BUF starting on LINE.
5643 BUF defaults to `current-buffer' and LINE defaults to 1.
5644
5645 A buffer can only have one scanner active at a time, which yields
5646 dramatically simpler code than using a defstruct. If you need to
5647 have simultaneous scanners in a buffer, copy the regions to scan
5648 into temp buffers."
5649 (with-current-buffer (or buf (current-buffer))
5650 (setq js2-ts-dirty-line nil
5651 js2-ts-hit-eof nil
5652 js2-ts-line-start 0
5653 js2-ts-lineno (or line 1)
5654 js2-ts-line-end-char -1
5655 js2-ts-cursor (point-min)
5656 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5657 js2-ti-tokens-cursor 0
5658 js2-ti-lookahead 0
5659 js2-ts-is-xml-attribute nil
5660 js2-ts-xml-is-tag-content nil
5661 js2-ts-xml-open-tags-count 0
5662 js2-ts-string-buffer nil)))
5663
5664 ;; This function uses the cached op, string and number fields in
5665 ;; TokenStream; if getToken has been called since the passed token
5666 ;; was scanned, the op or string printed may be incorrect.
5667 (defun js2-token-to-string (token)
5668 ;; Not sure where this function is used in Rhino. Not tested.
5669 (if (not js2-debug-print-trees)
5670 ""
5671 (let ((name (js2-tt-name token)))
5672 (cond
5673 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5674 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5675 (concat name " `" (js2-current-token-string) "'"))
5676 ((eq token js2-NUMBER)
5677 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5678 (t
5679 name)))))
5680
5681 (defconst js2-keywords
5682 '(break
5683 case catch class const continue
5684 debugger default delete do
5685 else extends export
5686 false finally for function
5687 if in instanceof import
5688 let
5689 new null
5690 return
5691 super switch
5692 this throw true try typeof
5693 var void
5694 while with
5695 yield))
5696
5697 ;; Token names aren't exactly the same as the keywords, unfortunately.
5698 ;; E.g. delete is js2-DELPROP.
5699 (defconst js2-kwd-tokens
5700 (let ((table (make-vector js2-num-tokens nil))
5701 (tokens
5702 (list js2-BREAK
5703 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5704 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5705 js2-ELSE js2-EXPORT
5706 js2-ELSE js2-EXTENDS js2-EXPORT
5707 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5708 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5709 js2-LET
5710 js2-NEW js2-NULL
5711 js2-RETURN
5712 js2-SUPER js2-SWITCH
5713 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5714 js2-VAR
5715 js2-WHILE js2-WITH
5716 js2-YIELD)))
5717 (dolist (i tokens)
5718 (aset table i 'font-lock-keyword-face))
5719 (aset table js2-STRING 'font-lock-string-face)
5720 (aset table js2-REGEXP 'font-lock-string-face)
5721 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5722 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5723 (aset table js2-COMMENT 'font-lock-comment-face)
5724 (aset table js2-THIS 'font-lock-builtin-face)
5725 (aset table js2-SUPER 'font-lock-builtin-face)
5726 (aset table js2-VOID 'font-lock-constant-face)
5727 (aset table js2-NULL 'font-lock-constant-face)
5728 (aset table js2-TRUE 'font-lock-constant-face)
5729 (aset table js2-FALSE 'font-lock-constant-face)
5730 (aset table js2-NOT 'font-lock-negation-char-face)
5731 table)
5732 "Vector whose values are non-nil for tokens that are keywords.
5733 The values are default faces to use for highlighting the keywords.")
5734
5735 ;; FIXME: Support strict mode-only future reserved words, after we know
5736 ;; which parts scopes are in strict mode, and which are not.
5737 (defconst js2-reserved-words '(class enum export extends import static super)
5738 "Future reserved keywords in ECMAScript 5.1.")
5739
5740 (defconst js2-keyword-names
5741 (let ((table (make-hash-table :test 'equal)))
5742 (cl-loop for k in js2-keywords
5743 do (puthash
5744 (symbol-name k) ; instanceof
5745 (intern (concat "js2-"
5746 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5747 table))
5748 table)
5749 "JavaScript keywords by name, mapped to their symbols.")
5750
5751 (defconst js2-reserved-word-names
5752 (let ((table (make-hash-table :test 'equal)))
5753 (cl-loop for k in js2-reserved-words
5754 do
5755 (puthash (symbol-name k) 'js2-RESERVED table))
5756 table)
5757 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5758
5759 (defun js2-collect-string (buf)
5760 "Convert BUF, a list of chars, to a string.
5761 Reverses BUF before converting."
5762 (if buf
5763 (apply #'string (nreverse buf))
5764 ""))
5765
5766 (defun js2-string-to-keyword (s)
5767 "Return token for S, a string, if S is a keyword or reserved word.
5768 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5769 (or (gethash s js2-keyword-names)
5770 (gethash s js2-reserved-word-names)))
5771
5772 (defsubst js2-ts-set-char-token-bounds (token)
5773 "Used when next token is one character."
5774 (setf (js2-token-beg token) (1- js2-ts-cursor)
5775 (js2-token-end token) js2-ts-cursor))
5776
5777 (defsubst js2-ts-return (token type)
5778 "Update the `end' and `type' slots of TOKEN,
5779 then throw `return' with value TYPE."
5780 (setf (js2-token-end token) js2-ts-cursor
5781 (js2-token-type token) type)
5782 (throw 'return type))
5783
5784 (defun js2-x-digit-to-int (c accumulator)
5785 "Build up a hex number.
5786 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5787 corresponding number. Otherwise return -1."
5788 (catch 'return
5789 (catch 'check
5790 ;; Use 0..9 < A..Z < a..z
5791 (cond
5792 ((<= c ?9)
5793 (cl-decf c ?0)
5794 (if (<= 0 c)
5795 (throw 'check nil)))
5796 ((<= c ?F)
5797 (when (<= ?A c)
5798 (cl-decf c (- ?A 10))
5799 (throw 'check nil)))
5800 ((<= c ?f)
5801 (when (<= ?a c)
5802 (cl-decf c (- ?a 10))
5803 (throw 'check nil))))
5804 (throw 'return -1))
5805 (logior c (lsh accumulator 4))))
5806
5807 (defun js2-get-token (&optional modifier)
5808 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5809 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5810 next saved token.
5811
5812 This function will not return a newline (js2-EOL) - instead, it
5813 gobbles newlines until it finds a non-newline token. Call
5814 `js2-peek-token-or-eol' when you care about newlines.
5815
5816 This function will also not return a js2-COMMENT. Instead, it
5817 records comments found in `js2-scanned-comments'. If the token
5818 returned by this function immediately follows a jsdoc comment,
5819 the token is flagged as such."
5820 (if (zerop js2-ti-lookahead)
5821 (js2-get-token-internal modifier)
5822 (cl-decf js2-ti-lookahead)
5823 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5824 (let ((tt (js2-current-token-type)))
5825 (cl-assert (not (= tt js2-EOL)))
5826 tt)))
5827
5828 (defun js2-unget-token ()
5829 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5830 (cl-incf js2-ti-lookahead)
5831 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5832
5833 (defun js2-get-token-internal (modifier)
5834 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5835 (tt (js2-token-type token))
5836 saw-eol
5837 face)
5838 ;; process comments
5839 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5840 (if (= tt js2-EOL)
5841 (setq saw-eol t)
5842 (setq saw-eol nil)
5843 (when js2-record-comments
5844 (js2-record-comment token)))
5845 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5846 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5847 tt (js2-token-type token)))
5848
5849 (when saw-eol
5850 (setf (js2-token-follows-eol-p token) t))
5851
5852 ;; perform lexical fontification as soon as token is scanned
5853 (when js2-parse-ide-mode
5854 (cond
5855 ((cl-minusp tt)
5856 (js2-record-face 'js2-error token))
5857 ((setq face (aref js2-kwd-tokens tt))
5858 (js2-record-face face token))
5859 ((and (= tt js2-NAME)
5860 (equal (js2-token-string token) "undefined"))
5861 (js2-record-face 'font-lock-constant-face token))))
5862 tt))
5863
5864 (defsubst js2-string-to-number (str base)
5865 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5866 (condition-case nil
5867 (string-to-number str base)
5868 (overflow-error -1)))
5869
5870 (defun js2-get-token-internal-1 (modifier)
5871 "Return next JavaScript token type, an int such as js2-RETURN.
5872 During operation, creates an instance of `js2-token' struct, sets
5873 its relevant fields and puts it into `js2-ti-tokens'."
5874 (let (identifier-start
5875 is-unicode-escape-start c
5876 contains-escape escape-val str result base
5877 quote-char look-for-slash continue tt
5878 (token (js2-new-token 0)))
5879 (setq
5880 tt
5881 (catch 'return
5882 (when (eq modifier 'TEMPLATE_TAIL)
5883 (setf (js2-token-beg token) (1- js2-ts-cursor))
5884 (throw 'return (js2-get-string-or-template-token ?` token)))
5885 (while t
5886 ;; Eat whitespace, possibly sensitive to newlines.
5887 (setq continue t)
5888 (while continue
5889 (setq c (js2-get-char))
5890 (cond
5891 ((eq c js2-EOF_CHAR)
5892 (js2-unget-char)
5893 (js2-ts-set-char-token-bounds token)
5894 (throw 'return js2-EOF))
5895 ((eq c ?\n)
5896 (js2-ts-set-char-token-bounds token)
5897 (setq js2-ts-dirty-line nil)
5898 (throw 'return js2-EOL))
5899 ((not (js2-js-space-p c))
5900 (if (/= c ?-) ; in case end of HTML comment
5901 (setq js2-ts-dirty-line t))
5902 (setq continue nil))))
5903 ;; Assume the token will be 1 char - fixed up below.
5904 (js2-ts-set-char-token-bounds token)
5905 (when (eq c ?@)
5906 (throw 'return js2-XMLATTR))
5907 ;; identifier/keyword/instanceof?
5908 ;; watch out for starting with a <backslash>
5909 (cond
5910 ((eq c ?\\)
5911 (setq c (js2-get-char))
5912 (if (eq c ?u)
5913 (setq identifier-start t
5914 is-unicode-escape-start t
5915 js2-ts-string-buffer nil)
5916 (setq identifier-start nil)
5917 (js2-unget-char)
5918 (setq c ?\\)))
5919 (t
5920 (when (setq identifier-start (js2-identifier-start-p c))
5921 (setq js2-ts-string-buffer nil)
5922 (js2-add-to-string c))))
5923 (when identifier-start
5924 (setq contains-escape is-unicode-escape-start)
5925 (catch 'break
5926 (while t
5927 (if is-unicode-escape-start
5928 ;; strictly speaking we should probably push-back
5929 ;; all the bad characters if the <backslash>uXXXX
5930 ;; sequence is malformed. But since there isn't a
5931 ;; correct context(is there?) for a bad Unicode
5932 ;; escape sequence in an identifier, we can report
5933 ;; an error here.
5934 (progn
5935 (setq escape-val 0)
5936 (dotimes (_ 4)
5937 (setq c (js2-get-char)
5938 escape-val (js2-x-digit-to-int c escape-val))
5939 ;; Next check takes care of c < 0 and bad escape
5940 (if (cl-minusp escape-val)
5941 (throw 'break nil)))
5942 (if (cl-minusp escape-val)
5943 (js2-report-scan-error "msg.invalid.escape" t))
5944 (js2-add-to-string escape-val)
5945 (setq is-unicode-escape-start nil))
5946 (setq c (js2-get-char))
5947 (cond
5948 ((eq c ?\\)
5949 (setq c (js2-get-char))
5950 (if (eq c ?u)
5951 (setq is-unicode-escape-start t
5952 contains-escape t)
5953 (js2-report-scan-error "msg.illegal.character" t)))
5954 (t
5955 (if (or (eq c js2-EOF_CHAR)
5956 (not (js2-identifier-part-p c)))
5957 (throw 'break nil))
5958 (js2-add-to-string c))))))
5959 (js2-unget-char)
5960 (setf str (js2-collect-string js2-ts-string-buffer)
5961 (js2-token-end token) js2-ts-cursor)
5962 ;; FIXME: Invalid in ES5 and ES6, see
5963 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5964 ;; Probably should just drop this conditional.
5965 (unless contains-escape
5966 ;; OPT we shouldn't have to make a string (object!) to
5967 ;; check if it's a keyword.
5968 ;; Return the corresponding token if it's a keyword
5969 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5970 (setq result (js2-string-to-keyword str)))
5971 (if (and (< js2-language-version 170)
5972 (memq result '(js2-LET js2-YIELD)))
5973 ;; LET and YIELD are tokens only in 1.7 and later
5974 (setq result 'js2-NAME))
5975 (when (eq result 'js2-RESERVED)
5976 (setf (js2-token-string token) str))
5977 (throw 'return (js2-tt-code result))))
5978 ;; If we want to intern these as Rhino does, just use (intern str)
5979 (setf (js2-token-string token) str)
5980 (throw 'return js2-NAME)) ; end identifier/kwd check
5981 ;; is it a number?
5982 (when (or (js2-digit-p c)
5983 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5984 (setq js2-ts-string-buffer nil
5985 base 10)
5986 (when (eq c ?0)
5987 (setq c (js2-get-char))
5988 (cond
5989 ((or (eq c ?x) (eq c ?X))
5990 (setq base 16)
5991 (setq c (js2-get-char)))
5992 ((and (or (eq c ?b) (eq c ?B))
5993 (>= js2-language-version 200))
5994 (setq base 2)
5995 (setq c (js2-get-char)))
5996 ((and (or (eq c ?o) (eq c ?O))
5997 (>= js2-language-version 200))
5998 (setq base 8)
5999 (setq c (js2-get-char)))
6000 ((js2-digit-p c)
6001 (setq base 'maybe-8))
6002 (t
6003 (js2-add-to-string ?0))))
6004 (cond
6005 ((eq base 16)
6006 (if (> 0 (js2-x-digit-to-int c 0))
6007 (js2-report-scan-error "msg.missing.hex.digits")
6008 (while (<= 0 (js2-x-digit-to-int c 0))
6009 (js2-add-to-string c)
6010 (setq c (js2-get-char)))))
6011 ((eq base 2)
6012 (if (not (memq c '(?0 ?1)))
6013 (js2-report-scan-error "msg.missing.binary.digits")
6014 (while (memq c '(?0 ?1))
6015 (js2-add-to-string c)
6016 (setq c (js2-get-char)))))
6017 ((eq base 8)
6018 (if (or (> ?0 c) (< ?7 c))
6019 (js2-report-scan-error "msg.missing.octal.digits")
6020 (while (and (<= ?0 c) (>= ?7 c))
6021 (js2-add-to-string c)
6022 (setq c (js2-get-char)))))
6023 (t
6024 (while (and (<= ?0 c) (<= c ?9))
6025 ;; We permit 08 and 09 as decimal numbers, which
6026 ;; makes our behavior a superset of the ECMA
6027 ;; numeric grammar. We might not always be so
6028 ;; permissive, so we warn about it.
6029 (when (and (eq base 'maybe-8) (>= c ?8))
6030 (js2-report-warning "msg.bad.octal.literal"
6031 (if (eq c ?8) "8" "9"))
6032 (setq base 10))
6033 (js2-add-to-string c)
6034 (setq c (js2-get-char)))
6035 (when (eq base 'maybe-8)
6036 (setq base 8))))
6037 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6038 (when (eq c ?.)
6039 (cl-loop do
6040 (js2-add-to-string c)
6041 (setq c (js2-get-char))
6042 while (js2-digit-p c)))
6043 (when (memq c '(?e ?E))
6044 (js2-add-to-string c)
6045 (setq c (js2-get-char))
6046 (when (memq c '(?+ ?-))
6047 (js2-add-to-string c)
6048 (setq c (js2-get-char)))
6049 (unless (js2-digit-p c)
6050 (js2-report-scan-error "msg.missing.exponent" t))
6051 (cl-loop do
6052 (js2-add-to-string c)
6053 (setq c (js2-get-char))
6054 while (js2-digit-p c))))
6055 (js2-unget-char)
6056 (let ((str (js2-set-string-from-buffer token)))
6057 (setf (js2-token-number token)
6058 (js2-string-to-number str base)))
6059 (throw 'return js2-NUMBER))
6060 ;; is it a string?
6061 (when (or (memq c '(?\" ?\'))
6062 (and (>= js2-language-version 200)
6063 (= c ?`)))
6064 (throw 'return
6065 (js2-get-string-or-template-token c token)))
6066 (js2-ts-return token
6067 (cl-case c
6068 (?\;
6069 (throw 'return js2-SEMI))
6070 (?\[
6071 (throw 'return js2-LB))
6072 (?\]
6073 (throw 'return js2-RB))
6074 (?{
6075 (throw 'return js2-LC))
6076 (?}
6077 (throw 'return js2-RC))
6078 (?\(
6079 (throw 'return js2-LP))
6080 (?\)
6081 (throw 'return js2-RP))
6082 (?,
6083 (throw 'return js2-COMMA))
6084 (??
6085 (throw 'return js2-HOOK))
6086 (?:
6087 (if (js2-match-char ?:)
6088 js2-COLONCOLON
6089 (throw 'return js2-COLON)))
6090 (?.
6091 (if (js2-match-char ?.)
6092 (if (js2-match-char ?.)
6093 js2-TRIPLEDOT js2-DOTDOT)
6094 (if (js2-match-char ?\()
6095 js2-DOTQUERY
6096 (throw 'return js2-DOT))))
6097 (?|
6098 (if (js2-match-char ?|)
6099 (throw 'return js2-OR)
6100 (if (js2-match-char ?=)
6101 js2-ASSIGN_BITOR
6102 (throw 'return js2-BITOR))))
6103 (?^
6104 (if (js2-match-char ?=)
6105 js2-ASSIGN_BITOR
6106 (throw 'return js2-BITXOR)))
6107 (?&
6108 (if (js2-match-char ?&)
6109 (throw 'return js2-AND)
6110 (if (js2-match-char ?=)
6111 js2-ASSIGN_BITAND
6112 (throw 'return js2-BITAND))))
6113 (?=
6114 (if (js2-match-char ?=)
6115 (if (js2-match-char ?=)
6116 js2-SHEQ
6117 (throw 'return js2-EQ))
6118 (if (js2-match-char ?>)
6119 (js2-ts-return token js2-ARROW)
6120 (throw 'return js2-ASSIGN))))
6121 (?!
6122 (if (js2-match-char ?=)
6123 (if (js2-match-char ?=)
6124 js2-SHNE
6125 js2-NE)
6126 (throw 'return js2-NOT)))
6127 (?<
6128 ;; NB:treat HTML begin-comment as comment-till-eol
6129 (when (js2-match-char ?!)
6130 (when (js2-match-char ?-)
6131 (when (js2-match-char ?-)
6132 (js2-skip-line)
6133 (setf (js2-token-comment-type (js2-current-token)) 'html)
6134 (throw 'return js2-COMMENT)))
6135 (js2-unget-char))
6136 (if (js2-match-char ?<)
6137 (if (js2-match-char ?=)
6138 js2-ASSIGN_LSH
6139 js2-LSH)
6140 (if (js2-match-char ?=)
6141 js2-LE
6142 (throw 'return js2-LT))))
6143 (?>
6144 (if (js2-match-char ?>)
6145 (if (js2-match-char ?>)
6146 (if (js2-match-char ?=)
6147 js2-ASSIGN_URSH
6148 js2-URSH)
6149 (if (js2-match-char ?=)
6150 js2-ASSIGN_RSH
6151 js2-RSH))
6152 (if (js2-match-char ?=)
6153 js2-GE
6154 (throw 'return js2-GT))))
6155 (?*
6156 (if (js2-match-char ?=)
6157 js2-ASSIGN_MUL
6158 (throw 'return js2-MUL)))
6159 (?/
6160 ;; is it a // comment?
6161 (when (js2-match-char ?/)
6162 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6163 (js2-skip-line)
6164 (setf (js2-token-comment-type token) 'line)
6165 ;; include newline so highlighting goes to end of
6166 ;; window, if there actually is a newline; if we
6167 ;; hit eof, then implicitly there isn't
6168 (unless js2-ts-hit-eof
6169 (cl-incf (js2-token-end token)))
6170 (throw 'return js2-COMMENT))
6171 ;; is it a /* comment?
6172 (when (js2-match-char ?*)
6173 (setf look-for-slash nil
6174 (js2-token-beg token) (- js2-ts-cursor 2)
6175 (js2-token-comment-type token)
6176 (if (js2-match-char ?*)
6177 (progn
6178 (setq look-for-slash t)
6179 'jsdoc)
6180 'block))
6181 (while t
6182 (setq c (js2-get-char))
6183 (cond
6184 ((eq c js2-EOF_CHAR)
6185 (setf (js2-token-end token) (1- js2-ts-cursor))
6186 (js2-report-error "msg.unterminated.comment")
6187 (throw 'return js2-COMMENT))
6188 ((eq c ?*)
6189 (setq look-for-slash t))
6190 ((eq c ?/)
6191 (if look-for-slash
6192 (js2-ts-return token js2-COMMENT)))
6193 (t
6194 (setf look-for-slash nil
6195 (js2-token-end token) js2-ts-cursor)))))
6196 (if (js2-match-char ?=)
6197 js2-ASSIGN_DIV
6198 (throw 'return js2-DIV)))
6199 (?#
6200 (when js2-skip-preprocessor-directives
6201 (js2-skip-line)
6202 (setf (js2-token-comment-type token) 'preprocessor
6203 (js2-token-end token) js2-ts-cursor)
6204 (throw 'return js2-COMMENT))
6205 (throw 'return js2-ERROR))
6206 (?%
6207 (if (js2-match-char ?=)
6208 js2-ASSIGN_MOD
6209 (throw 'return js2-MOD)))
6210 (?~
6211 (throw 'return js2-BITNOT))
6212 (?+
6213 (if (js2-match-char ?=)
6214 js2-ASSIGN_ADD
6215 (if (js2-match-char ?+)
6216 js2-INC
6217 (throw 'return js2-ADD))))
6218 (?-
6219 (cond
6220 ((js2-match-char ?=)
6221 (setq c js2-ASSIGN_SUB))
6222 ((js2-match-char ?-)
6223 (unless js2-ts-dirty-line
6224 ;; treat HTML end-comment after possible whitespace
6225 ;; after line start as comment-until-eol
6226 (when (js2-match-char ?>)
6227 (js2-skip-line)
6228 (setf (js2-token-comment-type (js2-current-token)) 'html)
6229 (throw 'return js2-COMMENT)))
6230 (setq c js2-DEC))
6231 (t
6232 (setq c js2-SUB)))
6233 (setq js2-ts-dirty-line t)
6234 c)
6235 (otherwise
6236 (js2-report-scan-error "msg.illegal.character")))))))
6237 (setf (js2-token-type token) tt)
6238 token))
6239
6240 (defun js2-get-string-or-template-token (quote-char token)
6241 ;; We attempt to accumulate a string the fast way, by
6242 ;; building it directly out of the reader. But if there
6243 ;; are any escaped characters in the string, we revert to
6244 ;; building it out of a string buffer.
6245 (let ((c (js2-get-char))
6246 js2-ts-string-buffer
6247 nc c1 val escape-val)
6248 (catch 'break
6249 (while (/= c quote-char)
6250 (catch 'continue
6251 (when (eq c js2-EOF_CHAR)
6252 (js2-unget-char)
6253 (js2-report-error "msg.unterminated.string.lit")
6254 (throw 'break nil))
6255 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6256 (js2-unget-char)
6257 (js2-report-error "msg.unterminated.string.lit")
6258 (throw 'break nil))
6259 (when (eq c ?\\)
6260 ;; We've hit an escaped character
6261 (setq c (js2-get-char))
6262 (cl-case c
6263 (?b (setq c ?\b))
6264 (?f (setq c ?\f))
6265 (?n (setq c ?\n))
6266 (?r (setq c ?\r))
6267 (?t (setq c ?\t))
6268 (?v (setq c ?\v))
6269 (?u
6270 (setq c1 (js2-read-unicode-escape))
6271 (if js2-parse-ide-mode
6272 (if c1
6273 (progn
6274 ;; just copy the string in IDE-mode
6275 (js2-add-to-string ?\\)
6276 (js2-add-to-string ?u)
6277 (dotimes (_ 3)
6278 (js2-add-to-string (js2-get-char)))
6279 (setq c (js2-get-char))) ; added at end of loop
6280 ;; flag it as an invalid escape
6281 (js2-report-warning "msg.invalid.escape"
6282 nil (- js2-ts-cursor 2) 6))
6283 ;; Get 4 hex digits; if the u escape is not
6284 ;; followed by 4 hex digits, use 'u' + the
6285 ;; literal character sequence that follows.
6286 (js2-add-to-string ?u)
6287 (setq escape-val 0)
6288 (dotimes (_ 4)
6289 (setq c (js2-get-char)
6290 escape-val (js2-x-digit-to-int c escape-val))
6291 (if (cl-minusp escape-val)
6292 (throw 'continue nil))
6293 (js2-add-to-string c))
6294 ;; prepare for replace of stored 'u' sequence by escape value
6295 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6296 c escape-val)))
6297 (?x
6298 ;; Get 2 hex digits, defaulting to 'x'+literal
6299 ;; sequence, as above.
6300 (setq c (js2-get-char)
6301 escape-val (js2-x-digit-to-int c 0))
6302 (if (cl-minusp escape-val)
6303 (progn
6304 (js2-add-to-string ?x)
6305 (throw 'continue nil))
6306 (setq c1 c
6307 c (js2-get-char)
6308 escape-val (js2-x-digit-to-int c escape-val))
6309 (if (cl-minusp escape-val)
6310 (progn
6311 (js2-add-to-string ?x)
6312 (js2-add-to-string c1)
6313 (throw 'continue nil))
6314 ;; got 2 hex digits
6315 (setq c escape-val))))
6316 (?\n
6317 ;; Remove line terminator after escape to follow
6318 ;; SpiderMonkey and C/C++
6319 (setq c (js2-get-char))
6320 (throw 'continue nil))
6321 (t
6322 (when (and (<= ?0 c) (< c ?8))
6323 (setq val (- c ?0)
6324 c (js2-get-char))
6325 (when (and (<= ?0 c) (< c ?8))
6326 (setq val (- (+ (* 8 val) c) ?0)
6327 c (js2-get-char))
6328 (when (and (<= ?0 c)
6329 (< c ?8)
6330 (< val #o37))
6331 ;; c is 3rd char of octal sequence only
6332 ;; if the resulting val <= 0377
6333 (setq val (- (+ (* 8 val) c) ?0)
6334 c (js2-get-char))))
6335 (js2-unget-char)
6336 (setq c val)))))
6337 (when (and (eq quote-char ?`) (eq c ?$))
6338 (when (eq (setq nc (js2-get-char)) ?\{)
6339 (throw 'break nil))
6340 (js2-unget-char))
6341 (js2-add-to-string c)
6342 (setq c (js2-get-char)))))
6343 (js2-set-string-from-buffer token)
6344 (if (not (eq quote-char ?`))
6345 js2-STRING
6346 (if (and (eq c ?$) (eq nc ?\{))
6347 js2-TEMPLATE_HEAD
6348 js2-NO_SUBS_TEMPLATE))))
6349
6350 (defun js2-read-regexp (start-tt)
6351 "Called by parser when it gets / or /= in literal context."
6352 (let (c err
6353 in-class ; inside a '[' .. ']' character-class
6354 flags
6355 (continue t)
6356 (token (js2-new-token 0)))
6357 (setq js2-ts-string-buffer nil)
6358 (if (eq start-tt js2-ASSIGN_DIV)
6359 ;; mis-scanned /=
6360 (js2-add-to-string ?=)
6361 (if (not (eq start-tt js2-DIV))
6362 (error "failed assertion")))
6363 (while (and (not err)
6364 (or (/= (setq c (js2-get-char)) ?/)
6365 in-class))
6366 (cond
6367 ((or (= c ?\n)
6368 (= c js2-EOF_CHAR))
6369 (setf (js2-token-end token) (1- js2-ts-cursor)
6370 err t
6371 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6372 (js2-report-error "msg.unterminated.re.lit"))
6373 (t (cond
6374 ((= c ?\\)
6375 (js2-add-to-string c)
6376 (setq c (js2-get-char)))
6377 ((= c ?\[)
6378 (setq in-class t))
6379 ((= c ?\])
6380 (setq in-class nil)))
6381 (js2-add-to-string c))))
6382 (unless err
6383 (while continue
6384 (cond
6385 ((js2-match-char ?g)
6386 (push ?g flags))
6387 ((js2-match-char ?i)
6388 (push ?i flags))
6389 ((js2-match-char ?m)
6390 (push ?m flags))
6391 ((and (js2-match-char ?u)
6392 (>= js2-language-version 200))
6393 (push ?u flags))
6394 ((and (js2-match-char ?y)
6395 (>= js2-language-version 200))
6396 (push ?y flags))
6397 (t
6398 (setq continue nil))))
6399 (if (js2-alpha-p (js2-peek-char))
6400 (js2-report-scan-error "msg.invalid.re.flag" t
6401 js2-ts-cursor 1))
6402 (js2-set-string-from-buffer token))
6403 (js2-collect-string flags)))
6404
6405 (defun js2-get-first-xml-token ()
6406 (setq js2-ts-xml-open-tags-count 0
6407 js2-ts-is-xml-attribute nil
6408 js2-ts-xml-is-tag-content nil)
6409 (js2-unget-char)
6410 (js2-get-next-xml-token))
6411
6412 (defun js2-xml-discard-string (token)
6413 "Throw away the string in progress and flag an XML parse error."
6414 (setf js2-ts-string-buffer nil
6415 (js2-token-string token) nil)
6416 (js2-report-scan-error "msg.XML.bad.form" t))
6417
6418 (defun js2-get-next-xml-token ()
6419 (setq js2-ts-string-buffer nil) ; for recording the XML
6420 (let ((token (js2-new-token 0))
6421 c result)
6422 (setq result
6423 (catch 'return
6424 (while t
6425 (setq c (js2-get-char))
6426 (cond
6427 ((= c js2-EOF_CHAR)
6428 (throw 'return js2-ERROR))
6429 (js2-ts-xml-is-tag-content
6430 (cl-case c
6431 (?>
6432 (js2-add-to-string c)
6433 (setq js2-ts-xml-is-tag-content nil
6434 js2-ts-is-xml-attribute nil))
6435 (?/
6436 (js2-add-to-string c)
6437 (when (eq ?> (js2-peek-char))
6438 (setq c (js2-get-char))
6439 (js2-add-to-string c)
6440 (setq js2-ts-xml-is-tag-content nil)
6441 (cl-decf js2-ts-xml-open-tags-count)))
6442 (?{
6443 (js2-unget-char)
6444 (js2-set-string-from-buffer token)
6445 (throw 'return js2-XML))
6446 ((?\' ?\")
6447 (js2-add-to-string c)
6448 (unless (js2-read-quoted-string c token)
6449 (throw 'return js2-ERROR)))
6450 (?=
6451 (js2-add-to-string c)
6452 (setq js2-ts-is-xml-attribute t))
6453 ((? ?\t ?\r ?\n)
6454 (js2-add-to-string c))
6455 (t
6456 (js2-add-to-string c)
6457 (setq js2-ts-is-xml-attribute nil)))
6458 (when (and (not js2-ts-xml-is-tag-content)
6459 (zerop js2-ts-xml-open-tags-count))
6460 (js2-set-string-from-buffer token)
6461 (throw 'return js2-XMLEND)))
6462 (t
6463 ;; else not tag content
6464 (cl-case c
6465 (?<
6466 (js2-add-to-string c)
6467 (setq c (js2-peek-char))
6468 (cl-case c
6469 (?!
6470 (setq c (js2-get-char)) ;; skip !
6471 (js2-add-to-string c)
6472 (setq c (js2-peek-char))
6473 (cl-case c
6474 (?-
6475 (setq c (js2-get-char)) ;; skip -
6476 (js2-add-to-string c)
6477 (if (eq c ?-)
6478 (progn
6479 (js2-add-to-string c)
6480 (unless (js2-read-xml-comment token)
6481 (throw 'return js2-ERROR)))
6482 (js2-xml-discard-string token)
6483 (throw 'return js2-ERROR)))
6484 (?\[
6485 (setq c (js2-get-char)) ;; skip [
6486 (js2-add-to-string c)
6487 (if (and (= (js2-get-char) ?C)
6488 (= (js2-get-char) ?D)
6489 (= (js2-get-char) ?A)
6490 (= (js2-get-char) ?T)
6491 (= (js2-get-char) ?A)
6492 (= (js2-get-char) ?\[))
6493 (progn
6494 (js2-add-to-string ?C)
6495 (js2-add-to-string ?D)
6496 (js2-add-to-string ?A)
6497 (js2-add-to-string ?T)
6498 (js2-add-to-string ?A)
6499 (js2-add-to-string ?\[)
6500 (unless (js2-read-cdata token)
6501 (throw 'return js2-ERROR)))
6502 (js2-xml-discard-string token)
6503 (throw 'return js2-ERROR)))
6504 (t
6505 (unless (js2-read-entity token)
6506 (throw 'return js2-ERROR))))
6507 ;; Allow bare CDATA section, e.g.:
6508 ;; let xml = <![CDATA[ foo bar baz ]]>;
6509 (when (zerop js2-ts-xml-open-tags-count)
6510 (throw 'return js2-XMLEND)))
6511 (??
6512 (setq c (js2-get-char)) ;; skip ?
6513 (js2-add-to-string c)
6514 (unless (js2-read-PI token)
6515 (throw 'return js2-ERROR)))
6516 (?/
6517 ;; end tag
6518 (setq c (js2-get-char)) ;; skip /
6519 (js2-add-to-string c)
6520 (when (zerop js2-ts-xml-open-tags-count)
6521 (js2-xml-discard-string token)
6522 (throw 'return js2-ERROR))
6523 (setq js2-ts-xml-is-tag-content t)
6524 (cl-decf js2-ts-xml-open-tags-count))
6525 (t
6526 ;; start tag
6527 (setq js2-ts-xml-is-tag-content t)
6528 (cl-incf js2-ts-xml-open-tags-count))))
6529 (?{
6530 (js2-unget-char)
6531 (js2-set-string-from-buffer token)
6532 (throw 'return js2-XML))
6533 (t
6534 (js2-add-to-string c))))))))
6535 (setf (js2-token-end token) js2-ts-cursor)
6536 (setf (js2-token-type token) result)
6537 result))
6538
6539 (defun js2-read-quoted-string (quote token)
6540 (let (c)
6541 (catch 'return
6542 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6543 (js2-add-to-string c)
6544 (if (eq c quote)
6545 (throw 'return t)))
6546 (js2-xml-discard-string token) ;; throw away string in progress
6547 nil)))
6548
6549 (defun js2-read-xml-comment (token)
6550 (let ((c (js2-get-char)))
6551 (catch 'return
6552 (while (/= c js2-EOF_CHAR)
6553 (catch 'continue
6554 (js2-add-to-string c)
6555 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6556 (setq c (js2-get-char))
6557 (js2-add-to-string c)
6558 (if (eq (js2-peek-char) ?>)
6559 (progn
6560 (setq c (js2-get-char)) ;; skip >
6561 (js2-add-to-string c)
6562 (throw 'return t))
6563 (throw 'continue nil)))
6564 (setq c (js2-get-char))))
6565 (js2-xml-discard-string token)
6566 nil)))
6567
6568 (defun js2-read-cdata (token)
6569 (let ((c (js2-get-char)))
6570 (catch 'return
6571 (while (/= c js2-EOF_CHAR)
6572 (catch 'continue
6573 (js2-add-to-string c)
6574 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6575 (setq c (js2-get-char))
6576 (js2-add-to-string c)
6577 (if (eq (js2-peek-char) ?>)
6578 (progn
6579 (setq c (js2-get-char)) ;; Skip >
6580 (js2-add-to-string c)
6581 (throw 'return t))
6582 (throw 'continue nil)))
6583 (setq c (js2-get-char))))
6584 (js2-xml-discard-string token)
6585 nil)))
6586
6587 (defun js2-read-entity (token)
6588 (let ((decl-tags 1)
6589 c)
6590 (catch 'return
6591 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6592 (js2-add-to-string c)
6593 (cl-case c
6594 (?<
6595 (cl-incf decl-tags))
6596 (?>
6597 (cl-decf decl-tags)
6598 (if (zerop decl-tags)
6599 (throw 'return t)))))
6600 (js2-xml-discard-string token)
6601 nil)))
6602
6603 (defun js2-read-PI (token)
6604 "Scan an XML processing instruction."
6605 (let (c)
6606 (catch 'return
6607 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6608 (js2-add-to-string c)
6609 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6610 (setq c (js2-get-char)) ;; Skip >
6611 (js2-add-to-string c)
6612 (throw 'return t)))
6613 (js2-xml-discard-string token)
6614 nil)))
6615
6616 ;;; Highlighting
6617
6618 (defun js2-set-face (beg end face &optional record)
6619 "Fontify a region. If RECORD is non-nil, record for later."
6620 (when (cl-plusp js2-highlight-level)
6621 (setq beg (min (point-max) beg)
6622 beg (max (point-min) beg)
6623 end (min (point-max) end)
6624 end (max (point-min) end))
6625 (if record
6626 (push (list beg end face) js2-mode-fontifications)
6627 (put-text-property beg end 'font-lock-face face))))
6628
6629 (defsubst js2-clear-face (beg end)
6630 (remove-text-properties beg end '(font-lock-face nil
6631 help-echo nil
6632 point-entered nil
6633 c-in-sws nil)))
6634
6635 (defconst js2-ecma-global-props
6636 (concat "^"
6637 (regexp-opt
6638 '("Infinity" "NaN" "undefined" "arguments") t)
6639 "$")
6640 "Value properties of the Ecma-262 Global Object.
6641 Shown at or above `js2-highlight-level' 2.")
6642
6643 ;; might want to add the name "arguments" to this list?
6644 (defconst js2-ecma-object-props
6645 (concat "^"
6646 (regexp-opt
6647 '("prototype" "__proto__" "__parent__") t)
6648 "$")
6649 "Value properties of the Ecma-262 Object constructor.
6650 Shown at or above `js2-highlight-level' 2.")
6651
6652 (defconst js2-ecma-global-funcs
6653 (concat
6654 "^"
6655 (regexp-opt
6656 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6657 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6658 "$")
6659 "Function properties of the Ecma-262 Global object.
6660 Shown at or above `js2-highlight-level' 2.")
6661
6662 (defconst js2-ecma-number-props
6663 (concat "^"
6664 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6665 "NEGATIVE_INFINITY"
6666 "POSITIVE_INFINITY") t)
6667 "$")
6668 "Properties of the Ecma-262 Number constructor.
6669 Shown at or above `js2-highlight-level' 2.")
6670
6671 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6672 "Properties of the Ecma-262 Date constructor.
6673 Shown at or above `js2-highlight-level' 2.")
6674
6675 (defconst js2-ecma-math-props
6676 (concat "^"
6677 (regexp-opt
6678 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6679 t)
6680 "$")
6681 "Properties of the Ecma-262 Math object.
6682 Shown at or above `js2-highlight-level' 2.")
6683
6684 (defconst js2-ecma-math-funcs
6685 (concat "^"
6686 (regexp-opt
6687 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6688 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6689 "$")
6690 "Function properties of the Ecma-262 Math object.
6691 Shown at or above `js2-highlight-level' 2.")
6692
6693 (defconst js2-ecma-function-props
6694 (concat
6695 "^"
6696 (regexp-opt
6697 '(;; properties of the Object prototype object
6698 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6699 "toLocaleString" "toString" "valueOf"
6700 ;; properties of the Function prototype object
6701 "apply" "call"
6702 ;; properties of the Array prototype object
6703 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6704 "splice" "unshift"
6705 ;; properties of the String prototype object
6706 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6707 "localeCompare" "match" "replace" "search" "split" "substring"
6708 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6709 "toUpperCase"
6710 ;; properties of the Number prototype object
6711 "toExponential" "toFixed" "toPrecision"
6712 ;; properties of the Date prototype object
6713 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6714 "getMinutes" "getMonth" "getSeconds" "getTime"
6715 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6716 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6717 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6718 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6719 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6720 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6721 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6722 "toTimeString" "toUTCString"
6723 ;; properties of the RegExp prototype object
6724 "exec" "test"
6725 ;; properties of the JSON prototype object
6726 "parse" "stringify"
6727 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6728 "toSource" "__defineGetter__" "__defineSetter__"
6729 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6730 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6731 t)
6732 "$")
6733 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6734 Shown at or above `js2-highlight-level' 3.")
6735
6736 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6737 (let ((target-name (and target
6738 (js2-name-node-p target)
6739 (js2-name-node-name target)))
6740 (prop-name (if prop (js2-name-node-name prop)))
6741 (level2 (>= js2-highlight-level 2))
6742 (level3 (>= js2-highlight-level 3)))
6743 (when level2
6744 (let ((face
6745 (if call-p
6746 (cond
6747 ((and target prop)
6748 (cond
6749 ((and level3 (string-match js2-ecma-function-props prop-name))
6750 'font-lock-builtin-face)
6751 ((and target-name prop)
6752 (cond
6753 ((string= target-name "Date")
6754 (if (string-match js2-ecma-date-props prop-name)
6755 'font-lock-builtin-face))
6756 ((string= target-name "Math")
6757 (if (string-match js2-ecma-math-funcs prop-name)
6758 'font-lock-builtin-face))))))
6759 (prop
6760 (if (string-match js2-ecma-global-funcs prop-name)
6761 'font-lock-builtin-face)))
6762 (cond
6763 ((and target prop)
6764 (cond
6765 ((string= target-name "Number")
6766 (if (string-match js2-ecma-number-props prop-name)
6767 'font-lock-constant-face))
6768 ((string= target-name "Math")
6769 (if (string-match js2-ecma-math-props prop-name)
6770 'font-lock-constant-face))))
6771 (prop
6772 (if (string-match js2-ecma-object-props prop-name)
6773 'font-lock-constant-face))))))
6774 (when face
6775 (let ((pos (+ (js2-node-pos parent) ; absolute
6776 (js2-node-pos prop)))) ; relative
6777 (js2-set-face pos
6778 (+ pos (js2-node-len prop))
6779 face 'record)))))))
6780
6781 (defun js2-parse-highlight-member-expr-node (node)
6782 "Perform syntax highlighting of EcmaScript built-in properties.
6783 The variable `js2-highlight-level' governs this highlighting."
6784 (let (face target prop name pos end parent call-p callee)
6785 (cond
6786 ;; case 1: simple name, e.g. foo
6787 ((js2-name-node-p node)
6788 (setq name (js2-name-node-name node))
6789 ;; possible for name to be nil in rare cases - saw it when
6790 ;; running js2-mode on an elisp buffer. Might as well try to
6791 ;; make it so js2-mode never barfs.
6792 (when name
6793 (setq face (if (string-match js2-ecma-global-props name)
6794 'font-lock-constant-face))
6795 (when face
6796 (setq pos (js2-node-pos node)
6797 end (+ pos (js2-node-len node)))
6798 (js2-set-face pos end face 'record))))
6799 ;; case 2: property access or function call
6800 ((or (js2-prop-get-node-p node)
6801 ;; highlight function call if expr is a prop-get node
6802 ;; or a plain name (i.e. unqualified function call)
6803 (and (setq call-p (js2-call-node-p node))
6804 (setq callee (js2-call-node-target node)) ; separate setq!
6805 (or (js2-prop-get-node-p callee)
6806 (js2-name-node-p callee))))
6807 (setq parent node
6808 node (if call-p callee node))
6809 (if (and call-p (js2-name-node-p callee))
6810 (setq prop callee)
6811 (setq target (js2-prop-get-node-left node)
6812 prop (js2-prop-get-node-right node)))
6813 (cond
6814 ((js2-name-node-p prop)
6815 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6816 (js2-parse-highlight-prop-get parent target prop call-p))
6817 ((js2-name-node-p target)
6818 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6819 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6820
6821 (defun js2-parse-highlight-member-expr-fn-name (expr)
6822 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6823 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6824 We currently only handle the case where the last component is a prop-get
6825 of a simple name. Called before EXPR has a parent node."
6826 (let (pos
6827 (name (and (js2-prop-get-node-p expr)
6828 (js2-prop-get-node-right expr))))
6829 (when (js2-name-node-p name)
6830 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6831 (js2-node-pos name)))
6832 (+ pos (js2-node-len name))
6833 'font-lock-function-name-face
6834 'record))))
6835
6836 ;; source: http://jsdoc.sourceforge.net/
6837 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6838 ;; allows type specifications, and needs work before entering the wild.
6839
6840 (defconst js2-jsdoc-param-tag-regexp
6841 (concat "^\\s-*\\*+\\s-*\\(@"
6842 "\\(?:param\\|argument\\)"
6843 "\\)"
6844 "\\s-*\\({[^}]+}\\)?" ; optional type
6845 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6846 "\\>")
6847 "Matches jsdoc tags with optional type and optional param name.")
6848
6849 (defconst js2-jsdoc-typed-tag-regexp
6850 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6851 (regexp-opt
6852 '("enum"
6853 "extends"
6854 "field"
6855 "id"
6856 "implements"
6857 "lends"
6858 "mods"
6859 "requires"
6860 "return"
6861 "returns"
6862 "throw"
6863 "throws"))
6864 "\\)\\)\\s-*\\({[^}]+}\\)?")
6865 "Matches jsdoc tags with optional type.")
6866
6867 (defconst js2-jsdoc-arg-tag-regexp
6868 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6869 (regexp-opt
6870 '("alias"
6871 "augments"
6872 "borrows"
6873 "bug"
6874 "base"
6875 "config"
6876 "default"
6877 "define"
6878 "exception"
6879 "function"
6880 "member"
6881 "memberOf"
6882 "name"
6883 "namespace"
6884 "property"
6885 "since"
6886 "suppress"
6887 "this"
6888 "throws"
6889 "type"
6890 "version"))
6891 "\\)\\)\\s-+\\([^ \t]+\\)")
6892 "Matches jsdoc tags with a single argument.")
6893
6894 (defconst js2-jsdoc-empty-tag-regexp
6895 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6896 (regexp-opt
6897 '("addon"
6898 "author"
6899 "class"
6900 "const"
6901 "constant"
6902 "constructor"
6903 "constructs"
6904 "deprecated"
6905 "desc"
6906 "description"
6907 "event"
6908 "example"
6909 "exec"
6910 "export"
6911 "fileoverview"
6912 "final"
6913 "function"
6914 "hidden"
6915 "ignore"
6916 "implicitCast"
6917 "inheritDoc"
6918 "inner"
6919 "interface"
6920 "license"
6921 "noalias"
6922 "noshadow"
6923 "notypecheck"
6924 "override"
6925 "owner"
6926 "preserve"
6927 "preserveTry"
6928 "private"
6929 "protected"
6930 "public"
6931 "static"
6932 "supported"
6933 ))
6934 "\\)\\)\\s-*")
6935 "Matches empty jsdoc tags.")
6936
6937 (defconst js2-jsdoc-link-tag-regexp
6938 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6939 "Matches a jsdoc link or code tag.")
6940
6941 (defconst js2-jsdoc-see-tag-regexp
6942 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6943 "Matches a jsdoc @see tag.")
6944
6945 (defconst js2-jsdoc-html-tag-regexp
6946 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6947 "Matches a simple (no attributes) html start- or end-tag.")
6948
6949 (defun js2-jsdoc-highlight-helper ()
6950 (js2-set-face (match-beginning 1)
6951 (match-end 1)
6952 'js2-jsdoc-tag)
6953 (if (match-beginning 2)
6954 (if (save-excursion
6955 (goto-char (match-beginning 2))
6956 (= (char-after) ?{))
6957 (js2-set-face (1+ (match-beginning 2))
6958 (1- (match-end 2))
6959 'js2-jsdoc-type)
6960 (js2-set-face (match-beginning 2)
6961 (match-end 2)
6962 'js2-jsdoc-value)))
6963 (if (match-beginning 3)
6964 (js2-set-face (match-beginning 3)
6965 (match-end 3)
6966 'js2-jsdoc-value)))
6967
6968 (defun js2-highlight-jsdoc (ast)
6969 "Highlight doc comment tags."
6970 (let ((comments (js2-ast-root-comments ast))
6971 beg end)
6972 (save-excursion
6973 (dolist (node comments)
6974 (when (eq (js2-comment-node-format node) 'jsdoc)
6975 (setq beg (js2-node-abs-pos node)
6976 end (+ beg (js2-node-len node)))
6977 (save-restriction
6978 (narrow-to-region beg end)
6979 (dolist (re (list js2-jsdoc-param-tag-regexp
6980 js2-jsdoc-typed-tag-regexp
6981 js2-jsdoc-arg-tag-regexp
6982 js2-jsdoc-link-tag-regexp
6983 js2-jsdoc-see-tag-regexp
6984 js2-jsdoc-empty-tag-regexp))
6985 (goto-char beg)
6986 (while (re-search-forward re nil t)
6987 (js2-jsdoc-highlight-helper)))
6988 ;; simple highlighting for html tags
6989 (goto-char beg)
6990 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6991 (js2-set-face (match-beginning 1)
6992 (match-end 1)
6993 'js2-jsdoc-html-tag-delimiter)
6994 (js2-set-face (match-beginning 2)
6995 (match-end 2)
6996 'js2-jsdoc-html-tag-name)
6997 (js2-set-face (match-beginning 3)
6998 (match-end 3)
6999 'js2-jsdoc-html-tag-delimiter))))))))
7000
7001 (defun js2-highlight-assign-targets (_node left right)
7002 "Highlight function properties and external variables."
7003 (let (leftpos name)
7004 ;; highlight vars and props assigned function values
7005 (when (or (js2-function-node-p right)
7006 (js2-class-node-p right))
7007 (cond
7008 ;; var foo = function() {...}
7009 ((js2-name-node-p left)
7010 (setq name left))
7011 ;; foo.bar.baz = function() {...}
7012 ((and (js2-prop-get-node-p left)
7013 (js2-name-node-p (js2-prop-get-node-right left)))
7014 (setq name (js2-prop-get-node-right left))))
7015 (when name
7016 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7017 (+ leftpos (js2-node-len name))
7018 'font-lock-function-name-face
7019 'record)))))
7020
7021 (defun js2-record-name-node (node)
7022 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7023 later. NODE must be a name node."
7024 (let ((leftpos (js2-node-abs-pos node)))
7025 (push (list node js2-current-scope
7026 leftpos
7027 (+ leftpos (js2-node-len node)))
7028 js2-recorded-identifiers)))
7029
7030 (defun js2-highlight-undeclared-vars ()
7031 "After entire parse is finished, look for undeclared variable references.
7032 We have to wait until entire buffer is parsed, since JavaScript permits var
7033 decls to occur after they're used.
7034
7035 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7036 it is considered declared."
7037 (let (name)
7038 (dolist (entry js2-recorded-identifiers)
7039 (cl-destructuring-bind (name-node scope pos end) entry
7040 (setq name (js2-name-node-name name-node))
7041 (unless (or (member name js2-global-externs)
7042 (member name js2-default-externs)
7043 (member name js2-additional-externs)
7044 (js2-get-defining-scope scope name pos))
7045 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7046 'js2-external-variable))))
7047 (setq js2-recorded-identifiers nil)))
7048
7049 (defun js2-set-default-externs ()
7050 "Set the value of `js2-default-externs' based on the various
7051 `js2-include-?-externs' variables."
7052 (setq js2-default-externs
7053 (append js2-ecma-262-externs
7054 (if js2-include-browser-externs js2-browser-externs)
7055 (if (and js2-include-browser-externs
7056 (>= js2-language-version 200)) js2-harmony-externs)
7057 (if js2-include-rhino-externs js2-rhino-externs)
7058 (if js2-include-node-externs js2-node-externs)
7059 (if (or js2-include-browser-externs js2-include-node-externs)
7060 js2-typed-array-externs))))
7061
7062 (defun js2-apply-jslint-globals ()
7063 (setq js2-additional-externs
7064 (nconc (js2-get-jslint-globals)
7065 js2-additional-externs)))
7066
7067 (defun js2-get-jslint-globals ()
7068 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7069 when (and (eq 'block (js2-comment-node-format node))
7070 (save-excursion
7071 (goto-char (js2-node-abs-pos node))
7072 (looking-at "/\\*global ")))
7073 append (js2-get-jslint-globals-in
7074 (match-end 0)
7075 (js2-node-abs-end node))))
7076
7077 (defun js2-get-jslint-globals-in (beg end)
7078 (let (res)
7079 (save-excursion
7080 (goto-char beg)
7081 (while (re-search-forward js2-mode-identifier-re end t)
7082 (let ((match (match-string 0)))
7083 (unless (member match '("true" "false"))
7084 (push match res)))))
7085 (nreverse res)))
7086
7087 ;;; IMenu support
7088
7089 ;; We currently only support imenu, but eventually should support speedbar and
7090 ;; possibly other browsing mechanisms.
7091
7092 ;; The basic strategy is to identify function assignment targets of the form
7093 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7094 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7095 ;; for imenu after parsing is finished.
7096
7097 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7098 ;; JavaScript, and the general problem is undecidable. However, several forms
7099 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7100 ;; include:
7101
7102 ;; function foo() -- function declaration
7103 ;; foo = function() -- function expression assigned to variable
7104 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7105 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7106 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7107 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7108 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7109 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7110 ;; function foo() {function bar() {...}} -- nested function
7111 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7112
7113 ;; This list boils down to a few forms that can be combined recursively.
7114 ;; Top-level named function declarations include both the left-hand (name)
7115 ;; and the right-hand (function value) expressions needed to produce an imenu
7116 ;; entry. The other "right-hand" forms we need to look for are:
7117 ;; - functions declared as props/getters/setters in object literals
7118 ;; - nested named function declarations
7119 ;; The "left-hand" expressions that functions can be assigned to include:
7120 ;; - local/global variables
7121 ;; - nested property-get expressions like a.b.c.d
7122 ;; - element gets like foo[10] or foo['bar'] where the index
7123 ;; expression can be trivially converted to a property name. They
7124 ;; effectively then become property gets.
7125
7126 ;; All the different definition types are canonicalized into the form
7127 ;; foo.bar.baz = position-of-function-keyword
7128
7129 ;; We need to build a trie-like structure for imenu. As an example,
7130 ;; consider the following JavaScript code:
7131
7132 ;; a = function() {...} // function at position 5
7133 ;; b = function() {...} // function at position 25
7134 ;; foo = function() {...} // function at position 100
7135 ;; foo.bar = function() {...} // function at position 200
7136 ;; foo.bar.baz = function() {...} // function at position 300
7137 ;; foo.bar.zab = function() {...} // function at position 400
7138
7139 ;; During parsing we accumulate an entry for each definition in
7140 ;; the variable `js2-imenu-recorder', like so:
7141
7142 ;; '((fn a 5)
7143 ;; (fn b 25)
7144 ;; (fn foo 100)
7145 ;; (fn foo bar 200)
7146 ;; (fn foo bar baz 300)
7147 ;; (fn foo bar zab 400))
7148
7149 ;; Where 'fn' is the respective function node.
7150 ;; After parsing these entries are merged into this alist-trie:
7151
7152 ;; '((a . 1)
7153 ;; (b . 2)
7154 ;; (foo (<definition> . 3)
7155 ;; (bar (<definition> . 6)
7156 ;; (baz . 100)
7157 ;; (zab . 200))))
7158
7159 ;; Note the wacky need for a <definition> name. The token can be anything
7160 ;; that isn't a valid JavaScript identifier, because you might make foo
7161 ;; a function and then start setting properties on it that are also functions.
7162
7163 (defun js2-prop-node-name (node)
7164 "Return the name of a node that may be a property-get/property-name.
7165 If NODE is not a valid name-node, string-node or integral number-node,
7166 returns nil. Otherwise returns the string name/value of the node."
7167 (cond
7168 ((js2-name-node-p node)
7169 (js2-name-node-name node))
7170 ((js2-string-node-p node)
7171 (js2-string-node-value node))
7172 ((and (js2-number-node-p node)
7173 (string-match "^[0-9]+$" (js2-number-node-value node)))
7174 (js2-number-node-value node))
7175 ((eq (js2-node-type node) js2-THIS)
7176 "this")
7177 ((eq (js2-node-type node) js2-SUPER)
7178 "super")))
7179
7180 (defun js2-node-qname-component (node)
7181 "Return the name of this node, if it contributes to a qname.
7182 Returns nil if the node doesn't contribute."
7183 (copy-sequence
7184 (or (js2-prop-node-name node)
7185 (if (and (js2-function-node-p node)
7186 (js2-function-node-name node))
7187 (js2-name-node-name (js2-function-node-name node))))))
7188
7189 (defun js2-record-imenu-entry (fn-node qname pos)
7190 "Add an entry to `js2-imenu-recorder'.
7191 FN-NODE should be the current item's function node.
7192
7193 Associate FN-NODE with its QNAME for later lookup.
7194 This is used in postprocessing the chain list. For each chain, we find
7195 the parent function, look up its qname, then prepend a copy of it to the chain."
7196 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7197 (unless js2-imenu-function-map
7198 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7199 (puthash fn-node qname js2-imenu-function-map))
7200
7201 (defun js2-record-imenu-functions (node &optional var)
7202 "Record function definitions for imenu.
7203 NODE is a function node or an object literal.
7204 VAR, if non-nil, is the expression that NODE is being assigned to.
7205 When passed arguments of wrong type, does nothing."
7206 (when js2-parse-ide-mode
7207 (let ((fun-p (js2-function-node-p node))
7208 qname fname-node)
7209 (cond
7210 ;; non-anonymous function declaration?
7211 ((and fun-p
7212 (not var)
7213 (setq fname-node (js2-function-node-name node)))
7214 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7215 ;; for remaining forms, compute left-side tree branch first
7216 ((and var (setq qname (js2-compute-nested-prop-get var)))
7217 (cond
7218 ;; foo.bar.baz = function
7219 (fun-p
7220 (js2-record-imenu-entry node qname (js2-node-pos node)))
7221 ;; foo.bar.baz = object-literal
7222 ;; look for nested functions: {a: {b: function() {...} }}
7223 ((js2-object-node-p node)
7224 ;; Node position here is still absolute, since the parser
7225 ;; passes the assignment target and value expressions
7226 ;; to us before they are added as children of the assignment node.
7227 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7228
7229 (defun js2-compute-nested-prop-get (node)
7230 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7231 component nodes as a list. Otherwise return nil. Element-gets are treated
7232 as property-gets if the index expression is a string, or a positive integer."
7233 (let (left right head)
7234 (cond
7235 ((or (js2-name-node-p node)
7236 (js2-this-or-super-node-p node))
7237 (list node))
7238 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7239 ((js2-prop-get-node-p node) ; foo.bar
7240 (setq left (js2-prop-get-node-left node)
7241 right (js2-prop-get-node-right node))
7242 (if (setq head (js2-compute-nested-prop-get left))
7243 (nconc head (list right))))
7244 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7245 (setq left (js2-elem-get-node-target node)
7246 right (js2-elem-get-node-element node))
7247 (if (or (js2-string-node-p right) ; ['bar']
7248 (and (js2-number-node-p right) ; [10]
7249 (string-match "^[0-9]+$"
7250 (js2-number-node-value right))))
7251 (if (setq head (js2-compute-nested-prop-get left))
7252 (nconc head (list right))))))))
7253
7254 (defun js2-record-object-literal (node qname pos)
7255 "Recursively process an object literal looking for functions.
7256 NODE is an object literal that is the right-hand child of an assignment
7257 expression. QNAME is a list of nodes representing the assignment target,
7258 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7259 POS is the absolute position of the node.
7260 We do a depth-first traversal of NODE. For any functions we find,
7261 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7262 (let (right)
7263 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7264 (let ((left (js2-infix-node-left e))
7265 ;; Element positions are relative to the parent position.
7266 (pos (+ pos (js2-node-pos e))))
7267 (cond
7268 ;; foo: function() {...}
7269 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7270 (when (js2-prop-node-name left)
7271 ;; As a policy decision, we record the position of the property,
7272 ;; not the position of the `function' keyword, since the property
7273 ;; is effectively the name of the function.
7274 (js2-record-imenu-entry right (append qname (list left)) pos)))
7275 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7276 ((js2-object-node-p right)
7277 (js2-record-object-literal right
7278 (append qname (list (js2-infix-node-left e)))
7279 (+ pos (js2-node-pos right)))))))))
7280
7281 (defun js2-node-top-level-decl-p (node)
7282 "Return t if NODE's name is defined in the top-level scope.
7283 Also returns t if NODE's name is not defined in any scope, since it implies
7284 that it's an external variable, which must also be in the top-level scope."
7285 (let* ((name (js2-prop-node-name node))
7286 (this-scope (js2-node-get-enclosing-scope node))
7287 defining-scope)
7288 (cond
7289 ((js2-this-or-super-node-p node)
7290 nil)
7291 ((null this-scope)
7292 t)
7293 ((setq defining-scope (js2-get-defining-scope this-scope name))
7294 (js2-ast-root-p defining-scope))
7295 (t t))))
7296
7297 (defun js2-wrapper-function-p (node)
7298 "Return t if NODE is a function expression that's immediately invoked.
7299 NODE must be `js2-function-node'."
7300 (let ((parent (js2-node-parent node)))
7301 (or
7302 ;; function(){...}();
7303 (and (js2-call-node-p parent)
7304 (eq node (js2-call-node-target parent)))
7305 (and (js2-paren-node-p parent)
7306 ;; (function(){...})();
7307 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7308 ;; (function(){...}).call(this);
7309 (and (js2-prop-get-node-p parent)
7310 (member (js2-name-node-name (js2-prop-get-node-right parent))
7311 '("call" "apply"))
7312 (js2-call-node-p (js2-node-parent parent))))))))
7313
7314 (defun js2-browse-postprocess-chains ()
7315 "Modify function-declaration name chains after parsing finishes.
7316 Some of the information is only available after the parse tree is complete.
7317 For instance, processing a nested scope requires a parent function node."
7318 (let (result fn parent-qname p elem)
7319 (dolist (entry js2-imenu-recorder)
7320 ;; function node goes first
7321 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7322 ;; Examine head's defining scope:
7323 ;; Pre-processed chain, or top-level/external, keep as-is.
7324 (if (or (stringp head) (js2-node-top-level-decl-p head))
7325 (push chain result)
7326 (when (js2-this-or-super-node-p head)
7327 (setq chain (cdr chain))) ; discard this-node
7328 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7329 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7330 (when (eq parent-qname 'not-found)
7331 ;; anonymous function expressions are not recorded
7332 ;; during the parse, so we need to handle this case here
7333 (setq parent-qname
7334 (if (js2-wrapper-function-p fn)
7335 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7336 (if (js2-ast-root-p grandparent)
7337 nil
7338 (gethash grandparent js2-imenu-function-map 'skip)))
7339 'skip))
7340 (puthash fn parent-qname js2-imenu-function-map))
7341 (if (eq parent-qname 'skip)
7342 ;; We don't show it, let's record that fact.
7343 (remhash current-fn js2-imenu-function-map)
7344 ;; Prepend parent fn qname to this chain.
7345 (let ((qname (append parent-qname chain)))
7346 (puthash current-fn (butlast qname) js2-imenu-function-map)
7347 (push qname result)))))))
7348 ;; Collect chains obtained by third-party code.
7349 (let (js2-imenu-recorder)
7350 (run-hooks 'js2-build-imenu-callbacks)
7351 (dolist (entry js2-imenu-recorder)
7352 (push (cdr entry) result)))
7353 ;; Finally replace each node in each chain with its name.
7354 (dolist (chain result)
7355 (setq p chain)
7356 (while p
7357 (if (js2-node-p (setq elem (car p)))
7358 (setcar p (js2-node-qname-component elem)))
7359 (setq p (cdr p))))
7360 result))
7361
7362 ;; Merge name chains into a trie-like tree structure of nested lists.
7363 ;; To simplify construction of the trie, we first build it out using the rule
7364 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7365 ;; [key, num-or-list]. The second element can be a number; if so, this key
7366 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7367 ;; associated with the key at this level.) Otherwise the second element is
7368 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7369 ;; a simple recursive formulation.
7370 ;;
7371 ;; js2-mode is building the data structure for imenu. The imenu documentation
7372 ;; claims that it's the structure above, but in practice it wants the children
7373 ;; at the same list level as the key for that level, which is how I've drawn
7374 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7375 ;; list wrapper around the children at each level.
7376 ;;
7377 ;; A completed nested imenu-alist entry looks like this:
7378 ;; '(("foo"
7379 ;; ("<definition>" . 7)
7380 ;; ("bar"
7381 ;; ("a" . 40)
7382 ;; ("b" . 60))))
7383 ;;
7384 ;; In particular, the documentation for `imenu--index-alist' says that
7385 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7386 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7387
7388 (defun js2-treeify (lst)
7389 "Convert (a b c d) to (a ((b ((c d)))))."
7390 (if (null (cddr lst)) ; list length <= 2
7391 lst
7392 (list (car lst) (list (js2-treeify (cdr lst))))))
7393
7394 (defun js2-build-alist-trie (chains trie)
7395 "Merge declaration name chains into a trie-like alist structure for imenu.
7396 CHAINS is the qname chain list produced during parsing. TRIE is a
7397 list of elements built up so far."
7398 (let (head tail pos branch kids)
7399 (dolist (chain chains)
7400 (setq head (car chain)
7401 tail (cdr chain)
7402 pos (if (numberp (car tail)) (car tail))
7403 branch (js2-find-if (lambda (n)
7404 (string= (car n) head))
7405 trie)
7406 kids (cl-second branch))
7407 (cond
7408 ;; case 1: this key isn't in the trie yet
7409 ((null branch)
7410 (if trie
7411 (setcdr (last trie) (list (js2-treeify chain)))
7412 (setq trie (list (js2-treeify chain)))))
7413 ;; case 2: key is present with a single number entry: replace w/ list
7414 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7415 ;; ("<definition>" 20)))
7416 ((numberp kids)
7417 (setcar (cdr branch)
7418 (list (list "<definition-1>" kids)
7419 (if pos
7420 (list "<definition-2>" pos)
7421 (js2-treeify tail)))))
7422 ;; case 3: key is there (with kids), and we're a number entry
7423 (pos
7424 (setcdr (last kids)
7425 (list
7426 (list (format "<definition-%d>"
7427 (1+ (cl-loop for kid in kids
7428 count (eq ?< (aref (car kid) 0)))))
7429 pos))))
7430 ;; case 4: key is there with kids, need to merge in our chain
7431 (t
7432 (js2-build-alist-trie (list tail) kids))))
7433 trie))
7434
7435 (defun js2-flatten-trie (trie)
7436 "Convert TRIE to imenu-format.
7437 Recurses through nodes, and for each one whose second element is a list,
7438 appends the list's flattened elements to the current element. Also
7439 changes the tails into conses. For instance, this pre-flattened trie
7440
7441 '(a ((b 20)
7442 (c ((d 30)
7443 (e 40)))))
7444
7445 becomes
7446
7447 '(a (b . 20)
7448 (c (d . 30)
7449 (e . 40)))
7450
7451 Note that the root of the trie has no key, just a list of chains.
7452 This is also true for the value of any key with multiple children,
7453 e.g. key 'c' in the example above."
7454 (cond
7455 ((listp (car trie))
7456 (mapcar #'js2-flatten-trie trie))
7457 (t
7458 (if (numberp (cl-second trie))
7459 (cons (car trie) (cl-second trie))
7460 ;; else pop list and append its kids
7461 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7462
7463 (defun js2-build-imenu-index ()
7464 "Turn `js2-imenu-recorder' into an imenu data structure."
7465 (when (eq js2-imenu-recorder 'empty)
7466 (setq js2-imenu-recorder nil))
7467 (let* ((chains (js2-browse-postprocess-chains))
7468 (result (js2-build-alist-trie chains nil)))
7469 (js2-flatten-trie result)))
7470
7471 (defun js2-test-print-chains (chains)
7472 "Print a list of qname chains.
7473 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7474 i.e. one or more nodes, and an integer position as the list tail."
7475 (mapconcat (lambda (chain)
7476 (concat "("
7477 (mapconcat (lambda (elem)
7478 (if (js2-node-p elem)
7479 (or (js2-node-qname-component elem)
7480 "nil")
7481 (number-to-string elem)))
7482 chain
7483 " ")
7484 ")"))
7485 chains
7486 "\n"))
7487
7488 ;;; Parser
7489
7490 (defconst js2-version "1.8.5"
7491 "Version of JavaScript supported.")
7492
7493 (defun js2-record-face (face &optional token)
7494 "Record a style run of FACE for TOKEN or the current token."
7495 (unless token (setq token (js2-current-token)))
7496 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7497
7498 (defsubst js2-node-end (n)
7499 "Computes the absolute end of node N.
7500 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7501 is only true until the node is added to its parent; i.e., while parsing."
7502 (+ (js2-node-pos n)
7503 (js2-node-len n)))
7504
7505 (defun js2-record-comment (token)
7506 "Record a comment in `js2-scanned-comments'."
7507 (let ((ct (js2-token-comment-type token))
7508 (beg (js2-token-beg token))
7509 (end (js2-token-end token)))
7510 (push (make-js2-comment-node :len (- end beg)
7511 :format ct)
7512 js2-scanned-comments)
7513 (when js2-parse-ide-mode
7514 (js2-record-face (if (eq ct 'jsdoc)
7515 'font-lock-doc-face
7516 'font-lock-comment-face)
7517 token)
7518 (when (memq ct '(html preprocessor))
7519 ;; Tell cc-engine the bounds of the comment.
7520 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7521
7522 (defun js2-peek-token ()
7523 "Return the next token type without consuming it.
7524 If `js2-ti-lookahead' is positive, return the type of next token
7525 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7526 (if (not (zerop js2-ti-lookahead))
7527 (js2-token-type
7528 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7529 (let ((tt (js2-get-token-internal nil)))
7530 (js2-unget-token)
7531 tt)))
7532
7533 (defalias 'js2-next-token 'js2-get-token)
7534
7535 (defun js2-match-token (match &optional dont-unget)
7536 "Get next token and return t if it matches MATCH, a bytecode.
7537 Returns nil and consumes nothing if MATCH is not the next token."
7538 (if (/= (js2-get-token) match)
7539 (ignore (unless dont-unget (js2-unget-token)))
7540 t))
7541
7542 (defun js2-match-contextual-kwd (name)
7543 "Consume and return t if next token is `js2-NAME', and its
7544 string is NAME. Returns nil and keeps current token otherwise."
7545 (if (or (/= (js2-get-token) js2-NAME)
7546 (not (string= (js2-current-token-string) name)))
7547 (progn
7548 (js2-unget-token)
7549 nil)
7550 (js2-record-face 'font-lock-keyword-face)
7551 t))
7552
7553 (defun js2-get-prop-name-token ()
7554 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7555
7556 (defun js2-match-prop-name ()
7557 "Consume token and return t if next token is a valid property name.
7558 If `js2-language-version' is >= 180, a keyword or reserved word
7559 is considered valid name as well."
7560 (if (eq js2-NAME (js2-get-prop-name-token))
7561 t
7562 (js2-unget-token)
7563 nil))
7564
7565 (defun js2-must-match-prop-name (msg-id &optional pos len)
7566 (if (js2-match-prop-name)
7567 t
7568 (js2-report-error msg-id nil pos len)
7569 nil))
7570
7571 (defun js2-peek-token-or-eol ()
7572 "Return js2-EOL if the next token immediately follows a newline.
7573 Else returns the next token. Used in situations where we don't
7574 consider certain token types valid if they are preceded by a newline.
7575 One example is the postfix ++ or -- operator, which has to be on the
7576 same line as its operand."
7577 (let ((tt (js2-get-token))
7578 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7579 (js2-unget-token)
7580 (if follows-eol
7581 js2-EOL
7582 tt)))
7583
7584 (defun js2-must-match (token msg-id &optional pos len)
7585 "Match next token to token code TOKEN, or record a syntax error.
7586 MSG-ID is the error message to report if the match fails.
7587 Returns t on match, nil if no match."
7588 (if (js2-match-token token t)
7589 t
7590 (js2-report-error msg-id nil pos len)
7591 (js2-unget-token)
7592 nil))
7593
7594 (defun js2-must-match-name (msg-id)
7595 (if (js2-match-token js2-NAME t)
7596 t
7597 (if (eq (js2-current-token-type) js2-RESERVED)
7598 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7599 (js2-report-error msg-id)
7600 (js2-unget-token))
7601 nil))
7602
7603 (defsubst js2-inside-function ()
7604 (cl-plusp js2-nesting-of-function))
7605
7606 (defun js2-set-requires-activation ()
7607 (if (js2-function-node-p js2-current-script-or-fn)
7608 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7609
7610 (defun js2-check-activation-name (name _token)
7611 (when (js2-inside-function)
7612 ;; skip language-version 1.2 check from Rhino
7613 (if (or (string= "arguments" name)
7614 (and js2-compiler-activation-names ; only used in codegen
7615 (gethash name js2-compiler-activation-names)))
7616 (js2-set-requires-activation))))
7617
7618 (defun js2-set-is-generator ()
7619 (let ((fn-node js2-current-script-or-fn))
7620 (when (and (js2-function-node-p fn-node)
7621 (not (js2-function-node-generator-type fn-node)))
7622 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7623
7624 (defun js2-must-have-xml ()
7625 (unless js2-compiler-xml-available
7626 (js2-report-error "msg.XML.not.available")))
7627
7628 (defun js2-push-scope (scope)
7629 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7630 (cl-assert (js2-scope-p scope))
7631 (cl-assert (null (js2-scope-parent-scope scope)))
7632 (cl-assert (not (eq js2-current-scope scope)))
7633 (setf (js2-scope-parent-scope scope) js2-current-scope
7634 js2-current-scope scope))
7635
7636 (defsubst js2-pop-scope ()
7637 (setq js2-current-scope
7638 (js2-scope-parent-scope js2-current-scope)))
7639
7640 (defun js2-enter-loop (loop-node)
7641 (push loop-node js2-loop-set)
7642 (push loop-node js2-loop-and-switch-set)
7643 (js2-push-scope loop-node)
7644 ;; Tell the current labeled statement (if any) its statement,
7645 ;; and set the jump target of the first label to the loop.
7646 ;; These are used in `js2-parse-continue' to verify that the
7647 ;; continue target is an actual labeled loop. (And for codegen.)
7648 (when js2-labeled-stmt
7649 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7650 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7651 js2-labeled-stmt))) loop-node)))
7652
7653 (defun js2-exit-loop ()
7654 (pop js2-loop-set)
7655 (pop js2-loop-and-switch-set)
7656 (js2-pop-scope))
7657
7658 (defsubst js2-enter-switch (switch-node)
7659 (push switch-node js2-loop-and-switch-set))
7660
7661 (defsubst js2-exit-switch ()
7662 (pop js2-loop-and-switch-set))
7663
7664 (defun js2-parse (&optional buf cb)
7665 "Tell the js2 parser to parse a region of JavaScript.
7666
7667 BUF is a buffer or buffer name containing the code to parse.
7668 Call `narrow-to-region' first to parse only part of the buffer.
7669
7670 The returned AST root node is given some additional properties:
7671 `node-count' - total number of nodes in the AST
7672 `buffer' - BUF. The buffer it refers to may change or be killed,
7673 so the value is not necessarily reliable.
7674
7675 An optional callback CB can be specified to report parsing
7676 progress. If `(functionp CB)' returns t, it will be called with
7677 the current line number once before parsing begins, then again
7678 each time the lexer reaches a new line number.
7679
7680 CB can also be a list of the form `(symbol cb ...)' to specify
7681 multiple callbacks with different criteria. Each symbol is a
7682 criterion keyword, and the following element is the callback to
7683 call
7684
7685 :line - called whenever the line number changes
7686 :token - called for each new token consumed
7687
7688 The list of criteria could be extended to include entering or
7689 leaving a statement, an expression, or a function definition."
7690 (if (and cb (not (functionp cb)))
7691 (error "criteria callbacks not yet implemented"))
7692 (let ((inhibit-point-motion-hooks t)
7693 (js2-compiler-xml-available (>= js2-language-version 160))
7694 ;; This is a recursive-descent parser, so give it a big stack.
7695 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7696 (max-specpdl-size (max max-specpdl-size 3000))
7697 (case-fold-search nil)
7698 ast)
7699 (with-current-buffer (or buf (current-buffer))
7700 (setq js2-scanned-comments nil
7701 js2-parsed-errors nil
7702 js2-parsed-warnings nil
7703 js2-imenu-recorder nil
7704 js2-imenu-function-map nil
7705 js2-label-set nil)
7706 (js2-init-scanner)
7707 (setq ast (js2-do-parse))
7708 (unless js2-ts-hit-eof
7709 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7710 (setf (js2-ast-root-errors ast) js2-parsed-errors
7711 (js2-ast-root-warnings ast) js2-parsed-warnings)
7712 ;; if we didn't find any declarations, put a dummy in this list so we
7713 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7714 (unless js2-imenu-recorder
7715 (setq js2-imenu-recorder 'empty))
7716 (run-hooks 'js2-parse-finished-hook)
7717 ast)))
7718
7719 ;; Corresponds to Rhino's Parser.parse() method.
7720 (defun js2-do-parse ()
7721 "Parse current buffer starting from current point.
7722 Scanner should be initialized."
7723 (let ((pos js2-ts-cursor)
7724 (end js2-ts-cursor) ; in case file is empty
7725 root n tt)
7726 ;; initialize buffer-local parsing vars
7727 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7728 js2-current-script-or-fn root
7729 js2-current-scope root
7730 js2-nesting-of-function 0
7731 js2-labeled-stmt nil
7732 js2-recorded-identifiers nil) ; for js2-highlight
7733 (while (/= (setq tt (js2-get-token)) js2-EOF)
7734 (if (= tt js2-FUNCTION)
7735 (progn
7736 (setq n (if js2-called-by-compile-function
7737 (js2-parse-function-expr)
7738 (js2-parse-function-stmt))))
7739 ;; not a function - parse a statement
7740 (js2-unget-token)
7741 (setq n (js2-parse-statement)))
7742 ;; add function or statement to script
7743 (setq end (js2-node-end n))
7744 (js2-block-node-push root n))
7745 ;; add comments to root in lexical order
7746 (when js2-scanned-comments
7747 ;; if we find a comment beyond end of normal kids, use its end
7748 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7749 (dolist (comment js2-scanned-comments)
7750 (push comment (js2-ast-root-comments root))
7751 (js2-node-add-children root comment)))
7752 (setf (js2-node-len root) (- end pos))
7753 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7754 ;; Give extensions a chance to muck with things before highlighting starts.
7755 (let ((js2-additional-externs js2-additional-externs))
7756 (save-excursion
7757 (run-hooks 'js2-post-parse-callbacks))
7758 (js2-highlight-undeclared-vars))
7759 root))
7760
7761 (defun js2-parse-function-closure-body (fn-node)
7762 "Parse a JavaScript 1.8 function closure body."
7763 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7764 (if js2-ts-hit-eof
7765 (js2-report-error "msg.no.brace.body" nil
7766 (js2-node-pos fn-node)
7767 (- js2-ts-cursor (js2-node-pos fn-node)))
7768 (js2-node-add-children fn-node
7769 (setf (js2-function-node-body fn-node)
7770 (js2-parse-expr t))))))
7771
7772 (defun js2-parse-function-body (fn-node)
7773 (js2-must-match js2-LC "msg.no.brace.body"
7774 (js2-node-pos fn-node)
7775 (- js2-ts-cursor (js2-node-pos fn-node)))
7776 (let ((pos (js2-current-token-beg)) ; LC position
7777 (pn (make-js2-block-node)) ; starts at LC position
7778 tt
7779 end)
7780 (cl-incf js2-nesting-of-function)
7781 (unwind-protect
7782 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7783 (= tt js2-EOF)
7784 (= tt js2-RC)))
7785 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7786 (js2-parse-statement)
7787 (js2-get-token)
7788 (js2-parse-function-stmt))))
7789 (cl-decf js2-nesting-of-function))
7790 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7791 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7792 (setq end (js2-current-token-end)))
7793 (setf (js2-node-pos pn) pos
7794 (js2-node-len pn) (- end pos))
7795 (setf (js2-function-node-body fn-node) pn)
7796 (js2-node-add-children fn-node pn)
7797 pn))
7798
7799 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7800 "Declare and fontify destructuring parameters inside NODE.
7801 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7802 (cond
7803 ((js2-name-node-p node)
7804 (let (leftpos)
7805 (js2-define-symbol decl-type (js2-name-node-name node)
7806 node ignore-not-in-block)
7807 (when face
7808 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7809 (+ leftpos (js2-node-len node))
7810 face 'record))))
7811 ((js2-object-node-p node)
7812 (dolist (elem (js2-object-node-elems node))
7813 (js2-define-destruct-symbols
7814 ;; In abbreviated destructuring {a, b}, right == left.
7815 (js2-object-prop-node-right elem)
7816 decl-type face ignore-not-in-block)))
7817 ((js2-array-node-p node)
7818 (dolist (elem (js2-array-node-elems node))
7819 (when elem
7820 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7821 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7822 (js2-node-len node)))))
7823
7824 (defun js2-parse-function-params (function-type fn-node pos)
7825 (if (js2-match-token js2-RP)
7826 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7827 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7828 (eq (js2-current-token-type) js2-NAME)))
7829 params param default-found rest-param-at)
7830 (when paren-free-arrow
7831 (js2-unget-token))
7832 (cl-loop for tt = (js2-peek-token)
7833 do
7834 (cond
7835 ;; destructuring param
7836 ((and (not paren-free-arrow)
7837 (or (= tt js2-LB) (= tt js2-LC)))
7838 (js2-get-token)
7839 (when default-found
7840 (js2-report-error "msg.no.default.after.default.param"))
7841 (setq param (js2-parse-destruct-primary-expr))
7842 (js2-define-destruct-symbols param
7843 js2-LP
7844 'js2-function-param)
7845 (push param params))
7846 ;; variable name
7847 (t
7848 (when (and (>= js2-language-version 200)
7849 (not paren-free-arrow)
7850 (js2-match-token js2-TRIPLEDOT)
7851 (not rest-param-at))
7852 ;; to report errors if there are more parameters
7853 (setq rest-param-at (length params)))
7854 (js2-must-match-name "msg.no.parm")
7855 (js2-record-face 'js2-function-param)
7856 (setq param (js2-create-name-node))
7857 (js2-define-symbol js2-LP (js2-current-token-string) param)
7858 ;; default parameter value
7859 (when (or (and default-found
7860 (not rest-param-at)
7861 (js2-must-match js2-ASSIGN
7862 "msg.no.default.after.default.param"
7863 (js2-node-pos param)
7864 (js2-node-len param)))
7865 (and (>= js2-language-version 200)
7866 (js2-match-token js2-ASSIGN)))
7867 (cl-assert (not paren-free-arrow))
7868 (let* ((pos (js2-node-pos param))
7869 (tt (js2-current-token-type))
7870 (op-pos (- (js2-current-token-beg) pos))
7871 (left param)
7872 (right (js2-parse-assign-expr))
7873 (len (- (js2-node-end right) pos)))
7874 (setq param (make-js2-assign-node
7875 :type tt :pos pos :len len :op-pos op-pos
7876 :left left :right right)
7877 default-found t)
7878 (js2-node-add-children param left right)))
7879 (push param params)))
7880 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7881 (js2-report-error "msg.param.after.rest" nil
7882 (js2-node-pos param) (js2-node-len param)))
7883 while
7884 (js2-match-token js2-COMMA))
7885 (when (and (not paren-free-arrow)
7886 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7887 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7888 (when rest-param-at
7889 (setf (js2-function-node-rest-p fn-node) t))
7890 (dolist (p params)
7891 (js2-node-add-children fn-node p)
7892 (push p (js2-function-node-params fn-node))))))
7893
7894 (defun js2-check-inconsistent-return-warning (fn-node name)
7895 "Possibly show inconsistent-return warning.
7896 Last token scanned is the close-curly for the function body."
7897 (when (and js2-mode-show-strict-warnings
7898 js2-strict-inconsistent-return-warning
7899 (not (js2-has-consistent-return-usage
7900 (js2-function-node-body fn-node))))
7901 ;; Have it extend from close-curly to bol or beginning of block.
7902 (let ((pos (save-excursion
7903 (goto-char (js2-current-token-end))
7904 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7905 (point-at-bol))))
7906 (end (js2-current-token-end)))
7907 (if (cl-plusp (js2-name-node-length name))
7908 (js2-add-strict-warning "msg.no.return.value"
7909 (js2-name-node-name name) pos end)
7910 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7911
7912 (defun js2-parse-function-stmt ()
7913 (let ((pos (js2-current-token-beg))
7914 (star-p (js2-match-token js2-MUL)))
7915 (js2-must-match-name "msg.unnamed.function.stmt")
7916 (let ((name (js2-create-name-node t))
7917 pn member-expr)
7918 (cond
7919 ((js2-match-token js2-LP)
7920 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7921 (js2-allow-member-expr-as-function-name
7922 (setq member-expr (js2-parse-member-expr-tail nil name))
7923 (js2-parse-highlight-member-expr-fn-name member-expr)
7924 (js2-must-match js2-LP "msg.no.paren.parms")
7925 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7926 (js2-function-node-member-expr pn) member-expr)
7927 pn)
7928 (t
7929 (js2-report-error "msg.no.paren.parms")
7930 (make-js2-error-node))))))
7931
7932 (defun js2-parse-function-expr ()
7933 (let ((pos (js2-current-token-beg))
7934 (star-p (js2-match-token js2-MUL))
7935 name)
7936 (when (js2-match-token js2-NAME)
7937 (setq name (js2-create-name-node t)))
7938 (js2-must-match js2-LP "msg.no.paren.parms")
7939 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7940
7941 (defun js2-parse-function (function-type pos star-p &optional name)
7942 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7943 beginning of the first token (function keyword, unless it's an
7944 arrow function), NAME is js2-name-node."
7945 (let (fn-node lp)
7946 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7947 (setq lp (js2-current-token-beg)))
7948 (setf fn-node (make-js2-function-node :pos pos
7949 :name name
7950 :form function-type
7951 :lp (if lp (- lp pos))
7952 :generator-type (and star-p 'STAR)))
7953 (when name
7954 (js2-set-face (js2-node-pos name) (js2-node-end name)
7955 'font-lock-function-name-face 'record)
7956 (when (and (eq function-type 'FUNCTION_STATEMENT)
7957 (cl-plusp (js2-name-node-length name)))
7958 ;; Function statements define a symbol in the enclosing scope
7959 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7960 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
7961 ;; 1. Nested functions are not affected by the dynamic scope flag
7962 ;; as dynamic scope is already a parent of their scope.
7963 ;; 2. Functions defined under the with statement also immune to
7964 ;; this setup, in which case dynamic scope is ignored in favor
7965 ;; of the with object.
7966 (setf (js2-function-node-ignore-dynamic fn-node) t))
7967 ;; dynamically bind all the per-function variables
7968 (let ((js2-current-script-or-fn fn-node)
7969 (js2-current-scope fn-node)
7970 (js2-nesting-of-with 0)
7971 (js2-end-flags 0)
7972 js2-label-set
7973 js2-loop-set
7974 js2-loop-and-switch-set)
7975 (js2-parse-function-params function-type fn-node pos)
7976 (when (eq function-type 'FUNCTION_ARROW)
7977 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7978 (if (and (>= js2-language-version 180)
7979 (/= (js2-peek-token) js2-LC))
7980 (js2-parse-function-closure-body fn-node)
7981 (js2-parse-function-body fn-node))
7982 (js2-check-inconsistent-return-warning fn-node name)
7983
7984 (when name
7985 (js2-node-add-children fn-node name)
7986 ;; Function expressions define a name only in the body of the
7987 ;; function, and only if not hidden by a parameter name
7988 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7989 (null (js2-scope-get-symbol js2-current-scope
7990 (js2-name-node-name name))))
7991 (js2-define-symbol js2-FUNCTION
7992 (js2-name-node-name name)
7993 fn-node))
7994 (when (eq function-type 'FUNCTION_STATEMENT)
7995 (js2-record-imenu-functions fn-node))))
7996
7997 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7998 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7999 ;; We wait until after parsing the function to set its parent scope,
8000 ;; since `js2-define-symbol' needs the defining-scope check to stop
8001 ;; at the function boundary when checking for redeclarations.
8002 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8003 fn-node))
8004
8005 (defun js2-parse-statements (&optional parent)
8006 "Parse a statement list. Last token consumed must be js2-LC.
8007
8008 PARENT can be a `js2-block-node', in which case the statements are
8009 appended to PARENT. Otherwise a new `js2-block-node' is created
8010 and returned.
8011
8012 This function does not match the closing js2-RC: the caller
8013 matches the RC so it can provide a suitable error message if not
8014 matched. This means it's up to the caller to set the length of
8015 the node to include the closing RC. The node start pos is set to
8016 the absolute buffer start position, and the caller should fix it
8017 up to be relative to the parent node. All children of this block
8018 node are given relative start positions and correct lengths."
8019 (let ((pn (or parent (make-js2-block-node)))
8020 tt)
8021 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8022 (/= tt js2-RC))
8023 (js2-block-node-push pn (js2-parse-statement)))
8024 pn))
8025
8026 (defun js2-parse-statement ()
8027 (let (pn beg end)
8028 ;; coarse-grained user-interrupt check - needs work
8029 (and js2-parse-interruptable-p
8030 (zerop (% (cl-incf js2-parse-stmt-count)
8031 js2-statements-per-pause))
8032 (input-pending-p)
8033 (throw 'interrupted t))
8034 (setq pn (js2-statement-helper))
8035 ;; no-side-effects warning check
8036 (unless (js2-node-has-side-effects pn)
8037 (setq end (js2-node-end pn))
8038 (save-excursion
8039 (goto-char end)
8040 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8041 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8042 pn))
8043
8044 ;; These correspond to the switch cases in Parser.statementHelper
8045 (defconst js2-parsers
8046 (let ((parsers (make-vector js2-num-tokens
8047 #'js2-parse-expr-stmt)))
8048 (aset parsers js2-BREAK #'js2-parse-break)
8049 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8050 (aset parsers js2-CONST #'js2-parse-const-var)
8051 (aset parsers js2-CONTINUE #'js2-parse-continue)
8052 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8053 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8054 (aset parsers js2-DO #'js2-parse-do)
8055 (aset parsers js2-EXPORT #'js2-parse-export)
8056 (aset parsers js2-FOR #'js2-parse-for)
8057 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8058 (aset parsers js2-IF #'js2-parse-if)
8059 (aset parsers js2-IMPORT #'js2-parse-import)
8060 (aset parsers js2-LC #'js2-parse-block)
8061 (aset parsers js2-LET #'js2-parse-let-stmt)
8062 (aset parsers js2-NAME #'js2-parse-name-or-label)
8063 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8064 (aset parsers js2-SEMI #'js2-parse-semi)
8065 (aset parsers js2-SWITCH #'js2-parse-switch)
8066 (aset parsers js2-THROW #'js2-parse-throw)
8067 (aset parsers js2-TRY #'js2-parse-try)
8068 (aset parsers js2-VAR #'js2-parse-const-var)
8069 (aset parsers js2-WHILE #'js2-parse-while)
8070 (aset parsers js2-WITH #'js2-parse-with)
8071 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8072 parsers)
8073 "A vector mapping token types to parser functions.")
8074
8075 (defun js2-parse-warn-missing-semi (beg end)
8076 (and js2-mode-show-strict-warnings
8077 js2-strict-missing-semi-warning
8078 (js2-add-strict-warning
8079 "msg.missing.semi" nil
8080 ;; back up to beginning of statement or line
8081 (max beg (save-excursion
8082 (goto-char end)
8083 (point-at-bol)))
8084 end)))
8085
8086 (defconst js2-no-semi-insertion
8087 (list js2-IF
8088 js2-SWITCH
8089 js2-WHILE
8090 js2-DO
8091 js2-FOR
8092 js2-TRY
8093 js2-WITH
8094 js2-LC
8095 js2-ERROR
8096 js2-SEMI
8097 js2-CLASS
8098 js2-FUNCTION
8099 js2-EXPORT)
8100 "List of tokens that don't do automatic semicolon insertion.")
8101
8102 (defconst js2-autoinsert-semi-and-warn
8103 (list js2-ERROR js2-EOF js2-RC))
8104
8105 (defun js2-statement-helper ()
8106 (let* ((tt (js2-get-token))
8107 (first-tt tt)
8108 (parser (if (= tt js2-ERROR)
8109 #'js2-parse-semi
8110 (aref js2-parsers tt)))
8111 pn)
8112 ;; If the statement is set, then it's been told its label by now.
8113 (and js2-labeled-stmt
8114 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8115 (setq js2-labeled-stmt nil))
8116 (setq pn (funcall parser))
8117 ;; Don't do auto semi insertion for certain statement types.
8118 (unless (or (memq first-tt js2-no-semi-insertion)
8119 (js2-labeled-stmt-node-p pn))
8120 (js2-auto-insert-semicolon pn))
8121 pn))
8122
8123 (defun js2-auto-insert-semicolon (pn)
8124 (let* ((tt (js2-get-token))
8125 (pos (js2-node-pos pn)))
8126 (cond
8127 ((= tt js2-SEMI)
8128 ;; extend the node bounds to include the semicolon.
8129 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8130 ((memq tt js2-autoinsert-semi-and-warn)
8131 (js2-unget-token) ; Not ';', do not consume.
8132 ;; Autoinsert ;
8133 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8134 (t
8135 (if (not (js2-token-follows-eol-p (js2-current-token)))
8136 ;; Report error if no EOL or autoinsert ';' otherwise
8137 (js2-report-error "msg.no.semi.stmt")
8138 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8139 (js2-unget-token) ; Not ';', do not consume.
8140 ))))
8141
8142 (defun js2-parse-condition ()
8143 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8144 The parens are discarded and the expression node is returned.
8145 The `pos' field of the return value is set to an absolute position
8146 that must be fixed up by the caller.
8147 Return value is a list (EXPR LP RP), with absolute paren positions."
8148 (let (pn lp rp)
8149 (if (js2-must-match js2-LP "msg.no.paren.cond")
8150 (setq lp (js2-current-token-beg)))
8151 (setq pn (js2-parse-expr))
8152 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8153 (setq rp (js2-current-token-beg)))
8154 ;; Report strict warning on code like "if (a = 7) ..."
8155 (if (and js2-strict-cond-assign-warning
8156 (js2-assign-node-p pn))
8157 (js2-add-strict-warning "msg.equal.as.assign" nil
8158 (js2-node-pos pn)
8159 (+ (js2-node-pos pn)
8160 (js2-node-len pn))))
8161 (list pn lp rp)))
8162
8163 (defun js2-parse-if ()
8164 "Parser for if-statement. Last matched token must be js2-IF."
8165 (let ((pos (js2-current-token-beg))
8166 cond if-true if-false else-pos end pn)
8167 (setq cond (js2-parse-condition)
8168 if-true (js2-parse-statement)
8169 if-false (if (js2-match-token js2-ELSE)
8170 (progn
8171 (setq else-pos (- (js2-current-token-beg) pos))
8172 (js2-parse-statement)))
8173 end (js2-node-end (or if-false if-true))
8174 pn (make-js2-if-node :pos pos
8175 :len (- end pos)
8176 :condition (car cond)
8177 :then-part if-true
8178 :else-part if-false
8179 :else-pos else-pos
8180 :lp (js2-relpos (cl-second cond) pos)
8181 :rp (js2-relpos (cl-third cond) pos)))
8182 (js2-node-add-children pn (car cond) if-true if-false)
8183 pn))
8184
8185 (defun js2-parse-import ()
8186 "Parse import statement. The current token must be js2-IMPORT."
8187 (unless (js2-ast-root-p js2-current-scope)
8188 (js2-report-error "msg.mod.import.decl.at.top.level"))
8189 (let ((beg (js2-current-token-beg)))
8190 (cond ((js2-match-token js2-STRING)
8191 (make-js2-import-node
8192 :pos beg
8193 :len (- (js2-current-token-end) beg)
8194 :module-id (js2-current-token-string)))
8195 (t
8196 (let* ((import-clause (js2-parse-import-clause))
8197 (from-clause (and import-clause (js2-parse-from-clause)))
8198 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8199 (node (make-js2-import-node
8200 :pos beg
8201 :len (- (js2-current-token-end) beg)
8202 :import import-clause
8203 :from from-clause
8204 :module-id module-id)))
8205 (when import-clause
8206 (js2-node-add-children node import-clause))
8207 (when from-clause
8208 (js2-node-add-children node from-clause))
8209 node)))))
8210
8211 (defun js2-parse-import-clause ()
8212 "Parse the bindings in an import statement.
8213 This can take many forms:
8214
8215 ImportedDefaultBinding -> 'foo'
8216 NameSpaceImport -> '* as lib'
8217 NamedImports -> '{foo as bar, bang}'
8218 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8219 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8220
8221 Try to match namespace imports and named imports first because nothing can
8222 come after them. If it is an imported default binding, then it could have named
8223 imports or a namespace import that follows it.
8224 "
8225 (let* ((beg (js2-current-token-beg))
8226 (clause (make-js2-import-clause-node
8227 :pos beg))
8228 (children (list)))
8229 (cond
8230 ((js2-match-token js2-MUL)
8231 (let ((ns-import (js2-parse-namespace-import)))
8232 (when ns-import
8233 (let ((name-node (js2-namespace-import-node-name ns-import)))
8234 (js2-define-symbol
8235 js2-LET (js2-name-node-name name-node) name-node t)))
8236 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8237 (push ns-import children)))
8238 ((js2-match-token js2-LC)
8239 (let ((imports (js2-parse-export-bindings t)))
8240 (setf (js2-import-clause-node-named-imports clause) imports)
8241 (dolist (import imports)
8242 (push import children)
8243 (let ((name-node (js2-export-binding-node-local-name import)))
8244 (when name-node
8245 (js2-define-symbol
8246 js2-LET (js2-name-node-name name-node) name-node t))))))
8247 ((= (js2-peek-token) js2-NAME)
8248 (let ((binding (js2-maybe-parse-export-binding)))
8249 (let ((node-name (js2-export-binding-node-local-name binding)))
8250 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8251 (setf (js2-import-clause-node-default-binding clause) binding)
8252 (push binding children))
8253 (when (js2-match-token js2-COMMA)
8254 (cond
8255 ((js2-match-token js2-MUL)
8256 (let ((ns-import (js2-parse-namespace-import)))
8257 (let ((name-node (js2-namespace-import-node-name ns-import)))
8258 (js2-define-symbol
8259 js2-LET (js2-name-node-name name-node) name-node t))
8260 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8261 (push ns-import children)))
8262 ((js2-match-token js2-LC)
8263 (let ((imports (js2-parse-export-bindings t)))
8264 (setf (js2-import-clause-node-named-imports clause) imports)
8265 (dolist (import imports)
8266 (push import children)
8267 (let ((name-node (js2-export-binding-node-local-name import)))
8268 (when name-node
8269 (js2-define-symbol
8270 js2-LET (js2-name-node-name name-node) name-node t))))))
8271 (t (js2-report-error "msg.syntax")))))
8272 (t (js2-report-error "msg.mod.declaration.after.import")))
8273 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8274 (apply #'js2-node-add-children clause children)
8275 clause))
8276
8277 (defun js2-parse-namespace-import ()
8278 "Parse a namespace import expression such as '* as bar'.
8279 The current token must be js2-MUL."
8280 (let ((beg (js2-current-token-beg)))
8281 (when (js2-must-match js2-NAME "msg.syntax")
8282 (if (equal "as" (js2-current-token-string))
8283 (when (js2-must-match-prop-name "msg.syntax")
8284 (let ((node (make-js2-namespace-import-node
8285 :pos beg
8286 :len (- (js2-current-token-end) beg)
8287 :name (make-js2-name-node
8288 :pos (js2-current-token-beg)
8289 :len (js2-current-token-end)
8290 :name (js2-current-token-string)))))
8291 (js2-node-add-children node (js2-namespace-import-node-name node))
8292 node))
8293 (js2-unget-token)
8294 (js2-report-error "msg.syntax")))))
8295
8296
8297 (defun js2-parse-from-clause ()
8298 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8299 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8300 (let ((beg (js2-current-token-beg)))
8301 (if (equal "from" (js2-current-token-string))
8302 (cond
8303 ((js2-match-token js2-STRING)
8304 (make-js2-from-clause-node
8305 :pos beg
8306 :len (- (js2-current-token-end) beg)
8307 :module-id (js2-current-token-string)
8308 :metadata-p nil))
8309 ((js2-match-token js2-THIS)
8310 (when (js2-must-match-name "msg.mod.spec.after.from")
8311 (if (equal "module" (js2-current-token-string))
8312 (make-js2-from-clause-node
8313 :pos beg
8314 :len (- (js2-current-token-end) beg)
8315 :module-id "this"
8316 :metadata-p t)
8317 (js2-unget-token)
8318 (js2-unget-token)
8319 (js2-report-error "msg.mod.spec.after.from")
8320 nil)))
8321 (t (js2-report-error "msg.mod.spec.after.from") nil))
8322 (js2-unget-token)
8323 (js2-report-error "msg.mod.from.after.import.spec.set")
8324 nil))))
8325
8326 (defun js2-parse-export-bindings (&optional import-p)
8327 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8328 {foo as bar, baz as bang}. The current token must be
8329 js2-LC. Return a lisp list of js2-export-binding-node"
8330 (let ((bindings (list)))
8331 (while
8332 (let ((binding (js2-maybe-parse-export-binding)))
8333 (when binding
8334 (push binding bindings))
8335 (js2-match-token js2-COMMA)))
8336 (when (js2-must-match js2-RC (if import-p
8337 "msg.mod.rc.after.import.spec.list"
8338 "msg.mod.rc.after.export.spec.list"))
8339 (reverse bindings))))
8340
8341 (defun js2-maybe-parse-export-binding ()
8342 "Attempt to parse a binding expression found inside an import/export statement.
8343 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8344 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8345 js2-export-binding-node and consume all the tokens. If it does not match, it
8346 consumes no tokens."
8347 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8348 (beg (js2-current-token-beg))
8349 (extern-name-len (js2-current-token-len))
8350 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8351 (aref js2-kwd-tokens (js2-current-token-type)))))
8352 (if extern-name
8353 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8354 (if (and as (equal "as" (js2-current-token-string)))
8355 (let ((name
8356 (or
8357 (and (js2-match-token js2-DEFAULT) "default")
8358 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8359 (if name
8360 (let ((node (make-js2-export-binding-node
8361 :pos beg
8362 :len (- (js2-current-token-end) beg)
8363 :local-name (make-js2-name-node
8364 :name name
8365 :pos (js2-current-token-beg)
8366 :len (js2-current-token-len))
8367 :extern-name (make-js2-name-node
8368 :name extern-name
8369 :pos beg
8370 :len extern-name-len))))
8371 (js2-node-add-children
8372 node
8373 (js2-export-binding-node-local-name node)
8374 (js2-export-binding-node-extern-name node))
8375 node)
8376 (js2-unget-token)
8377 nil))
8378 (when as (js2-unget-token))
8379 (let* ((name-node (make-js2-name-node
8380 :name (js2-current-token-string)
8381 :pos (js2-current-token-beg)
8382 :len (js2-current-token-len)))
8383 (node (make-js2-export-binding-node
8384 :pos (js2-current-token-beg)
8385 :len (js2-current-token-len)
8386 :local-name name-node
8387 :extern-name name-node)))
8388 (when is-reserved-name
8389 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8390 (js2-node-add-children node name-node)
8391 node)))
8392 nil)))
8393
8394 (defun js2-parse-switch ()
8395 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8396 (let ((pos (js2-current-token-beg))
8397 tt pn discriminant has-default case-expr case-node
8398 case-pos cases stmt lp)
8399 (if (js2-must-match js2-LP "msg.no.paren.switch")
8400 (setq lp (js2-current-token-beg)))
8401 (setq discriminant (js2-parse-expr)
8402 pn (make-js2-switch-node :discriminant discriminant
8403 :pos pos
8404 :lp (js2-relpos lp pos)))
8405 (js2-node-add-children pn discriminant)
8406 (js2-enter-switch pn)
8407 (unwind-protect
8408 (progn
8409 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8410 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8411 (js2-must-match js2-LC "msg.no.brace.switch")
8412 (catch 'break
8413 (while t
8414 (setq tt (js2-next-token)
8415 case-pos (js2-current-token-beg))
8416 (cond
8417 ((= tt js2-RC)
8418 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8419 (throw 'break nil)) ; done
8420 ((= tt js2-CASE)
8421 (setq case-expr (js2-parse-expr))
8422 (js2-must-match js2-COLON "msg.no.colon.case"))
8423 ((= tt js2-DEFAULT)
8424 (if has-default
8425 (js2-report-error "msg.double.switch.default"))
8426 (setq has-default t
8427 case-expr nil)
8428 (js2-must-match js2-COLON "msg.no.colon.case"))
8429 (t
8430 (js2-report-error "msg.bad.switch")
8431 (throw 'break nil)))
8432 (setq case-node (make-js2-case-node :pos case-pos
8433 :len (- (js2-current-token-end) case-pos)
8434 :expr case-expr))
8435 (js2-node-add-children case-node case-expr)
8436 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8437 (/= tt js2-CASE)
8438 (/= tt js2-DEFAULT)
8439 (/= tt js2-EOF))
8440 (setf stmt (js2-parse-statement)
8441 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8442 (js2-block-node-push case-node stmt))
8443 (push case-node cases)))
8444 ;; add cases last, as pushing reverses the order to be correct
8445 (dolist (kid cases)
8446 (js2-node-add-children pn kid)
8447 (push kid (js2-switch-node-cases pn)))
8448 pn) ; return value
8449 (js2-exit-switch))))
8450
8451 (defun js2-parse-while ()
8452 "Parser for while-statement. Last matched token must be js2-WHILE."
8453 (let ((pos (js2-current-token-beg))
8454 (pn (make-js2-while-node))
8455 cond body)
8456 (js2-enter-loop pn)
8457 (unwind-protect
8458 (progn
8459 (setf cond (js2-parse-condition)
8460 (js2-while-node-condition pn) (car cond)
8461 body (js2-parse-statement)
8462 (js2-while-node-body pn) body
8463 (js2-node-len pn) (- (js2-node-end body) pos)
8464 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8465 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8466 (js2-node-add-children pn body (car cond)))
8467 (js2-exit-loop))
8468 pn))
8469
8470 (defun js2-parse-do ()
8471 "Parser for do-statement. Last matched token must be js2-DO."
8472 (let ((pos (js2-current-token-beg))
8473 (pn (make-js2-do-node))
8474 cond body end)
8475 (js2-enter-loop pn)
8476 (unwind-protect
8477 (progn
8478 (setq body (js2-parse-statement))
8479 (js2-must-match js2-WHILE "msg.no.while.do")
8480 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8481 cond (js2-parse-condition)
8482 (js2-do-node-condition pn) (car cond)
8483 (js2-do-node-body pn) body
8484 end js2-ts-cursor
8485 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8486 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8487 (js2-node-add-children pn (car cond) body))
8488 (js2-exit-loop))
8489 ;; Always auto-insert semicolon to follow SpiderMonkey:
8490 ;; It is required by ECMAScript but is ignored by the rest of
8491 ;; world; see bug 238945
8492 (if (js2-match-token js2-SEMI)
8493 (setq end js2-ts-cursor))
8494 (setf (js2-node-len pn) (- end pos))
8495 pn))
8496
8497 (defun js2-parse-export ()
8498 "Parse an export statement.
8499 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8500 expressions should only be either hoistable expressions (function or generator)
8501 or assignment expressions, but there is no checking to enforce that and so it
8502 will parse without error a small subset of
8503 invalid export statements."
8504 (unless (js2-ast-root-p js2-current-scope)
8505 (js2-report-error "msg.mod.export.decl.at.top.level"))
8506 (let ((beg (js2-current-token-beg))
8507 (children (list))
8508 exports-list from-clause declaration default)
8509 (cond
8510 ((js2-match-token js2-MUL)
8511 (setq from-clause (js2-parse-from-clause))
8512 (when from-clause
8513 (push from-clause children)))
8514 ((js2-match-token js2-LC)
8515 (setq exports-list (js2-parse-export-bindings))
8516 (when exports-list
8517 (dolist (export exports-list)
8518 (push export children)))
8519 (when (js2-match-token js2-NAME)
8520 (if (equal "from" (js2-current-token-string))
8521 (progn
8522 (js2-unget-token)
8523 (setq from-clause (js2-parse-from-clause)))
8524 (js2-unget-token))))
8525 ((js2-match-token js2-DEFAULT)
8526 (setq default (js2-parse-expr)))
8527 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8528 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8529 (t
8530 (setq declaration (js2-parse-expr))))
8531 (when from-clause
8532 (push from-clause children))
8533 (when declaration
8534 (push declaration children)
8535 (when (not (js2-function-node-p declaration))
8536 (js2-auto-insert-semicolon declaration)))
8537 (when default
8538 (push default children)
8539 (when (not (js2-function-node-p default))
8540 (js2-auto-insert-semicolon default)))
8541 (let ((node (make-js2-export-node
8542 :pos beg
8543 :len (- (js2-current-token-end) beg)
8544 :exports-list exports-list
8545 :from-clause from-clause
8546 :declaration declaration
8547 :default default)))
8548 (apply #'js2-node-add-children node children)
8549 node)))
8550
8551 (defun js2-parse-for ()
8552 "Parse a for, for-in or for each-in statement.
8553 Last matched token must be js2-FOR."
8554 (let ((for-pos (js2-current-token-beg))
8555 (tmp-scope (make-js2-scope))
8556 pn is-for-each is-for-in-or-of is-for-of
8557 in-pos each-pos tmp-pos
8558 init ; Node init is also foo in 'foo in object'.
8559 cond ; Node cond is also object in 'foo in object'.
8560 incr ; 3rd section of for-loop initializer.
8561 body tt lp rp)
8562 ;; See if this is a for each () instead of just a for ()
8563 (when (js2-match-token js2-NAME)
8564 (if (string= "each" (js2-current-token-string))
8565 (progn
8566 (setq is-for-each t
8567 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8568 (js2-record-face 'font-lock-keyword-face))
8569 (js2-report-error "msg.no.paren.for")))
8570 (if (js2-must-match js2-LP "msg.no.paren.for")
8571 (setq lp (- (js2-current-token-beg) for-pos)))
8572 (setq tt (js2-get-token))
8573 ;; Capture identifiers inside parens. We can't create the node
8574 ;; (and use it as the current scope) until we know its type.
8575 (js2-push-scope tmp-scope)
8576 (unwind-protect
8577 (progn
8578 ;; parse init clause
8579 (let ((js2-in-for-init t)) ; set as dynamic variable
8580 (cond
8581 ((= tt js2-SEMI)
8582 (js2-unget-token)
8583 (setq init (make-js2-empty-expr-node)))
8584 ((or (= tt js2-VAR) (= tt js2-LET))
8585 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8586 (t
8587 (js2-unget-token)
8588 (setq init (js2-parse-expr)))))
8589 (if (or (js2-match-token js2-IN)
8590 (and (>= js2-language-version 200)
8591 (js2-match-contextual-kwd "of")
8592 (setq is-for-of t)))
8593 (setq is-for-in-or-of t
8594 in-pos (- (js2-current-token-beg) for-pos)
8595 ;; scope of iteration target object is not the scope we've created above.
8596 ;; stash current scope temporary.
8597 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8598 (js2-parse-expr))) ; object over which we're iterating
8599 ;; else ordinary for loop - parse cond and incr
8600 (js2-must-match js2-SEMI "msg.no.semi.for")
8601 (setq cond (if (= (js2-peek-token) js2-SEMI)
8602 (make-js2-empty-expr-node) ; no loop condition
8603 (js2-parse-expr)))
8604 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8605 (setq tmp-pos (js2-current-token-end)
8606 incr (if (= (js2-peek-token) js2-RP)
8607 (make-js2-empty-expr-node :pos tmp-pos)
8608 (js2-parse-expr)))))
8609 (js2-pop-scope))
8610 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8611 (setq rp (- (js2-current-token-beg) for-pos)))
8612 (if (not is-for-in-or-of)
8613 (setq pn (make-js2-for-node :init init
8614 :condition cond
8615 :update incr
8616 :lp lp
8617 :rp rp))
8618 ;; cond could be null if 'in obj' got eaten by the init node.
8619 (if (js2-infix-node-p init)
8620 ;; it was (foo in bar) instead of (var foo in bar)
8621 (setq cond (js2-infix-node-right init)
8622 init (js2-infix-node-left init))
8623 (if (and (js2-var-decl-node-p init)
8624 (> (length (js2-var-decl-node-kids init)) 1))
8625 (js2-report-error "msg.mult.index")))
8626 (setq pn (make-js2-for-in-node :iterator init
8627 :object cond
8628 :in-pos in-pos
8629 :foreach-p is-for-each
8630 :each-pos each-pos
8631 :forof-p is-for-of
8632 :lp lp
8633 :rp rp)))
8634 ;; Transplant the declarations.
8635 (setf (js2-scope-symbol-table pn)
8636 (js2-scope-symbol-table tmp-scope))
8637 (unwind-protect
8638 (progn
8639 (js2-enter-loop pn)
8640 ;; We have to parse the body -after- creating the loop node,
8641 ;; so that the loop node appears in the js2-loop-set, allowing
8642 ;; break/continue statements to find the enclosing loop.
8643 (setf body (js2-parse-statement)
8644 (js2-loop-node-body pn) body
8645 (js2-node-pos pn) for-pos
8646 (js2-node-len pn) (- (js2-node-end body) for-pos))
8647 (js2-node-add-children pn init cond incr body))
8648 ;; finally
8649 (js2-exit-loop))
8650 pn))
8651
8652 (defun js2-parse-try ()
8653 "Parse a try statement. Last matched token must be js2-TRY."
8654 (let ((try-pos (js2-current-token-beg))
8655 try-end
8656 try-block
8657 catch-blocks
8658 finally-block
8659 saw-default-catch
8660 peek)
8661 (if (/= (js2-peek-token) js2-LC)
8662 (js2-report-error "msg.no.brace.try"))
8663 (setq try-block (js2-parse-statement)
8664 try-end (js2-node-end try-block)
8665 peek (js2-peek-token))
8666 (cond
8667 ((= peek js2-CATCH)
8668 (while (js2-match-token js2-CATCH)
8669 (let* ((catch-pos (js2-current-token-beg))
8670 (catch-node (make-js2-catch-node :pos catch-pos))
8671 param
8672 guard-kwd
8673 catch-cond
8674 lp rp)
8675 (if saw-default-catch
8676 (js2-report-error "msg.catch.unreachable"))
8677 (if (js2-must-match js2-LP "msg.no.paren.catch")
8678 (setq lp (- (js2-current-token-beg) catch-pos)))
8679 (js2-push-scope catch-node)
8680 (let ((tt (js2-peek-token)))
8681 (cond
8682 ;; Destructuring pattern:
8683 ;; catch ({ message, file }) { ... }
8684 ((or (= tt js2-LB) (= tt js2-LC))
8685 (js2-get-token)
8686 (setq param (js2-parse-destruct-primary-expr))
8687 (js2-define-destruct-symbols param js2-LET nil))
8688 ;; Simple name.
8689 (t
8690 (js2-must-match-name "msg.bad.catchcond")
8691 (setq param (js2-create-name-node))
8692 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8693 ;; Catch condition.
8694 (if (js2-match-token js2-IF)
8695 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8696 catch-cond (js2-parse-expr))
8697 (setq saw-default-catch t))
8698 (if (js2-must-match js2-RP "msg.bad.catchcond")
8699 (setq rp (- (js2-current-token-beg) catch-pos)))
8700 (js2-must-match js2-LC "msg.no.brace.catchblock")
8701 (js2-parse-statements catch-node)
8702 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8703 (setq try-end (js2-current-token-end)))
8704 (js2-pop-scope)
8705 (setf (js2-node-len catch-node) (- try-end catch-pos)
8706 (js2-catch-node-param catch-node) param
8707 (js2-catch-node-guard-expr catch-node) catch-cond
8708 (js2-catch-node-guard-kwd catch-node) guard-kwd
8709 (js2-catch-node-lp catch-node) lp
8710 (js2-catch-node-rp catch-node) rp)
8711 (js2-node-add-children catch-node param catch-cond)
8712 (push catch-node catch-blocks))))
8713 ((/= peek js2-FINALLY)
8714 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8715 (js2-node-pos try-block)
8716 (- (setq try-end (js2-node-end try-block))
8717 (js2-node-pos try-block)))))
8718 (when (js2-match-token js2-FINALLY)
8719 (let ((finally-pos (js2-current-token-beg))
8720 (block (js2-parse-statement)))
8721 (setq try-end (js2-node-end block)
8722 finally-block (make-js2-finally-node :pos finally-pos
8723 :len (- try-end finally-pos)
8724 :body block))
8725 (js2-node-add-children finally-block block)))
8726 (let ((pn (make-js2-try-node :pos try-pos
8727 :len (- try-end try-pos)
8728 :try-block try-block
8729 :finally-block finally-block)))
8730 (js2-node-add-children pn try-block finally-block)
8731 ;; Push them onto the try-node, which reverses and corrects their order.
8732 (dolist (cb catch-blocks)
8733 (js2-node-add-children pn cb)
8734 (push cb (js2-try-node-catch-clauses pn)))
8735 pn)))
8736
8737 (defun js2-parse-throw ()
8738 "Parser for throw-statement. Last matched token must be js2-THROW."
8739 (let ((pos (js2-current-token-beg))
8740 expr pn)
8741 (if (= (js2-peek-token-or-eol) js2-EOL)
8742 ;; ECMAScript does not allow new lines before throw expression,
8743 ;; see bug 256617
8744 (js2-report-error "msg.bad.throw.eol"))
8745 (setq expr (js2-parse-expr)
8746 pn (make-js2-throw-node :pos pos
8747 :len (- (js2-node-end expr) pos)
8748 :expr expr))
8749 (js2-node-add-children pn expr)
8750 pn))
8751
8752 (defun js2-match-jump-label-name (label-name)
8753 "If break/continue specified a label, return that label's labeled stmt.
8754 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8755 does not match an existing label, reports an error and returns nil."
8756 (let ((bundle (cdr (assoc label-name js2-label-set))))
8757 (if (null bundle)
8758 (js2-report-error "msg.undef.label"))
8759 bundle))
8760
8761 (defun js2-parse-break ()
8762 "Parser for break-statement. Last matched token must be js2-BREAK."
8763 (let ((pos (js2-current-token-beg))
8764 (end (js2-current-token-end))
8765 break-target ; statement to break from
8766 break-label ; in "break foo", name-node representing the foo
8767 labels ; matching labeled statement to break to
8768 pn)
8769 (when (eq (js2-peek-token-or-eol) js2-NAME)
8770 (js2-get-token)
8771 (setq break-label (js2-create-name-node)
8772 end (js2-node-end break-label)
8773 ;; matchJumpLabelName only matches if there is one
8774 labels (js2-match-jump-label-name (js2-current-token-string))
8775 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8776 (unless (or break-target break-label)
8777 ;; no break target specified - try for innermost enclosing loop/switch
8778 (if (null js2-loop-and-switch-set)
8779 (unless break-label
8780 (js2-report-error "msg.bad.break" nil pos (length "break")))
8781 (setq break-target (car js2-loop-and-switch-set))))
8782 (setq pn (make-js2-break-node :pos pos
8783 :len (- end pos)
8784 :label break-label
8785 :target break-target))
8786 (js2-node-add-children pn break-label) ; but not break-target
8787 pn))
8788
8789 (defun js2-parse-continue ()
8790 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8791 (let ((pos (js2-current-token-beg))
8792 (end (js2-current-token-end))
8793 label ; optional user-specified label, a `js2-name-node'
8794 labels ; current matching labeled stmt, if any
8795 target ; the `js2-loop-node' target of this continue stmt
8796 pn)
8797 (when (= (js2-peek-token-or-eol) js2-NAME)
8798 (js2-get-token)
8799 (setq label (js2-create-name-node)
8800 end (js2-node-end label)
8801 ;; matchJumpLabelName only matches if there is one
8802 labels (js2-match-jump-label-name (js2-current-token-string))))
8803 (cond
8804 ((null labels) ; no current label to go to
8805 (if (null js2-loop-set) ; no loop to continue to
8806 (js2-report-error "msg.continue.outside" nil pos
8807 (length "continue"))
8808 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8809 (t
8810 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8811 (setq target (js2-labeled-stmt-node-stmt labels))
8812 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8813 (setq pn (make-js2-continue-node :pos pos
8814 :len (- end pos)
8815 :label label
8816 :target target))
8817 (js2-node-add-children pn label) ; but not target - it's not our child
8818 pn))
8819
8820 (defun js2-parse-with ()
8821 "Parser for with-statement. Last matched token must be js2-WITH."
8822 (let ((pos (js2-current-token-beg))
8823 obj body pn lp rp)
8824 (if (js2-must-match js2-LP "msg.no.paren.with")
8825 (setq lp (js2-current-token-beg)))
8826 (setq obj (js2-parse-expr))
8827 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8828 (setq rp (js2-current-token-beg)))
8829 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8830 (setq body (js2-parse-statement)))
8831 (setq pn (make-js2-with-node :pos pos
8832 :len (- (js2-node-end body) pos)
8833 :object obj
8834 :body body
8835 :lp (js2-relpos lp pos)
8836 :rp (js2-relpos rp pos)))
8837 (js2-node-add-children pn obj body)
8838 pn))
8839
8840 (defun js2-parse-const-var ()
8841 "Parser for var- or const-statement.
8842 Last matched token must be js2-CONST or js2-VAR."
8843 (let ((tt (js2-current-token-type))
8844 (pos (js2-current-token-beg))
8845 expr pn)
8846 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8847 pn (make-js2-expr-stmt-node :pos pos
8848 :len (- (js2-node-end expr) pos)
8849 :expr expr))
8850 (js2-node-add-children pn expr)
8851 pn))
8852
8853 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8854 (let ((pn (make-js2-expr-stmt-node :pos pos
8855 :len (js2-node-len expr)
8856 :type (if (js2-inside-function)
8857 js2-EXPR_VOID
8858 js2-EXPR_RESULT)
8859 :expr expr)))
8860 (if add-child
8861 (js2-node-add-children pn expr))
8862 pn))
8863
8864 (defun js2-parse-let-stmt ()
8865 "Parser for let-statement. Last matched token must be js2-LET."
8866 (let ((pos (js2-current-token-beg))
8867 expr pn)
8868 (if (= (js2-peek-token) js2-LP)
8869 ;; let expression in statement context
8870 (setq expr (js2-parse-let pos 'statement)
8871 pn (js2-wrap-with-expr-stmt pos expr t))
8872 ;; else we're looking at a statement like let x=6, y=7;
8873 (setf expr (js2-parse-variables js2-LET pos)
8874 pn (js2-wrap-with-expr-stmt pos expr t)
8875 (js2-node-type pn) js2-EXPR_RESULT))
8876 pn))
8877
8878 (defun js2-parse-ret-yield ()
8879 (js2-parse-return-or-yield (js2-current-token-type) nil))
8880
8881 (defconst js2-parse-return-stmt-enders
8882 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8883
8884 (defsubst js2-now-all-set (before after mask)
8885 "Return whether or not the bits in the mask have changed to all set.
8886 BEFORE is bits before change, AFTER is bits after change, and MASK is
8887 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8888 but not BEFORE."
8889 (and (/= (logand before mask) mask)
8890 (= (logand after mask) mask)))
8891
8892 (defun js2-parse-return-or-yield (tt expr-context)
8893 (let* ((pos (js2-current-token-beg))
8894 (end (js2-current-token-end))
8895 (before js2-end-flags)
8896 (inside-function (js2-inside-function))
8897 (gen-type (and inside-function (js2-function-node-generator-type
8898 js2-current-script-or-fn)))
8899 e ret name yield-star-p)
8900 (unless inside-function
8901 (js2-report-error (if (eq tt js2-RETURN)
8902 "msg.bad.return"
8903 "msg.bad.yield")))
8904 (when (and inside-function
8905 (eq gen-type 'STAR)
8906 (js2-match-token js2-MUL))
8907 (setq yield-star-p t))
8908 ;; This is ugly, but we don't want to require a semicolon.
8909 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8910 (setq e (js2-parse-expr)
8911 end (js2-node-end e)))
8912 (cond
8913 ((eq tt js2-RETURN)
8914 (js2-set-flag js2-end-flags (if (null e)
8915 js2-end-returns
8916 js2-end-returns-value))
8917 (setq ret (make-js2-return-node :pos pos
8918 :len (- end pos)
8919 :retval e))
8920 (js2-node-add-children ret e)
8921 ;; See if we need a strict mode warning.
8922 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8923 ;; more thorough and accurate than this before/after flag check.
8924 ;; E.g. if there's a finally-block that always returns, we shouldn't
8925 ;; show a warning generated by inconsistent returns in the catch blocks.
8926 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8927 ;; so we know which returns/yields to highlight, and we should get rid of
8928 ;; all the checking in `js2-parse-return-or-yield'.
8929 (if (and js2-strict-inconsistent-return-warning
8930 (js2-now-all-set before js2-end-flags
8931 (logior js2-end-returns js2-end-returns-value)))
8932 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8933 ((eq gen-type 'COMPREHENSION)
8934 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8935 ;; like SpiderMonkey does.
8936 (js2-report-error "msg.syntax" nil pos 5))
8937 (t
8938 (setq ret (make-js2-yield-node :pos pos
8939 :len (- end pos)
8940 :value e
8941 :star-p yield-star-p))
8942 (js2-node-add-children ret e)
8943 (unless expr-context
8944 (setq e ret
8945 ret (js2-wrap-with-expr-stmt pos e t))
8946 (js2-set-requires-activation)
8947 (js2-set-is-generator))))
8948 ;; see if we are mixing yields and value returns.
8949 (when (and inside-function
8950 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8951 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8952 'LEGACY))
8953 (setq name (js2-function-name js2-current-script-or-fn))
8954 (if (zerop (length name))
8955 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8956 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8957 ret))
8958
8959 (defun js2-parse-debugger ()
8960 (make-js2-keyword-node :type js2-DEBUGGER))
8961
8962 (defun js2-parse-block ()
8963 "Parser for a curly-delimited statement block.
8964 Last token matched must be `js2-LC'."
8965 (let ((pos (js2-current-token-beg))
8966 (pn (make-js2-scope)))
8967 (js2-push-scope pn)
8968 (unwind-protect
8969 (progn
8970 (js2-parse-statements pn)
8971 (js2-must-match js2-RC "msg.no.brace.block")
8972 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8973 (js2-pop-scope))
8974 pn))
8975
8976 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8977 (defun js2-parse-semi ()
8978 "Parse a statement or handle an error.
8979 Current token type is `js2-SEMI' or `js2-ERROR'."
8980 (let ((tt (js2-current-token-type)) pos len)
8981 (if (eq tt js2-SEMI)
8982 (make-js2-empty-expr-node :len 1)
8983 (setq pos (js2-current-token-beg)
8984 len (- (js2-current-token-end) pos))
8985 (js2-report-error "msg.syntax" nil pos len)
8986 (make-js2-error-node :pos pos :len len))))
8987
8988 (defun js2-parse-default-xml-namespace ()
8989 "Parse a `default xml namespace = <expr>' e4x statement."
8990 (let ((pos (js2-current-token-beg))
8991 end len expr unary)
8992 (js2-must-have-xml)
8993 (js2-set-requires-activation)
8994 (setq len (- js2-ts-cursor pos))
8995 (unless (and (js2-match-token js2-NAME)
8996 (string= (js2-current-token-string) "xml"))
8997 (js2-report-error "msg.bad.namespace" nil pos len))
8998 (unless (and (js2-match-token js2-NAME)
8999 (string= (js2-current-token-string) "namespace"))
9000 (js2-report-error "msg.bad.namespace" nil pos len))
9001 (unless (js2-match-token js2-ASSIGN)
9002 (js2-report-error "msg.bad.namespace" nil pos len))
9003 (setq expr (js2-parse-expr)
9004 end (js2-node-end expr)
9005 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9006 :pos pos
9007 :len (- end pos)
9008 :operand expr))
9009 (js2-node-add-children unary expr)
9010 (make-js2-expr-stmt-node :pos pos
9011 :len (- end pos)
9012 :expr unary)))
9013
9014 (defun js2-record-label (label bundle)
9015 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9016 (js2-get-token)
9017 (let ((name (js2-label-node-name label))
9018 labeled-stmt
9019 dup)
9020 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9021 ;; flag both labels if possible when used in editing mode
9022 (if (and js2-parse-ide-mode
9023 (setq dup (js2-get-label-by-name labeled-stmt name)))
9024 (js2-report-error "msg.dup.label" nil
9025 (js2-node-abs-pos dup) (js2-node-len dup)))
9026 (js2-report-error "msg.dup.label" nil
9027 (js2-node-pos label) (js2-node-len label)))
9028 (js2-labeled-stmt-node-add-label bundle label)
9029 (js2-node-add-children bundle label)
9030 ;; Add one reference to the bundle per label in `js2-label-set'
9031 (push (cons name bundle) js2-label-set)))
9032
9033 (defun js2-parse-name-or-label ()
9034 "Parser for identifier or label. Last token matched must be js2-NAME.
9035 Called when we found a name in a statement context. If it's a label, we gather
9036 up any following labels and the next non-label statement into a
9037 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9038 expression and return it wrapped in a `js2-expr-stmt-node'."
9039 (let ((pos (js2-current-token-beg))
9040 expr stmt bundle
9041 (continue t))
9042 ;; set check for label and call down to `js2-parse-primary-expr'
9043 (setq expr (js2-maybe-parse-label))
9044 (if (null expr)
9045 ;; Parse the non-label expression and wrap with expression stmt.
9046 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9047 ;; else parsed a label
9048 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9049 (js2-record-label expr bundle)
9050 ;; look for more labels
9051 (while (and continue (= (js2-get-token) js2-NAME))
9052 (if (setq expr (js2-maybe-parse-label))
9053 (js2-record-label expr bundle)
9054 (setq expr (js2-parse-expr)
9055 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9056 continue nil)
9057 (js2-auto-insert-semicolon stmt)))
9058 ;; no more labels; now parse the labeled statement
9059 (unwind-protect
9060 (unless stmt
9061 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9062 (js2-unget-token)
9063 (setq stmt (js2-statement-helper))))
9064 ;; remove the labels for this statement from the global set
9065 (dolist (label (js2-labeled-stmt-node-labels bundle))
9066 (setq js2-label-set (remove label js2-label-set))))
9067 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9068 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9069 (js2-node-add-children bundle stmt)
9070 bundle)))
9071
9072 (defun js2-maybe-parse-label ()
9073 (cl-assert (= (js2-current-token-type) js2-NAME))
9074 (let (label-pos
9075 (next-tt (js2-get-token))
9076 (label-end (js2-current-token-end)))
9077 ;; Do not consume colon, it is used as unwind indicator
9078 ;; to return to statementHelper.
9079 (js2-unget-token)
9080 (if (= next-tt js2-COLON)
9081 (prog2
9082 (setq label-pos (js2-current-token-beg))
9083 (make-js2-label-node :pos label-pos
9084 :len (- label-end label-pos)
9085 :name (js2-current-token-string))
9086 (js2-set-face label-pos
9087 label-end
9088 'font-lock-variable-name-face 'record))
9089 ;; Backtrack from the name token, too.
9090 (js2-unget-token)
9091 nil)))
9092
9093 (defun js2-parse-expr-stmt ()
9094 "Default parser in statement context, if no recognized statement found."
9095 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9096 (progn
9097 (js2-unget-token)
9098 (js2-parse-expr)) t))
9099
9100 (defun js2-parse-variables (decl-type pos)
9101 "Parse a comma-separated list of variable declarations.
9102 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9103
9104 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9105 For 'var' or 'const', the keyword should be the token last scanned.
9106
9107 POS is the position where the node should start. It's sometimes the
9108 var/const/let keyword, and other times the beginning of the first token
9109 in the first variable declaration.
9110
9111 Returns the parsed `js2-var-decl-node' expression node."
9112 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9113 :pos pos))
9114 destructuring kid-pos tt init name end nbeg nend vi
9115 (continue t))
9116 ;; Example:
9117 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9118 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9119 ;; var {a, b} = baz;
9120 (while continue
9121 (setq destructuring nil
9122 name nil
9123 tt (js2-get-token)
9124 kid-pos (js2-current-token-beg)
9125 end (js2-current-token-end)
9126 init nil)
9127 (if (or (= tt js2-LB) (= tt js2-LC))
9128 ;; Destructuring assignment, e.g., var [a, b] = ...
9129 (setq destructuring (js2-parse-destruct-primary-expr)
9130 end (js2-node-end destructuring))
9131 ;; Simple variable name
9132 (js2-unget-token)
9133 (when (js2-must-match-name "msg.bad.var")
9134 (setq name (js2-create-name-node)
9135 nbeg (js2-current-token-beg)
9136 nend (js2-current-token-end)
9137 end nend)
9138 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9139 (when (js2-match-token js2-ASSIGN)
9140 (setq init (js2-parse-assign-expr)
9141 end (js2-node-end init))
9142 (js2-record-imenu-functions init name))
9143 (when name
9144 (js2-set-face nbeg nend (if (js2-function-node-p init)
9145 'font-lock-function-name-face
9146 'font-lock-variable-name-face)
9147 'record))
9148 (setq vi (make-js2-var-init-node :pos kid-pos
9149 :len (- end kid-pos)
9150 :type decl-type))
9151 (if destructuring
9152 (progn
9153 (if (and (null init) (not js2-in-for-init))
9154 (js2-report-error "msg.destruct.assign.no.init"))
9155 (js2-define-destruct-symbols destructuring
9156 decl-type
9157 'font-lock-variable-name-face)
9158 (setf (js2-var-init-node-target vi) destructuring))
9159 (setf (js2-var-init-node-target vi) name))
9160 (setf (js2-var-init-node-initializer vi) init)
9161 (js2-node-add-children vi name destructuring init)
9162 (js2-block-node-push result vi)
9163 (unless (js2-match-token js2-COMMA)
9164 (setq continue nil)))
9165 (setf (js2-node-len result) (- end pos))
9166 result))
9167
9168 (defun js2-parse-let (pos &optional stmt-p)
9169 "Parse a let expression or statement.
9170 A let-expression is of the form `let (vars) expr'.
9171 A let-statement is of the form `let (vars) {statements}'.
9172 The third form of let is a variable declaration list, handled
9173 by `js2-parse-variables'."
9174 (let ((pn (make-js2-let-node :pos pos))
9175 beg vars body)
9176 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9177 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9178 (js2-push-scope pn)
9179 (unwind-protect
9180 (progn
9181 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9182 (if (js2-must-match js2-RP "msg.no.paren.let")
9183 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9184 (if (and stmt-p (js2-match-token js2-LC))
9185 ;; let statement
9186 (progn
9187 (setf beg (js2-current-token-beg) ; position stmt at LC
9188 body (js2-parse-statements))
9189 (js2-must-match js2-RC "msg.no.curly.let")
9190 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9191 (js2-node-len pn) (- (js2-current-token-end) pos)
9192 (js2-let-node-body pn) body
9193 (js2-node-type pn) js2-LET))
9194 ;; let expression
9195 (setf body (js2-parse-expr)
9196 (js2-node-len pn) (- (js2-node-end body) pos)
9197 (js2-let-node-body pn) body))
9198 (setf (js2-let-node-vars pn) vars)
9199 (js2-node-add-children pn vars body))
9200 (js2-pop-scope))
9201 pn))
9202
9203 (defun js2-define-new-symbol (decl-type name node &optional scope)
9204 (js2-scope-put-symbol (or scope js2-current-scope)
9205 name
9206 (make-js2-symbol decl-type name node)))
9207
9208 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9209 "Define a symbol in the current scope.
9210 If NODE is non-nil, it is the AST node associated with the symbol."
9211 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9212 (symbol (if defining-scope
9213 (js2-scope-get-symbol defining-scope name)))
9214 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9215 (pos (if node (js2-node-abs-pos node)))
9216 (len (if node (js2-node-len node))))
9217 (cond
9218 ((and symbol ; already defined
9219 (or (= sdt js2-CONST) ; old version is const
9220 (= decl-type js2-CONST) ; new version is const
9221 ;; two let-bound vars in this block have same name
9222 (and (= sdt js2-LET)
9223 (eq defining-scope js2-current-scope))))
9224 (js2-report-error
9225 (cond
9226 ((= sdt js2-CONST) "msg.const.redecl")
9227 ((= sdt js2-LET) "msg.let.redecl")
9228 ((= sdt js2-VAR) "msg.var.redecl")
9229 ((= sdt js2-FUNCTION) "msg.function.redecl")
9230 (t "msg.parm.redecl"))
9231 name pos len))
9232 ((= decl-type js2-LET)
9233 (if (and (not ignore-not-in-block)
9234 (or (= (js2-node-type js2-current-scope) js2-IF)
9235 (js2-loop-node-p js2-current-scope)))
9236 (js2-report-error "msg.let.decl.not.in.block")
9237 (js2-define-new-symbol decl-type name node)))
9238 ((or (= decl-type js2-VAR)
9239 (= decl-type js2-CONST)
9240 (= decl-type js2-FUNCTION))
9241 (if symbol
9242 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9243 (js2-add-strict-warning "msg.var.redecl" name)
9244 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9245 (js2-add-strict-warning "msg.var.hides.arg" name)))
9246 (js2-define-new-symbol decl-type name node
9247 js2-current-script-or-fn)))
9248 ((= decl-type js2-LP)
9249 (if symbol
9250 ;; must be duplicate parameter. Second parameter hides the
9251 ;; first, so go ahead and add the second pararameter
9252 (js2-report-warning "msg.dup.parms" name))
9253 (js2-define-new-symbol decl-type name node))
9254 (t (js2-code-bug)))))
9255
9256 (defun js2-parse-paren-expr-or-generator-comp ()
9257 (let ((px-pos (js2-current-token-beg)))
9258 (cond
9259 ((and (>= js2-language-version 200)
9260 (js2-match-token js2-FOR))
9261 (js2-parse-generator-comp px-pos))
9262 ((and (>= js2-language-version 200)
9263 (js2-match-token js2-RP))
9264 ;; Not valid expression syntax, but this is valid in an arrow
9265 ;; function with no params: () => body.
9266 (if (eq (js2-peek-token) js2-ARROW)
9267 ;; Return whatever, it will hopefully be rewinded and
9268 ;; reparsed when we reach the =>.
9269 (make-js2-keyword-node :type js2-NULL)
9270 (js2-report-error "msg.syntax")
9271 (make-js2-error-node)))
9272 (t
9273 (let* ((js2-in-for-init nil)
9274 (expr (js2-parse-expr))
9275 (pn (make-js2-paren-node :pos px-pos
9276 :expr expr)))
9277 (js2-node-add-children pn (js2-paren-node-expr pn))
9278 (js2-must-match js2-RP "msg.no.paren")
9279 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9280 pn)))))
9281
9282 (defun js2-parse-expr (&optional oneshot)
9283 (let* ((pn (js2-parse-assign-expr))
9284 (pos (js2-node-pos pn))
9285 left
9286 right
9287 op-pos)
9288 (while (and (not oneshot)
9289 (js2-match-token js2-COMMA))
9290 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9291 (if (= (js2-peek-token) js2-YIELD)
9292 (js2-report-error "msg.yield.parenthesized"))
9293 (setq right (js2-parse-assign-expr)
9294 left pn
9295 pn (make-js2-infix-node :type js2-COMMA
9296 :pos pos
9297 :len (- js2-ts-cursor pos)
9298 :op-pos op-pos
9299 :left left
9300 :right right))
9301 (js2-node-add-children pn left right))
9302 pn))
9303
9304 (defun js2-parse-assign-expr ()
9305 (let ((tt (js2-get-token))
9306 (pos (js2-current-token-beg))
9307 pn left right op-pos
9308 ts-state recorded-identifiers parsed-errors)
9309 (if (= tt js2-YIELD)
9310 (js2-parse-return-or-yield tt t)
9311 ;; Save the tokenizer state in case we find an arrow function
9312 ;; and have to rewind.
9313 (setq ts-state (make-js2-ts-state)
9314 recorded-identifiers js2-recorded-identifiers
9315 parsed-errors js2-parsed-errors)
9316 ;; not yield - parse assignment expression
9317 (setq pn (js2-parse-cond-expr)
9318 tt (js2-get-token))
9319 (cond
9320 ((and (<= js2-first-assign tt)
9321 (<= tt js2-last-assign))
9322 ;; tt express assignment (=, |=, ^=, ..., %=)
9323 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9324 left pn)
9325 (setq right (js2-parse-assign-expr)
9326 pn (make-js2-assign-node :type tt
9327 :pos pos
9328 :len (- (js2-node-end right) pos)
9329 :op-pos op-pos
9330 :left left
9331 :right right))
9332 (when js2-parse-ide-mode
9333 (js2-highlight-assign-targets pn left right)
9334 (js2-record-imenu-functions right left))
9335 ;; do this last so ide checks above can use absolute positions
9336 (js2-node-add-children pn left right))
9337 ((and (= tt js2-ARROW)
9338 (>= js2-language-version 200))
9339 (js2-ts-seek ts-state)
9340 (setq js2-recorded-identifiers recorded-identifiers
9341 js2-parsed-errors parsed-errors)
9342 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9343 (t
9344 (js2-unget-token)))
9345 pn)))
9346
9347 (defun js2-parse-cond-expr ()
9348 (let ((pos (js2-current-token-beg))
9349 (pn (js2-parse-or-expr))
9350 test-expr
9351 if-true
9352 if-false
9353 q-pos
9354 c-pos)
9355 (when (js2-match-token js2-HOOK)
9356 (setq q-pos (- (js2-current-token-beg) pos)
9357 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9358 (js2-must-match js2-COLON "msg.no.colon.cond")
9359 (setq c-pos (- (js2-current-token-beg) pos)
9360 if-false (js2-parse-assign-expr)
9361 test-expr pn
9362 pn (make-js2-cond-node :pos pos
9363 :len (- (js2-node-end if-false) pos)
9364 :test-expr test-expr
9365 :true-expr if-true
9366 :false-expr if-false
9367 :q-pos q-pos
9368 :c-pos c-pos))
9369 (js2-node-add-children pn test-expr if-true if-false))
9370 pn))
9371
9372 (defun js2-make-binary (type left parser)
9373 "Helper for constructing a binary-operator AST node.
9374 LEFT is the left-side-expression, already parsed, and the
9375 binary operator should have just been matched.
9376 PARSER is a function to call to parse the right operand,
9377 or a `js2-node' struct if it has already been parsed.
9378 FIXME: The latter option is unused?"
9379 (let* ((pos (js2-node-pos left))
9380 (op-pos (- (js2-current-token-beg) pos))
9381 (right (if (js2-node-p parser)
9382 parser
9383 (js2-get-token)
9384 (funcall parser)))
9385 (pn (make-js2-infix-node :type type
9386 :pos pos
9387 :len (- (js2-node-end right) pos)
9388 :op-pos op-pos
9389 :left left
9390 :right right)))
9391 (js2-node-add-children pn left right)
9392 pn))
9393
9394 (defun js2-parse-or-expr ()
9395 (let ((pn (js2-parse-and-expr)))
9396 (when (js2-match-token js2-OR)
9397 (setq pn (js2-make-binary js2-OR
9398 pn
9399 'js2-parse-or-expr)))
9400 pn))
9401
9402 (defun js2-parse-and-expr ()
9403 (let ((pn (js2-parse-bit-or-expr)))
9404 (when (js2-match-token js2-AND)
9405 (setq pn (js2-make-binary js2-AND
9406 pn
9407 'js2-parse-and-expr)))
9408 pn))
9409
9410 (defun js2-parse-bit-or-expr ()
9411 (let ((pn (js2-parse-bit-xor-expr)))
9412 (while (js2-match-token js2-BITOR)
9413 (setq pn (js2-make-binary js2-BITOR
9414 pn
9415 'js2-parse-bit-xor-expr)))
9416 pn))
9417
9418 (defun js2-parse-bit-xor-expr ()
9419 (let ((pn (js2-parse-bit-and-expr)))
9420 (while (js2-match-token js2-BITXOR)
9421 (setq pn (js2-make-binary js2-BITXOR
9422 pn
9423 'js2-parse-bit-and-expr)))
9424 pn))
9425
9426 (defun js2-parse-bit-and-expr ()
9427 (let ((pn (js2-parse-eq-expr)))
9428 (while (js2-match-token js2-BITAND)
9429 (setq pn (js2-make-binary js2-BITAND
9430 pn
9431 'js2-parse-eq-expr)))
9432 pn))
9433
9434 (defconst js2-parse-eq-ops
9435 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9436
9437 (defun js2-parse-eq-expr ()
9438 (let ((pn (js2-parse-rel-expr))
9439 tt)
9440 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9441 (setq pn (js2-make-binary tt
9442 pn
9443 'js2-parse-rel-expr)))
9444 (js2-unget-token)
9445 pn))
9446
9447 (defconst js2-parse-rel-ops
9448 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9449
9450 (defun js2-parse-rel-expr ()
9451 (let ((pn (js2-parse-shift-expr))
9452 (continue t)
9453 tt)
9454 (while continue
9455 (setq tt (js2-get-token))
9456 (cond
9457 ((and js2-in-for-init (= tt js2-IN))
9458 (js2-unget-token)
9459 (setq continue nil))
9460 ((memq tt js2-parse-rel-ops)
9461 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9462 (t
9463 (js2-unget-token)
9464 (setq continue nil))))
9465 pn))
9466
9467 (defconst js2-parse-shift-ops
9468 (list js2-LSH js2-URSH js2-RSH))
9469
9470 (defun js2-parse-shift-expr ()
9471 (let ((pn (js2-parse-add-expr))
9472 tt
9473 (continue t))
9474 (while continue
9475 (setq tt (js2-get-token))
9476 (if (memq tt js2-parse-shift-ops)
9477 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9478 (js2-unget-token)
9479 (setq continue nil)))
9480 pn))
9481
9482 (defun js2-parse-add-expr ()
9483 (let ((pn (js2-parse-mul-expr))
9484 tt
9485 (continue t))
9486 (while continue
9487 (setq tt (js2-get-token))
9488 (if (or (= tt js2-ADD) (= tt js2-SUB))
9489 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9490 (js2-unget-token)
9491 (setq continue nil)))
9492 pn))
9493
9494 (defconst js2-parse-mul-ops
9495 (list js2-MUL js2-DIV js2-MOD))
9496
9497 (defun js2-parse-mul-expr ()
9498 (let ((pn (js2-parse-unary-expr))
9499 tt
9500 (continue t))
9501 (while continue
9502 (setq tt (js2-get-token))
9503 (if (memq tt js2-parse-mul-ops)
9504 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9505 (js2-unget-token)
9506 (setq continue nil)))
9507 pn))
9508
9509 (defun js2-make-unary (type parser &rest args)
9510 "Make a unary node of type TYPE.
9511 PARSER is either a node (for postfix operators) or a function to call
9512 to parse the operand (for prefix operators)."
9513 (let* ((pos (js2-current-token-beg))
9514 (postfix (js2-node-p parser))
9515 (expr (if postfix
9516 parser
9517 (apply parser args)))
9518 end
9519 pn)
9520 (if postfix ; e.g. i++
9521 (setq pos (js2-node-pos expr)
9522 end (js2-current-token-end))
9523 (setq end (js2-node-end expr)))
9524 (setq pn (make-js2-unary-node :type type
9525 :pos pos
9526 :len (- end pos)
9527 :operand expr))
9528 (js2-node-add-children pn expr)
9529 pn))
9530
9531 (defconst js2-incrementable-node-types
9532 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9533 "Node types that can be the operand of a ++ or -- operator.")
9534
9535 (defun js2-check-bad-inc-dec (tt beg end unary)
9536 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9537 js2-incrementable-node-types)
9538 (js2-report-error (if (= tt js2-INC)
9539 "msg.bad.incr"
9540 "msg.bad.decr")
9541 nil beg (- end beg))))
9542
9543 (defun js2-parse-unary-expr ()
9544 (let ((tt (js2-current-token-type))
9545 pn expr beg end)
9546 (cond
9547 ((or (= tt js2-VOID)
9548 (= tt js2-NOT)
9549 (= tt js2-BITNOT)
9550 (= tt js2-TYPEOF))
9551 (js2-get-token)
9552 (js2-make-unary tt 'js2-parse-unary-expr))
9553 ((= tt js2-ADD)
9554 (js2-get-token)
9555 ;; Convert to special POS token in decompiler and parse tree
9556 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9557 ((= tt js2-SUB)
9558 (js2-get-token)
9559 ;; Convert to special NEG token in decompiler and parse tree
9560 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9561 ((or (= tt js2-INC)
9562 (= tt js2-DEC))
9563 (js2-get-token)
9564 (prog1
9565 (setq beg (js2-current-token-beg)
9566 end (js2-current-token-end)
9567 expr (js2-make-unary tt 'js2-parse-member-expr t))
9568 (js2-check-bad-inc-dec tt beg end expr)))
9569 ((= tt js2-DELPROP)
9570 (js2-get-token)
9571 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9572 ((= tt js2-ERROR)
9573 (js2-get-token)
9574 (make-js2-error-node)) ; try to continue
9575 ((and (= tt js2-LT)
9576 js2-compiler-xml-available)
9577 ;; XML stream encountered in expression.
9578 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9579 (t
9580 (setq pn (js2-parse-member-expr t)
9581 ;; Don't look across a newline boundary for a postfix incop.
9582 tt (js2-peek-token-or-eol))
9583 (when (or (= tt js2-INC) (= tt js2-DEC))
9584 (js2-get-token)
9585 (setf expr pn
9586 pn (js2-make-unary tt expr))
9587 (js2-node-set-prop pn 'postfix t)
9588 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9589 pn))))
9590
9591 (defun js2-parse-xml-initializer ()
9592 "Parse an E4X XML initializer.
9593 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9594 Then I'll postprocess the result, depending on whether we're in IDE
9595 mode or codegen mode, and generate the appropriate rewritten AST.
9596 IDE mode uses a rich AST that models the XML structure. Codegen mode
9597 just concatenates everything and makes a new XML or XMLList out of it."
9598 (let ((tt (js2-get-first-xml-token))
9599 pn-xml pn expr kids expr-pos
9600 (continue t)
9601 (first-token t))
9602 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9603 (js2-report-error "msg.syntax"))
9604 (setq pn-xml (make-js2-xml-node))
9605 (while continue
9606 (if first-token
9607 (setq first-token nil)
9608 (setq tt (js2-get-next-xml-token)))
9609 (cond
9610 ;; js2-XML means we found a {expr} in the XML stream.
9611 ;; The token string is the XML up to the left-curly.
9612 ((= tt js2-XML)
9613 (push (make-js2-string-node :pos (js2-current-token-beg)
9614 :len (- js2-ts-cursor (js2-current-token-beg)))
9615 kids)
9616 (js2-must-match js2-LC "msg.syntax")
9617 (setq expr-pos js2-ts-cursor
9618 expr (if (eq (js2-peek-token) js2-RC)
9619 (make-js2-empty-expr-node :pos expr-pos)
9620 (js2-parse-expr)))
9621 (js2-must-match js2-RC "msg.syntax")
9622 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9623 :len (js2-node-len expr)
9624 :expr expr))
9625 (js2-node-add-children pn expr)
9626 (push pn kids))
9627 ;; a js2-XMLEND token means we hit the final close-tag.
9628 ((= tt js2-XMLEND)
9629 (push (make-js2-string-node :pos (js2-current-token-beg)
9630 :len (- js2-ts-cursor (js2-current-token-beg)))
9631 kids)
9632 (dolist (kid (nreverse kids))
9633 (js2-block-node-push pn-xml kid))
9634 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9635 (js2-node-pos pn-xml))
9636 continue nil))
9637 (t
9638 (js2-report-error "msg.syntax")
9639 (setq continue nil))))
9640 pn-xml))
9641
9642
9643 (defun js2-parse-argument-list ()
9644 "Parse an argument list and return it as a Lisp list of nodes.
9645 Returns the list in reverse order. Consumes the right-paren token."
9646 (let (result)
9647 (unless (js2-match-token js2-RP)
9648 (cl-loop do
9649 (let ((tt (js2-get-token)))
9650 (if (= tt js2-YIELD)
9651 (js2-report-error "msg.yield.parenthesized"))
9652 (if (and (= tt js2-TRIPLEDOT)
9653 (>= js2-language-version 200))
9654 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9655 (js2-unget-token)
9656 (push (js2-parse-assign-expr) result)))
9657 while
9658 (js2-match-token js2-COMMA))
9659 (js2-must-match js2-RP "msg.no.paren.arg")
9660 result)))
9661
9662 (defun js2-parse-member-expr (&optional allow-call-syntax)
9663 (let ((tt (js2-current-token-type))
9664 pn pos target args beg end init)
9665 (if (/= tt js2-NEW)
9666 (setq pn (js2-parse-primary-expr))
9667 ;; parse a 'new' expression
9668 (js2-get-token)
9669 (setq pos (js2-current-token-beg)
9670 beg pos
9671 target (js2-parse-member-expr)
9672 end (js2-node-end target)
9673 pn (make-js2-new-node :pos pos
9674 :target target
9675 :len (- end pos)))
9676 (js2-highlight-function-call (js2-current-token))
9677 (js2-node-add-children pn target)
9678 (when (js2-match-token js2-LP)
9679 ;; Add the arguments to pn, if any are supplied.
9680 (setf beg pos ; start of "new" keyword
9681 pos (js2-current-token-beg)
9682 args (nreverse (js2-parse-argument-list))
9683 (js2-new-node-args pn) args
9684 end (js2-current-token-end)
9685 (js2-new-node-lp pn) (- pos beg)
9686 (js2-new-node-rp pn) (- end 1 beg))
9687 (apply #'js2-node-add-children pn args))
9688 (when (and js2-allow-rhino-new-expr-initializer
9689 (js2-match-token js2-LC))
9690 (setf init (js2-parse-object-literal)
9691 end (js2-node-end init)
9692 (js2-new-node-initializer pn) init)
9693 (js2-node-add-children pn init))
9694 (setf (js2-node-len pn) (- end beg))) ; end outer if
9695 (js2-parse-member-expr-tail allow-call-syntax pn)))
9696
9697 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9698 "Parse a chain of property/array accesses or function calls.
9699 Includes parsing for E4X operators like `..' and `.@'.
9700 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9701 Returns an expression tree that includes PN, the parent node."
9702 (let (tt
9703 (continue t))
9704 (while continue
9705 (setq tt (js2-get-token))
9706 (cond
9707 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9708 (setq pn (js2-parse-property-access tt pn)))
9709 ((= tt js2-DOTQUERY)
9710 (setq pn (js2-parse-dot-query pn)))
9711 ((= tt js2-LB)
9712 (setq pn (js2-parse-element-get pn)))
9713 ((= tt js2-LP)
9714 (js2-unget-token)
9715 (if allow-call-syntax
9716 (setq pn (js2-parse-function-call pn))
9717 (setq continue nil)))
9718 ((= tt js2-TEMPLATE_HEAD)
9719 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9720 ((= tt js2-NO_SUBS_TEMPLATE)
9721 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9722 (t
9723 (js2-unget-token)
9724 (setq continue nil))))
9725 (if (>= js2-highlight-level 2)
9726 (js2-parse-highlight-member-expr-node pn))
9727 pn))
9728
9729 (defun js2-parse-tagged-template (tag-node tpl-node)
9730 "Parse tagged template expression."
9731 (let* ((beg (js2-node-pos tag-node))
9732 (pn (make-js2-tagged-template-node :beg beg
9733 :len (- (js2-current-token-end) beg)
9734 :tag tag-node
9735 :template tpl-node)))
9736 (js2-node-add-children pn tag-node tpl-node)
9737 pn))
9738
9739 (defun js2-parse-dot-query (pn)
9740 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9741 Last token parsed must be `js2-DOTQUERY'."
9742 (let ((pos (js2-node-pos pn))
9743 op-pos expr end)
9744 (js2-must-have-xml)
9745 (js2-set-requires-activation)
9746 (setq op-pos (js2-current-token-beg)
9747 expr (js2-parse-expr)
9748 end (js2-node-end expr)
9749 pn (make-js2-xml-dot-query-node :left pn
9750 :pos pos
9751 :op-pos op-pos
9752 :right expr))
9753 (js2-node-add-children pn
9754 (js2-xml-dot-query-node-left pn)
9755 (js2-xml-dot-query-node-right pn))
9756 (if (js2-must-match js2-RP "msg.no.paren")
9757 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9758 end (js2-current-token-end)))
9759 (setf (js2-node-len pn) (- end pos))
9760 pn))
9761
9762 (defun js2-parse-element-get (pn)
9763 "Parse an element-get expression, e.g. foo[bar].
9764 Last token parsed must be `js2-RB'."
9765 (let ((lb (js2-current-token-beg))
9766 (pos (js2-node-pos pn))
9767 rb expr)
9768 (setq expr (js2-parse-expr))
9769 (if (js2-must-match js2-RB "msg.no.bracket.index")
9770 (setq rb (js2-current-token-beg)))
9771 (setq pn (make-js2-elem-get-node :target pn
9772 :pos pos
9773 :element expr
9774 :lb (js2-relpos lb pos)
9775 :rb (js2-relpos rb pos)
9776 :len (- (js2-current-token-end) pos)))
9777 (js2-node-add-children pn
9778 (js2-elem-get-node-target pn)
9779 (js2-elem-get-node-element pn))
9780 pn))
9781
9782 (defun js2-highlight-function-call (token)
9783 (when (eq (js2-token-type token) js2-NAME)
9784 (js2-record-face 'js2-function-call token)))
9785
9786 (defun js2-parse-function-call (pn)
9787 (js2-highlight-function-call (js2-current-token))
9788 (js2-get-token)
9789 (let (args
9790 (pos (js2-node-pos pn)))
9791 (setq pn (make-js2-call-node :pos pos
9792 :target pn
9793 :lp (- (js2-current-token-beg) pos)))
9794 (js2-node-add-children pn (js2-call-node-target pn))
9795 ;; Add the arguments to pn, if any are supplied.
9796 (setf args (nreverse (js2-parse-argument-list))
9797 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9798 (js2-call-node-args pn) args)
9799 (apply #'js2-node-add-children pn args)
9800 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9801 pn))
9802
9803 (defun js2-parse-property-access (tt pn)
9804 "Parse a property access, XML descendants access, or XML attr access."
9805 (let ((member-type-flags 0)
9806 (dot-pos (js2-current-token-beg))
9807 (dot-len (if (= tt js2-DOTDOT) 2 1))
9808 name
9809 ref ; right side of . or .. operator
9810 result)
9811 (when (= tt js2-DOTDOT)
9812 (js2-must-have-xml)
9813 (setq member-type-flags js2-descendants-flag))
9814 (if (not js2-compiler-xml-available)
9815 (progn
9816 (js2-must-match-prop-name "msg.no.name.after.dot")
9817 (setq name (js2-create-name-node t js2-GETPROP)
9818 result (make-js2-prop-get-node :left pn
9819 :pos (js2-current-token-beg)
9820 :right name
9821 :len (js2-current-token-len)))
9822 (js2-node-add-children result pn name)
9823 result)
9824 ;; otherwise look for XML operators
9825 (setf result (if (= tt js2-DOT)
9826 (make-js2-prop-get-node)
9827 (make-js2-infix-node :type js2-DOTDOT))
9828 (js2-node-pos result) (js2-node-pos pn)
9829 (js2-infix-node-op-pos result) dot-pos
9830 (js2-infix-node-left result) pn ; do this after setting position
9831 tt (js2-get-prop-name-token))
9832 (cond
9833 ;; handles: name, ns::name, ns::*, ns::[expr]
9834 ((= tt js2-NAME)
9835 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9836 ;; handles: *, *::name, *::*, *::[expr]
9837 ((= tt js2-MUL)
9838 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9839 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9840 ((= tt js2-XMLATTR)
9841 (setq result (js2-parse-attribute-access)))
9842 (t
9843 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9844 (if ref
9845 (setf (js2-node-len result) (- (js2-node-end ref)
9846 (js2-node-pos result))
9847 (js2-infix-node-right result) ref))
9848 (if (js2-infix-node-p result)
9849 (js2-node-add-children result
9850 (js2-infix-node-left result)
9851 (js2-infix-node-right result)))
9852 result)))
9853
9854 (defun js2-parse-attribute-access ()
9855 "Parse an E4X XML attribute expression.
9856 This includes expressions of the forms:
9857
9858 @attr @ns::attr @ns::*
9859 @* @*::attr @*::*
9860 @[expr] @*::[expr] @ns::[expr]
9861
9862 Called if we peeked an '@' token."
9863 (let ((tt (js2-get-prop-name-token))
9864 (at-pos (js2-current-token-beg)))
9865 (cond
9866 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9867 ((= tt js2-NAME)
9868 (js2-parse-property-name at-pos nil 0))
9869 ;; handles: @*, @*::name, @*::*, @*::[expr]
9870 ((= tt js2-MUL)
9871 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9872 ;; handles @[expr]
9873 ((= tt js2-LB)
9874 (js2-parse-xml-elem-ref at-pos))
9875 (t
9876 (js2-report-error "msg.no.name.after.xmlAttr")
9877 ;; Avoid cascaded errors that happen if we make an error node here.
9878 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9879
9880 (defun js2-parse-property-name (at-pos s member-type-flags)
9881 "Check if :: follows name in which case it becomes qualified name.
9882
9883 AT-POS is a natural number if we just read an '@' token, else nil.
9884 S is the name or string that was matched: an identifier, 'throw' or '*'.
9885 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9886
9887 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9888 operator, or the name is followed by ::. For a plain name, returns a
9889 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9890 (let ((pos (or at-pos (js2-current-token-beg)))
9891 colon-pos
9892 (name (js2-create-name-node t (js2-current-token-type) s))
9893 ns tt pn)
9894 (catch 'return
9895 (when (js2-match-token js2-COLONCOLON)
9896 (setq ns name
9897 colon-pos (js2-current-token-beg)
9898 tt (js2-get-prop-name-token))
9899 (cond
9900 ;; handles name::name
9901 ((= tt js2-NAME)
9902 (setq name (js2-create-name-node)))
9903 ;; handles name::*
9904 ((= tt js2-MUL)
9905 (setq name (js2-create-name-node nil nil "*")))
9906 ;; handles name::[expr]
9907 ((= tt js2-LB)
9908 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9909 (t
9910 (js2-report-error "msg.no.name.after.coloncolon"))))
9911 (if (and (null ns) (zerop member-type-flags))
9912 name
9913 (prog1
9914 (setq pn
9915 (make-js2-xml-prop-ref-node :pos pos
9916 :len (- (js2-node-end name) pos)
9917 :at-pos at-pos
9918 :colon-pos colon-pos
9919 :propname name))
9920 (js2-node-add-children pn name))))))
9921
9922 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9923 "Parse the [expr] portion of an xml element reference.
9924 For instance, @[expr], @*::[expr], or ns::[expr]."
9925 (let* ((lb (js2-current-token-beg))
9926 (pos (or at-pos lb))
9927 rb
9928 (expr (js2-parse-expr))
9929 (end (js2-node-end expr))
9930 pn)
9931 (if (js2-must-match js2-RB "msg.no.bracket.index")
9932 (setq rb (js2-current-token-beg)
9933 end (js2-current-token-end)))
9934 (prog1
9935 (setq pn
9936 (make-js2-xml-elem-ref-node :pos pos
9937 :len (- end pos)
9938 :namespace namespace
9939 :colon-pos colon-pos
9940 :at-pos at-pos
9941 :expr expr
9942 :lb (js2-relpos lb pos)
9943 :rb (js2-relpos rb pos)))
9944 (js2-node-add-children pn namespace expr))))
9945
9946 (defun js2-parse-destruct-primary-expr ()
9947 (let ((js2-is-in-destructuring t))
9948 (js2-parse-primary-expr)))
9949
9950 (defun js2-parse-primary-expr ()
9951 "Parse a literal (leaf) expression of some sort.
9952 Includes complex literals such as functions, object-literals,
9953 array-literals, array comprehensions and regular expressions."
9954 (let (pn ; parent node (usually return value)
9955 tt)
9956 (setq tt (js2-current-token-type))
9957 (cond
9958 ((= tt js2-CLASS)
9959 (js2-parse-class-expr))
9960 ((= tt js2-FUNCTION)
9961 (js2-parse-function-expr))
9962 ((= tt js2-LB)
9963 (js2-parse-array-comp-or-literal))
9964 ((= tt js2-LC)
9965 (js2-parse-object-literal))
9966 ((= tt js2-LET)
9967 (js2-parse-let (js2-current-token-beg)))
9968 ((= tt js2-LP)
9969 (js2-parse-paren-expr-or-generator-comp))
9970 ((= tt js2-XMLATTR)
9971 (js2-must-have-xml)
9972 (js2-parse-attribute-access))
9973 ((= tt js2-NAME)
9974 (js2-parse-name tt))
9975 ((= tt js2-NUMBER)
9976 (make-js2-number-node))
9977 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9978 (make-js2-string-node :type tt))
9979 ((= tt js2-TEMPLATE_HEAD)
9980 (js2-parse-template-literal))
9981 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9982 ;; Got / or /= which in this context means a regexp literal
9983 (let ((px-pos (js2-current-token-beg))
9984 (flags (js2-read-regexp tt))
9985 (end (js2-current-token-end)))
9986 (prog1
9987 (make-js2-regexp-node :pos px-pos
9988 :len (- end px-pos)
9989 :value (js2-current-token-string)
9990 :flags flags)
9991 (js2-set-face px-pos end 'font-lock-string-face 'record)
9992 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9993 ((or (= tt js2-NULL)
9994 (= tt js2-THIS)
9995 (= tt js2-SUPER)
9996 (= tt js2-FALSE)
9997 (= tt js2-TRUE))
9998 (make-js2-keyword-node :type tt))
9999 ((= tt js2-TRIPLEDOT)
10000 ;; Likewise, only valid in an arrow function with a rest param.
10001 (if (and (js2-match-token js2-NAME)
10002 (js2-match-token js2-RP)
10003 (eq (js2-peek-token) js2-ARROW))
10004 (progn
10005 (js2-unget-token) ; Put back the right paren.
10006 ;; See the previous case.
10007 (make-js2-keyword-node :type js2-NULL))
10008 (js2-report-error "msg.syntax")
10009 (make-js2-error-node)))
10010 ((= tt js2-RESERVED)
10011 (js2-report-error "msg.reserved.id")
10012 (make-js2-name-node))
10013 ((= tt js2-ERROR)
10014 ;; the scanner or one of its subroutines reported the error.
10015 (make-js2-error-node))
10016 ((= tt js2-EOF)
10017 (let* ((px-pos (point-at-bol))
10018 (len (- js2-ts-cursor px-pos)))
10019 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10020 (make-js2-error-node :pos (1- js2-ts-cursor)))
10021 (t
10022 (js2-report-error "msg.syntax")
10023 (make-js2-error-node)))))
10024
10025 (defun js2-parse-template-literal ()
10026 (let ((beg (js2-current-token-beg))
10027 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10028 (tt js2-TEMPLATE_HEAD))
10029 (while (eq tt js2-TEMPLATE_HEAD)
10030 (push (js2-parse-expr) kids)
10031 (js2-must-match js2-RC "msg.syntax")
10032 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10033 (push (make-js2-string-node :type tt) kids))
10034 (setq kids (nreverse kids))
10035 (let ((tpl (make-js2-template-node :beg beg
10036 :len (- (js2-current-token-end) beg)
10037 :kids kids)))
10038 (apply #'js2-node-add-children tpl kids)
10039 tpl)))
10040
10041 (defun js2-parse-name (_tt)
10042 (let ((name (js2-current-token-string))
10043 node)
10044 (setq node (if js2-compiler-xml-available
10045 (js2-parse-property-name nil name 0)
10046 (js2-create-name-node 'check-activation nil name)))
10047 (if js2-highlight-external-variables
10048 (js2-record-name-node node))
10049 node))
10050
10051 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10052 (js2-add-strict-warning
10053 msg nil
10054 ;; back up from comma to beginning of line or array/objlit
10055 (max (if elems
10056 (js2-node-pos (car elems))
10057 pos)
10058 (save-excursion
10059 (goto-char comma-pos)
10060 (back-to-indentation)
10061 (point)))
10062 comma-pos))
10063
10064 (defun js2-parse-array-comp-or-literal ()
10065 (let ((pos (js2-current-token-beg)))
10066 (if (and (>= js2-language-version 200)
10067 (js2-match-token js2-FOR))
10068 (js2-parse-array-comp pos)
10069 (js2-parse-array-literal pos))))
10070
10071 (defun js2-parse-array-literal (pos)
10072 (let ((after-lb-or-comma t)
10073 after-comma tt elems pn
10074 (continue t))
10075 (unless js2-is-in-destructuring
10076 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10077 (while continue
10078 (setq tt (js2-get-token))
10079 (cond
10080 ;; comma
10081 ((= tt js2-COMMA)
10082 (setq after-comma (js2-current-token-end))
10083 (if (not after-lb-or-comma)
10084 (setq after-lb-or-comma t)
10085 (push nil elems)))
10086 ;; end of array
10087 ((or (= tt js2-RB)
10088 (= tt js2-EOF)) ; prevent infinite loop
10089 (if (= tt js2-EOF)
10090 (js2-report-error "msg.no.bracket.arg" nil pos))
10091 (when (and after-comma (< js2-language-version 170))
10092 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10093 pos (remove nil elems) after-comma))
10094 (setq continue nil
10095 pn (make-js2-array-node :pos pos
10096 :len (- js2-ts-cursor pos)
10097 :elems (nreverse elems)))
10098 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10099 ;; destructuring binding
10100 (js2-is-in-destructuring
10101 (push (if (or (= tt js2-LC)
10102 (= tt js2-LB)
10103 (= tt js2-NAME))
10104 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10105 (js2-parse-destruct-primary-expr)
10106 ;; invalid pattern
10107 (js2-report-error "msg.bad.var")
10108 (make-js2-error-node))
10109 elems)
10110 (setq after-lb-or-comma nil
10111 after-comma nil))
10112 ;; array comp
10113 ((and (>= js2-language-version 170)
10114 (= tt js2-FOR) ; check for array comprehension
10115 (not after-lb-or-comma) ; "for" can't follow a comma
10116 elems ; must have at least 1 element
10117 (not (cdr elems))) ; but no 2nd element
10118 (js2-unget-token)
10119 (setf continue nil
10120 pn (js2-parse-legacy-array-comp (car elems) pos)))
10121 ;; another element
10122 (t
10123 (unless after-lb-or-comma
10124 (js2-report-error "msg.no.bracket.arg"))
10125 (if (and (= tt js2-TRIPLEDOT)
10126 (>= js2-language-version 200))
10127 ;; spread operator
10128 (push (js2-make-unary tt 'js2-parse-assign-expr)
10129 elems)
10130 (js2-unget-token)
10131 (push (js2-parse-assign-expr) elems))
10132 (setq after-lb-or-comma nil
10133 after-comma nil))))
10134 (unless js2-is-in-destructuring
10135 (js2-pop-scope))
10136 pn))
10137
10138 (defun js2-parse-legacy-array-comp (expr pos)
10139 "Parse a legacy array comprehension (JavaScript 1.7).
10140 EXPR is the first expression after the opening left-bracket.
10141 POS is the beginning of the LB token preceding EXPR.
10142 We should have just parsed the 'for' keyword before calling this function."
10143 (let ((current-scope js2-current-scope)
10144 loops first filter result)
10145 (unwind-protect
10146 (progn
10147 (while (js2-match-token js2-FOR)
10148 (let ((loop (make-js2-comp-loop-node)))
10149 (js2-push-scope loop)
10150 (push loop loops)
10151 (js2-parse-comp-loop loop)))
10152 ;; First loop takes expr scope's parent.
10153 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10154 (js2-scope-parent-scope current-scope))
10155 ;; Set expr scope's parent to the last loop.
10156 (setf (js2-scope-parent-scope current-scope) (car loops))
10157 (if (/= (js2-get-token) js2-IF)
10158 (js2-unget-token)
10159 (setq filter (js2-parse-condition))))
10160 (dotimes (_ (1- (length loops)))
10161 (js2-pop-scope)))
10162 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10163 (setq result (make-js2-comp-node :pos pos
10164 :len (- js2-ts-cursor pos)
10165 :result expr
10166 :loops (nreverse loops)
10167 :filters (and filter (list (car filter)))
10168 :form 'LEGACY_ARRAY))
10169 ;; Set comp loop's parent to the last loop.
10170 ;; TODO: Get rid of the bogus expr scope.
10171 (setf (js2-scope-parent-scope result) first)
10172 (apply #'js2-node-add-children result expr (car filter)
10173 (js2-comp-node-loops result))
10174 result))
10175
10176 (defun js2-parse-array-comp (pos)
10177 "Parse an ES6 array comprehension.
10178 POS is the beginning of the LB token.
10179 We should have just parsed the 'for' keyword before calling this function."
10180 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10181 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10182 pn))
10183
10184 (defun js2-parse-generator-comp (pos)
10185 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10186 (js2-current-script-or-fn
10187 (make-js2-function-node :generator-type 'COMPREHENSION))
10188 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10189 (js2-must-match js2-RP "msg.no.paren" pos)
10190 pn))
10191
10192 (defun js2-parse-comprehension (pos form)
10193 (let (loops filters expr result)
10194 (unwind-protect
10195 (progn
10196 (js2-unget-token)
10197 (while (js2-match-token js2-FOR)
10198 (let ((loop (make-js2-comp-loop-node)))
10199 (js2-push-scope loop)
10200 (push loop loops)
10201 (js2-parse-comp-loop loop)))
10202 (while (js2-match-token js2-IF)
10203 (push (car (js2-parse-condition)) filters))
10204 (setq expr (js2-parse-assign-expr)))
10205 (dolist (_ loops)
10206 (js2-pop-scope)))
10207 (setq result (make-js2-comp-node :pos pos
10208 :len (- js2-ts-cursor pos)
10209 :result expr
10210 :loops (nreverse loops)
10211 :filters (nreverse filters)
10212 :form form))
10213 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10214 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10215 result))
10216
10217 (defun js2-parse-comp-loop (pn &optional only-of-p)
10218 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10219 The current token should be the initial FOR.
10220 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10221 (let ((pos (js2-comp-loop-node-pos pn))
10222 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10223 (when (and (not only-of-p) (js2-match-token js2-NAME))
10224 (if (string= (js2-current-token-string) "each")
10225 (progn
10226 (setq foreach-p t
10227 each-pos (- (js2-current-token-beg) pos)) ; relative
10228 (js2-record-face 'font-lock-keyword-face))
10229 (js2-report-error "msg.no.paren.for")))
10230 (if (js2-must-match js2-LP "msg.no.paren.for")
10231 (setq lp (- (js2-current-token-beg) pos)))
10232 (setq tt (js2-peek-token))
10233 (cond
10234 ((or (= tt js2-LB)
10235 (= tt js2-LC))
10236 (js2-get-token)
10237 (setq iter (js2-parse-destruct-primary-expr))
10238 (js2-define-destruct-symbols iter js2-LET
10239 'font-lock-variable-name-face t))
10240 ((js2-match-token js2-NAME)
10241 (setq iter (js2-create-name-node)))
10242 (t
10243 (js2-report-error "msg.bad.var")))
10244 ;; Define as a let since we want the scope of the variable to
10245 ;; be restricted to the array comprehension
10246 (if (js2-name-node-p iter)
10247 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10248 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10249 (and (>= js2-language-version 200)
10250 (js2-match-contextual-kwd "of")
10251 (setq forof-p t)))
10252 (setq in-pos (- (js2-current-token-beg) pos))
10253 (js2-report-error "msg.in.after.for.name"))
10254 (setq obj (js2-parse-expr))
10255 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10256 (setq rp (- (js2-current-token-beg) pos)))
10257 (setf (js2-node-pos pn) pos
10258 (js2-node-len pn) (- js2-ts-cursor pos)
10259 (js2-comp-loop-node-iterator pn) iter
10260 (js2-comp-loop-node-object pn) obj
10261 (js2-comp-loop-node-in-pos pn) in-pos
10262 (js2-comp-loop-node-each-pos pn) each-pos
10263 (js2-comp-loop-node-foreach-p pn) foreach-p
10264 (js2-comp-loop-node-forof-p pn) forof-p
10265 (js2-comp-loop-node-lp pn) lp
10266 (js2-comp-loop-node-rp pn) rp)
10267 (js2-node-add-children pn iter obj)
10268 pn))
10269
10270 (defun js2-parse-class-stmt ()
10271 (let ((pos (js2-current-token-beg))
10272 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10273 (name (js2-create-name-node t)))
10274 (js2-set-face (js2-node-pos name) (js2-node-end name)
10275 'font-lock-function-name-face 'record)
10276 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10277 (js2-define-symbol js2-FUNCTION
10278 (js2-name-node-name name)
10279 node)
10280 node)))
10281
10282 (defun js2-parse-class-expr ()
10283 (let ((pos (js2-current-token-beg))
10284 name)
10285 (when (js2-match-token js2-NAME)
10286 (setq name (js2-create-name-node t)))
10287 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10288
10289 (defun js2-parse-class (pos form name)
10290 ;; class X [extends ...] {
10291 (let (pn elems extends)
10292 (if (js2-match-token js2-EXTENDS)
10293 (if (= (js2-peek-token) js2-LC)
10294 (js2-report-error "msg.missing.extends")
10295 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10296 (setq extends (js2-parse-assign-expr))
10297 (if (not extends)
10298 (js2-report-error "msg.bad.extends"))))
10299 (js2-must-match js2-LC "msg.no.brace.class")
10300 (setq elems (js2-parse-object-literal-elems t)
10301 pn (make-js2-class-node :pos pos
10302 :len (- js2-ts-cursor pos)
10303 :form form
10304 :name name
10305 :extends extends
10306 :elems elems))
10307 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10308 pn))
10309
10310 (defun js2-parse-object-literal ()
10311 (let* ((pos (js2-current-token-beg))
10312 (elems (js2-parse-object-literal-elems))
10313 (result (make-js2-object-node :pos pos
10314 :len (- js2-ts-cursor pos)
10315 :elems elems)))
10316 (apply #'js2-node-add-children result (js2-object-node-elems result))
10317 result))
10318
10319 (defun js2-parse-object-literal-elems (&optional class-p)
10320 (let ((pos (js2-current-token-beg))
10321 (static nil)
10322 (continue t)
10323 tt elems elem after-comma)
10324 (while continue
10325 (setq tt (js2-get-prop-name-token)
10326 static nil
10327 elem nil)
10328 (when (and class-p (= js2-NAME tt)
10329 (string= "static" (js2-current-token-string)))
10330 (js2-record-face 'font-lock-keyword-face)
10331 (setq static t
10332 tt (js2-get-prop-name-token)))
10333 (cond
10334 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
10335 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
10336 ;; TODO(sdh): support *foo() {...}
10337 ((or (= js2-NAME tt)
10338 (= tt js2-STRING))
10339 (setq after-comma nil
10340 elem (js2-parse-named-prop tt))
10341 (if (and (null elem)
10342 (not js2-recover-from-parse-errors))
10343 (setq continue nil)))
10344 ;; {[Symbol.iterator]: ...}
10345 ((and (= tt js2-LB)
10346 (>= js2-language-version 200))
10347 (let ((expr (js2-parse-expr)))
10348 (js2-must-match js2-RB "msg.missing.computed.rb")
10349 (setq after-comma nil
10350 elem (js2-parse-plain-property expr))))
10351 ;; {12: x} or {10.7: x}
10352 ((= tt js2-NUMBER)
10353 (setq after-comma nil
10354 elem (js2-parse-plain-property (make-js2-number-node))))
10355 ;; Break out of loop, and handle trailing commas.
10356 ((or (= tt js2-RC)
10357 (= tt js2-EOF))
10358 (js2-unget-token)
10359 (setq continue nil)
10360 (if after-comma
10361 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10362 pos elems after-comma)))
10363 (t
10364 (js2-report-error "msg.bad.prop")
10365 (unless js2-recover-from-parse-errors
10366 (setq continue nil)))) ; end switch
10367 ;; Handle static for classes' codegen.
10368 (if static
10369 (if elem (js2-node-set-prop elem 'STATIC t)
10370 (js2-report-error "msg.unexpected.static")))
10371 ;; Handle commas, depending on class-p.
10372 (let ((tok (js2-get-prop-name-token)))
10373 (if (eq tok js2-COMMA)
10374 (if class-p
10375 (js2-report-error "msg.class.unexpected.comma")
10376 (setq after-comma (js2-current-token-end)))
10377 (js2-unget-token)
10378 (unless class-p (setq continue nil))))
10379 ;; Append any parsed element.
10380 (if elem (push elem elems))) ; end loop
10381 (js2-must-match js2-RC "msg.no.brace.prop")
10382 (nreverse elems)))
10383
10384 (defun js2-parse-named-prop (tt)
10385 "Parse a name, string, or getter/setter object property.
10386 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10387 (let ((string-prop (and (= tt js2-STRING)
10388 (make-js2-string-node)))
10389 expr
10390 (ppos (js2-current-token-beg))
10391 (pend (js2-current-token-end))
10392 (name (js2-create-name-node))
10393 (prop (js2-current-token-string)))
10394 (cond
10395 ;; getter/setter prop
10396 ((and (= tt js2-NAME)
10397 (= (js2-peek-token) js2-NAME)
10398 (or (string= prop "get")
10399 (string= prop "set")))
10400 (js2-get-token)
10401 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
10402 (js2-record-face 'font-lock-function-name-face) ; for peeked name
10403 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
10404 (js2-parse-getter-setter-prop ppos name prop))
10405 ;; method definition: {f() {...}}
10406 ((and (= (js2-peek-token) js2-LP)
10407 (>= js2-language-version 200))
10408 (js2-record-face 'font-lock-function-name-face) ; name
10409 (js2-parse-getter-setter-prop ppos name ""))
10410 ;; regular prop
10411 (t
10412 (prog1
10413 (setq expr (js2-parse-plain-property (or string-prop name)))
10414 (when (and (not string-prop)
10415 (not js2-is-in-destructuring)
10416 js2-highlight-external-variables
10417 (js2-node-get-prop expr 'SHORTHAND))
10418 (js2-record-name-node name))
10419 (js2-set-face ppos pend
10420 (if (js2-function-node-p
10421 (js2-object-prop-node-right expr))
10422 'font-lock-function-name-face
10423 'font-lock-variable-name-face)
10424 'record))))))
10425
10426 (defun js2-parse-plain-property (prop)
10427 "Parse a non-getter/setter property in an object literal.
10428 PROP is the node representing the property: a number, name or string."
10429 (let* ((tt (js2-get-token))
10430 (pos (js2-node-pos prop))
10431 colon expr result)
10432 (cond
10433 ;; Abbreviated property, as in {foo, bar}
10434 ((and (>= js2-language-version 200)
10435 (or (= tt js2-COMMA)
10436 (= tt js2-RC))
10437 (not (js2-number-node-p prop)))
10438 (js2-unget-token)
10439 (setq result (make-js2-object-prop-node
10440 :pos pos
10441 :left prop
10442 :right prop
10443 :op-pos (js2-current-token-len)))
10444 (js2-node-add-children result prop)
10445 (js2-node-set-prop result 'SHORTHAND t)
10446 result)
10447 ;; Normal property
10448 (t
10449 (if (= tt js2-COLON)
10450 (setq colon (- (js2-current-token-beg) pos)
10451 expr (js2-parse-assign-expr))
10452 (js2-report-error "msg.no.colon.prop")
10453 (setq expr (make-js2-error-node)))
10454 (setq result (make-js2-object-prop-node
10455 :pos pos
10456 ;; don't include last consumed token in length
10457 :len (- (+ (js2-node-pos expr)
10458 (js2-node-len expr))
10459 pos)
10460 :left prop
10461 :right expr
10462 :op-pos colon))
10463 (js2-node-add-children result prop expr)
10464 result))))
10465
10466 (defun js2-parse-getter-setter-prop (pos prop type-string)
10467 "Parse getter or setter property in an object literal.
10468 JavaScript syntax is:
10469
10470 { get foo() {...}, set foo(x) {...} }
10471
10472 and expression closure style is also supported
10473
10474 { get foo() x, set foo(x) _x = x }
10475
10476 POS is the start position of the `get' or `set' keyword.
10477 PROP is the `js2-name-node' representing the property name.
10478 GET-P is non-nil if the keyword was `get'."
10479 (let ((type (cond
10480 ((string= "get" type-string) js2-GET)
10481 ((string= "set" type-string) js2-SET)
10482 (t js2-FUNCTION)))
10483 result end
10484 (fn (js2-parse-function-expr)))
10485 ;; it has to be an anonymous function, as we already parsed the name
10486 (if (/= (js2-node-type fn) js2-FUNCTION)
10487 (js2-report-error "msg.bad.prop")
10488 (if (cl-plusp (length (js2-function-name fn)))
10489 (js2-report-error "msg.bad.prop")))
10490 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10491 (setq end (js2-node-end fn)
10492 result (make-js2-getter-setter-node :type type
10493 :pos pos
10494 :len (- end pos)
10495 :left prop
10496 :right fn))
10497 (js2-node-add-children result prop fn)
10498 result))
10499
10500 (defun js2-create-name-node (&optional check-activation-p token string)
10501 "Create a name node using the current token and, optionally, STRING.
10502 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10503 (let* ((beg (js2-current-token-beg))
10504 (tt (js2-current-token-type))
10505 (s (or string
10506 (if (= js2-NAME tt)
10507 (js2-current-token-string)
10508 (js2-tt-name tt))))
10509 name)
10510 (setq name (make-js2-name-node :pos beg
10511 :name s
10512 :len (length s)))
10513 (if check-activation-p
10514 (js2-check-activation-name s (or token js2-NAME)))
10515 name))
10516
10517 ;;; Indentation support
10518
10519 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10520 ;; Karl cleverly deduces that the desired indentation level is often a
10521 ;; function of paren/bracket/brace nesting depth, which can be determined
10522 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10523 ;; then does some equally clever checks to see if we're in the context of a
10524 ;; substatement of a possibly braceless statement keyword such as if, while,
10525 ;; or finally. This approach yields pretty good results.
10526
10527 ;; The indenter is often "wrong", however, and needs to be overridden.
10528 ;; The right long-term solution is probably to emulate (or integrate
10529 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10530 ;; parse tree from `js2-parse' is present, which is not true at the
10531 ;; moment the user is typing, computing indentation is still thousands
10532 ;; of lines of code to handle every possible syntactic edge case.
10533
10534 ;; In the meantime, the compromise solution is that we offer a "bounce
10535 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10536 ;; current line indent among various likely guess points. This approach
10537 ;; is far from perfect, but should at least make it slightly easier to
10538 ;; move the line towards its desired indentation when manually
10539 ;; overriding Karl's heuristic nesting guesser.
10540
10541 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10542 ;; extensions such as `let' and Array comprehensions. Major kudos to
10543 ;; Karl for coming up with the initial approach, which packs a lot of
10544 ;; punch for so little code.
10545
10546 (defconst js2-possibly-braceless-keywords-re
10547 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10548 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10549 "try" "while" "with" "let")))
10550 "Regular expression matching keywords that are optionally
10551 followed by an opening brace.")
10552
10553 (defconst js2-indent-operator-re
10554 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10555 (regexp-opt '("in" "instanceof") 'words))
10556 "Regular expression matching operators that affect indentation
10557 of continued expressions.")
10558
10559 (defconst js2-declaration-keyword-re
10560 (regexp-opt '("var" "let" "const") 'words)
10561 "Regular expression matching variable declaration keywords.")
10562
10563 (defun js2-re-search-forward-inner (regexp &optional bound count)
10564 "Auxiliary function for `js2-re-search-forward'."
10565 (let (parse saved-point)
10566 (while (> count 0)
10567 (re-search-forward regexp bound)
10568 (setq parse (if saved-point
10569 (parse-partial-sexp saved-point (point))
10570 (syntax-ppss (point))))
10571 (cond ((nth 3 parse)
10572 (re-search-forward
10573 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10574 (save-excursion (end-of-line) (point)) t))
10575 ((nth 7 parse)
10576 (forward-line))
10577 ((or (nth 4 parse)
10578 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10579 (re-search-forward "\\*/"))
10580 (t
10581 (setq count (1- count))))
10582 (setq saved-point (point))))
10583 (point))
10584
10585 (defun js2-re-search-forward (regexp &optional bound noerror count)
10586 "Search forward but ignore strings and comments.
10587 Invokes `re-search-forward' but treats the buffer as if strings
10588 and comments have been removed."
10589 (let ((saved-point (point)))
10590 (condition-case err
10591 (cond ((null count)
10592 (js2-re-search-forward-inner regexp bound 1))
10593 ((< count 0)
10594 (js2-re-search-backward-inner regexp bound (- count)))
10595 ((> count 0)
10596 (js2-re-search-forward-inner regexp bound count)))
10597 (search-failed
10598 (goto-char saved-point)
10599 (unless noerror
10600 (error (error-message-string err)))))))
10601
10602 (defun js2-re-search-backward-inner (regexp &optional bound count)
10603 "Auxiliary function for `js2-re-search-backward'."
10604 (let (parse)
10605 (while (> count 0)
10606 (re-search-backward regexp bound)
10607 (setq parse (syntax-ppss (point)))
10608 (cond ((nth 3 parse)
10609 (re-search-backward
10610 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10611 (line-beginning-position) t))
10612 ((nth 7 parse)
10613 (goto-char (nth 8 parse)))
10614 ((or (nth 4 parse)
10615 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10616 (re-search-backward "/\\*"))
10617 (t
10618 (setq count (1- count))))))
10619 (point))
10620
10621 (defun js2-re-search-backward (regexp &optional bound noerror count)
10622 "Search backward but ignore strings and comments.
10623 Invokes `re-search-backward' but treats the buffer as if strings
10624 and comments have been removed."
10625 (let ((saved-point (point)))
10626 (condition-case err
10627 (cond ((null count)
10628 (js2-re-search-backward-inner regexp bound 1))
10629 ((< count 0)
10630 (js2-re-search-forward-inner regexp bound (- count)))
10631 ((> count 0)
10632 (js2-re-search-backward-inner regexp bound count)))
10633 (search-failed
10634 (goto-char saved-point)
10635 (unless noerror
10636 (error (error-message-string err)))))))
10637
10638 (defun js2-looking-at-operator-p ()
10639 "Return non-nil if text after point is a non-comma operator."
10640 (and (looking-at js2-indent-operator-re)
10641 (or (not (looking-at ":"))
10642 (save-excursion
10643 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10644 (looking-at "?"))))))
10645
10646 (defun js2-continued-expression-p ()
10647 "Return non-nil if the current line continues an expression."
10648 (save-excursion
10649 (back-to-indentation)
10650 (or (js2-looking-at-operator-p)
10651 (when (catch 'found
10652 (while (and (re-search-backward "\n" nil t)
10653 (let ((state (syntax-ppss)))
10654 (when (nth 4 state)
10655 (goto-char (nth 8 state))) ;; skip comments
10656 (skip-chars-backward " \t")
10657 (if (bolp)
10658 t
10659 (throw 'found t))))))
10660 (backward-char)
10661 (when (js2-looking-at-operator-p)
10662 (backward-char)
10663 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10664
10665 (defun js2-end-of-do-while-loop-p ()
10666 "Return non-nil if word after point is `while' of a do-while
10667 statement, else returns nil. A braceless do-while statement
10668 spanning several lines requires that the start of the loop is
10669 indented to the same column as the current line."
10670 (interactive)
10671 (save-excursion
10672 (when (looking-at "\\s-*\\<while\\>")
10673 (if (save-excursion
10674 (skip-chars-backward "[ \t\n]*}")
10675 (looking-at "[ \t\n]*}"))
10676 (save-excursion
10677 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10678 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10679 (or (looking-at "\\<do\\>")
10680 (let ((saved-indent (current-indentation)))
10681 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10682 (/= (current-indentation) saved-indent)))
10683 (and (looking-at "[ \t]*\\<do\\>")
10684 (not (js2-re-search-forward
10685 "\\<while\\>" (point-at-eol) t))
10686 (= (current-indentation) saved-indent))))))))
10687
10688 (defun js2-multiline-decl-indentation ()
10689 "Return the declaration indentation column if the current line belongs
10690 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10691 (let (forward-sexp-function ; use Lisp version
10692 at-opening-bracket)
10693 (save-excursion
10694 (back-to-indentation)
10695 (when (not (looking-at js2-declaration-keyword-re))
10696 (when (looking-at js2-indent-operator-re)
10697 (goto-char (match-end 0))) ; continued expressions are ok
10698 (while (and (not at-opening-bracket)
10699 (not (bobp))
10700 (let ((pos (point)))
10701 (save-excursion
10702 (js2-backward-sws)
10703 (or (eq (char-before) ?,)
10704 (and (not (eq (char-before) ?\;))
10705 (prog2 (skip-syntax-backward ".")
10706 (looking-at js2-indent-operator-re)
10707 (js2-backward-sws))
10708 (not (eq (char-before) ?\;)))
10709 (js2-same-line pos)))))
10710 (condition-case _
10711 (backward-sexp)
10712 (scan-error (setq at-opening-bracket t))))
10713 (when (looking-at js2-declaration-keyword-re)
10714 (goto-char (match-end 0))
10715 (1+ (current-column)))))))
10716
10717 (defun js2-ctrl-statement-indentation ()
10718 "Return the proper indentation of current line if it is a control statement.
10719 Returns an indentation if this line starts the body of a control
10720 statement without braces, else returns nil."
10721 (let (forward-sexp-function)
10722 (save-excursion
10723 (back-to-indentation)
10724 (when (and (not (js2-same-line (point-min)))
10725 (not (looking-at "{"))
10726 (js2-re-search-backward "[[:graph:]]" nil t)
10727 (not (looking-at "[{([]"))
10728 (progn
10729 (forward-char)
10730 (when (= (char-before) ?\))
10731 ;; scan-sexps sometimes throws an error
10732 (ignore-errors (backward-sexp))
10733 (skip-chars-backward " \t" (point-at-bol)))
10734 (let ((pt (point)))
10735 (back-to-indentation)
10736 (when (looking-at "}[ \t]*")
10737 (goto-char (match-end 0)))
10738 (and (looking-at js2-possibly-braceless-keywords-re)
10739 (= (match-end 0) pt)
10740 (not (js2-end-of-do-while-loop-p))))))
10741 (+ (current-indentation) js2-basic-offset)))))
10742
10743 (defun js2-indent-in-array-comp (parse-status)
10744 "Return non-nil if we think we're in an array comprehension.
10745 In particular, return the buffer position of the first `for' kwd."
10746 (let ((bracket (nth 1 parse-status))
10747 (end (point)))
10748 (when bracket
10749 (save-excursion
10750 (goto-char bracket)
10751 (when (looking-at "\\[")
10752 (forward-char 1)
10753 (js2-forward-sws)
10754 (if (looking-at "[[{]")
10755 (let (forward-sexp-function) ; use Lisp version
10756 (forward-sexp) ; skip destructuring form
10757 (js2-forward-sws)
10758 (if (and (/= (char-after) ?,) ; regular array
10759 (looking-at "for"))
10760 (match-beginning 0)))
10761 ;; to skip arbitrary expressions we need the parser,
10762 ;; so we'll just guess at it.
10763 (if (and (> end (point)) ; not empty literal
10764 (re-search-forward "[^,]]* \\(for\\) " end t)
10765 ;; not inside comment or string literal
10766 (let ((state (parse-partial-sexp bracket (point))))
10767 (not (or (nth 3 state) (nth 4 state)))))
10768 (match-beginning 1))))))))
10769
10770 (defun js2-array-comp-indentation (parse-status for-kwd)
10771 (if (js2-same-line for-kwd)
10772 ;; first continuation line
10773 (save-excursion
10774 (goto-char (nth 1 parse-status))
10775 (forward-char 1)
10776 (skip-chars-forward " \t")
10777 (current-column))
10778 (save-excursion
10779 (goto-char for-kwd)
10780 (current-column))))
10781
10782 (defun js2-proper-indentation (parse-status)
10783 "Return the proper indentation for the current line."
10784 (save-excursion
10785 (back-to-indentation)
10786 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10787 (at-closing-bracket (looking-at "[]})]"))
10788 (same-indent-p (or at-closing-bracket
10789 (looking-at "\\<case\\>[^:]")
10790 (and (looking-at "\\<default:")
10791 (save-excursion
10792 (js2-backward-sws)
10793 (not (memq (char-before) '(?, ?{)))))))
10794 (continued-expr-p (js2-continued-expression-p))
10795 (declaration-indent (and js2-pretty-multiline-declarations
10796 (js2-multiline-decl-indentation)))
10797 (bracket (nth 1 parse-status))
10798 beg indent)
10799 (cond
10800 ;; indent array comprehension continuation lines specially
10801 ((and bracket
10802 (>= js2-language-version 170)
10803 (not (js2-same-line bracket))
10804 (setq beg (js2-indent-in-array-comp parse-status))
10805 (>= (point) (save-excursion
10806 (goto-char beg)
10807 (point-at-bol)))) ; at or after first loop?
10808 (js2-array-comp-indentation parse-status beg))
10809
10810 (ctrl-stmt-indent)
10811
10812 ((and declaration-indent continued-expr-p)
10813 (+ declaration-indent js2-basic-offset))
10814
10815 (declaration-indent)
10816
10817 (bracket
10818 (goto-char bracket)
10819 (cond
10820 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10821 (when (save-excursion (skip-chars-backward " \t)")
10822 (looking-at ")"))
10823 (backward-list))
10824 (back-to-indentation)
10825 (and (eq js2-pretty-multiline-declarations 'all)
10826 (looking-at js2-declaration-keyword-re)
10827 (goto-char (1+ (match-end 0))))
10828 (setq indent
10829 (cond (same-indent-p
10830 (current-column))
10831 (continued-expr-p
10832 (+ (current-column) (* 2 js2-basic-offset)))
10833 (t
10834 (+ (current-column) js2-basic-offset))))
10835 (if (and js2-indent-switch-body
10836 (not at-closing-bracket)
10837 (looking-at "\\_<switch\\_>"))
10838 (+ indent js2-basic-offset)
10839 indent))
10840 (t
10841 (unless same-indent-p
10842 (forward-char)
10843 (skip-chars-forward " \t"))
10844 (current-column))))
10845
10846 (continued-expr-p js2-basic-offset)
10847
10848 (t 0)))))
10849
10850 (defun js2-lineup-comment (parse-status)
10851 "Indent a multi-line block comment continuation line."
10852 (let* ((beg (nth 8 parse-status))
10853 (first-line (js2-same-line beg))
10854 (offset (save-excursion
10855 (goto-char beg)
10856 (if (looking-at "/\\*")
10857 (+ 1 (current-column))
10858 0))))
10859 (unless first-line
10860 (indent-line-to offset))))
10861
10862 (defun js2-backward-sws ()
10863 "Move backward through whitespace and comments."
10864 (interactive)
10865 (while (forward-comment -1)))
10866
10867 (defun js2-forward-sws ()
10868 "Move forward through whitespace and comments."
10869 (interactive)
10870 (while (forward-comment 1)))
10871
10872 (defun js2-current-indent (&optional pos)
10873 "Return column of indentation on current line.
10874 If POS is non-nil, go to that point and return indentation for that line."
10875 (save-excursion
10876 (if pos
10877 (goto-char pos))
10878 (back-to-indentation)
10879 (current-column)))
10880
10881 (defun js2-arglist-close ()
10882 "Return non-nil if we're on a line beginning with a close-paren/brace."
10883 (save-excursion
10884 (goto-char (point-at-bol))
10885 (js2-forward-sws)
10886 (looking-at "[])}]")))
10887
10888 (defun js2-indent-looks-like-label-p ()
10889 (goto-char (point-at-bol))
10890 (js2-forward-sws)
10891 (looking-at (concat js2-mode-identifier-re ":")))
10892
10893 (defun js2-indent-in-objlit-p (parse-status)
10894 "Return non-nil if this looks like an object-literal entry."
10895 (let ((start (nth 1 parse-status)))
10896 (and
10897 start
10898 (save-excursion
10899 (and (zerop (forward-line -1))
10900 (not (< (point) start)) ; crossed a {} boundary
10901 (js2-indent-looks-like-label-p)))
10902 (save-excursion
10903 (js2-indent-looks-like-label-p)))))
10904
10905 ;; If prev line looks like foobar({ then we're passing an object
10906 ;; literal to a function call, and people pretty much always want to
10907 ;; de-dent back to the previous line, so move the 'basic-offset'
10908 ;; position to the front.
10909 (defun js2-indent-objlit-arg-p (parse-status)
10910 (save-excursion
10911 (back-to-indentation)
10912 (js2-backward-sws)
10913 (and (eq (1- (point)) (nth 1 parse-status))
10914 (eq (char-before) ?{)
10915 (progn
10916 (forward-char -1)
10917 (skip-chars-backward " \t")
10918 (eq (char-before) ?\()))))
10919
10920 (defun js2-indent-case-block-p ()
10921 (save-excursion
10922 (back-to-indentation)
10923 (js2-backward-sws)
10924 (goto-char (point-at-bol))
10925 (skip-chars-forward " \t")
10926 (looking-at "case\\s-.+:")))
10927
10928 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10929 "Cycle among alternate computed indentation positions.
10930 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10931 of the buffer to the current point. NORMAL-COL is the indentation
10932 column computed by the heuristic guesser based on current paren,
10933 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10934 in reverse."
10935 (let ((cur-indent (js2-current-indent))
10936 (old-buffer-undo-list buffer-undo-list)
10937 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10938 (current-line (save-excursion
10939 (forward-line 0) ; move to bol
10940 (1+ (count-lines (point-min) (point)))))
10941 positions pos main-pos anchor arglist-cont same-indent
10942 basic-offset computed-pos)
10943 ;; temporarily don't record undo info, if user requested this
10944 (when js2-mode-indent-inhibit-undo
10945 (setq buffer-undo-list t))
10946 (unwind-protect
10947 (progn
10948 ;; First likely point: indent from beginning of previous code line
10949 (push (setq basic-offset
10950 (+ (save-excursion
10951 (back-to-indentation)
10952 (js2-backward-sws)
10953 (back-to-indentation)
10954 (current-column))
10955 js2-basic-offset))
10956 positions)
10957
10958 ;; (First + epsilon) likely point: indent 2x from beginning of
10959 ;; previous code line. Google does it this way.
10960 (push (setq basic-offset
10961 (+ (save-excursion
10962 (back-to-indentation)
10963 (js2-backward-sws)
10964 (back-to-indentation)
10965 (current-column))
10966 (* 2 js2-basic-offset)))
10967 positions)
10968
10969 ;; Second likely point: indent from assign-expr RHS. This
10970 ;; is just a crude guess based on finding " = " on the previous
10971 ;; line containing actual code.
10972 (setq pos (save-excursion
10973 (forward-line -1)
10974 (goto-char (point-at-bol))
10975 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10976 (point-at-eol) t)
10977 (goto-char (match-end 1))
10978 (skip-chars-forward " \t\r\n")
10979 (current-column))))
10980 (when pos
10981 (cl-incf pos js2-basic-offset)
10982 (push pos positions))
10983
10984 ;; Third likely point: same indent as previous line of code.
10985 ;; Make it the first likely point if we're not on an
10986 ;; arglist-close line and previous line ends in a comma, or
10987 ;; both this line and prev line look like object-literal
10988 ;; elements.
10989 (setq pos (save-excursion
10990 (goto-char (point-at-bol))
10991 (js2-backward-sws)
10992 (back-to-indentation)
10993 (prog1
10994 (current-column)
10995 ;; while we're here, look for trailing comma
10996 (if (save-excursion
10997 (goto-char (point-at-eol))
10998 (js2-backward-sws)
10999 (eq (char-before) ?,))
11000 (setq arglist-cont (1- (point)))))))
11001 (when pos
11002 (if (and (or arglist-cont
11003 (js2-indent-in-objlit-p parse-status))
11004 (not (js2-arglist-close)))
11005 (setq same-indent pos))
11006 (push pos positions))
11007
11008 ;; Fourth likely point: first preceding code with less indentation.
11009 ;; than the immediately preceding code line.
11010 (setq pos (save-excursion
11011 (back-to-indentation)
11012 (js2-backward-sws)
11013 (back-to-indentation)
11014 (setq anchor (current-column))
11015 (while (and (zerop (forward-line -1))
11016 (>= (progn
11017 (back-to-indentation)
11018 (current-column))
11019 anchor)))
11020 (setq pos (current-column))))
11021 (push pos positions)
11022
11023 ;; nesting-heuristic position, main by default
11024 (push (setq main-pos normal-col) positions)
11025
11026 ;; delete duplicates and sort positions list
11027 (setq positions (sort (delete-dups positions) '<))
11028
11029 ;; comma-list continuation lines: prev line indent takes precedence
11030 (if same-indent
11031 (setq main-pos same-indent))
11032
11033 ;; common special cases where we want to indent in from previous line
11034 (if (or (js2-indent-case-block-p)
11035 (js2-indent-objlit-arg-p parse-status))
11036 (setq main-pos basic-offset))
11037
11038 ;; if bouncing backwards, reverse positions list
11039 (if backwards
11040 (setq positions (reverse positions)))
11041
11042 ;; record whether we're already sitting on one of the alternatives
11043 (setq pos (member cur-indent positions))
11044
11045 (cond
11046 ;; case 0: we're one one of the alternatives and this is the
11047 ;; first time they've pressed TAB on this line (best-guess).
11048 ((and js2-mode-indent-ignore-first-tab
11049 pos
11050 ;; first time pressing TAB on this line?
11051 (not (eq js2-mode-last-indented-line current-line)))
11052 ;; do nothing
11053 (setq computed-pos nil))
11054 ;; case 1: only one computed position => use it
11055 ((null (cdr positions))
11056 (setq computed-pos 0))
11057 ;; case 2: not on any of the computed spots => use main spot
11058 ((not pos)
11059 (setq computed-pos (js2-position main-pos positions)))
11060 ;; case 3: on last position: cycle to first position
11061 ((null (cdr pos))
11062 (setq computed-pos 0))
11063 ;; case 4: on intermediate position: cycle to next position
11064 (t
11065 (setq computed-pos (js2-position (cl-second pos) positions))))
11066
11067 ;; see if any hooks want to indent; otherwise we do it
11068 (cl-loop with result = nil
11069 for hook in js2-indent-hook
11070 while (null result)
11071 do
11072 (setq result (funcall hook positions computed-pos))
11073 finally do
11074 (unless (or result (null computed-pos))
11075 (indent-line-to (nth computed-pos positions)))))
11076
11077 ;; finally
11078 (if js2-mode-indent-inhibit-undo
11079 (setq buffer-undo-list old-buffer-undo-list))
11080 ;; see commentary for `js2-mode-last-indented-line'
11081 (setq js2-mode-last-indented-line current-line))))
11082
11083 (defun js2-indent-bounce-backwards ()
11084 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11085 cycles between the computed indentation positions in reverse order."
11086 (interactive)
11087 (js2-indent-line t))
11088
11089 (defun js2-1-line-comment-continuation-p ()
11090 "Return t if we're in a 1-line comment continuation.
11091 If so, we don't ever want to use bounce-indent."
11092 (save-excursion
11093 (and (progn
11094 (forward-line 0)
11095 (looking-at "\\s-*//"))
11096 (progn
11097 (forward-line -1)
11098 (forward-line 0)
11099 (when (looking-at "\\s-*$")
11100 (js2-backward-sws)
11101 (forward-line 0))
11102 (looking-at "\\s-*//")))))
11103
11104 (defun js2-indent-line (&optional bounce-backwards)
11105 "Indent the current line as JavaScript source text."
11106 (interactive)
11107 (let (parse-status offset indent-col
11108 ;; Don't whine about errors/warnings when we're indenting.
11109 ;; This has to be set before calling parse-partial-sexp below.
11110 (inhibit-point-motion-hooks t))
11111 (setq parse-status (save-excursion
11112 (syntax-ppss (point-at-bol)))
11113 offset (- (point) (save-excursion
11114 (back-to-indentation)
11115 (point))))
11116 (js2-with-underscore-as-word-syntax
11117 (if (nth 4 parse-status)
11118 (js2-lineup-comment parse-status)
11119 (setq indent-col (js2-proper-indentation parse-status))
11120 ;; See comments below about `js2-mode-last-indented-line'.
11121 (cond
11122 ;; bounce-indenting is disabled during electric-key indent.
11123 ;; It doesn't work well on first line of buffer.
11124 ((and js2-bounce-indent-p
11125 (not (js2-same-line (point-min)))
11126 (not (js2-1-line-comment-continuation-p)))
11127 (js2-bounce-indent indent-col parse-status bounce-backwards))
11128 ;; just indent to the guesser's likely spot
11129 (t (indent-line-to indent-col))))
11130 (when (cl-plusp offset)
11131 (forward-char offset)))))
11132
11133 (defun js2-indent-region (start end)
11134 "Indent the region, but don't use bounce indenting."
11135 (let ((js2-bounce-indent-p nil)
11136 (indent-region-function nil)
11137 (after-change-functions (remq 'js2-mode-edit
11138 after-change-functions)))
11139 (indent-region start end nil) ; nil for byte-compiler
11140 (js2-mode-edit start end (- end start))))
11141
11142 (defvar js2-minor-mode-map
11143 (let ((map (make-sparse-keymap)))
11144 (define-key map (kbd "C-c C-`") #'js2-next-error)
11145 (define-key map [mouse-1] #'js2-mode-show-node)
11146 map)
11147 "Keymap used when `js2-minor-mode' is active.")
11148
11149 ;;;###autoload
11150 (define-minor-mode js2-minor-mode
11151 "Minor mode for running js2 as a background linter.
11152 This allows you to use a different major mode for JavaScript editing,
11153 such as `js-mode', while retaining the asynchronous error/warning
11154 highlighting features of `js2-mode'."
11155 :group 'js2-mode
11156 :lighter " js-lint"
11157 (if js2-minor-mode
11158 (js2-minor-mode-enter)
11159 (js2-minor-mode-exit)))
11160
11161 (defun js2-minor-mode-enter ()
11162 "Initialization for `js2-minor-mode'."
11163 (set (make-local-variable 'max-lisp-eval-depth)
11164 (max max-lisp-eval-depth 3000))
11165 (setq next-error-function #'js2-next-error)
11166 (js2-set-default-externs)
11167 ;; Experiment: make reparse-delay longer for longer files.
11168 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11169 (setq js2-idle-timer-delay
11170 (* js2-idle-timer-delay
11171 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11172 (setq js2-mode-buffer-dirty-p t
11173 js2-mode-parsing nil)
11174 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11175 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11176 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11177 (when js2-include-jslint-globals
11178 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11179 (run-hooks 'js2-init-hook)
11180 (js2-reparse))
11181
11182 (defun js2-minor-mode-exit ()
11183 "Turn off `js2-minor-mode'."
11184 (setq next-error-function nil)
11185 (remove-hook 'after-change-functions #'js2-mode-edit t)
11186 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11187 (when js2-mode-node-overlay
11188 (delete-overlay js2-mode-node-overlay)
11189 (setq js2-mode-node-overlay nil))
11190 (js2-remove-overlays)
11191 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11192 (setq js2-mode-ast nil))
11193
11194 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11195 (make-variable-buffer-local 'js2-source-buffer)
11196
11197 (cl-defun js2-display-error-list ()
11198 "Display a navigable buffer listing parse errors/warnings."
11199 (interactive)
11200 (unless (js2-have-errors-p)
11201 (message "No errors")
11202 (cl-return-from js2-display-error-list))
11203 (cl-labels ((annotate-list
11204 (lst type)
11205 "Add diagnostic TYPE and line number to errs list"
11206 (mapcar (lambda (err)
11207 (list err type (line-number-at-pos (nth 1 err))))
11208 lst)))
11209 (let* ((srcbuf (current-buffer))
11210 (errbuf (get-buffer-create "*js-lint*"))
11211 (errors (annotate-list
11212 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11213 'js2-error)) ; must be a valid face name
11214 (warnings (annotate-list
11215 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11216 'js2-warning)) ; must be a valid face name
11217 (all-errs (sort (append errors warnings)
11218 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11219 (with-current-buffer errbuf
11220 (let ((inhibit-read-only t))
11221 (erase-buffer)
11222 (dolist (err all-errs)
11223 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11224 (insert-text-button
11225 (format "line %d: %s" line (js2-get-msg msg-key))
11226 'face type
11227 'follow-link "\C-m"
11228 'action 'js2-error-buffer-jump
11229 'js2-msg (js2-get-msg msg-key)
11230 'js2-pos beg)
11231 (insert "\n"))))
11232 (js2-error-buffer-mode)
11233 (setq js2-source-buffer srcbuf)
11234 (pop-to-buffer errbuf)
11235 (goto-char (point-min))
11236 (unless (eobp)
11237 (js2-error-buffer-view))))))
11238
11239 (defvar js2-error-buffer-mode-map
11240 (let ((map (make-sparse-keymap)))
11241 (define-key map "n" #'js2-error-buffer-next)
11242 (define-key map "p" #'js2-error-buffer-prev)
11243 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11244 (define-key map "o" #'js2-error-buffer-view)
11245 (define-key map "q" #'js2-error-buffer-quit)
11246 map)
11247 "Keymap used for js2 diagnostics buffers.")
11248
11249 (defun js2-error-buffer-mode ()
11250 "Major mode for js2 diagnostics buffers.
11251 Selecting an error will jump it to the corresponding source-buffer error.
11252 \\{js2-error-buffer-mode-map}"
11253 (interactive)
11254 (setq major-mode 'js2-error-buffer-mode
11255 mode-name "JS Lint Diagnostics")
11256 (use-local-map js2-error-buffer-mode-map)
11257 (setq truncate-lines t)
11258 (set-buffer-modified-p nil)
11259 (setq buffer-read-only t)
11260 (run-hooks 'js2-error-buffer-mode-hook))
11261
11262 (defun js2-error-buffer-next ()
11263 "Move to next error and view it."
11264 (interactive)
11265 (when (zerop (forward-line 1))
11266 (js2-error-buffer-view)))
11267
11268 (defun js2-error-buffer-prev ()
11269 "Move to previous error and view it."
11270 (interactive)
11271 (when (zerop (forward-line -1))
11272 (js2-error-buffer-view)))
11273
11274 (defun js2-error-buffer-quit ()
11275 "Kill the current buffer."
11276 (interactive)
11277 (kill-buffer))
11278
11279 (defun js2-error-buffer-jump (&rest ignored)
11280 "Jump cursor to current error in source buffer."
11281 (interactive)
11282 (when (js2-error-buffer-view)
11283 (pop-to-buffer js2-source-buffer)))
11284
11285 (defun js2-error-buffer-view ()
11286 "Scroll source buffer to show error at current line."
11287 (interactive)
11288 (cond
11289 ((not (eq major-mode 'js2-error-buffer-mode))
11290 (message "Not in a js2 errors buffer"))
11291 ((not (buffer-live-p js2-source-buffer))
11292 (message "Source buffer has been killed"))
11293 ((not (wholenump (get-text-property (point) 'js2-pos)))
11294 (message "There does not seem to be an error here"))
11295 (t
11296 (let ((pos (get-text-property (point) 'js2-pos))
11297 (msg (get-text-property (point) 'js2-msg)))
11298 (save-selected-window
11299 (pop-to-buffer js2-source-buffer)
11300 (goto-char pos)
11301 (message msg))))))
11302
11303 ;;;###autoload
11304 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11305 ;; FIXME: Should derive from js-mode.
11306 "Major mode for editing JavaScript code."
11307 ;; Used by comment-region; don't change it.
11308 (set (make-local-variable 'comment-start) "//")
11309 (set (make-local-variable 'comment-end) "")
11310 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11311 (set (make-local-variable 'max-lisp-eval-depth)
11312 (max max-lisp-eval-depth 3000))
11313 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11314 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11315 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11316 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11317 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11318 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11319 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11320 ;; for characters inside regexp literals.
11321 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11322 ;; this is necessary to make `show-paren-function' work properly
11323 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11324 ;; needed for M-x rgrep, among other things
11325 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11326
11327 (set (make-local-variable 'electric-indent-chars)
11328 (append "{}()[]:;,*." electric-indent-chars))
11329 (set (make-local-variable 'electric-layout-rules)
11330 '((?\; . after) (?\{ . after) (?\} . before)))
11331
11332 ;; some variables needed by cc-engine for paragraph-fill, etc.
11333 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11334 c-comment-start-regexp "/[*/]\\|\\s|"
11335 c-line-comment-starter "//"
11336 c-paragraph-start js2-paragraph-start
11337 c-paragraph-separate "$"
11338 c-syntactic-ws-start js2-syntactic-ws-start
11339 c-syntactic-ws-end js2-syntactic-ws-end
11340 c-syntactic-eol js2-syntactic-eol)
11341
11342 (let ((c-buffer-is-cc-mode t))
11343 ;; Copied from `js-mode'. Also see Bug#6071.
11344 (make-local-variable 'paragraph-start)
11345 (make-local-variable 'paragraph-separate)
11346 (make-local-variable 'paragraph-ignore-fill-prefix)
11347 (make-local-variable 'adaptive-fill-mode)
11348 (make-local-variable 'adaptive-fill-regexp)
11349 (c-setup-paragraph-variables))
11350
11351 (setq font-lock-defaults '(nil t))
11352
11353 ;; Experiment: make reparse-delay longer for longer files.
11354 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11355 (setq js2-idle-timer-delay
11356 (* js2-idle-timer-delay
11357 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11358
11359 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11360 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11361 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11362 (setq next-error-function #'js2-next-error)
11363 (imenu-add-to-menubar (concat "IM-" mode-name))
11364 (add-to-invisibility-spec '(js2-outline . t))
11365 (set (make-local-variable 'line-move-ignore-invisible) t)
11366 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11367
11368 (setq js2-mode-functions-hidden nil
11369 js2-mode-comments-hidden nil
11370 js2-mode-buffer-dirty-p t
11371 js2-mode-parsing nil)
11372
11373 (js2-set-default-externs)
11374
11375 (when js2-include-jslint-globals
11376 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11377
11378 (run-hooks 'js2-init-hook)
11379
11380 (js2-reparse))
11381
11382 (defun js2-mode-exit ()
11383 "Exit `js2-mode' and clean up."
11384 (interactive)
11385 (when js2-mode-node-overlay
11386 (delete-overlay js2-mode-node-overlay)
11387 (setq js2-mode-node-overlay nil))
11388 (js2-remove-overlays)
11389 (setq js2-mode-ast nil)
11390 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11391 (remove-from-invisibility-spec '(js2-outline . t))
11392 (js2-mode-show-all)
11393 (with-silent-modifications
11394 (js2-clear-face (point-min) (point-max))))
11395
11396 (defun js2-mode-reset-timer ()
11397 "Cancel any existing parse timer and schedule a new one."
11398 (if js2-mode-parse-timer
11399 (cancel-timer js2-mode-parse-timer))
11400 (setq js2-mode-parsing nil)
11401 (let ((timer (timer-create)))
11402 (setq js2-mode-parse-timer timer)
11403 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11404 (timer-set-idle-time timer js2-idle-timer-delay)
11405 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11406 (timer-activate-when-idle timer nil)))
11407
11408 (defun js2-mode-idle-reparse (buffer)
11409 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11410 it to be reparsed when the buffer is selected."
11411 (cond ((eq buffer (current-buffer))
11412 (js2-reparse))
11413 ((buffer-live-p buffer)
11414 ;; reparse when the buffer is selected again
11415 (with-current-buffer buffer
11416 (add-hook 'window-configuration-change-hook
11417 #'js2-mode-idle-reparse-inner
11418 nil t)))))
11419
11420 (defun js2-mode-idle-reparse-inner ()
11421 (remove-hook 'window-configuration-change-hook
11422 #'js2-mode-idle-reparse-inner
11423 t)
11424 (js2-reparse))
11425
11426 (defun js2-mode-edit (_beg _end _len)
11427 "Schedule a new parse after buffer is edited.
11428 Buffer edit spans from BEG to END and is of length LEN."
11429 (setq js2-mode-buffer-dirty-p t)
11430 (js2-mode-hide-overlay)
11431 (js2-mode-reset-timer))
11432
11433 (defun js2-minor-mode-edit (_beg _end _len)
11434 "Callback for buffer edits in `js2-mode'.
11435 Schedules a new parse after buffer is edited.
11436 Buffer edit spans from BEG to END and is of length LEN."
11437 (setq js2-mode-buffer-dirty-p t)
11438 (js2-mode-hide-overlay)
11439 (js2-mode-reset-timer))
11440
11441 (defun js2-reparse (&optional force)
11442 "Re-parse current buffer after user finishes some data entry.
11443 If we get any user input while parsing, including cursor motion,
11444 we discard the parse and reschedule it. If FORCE is nil, then the
11445 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11446 (let (time
11447 interrupted-p
11448 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11449 (unless js2-mode-parsing
11450 (setq js2-mode-parsing t)
11451 (unwind-protect
11452 (when (or js2-mode-buffer-dirty-p force)
11453 (js2-remove-overlays)
11454 (setq js2-mode-buffer-dirty-p nil
11455 js2-mode-fontifications nil
11456 js2-mode-deferred-properties nil)
11457 (if js2-mode-verbose-parse-p
11458 (message "parsing..."))
11459 (setq time
11460 (js2-time
11461 (setq interrupted-p
11462 (catch 'interrupted
11463 (js2-parse)
11464 (with-silent-modifications
11465 ;; if parsing is interrupted, comments and regex
11466 ;; literals stay ignored by `parse-partial-sexp'
11467 (remove-text-properties (point-min) (point-max)
11468 '(syntax-table))
11469 (js2-mode-apply-deferred-properties)
11470 (js2-mode-remove-suppressed-warnings)
11471 (js2-mode-show-warnings)
11472 (js2-mode-show-errors)
11473 (if (>= js2-highlight-level 1)
11474 (js2-highlight-jsdoc js2-mode-ast)))
11475 nil))))
11476 (if interrupted-p
11477 (progn
11478 ;; unfinished parse => try again
11479 (setq js2-mode-buffer-dirty-p t)
11480 (js2-mode-reset-timer))
11481 (if js2-mode-verbose-parse-p
11482 (message "Parse time: %s" time))))
11483 (setq js2-mode-parsing nil)
11484 (unless interrupted-p
11485 (setq js2-mode-parse-timer nil))))))
11486
11487 (defun js2-mode-show-node (event)
11488 "Debugging aid: highlight selected AST node on mouse click."
11489 (interactive "e")
11490 (mouse-set-point event)
11491 (setq deactivate-mark t)
11492 (when js2-mode-show-overlay
11493 (let ((node (js2-node-at-point))
11494 beg end)
11495 (if (null node)
11496 (message "No node found at location %s" (point))
11497 (setq beg (js2-node-abs-pos node)
11498 end (+ beg (js2-node-len node)))
11499 (if js2-mode-node-overlay
11500 (move-overlay js2-mode-node-overlay beg end)
11501 (setq js2-mode-node-overlay (make-overlay beg end))
11502 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11503 (with-silent-modifications
11504 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
11505 (message "%s, parent: %s"
11506 (js2-node-short-name node)
11507 (if (js2-node-parent node)
11508 (js2-node-short-name (js2-node-parent node))
11509 "nil"))))))
11510
11511 (defun js2-mode-hide-overlay (&optional _p1 p2)
11512 "Remove the debugging overlay when the point moves.
11513 P1 and P2 are the old and new values of point, respectively."
11514 (when js2-mode-node-overlay
11515 (let ((beg (overlay-start js2-mode-node-overlay))
11516 (end (overlay-end js2-mode-node-overlay)))
11517 ;; Sometimes we're called spuriously.
11518 (unless (and p2
11519 (>= p2 beg)
11520 (<= p2 end))
11521 (with-silent-modifications
11522 (remove-text-properties beg end '(point-left nil)))
11523 (delete-overlay js2-mode-node-overlay)
11524 (setq js2-mode-node-overlay nil)))))
11525
11526 (defun js2-mode-reset ()
11527 "Debugging helper: reset everything."
11528 (interactive)
11529 (js2-mode-exit)
11530 (js2-mode))
11531
11532 (defun js2-mode-show-warn-or-err (e face)
11533 "Highlight a warning or error E with FACE.
11534 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11535 The last element is optional. When present, use instead of FACE."
11536 (let* ((key (cl-first e))
11537 (beg (cl-second e))
11538 (end (+ beg (cl-third e)))
11539 ;; Don't inadvertently go out of bounds.
11540 (beg (max (point-min) (min beg (point-max))))
11541 (end (max (point-min) (min end (point-max))))
11542 (ovl (make-overlay beg end)))
11543 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11544 (overlay-put ovl 'js2-error t)
11545 (put-text-property beg end 'help-echo (js2-get-msg key))
11546 (put-text-property beg end 'point-entered #'js2-echo-error)))
11547
11548 (defun js2-remove-overlays ()
11549 "Remove overlays from buffer that have a `js2-error' property."
11550 (let ((beg (point-min))
11551 (end (point-max)))
11552 (save-excursion
11553 (dolist (o (overlays-in beg end))
11554 (when (overlay-get o 'js2-error)
11555 (delete-overlay o))))))
11556
11557 (defun js2-error-at-point (&optional pos)
11558 "Return non-nil if there's an error overlay at POS.
11559 Defaults to point."
11560 (cl-loop with pos = (or pos (point))
11561 for o in (overlays-at pos)
11562 thereis (overlay-get o 'js2-error)))
11563
11564 (defun js2-mode-apply-deferred-properties ()
11565 "Apply fontifications and other text properties recorded during parsing."
11566 (when (cl-plusp js2-highlight-level)
11567 ;; We defer clearing faces as long as possible to eliminate flashing.
11568 (js2-clear-face (point-min) (point-max))
11569 ;; Have to reverse the recorded fontifications list so that errors
11570 ;; and warnings overwrite the normal fontifications.
11571 (dolist (f (nreverse js2-mode-fontifications))
11572 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11573 (setq js2-mode-fontifications nil))
11574 (dolist (p js2-mode-deferred-properties)
11575 (apply #'put-text-property p))
11576 (setq js2-mode-deferred-properties nil))
11577
11578 (defun js2-mode-show-errors ()
11579 "Highlight syntax errors."
11580 (when js2-mode-show-parse-errors
11581 (dolist (e (js2-ast-root-errors js2-mode-ast))
11582 (js2-mode-show-warn-or-err e 'js2-error))))
11583
11584 (defun js2-mode-remove-suppressed-warnings ()
11585 "Take suppressed warnings out of the AST warnings list.
11586 This ensures that the counts and `next-error' are correct."
11587 (setf (js2-ast-root-warnings js2-mode-ast)
11588 (js2-delete-if
11589 (lambda (e)
11590 (let ((key (caar e)))
11591 (or
11592 (and (not js2-strict-trailing-comma-warning)
11593 (string-match "trailing\\.comma" key))
11594 (and (not js2-strict-cond-assign-warning)
11595 (string= key "msg.equal.as.assign"))
11596 (and js2-missing-semi-one-line-override
11597 (string= key "msg.missing.semi")
11598 (let* ((beg (cl-second e))
11599 (node (js2-node-at-point beg))
11600 (fn (js2-mode-find-parent-fn node))
11601 (body (and fn (js2-function-node-body fn)))
11602 (lc (and body (js2-node-abs-pos body)))
11603 (rc (and lc (+ lc (js2-node-len body)))))
11604 (and fn
11605 (or (null body)
11606 (save-excursion
11607 (goto-char beg)
11608 (and (js2-same-line lc)
11609 (js2-same-line rc))))))))))
11610 (js2-ast-root-warnings js2-mode-ast))))
11611
11612 (defun js2-mode-show-warnings ()
11613 "Highlight strict-mode warnings."
11614 (when js2-mode-show-strict-warnings
11615 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11616 (js2-mode-show-warn-or-err e 'js2-warning))))
11617
11618 (defun js2-echo-error (_old-point new-point)
11619 "Called by point-motion hooks."
11620 (let ((msg (get-text-property new-point 'help-echo)))
11621 (when (and (stringp msg)
11622 (not (active-minibuffer-window))
11623 (not (current-message)))
11624 (message msg))))
11625
11626 (defalias 'js2-echo-help #'js2-echo-error)
11627
11628 (defun js2-line-break (&optional _soft)
11629 "Break line at point and indent, continuing comment if within one.
11630 If inside a string, and `js2-concat-multiline-strings' is not
11631 nil, turn it into concatenation."
11632 (interactive)
11633 (let ((parse-status (syntax-ppss)))
11634 (cond
11635 ;; Check if we're inside a string.
11636 ((nth 3 parse-status)
11637 (if js2-concat-multiline-strings
11638 (js2-mode-split-string parse-status)
11639 (insert "\n")))
11640 ;; Check if inside a block comment.
11641 ((nth 4 parse-status)
11642 (js2-mode-extend-comment (nth 8 parse-status)))
11643 (t
11644 (newline-and-indent)))))
11645
11646 (defun js2-mode-split-string (parse-status)
11647 "Turn a newline in mid-string into a string concatenation.
11648 PARSE-STATUS is as documented in `parse-partial-sexp'."
11649 (let* ((quote-char (nth 3 parse-status))
11650 (at-eol (eq js2-concat-multiline-strings 'eol)))
11651 (insert quote-char)
11652 (insert (if at-eol " +\n" "\n"))
11653 (unless at-eol
11654 (insert "+ "))
11655 (js2-indent-line)
11656 (insert quote-char)
11657 (when (eolp)
11658 (insert quote-char)
11659 (backward-char 1))))
11660
11661 (defun js2-mode-extend-comment (start-pos)
11662 "Indent the line and, when inside a comment block, add comment prefix."
11663 (let (star single col first-line needs-close)
11664 (save-excursion
11665 (back-to-indentation)
11666 (when (< (point) start-pos)
11667 (goto-char start-pos))
11668 (cond
11669 ((looking-at "\\*[^/]")
11670 (setq star t
11671 col (current-column)))
11672 ((looking-at "/\\*")
11673 (setq star t
11674 first-line t
11675 col (1+ (current-column))))
11676 ((looking-at "//")
11677 (setq single t
11678 col (current-column)))))
11679 ;; Heuristic for whether we need to close the comment:
11680 ;; if we've got a parse error here, assume it's an unterminated
11681 ;; comment.
11682 (setq needs-close
11683 (or
11684 (eq (get-text-property (1- (point)) 'point-entered)
11685 'js2-echo-error)
11686 ;; The heuristic above doesn't work well when we're
11687 ;; creating a comment and there's another one downstream,
11688 ;; as our parser thinks this one ends at the end of the
11689 ;; next one. (You can have a /* inside a js block comment.)
11690 ;; So just close it if the next non-ws char isn't a *.
11691 (and first-line
11692 (eolp)
11693 (save-excursion
11694 (skip-chars-forward " \t\r\n")
11695 (not (eq (char-after) ?*))))))
11696 (delete-horizontal-space)
11697 (insert "\n")
11698 (cond
11699 (star
11700 (indent-to col)
11701 (insert "* ")
11702 (if (and first-line needs-close)
11703 (save-excursion
11704 (insert "\n")
11705 (indent-to col)
11706 (insert "*/"))))
11707 ((and single
11708 (save-excursion
11709 (and (zerop (forward-line 1))
11710 (looking-at "\\s-*//"))))
11711 (indent-to col)
11712 (insert "// ")))
11713 ;; Don't need to extend the comment after all.
11714 (js2-indent-line)))
11715
11716 (defun js2-beginning-of-line ()
11717 "Toggle point between bol and first non-whitespace char in line.
11718 Also moves past comment delimiters when inside comments."
11719 (interactive)
11720 (let (node)
11721 (cond
11722 ((bolp)
11723 (back-to-indentation))
11724 ((looking-at "//")
11725 (skip-chars-forward "/ \t"))
11726 ((and (eq (char-after) ?*)
11727 (setq node (js2-comment-at-point))
11728 (memq (js2-comment-node-format node) '(jsdoc block))
11729 (save-excursion
11730 (skip-chars-backward " \t")
11731 (bolp)))
11732 (skip-chars-forward "\* \t"))
11733 (t
11734 (goto-char (point-at-bol))))))
11735
11736 (defun js2-end-of-line ()
11737 "Toggle point between eol and last non-whitespace char in line."
11738 (interactive)
11739 (if (eolp)
11740 (skip-chars-backward " \t")
11741 (goto-char (point-at-eol))))
11742
11743 (defun js2-mode-wait-for-parse (callback)
11744 "Invoke CALLBACK when parsing is finished.
11745 If parsing is already finished, calls CALLBACK immediately."
11746 (if (not js2-mode-buffer-dirty-p)
11747 (funcall callback)
11748 (push callback js2-mode-pending-parse-callbacks)
11749 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11750
11751 (defun js2-mode-parse-finished ()
11752 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11753 ;; We can't let errors propagate up, since it prevents the
11754 ;; `js2-parse' method from completing normally and returning
11755 ;; the ast, which makes things mysteriously not work right.
11756 (unwind-protect
11757 (dolist (cb js2-mode-pending-parse-callbacks)
11758 (condition-case err
11759 (funcall cb)
11760 (error (message "%s" err))))
11761 (setq js2-mode-pending-parse-callbacks nil)))
11762
11763 (defun js2-mode-flag-region (from to flag)
11764 "Hide or show text from FROM to TO, according to FLAG.
11765 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11766 Returns the created overlay if FLAG is non-nil."
11767 (remove-overlays from to 'invisible 'js2-outline)
11768 (when flag
11769 (let ((o (make-overlay from to)))
11770 (overlay-put o 'invisible 'js2-outline)
11771 (overlay-put o 'isearch-open-invisible
11772 'js2-isearch-open-invisible)
11773 o)))
11774
11775 ;; Function to be set as an outline-isearch-open-invisible' property
11776 ;; to the overlay that makes the outline invisible (see
11777 ;; `js2-mode-flag-region').
11778 (defun js2-isearch-open-invisible (_overlay)
11779 ;; We rely on the fact that isearch places point on the matched text.
11780 (js2-mode-show-element))
11781
11782 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11783 "Return cons cell of bounds of folding overlay at POS.
11784 Returns nil if not found."
11785 (let ((overlays (overlays-at (or pos (point))))
11786 o)
11787 (while (and overlays
11788 (not o))
11789 (if (overlay-get (car overlays) 'invisible)
11790 (setq o (car overlays))
11791 (setq overlays (cdr overlays))))
11792 (if o
11793 (cons (overlay-start o) (overlay-end o)))))
11794
11795 (defun js2-mode-function-at-point (&optional pos)
11796 "Return the innermost function node enclosing current point.
11797 Returns nil if point is not in a function."
11798 (let ((node (js2-node-at-point pos)))
11799 (while (and node (not (js2-function-node-p node)))
11800 (setq node (js2-node-parent node)))
11801 (if (js2-function-node-p node)
11802 node)))
11803
11804 (defun js2-mode-toggle-element ()
11805 "Hide or show the foldable element at the point."
11806 (interactive)
11807 (let (comment fn pos)
11808 (save-excursion
11809 (cond
11810 ;; /* ... */ comment?
11811 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11812 (if (js2-mode-invisible-overlay-bounds
11813 (setq pos (+ 3 (js2-node-abs-pos comment))))
11814 (progn
11815 (goto-char pos)
11816 (js2-mode-show-element))
11817 (js2-mode-hide-element)))
11818 ;; //-comment?
11819 ((save-excursion
11820 (back-to-indentation)
11821 (looking-at js2-mode-//-comment-re))
11822 (js2-mode-toggle-//-comment))
11823 ;; function?
11824 ((setq fn (js2-mode-function-at-point))
11825 (setq pos (and (js2-function-node-body fn)
11826 (js2-node-abs-pos (js2-function-node-body fn))))
11827 (goto-char (1+ pos))
11828 (if (js2-mode-invisible-overlay-bounds)
11829 (js2-mode-show-element)
11830 (js2-mode-hide-element)))
11831 (t
11832 (message "Nothing at point to hide or show"))))))
11833
11834 (defun js2-mode-hide-element ()
11835 "Fold/hide contents of a block, showing ellipses.
11836 Show the hidden text with \\[js2-mode-show-element]."
11837 (interactive)
11838 (if js2-mode-buffer-dirty-p
11839 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11840 (let (node body beg end)
11841 (cond
11842 ((js2-mode-invisible-overlay-bounds)
11843 (message "already hidden"))
11844 (t
11845 (setq node (js2-node-at-point))
11846 (cond
11847 ((js2-block-comment-p node)
11848 (js2-mode-hide-comment node))
11849 (t
11850 (while (and node (not (js2-function-node-p node)))
11851 (setq node (js2-node-parent node)))
11852 (if (and node
11853 (setq body (js2-function-node-body node)))
11854 (progn
11855 (setq beg (js2-node-abs-pos body)
11856 end (+ beg (js2-node-len body)))
11857 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11858 (message "No collapsable element found at point"))))))))
11859
11860 (defun js2-mode-show-element ()
11861 "Show the hidden element at current point."
11862 (interactive)
11863 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11864 (if bounds
11865 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11866 (message "Nothing to un-hide"))))
11867
11868 (defun js2-mode-show-all ()
11869 "Show all of the text in the buffer."
11870 (interactive)
11871 (js2-mode-flag-region (point-min) (point-max) nil))
11872
11873 (defun js2-mode-toggle-hide-functions ()
11874 (interactive)
11875 (if js2-mode-functions-hidden
11876 (js2-mode-show-functions)
11877 (js2-mode-hide-functions)))
11878
11879 (defun js2-mode-hide-functions ()
11880 "Hides all non-nested function bodies in the buffer.
11881 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11882 to open an individual entry."
11883 (interactive)
11884 (if js2-mode-buffer-dirty-p
11885 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11886 (if (null js2-mode-ast)
11887 (message "Oops - parsing failed")
11888 (setq js2-mode-functions-hidden t)
11889 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11890
11891 (defun js2-mode-function-hider (n endp)
11892 (when (not endp)
11893 (let ((tt (js2-node-type n))
11894 body beg end)
11895 (cond
11896 ((and (= tt js2-FUNCTION)
11897 (setq body (js2-function-node-body n)))
11898 (setq beg (js2-node-abs-pos body)
11899 end (+ beg (js2-node-len body)))
11900 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11901 nil) ; don't process children of function
11902 (t
11903 t))))) ; keep processing other AST nodes
11904
11905 (defun js2-mode-show-functions ()
11906 "Un-hide any folded function bodies in the buffer."
11907 (interactive)
11908 (setq js2-mode-functions-hidden nil)
11909 (save-excursion
11910 (goto-char (point-min))
11911 (while (/= (goto-char (next-overlay-change (point)))
11912 (point-max))
11913 (dolist (o (overlays-at (point)))
11914 (when (and (overlay-get o 'invisible)
11915 (not (overlay-get o 'comment)))
11916 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11917
11918 (defun js2-mode-hide-comment (n)
11919 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11920 3 ; /**
11921 2)) ; /*
11922 (beg (+ (js2-node-abs-pos n) head))
11923 (end (- (+ beg (js2-node-len n)) head 2))
11924 (o (js2-mode-flag-region beg end 'hide)))
11925 (overlay-put o 'comment t)))
11926
11927 (defun js2-mode-toggle-hide-comments ()
11928 "Folds all block comments in the buffer.
11929 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11930 to open an individual entry."
11931 (interactive)
11932 (if js2-mode-comments-hidden
11933 (js2-mode-show-comments)
11934 (js2-mode-hide-comments)))
11935
11936 (defun js2-mode-hide-comments ()
11937 (interactive)
11938 (if js2-mode-buffer-dirty-p
11939 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11940 (if (null js2-mode-ast)
11941 (message "Oops - parsing failed")
11942 (setq js2-mode-comments-hidden t)
11943 (dolist (n (js2-ast-root-comments js2-mode-ast))
11944 (when (js2-block-comment-p n)
11945 (js2-mode-hide-comment n)))
11946 (js2-mode-hide-//-comments)))
11947
11948 (defun js2-mode-extend-//-comment (direction)
11949 "Find start or end of a block of similar //-comment lines.
11950 DIRECTION is -1 to look back, 1 to look forward.
11951 INDENT is the indentation level to match.
11952 Returns the end-of-line position of the furthest adjacent
11953 //-comment line with the same indentation as the current line.
11954 If there is no such matching line, returns current end of line."
11955 (let ((pos (point-at-eol))
11956 (indent (current-indentation)))
11957 (save-excursion
11958 (while (and (zerop (forward-line direction))
11959 (looking-at js2-mode-//-comment-re)
11960 (eq indent (length (match-string 1))))
11961 (setq pos (point-at-eol)))
11962 pos)))
11963
11964 (defun js2-mode-hide-//-comments ()
11965 "Fold adjacent 1-line comments, showing only snippet of first one."
11966 (let (beg end)
11967 (save-excursion
11968 (goto-char (point-min))
11969 (while (re-search-forward js2-mode-//-comment-re nil t)
11970 (setq beg (point)
11971 end (js2-mode-extend-//-comment 1))
11972 (unless (eq beg end)
11973 (overlay-put (js2-mode-flag-region beg end 'hide)
11974 'comment t))
11975 (goto-char end)
11976 (forward-char 1)))))
11977
11978 (defun js2-mode-toggle-//-comment ()
11979 "Fold or un-fold any multi-line //-comment at point.
11980 Caller should have determined that this line starts with a //-comment."
11981 (let* ((beg (point-at-eol))
11982 (end beg))
11983 (save-excursion
11984 (goto-char end)
11985 (if (js2-mode-invisible-overlay-bounds)
11986 (js2-mode-show-element)
11987 ;; else hide the comment
11988 (setq beg (js2-mode-extend-//-comment -1)
11989 end (js2-mode-extend-//-comment 1))
11990 (unless (eq beg end)
11991 (overlay-put (js2-mode-flag-region beg end 'hide)
11992 'comment t))))))
11993
11994 (defun js2-mode-show-comments ()
11995 "Un-hide any hidden comments, leaving other hidden elements alone."
11996 (interactive)
11997 (setq js2-mode-comments-hidden nil)
11998 (save-excursion
11999 (goto-char (point-min))
12000 (while (/= (goto-char (next-overlay-change (point)))
12001 (point-max))
12002 (dolist (o (overlays-at (point)))
12003 (when (overlay-get o 'comment)
12004 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12005
12006 (defun js2-mode-display-warnings-and-errors ()
12007 "Turn on display of warnings and errors."
12008 (interactive)
12009 (setq js2-mode-show-parse-errors t
12010 js2-mode-show-strict-warnings t)
12011 (js2-reparse 'force))
12012
12013 (defun js2-mode-hide-warnings-and-errors ()
12014 "Turn off display of warnings and errors."
12015 (interactive)
12016 (setq js2-mode-show-parse-errors nil
12017 js2-mode-show-strict-warnings nil)
12018 (js2-reparse 'force))
12019
12020 (defun js2-mode-toggle-warnings-and-errors ()
12021 "Toggle the display of warnings and errors.
12022 Some users don't like having warnings/errors reported while they type."
12023 (interactive)
12024 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12025 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12026 (if (called-interactively-p 'any)
12027 (message "warnings and errors %s"
12028 (if js2-mode-show-parse-errors
12029 "enabled"
12030 "disabled")))
12031 (js2-reparse 'force))
12032
12033 (defun js2-mode-customize ()
12034 (interactive)
12035 (customize-group 'js2-mode))
12036
12037 (defun js2-mode-forward-sexp (&optional arg)
12038 "Move forward across one statement or balanced expression.
12039 With ARG, do it that many times. Negative arg -N means
12040 move backward across N balanced expressions."
12041 (interactive "p")
12042 (setq arg (or arg 1))
12043 (save-restriction
12044 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12045 (js2-reparse)
12046 (let (forward-sexp-function
12047 node (start (point)) pos lp rp child)
12048 (cond
12049 ;; backward-sexp
12050 ;; could probably make this better for some cases:
12051 ;; - if in statement block (e.g. function body), go to parent
12052 ;; - infix exprs like (foo in bar) - maybe go to beginning
12053 ;; of infix expr if in the right-side expression?
12054 ((and arg (cl-minusp arg))
12055 (dotimes (_ (- arg))
12056 (js2-backward-sws)
12057 (forward-char -1) ; Enter the node we backed up to.
12058 (when (setq node (js2-node-at-point (point) t))
12059 (setq pos (js2-node-abs-pos node))
12060 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12061 (setq lp (car parens)
12062 rp (cdr parens)))
12063 (when (and lp (> start lp))
12064 (if (and rp (<= start rp))
12065 ;; Between parens, check if there's a child node we can jump.
12066 (when (setq child (js2-node-closest-child node (point) lp t))
12067 (setq pos (js2-node-abs-pos child)))
12068 ;; Before both parens.
12069 (setq pos lp)))
12070 (let ((state (parse-partial-sexp start pos)))
12071 (goto-char (if (not (zerop (car state)))
12072 ;; Stumble at the unbalanced paren if < 0, or
12073 ;; jump a bit further if > 0.
12074 (scan-sexps start -1)
12075 pos))))
12076 (unless pos (goto-char (point-min)))))
12077 (t
12078 ;; forward-sexp
12079 (dotimes (_ arg)
12080 (js2-forward-sws)
12081 (when (setq node (js2-node-at-point (point) t))
12082 (setq pos (js2-node-abs-pos node))
12083 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12084 (setq lp (car parens)
12085 rp (cdr parens)))
12086 (or
12087 (when (and rp (<= start rp))
12088 (if (> start lp)
12089 (when (setq child (js2-node-closest-child node (point) rp))
12090 (setq pos (js2-node-abs-end child)))
12091 (setq pos (1+ rp))))
12092 ;; No parens or child nodes, looks for the end of the current node.
12093 (cl-incf pos (js2-node-len
12094 (if (js2-expr-stmt-node-p (js2-node-parent node))
12095 ;; Stop after the semicolon.
12096 (js2-node-parent node)
12097 node))))
12098 (let ((state (save-excursion (parse-partial-sexp start pos))))
12099 (goto-char (if (not (zerop (car state)))
12100 (scan-sexps start 1)
12101 pos))))
12102 (unless pos (goto-char (point-max)))))))))
12103
12104 (defun js2-mode-forward-sexp-parens (node abs-pos)
12105 "Return a cons cell with positions of main parens in NODE."
12106 (cond
12107 ((or (js2-array-node-p node)
12108 (js2-object-node-p node)
12109 (js2-comp-node-p node)
12110 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12111 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12112 ((js2-paren-expr-node-p node)
12113 (let ((lp (js2-node-lp node))
12114 (rp (js2-node-rp node)))
12115 (cons (when lp (+ abs-pos lp))
12116 (when rp (+ abs-pos rp)))))))
12117
12118 (defun js2-node-closest-child (parent point limit &optional before)
12119 (let* ((parent-pos (js2-node-abs-pos parent))
12120 (rpoint (- point parent-pos))
12121 (rlimit (- limit parent-pos))
12122 (min (min rpoint rlimit))
12123 (max (max rpoint rlimit))
12124 found)
12125 (catch 'done
12126 (js2-visit-ast
12127 parent
12128 (lambda (node _end-p)
12129 (if (eq node parent)
12130 t
12131 (let ((pos (js2-node-pos node)) ;; Both relative values.
12132 (end (+ (js2-node-pos node) (js2-node-len node))))
12133 (when (and (>= pos min) (<= end max)
12134 (if before (< pos rpoint) (> end rpoint)))
12135 (setq found node))
12136 (when (> end rpoint)
12137 (throw 'done nil)))
12138 nil))))
12139 found))
12140
12141 (defun js2-errors ()
12142 "Return a list of errors found."
12143 (and js2-mode-ast
12144 (js2-ast-root-errors js2-mode-ast)))
12145
12146 (defun js2-warnings ()
12147 "Return a list of warnings found."
12148 (and js2-mode-ast
12149 (js2-ast-root-warnings js2-mode-ast)))
12150
12151 (defun js2-have-errors-p ()
12152 "Return non-nil if any parse errors or warnings were found."
12153 (or (js2-errors) (js2-warnings)))
12154
12155 (defun js2-errors-and-warnings ()
12156 "Return a copy of the concatenated errors and warnings lists.
12157 They are appended: first the errors, then the warnings.
12158 Entries are of the form (MSG BEG END)."
12159 (when js2-mode-ast
12160 (append (js2-ast-root-errors js2-mode-ast)
12161 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12162
12163 (defun js2-next-error (&optional arg reset)
12164 "Move to next parse error.
12165 Typically invoked via \\[next-error].
12166 ARG is the number of errors, forward or backward, to move.
12167 RESET means start over from the beginning."
12168 (interactive "p")
12169 (if (not (or (js2-errors) (js2-warnings)))
12170 (message "No errors")
12171 (when reset
12172 (goto-char (point-min)))
12173 (let* ((errs (js2-errors-and-warnings))
12174 (continue t)
12175 (start (point))
12176 (count (or arg 1))
12177 (backward (cl-minusp count))
12178 (sorter (if backward '> '<))
12179 (stopper (if backward '< '>))
12180 (count (abs count))
12181 all-errs err)
12182 ;; Sort by start position.
12183 (setq errs (sort errs (lambda (e1 e2)
12184 (funcall sorter (cl-second e1) (cl-second e2))))
12185 all-errs errs)
12186 ;; Find nth error with pos > start.
12187 (while (and errs continue)
12188 (when (funcall stopper (cl-cadar errs) start)
12189 (setq err (car errs))
12190 (if (zerop (cl-decf count))
12191 (setq continue nil)))
12192 (setq errs (cdr errs)))
12193 ;; Clear for `js2-echo-error'.
12194 (message nil)
12195 (if err
12196 (goto-char (cl-second err))
12197 ;; Wrap around to first error.
12198 (goto-char (cl-second (car all-errs)))
12199 ;; If we were already on it, echo msg again.
12200 (if (= (point) start)
12201 (js2-echo-error (point) (point)))))))
12202
12203 (defun js2-down-mouse-3 ()
12204 "Make right-click move the point to the click location.
12205 This makes right-click context menu operations a bit more intuitive.
12206 The point will not move if the region is active, however, to avoid
12207 destroying the region selection."
12208 (interactive)
12209 (when (and js2-move-point-on-right-click
12210 (not mark-active))
12211 (let ((e last-input-event))
12212 (ignore-errors
12213 (goto-char (cl-cadadr e))))))
12214
12215 (defun js2-mode-create-imenu-index ()
12216 "Return an alist for `imenu--index-alist'."
12217 ;; This is built up in `js2-parse-record-imenu' during parsing.
12218 (when js2-mode-ast
12219 ;; if we have an ast but no recorder, they're requesting a rescan
12220 (unless js2-imenu-recorder
12221 (js2-reparse 'force))
12222 (prog1
12223 (js2-build-imenu-index)
12224 (setq js2-imenu-recorder nil
12225 js2-imenu-function-map nil))))
12226
12227 (defun js2-mode-find-tag ()
12228 "Replacement for `find-tag-default'.
12229 `find-tag-default' returns a ridiculous answer inside comments."
12230 (let (beg end)
12231 (js2-with-underscore-as-word-syntax
12232 (save-excursion
12233 (if (and (not (looking-at "[[:alnum:]_$]"))
12234 (looking-back "[[:alnum:]_$]"))
12235 (setq beg (progn (forward-word -1) (point))
12236 end (progn (forward-word 1) (point)))
12237 (setq beg (progn (forward-word 1) (point))
12238 end (progn (forward-word -1) (point))))
12239 (replace-regexp-in-string
12240 "[\"']" ""
12241 (buffer-substring-no-properties beg end))))))
12242
12243 (defun js2-mode-forward-sibling ()
12244 "Move to the end of the sibling following point in parent.
12245 Returns non-nil if successful, or nil if there was no following sibling."
12246 (let* ((node (js2-node-at-point))
12247 (parent (js2-mode-find-enclosing-fn node))
12248 sib)
12249 (when (setq sib (js2-node-find-child-after (point) parent))
12250 (goto-char (+ (js2-node-abs-pos sib)
12251 (js2-node-len sib))))))
12252
12253 (defun js2-mode-backward-sibling ()
12254 "Move to the beginning of the sibling node preceding point in parent.
12255 Parent is defined as the enclosing script or function."
12256 (let* ((node (js2-node-at-point))
12257 (parent (js2-mode-find-enclosing-fn node))
12258 sib)
12259 (when (setq sib (js2-node-find-child-before (point) parent))
12260 (goto-char (js2-node-abs-pos sib)))))
12261
12262 (defun js2-beginning-of-defun (&optional arg)
12263 "Go to line on which current function starts, and return t on success.
12264 If we're not in a function or already at the beginning of one, go
12265 to beginning of previous script-level element.
12266 With ARG N, do that N times. If N is negative, move forward."
12267 (setq arg (or arg 1))
12268 (if (cl-plusp arg)
12269 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12270 (when (cond
12271 ((js2-function-node-p parent)
12272 (goto-char (js2-node-abs-pos parent)))
12273 (t
12274 (js2-mode-backward-sibling)))
12275 (if (> arg 1)
12276 (js2-beginning-of-defun (1- arg))
12277 t)))
12278 (when (js2-end-of-defun)
12279 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12280
12281 (defun js2-end-of-defun ()
12282 "Go to the char after the last position of the current function
12283 or script-level element."
12284 (let* ((node (js2-node-at-point))
12285 (parent (or (and (js2-function-node-p node) node)
12286 (js2-node-parent-script-or-fn node)))
12287 script)
12288 (unless (js2-function-node-p parent)
12289 ;; Use current script-level node, or, if none, the next one.
12290 (setq script (or parent node)
12291 parent (js2-node-find-child-before (point) script))
12292 (when (or (null parent)
12293 (>= (point) (+ (js2-node-abs-pos parent)
12294 (js2-node-len parent))))
12295 (setq parent (js2-node-find-child-after (point) script))))
12296 (when parent
12297 (goto-char (+ (js2-node-abs-pos parent)
12298 (js2-node-len parent))))))
12299
12300 (defun js2-mark-defun (&optional allow-extend)
12301 "Put mark at end of this function, point at beginning.
12302 The function marked is the one that contains point.
12303
12304 Interactively, if this command is repeated,
12305 or (in Transient Mark mode) if the mark is active,
12306 it marks the next defun after the ones already marked."
12307 (interactive "p")
12308 (let (extended)
12309 (when (and allow-extend
12310 (or (and (eq last-command this-command) (mark t))
12311 (and transient-mark-mode mark-active)))
12312 (let ((sib (save-excursion
12313 (goto-char (mark))
12314 (if (js2-mode-forward-sibling)
12315 (point)))))
12316 (if sib
12317 (progn
12318 (set-mark sib)
12319 (setq extended t))
12320 ;; no more siblings - try extending to enclosing node
12321 (goto-char (mark t)))))
12322 (when (not extended)
12323 (let ((node (js2-node-at-point (point) t)) ; skip comments
12324 ast fn stmt parent beg end)
12325 (when (js2-ast-root-p node)
12326 (setq ast node
12327 node (or (js2-node-find-child-after (point) node)
12328 (js2-node-find-child-before (point) node))))
12329 ;; only mark whole buffer if we can't find any children
12330 (if (null node)
12331 (setq node ast))
12332 (if (js2-function-node-p node)
12333 (setq parent node)
12334 (setq fn (js2-mode-find-enclosing-fn node)
12335 stmt (if (or (null fn)
12336 (js2-ast-root-p fn))
12337 (js2-mode-find-first-stmt node))
12338 parent (or stmt fn)))
12339 (setq beg (js2-node-abs-pos parent)
12340 end (+ beg (js2-node-len parent)))
12341 (push-mark beg)
12342 (goto-char end)
12343 (exchange-point-and-mark)))))
12344
12345 (defun js2-narrow-to-defun ()
12346 "Narrow to the function enclosing point."
12347 (interactive)
12348 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12349 (fn (if (js2-script-node-p node)
12350 node
12351 (js2-mode-find-enclosing-fn node)))
12352 (beg (js2-node-abs-pos fn)))
12353 (unless (js2-ast-root-p fn)
12354 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12355
12356 (provide 'js2-mode)
12357
12358 ;;; js2-mode.el ends here