]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Comment the new token types
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2014 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20141118
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
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 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 (defvar js2-harmony-externs
207 (mapcar 'symbol-name
208 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
209 "ES6 externs. If `js2-include-browser-externs' is enabled and
210 `js2-language-version' is sufficiently high, these will be included.")
211
212 ;;; Variables
213
214 (defun js2-mark-safe-local (name pred)
215 "Make the variable NAME buffer-local and mark it as safe file-local
216 variable with predicate PRED."
217 (make-variable-buffer-local name)
218 (put name 'safe-local-variable pred))
219
220 (defcustom js2-highlight-level 2
221 "Amount of syntax highlighting to perform.
222 0 or a negative value means none.
223 1 adds basic syntax highlighting.
224 2 adds highlighting of some Ecma built-in properties.
225 3 adds highlighting of many Ecma built-in functions."
226 :group 'js2-mode
227 :type '(choice (const :tag "None" 0)
228 (const :tag "Basic" 1)
229 (const :tag "Include Properties" 2)
230 (const :tag "Include Functions" 3)))
231
232 (defvar js2-mode-dev-mode-p nil
233 "Non-nil if running in development mode. Normally nil.")
234
235 (defgroup js2-mode nil
236 "An improved JavaScript mode."
237 :group 'languages)
238
239 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
240 (numberp c-basic-offset))
241 c-basic-offset
242 4)
243 "Number of spaces to indent nested statements.
244 Similar to `c-basic-offset'."
245 :group 'js2-mode
246 :type 'integer)
247 (js2-mark-safe-local 'js2-basic-offset 'integerp)
248
249 (defcustom js2-bounce-indent-p nil
250 "Non-nil to have indent-line function choose among alternatives.
251 If nil, the indent-line function will indent to a predetermined column
252 based on heuristic guessing. If non-nil, then if the current line is
253 already indented to that predetermined column, indenting will choose
254 another likely column and indent to that spot. Repeated invocation of
255 the indent-line function will cycle among the computed alternatives.
256 See the function `js2-bounce-indent' for details. When it is non-nil,
257 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
258 :type 'boolean
259 :group 'js2-mode)
260
261 (defcustom js2-pretty-multiline-declarations t
262 "Non-nil to line up multiline declarations vertically:
263
264 var a = 10,
265 b = 20,
266 c = 30;
267
268 If the value is not `all', and the first assigned value in
269 declaration is a function/array/object literal spanning several
270 lines, it won't be indented additionally:
271
272 var o = { var bar = 2,
273 foo: 3 vs. o = {
274 }, foo: 3
275 bar = 2; };"
276 :group 'js2-mode
277 :type 'symbol)
278 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
279
280 (defcustom js2-indent-switch-body nil
281 "When nil, case labels are indented on the same level as the
282 containing switch statement. Otherwise, all lines inside
283 switch statement body are indented one additional level."
284 :type 'boolean
285 :group 'js2-mode)
286 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
287
288 (defcustom js2-idle-timer-delay 0.2
289 "Delay in secs before re-parsing after user makes changes.
290 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
291 :type 'number
292 :group 'js2-mode)
293 (make-variable-buffer-local 'js2-idle-timer-delay)
294
295 (defcustom js2-dynamic-idle-timer-adjust 0
296 "Positive to adjust `js2-idle-timer-delay' based on file size.
297 The idea is that for short files, parsing is faster so we can be
298 more responsive to user edits without interfering with editing.
299 The buffer length in characters (typically bytes) is divided by
300 this value and used to multiply `js2-idle-timer-delay' for the
301 buffer. For example, a 21k file and 10k adjust yields 21k/10k
302 == 2, so js2-idle-timer-delay is multiplied by 2.
303 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
304 `js2-idle-timer-delay' is not dependent on the file size."
305 :type 'number
306 :group 'js2-mode)
307
308 (defcustom js2-concat-multiline-strings t
309 "When non-nil, `js2-line-break' in mid-string will make it a
310 string concatenation. When `eol', the '+' will be inserted at the
311 end of the line, otherwise, at the beginning of the next line."
312 :type '(choice (const t) (const eol) (const nil))
313 :group 'js2-mode)
314
315 (defcustom js2-mode-show-parse-errors t
316 "True to highlight parse errors."
317 :type 'boolean
318 :group 'js2-mode)
319
320 (defcustom js2-mode-show-strict-warnings t
321 "Non-nil to emit Ecma strict-mode warnings.
322 Some of the warnings can be individually disabled by other flags,
323 even if this flag is non-nil."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-trailing-comma-warning t
328 "Non-nil to warn about trailing commas in array literals.
329 Ecma-262-5.1 allows them, but older versions of IE raise an error."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-var-redeclaration-warning t
366 "Non-nil to warn about redeclaring variables in a script or function."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-strict-var-hides-function-arg-warning t
371 "Non-nil to warn about a var decl hiding a function argument."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-skip-preprocessor-directives nil
376 "Non-nil to treat lines beginning with # as comments.
377 Useful for viewing Mozilla JavaScript source code."
378 :type 'boolean
379 :group 'js2-mode)
380
381 (defcustom js2-language-version 200
382 "Configures what JavaScript language version to recognize.
383 Currently versions 150, 160, 170, 180 and 200 are supported,
384 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
385 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
386 yield, and Array comprehensions, and 1.8 adds function closures."
387 :type 'integer
388 :group 'js2-mode)
389
390 (defcustom js2-allow-keywords-as-property-names t
391 "If non-nil, you can use JavaScript keywords as object property names.
392 Examples:
393
394 var foo = {int: 5, while: 6, continue: 7};
395 foo.return = 8;
396
397 Ecma-262 5.1 allows this syntax, but some engines still don't."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-instanceof-has-side-effects nil
402 "If non-nil, treats the instanceof operator as having side effects.
403 This is useful for xulrunner apps."
404 :type 'boolean
405 :group 'js2-mode)
406
407 (defcustom js2-move-point-on-right-click t
408 "Non-nil to move insertion point when you right-click.
409 This makes right-click context menu behavior a bit more intuitive,
410 since menu operations generally apply to the point. The exception
411 is if there is a region selection, in which case the point does -not-
412 move, so cut/copy/paste can work properly.
413
414 Note that IntelliJ moves the point, and Eclipse leaves it alone,
415 so this behavior is customizable."
416 :group 'js2-mode
417 :type 'boolean)
418
419 (defcustom js2-allow-rhino-new-expr-initializer t
420 "Non-nil to support a Rhino's experimental syntactic construct.
421
422 Rhino supports the ability to follow a `new' expression with an object
423 literal, which is used to set additional properties on the new object
424 after calling its constructor. Syntax:
425
426 new <expr> [ ( arglist ) ] [initializer]
427
428 Hence, this expression:
429
430 new Object {a: 1, b: 2}
431
432 results in an Object with properties a=1 and b=2. This syntax is
433 apparently not configurable in Rhino - it's currently always enabled,
434 as of Rhino version 1.7R2."
435 :type 'boolean
436 :group 'js2-mode)
437
438 (defcustom js2-allow-member-expr-as-function-name nil
439 "Non-nil to support experimental Rhino syntax for function names.
440
441 Rhino supports an experimental syntax configured via the Rhino Context
442 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
443
444 function <member-expr> ( [ arg-list ] ) { <body> }
445
446 Where member-expr is a non-parenthesized 'member expression', which
447 is anything at the grammar level of a new-expression or lower, meaning
448 any expression that does not involve infix or unary operators.
449
450 When <member-expr> is not a simple identifier, then it is syntactic
451 sugar for assigning the anonymous function to the <member-expr>. Hence,
452 this code:
453
454 function a.b().c[2] (x, y) { ... }
455
456 is rewritten as:
457
458 a.b().c[2] = function(x, y) {...}
459
460 which doesn't seem particularly useful, but Rhino permits it."
461 :type 'boolean
462 :group 'js2-mode)
463
464 ;; scanner variables
465
466 (defmacro js2-deflocal (name value &optional comment)
467 "Define a buffer-local variable NAME with VALUE and COMMENT."
468 `(progn
469 (defvar ,name ,value ,comment)
470 (make-variable-buffer-local ',name)))
471
472 (defvar js2-EOF_CHAR -1
473 "Represents end of stream. Distinct from js2-EOF token type.")
474
475 ;; I originally used symbols to represent tokens, but Rhino uses
476 ;; ints and then sets various flag bits in them, so ints it is.
477 ;; The upshot is that we need a `js2-' prefix in front of each name.
478 (defvar js2-ERROR -1)
479 (defvar js2-EOF 0)
480 (defvar js2-EOL 1)
481 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
482 (defvar js2-LEAVEWITH 3)
483 (defvar js2-RETURN 4)
484 (defvar js2-GOTO 5)
485 (defvar js2-IFEQ 6)
486 (defvar js2-IFNE 7)
487 (defvar js2-SETNAME 8)
488 (defvar js2-BITOR 9)
489 (defvar js2-BITXOR 10)
490 (defvar js2-BITAND 11)
491 (defvar js2-EQ 12)
492 (defvar js2-NE 13)
493 (defvar js2-LT 14)
494 (defvar js2-LE 15)
495 (defvar js2-GT 16)
496 (defvar js2-GE 17)
497 (defvar js2-LSH 18)
498 (defvar js2-RSH 19)
499 (defvar js2-URSH 20)
500 (defvar js2-ADD 21) ; infix plus
501 (defvar js2-SUB 22) ; infix minus
502 (defvar js2-MUL 23)
503 (defvar js2-DIV 24)
504 (defvar js2-MOD 25)
505 (defvar js2-NOT 26)
506 (defvar js2-BITNOT 27)
507 (defvar js2-POS 28) ; unary plus
508 (defvar js2-NEG 29) ; unary minus
509 (defvar js2-NEW 30)
510 (defvar js2-DELPROP 31)
511 (defvar js2-TYPEOF 32)
512 (defvar js2-GETPROP 33)
513 (defvar js2-GETPROPNOWARN 34)
514 (defvar js2-SETPROP 35)
515 (defvar js2-GETELEM 36)
516 (defvar js2-SETELEM 37)
517 (defvar js2-CALL 38)
518 (defvar js2-NAME 39) ; an identifier
519 (defvar js2-NUMBER 40)
520 (defvar js2-STRING 41)
521 (defvar js2-NULL 42)
522 (defvar js2-THIS 43)
523 (defvar js2-FALSE 44)
524 (defvar js2-TRUE 45)
525 (defvar js2-SHEQ 46) ; shallow equality (===)
526 (defvar js2-SHNE 47) ; shallow inequality (!==)
527 (defvar js2-REGEXP 48)
528 (defvar js2-BINDNAME 49)
529 (defvar js2-THROW 50)
530 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
531 (defvar js2-IN 52)
532 (defvar js2-INSTANCEOF 53)
533 (defvar js2-LOCAL_LOAD 54)
534 (defvar js2-GETVAR 55)
535 (defvar js2-SETVAR 56)
536 (defvar js2-CATCH_SCOPE 57)
537 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
538 (defvar js2-ENUM_INIT_VALUES 59)
539 (defvar js2-ENUM_INIT_ARRAY 60)
540 (defvar js2-ENUM_NEXT 61)
541 (defvar js2-ENUM_ID 62)
542 (defvar js2-THISFN 63)
543 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
544 (defvar js2-ARRAYLIT 65) ; array literal
545 (defvar js2-OBJECTLIT 66) ; object literal
546 (defvar js2-GET_REF 67) ; *reference
547 (defvar js2-SET_REF 68) ; *reference = something
548 (defvar js2-DEL_REF 69) ; delete reference
549 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
550 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
551 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
552
553 ;; XML support
554 (defvar js2-DEFAULTNAMESPACE 73)
555 (defvar js2-ESCXMLATTR 74)
556 (defvar js2-ESCXMLTEXT 75)
557 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
558 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
559 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
560 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
561
562 (defvar js2-first-bytecode js2-ENTERWITH)
563 (defvar js2-last-bytecode js2-REF_NS_NAME)
564
565 (defvar js2-TRY 80)
566 (defvar js2-SEMI 81) ; semicolon
567 (defvar js2-LB 82) ; left and right brackets
568 (defvar js2-RB 83)
569 (defvar js2-LC 84) ; left and right curly-braces
570 (defvar js2-RC 85)
571 (defvar js2-LP 86) ; left and right parens
572 (defvar js2-RP 87)
573 (defvar js2-COMMA 88) ; comma operator
574
575 (defvar js2-ASSIGN 89) ; simple assignment (=)
576 (defvar js2-ASSIGN_BITOR 90) ; |=
577 (defvar js2-ASSIGN_BITXOR 91) ; ^=
578 (defvar js2-ASSIGN_BITAND 92) ; &=
579 (defvar js2-ASSIGN_LSH 93) ; <<=
580 (defvar js2-ASSIGN_RSH 94) ; >>=
581 (defvar js2-ASSIGN_URSH 95) ; >>>=
582 (defvar js2-ASSIGN_ADD 96) ; +=
583 (defvar js2-ASSIGN_SUB 97) ; -=
584 (defvar js2-ASSIGN_MUL 98) ; *=
585 (defvar js2-ASSIGN_DIV 99) ; /=
586 (defvar js2-ASSIGN_MOD 100) ; %=
587
588 (defvar js2-first-assign js2-ASSIGN)
589 (defvar js2-last-assign js2-ASSIGN_MOD)
590
591 (defvar js2-HOOK 101) ; conditional (?:)
592 (defvar js2-COLON 102)
593 (defvar js2-OR 103) ; logical or (||)
594 (defvar js2-AND 104) ; logical and (&&)
595 (defvar js2-INC 105) ; increment/decrement (++ --)
596 (defvar js2-DEC 106)
597 (defvar js2-DOT 107) ; member operator (.)
598 (defvar js2-FUNCTION 108) ; function keyword
599 (defvar js2-EXPORT 109) ; export keyword
600 (defvar js2-IMPORT 110) ; import keyword
601 (defvar js2-IF 111) ; if keyword
602 (defvar js2-ELSE 112) ; else keyword
603 (defvar js2-SWITCH 113) ; switch keyword
604 (defvar js2-CASE 114) ; case keyword
605 (defvar js2-DEFAULT 115) ; default keyword
606 (defvar js2-WHILE 116) ; while keyword
607 (defvar js2-DO 117) ; do keyword
608 (defvar js2-FOR 118) ; for keyword
609 (defvar js2-BREAK 119) ; break keyword
610 (defvar js2-CONTINUE 120) ; continue keyword
611 (defvar js2-VAR 121) ; var keyword
612 (defvar js2-WITH 122) ; with keyword
613 (defvar js2-CATCH 123) ; catch keyword
614 (defvar js2-FINALLY 124) ; finally keyword
615 (defvar js2-VOID 125) ; void keyword
616 (defvar js2-RESERVED 126) ; reserved keywords
617
618 (defvar js2-EMPTY 127)
619
620 ;; Types used for the parse tree - never returned by scanner.
621
622 (defvar js2-BLOCK 128) ; statement block
623 (defvar js2-LABEL 129) ; label
624 (defvar js2-TARGET 130)
625 (defvar js2-LOOP 131)
626 (defvar js2-EXPR_VOID 132) ; expression statement in functions
627 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
628 (defvar js2-JSR 134)
629 (defvar js2-SCRIPT 135) ; top-level node for entire script
630 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
631 (defvar js2-USE_STACK 137)
632 (defvar js2-SETPROP_OP 138) ; x.y op= something
633 (defvar js2-SETELEM_OP 139) ; x[y] op= something
634 (defvar js2-LOCAL_BLOCK 140)
635 (defvar js2-SET_REF_OP 141) ; *reference op= something
636
637 ;; For XML support:
638 (defvar js2-DOTDOT 142) ; member operator (..)
639 (defvar js2-COLONCOLON 143) ; namespace::name
640 (defvar js2-XML 144) ; XML type
641 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
642 (defvar js2-XMLATTR 146) ; @
643 (defvar js2-XMLEND 147)
644
645 ;; Optimizer-only tokens
646 (defvar js2-TO_OBJECT 148)
647 (defvar js2-TO_DOUBLE 149)
648
649 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
650 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
651 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
652 (defvar js2-CONST 153)
653 (defvar js2-SETCONST 154)
654 (defvar js2-SETCONSTVAR 155)
655 (defvar js2-ARRAYCOMP 156)
656 (defvar js2-LETEXPR 157)
657 (defvar js2-WITHEXPR 158)
658 (defvar js2-DEBUGGER 159)
659
660 (defvar js2-COMMENT 160)
661 (defvar js2-TRIPLEDOT 161) ; for rest parameter
662 (defvar js2-ARROW 162) ; function arrow (=>)
663 (defvar js2-CLASS 163)
664 (defvar js2-EXTENDS 164)
665 (defvar js2-STATIC 165)
666 (defvar js2-SUPER 166)
667 (defvar js2-TEMPLATE_HEAD 167) ; part of template literal before substitution
668 (defvar js2-NO_SUBS_TEMPLATE 168) ; template literal without substitutions
669
670 (defconst js2-num-tokens (1+ js2-NO_SUBS_TEMPLATE))
671
672 (defconst js2-debug-print-trees nil)
673
674 ;; Rhino accepts any string or stream as input. Emacs character
675 ;; processing works best in buffers, so we'll assume the input is a
676 ;; buffer. JavaScript strings can be copied into temp buffers before
677 ;; scanning them.
678
679 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
680 ;; They're the Emacs equivalent of instance variables, more or less.
681
682 (js2-deflocal js2-ts-dirty-line nil
683 "Token stream buffer-local variable.
684 Indicates stuff other than whitespace since start of line.")
685
686 (js2-deflocal js2-ts-hit-eof nil
687 "Token stream buffer-local variable.")
688
689 ;; FIXME: Unused.
690 (js2-deflocal js2-ts-line-start 0
691 "Token stream buffer-local variable.")
692
693 (js2-deflocal js2-ts-lineno 1
694 "Token stream buffer-local variable.")
695
696 ;; FIXME: Unused.
697 (js2-deflocal js2-ts-line-end-char -1
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
701 "Token stream buffer-local variable.
702 Current scan position.")
703
704 ;; FIXME: Unused.
705 (js2-deflocal js2-ts-is-xml-attribute nil
706 "Token stream buffer-local variable.")
707
708 (js2-deflocal js2-ts-xml-is-tag-content nil
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-xml-open-tags-count 0
712 "Token stream buffer-local variable.")
713
714 (js2-deflocal js2-ts-string-buffer nil
715 "Token stream buffer-local variable.
716 List of chars built up while scanning various tokens.")
717
718 (defstruct (js2-token
719 (:constructor nil)
720 (:constructor make-js2-token (beg)))
721 "Value returned from the token stream."
722 (type js2-EOF)
723 (beg 1)
724 (end -1)
725 (string "")
726 number
727 regexp-flags
728 comment-type
729 follows-eol-p)
730
731 (defstruct (js2-ts-state
732 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
733 (cursor js2-ts-cursor)
734 (tokens (copy-sequence js2-ti-tokens))
735 (tokens-cursor js2-ti-tokens-cursor)
736 (lookahead js2-ti-lookahead))))
737 lineno
738 cursor
739 tokens
740 tokens-cursor
741 lookahead)
742
743 ;;; Parser variables
744
745 (js2-deflocal js2-parsed-errors nil
746 "List of errors produced during scanning/parsing.")
747
748 (js2-deflocal js2-parsed-warnings nil
749 "List of warnings produced during scanning/parsing.")
750
751 (js2-deflocal js2-recover-from-parse-errors t
752 "Non-nil to continue parsing after a syntax error.
753
754 In recovery mode, the AST will be built in full, and any error
755 nodes will be flagged with appropriate error information. If
756 this flag is nil, a syntax error will result in an error being
757 signaled.
758
759 The variable is automatically buffer-local, because different
760 modes that use the parser will need different settings.")
761
762 (js2-deflocal js2-parse-hook nil
763 "List of callbacks for receiving parsing progress.")
764
765 (defvar js2-parse-finished-hook nil
766 "List of callbacks to notify when parsing finishes.
767 Not called if parsing was interrupted.")
768
769 (js2-deflocal js2-is-eval-code nil
770 "True if we're evaluating code in a string.
771 If non-nil, the tokenizer will record the token text, and the AST nodes
772 will record their source text. Off by default for IDE modes, since the
773 text is available in the buffer.")
774
775 (defvar js2-parse-ide-mode t
776 "Non-nil if the parser is being used for `js2-mode'.
777 If non-nil, the parser will set text properties for fontification
778 and the syntax table. The value should be nil when using the
779 parser as a frontend to an interpreter or byte compiler.")
780
781 ;;; Parser instance variables (buffer-local vars for js2-parse)
782
783 (defconst js2-ti-after-eol (lsh 1 16)
784 "Flag: first token of the source line.")
785
786 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
787
788 (js2-deflocal js2-compiler-generate-debug-info t)
789 (js2-deflocal js2-compiler-use-dynamic-scope nil)
790 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
791 (js2-deflocal js2-compiler-xml-available t)
792 (js2-deflocal js2-compiler-optimization-level 0)
793 (js2-deflocal js2-compiler-generating-source t)
794 (js2-deflocal js2-compiler-strict-mode nil)
795 (js2-deflocal js2-compiler-report-warning-as-error nil)
796 (js2-deflocal js2-compiler-generate-observer-count nil)
797 (js2-deflocal js2-compiler-activation-names nil)
798
799 ;; SKIP: sourceURI
800
801 ;; There's a compileFunction method in Context.java - may need it.
802 (js2-deflocal js2-called-by-compile-function nil
803 "True if `js2-parse' was called by `js2-compile-function'.
804 Will only be used when we finish implementing the interpreter.")
805
806 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
807
808 ;; SKIP: node factory - we're going to just call functions directly,
809 ;; and eventually go to a unified AST format.
810
811 (js2-deflocal js2-nesting-of-function 0)
812
813 (js2-deflocal js2-recorded-identifiers nil
814 "Tracks identifiers found during parsing.")
815
816 (js2-deflocal js2-is-in-destructuring nil
817 "True while parsing destructuring expression.")
818
819 (defcustom js2-global-externs nil
820 "A list of any extern names you'd like to consider always declared.
821 This list is global and is used by all `js2-mode' files.
822 You can create buffer-local externs list using `js2-additional-externs'.
823
824 There is also a buffer-local variable `js2-default-externs',
825 which is initialized by default to include the Ecma-262 externs
826 and the standard browser externs. The three lists are all
827 checked during highlighting."
828 :type 'list
829 :group 'js2-mode)
830
831 (js2-deflocal js2-default-externs nil
832 "Default external declarations.
833
834 These are currently only used for highlighting undeclared variables,
835 which only worries about top-level (unqualified) references.
836 As js2-mode's processing improves, we will flesh out this list.
837
838 The initial value is set to `js2-ecma-262-externs', unless some
839 of the `js2-include-?-externs' variables are set to t, in which
840 case the browser, Rhino and/or Node.js externs are also included.
841
842 See `js2-additional-externs' for more information.")
843
844 (defcustom js2-include-browser-externs t
845 "Non-nil to include browser externs in the master externs list.
846 If you work on JavaScript files that are not intended for browsers,
847 such as Mozilla Rhino server-side JavaScript, set this to nil.
848 See `js2-additional-externs' for more information about externs."
849 :type 'boolean
850 :group 'js2-mode)
851
852 (defcustom js2-include-rhino-externs nil
853 "Non-nil to include Mozilla Rhino externs in the master externs list.
854 See `js2-additional-externs' for more information about externs."
855 :type 'boolean
856 :group 'js2-mode)
857
858 (defcustom js2-include-node-externs nil
859 "Non-nil to include Node.js externs in the master externs list.
860 See `js2-additional-externs' for more information about externs."
861 :type 'boolean
862 :group 'js2-mode)
863
864 (js2-deflocal js2-additional-externs nil
865 "A buffer-local list of additional external declarations.
866 It is used to decide whether variables are considered undeclared
867 for purposes of highlighting.
868
869 Each entry is a Lisp string. The string should be the fully qualified
870 name of an external entity. All externs should be added to this list,
871 so that as js2-mode's processing improves it can take advantage of them.
872
873 You may want to declare your externs in three ways.
874 First, you can add externs that are valid for all your JavaScript files.
875 You should probably do this by adding them to `js2-global-externs', which
876 is a global list used for all js2-mode files.
877
878 Next, you can add a function to `js2-init-hook' that adds additional
879 externs appropriate for the specific file, perhaps based on its path.
880 These should go in `js2-additional-externs', which is buffer-local.
881
882 Third, you can use JSLint's global declaration, as long as
883 `js2-include-jslint-globals' is non-nil, which see.
884
885 Finally, you can add a function to `js2-post-parse-callbacks',
886 which is called after parsing completes, and `js2-mode-ast' is bound to
887 the root of the parse tree. At this stage you can set up an AST
888 node visitor using `js2-visit-ast' and examine the parse tree
889 for specific import patterns that may imply the existence of
890 other externs, possibly tied to your build system. These should also
891 be added to `js2-additional-externs'.
892
893 Your post-parse callback may of course also use the simpler and
894 faster (but perhaps less robust) approach of simply scanning the
895 buffer text for your imports, using regular expressions.")
896
897 ;; SKIP: decompiler
898 ;; SKIP: encoded-source
899
900 ;;; The following variables are per-function and should be saved/restored
901 ;;; during function parsing...
902
903 (js2-deflocal js2-current-script-or-fn nil)
904 (js2-deflocal js2-current-scope nil)
905 (js2-deflocal js2-nesting-of-with 0)
906 (js2-deflocal js2-label-set nil
907 "An alist mapping label names to nodes.")
908
909 (js2-deflocal js2-loop-set nil)
910 (js2-deflocal js2-loop-and-switch-set nil)
911 (js2-deflocal js2-has-return-value nil)
912 (js2-deflocal js2-end-flags 0)
913
914 ;;; ...end of per function variables
915
916 ;; These flags enumerate the possible ways a statement/function can
917 ;; terminate. These flags are used by endCheck() and by the Parser to
918 ;; detect inconsistent return usage.
919 ;;
920 ;; END_UNREACHED is reserved for code paths that are assumed to always be
921 ;; able to execute (example: throw, continue)
922 ;;
923 ;; END_DROPS_OFF indicates if the statement can transfer control to the
924 ;; next one. Statement such as return dont. A compound statement may have
925 ;; some branch that drops off control to the next statement.
926 ;;
927 ;; END_RETURNS indicates that the statement can return (without arguments)
928 ;; END_RETURNS_VALUE indicates that the statement can return a value.
929 ;;
930 ;; A compound statement such as
931 ;; if (condition) {
932 ;; return value;
933 ;; }
934 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
935
936 (defconst js2-end-unreached #x0)
937 (defconst js2-end-drops-off #x1)
938 (defconst js2-end-returns #x2)
939 (defconst js2-end-returns-value #x4)
940
941 ;; Rhino awkwardly passes a statementLabel parameter to the
942 ;; statementHelper() function, the main statement parser, which
943 ;; is then used by quite a few of the sub-parsers. We just make
944 ;; it a buffer-local variable and make sure it's cleaned up properly.
945 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
946
947 ;; Similarly, Rhino passes an inForInit boolean through about half
948 ;; the expression parsers. We use a dynamically-scoped variable,
949 ;; which makes it easier to funcall the parsers individually without
950 ;; worrying about whether they take the parameter or not.
951 (js2-deflocal js2-in-for-init nil)
952 (js2-deflocal js2-temp-name-counter 0)
953 (js2-deflocal js2-parse-stmt-count 0)
954
955 (defsubst js2-get-next-temp-name ()
956 (format "$%d" (incf js2-temp-name-counter)))
957
958 (defvar js2-parse-interruptable-p t
959 "Set this to nil to force parse to continue until finished.
960 This will mostly be useful for interpreters.")
961
962 (defvar js2-statements-per-pause 50
963 "Pause after this many statements to check for user input.
964 If user input is pending, stop the parse and discard the tree.
965 This makes for a smoother user experience for large files.
966 You may have to wait a second or two before the highlighting
967 and error-reporting appear, but you can always type ahead if
968 you wish. This appears to be more or less how Eclipse, IntelliJ
969 and other editors work.")
970
971 (js2-deflocal js2-record-comments t
972 "Instructs the scanner to record comments in `js2-scanned-comments'.")
973
974 (js2-deflocal js2-scanned-comments nil
975 "List of all comments from the current parse.")
976
977 (defcustom js2-mode-indent-inhibit-undo nil
978 "Non-nil to disable collection of Undo information when indenting lines.
979 Some users have requested this behavior. It's nil by default because
980 other Emacs modes don't work this way."
981 :type 'boolean
982 :group 'js2-mode)
983
984 (defcustom js2-mode-indent-ignore-first-tab nil
985 "If non-nil, ignore first TAB keypress if we look indented properly.
986 It's fairly common for users to navigate to an already-indented line
987 and press TAB for reassurance that it's been indented. For this class
988 of users, we want the first TAB press on a line to be ignored if the
989 line is already indented to one of the precomputed alternatives.
990
991 This behavior is only partly implemented. If you TAB-indent a line,
992 navigate to another line, and then navigate back, it fails to clear
993 the last-indented variable, so it thinks you've already hit TAB once,
994 and performs the indent. A full solution would involve getting on the
995 point-motion hooks for the entire buffer. If we come across another
996 use cases that requires watching point motion, I'll consider doing it.
997
998 If you set this variable to nil, then the TAB key will always change
999 the indentation of the current line, if more than one alternative
1000 indentation spot exists."
1001 :type 'boolean
1002 :group 'js2-mode)
1003
1004 (defvar js2-indent-hook nil
1005 "A hook for user-defined indentation rules.
1006
1007 Functions on this hook should expect two arguments: (LIST INDEX)
1008 The LIST argument is the list of computed indentation points for
1009 the current line. INDEX is the list index of the indentation point
1010 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1011 indent function is not going to change the current line indentation.
1012
1013 If a hook function on this list returns a non-nil value, then
1014 `js2-bounce-indent' assumes the hook function has performed its own
1015 indentation, and will do nothing. If all hook functions on the list
1016 return nil, then `js2-bounce-indent' will use its computed indentation
1017 and reindent the line.
1018
1019 When hook functions on this hook list are called, the variable
1020 `js2-mode-ast' may or may not be set, depending on whether the
1021 parse tree is available. If the variable is nil, you can pass a
1022 callback to `js2-mode-wait-for-parse', and your callback will be
1023 called after the new parse tree is built. This can take some time
1024 in large files.")
1025
1026 (defface js2-warning
1027 `((((class color) (background light))
1028 (:underline "orange"))
1029 (((class color) (background dark))
1030 (:underline "orange"))
1031 (t (:underline t)))
1032 "Face for JavaScript warnings."
1033 :group 'js2-mode)
1034
1035 (defface js2-error
1036 `((((class color) (background light))
1037 (:foreground "red"))
1038 (((class color) (background dark))
1039 (:foreground "red"))
1040 (t (:foreground "red")))
1041 "Face for JavaScript errors."
1042 :group 'js2-mode)
1043
1044 (defface js2-jsdoc-tag
1045 '((t :foreground "SlateGray"))
1046 "Face used to highlight @whatever tags in jsdoc comments."
1047 :group 'js2-mode)
1048
1049 (defface js2-jsdoc-type
1050 '((t :foreground "SteelBlue"))
1051 "Face used to highlight {FooBar} types in jsdoc comments."
1052 :group 'js2-mode)
1053
1054 (defface js2-jsdoc-value
1055 '((t :foreground "PeachPuff3"))
1056 "Face used to highlight tag values in jsdoc comments."
1057 :group 'js2-mode)
1058
1059 (defface js2-function-param
1060 '((t :foreground "SeaGreen"))
1061 "Face used to highlight function parameters in javascript."
1062 :group 'js2-mode)
1063
1064 (defface js2-function-call
1065 '((t :inherit default))
1066 "Face used to highlight function name in calls."
1067 :group 'js2-mode)
1068
1069 (defface js2-instance-member
1070 '((t :foreground "DarkOrchid"))
1071 "Face used to highlight instance variables in javascript.
1072 Not currently used."
1073 :group 'js2-mode)
1074
1075 (defface js2-private-member
1076 '((t :foreground "PeachPuff3"))
1077 "Face used to highlight calls to private methods in javascript.
1078 Not currently used."
1079 :group 'js2-mode)
1080
1081 (defface js2-private-function-call
1082 '((t :foreground "goldenrod"))
1083 "Face used to highlight calls to private functions in javascript.
1084 Not currently used."
1085 :group 'js2-mode)
1086
1087 (defface js2-jsdoc-html-tag-name
1088 '((((class color) (min-colors 88) (background light))
1089 (:foreground "rosybrown"))
1090 (((class color) (min-colors 8) (background dark))
1091 (:foreground "yellow"))
1092 (((class color) (min-colors 8) (background light))
1093 (:foreground "magenta")))
1094 "Face used to highlight jsdoc html tag names"
1095 :group 'js2-mode)
1096
1097 (defface js2-jsdoc-html-tag-delimiter
1098 '((((class color) (min-colors 88) (background light))
1099 (:foreground "dark khaki"))
1100 (((class color) (min-colors 8) (background dark))
1101 (:foreground "green"))
1102 (((class color) (min-colors 8) (background light))
1103 (:foreground "green")))
1104 "Face used to highlight brackets in jsdoc html tags."
1105 :group 'js2-mode)
1106
1107 (defface js2-external-variable
1108 '((t :foreground "orange"))
1109 "Face used to highlight undeclared variable identifiers.")
1110
1111 (defcustom js2-init-hook nil
1112 "List of functions to be called after `js2-mode' or
1113 `js2-minor-mode' has initialized all variables, before parsing
1114 the buffer for the first time."
1115 :type 'hook
1116 :group 'js2-mode
1117 :version "20130608")
1118
1119 (defcustom js2-post-parse-callbacks nil
1120 "List of callback functions invoked after parsing finishes.
1121 Currently, the main use for this function is to add synthetic
1122 declarations to `js2-recorded-identifiers', which see."
1123 :type 'hook
1124 :group 'js2-mode)
1125
1126 (defcustom js2-build-imenu-callbacks nil
1127 "List of functions called during Imenu index generation.
1128 It's a good place to add additional entries to it, using
1129 `js2-record-imenu-entry'."
1130 :type 'hook
1131 :group 'js2-mode)
1132
1133 (defcustom js2-highlight-external-variables t
1134 "Non-nil to highlight undeclared variable identifiers.
1135 An undeclared variable is any variable not declared with var or let
1136 in the current scope or any lexically enclosing scope. If you use
1137 such a variable, then you are either expecting it to originate from
1138 another file, or you've got a potential bug."
1139 :type 'boolean
1140 :group 'js2-mode)
1141
1142 (defcustom js2-include-jslint-globals t
1143 "Non-nil to include the identifiers from JSLint global
1144 declaration (see http://www.jslint.com/lint.html#global) in the
1145 buffer-local externs list. See `js2-additional-externs' for more
1146 information."
1147 :type 'boolean
1148 :group 'js2-mode)
1149
1150 (defvar js2-mode-map
1151 (let ((map (make-sparse-keymap)))
1152 (define-key map [mouse-1] #'js2-mode-show-node)
1153 (define-key map (kbd "M-j") #'js2-line-break)
1154 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1155 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1156 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1157 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1158 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1159 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1160 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1161 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1162 (when js2-bounce-indent-p
1163 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1164
1165 (define-key map [menu-bar javascript]
1166 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1167
1168 (define-key map [menu-bar javascript customize-js2-mode]
1169 '(menu-item "Customize js2-mode" js2-mode-customize
1170 :help "Customize the behavior of this mode"))
1171
1172 (define-key map [menu-bar javascript js2-force-refresh]
1173 '(menu-item "Force buffer refresh" js2-mode-reset
1174 :help "Re-parse the buffer from scratch"))
1175
1176 (define-key map [menu-bar javascript separator-2]
1177 '("--"))
1178
1179 (define-key map [menu-bar javascript next-error]
1180 '(menu-item "Next warning or error" next-error
1181 :enabled (and js2-mode-ast
1182 (or (js2-ast-root-errors js2-mode-ast)
1183 (js2-ast-root-warnings js2-mode-ast)))
1184 :help "Move to next warning or error"))
1185
1186 (define-key map [menu-bar javascript display-errors]
1187 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1188 :visible (not js2-mode-show-parse-errors)
1189 :help "Turn on display of warnings and errors"))
1190
1191 (define-key map [menu-bar javascript hide-errors]
1192 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1193 :visible js2-mode-show-parse-errors
1194 :help "Turn off display of warnings and errors"))
1195
1196 (define-key map [menu-bar javascript separator-1]
1197 '("--"))
1198
1199 (define-key map [menu-bar javascript js2-toggle-function]
1200 '(menu-item "Show/collapse element" js2-mode-toggle-element
1201 :help "Hide or show function body or comment"))
1202
1203 (define-key map [menu-bar javascript show-comments]
1204 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1205 :visible js2-mode-comments-hidden
1206 :help "Expand all hidden block comments"))
1207
1208 (define-key map [menu-bar javascript hide-comments]
1209 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1210 :visible (not js2-mode-comments-hidden)
1211 :help "Show block comments as /*...*/"))
1212
1213 (define-key map [menu-bar javascript show-all-functions]
1214 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1215 :visible js2-mode-functions-hidden
1216 :help "Expand all hidden function bodies"))
1217
1218 (define-key map [menu-bar javascript hide-all-functions]
1219 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1220 :visible (not js2-mode-functions-hidden)
1221 :help "Show {...} for all top-level function bodies"))
1222
1223 map)
1224 "Keymap used in `js2-mode' buffers.")
1225
1226 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1227
1228 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1229 "Matches a //-comment line. Must be first non-whitespace on line.
1230 First match-group is the leading whitespace.")
1231
1232 (defvar js2-mode-hook nil)
1233
1234 (js2-deflocal js2-mode-ast nil "Private variable.")
1235 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1236 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1237 (js2-deflocal js2-mode-parsing nil "Private variable.")
1238 (js2-deflocal js2-mode-node-overlay nil)
1239
1240 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1241 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1242
1243 (js2-deflocal js2-mode-fontifications nil "Private variable")
1244 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1245 (js2-deflocal js2-imenu-recorder nil "Private variable")
1246 (js2-deflocal js2-imenu-function-map nil "Private variable")
1247
1248 (defvar js2-paragraph-start
1249 "\\(@[[:alpha:]]+\\>\\|$\\)")
1250
1251 ;; Note that we also set a 'c-in-sws text property in html comments,
1252 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1253 (defvar js2-syntactic-ws-start
1254 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1255
1256 (defvar js2-syntactic-ws-end
1257 "\\s \\|[\n\r/]\\|\\s!")
1258
1259 (defvar js2-syntactic-eol
1260 (concat "\\s *\\(/\\*[^*\n\r]*"
1261 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1262 "\\*+/\\s *\\)*"
1263 "\\(//\\|/\\*[^*\n\r]*"
1264 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1265 "\\|\\\\$\\|$\\)")
1266 "Copied from `java-mode'. Needed for some cc-engine functions.")
1267
1268 (defvar js2-comment-prefix-regexp
1269 "//+\\|\\**")
1270
1271 (defvar js2-comment-start-skip
1272 "\\(//+\\|/\\*+\\)\\s *")
1273
1274 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1275 "Non-nil to emit status messages during parsing.")
1276
1277 (defvar js2-mode-functions-hidden nil "Private variable.")
1278 (defvar js2-mode-comments-hidden nil "Private variable.")
1279
1280 (defvar js2-mode-syntax-table
1281 (let ((table (make-syntax-table)))
1282 (c-populate-syntax-table table)
1283 table)
1284 "Syntax table used in `js2-mode' buffers.")
1285
1286 (defvar js2-mode-abbrev-table nil
1287 "Abbrev table in use in `js2-mode' buffers.")
1288 (define-abbrev-table 'js2-mode-abbrev-table ())
1289
1290 (defvar js2-mode-pending-parse-callbacks nil
1291 "List of functions waiting to be notified that parse is finished.")
1292
1293 (defvar js2-mode-last-indented-line -1)
1294
1295 ;;; Localizable error and warning messages
1296
1297 ;; Messages are copied from Rhino's Messages.properties.
1298 ;; Many of the Java-specific messages have been elided.
1299 ;; Add any js2-specific ones at the end, so we can keep
1300 ;; this file synced with changes to Rhino's.
1301
1302 (defvar js2-message-table
1303 (make-hash-table :test 'equal :size 250)
1304 "Contains localized messages for `js2-mode'.")
1305
1306 ;; TODO(stevey): construct this table at compile-time.
1307 (defmacro js2-msg (key &rest strings)
1308 `(puthash ,key (concat ,@strings)
1309 js2-message-table))
1310
1311 (defun js2-get-msg (msg-key)
1312 "Look up a localized message.
1313 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1314 the correct number of ARGS must be provided."
1315 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1316 (args (if (listp msg-key) (cdr msg-key)))
1317 (msg (gethash key js2-message-table)))
1318 (if msg
1319 (apply #'format msg args)
1320 key))) ; default to showing the key
1321
1322 (js2-msg "msg.dup.parms"
1323 "Duplicate parameter name '%s'.")
1324
1325 (js2-msg "msg.too.big.jump"
1326 "Program too complex: jump offset too big.")
1327
1328 (js2-msg "msg.too.big.index"
1329 "Program too complex: internal index exceeds 64K limit.")
1330
1331 (js2-msg "msg.while.compiling.fn"
1332 "Encountered code generation error while compiling function '%s': %s")
1333
1334 (js2-msg "msg.while.compiling.script"
1335 "Encountered code generation error while compiling script: %s")
1336
1337 ;; Context
1338 (js2-msg "msg.ctor.not.found"
1339 "Constructor for '%s' not found.")
1340
1341 (js2-msg "msg.not.ctor"
1342 "'%s' is not a constructor.")
1343
1344 ;; FunctionObject
1345 (js2-msg "msg.varargs.ctor"
1346 "Method or constructor '%s' must be static "
1347 "with the signature (Context cx, Object[] args, "
1348 "Function ctorObj, boolean inNewExpr) "
1349 "to define a variable arguments constructor.")
1350
1351 (js2-msg "msg.varargs.fun"
1352 "Method '%s' must be static with the signature "
1353 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1354 "to define a variable arguments function.")
1355
1356 (js2-msg "msg.incompat.call"
1357 "Method '%s' called on incompatible object.")
1358
1359 (js2-msg "msg.bad.parms"
1360 "Unsupported parameter type '%s' in method '%s'.")
1361
1362 (js2-msg "msg.bad.method.return"
1363 "Unsupported return type '%s' in method '%s'.")
1364
1365 (js2-msg "msg.bad.ctor.return"
1366 "Construction of objects of type '%s' is not supported.")
1367
1368 (js2-msg "msg.no.overload"
1369 "Method '%s' occurs multiple times in class '%s'.")
1370
1371 (js2-msg "msg.method.not.found"
1372 "Method '%s' not found in '%s'.")
1373
1374 ;; IRFactory
1375
1376 (js2-msg "msg.bad.for.in.lhs"
1377 "Invalid left-hand side of for..in loop.")
1378
1379 (js2-msg "msg.mult.index"
1380 "Only one variable allowed in for..in loop.")
1381
1382 (js2-msg "msg.bad.for.in.destruct"
1383 "Left hand side of for..in loop must be an array of "
1384 "length 2 to accept key/value pair.")
1385
1386 (js2-msg "msg.cant.convert"
1387 "Can't convert to type '%s'.")
1388
1389 (js2-msg "msg.bad.assign.left"
1390 "Invalid assignment left-hand side.")
1391
1392 (js2-msg "msg.bad.decr"
1393 "Invalid decerement operand.")
1394
1395 (js2-msg "msg.bad.incr"
1396 "Invalid increment operand.")
1397
1398 (js2-msg "msg.bad.yield"
1399 "yield must be in a function.")
1400
1401 (js2-msg "msg.yield.parenthesized"
1402 "yield expression must be parenthesized.")
1403
1404 ;; NativeGlobal
1405 (js2-msg "msg.cant.call.indirect"
1406 "Function '%s' must be called directly, and not by way of a "
1407 "function of another name.")
1408
1409 (js2-msg "msg.eval.nonstring"
1410 "Calling eval() with anything other than a primitive "
1411 "string value will simply return the value. "
1412 "Is this what you intended?")
1413
1414 (js2-msg "msg.eval.nonstring.strict"
1415 "Calling eval() with anything other than a primitive "
1416 "string value is not allowed in strict mode.")
1417
1418 (js2-msg "msg.bad.destruct.op"
1419 "Invalid destructuring assignment operator")
1420
1421 ;; NativeCall
1422 (js2-msg "msg.only.from.new"
1423 "'%s' may only be invoked from a `new' expression.")
1424
1425 (js2-msg "msg.deprec.ctor"
1426 "The '%s' constructor is deprecated.")
1427
1428 ;; NativeFunction
1429 (js2-msg "msg.no.function.ref.found"
1430 "no source found to decompile function reference %s")
1431
1432 (js2-msg "msg.arg.isnt.array"
1433 "second argument to Function.prototype.apply must be an array")
1434
1435 ;; NativeGlobal
1436 (js2-msg "msg.bad.esc.mask"
1437 "invalid string escape mask")
1438
1439 ;; NativeRegExp
1440 (js2-msg "msg.bad.quant"
1441 "Invalid quantifier %s")
1442
1443 (js2-msg "msg.overlarge.backref"
1444 "Overly large back reference %s")
1445
1446 (js2-msg "msg.overlarge.min"
1447 "Overly large minimum %s")
1448
1449 (js2-msg "msg.overlarge.max"
1450 "Overly large maximum %s")
1451
1452 (js2-msg "msg.zero.quant"
1453 "Zero quantifier %s")
1454
1455 (js2-msg "msg.max.lt.min"
1456 "Maximum %s less than minimum")
1457
1458 (js2-msg "msg.unterm.quant"
1459 "Unterminated quantifier %s")
1460
1461 (js2-msg "msg.unterm.paren"
1462 "Unterminated parenthetical %s")
1463
1464 (js2-msg "msg.unterm.class"
1465 "Unterminated character class %s")
1466
1467 (js2-msg "msg.bad.range"
1468 "Invalid range in character class.")
1469
1470 (js2-msg "msg.trail.backslash"
1471 "Trailing \\ in regular expression.")
1472
1473 (js2-msg "msg.re.unmatched.right.paren"
1474 "unmatched ) in regular expression.")
1475
1476 (js2-msg "msg.no.regexp"
1477 "Regular expressions are not available.")
1478
1479 (js2-msg "msg.bad.backref"
1480 "back-reference exceeds number of capturing parentheses.")
1481
1482 (js2-msg "msg.bad.regexp.compile"
1483 "Only one argument may be specified if the first "
1484 "argument to RegExp.prototype.compile is a RegExp object.")
1485
1486 ;; Parser
1487 (js2-msg "msg.got.syntax.errors"
1488 "Compilation produced %s syntax errors.")
1489
1490 (js2-msg "msg.var.redecl"
1491 "TypeError: redeclaration of var %s.")
1492
1493 (js2-msg "msg.const.redecl"
1494 "TypeError: redeclaration of const %s.")
1495
1496 (js2-msg "msg.let.redecl"
1497 "TypeError: redeclaration of variable %s.")
1498
1499 (js2-msg "msg.parm.redecl"
1500 "TypeError: redeclaration of formal parameter %s.")
1501
1502 (js2-msg "msg.fn.redecl"
1503 "TypeError: redeclaration of function %s.")
1504
1505 (js2-msg "msg.let.decl.not.in.block"
1506 "SyntaxError: let declaration not directly within block")
1507
1508 ;; NodeTransformer
1509 (js2-msg "msg.dup.label"
1510 "duplicated label")
1511
1512 (js2-msg "msg.undef.label"
1513 "undefined label")
1514
1515 (js2-msg "msg.bad.break"
1516 "unlabelled break must be inside loop or switch")
1517
1518 (js2-msg "msg.continue.outside"
1519 "continue must be inside loop")
1520
1521 (js2-msg "msg.continue.nonloop"
1522 "continue can only use labels of iteration statements")
1523
1524 (js2-msg "msg.bad.throw.eol"
1525 "Line terminator is not allowed between the throw "
1526 "keyword and throw expression.")
1527
1528 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1529 "function statement requires a name")
1530
1531 (js2-msg "msg.no.paren.parms"
1532 "missing ( before function parameters.")
1533
1534 (js2-msg "msg.no.parm"
1535 "missing formal parameter")
1536
1537 (js2-msg "msg.no.paren.after.parms"
1538 "missing ) after formal parameters")
1539
1540 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1541 "parameter without default follows parameter with default")
1542
1543 (js2-msg "msg.param.after.rest" ; added by js2-mode
1544 "parameter after rest parameter")
1545
1546 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1547 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1548
1549 (js2-msg "msg.no.brace.body"
1550 "missing '{' before function body")
1551
1552 (js2-msg "msg.no.brace.after.body"
1553 "missing } after function body")
1554
1555 (js2-msg "msg.no.paren.cond"
1556 "missing ( before condition")
1557
1558 (js2-msg "msg.no.paren.after.cond"
1559 "missing ) after condition")
1560
1561 (js2-msg "msg.no.semi.stmt"
1562 "missing ; before statement")
1563
1564 (js2-msg "msg.missing.semi"
1565 "missing ; after statement")
1566
1567 (js2-msg "msg.no.name.after.dot"
1568 "missing name after . operator")
1569
1570 (js2-msg "msg.no.name.after.coloncolon"
1571 "missing name after :: operator")
1572
1573 (js2-msg "msg.no.name.after.dotdot"
1574 "missing name after .. operator")
1575
1576 (js2-msg "msg.no.name.after.xmlAttr"
1577 "missing name after .@")
1578
1579 (js2-msg "msg.no.bracket.index"
1580 "missing ] in index expression")
1581
1582 (js2-msg "msg.no.paren.switch"
1583 "missing ( before switch expression")
1584
1585 (js2-msg "msg.no.paren.after.switch"
1586 "missing ) after switch expression")
1587
1588 (js2-msg "msg.no.brace.switch"
1589 "missing '{' before switch body")
1590
1591 (js2-msg "msg.bad.switch"
1592 "invalid switch statement")
1593
1594 (js2-msg "msg.no.colon.case"
1595 "missing : after case expression")
1596
1597 (js2-msg "msg.double.switch.default"
1598 "double default label in the switch statement")
1599
1600 (js2-msg "msg.no.while.do"
1601 "missing while after do-loop body")
1602
1603 (js2-msg "msg.no.paren.for"
1604 "missing ( after for")
1605
1606 (js2-msg "msg.no.semi.for"
1607 "missing ; after for-loop initializer")
1608
1609 (js2-msg "msg.no.semi.for.cond"
1610 "missing ; after for-loop condition")
1611
1612 (js2-msg "msg.in.after.for.name"
1613 "missing in or of after for")
1614
1615 (js2-msg "msg.no.paren.for.ctrl"
1616 "missing ) after for-loop control")
1617
1618 (js2-msg "msg.no.paren.with"
1619 "missing ( before with-statement object")
1620
1621 (js2-msg "msg.no.paren.after.with"
1622 "missing ) after with-statement object")
1623
1624 (js2-msg "msg.no.paren.after.let"
1625 "missing ( after let")
1626
1627 (js2-msg "msg.no.paren.let"
1628 "missing ) after variable list")
1629
1630 (js2-msg "msg.no.curly.let"
1631 "missing } after let statement")
1632
1633 (js2-msg "msg.bad.return"
1634 "invalid return")
1635
1636 (js2-msg "msg.no.brace.block"
1637 "missing } in compound statement")
1638
1639 (js2-msg "msg.bad.label"
1640 "invalid label")
1641
1642 (js2-msg "msg.bad.var"
1643 "missing variable name")
1644
1645 (js2-msg "msg.bad.var.init"
1646 "invalid variable initialization")
1647
1648 (js2-msg "msg.no.colon.cond"
1649 "missing : in conditional expression")
1650
1651 (js2-msg "msg.no.paren.arg"
1652 "missing ) after argument list")
1653
1654 (js2-msg "msg.no.bracket.arg"
1655 "missing ] after element list")
1656
1657 (js2-msg "msg.bad.prop"
1658 "invalid property id")
1659
1660 (js2-msg "msg.no.colon.prop"
1661 "missing : after property id")
1662
1663 (js2-msg "msg.no.brace.prop"
1664 "missing } after property list")
1665
1666 (js2-msg "msg.no.paren"
1667 "missing ) in parenthetical")
1668
1669 (js2-msg "msg.reserved.id"
1670 "'%s' is a reserved identifier")
1671
1672 (js2-msg "msg.no.paren.catch"
1673 "missing ( before catch-block condition")
1674
1675 (js2-msg "msg.bad.catchcond"
1676 "invalid catch block condition")
1677
1678 (js2-msg "msg.catch.unreachable"
1679 "any catch clauses following an unqualified catch are unreachable")
1680
1681 (js2-msg "msg.no.brace.try"
1682 "missing '{' before try block")
1683
1684 (js2-msg "msg.no.brace.catchblock"
1685 "missing '{' before catch-block body")
1686
1687 (js2-msg "msg.try.no.catchfinally"
1688 "'try' without 'catch' or 'finally'")
1689
1690 (js2-msg "msg.no.return.value"
1691 "function %s does not always return a value")
1692
1693 (js2-msg "msg.anon.no.return.value"
1694 "anonymous function does not always return a value")
1695
1696 (js2-msg "msg.return.inconsistent"
1697 "return statement is inconsistent with previous usage")
1698
1699 (js2-msg "msg.generator.returns"
1700 "TypeError: legacy generator function '%s' returns a value")
1701
1702 (js2-msg "msg.anon.generator.returns"
1703 "TypeError: anonymous legacy generator function returns a value")
1704
1705 (js2-msg "msg.syntax"
1706 "syntax error")
1707
1708 (js2-msg "msg.unexpected.eof"
1709 "Unexpected end of file")
1710
1711 (js2-msg "msg.XML.bad.form"
1712 "illegally formed XML syntax")
1713
1714 (js2-msg "msg.XML.not.available"
1715 "XML runtime not available")
1716
1717 (js2-msg "msg.too.deep.parser.recursion"
1718 "Too deep recursion while parsing")
1719
1720 (js2-msg "msg.no.side.effects"
1721 "Code has no side effects")
1722
1723 (js2-msg "msg.extra.trailing.comma"
1724 "Trailing comma is not supported in some browsers")
1725
1726 (js2-msg "msg.array.trailing.comma"
1727 "Trailing comma yields different behavior across browsers")
1728
1729 (js2-msg "msg.equal.as.assign"
1730 (concat "Test for equality (==) mistyped as assignment (=)?"
1731 " (parenthesize to suppress warning)"))
1732
1733 (js2-msg "msg.var.hides.arg"
1734 "Variable %s hides argument")
1735
1736 (js2-msg "msg.destruct.assign.no.init"
1737 "Missing = in destructuring declaration")
1738
1739 ;; ScriptRuntime
1740 (js2-msg "msg.no.properties"
1741 "%s has no properties.")
1742
1743 (js2-msg "msg.invalid.iterator"
1744 "Invalid iterator value")
1745
1746 (js2-msg "msg.iterator.primitive"
1747 "__iterator__ returned a primitive value")
1748
1749 (js2-msg "msg.assn.create.strict"
1750 "Assignment to undeclared variable %s")
1751
1752 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1753 "Undeclared variable or function '%s'")
1754
1755 (js2-msg "msg.ref.undefined.prop"
1756 "Reference to undefined property '%s'")
1757
1758 (js2-msg "msg.prop.not.found"
1759 "Property %s not found.")
1760
1761 (js2-msg "msg.invalid.type"
1762 "Invalid JavaScript value of type %s")
1763
1764 (js2-msg "msg.primitive.expected"
1765 "Primitive type expected (had %s instead)")
1766
1767 (js2-msg "msg.namespace.expected"
1768 "Namespace object expected to left of :: (found %s instead)")
1769
1770 (js2-msg "msg.null.to.object"
1771 "Cannot convert null to an object.")
1772
1773 (js2-msg "msg.undef.to.object"
1774 "Cannot convert undefined to an object.")
1775
1776 (js2-msg "msg.cyclic.value"
1777 "Cyclic %s value not allowed.")
1778
1779 (js2-msg "msg.is.not.defined"
1780 "'%s' is not defined.")
1781
1782 (js2-msg "msg.undef.prop.read"
1783 "Cannot read property '%s' from %s")
1784
1785 (js2-msg "msg.undef.prop.write"
1786 "Cannot set property '%s' of %s to '%s'")
1787
1788 (js2-msg "msg.undef.prop.delete"
1789 "Cannot delete property '%s' of %s")
1790
1791 (js2-msg "msg.undef.method.call"
1792 "Cannot call method '%s' of %s")
1793
1794 (js2-msg "msg.undef.with"
1795 "Cannot apply 'with' to %s")
1796
1797 (js2-msg "msg.isnt.function"
1798 "%s is not a function, it is %s.")
1799
1800 (js2-msg "msg.isnt.function.in"
1801 "Cannot call property %s in object %s. "
1802 "It is not a function, it is '%s'.")
1803
1804 (js2-msg "msg.function.not.found"
1805 "Cannot find function %s.")
1806
1807 (js2-msg "msg.function.not.found.in"
1808 "Cannot find function %s in object %s.")
1809
1810 (js2-msg "msg.isnt.xml.object"
1811 "%s is not an xml object.")
1812
1813 (js2-msg "msg.no.ref.to.get"
1814 "%s is not a reference to read reference value.")
1815
1816 (js2-msg "msg.no.ref.to.set"
1817 "%s is not a reference to set reference value to %s.")
1818
1819 (js2-msg "msg.no.ref.from.function"
1820 "Function %s can not be used as the left-hand "
1821 "side of assignment or as an operand of ++ or -- operator.")
1822
1823 (js2-msg "msg.bad.default.value"
1824 "Object's getDefaultValue() method returned an object.")
1825
1826 (js2-msg "msg.instanceof.not.object"
1827 "Can't use instanceof on a non-object.")
1828
1829 (js2-msg "msg.instanceof.bad.prototype"
1830 "'prototype' property of %s is not an object.")
1831
1832 (js2-msg "msg.bad.radix"
1833 "illegal radix %s.")
1834
1835 ;; ScriptableObject
1836 (js2-msg "msg.default.value"
1837 "Cannot find default value for object.")
1838
1839 (js2-msg "msg.zero.arg.ctor"
1840 "Cannot load class '%s' which has no zero-parameter constructor.")
1841
1842 (js2-msg "msg.ctor.multiple.parms"
1843 "Can't define constructor or class %s since more than "
1844 "one constructor has multiple parameters.")
1845
1846 (js2-msg "msg.extend.scriptable"
1847 "%s must extend ScriptableObject in order to define property %s.")
1848
1849 (js2-msg "msg.bad.getter.parms"
1850 "In order to define a property, getter %s must have zero "
1851 "parameters or a single ScriptableObject parameter.")
1852
1853 (js2-msg "msg.obj.getter.parms"
1854 "Expected static or delegated getter %s to take "
1855 "a ScriptableObject parameter.")
1856
1857 (js2-msg "msg.getter.static"
1858 "Getter and setter must both be static or neither be static.")
1859
1860 (js2-msg "msg.setter.return"
1861 "Setter must have void return type: %s")
1862
1863 (js2-msg "msg.setter2.parms"
1864 "Two-parameter setter must take a ScriptableObject as "
1865 "its first parameter.")
1866
1867 (js2-msg "msg.setter1.parms"
1868 "Expected single parameter setter for %s")
1869
1870 (js2-msg "msg.setter2.expected"
1871 "Expected static or delegated setter %s to take two parameters.")
1872
1873 (js2-msg "msg.setter.parms"
1874 "Expected either one or two parameters for setter.")
1875
1876 (js2-msg "msg.setter.bad.type"
1877 "Unsupported parameter type '%s' in setter '%s'.")
1878
1879 (js2-msg "msg.add.sealed"
1880 "Cannot add a property to a sealed object: %s.")
1881
1882 (js2-msg "msg.remove.sealed"
1883 "Cannot remove a property from a sealed object: %s.")
1884
1885 (js2-msg "msg.modify.sealed"
1886 "Cannot modify a property of a sealed object: %s.")
1887
1888 (js2-msg "msg.modify.readonly"
1889 "Cannot modify readonly property: %s.")
1890
1891 ;; TokenStream
1892 (js2-msg "msg.missing.exponent"
1893 "missing exponent")
1894
1895 (js2-msg "msg.caught.nfe"
1896 "number format error")
1897
1898 (js2-msg "msg.unterminated.string.lit"
1899 "unterminated string literal")
1900
1901 (js2-msg "msg.unterminated.comment"
1902 "unterminated comment")
1903
1904 (js2-msg "msg.unterminated.re.lit"
1905 "unterminated regular expression literal")
1906
1907 (js2-msg "msg.invalid.re.flag"
1908 "invalid flag after regular expression")
1909
1910 (js2-msg "msg.no.re.input.for"
1911 "no input for %s")
1912
1913 (js2-msg "msg.illegal.character"
1914 "illegal character")
1915
1916 (js2-msg "msg.invalid.escape"
1917 "invalid Unicode escape sequence")
1918
1919 (js2-msg "msg.bad.namespace"
1920 "not a valid default namespace statement. "
1921 "Syntax is: default xml namespace = EXPRESSION;")
1922
1923 ;; TokensStream warnings
1924 (js2-msg "msg.bad.octal.literal"
1925 "illegal octal literal digit %s; "
1926 "interpreting it as a decimal digit")
1927
1928 (js2-msg "msg.missing.hex.digits"
1929 "missing hexadecimal digits after '0x'")
1930
1931 (js2-msg "msg.missing.binary.digits"
1932 "missing binary digits after '0b'")
1933
1934 (js2-msg "msg.missing.octal.digits"
1935 "missing octal digits after '0o'")
1936
1937 (js2-msg "msg.script.is.not.constructor"
1938 "Script objects are not constructors.")
1939
1940 ;; Arrays
1941 (js2-msg "msg.arraylength.bad"
1942 "Inappropriate array length.")
1943
1944 ;; Arrays
1945 (js2-msg "msg.arraylength.too.big"
1946 "Array length %s exceeds supported capacity limit.")
1947
1948 ;; URI
1949 (js2-msg "msg.bad.uri"
1950 "Malformed URI sequence.")
1951
1952 ;; Number
1953 (js2-msg "msg.bad.precision"
1954 "Precision %s out of range.")
1955
1956 ;; NativeGenerator
1957 (js2-msg "msg.send.newborn"
1958 "Attempt to send value to newborn generator")
1959
1960 (js2-msg "msg.already.exec.gen"
1961 "Already executing generator")
1962
1963 (js2-msg "msg.StopIteration.invalid"
1964 "StopIteration may not be changed to an arbitrary object.")
1965
1966 ;; Interpreter
1967 (js2-msg "msg.yield.closing"
1968 "Yield from closing generator")
1969
1970 ;; Classes
1971 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1972 "class statement requires a name")
1973
1974 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1975 "unexpected ',' between class properties")
1976
1977 (js2-msg "msg.unexpected.static" ; added by js2-mode
1978 "unexpected 'static'")
1979
1980 (js2-msg "msg.missing.extends" ; added by js2-mode
1981 "name is required after extends")
1982
1983 (js2-msg "msg.no.brace.class" ; added by js2-mode
1984 "missing '{' before class body")
1985
1986 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1987 "missing ']' after computed property expression")
1988
1989 ;;; Tokens Buffer
1990
1991 (defconst js2-ti-max-lookahead 2)
1992 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1993
1994 ;; Have to call `js2-init-scanner' to initialize the values.
1995 (js2-deflocal js2-ti-tokens nil)
1996 (js2-deflocal js2-ti-tokens-cursor nil)
1997 (js2-deflocal js2-ti-lookahead nil)
1998
1999 (defun js2-new-token (offset)
2000 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2001 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2002 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2003 token))
2004
2005 (defsubst js2-current-token ()
2006 (aref js2-ti-tokens js2-ti-tokens-cursor))
2007
2008 (defsubst js2-current-token-string ()
2009 (js2-token-string (js2-current-token)))
2010
2011 (defsubst js2-current-token-type ()
2012 (js2-token-type (js2-current-token)))
2013
2014 (defsubst js2-current-token-beg ()
2015 (js2-token-beg (js2-current-token)))
2016
2017 (defsubst js2-current-token-end ()
2018 (js2-token-end (js2-current-token)))
2019
2020 (defun js2-current-token-len ()
2021 (let ((token (js2-current-token)))
2022 (- (js2-token-end token)
2023 (js2-token-beg token))))
2024
2025 (defun js2-ts-seek (state)
2026 (setq js2-ts-lineno (js2-ts-state-lineno state)
2027 js2-ts-cursor (js2-ts-state-cursor state)
2028 js2-ti-tokens (js2-ts-state-tokens state)
2029 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2030 js2-ti-lookahead (js2-ts-state-lookahead state)))
2031
2032 ;;; Utilities
2033
2034 (defun js2-delete-if (predicate list)
2035 "Remove all items satisfying PREDICATE in LIST."
2036 (loop for item in list
2037 if (not (funcall predicate item))
2038 collect item))
2039
2040 (defun js2-position (element list)
2041 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2042 Returns nil if element is not found in the list."
2043 (let ((count 0)
2044 found)
2045 (while (and list (not found))
2046 (if (eq element (car list))
2047 (setq found t)
2048 (setq count (1+ count)
2049 list (cdr list))))
2050 (if found count)))
2051
2052 (defun js2-find-if (predicate list)
2053 "Find first item satisfying PREDICATE in LIST."
2054 (let (result)
2055 (while (and list (not result))
2056 (if (funcall predicate (car list))
2057 (setq result (car list)))
2058 (setq list (cdr list)))
2059 result))
2060
2061 (defmacro js2-time (form)
2062 "Evaluate FORM, discard result, and return elapsed time in sec."
2063 (declare (debug t))
2064 (let ((beg (make-symbol "--js2-time-beg--"))
2065 (delta (make-symbol "--js2-time-end--")))
2066 `(let ((,beg (current-time))
2067 ,delta)
2068 ,form
2069 (/ (truncate (* (- (float-time (current-time))
2070 (float-time ,beg))
2071 10000))
2072 10000.0))))
2073
2074 (defsubst js2-same-line (pos)
2075 "Return t if POS is on the same line as current point."
2076 (and (>= pos (point-at-bol))
2077 (<= pos (point-at-eol))))
2078
2079 (defun js2-code-bug ()
2080 "Signal an error when we encounter an unexpected code path."
2081 (error "failed assertion"))
2082
2083 (defsubst js2-record-text-property (beg end prop value)
2084 "Record a text property to set when parsing finishes."
2085 (push (list beg end prop value) js2-mode-deferred-properties))
2086
2087 ;; I'd like to associate errors with nodes, but for now the
2088 ;; easiest thing to do is get the context info from the last token.
2089 (defun js2-record-parse-error (msg &optional arg pos len)
2090 (push (list (list msg arg)
2091 (or pos (js2-current-token-beg))
2092 (or len (js2-current-token-len)))
2093 js2-parsed-errors))
2094
2095 (defun js2-report-error (msg &optional msg-arg pos len)
2096 "Signal a syntax error or record a parse error."
2097 (if js2-recover-from-parse-errors
2098 (js2-record-parse-error msg msg-arg pos len)
2099 (signal 'js2-syntax-error
2100 (list msg
2101 js2-ts-lineno
2102 (save-excursion
2103 (goto-char js2-ts-cursor)
2104 (current-column))
2105 js2-ts-hit-eof))))
2106
2107 (defun js2-report-warning (msg &optional msg-arg pos len face)
2108 (if js2-compiler-report-warning-as-error
2109 (js2-report-error msg msg-arg pos len)
2110 (push (list (list msg msg-arg)
2111 (or pos (js2-current-token-beg))
2112 (or len (js2-current-token-len))
2113 face)
2114 js2-parsed-warnings)))
2115
2116 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2117 (if js2-compiler-strict-mode
2118 (js2-report-warning msg-id msg-arg beg
2119 (and beg end (- end beg)))))
2120
2121 (put 'js2-syntax-error 'error-conditions
2122 '(error syntax-error js2-syntax-error))
2123 (put 'js2-syntax-error 'error-message "Syntax error")
2124
2125 (put 'js2-parse-error 'error-conditions
2126 '(error parse-error js2-parse-error))
2127 (put 'js2-parse-error 'error-message "Parse error")
2128
2129 (defmacro js2-clear-flag (flags flag)
2130 `(setq ,flags (logand ,flags (lognot ,flag))))
2131
2132 (defmacro js2-set-flag (flags flag)
2133 "Logical-or FLAG into FLAGS."
2134 `(setq ,flags (logior ,flags ,flag)))
2135
2136 (defsubst js2-flag-set-p (flags flag)
2137 (/= 0 (logand flags flag)))
2138
2139 (defsubst js2-flag-not-set-p (flags flag)
2140 (zerop (logand flags flag)))
2141
2142 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2143 "Evaluate BODY with the _ character set to be word-syntax."
2144 (declare (indent 0) (debug t))
2145 (let ((old-syntax (make-symbol "old-syntax")))
2146 `(let ((,old-syntax (string (char-syntax ?_))))
2147 (unwind-protect
2148 (progn
2149 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2150 ,@body)
2151 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2152
2153 ;;; AST struct and function definitions
2154
2155 ;; flags for ast node property 'member-type (used for e4x operators)
2156 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2157 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2158 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2159
2160 (defsubst js2-relpos (pos anchor)
2161 "Convert POS to be relative to ANCHOR.
2162 If POS is nil, returns nil."
2163 (and pos (- pos anchor)))
2164
2165 (defun js2-make-pad (indent)
2166 (if (zerop indent)
2167 ""
2168 (make-string (* indent js2-basic-offset) ? )))
2169
2170 (defun js2-visit-ast (node callback)
2171 "Visit every node in ast NODE with visitor CALLBACK.
2172
2173 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2174 called twice: once to visit the node, and again after all the node's
2175 children have been processed. The END-P argument is nil on the first
2176 call and non-nil on the second call. The return value of the callback
2177 affects the traversal: if non-nil, the children of NODE are processed.
2178 If the callback returns nil, or if the node has no children, then the
2179 callback is called immediately with a non-nil END-P argument.
2180
2181 The node traversal is approximately lexical-order, although there
2182 are currently no guarantees around this."
2183 (when node
2184 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2185 ;; visit the node
2186 (when (funcall callback node nil)
2187 ;; visit the kids
2188 (cond
2189 ((eq vfunc 'js2-visit-none)
2190 nil) ; don't even bother calling it
2191 ;; Each AST node type has to define a `js2-visitor' function
2192 ;; that takes a node and a callback, and calls `js2-visit-ast'
2193 ;; on each child of the node.
2194 (vfunc
2195 (funcall vfunc node callback))
2196 (t
2197 (error "%s does not define a visitor-traversal function"
2198 (aref node 0)))))
2199 ;; call the end-visit
2200 (funcall callback node t))))
2201
2202 (defstruct (js2-node
2203 (:constructor nil)) ; abstract
2204 "Base AST node type."
2205 (type -1) ; token type
2206 (pos -1) ; start position of this AST node in parsed input
2207 (len 1) ; num characters spanned by the node
2208 props ; optional node property list (an alist)
2209 parent) ; link to parent node; null for root
2210
2211 (defsubst js2-node-get-prop (node prop &optional default)
2212 (or (cadr (assoc prop (js2-node-props node))) default))
2213
2214 (defsubst js2-node-set-prop (node prop value)
2215 (setf (js2-node-props node)
2216 (cons (list prop value) (js2-node-props node))))
2217
2218 (defun js2-fixup-starts (n nodes)
2219 "Adjust the start positions of NODES to be relative to N.
2220 Any node in the list may be nil, for convenience."
2221 (dolist (node nodes)
2222 (when node
2223 (setf (js2-node-pos node) (- (js2-node-pos node)
2224 (js2-node-pos n))))))
2225
2226 (defun js2-node-add-children (parent &rest nodes)
2227 "Set parent node of NODES to PARENT, and return PARENT.
2228 Does nothing if we're not recording parent links.
2229 If any given node in NODES is nil, doesn't record that link."
2230 (js2-fixup-starts parent nodes)
2231 (dolist (node nodes)
2232 (and node
2233 (setf (js2-node-parent node) parent))))
2234
2235 ;; Non-recursive since it's called a frightening number of times.
2236 (defun js2-node-abs-pos (n)
2237 (let ((pos (js2-node-pos n)))
2238 (while (setq n (js2-node-parent n))
2239 (setq pos (+ pos (js2-node-pos n))))
2240 pos))
2241
2242 (defsubst js2-node-abs-end (n)
2243 "Return absolute buffer position of end of N."
2244 (+ (js2-node-abs-pos n) (js2-node-len n)))
2245
2246 ;; It's important to make sure block nodes have a Lisp list for the
2247 ;; child nodes, to limit printing recursion depth in an AST that
2248 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2249 ;; a sufficiently large vector tree.
2250
2251 (defstruct (js2-block-node
2252 (:include js2-node)
2253 (:constructor nil)
2254 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2255 (pos (js2-current-token-beg))
2256 len
2257 props
2258 kids)))
2259 "A block of statements."
2260 kids) ; a Lisp list of the child statement nodes
2261
2262 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2263 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2264
2265 (defun js2-visit-block (ast callback)
2266 "Visit the `js2-block-node' children of AST."
2267 (dolist (kid (js2-block-node-kids ast))
2268 (js2-visit-ast kid callback)))
2269
2270 (defun js2-print-block (n i)
2271 (let ((pad (js2-make-pad i)))
2272 (insert pad "{\n")
2273 (dolist (kid (js2-block-node-kids n))
2274 (js2-print-ast kid (1+ i)))
2275 (insert pad "}")))
2276
2277 (defstruct (js2-scope
2278 (:include js2-block-node)
2279 (:constructor nil)
2280 (:constructor make-js2-scope (&key (type js2-BLOCK)
2281 (pos (js2-current-token-beg))
2282 len
2283 kids)))
2284 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2285 ;; I don't have one of those handy, so I'll use an alist for now.
2286 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2287 ;; and is much lighter-weight to construct (both CPU and mem).
2288 ;; The keys are interned strings (symbols) for faster lookup.
2289 ;; Should switch to hybrid alist/hashtable eventually.
2290 symbol-table ; an alist of (symbol . js2-symbol)
2291 parent-scope ; a `js2-scope'
2292 top) ; top-level `js2-scope' (script/function)
2293
2294 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2295 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2296
2297 (defun js2-node-get-enclosing-scope (node)
2298 "Return the innermost `js2-scope' node surrounding NODE.
2299 Returns nil if there is no enclosing scope node."
2300 (let ((parent (js2-node-parent node)))
2301 (while (not (js2-scope-p parent))
2302 (setq parent (js2-node-parent parent)))
2303 parent))
2304
2305 (defun js2-get-defining-scope (scope name)
2306 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2307 Returns `js2-scope' in which NAME is defined, or nil if not found."
2308 (let ((sym (if (symbolp name)
2309 name
2310 (intern name)))
2311 table
2312 result
2313 (continue t))
2314 (while (and scope continue)
2315 (if (and (setq table (js2-scope-symbol-table scope))
2316 (assq sym table))
2317 (setq continue nil
2318 result scope)
2319 (setq scope (js2-scope-parent-scope scope))))
2320 result))
2321
2322 (defun js2-scope-get-symbol (scope name)
2323 "Return symbol table entry for NAME in SCOPE.
2324 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2325 (and (js2-scope-symbol-table scope)
2326 (cdr (assq (if (symbolp name)
2327 name
2328 (intern name))
2329 (js2-scope-symbol-table scope)))))
2330
2331 (defun js2-scope-put-symbol (scope name symbol)
2332 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2333 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2334 (let* ((table (js2-scope-symbol-table scope))
2335 (sym (if (symbolp name) name (intern name)))
2336 (entry (assq sym table)))
2337 (if entry
2338 (setcdr entry symbol)
2339 (push (cons sym symbol)
2340 (js2-scope-symbol-table scope)))))
2341
2342 (defstruct (js2-symbol
2343 (:constructor nil)
2344 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2345 "A symbol table entry."
2346 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2347 ;; js2-LET, or js2-CONST
2348 decl-type
2349 name ; string
2350 ast-node) ; a `js2-node'
2351
2352 (defstruct (js2-error-node
2353 (:include js2-node)
2354 (:constructor nil) ; silence emacs21 byte-compiler
2355 (:constructor make-js2-error-node (&key (type js2-ERROR)
2356 (pos (js2-current-token-beg))
2357 len)))
2358 "AST node representing a parse error.")
2359
2360 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2361 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2362
2363 (defstruct (js2-script-node
2364 (:include js2-scope)
2365 (:constructor nil)
2366 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2367 (pos (js2-current-token-beg))
2368 len
2369 ;; FIXME: What are those?
2370 var-decls
2371 fun-decls)))
2372 functions ; Lisp list of nested functions
2373 regexps ; Lisp list of (string . flags)
2374 symbols ; alist (every symbol gets unique index)
2375 (param-count 0)
2376 var-names ; vector of string names
2377 consts ; bool-vector matching var-decls
2378 (temp-number 0)) ; for generating temp variables
2379
2380 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2381 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2382
2383 (defun js2-print-script (node indent)
2384 (dolist (kid (js2-block-node-kids node))
2385 (js2-print-ast kid indent)))
2386
2387 (defstruct (js2-ast-root
2388 (:include js2-script-node)
2389 (:constructor nil)
2390 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2391 (pos (js2-current-token-beg))
2392 len
2393 buffer)))
2394 "The root node of a js2 AST."
2395 buffer ; the source buffer from which the code was parsed
2396 comments ; a Lisp list of comments, ordered by start position
2397 errors ; a Lisp list of errors found during parsing
2398 warnings ; a Lisp list of warnings found during parsing
2399 node-count) ; number of nodes in the tree, including the root
2400
2401 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2402 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2403
2404 (defun js2-visit-ast-root (ast callback)
2405 (dolist (kid (js2-ast-root-kids ast))
2406 (js2-visit-ast kid callback))
2407 (dolist (comment (js2-ast-root-comments ast))
2408 (js2-visit-ast comment callback)))
2409
2410 (defstruct (js2-comment-node
2411 (:include js2-node)
2412 (:constructor nil)
2413 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2414 (pos (js2-current-token-beg))
2415 len
2416 format)))
2417 format) ; 'line, 'block, 'jsdoc or 'html
2418
2419 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2420 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2421
2422 (defun js2-print-comment (n i)
2423 ;; We really ought to link end-of-line comments to their nodes.
2424 ;; Or maybe we could add a new comment type, 'endline.
2425 (insert (js2-make-pad i)
2426 (js2-node-string n)))
2427
2428 (defstruct (js2-expr-stmt-node
2429 (:include js2-node)
2430 (:constructor nil)
2431 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2432 (pos js2-ts-cursor)
2433 len
2434 expr)))
2435 "An expression statement."
2436 expr)
2437
2438 (defsubst js2-expr-stmt-node-set-has-result (node)
2439 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2440 (setf (js2-node-type node) js2-EXPR_RESULT))
2441
2442 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2443 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2444
2445 (defun js2-visit-expr-stmt-node (n v)
2446 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2447
2448 (defun js2-print-expr-stmt-node (n indent)
2449 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2450 (insert ";\n"))
2451
2452 (defstruct (js2-loop-node
2453 (:include js2-scope)
2454 (:constructor nil))
2455 "Abstract supertype of loop nodes."
2456 body ; a `js2-block-node'
2457 lp ; position of left-paren, nil if omitted
2458 rp) ; position of right-paren, nil if omitted
2459
2460 (defstruct (js2-do-node
2461 (:include js2-loop-node)
2462 (:constructor nil)
2463 (:constructor make-js2-do-node (&key (type js2-DO)
2464 (pos (js2-current-token-beg))
2465 len
2466 body
2467 condition
2468 while-pos
2469 lp
2470 rp)))
2471 "AST node for do-loop."
2472 condition ; while (expression)
2473 while-pos) ; buffer position of 'while' keyword
2474
2475 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2476 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2477
2478 (defun js2-visit-do-node (n v)
2479 (js2-visit-ast (js2-do-node-body n) v)
2480 (js2-visit-ast (js2-do-node-condition n) v))
2481
2482 (defun js2-print-do-node (n i)
2483 (let ((pad (js2-make-pad i)))
2484 (insert pad "do {\n")
2485 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2486 (js2-print-ast kid (1+ i)))
2487 (insert pad "} while (")
2488 (js2-print-ast (js2-do-node-condition n) 0)
2489 (insert ");\n")))
2490
2491 (defstruct (js2-while-node
2492 (:include js2-loop-node)
2493 (:constructor nil)
2494 (:constructor make-js2-while-node (&key (type js2-WHILE)
2495 (pos (js2-current-token-beg))
2496 len body
2497 condition lp
2498 rp)))
2499 "AST node for while-loop."
2500 condition) ; while-condition
2501
2502 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2503 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2504
2505 (defun js2-visit-while-node (n v)
2506 (js2-visit-ast (js2-while-node-condition n) v)
2507 (js2-visit-ast (js2-while-node-body n) v))
2508
2509 (defun js2-print-while-node (n i)
2510 (let ((pad (js2-make-pad i)))
2511 (insert pad "while (")
2512 (js2-print-ast (js2-while-node-condition n) 0)
2513 (insert ") {\n")
2514 (js2-print-body (js2-while-node-body n) (1+ i))
2515 (insert pad "}\n")))
2516
2517 (defstruct (js2-for-node
2518 (:include js2-loop-node)
2519 (:constructor nil)
2520 (:constructor make-js2-for-node (&key (type js2-FOR)
2521 (pos js2-ts-cursor)
2522 len body init
2523 condition
2524 update lp rp)))
2525 "AST node for a C-style for-loop."
2526 init ; initialization expression
2527 condition ; loop condition
2528 update) ; update clause
2529
2530 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2531 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2532
2533 (defun js2-visit-for-node (n v)
2534 (js2-visit-ast (js2-for-node-init n) v)
2535 (js2-visit-ast (js2-for-node-condition n) v)
2536 (js2-visit-ast (js2-for-node-update n) v)
2537 (js2-visit-ast (js2-for-node-body n) v))
2538
2539 (defun js2-print-for-node (n i)
2540 (let ((pad (js2-make-pad i)))
2541 (insert pad "for (")
2542 (js2-print-ast (js2-for-node-init n) 0)
2543 (insert "; ")
2544 (js2-print-ast (js2-for-node-condition n) 0)
2545 (insert "; ")
2546 (js2-print-ast (js2-for-node-update n) 0)
2547 (insert ") {\n")
2548 (js2-print-body (js2-for-node-body n) (1+ i))
2549 (insert pad "}\n")))
2550
2551 (defstruct (js2-for-in-node
2552 (:include js2-loop-node)
2553 (:constructor nil)
2554 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2555 (pos js2-ts-cursor)
2556 len body
2557 iterator
2558 object
2559 in-pos
2560 each-pos
2561 foreach-p forof-p
2562 lp rp)))
2563 "AST node for a for..in loop."
2564 iterator ; [var] foo in ...
2565 object ; object over which we're iterating
2566 in-pos ; buffer position of 'in' keyword
2567 each-pos ; buffer position of 'each' keyword, if foreach-p
2568 foreach-p ; t if it's a for-each loop
2569 forof-p) ; t if it's a for-of loop
2570
2571 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2572 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2573
2574 (defun js2-visit-for-in-node (n v)
2575 (js2-visit-ast (js2-for-in-node-iterator n) v)
2576 (js2-visit-ast (js2-for-in-node-object n) v)
2577 (js2-visit-ast (js2-for-in-node-body n) v))
2578
2579 (defun js2-print-for-in-node (n i)
2580 (let ((pad (js2-make-pad i))
2581 (foreach (js2-for-in-node-foreach-p n))
2582 (forof (js2-for-in-node-forof-p n)))
2583 (insert pad "for ")
2584 (if foreach
2585 (insert "each "))
2586 (insert "(")
2587 (js2-print-ast (js2-for-in-node-iterator n) 0)
2588 (insert (if forof " of " " in "))
2589 (js2-print-ast (js2-for-in-node-object n) 0)
2590 (insert ") {\n")
2591 (js2-print-body (js2-for-in-node-body n) (1+ i))
2592 (insert pad "}\n")))
2593
2594 (defstruct (js2-return-node
2595 (:include js2-node)
2596 (:constructor nil)
2597 (:constructor make-js2-return-node (&key (type js2-RETURN)
2598 (pos js2-ts-cursor)
2599 len
2600 retval)))
2601 "AST node for a return statement."
2602 retval) ; expression to return, or 'undefined
2603
2604 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2605 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2606
2607 (defun js2-visit-return-node (n v)
2608 (js2-visit-ast (js2-return-node-retval n) v))
2609
2610 (defun js2-print-return-node (n i)
2611 (insert (js2-make-pad i) "return")
2612 (when (js2-return-node-retval n)
2613 (insert " ")
2614 (js2-print-ast (js2-return-node-retval n) 0))
2615 (insert ";\n"))
2616
2617 (defstruct (js2-if-node
2618 (:include js2-node)
2619 (:constructor nil)
2620 (:constructor make-js2-if-node (&key (type js2-IF)
2621 (pos js2-ts-cursor)
2622 len condition
2623 then-part
2624 else-pos
2625 else-part lp
2626 rp)))
2627 "AST node for an if-statement."
2628 condition ; expression
2629 then-part ; statement or block
2630 else-pos ; optional buffer position of 'else' keyword
2631 else-part ; optional statement or block
2632 lp ; position of left-paren, nil if omitted
2633 rp) ; position of right-paren, nil if omitted
2634
2635 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2636 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2637
2638 (defun js2-visit-if-node (n v)
2639 (js2-visit-ast (js2-if-node-condition n) v)
2640 (js2-visit-ast (js2-if-node-then-part n) v)
2641 (js2-visit-ast (js2-if-node-else-part n) v))
2642
2643 (defun js2-print-if-node (n i)
2644 (let ((pad (js2-make-pad i))
2645 (then-part (js2-if-node-then-part n))
2646 (else-part (js2-if-node-else-part n)))
2647 (insert pad "if (")
2648 (js2-print-ast (js2-if-node-condition n) 0)
2649 (insert ") {\n")
2650 (js2-print-body then-part (1+ i))
2651 (insert pad "}")
2652 (cond
2653 ((not else-part)
2654 (insert "\n"))
2655 ((js2-if-node-p else-part)
2656 (insert " else ")
2657 (js2-print-body else-part i))
2658 (t
2659 (insert " else {\n")
2660 (js2-print-body else-part (1+ i))
2661 (insert pad "}\n")))))
2662
2663 (defstruct (js2-try-node
2664 (:include js2-node)
2665 (:constructor nil)
2666 (:constructor make-js2-try-node (&key (type js2-TRY)
2667 (pos js2-ts-cursor)
2668 len
2669 try-block
2670 catch-clauses
2671 finally-block)))
2672 "AST node for a try-statement."
2673 try-block
2674 catch-clauses ; a Lisp list of `js2-catch-node'
2675 finally-block) ; a `js2-finally-node'
2676
2677 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2678 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2679
2680 (defun js2-visit-try-node (n v)
2681 (js2-visit-ast (js2-try-node-try-block n) v)
2682 (dolist (clause (js2-try-node-catch-clauses n))
2683 (js2-visit-ast clause v))
2684 (js2-visit-ast (js2-try-node-finally-block n) v))
2685
2686 (defun js2-print-try-node (n i)
2687 (let ((pad (js2-make-pad i))
2688 (catches (js2-try-node-catch-clauses n))
2689 (finally (js2-try-node-finally-block n)))
2690 (insert pad "try {\n")
2691 (js2-print-body (js2-try-node-try-block n) (1+ i))
2692 (insert pad "}")
2693 (when catches
2694 (dolist (catch catches)
2695 (js2-print-ast catch i)))
2696 (if finally
2697 (js2-print-ast finally i)
2698 (insert "\n"))))
2699
2700 (defstruct (js2-catch-node
2701 (:include js2-node)
2702 (:constructor nil)
2703 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2704 (pos js2-ts-cursor)
2705 len
2706 param
2707 guard-kwd
2708 guard-expr
2709 block lp
2710 rp)))
2711 "AST node for a catch clause."
2712 param ; destructuring form or simple name node
2713 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2714 guard-expr ; catch condition, a `js2-node'
2715 block ; statements, a `js2-block-node'
2716 lp ; buffer position of left-paren, nil if omitted
2717 rp) ; buffer position of right-paren, nil if omitted
2718
2719 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2720 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2721
2722 (defun js2-visit-catch-node (n v)
2723 (js2-visit-ast (js2-catch-node-param n) v)
2724 (when (js2-catch-node-guard-kwd n)
2725 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2726 (js2-visit-ast (js2-catch-node-block n) v))
2727
2728 (defun js2-print-catch-node (n i)
2729 (let ((pad (js2-make-pad i))
2730 (guard-kwd (js2-catch-node-guard-kwd n))
2731 (guard-expr (js2-catch-node-guard-expr n)))
2732 (insert " catch (")
2733 (js2-print-ast (js2-catch-node-param n) 0)
2734 (when guard-kwd
2735 (insert " if ")
2736 (js2-print-ast guard-expr 0))
2737 (insert ") {\n")
2738 (js2-print-body (js2-catch-node-block n) (1+ i))
2739 (insert pad "}")))
2740
2741 (defstruct (js2-finally-node
2742 (:include js2-node)
2743 (:constructor nil)
2744 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2745 (pos js2-ts-cursor)
2746 len body)))
2747 "AST node for a finally clause."
2748 body) ; a `js2-node', often but not always a block node
2749
2750 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2751 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2752
2753 (defun js2-visit-finally-node (n v)
2754 (js2-visit-ast (js2-finally-node-body n) v))
2755
2756 (defun js2-print-finally-node (n i)
2757 (let ((pad (js2-make-pad i)))
2758 (insert " finally {\n")
2759 (js2-print-body (js2-finally-node-body n) (1+ i))
2760 (insert pad "}\n")))
2761
2762 (defstruct (js2-switch-node
2763 (:include js2-node)
2764 (:constructor nil)
2765 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2766 (pos js2-ts-cursor)
2767 len
2768 discriminant
2769 cases lp
2770 rp)))
2771 "AST node for a switch statement."
2772 discriminant ; a `js2-node' (switch expression)
2773 cases ; a Lisp list of `js2-case-node'
2774 lp ; position of open-paren for discriminant, nil if omitted
2775 rp) ; position of close-paren for discriminant, nil if omitted
2776
2777 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2778 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2779
2780 (defun js2-visit-switch-node (n v)
2781 (js2-visit-ast (js2-switch-node-discriminant n) v)
2782 (dolist (c (js2-switch-node-cases n))
2783 (js2-visit-ast c v)))
2784
2785 (defun js2-print-switch-node (n i)
2786 (let ((pad (js2-make-pad i))
2787 (cases (js2-switch-node-cases n)))
2788 (insert pad "switch (")
2789 (js2-print-ast (js2-switch-node-discriminant n) 0)
2790 (insert ") {\n")
2791 (dolist (case cases)
2792 (js2-print-ast case i))
2793 (insert pad "}\n")))
2794
2795 (defstruct (js2-case-node
2796 (:include js2-block-node)
2797 (:constructor nil)
2798 (:constructor make-js2-case-node (&key (type js2-CASE)
2799 (pos js2-ts-cursor)
2800 len kids expr)))
2801 "AST node for a case clause of a switch statement."
2802 expr) ; the case expression (nil for default)
2803
2804 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2805 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2806
2807 (defun js2-visit-case-node (n v)
2808 (js2-visit-ast (js2-case-node-expr n) v)
2809 (js2-visit-block n v))
2810
2811 (defun js2-print-case-node (n i)
2812 (let ((pad (js2-make-pad i))
2813 (expr (js2-case-node-expr n)))
2814 (insert pad)
2815 (if (null expr)
2816 (insert "default:\n")
2817 (insert "case ")
2818 (js2-print-ast expr 0)
2819 (insert ":\n"))
2820 (dolist (kid (js2-case-node-kids n))
2821 (js2-print-ast kid (1+ i)))))
2822
2823 (defstruct (js2-throw-node
2824 (:include js2-node)
2825 (:constructor nil)
2826 (:constructor make-js2-throw-node (&key (type js2-THROW)
2827 (pos js2-ts-cursor)
2828 len expr)))
2829 "AST node for a throw statement."
2830 expr) ; the expression to throw
2831
2832 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2833 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2834
2835 (defun js2-visit-throw-node (n v)
2836 (js2-visit-ast (js2-throw-node-expr n) v))
2837
2838 (defun js2-print-throw-node (n i)
2839 (insert (js2-make-pad i) "throw ")
2840 (js2-print-ast (js2-throw-node-expr n) 0)
2841 (insert ";\n"))
2842
2843 (defstruct (js2-with-node
2844 (:include js2-node)
2845 (:constructor nil)
2846 (:constructor make-js2-with-node (&key (type js2-WITH)
2847 (pos js2-ts-cursor)
2848 len object
2849 body lp rp)))
2850 "AST node for a with-statement."
2851 object
2852 body
2853 lp ; buffer position of left-paren around object, nil if omitted
2854 rp) ; buffer position of right-paren around object, nil if omitted
2855
2856 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2857 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2858
2859 (defun js2-visit-with-node (n v)
2860 (js2-visit-ast (js2-with-node-object n) v)
2861 (js2-visit-ast (js2-with-node-body n) v))
2862
2863 (defun js2-print-with-node (n i)
2864 (let ((pad (js2-make-pad i)))
2865 (insert pad "with (")
2866 (js2-print-ast (js2-with-node-object n) 0)
2867 (insert ") {\n")
2868 (js2-print-body (js2-with-node-body n) (1+ i))
2869 (insert pad "}\n")))
2870
2871 (defstruct (js2-label-node
2872 (:include js2-node)
2873 (:constructor nil)
2874 (:constructor make-js2-label-node (&key (type js2-LABEL)
2875 (pos js2-ts-cursor)
2876 len name)))
2877 "AST node for a statement label or case label."
2878 name ; a string
2879 loop) ; for validating and code-generating continue-to-label
2880
2881 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2882 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2883
2884 (defun js2-print-label (n i)
2885 (insert (js2-make-pad i)
2886 (js2-label-node-name n)
2887 ":\n"))
2888
2889 (defstruct (js2-labeled-stmt-node
2890 (:include js2-node)
2891 (:constructor nil)
2892 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2893 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2894 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2895 (pos js2-ts-cursor)
2896 len labels stmt)))
2897 "AST node for a statement with one or more labels.
2898 Multiple labels for a statement are collapsed into the labels field."
2899 labels ; Lisp list of `js2-label-node'
2900 stmt) ; the statement these labels are for
2901
2902 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2903 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2904
2905 (defun js2-get-label-by-name (lbl-stmt name)
2906 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2907 Returns nil if no such label is in the list."
2908 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2909 result)
2910 (while (and label-list (not result))
2911 (if (string= (js2-label-node-name (car label-list)) name)
2912 (setq result (car label-list))
2913 (setq label-list (cdr label-list))))
2914 result))
2915
2916 (defun js2-visit-labeled-stmt (n v)
2917 (dolist (label (js2-labeled-stmt-node-labels n))
2918 (js2-visit-ast label v))
2919 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2920
2921 (defun js2-print-labeled-stmt (n i)
2922 (dolist (label (js2-labeled-stmt-node-labels n))
2923 (js2-print-ast label i))
2924 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2925
2926 (defun js2-labeled-stmt-node-contains (node label)
2927 "Return t if NODE contains LABEL in its label set.
2928 NODE is a `js2-labels-node'. LABEL is an identifier."
2929 (loop for nl in (js2-labeled-stmt-node-labels node)
2930 if (string= label (js2-label-node-name nl))
2931 return t
2932 finally return nil))
2933
2934 (defsubst js2-labeled-stmt-node-add-label (node label)
2935 "Add a `js2-label-node' to the label set for this statement."
2936 (setf (js2-labeled-stmt-node-labels node)
2937 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2938
2939 (defstruct (js2-jump-node
2940 (:include js2-node)
2941 (:constructor nil))
2942 "Abstract supertype of break and continue nodes."
2943 label ; `js2-name-node' for location of label identifier, if present
2944 target) ; target js2-labels-node or loop/switch statement
2945
2946 (defun js2-visit-jump-node (n v)
2947 ;; We don't visit the target, since it's a back-link.
2948 (js2-visit-ast (js2-jump-node-label n) v))
2949
2950 (defstruct (js2-break-node
2951 (:include js2-jump-node)
2952 (:constructor nil)
2953 (:constructor make-js2-break-node (&key (type js2-BREAK)
2954 (pos js2-ts-cursor)
2955 len label target)))
2956 "AST node for a break statement.
2957 The label field is a `js2-name-node', possibly nil, for the named label
2958 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2959 is the target of the break - a label node or enclosing loop/switch statement.")
2960
2961 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2962 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2963
2964 (defun js2-print-break-node (n i)
2965 (insert (js2-make-pad i) "break")
2966 (when (js2-break-node-label n)
2967 (insert " ")
2968 (js2-print-ast (js2-break-node-label n) 0))
2969 (insert ";\n"))
2970
2971 (defstruct (js2-continue-node
2972 (:include js2-jump-node)
2973 (:constructor nil)
2974 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2975 (pos js2-ts-cursor)
2976 len label target)))
2977 "AST node for a continue statement.
2978 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2979 It is nil if continue specifies no label. The target field is the jump target:
2980 a `js2-label-node' or the innermost enclosing loop.")
2981
2982 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2983 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2984
2985 (defun js2-print-continue-node (n i)
2986 (insert (js2-make-pad i) "continue")
2987 (when (js2-continue-node-label n)
2988 (insert " ")
2989 (js2-print-ast (js2-continue-node-label n) 0))
2990 (insert ";\n"))
2991
2992 (defstruct (js2-function-node
2993 (:include js2-script-node)
2994 (:constructor nil)
2995 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2996 (pos js2-ts-cursor)
2997 len
2998 (ftype 'FUNCTION)
2999 (form 'FUNCTION_STATEMENT)
3000 (name "")
3001 params rest-p
3002 body
3003 generator-type
3004 lp rp)))
3005 "AST node for a function declaration.
3006 The `params' field is a Lisp list of nodes. Each node is either a simple
3007 `js2-name-node', or if it's a destructuring-assignment parameter, a
3008 `js2-array-node' or `js2-object-node'."
3009 ftype ; FUNCTION, GETTER or SETTER
3010 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3011 name ; function name (a `js2-name-node', or nil if anonymous)
3012 params ; a Lisp list of destructuring forms or simple name nodes
3013 rest-p ; if t, the last parameter is rest parameter
3014 body ; a `js2-block-node' or expression node (1.8 only)
3015 lp ; position of arg-list open-paren, or nil if omitted
3016 rp ; position of arg-list close-paren, or nil if omitted
3017 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3018 needs-activation ; t if we need an activation object for this frame
3019 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3020 member-expr) ; nonstandard Ecma extension from Rhino
3021
3022 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3023 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3024
3025 (defun js2-visit-function-node (n v)
3026 (js2-visit-ast (js2-function-node-name n) v)
3027 (dolist (p (js2-function-node-params n))
3028 (js2-visit-ast p v))
3029 (js2-visit-ast (js2-function-node-body n) v))
3030
3031 (defun js2-print-function-node (n i)
3032 (let* ((pad (js2-make-pad i))
3033 (getter (js2-node-get-prop n 'GETTER_SETTER))
3034 (name (or (js2-function-node-name n)
3035 (js2-function-node-member-expr n)))
3036 (params (js2-function-node-params n))
3037 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3038 (rest-p (js2-function-node-rest-p n))
3039 (body (js2-function-node-body n))
3040 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3041 (unless (or getter arrow)
3042 (insert pad "function")
3043 (when (eq (js2-function-node-generator-type n) 'STAR)
3044 (insert "*")))
3045 (when name
3046 (insert " ")
3047 (js2-print-ast name 0))
3048 (insert "(")
3049 (loop with len = (length params)
3050 for param in params
3051 for count from 1
3052 do
3053 (when (and rest-p (= count len))
3054 (insert "..."))
3055 (js2-print-ast param 0)
3056 (when (< count len)
3057 (insert ", ")))
3058 (insert ") ")
3059 (when arrow
3060 (insert "=> "))
3061 (insert "{")
3062 ;; TODO: fix this to be smarter about indenting, etc.
3063 (unless expr
3064 (insert "\n"))
3065 (if (js2-block-node-p body)
3066 (js2-print-body body (1+ i))
3067 (js2-print-ast body 0))
3068 (insert pad "}")
3069 (unless expr
3070 (insert "\n"))))
3071
3072 (defun js2-function-name (node)
3073 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3074 (and (js2-function-node-name node)
3075 (js2-name-node-name (js2-function-node-name node))))
3076
3077 ;; Having this be an expression node makes it more flexible.
3078 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3079 ;; that work better if you assume it's an expression. Whenever we have
3080 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3081 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3082 (defstruct (js2-var-decl-node
3083 (:include js2-node)
3084 (:constructor nil)
3085 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3086 (pos (js2-current-token-beg))
3087 len kids
3088 decl-type)))
3089 "AST node for a variable declaration list (VAR, CONST or LET).
3090 The node bounds differ depending on the declaration type. For VAR or
3091 CONST declarations, the bounds include the var/const keyword. For LET
3092 declarations, the node begins at the position of the first child."
3093 kids ; a Lisp list of `js2-var-init-node' structs.
3094 decl-type) ; js2-VAR, js2-CONST or js2-LET
3095
3096 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3097 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3098
3099 (defun js2-visit-var-decl (n v)
3100 (dolist (kid (js2-var-decl-node-kids n))
3101 (js2-visit-ast kid v)))
3102
3103 (defun js2-print-var-decl (n i)
3104 (let ((pad (js2-make-pad i))
3105 (tt (js2-var-decl-node-decl-type n)))
3106 (insert pad)
3107 (insert (cond
3108 ((= tt js2-VAR) "var ")
3109 ((= tt js2-LET) "let ")
3110 ((= tt js2-CONST) "const ")
3111 (t
3112 (error "malformed var-decl node"))))
3113 (loop with kids = (js2-var-decl-node-kids n)
3114 with len = (length kids)
3115 for kid in kids
3116 for count from 1
3117 do
3118 (js2-print-ast kid 0)
3119 (if (< count len)
3120 (insert ", ")))))
3121
3122 (defstruct (js2-var-init-node
3123 (:include js2-node)
3124 (:constructor nil)
3125 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3126 (pos js2-ts-cursor)
3127 len target
3128 initializer)))
3129 "AST node for a variable declaration.
3130 The type field will be js2-CONST for a const decl."
3131 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3132 initializer) ; initializer expression, a `js2-node'
3133
3134 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3135 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3136
3137 (defun js2-visit-var-init-node (n v)
3138 (js2-visit-ast (js2-var-init-node-target n) v)
3139 (js2-visit-ast (js2-var-init-node-initializer n) v))
3140
3141 (defun js2-print-var-init-node (n i)
3142 (let ((pad (js2-make-pad i))
3143 (name (js2-var-init-node-target n))
3144 (init (js2-var-init-node-initializer n)))
3145 (insert pad)
3146 (js2-print-ast name 0)
3147 (when init
3148 (insert " = ")
3149 (js2-print-ast init 0))))
3150
3151 (defstruct (js2-cond-node
3152 (:include js2-node)
3153 (:constructor nil)
3154 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3155 (pos js2-ts-cursor)
3156 len
3157 test-expr
3158 true-expr
3159 false-expr
3160 q-pos c-pos)))
3161 "AST node for the ternary operator"
3162 test-expr
3163 true-expr
3164 false-expr
3165 q-pos ; buffer position of ?
3166 c-pos) ; buffer position of :
3167
3168 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3169 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3170
3171 (defun js2-visit-cond-node (n v)
3172 (js2-visit-ast (js2-cond-node-test-expr n) v)
3173 (js2-visit-ast (js2-cond-node-true-expr n) v)
3174 (js2-visit-ast (js2-cond-node-false-expr n) v))
3175
3176 (defun js2-print-cond-node (n i)
3177 (let ((pad (js2-make-pad i)))
3178 (insert pad)
3179 (js2-print-ast (js2-cond-node-test-expr n) 0)
3180 (insert " ? ")
3181 (js2-print-ast (js2-cond-node-true-expr n) 0)
3182 (insert " : ")
3183 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3184
3185 (defstruct (js2-infix-node
3186 (:include js2-node)
3187 (:constructor nil)
3188 (:constructor make-js2-infix-node (&key type
3189 (pos js2-ts-cursor)
3190 len op-pos
3191 left right)))
3192 "Represents infix expressions.
3193 Includes assignment ops like `|=', and the comma operator.
3194 The type field inherited from `js2-node' holds the operator."
3195 op-pos ; buffer position where operator begins
3196 left ; any `js2-node'
3197 right) ; any `js2-node'
3198
3199 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3200 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3201
3202 (defun js2-visit-infix-node (n v)
3203 (js2-visit-ast (js2-infix-node-left n) v)
3204 (js2-visit-ast (js2-infix-node-right n) v))
3205
3206 (defconst js2-operator-tokens
3207 (let ((table (make-hash-table :test 'eq))
3208 (tokens
3209 (list (cons js2-IN "in")
3210 (cons js2-TYPEOF "typeof")
3211 (cons js2-INSTANCEOF "instanceof")
3212 (cons js2-DELPROP "delete")
3213 (cons js2-COMMA ",")
3214 (cons js2-COLON ":")
3215 (cons js2-OR "||")
3216 (cons js2-AND "&&")
3217 (cons js2-INC "++")
3218 (cons js2-DEC "--")
3219 (cons js2-BITOR "|")
3220 (cons js2-BITXOR "^")
3221 (cons js2-BITAND "&")
3222 (cons js2-EQ "==")
3223 (cons js2-NE "!=")
3224 (cons js2-LT "<")
3225 (cons js2-LE "<=")
3226 (cons js2-GT ">")
3227 (cons js2-GE ">=")
3228 (cons js2-LSH "<<")
3229 (cons js2-RSH ">>")
3230 (cons js2-URSH ">>>")
3231 (cons js2-ADD "+") ; infix plus
3232 (cons js2-SUB "-") ; infix minus
3233 (cons js2-MUL "*")
3234 (cons js2-DIV "/")
3235 (cons js2-MOD "%")
3236 (cons js2-NOT "!")
3237 (cons js2-BITNOT "~")
3238 (cons js2-POS "+") ; unary plus
3239 (cons js2-NEG "-") ; unary minus
3240 (cons js2-TRIPLEDOT "...")
3241 (cons js2-SHEQ "===") ; shallow equality
3242 (cons js2-SHNE "!==") ; shallow inequality
3243 (cons js2-ASSIGN "=")
3244 (cons js2-ASSIGN_BITOR "|=")
3245 (cons js2-ASSIGN_BITXOR "^=")
3246 (cons js2-ASSIGN_BITAND "&=")
3247 (cons js2-ASSIGN_LSH "<<=")
3248 (cons js2-ASSIGN_RSH ">>=")
3249 (cons js2-ASSIGN_URSH ">>>=")
3250 (cons js2-ASSIGN_ADD "+=")
3251 (cons js2-ASSIGN_SUB "-=")
3252 (cons js2-ASSIGN_MUL "*=")
3253 (cons js2-ASSIGN_DIV "/=")
3254 (cons js2-ASSIGN_MOD "%="))))
3255 (loop for (k . v) in tokens do
3256 (puthash k v table))
3257 table))
3258
3259 (defun js2-print-infix-node (n i)
3260 (let* ((tt (js2-node-type n))
3261 (op (gethash tt js2-operator-tokens)))
3262 (unless op
3263 (error "unrecognized infix operator %s" (js2-node-type n)))
3264 (insert (js2-make-pad i))
3265 (js2-print-ast (js2-infix-node-left n) 0)
3266 (unless (= tt js2-COMMA)
3267 (insert " "))
3268 (insert op)
3269 (insert " ")
3270 (js2-print-ast (js2-infix-node-right n) 0)))
3271
3272 (defstruct (js2-assign-node
3273 (:include js2-infix-node)
3274 (:constructor nil)
3275 (:constructor make-js2-assign-node (&key type
3276 (pos js2-ts-cursor)
3277 len op-pos
3278 left right)))
3279 "Represents any assignment.
3280 The type field holds the actual assignment operator.")
3281
3282 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3283 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3284
3285 (defstruct (js2-unary-node
3286 (:include js2-node)
3287 (:constructor nil)
3288 (:constructor make-js2-unary-node (&key type ; required
3289 (pos js2-ts-cursor)
3290 len operand)))
3291 "AST node type for unary operator nodes.
3292 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3293 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3294 property is added if the operator follows the operand."
3295 operand) ; a `js2-node' expression
3296
3297 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3298 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3299
3300 (defun js2-visit-unary-node (n v)
3301 (js2-visit-ast (js2-unary-node-operand n) v))
3302
3303 (defun js2-print-unary-node (n i)
3304 (let* ((tt (js2-node-type n))
3305 (op (gethash tt js2-operator-tokens))
3306 (postfix (js2-node-get-prop n 'postfix)))
3307 (unless op
3308 (error "unrecognized unary operator %s" tt))
3309 (insert (js2-make-pad i))
3310 (unless postfix
3311 (insert op))
3312 (if (or (= tt js2-TYPEOF)
3313 (= tt js2-DELPROP))
3314 (insert " "))
3315 (js2-print-ast (js2-unary-node-operand n) 0)
3316 (when postfix
3317 (insert op))))
3318
3319 (defstruct (js2-let-node
3320 (:include js2-scope)
3321 (:constructor nil)
3322 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3323 (pos (js2-current-token-beg))
3324 len vars body
3325 lp rp)))
3326 "AST node for a let expression or a let statement.
3327 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3328 vars ; a `js2-var-decl-node'
3329 body ; a `js2-node' representing the expression or body block
3330 lp
3331 rp)
3332
3333 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3334 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3335
3336 (defun js2-visit-let-node (n v)
3337 (js2-visit-ast (js2-let-node-vars n) v)
3338 (js2-visit-ast (js2-let-node-body n) v))
3339
3340 (defun js2-print-let-node (n i)
3341 (insert (js2-make-pad i) "let (")
3342 (let ((p (point)))
3343 (js2-print-ast (js2-let-node-vars n) 0)
3344 (delete-region p (+ p 4)))
3345 (insert ") ")
3346 (js2-print-ast (js2-let-node-body n) i))
3347
3348 (defstruct (js2-keyword-node
3349 (:include js2-node)
3350 (:constructor nil)
3351 (:constructor make-js2-keyword-node (&key type
3352 (pos (js2-current-token-beg))
3353 (len (- js2-ts-cursor pos)))))
3354 "AST node representing a literal keyword such as `null'.
3355 Used for `null', `this', `true', `false' and `debugger'.
3356 The node type is set to js2-NULL, js2-THIS, etc.")
3357
3358 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3359 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3360
3361 (defun js2-print-keyword-node (n i)
3362 (insert (js2-make-pad i)
3363 (let ((tt (js2-node-type n)))
3364 (cond
3365 ((= tt js2-THIS) "this")
3366 ((= tt js2-SUPER) "super")
3367 ((= tt js2-NULL) "null")
3368 ((= tt js2-TRUE) "true")
3369 ((= tt js2-FALSE) "false")
3370 ((= tt js2-DEBUGGER) "debugger")
3371 (t (error "Invalid keyword literal type: %d" tt))))))
3372
3373 (defsubst js2-this-or-super-node-p (node)
3374 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3375 (let ((type (js2-node-type node)))
3376 (or (eq type js2-THIS) (eq type js2-SUPER))))
3377
3378 (defstruct (js2-new-node
3379 (:include js2-node)
3380 (:constructor nil)
3381 (:constructor make-js2-new-node (&key (type js2-NEW)
3382 (pos (js2-current-token-beg))
3383 len target
3384 args initializer
3385 lp rp)))
3386 "AST node for new-expression such as new Foo()."
3387 target ; an identifier or reference
3388 args ; a Lisp list of argument nodes
3389 lp ; position of left-paren, nil if omitted
3390 rp ; position of right-paren, nil if omitted
3391 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3392
3393 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3394 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3395
3396 (defun js2-visit-new-node (n v)
3397 (js2-visit-ast (js2-new-node-target n) v)
3398 (dolist (arg (js2-new-node-args n))
3399 (js2-visit-ast arg v))
3400 (js2-visit-ast (js2-new-node-initializer n) v))
3401
3402 (defun js2-print-new-node (n i)
3403 (insert (js2-make-pad i) "new ")
3404 (js2-print-ast (js2-new-node-target n))
3405 (insert "(")
3406 (js2-print-list (js2-new-node-args n))
3407 (insert ")")
3408 (when (js2-new-node-initializer n)
3409 (insert " ")
3410 (js2-print-ast (js2-new-node-initializer n))))
3411
3412 (defstruct (js2-name-node
3413 (:include js2-node)
3414 (:constructor nil)
3415 (:constructor make-js2-name-node (&key (type js2-NAME)
3416 (pos (js2-current-token-beg))
3417 (len (- js2-ts-cursor
3418 (js2-current-token-beg)))
3419 (name (js2-current-token-string)))))
3420 "AST node for a JavaScript identifier"
3421 name ; a string
3422 scope) ; a `js2-scope' (optional, used for codegen)
3423
3424 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3425 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3426
3427 (defun js2-print-name-node (n i)
3428 (insert (js2-make-pad i)
3429 (js2-name-node-name n)))
3430
3431 (defsubst js2-name-node-length (node)
3432 "Return identifier length of NODE, a `js2-name-node'.
3433 Returns 0 if NODE is nil or its identifier field is nil."
3434 (if node
3435 (length (js2-name-node-name node))
3436 0))
3437
3438 (defstruct (js2-number-node
3439 (:include js2-node)
3440 (:constructor nil)
3441 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3442 (pos (js2-current-token-beg))
3443 (len (- js2-ts-cursor
3444 (js2-current-token-beg)))
3445 (value (js2-current-token-string))
3446 (num-value (js2-token-number
3447 (js2-current-token))))))
3448 "AST node for a number literal."
3449 value ; the original string, e.g. "6.02e23"
3450 num-value) ; the parsed number value
3451
3452 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3453 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3454
3455 (defun js2-print-number-node (n i)
3456 (insert (js2-make-pad i)
3457 (number-to-string (js2-number-node-num-value n))))
3458
3459 (defstruct (js2-regexp-node
3460 (:include js2-node)
3461 (:constructor nil)
3462 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3463 (pos (js2-current-token-beg))
3464 (len (- js2-ts-cursor
3465 (js2-current-token-beg)))
3466 value flags)))
3467 "AST node for a regular expression literal."
3468 value ; the regexp string, without // delimiters
3469 flags) ; a string of flags, e.g. `mi'.
3470
3471 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3472 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3473
3474 (defun js2-print-regexp (n i)
3475 (insert (js2-make-pad i)
3476 "/"
3477 (js2-regexp-node-value n)
3478 "/")
3479 (if (js2-regexp-node-flags n)
3480 (insert (js2-regexp-node-flags n))))
3481
3482 (defstruct (js2-string-node
3483 (:include js2-node)
3484 (:constructor nil)
3485 (:constructor make-js2-string-node (&key (type js2-STRING)
3486 (pos (js2-current-token-beg))
3487 (len (- js2-ts-cursor
3488 (js2-current-token-beg)))
3489 (value (js2-current-token-string)))))
3490 "String literal.
3491 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3492 You can tell the quote type by looking at the first character."
3493 value) ; the characters of the string, including the quotes
3494
3495 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3496 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3497
3498 (defun js2-print-string-node (n i)
3499 (insert (js2-make-pad i)
3500 (js2-node-string n)))
3501
3502 (defstruct (js2-template-node
3503 (:include js2-node)
3504 (:constructor nil)
3505 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3506 beg len kids)))
3507 "Template literal."
3508 kids) ; `js2-string-node' is used for string segments, other nodes
3509 ; for substitutions inside.
3510
3511 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3512 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3513
3514 (defun js2-visit-template (n callback)
3515 "Visit the `js2-template-node' children of AST."
3516 (dolist (kid (js2-template-node-kids n))
3517 (js2-visit-ast kid callback)))
3518
3519 (defun js2-print-template (n i)
3520 (insert (js2-make-pad i))
3521 (dolist (kid (js2-template-node-kids n))
3522 (if (js2-string-node-p kid)
3523 (insert (js2-node-string kid))
3524 (js2-print-ast kid))))
3525
3526 (defstruct (js2-array-node
3527 (:include js2-node)
3528 (:constructor nil)
3529 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3530 (pos js2-ts-cursor)
3531 len elems)))
3532 "AST node for an array literal."
3533 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3534
3535 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3536 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3537
3538 (defun js2-visit-array-node (n v)
3539 (dolist (e (js2-array-node-elems n))
3540 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3541
3542 (defun js2-print-array-node (n i)
3543 (insert (js2-make-pad i) "[")
3544 (let ((elems (js2-array-node-elems n)))
3545 (js2-print-list elems)
3546 (when (and elems (null (car (last elems))))
3547 (insert ",")))
3548 (insert "]"))
3549
3550 (defstruct (js2-class-node
3551 (:include js2-node)
3552 (:constructor nil)
3553 (:constructor make-js2-class-node (&key (type js2-CLASS)
3554 (pos js2-ts-cursor)
3555 (form 'CLASS_STATEMENT)
3556 (name "")
3557 extends len elems)))
3558 "AST node for an class expression.
3559 `elems' is a list of `js2-object-prop-node', and `extends' is an
3560 optional `js2-expr-node'"
3561 form ; CLASS_{STATEMENT|EXPRESSION}
3562 name ; class name (a `js2-node-name', or nil if anonymous)
3563 extends ; class heritage (a `js2-expr-node', or nil if none)
3564 elems)
3565
3566 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3567 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3568
3569 (defun js2-visit-class-node (n v)
3570 (js2-visit-ast (js2-class-node-name n) v)
3571 (js2-visit-ast (js2-class-node-extends n) v)
3572 (dolist (e (js2-class-node-elems n))
3573 (js2-visit-ast e v)))
3574
3575 (defun js2-print-class-node (n i)
3576 (let* ((pad (js2-make-pad i))
3577 (name (js2-class-node-name n))
3578 (extends (js2-class-node-extends n))
3579 (elems (js2-class-node-elems n)))
3580 (insert pad "class")
3581 (when name
3582 (insert " ")
3583 (js2-print-ast name 0))
3584 (when extends
3585 (insert " extends ")
3586 (js2-print-ast extends))
3587 (insert " {")
3588 (dolist (elem elems)
3589 (insert "\n")
3590 (if (js2-node-get-prop elem 'STATIC)
3591 (progn (insert (js2-make-pad (1+ i)) "static ")
3592 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3593 (js2-print-ast elem (1+ i))))
3594 (insert "\n" pad "}")))
3595
3596 (defstruct (js2-object-node
3597 (:include js2-node)
3598 (:constructor nil)
3599 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3600 (pos js2-ts-cursor)
3601 len
3602 elems)))
3603 "AST node for an object literal expression.
3604 `elems' is a list of `js2-object-prop-node'."
3605 elems)
3606
3607 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3608 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3609
3610 (defun js2-visit-object-node (n v)
3611 (dolist (e (js2-object-node-elems n))
3612 (js2-visit-ast e v)))
3613
3614 (defun js2-print-object-node (n i)
3615 (insert (js2-make-pad i) "{")
3616 (js2-print-list (js2-object-node-elems n))
3617 (insert "}"))
3618
3619 (defstruct (js2-object-prop-node
3620 (:include js2-infix-node)
3621 (:constructor nil)
3622 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3623 (pos js2-ts-cursor)
3624 len left
3625 right op-pos)))
3626 "AST node for an object literal prop:value entry.
3627 The `left' field is the property: a name node, string node or number node.
3628 The `right' field is a `js2-node' representing the initializer value.
3629 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3630 and both fields have the same value.")
3631
3632 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3633 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3634
3635 (defun js2-print-object-prop-node (n i)
3636 (let* ((left (js2-object-prop-node-left n))
3637 (computed (not (or (js2-string-node-p left)
3638 (js2-number-node-p left)
3639 (js2-name-node-p left)))))
3640 (insert (js2-make-pad i))
3641 (if computed
3642 (insert "["))
3643 (js2-print-ast left 0)
3644 (if computed
3645 (insert "]"))
3646 (if (not (js2-node-get-prop n 'SHORTHAND))
3647 (progn
3648 (insert ": ")
3649 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3650
3651 (defstruct (js2-getter-setter-node
3652 (:include js2-infix-node)
3653 (:constructor nil)
3654 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3655 (pos js2-ts-cursor)
3656 len left right)))
3657 "AST node for a getter/setter property in an object literal.
3658 The `left' field is the `js2-name-node' naming the getter/setter prop.
3659 The `right' field is always an anonymous `js2-function-node' with a node
3660 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3661
3662 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3663 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3664
3665 (defun js2-print-getter-setter (n i)
3666 (let ((pad (js2-make-pad i))
3667 (left (js2-getter-setter-node-left n))
3668 (right (js2-getter-setter-node-right n)))
3669 (insert pad)
3670 (if (/= (js2-node-type n) js2-FUNCTION)
3671 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3672 (js2-print-ast left 0)
3673 (js2-print-ast right 0)))
3674
3675 (defstruct (js2-prop-get-node
3676 (:include js2-infix-node)
3677 (:constructor nil)
3678 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3679 (pos js2-ts-cursor)
3680 len left right)))
3681 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3682
3683 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3684 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3685
3686 (defun js2-visit-prop-get-node (n v)
3687 (js2-visit-ast (js2-prop-get-node-left n) v)
3688 (js2-visit-ast (js2-prop-get-node-right n) v))
3689
3690 (defun js2-print-prop-get-node (n i)
3691 (insert (js2-make-pad i))
3692 (js2-print-ast (js2-prop-get-node-left n) 0)
3693 (insert ".")
3694 (js2-print-ast (js2-prop-get-node-right n) 0))
3695
3696 (defstruct (js2-elem-get-node
3697 (:include js2-node)
3698 (:constructor nil)
3699 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3700 (pos js2-ts-cursor)
3701 len target element
3702 lb rb)))
3703 "AST node for an array index expression such as foo[bar]."
3704 target ; a `js2-node' - the expression preceding the "."
3705 element ; a `js2-node' - the expression in brackets
3706 lb ; position of left-bracket, nil if omitted
3707 rb) ; position of right-bracket, nil if omitted
3708
3709 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3710 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3711
3712 (defun js2-visit-elem-get-node (n v)
3713 (js2-visit-ast (js2-elem-get-node-target n) v)
3714 (js2-visit-ast (js2-elem-get-node-element n) v))
3715
3716 (defun js2-print-elem-get-node (n i)
3717 (insert (js2-make-pad i))
3718 (js2-print-ast (js2-elem-get-node-target n) 0)
3719 (insert "[")
3720 (js2-print-ast (js2-elem-get-node-element n) 0)
3721 (insert "]"))
3722
3723 (defstruct (js2-call-node
3724 (:include js2-node)
3725 (:constructor nil)
3726 (:constructor make-js2-call-node (&key (type js2-CALL)
3727 (pos js2-ts-cursor)
3728 len target args
3729 lp rp)))
3730 "AST node for a JavaScript function call."
3731 target ; a `js2-node' evaluating to the function to call
3732 args ; a Lisp list of `js2-node' arguments
3733 lp ; position of open-paren, or nil if missing
3734 rp) ; position of close-paren, or nil if missing
3735
3736 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3737 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3738
3739 (defun js2-visit-call-node (n v)
3740 (js2-visit-ast (js2-call-node-target n) v)
3741 (dolist (arg (js2-call-node-args n))
3742 (js2-visit-ast arg v)))
3743
3744 (defun js2-print-call-node (n i)
3745 (insert (js2-make-pad i))
3746 (js2-print-ast (js2-call-node-target n) 0)
3747 (insert "(")
3748 (js2-print-list (js2-call-node-args n))
3749 (insert ")"))
3750
3751 (defstruct (js2-yield-node
3752 (:include js2-node)
3753 (:constructor nil)
3754 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3755 (pos js2-ts-cursor)
3756 len value star-p)))
3757 "AST node for yield statement or expression."
3758 star-p ; whether it's yield*
3759 value) ; optional: value to be yielded
3760
3761 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3762 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3763
3764 (defun js2-visit-yield-node (n v)
3765 (js2-visit-ast (js2-yield-node-value n) v))
3766
3767 (defun js2-print-yield-node (n i)
3768 (insert (js2-make-pad i))
3769 (insert "yield")
3770 (when (js2-yield-node-star-p n)
3771 (insert "*"))
3772 (when (js2-yield-node-value n)
3773 (insert " ")
3774 (js2-print-ast (js2-yield-node-value n) 0)))
3775
3776 (defstruct (js2-paren-node
3777 (:include js2-node)
3778 (:constructor nil)
3779 (:constructor make-js2-paren-node (&key (type js2-LP)
3780 (pos js2-ts-cursor)
3781 len expr)))
3782 "AST node for a parenthesized expression.
3783 In particular, used when the parens are syntactically optional,
3784 as opposed to required parens such as those enclosing an if-conditional."
3785 expr) ; `js2-node'
3786
3787 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3788 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3789
3790 (defun js2-visit-paren-node (n v)
3791 (js2-visit-ast (js2-paren-node-expr n) v))
3792
3793 (defun js2-print-paren-node (n i)
3794 (insert (js2-make-pad i))
3795 (insert "(")
3796 (js2-print-ast (js2-paren-node-expr n) 0)
3797 (insert ")"))
3798
3799 (defstruct (js2-comp-node
3800 (:include js2-scope)
3801 (:constructor nil)
3802 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3803 (pos js2-ts-cursor)
3804 len result
3805 loops filters
3806 form)))
3807 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3808 result ; result expression (just after left-bracket)
3809 loops ; a Lisp list of `js2-comp-loop-node'
3810 filters ; a Lisp list of guard/filter expressions
3811 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3812 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3813 )
3814
3815 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3816 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3817
3818 (defun js2-visit-comp-node (n v)
3819 (js2-visit-ast (js2-comp-node-result n) v)
3820 (dolist (l (js2-comp-node-loops n))
3821 (js2-visit-ast l v))
3822 (dolist (f (js2-comp-node-filters n))
3823 (js2-visit-ast f v)))
3824
3825 (defun js2-print-comp-node (n i)
3826 (let ((pad (js2-make-pad i))
3827 (result (js2-comp-node-result n))
3828 (loops (js2-comp-node-loops n))
3829 (filters (js2-comp-node-filters n))
3830 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3831 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3832 (insert pad (if gen-p "(" "["))
3833 (when legacy-p
3834 (js2-print-ast result 0))
3835 (dolist (l loops)
3836 (when legacy-p
3837 (insert " "))
3838 (js2-print-ast l 0)
3839 (unless legacy-p
3840 (insert " ")))
3841 (dolist (f filters)
3842 (when legacy-p
3843 (insert " "))
3844 (insert "if (")
3845 (js2-print-ast f 0)
3846 (insert ")")
3847 (unless legacy-p
3848 (insert " ")))
3849 (unless legacy-p
3850 (js2-print-ast result 0))
3851 (insert (if gen-p ")" "]"))))
3852
3853 (defstruct (js2-comp-loop-node
3854 (:include js2-for-in-node)
3855 (:constructor nil)
3856 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3857 (pos js2-ts-cursor)
3858 len iterator
3859 object in-pos
3860 foreach-p
3861 each-pos
3862 forof-p
3863 lp rp)))
3864 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3865
3866 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3867 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3868
3869 (defun js2-visit-comp-loop (n v)
3870 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3871 (js2-visit-ast (js2-comp-loop-node-object n) v))
3872
3873 (defun js2-print-comp-loop (n _i)
3874 (insert "for ")
3875 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3876 (insert "(")
3877 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3878 (insert (if (js2-comp-loop-node-forof-p n)
3879 " of " " in "))
3880 (js2-print-ast (js2-comp-loop-node-object n) 0)
3881 (insert ")"))
3882
3883 (defstruct (js2-empty-expr-node
3884 (:include js2-node)
3885 (:constructor nil)
3886 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3887 (pos (js2-current-token-beg))
3888 len)))
3889 "AST node for an empty expression.")
3890
3891 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3892 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3893
3894 (defstruct (js2-xml-node
3895 (:include js2-block-node)
3896 (:constructor nil)
3897 (:constructor make-js2-xml-node (&key (type js2-XML)
3898 (pos (js2-current-token-beg))
3899 len kids)))
3900 "AST node for initial parse of E4X literals.
3901 The kids field is a list of XML fragments, each a `js2-string-node' or
3902 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3903
3904 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3905 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3906
3907 (defun js2-print-xml-node (n i)
3908 (dolist (kid (js2-xml-node-kids n))
3909 (js2-print-ast kid i)))
3910
3911 (defstruct (js2-xml-js-expr-node
3912 (:include js2-xml-node)
3913 (:constructor nil)
3914 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3915 (pos js2-ts-cursor)
3916 len expr)))
3917 "AST node for an embedded JavaScript {expression} in an E4X literal.
3918 The start and end fields correspond to the curly-braces."
3919 expr) ; a `js2-expr-node' of some sort
3920
3921 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3922 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3923
3924 (defun js2-visit-xml-js-expr (n v)
3925 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3926
3927 (defun js2-print-xml-js-expr (n i)
3928 (insert (js2-make-pad i))
3929 (insert "{")
3930 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3931 (insert "}"))
3932
3933 (defstruct (js2-xml-dot-query-node
3934 (:include js2-infix-node)
3935 (:constructor nil)
3936 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3937 (pos js2-ts-cursor)
3938 op-pos len left
3939 right rp)))
3940 "AST node for an E4X foo.(bar) filter expression.
3941 Note that the left-paren is automatically the character immediately
3942 following the dot (.) in the operator. No whitespace is permitted
3943 between the dot and the lp by the scanner."
3944 rp)
3945
3946 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3947 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3948
3949 (defun js2-print-xml-dot-query (n i)
3950 (insert (js2-make-pad i))
3951 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3952 (insert ".(")
3953 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3954 (insert ")"))
3955
3956 (defstruct (js2-xml-ref-node
3957 (:include js2-node)
3958 (:constructor nil)) ; abstract
3959 "Base type for E4X XML attribute-access or property-get expressions.
3960 Such expressions can take a variety of forms. The general syntax has
3961 three parts:
3962
3963 - (optional) an @ (specifying an attribute access)
3964 - (optional) a namespace (a `js2-name-node') and double-colon
3965 - (required) either a `js2-name-node' or a bracketed [expression]
3966
3967 The property-name expressions (examples: ns::name, @name) are
3968 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3969 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3970
3971 This node type (or more specifically, its subclasses) will sometimes
3972 be the right-hand child of a `js2-prop-get-node' or a
3973 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3974 The `js2-xml-ref-node' may also be a standalone primary expression with
3975 no explicit target, which is valid in certain expression contexts such as
3976
3977 company..employee.(@id < 100)
3978
3979 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3980 expression whose parent is a `js2-xml-dot-query-node'."
3981 namespace
3982 at-pos
3983 colon-pos)
3984
3985 (defsubst js2-xml-ref-node-attr-access-p (node)
3986 "Return non-nil if this expression began with an @-token."
3987 (and (numberp (js2-xml-ref-node-at-pos node))
3988 (plusp (js2-xml-ref-node-at-pos node))))
3989
3990 (defstruct (js2-xml-prop-ref-node
3991 (:include js2-xml-ref-node)
3992 (:constructor nil)
3993 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3994 (pos (js2-current-token-beg))
3995 len propname
3996 namespace at-pos
3997 colon-pos)))
3998 "AST node for an E4X XML [expr] property-ref expression.
3999 The JavaScript syntax is an optional @, an optional ns::, and a name.
4000
4001 [ '@' ] [ name '::' ] name
4002
4003 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4004 @ns::*, @*::attr, @*::*, and @*.
4005
4006 The node starts at the @ token, if present. Otherwise it starts at the
4007 namespace name. The node bounds extend through the closing right-bracket,
4008 or if it is missing due to a syntax error, through the end of the index
4009 expression."
4010 propname)
4011
4012 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4013 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4014
4015 (defun js2-visit-xml-prop-ref-node (n v)
4016 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4017 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4018
4019 (defun js2-print-xml-prop-ref-node (n i)
4020 (insert (js2-make-pad i))
4021 (if (js2-xml-ref-node-attr-access-p n)
4022 (insert "@"))
4023 (when (js2-xml-prop-ref-node-namespace n)
4024 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4025 (insert "::"))
4026 (if (js2-xml-prop-ref-node-propname n)
4027 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4028
4029 (defstruct (js2-xml-elem-ref-node
4030 (:include js2-xml-ref-node)
4031 (:constructor nil)
4032 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4033 (pos (js2-current-token-beg))
4034 len expr lb rb
4035 namespace at-pos
4036 colon-pos)))
4037 "AST node for an E4X XML [expr] member-ref expression.
4038 Syntax:
4039
4040 [ '@' ] [ name '::' ] '[' expr ']'
4041
4042 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4043
4044 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4045 is not a legal E4X XML element-ref expression, since it's already used
4046 for standard JavaScript element-get array indexing. Hence, a
4047 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4048 non-nil namespace node, or both.
4049
4050 The node starts at the @ token, if present. Otherwise it starts
4051 at the namespace name. The node bounds extend through the closing
4052 right-bracket, or if it is missing due to a syntax error, through the
4053 end of the index expression."
4054 expr ; the bracketed index expression
4055 lb
4056 rb)
4057
4058 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4059 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4060
4061 (defun js2-visit-xml-elem-ref-node (n v)
4062 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4063 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4064
4065 (defun js2-print-xml-elem-ref-node (n i)
4066 (insert (js2-make-pad i))
4067 (if (js2-xml-ref-node-attr-access-p n)
4068 (insert "@"))
4069 (when (js2-xml-elem-ref-node-namespace n)
4070 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4071 (insert "::"))
4072 (insert "[")
4073 (if (js2-xml-elem-ref-node-expr n)
4074 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4075 (insert "]"))
4076
4077 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4078
4079 (defstruct (js2-xml-start-tag-node
4080 (:include js2-xml-node)
4081 (:constructor nil)
4082 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4083 (pos js2-ts-cursor)
4084 len name attrs kids
4085 empty-p)))
4086 "AST node for an XML start-tag. Not currently used.
4087 The `kids' field is a Lisp list of child content nodes."
4088 name ; a `js2-xml-name-node'
4089 attrs ; a Lisp list of `js2-xml-attr-node'
4090 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4091
4092 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4093 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4094
4095 (defun js2-visit-xml-start-tag (n v)
4096 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4097 (dolist (attr (js2-xml-start-tag-node-attrs n))
4098 (js2-visit-ast attr v))
4099 (js2-visit-block n v))
4100
4101 (defun js2-print-xml-start-tag (n i)
4102 (insert (js2-make-pad i) "<")
4103 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4104 (when (js2-xml-start-tag-node-attrs n)
4105 (insert " ")
4106 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4107 (insert ">"))
4108
4109 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4110 ;; and add the end-tag to the kids list of the parent as well.
4111 (defstruct (js2-xml-end-tag-node
4112 (:include js2-xml-node)
4113 (:constructor nil)
4114 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4115 (pos js2-ts-cursor)
4116 len name)))
4117 "AST node for an XML end-tag. Not currently used."
4118 name) ; a `js2-xml-name-node'
4119
4120 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4121 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4122
4123 (defun js2-visit-xml-end-tag (n v)
4124 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4125
4126 (defun js2-print-xml-end-tag (n i)
4127 (insert (js2-make-pad i))
4128 (insert "</")
4129 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4130 (insert ">"))
4131
4132 (defstruct (js2-xml-name-node
4133 (:include js2-xml-node)
4134 (:constructor nil)
4135 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4136 (pos js2-ts-cursor)
4137 len namespace kids)))
4138 "AST node for an E4X XML name. Not currently used.
4139 Any XML name can be qualified with a namespace, hence the namespace field.
4140 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4141 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4142 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4143 namespace) ; a `js2-string-node'
4144
4145 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4146 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4147
4148 (defun js2-visit-xml-name-node (n v)
4149 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4150
4151 (defun js2-print-xml-name-node (n i)
4152 (insert (js2-make-pad i))
4153 (when (js2-xml-name-node-namespace n)
4154 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4155 (insert "::"))
4156 (dolist (kid (js2-xml-name-node-kids n))
4157 (js2-print-ast kid 0)))
4158
4159 (defstruct (js2-xml-pi-node
4160 (:include js2-xml-node)
4161 (:constructor nil)
4162 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4163 (pos js2-ts-cursor)
4164 len name attrs)))
4165 "AST node for an E4X XML processing instruction. Not currently used."
4166 name ; a `js2-xml-name-node'
4167 attrs) ; a list of `js2-xml-attr-node'
4168
4169 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4170 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4171
4172 (defun js2-visit-xml-pi-node (n v)
4173 (js2-visit-ast (js2-xml-pi-node-name n) v)
4174 (dolist (attr (js2-xml-pi-node-attrs n))
4175 (js2-visit-ast attr v)))
4176
4177 (defun js2-print-xml-pi-node (n i)
4178 (insert (js2-make-pad i) "<?")
4179 (js2-print-ast (js2-xml-pi-node-name n))
4180 (when (js2-xml-pi-node-attrs n)
4181 (insert " ")
4182 (js2-print-list (js2-xml-pi-node-attrs n)))
4183 (insert "?>"))
4184
4185 (defstruct (js2-xml-cdata-node
4186 (:include js2-xml-node)
4187 (:constructor nil)
4188 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4189 (pos js2-ts-cursor)
4190 len content)))
4191 "AST node for a CDATA escape section. Not currently used."
4192 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4193
4194 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4195 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4196
4197 (defun js2-visit-xml-cdata-node (n v)
4198 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4199
4200 (defun js2-print-xml-cdata-node (n i)
4201 (insert (js2-make-pad i))
4202 (js2-print-ast (js2-xml-cdata-node-content n)))
4203
4204 (defstruct (js2-xml-attr-node
4205 (:include js2-xml-node)
4206 (:constructor nil)
4207 (:constructor make-js2-attr-node (&key (type js2-XML)
4208 (pos js2-ts-cursor)
4209 len name value
4210 eq-pos quote-type)))
4211 "AST node representing a foo='bar' XML attribute value. Not yet used."
4212 name ; a `js2-xml-name-node'
4213 value ; a `js2-xml-name-node'
4214 eq-pos ; buffer position of "=" sign
4215 quote-type) ; 'single or 'double
4216
4217 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4218 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4219
4220 (defun js2-visit-xml-attr-node (n v)
4221 (js2-visit-ast (js2-xml-attr-node-name n) v)
4222 (js2-visit-ast (js2-xml-attr-node-value n) v))
4223
4224 (defun js2-print-xml-attr-node (n i)
4225 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4226 "'"
4227 "\"")))
4228 (insert (js2-make-pad i))
4229 (js2-print-ast (js2-xml-attr-node-name n) 0)
4230 (insert "=" quote)
4231 (js2-print-ast (js2-xml-attr-node-value n) 0)
4232 (insert quote)))
4233
4234 (defstruct (js2-xml-text-node
4235 (:include js2-xml-node)
4236 (:constructor nil)
4237 (:constructor make-js2-text-node (&key (type js2-XML)
4238 (pos js2-ts-cursor)
4239 len content)))
4240 "AST node for an E4X XML text node. Not currently used."
4241 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4242
4243 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4244 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4245
4246 (defun js2-visit-xml-text-node (n v)
4247 (js2-visit-ast (js2-xml-text-node-content n) v))
4248
4249 (defun js2-print-xml-text-node (n i)
4250 (insert (js2-make-pad i))
4251 (dolist (kid (js2-xml-text-node-content n))
4252 (js2-print-ast kid)))
4253
4254 (defstruct (js2-xml-comment-node
4255 (:include js2-xml-node)
4256 (:constructor nil)
4257 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4258 (pos js2-ts-cursor)
4259 len)))
4260 "AST node for E4X XML comment. Not currently used.")
4261
4262 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4263 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4264
4265 (defun js2-print-xml-comment (n i)
4266 (insert (js2-make-pad i)
4267 (js2-node-string n)))
4268
4269 ;;; Node utilities
4270
4271 (defsubst js2-node-line (n)
4272 "Fetch the source line number at the start of node N.
4273 This is O(n) in the length of the source buffer; use prudently."
4274 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4275
4276 (defsubst js2-block-node-kid (n i)
4277 "Return child I of node N, or nil if there aren't that many."
4278 (nth i (js2-block-node-kids n)))
4279
4280 (defsubst js2-block-node-first (n)
4281 "Return first child of block node N, or nil if there is none."
4282 (first (js2-block-node-kids n)))
4283
4284 (defun js2-node-root (n)
4285 "Return the root of the AST containing N.
4286 If N has no parent pointer, returns N."
4287 (let ((parent (js2-node-parent n)))
4288 (if parent
4289 (js2-node-root parent)
4290 n)))
4291
4292 (defsubst js2-node-short-name (n)
4293 "Return the short name of node N as a string, e.g. `js2-if-node'."
4294 (substring (symbol-name (aref n 0))
4295 (length "cl-struct-")))
4296
4297 (defun js2-node-child-list (node)
4298 "Return the child list for NODE, a Lisp list of nodes.
4299 Works for block nodes, array nodes, obj literals, funarg lists,
4300 var decls and try nodes (for catch clauses). Note that you should call
4301 `js2-block-node-kids' on the function body for the body statements.
4302 Returns nil for zero-length child lists or unsupported nodes."
4303 (cond
4304 ((js2-function-node-p node)
4305 (js2-function-node-params node))
4306 ((js2-block-node-p node)
4307 (js2-block-node-kids node))
4308 ((js2-try-node-p node)
4309 (js2-try-node-catch-clauses node))
4310 ((js2-array-node-p node)
4311 (js2-array-node-elems node))
4312 ((js2-object-node-p node)
4313 (js2-object-node-elems node))
4314 ((js2-call-node-p node)
4315 (js2-call-node-args node))
4316 ((js2-new-node-p node)
4317 (js2-new-node-args node))
4318 ((js2-var-decl-node-p node)
4319 (js2-var-decl-node-kids node))
4320 (t
4321 nil)))
4322
4323 (defun js2-node-set-child-list (node kids)
4324 "Set the child list for NODE to KIDS."
4325 (cond
4326 ((js2-function-node-p node)
4327 (setf (js2-function-node-params node) kids))
4328 ((js2-block-node-p node)
4329 (setf (js2-block-node-kids node) kids))
4330 ((js2-try-node-p node)
4331 (setf (js2-try-node-catch-clauses node) kids))
4332 ((js2-array-node-p node)
4333 (setf (js2-array-node-elems node) kids))
4334 ((js2-object-node-p node)
4335 (setf (js2-object-node-elems node) kids))
4336 ((js2-call-node-p node)
4337 (setf (js2-call-node-args node) kids))
4338 ((js2-new-node-p node)
4339 (setf (js2-new-node-args node) kids))
4340 ((js2-var-decl-node-p node)
4341 (setf (js2-var-decl-node-kids node) kids))
4342 (t
4343 (error "Unsupported node type: %s" (js2-node-short-name node))))
4344 kids)
4345
4346 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4347 (defconst js2-paren-expr-nodes
4348 '(cl-struct-js2-comp-loop-node
4349 cl-struct-js2-comp-node
4350 cl-struct-js2-call-node
4351 cl-struct-js2-catch-node
4352 cl-struct-js2-do-node
4353 cl-struct-js2-elem-get-node
4354 cl-struct-js2-for-in-node
4355 cl-struct-js2-for-node
4356 cl-struct-js2-function-node
4357 cl-struct-js2-if-node
4358 cl-struct-js2-let-node
4359 cl-struct-js2-new-node
4360 cl-struct-js2-paren-node
4361 cl-struct-js2-switch-node
4362 cl-struct-js2-while-node
4363 cl-struct-js2-with-node
4364 cl-struct-js2-xml-dot-query-node)
4365 "Node types that can have a parenthesized child expression.
4366 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4367
4368 (defsubst js2-paren-expr-node-p (node)
4369 "Return t for nodes that typically have a parenthesized child expression.
4370 Useful for computing the indentation anchors for arg-lists and conditions.
4371 Note that it may return a false positive, for instance when NODE is
4372 a `js2-new-node' and there are no arguments or parentheses."
4373 (memq (aref node 0) js2-paren-expr-nodes))
4374
4375 ;; Fake polymorphism... yech.
4376 (defun js2-node-lp (node)
4377 "Return relative left-paren position for NODE, if applicable.
4378 For `js2-elem-get-node' structs, returns left-bracket position.
4379 Note that the position may be nil in the case of a parse error."
4380 (cond
4381 ((js2-elem-get-node-p node)
4382 (js2-elem-get-node-lb node))
4383 ((js2-loop-node-p node)
4384 (js2-loop-node-lp node))
4385 ((js2-function-node-p node)
4386 (js2-function-node-lp node))
4387 ((js2-if-node-p node)
4388 (js2-if-node-lp node))
4389 ((js2-new-node-p node)
4390 (js2-new-node-lp node))
4391 ((js2-call-node-p node)
4392 (js2-call-node-lp node))
4393 ((js2-paren-node-p node)
4394 0)
4395 ((js2-switch-node-p node)
4396 (js2-switch-node-lp node))
4397 ((js2-catch-node-p node)
4398 (js2-catch-node-lp node))
4399 ((js2-let-node-p node)
4400 (js2-let-node-lp node))
4401 ((js2-comp-node-p node)
4402 0)
4403 ((js2-with-node-p node)
4404 (js2-with-node-lp node))
4405 ((js2-xml-dot-query-node-p node)
4406 (1+ (js2-infix-node-op-pos node)))
4407 (t
4408 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4409
4410 ;; Fake polymorphism... blech.
4411 (defun js2-node-rp (node)
4412 "Return relative right-paren position for NODE, if applicable.
4413 For `js2-elem-get-node' structs, returns right-bracket position.
4414 Note that the position may be nil in the case of a parse error."
4415 (cond
4416 ((js2-elem-get-node-p node)
4417 (js2-elem-get-node-rb node))
4418 ((js2-loop-node-p node)
4419 (js2-loop-node-rp node))
4420 ((js2-function-node-p node)
4421 (js2-function-node-rp node))
4422 ((js2-if-node-p node)
4423 (js2-if-node-rp node))
4424 ((js2-new-node-p node)
4425 (js2-new-node-rp node))
4426 ((js2-call-node-p node)
4427 (js2-call-node-rp node))
4428 ((js2-paren-node-p node)
4429 (1- (js2-node-len node)))
4430 ((js2-switch-node-p node)
4431 (js2-switch-node-rp node))
4432 ((js2-catch-node-p node)
4433 (js2-catch-node-rp node))
4434 ((js2-let-node-p node)
4435 (js2-let-node-rp node))
4436 ((js2-comp-node-p node)
4437 (1- (js2-node-len node)))
4438 ((js2-with-node-p node)
4439 (js2-with-node-rp node))
4440 ((js2-xml-dot-query-node-p node)
4441 (1+ (js2-xml-dot-query-node-rp node)))
4442 (t
4443 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4444
4445 (defsubst js2-node-first-child (node)
4446 "Return the first element of `js2-node-child-list' for NODE."
4447 (car (js2-node-child-list node)))
4448
4449 (defsubst js2-node-last-child (node)
4450 "Return the last element of `js2-node-last-child' for NODE."
4451 (car (last (js2-node-child-list node))))
4452
4453 (defun js2-node-prev-sibling (node)
4454 "Return the previous statement in parent.
4455 Works for parents supported by `js2-node-child-list'.
4456 Returns nil if NODE is not in the parent, or PARENT is
4457 not a supported node, or if NODE is the first child."
4458 (let* ((p (js2-node-parent node))
4459 (kids (js2-node-child-list p))
4460 (sib (car kids)))
4461 (while (and kids
4462 (not (eq node (cadr kids))))
4463 (setq kids (cdr kids)
4464 sib (car kids)))
4465 sib))
4466
4467 (defun js2-node-next-sibling (node)
4468 "Return the next statement in parent block.
4469 Returns nil if NODE is not in the block, or PARENT is not
4470 a block node, or if NODE is the last statement."
4471 (let* ((p (js2-node-parent node))
4472 (kids (js2-node-child-list p)))
4473 (while (and kids
4474 (not (eq node (car kids))))
4475 (setq kids (cdr kids)))
4476 (cadr kids)))
4477
4478 (defun js2-node-find-child-before (pos parent &optional after)
4479 "Find the last child that starts before POS in parent.
4480 If AFTER is non-nil, returns first child starting after POS.
4481 POS is an absolute buffer position. PARENT is any node
4482 supported by `js2-node-child-list'.
4483 Returns nil if no applicable child is found."
4484 (let ((kids (if (js2-function-node-p parent)
4485 (js2-block-node-kids (js2-function-node-body parent))
4486 (js2-node-child-list parent)))
4487 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4488 (js2-function-node-body parent)
4489 parent)))
4490 kid result fn
4491 (continue t))
4492 (setq fn (if after '>= '<))
4493 (while (and kids continue)
4494 (setq kid (car kids))
4495 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4496 (setq result kid
4497 continue (not after))
4498 (setq continue after))
4499 (setq kids (cdr kids)))
4500 result))
4501
4502 (defun js2-node-find-child-after (pos parent)
4503 "Find first child that starts after POS in parent.
4504 POS is an absolute buffer position. PARENT is any node
4505 supported by `js2-node-child-list'.
4506 Returns nil if no applicable child is found."
4507 (js2-node-find-child-before pos parent 'after))
4508
4509 (defun js2-node-replace-child (pos parent new-node)
4510 "Replace node at index POS in PARENT with NEW-NODE.
4511 Only works for parents supported by `js2-node-child-list'."
4512 (let ((kids (js2-node-child-list parent))
4513 (i 0))
4514 (while (< i pos)
4515 (setq kids (cdr kids)
4516 i (1+ i)))
4517 (setcar kids new-node)
4518 (js2-node-add-children parent new-node)))
4519
4520 (defun js2-node-buffer (n)
4521 "Return the buffer associated with AST N.
4522 Returns nil if the buffer is not set as a property on the root
4523 node, or if parent links were not recorded during parsing."
4524 (let ((root (js2-node-root n)))
4525 (and root
4526 (js2-ast-root-p root)
4527 (js2-ast-root-buffer root))))
4528
4529 (defun js2-block-node-push (n kid)
4530 "Push js2-node KID onto the end of js2-block-node N's child list.
4531 KID is always added to the -end- of the kids list.
4532 Function also calls `js2-node-add-children' to add the parent link."
4533 (let ((kids (js2-node-child-list n)))
4534 (if kids
4535 (setcdr kids (nconc (cdr kids) (list kid)))
4536 (js2-node-set-child-list n (list kid)))
4537 (js2-node-add-children n kid)))
4538
4539 (defun js2-node-string (node)
4540 (with-current-buffer (or (js2-node-buffer node)
4541 (error "No buffer available for node %s" node))
4542 (let ((pos (js2-node-abs-pos node)))
4543 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4544
4545 ;; Container for storing the node we're looking for in a traversal.
4546 (js2-deflocal js2-discovered-node nil)
4547
4548 ;; Keep track of absolute node position during traversals.
4549 (js2-deflocal js2-visitor-offset nil)
4550
4551 (js2-deflocal js2-node-search-point nil)
4552
4553 (when js2-mode-dev-mode-p
4554 (defun js2-find-node-at-point ()
4555 (interactive)
4556 (let ((node (js2-node-at-point)))
4557 (message "%s" (or node "No node found at point"))))
4558 (defun js2-node-name-at-point ()
4559 (interactive)
4560 (let ((node (js2-node-at-point)))
4561 (message "%s" (if node
4562 (js2-node-short-name node)
4563 "No node found at point.")))))
4564
4565 (defun js2-node-at-point (&optional pos skip-comments)
4566 "Return AST node at POS, a buffer position, defaulting to current point.
4567 The `js2-mode-ast' variable must be set to the current parse tree.
4568 Signals an error if the AST (`js2-mode-ast') is nil.
4569 Always returns a node - if it can't find one, it returns the root.
4570 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4571 (let ((ast js2-mode-ast)
4572 result)
4573 (unless ast
4574 (error "No JavaScript AST available"))
4575 ;; Look through comments first, since they may be inside nodes that
4576 ;; would otherwise report a match.
4577 (setq pos (or pos (point))
4578 result (if (> pos (js2-node-abs-end ast))
4579 ast
4580 (if (not skip-comments)
4581 (js2-comment-at-point pos))))
4582 (unless result
4583 (setq js2-discovered-node nil
4584 js2-visitor-offset 0
4585 js2-node-search-point pos)
4586 (unwind-protect
4587 (catch 'js2-visit-done
4588 (js2-visit-ast ast #'js2-node-at-point-visitor))
4589 (setq js2-visitor-offset nil
4590 js2-node-search-point nil))
4591 (setq result js2-discovered-node))
4592 ;; may have found a comment beyond end of last child node,
4593 ;; since visiting the ast-root looks at the comment-list last.
4594 (if (and skip-comments
4595 (js2-comment-node-p result))
4596 (setq result nil))
4597 (or result js2-mode-ast)))
4598
4599 (defun js2-node-at-point-visitor (node end-p)
4600 (let ((rel-pos (js2-node-pos node))
4601 abs-pos
4602 abs-end
4603 (point js2-node-search-point))
4604 (cond
4605 (end-p
4606 ;; this evaluates to a non-nil return value, even if it's zero
4607 (decf js2-visitor-offset rel-pos))
4608 ;; we already looked for comments before visiting, and don't want them now
4609 ((js2-comment-node-p node)
4610 nil)
4611 (t
4612 (setq abs-pos (incf js2-visitor-offset rel-pos)
4613 ;; we only want to use the node if the point is before
4614 ;; the last character position in the node, so we decrement
4615 ;; the absolute end by 1.
4616 abs-end (+ abs-pos (js2-node-len node) -1))
4617 (cond
4618 ;; If this node starts after search-point, stop the search.
4619 ((> abs-pos point)
4620 (throw 'js2-visit-done nil))
4621 ;; If this node ends before the search-point, don't check kids.
4622 ((> point abs-end)
4623 nil)
4624 (t
4625 ;; Otherwise point is within this node, possibly in a child.
4626 (setq js2-discovered-node node)
4627 t)))))) ; keep processing kids to look for more specific match
4628
4629 (defsubst js2-block-comment-p (node)
4630 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4631 (and (js2-comment-node-p node)
4632 (memq (js2-comment-node-format node) '(jsdoc block))))
4633
4634 ;; TODO: put the comments in a vector and binary-search them instead
4635 (defun js2-comment-at-point (&optional pos)
4636 "Look through scanned comment nodes for one containing POS.
4637 POS is a buffer position that defaults to current point.
4638 Function returns nil if POS was not in any comment node."
4639 (let ((ast js2-mode-ast)
4640 (x (or pos (point)))
4641 beg end)
4642 (unless ast
4643 (error "No JavaScript AST available"))
4644 (catch 'done
4645 ;; Comments are stored in lexical order.
4646 (dolist (comment (js2-ast-root-comments ast) nil)
4647 (setq beg (js2-node-abs-pos comment)
4648 end (+ beg (js2-node-len comment)))
4649 (if (and (>= x beg)
4650 (<= x end))
4651 (throw 'done comment))))))
4652
4653 (defun js2-mode-find-parent-fn (node)
4654 "Find function enclosing NODE.
4655 Returns nil if NODE is not inside a function."
4656 (setq node (js2-node-parent node))
4657 (while (and node (not (js2-function-node-p node)))
4658 (setq node (js2-node-parent node)))
4659 (and (js2-function-node-p node) node))
4660
4661 (defun js2-mode-find-enclosing-fn (node)
4662 "Find function or root enclosing NODE."
4663 (if (js2-ast-root-p node)
4664 node
4665 (setq node (js2-node-parent node))
4666 (while (not (or (js2-ast-root-p node)
4667 (js2-function-node-p node)))
4668 (setq node (js2-node-parent node)))
4669 node))
4670
4671 (defun js2-mode-find-enclosing-node (beg end)
4672 "Find node fully enclosing BEG and END."
4673 (let ((node (js2-node-at-point beg))
4674 pos
4675 (continue t))
4676 (while continue
4677 (if (or (js2-ast-root-p node)
4678 (and
4679 (<= (setq pos (js2-node-abs-pos node)) beg)
4680 (>= (+ pos (js2-node-len node)) end)))
4681 (setq continue nil)
4682 (setq node (js2-node-parent node))))
4683 node))
4684
4685 (defun js2-node-parent-script-or-fn (node)
4686 "Find script or function immediately enclosing NODE.
4687 If NODE is the ast-root, returns nil."
4688 (if (js2-ast-root-p node)
4689 nil
4690 (setq node (js2-node-parent node))
4691 (while (and node (not (or (js2-function-node-p node)
4692 (js2-script-node-p node))))
4693 (setq node (js2-node-parent node)))
4694 node))
4695
4696 (defun js2-node-is-descendant (node ancestor)
4697 "Return t if NODE is a descendant of ANCESTOR."
4698 (while (and node
4699 (not (eq node ancestor)))
4700 (setq node (js2-node-parent node)))
4701 node)
4702
4703 ;;; visitor infrastructure
4704
4705 (defun js2-visit-none (_node _callback)
4706 "Visitor for AST node that have no node children."
4707 nil)
4708
4709 (defun js2-print-none (_node _indent)
4710 "Visitor for AST node with no printed representation.")
4711
4712 (defun js2-print-body (node indent)
4713 "Print a statement, or a block without braces."
4714 (if (js2-block-node-p node)
4715 (dolist (kid (js2-block-node-kids node))
4716 (js2-print-ast kid indent))
4717 (js2-print-ast node indent)))
4718
4719 (defun js2-print-list (args &optional delimiter)
4720 (loop with len = (length args)
4721 for arg in args
4722 for count from 1
4723 do
4724 (when arg (js2-print-ast arg 0))
4725 (if (< count len)
4726 (insert (or delimiter ", ")))))
4727
4728 (defun js2-print-tree (ast)
4729 "Prints an AST to the current buffer.
4730 Makes `js2-ast-parent-nodes' available to the printer functions."
4731 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4732 (js2-print-ast ast)))
4733
4734 (defun js2-print-ast (node &optional indent)
4735 "Helper function for printing AST nodes.
4736 Requires `js2-ast-parent-nodes' to be non-nil.
4737 You should use `js2-print-tree' instead of this function."
4738 (let ((printer (get (aref node 0) 'js2-printer))
4739 (i (or indent 0)))
4740 ;; TODO: wedge comments in here somewhere
4741 (if printer
4742 (funcall printer node i))))
4743
4744 (defconst js2-side-effecting-tokens
4745 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4746 (dolist (tt (list js2-ASSIGN
4747 js2-ASSIGN_ADD
4748 js2-ASSIGN_BITAND
4749 js2-ASSIGN_BITOR
4750 js2-ASSIGN_BITXOR
4751 js2-ASSIGN_DIV
4752 js2-ASSIGN_LSH
4753 js2-ASSIGN_MOD
4754 js2-ASSIGN_MUL
4755 js2-ASSIGN_RSH
4756 js2-ASSIGN_SUB
4757 js2-ASSIGN_URSH
4758 js2-BLOCK
4759 js2-BREAK
4760 js2-CALL
4761 js2-CATCH
4762 js2-CATCH_SCOPE
4763 js2-CLASS
4764 js2-CONST
4765 js2-CONTINUE
4766 js2-DEBUGGER
4767 js2-DEC
4768 js2-DELPROP
4769 js2-DEL_REF
4770 js2-DO
4771 js2-ELSE
4772 js2-EMPTY
4773 js2-ENTERWITH
4774 js2-EXPORT
4775 js2-EXPR_RESULT
4776 js2-FINALLY
4777 js2-FOR
4778 js2-FUNCTION
4779 js2-GOTO
4780 js2-IF
4781 js2-IFEQ
4782 js2-IFNE
4783 js2-IMPORT
4784 js2-INC
4785 js2-JSR
4786 js2-LABEL
4787 js2-LEAVEWITH
4788 js2-LET
4789 js2-LETEXPR
4790 js2-LOCAL_BLOCK
4791 js2-LOOP
4792 js2-NEW
4793 js2-REF_CALL
4794 js2-RETHROW
4795 js2-RETURN
4796 js2-RETURN_RESULT
4797 js2-SEMI
4798 js2-SETELEM
4799 js2-SETELEM_OP
4800 js2-SETNAME
4801 js2-SETPROP
4802 js2-SETPROP_OP
4803 js2-SETVAR
4804 js2-SET_REF
4805 js2-SET_REF_OP
4806 js2-SWITCH
4807 js2-TARGET
4808 js2-THROW
4809 js2-TRY
4810 js2-VAR
4811 js2-WHILE
4812 js2-WITH
4813 js2-WITHEXPR
4814 js2-YIELD))
4815 (aset tokens tt t))
4816 (if js2-instanceof-has-side-effects
4817 (aset tokens js2-INSTANCEOF t))
4818 tokens))
4819
4820 (defun js2-node-has-side-effects (node)
4821 "Return t if NODE has side effects."
4822 (when node ; makes it easier to handle malformed expressions
4823 (let ((tt (js2-node-type node)))
4824 (cond
4825 ;; This doubtless needs some work, since EXPR_VOID is used
4826 ;; in several ways in Rhino and I may not have caught them all.
4827 ;; I'll wait for people to notice incorrect warnings.
4828 ((and (= tt js2-EXPR_VOID)
4829 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4830 (let ((expr (js2-expr-stmt-node-expr node)))
4831 (or (js2-node-has-side-effects expr)
4832 (when (js2-string-node-p expr)
4833 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4834 ((= tt js2-COMMA)
4835 (js2-node-has-side-effects (js2-infix-node-right node)))
4836 ((or (= tt js2-AND)
4837 (= tt js2-OR))
4838 (or (js2-node-has-side-effects (js2-infix-node-right node))
4839 (js2-node-has-side-effects (js2-infix-node-left node))))
4840 ((= tt js2-HOOK)
4841 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4842 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4843 ((js2-paren-node-p node)
4844 (js2-node-has-side-effects (js2-paren-node-expr node)))
4845 ((= tt js2-ERROR) ; avoid cascaded error messages
4846 nil)
4847 (t
4848 (aref js2-side-effecting-tokens tt))))))
4849
4850 (defconst js2-stmt-node-types
4851 (list js2-BLOCK
4852 js2-BREAK
4853 js2-CONTINUE
4854 js2-DEFAULT ; e4x "default xml namespace" statement
4855 js2-DO
4856 js2-EXPR_RESULT
4857 js2-EXPR_VOID
4858 js2-FOR
4859 js2-IF
4860 js2-RETURN
4861 js2-SWITCH
4862 js2-THROW
4863 js2-TRY
4864 js2-WHILE
4865 js2-WITH)
4866 "Node types that only appear in statement contexts.
4867 The list does not include nodes that always appear as the child
4868 of another specific statement type, such as switch-cases,
4869 catch and finally blocks, and else-clauses. The list also excludes
4870 nodes like yield, let and var, which may appear in either expression
4871 or statement context, and in the latter context always have a
4872 `js2-expr-stmt-node' parent. Finally, the list does not include
4873 functions or scripts, which are treated separately from statements
4874 by the JavaScript parser and runtime.")
4875
4876 (defun js2-stmt-node-p (node)
4877 "Heuristic for figuring out if NODE is a statement.
4878 Some node types can appear in either an expression context or a
4879 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4880 For these node types in a statement context, the parent will be a
4881 `js2-expr-stmt-node'.
4882 Functions aren't included in the check."
4883 (memq (js2-node-type node) js2-stmt-node-types))
4884
4885 (defun js2-mode-find-first-stmt (node)
4886 "Search upward starting from NODE looking for a statement.
4887 For purposes of this function, a `js2-function-node' counts."
4888 (while (not (or (js2-stmt-node-p node)
4889 (js2-function-node-p node)))
4890 (setq node (js2-node-parent node)))
4891 node)
4892
4893 (defun js2-node-parent-stmt (node)
4894 "Return the node's first ancestor that is a statement.
4895 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4896 appearing in a statement context will have a parent that is a
4897 `js2-expr-stmt-node' that will be returned by this function."
4898 (let ((parent (js2-node-parent node)))
4899 (if (or (null parent)
4900 (js2-stmt-node-p parent)
4901 (and (js2-function-node-p parent)
4902 (not (eq (js2-function-node-form parent)
4903 'FUNCTION_EXPRESSION))))
4904 parent
4905 (js2-node-parent-stmt parent))))
4906
4907 ;; In the Mozilla Rhino sources, Roshan James writes:
4908 ;; Does consistent-return analysis on the function body when strict mode is
4909 ;; enabled.
4910 ;;
4911 ;; function (x) { return (x+1) }
4912 ;;
4913 ;; is ok, but
4914 ;;
4915 ;; function (x) { if (x < 0) return (x+1); }
4916 ;;
4917 ;; is not because the function can potentially return a value when the
4918 ;; condition is satisfied and if not, the function does not explicitly
4919 ;; return a value.
4920 ;;
4921 ;; This extends to checking mismatches such as "return" and "return <value>"
4922 ;; used in the same function. Warnings are not emitted if inconsistent
4923 ;; returns exist in code that can be statically shown to be unreachable.
4924 ;; Ex.
4925 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4926 ;;
4927 ;; emits no warning. However if the loop had a break statement, then a
4928 ;; warning would be emitted.
4929 ;;
4930 ;; The consistency analysis looks at control structures such as loops, ifs,
4931 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4932 ;; warns the user about an inconsistent set of termination possibilities.
4933 ;;
4934 ;; These flags enumerate the possible ways a statement/function can
4935 ;; terminate. These flags are used by endCheck() and by the Parser to
4936 ;; detect inconsistent return usage.
4937 ;;
4938 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4939 ;; able to execute (example: throw, continue)
4940 ;;
4941 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4942 ;; next one. Statement such as return dont. A compound statement may have
4943 ;; some branch that drops off control to the next statement.
4944 ;;
4945 ;; END_RETURNS indicates that the statement can return with no value.
4946 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4947 ;;
4948 ;; A compound statement such as
4949 ;; if (condition) {
4950 ;; return value;
4951 ;; }
4952 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4953
4954 (defconst js2-END_UNREACHED 0)
4955 (defconst js2-END_DROPS_OFF 1)
4956 (defconst js2-END_RETURNS 2)
4957 (defconst js2-END_RETURNS_VALUE 4)
4958 (defconst js2-END_YIELDS 8)
4959
4960 (defun js2-has-consistent-return-usage (node)
4961 "Check that every return usage in a function body is consistent.
4962 Returns t if the function satisfies strict mode requirement."
4963 (let ((n (js2-end-check node)))
4964 ;; either it doesn't return a value in any branch...
4965 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4966 ;; or it returns a value (or is unreached) at every branch
4967 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4968 js2-END_RETURNS
4969 js2-END_YIELDS)))))
4970
4971 (defun js2-end-check-if (node)
4972 "Ensure that return usage in then/else blocks is consistent.
4973 If there is no else block, then the return statement can fall through.
4974 Returns logical OR of END_* flags"
4975 (let ((th (js2-if-node-then-part node))
4976 (el (js2-if-node-else-part node)))
4977 (if (null th)
4978 js2-END_UNREACHED
4979 (logior (js2-end-check th) (if el
4980 (js2-end-check el)
4981 js2-END_DROPS_OFF)))))
4982
4983 (defun js2-end-check-switch (node)
4984 "Consistency of return statements is checked between the case statements.
4985 If there is no default, then the switch can fall through. If there is a
4986 default, we check to see if all code paths in the default return or if
4987 there is a code path that can fall through.
4988 Returns logical OR of END_* flags."
4989 (let ((rv js2-END_UNREACHED)
4990 default-case)
4991 ;; examine the cases
4992 (catch 'break
4993 (dolist (c (js2-switch-node-cases node))
4994 (if (js2-case-node-expr c)
4995 (js2-set-flag rv (js2-end-check-block c))
4996 (setq default-case c)
4997 (throw 'break nil))))
4998 ;; we don't care how the cases drop into each other
4999 (js2-clear-flag rv js2-END_DROPS_OFF)
5000 ;; examine the default
5001 (js2-set-flag rv (if default-case
5002 (js2-end-check default-case)
5003 js2-END_DROPS_OFF))
5004 rv))
5005
5006 (defun js2-end-check-try (node)
5007 "If the block has a finally, return consistency is checked in the
5008 finally block. If all code paths in the finally return, then the
5009 returns in the try-catch blocks don't matter. If there is a code path
5010 that does not return or if there is no finally block, the returns
5011 of the try and catch blocks are checked for mismatch.
5012 Returns logical OR of END_* flags."
5013 (let ((finally (js2-try-node-finally-block node))
5014 rv)
5015 ;; check the finally if it exists
5016 (setq rv (if finally
5017 (js2-end-check (js2-finally-node-body finally))
5018 js2-END_DROPS_OFF))
5019 ;; If the finally block always returns, then none of the returns
5020 ;; in the try or catch blocks matter.
5021 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5022 (js2-clear-flag rv js2-END_DROPS_OFF)
5023 ;; examine the try block
5024 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5025 ;; check each catch block
5026 (dolist (cb (js2-try-node-catch-clauses node))
5027 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5028 rv))
5029
5030 (defun js2-end-check-loop (node)
5031 "Return statement in the loop body must be consistent.
5032 The default assumption for any kind of a loop is that it will eventually
5033 terminate. The only exception is a loop with a constant true condition.
5034 Code that follows such a loop is examined only if one can determine
5035 statically that there is a break out of the loop.
5036
5037 for(... ; ... ; ...) {}
5038 for(... in ... ) {}
5039 while(...) { }
5040 do { } while(...)
5041
5042 Returns logical OR of END_* flags."
5043 (let ((rv (js2-end-check (js2-loop-node-body node)))
5044 (condition (cond
5045 ((js2-while-node-p node)
5046 (js2-while-node-condition node))
5047 ((js2-do-node-p node)
5048 (js2-do-node-condition node))
5049 ((js2-for-node-p node)
5050 (js2-for-node-condition node)))))
5051
5052 ;; check to see if the loop condition is always true
5053 (if (and condition
5054 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5055 (js2-clear-flag rv js2-END_DROPS_OFF))
5056
5057 ;; look for effect of breaks
5058 (js2-set-flag rv (js2-node-get-prop node
5059 'CONTROL_BLOCK_PROP
5060 js2-END_UNREACHED))
5061 rv))
5062
5063 (defun js2-end-check-block (node)
5064 "A general block of code is examined statement by statement.
5065 If any statement (even a compound one) returns in all branches, then
5066 subsequent statements are not examined.
5067 Returns logical OR of END_* flags."
5068 (let* ((rv js2-END_DROPS_OFF)
5069 (kids (js2-block-node-kids node))
5070 (n (car kids)))
5071 ;; Check each statment. If the statement can continue onto the next
5072 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5073 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5074 (js2-clear-flag rv js2-END_DROPS_OFF)
5075 (js2-set-flag rv (js2-end-check n))
5076 (setq kids (cdr kids)
5077 n (car kids)))
5078 rv))
5079
5080 (defun js2-end-check-label (node)
5081 "A labeled statement implies that there may be a break to the label.
5082 The function processes the labeled statement and then checks the
5083 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5084 particular label.
5085 Returns logical OR of END_* flags."
5086 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5087 (logior rv (js2-node-get-prop node
5088 'CONTROL_BLOCK_PROP
5089 js2-END_UNREACHED))))
5090
5091 (defun js2-end-check-break (node)
5092 "When a break is encountered annotate the statement being broken
5093 out of by setting its CONTROL_BLOCK_PROP property.
5094 Returns logical OR of END_* flags."
5095 (and (js2-break-node-target node)
5096 (js2-node-set-prop (js2-break-node-target node)
5097 'CONTROL_BLOCK_PROP
5098 js2-END_DROPS_OFF))
5099 js2-END_UNREACHED)
5100
5101 (defun js2-end-check (node)
5102 "Examine the body of a function, doing a basic reachability analysis.
5103 Returns a combination of flags END_* flags that indicate
5104 how the function execution can terminate. These constitute only the
5105 pessimistic set of termination conditions. It is possible that at
5106 runtime certain code paths will never be actually taken. Hence this
5107 analysis will flag errors in cases where there may not be errors.
5108 Returns logical OR of END_* flags"
5109 (let (kid)
5110 (cond
5111 ((js2-break-node-p node)
5112 (js2-end-check-break node))
5113 ((js2-expr-stmt-node-p node)
5114 (if (setq kid (js2-expr-stmt-node-expr node))
5115 (js2-end-check kid)
5116 js2-END_DROPS_OFF))
5117 ((or (js2-continue-node-p node)
5118 (js2-throw-node-p node))
5119 js2-END_UNREACHED)
5120 ((js2-return-node-p node)
5121 (if (setq kid (js2-return-node-retval node))
5122 js2-END_RETURNS_VALUE
5123 js2-END_RETURNS))
5124 ((js2-loop-node-p node)
5125 (js2-end-check-loop node))
5126 ((js2-switch-node-p node)
5127 (js2-end-check-switch node))
5128 ((js2-labeled-stmt-node-p node)
5129 (js2-end-check-label node))
5130 ((js2-if-node-p node)
5131 (js2-end-check-if node))
5132 ((js2-try-node-p node)
5133 (js2-end-check-try node))
5134 ((js2-block-node-p node)
5135 (if (null (js2-block-node-kids node))
5136 js2-END_DROPS_OFF
5137 (js2-end-check-block node)))
5138 ((js2-yield-node-p node)
5139 js2-END_YIELDS)
5140 (t
5141 js2-END_DROPS_OFF))))
5142
5143 (defun js2-always-defined-boolean-p (node)
5144 "Check if NODE always evaluates to true or false in boolean context.
5145 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5146 nor always false."
5147 (let ((tt (js2-node-type node))
5148 num)
5149 (cond
5150 ((or (= tt js2-FALSE) (= tt js2-NULL))
5151 'ALWAYS_FALSE)
5152 ((= tt js2-TRUE)
5153 'ALWAYS_TRUE)
5154 ((= tt js2-NUMBER)
5155 (setq num (js2-number-node-num-value node))
5156 (if (and (not (eq num 0.0e+NaN))
5157 (not (zerop num)))
5158 'ALWAYS_TRUE
5159 'ALWAYS_FALSE))
5160 (t
5161 nil))))
5162
5163 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5164 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5165
5166 (defvar js2-tokens nil
5167 "List of all defined token names.") ; initialized in `js2-token-names'
5168
5169 (defconst js2-token-names
5170 (let* ((names (make-vector js2-num-tokens -1))
5171 (case-fold-search nil) ; only match js2-UPPER_CASE
5172 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5173 (loop for sym in syms
5174 for i from 0
5175 do
5176 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5177 (not (boundp sym)))
5178 (aset names (symbol-value sym) ; code, e.g. 152
5179 (downcase
5180 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5181 (push sym js2-tokens)))
5182 names)
5183 "Vector mapping int values to token string names, sans `js2-' prefix.")
5184
5185 (defun js2-tt-name (tok)
5186 "Return a string name for TOK, a token symbol or code.
5187 Signals an error if it's not a recognized token."
5188 (let ((code tok))
5189 (if (symbolp tok)
5190 (setq code (symbol-value tok)))
5191 (if (eq code -1)
5192 "ERROR"
5193 (if (and (numberp code)
5194 (not (minusp code))
5195 (< code js2-num-tokens))
5196 (aref js2-token-names code)
5197 (error "Invalid token: %s" code)))))
5198
5199 (defsubst js2-tt-sym (tok)
5200 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5201 (intern (js2-tt-name tok)))
5202
5203 (defconst js2-token-codes
5204 (let ((table (make-hash-table :test 'eq :size 256)))
5205 (loop for name across js2-token-names
5206 for sym = (intern (concat "js2-" (upcase name)))
5207 do
5208 (puthash sym (symbol-value sym) table))
5209 ;; clean up a few that are "wrong" in Rhino's token codes
5210 (puthash 'js2-DELETE js2-DELPROP table)
5211 table)
5212 "Hashtable mapping token type symbols to their bytecodes.")
5213
5214 (defsubst js2-tt-code (sym)
5215 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5216 (or (gethash sym js2-token-codes)
5217 (error "Invalid token symbol: %s " sym))) ; signal code bug
5218
5219 (defun js2-report-scan-error (msg &optional no-throw beg len)
5220 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5221 (js2-report-error msg nil
5222 (or beg (js2-current-token-beg))
5223 (or len (js2-current-token-len)))
5224 (unless no-throw
5225 (throw 'return js2-ERROR)))
5226
5227 (defun js2-set-string-from-buffer (token)
5228 "Set `string' and `end' slots for TOKEN, return the string."
5229 (setf (js2-token-end token) js2-ts-cursor
5230 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5231
5232 ;; TODO: could potentially avoid a lot of consing by allocating a
5233 ;; char buffer the way Rhino does.
5234 (defsubst js2-add-to-string (c)
5235 (push c js2-ts-string-buffer))
5236
5237 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5238 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5239 ;; any other character: when it's not part of the current token, we
5240 ;; unget it, allowing it to be read again by the following call.
5241 (defsubst js2-unget-char ()
5242 (decf js2-ts-cursor))
5243
5244 ;; Rhino distinguishes \r and \n line endings. We don't need to
5245 ;; because we only scan from Emacs buffers, which always use \n.
5246 (defun js2-get-char ()
5247 "Read and return the next character from the input buffer.
5248 Increments `js2-ts-lineno' if the return value is a newline char.
5249 Updates `js2-ts-cursor' to the point after the returned char.
5250 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5251 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5252 (let (c)
5253 ;; check for end of buffer
5254 (if (>= js2-ts-cursor (point-max))
5255 (setq js2-ts-hit-eof t
5256 js2-ts-cursor (1+ js2-ts-cursor)
5257 c js2-EOF_CHAR) ; return value
5258 ;; otherwise read next char
5259 (setq c (char-before (incf js2-ts-cursor)))
5260 ;; if we read a newline, update counters
5261 (if (= c ?\n)
5262 (setq js2-ts-line-start js2-ts-cursor
5263 js2-ts-lineno (1+ js2-ts-lineno)))
5264 ;; TODO: skip over format characters
5265 c)))
5266
5267 (defun js2-read-unicode-escape ()
5268 "Read a \\uNNNN sequence from the input.
5269 Assumes the ?\ and ?u have already been read.
5270 Returns the unicode character, or nil if it wasn't a valid character.
5271 Doesn't change the values of any scanner variables."
5272 ;; I really wish I knew a better way to do this, but I can't
5273 ;; find the Emacs function that takes a 16-bit int and converts
5274 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5275 ;; Have to first check that it's 4 hex characters or it may stop
5276 ;; the read early.
5277 (ignore-errors
5278 (let ((s (buffer-substring-no-properties js2-ts-cursor
5279 (+ 4 js2-ts-cursor))))
5280 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5281 (read (concat "?\\u" s))))))
5282
5283 (defun js2-match-char (test)
5284 "Consume and return next character if it matches TEST, a character.
5285 Returns nil and consumes nothing if TEST is not the next character."
5286 (let ((c (js2-get-char)))
5287 (if (eq c test)
5288 t
5289 (js2-unget-char)
5290 nil)))
5291
5292 (defun js2-peek-char ()
5293 (prog1
5294 (js2-get-char)
5295 (js2-unget-char)))
5296
5297 (defun js2-identifier-start-p (c)
5298 "Is C a valid start to an ES5 Identifier?
5299 See http://es5.github.io/#x7.6"
5300 (or
5301 (memq c '(?$ ?_))
5302 (memq (get-char-code-property c 'general-category)
5303 ;; Letters
5304 '(Lu Ll Lt Lm Lo Nl))))
5305
5306 (defun js2-identifier-part-p (c)
5307 "Is C a valid part of an ES5 Identifier?
5308 See http://es5.github.io/#x7.6"
5309 (or
5310 (memq c '(?$ ?_ ?\u200c ?\u200d))
5311 (memq (get-char-code-property c 'general-category)
5312 '(;; Letters
5313 Lu Ll Lt Lm Lo Nl
5314 ;; Combining Marks
5315 Mn Mc
5316 ;; Digits
5317 Nd
5318 ;; Connector Punctuation
5319 Pc))))
5320
5321 (defun js2-alpha-p (c)
5322 (cond ((and (<= ?A c) (<= c ?Z)) t)
5323 ((and (<= ?a c) (<= c ?z)) t)
5324 (t nil)))
5325
5326 (defsubst js2-digit-p (c)
5327 (and (<= ?0 c) (<= c ?9)))
5328
5329 (defun js2-js-space-p (c)
5330 (if (<= c 127)
5331 (memq c '(#x20 #x9 #xB #xC #xD))
5332 (or
5333 (eq c #xA0)
5334 ;; TODO: change this nil to check for Unicode space character
5335 nil)))
5336
5337 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5338
5339 (defun js2-skip-line ()
5340 "Skip to end of line."
5341 (while (not (memq (js2-get-char) js2-eol-chars)))
5342 (js2-unget-char)
5343 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5344 (setq js2-token-end js2-ts-cursor))
5345
5346 (defun js2-init-scanner (&optional buf line)
5347 "Create token stream for BUF starting on LINE.
5348 BUF defaults to `current-buffer' and LINE defaults to 1.
5349
5350 A buffer can only have one scanner active at a time, which yields
5351 dramatically simpler code than using a defstruct. If you need to
5352 have simultaneous scanners in a buffer, copy the regions to scan
5353 into temp buffers."
5354 (with-current-buffer (or buf (current-buffer))
5355 (setq js2-ts-dirty-line nil
5356 js2-ts-hit-eof nil
5357 js2-ts-line-start 0
5358 js2-ts-lineno (or line 1)
5359 js2-ts-line-end-char -1
5360 js2-ts-cursor (point-min)
5361 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5362 js2-ti-tokens-cursor 0
5363 js2-ti-lookahead 0
5364 js2-ts-is-xml-attribute nil
5365 js2-ts-xml-is-tag-content nil
5366 js2-ts-xml-open-tags-count 0
5367 js2-ts-string-buffer nil)))
5368
5369 ;; This function uses the cached op, string and number fields in
5370 ;; TokenStream; if getToken has been called since the passed token
5371 ;; was scanned, the op or string printed may be incorrect.
5372 (defun js2-token-to-string (token)
5373 ;; Not sure where this function is used in Rhino. Not tested.
5374 (if (not js2-debug-print-trees)
5375 ""
5376 (let ((name (js2-tt-name token)))
5377 (cond
5378 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5379 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5380 (concat name " `" (js2-current-token-string) "'"))
5381 ((eq token js2-NUMBER)
5382 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5383 (t
5384 name)))))
5385
5386 (defconst js2-keywords
5387 '(break
5388 case catch class const continue
5389 debugger default delete do
5390 else extends
5391 false finally for function
5392 if in instanceof import
5393 let
5394 new null
5395 return
5396 static super switch
5397 this throw true try typeof
5398 var void
5399 while with
5400 yield))
5401
5402 ;; Token names aren't exactly the same as the keywords, unfortunately.
5403 ;; E.g. delete is js2-DELPROP.
5404 (defconst js2-kwd-tokens
5405 (let ((table (make-vector js2-num-tokens nil))
5406 (tokens
5407 (list js2-BREAK
5408 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5409 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5410 js2-ELSE js2-EXTENDS
5411 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5412 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5413 js2-LET
5414 js2-NEW js2-NULL
5415 js2-RETURN
5416 js2-STATIC js2-SUPER js2-SWITCH
5417 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5418 js2-VAR
5419 js2-WHILE js2-WITH
5420 js2-YIELD)))
5421 (dolist (i tokens)
5422 (aset table i 'font-lock-keyword-face))
5423 (aset table js2-STRING 'font-lock-string-face)
5424 (aset table js2-REGEXP 'font-lock-string-face)
5425 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5426 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5427 (aset table js2-COMMENT 'font-lock-comment-face)
5428 (aset table js2-THIS 'font-lock-builtin-face)
5429 (aset table js2-SUPER 'font-lock-builtin-face)
5430 (aset table js2-VOID 'font-lock-constant-face)
5431 (aset table js2-NULL 'font-lock-constant-face)
5432 (aset table js2-TRUE 'font-lock-constant-face)
5433 (aset table js2-FALSE 'font-lock-constant-face)
5434 (aset table js2-NOT 'font-lock-negation-char-face)
5435 table)
5436 "Vector whose values are non-nil for tokens that are keywords.
5437 The values are default faces to use for highlighting the keywords.")
5438
5439 ;; FIXME: Support strict mode-only future reserved words, after we know
5440 ;; which parts scopes are in strict mode, and which are not.
5441 (defconst js2-reserved-words '(class enum export extends import super)
5442 "Future reserved keywords in ECMAScript 5.1.")
5443
5444 (defconst js2-keyword-names
5445 (let ((table (make-hash-table :test 'equal)))
5446 (loop for k in js2-keywords
5447 do (puthash
5448 (symbol-name k) ; instanceof
5449 (intern (concat "js2-"
5450 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5451 table))
5452 table)
5453 "JavaScript keywords by name, mapped to their symbols.")
5454
5455 (defconst js2-reserved-word-names
5456 (let ((table (make-hash-table :test 'equal)))
5457 (loop for k in js2-reserved-words
5458 do
5459 (puthash (symbol-name k) 'js2-RESERVED table))
5460 table)
5461 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5462
5463 (defun js2-collect-string (buf)
5464 "Convert BUF, a list of chars, to a string.
5465 Reverses BUF before converting."
5466 (if buf
5467 (apply #'string (nreverse buf))
5468 ""))
5469
5470 (defun js2-string-to-keyword (s)
5471 "Return token for S, a string, if S is a keyword or reserved word.
5472 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5473 (or (gethash s js2-keyword-names)
5474 (gethash s js2-reserved-word-names)))
5475
5476 (defsubst js2-ts-set-char-token-bounds (token)
5477 "Used when next token is one character."
5478 (setf (js2-token-beg token) (1- js2-ts-cursor)
5479 (js2-token-end token) js2-ts-cursor))
5480
5481 (defsubst js2-ts-return (token type)
5482 "Update the `end' and `type' slots of TOKEN,
5483 then throw `return' with value TYPE."
5484 (setf (js2-token-end token) js2-ts-cursor
5485 (js2-token-type token) type)
5486 (throw 'return type))
5487
5488 (defun js2-x-digit-to-int (c accumulator)
5489 "Build up a hex number.
5490 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5491 corresponding number. Otherwise return -1."
5492 (catch 'return
5493 (catch 'check
5494 ;; Use 0..9 < A..Z < a..z
5495 (cond
5496 ((<= c ?9)
5497 (decf c ?0)
5498 (if (<= 0 c)
5499 (throw 'check nil)))
5500 ((<= c ?F)
5501 (when (<= ?A c)
5502 (decf c (- ?A 10))
5503 (throw 'check nil)))
5504 ((<= c ?f)
5505 (when (<= ?a c)
5506 (decf c (- ?a 10))
5507 (throw 'check nil))))
5508 (throw 'return -1))
5509 (logior c (lsh accumulator 4))))
5510
5511 (defun js2-get-token (&optional modifier)
5512 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5513 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5514 next saved token.
5515
5516 This function will not return a newline (js2-EOL) - instead, it
5517 gobbles newlines until it finds a non-newline token. Call
5518 `js2-peek-token-or-eol' when you care about newlines.
5519
5520 This function will also not return a js2-COMMENT. Instead, it
5521 records comments found in `js2-scanned-comments'. If the token
5522 returned by this function immediately follows a jsdoc comment,
5523 the token is flagged as such."
5524 (if (zerop js2-ti-lookahead)
5525 (js2-get-token-internal modifier)
5526 (decf js2-ti-lookahead)
5527 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5528 (let ((tt (js2-current-token-type)))
5529 (assert (not (= tt js2-EOL)))
5530 tt)))
5531
5532 (defun js2-unget-token ()
5533 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5534 (incf js2-ti-lookahead)
5535 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5536
5537 (defun js2-get-token-internal (modifier)
5538 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5539 (tt (js2-token-type token))
5540 saw-eol
5541 face)
5542 ;; process comments
5543 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5544 (if (= tt js2-EOL)
5545 (setq saw-eol t)
5546 (setq saw-eol nil)
5547 (when js2-record-comments
5548 (js2-record-comment token)))
5549 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5550 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5551 tt (js2-token-type token)))
5552
5553 (when saw-eol
5554 (setf (js2-token-follows-eol-p token) t))
5555
5556 ;; perform lexical fontification as soon as token is scanned
5557 (when js2-parse-ide-mode
5558 (cond
5559 ((minusp tt)
5560 (js2-record-face 'js2-error token))
5561 ((setq face (aref js2-kwd-tokens tt))
5562 (js2-record-face face token))
5563 ((and (= tt js2-NAME)
5564 (equal (js2-token-string token) "undefined"))
5565 (js2-record-face 'font-lock-constant-face token))))
5566 tt))
5567
5568 (defun js2-get-token-internal-1 (modifier)
5569 "Return next JavaScript token type, an int such as js2-RETURN.
5570 During operation, creates an instance of `js2-token' struct, sets
5571 its relevant fields and puts it into `js2-ti-tokens'."
5572 (let (c c1 identifier-start is-unicode-escape-start
5573 contains-escape escape-val str result base
5574 quote-char val look-for-slash continue tt
5575 (token (js2-new-token 0)))
5576 (setq
5577 tt
5578 (catch 'return
5579 (when (eq modifier 'TEMPLATE_TAIL)
5580 (setf (js2-token-beg token) (1- js2-ts-cursor))
5581 (throw 'return (js2-get-string-or-template-token ?` token)))
5582 (while t
5583 ;; Eat whitespace, possibly sensitive to newlines.
5584 (setq continue t)
5585 (while continue
5586 (setq c (js2-get-char))
5587 (cond
5588 ((eq c js2-EOF_CHAR)
5589 (js2-unget-char)
5590 (js2-ts-set-char-token-bounds token)
5591 (throw 'return js2-EOF))
5592 ((eq c ?\n)
5593 (js2-ts-set-char-token-bounds token)
5594 (setq js2-ts-dirty-line nil)
5595 (throw 'return js2-EOL))
5596 ((not (js2-js-space-p c))
5597 (if (/= c ?-) ; in case end of HTML comment
5598 (setq js2-ts-dirty-line t))
5599 (setq continue nil))))
5600 ;; Assume the token will be 1 char - fixed up below.
5601 (js2-ts-set-char-token-bounds token)
5602 (when (eq c ?@)
5603 (throw 'return js2-XMLATTR))
5604 ;; identifier/keyword/instanceof?
5605 ;; watch out for starting with a <backslash>
5606 (cond
5607 ((eq c ?\\)
5608 (setq c (js2-get-char))
5609 (if (eq c ?u)
5610 (setq identifier-start t
5611 is-unicode-escape-start t
5612 js2-ts-string-buffer nil)
5613 (setq identifier-start nil)
5614 (js2-unget-char)
5615 (setq c ?\\)))
5616 (t
5617 (when (setq identifier-start (js2-identifier-start-p c))
5618 (setq js2-ts-string-buffer nil)
5619 (js2-add-to-string c))))
5620 (when identifier-start
5621 (setq contains-escape is-unicode-escape-start)
5622 (catch 'break
5623 (while t
5624 (if is-unicode-escape-start
5625 ;; strictly speaking we should probably push-back
5626 ;; all the bad characters if the <backslash>uXXXX
5627 ;; sequence is malformed. But since there isn't a
5628 ;; correct context(is there?) for a bad Unicode
5629 ;; escape sequence in an identifier, we can report
5630 ;; an error here.
5631 (progn
5632 (setq escape-val 0)
5633 (dotimes (_ 4)
5634 (setq c (js2-get-char)
5635 escape-val (js2-x-digit-to-int c escape-val))
5636 ;; Next check takes care of c < 0 and bad escape
5637 (if (minusp escape-val)
5638 (throw 'break nil)))
5639 (if (minusp escape-val)
5640 (js2-report-scan-error "msg.invalid.escape" t))
5641 (js2-add-to-string escape-val)
5642 (setq is-unicode-escape-start nil))
5643 (setq c (js2-get-char))
5644 (cond
5645 ((eq c ?\\)
5646 (setq c (js2-get-char))
5647 (if (eq c ?u)
5648 (setq is-unicode-escape-start t
5649 contains-escape t)
5650 (js2-report-scan-error "msg.illegal.character" t)))
5651 (t
5652 (if (or (eq c js2-EOF_CHAR)
5653 (not (js2-identifier-part-p c)))
5654 (throw 'break nil))
5655 (js2-add-to-string c))))))
5656 (js2-unget-char)
5657 (setf str (js2-collect-string js2-ts-string-buffer)
5658 (js2-token-end token) js2-ts-cursor)
5659 ;; FIXME: Invalid in ES5 and ES6, see
5660 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5661 ;; Probably should just drop this conditional.
5662 (unless contains-escape
5663 ;; OPT we shouldn't have to make a string (object!) to
5664 ;; check if it's a keyword.
5665 ;; Return the corresponding token if it's a keyword
5666 (when (setq result (js2-string-to-keyword str))
5667 (if (and (< js2-language-version 170)
5668 (memq result '(js2-LET js2-YIELD)))
5669 ;; LET and YIELD are tokens only in 1.7 and later
5670 (setq result 'js2-NAME))
5671 (when (eq result 'js2-RESERVED)
5672 (setf (js2-token-string token) str))
5673 (throw 'return (js2-tt-code result))))
5674 ;; If we want to intern these as Rhino does, just use (intern str)
5675 (setf (js2-token-string token) str)
5676 (throw 'return js2-NAME)) ; end identifier/kwd check
5677 ;; is it a number?
5678 (when (or (js2-digit-p c)
5679 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5680 (setq js2-ts-string-buffer nil
5681 base 10)
5682 (when (eq c ?0)
5683 (setq c (js2-get-char))
5684 (cond
5685 ((or (eq c ?x) (eq c ?X))
5686 (setq base 16)
5687 (setq c (js2-get-char)))
5688 ((and (or (eq c ?b) (eq c ?B))
5689 (>= js2-language-version 200))
5690 (setq base 2)
5691 (setq c (js2-get-char)))
5692 ((and (or (eq c ?o) (eq c ?O))
5693 (>= js2-language-version 200))
5694 (setq base 8)
5695 (setq c (js2-get-char)))
5696 ((js2-digit-p c)
5697 (setq base 'maybe-8))
5698 (t
5699 (js2-add-to-string ?0))))
5700 (cond
5701 ((eq base 16)
5702 (if (> 0 (js2-x-digit-to-int c 0))
5703 (js2-report-scan-error "msg.missing.hex.digits")
5704 (while (<= 0 (js2-x-digit-to-int c 0))
5705 (js2-add-to-string c)
5706 (setq c (js2-get-char)))))
5707 ((eq base 2)
5708 (if (not (memq c '(?0 ?1)))
5709 (js2-report-scan-error "msg.missing.binary.digits")
5710 (while (memq c '(?0 ?1))
5711 (js2-add-to-string c)
5712 (setq c (js2-get-char)))))
5713 ((eq base 8)
5714 (if (or (> ?0 c) (< ?7 c))
5715 (js2-report-scan-error "msg.missing.octal.digits")
5716 (while (and (<= ?0 c) (>= ?7 c))
5717 (js2-add-to-string c)
5718 (setq c (js2-get-char)))))
5719 (t
5720 (while (and (<= ?0 c) (<= c ?9))
5721 ;; We permit 08 and 09 as decimal numbers, which
5722 ;; makes our behavior a superset of the ECMA
5723 ;; numeric grammar. We might not always be so
5724 ;; permissive, so we warn about it.
5725 (when (and (eq base 'maybe-8) (>= c ?8))
5726 (js2-report-warning "msg.bad.octal.literal"
5727 (if (eq c ?8) "8" "9"))
5728 (setq base 10))
5729 (js2-add-to-string c)
5730 (setq c (js2-get-char)))
5731 (when (eq base 'maybe-8)
5732 (setq base 8))))
5733 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5734 (when (eq c ?.)
5735 (loop do
5736 (js2-add-to-string c)
5737 (setq c (js2-get-char))
5738 while (js2-digit-p c)))
5739 (when (memq c '(?e ?E))
5740 (js2-add-to-string c)
5741 (setq c (js2-get-char))
5742 (when (memq c '(?+ ?-))
5743 (js2-add-to-string c)
5744 (setq c (js2-get-char)))
5745 (unless (js2-digit-p c)
5746 (js2-report-scan-error "msg.missing.exponent" t))
5747 (loop do
5748 (js2-add-to-string c)
5749 (setq c (js2-get-char))
5750 while (js2-digit-p c))))
5751 (js2-unget-char)
5752 (let ((str (js2-set-string-from-buffer token)))
5753 (setf (js2-token-number token)
5754 (js2-string-to-number str base)))
5755 (throw 'return js2-NUMBER))
5756 ;; is it a string?
5757 (when (memq c '(?\" ?\' ?`))
5758 (throw 'return
5759 (js2-get-string-or-template-token c token)))
5760 (js2-ts-return token
5761 (case c
5762 (?\;
5763 (throw 'return js2-SEMI))
5764 (?\[
5765 (throw 'return js2-LB))
5766 (?\]
5767 (throw 'return js2-RB))
5768 (?{
5769 (throw 'return js2-LC))
5770 (?}
5771 (throw 'return js2-RC))
5772 (?\(
5773 (throw 'return js2-LP))
5774 (?\)
5775 (throw 'return js2-RP))
5776 (?,
5777 (throw 'return js2-COMMA))
5778 (??
5779 (throw 'return js2-HOOK))
5780 (?:
5781 (if (js2-match-char ?:)
5782 js2-COLONCOLON
5783 (throw 'return js2-COLON)))
5784 (?.
5785 (if (js2-match-char ?.)
5786 (if (js2-match-char ?.)
5787 js2-TRIPLEDOT js2-DOTDOT)
5788 (if (js2-match-char ?\()
5789 js2-DOTQUERY
5790 (throw 'return js2-DOT))))
5791 (?|
5792 (if (js2-match-char ?|)
5793 (throw 'return js2-OR)
5794 (if (js2-match-char ?=)
5795 js2-ASSIGN_BITOR
5796 (throw 'return js2-BITOR))))
5797 (?^
5798 (if (js2-match-char ?=)
5799 js2-ASSIGN_BITOR
5800 (throw 'return js2-BITXOR)))
5801 (?&
5802 (if (js2-match-char ?&)
5803 (throw 'return js2-AND)
5804 (if (js2-match-char ?=)
5805 js2-ASSIGN_BITAND
5806 (throw 'return js2-BITAND))))
5807 (?=
5808 (if (js2-match-char ?=)
5809 (if (js2-match-char ?=)
5810 js2-SHEQ
5811 (throw 'return js2-EQ))
5812 (if (js2-match-char ?>)
5813 (js2-ts-return token js2-ARROW)
5814 (throw 'return js2-ASSIGN))))
5815 (?!
5816 (if (js2-match-char ?=)
5817 (if (js2-match-char ?=)
5818 js2-SHNE
5819 js2-NE)
5820 (throw 'return js2-NOT)))
5821 (?<
5822 ;; NB:treat HTML begin-comment as comment-till-eol
5823 (when (js2-match-char ?!)
5824 (when (js2-match-char ?-)
5825 (when (js2-match-char ?-)
5826 (js2-skip-line)
5827 (setf (js2-token-comment-type (js2-current-token)) 'html)
5828 (throw 'return js2-COMMENT)))
5829 (js2-unget-char))
5830 (if (js2-match-char ?<)
5831 (if (js2-match-char ?=)
5832 js2-ASSIGN_LSH
5833 js2-LSH)
5834 (if (js2-match-char ?=)
5835 js2-LE
5836 (throw 'return js2-LT))))
5837 (?>
5838 (if (js2-match-char ?>)
5839 (if (js2-match-char ?>)
5840 (if (js2-match-char ?=)
5841 js2-ASSIGN_URSH
5842 js2-URSH)
5843 (if (js2-match-char ?=)
5844 js2-ASSIGN_RSH
5845 js2-RSH))
5846 (if (js2-match-char ?=)
5847 js2-GE
5848 (throw 'return js2-GT))))
5849 (?*
5850 (if (js2-match-char ?=)
5851 js2-ASSIGN_MUL
5852 (throw 'return js2-MUL)))
5853 (?/
5854 ;; is it a // comment?
5855 (when (js2-match-char ?/)
5856 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5857 (js2-skip-line)
5858 (setf (js2-token-comment-type token) 'line)
5859 ;; include newline so highlighting goes to end of window
5860 (incf (js2-token-end token))
5861 (throw 'return js2-COMMENT))
5862 ;; is it a /* comment?
5863 (when (js2-match-char ?*)
5864 (setf look-for-slash nil
5865 (js2-token-beg token) (- js2-ts-cursor 2)
5866 (js2-token-comment-type token)
5867 (if (js2-match-char ?*)
5868 (progn
5869 (setq look-for-slash t)
5870 'jsdoc)
5871 'block))
5872 (while t
5873 (setq c (js2-get-char))
5874 (cond
5875 ((eq c js2-EOF_CHAR)
5876 (setf (js2-token-end token) (1- js2-ts-cursor))
5877 (js2-report-error "msg.unterminated.comment")
5878 (throw 'return js2-COMMENT))
5879 ((eq c ?*)
5880 (setq look-for-slash t))
5881 ((eq c ?/)
5882 (if look-for-slash
5883 (js2-ts-return token js2-COMMENT)))
5884 (t
5885 (setf look-for-slash nil
5886 (js2-token-end token) js2-ts-cursor)))))
5887 (if (js2-match-char ?=)
5888 js2-ASSIGN_DIV
5889 (throw 'return js2-DIV)))
5890 (?#
5891 (when js2-skip-preprocessor-directives
5892 (js2-skip-line)
5893 (setf (js2-token-comment-type token) 'preprocessor
5894 (js2-token-end token) js2-ts-cursor)
5895 (throw 'return js2-COMMENT))
5896 (throw 'return js2-ERROR))
5897 (?%
5898 (if (js2-match-char ?=)
5899 js2-ASSIGN_MOD
5900 (throw 'return js2-MOD)))
5901 (?~
5902 (throw 'return js2-BITNOT))
5903 (?+
5904 (if (js2-match-char ?=)
5905 js2-ASSIGN_ADD
5906 (if (js2-match-char ?+)
5907 js2-INC
5908 (throw 'return js2-ADD))))
5909 (?-
5910 (cond
5911 ((js2-match-char ?=)
5912 (setq c js2-ASSIGN_SUB))
5913 ((js2-match-char ?-)
5914 (unless js2-ts-dirty-line
5915 ;; treat HTML end-comment after possible whitespace
5916 ;; after line start as comment-until-eol
5917 (when (js2-match-char ?>)
5918 (js2-skip-line)
5919 (setf (js2-token-comment-type (js2-current-token)) 'html)
5920 (throw 'return js2-COMMENT)))
5921 (setq c js2-DEC))
5922 (t
5923 (setq c js2-SUB)))
5924 (setq js2-ts-dirty-line t)
5925 c)
5926 (otherwise
5927 (js2-report-scan-error "msg.illegal.character")))))))
5928 (setf (js2-token-type token) tt)
5929 token))
5930
5931 (defun js2-get-string-or-template-token (quote-char token)
5932 ;; We attempt to accumulate a string the fast way, by
5933 ;; building it directly out of the reader. But if there
5934 ;; are any escaped characters in the string, we revert to
5935 ;; building it out of a string buffer.
5936 (let ((c (js2-get-char))
5937 js2-ts-string-buffer
5938 nc)
5939 (catch 'break
5940 (while (/= c quote-char)
5941 (catch 'continue
5942 (when (eq c js2-EOF_CHAR)
5943 (js2-unget-char)
5944 (js2-report-error "msg.unterminated.string.lit")
5945 (throw 'break nil))
5946 (when (and (eq c ?\n) (not (eq quote-char ?`)))
5947 (js2-unget-char)
5948 (js2-report-error "msg.unterminated.string.lit")
5949 (throw 'break nil))
5950 (when (eq c ?\\)
5951 ;; We've hit an escaped character
5952 (setq c (js2-get-char))
5953 (case c
5954 (?b (setq c ?\b))
5955 (?f (setq c ?\f))
5956 (?n (setq c ?\n))
5957 (?r (setq c ?\r))
5958 (?t (setq c ?\t))
5959 (?v (setq c ?\v))
5960 (?u
5961 (setq c1 (js2-read-unicode-escape))
5962 (if js2-parse-ide-mode
5963 (if c1
5964 (progn
5965 ;; just copy the string in IDE-mode
5966 (js2-add-to-string ?\\)
5967 (js2-add-to-string ?u)
5968 (dotimes (_ 3)
5969 (js2-add-to-string (js2-get-char)))
5970 (setq c (js2-get-char))) ; added at end of loop
5971 ;; flag it as an invalid escape
5972 (js2-report-warning "msg.invalid.escape"
5973 nil (- js2-ts-cursor 2) 6))
5974 ;; Get 4 hex digits; if the u escape is not
5975 ;; followed by 4 hex digits, use 'u' + the
5976 ;; literal character sequence that follows.
5977 (js2-add-to-string ?u)
5978 (setq escape-val 0)
5979 (dotimes (_ 4)
5980 (setq c (js2-get-char)
5981 escape-val (js2-x-digit-to-int c escape-val))
5982 (if (minusp escape-val)
5983 (throw 'continue nil))
5984 (js2-add-to-string c))
5985 ;; prepare for replace of stored 'u' sequence by escape value
5986 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5987 c escape-val)))
5988 (?x
5989 ;; Get 2 hex digits, defaulting to 'x'+literal
5990 ;; sequence, as above.
5991 (setq c (js2-get-char)
5992 escape-val (js2-x-digit-to-int c 0))
5993 (if (minusp escape-val)
5994 (progn
5995 (js2-add-to-string ?x)
5996 (throw 'continue nil))
5997 (setq c1 c
5998 c (js2-get-char)
5999 escape-val (js2-x-digit-to-int c escape-val))
6000 (if (minusp escape-val)
6001 (progn
6002 (js2-add-to-string ?x)
6003 (js2-add-to-string c1)
6004 (throw 'continue nil))
6005 ;; got 2 hex digits
6006 (setq c escape-val))))
6007 (?\n
6008 ;; Remove line terminator after escape to follow
6009 ;; SpiderMonkey and C/C++
6010 (setq c (js2-get-char))
6011 (throw 'continue nil))
6012 (t
6013 (when (and (<= ?0 c) (< c ?8))
6014 (setq val (- c ?0)
6015 c (js2-get-char))
6016 (when (and (<= ?0 c) (< c ?8))
6017 (setq val (- (+ (* 8 val) c) ?0)
6018 c (js2-get-char))
6019 (when (and (<= ?0 c)
6020 (< c ?8)
6021 (< val #o37))
6022 ;; c is 3rd char of octal sequence only
6023 ;; if the resulting val <= 0377
6024 (setq val (- (+ (* 8 val) c) ?0)
6025 c (js2-get-char))))
6026 (js2-unget-char)
6027 (setq c val)))))
6028 (when (and (eq quote-char ?`) (eq c ?$))
6029 (when (eq (setq nc (js2-get-char)) ?\{)
6030 (throw 'break nil))
6031 (js2-unget-char))
6032 (js2-add-to-string c)
6033 (setq c (js2-get-char)))))
6034 (js2-set-string-from-buffer token)
6035 (if (not (eq quote-char ?`))
6036 js2-STRING
6037 (if (and (eq c ?$) (eq nc ?\{))
6038 js2-TEMPLATE_HEAD
6039 js2-NO_SUBS_TEMPLATE))))
6040
6041 (defsubst js2-string-to-number (str base)
6042 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
6043 (condition-case nil
6044 (string-to-number str base)
6045 (overflow-error -1)))
6046
6047 (defun js2-read-regexp (start-tt)
6048 "Called by parser when it gets / or /= in literal context."
6049 (let (c err
6050 in-class ; inside a '[' .. ']' character-class
6051 flags
6052 (continue t)
6053 (token (js2-new-token 0)))
6054 (setq js2-ts-string-buffer nil)
6055 (if (eq start-tt js2-ASSIGN_DIV)
6056 ;; mis-scanned /=
6057 (js2-add-to-string ?=)
6058 (if (not (eq start-tt js2-DIV))
6059 (error "failed assertion")))
6060 (while (and (not err)
6061 (or (/= (setq c (js2-get-char)) ?/)
6062 in-class))
6063 (cond
6064 ((or (= c ?\n)
6065 (= c js2-EOF_CHAR))
6066 (setf (js2-token-end token) (1- js2-ts-cursor)
6067 err t
6068 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6069 (js2-report-error "msg.unterminated.re.lit"))
6070 (t (cond
6071 ((= c ?\\)
6072 (js2-add-to-string c)
6073 (setq c (js2-get-char)))
6074 ((= c ?\[)
6075 (setq in-class t))
6076 ((= c ?\])
6077 (setq in-class nil)))
6078 (js2-add-to-string c))))
6079 (unless err
6080 (while continue
6081 (cond
6082 ((js2-match-char ?g)
6083 (push ?g flags))
6084 ((js2-match-char ?i)
6085 (push ?i flags))
6086 ((js2-match-char ?m)
6087 (push ?m flags))
6088 ((and (js2-match-char ?u)
6089 (>= js2-language-version 200))
6090 (push ?u flags))
6091 ((and (js2-match-char ?y)
6092 (>= js2-language-version 200))
6093 (push ?y flags))
6094 (t
6095 (setq continue nil))))
6096 (if (js2-alpha-p (js2-peek-char))
6097 (js2-report-scan-error "msg.invalid.re.flag" t
6098 js2-ts-cursor 1))
6099 (js2-set-string-from-buffer token))
6100 (js2-collect-string flags)))
6101
6102 (defun js2-get-first-xml-token ()
6103 (setq js2-ts-xml-open-tags-count 0
6104 js2-ts-is-xml-attribute nil
6105 js2-ts-xml-is-tag-content nil)
6106 (js2-unget-char)
6107 (js2-get-next-xml-token))
6108
6109 (defun js2-xml-discard-string (token)
6110 "Throw away the string in progress and flag an XML parse error."
6111 (setf js2-ts-string-buffer nil
6112 (js2-token-string token) nil)
6113 (js2-report-scan-error "msg.XML.bad.form" t))
6114
6115 (defun js2-get-next-xml-token ()
6116 (setq js2-ts-string-buffer nil) ; for recording the XML
6117 (let ((token (js2-new-token 0))
6118 c result)
6119 (setq result
6120 (catch 'return
6121 (while t
6122 (setq c (js2-get-char))
6123 (cond
6124 ((= c js2-EOF_CHAR)
6125 (throw 'return js2-ERROR))
6126 (js2-ts-xml-is-tag-content
6127 (case c
6128 (?>
6129 (js2-add-to-string c)
6130 (setq js2-ts-xml-is-tag-content nil
6131 js2-ts-is-xml-attribute nil))
6132 (?/
6133 (js2-add-to-string c)
6134 (when (eq ?> (js2-peek-char))
6135 (setq c (js2-get-char))
6136 (js2-add-to-string c)
6137 (setq js2-ts-xml-is-tag-content nil)
6138 (decf js2-ts-xml-open-tags-count)))
6139 (?{
6140 (js2-unget-char)
6141 (js2-set-string-from-buffer token)
6142 (throw 'return js2-XML))
6143 ((?\' ?\")
6144 (js2-add-to-string c)
6145 (unless (js2-read-quoted-string c token)
6146 (throw 'return js2-ERROR)))
6147 (?=
6148 (js2-add-to-string c)
6149 (setq js2-ts-is-xml-attribute t))
6150 ((? ?\t ?\r ?\n)
6151 (js2-add-to-string c))
6152 (t
6153 (js2-add-to-string c)
6154 (setq js2-ts-is-xml-attribute nil)))
6155 (when (and (not js2-ts-xml-is-tag-content)
6156 (zerop js2-ts-xml-open-tags-count))
6157 (js2-set-string-from-buffer token)
6158 (throw 'return js2-XMLEND)))
6159 (t
6160 ;; else not tag content
6161 (case c
6162 (?<
6163 (js2-add-to-string c)
6164 (setq c (js2-peek-char))
6165 (case c
6166 (?!
6167 (setq c (js2-get-char)) ;; skip !
6168 (js2-add-to-string c)
6169 (setq c (js2-peek-char))
6170 (case c
6171 (?-
6172 (setq c (js2-get-char)) ;; skip -
6173 (js2-add-to-string c)
6174 (if (eq c ?-)
6175 (progn
6176 (js2-add-to-string c)
6177 (unless (js2-read-xml-comment token)
6178 (throw 'return js2-ERROR)))
6179 (js2-xml-discard-string token)
6180 (throw 'return js2-ERROR)))
6181 (?\[
6182 (setq c (js2-get-char)) ;; skip [
6183 (js2-add-to-string c)
6184 (if (and (= (js2-get-char) ?C)
6185 (= (js2-get-char) ?D)
6186 (= (js2-get-char) ?A)
6187 (= (js2-get-char) ?T)
6188 (= (js2-get-char) ?A)
6189 (= (js2-get-char) ?\[))
6190 (progn
6191 (js2-add-to-string ?C)
6192 (js2-add-to-string ?D)
6193 (js2-add-to-string ?A)
6194 (js2-add-to-string ?T)
6195 (js2-add-to-string ?A)
6196 (js2-add-to-string ?\[)
6197 (unless (js2-read-cdata token)
6198 (throw 'return js2-ERROR)))
6199 (js2-xml-discard-string token)
6200 (throw 'return js2-ERROR)))
6201 (t
6202 (unless (js2-read-entity token)
6203 (throw 'return js2-ERROR))))
6204 ;; Allow bare CDATA section, e.g.:
6205 ;; let xml = <![CDATA[ foo bar baz ]]>;
6206 (when (zerop js2-ts-xml-open-tags-count)
6207 (throw 'return js2-XMLEND)))
6208 (??
6209 (setq c (js2-get-char)) ;; skip ?
6210 (js2-add-to-string c)
6211 (unless (js2-read-PI token)
6212 (throw 'return js2-ERROR)))
6213 (?/
6214 ;; end tag
6215 (setq c (js2-get-char)) ;; skip /
6216 (js2-add-to-string c)
6217 (when (zerop js2-ts-xml-open-tags-count)
6218 (js2-xml-discard-string token)
6219 (throw 'return js2-ERROR))
6220 (setq js2-ts-xml-is-tag-content t)
6221 (decf js2-ts-xml-open-tags-count))
6222 (t
6223 ;; start tag
6224 (setq js2-ts-xml-is-tag-content t)
6225 (incf js2-ts-xml-open-tags-count))))
6226 (?{
6227 (js2-unget-char)
6228 (js2-set-string-from-buffer token)
6229 (throw 'return js2-XML))
6230 (t
6231 (js2-add-to-string c))))))))
6232 (setf (js2-token-end token) js2-ts-cursor)
6233 (setf (js2-token-type token) result)
6234 result))
6235
6236 (defun js2-read-quoted-string (quote token)
6237 (let (c)
6238 (catch 'return
6239 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6240 (js2-add-to-string c)
6241 (if (eq c quote)
6242 (throw 'return t)))
6243 (js2-xml-discard-string token) ;; throw away string in progress
6244 nil)))
6245
6246 (defun js2-read-xml-comment (token)
6247 (let ((c (js2-get-char)))
6248 (catch 'return
6249 (while (/= c js2-EOF_CHAR)
6250 (catch 'continue
6251 (js2-add-to-string c)
6252 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6253 (setq c (js2-get-char))
6254 (js2-add-to-string c)
6255 (if (eq (js2-peek-char) ?>)
6256 (progn
6257 (setq c (js2-get-char)) ;; skip >
6258 (js2-add-to-string c)
6259 (throw 'return t))
6260 (throw 'continue nil)))
6261 (setq c (js2-get-char))))
6262 (js2-xml-discard-string token)
6263 nil)))
6264
6265 (defun js2-read-cdata (token)
6266 (let ((c (js2-get-char)))
6267 (catch 'return
6268 (while (/= c js2-EOF_CHAR)
6269 (catch 'continue
6270 (js2-add-to-string c)
6271 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6272 (setq c (js2-get-char))
6273 (js2-add-to-string c)
6274 (if (eq (js2-peek-char) ?>)
6275 (progn
6276 (setq c (js2-get-char)) ;; Skip >
6277 (js2-add-to-string c)
6278 (throw 'return t))
6279 (throw 'continue nil)))
6280 (setq c (js2-get-char))))
6281 (js2-xml-discard-string token)
6282 nil)))
6283
6284 (defun js2-read-entity (token)
6285 (let ((decl-tags 1)
6286 c)
6287 (catch 'return
6288 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6289 (js2-add-to-string c)
6290 (case c
6291 (?<
6292 (incf decl-tags))
6293 (?>
6294 (decf decl-tags)
6295 (if (zerop decl-tags)
6296 (throw 'return t)))))
6297 (js2-xml-discard-string token)
6298 nil)))
6299
6300 (defun js2-read-PI (token)
6301 "Scan an XML processing instruction."
6302 (let (c)
6303 (catch 'return
6304 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6305 (js2-add-to-string c)
6306 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6307 (setq c (js2-get-char)) ;; Skip >
6308 (js2-add-to-string c)
6309 (throw 'return t)))
6310 (js2-xml-discard-string token)
6311 nil)))
6312
6313 ;;; Highlighting
6314
6315 (defun js2-set-face (beg end face &optional record)
6316 "Fontify a region. If RECORD is non-nil, record for later."
6317 (when (plusp js2-highlight-level)
6318 (setq beg (min (point-max) beg)
6319 beg (max (point-min) beg)
6320 end (min (point-max) end)
6321 end (max (point-min) end))
6322 (if record
6323 (push (list beg end face) js2-mode-fontifications)
6324 (put-text-property beg end 'font-lock-face face))))
6325
6326 (defsubst js2-clear-face (beg end)
6327 (remove-text-properties beg end '(font-lock-face nil
6328 help-echo nil
6329 point-entered nil
6330 c-in-sws nil)))
6331
6332 (defconst js2-ecma-global-props
6333 (concat "^"
6334 (regexp-opt
6335 '("Infinity" "NaN" "undefined" "arguments") t)
6336 "$")
6337 "Value properties of the Ecma-262 Global Object.
6338 Shown at or above `js2-highlight-level' 2.")
6339
6340 ;; might want to add the name "arguments" to this list?
6341 (defconst js2-ecma-object-props
6342 (concat "^"
6343 (regexp-opt
6344 '("prototype" "__proto__" "__parent__") t)
6345 "$")
6346 "Value properties of the Ecma-262 Object constructor.
6347 Shown at or above `js2-highlight-level' 2.")
6348
6349 (defconst js2-ecma-global-funcs
6350 (concat
6351 "^"
6352 (regexp-opt
6353 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6354 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6355 "$")
6356 "Function properties of the Ecma-262 Global object.
6357 Shown at or above `js2-highlight-level' 2.")
6358
6359 (defconst js2-ecma-number-props
6360 (concat "^"
6361 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6362 "NEGATIVE_INFINITY"
6363 "POSITIVE_INFINITY") t)
6364 "$")
6365 "Properties of the Ecma-262 Number constructor.
6366 Shown at or above `js2-highlight-level' 2.")
6367
6368 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6369 "Properties of the Ecma-262 Date constructor.
6370 Shown at or above `js2-highlight-level' 2.")
6371
6372 (defconst js2-ecma-math-props
6373 (concat "^"
6374 (regexp-opt
6375 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6376 t)
6377 "$")
6378 "Properties of the Ecma-262 Math object.
6379 Shown at or above `js2-highlight-level' 2.")
6380
6381 (defconst js2-ecma-math-funcs
6382 (concat "^"
6383 (regexp-opt
6384 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6385 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6386 "$")
6387 "Function properties of the Ecma-262 Math object.
6388 Shown at or above `js2-highlight-level' 2.")
6389
6390 (defconst js2-ecma-function-props
6391 (concat
6392 "^"
6393 (regexp-opt
6394 '(;; properties of the Object prototype object
6395 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6396 "toLocaleString" "toString" "valueOf"
6397 ;; properties of the Function prototype object
6398 "apply" "call"
6399 ;; properties of the Array prototype object
6400 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6401 "splice" "unshift"
6402 ;; properties of the String prototype object
6403 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6404 "localeCompare" "match" "replace" "search" "split" "substring"
6405 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6406 "toUpperCase"
6407 ;; properties of the Number prototype object
6408 "toExponential" "toFixed" "toPrecision"
6409 ;; properties of the Date prototype object
6410 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6411 "getMinutes" "getMonth" "getSeconds" "getTime"
6412 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6413 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6414 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6415 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6416 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6417 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6418 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6419 "toTimeString" "toUTCString"
6420 ;; properties of the RegExp prototype object
6421 "exec" "test"
6422 ;; properties of the JSON prototype object
6423 "parse" "stringify"
6424 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6425 "toSource" "__defineGetter__" "__defineSetter__"
6426 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6427 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6428 t)
6429 "$")
6430 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6431 Shown at or above `js2-highlight-level' 3.")
6432
6433 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6434 (let ((target-name (and target
6435 (js2-name-node-p target)
6436 (js2-name-node-name target)))
6437 (prop-name (if prop (js2-name-node-name prop)))
6438 (level2 (>= js2-highlight-level 2))
6439 (level3 (>= js2-highlight-level 3)))
6440 (when level2
6441 (let ((face
6442 (if call-p
6443 (cond
6444 ((and target prop)
6445 (cond
6446 ((and level3 (string-match js2-ecma-function-props prop-name))
6447 'font-lock-builtin-face)
6448 ((and target-name prop)
6449 (cond
6450 ((string= target-name "Date")
6451 (if (string-match js2-ecma-date-props prop-name)
6452 'font-lock-builtin-face))
6453 ((string= target-name "Math")
6454 (if (string-match js2-ecma-math-funcs prop-name)
6455 'font-lock-builtin-face))))))
6456 (prop
6457 (if (string-match js2-ecma-global-funcs prop-name)
6458 'font-lock-builtin-face)))
6459 (cond
6460 ((and target prop)
6461 (cond
6462 ((string= target-name "Number")
6463 (if (string-match js2-ecma-number-props prop-name)
6464 'font-lock-constant-face))
6465 ((string= target-name "Math")
6466 (if (string-match js2-ecma-math-props prop-name)
6467 'font-lock-constant-face))))
6468 (prop
6469 (if (string-match js2-ecma-object-props prop-name)
6470 'font-lock-constant-face))))))
6471 (when face
6472 (let ((pos (+ (js2-node-pos parent) ; absolute
6473 (js2-node-pos prop)))) ; relative
6474 (js2-set-face pos
6475 (+ pos (js2-node-len prop))
6476 face 'record)))))))
6477
6478 (defun js2-parse-highlight-member-expr-node (node)
6479 "Perform syntax highlighting of EcmaScript built-in properties.
6480 The variable `js2-highlight-level' governs this highighting."
6481 (let (face target prop name pos end parent call-p callee)
6482 (cond
6483 ;; case 1: simple name, e.g. foo
6484 ((js2-name-node-p node)
6485 (setq name (js2-name-node-name node))
6486 ;; possible for name to be nil in rare cases - saw it when
6487 ;; running js2-mode on an elisp buffer. Might as well try to
6488 ;; make it so js2-mode never barfs.
6489 (when name
6490 (setq face (if (string-match js2-ecma-global-props name)
6491 'font-lock-constant-face))
6492 (when face
6493 (setq pos (js2-node-pos node)
6494 end (+ pos (js2-node-len node)))
6495 (js2-set-face pos end face 'record))))
6496 ;; case 2: property access or function call
6497 ((or (js2-prop-get-node-p node)
6498 ;; highlight function call if expr is a prop-get node
6499 ;; or a plain name (i.e. unqualified function call)
6500 (and (setq call-p (js2-call-node-p node))
6501 (setq callee (js2-call-node-target node)) ; separate setq!
6502 (or (js2-prop-get-node-p callee)
6503 (js2-name-node-p callee))))
6504 (setq parent node
6505 node (if call-p callee node))
6506 (if (and call-p (js2-name-node-p callee))
6507 (setq prop callee)
6508 (setq target (js2-prop-get-node-left node)
6509 prop (js2-prop-get-node-right node)))
6510 (cond
6511 ((js2-name-node-p prop)
6512 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6513 (js2-parse-highlight-prop-get parent target prop call-p))
6514 ((js2-name-node-p target)
6515 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6516 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6517
6518 (defun js2-parse-highlight-member-expr-fn-name (expr)
6519 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6520 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6521 We currently only handle the case where the last component is a prop-get
6522 of a simple name. Called before EXPR has a parent node."
6523 (let (pos
6524 (name (and (js2-prop-get-node-p expr)
6525 (js2-prop-get-node-right expr))))
6526 (when (js2-name-node-p name)
6527 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6528 (js2-node-pos name)))
6529 (+ pos (js2-node-len name))
6530 'font-lock-function-name-face
6531 'record))))
6532
6533 ;; source: http://jsdoc.sourceforge.net/
6534 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6535 ;; allows type specifications, and needs work before entering the wild.
6536
6537 (defconst js2-jsdoc-param-tag-regexp
6538 (concat "^\\s-*\\*+\\s-*\\(@"
6539 "\\(?:param\\|argument\\)"
6540 "\\)"
6541 "\\s-*\\({[^}]+}\\)?" ; optional type
6542 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6543 "\\>")
6544 "Matches jsdoc tags with optional type and optional param name.")
6545
6546 (defconst js2-jsdoc-typed-tag-regexp
6547 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6548 (regexp-opt
6549 '("enum"
6550 "extends"
6551 "field"
6552 "id"
6553 "implements"
6554 "lends"
6555 "mods"
6556 "requires"
6557 "return"
6558 "returns"
6559 "throw"
6560 "throws"))
6561 "\\)\\)\\s-*\\({[^}]+}\\)?")
6562 "Matches jsdoc tags with optional type.")
6563
6564 (defconst js2-jsdoc-arg-tag-regexp
6565 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6566 (regexp-opt
6567 '("alias"
6568 "augments"
6569 "borrows"
6570 "bug"
6571 "base"
6572 "config"
6573 "default"
6574 "define"
6575 "exception"
6576 "function"
6577 "member"
6578 "memberOf"
6579 "name"
6580 "namespace"
6581 "property"
6582 "since"
6583 "suppress"
6584 "this"
6585 "throws"
6586 "type"
6587 "version"))
6588 "\\)\\)\\s-+\\([^ \t]+\\)")
6589 "Matches jsdoc tags with a single argument.")
6590
6591 (defconst js2-jsdoc-empty-tag-regexp
6592 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6593 (regexp-opt
6594 '("addon"
6595 "author"
6596 "class"
6597 "const"
6598 "constant"
6599 "constructor"
6600 "constructs"
6601 "deprecated"
6602 "desc"
6603 "description"
6604 "event"
6605 "example"
6606 "exec"
6607 "export"
6608 "fileoverview"
6609 "final"
6610 "function"
6611 "hidden"
6612 "ignore"
6613 "implicitCast"
6614 "inheritDoc"
6615 "inner"
6616 "interface"
6617 "license"
6618 "noalias"
6619 "noshadow"
6620 "notypecheck"
6621 "override"
6622 "owner"
6623 "preserve"
6624 "preserveTry"
6625 "private"
6626 "protected"
6627 "public"
6628 "static"
6629 "supported"
6630 ))
6631 "\\)\\)\\s-*")
6632 "Matches empty jsdoc tags.")
6633
6634 (defconst js2-jsdoc-link-tag-regexp
6635 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6636 "Matches a jsdoc link or code tag.")
6637
6638 (defconst js2-jsdoc-see-tag-regexp
6639 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6640 "Matches a jsdoc @see tag.")
6641
6642 (defconst js2-jsdoc-html-tag-regexp
6643 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6644 "Matches a simple (no attributes) html start- or end-tag.")
6645
6646 (defun js2-jsdoc-highlight-helper ()
6647 (js2-set-face (match-beginning 1)
6648 (match-end 1)
6649 'js2-jsdoc-tag)
6650 (if (match-beginning 2)
6651 (if (save-excursion
6652 (goto-char (match-beginning 2))
6653 (= (char-after) ?{))
6654 (js2-set-face (1+ (match-beginning 2))
6655 (1- (match-end 2))
6656 'js2-jsdoc-type)
6657 (js2-set-face (match-beginning 2)
6658 (match-end 2)
6659 'js2-jsdoc-value)))
6660 (if (match-beginning 3)
6661 (js2-set-face (match-beginning 3)
6662 (match-end 3)
6663 'js2-jsdoc-value)))
6664
6665 (defun js2-highlight-jsdoc (ast)
6666 "Highlight doc comment tags."
6667 (let ((comments (js2-ast-root-comments ast))
6668 beg end)
6669 (save-excursion
6670 (dolist (node comments)
6671 (when (eq (js2-comment-node-format node) 'jsdoc)
6672 (setq beg (js2-node-abs-pos node)
6673 end (+ beg (js2-node-len node)))
6674 (save-restriction
6675 (narrow-to-region beg end)
6676 (dolist (re (list js2-jsdoc-param-tag-regexp
6677 js2-jsdoc-typed-tag-regexp
6678 js2-jsdoc-arg-tag-regexp
6679 js2-jsdoc-link-tag-regexp
6680 js2-jsdoc-see-tag-regexp
6681 js2-jsdoc-empty-tag-regexp))
6682 (goto-char beg)
6683 (while (re-search-forward re nil t)
6684 (js2-jsdoc-highlight-helper)))
6685 ;; simple highlighting for html tags
6686 (goto-char beg)
6687 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6688 (js2-set-face (match-beginning 1)
6689 (match-end 1)
6690 'js2-jsdoc-html-tag-delimiter)
6691 (js2-set-face (match-beginning 2)
6692 (match-end 2)
6693 'js2-jsdoc-html-tag-name)
6694 (js2-set-face (match-beginning 3)
6695 (match-end 3)
6696 'js2-jsdoc-html-tag-delimiter))))))))
6697
6698 (defun js2-highlight-assign-targets (_node left right)
6699 "Highlight function properties and external variables."
6700 (let (leftpos name)
6701 ;; highlight vars and props assigned function values
6702 (when (or (js2-function-node-p right)
6703 (js2-class-node-p right))
6704 (cond
6705 ;; var foo = function() {...}
6706 ((js2-name-node-p left)
6707 (setq name left))
6708 ;; foo.bar.baz = function() {...}
6709 ((and (js2-prop-get-node-p left)
6710 (js2-name-node-p (js2-prop-get-node-right left)))
6711 (setq name (js2-prop-get-node-right left))))
6712 (when name
6713 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6714 (+ leftpos (js2-node-len name))
6715 'font-lock-function-name-face
6716 'record)))))
6717
6718 (defun js2-record-name-node (node)
6719 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6720 later. NODE must be a name node."
6721 (let ((leftpos (js2-node-abs-pos node)))
6722 (push (list node js2-current-scope
6723 leftpos
6724 (+ leftpos (js2-node-len node)))
6725 js2-recorded-identifiers)))
6726
6727 (defun js2-highlight-undeclared-vars ()
6728 "After entire parse is finished, look for undeclared variable references.
6729 We have to wait until entire buffer is parsed, since JavaScript permits var
6730 decls to occur after they're used.
6731
6732 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6733 it is considered declared."
6734 (let (name)
6735 (dolist (entry js2-recorded-identifiers)
6736 (destructuring-bind (name-node scope pos end) entry
6737 (setq name (js2-name-node-name name-node))
6738 (unless (or (member name js2-global-externs)
6739 (member name js2-default-externs)
6740 (member name js2-additional-externs)
6741 (js2-get-defining-scope scope name))
6742 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6743 'js2-external-variable))))
6744 (setq js2-recorded-identifiers nil)))
6745
6746 (defun js2-set-default-externs ()
6747 "Set the value of `js2-default-externs' based on the various
6748 `js2-include-?-externs' variables."
6749 (setq js2-default-externs
6750 (append js2-ecma-262-externs
6751 (if js2-include-browser-externs js2-browser-externs)
6752 (if (and js2-include-browser-externs
6753 (>= js2-language-version 200)) js2-harmony-externs)
6754 (if js2-include-rhino-externs js2-rhino-externs)
6755 (if js2-include-node-externs js2-node-externs)
6756 (if (or js2-include-browser-externs js2-include-node-externs)
6757 js2-typed-array-externs))))
6758
6759 (defun js2-apply-jslint-globals ()
6760 (setq js2-additional-externs
6761 (nconc (js2-get-jslint-globals)
6762 js2-additional-externs)))
6763
6764 (defun js2-get-jslint-globals ()
6765 (loop for node in (js2-ast-root-comments js2-mode-ast)
6766 when (and (eq 'block (js2-comment-node-format node))
6767 (save-excursion
6768 (goto-char (js2-node-abs-pos node))
6769 (looking-at "/\\*global ")))
6770 append (js2-get-jslint-globals-in
6771 (match-end 0)
6772 (js2-node-abs-end node))))
6773
6774 (defun js2-get-jslint-globals-in (beg end)
6775 (let (res)
6776 (save-excursion
6777 (goto-char beg)
6778 (while (re-search-forward js2-mode-identifier-re end t)
6779 (let ((match (match-string 0)))
6780 (unless (member match '("true" "false"))
6781 (push match res)))))
6782 (nreverse res)))
6783
6784 ;;; IMenu support
6785
6786 ;; We currently only support imenu, but eventually should support speedbar and
6787 ;; possibly other browsing mechanisms.
6788
6789 ;; The basic strategy is to identify function assignment targets of the form
6790 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6791 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6792 ;; for imenu after parsing is finished.
6793
6794 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6795 ;; JavaScript, and the general problem is undecidable. However, several forms
6796 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6797 ;; include:
6798
6799 ;; function foo() -- function declaration
6800 ;; foo = function() -- function expression assigned to variable
6801 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6802 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6803 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6804 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6805 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6806 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6807 ;; function foo() {function bar() {...}} -- nested function
6808 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6809
6810 ;; This list boils down to a few forms that can be combined recursively.
6811 ;; Top-level named function declarations include both the left-hand (name)
6812 ;; and the right-hand (function value) expressions needed to produce an imenu
6813 ;; entry. The other "right-hand" forms we need to look for are:
6814 ;; - functions declared as props/getters/setters in object literals
6815 ;; - nested named function declarations
6816 ;; The "left-hand" expressions that functions can be assigned to include:
6817 ;; - local/global variables
6818 ;; - nested property-get expressions like a.b.c.d
6819 ;; - element gets like foo[10] or foo['bar'] where the index
6820 ;; expression can be trivially converted to a property name. They
6821 ;; effectively then become property gets.
6822
6823 ;; All the different definition types are canonicalized into the form
6824 ;; foo.bar.baz = position-of-function-keyword
6825
6826 ;; We need to build a trie-like structure for imenu. As an example,
6827 ;; consider the following JavaScript code:
6828
6829 ;; a = function() {...} // function at position 5
6830 ;; b = function() {...} // function at position 25
6831 ;; foo = function() {...} // function at position 100
6832 ;; foo.bar = function() {...} // function at position 200
6833 ;; foo.bar.baz = function() {...} // function at position 300
6834 ;; foo.bar.zab = function() {...} // function at position 400
6835
6836 ;; During parsing we accumulate an entry for each definition in
6837 ;; the variable `js2-imenu-recorder', like so:
6838
6839 ;; '((fn a 5)
6840 ;; (fn b 25)
6841 ;; (fn foo 100)
6842 ;; (fn foo bar 200)
6843 ;; (fn foo bar baz 300)
6844 ;; (fn foo bar zab 400))
6845
6846 ;; Where 'fn' is the respective function node.
6847 ;; After parsing these entries are merged into this alist-trie:
6848
6849 ;; '((a . 1)
6850 ;; (b . 2)
6851 ;; (foo (<definition> . 3)
6852 ;; (bar (<definition> . 6)
6853 ;; (baz . 100)
6854 ;; (zab . 200))))
6855
6856 ;; Note the wacky need for a <definition> name. The token can be anything
6857 ;; that isn't a valid JavaScript identifier, because you might make foo
6858 ;; a function and then start setting properties on it that are also functions.
6859
6860 (defun js2-prop-node-name (node)
6861 "Return the name of a node that may be a property-get/property-name.
6862 If NODE is not a valid name-node, string-node or integral number-node,
6863 returns nil. Otherwise returns the string name/value of the node."
6864 (cond
6865 ((js2-name-node-p node)
6866 (js2-name-node-name node))
6867 ((js2-string-node-p node)
6868 (js2-string-node-value node))
6869 ((and (js2-number-node-p node)
6870 (string-match "^[0-9]+$" (js2-number-node-value node)))
6871 (js2-number-node-value node))
6872 ((eq (js2-node-type node) js2-THIS)
6873 "this")
6874 ((eq (js2-node-type node) js2-SUPER)
6875 "super")))
6876
6877 (defun js2-node-qname-component (node)
6878 "Return the name of this node, if it contributes to a qname.
6879 Returns nil if the node doesn't contribute."
6880 (copy-sequence
6881 (or (js2-prop-node-name node)
6882 (if (and (js2-function-node-p node)
6883 (js2-function-node-name node))
6884 (js2-name-node-name (js2-function-node-name node))))))
6885
6886 (defun js2-record-imenu-entry (fn-node qname pos)
6887 "Add an entry to `js2-imenu-recorder'.
6888 FN-NODE should be the current item's function node.
6889
6890 Associate FN-NODE with its QNAME for later lookup.
6891 This is used in postprocessing the chain list. For each chain, we find
6892 the parent function, look up its qname, then prepend a copy of it to the chain."
6893 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6894 (unless js2-imenu-function-map
6895 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6896 (puthash fn-node qname js2-imenu-function-map))
6897
6898 (defun js2-record-imenu-functions (node &optional var)
6899 "Record function definitions for imenu.
6900 NODE is a function node or an object literal.
6901 VAR, if non-nil, is the expression that NODE is being assigned to.
6902 When passed arguments of wrong type, does nothing."
6903 (when js2-parse-ide-mode
6904 (let ((fun-p (js2-function-node-p node))
6905 qname fname-node)
6906 (cond
6907 ;; non-anonymous function declaration?
6908 ((and fun-p
6909 (not var)
6910 (setq fname-node (js2-function-node-name node)))
6911 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6912 ;; for remaining forms, compute left-side tree branch first
6913 ((and var (setq qname (js2-compute-nested-prop-get var)))
6914 (cond
6915 ;; foo.bar.baz = function
6916 (fun-p
6917 (js2-record-imenu-entry node qname (js2-node-pos node)))
6918 ;; foo.bar.baz = object-literal
6919 ;; look for nested functions: {a: {b: function() {...} }}
6920 ((js2-object-node-p node)
6921 ;; Node position here is still absolute, since the parser
6922 ;; passes the assignment target and value expressions
6923 ;; to us before they are added as children of the assignment node.
6924 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6925
6926 (defun js2-compute-nested-prop-get (node)
6927 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6928 component nodes as a list. Otherwise return nil. Element-gets are treated
6929 as property-gets if the index expression is a string, or a positive integer."
6930 (let (left right head)
6931 (cond
6932 ((or (js2-name-node-p node)
6933 (js2-this-or-super-node-p node))
6934 (list node))
6935 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6936 ((js2-prop-get-node-p node) ; foo.bar
6937 (setq left (js2-prop-get-node-left node)
6938 right (js2-prop-get-node-right node))
6939 (if (setq head (js2-compute-nested-prop-get left))
6940 (nconc head (list right))))
6941 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6942 (setq left (js2-elem-get-node-target node)
6943 right (js2-elem-get-node-element node))
6944 (if (or (js2-string-node-p right) ; ['bar']
6945 (and (js2-number-node-p right) ; [10]
6946 (string-match "^[0-9]+$"
6947 (js2-number-node-value right))))
6948 (if (setq head (js2-compute-nested-prop-get left))
6949 (nconc head (list right))))))))
6950
6951 (defun js2-record-object-literal (node qname pos)
6952 "Recursively process an object literal looking for functions.
6953 NODE is an object literal that is the right-hand child of an assignment
6954 expression. QNAME is a list of nodes representing the assignment target,
6955 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6956 POS is the absolute position of the node.
6957 We do a depth-first traversal of NODE. For any functions we find,
6958 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6959 (let (right)
6960 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6961 (let ((left (js2-infix-node-left e))
6962 ;; Element positions are relative to the parent position.
6963 (pos (+ pos (js2-node-pos e))))
6964 (cond
6965 ;; foo: function() {...}
6966 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6967 (when (js2-prop-node-name left)
6968 ;; As a policy decision, we record the position of the property,
6969 ;; not the position of the `function' keyword, since the property
6970 ;; is effectively the name of the function.
6971 (js2-record-imenu-entry right (append qname (list left)) pos)))
6972 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6973 ((js2-object-node-p right)
6974 (js2-record-object-literal right
6975 (append qname (list (js2-infix-node-left e)))
6976 (+ pos (js2-node-pos right)))))))))
6977
6978 (defun js2-node-top-level-decl-p (node)
6979 "Return t if NODE's name is defined in the top-level scope.
6980 Also returns t if NODE's name is not defined in any scope, since it implies
6981 that it's an external variable, which must also be in the top-level scope."
6982 (let* ((name (js2-prop-node-name node))
6983 (this-scope (js2-node-get-enclosing-scope node))
6984 defining-scope)
6985 (cond
6986 ((js2-this-or-super-node-p node)
6987 nil)
6988 ((null this-scope)
6989 t)
6990 ((setq defining-scope (js2-get-defining-scope this-scope name))
6991 (js2-ast-root-p defining-scope))
6992 (t t))))
6993
6994 (defun js2-wrapper-function-p (node)
6995 "Return t if NODE is a function expression that's immediately invoked.
6996 NODE must be `js2-function-node'."
6997 (let ((parent (js2-node-parent node)))
6998 (or
6999 ;; function(){...}();
7000 (and (js2-call-node-p parent)
7001 (eq node (js2-call-node-target parent)))
7002 (and (js2-paren-node-p parent)
7003 ;; (function(){...})();
7004 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7005 ;; (function(){...}).call(this);
7006 (and (js2-prop-get-node-p parent)
7007 (member (js2-name-node-name (js2-prop-get-node-right parent))
7008 '("call" "apply"))
7009 (js2-call-node-p (js2-node-parent parent))))))))
7010
7011 (defun js2-browse-postprocess-chains ()
7012 "Modify function-declaration name chains after parsing finishes.
7013 Some of the information is only available after the parse tree is complete.
7014 For instance, processing a nested scope requires a parent function node."
7015 (let (result fn parent-qname p elem)
7016 (dolist (entry js2-imenu-recorder)
7017 ;; function node goes first
7018 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7019 ;; Examine head's defining scope:
7020 ;; Pre-processed chain, or top-level/external, keep as-is.
7021 (if (or (stringp head) (js2-node-top-level-decl-p head))
7022 (push chain result)
7023 (when (js2-this-or-super-node-p head)
7024 (setq chain (cdr chain))) ; discard this-node
7025 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7026 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7027 (when (eq parent-qname 'not-found)
7028 ;; anonymous function expressions are not recorded
7029 ;; during the parse, so we need to handle this case here
7030 (setq parent-qname
7031 (if (js2-wrapper-function-p fn)
7032 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7033 (if (js2-ast-root-p grandparent)
7034 nil
7035 (gethash grandparent js2-imenu-function-map 'skip)))
7036 'skip))
7037 (puthash fn parent-qname js2-imenu-function-map))
7038 (if (eq parent-qname 'skip)
7039 ;; We don't show it, let's record that fact.
7040 (remhash current-fn js2-imenu-function-map)
7041 ;; Prepend parent fn qname to this chain.
7042 (let ((qname (append parent-qname chain)))
7043 (puthash current-fn (butlast qname) js2-imenu-function-map)
7044 (push qname result)))))))
7045 ;; Collect chains obtained by third-party code.
7046 (let (js2-imenu-recorder)
7047 (run-hooks 'js2-build-imenu-callbacks)
7048 (dolist (entry js2-imenu-recorder)
7049 (push (cdr entry) result)))
7050 ;; Finally replace each node in each chain with its name.
7051 (dolist (chain result)
7052 (setq p chain)
7053 (while p
7054 (if (js2-node-p (setq elem (car p)))
7055 (setcar p (js2-node-qname-component elem)))
7056 (setq p (cdr p))))
7057 result))
7058
7059 ;; Merge name chains into a trie-like tree structure of nested lists.
7060 ;; To simplify construction of the trie, we first build it out using the rule
7061 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7062 ;; [key, num-or-list]. The second element can be a number; if so, this key
7063 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7064 ;; associated with the key at this level.) Otherwise the second element is
7065 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7066 ;; a simple recursive formulation.
7067 ;;
7068 ;; js2-mode is building the data structure for imenu. The imenu documentation
7069 ;; claims that it's the structure above, but in practice it wants the children
7070 ;; at the same list level as the key for that level, which is how I've drawn
7071 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7072 ;; list wrapper around the children at each level.
7073 ;;
7074 ;; A completed nested imenu-alist entry looks like this:
7075 ;; '(("foo"
7076 ;; ("<definition>" . 7)
7077 ;; ("bar"
7078 ;; ("a" . 40)
7079 ;; ("b" . 60))))
7080 ;;
7081 ;; In particular, the documentation for `imenu--index-alist' says that
7082 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7083 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7084
7085 (defun js2-treeify (lst)
7086 "Convert (a b c d) to (a ((b ((c d)))))."
7087 (if (null (cddr lst)) ; list length <= 2
7088 lst
7089 (list (car lst) (list (js2-treeify (cdr lst))))))
7090
7091 (defun js2-build-alist-trie (chains trie)
7092 "Merge declaration name chains into a trie-like alist structure for imenu.
7093 CHAINS is the qname chain list produced during parsing. TRIE is a
7094 list of elements built up so far."
7095 (let (head tail pos branch kids)
7096 (dolist (chain chains)
7097 (setq head (car chain)
7098 tail (cdr chain)
7099 pos (if (numberp (car tail)) (car tail))
7100 branch (js2-find-if (lambda (n)
7101 (string= (car n) head))
7102 trie)
7103 kids (second branch))
7104 (cond
7105 ;; case 1: this key isn't in the trie yet
7106 ((null branch)
7107 (if trie
7108 (setcdr (last trie) (list (js2-treeify chain)))
7109 (setq trie (list (js2-treeify chain)))))
7110 ;; case 2: key is present with a single number entry: replace w/ list
7111 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7112 ;; ("<definition>" 20)))
7113 ((numberp kids)
7114 (setcar (cdr branch)
7115 (list (list "<definition-1>" kids)
7116 (if pos
7117 (list "<definition-2>" pos)
7118 (js2-treeify tail)))))
7119 ;; case 3: key is there (with kids), and we're a number entry
7120 (pos
7121 (setcdr (last kids)
7122 (list
7123 (list (format "<definition-%d>"
7124 (1+ (loop for kid in kids
7125 count (eq ?< (aref (car kid) 0)))))
7126 pos))))
7127 ;; case 4: key is there with kids, need to merge in our chain
7128 (t
7129 (js2-build-alist-trie (list tail) kids))))
7130 trie))
7131
7132 (defun js2-flatten-trie (trie)
7133 "Convert TRIE to imenu-format.
7134 Recurses through nodes, and for each one whose second element is a list,
7135 appends the list's flattened elements to the current element. Also
7136 changes the tails into conses. For instance, this pre-flattened trie
7137
7138 '(a ((b 20)
7139 (c ((d 30)
7140 (e 40)))))
7141
7142 becomes
7143
7144 '(a (b . 20)
7145 (c (d . 30)
7146 (e . 40)))
7147
7148 Note that the root of the trie has no key, just a list of chains.
7149 This is also true for the value of any key with multiple children,
7150 e.g. key 'c' in the example above."
7151 (cond
7152 ((listp (car trie))
7153 (mapcar #'js2-flatten-trie trie))
7154 (t
7155 (if (numberp (second trie))
7156 (cons (car trie) (second trie))
7157 ;; else pop list and append its kids
7158 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7159
7160 (defun js2-build-imenu-index ()
7161 "Turn `js2-imenu-recorder' into an imenu data structure."
7162 (when (eq js2-imenu-recorder 'empty)
7163 (setq js2-imenu-recorder nil))
7164 (let* ((chains (js2-browse-postprocess-chains))
7165 (result (js2-build-alist-trie chains nil)))
7166 (js2-flatten-trie result)))
7167
7168 (defun js2-test-print-chains (chains)
7169 "Print a list of qname chains.
7170 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7171 i.e. one or more nodes, and an integer position as the list tail."
7172 (mapconcat (lambda (chain)
7173 (concat "("
7174 (mapconcat (lambda (elem)
7175 (if (js2-node-p elem)
7176 (or (js2-node-qname-component elem)
7177 "nil")
7178 (number-to-string elem)))
7179 chain
7180 " ")
7181 ")"))
7182 chains
7183 "\n"))
7184
7185 ;;; Parser
7186
7187 (defconst js2-version "1.8.5"
7188 "Version of JavaScript supported.")
7189
7190 (defun js2-record-face (face &optional token)
7191 "Record a style run of FACE for TOKEN or the current token."
7192 (unless token (setq token (js2-current-token)))
7193 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7194
7195 (defsubst js2-node-end (n)
7196 "Computes the absolute end of node N.
7197 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7198 is only true until the node is added to its parent; i.e., while parsing."
7199 (+ (js2-node-pos n)
7200 (js2-node-len n)))
7201
7202 (defun js2-record-comment (token)
7203 "Record a comment in `js2-scanned-comments'."
7204 (let ((ct (js2-token-comment-type token))
7205 (beg (js2-token-beg token))
7206 (end (js2-token-end token)))
7207 (push (make-js2-comment-node :len (- end beg)
7208 :format ct)
7209 js2-scanned-comments)
7210 (when js2-parse-ide-mode
7211 (js2-record-face (if (eq ct 'jsdoc)
7212 'font-lock-doc-face
7213 'font-lock-comment-face)
7214 token)
7215 (when (memq ct '(html preprocessor))
7216 ;; Tell cc-engine the bounds of the comment.
7217 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7218
7219 (defun js2-peek-token ()
7220 "Return the next token type without consuming it.
7221 If `js2-ti-lookahead' is positive, return the type of next token
7222 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7223 (if (not (zerop js2-ti-lookahead))
7224 (js2-token-type
7225 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7226 (let ((tt (js2-get-token-internal nil)))
7227 (js2-unget-token)
7228 tt)))
7229
7230 (defalias 'js2-next-token 'js2-get-token)
7231
7232 (defun js2-match-token (match &optional dont-unget)
7233 "Get next token and return t if it matches MATCH, a bytecode.
7234 Returns nil and consumes nothing if MATCH is not the next token."
7235 (if (/= (js2-get-token) match)
7236 (ignore (unless dont-unget (js2-unget-token)))
7237 t))
7238
7239 (defun js2-match-contextual-kwd (name)
7240 "Consume and return t if next token is `js2-NAME', and its
7241 string is NAME. Returns nil and keeps current token otherwise."
7242 (if (or (/= (js2-get-token) js2-NAME)
7243 (not (string= (js2-current-token-string) name)))
7244 (progn
7245 (js2-unget-token)
7246 nil)
7247 (js2-record-face 'font-lock-keyword-face)
7248 t))
7249
7250 (defun js2-valid-prop-name-token (tt)
7251 (or (= tt js2-NAME)
7252 (and js2-allow-keywords-as-property-names
7253 (plusp tt)
7254 (or (= tt js2-RESERVED)
7255 (aref js2-kwd-tokens tt)))))
7256
7257 (defun js2-match-prop-name ()
7258 "Consume token and return t if next token is a valid property name.
7259 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7260 is non-nil and it's a keyword token."
7261 (if (js2-valid-prop-name-token (js2-get-token))
7262 t
7263 (js2-unget-token)
7264 nil))
7265
7266 (defun js2-must-match-prop-name (msg-id &optional pos len)
7267 (if (js2-match-prop-name)
7268 t
7269 (js2-report-error msg-id nil pos len)
7270 nil))
7271
7272 (defun js2-peek-token-or-eol ()
7273 "Return js2-EOL if the next token immediately follows a newline.
7274 Else returns the next token. Used in situations where we don't
7275 consider certain token types valid if they are preceded by a newline.
7276 One example is the postfix ++ or -- operator, which has to be on the
7277 same line as its operand."
7278 (let ((tt (js2-get-token))
7279 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7280 (js2-unget-token)
7281 (if follows-eol
7282 js2-EOL
7283 tt)))
7284
7285 (defun js2-must-match (token msg-id &optional pos len)
7286 "Match next token to token code TOKEN, or record a syntax error.
7287 MSG-ID is the error message to report if the match fails.
7288 Returns t on match, nil if no match."
7289 (if (js2-match-token token t)
7290 t
7291 (js2-report-error msg-id nil pos len)
7292 (js2-unget-token)
7293 nil))
7294
7295 (defun js2-must-match-name (msg-id)
7296 (if (js2-match-token js2-NAME t)
7297 t
7298 (if (eq (js2-current-token-type) js2-RESERVED)
7299 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7300 (js2-report-error msg-id)
7301 (js2-unget-token))
7302 nil))
7303
7304 (defsubst js2-inside-function ()
7305 (plusp js2-nesting-of-function))
7306
7307 (defun js2-set-requires-activation ()
7308 (if (js2-function-node-p js2-current-script-or-fn)
7309 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7310
7311 (defun js2-check-activation-name (name _token)
7312 (when (js2-inside-function)
7313 ;; skip language-version 1.2 check from Rhino
7314 (if (or (string= "arguments" name)
7315 (and js2-compiler-activation-names ; only used in codegen
7316 (gethash name js2-compiler-activation-names)))
7317 (js2-set-requires-activation))))
7318
7319 (defun js2-set-is-generator ()
7320 (let ((fn-node js2-current-script-or-fn))
7321 (when (and (js2-function-node-p fn-node)
7322 (not (js2-function-node-generator-type fn-node)))
7323 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7324
7325 (defun js2-must-have-xml ()
7326 (unless js2-compiler-xml-available
7327 (js2-report-error "msg.XML.not.available")))
7328
7329 (defun js2-push-scope (scope)
7330 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7331 (assert (js2-scope-p scope))
7332 (assert (null (js2-scope-parent-scope scope)))
7333 (assert (not (eq js2-current-scope scope)))
7334 (setf (js2-scope-parent-scope scope) js2-current-scope
7335 js2-current-scope scope))
7336
7337 (defsubst js2-pop-scope ()
7338 (setq js2-current-scope
7339 (js2-scope-parent-scope js2-current-scope)))
7340
7341 (defun js2-enter-loop (loop-node)
7342 (push loop-node js2-loop-set)
7343 (push loop-node js2-loop-and-switch-set)
7344 (js2-push-scope loop-node)
7345 ;; Tell the current labeled statement (if any) its statement,
7346 ;; and set the jump target of the first label to the loop.
7347 ;; These are used in `js2-parse-continue' to verify that the
7348 ;; continue target is an actual labeled loop. (And for codegen.)
7349 (when js2-labeled-stmt
7350 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7351 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7352 js2-labeled-stmt))) loop-node)))
7353
7354 (defun js2-exit-loop ()
7355 (pop js2-loop-set)
7356 (pop js2-loop-and-switch-set)
7357 (js2-pop-scope))
7358
7359 (defsubst js2-enter-switch (switch-node)
7360 (push switch-node js2-loop-and-switch-set))
7361
7362 (defsubst js2-exit-switch ()
7363 (pop js2-loop-and-switch-set))
7364
7365 (defun js2-parse (&optional buf cb)
7366 "Tell the js2 parser to parse a region of JavaScript.
7367
7368 BUF is a buffer or buffer name containing the code to parse.
7369 Call `narrow-to-region' first to parse only part of the buffer.
7370
7371 The returned AST root node is given some additional properties:
7372 `node-count' - total number of nodes in the AST
7373 `buffer' - BUF. The buffer it refers to may change or be killed,
7374 so the value is not necessarily reliable.
7375
7376 An optional callback CB can be specified to report parsing
7377 progress. If `(functionp CB)' returns t, it will be called with
7378 the current line number once before parsing begins, then again
7379 each time the lexer reaches a new line number.
7380
7381 CB can also be a list of the form `(symbol cb ...)' to specify
7382 multiple callbacks with different criteria. Each symbol is a
7383 criterion keyword, and the following element is the callback to
7384 call
7385
7386 :line - called whenever the line number changes
7387 :token - called for each new token consumed
7388
7389 The list of criteria could be extended to include entering or
7390 leaving a statement, an expression, or a function definition."
7391 (if (and cb (not (functionp cb)))
7392 (error "criteria callbacks not yet implemented"))
7393 (let ((inhibit-point-motion-hooks t)
7394 (js2-compiler-xml-available (>= js2-language-version 160))
7395 ;; This is a recursive-descent parser, so give it a big stack.
7396 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7397 (max-specpdl-size (max max-specpdl-size 3000))
7398 (case-fold-search nil)
7399 ast)
7400 (with-current-buffer (or buf (current-buffer))
7401 (setq js2-scanned-comments nil
7402 js2-parsed-errors nil
7403 js2-parsed-warnings nil
7404 js2-imenu-recorder nil
7405 js2-imenu-function-map nil
7406 js2-label-set nil)
7407 (js2-init-scanner)
7408 (setq ast (with-silent-modifications
7409 (js2-do-parse)))
7410 (unless js2-ts-hit-eof
7411 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7412 (setf (js2-ast-root-errors ast) js2-parsed-errors
7413 (js2-ast-root-warnings ast) js2-parsed-warnings)
7414 ;; if we didn't find any declarations, put a dummy in this list so we
7415 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7416 (unless js2-imenu-recorder
7417 (setq js2-imenu-recorder 'empty))
7418 (run-hooks 'js2-parse-finished-hook)
7419 ast)))
7420
7421 ;; Corresponds to Rhino's Parser.parse() method.
7422 (defun js2-do-parse ()
7423 "Parse current buffer starting from current point.
7424 Scanner should be initialized."
7425 (let ((pos js2-ts-cursor)
7426 (end js2-ts-cursor) ; in case file is empty
7427 root n tt)
7428 ;; initialize buffer-local parsing vars
7429 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7430 js2-current-script-or-fn root
7431 js2-current-scope root
7432 js2-nesting-of-function 0
7433 js2-labeled-stmt nil
7434 js2-recorded-identifiers nil) ; for js2-highlight
7435 (while (/= (setq tt (js2-get-token)) js2-EOF)
7436 (if (= tt js2-FUNCTION)
7437 (progn
7438 (setq n (if js2-called-by-compile-function
7439 (js2-parse-function-expr)
7440 (js2-parse-function-stmt))))
7441 ;; not a function - parse a statement
7442 (js2-unget-token)
7443 (setq n (js2-parse-statement)))
7444 ;; add function or statement to script
7445 (setq end (js2-node-end n))
7446 (js2-block-node-push root n))
7447 ;; add comments to root in lexical order
7448 (when js2-scanned-comments
7449 ;; if we find a comment beyond end of normal kids, use its end
7450 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7451 (dolist (comment js2-scanned-comments)
7452 (push comment (js2-ast-root-comments root))
7453 (js2-node-add-children root comment)))
7454 (setf (js2-node-len root) (- end pos))
7455 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7456 ;; Give extensions a chance to muck with things before highlighting starts.
7457 (let ((js2-additional-externs js2-additional-externs))
7458 (save-excursion
7459 (run-hooks 'js2-post-parse-callbacks))
7460 (js2-highlight-undeclared-vars))
7461 root))
7462
7463 (defun js2-parse-function-closure-body (fn-node)
7464 "Parse a JavaScript 1.8 function closure body."
7465 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7466 (if js2-ts-hit-eof
7467 (js2-report-error "msg.no.brace.body" nil
7468 (js2-node-pos fn-node)
7469 (- js2-ts-cursor (js2-node-pos fn-node)))
7470 (js2-node-add-children fn-node
7471 (setf (js2-function-node-body fn-node)
7472 (js2-parse-expr t))))))
7473
7474 (defun js2-parse-function-body (fn-node)
7475 (js2-must-match js2-LC "msg.no.brace.body"
7476 (js2-node-pos fn-node)
7477 (- js2-ts-cursor (js2-node-pos fn-node)))
7478 (let ((pos (js2-current-token-beg)) ; LC position
7479 (pn (make-js2-block-node)) ; starts at LC position
7480 tt
7481 end)
7482 (incf js2-nesting-of-function)
7483 (unwind-protect
7484 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7485 (= tt js2-EOF)
7486 (= tt js2-RC)))
7487 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7488 (js2-parse-statement)
7489 (js2-get-token)
7490 (js2-parse-function-stmt))))
7491 (decf js2-nesting-of-function))
7492 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7493 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7494 (setq end (js2-current-token-end)))
7495 (setf (js2-node-pos pn) pos
7496 (js2-node-len pn) (- end pos))
7497 (setf (js2-function-node-body fn-node) pn)
7498 (js2-node-add-children fn-node pn)
7499 pn))
7500
7501 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7502 "Declare and fontify destructuring parameters inside NODE.
7503 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7504 (cond
7505 ((js2-name-node-p node)
7506 (let (leftpos)
7507 (js2-define-symbol decl-type (js2-name-node-name node)
7508 node ignore-not-in-block)
7509 (when face
7510 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7511 (+ leftpos (js2-node-len node))
7512 face 'record))))
7513 ((js2-object-node-p node)
7514 (dolist (elem (js2-object-node-elems node))
7515 (js2-define-destruct-symbols
7516 ;; In abbreviated destructuring {a, b}, right == left.
7517 (js2-object-prop-node-right elem)
7518 decl-type face ignore-not-in-block)))
7519 ((js2-array-node-p node)
7520 (dolist (elem (js2-array-node-elems node))
7521 (when elem
7522 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7523 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7524 (js2-node-len node)))))
7525
7526 (defun js2-parse-function-params (function-type fn-node pos)
7527 (if (js2-match-token js2-RP)
7528 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7529 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7530 (eq (js2-current-token-type) js2-NAME)))
7531 params param default-found rest-param-at)
7532 (when paren-free-arrow
7533 (js2-unget-token))
7534 (loop for tt = (js2-peek-token)
7535 do
7536 (cond
7537 ;; destructuring param
7538 ((and (not paren-free-arrow)
7539 (or (= tt js2-LB) (= tt js2-LC)))
7540 (js2-get-token)
7541 (when default-found
7542 (js2-report-error "msg.no.default.after.default.param"))
7543 (setq param (js2-parse-destruct-primary-expr))
7544 (js2-define-destruct-symbols param
7545 js2-LP
7546 'js2-function-param)
7547 (push param params))
7548 ;; variable name
7549 (t
7550 (when (and (>= js2-language-version 200)
7551 (not paren-free-arrow)
7552 (js2-match-token js2-TRIPLEDOT)
7553 (not rest-param-at))
7554 ;; to report errors if there are more parameters
7555 (setq rest-param-at (length params)))
7556 (js2-must-match-name "msg.no.parm")
7557 (js2-record-face 'js2-function-param)
7558 (setq param (js2-create-name-node))
7559 (js2-define-symbol js2-LP (js2-current-token-string) param)
7560 ;; default parameter value
7561 (when (or (and default-found
7562 (not rest-param-at)
7563 (js2-must-match js2-ASSIGN
7564 "msg.no.default.after.default.param"
7565 (js2-node-pos param)
7566 (js2-node-len param)))
7567 (and (>= js2-language-version 200)
7568 (js2-match-token js2-ASSIGN)))
7569 (assert (not paren-free-arrow))
7570 (let* ((pos (js2-node-pos param))
7571 (tt (js2-current-token-type))
7572 (op-pos (- (js2-current-token-beg) pos))
7573 (left param)
7574 (right (js2-parse-assign-expr))
7575 (len (- (js2-node-end right) pos)))
7576 (setq param (make-js2-assign-node
7577 :type tt :pos pos :len len :op-pos op-pos
7578 :left left :right right)
7579 default-found t)
7580 (js2-node-add-children param left right)))
7581 (push param params)))
7582 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7583 (js2-report-error "msg.param.after.rest" nil
7584 (js2-node-pos param) (js2-node-len param)))
7585 while
7586 (js2-match-token js2-COMMA))
7587 (when (and (not paren-free-arrow)
7588 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7589 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7590 (when rest-param-at
7591 (setf (js2-function-node-rest-p fn-node) t))
7592 (dolist (p params)
7593 (js2-node-add-children fn-node p)
7594 (push p (js2-function-node-params fn-node))))))
7595
7596 (defun js2-check-inconsistent-return-warning (fn-node name)
7597 "Possibly show inconsistent-return warning.
7598 Last token scanned is the close-curly for the function body."
7599 (when (and js2-mode-show-strict-warnings
7600 js2-strict-inconsistent-return-warning
7601 (not (js2-has-consistent-return-usage
7602 (js2-function-node-body fn-node))))
7603 ;; Have it extend from close-curly to bol or beginning of block.
7604 (let ((pos (save-excursion
7605 (goto-char (js2-current-token-end))
7606 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7607 (point-at-bol))))
7608 (end (js2-current-token-end)))
7609 (if (plusp (js2-name-node-length name))
7610 (js2-add-strict-warning "msg.no.return.value"
7611 (js2-name-node-name name) pos end)
7612 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7613
7614 (defun js2-parse-function-stmt ()
7615 (let ((pos (js2-current-token-beg))
7616 (star-p (js2-match-token js2-MUL)))
7617 (js2-must-match-name "msg.unnamed.function.stmt")
7618 (let ((name (js2-create-name-node t))
7619 pn member-expr)
7620 (cond
7621 ((js2-match-token js2-LP)
7622 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7623 (js2-allow-member-expr-as-function-name
7624 (setq member-expr (js2-parse-member-expr-tail nil name))
7625 (js2-parse-highlight-member-expr-fn-name member-expr)
7626 (js2-must-match js2-LP "msg.no.paren.parms")
7627 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7628 (js2-function-node-member-expr pn) member-expr)
7629 pn)
7630 (t
7631 (js2-report-error "msg.no.paren.parms")
7632 (make-js2-error-node))))))
7633
7634 (defun js2-parse-function-expr ()
7635 (let ((pos (js2-current-token-beg))
7636 (star-p (js2-match-token js2-MUL))
7637 name)
7638 (when (js2-match-token js2-NAME)
7639 (setq name (js2-create-name-node t)))
7640 (js2-must-match js2-LP "msg.no.paren.parms")
7641 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7642
7643 (defun js2-parse-function (function-type pos star-p &optional name)
7644 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7645 beginning of the first token (function keyword, unless it's an
7646 arrow function), NAME is js2-name-node."
7647 (let (fn-node lp)
7648 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7649 (setq lp (js2-current-token-beg)))
7650 (setf fn-node (make-js2-function-node :pos pos
7651 :name name
7652 :form function-type
7653 :lp (if lp (- lp pos))
7654 :generator-type (and star-p 'STAR)))
7655 (when name
7656 (js2-set-face (js2-node-pos name) (js2-node-end name)
7657 'font-lock-function-name-face 'record)
7658 (when (plusp (js2-name-node-length name))
7659 ;; Function statements define a symbol in the enclosing scope
7660 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7661 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7662 ;; 1. Nested functions are not affected by the dynamic scope flag
7663 ;; as dynamic scope is already a parent of their scope.
7664 ;; 2. Functions defined under the with statement also immune to
7665 ;; this setup, in which case dynamic scope is ignored in favor
7666 ;; of the with object.
7667 (setf (js2-function-node-ignore-dynamic fn-node) t))
7668 ;; dynamically bind all the per-function variables
7669 (let ((js2-current-script-or-fn fn-node)
7670 (js2-current-scope fn-node)
7671 (js2-nesting-of-with 0)
7672 (js2-end-flags 0)
7673 js2-label-set
7674 js2-loop-set
7675 js2-loop-and-switch-set)
7676 (js2-parse-function-params function-type fn-node pos)
7677 (when (eq function-type 'FUNCTION_ARROW)
7678 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7679 (if (and (>= js2-language-version 180)
7680 (/= (js2-peek-token) js2-LC))
7681 (js2-parse-function-closure-body fn-node)
7682 (js2-parse-function-body fn-node))
7683 (js2-check-inconsistent-return-warning fn-node name)
7684
7685 (when name
7686 (js2-node-add-children fn-node name)
7687 ;; Function expressions define a name only in the body of the
7688 ;; function, and only if not hidden by a parameter name
7689 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7690 (null (js2-scope-get-symbol js2-current-scope
7691 (js2-name-node-name name))))
7692 (js2-define-symbol js2-FUNCTION
7693 (js2-name-node-name name)
7694 fn-node))
7695 (when (eq function-type 'FUNCTION_STATEMENT)
7696 (js2-record-imenu-functions fn-node))))
7697
7698 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7699 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7700 ;; We wait until after parsing the function to set its parent scope,
7701 ;; since `js2-define-symbol' needs the defining-scope check to stop
7702 ;; at the function boundary when checking for redeclarations.
7703 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7704 fn-node))
7705
7706 (defun js2-parse-statements (&optional parent)
7707 "Parse a statement list. Last token consumed must be js2-LC.
7708
7709 PARENT can be a `js2-block-node', in which case the statements are
7710 appended to PARENT. Otherwise a new `js2-block-node' is created
7711 and returned.
7712
7713 This function does not match the closing js2-RC: the caller
7714 matches the RC so it can provide a suitable error message if not
7715 matched. This means it's up to the caller to set the length of
7716 the node to include the closing RC. The node start pos is set to
7717 the absolute buffer start position, and the caller should fix it
7718 up to be relative to the parent node. All children of this block
7719 node are given relative start positions and correct lengths."
7720 (let ((pn (or parent (make-js2-block-node)))
7721 tt)
7722 (setf (js2-node-pos pn) (js2-current-token-beg))
7723 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7724 (/= tt js2-RC))
7725 (js2-block-node-push pn (js2-parse-statement)))
7726 pn))
7727
7728 (defun js2-parse-statement ()
7729 (let (pn beg end)
7730 ;; coarse-grained user-interrupt check - needs work
7731 (and js2-parse-interruptable-p
7732 (zerop (% (incf js2-parse-stmt-count)
7733 js2-statements-per-pause))
7734 (input-pending-p)
7735 (throw 'interrupted t))
7736 (setq pn (js2-statement-helper))
7737 ;; no-side-effects warning check
7738 (unless (js2-node-has-side-effects pn)
7739 (setq end (js2-node-end pn))
7740 (save-excursion
7741 (goto-char end)
7742 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7743 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7744 pn))
7745
7746 ;; These correspond to the switch cases in Parser.statementHelper
7747 (defconst js2-parsers
7748 (let ((parsers (make-vector js2-num-tokens
7749 #'js2-parse-expr-stmt)))
7750 (aset parsers js2-BREAK #'js2-parse-break)
7751 (aset parsers js2-CLASS #'js2-parse-class-stmt)
7752 (aset parsers js2-CONST #'js2-parse-const-var)
7753 (aset parsers js2-CONTINUE #'js2-parse-continue)
7754 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7755 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7756 (aset parsers js2-DO #'js2-parse-do)
7757 (aset parsers js2-FOR #'js2-parse-for)
7758 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7759 (aset parsers js2-IF #'js2-parse-if)
7760 (aset parsers js2-LC #'js2-parse-block)
7761 (aset parsers js2-LET #'js2-parse-let-stmt)
7762 (aset parsers js2-NAME #'js2-parse-name-or-label)
7763 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7764 (aset parsers js2-SEMI #'js2-parse-semi)
7765 (aset parsers js2-SWITCH #'js2-parse-switch)
7766 (aset parsers js2-THROW #'js2-parse-throw)
7767 (aset parsers js2-TRY #'js2-parse-try)
7768 (aset parsers js2-VAR #'js2-parse-const-var)
7769 (aset parsers js2-WHILE #'js2-parse-while)
7770 (aset parsers js2-WITH #'js2-parse-with)
7771 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7772 parsers)
7773 "A vector mapping token types to parser functions.")
7774
7775 (defun js2-parse-warn-missing-semi (beg end)
7776 (and js2-mode-show-strict-warnings
7777 js2-strict-missing-semi-warning
7778 (js2-add-strict-warning
7779 "msg.missing.semi" nil
7780 ;; back up to beginning of statement or line
7781 (max beg (save-excursion
7782 (goto-char end)
7783 (point-at-bol)))
7784 end)))
7785
7786 (defconst js2-no-semi-insertion
7787 (list js2-IF
7788 js2-SWITCH
7789 js2-WHILE
7790 js2-DO
7791 js2-FOR
7792 js2-TRY
7793 js2-WITH
7794 js2-LC
7795 js2-ERROR
7796 js2-SEMI
7797 js2-CLASS
7798 js2-FUNCTION)
7799 "List of tokens that don't do automatic semicolon insertion.")
7800
7801 (defconst js2-autoinsert-semi-and-warn
7802 (list js2-ERROR js2-EOF js2-RC))
7803
7804 (defun js2-statement-helper ()
7805 (let* ((tt (js2-get-token))
7806 (first-tt tt)
7807 (parser (if (= tt js2-ERROR)
7808 #'js2-parse-semi
7809 (aref js2-parsers tt)))
7810 pn)
7811 ;; If the statement is set, then it's been told its label by now.
7812 (and js2-labeled-stmt
7813 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7814 (setq js2-labeled-stmt nil))
7815 (setq pn (funcall parser))
7816 ;; Don't do auto semi insertion for certain statement types.
7817 (unless (or (memq first-tt js2-no-semi-insertion)
7818 (js2-labeled-stmt-node-p pn))
7819 (js2-auto-insert-semicolon pn))
7820 pn))
7821
7822 (defun js2-auto-insert-semicolon (pn)
7823 (let* ((tt (js2-get-token))
7824 (pos (js2-node-pos pn)))
7825 (cond
7826 ((= tt js2-SEMI)
7827 ;; extend the node bounds to include the semicolon.
7828 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7829 ((memq tt js2-autoinsert-semi-and-warn)
7830 (js2-unget-token) ; Not ';', do not consume.
7831 ;; Autoinsert ;
7832 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7833 (t
7834 (if (not (js2-token-follows-eol-p (js2-current-token)))
7835 ;; Report error if no EOL or autoinsert ';' otherwise
7836 (js2-report-error "msg.no.semi.stmt")
7837 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7838 (js2-unget-token) ; Not ';', do not consume.
7839 ))))
7840
7841 (defun js2-parse-condition ()
7842 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7843 The parens are discarded and the expression node is returned.
7844 The `pos' field of the return value is set to an absolute position
7845 that must be fixed up by the caller.
7846 Return value is a list (EXPR LP RP), with absolute paren positions."
7847 (let (pn lp rp)
7848 (if (js2-must-match js2-LP "msg.no.paren.cond")
7849 (setq lp (js2-current-token-beg)))
7850 (setq pn (js2-parse-expr))
7851 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7852 (setq rp (js2-current-token-beg)))
7853 ;; Report strict warning on code like "if (a = 7) ..."
7854 (if (and js2-strict-cond-assign-warning
7855 (js2-assign-node-p pn))
7856 (js2-add-strict-warning "msg.equal.as.assign" nil
7857 (js2-node-pos pn)
7858 (+ (js2-node-pos pn)
7859 (js2-node-len pn))))
7860 (list pn lp rp)))
7861
7862 (defun js2-parse-if ()
7863 "Parser for if-statement. Last matched token must be js2-IF."
7864 (let ((pos (js2-current-token-beg))
7865 cond if-true if-false else-pos end pn)
7866 (setq cond (js2-parse-condition)
7867 if-true (js2-parse-statement)
7868 if-false (if (js2-match-token js2-ELSE)
7869 (progn
7870 (setq else-pos (- (js2-current-token-beg) pos))
7871 (js2-parse-statement)))
7872 end (js2-node-end (or if-false if-true))
7873 pn (make-js2-if-node :pos pos
7874 :len (- end pos)
7875 :condition (car cond)
7876 :then-part if-true
7877 :else-part if-false
7878 :else-pos else-pos
7879 :lp (js2-relpos (second cond) pos)
7880 :rp (js2-relpos (third cond) pos)))
7881 (js2-node-add-children pn (car cond) if-true if-false)
7882 pn))
7883
7884 (defun js2-parse-switch ()
7885 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7886 (let ((pos (js2-current-token-beg))
7887 tt pn discriminant has-default case-expr case-node
7888 case-pos cases stmt lp)
7889 (if (js2-must-match js2-LP "msg.no.paren.switch")
7890 (setq lp (js2-current-token-beg)))
7891 (setq discriminant (js2-parse-expr)
7892 pn (make-js2-switch-node :discriminant discriminant
7893 :pos pos
7894 :lp (js2-relpos lp pos)))
7895 (js2-node-add-children pn discriminant)
7896 (js2-enter-switch pn)
7897 (unwind-protect
7898 (progn
7899 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7900 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7901 (js2-must-match js2-LC "msg.no.brace.switch")
7902 (catch 'break
7903 (while t
7904 (setq tt (js2-next-token)
7905 case-pos (js2-current-token-beg))
7906 (cond
7907 ((= tt js2-RC)
7908 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7909 (throw 'break nil)) ; done
7910 ((= tt js2-CASE)
7911 (setq case-expr (js2-parse-expr))
7912 (js2-must-match js2-COLON "msg.no.colon.case"))
7913 ((= tt js2-DEFAULT)
7914 (if has-default
7915 (js2-report-error "msg.double.switch.default"))
7916 (setq has-default t
7917 case-expr nil)
7918 (js2-must-match js2-COLON "msg.no.colon.case"))
7919 (t
7920 (js2-report-error "msg.bad.switch")
7921 (throw 'break nil)))
7922 (setq case-node (make-js2-case-node :pos case-pos
7923 :len (- (js2-current-token-end) case-pos)
7924 :expr case-expr))
7925 (js2-node-add-children case-node case-expr)
7926 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7927 (/= tt js2-CASE)
7928 (/= tt js2-DEFAULT)
7929 (/= tt js2-EOF))
7930 (setf stmt (js2-parse-statement)
7931 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7932 (js2-block-node-push case-node stmt))
7933 (push case-node cases)))
7934 ;; add cases last, as pushing reverses the order to be correct
7935 (dolist (kid cases)
7936 (js2-node-add-children pn kid)
7937 (push kid (js2-switch-node-cases pn)))
7938 pn) ; return value
7939 (js2-exit-switch))))
7940
7941 (defun js2-parse-while ()
7942 "Parser for while-statement. Last matched token must be js2-WHILE."
7943 (let ((pos (js2-current-token-beg))
7944 (pn (make-js2-while-node))
7945 cond body)
7946 (js2-enter-loop pn)
7947 (unwind-protect
7948 (progn
7949 (setf cond (js2-parse-condition)
7950 (js2-while-node-condition pn) (car cond)
7951 body (js2-parse-statement)
7952 (js2-while-node-body pn) body
7953 (js2-node-len pn) (- (js2-node-end body) pos)
7954 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7955 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7956 (js2-node-add-children pn body (car cond)))
7957 (js2-exit-loop))
7958 pn))
7959
7960 (defun js2-parse-do ()
7961 "Parser for do-statement. Last matched token must be js2-DO."
7962 (let ((pos (js2-current-token-beg))
7963 (pn (make-js2-do-node))
7964 cond body end)
7965 (js2-enter-loop pn)
7966 (unwind-protect
7967 (progn
7968 (setq body (js2-parse-statement))
7969 (js2-must-match js2-WHILE "msg.no.while.do")
7970 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7971 cond (js2-parse-condition)
7972 (js2-do-node-condition pn) (car cond)
7973 (js2-do-node-body pn) body
7974 end js2-ts-cursor
7975 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7976 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7977 (js2-node-add-children pn (car cond) body))
7978 (js2-exit-loop))
7979 ;; Always auto-insert semicolon to follow SpiderMonkey:
7980 ;; It is required by ECMAScript but is ignored by the rest of
7981 ;; world; see bug 238945
7982 (if (js2-match-token js2-SEMI)
7983 (setq end js2-ts-cursor))
7984 (setf (js2-node-len pn) (- end pos))
7985 pn))
7986
7987 (defun js2-parse-for ()
7988 "Parser for for-statement. Last matched token must be js2-FOR.
7989 Parses for, for-in, and for each-in statements."
7990 (let ((for-pos (js2-current-token-beg))
7991 pn is-for-each is-for-in-or-of is-for-of
7992 in-pos each-pos tmp-pos
7993 init ; Node init is also foo in 'foo in object'
7994 cond ; Node cond is also object in 'foo in object'
7995 incr ; 3rd section of for-loop initializer
7996 body tt lp rp)
7997 ;; See if this is a for each () instead of just a for ()
7998 (when (js2-match-token js2-NAME)
7999 (if (string= "each" (js2-current-token-string))
8000 (progn
8001 (setq is-for-each t
8002 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8003 (js2-record-face 'font-lock-keyword-face))
8004 (js2-report-error "msg.no.paren.for")))
8005 (if (js2-must-match js2-LP "msg.no.paren.for")
8006 (setq lp (- (js2-current-token-beg) for-pos)))
8007 (setq tt (js2-get-token))
8008 ;; 'for' makes local scope
8009 (js2-push-scope (make-js2-scope))
8010 (unwind-protect
8011 ;; parse init clause
8012 (let ((js2-in-for-init t)) ; set as dynamic variable
8013 (cond
8014 ((= tt js2-SEMI)
8015 (js2-unget-token)
8016 (setq init (make-js2-empty-expr-node)))
8017 ((or (= tt js2-VAR) (= tt js2-LET))
8018 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8019 (t
8020 (js2-unget-token)
8021 (setq init (js2-parse-expr)))))
8022 (if (or (js2-match-token js2-IN)
8023 (and (>= js2-language-version 200)
8024 (js2-match-contextual-kwd "of")
8025 (setq is-for-of t)))
8026 (setq is-for-in-or-of t
8027 in-pos (- (js2-current-token-beg) for-pos)
8028 ;; scope of iteration target object is not the scope we've created above.
8029 ;; stash current scope temporary.
8030 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8031 (js2-parse-expr))) ; object over which we're iterating
8032 ;; else ordinary for loop - parse cond and incr
8033 (js2-must-match js2-SEMI "msg.no.semi.for")
8034 (setq cond (if (= (js2-peek-token) js2-SEMI)
8035 (make-js2-empty-expr-node) ; no loop condition
8036 (js2-parse-expr)))
8037 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8038 (setq tmp-pos (js2-current-token-end)
8039 incr (if (= (js2-peek-token) js2-RP)
8040 (make-js2-empty-expr-node :pos tmp-pos)
8041 (js2-parse-expr))))
8042 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8043 (setq rp (- (js2-current-token-beg) for-pos)))
8044 (if (not is-for-in-or-of)
8045 (setq pn (make-js2-for-node :init init
8046 :condition cond
8047 :update incr
8048 :lp lp
8049 :rp rp))
8050 ;; cond could be null if 'in obj' got eaten by the init node.
8051 (if (js2-infix-node-p init)
8052 ;; it was (foo in bar) instead of (var foo in bar)
8053 (setq cond (js2-infix-node-right init)
8054 init (js2-infix-node-left init))
8055 (if (and (js2-var-decl-node-p init)
8056 (> (length (js2-var-decl-node-kids init)) 1))
8057 (js2-report-error "msg.mult.index")))
8058 (setq pn (make-js2-for-in-node :iterator init
8059 :object cond
8060 :in-pos in-pos
8061 :foreach-p is-for-each
8062 :each-pos each-pos
8063 :forof-p is-for-of
8064 :lp lp
8065 :rp rp)))
8066 (unwind-protect
8067 (progn
8068 (js2-enter-loop pn)
8069 ;; We have to parse the body -after- creating the loop node,
8070 ;; so that the loop node appears in the js2-loop-set, allowing
8071 ;; break/continue statements to find the enclosing loop.
8072 (setf body (js2-parse-statement)
8073 (js2-loop-node-body pn) body
8074 (js2-node-pos pn) for-pos
8075 (js2-node-len pn) (- (js2-node-end body) for-pos))
8076 (js2-node-add-children pn init cond incr body))
8077 ;; finally
8078 (js2-exit-loop))
8079 (js2-pop-scope))
8080 pn))
8081
8082 (defun js2-parse-try ()
8083 "Parser for try-statement. Last matched token must be js2-TRY."
8084 (let ((try-pos (js2-current-token-beg))
8085 try-end
8086 try-block
8087 catch-blocks
8088 finally-block
8089 saw-default-catch
8090 peek
8091 param
8092 catch-cond
8093 catch-node
8094 guard-kwd
8095 catch-pos
8096 finally-pos
8097 pn
8098 block
8099 lp
8100 rp)
8101 (if (/= (js2-peek-token) js2-LC)
8102 (js2-report-error "msg.no.brace.try"))
8103 (setq try-block (js2-parse-statement)
8104 try-end (js2-node-end try-block)
8105 peek (js2-peek-token))
8106 (cond
8107 ((= peek js2-CATCH)
8108 (while (js2-match-token js2-CATCH)
8109 (setq catch-pos (js2-current-token-beg)
8110 guard-kwd nil
8111 catch-cond nil
8112 lp nil
8113 rp nil)
8114 (if saw-default-catch
8115 (js2-report-error "msg.catch.unreachable"))
8116 (if (js2-must-match js2-LP "msg.no.paren.catch")
8117 (setq lp (- (js2-current-token-beg) catch-pos)))
8118 (js2-push-scope (make-js2-scope))
8119 (let ((tt (js2-peek-token)))
8120 (cond
8121 ;; destructuring pattern
8122 ;; catch ({ message, file }) { ... }
8123 ((or (= tt js2-LB) (= tt js2-LC))
8124 (js2-get-token)
8125 (setq param (js2-parse-destruct-primary-expr))
8126 (js2-define-destruct-symbols param js2-LET nil))
8127 ;; simple name
8128 (t
8129 (js2-must-match-name "msg.bad.catchcond")
8130 (setq param (js2-create-name-node))
8131 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8132 ;; pattern guard
8133 (if (js2-match-token js2-IF)
8134 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8135 catch-cond (js2-parse-expr))
8136 (setq saw-default-catch t))
8137 (if (js2-must-match js2-RP "msg.bad.catchcond")
8138 (setq rp (- (js2-current-token-beg) catch-pos)))
8139 (js2-must-match js2-LC "msg.no.brace.catchblock")
8140 (setq block (js2-parse-statements)
8141 try-end (js2-node-end block)
8142 catch-node (make-js2-catch-node :pos catch-pos
8143 :param param
8144 :guard-expr catch-cond
8145 :guard-kwd guard-kwd
8146 :block block
8147 :lp lp
8148 :rp rp))
8149 (js2-pop-scope)
8150 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8151 (setq try-end (js2-current-token-beg)))
8152 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8153 (js2-node-len catch-node) (- try-end catch-pos))
8154 (js2-node-add-children catch-node param catch-cond block)
8155 (push catch-node catch-blocks)))
8156 ((/= peek js2-FINALLY)
8157 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8158 (js2-node-pos try-block)
8159 (- (setq try-end (js2-node-end try-block))
8160 (js2-node-pos try-block)))))
8161 (when (js2-match-token js2-FINALLY)
8162 (setq finally-pos (js2-current-token-beg)
8163 block (js2-parse-statement)
8164 try-end (js2-node-end block)
8165 finally-block (make-js2-finally-node :pos finally-pos
8166 :len (- try-end finally-pos)
8167 :body block))
8168 (js2-node-add-children finally-block block))
8169 (setq pn (make-js2-try-node :pos try-pos
8170 :len (- try-end try-pos)
8171 :try-block try-block
8172 :finally-block finally-block))
8173 (js2-node-add-children pn try-block finally-block)
8174 ;; push them onto the try-node, which reverses and corrects their order
8175 (dolist (cb catch-blocks)
8176 (js2-node-add-children pn cb)
8177 (push cb (js2-try-node-catch-clauses pn)))
8178 pn))
8179
8180 (defun js2-parse-throw ()
8181 "Parser for throw-statement. Last matched token must be js2-THROW."
8182 (let ((pos (js2-current-token-beg))
8183 expr pn)
8184 (if (= (js2-peek-token-or-eol) js2-EOL)
8185 ;; ECMAScript does not allow new lines before throw expression,
8186 ;; see bug 256617
8187 (js2-report-error "msg.bad.throw.eol"))
8188 (setq expr (js2-parse-expr)
8189 pn (make-js2-throw-node :pos pos
8190 :len (- (js2-node-end expr) pos)
8191 :expr expr))
8192 (js2-node-add-children pn expr)
8193 pn))
8194
8195 (defun js2-match-jump-label-name (label-name)
8196 "If break/continue specified a label, return that label's labeled stmt.
8197 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8198 does not match an existing label, reports an error and returns nil."
8199 (let ((bundle (cdr (assoc label-name js2-label-set))))
8200 (if (null bundle)
8201 (js2-report-error "msg.undef.label"))
8202 bundle))
8203
8204 (defun js2-parse-break ()
8205 "Parser for break-statement. Last matched token must be js2-BREAK."
8206 (let ((pos (js2-current-token-beg))
8207 (end (js2-current-token-end))
8208 break-target ; statement to break from
8209 break-label ; in "break foo", name-node representing the foo
8210 labels ; matching labeled statement to break to
8211 pn)
8212 (when (eq (js2-peek-token-or-eol) js2-NAME)
8213 (js2-get-token)
8214 (setq break-label (js2-create-name-node)
8215 end (js2-node-end break-label)
8216 ;; matchJumpLabelName only matches if there is one
8217 labels (js2-match-jump-label-name (js2-current-token-string))
8218 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8219 (unless (or break-target break-label)
8220 ;; no break target specified - try for innermost enclosing loop/switch
8221 (if (null js2-loop-and-switch-set)
8222 (unless break-label
8223 (js2-report-error "msg.bad.break" nil pos (length "break")))
8224 (setq break-target (car js2-loop-and-switch-set))))
8225 (setq pn (make-js2-break-node :pos pos
8226 :len (- end pos)
8227 :label break-label
8228 :target break-target))
8229 (js2-node-add-children pn break-label) ; but not break-target
8230 pn))
8231
8232 (defun js2-parse-continue ()
8233 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8234 (let ((pos (js2-current-token-beg))
8235 (end (js2-current-token-end))
8236 label ; optional user-specified label, a `js2-name-node'
8237 labels ; current matching labeled stmt, if any
8238 target ; the `js2-loop-node' target of this continue stmt
8239 pn)
8240 (when (= (js2-peek-token-or-eol) js2-NAME)
8241 (js2-get-token)
8242 (setq label (js2-create-name-node)
8243 end (js2-node-end label)
8244 ;; matchJumpLabelName only matches if there is one
8245 labels (js2-match-jump-label-name (js2-current-token-string))))
8246 (cond
8247 ((null labels) ; no current label to go to
8248 (if (null js2-loop-set) ; no loop to continue to
8249 (js2-report-error "msg.continue.outside" nil pos
8250 (length "continue"))
8251 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8252 (t
8253 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8254 (setq target (js2-labeled-stmt-node-stmt labels))
8255 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8256 (setq pn (make-js2-continue-node :pos pos
8257 :len (- end pos)
8258 :label label
8259 :target target))
8260 (js2-node-add-children pn label) ; but not target - it's not our child
8261 pn))
8262
8263 (defun js2-parse-with ()
8264 "Parser for with-statement. Last matched token must be js2-WITH."
8265 (let ((pos (js2-current-token-beg))
8266 obj body pn lp rp)
8267 (if (js2-must-match js2-LP "msg.no.paren.with")
8268 (setq lp (js2-current-token-beg)))
8269 (setq obj (js2-parse-expr))
8270 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8271 (setq rp (js2-current-token-beg)))
8272 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8273 (setq body (js2-parse-statement)))
8274 (setq pn (make-js2-with-node :pos pos
8275 :len (- (js2-node-end body) pos)
8276 :object obj
8277 :body body
8278 :lp (js2-relpos lp pos)
8279 :rp (js2-relpos rp pos)))
8280 (js2-node-add-children pn obj body)
8281 pn))
8282
8283 (defun js2-parse-const-var ()
8284 "Parser for var- or const-statement.
8285 Last matched token must be js2-CONST or js2-VAR."
8286 (let ((tt (js2-current-token-type))
8287 (pos (js2-current-token-beg))
8288 expr pn)
8289 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8290 pn (make-js2-expr-stmt-node :pos pos
8291 :len (- (js2-node-end expr) pos)
8292 :expr expr))
8293 (js2-node-add-children pn expr)
8294 pn))
8295
8296 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8297 (let ((pn (make-js2-expr-stmt-node :pos pos
8298 :len (js2-node-len expr)
8299 :type (if (js2-inside-function)
8300 js2-EXPR_VOID
8301 js2-EXPR_RESULT)
8302 :expr expr)))
8303 (if add-child
8304 (js2-node-add-children pn expr))
8305 pn))
8306
8307 (defun js2-parse-let-stmt ()
8308 "Parser for let-statement. Last matched token must be js2-LET."
8309 (let ((pos (js2-current-token-beg))
8310 expr pn)
8311 (if (= (js2-peek-token) js2-LP)
8312 ;; let expression in statement context
8313 (setq expr (js2-parse-let pos 'statement)
8314 pn (js2-wrap-with-expr-stmt pos expr t))
8315 ;; else we're looking at a statement like let x=6, y=7;
8316 (setf expr (js2-parse-variables js2-LET pos)
8317 pn (js2-wrap-with-expr-stmt pos expr t)
8318 (js2-node-type pn) js2-EXPR_RESULT))
8319 pn))
8320
8321 (defun js2-parse-ret-yield ()
8322 (js2-parse-return-or-yield (js2-current-token-type) nil))
8323
8324 (defconst js2-parse-return-stmt-enders
8325 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8326
8327 (defsubst js2-now-all-set (before after mask)
8328 "Return whether or not the bits in the mask have changed to all set.
8329 BEFORE is bits before change, AFTER is bits after change, and MASK is
8330 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8331 but not BEFORE."
8332 (and (/= (logand before mask) mask)
8333 (= (logand after mask) mask)))
8334
8335 (defun js2-parse-return-or-yield (tt expr-context)
8336 (let* ((pos (js2-current-token-beg))
8337 (end (js2-current-token-end))
8338 (before js2-end-flags)
8339 (inside-function (js2-inside-function))
8340 (gen-type (and inside-function (js2-function-node-generator-type
8341 js2-current-script-or-fn)))
8342 e ret name yield-star-p)
8343 (unless inside-function
8344 (js2-report-error (if (eq tt js2-RETURN)
8345 "msg.bad.return"
8346 "msg.bad.yield")))
8347 (when (and inside-function
8348 (eq gen-type 'STAR)
8349 (js2-match-token js2-MUL))
8350 (setq yield-star-p t))
8351 ;; This is ugly, but we don't want to require a semicolon.
8352 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8353 (setq e (js2-parse-expr)
8354 end (js2-node-end e)))
8355 (cond
8356 ((eq tt js2-RETURN)
8357 (js2-set-flag js2-end-flags (if (null e)
8358 js2-end-returns
8359 js2-end-returns-value))
8360 (setq ret (make-js2-return-node :pos pos
8361 :len (- end pos)
8362 :retval e))
8363 (js2-node-add-children ret e)
8364 ;; See if we need a strict mode warning.
8365 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8366 ;; more thorough and accurate than this before/after flag check.
8367 ;; E.g. if there's a finally-block that always returns, we shouldn't
8368 ;; show a warning generated by inconsistent returns in the catch blocks.
8369 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8370 ;; so we know which returns/yields to highlight, and we should get rid of
8371 ;; all the checking in `js2-parse-return-or-yield'.
8372 (if (and js2-strict-inconsistent-return-warning
8373 (js2-now-all-set before js2-end-flags
8374 (logior js2-end-returns js2-end-returns-value)))
8375 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8376 ((eq gen-type 'COMPREHENSION)
8377 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8378 ;; like SpiderMonkey does.
8379 (js2-report-error "msg.syntax" nil pos 5))
8380 (t
8381 (setq ret (make-js2-yield-node :pos pos
8382 :len (- end pos)
8383 :value e
8384 :star-p yield-star-p))
8385 (js2-node-add-children ret e)
8386 (unless expr-context
8387 (setq e ret
8388 ret (js2-wrap-with-expr-stmt pos e t))
8389 (js2-set-requires-activation)
8390 (js2-set-is-generator))))
8391 ;; see if we are mixing yields and value returns.
8392 (when (and inside-function
8393 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8394 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8395 'LEGACY))
8396 (setq name (js2-function-name js2-current-script-or-fn))
8397 (if (zerop (length name))
8398 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8399 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8400 ret))
8401
8402 (defun js2-parse-debugger ()
8403 (make-js2-keyword-node :type js2-DEBUGGER))
8404
8405 (defun js2-parse-block ()
8406 "Parser for a curly-delimited statement block.
8407 Last token matched must be `js2-LC'."
8408 (let ((pos (js2-current-token-beg))
8409 (pn (make-js2-scope)))
8410 (js2-push-scope pn)
8411 (unwind-protect
8412 (progn
8413 (js2-parse-statements pn)
8414 (js2-must-match js2-RC "msg.no.brace.block")
8415 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8416 (js2-pop-scope))
8417 pn))
8418
8419 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8420 (defun js2-parse-semi ()
8421 "Parse a statement or handle an error.
8422 Current token type is `js2-SEMI' or `js2-ERROR'."
8423 (let ((tt (js2-current-token-type)) pos len)
8424 (if (eq tt js2-SEMI)
8425 (make-js2-empty-expr-node :len 1)
8426 (setq pos (js2-current-token-beg)
8427 len (- (js2-current-token-end) pos))
8428 (js2-report-error "msg.syntax" nil pos len)
8429 (make-js2-error-node :pos pos :len len))))
8430
8431 (defun js2-parse-default-xml-namespace ()
8432 "Parse a `default xml namespace = <expr>' e4x statement."
8433 (let ((pos (js2-current-token-beg))
8434 end len expr unary)
8435 (js2-must-have-xml)
8436 (js2-set-requires-activation)
8437 (setq len (- js2-ts-cursor pos))
8438 (unless (and (js2-match-token js2-NAME)
8439 (string= (js2-current-token-string) "xml"))
8440 (js2-report-error "msg.bad.namespace" nil pos len))
8441 (unless (and (js2-match-token js2-NAME)
8442 (string= (js2-current-token-string) "namespace"))
8443 (js2-report-error "msg.bad.namespace" nil pos len))
8444 (unless (js2-match-token js2-ASSIGN)
8445 (js2-report-error "msg.bad.namespace" nil pos len))
8446 (setq expr (js2-parse-expr)
8447 end (js2-node-end expr)
8448 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8449 :pos pos
8450 :len (- end pos)
8451 :operand expr))
8452 (js2-node-add-children unary expr)
8453 (make-js2-expr-stmt-node :pos pos
8454 :len (- end pos)
8455 :expr unary)))
8456
8457 (defun js2-record-label (label bundle)
8458 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8459 (js2-get-token)
8460 (let ((name (js2-label-node-name label))
8461 labeled-stmt
8462 dup)
8463 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8464 ;; flag both labels if possible when used in editing mode
8465 (if (and js2-parse-ide-mode
8466 (setq dup (js2-get-label-by-name labeled-stmt name)))
8467 (js2-report-error "msg.dup.label" nil
8468 (js2-node-abs-pos dup) (js2-node-len dup)))
8469 (js2-report-error "msg.dup.label" nil
8470 (js2-node-pos label) (js2-node-len label)))
8471 (js2-labeled-stmt-node-add-label bundle label)
8472 (js2-node-add-children bundle label)
8473 ;; Add one reference to the bundle per label in `js2-label-set'
8474 (push (cons name bundle) js2-label-set)))
8475
8476 (defun js2-parse-name-or-label ()
8477 "Parser for identifier or label. Last token matched must be js2-NAME.
8478 Called when we found a name in a statement context. If it's a label, we gather
8479 up any following labels and the next non-label statement into a
8480 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8481 expression and return it wrapped in a `js2-expr-stmt-node'."
8482 (let ((pos (js2-current-token-beg))
8483 expr stmt bundle
8484 (continue t))
8485 ;; set check for label and call down to `js2-parse-primary-expr'
8486 (setq expr (js2-maybe-parse-label))
8487 (if (null expr)
8488 ;; Parse the non-label expression and wrap with expression stmt.
8489 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8490 ;; else parsed a label
8491 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8492 (js2-record-label expr bundle)
8493 ;; look for more labels
8494 (while (and continue (= (js2-get-token) js2-NAME))
8495 (if (setq expr (js2-maybe-parse-label))
8496 (js2-record-label expr bundle)
8497 (setq expr (js2-parse-expr)
8498 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8499 continue nil)
8500 (js2-auto-insert-semicolon stmt)))
8501 ;; no more labels; now parse the labeled statement
8502 (unwind-protect
8503 (unless stmt
8504 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8505 (js2-unget-token)
8506 (setq stmt (js2-statement-helper))))
8507 ;; remove the labels for this statement from the global set
8508 (dolist (label (js2-labeled-stmt-node-labels bundle))
8509 (setq js2-label-set (remove label js2-label-set))))
8510 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8511 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8512 (js2-node-add-children bundle stmt)
8513 bundle)))
8514
8515 (defun js2-maybe-parse-label ()
8516 (assert (= (js2-current-token-type) js2-NAME))
8517 (let (label-pos
8518 (next-tt (js2-get-token))
8519 (label-end (js2-current-token-end)))
8520 ;; Do not consume colon, it is used as unwind indicator
8521 ;; to return to statementHelper.
8522 (js2-unget-token)
8523 (if (= next-tt js2-COLON)
8524 (prog2
8525 (setq label-pos (js2-current-token-beg))
8526 (make-js2-label-node :pos label-pos
8527 :len (- label-end label-pos)
8528 :name (js2-current-token-string))
8529 (js2-set-face label-pos
8530 label-end
8531 'font-lock-variable-name-face 'record))
8532 ;; Backtrack from the name token, too.
8533 (js2-unget-token)
8534 nil)))
8535
8536 (defun js2-parse-expr-stmt ()
8537 "Default parser in statement context, if no recognized statement found."
8538 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8539 (progn
8540 (js2-unget-token)
8541 (js2-parse-expr)) t))
8542
8543 (defun js2-parse-variables (decl-type pos)
8544 "Parse a comma-separated list of variable declarations.
8545 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8546
8547 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8548 For 'var' or 'const', the keyword should be the token last scanned.
8549
8550 POS is the position where the node should start. It's sometimes the
8551 var/const/let keyword, and other times the beginning of the first token
8552 in the first variable declaration.
8553
8554 Returns the parsed `js2-var-decl-node' expression node."
8555 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8556 :pos pos))
8557 destructuring kid-pos tt init name end nbeg nend vi
8558 (continue t))
8559 ;; Example:
8560 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8561 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8562 ;; var {a, b} = baz;
8563 (while continue
8564 (setq destructuring nil
8565 name nil
8566 tt (js2-get-token)
8567 kid-pos (js2-current-token-beg)
8568 end (js2-current-token-end)
8569 init nil)
8570 (if (or (= tt js2-LB) (= tt js2-LC))
8571 ;; Destructuring assignment, e.g., var [a, b] = ...
8572 (setq destructuring (js2-parse-destruct-primary-expr)
8573 end (js2-node-end destructuring))
8574 ;; Simple variable name
8575 (js2-unget-token)
8576 (when (js2-must-match-name "msg.bad.var")
8577 (setq name (js2-create-name-node)
8578 nbeg (js2-current-token-beg)
8579 nend (js2-current-token-end)
8580 end nend)
8581 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8582 (when (js2-match-token js2-ASSIGN)
8583 (setq init (js2-parse-assign-expr)
8584 end (js2-node-end init))
8585 (js2-record-imenu-functions init name))
8586 (when name
8587 (js2-set-face nbeg nend (if (js2-function-node-p init)
8588 'font-lock-function-name-face
8589 'font-lock-variable-name-face)
8590 'record))
8591 (setq vi (make-js2-var-init-node :pos kid-pos
8592 :len (- end kid-pos)
8593 :type decl-type))
8594 (if destructuring
8595 (progn
8596 (if (and (null init) (not js2-in-for-init))
8597 (js2-report-error "msg.destruct.assign.no.init"))
8598 (js2-define-destruct-symbols destructuring
8599 decl-type
8600 'font-lock-variable-name-face)
8601 (setf (js2-var-init-node-target vi) destructuring))
8602 (setf (js2-var-init-node-target vi) name))
8603 (setf (js2-var-init-node-initializer vi) init)
8604 (js2-node-add-children vi name destructuring init)
8605 (js2-block-node-push result vi)
8606 (unless (js2-match-token js2-COMMA)
8607 (setq continue nil)))
8608 (setf (js2-node-len result) (- end pos))
8609 result))
8610
8611 (defun js2-parse-let (pos &optional stmt-p)
8612 "Parse a let expression or statement.
8613 A let-expression is of the form `let (vars) expr'.
8614 A let-statment is of the form `let (vars) {statements}'.
8615 The third form of let is a variable declaration list, handled
8616 by `js2-parse-variables'."
8617 (let ((pn (make-js2-let-node :pos pos))
8618 beg vars body)
8619 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8620 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8621 (js2-push-scope pn)
8622 (unwind-protect
8623 (progn
8624 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8625 (if (js2-must-match js2-RP "msg.no.paren.let")
8626 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8627 (if (and stmt-p (js2-match-token js2-LC))
8628 ;; let statement
8629 (progn
8630 (setf beg (js2-current-token-beg) ; position stmt at LC
8631 body (js2-parse-statements))
8632 (js2-must-match js2-RC "msg.no.curly.let")
8633 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8634 (js2-node-len pn) (- (js2-current-token-end) pos)
8635 (js2-let-node-body pn) body
8636 (js2-node-type pn) js2-LET))
8637 ;; let expression
8638 (setf body (js2-parse-expr)
8639 (js2-node-len pn) (- (js2-node-end body) pos)
8640 (js2-let-node-body pn) body))
8641 (setf (js2-let-node-vars pn) vars)
8642 (js2-node-add-children pn vars body))
8643 (js2-pop-scope))
8644 pn))
8645
8646 (defun js2-define-new-symbol (decl-type name node &optional scope)
8647 (js2-scope-put-symbol (or scope js2-current-scope)
8648 name
8649 (make-js2-symbol decl-type name node)))
8650
8651 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8652 "Define a symbol in the current scope.
8653 If NODE is non-nil, it is the AST node associated with the symbol."
8654 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8655 (symbol (if defining-scope
8656 (js2-scope-get-symbol defining-scope name)))
8657 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8658 (cond
8659 ((and symbol ; already defined
8660 (or (= sdt js2-CONST) ; old version is const
8661 (= decl-type js2-CONST) ; new version is const
8662 ;; two let-bound vars in this block have same name
8663 (and (= sdt js2-LET)
8664 (eq defining-scope js2-current-scope))))
8665 (js2-report-error
8666 (cond
8667 ((= sdt js2-CONST) "msg.const.redecl")
8668 ((= sdt js2-LET) "msg.let.redecl")
8669 ((= sdt js2-VAR) "msg.var.redecl")
8670 ((= sdt js2-FUNCTION) "msg.function.redecl")
8671 (t "msg.parm.redecl"))
8672 name))
8673 ((= decl-type js2-LET)
8674 (if (and (not ignore-not-in-block)
8675 (or (= (js2-node-type js2-current-scope) js2-IF)
8676 (js2-loop-node-p js2-current-scope)))
8677 (js2-report-error "msg.let.decl.not.in.block")
8678 (js2-define-new-symbol decl-type name node)))
8679 ((or (= decl-type js2-VAR)
8680 (= decl-type js2-CONST)
8681 (= decl-type js2-FUNCTION))
8682 (if symbol
8683 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8684 (js2-add-strict-warning "msg.var.redecl" name)
8685 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8686 (js2-add-strict-warning "msg.var.hides.arg" name)))
8687 (js2-define-new-symbol decl-type name node
8688 js2-current-script-or-fn)))
8689 ((= decl-type js2-LP)
8690 (if symbol
8691 ;; must be duplicate parameter. Second parameter hides the
8692 ;; first, so go ahead and add the second pararameter
8693 (js2-report-warning "msg.dup.parms" name))
8694 (js2-define-new-symbol decl-type name node))
8695 (t (js2-code-bug)))))
8696
8697 (defun js2-parse-paren-expr-or-generator-comp ()
8698 (let ((px-pos (js2-current-token-beg)))
8699 (if (and (>= js2-language-version 200)
8700 (js2-match-token js2-FOR))
8701 (js2-parse-generator-comp px-pos)
8702 (let* ((js2-in-for-init nil)
8703 (expr (js2-parse-expr))
8704 (pn (make-js2-paren-node :pos px-pos
8705 :expr expr
8706 :len (- (js2-current-token-end)
8707 px-pos))))
8708 (js2-node-add-children pn (js2-paren-node-expr pn))
8709 (js2-must-match js2-RP "msg.no.paren")
8710 pn))))
8711
8712 (defun js2-parse-expr (&optional oneshot)
8713 (let* ((pn (js2-parse-assign-expr))
8714 (pos (js2-node-pos pn))
8715 left
8716 right
8717 op-pos)
8718 (while (and (not oneshot)
8719 (js2-match-token js2-COMMA))
8720 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8721 (if (= (js2-peek-token) js2-YIELD)
8722 (js2-report-error "msg.yield.parenthesized"))
8723 (setq right (js2-parse-assign-expr)
8724 left pn
8725 pn (make-js2-infix-node :type js2-COMMA
8726 :pos pos
8727 :len (- js2-ts-cursor pos)
8728 :op-pos op-pos
8729 :left left
8730 :right right))
8731 (js2-node-add-children pn left right))
8732 pn))
8733
8734 (defun js2-parse-assign-expr ()
8735 (let ((tt (js2-get-token))
8736 (pos (js2-current-token-beg))
8737 pn left right op-pos
8738 ts-state recorded-identifiers parsed-errors)
8739 (if (= tt js2-YIELD)
8740 (js2-parse-return-or-yield tt t)
8741 ;; Save the tokenizer state in case we find an arrow function
8742 ;; and have to rewind.
8743 (setq ts-state (make-js2-ts-state)
8744 recorded-identifiers js2-recorded-identifiers
8745 parsed-errors js2-parsed-errors)
8746 ;; not yield - parse assignment expression
8747 (setq pn (js2-parse-cond-expr)
8748 tt (js2-get-token))
8749 (cond
8750 ((and (<= js2-first-assign tt)
8751 (<= tt js2-last-assign))
8752 ;; tt express assignment (=, |=, ^=, ..., %=)
8753 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8754 left pn)
8755 (setq right (js2-parse-assign-expr)
8756 pn (make-js2-assign-node :type tt
8757 :pos pos
8758 :len (- (js2-node-end right) pos)
8759 :op-pos op-pos
8760 :left left
8761 :right right))
8762 (when js2-parse-ide-mode
8763 (js2-highlight-assign-targets pn left right)
8764 (js2-record-imenu-functions right left))
8765 ;; do this last so ide checks above can use absolute positions
8766 (js2-node-add-children pn left right))
8767 ((and (= tt js2-ARROW)
8768 (>= js2-language-version 200))
8769 (js2-ts-seek ts-state)
8770 (setq js2-recorded-identifiers recorded-identifiers
8771 js2-parsed-errors parsed-errors)
8772 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8773 (t
8774 (js2-unget-token)))
8775 pn)))
8776
8777 (defun js2-parse-cond-expr ()
8778 (let ((pos (js2-current-token-beg))
8779 (pn (js2-parse-or-expr))
8780 test-expr
8781 if-true
8782 if-false
8783 q-pos
8784 c-pos)
8785 (when (js2-match-token js2-HOOK)
8786 (setq q-pos (- (js2-current-token-beg) pos)
8787 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8788 (js2-must-match js2-COLON "msg.no.colon.cond")
8789 (setq c-pos (- (js2-current-token-beg) pos)
8790 if-false (js2-parse-assign-expr)
8791 test-expr pn
8792 pn (make-js2-cond-node :pos pos
8793 :len (- (js2-node-end if-false) pos)
8794 :test-expr test-expr
8795 :true-expr if-true
8796 :false-expr if-false
8797 :q-pos q-pos
8798 :c-pos c-pos))
8799 (js2-node-add-children pn test-expr if-true if-false))
8800 pn))
8801
8802 (defun js2-make-binary (type left parser)
8803 "Helper for constructing a binary-operator AST node.
8804 LEFT is the left-side-expression, already parsed, and the
8805 binary operator should have just been matched.
8806 PARSER is a function to call to parse the right operand,
8807 or a `js2-node' struct if it has already been parsed.
8808 FIXME: The latter option is unused?"
8809 (let* ((pos (js2-node-pos left))
8810 (op-pos (- (js2-current-token-beg) pos))
8811 (right (if (js2-node-p parser)
8812 parser
8813 (js2-get-token)
8814 (funcall parser)))
8815 (pn (make-js2-infix-node :type type
8816 :pos pos
8817 :len (- (js2-node-end right) pos)
8818 :op-pos op-pos
8819 :left left
8820 :right right)))
8821 (js2-node-add-children pn left right)
8822 pn))
8823
8824 (defun js2-parse-or-expr ()
8825 (let ((pn (js2-parse-and-expr)))
8826 (when (js2-match-token js2-OR)
8827 (setq pn (js2-make-binary js2-OR
8828 pn
8829 'js2-parse-or-expr)))
8830 pn))
8831
8832 (defun js2-parse-and-expr ()
8833 (let ((pn (js2-parse-bit-or-expr)))
8834 (when (js2-match-token js2-AND)
8835 (setq pn (js2-make-binary js2-AND
8836 pn
8837 'js2-parse-and-expr)))
8838 pn))
8839
8840 (defun js2-parse-bit-or-expr ()
8841 (let ((pn (js2-parse-bit-xor-expr)))
8842 (while (js2-match-token js2-BITOR)
8843 (setq pn (js2-make-binary js2-BITOR
8844 pn
8845 'js2-parse-bit-xor-expr)))
8846 pn))
8847
8848 (defun js2-parse-bit-xor-expr ()
8849 (let ((pn (js2-parse-bit-and-expr)))
8850 (while (js2-match-token js2-BITXOR)
8851 (setq pn (js2-make-binary js2-BITXOR
8852 pn
8853 'js2-parse-bit-and-expr)))
8854 pn))
8855
8856 (defun js2-parse-bit-and-expr ()
8857 (let ((pn (js2-parse-eq-expr)))
8858 (while (js2-match-token js2-BITAND)
8859 (setq pn (js2-make-binary js2-BITAND
8860 pn
8861 'js2-parse-eq-expr)))
8862 pn))
8863
8864 (defconst js2-parse-eq-ops
8865 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8866
8867 (defun js2-parse-eq-expr ()
8868 (let ((pn (js2-parse-rel-expr))
8869 tt)
8870 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8871 (setq pn (js2-make-binary tt
8872 pn
8873 'js2-parse-rel-expr)))
8874 (js2-unget-token)
8875 pn))
8876
8877 (defconst js2-parse-rel-ops
8878 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8879
8880 (defun js2-parse-rel-expr ()
8881 (let ((pn (js2-parse-shift-expr))
8882 (continue t)
8883 tt)
8884 (while continue
8885 (setq tt (js2-get-token))
8886 (cond
8887 ((and js2-in-for-init (= tt js2-IN))
8888 (js2-unget-token)
8889 (setq continue nil))
8890 ((memq tt js2-parse-rel-ops)
8891 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8892 (t
8893 (js2-unget-token)
8894 (setq continue nil))))
8895 pn))
8896
8897 (defconst js2-parse-shift-ops
8898 (list js2-LSH js2-URSH js2-RSH))
8899
8900 (defun js2-parse-shift-expr ()
8901 (let ((pn (js2-parse-add-expr))
8902 tt
8903 (continue t))
8904 (while continue
8905 (setq tt (js2-get-token))
8906 (if (memq tt js2-parse-shift-ops)
8907 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8908 (js2-unget-token)
8909 (setq continue nil)))
8910 pn))
8911
8912 (defun js2-parse-add-expr ()
8913 (let ((pn (js2-parse-mul-expr))
8914 tt
8915 (continue t))
8916 (while continue
8917 (setq tt (js2-get-token))
8918 (if (or (= tt js2-ADD) (= tt js2-SUB))
8919 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8920 (js2-unget-token)
8921 (setq continue nil)))
8922 pn))
8923
8924 (defconst js2-parse-mul-ops
8925 (list js2-MUL js2-DIV js2-MOD))
8926
8927 (defun js2-parse-mul-expr ()
8928 (let ((pn (js2-parse-unary-expr))
8929 tt
8930 (continue t))
8931 (while continue
8932 (setq tt (js2-get-token))
8933 (if (memq tt js2-parse-mul-ops)
8934 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8935 (js2-unget-token)
8936 (setq continue nil)))
8937 pn))
8938
8939 (defun js2-make-unary (type parser &rest args)
8940 "Make a unary node of type TYPE.
8941 PARSER is either a node (for postfix operators) or a function to call
8942 to parse the operand (for prefix operators)."
8943 (let* ((pos (js2-current-token-beg))
8944 (postfix (js2-node-p parser))
8945 (expr (if postfix
8946 parser
8947 (apply parser args)))
8948 end
8949 pn)
8950 (if postfix ; e.g. i++
8951 (setq pos (js2-node-pos expr)
8952 end (js2-current-token-end))
8953 (setq end (js2-node-end expr)))
8954 (setq pn (make-js2-unary-node :type type
8955 :pos pos
8956 :len (- end pos)
8957 :operand expr))
8958 (js2-node-add-children pn expr)
8959 pn))
8960
8961 (defconst js2-incrementable-node-types
8962 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8963 "Node types that can be the operand of a ++ or -- operator.")
8964
8965 (defun js2-check-bad-inc-dec (tt beg end unary)
8966 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8967 js2-incrementable-node-types)
8968 (js2-report-error (if (= tt js2-INC)
8969 "msg.bad.incr"
8970 "msg.bad.decr")
8971 nil beg (- end beg))))
8972
8973 (defun js2-parse-unary-expr ()
8974 (let ((tt (js2-current-token-type))
8975 pn expr beg end)
8976 (cond
8977 ((or (= tt js2-VOID)
8978 (= tt js2-NOT)
8979 (= tt js2-BITNOT)
8980 (= tt js2-TYPEOF))
8981 (js2-get-token)
8982 (js2-make-unary tt 'js2-parse-unary-expr))
8983 ((= tt js2-ADD)
8984 (js2-get-token)
8985 ;; Convert to special POS token in decompiler and parse tree
8986 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8987 ((= tt js2-SUB)
8988 (js2-get-token)
8989 ;; Convert to special NEG token in decompiler and parse tree
8990 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8991 ((or (= tt js2-INC)
8992 (= tt js2-DEC))
8993 (js2-get-token)
8994 (prog1
8995 (setq beg (js2-current-token-beg)
8996 end (js2-current-token-end)
8997 expr (js2-make-unary tt 'js2-parse-member-expr t))
8998 (js2-check-bad-inc-dec tt beg end expr)))
8999 ((= tt js2-DELPROP)
9000 (js2-get-token)
9001 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9002 ((= tt js2-ERROR)
9003 (js2-get-token)
9004 (make-js2-error-node)) ; try to continue
9005 ((and (= tt js2-LT)
9006 js2-compiler-xml-available)
9007 ;; XML stream encountered in expression.
9008 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9009 (t
9010 (setq pn (js2-parse-member-expr t)
9011 ;; Don't look across a newline boundary for a postfix incop.
9012 tt (js2-peek-token-or-eol))
9013 (when (or (= tt js2-INC) (= tt js2-DEC))
9014 (js2-get-token)
9015 (setf expr pn
9016 pn (js2-make-unary tt expr))
9017 (js2-node-set-prop pn 'postfix t)
9018 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9019 pn))))
9020
9021 (defun js2-parse-xml-initializer ()
9022 "Parse an E4X XML initializer.
9023 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9024 Then I'll postprocess the result, depending on whether we're in IDE
9025 mode or codegen mode, and generate the appropriate rewritten AST.
9026 IDE mode uses a rich AST that models the XML structure. Codegen mode
9027 just concatenates everything and makes a new XML or XMLList out of it."
9028 (let ((tt (js2-get-first-xml-token))
9029 pn-xml pn expr kids expr-pos
9030 (continue t)
9031 (first-token t))
9032 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9033 (js2-report-error "msg.syntax"))
9034 (setq pn-xml (make-js2-xml-node))
9035 (while continue
9036 (if first-token
9037 (setq first-token nil)
9038 (setq tt (js2-get-next-xml-token)))
9039 (cond
9040 ;; js2-XML means we found a {expr} in the XML stream.
9041 ;; The token string is the XML up to the left-curly.
9042 ((= tt js2-XML)
9043 (push (make-js2-string-node :pos (js2-current-token-beg)
9044 :len (- js2-ts-cursor (js2-current-token-beg)))
9045 kids)
9046 (js2-must-match js2-LC "msg.syntax")
9047 (setq expr-pos js2-ts-cursor
9048 expr (if (eq (js2-peek-token) js2-RC)
9049 (make-js2-empty-expr-node :pos expr-pos)
9050 (js2-parse-expr)))
9051 (js2-must-match js2-RC "msg.syntax")
9052 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9053 :len (js2-node-len expr)
9054 :expr expr))
9055 (js2-node-add-children pn expr)
9056 (push pn kids))
9057 ;; a js2-XMLEND token means we hit the final close-tag.
9058 ((= tt js2-XMLEND)
9059 (push (make-js2-string-node :pos (js2-current-token-beg)
9060 :len (- js2-ts-cursor (js2-current-token-beg)))
9061 kids)
9062 (dolist (kid (nreverse kids))
9063 (js2-block-node-push pn-xml kid))
9064 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9065 (js2-node-pos pn-xml))
9066 continue nil))
9067 (t
9068 (js2-report-error "msg.syntax")
9069 (setq continue nil))))
9070 pn-xml))
9071
9072
9073 (defun js2-parse-argument-list ()
9074 "Parse an argument list and return it as a Lisp list of nodes.
9075 Returns the list in reverse order. Consumes the right-paren token."
9076 (let (result)
9077 (unless (js2-match-token js2-RP)
9078 (loop do
9079 (let ((tt (js2-get-token)))
9080 (if (= tt js2-YIELD)
9081 (js2-report-error "msg.yield.parenthesized"))
9082 (if (and (= tt js2-TRIPLEDOT)
9083 (>= js2-language-version 200))
9084 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9085 (js2-unget-token)
9086 (push (js2-parse-assign-expr) result)))
9087 while
9088 (js2-match-token js2-COMMA))
9089 (js2-must-match js2-RP "msg.no.paren.arg")
9090 result)))
9091
9092 (defun js2-parse-member-expr (&optional allow-call-syntax)
9093 (let ((tt (js2-current-token-type))
9094 pn pos target args beg end init)
9095 (if (/= tt js2-NEW)
9096 (setq pn (js2-parse-primary-expr))
9097 ;; parse a 'new' expression
9098 (js2-get-token)
9099 (setq pos (js2-current-token-beg)
9100 beg pos
9101 target (js2-parse-member-expr)
9102 end (js2-node-end target)
9103 pn (make-js2-new-node :pos pos
9104 :target target
9105 :len (- end pos)))
9106 (js2-highlight-function-call (js2-current-token))
9107 (js2-node-add-children pn target)
9108 (when (js2-match-token js2-LP)
9109 ;; Add the arguments to pn, if any are supplied.
9110 (setf beg pos ; start of "new" keyword
9111 pos (js2-current-token-beg)
9112 args (nreverse (js2-parse-argument-list))
9113 (js2-new-node-args pn) args
9114 end (js2-current-token-end)
9115 (js2-new-node-lp pn) (- pos beg)
9116 (js2-new-node-rp pn) (- end 1 beg))
9117 (apply #'js2-node-add-children pn args))
9118 (when (and js2-allow-rhino-new-expr-initializer
9119 (js2-match-token js2-LC))
9120 (setf init (js2-parse-object-literal)
9121 end (js2-node-end init)
9122 (js2-new-node-initializer pn) init)
9123 (js2-node-add-children pn init))
9124 (setf (js2-node-len pn) (- end beg))) ; end outer if
9125 (js2-parse-member-expr-tail allow-call-syntax pn)))
9126
9127 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9128 "Parse a chain of property/array accesses or function calls.
9129 Includes parsing for E4X operators like `..' and `.@'.
9130 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9131 Returns an expression tree that includes PN, the parent node."
9132 (let (tt
9133 (continue t))
9134 (while continue
9135 (setq tt (js2-get-token))
9136 (cond
9137 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9138 (setq pn (js2-parse-property-access tt pn)))
9139 ((= tt js2-DOTQUERY)
9140 (setq pn (js2-parse-dot-query pn)))
9141 ((= tt js2-LB)
9142 (setq pn (js2-parse-element-get pn)))
9143 ((= tt js2-LP)
9144 (js2-unget-token)
9145 (if allow-call-syntax
9146 (setq pn (js2-parse-function-call pn))
9147 (setq continue nil)))
9148 (t
9149 (js2-unget-token)
9150 (setq continue nil))))
9151 (if (>= js2-highlight-level 2)
9152 (js2-parse-highlight-member-expr-node pn))
9153 pn))
9154
9155 (defun js2-parse-dot-query (pn)
9156 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9157 Last token parsed must be `js2-DOTQUERY'."
9158 (let ((pos (js2-node-pos pn))
9159 op-pos expr end)
9160 (js2-must-have-xml)
9161 (js2-set-requires-activation)
9162 (setq op-pos (js2-current-token-beg)
9163 expr (js2-parse-expr)
9164 end (js2-node-end expr)
9165 pn (make-js2-xml-dot-query-node :left pn
9166 :pos pos
9167 :op-pos op-pos
9168 :right expr))
9169 (js2-node-add-children pn
9170 (js2-xml-dot-query-node-left pn)
9171 (js2-xml-dot-query-node-right pn))
9172 (if (js2-must-match js2-RP "msg.no.paren")
9173 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9174 end (js2-current-token-end)))
9175 (setf (js2-node-len pn) (- end pos))
9176 pn))
9177
9178 (defun js2-parse-element-get (pn)
9179 "Parse an element-get expression, e.g. foo[bar].
9180 Last token parsed must be `js2-RB'."
9181 (let ((lb (js2-current-token-beg))
9182 (pos (js2-node-pos pn))
9183 rb expr)
9184 (setq expr (js2-parse-expr))
9185 (if (js2-must-match js2-RB "msg.no.bracket.index")
9186 (setq rb (js2-current-token-beg)))
9187 (setq pn (make-js2-elem-get-node :target pn
9188 :pos pos
9189 :element expr
9190 :lb (js2-relpos lb pos)
9191 :rb (js2-relpos rb pos)
9192 :len (- (js2-current-token-end) pos)))
9193 (js2-node-add-children pn
9194 (js2-elem-get-node-target pn)
9195 (js2-elem-get-node-element pn))
9196 pn))
9197
9198 (defun js2-highlight-function-call (token)
9199 (when (eq (js2-token-type token) js2-NAME)
9200 (js2-record-face 'js2-function-call token)))
9201
9202 (defun js2-parse-function-call (pn)
9203 (js2-highlight-function-call (js2-current-token))
9204 (js2-get-token)
9205 (let (args
9206 (pos (js2-node-pos pn)))
9207 (setq pn (make-js2-call-node :pos pos
9208 :target pn
9209 :lp (- (js2-current-token-beg) pos)))
9210 (js2-node-add-children pn (js2-call-node-target pn))
9211 ;; Add the arguments to pn, if any are supplied.
9212 (setf args (nreverse (js2-parse-argument-list))
9213 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9214 (js2-call-node-args pn) args)
9215 (apply #'js2-node-add-children pn args)
9216 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9217 pn))
9218
9219 (defun js2-parse-property-access (tt pn)
9220 "Parse a property access, XML descendants access, or XML attr access."
9221 (let ((member-type-flags 0)
9222 (dot-pos (js2-current-token-beg))
9223 (dot-len (if (= tt js2-DOTDOT) 2 1))
9224 name
9225 ref ; right side of . or .. operator
9226 result)
9227 (when (= tt js2-DOTDOT)
9228 (js2-must-have-xml)
9229 (setq member-type-flags js2-descendants-flag))
9230 (if (not js2-compiler-xml-available)
9231 (progn
9232 (js2-must-match-prop-name "msg.no.name.after.dot")
9233 (setq name (js2-create-name-node t js2-GETPROP)
9234 result (make-js2-prop-get-node :left pn
9235 :pos (js2-current-token-beg)
9236 :right name
9237 :len (js2-current-token-len)))
9238 (js2-node-add-children result pn name)
9239 result)
9240 ;; otherwise look for XML operators
9241 (setf result (if (= tt js2-DOT)
9242 (make-js2-prop-get-node)
9243 (make-js2-infix-node :type js2-DOTDOT))
9244 (js2-node-pos result) (js2-node-pos pn)
9245 (js2-infix-node-op-pos result) dot-pos
9246 (js2-infix-node-left result) pn ; do this after setting position
9247 tt (js2-next-token))
9248 (cond
9249 ;; needed for generator.throw()
9250 ((= tt js2-THROW)
9251 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9252 ;; handles: name, ns::name, ns::*, ns::[expr]
9253 ((js2-valid-prop-name-token tt)
9254 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9255 ;; handles: *, *::name, *::*, *::[expr]
9256 ((= tt js2-MUL)
9257 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9258 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9259 ((= tt js2-XMLATTR)
9260 (setq result (js2-parse-attribute-access)))
9261 (t
9262 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9263 (if ref
9264 (setf (js2-node-len result) (- (js2-node-end ref)
9265 (js2-node-pos result))
9266 (js2-infix-node-right result) ref))
9267 (if (js2-infix-node-p result)
9268 (js2-node-add-children result
9269 (js2-infix-node-left result)
9270 (js2-infix-node-right result)))
9271 result)))
9272
9273 (defun js2-parse-attribute-access ()
9274 "Parse an E4X XML attribute expression.
9275 This includes expressions of the forms:
9276
9277 @attr @ns::attr @ns::*
9278 @* @*::attr @*::*
9279 @[expr] @*::[expr] @ns::[expr]
9280
9281 Called if we peeked an '@' token."
9282 (let ((tt (js2-next-token))
9283 (at-pos (js2-current-token-beg)))
9284 (cond
9285 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9286 ((js2-valid-prop-name-token tt)
9287 (js2-parse-property-name at-pos nil 0))
9288 ;; handles: @*, @*::name, @*::*, @*::[expr]
9289 ((= tt js2-MUL)
9290 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9291 ;; handles @[expr]
9292 ((= tt js2-LB)
9293 (js2-parse-xml-elem-ref at-pos))
9294 (t
9295 (js2-report-error "msg.no.name.after.xmlAttr")
9296 ;; Avoid cascaded errors that happen if we make an error node here.
9297 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9298
9299 (defun js2-parse-property-name (at-pos s member-type-flags)
9300 "Check if :: follows name in which case it becomes qualified name.
9301
9302 AT-POS is a natural number if we just read an '@' token, else nil.
9303 S is the name or string that was matched: an identifier, 'throw' or '*'.
9304 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9305
9306 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9307 operator, or the name is followed by ::. For a plain name, returns a
9308 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9309 (let ((pos (or at-pos (js2-current-token-beg)))
9310 colon-pos
9311 (name (js2-create-name-node t (js2-current-token-type) s))
9312 ns tt pn)
9313 (catch 'return
9314 (when (js2-match-token js2-COLONCOLON)
9315 (setq ns name
9316 colon-pos (js2-current-token-beg)
9317 tt (js2-next-token))
9318 (cond
9319 ;; handles name::name
9320 ((js2-valid-prop-name-token tt)
9321 (setq name (js2-create-name-node)))
9322 ;; handles name::*
9323 ((= tt js2-MUL)
9324 (setq name (js2-create-name-node nil nil "*")))
9325 ;; handles name::[expr]
9326 ((= tt js2-LB)
9327 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9328 (t
9329 (js2-report-error "msg.no.name.after.coloncolon"))))
9330 (if (and (null ns) (zerop member-type-flags))
9331 name
9332 (prog1
9333 (setq pn
9334 (make-js2-xml-prop-ref-node :pos pos
9335 :len (- (js2-node-end name) pos)
9336 :at-pos at-pos
9337 :colon-pos colon-pos
9338 :propname name))
9339 (js2-node-add-children pn name))))))
9340
9341 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9342 "Parse the [expr] portion of an xml element reference.
9343 For instance, @[expr], @*::[expr], or ns::[expr]."
9344 (let* ((lb (js2-current-token-beg))
9345 (pos (or at-pos lb))
9346 rb
9347 (expr (js2-parse-expr))
9348 (end (js2-node-end expr))
9349 pn)
9350 (if (js2-must-match js2-RB "msg.no.bracket.index")
9351 (setq rb (js2-current-token-beg)
9352 end (js2-current-token-end)))
9353 (prog1
9354 (setq pn
9355 (make-js2-xml-elem-ref-node :pos pos
9356 :len (- end pos)
9357 :namespace namespace
9358 :colon-pos colon-pos
9359 :at-pos at-pos
9360 :expr expr
9361 :lb (js2-relpos lb pos)
9362 :rb (js2-relpos rb pos)))
9363 (js2-node-add-children pn namespace expr))))
9364
9365 (defun js2-parse-destruct-primary-expr ()
9366 (let ((js2-is-in-destructuring t))
9367 (js2-parse-primary-expr)))
9368
9369 (defun js2-parse-primary-expr ()
9370 "Parse a literal (leaf) expression of some sort.
9371 Includes complex literals such as functions, object-literals,
9372 array-literals, array comprehensions and regular expressions."
9373 (let (pn ; parent node (usually return value)
9374 tt)
9375 (setq tt (js2-current-token-type))
9376 (cond
9377 ((= tt js2-CLASS)
9378 (js2-parse-class-expr))
9379 ((= tt js2-FUNCTION)
9380 (js2-parse-function-expr))
9381 ((= tt js2-LB)
9382 (js2-parse-array-comp-or-literal))
9383 ((= tt js2-LC)
9384 (js2-parse-object-literal))
9385 ((= tt js2-LET)
9386 (js2-parse-let (js2-current-token-beg)))
9387 ((= tt js2-LP)
9388 (js2-parse-paren-expr-or-generator-comp))
9389 ((= tt js2-XMLATTR)
9390 (js2-must-have-xml)
9391 (js2-parse-attribute-access))
9392 ((= tt js2-NAME)
9393 (js2-parse-name tt))
9394 ((= tt js2-NUMBER)
9395 (make-js2-number-node))
9396 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9397 (make-js2-string-node :type tt))
9398 ((= tt js2-TEMPLATE_HEAD)
9399 (js2-parse-template-literal))
9400 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9401 ;; Got / or /= which in this context means a regexp literal
9402 (let ((px-pos (js2-current-token-beg))
9403 (flags (js2-read-regexp tt))
9404 (end (js2-current-token-end)))
9405 (prog1
9406 (make-js2-regexp-node :pos px-pos
9407 :len (- end px-pos)
9408 :value (js2-current-token-string)
9409 :flags flags)
9410 (js2-set-face px-pos end 'font-lock-string-face 'record)
9411 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9412 ((or (= tt js2-NULL)
9413 (= tt js2-THIS)
9414 (= tt js2-SUPER)
9415 (= tt js2-FALSE)
9416 (= tt js2-TRUE))
9417 (make-js2-keyword-node :type tt))
9418 ((= tt js2-RP)
9419 ;; Not valid expression syntax, but this is valid in an arrow
9420 ;; function with no params: () => body.
9421 (if (eq (js2-peek-token) js2-ARROW)
9422 (progn
9423 (js2-unget-token) ; Put back the right paren.
9424 ;; Return whatever, it will hopefully be rewinded and
9425 ;; reparsed when we reach the =>.
9426 (make-js2-keyword-node :type js2-NULL))
9427 (js2-report-error "msg.syntax")
9428 (make-js2-error-node)))
9429 ((= tt js2-TRIPLEDOT)
9430 ;; Likewise, only valid in an arrow function with a rest param.
9431 (if (and (js2-match-token js2-NAME)
9432 (js2-match-token js2-RP)
9433 (eq (js2-peek-token) js2-ARROW))
9434 (progn
9435 (js2-unget-token) ; Put back the right paren.
9436 ;; See the previous case.
9437 (make-js2-keyword-node :type js2-NULL))
9438 (js2-report-error "msg.syntax")
9439 (make-js2-error-node)))
9440 ((= tt js2-RESERVED)
9441 (js2-report-error "msg.reserved.id")
9442 (make-js2-name-node))
9443 ((= tt js2-ERROR)
9444 ;; the scanner or one of its subroutines reported the error.
9445 (make-js2-error-node))
9446 ((= tt js2-EOF)
9447 (let* ((px-pos (point-at-bol))
9448 (len (- js2-ts-cursor px-pos)))
9449 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9450 (make-js2-error-node :pos (1- js2-ts-cursor)))
9451 (t
9452 (js2-report-error "msg.syntax")
9453 (make-js2-error-node)))))
9454
9455 (defun js2-parse-template-literal ()
9456 (let ((beg (js2-current-token-beg))
9457 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
9458 (tt js2-TEMPLATE_HEAD))
9459 (while (eq tt js2-TEMPLATE_HEAD)
9460 (push (js2-parse-expr) kids)
9461 (js2-must-match js2-RC "msg.syntax")
9462 (setq tt (js2-get-token 'TEMPLATE_TAIL))
9463 (push (make-js2-string-node :type tt) kids))
9464 (setq kids (nreverse kids))
9465 (let ((tpl (make-js2-template-node :beg beg
9466 :len (- (js2-current-token-end) beg)
9467 :kids kids)))
9468 (apply #'js2-node-add-children tpl kids)
9469 tpl)))
9470
9471 (defun js2-parse-name (_tt)
9472 (let ((name (js2-current-token-string))
9473 node)
9474 (setq node (if js2-compiler-xml-available
9475 (js2-parse-property-name nil name 0)
9476 (js2-create-name-node 'check-activation nil name)))
9477 (if js2-highlight-external-variables
9478 (js2-record-name-node node))
9479 node))
9480
9481 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9482 (js2-add-strict-warning
9483 msg nil
9484 ;; back up from comma to beginning of line or array/objlit
9485 (max (if elems
9486 (js2-node-pos (car elems))
9487 pos)
9488 (save-excursion
9489 (goto-char comma-pos)
9490 (back-to-indentation)
9491 (point)))
9492 comma-pos))
9493
9494 (defun js2-parse-array-comp-or-literal ()
9495 (let ((pos (js2-current-token-beg)))
9496 (if (and (>= js2-language-version 200)
9497 (js2-match-token js2-FOR))
9498 (js2-parse-array-comp pos)
9499 (js2-parse-array-literal pos))))
9500
9501 (defun js2-parse-array-literal (pos)
9502 (let ((after-lb-or-comma t)
9503 after-comma tt elems pn
9504 (continue t))
9505 (unless js2-is-in-destructuring
9506 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9507 (while continue
9508 (setq tt (js2-get-token))
9509 (cond
9510 ;; comma
9511 ((= tt js2-COMMA)
9512 (setq after-comma (js2-current-token-end))
9513 (if (not after-lb-or-comma)
9514 (setq after-lb-or-comma t)
9515 (push nil elems)))
9516 ;; end of array
9517 ((or (= tt js2-RB)
9518 (= tt js2-EOF)) ; prevent infinite loop
9519 (if (= tt js2-EOF)
9520 (js2-report-error "msg.no.bracket.arg" nil pos))
9521 (when (and after-comma (< js2-language-version 170))
9522 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9523 pos (remove nil elems) after-comma))
9524 (setq continue nil
9525 pn (make-js2-array-node :pos pos
9526 :len (- js2-ts-cursor pos)
9527 :elems (nreverse elems)))
9528 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9529 ;; destructuring binding
9530 (js2-is-in-destructuring
9531 (push (if (or (= tt js2-LC)
9532 (= tt js2-LB)
9533 (= tt js2-NAME))
9534 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9535 (js2-parse-destruct-primary-expr)
9536 ;; invalid pattern
9537 (js2-report-error "msg.bad.var")
9538 (make-js2-error-node))
9539 elems)
9540 (setq after-lb-or-comma nil
9541 after-comma nil))
9542 ;; array comp
9543 ((and (>= js2-language-version 170)
9544 (= tt js2-FOR) ; check for array comprehension
9545 (not after-lb-or-comma) ; "for" can't follow a comma
9546 elems ; must have at least 1 element
9547 (not (cdr elems))) ; but no 2nd element
9548 (js2-unget-token)
9549 (setf continue nil
9550 pn (js2-parse-legacy-array-comp (car elems) pos)))
9551 ;; another element
9552 (t
9553 (unless after-lb-or-comma
9554 (js2-report-error "msg.no.bracket.arg"))
9555 (if (and (= tt js2-TRIPLEDOT)
9556 (>= js2-language-version 200))
9557 ;; spread operator
9558 (push (js2-make-unary tt 'js2-parse-assign-expr)
9559 elems)
9560 (js2-unget-token)
9561 (push (js2-parse-assign-expr) elems))
9562 (setq after-lb-or-comma nil
9563 after-comma nil))))
9564 (unless js2-is-in-destructuring
9565 (js2-pop-scope))
9566 pn))
9567
9568 (defun js2-parse-legacy-array-comp (expr pos)
9569 "Parse a legacy array comprehension (JavaScript 1.7).
9570 EXPR is the first expression after the opening left-bracket.
9571 POS is the beginning of the LB token preceding EXPR.
9572 We should have just parsed the 'for' keyword before calling this function."
9573 (let ((current-scope js2-current-scope)
9574 loops first filter result)
9575 (unwind-protect
9576 (progn
9577 (while (js2-match-token js2-FOR)
9578 (let ((loop (make-js2-comp-loop-node)))
9579 (js2-push-scope loop)
9580 (push loop loops)
9581 (js2-parse-comp-loop loop)))
9582 ;; First loop takes expr scope's parent.
9583 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9584 (js2-scope-parent-scope current-scope))
9585 ;; Set expr scope's parent to the last loop.
9586 (setf (js2-scope-parent-scope current-scope) (car loops))
9587 (if (/= (js2-get-token) js2-IF)
9588 (js2-unget-token)
9589 (setq filter (js2-parse-condition))))
9590 (dotimes (_ (1- (length loops)))
9591 (js2-pop-scope)))
9592 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9593 (setq result (make-js2-comp-node :pos pos
9594 :len (- js2-ts-cursor pos)
9595 :result expr
9596 :loops (nreverse loops)
9597 :filters (and filter (list (car filter)))
9598 :form 'LEGACY_ARRAY))
9599 (apply #'js2-node-add-children result expr (car filter)
9600 (js2-comp-node-loops result))
9601 result))
9602
9603 (defun js2-parse-array-comp (pos)
9604 "Parse an ES6 array comprehension.
9605 POS is the beginning of the LB token.
9606 We should have just parsed the 'for' keyword before calling this function."
9607 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9608 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9609 pn))
9610
9611 (defun js2-parse-generator-comp (pos)
9612 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9613 (js2-current-script-or-fn
9614 (make-js2-function-node :generator-type 'COMPREHENSION))
9615 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9616 (js2-must-match js2-RP "msg.no.paren" pos)
9617 pn))
9618
9619 (defun js2-parse-comprehension (pos form)
9620 (let (loops filters expr result)
9621 (unwind-protect
9622 (progn
9623 (js2-unget-token)
9624 (while (js2-match-token js2-FOR)
9625 (let ((loop (make-js2-comp-loop-node)))
9626 (js2-push-scope loop)
9627 (push loop loops)
9628 (js2-parse-comp-loop loop)))
9629 (while (js2-match-token js2-IF)
9630 (push (car (js2-parse-condition)) filters))
9631 (setq expr (js2-parse-assign-expr)))
9632 (dolist (_ loops)
9633 (js2-pop-scope)))
9634 (setq result (make-js2-comp-node :pos pos
9635 :len (- js2-ts-cursor pos)
9636 :result expr
9637 :loops (nreverse loops)
9638 :filters (nreverse filters)
9639 :form form))
9640 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9641 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9642 result))
9643
9644 (defun js2-parse-comp-loop (pn &optional only-of-p)
9645 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9646 The current token should be the initial FOR.
9647 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9648 (let ((pos (js2-comp-loop-node-pos pn))
9649 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9650 (when (and (not only-of-p) (js2-match-token js2-NAME))
9651 (if (string= (js2-current-token-string) "each")
9652 (progn
9653 (setq foreach-p t
9654 each-pos (- (js2-current-token-beg) pos)) ; relative
9655 (js2-record-face 'font-lock-keyword-face))
9656 (js2-report-error "msg.no.paren.for")))
9657 (if (js2-must-match js2-LP "msg.no.paren.for")
9658 (setq lp (- (js2-current-token-beg) pos)))
9659 (setq tt (js2-peek-token))
9660 (cond
9661 ((or (= tt js2-LB)
9662 (= tt js2-LC))
9663 (js2-get-token)
9664 (setq iter (js2-parse-destruct-primary-expr))
9665 (js2-define-destruct-symbols iter js2-LET
9666 'font-lock-variable-name-face t))
9667 ((js2-match-token js2-NAME)
9668 (setq iter (js2-create-name-node)))
9669 (t
9670 (js2-report-error "msg.bad.var")))
9671 ;; Define as a let since we want the scope of the variable to
9672 ;; be restricted to the array comprehension
9673 (if (js2-name-node-p iter)
9674 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9675 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9676 (and (>= js2-language-version 200)
9677 (js2-match-contextual-kwd "of")
9678 (setq forof-p t)))
9679 (setq in-pos (- (js2-current-token-beg) pos))
9680 (js2-report-error "msg.in.after.for.name"))
9681 (setq obj (js2-parse-expr))
9682 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9683 (setq rp (- (js2-current-token-beg) pos)))
9684 (setf (js2-node-pos pn) pos
9685 (js2-node-len pn) (- js2-ts-cursor pos)
9686 (js2-comp-loop-node-iterator pn) iter
9687 (js2-comp-loop-node-object pn) obj
9688 (js2-comp-loop-node-in-pos pn) in-pos
9689 (js2-comp-loop-node-each-pos pn) each-pos
9690 (js2-comp-loop-node-foreach-p pn) foreach-p
9691 (js2-comp-loop-node-forof-p pn) forof-p
9692 (js2-comp-loop-node-lp pn) lp
9693 (js2-comp-loop-node-rp pn) rp)
9694 (js2-node-add-children pn iter obj)
9695 pn))
9696
9697 (defun js2-parse-class-stmt ()
9698 (let ((pos (js2-current-token-beg)))
9699 (js2-must-match-name "msg.unnamed.class.stmt")
9700 (js2-parse-class pos 'CLASS_STATEMENT (js2-create-name-node t))))
9701
9702 (defun js2-parse-class-expr ()
9703 (let ((pos (js2-current-token-beg))
9704 name)
9705 (when (js2-match-token js2-NAME)
9706 (setq name (js2-create-name-node t)))
9707 (js2-parse-class pos 'CLASS_EXPRESSION name)))
9708
9709 (defun js2-parse-class (pos form name)
9710 ;; class X [extends ...] {
9711 (let (pn elems extends)
9712 (when name
9713 (js2-set-face (js2-node-pos name) (js2-node-end name)
9714 'font-lock-function-name-face 'record))
9715 (if (js2-match-token js2-EXTENDS)
9716 (if (= (js2-peek-token) js2-LC)
9717 (js2-report-error "msg.missing.extends")
9718 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
9719 (setq extends (js2-parse-assign-expr))
9720 (if (not extends)
9721 (js2-report-error "msg.bad.extends"))))
9722 (js2-must-match js2-LC "msg.no.brace.class")
9723 (setq elems (js2-parse-object-literal-elems t)
9724 pn (make-js2-class-node :pos pos
9725 :len (- js2-ts-cursor pos)
9726 :form form
9727 :name name
9728 :extends extends
9729 :elems elems))
9730 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
9731 pn))
9732
9733 (defun js2-parse-object-literal ()
9734 (let* ((pos (js2-current-token-beg))
9735 (elems (js2-parse-object-literal-elems))
9736 (result (make-js2-object-node :pos pos
9737 :len (- js2-ts-cursor pos)
9738 :elems elems)))
9739 (apply #'js2-node-add-children result (js2-object-node-elems result))
9740 result))
9741
9742 (defun js2-parse-object-literal-elems (&optional class-p)
9743 (let ((pos (js2-current-token-beg))
9744 (static nil)
9745 (continue t)
9746 tt elems elem after-comma)
9747 (while continue
9748 (setq static (and class-p (js2-match-token js2-STATIC))
9749 tt (js2-get-token)
9750 elem nil)
9751 (cond
9752 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9753 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
9754 ;; TODO(sdh): support *foo() {...}
9755 ((or (js2-valid-prop-name-token tt)
9756 (= tt js2-STRING))
9757 (setq after-comma nil
9758 elem (js2-parse-named-prop tt))
9759 (if (and (null elem)
9760 (not js2-recover-from-parse-errors))
9761 (setq continue nil)))
9762 ;; {[Symbol.iterator]: ...}
9763 ((and (= tt js2-LB)
9764 (>= js2-language-version 200))
9765 (let ((expr (js2-parse-expr)))
9766 (js2-must-match js2-RB "msg.missing.computed.rb")
9767 (setq after-comma nil
9768 elem (js2-parse-plain-property expr))))
9769 ;; {12: x} or {10.7: x}
9770 ((= tt js2-NUMBER)
9771 (setq after-comma nil
9772 elem (js2-parse-plain-property (make-js2-number-node))))
9773 ;; Break out of loop, and handle trailing commas.
9774 ((or (= tt js2-RC)
9775 (= tt js2-EOF))
9776 (js2-unget-token)
9777 (setq continue nil)
9778 (if after-comma
9779 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9780 pos elems after-comma)))
9781 (t
9782 (js2-report-error "msg.bad.prop")
9783 (unless js2-recover-from-parse-errors
9784 (setq continue nil)))) ; end switch
9785 ;; Handle static for classes' codegen.
9786 (if static
9787 (if elem (js2-node-set-prop elem 'STATIC t)
9788 (js2-report-error "msg.unexpected.static")))
9789 ;; Handle commas, depending on class-p.
9790 (let ((comma (js2-match-token js2-COMMA)))
9791 (if class-p
9792 (if comma
9793 (js2-report-error "msg.class.unexpected.comma"))
9794 (if comma
9795 (setq after-comma (js2-current-token-end))
9796 (setq continue nil))))
9797 ;; Append any parsed element.
9798 (if elem (push elem elems))) ; end loop
9799 (js2-must-match js2-RC "msg.no.brace.prop")
9800 (nreverse elems)))
9801
9802 (defun js2-parse-named-prop (tt)
9803 "Parse a name, string, or getter/setter object property.
9804 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9805 (let ((string-prop (and (= tt js2-STRING)
9806 (make-js2-string-node)))
9807 expr
9808 (ppos (js2-current-token-beg))
9809 (pend (js2-current-token-end))
9810 (name (js2-create-name-node))
9811 (prop (js2-current-token-string)))
9812 (cond
9813 ;; getter/setter prop
9814 ((and (= tt js2-NAME)
9815 (= (js2-peek-token) js2-NAME)
9816 (or (string= prop "get")
9817 (string= prop "set")))
9818 (js2-get-token)
9819 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9820 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9821 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9822 (js2-parse-getter-setter-prop ppos name prop))
9823 ;; method definition: {f() {...}}
9824 ((and (= (js2-peek-token) js2-LP)
9825 (>= js2-language-version 200))
9826 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; name
9827 (js2-parse-getter-setter-prop ppos name ""))
9828 ;; regular prop
9829 (t
9830 (prog1
9831 (setq expr (js2-parse-plain-property (or string-prop name)))
9832 (when (and (not string-prop)
9833 (not js2-is-in-destructuring)
9834 js2-highlight-external-variables
9835 (js2-node-get-prop expr 'SHORTHAND))
9836 (js2-record-name-node name))
9837 (js2-set-face ppos pend
9838 (if (js2-function-node-p
9839 (js2-object-prop-node-right expr))
9840 'font-lock-function-name-face
9841 'font-lock-variable-name-face)
9842 'record))))))
9843
9844 (defun js2-parse-plain-property (prop)
9845 "Parse a non-getter/setter property in an object literal.
9846 PROP is the node representing the property: a number, name or string."
9847 (let* ((tt (js2-get-token))
9848 (pos (js2-node-pos prop))
9849 colon expr result)
9850 (cond
9851 ;; Abbreviated property, as in {foo, bar}
9852 ((and (>= js2-language-version 200)
9853 (or (= tt js2-COMMA)
9854 (= tt js2-RC))
9855 (not (js2-number-node-p prop)))
9856 (js2-unget-token)
9857 (setq result (make-js2-object-prop-node
9858 :pos pos
9859 :left prop
9860 :right prop
9861 :op-pos (js2-current-token-len)))
9862 (js2-node-add-children result prop)
9863 (js2-node-set-prop result 'SHORTHAND t)
9864 result)
9865 ;; Normal property
9866 (t
9867 (if (= tt js2-COLON)
9868 (setq colon (- (js2-current-token-beg) pos)
9869 expr (js2-parse-assign-expr))
9870 (js2-report-error "msg.no.colon.prop")
9871 (setq expr (make-js2-error-node)))
9872 (setq result (make-js2-object-prop-node
9873 :pos pos
9874 ;; don't include last consumed token in length
9875 :len (- (+ (js2-node-pos expr)
9876 (js2-node-len expr))
9877 pos)
9878 :left prop
9879 :right expr
9880 :op-pos colon))
9881 (js2-node-add-children result prop expr)
9882 result))))
9883
9884 (defun js2-parse-getter-setter-prop (pos prop type-string)
9885 "Parse getter or setter property in an object literal.
9886 JavaScript syntax is:
9887
9888 { get foo() {...}, set foo(x) {...} }
9889
9890 and expression closure style is also supported
9891
9892 { get foo() x, set foo(x) _x = x }
9893
9894 POS is the start position of the `get' or `set' keyword.
9895 PROP is the `js2-name-node' representing the property name.
9896 GET-P is non-nil if the keyword was `get'."
9897 (let ((type (cond
9898 ((string= "get" type-string) js2-GET)
9899 ((string= "set" type-string) js2-SET)
9900 (t js2-FUNCTION)))
9901 result end
9902 (fn (js2-parse-function-expr)))
9903 ;; it has to be an anonymous function, as we already parsed the name
9904 (if (/= (js2-node-type fn) js2-FUNCTION)
9905 (js2-report-error "msg.bad.prop")
9906 (if (plusp (length (js2-function-name fn)))
9907 (js2-report-error "msg.bad.prop")))
9908 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9909 (setq end (js2-node-end fn)
9910 result (make-js2-getter-setter-node :type type
9911 :pos pos
9912 :len (- end pos)
9913 :left prop
9914 :right fn))
9915 (js2-node-add-children result prop fn)
9916 result))
9917
9918 (defun js2-create-name-node (&optional check-activation-p token string)
9919 "Create a name node using the current token and, optionally, STRING.
9920 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9921 (let* ((beg (js2-current-token-beg))
9922 (tt (js2-current-token-type))
9923 (s (or string
9924 (if (= js2-NAME tt)
9925 (js2-current-token-string)
9926 (js2-tt-name tt))))
9927 name)
9928 (setq name (make-js2-name-node :pos beg
9929 :name s
9930 :len (length s)))
9931 (if check-activation-p
9932 (js2-check-activation-name s (or token js2-NAME)))
9933 name))
9934
9935 ;;; Indentation support
9936
9937 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9938 ;; Karl cleverly deduces that the desired indentation level is often a
9939 ;; function of paren/bracket/brace nesting depth, which can be determined
9940 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9941 ;; then does some equally clever checks to see if we're in the context of a
9942 ;; substatement of a possibly braceless statement keyword such as if, while,
9943 ;; or finally. This approach yields pretty good results.
9944
9945 ;; The indenter is often "wrong", however, and needs to be overridden.
9946 ;; The right long-term solution is probably to emulate (or integrate
9947 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9948 ;; parse tree from `js2-parse' is present, which is not true at the
9949 ;; moment the user is typing, computing indentation is still thousands
9950 ;; of lines of code to handle every possible syntactic edge case.
9951
9952 ;; In the meantime, the compromise solution is that we offer a "bounce
9953 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9954 ;; current line indent among various likely guess points. This approach
9955 ;; is far from perfect, but should at least make it slightly easier to
9956 ;; move the line towards its desired indentation when manually
9957 ;; overriding Karl's heuristic nesting guesser.
9958
9959 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9960 ;; extensions such as `let' and Array comprehensions. Major kudos to
9961 ;; Karl for coming up with the initial approach, which packs a lot of
9962 ;; punch for so little code.
9963
9964 (defconst js2-possibly-braceless-keywords-re
9965 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9966 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9967 "try" "while" "with" "let")))
9968 "Regular expression matching keywords that are optionally
9969 followed by an opening brace.")
9970
9971 (defconst js2-indent-operator-re
9972 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9973 (regexp-opt '("in" "instanceof") 'words))
9974 "Regular expression matching operators that affect indentation
9975 of continued expressions.")
9976
9977 (defconst js2-declaration-keyword-re
9978 (regexp-opt '("var" "let" "const") 'words)
9979 "Regular expression matching variable declaration keywords.")
9980
9981 (defun js2-re-search-forward-inner (regexp &optional bound count)
9982 "Auxiliary function for `js2-re-search-forward'."
9983 (let (parse saved-point)
9984 (while (> count 0)
9985 (re-search-forward regexp bound)
9986 (setq parse (if saved-point
9987 (parse-partial-sexp saved-point (point))
9988 (syntax-ppss (point))))
9989 (cond ((nth 3 parse)
9990 (re-search-forward
9991 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9992 (save-excursion (end-of-line) (point)) t))
9993 ((nth 7 parse)
9994 (forward-line))
9995 ((or (nth 4 parse)
9996 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9997 (re-search-forward "\\*/"))
9998 (t
9999 (setq count (1- count))))
10000 (setq saved-point (point))))
10001 (point))
10002
10003 (defun js2-re-search-forward (regexp &optional bound noerror count)
10004 "Search forward but ignore strings and comments.
10005 Invokes `re-search-forward' but treats the buffer as if strings
10006 and comments have been removed."
10007 (let ((saved-point (point)))
10008 (condition-case err
10009 (cond ((null count)
10010 (js2-re-search-forward-inner regexp bound 1))
10011 ((< count 0)
10012 (js2-re-search-backward-inner regexp bound (- count)))
10013 ((> count 0)
10014 (js2-re-search-forward-inner regexp bound count)))
10015 (search-failed
10016 (goto-char saved-point)
10017 (unless noerror
10018 (error (error-message-string err)))))))
10019
10020 (defun js2-re-search-backward-inner (regexp &optional bound count)
10021 "Auxiliary function for `js2-re-search-backward'."
10022 (let (parse)
10023 (while (> count 0)
10024 (re-search-backward regexp bound)
10025 (setq parse (syntax-ppss (point)))
10026 (cond ((nth 3 parse)
10027 (re-search-backward
10028 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10029 (line-beginning-position) t))
10030 ((nth 7 parse)
10031 (goto-char (nth 8 parse)))
10032 ((or (nth 4 parse)
10033 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10034 (re-search-backward "/\\*"))
10035 (t
10036 (setq count (1- count))))))
10037 (point))
10038
10039 (defun js2-re-search-backward (regexp &optional bound noerror count)
10040 "Search backward but ignore strings and comments.
10041 Invokes `re-search-backward' but treats the buffer as if strings
10042 and comments have been removed."
10043 (let ((saved-point (point)))
10044 (condition-case err
10045 (cond ((null count)
10046 (js2-re-search-backward-inner regexp bound 1))
10047 ((< count 0)
10048 (js2-re-search-forward-inner regexp bound (- count)))
10049 ((> count 0)
10050 (js2-re-search-backward-inner regexp bound count)))
10051 (search-failed
10052 (goto-char saved-point)
10053 (unless noerror
10054 (error (error-message-string err)))))))
10055
10056 (defun js2-looking-at-operator-p ()
10057 "Return non-nil if text after point is a non-comma operator."
10058 (and (looking-at js2-indent-operator-re)
10059 (or (not (looking-at ":"))
10060 (save-excursion
10061 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10062 (looking-at "?"))))))
10063
10064 (defun js2-continued-expression-p ()
10065 "Return non-nil if the current line continues an expression."
10066 (save-excursion
10067 (back-to-indentation)
10068 (or (js2-looking-at-operator-p)
10069 (when (catch 'found
10070 (while (and (re-search-backward "\n" nil t)
10071 (let ((state (syntax-ppss)))
10072 (when (nth 4 state)
10073 (goto-char (nth 8 state))) ;; skip comments
10074 (skip-chars-backward " \t")
10075 (if (bolp)
10076 t
10077 (throw 'found t))))))
10078 (backward-char)
10079 (when (js2-looking-at-operator-p)
10080 (backward-char)
10081 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10082
10083 (defun js2-end-of-do-while-loop-p ()
10084 "Return non-nil if word after point is `while' of a do-while
10085 statement, else returns nil. A braceless do-while statement
10086 spanning several lines requires that the start of the loop is
10087 indented to the same column as the current line."
10088 (interactive)
10089 (save-excursion
10090 (when (looking-at "\\s-*\\<while\\>")
10091 (if (save-excursion
10092 (skip-chars-backward "[ \t\n]*}")
10093 (looking-at "[ \t\n]*}"))
10094 (save-excursion
10095 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10096 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10097 (or (looking-at "\\<do\\>")
10098 (let ((saved-indent (current-indentation)))
10099 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10100 (/= (current-indentation) saved-indent)))
10101 (and (looking-at "[ \t]*\\<do\\>")
10102 (not (js2-re-search-forward
10103 "\\<while\\>" (point-at-eol) t))
10104 (= (current-indentation) saved-indent))))))))
10105
10106 (defun js2-multiline-decl-indentation ()
10107 "Return the declaration indentation column if the current line belongs
10108 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10109 (let (forward-sexp-function ; use Lisp version
10110 at-opening-bracket)
10111 (save-excursion
10112 (back-to-indentation)
10113 (when (not (looking-at js2-declaration-keyword-re))
10114 (when (looking-at js2-indent-operator-re)
10115 (goto-char (match-end 0))) ; continued expressions are ok
10116 (while (and (not at-opening-bracket)
10117 (not (bobp))
10118 (let ((pos (point)))
10119 (save-excursion
10120 (js2-backward-sws)
10121 (or (eq (char-before) ?,)
10122 (and (not (eq (char-before) ?\;))
10123 (prog2 (skip-syntax-backward ".")
10124 (looking-at js2-indent-operator-re)
10125 (js2-backward-sws))
10126 (not (eq (char-before) ?\;)))
10127 (js2-same-line pos)))))
10128 (condition-case _
10129 (backward-sexp)
10130 (scan-error (setq at-opening-bracket t))))
10131 (when (looking-at js2-declaration-keyword-re)
10132 (goto-char (match-end 0))
10133 (1+ (current-column)))))))
10134
10135 (defun js2-ctrl-statement-indentation ()
10136 "Return the proper indentation of current line if it is a control statement.
10137 Returns an indentation if this line starts the body of a control
10138 statement without braces, else returns nil."
10139 (let (forward-sexp-function)
10140 (save-excursion
10141 (back-to-indentation)
10142 (when (and (not (js2-same-line (point-min)))
10143 (not (looking-at "{"))
10144 (js2-re-search-backward "[[:graph:]]" nil t)
10145 (not (looking-at "[{([]"))
10146 (progn
10147 (forward-char)
10148 (when (= (char-before) ?\))
10149 ;; scan-sexps sometimes throws an error
10150 (ignore-errors (backward-sexp))
10151 (skip-chars-backward " \t" (point-at-bol)))
10152 (let ((pt (point)))
10153 (back-to-indentation)
10154 (when (looking-at "}[ \t]*")
10155 (goto-char (match-end 0)))
10156 (and (looking-at js2-possibly-braceless-keywords-re)
10157 (= (match-end 0) pt)
10158 (not (js2-end-of-do-while-loop-p))))))
10159 (+ (current-indentation) js2-basic-offset)))))
10160
10161 (defun js2-indent-in-array-comp (parse-status)
10162 "Return non-nil if we think we're in an array comprehension.
10163 In particular, return the buffer position of the first `for' kwd."
10164 (let ((bracket (nth 1 parse-status))
10165 (end (point)))
10166 (when bracket
10167 (save-excursion
10168 (goto-char bracket)
10169 (when (looking-at "\\[")
10170 (forward-char 1)
10171 (js2-forward-sws)
10172 (if (looking-at "[[{]")
10173 (let (forward-sexp-function) ; use Lisp version
10174 (forward-sexp) ; skip destructuring form
10175 (js2-forward-sws)
10176 (if (and (/= (char-after) ?,) ; regular array
10177 (looking-at "for"))
10178 (match-beginning 0)))
10179 ;; to skip arbitrary expressions we need the parser,
10180 ;; so we'll just guess at it.
10181 (if (and (> end (point)) ; not empty literal
10182 (re-search-forward "[^,]]* \\(for\\) " end t)
10183 ;; not inside comment or string literal
10184 (let ((state (parse-partial-sexp bracket (point))))
10185 (not (or (nth 3 state) (nth 4 state)))))
10186 (match-beginning 1))))))))
10187
10188 (defun js2-array-comp-indentation (parse-status for-kwd)
10189 (if (js2-same-line for-kwd)
10190 ;; first continuation line
10191 (save-excursion
10192 (goto-char (nth 1 parse-status))
10193 (forward-char 1)
10194 (skip-chars-forward " \t")
10195 (current-column))
10196 (save-excursion
10197 (goto-char for-kwd)
10198 (current-column))))
10199
10200 (defun js2-proper-indentation (parse-status)
10201 "Return the proper indentation for the current line."
10202 (save-excursion
10203 (back-to-indentation)
10204 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10205 (at-closing-bracket (looking-at "[]})]"))
10206 (same-indent-p (or at-closing-bracket
10207 (looking-at "\\<case\\>[^:]")
10208 (and (looking-at "\\<default:")
10209 (save-excursion
10210 (js2-backward-sws)
10211 (not (memq (char-before) '(?, ?{)))))))
10212 (continued-expr-p (js2-continued-expression-p))
10213 (declaration-indent (and js2-pretty-multiline-declarations
10214 (js2-multiline-decl-indentation)))
10215 (bracket (nth 1 parse-status))
10216 beg indent)
10217 (cond
10218 ;; indent array comprehension continuation lines specially
10219 ((and bracket
10220 (>= js2-language-version 170)
10221 (not (js2-same-line bracket))
10222 (setq beg (js2-indent-in-array-comp parse-status))
10223 (>= (point) (save-excursion
10224 (goto-char beg)
10225 (point-at-bol)))) ; at or after first loop?
10226 (js2-array-comp-indentation parse-status beg))
10227
10228 (ctrl-stmt-indent)
10229
10230 ((and declaration-indent continued-expr-p)
10231 (+ declaration-indent js2-basic-offset))
10232
10233 (declaration-indent)
10234
10235 (bracket
10236 (goto-char bracket)
10237 (cond
10238 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10239 (when (save-excursion (skip-chars-backward " \t)")
10240 (looking-at ")"))
10241 (backward-list))
10242 (back-to-indentation)
10243 (and (eq js2-pretty-multiline-declarations 'all)
10244 (looking-at js2-declaration-keyword-re)
10245 (goto-char (1+ (match-end 0))))
10246 (setq indent
10247 (cond (same-indent-p
10248 (current-column))
10249 (continued-expr-p
10250 (+ (current-column) (* 2 js2-basic-offset)))
10251 (t
10252 (+ (current-column) js2-basic-offset))))
10253 (if (and js2-indent-switch-body
10254 (not at-closing-bracket)
10255 (looking-at "\\_<switch\\_>"))
10256 (+ indent js2-basic-offset)
10257 indent))
10258 (t
10259 (unless same-indent-p
10260 (forward-char)
10261 (skip-chars-forward " \t"))
10262 (current-column))))
10263
10264 (continued-expr-p js2-basic-offset)
10265
10266 (t 0)))))
10267
10268 (defun js2-lineup-comment (parse-status)
10269 "Indent a multi-line block comment continuation line."
10270 (let* ((beg (nth 8 parse-status))
10271 (first-line (js2-same-line beg))
10272 (offset (save-excursion
10273 (goto-char beg)
10274 (if (looking-at "/\\*")
10275 (+ 1 (current-column))
10276 0))))
10277 (unless first-line
10278 (indent-line-to offset))))
10279
10280 (defun js2-backward-sws ()
10281 "Move backward through whitespace and comments."
10282 (interactive)
10283 (while (forward-comment -1)))
10284
10285 (defun js2-forward-sws ()
10286 "Move forward through whitespace and comments."
10287 (interactive)
10288 (while (forward-comment 1)))
10289
10290 (defun js2-current-indent (&optional pos)
10291 "Return column of indentation on current line.
10292 If POS is non-nil, go to that point and return indentation for that line."
10293 (save-excursion
10294 (if pos
10295 (goto-char pos))
10296 (back-to-indentation)
10297 (current-column)))
10298
10299 (defun js2-arglist-close ()
10300 "Return non-nil if we're on a line beginning with a close-paren/brace."
10301 (save-excursion
10302 (goto-char (point-at-bol))
10303 (js2-forward-sws)
10304 (looking-at "[])}]")))
10305
10306 (defun js2-indent-looks-like-label-p ()
10307 (goto-char (point-at-bol))
10308 (js2-forward-sws)
10309 (looking-at (concat js2-mode-identifier-re ":")))
10310
10311 (defun js2-indent-in-objlit-p (parse-status)
10312 "Return non-nil if this looks like an object-literal entry."
10313 (let ((start (nth 1 parse-status)))
10314 (and
10315 start
10316 (save-excursion
10317 (and (zerop (forward-line -1))
10318 (not (< (point) start)) ; crossed a {} boundary
10319 (js2-indent-looks-like-label-p)))
10320 (save-excursion
10321 (js2-indent-looks-like-label-p)))))
10322
10323 ;; If prev line looks like foobar({ then we're passing an object
10324 ;; literal to a function call, and people pretty much always want to
10325 ;; de-dent back to the previous line, so move the 'basic-offset'
10326 ;; position to the front.
10327 (defun js2-indent-objlit-arg-p (parse-status)
10328 (save-excursion
10329 (back-to-indentation)
10330 (js2-backward-sws)
10331 (and (eq (1- (point)) (nth 1 parse-status))
10332 (eq (char-before) ?{)
10333 (progn
10334 (forward-char -1)
10335 (skip-chars-backward " \t")
10336 (eq (char-before) ?\()))))
10337
10338 (defun js2-indent-case-block-p ()
10339 (save-excursion
10340 (back-to-indentation)
10341 (js2-backward-sws)
10342 (goto-char (point-at-bol))
10343 (skip-chars-forward " \t")
10344 (looking-at "case\\s-.+:")))
10345
10346 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10347 "Cycle among alternate computed indentation positions.
10348 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10349 of the buffer to the current point. NORMAL-COL is the indentation
10350 column computed by the heuristic guesser based on current paren,
10351 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10352 in reverse."
10353 (let ((cur-indent (js2-current-indent))
10354 (old-buffer-undo-list buffer-undo-list)
10355 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10356 (current-line (save-excursion
10357 (forward-line 0) ; move to bol
10358 (1+ (count-lines (point-min) (point)))))
10359 positions pos main-pos anchor arglist-cont same-indent
10360 basic-offset computed-pos)
10361 ;; temporarily don't record undo info, if user requested this
10362 (when js2-mode-indent-inhibit-undo
10363 (setq buffer-undo-list t))
10364 (unwind-protect
10365 (progn
10366 ;; First likely point: indent from beginning of previous code line
10367 (push (setq basic-offset
10368 (+ (save-excursion
10369 (back-to-indentation)
10370 (js2-backward-sws)
10371 (back-to-indentation)
10372 (current-column))
10373 js2-basic-offset))
10374 positions)
10375
10376 ;; (First + epsilon) likely point: indent 2x from beginning of
10377 ;; previous code line. Google does it this way.
10378 (push (setq basic-offset
10379 (+ (save-excursion
10380 (back-to-indentation)
10381 (js2-backward-sws)
10382 (back-to-indentation)
10383 (current-column))
10384 (* 2 js2-basic-offset)))
10385 positions)
10386
10387 ;; Second likely point: indent from assign-expr RHS. This
10388 ;; is just a crude guess based on finding " = " on the previous
10389 ;; line containing actual code.
10390 (setq pos (save-excursion
10391 (forward-line -1)
10392 (goto-char (point-at-bol))
10393 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10394 (point-at-eol) t)
10395 (goto-char (match-end 1))
10396 (skip-chars-forward " \t\r\n")
10397 (current-column))))
10398 (when pos
10399 (incf pos js2-basic-offset)
10400 (push pos positions))
10401
10402 ;; Third likely point: same indent as previous line of code.
10403 ;; Make it the first likely point if we're not on an
10404 ;; arglist-close line and previous line ends in a comma, or
10405 ;; both this line and prev line look like object-literal
10406 ;; elements.
10407 (setq pos (save-excursion
10408 (goto-char (point-at-bol))
10409 (js2-backward-sws)
10410 (back-to-indentation)
10411 (prog1
10412 (current-column)
10413 ;; while we're here, look for trailing comma
10414 (if (save-excursion
10415 (goto-char (point-at-eol))
10416 (js2-backward-sws)
10417 (eq (char-before) ?,))
10418 (setq arglist-cont (1- (point)))))))
10419 (when pos
10420 (if (and (or arglist-cont
10421 (js2-indent-in-objlit-p parse-status))
10422 (not (js2-arglist-close)))
10423 (setq same-indent pos))
10424 (push pos positions))
10425
10426 ;; Fourth likely point: first preceding code with less indentation.
10427 ;; than the immediately preceding code line.
10428 (setq pos (save-excursion
10429 (back-to-indentation)
10430 (js2-backward-sws)
10431 (back-to-indentation)
10432 (setq anchor (current-column))
10433 (while (and (zerop (forward-line -1))
10434 (>= (progn
10435 (back-to-indentation)
10436 (current-column))
10437 anchor)))
10438 (setq pos (current-column))))
10439 (push pos positions)
10440
10441 ;; nesting-heuristic position, main by default
10442 (push (setq main-pos normal-col) positions)
10443
10444 ;; delete duplicates and sort positions list
10445 (setq positions (sort (delete-dups positions) '<))
10446
10447 ;; comma-list continuation lines: prev line indent takes precedence
10448 (if same-indent
10449 (setq main-pos same-indent))
10450
10451 ;; common special cases where we want to indent in from previous line
10452 (if (or (js2-indent-case-block-p)
10453 (js2-indent-objlit-arg-p parse-status))
10454 (setq main-pos basic-offset))
10455
10456 ;; if bouncing backwards, reverse positions list
10457 (if backwards
10458 (setq positions (reverse positions)))
10459
10460 ;; record whether we're already sitting on one of the alternatives
10461 (setq pos (member cur-indent positions))
10462
10463 (cond
10464 ;; case 0: we're one one of the alternatives and this is the
10465 ;; first time they've pressed TAB on this line (best-guess).
10466 ((and js2-mode-indent-ignore-first-tab
10467 pos
10468 ;; first time pressing TAB on this line?
10469 (not (eq js2-mode-last-indented-line current-line)))
10470 ;; do nothing
10471 (setq computed-pos nil))
10472 ;; case 1: only one computed position => use it
10473 ((null (cdr positions))
10474 (setq computed-pos 0))
10475 ;; case 2: not on any of the computed spots => use main spot
10476 ((not pos)
10477 (setq computed-pos (js2-position main-pos positions)))
10478 ;; case 3: on last position: cycle to first position
10479 ((null (cdr pos))
10480 (setq computed-pos 0))
10481 ;; case 4: on intermediate position: cycle to next position
10482 (t
10483 (setq computed-pos (js2-position (second pos) positions))))
10484
10485 ;; see if any hooks want to indent; otherwise we do it
10486 (loop with result = nil
10487 for hook in js2-indent-hook
10488 while (null result)
10489 do
10490 (setq result (funcall hook positions computed-pos))
10491 finally do
10492 (unless (or result (null computed-pos))
10493 (indent-line-to (nth computed-pos positions)))))
10494
10495 ;; finally
10496 (if js2-mode-indent-inhibit-undo
10497 (setq buffer-undo-list old-buffer-undo-list))
10498 ;; see commentary for `js2-mode-last-indented-line'
10499 (setq js2-mode-last-indented-line current-line))))
10500
10501 (defun js2-indent-bounce-backwards ()
10502 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10503 cycles between the computed indentation positions in reverse order."
10504 (interactive)
10505 (js2-indent-line t))
10506
10507 (defun js2-1-line-comment-continuation-p ()
10508 "Return t if we're in a 1-line comment continuation.
10509 If so, we don't ever want to use bounce-indent."
10510 (save-excursion
10511 (and (progn
10512 (forward-line 0)
10513 (looking-at "\\s-*//"))
10514 (progn
10515 (forward-line -1)
10516 (forward-line 0)
10517 (when (looking-at "\\s-*$")
10518 (js2-backward-sws)
10519 (forward-line 0))
10520 (looking-at "\\s-*//")))))
10521
10522 (defun js2-indent-line (&optional bounce-backwards)
10523 "Indent the current line as JavaScript source text."
10524 (interactive)
10525 (let (parse-status offset indent-col
10526 ;; Don't whine about errors/warnings when we're indenting.
10527 ;; This has to be set before calling parse-partial-sexp below.
10528 (inhibit-point-motion-hooks t))
10529 (setq parse-status (save-excursion
10530 (syntax-ppss (point-at-bol)))
10531 offset (- (point) (save-excursion
10532 (back-to-indentation)
10533 (point))))
10534 (js2-with-underscore-as-word-syntax
10535 (if (nth 4 parse-status)
10536 (js2-lineup-comment parse-status)
10537 (setq indent-col (js2-proper-indentation parse-status))
10538 ;; See comments below about `js2-mode-last-indented-line'.
10539 (cond
10540 ;; bounce-indenting is disabled during electric-key indent.
10541 ;; It doesn't work well on first line of buffer.
10542 ((and js2-bounce-indent-p
10543 (not (js2-same-line (point-min)))
10544 (not (js2-1-line-comment-continuation-p)))
10545 (js2-bounce-indent indent-col parse-status bounce-backwards))
10546 ;; just indent to the guesser's likely spot
10547 (t (indent-line-to indent-col))))
10548 (when (plusp offset)
10549 (forward-char offset)))))
10550
10551 (defun js2-indent-region (start end)
10552 "Indent the region, but don't use bounce indenting."
10553 (let ((js2-bounce-indent-p nil)
10554 (indent-region-function nil)
10555 (after-change-functions (remq 'js2-mode-edit
10556 after-change-functions)))
10557 (indent-region start end nil) ; nil for byte-compiler
10558 (js2-mode-edit start end (- end start))))
10559
10560 (defvar js2-minor-mode-map
10561 (let ((map (make-sparse-keymap)))
10562 (define-key map (kbd "C-c C-`") #'js2-next-error)
10563 (define-key map [mouse-1] #'js2-mode-show-node)
10564 map)
10565 "Keymap used when `js2-minor-mode' is active.")
10566
10567 ;;;###autoload
10568 (define-minor-mode js2-minor-mode
10569 "Minor mode for running js2 as a background linter.
10570 This allows you to use a different major mode for JavaScript editing,
10571 such as `js-mode', while retaining the asynchronous error/warning
10572 highlighting features of `js2-mode'."
10573 :group 'js2-mode
10574 :lighter " js-lint"
10575 (if js2-minor-mode
10576 (js2-minor-mode-enter)
10577 (js2-minor-mode-exit)))
10578
10579 (defun js2-minor-mode-enter ()
10580 "Initialization for `js2-minor-mode'."
10581 (set (make-local-variable 'max-lisp-eval-depth)
10582 (max max-lisp-eval-depth 3000))
10583 (setq next-error-function #'js2-next-error)
10584 (js2-set-default-externs)
10585 ;; Experiment: make reparse-delay longer for longer files.
10586 (if (plusp js2-dynamic-idle-timer-adjust)
10587 (setq js2-idle-timer-delay
10588 (* js2-idle-timer-delay
10589 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10590 (setq js2-mode-buffer-dirty-p t
10591 js2-mode-parsing nil)
10592 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10593 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10594 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10595 (when js2-include-jslint-globals
10596 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10597 (run-hooks 'js2-init-hook)
10598 (js2-reparse))
10599
10600 (defun js2-minor-mode-exit ()
10601 "Turn off `js2-minor-mode'."
10602 (setq next-error-function nil)
10603 (remove-hook 'after-change-functions #'js2-mode-edit t)
10604 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10605 (when js2-mode-node-overlay
10606 (delete-overlay js2-mode-node-overlay)
10607 (setq js2-mode-node-overlay nil))
10608 (js2-remove-overlays)
10609 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10610 (setq js2-mode-ast nil))
10611
10612 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10613 (make-variable-buffer-local 'js2-source-buffer)
10614
10615 (defun* js2-display-error-list ()
10616 "Display a navigable buffer listing parse errors/warnings."
10617 (interactive)
10618 (unless (js2-have-errors-p)
10619 (message "No errors")
10620 (return-from js2-display-error-list))
10621 (labels ((annotate-list
10622 (lst type)
10623 "Add diagnostic TYPE and line number to errs list"
10624 (mapcar (lambda (err)
10625 (list err type (line-number-at-pos (nth 1 err))))
10626 lst)))
10627 (let* ((srcbuf (current-buffer))
10628 (errbuf (get-buffer-create "*js-lint*"))
10629 (errors (annotate-list
10630 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10631 'js2-error)) ; must be a valid face name
10632 (warnings (annotate-list
10633 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10634 'js2-warning)) ; must be a valid face name
10635 (all-errs (sort (append errors warnings)
10636 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10637 (with-current-buffer errbuf
10638 (let ((inhibit-read-only t))
10639 (erase-buffer)
10640 (dolist (err all-errs)
10641 (destructuring-bind ((msg-key beg _end &rest) type line) err
10642 (insert-text-button
10643 (format "line %d: %s" line (js2-get-msg msg-key))
10644 'face type
10645 'follow-link "\C-m"
10646 'action 'js2-error-buffer-jump
10647 'js2-msg (js2-get-msg msg-key)
10648 'js2-pos beg)
10649 (insert "\n"))))
10650 (js2-error-buffer-mode)
10651 (setq js2-source-buffer srcbuf)
10652 (pop-to-buffer errbuf)
10653 (goto-char (point-min))
10654 (unless (eobp)
10655 (js2-error-buffer-view))))))
10656
10657 (defvar js2-error-buffer-mode-map
10658 (let ((map (make-sparse-keymap)))
10659 (define-key map "n" #'js2-error-buffer-next)
10660 (define-key map "p" #'js2-error-buffer-prev)
10661 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10662 (define-key map "o" #'js2-error-buffer-view)
10663 (define-key map "q" #'js2-error-buffer-quit)
10664 map)
10665 "Keymap used for js2 diagnostics buffers.")
10666
10667 (defun js2-error-buffer-mode ()
10668 "Major mode for js2 diagnostics buffers.
10669 Selecting an error will jump it to the corresponding source-buffer error.
10670 \\{js2-error-buffer-mode-map}"
10671 (interactive)
10672 (setq major-mode 'js2-error-buffer-mode
10673 mode-name "JS Lint Diagnostics")
10674 (use-local-map js2-error-buffer-mode-map)
10675 (setq truncate-lines t)
10676 (set-buffer-modified-p nil)
10677 (setq buffer-read-only t)
10678 (run-hooks 'js2-error-buffer-mode-hook))
10679
10680 (defun js2-error-buffer-next ()
10681 "Move to next error and view it."
10682 (interactive)
10683 (when (zerop (forward-line 1))
10684 (js2-error-buffer-view)))
10685
10686 (defun js2-error-buffer-prev ()
10687 "Move to previous error and view it."
10688 (interactive)
10689 (when (zerop (forward-line -1))
10690 (js2-error-buffer-view)))
10691
10692 (defun js2-error-buffer-quit ()
10693 "Kill the current buffer."
10694 (interactive)
10695 (kill-buffer))
10696
10697 (defun js2-error-buffer-jump (&rest ignored)
10698 "Jump cursor to current error in source buffer."
10699 (interactive)
10700 (when (js2-error-buffer-view)
10701 (pop-to-buffer js2-source-buffer)))
10702
10703 (defun js2-error-buffer-view ()
10704 "Scroll source buffer to show error at current line."
10705 (interactive)
10706 (cond
10707 ((not (eq major-mode 'js2-error-buffer-mode))
10708 (message "Not in a js2 errors buffer"))
10709 ((not (buffer-live-p js2-source-buffer))
10710 (message "Source buffer has been killed"))
10711 ((not (wholenump (get-text-property (point) 'js2-pos)))
10712 (message "There does not seem to be an error here"))
10713 (t
10714 (let ((pos (get-text-property (point) 'js2-pos))
10715 (msg (get-text-property (point) 'js2-msg)))
10716 (save-selected-window
10717 (pop-to-buffer js2-source-buffer)
10718 (goto-char pos)
10719 (message msg))))))
10720
10721 ;;;###autoload
10722 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10723 ;; FIXME: Should derive from js-mode.
10724 "Major mode for editing JavaScript code."
10725 ;; Used by comment-region; don't change it.
10726 (set (make-local-variable 'comment-start) "//")
10727 (set (make-local-variable 'comment-end) "")
10728 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10729 (set (make-local-variable 'max-lisp-eval-depth)
10730 (max max-lisp-eval-depth 3000))
10731 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10732 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10733 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10734 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10735 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10736 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10737 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10738 ;; for characters inside regexp literals.
10739 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10740 ;; this is necessary to make `show-paren-function' work properly
10741 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10742 ;; needed for M-x rgrep, among other things
10743 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10744
10745 (set (make-local-variable 'electric-indent-chars)
10746 (append "{}()[]:;,*." electric-indent-chars))
10747 (set (make-local-variable 'electric-layout-rules)
10748 '((?\; . after) (?\{ . after) (?\} . before)))
10749
10750 ;; some variables needed by cc-engine for paragraph-fill, etc.
10751 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10752 c-comment-start-regexp "/[*/]\\|\\s|"
10753 c-line-comment-starter "//"
10754 c-paragraph-start js2-paragraph-start
10755 c-paragraph-separate "$"
10756 c-syntactic-ws-start js2-syntactic-ws-start
10757 c-syntactic-ws-end js2-syntactic-ws-end
10758 c-syntactic-eol js2-syntactic-eol)
10759
10760 (let ((c-buffer-is-cc-mode t))
10761 ;; Copied from `js-mode'. Also see Bug#6071.
10762 (make-local-variable 'paragraph-start)
10763 (make-local-variable 'paragraph-separate)
10764 (make-local-variable 'paragraph-ignore-fill-prefix)
10765 (make-local-variable 'adaptive-fill-mode)
10766 (make-local-variable 'adaptive-fill-regexp)
10767 (c-setup-paragraph-variables))
10768
10769 (setq font-lock-defaults '(nil t))
10770
10771 ;; Experiment: make reparse-delay longer for longer files.
10772 (when (plusp js2-dynamic-idle-timer-adjust)
10773 (setq js2-idle-timer-delay
10774 (* js2-idle-timer-delay
10775 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10776
10777 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10778 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10779 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10780 (setq next-error-function #'js2-next-error)
10781 (imenu-add-to-menubar (concat "IM-" mode-name))
10782 (add-to-invisibility-spec '(js2-outline . t))
10783 (set (make-local-variable 'line-move-ignore-invisible) t)
10784 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10785
10786 (setq js2-mode-functions-hidden nil
10787 js2-mode-comments-hidden nil
10788 js2-mode-buffer-dirty-p t
10789 js2-mode-parsing nil)
10790
10791 (js2-set-default-externs)
10792
10793 (when js2-include-jslint-globals
10794 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10795
10796 (run-hooks 'js2-init-hook)
10797
10798 (js2-reparse))
10799
10800 (defun js2-mode-exit ()
10801 "Exit `js2-mode' and clean up."
10802 (interactive)
10803 (when js2-mode-node-overlay
10804 (delete-overlay js2-mode-node-overlay)
10805 (setq js2-mode-node-overlay nil))
10806 (js2-remove-overlays)
10807 (setq js2-mode-ast nil)
10808 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10809 (remove-from-invisibility-spec '(js2-outline . t))
10810 (js2-mode-show-all)
10811 (with-silent-modifications
10812 (js2-clear-face (point-min) (point-max))))
10813
10814 (defun js2-mode-reset-timer ()
10815 "Cancel any existing parse timer and schedule a new one."
10816 (if js2-mode-parse-timer
10817 (cancel-timer js2-mode-parse-timer))
10818 (setq js2-mode-parsing nil)
10819 (let ((timer (timer-create)))
10820 (setq js2-mode-parse-timer timer)
10821 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10822 (timer-set-idle-time timer js2-idle-timer-delay)
10823 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10824 (timer-activate-when-idle timer nil)))
10825
10826 (defun js2-mode-idle-reparse (buffer)
10827 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10828 it to be reparsed when the buffer is selected."
10829 (cond ((eq buffer (current-buffer))
10830 (js2-reparse))
10831 ((buffer-live-p buffer)
10832 ;; reparse when the buffer is selected again
10833 (with-current-buffer buffer
10834 (add-hook 'window-configuration-change-hook
10835 #'js2-mode-idle-reparse-inner
10836 nil t)))))
10837
10838 (defun js2-mode-idle-reparse-inner ()
10839 (remove-hook 'window-configuration-change-hook
10840 #'js2-mode-idle-reparse-inner
10841 t)
10842 (js2-reparse))
10843
10844 (defun js2-mode-edit (_beg _end _len)
10845 "Schedule a new parse after buffer is edited.
10846 Buffer edit spans from BEG to END and is of length LEN."
10847 (setq js2-mode-buffer-dirty-p t)
10848 (js2-mode-hide-overlay)
10849 (js2-mode-reset-timer))
10850
10851 (defun js2-minor-mode-edit (_beg _end _len)
10852 "Callback for buffer edits in `js2-mode'.
10853 Schedules a new parse after buffer is edited.
10854 Buffer edit spans from BEG to END and is of length LEN."
10855 (setq js2-mode-buffer-dirty-p t)
10856 (js2-mode-hide-overlay)
10857 (js2-mode-reset-timer))
10858
10859 (defun js2-reparse (&optional force)
10860 "Re-parse current buffer after user finishes some data entry.
10861 If we get any user input while parsing, including cursor motion,
10862 we discard the parse and reschedule it. If FORCE is nil, then the
10863 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10864 (let (time
10865 interrupted-p
10866 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10867 (unless js2-mode-parsing
10868 (setq js2-mode-parsing t)
10869 (unwind-protect
10870 (when (or js2-mode-buffer-dirty-p force)
10871 (js2-remove-overlays)
10872 (with-silent-modifications
10873 (setq js2-mode-buffer-dirty-p nil
10874 js2-mode-fontifications nil
10875 js2-mode-deferred-properties nil)
10876 (if js2-mode-verbose-parse-p
10877 (message "parsing..."))
10878 (setq time
10879 (js2-time
10880 (setq interrupted-p
10881 (catch 'interrupted
10882 (js2-parse)
10883 ;; if parsing is interrupted, comments and regex
10884 ;; literals stay ignored by `parse-partial-sexp'
10885 (remove-text-properties (point-min) (point-max)
10886 '(syntax-table))
10887 (js2-mode-apply-deferred-properties)
10888 (js2-mode-remove-suppressed-warnings)
10889 (js2-mode-show-warnings)
10890 (js2-mode-show-errors)
10891 (if (>= js2-highlight-level 1)
10892 (js2-highlight-jsdoc js2-mode-ast))
10893 nil))))
10894 (if interrupted-p
10895 (progn
10896 ;; unfinished parse => try again
10897 (setq js2-mode-buffer-dirty-p t)
10898 (js2-mode-reset-timer))
10899 (if js2-mode-verbose-parse-p
10900 (message "Parse time: %s" time)))))
10901 (setq js2-mode-parsing nil)
10902 (unless interrupted-p
10903 (setq js2-mode-parse-timer nil))))))
10904
10905 (defun js2-mode-show-node (event)
10906 "Debugging aid: highlight selected AST node on mouse click."
10907 (interactive "e")
10908 (mouse-set-point event)
10909 (setq deactivate-mark t)
10910 (when js2-mode-show-overlay
10911 (let ((node (js2-node-at-point))
10912 beg end)
10913 (if (null node)
10914 (message "No node found at location %s" (point))
10915 (setq beg (js2-node-abs-pos node)
10916 end (+ beg (js2-node-len node)))
10917 (if js2-mode-node-overlay
10918 (move-overlay js2-mode-node-overlay beg end)
10919 (setq js2-mode-node-overlay (make-overlay beg end))
10920 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10921 (with-silent-modifications
10922 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10923 (message "%s, parent: %s"
10924 (js2-node-short-name node)
10925 (if (js2-node-parent node)
10926 (js2-node-short-name (js2-node-parent node))
10927 "nil"))))))
10928
10929 (defun js2-mode-hide-overlay (&optional _p1 p2)
10930 "Remove the debugging overlay when the point moves.
10931 P1 and P2 are the old and new values of point, respectively."
10932 (when js2-mode-node-overlay
10933 (let ((beg (overlay-start js2-mode-node-overlay))
10934 (end (overlay-end js2-mode-node-overlay)))
10935 ;; Sometimes we're called spuriously.
10936 (unless (and p2
10937 (>= p2 beg)
10938 (<= p2 end))
10939 (with-silent-modifications
10940 (remove-text-properties beg end '(point-left nil)))
10941 (delete-overlay js2-mode-node-overlay)
10942 (setq js2-mode-node-overlay nil)))))
10943
10944 (defun js2-mode-reset ()
10945 "Debugging helper: reset everything."
10946 (interactive)
10947 (js2-mode-exit)
10948 (js2-mode))
10949
10950 (defun js2-mode-show-warn-or-err (e face)
10951 "Highlight a warning or error E with FACE.
10952 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10953 The last element is optional. When present, use instead of FACE."
10954 (let* ((key (first e))
10955 (beg (second e))
10956 (end (+ beg (third e)))
10957 ;; Don't inadvertently go out of bounds.
10958 (beg (max (point-min) (min beg (point-max))))
10959 (end (max (point-min) (min end (point-max))))
10960 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10961 (ovl (make-overlay beg end)))
10962 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10963 (overlay-put ovl 'js2-error t)
10964 (put-text-property beg end 'help-echo (js2-get-msg key))
10965 (put-text-property beg end 'point-entered #'js2-echo-error)))
10966
10967 (defun js2-remove-overlays ()
10968 "Remove overlays from buffer that have a `js2-error' property."
10969 (let ((beg (point-min))
10970 (end (point-max)))
10971 (save-excursion
10972 (dolist (o (overlays-in beg end))
10973 (when (overlay-get o 'js2-error)
10974 (delete-overlay o))))))
10975
10976 (defun js2-error-at-point (&optional pos)
10977 "Return non-nil if there's an error overlay at POS.
10978 Defaults to point."
10979 (loop with pos = (or pos (point))
10980 for o in (overlays-at pos)
10981 thereis (overlay-get o 'js2-error)))
10982
10983 (defun js2-mode-apply-deferred-properties ()
10984 "Apply fontifications and other text properties recorded during parsing."
10985 (when (plusp js2-highlight-level)
10986 ;; We defer clearing faces as long as possible to eliminate flashing.
10987 (js2-clear-face (point-min) (point-max))
10988 ;; Have to reverse the recorded fontifications list so that errors
10989 ;; and warnings overwrite the normal fontifications.
10990 (dolist (f (nreverse js2-mode-fontifications))
10991 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10992 (setq js2-mode-fontifications nil))
10993 (dolist (p js2-mode-deferred-properties)
10994 (apply #'put-text-property p))
10995 (setq js2-mode-deferred-properties nil))
10996
10997 (defun js2-mode-show-errors ()
10998 "Highlight syntax errors."
10999 (when js2-mode-show-parse-errors
11000 (dolist (e (js2-ast-root-errors js2-mode-ast))
11001 (js2-mode-show-warn-or-err e 'js2-error))))
11002
11003 (defun js2-mode-remove-suppressed-warnings ()
11004 "Take suppressed warnings out of the AST warnings list.
11005 This ensures that the counts and `next-error' are correct."
11006 (setf (js2-ast-root-warnings js2-mode-ast)
11007 (js2-delete-if
11008 (lambda (e)
11009 (let ((key (caar e)))
11010 (or
11011 (and (not js2-strict-trailing-comma-warning)
11012 (string-match "trailing\\.comma" key))
11013 (and (not js2-strict-cond-assign-warning)
11014 (string= key "msg.equal.as.assign"))
11015 (and js2-missing-semi-one-line-override
11016 (string= key "msg.missing.semi")
11017 (let* ((beg (second e))
11018 (node (js2-node-at-point beg))
11019 (fn (js2-mode-find-parent-fn node))
11020 (body (and fn (js2-function-node-body fn)))
11021 (lc (and body (js2-node-abs-pos body)))
11022 (rc (and lc (+ lc (js2-node-len body)))))
11023 (and fn
11024 (or (null body)
11025 (save-excursion
11026 (goto-char beg)
11027 (and (js2-same-line lc)
11028 (js2-same-line rc))))))))))
11029 (js2-ast-root-warnings js2-mode-ast))))
11030
11031 (defun js2-mode-show-warnings ()
11032 "Highlight strict-mode warnings."
11033 (when js2-mode-show-strict-warnings
11034 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11035 (js2-mode-show-warn-or-err e 'js2-warning))))
11036
11037 (defun js2-echo-error (_old-point new-point)
11038 "Called by point-motion hooks."
11039 (let ((msg (get-text-property new-point 'help-echo)))
11040 (when (and (stringp msg)
11041 (not (active-minibuffer-window))
11042 (not (current-message)))
11043 (message msg))))
11044
11045 (defalias 'js2-echo-help #'js2-echo-error)
11046
11047 (defun js2-line-break (&optional _soft)
11048 "Break line at point and indent, continuing comment if within one.
11049 If inside a string, and `js2-concat-multiline-strings' is not
11050 nil, turn it into concatenation."
11051 (interactive)
11052 (let ((parse-status (syntax-ppss)))
11053 (cond
11054 ;; Check if we're inside a string.
11055 ((nth 3 parse-status)
11056 (if js2-concat-multiline-strings
11057 (js2-mode-split-string parse-status)
11058 (insert "\n")))
11059 ;; Check if inside a block comment.
11060 ((nth 4 parse-status)
11061 (js2-mode-extend-comment (nth 8 parse-status)))
11062 (t
11063 (newline-and-indent)))))
11064
11065 (defun js2-mode-split-string (parse-status)
11066 "Turn a newline in mid-string into a string concatenation.
11067 PARSE-STATUS is as documented in `parse-partial-sexp'."
11068 (let* ((quote-char (nth 3 parse-status))
11069 (at-eol (eq js2-concat-multiline-strings 'eol)))
11070 (insert quote-char)
11071 (insert (if at-eol " +\n" "\n"))
11072 (unless at-eol
11073 (insert "+ "))
11074 (js2-indent-line)
11075 (insert quote-char)
11076 (when (eolp)
11077 (insert quote-char)
11078 (backward-char 1))))
11079
11080 (defun js2-mode-extend-comment (start-pos)
11081 "Indent the line and, when inside a comment block, add comment prefix."
11082 (let (star single col first-line needs-close)
11083 (save-excursion
11084 (back-to-indentation)
11085 (when (< (point) start-pos)
11086 (goto-char start-pos))
11087 (cond
11088 ((looking-at "\\*[^/]")
11089 (setq star t
11090 col (current-column)))
11091 ((looking-at "/\\*")
11092 (setq star t
11093 first-line t
11094 col (1+ (current-column))))
11095 ((looking-at "//")
11096 (setq single t
11097 col (current-column)))))
11098 ;; Heuristic for whether we need to close the comment:
11099 ;; if we've got a parse error here, assume it's an unterminated
11100 ;; comment.
11101 (setq needs-close
11102 (or
11103 (eq (get-text-property (1- (point)) 'point-entered)
11104 'js2-echo-error)
11105 ;; The heuristic above doesn't work well when we're
11106 ;; creating a comment and there's another one downstream,
11107 ;; as our parser thinks this one ends at the end of the
11108 ;; next one. (You can have a /* inside a js block comment.)
11109 ;; So just close it if the next non-ws char isn't a *.
11110 (and first-line
11111 (eolp)
11112 (save-excursion
11113 (skip-chars-forward " \t\r\n")
11114 (not (eq (char-after) ?*))))))
11115 (delete-horizontal-space)
11116 (insert "\n")
11117 (cond
11118 (star
11119 (indent-to col)
11120 (insert "* ")
11121 (if (and first-line needs-close)
11122 (save-excursion
11123 (insert "\n")
11124 (indent-to col)
11125 (insert "*/"))))
11126 ((and single
11127 (save-excursion
11128 (and (zerop (forward-line 1))
11129 (looking-at "\\s-*//"))))
11130 (indent-to col)
11131 (insert "// ")))
11132 ;; Don't need to extend the comment after all.
11133 (js2-indent-line)))
11134
11135 (defun js2-beginning-of-line ()
11136 "Toggle point between bol and first non-whitespace char in line.
11137 Also moves past comment delimiters when inside comments."
11138 (interactive)
11139 (let (node)
11140 (cond
11141 ((bolp)
11142 (back-to-indentation))
11143 ((looking-at "//")
11144 (skip-chars-forward "/ \t"))
11145 ((and (eq (char-after) ?*)
11146 (setq node (js2-comment-at-point))
11147 (memq (js2-comment-node-format node) '(jsdoc block))
11148 (save-excursion
11149 (skip-chars-backward " \t")
11150 (bolp)))
11151 (skip-chars-forward "\* \t"))
11152 (t
11153 (goto-char (point-at-bol))))))
11154
11155 (defun js2-end-of-line ()
11156 "Toggle point between eol and last non-whitespace char in line."
11157 (interactive)
11158 (if (eolp)
11159 (skip-chars-backward " \t")
11160 (goto-char (point-at-eol))))
11161
11162 (defun js2-mode-wait-for-parse (callback)
11163 "Invoke CALLBACK when parsing is finished.
11164 If parsing is already finished, calls CALLBACK immediately."
11165 (if (not js2-mode-buffer-dirty-p)
11166 (funcall callback)
11167 (push callback js2-mode-pending-parse-callbacks)
11168 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11169
11170 (defun js2-mode-parse-finished ()
11171 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11172 ;; We can't let errors propagate up, since it prevents the
11173 ;; `js2-parse' method from completing normally and returning
11174 ;; the ast, which makes things mysteriously not work right.
11175 (unwind-protect
11176 (dolist (cb js2-mode-pending-parse-callbacks)
11177 (condition-case err
11178 (funcall cb)
11179 (error (message "%s" err))))
11180 (setq js2-mode-pending-parse-callbacks nil)))
11181
11182 (defun js2-mode-flag-region (from to flag)
11183 "Hide or show text from FROM to TO, according to FLAG.
11184 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11185 Returns the created overlay if FLAG is non-nil."
11186 (remove-overlays from to 'invisible 'js2-outline)
11187 (when flag
11188 (let ((o (make-overlay from to)))
11189 (overlay-put o 'invisible 'js2-outline)
11190 (overlay-put o 'isearch-open-invisible
11191 'js2-isearch-open-invisible)
11192 o)))
11193
11194 ;; Function to be set as an outline-isearch-open-invisible' property
11195 ;; to the overlay that makes the outline invisible (see
11196 ;; `js2-mode-flag-region').
11197 (defun js2-isearch-open-invisible (_overlay)
11198 ;; We rely on the fact that isearch places point on the matched text.
11199 (js2-mode-show-element))
11200
11201 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11202 "Return cons cell of bounds of folding overlay at POS.
11203 Returns nil if not found."
11204 (let ((overlays (overlays-at (or pos (point))))
11205 o)
11206 (while (and overlays
11207 (not o))
11208 (if (overlay-get (car overlays) 'invisible)
11209 (setq o (car overlays))
11210 (setq overlays (cdr overlays))))
11211 (if o
11212 (cons (overlay-start o) (overlay-end o)))))
11213
11214 (defun js2-mode-function-at-point (&optional pos)
11215 "Return the innermost function node enclosing current point.
11216 Returns nil if point is not in a function."
11217 (let ((node (js2-node-at-point pos)))
11218 (while (and node (not (js2-function-node-p node)))
11219 (setq node (js2-node-parent node)))
11220 (if (js2-function-node-p node)
11221 node)))
11222
11223 (defun js2-mode-toggle-element ()
11224 "Hide or show the foldable element at the point."
11225 (interactive)
11226 (let (comment fn pos)
11227 (save-excursion
11228 (cond
11229 ;; /* ... */ comment?
11230 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11231 (if (js2-mode-invisible-overlay-bounds
11232 (setq pos (+ 3 (js2-node-abs-pos comment))))
11233 (progn
11234 (goto-char pos)
11235 (js2-mode-show-element))
11236 (js2-mode-hide-element)))
11237 ;; //-comment?
11238 ((save-excursion
11239 (back-to-indentation)
11240 (looking-at js2-mode-//-comment-re))
11241 (js2-mode-toggle-//-comment))
11242 ;; function?
11243 ((setq fn (js2-mode-function-at-point))
11244 (setq pos (and (js2-function-node-body fn)
11245 (js2-node-abs-pos (js2-function-node-body fn))))
11246 (goto-char (1+ pos))
11247 (if (js2-mode-invisible-overlay-bounds)
11248 (js2-mode-show-element)
11249 (js2-mode-hide-element)))
11250 (t
11251 (message "Nothing at point to hide or show"))))))
11252
11253 (defun js2-mode-hide-element ()
11254 "Fold/hide contents of a block, showing ellipses.
11255 Show the hidden text with \\[js2-mode-show-element]."
11256 (interactive)
11257 (if js2-mode-buffer-dirty-p
11258 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11259 (let (node body beg end)
11260 (cond
11261 ((js2-mode-invisible-overlay-bounds)
11262 (message "already hidden"))
11263 (t
11264 (setq node (js2-node-at-point))
11265 (cond
11266 ((js2-block-comment-p node)
11267 (js2-mode-hide-comment node))
11268 (t
11269 (while (and node (not (js2-function-node-p node)))
11270 (setq node (js2-node-parent node)))
11271 (if (and node
11272 (setq body (js2-function-node-body node)))
11273 (progn
11274 (setq beg (js2-node-abs-pos body)
11275 end (+ beg (js2-node-len body)))
11276 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11277 (message "No collapsable element found at point"))))))))
11278
11279 (defun js2-mode-show-element ()
11280 "Show the hidden element at current point."
11281 (interactive)
11282 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11283 (if bounds
11284 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11285 (message "Nothing to un-hide"))))
11286
11287 (defun js2-mode-show-all ()
11288 "Show all of the text in the buffer."
11289 (interactive)
11290 (js2-mode-flag-region (point-min) (point-max) nil))
11291
11292 (defun js2-mode-toggle-hide-functions ()
11293 (interactive)
11294 (if js2-mode-functions-hidden
11295 (js2-mode-show-functions)
11296 (js2-mode-hide-functions)))
11297
11298 (defun js2-mode-hide-functions ()
11299 "Hides all non-nested function bodies in the buffer.
11300 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11301 to open an individual entry."
11302 (interactive)
11303 (if js2-mode-buffer-dirty-p
11304 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11305 (if (null js2-mode-ast)
11306 (message "Oops - parsing failed")
11307 (setq js2-mode-functions-hidden t)
11308 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11309
11310 (defun js2-mode-function-hider (n endp)
11311 (when (not endp)
11312 (let ((tt (js2-node-type n))
11313 body beg end)
11314 (cond
11315 ((and (= tt js2-FUNCTION)
11316 (setq body (js2-function-node-body n)))
11317 (setq beg (js2-node-abs-pos body)
11318 end (+ beg (js2-node-len body)))
11319 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11320 nil) ; don't process children of function
11321 (t
11322 t))))) ; keep processing other AST nodes
11323
11324 (defun js2-mode-show-functions ()
11325 "Un-hide any folded function bodies in the buffer."
11326 (interactive)
11327 (setq js2-mode-functions-hidden nil)
11328 (save-excursion
11329 (goto-char (point-min))
11330 (while (/= (goto-char (next-overlay-change (point)))
11331 (point-max))
11332 (dolist (o (overlays-at (point)))
11333 (when (and (overlay-get o 'invisible)
11334 (not (overlay-get o 'comment)))
11335 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11336
11337 (defun js2-mode-hide-comment (n)
11338 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11339 3 ; /**
11340 2)) ; /*
11341 (beg (+ (js2-node-abs-pos n) head))
11342 (end (- (+ beg (js2-node-len n)) head 2))
11343 (o (js2-mode-flag-region beg end 'hide)))
11344 (overlay-put o 'comment t)))
11345
11346 (defun js2-mode-toggle-hide-comments ()
11347 "Folds all block comments in the buffer.
11348 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11349 to open an individual entry."
11350 (interactive)
11351 (if js2-mode-comments-hidden
11352 (js2-mode-show-comments)
11353 (js2-mode-hide-comments)))
11354
11355 (defun js2-mode-hide-comments ()
11356 (interactive)
11357 (if js2-mode-buffer-dirty-p
11358 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11359 (if (null js2-mode-ast)
11360 (message "Oops - parsing failed")
11361 (setq js2-mode-comments-hidden t)
11362 (dolist (n (js2-ast-root-comments js2-mode-ast))
11363 (when (js2-block-comment-p n)
11364 (js2-mode-hide-comment n)))
11365 (js2-mode-hide-//-comments)))
11366
11367 (defun js2-mode-extend-//-comment (direction)
11368 "Find start or end of a block of similar //-comment lines.
11369 DIRECTION is -1 to look back, 1 to look forward.
11370 INDENT is the indentation level to match.
11371 Returns the end-of-line position of the furthest adjacent
11372 //-comment line with the same indentation as the current line.
11373 If there is no such matching line, returns current end of line."
11374 (let ((pos (point-at-eol))
11375 (indent (current-indentation)))
11376 (save-excursion
11377 (while (and (zerop (forward-line direction))
11378 (looking-at js2-mode-//-comment-re)
11379 (eq indent (length (match-string 1))))
11380 (setq pos (point-at-eol)))
11381 pos)))
11382
11383 (defun js2-mode-hide-//-comments ()
11384 "Fold adjacent 1-line comments, showing only snippet of first one."
11385 (let (beg end)
11386 (save-excursion
11387 (goto-char (point-min))
11388 (while (re-search-forward js2-mode-//-comment-re nil t)
11389 (setq beg (point)
11390 end (js2-mode-extend-//-comment 1))
11391 (unless (eq beg end)
11392 (overlay-put (js2-mode-flag-region beg end 'hide)
11393 'comment t))
11394 (goto-char end)
11395 (forward-char 1)))))
11396
11397 (defun js2-mode-toggle-//-comment ()
11398 "Fold or un-fold any multi-line //-comment at point.
11399 Caller should have determined that this line starts with a //-comment."
11400 (let* ((beg (point-at-eol))
11401 (end beg))
11402 (save-excursion
11403 (goto-char end)
11404 (if (js2-mode-invisible-overlay-bounds)
11405 (js2-mode-show-element)
11406 ;; else hide the comment
11407 (setq beg (js2-mode-extend-//-comment -1)
11408 end (js2-mode-extend-//-comment 1))
11409 (unless (eq beg end)
11410 (overlay-put (js2-mode-flag-region beg end 'hide)
11411 'comment t))))))
11412
11413 (defun js2-mode-show-comments ()
11414 "Un-hide any hidden comments, leaving other hidden elements alone."
11415 (interactive)
11416 (setq js2-mode-comments-hidden nil)
11417 (save-excursion
11418 (goto-char (point-min))
11419 (while (/= (goto-char (next-overlay-change (point)))
11420 (point-max))
11421 (dolist (o (overlays-at (point)))
11422 (when (overlay-get o 'comment)
11423 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11424
11425 (defun js2-mode-display-warnings-and-errors ()
11426 "Turn on display of warnings and errors."
11427 (interactive)
11428 (setq js2-mode-show-parse-errors t
11429 js2-mode-show-strict-warnings t)
11430 (js2-reparse 'force))
11431
11432 (defun js2-mode-hide-warnings-and-errors ()
11433 "Turn off display of warnings and errors."
11434 (interactive)
11435 (setq js2-mode-show-parse-errors nil
11436 js2-mode-show-strict-warnings nil)
11437 (js2-reparse 'force))
11438
11439 (defun js2-mode-toggle-warnings-and-errors ()
11440 "Toggle the display of warnings and errors.
11441 Some users don't like having warnings/errors reported while they type."
11442 (interactive)
11443 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11444 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11445 (if (called-interactively-p 'any)
11446 (message "warnings and errors %s"
11447 (if js2-mode-show-parse-errors
11448 "enabled"
11449 "disabled")))
11450 (js2-reparse 'force))
11451
11452 (defun js2-mode-customize ()
11453 (interactive)
11454 (customize-group 'js2-mode))
11455
11456 (defun js2-mode-forward-sexp (&optional arg)
11457 "Move forward across one statement or balanced expression.
11458 With ARG, do it that many times. Negative arg -N means
11459 move backward across N balanced expressions."
11460 (interactive "p")
11461 (setq arg (or arg 1))
11462 (save-restriction
11463 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11464 (js2-reparse)
11465 (let (forward-sexp-function
11466 node (start (point)) pos lp rp child)
11467 (cond
11468 ;; backward-sexp
11469 ;; could probably make this better for some cases:
11470 ;; - if in statement block (e.g. function body), go to parent
11471 ;; - infix exprs like (foo in bar) - maybe go to beginning
11472 ;; of infix expr if in the right-side expression?
11473 ((and arg (minusp arg))
11474 (dotimes (_ (- arg))
11475 (js2-backward-sws)
11476 (forward-char -1) ; Enter the node we backed up to.
11477 (when (setq node (js2-node-at-point (point) t))
11478 (setq pos (js2-node-abs-pos node))
11479 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11480 (setq lp (car parens)
11481 rp (cdr parens)))
11482 (when (and lp (> start lp))
11483 (if (and rp (<= start rp))
11484 ;; Between parens, check if there's a child node we can jump.
11485 (when (setq child (js2-node-closest-child node (point) lp t))
11486 (setq pos (js2-node-abs-pos child)))
11487 ;; Before both parens.
11488 (setq pos lp)))
11489 (let ((state (parse-partial-sexp start pos)))
11490 (goto-char (if (not (zerop (car state)))
11491 ;; Stumble at the unbalanced paren if < 0, or
11492 ;; jump a bit further if > 0.
11493 (scan-sexps start -1)
11494 pos))))
11495 (unless pos (goto-char (point-min)))))
11496 (t
11497 ;; forward-sexp
11498 (dotimes (_ arg)
11499 (js2-forward-sws)
11500 (when (setq node (js2-node-at-point (point) t))
11501 (setq pos (js2-node-abs-pos node))
11502 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11503 (setq lp (car parens)
11504 rp (cdr parens)))
11505 (or
11506 (when (and rp (<= start rp))
11507 (if (> start lp)
11508 (when (setq child (js2-node-closest-child node (point) rp))
11509 (setq pos (js2-node-abs-end child)))
11510 (setq pos (1+ rp))))
11511 ;; No parens or child nodes, looks for the end of the curren node.
11512 (incf pos (js2-node-len
11513 (if (js2-expr-stmt-node-p (js2-node-parent node))
11514 ;; Stop after the semicolon.
11515 (js2-node-parent node)
11516 node))))
11517 (let ((state (save-excursion (parse-partial-sexp start pos))))
11518 (goto-char (if (not (zerop (car state)))
11519 (scan-sexps start 1)
11520 pos))))
11521 (unless pos (goto-char (point-max)))))))))
11522
11523 (defun js2-mode-forward-sexp-parens (node abs-pos)
11524 "Return a cons cell with positions of main parens in NODE."
11525 (cond
11526 ((or (js2-array-node-p node)
11527 (js2-object-node-p node)
11528 (js2-comp-node-p node)
11529 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11530 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11531 ((js2-paren-expr-node-p node)
11532 (let ((lp (js2-node-lp node))
11533 (rp (js2-node-rp node)))
11534 (cons (when lp (+ abs-pos lp))
11535 (when rp (+ abs-pos rp)))))))
11536
11537 (defun js2-node-closest-child (parent point limit &optional before)
11538 (let* ((parent-pos (js2-node-abs-pos parent))
11539 (rpoint (- point parent-pos))
11540 (rlimit (- limit parent-pos))
11541 (min (min rpoint rlimit))
11542 (max (max rpoint rlimit))
11543 found)
11544 (catch 'done
11545 (js2-visit-ast
11546 parent
11547 (lambda (node _end-p)
11548 (if (eq node parent)
11549 t
11550 (let ((pos (js2-node-pos node)) ;; Both relative values.
11551 (end (+ (js2-node-pos node) (js2-node-len node))))
11552 (when (and (>= pos min) (<= end max)
11553 (if before (< pos rpoint) (> end rpoint)))
11554 (setq found node))
11555 (when (> end rpoint)
11556 (throw 'done nil)))
11557 nil))))
11558 found))
11559
11560 (defun js2-errors ()
11561 "Return a list of errors found."
11562 (and js2-mode-ast
11563 (js2-ast-root-errors js2-mode-ast)))
11564
11565 (defun js2-warnings ()
11566 "Return a list of warnings found."
11567 (and js2-mode-ast
11568 (js2-ast-root-warnings js2-mode-ast)))
11569
11570 (defun js2-have-errors-p ()
11571 "Return non-nil if any parse errors or warnings were found."
11572 (or (js2-errors) (js2-warnings)))
11573
11574 (defun js2-errors-and-warnings ()
11575 "Return a copy of the concatenated errors and warnings lists.
11576 They are appended: first the errors, then the warnings.
11577 Entries are of the form (MSG BEG END)."
11578 (when js2-mode-ast
11579 (append (js2-ast-root-errors js2-mode-ast)
11580 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11581
11582 (defun js2-next-error (&optional arg reset)
11583 "Move to next parse error.
11584 Typically invoked via \\[next-error].
11585 ARG is the number of errors, forward or backward, to move.
11586 RESET means start over from the beginning."
11587 (interactive "p")
11588 (if (not (or (js2-errors) (js2-warnings)))
11589 (message "No errors")
11590 (when reset
11591 (goto-char (point-min)))
11592 (let* ((errs (js2-errors-and-warnings))
11593 (continue t)
11594 (start (point))
11595 (count (or arg 1))
11596 (backward (minusp count))
11597 (sorter (if backward '> '<))
11598 (stopper (if backward '< '>))
11599 (count (abs count))
11600 all-errs err)
11601 ;; Sort by start position.
11602 (setq errs (sort errs (lambda (e1 e2)
11603 (funcall sorter (second e1) (second e2))))
11604 all-errs errs)
11605 ;; Find nth error with pos > start.
11606 (while (and errs continue)
11607 (when (funcall stopper (cadar errs) start)
11608 (setq err (car errs))
11609 (if (zerop (decf count))
11610 (setq continue nil)))
11611 (setq errs (cdr errs)))
11612 ;; Clear for `js2-echo-error'.
11613 (message nil)
11614 (if err
11615 (goto-char (second err))
11616 ;; Wrap around to first error.
11617 (goto-char (second (car all-errs)))
11618 ;; If we were already on it, echo msg again.
11619 (if (= (point) start)
11620 (js2-echo-error (point) (point)))))))
11621
11622 (defun js2-down-mouse-3 ()
11623 "Make right-click move the point to the click location.
11624 This makes right-click context menu operations a bit more intuitive.
11625 The point will not move if the region is active, however, to avoid
11626 destroying the region selection."
11627 (interactive)
11628 (when (and js2-move-point-on-right-click
11629 (not mark-active))
11630 (let ((e last-input-event))
11631 (ignore-errors
11632 (goto-char (cadadr e))))))
11633
11634 (defun js2-mode-create-imenu-index ()
11635 "Return an alist for `imenu--index-alist'."
11636 ;; This is built up in `js2-parse-record-imenu' during parsing.
11637 (when js2-mode-ast
11638 ;; if we have an ast but no recorder, they're requesting a rescan
11639 (unless js2-imenu-recorder
11640 (js2-reparse 'force))
11641 (prog1
11642 (js2-build-imenu-index)
11643 (setq js2-imenu-recorder nil
11644 js2-imenu-function-map nil))))
11645
11646 (defun js2-mode-find-tag ()
11647 "Replacement for `find-tag-default'.
11648 `find-tag-default' returns a ridiculous answer inside comments."
11649 (let (beg end)
11650 (js2-with-underscore-as-word-syntax
11651 (save-excursion
11652 (if (and (not (looking-at "[[:alnum:]_$]"))
11653 (looking-back "[[:alnum:]_$]"))
11654 (setq beg (progn (forward-word -1) (point))
11655 end (progn (forward-word 1) (point)))
11656 (setq beg (progn (forward-word 1) (point))
11657 end (progn (forward-word -1) (point))))
11658 (replace-regexp-in-string
11659 "[\"']" ""
11660 (buffer-substring-no-properties beg end))))))
11661
11662 (defun js2-mode-forward-sibling ()
11663 "Move to the end of the sibling following point in parent.
11664 Returns non-nil if successful, or nil if there was no following sibling."
11665 (let* ((node (js2-node-at-point))
11666 (parent (js2-mode-find-enclosing-fn node))
11667 sib)
11668 (when (setq sib (js2-node-find-child-after (point) parent))
11669 (goto-char (+ (js2-node-abs-pos sib)
11670 (js2-node-len sib))))))
11671
11672 (defun js2-mode-backward-sibling ()
11673 "Move to the beginning of the sibling node preceding point in parent.
11674 Parent is defined as the enclosing script or function."
11675 (let* ((node (js2-node-at-point))
11676 (parent (js2-mode-find-enclosing-fn node))
11677 sib)
11678 (when (setq sib (js2-node-find-child-before (point) parent))
11679 (goto-char (js2-node-abs-pos sib)))))
11680
11681 (defun js2-beginning-of-defun (&optional arg)
11682 "Go to line on which current function starts, and return t on success.
11683 If we're not in a function or already at the beginning of one, go
11684 to beginning of previous script-level element.
11685 With ARG N, do that N times. If N is negative, move forward."
11686 (setq arg (or arg 1))
11687 (if (plusp arg)
11688 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11689 (when (cond
11690 ((js2-function-node-p parent)
11691 (goto-char (js2-node-abs-pos parent)))
11692 (t
11693 (js2-mode-backward-sibling)))
11694 (if (> arg 1)
11695 (js2-beginning-of-defun (1- arg))
11696 t)))
11697 (when (js2-end-of-defun)
11698 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11699
11700 (defun js2-end-of-defun ()
11701 "Go to the char after the last position of the current function
11702 or script-level element."
11703 (let* ((node (js2-node-at-point))
11704 (parent (or (and (js2-function-node-p node) node)
11705 (js2-node-parent-script-or-fn node)))
11706 script)
11707 (unless (js2-function-node-p parent)
11708 ;; Use current script-level node, or, if none, the next one.
11709 (setq script (or parent node)
11710 parent (js2-node-find-child-before (point) script))
11711 (when (or (null parent)
11712 (>= (point) (+ (js2-node-abs-pos parent)
11713 (js2-node-len parent))))
11714 (setq parent (js2-node-find-child-after (point) script))))
11715 (when parent
11716 (goto-char (+ (js2-node-abs-pos parent)
11717 (js2-node-len parent))))))
11718
11719 (defun js2-mark-defun (&optional allow-extend)
11720 "Put mark at end of this function, point at beginning.
11721 The function marked is the one that contains point.
11722
11723 Interactively, if this command is repeated,
11724 or (in Transient Mark mode) if the mark is active,
11725 it marks the next defun after the ones already marked."
11726 (interactive "p")
11727 (let (extended)
11728 (when (and allow-extend
11729 (or (and (eq last-command this-command) (mark t))
11730 (and transient-mark-mode mark-active)))
11731 (let ((sib (save-excursion
11732 (goto-char (mark))
11733 (if (js2-mode-forward-sibling)
11734 (point)))))
11735 (if sib
11736 (progn
11737 (set-mark sib)
11738 (setq extended t))
11739 ;; no more siblings - try extending to enclosing node
11740 (goto-char (mark t)))))
11741 (when (not extended)
11742 (let ((node (js2-node-at-point (point) t)) ; skip comments
11743 ast fn stmt parent beg end)
11744 (when (js2-ast-root-p node)
11745 (setq ast node
11746 node (or (js2-node-find-child-after (point) node)
11747 (js2-node-find-child-before (point) node))))
11748 ;; only mark whole buffer if we can't find any children
11749 (if (null node)
11750 (setq node ast))
11751 (if (js2-function-node-p node)
11752 (setq parent node)
11753 (setq fn (js2-mode-find-enclosing-fn node)
11754 stmt (if (or (null fn)
11755 (js2-ast-root-p fn))
11756 (js2-mode-find-first-stmt node))
11757 parent (or stmt fn)))
11758 (setq beg (js2-node-abs-pos parent)
11759 end (+ beg (js2-node-len parent)))
11760 (push-mark beg)
11761 (goto-char end)
11762 (exchange-point-and-mark)))))
11763
11764 (defun js2-narrow-to-defun ()
11765 "Narrow to the function enclosing point."
11766 (interactive)
11767 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11768 (fn (if (js2-script-node-p node)
11769 node
11770 (js2-mode-find-enclosing-fn node)))
11771 (beg (js2-node-abs-pos fn)))
11772 (unless (js2-ast-root-p fn)
11773 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11774
11775 (provide 'js2-mode)
11776
11777 ;;; js2-mode.el ends here