]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Support ES6 class statements/expressions.
[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: 20140114
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)
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-ENUM 161) ; for "enum" reserved word
662 (defvar js2-TRIPLEDOT 162) ; for rest parameter
663 (defvar js2-ARROW 163) ; function arrow (=>)
664 (defvar js2-CLASS 164)
665 (defvar js2-EXTENDS 165)
666
667 (defconst js2-num-tokens (1+ js2-EXTENDS))
668
669 (defconst js2-debug-print-trees nil)
670
671 ;; Rhino accepts any string or stream as input. Emacs character
672 ;; processing works best in buffers, so we'll assume the input is a
673 ;; buffer. JavaScript strings can be copied into temp buffers before
674 ;; scanning them.
675
676 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
677 ;; They're the Emacs equivalent of instance variables, more or less.
678
679 (js2-deflocal js2-ts-dirty-line nil
680 "Token stream buffer-local variable.
681 Indicates stuff other than whitespace since start of line.")
682
683 (js2-deflocal js2-ts-hit-eof nil
684 "Token stream buffer-local variable.")
685
686 ;; FIXME: Unused.
687 (js2-deflocal js2-ts-line-start 0
688 "Token stream buffer-local variable.")
689
690 (js2-deflocal js2-ts-lineno 1
691 "Token stream buffer-local variable.")
692
693 ;; FIXME: Unused.
694 (js2-deflocal js2-ts-line-end-char -1
695 "Token stream buffer-local variable.")
696
697 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
698 "Token stream buffer-local variable.
699 Current scan position.")
700
701 ;; FIXME: Unused.
702 (js2-deflocal js2-ts-is-xml-attribute nil
703 "Token stream buffer-local variable.")
704
705 (js2-deflocal js2-ts-xml-is-tag-content nil
706 "Token stream buffer-local variable.")
707
708 (js2-deflocal js2-ts-xml-open-tags-count 0
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-string-buffer nil
712 "Token stream buffer-local variable.
713 List of chars built up while scanning various tokens.")
714
715 (defstruct (js2-token
716 (:constructor nil)
717 (:constructor make-js2-token (beg)))
718 "Value returned from the token stream."
719 (type js2-EOF)
720 (beg 1)
721 (end -1)
722 (string "")
723 number
724 regexp-flags
725 comment-type
726 follows-eol-p)
727
728 (defstruct (js2-ts-state
729 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
730 (cursor js2-ts-cursor)
731 (tokens (copy-sequence js2-ti-tokens))
732 (tokens-cursor js2-ti-tokens-cursor)
733 (lookahead js2-ti-lookahead))))
734 lineno
735 cursor
736 tokens
737 tokens-cursor
738 lookahead)
739
740 ;;; Parser variables
741
742 (js2-deflocal js2-parsed-errors nil
743 "List of errors produced during scanning/parsing.")
744
745 (js2-deflocal js2-parsed-warnings nil
746 "List of warnings produced during scanning/parsing.")
747
748 (js2-deflocal js2-recover-from-parse-errors t
749 "Non-nil to continue parsing after a syntax error.
750
751 In recovery mode, the AST will be built in full, and any error
752 nodes will be flagged with appropriate error information. If
753 this flag is nil, a syntax error will result in an error being
754 signaled.
755
756 The variable is automatically buffer-local, because different
757 modes that use the parser will need different settings.")
758
759 (js2-deflocal js2-parse-hook nil
760 "List of callbacks for receiving parsing progress.")
761
762 (defvar js2-parse-finished-hook nil
763 "List of callbacks to notify when parsing finishes.
764 Not called if parsing was interrupted.")
765
766 (js2-deflocal js2-is-eval-code nil
767 "True if we're evaluating code in a string.
768 If non-nil, the tokenizer will record the token text, and the AST nodes
769 will record their source text. Off by default for IDE modes, since the
770 text is available in the buffer.")
771
772 (defvar js2-parse-ide-mode t
773 "Non-nil if the parser is being used for `js2-mode'.
774 If non-nil, the parser will set text properties for fontification
775 and the syntax table. The value should be nil when using the
776 parser as a frontend to an interpreter or byte compiler.")
777
778 ;;; Parser instance variables (buffer-local vars for js2-parse)
779
780 (defconst js2-ti-after-eol (lsh 1 16)
781 "Flag: first token of the source line.")
782
783 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
784
785 (js2-deflocal js2-compiler-generate-debug-info t)
786 (js2-deflocal js2-compiler-use-dynamic-scope nil)
787 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
788 (js2-deflocal js2-compiler-xml-available t)
789 (js2-deflocal js2-compiler-optimization-level 0)
790 (js2-deflocal js2-compiler-generating-source t)
791 (js2-deflocal js2-compiler-strict-mode nil)
792 (js2-deflocal js2-compiler-report-warning-as-error nil)
793 (js2-deflocal js2-compiler-generate-observer-count nil)
794 (js2-deflocal js2-compiler-activation-names nil)
795
796 ;; SKIP: sourceURI
797
798 ;; There's a compileFunction method in Context.java - may need it.
799 (js2-deflocal js2-called-by-compile-function nil
800 "True if `js2-parse' was called by `js2-compile-function'.
801 Will only be used when we finish implementing the interpreter.")
802
803 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
804
805 ;; SKIP: node factory - we're going to just call functions directly,
806 ;; and eventually go to a unified AST format.
807
808 (js2-deflocal js2-nesting-of-function 0)
809
810 (js2-deflocal js2-recorded-identifiers nil
811 "Tracks identifiers found during parsing.")
812
813 (js2-deflocal js2-is-in-destructuring nil
814 "True while parsing destructuring expression.")
815
816 (defcustom js2-global-externs nil
817 "A list of any extern names you'd like to consider always declared.
818 This list is global and is used by all `js2-mode' files.
819 You can create buffer-local externs list using `js2-additional-externs'.
820
821 There is also a buffer-local variable `js2-default-externs',
822 which is initialized by default to include the Ecma-262 externs
823 and the standard browser externs. The three lists are all
824 checked during highlighting."
825 :type 'list
826 :group 'js2-mode)
827
828 (js2-deflocal js2-default-externs nil
829 "Default external declarations.
830
831 These are currently only used for highlighting undeclared variables,
832 which only worries about top-level (unqualified) references.
833 As js2-mode's processing improves, we will flesh out this list.
834
835 The initial value is set to `js2-ecma-262-externs', unless some
836 of the `js2-include-?-externs' variables are set to t, in which
837 case the browser, Rhino and/or Node.js externs are also included.
838
839 See `js2-additional-externs' for more information.")
840
841 (defcustom js2-include-browser-externs t
842 "Non-nil to include browser externs in the master externs list.
843 If you work on JavaScript files that are not intended for browsers,
844 such as Mozilla Rhino server-side JavaScript, set this to nil.
845 See `js2-additional-externs' for more information about externs."
846 :type 'boolean
847 :group 'js2-mode)
848
849 (defcustom js2-include-rhino-externs nil
850 "Non-nil to include Mozilla Rhino externs in the master externs list.
851 See `js2-additional-externs' for more information about externs."
852 :type 'boolean
853 :group 'js2-mode)
854
855 (defcustom js2-include-node-externs nil
856 "Non-nil to include Node.js externs in the master externs list.
857 See `js2-additional-externs' for more information about externs."
858 :type 'boolean
859 :group 'js2-mode)
860
861 (js2-deflocal js2-additional-externs nil
862 "A buffer-local list of additional external declarations.
863 It is used to decide whether variables are considered undeclared
864 for purposes of highlighting.
865
866 Each entry is a Lisp string. The string should be the fully qualified
867 name of an external entity. All externs should be added to this list,
868 so that as js2-mode's processing improves it can take advantage of them.
869
870 You may want to declare your externs in three ways.
871 First, you can add externs that are valid for all your JavaScript files.
872 You should probably do this by adding them to `js2-global-externs', which
873 is a global list used for all js2-mode files.
874
875 Next, you can add a function to `js2-init-hook' that adds additional
876 externs appropriate for the specific file, perhaps based on its path.
877 These should go in `js2-additional-externs', which is buffer-local.
878
879 Third, you can use JSLint's global declaration, as long as
880 `js2-include-jslint-globals' is non-nil, which see.
881
882 Finally, you can add a function to `js2-post-parse-callbacks',
883 which is called after parsing completes, and `js2-mode-ast' is bound to
884 the root of the parse tree. At this stage you can set up an AST
885 node visitor using `js2-visit-ast' and examine the parse tree
886 for specific import patterns that may imply the existence of
887 other externs, possibly tied to your build system. These should also
888 be added to `js2-additional-externs'.
889
890 Your post-parse callback may of course also use the simpler and
891 faster (but perhaps less robust) approach of simply scanning the
892 buffer text for your imports, using regular expressions.")
893
894 ;; SKIP: decompiler
895 ;; SKIP: encoded-source
896
897 ;;; The following variables are per-function and should be saved/restored
898 ;;; during function parsing...
899
900 (js2-deflocal js2-current-script-or-fn nil)
901 (js2-deflocal js2-current-scope nil)
902 (js2-deflocal js2-nesting-of-with 0)
903 (js2-deflocal js2-label-set nil
904 "An alist mapping label names to nodes.")
905
906 (js2-deflocal js2-loop-set nil)
907 (js2-deflocal js2-loop-and-switch-set nil)
908 (js2-deflocal js2-has-return-value nil)
909 (js2-deflocal js2-end-flags 0)
910
911 ;;; ...end of per function variables
912
913 ;; These flags enumerate the possible ways a statement/function can
914 ;; terminate. These flags are used by endCheck() and by the Parser to
915 ;; detect inconsistent return usage.
916 ;;
917 ;; END_UNREACHED is reserved for code paths that are assumed to always be
918 ;; able to execute (example: throw, continue)
919 ;;
920 ;; END_DROPS_OFF indicates if the statement can transfer control to the
921 ;; next one. Statement such as return dont. A compound statement may have
922 ;; some branch that drops off control to the next statement.
923 ;;
924 ;; END_RETURNS indicates that the statement can return (without arguments)
925 ;; END_RETURNS_VALUE indicates that the statement can return a value.
926 ;;
927 ;; A compound statement such as
928 ;; if (condition) {
929 ;; return value;
930 ;; }
931 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
932
933 (defconst js2-end-unreached #x0)
934 (defconst js2-end-drops-off #x1)
935 (defconst js2-end-returns #x2)
936 (defconst js2-end-returns-value #x4)
937
938 ;; Rhino awkwardly passes a statementLabel parameter to the
939 ;; statementHelper() function, the main statement parser, which
940 ;; is then used by quite a few of the sub-parsers. We just make
941 ;; it a buffer-local variable and make sure it's cleaned up properly.
942 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
943
944 ;; Similarly, Rhino passes an inForInit boolean through about half
945 ;; the expression parsers. We use a dynamically-scoped variable,
946 ;; which makes it easier to funcall the parsers individually without
947 ;; worrying about whether they take the parameter or not.
948 (js2-deflocal js2-in-for-init nil)
949 (js2-deflocal js2-temp-name-counter 0)
950 (js2-deflocal js2-parse-stmt-count 0)
951
952 (defsubst js2-get-next-temp-name ()
953 (format "$%d" (incf js2-temp-name-counter)))
954
955 (defvar js2-parse-interruptable-p t
956 "Set this to nil to force parse to continue until finished.
957 This will mostly be useful for interpreters.")
958
959 (defvar js2-statements-per-pause 50
960 "Pause after this many statements to check for user input.
961 If user input is pending, stop the parse and discard the tree.
962 This makes for a smoother user experience for large files.
963 You may have to wait a second or two before the highlighting
964 and error-reporting appear, but you can always type ahead if
965 you wish. This appears to be more or less how Eclipse, IntelliJ
966 and other editors work.")
967
968 (js2-deflocal js2-record-comments t
969 "Instructs the scanner to record comments in `js2-scanned-comments'.")
970
971 (js2-deflocal js2-scanned-comments nil
972 "List of all comments from the current parse.")
973
974 (defcustom js2-mode-indent-inhibit-undo nil
975 "Non-nil to disable collection of Undo information when indenting lines.
976 Some users have requested this behavior. It's nil by default because
977 other Emacs modes don't work this way."
978 :type 'boolean
979 :group 'js2-mode)
980
981 (defcustom js2-mode-indent-ignore-first-tab nil
982 "If non-nil, ignore first TAB keypress if we look indented properly.
983 It's fairly common for users to navigate to an already-indented line
984 and press TAB for reassurance that it's been indented. For this class
985 of users, we want the first TAB press on a line to be ignored if the
986 line is already indented to one of the precomputed alternatives.
987
988 This behavior is only partly implemented. If you TAB-indent a line,
989 navigate to another line, and then navigate back, it fails to clear
990 the last-indented variable, so it thinks you've already hit TAB once,
991 and performs the indent. A full solution would involve getting on the
992 point-motion hooks for the entire buffer. If we come across another
993 use cases that requires watching point motion, I'll consider doing it.
994
995 If you set this variable to nil, then the TAB key will always change
996 the indentation of the current line, if more than one alternative
997 indentation spot exists."
998 :type 'boolean
999 :group 'js2-mode)
1000
1001 (defvar js2-indent-hook nil
1002 "A hook for user-defined indentation rules.
1003
1004 Functions on this hook should expect two arguments: (LIST INDEX)
1005 The LIST argument is the list of computed indentation points for
1006 the current line. INDEX is the list index of the indentation point
1007 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1008 indent function is not going to change the current line indentation.
1009
1010 If a hook function on this list returns a non-nil value, then
1011 `js2-bounce-indent' assumes the hook function has performed its own
1012 indentation, and will do nothing. If all hook functions on the list
1013 return nil, then `js2-bounce-indent' will use its computed indentation
1014 and reindent the line.
1015
1016 When hook functions on this hook list are called, the variable
1017 `js2-mode-ast' may or may not be set, depending on whether the
1018 parse tree is available. If the variable is nil, you can pass a
1019 callback to `js2-mode-wait-for-parse', and your callback will be
1020 called after the new parse tree is built. This can take some time
1021 in large files.")
1022
1023 (defface js2-warning
1024 `((((class color) (background light))
1025 (:underline "orange"))
1026 (((class color) (background dark))
1027 (:underline "orange"))
1028 (t (:underline t)))
1029 "Face for JavaScript warnings."
1030 :group 'js2-mode)
1031
1032 (defface js2-error
1033 `((((class color) (background light))
1034 (:foreground "red"))
1035 (((class color) (background dark))
1036 (:foreground "red"))
1037 (t (:foreground "red")))
1038 "Face for JavaScript errors."
1039 :group 'js2-mode)
1040
1041 (defface js2-jsdoc-tag
1042 '((t :foreground "SlateGray"))
1043 "Face used to highlight @whatever tags in jsdoc comments."
1044 :group 'js2-mode)
1045
1046 (defface js2-jsdoc-type
1047 '((t :foreground "SteelBlue"))
1048 "Face used to highlight {FooBar} types in jsdoc comments."
1049 :group 'js2-mode)
1050
1051 (defface js2-jsdoc-value
1052 '((t :foreground "PeachPuff3"))
1053 "Face used to highlight tag values in jsdoc comments."
1054 :group 'js2-mode)
1055
1056 (defface js2-function-param
1057 '((t :foreground "SeaGreen"))
1058 "Face used to highlight function parameters in javascript."
1059 :group 'js2-mode)
1060
1061 (defface js2-function-call
1062 '((t :inherit default))
1063 "Face used to highlight function name in calls."
1064 :group 'js2-mode)
1065
1066 (defface js2-instance-member
1067 '((t :foreground "DarkOrchid"))
1068 "Face used to highlight instance variables in javascript.
1069 Not currently used."
1070 :group 'js2-mode)
1071
1072 (defface js2-private-member
1073 '((t :foreground "PeachPuff3"))
1074 "Face used to highlight calls to private methods in javascript.
1075 Not currently used."
1076 :group 'js2-mode)
1077
1078 (defface js2-private-function-call
1079 '((t :foreground "goldenrod"))
1080 "Face used to highlight calls to private functions in javascript.
1081 Not currently used."
1082 :group 'js2-mode)
1083
1084 (defface js2-jsdoc-html-tag-name
1085 '((((class color) (min-colors 88) (background light))
1086 (:foreground "rosybrown"))
1087 (((class color) (min-colors 8) (background dark))
1088 (:foreground "yellow"))
1089 (((class color) (min-colors 8) (background light))
1090 (:foreground "magenta")))
1091 "Face used to highlight jsdoc html tag names"
1092 :group 'js2-mode)
1093
1094 (defface js2-jsdoc-html-tag-delimiter
1095 '((((class color) (min-colors 88) (background light))
1096 (:foreground "dark khaki"))
1097 (((class color) (min-colors 8) (background dark))
1098 (:foreground "green"))
1099 (((class color) (min-colors 8) (background light))
1100 (:foreground "green")))
1101 "Face used to highlight brackets in jsdoc html tags."
1102 :group 'js2-mode)
1103
1104 (defface js2-external-variable
1105 '((t :foreground "orange"))
1106 "Face used to highlight undeclared variable identifiers.")
1107
1108 (defcustom js2-init-hook nil
1109 "List of functions to be called after `js2-mode' or
1110 `js2-minor-mode' has initialized all variables, before parsing
1111 the buffer for the first time."
1112 :type 'hook
1113 :group 'js2-mode
1114 :version "20130608")
1115
1116 (defcustom js2-post-parse-callbacks nil
1117 "List of callback functions invoked after parsing finishes.
1118 Currently, the main use for this function is to add synthetic
1119 declarations to `js2-recorded-identifiers', which see."
1120 :type 'hook
1121 :group 'js2-mode)
1122
1123 (defcustom js2-highlight-external-variables t
1124 "Non-nil to highlight undeclared variable identifiers.
1125 An undeclared variable is any variable not declared with var or let
1126 in the current scope or any lexically enclosing scope. If you use
1127 such a variable, then you are either expecting it to originate from
1128 another file, or you've got a potential bug."
1129 :type 'boolean
1130 :group 'js2-mode)
1131
1132 (defcustom js2-include-jslint-globals t
1133 "Non-nil to include the identifiers from JSLint global
1134 declaration (see http://www.jslint.com/lint.html#global) in the
1135 buffer-local externs list. See `js2-additional-externs' for more
1136 information."
1137 :type 'boolean
1138 :group 'js2-mode)
1139
1140 (defvar js2-mode-map
1141 (let ((map (make-sparse-keymap)))
1142 (define-key map [mouse-1] #'js2-mode-show-node)
1143 (define-key map (kbd "M-j") #'js2-line-break)
1144 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1145 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1146 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1147 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1148 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1149 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1150 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1151 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1152 (when js2-bounce-indent-p
1153 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1154
1155 (define-key map [menu-bar javascript]
1156 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1157
1158 (define-key map [menu-bar javascript customize-js2-mode]
1159 '(menu-item "Customize js2-mode" js2-mode-customize
1160 :help "Customize the behavior of this mode"))
1161
1162 (define-key map [menu-bar javascript js2-force-refresh]
1163 '(menu-item "Force buffer refresh" js2-mode-reset
1164 :help "Re-parse the buffer from scratch"))
1165
1166 (define-key map [menu-bar javascript separator-2]
1167 '("--"))
1168
1169 (define-key map [menu-bar javascript next-error]
1170 '(menu-item "Next warning or error" next-error
1171 :enabled (and js2-mode-ast
1172 (or (js2-ast-root-errors js2-mode-ast)
1173 (js2-ast-root-warnings js2-mode-ast)))
1174 :help "Move to next warning or error"))
1175
1176 (define-key map [menu-bar javascript display-errors]
1177 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1178 :visible (not js2-mode-show-parse-errors)
1179 :help "Turn on display of warnings and errors"))
1180
1181 (define-key map [menu-bar javascript hide-errors]
1182 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1183 :visible js2-mode-show-parse-errors
1184 :help "Turn off display of warnings and errors"))
1185
1186 (define-key map [menu-bar javascript separator-1]
1187 '("--"))
1188
1189 (define-key map [menu-bar javascript js2-toggle-function]
1190 '(menu-item "Show/collapse element" js2-mode-toggle-element
1191 :help "Hide or show function body or comment"))
1192
1193 (define-key map [menu-bar javascript show-comments]
1194 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1195 :visible js2-mode-comments-hidden
1196 :help "Expand all hidden block comments"))
1197
1198 (define-key map [menu-bar javascript hide-comments]
1199 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1200 :visible (not js2-mode-comments-hidden)
1201 :help "Show block comments as /*...*/"))
1202
1203 (define-key map [menu-bar javascript show-all-functions]
1204 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1205 :visible js2-mode-functions-hidden
1206 :help "Expand all hidden function bodies"))
1207
1208 (define-key map [menu-bar javascript hide-all-functions]
1209 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1210 :visible (not js2-mode-functions-hidden)
1211 :help "Show {...} for all top-level function bodies"))
1212
1213 map)
1214 "Keymap used in `js2-mode' buffers.")
1215
1216 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1217
1218 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1219 "Matches a //-comment line. Must be first non-whitespace on line.
1220 First match-group is the leading whitespace.")
1221
1222 (defvar js2-mode-hook nil)
1223
1224 (js2-deflocal js2-mode-ast nil "Private variable.")
1225 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1226 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1227 (js2-deflocal js2-mode-parsing nil "Private variable.")
1228 (js2-deflocal js2-mode-node-overlay nil)
1229
1230 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1231 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1232
1233 (js2-deflocal js2-mode-fontifications nil "Private variable")
1234 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1235 (js2-deflocal js2-imenu-recorder nil "Private variable")
1236 (js2-deflocal js2-imenu-function-map nil "Private variable")
1237
1238 (defvar js2-paragraph-start
1239 "\\(@[[:alpha:]]+\\>\\|$\\)")
1240
1241 ;; Note that we also set a 'c-in-sws text property in html comments,
1242 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1243 (defvar js2-syntactic-ws-start
1244 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1245
1246 (defvar js2-syntactic-ws-end
1247 "\\s \\|[\n\r/]\\|\\s!")
1248
1249 (defvar js2-syntactic-eol
1250 (concat "\\s *\\(/\\*[^*\n\r]*"
1251 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1252 "\\*+/\\s *\\)*"
1253 "\\(//\\|/\\*[^*\n\r]*"
1254 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1255 "\\|\\\\$\\|$\\)")
1256 "Copied from `java-mode'. Needed for some cc-engine functions.")
1257
1258 (defvar js2-comment-prefix-regexp
1259 "//+\\|\\**")
1260
1261 (defvar js2-comment-start-skip
1262 "\\(//+\\|/\\*+\\)\\s *")
1263
1264 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1265 "Non-nil to emit status messages during parsing.")
1266
1267 (defvar js2-mode-functions-hidden nil "Private variable.")
1268 (defvar js2-mode-comments-hidden nil "Private variable.")
1269
1270 (defvar js2-mode-syntax-table
1271 (let ((table (make-syntax-table)))
1272 (c-populate-syntax-table table)
1273 table)
1274 "Syntax table used in `js2-mode' buffers.")
1275
1276 (defvar js2-mode-abbrev-table nil
1277 "Abbrev table in use in `js2-mode' buffers.")
1278 (define-abbrev-table 'js2-mode-abbrev-table ())
1279
1280 (defvar js2-mode-pending-parse-callbacks nil
1281 "List of functions waiting to be notified that parse is finished.")
1282
1283 (defvar js2-mode-last-indented-line -1)
1284
1285 ;;; Localizable error and warning messages
1286
1287 ;; Messages are copied from Rhino's Messages.properties.
1288 ;; Many of the Java-specific messages have been elided.
1289 ;; Add any js2-specific ones at the end, so we can keep
1290 ;; this file synced with changes to Rhino's.
1291
1292 (defvar js2-message-table
1293 (make-hash-table :test 'equal :size 250)
1294 "Contains localized messages for `js2-mode'.")
1295
1296 ;; TODO(stevey): construct this table at compile-time.
1297 (defmacro js2-msg (key &rest strings)
1298 `(puthash ,key (concat ,@strings)
1299 js2-message-table))
1300
1301 (defun js2-get-msg (msg-key)
1302 "Look up a localized message.
1303 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1304 the correct number of ARGS must be provided."
1305 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1306 (args (if (listp msg-key) (cdr msg-key)))
1307 (msg (gethash key js2-message-table)))
1308 (if msg
1309 (apply #'format msg args)
1310 key))) ; default to showing the key
1311
1312 (js2-msg "msg.dup.parms"
1313 "Duplicate parameter name '%s'.")
1314
1315 (js2-msg "msg.too.big.jump"
1316 "Program too complex: jump offset too big.")
1317
1318 (js2-msg "msg.too.big.index"
1319 "Program too complex: internal index exceeds 64K limit.")
1320
1321 (js2-msg "msg.while.compiling.fn"
1322 "Encountered code generation error while compiling function '%s': %s")
1323
1324 (js2-msg "msg.while.compiling.script"
1325 "Encountered code generation error while compiling script: %s")
1326
1327 ;; Context
1328 (js2-msg "msg.ctor.not.found"
1329 "Constructor for '%s' not found.")
1330
1331 (js2-msg "msg.not.ctor"
1332 "'%s' is not a constructor.")
1333
1334 ;; FunctionObject
1335 (js2-msg "msg.varargs.ctor"
1336 "Method or constructor '%s' must be static "
1337 "with the signature (Context cx, Object[] args, "
1338 "Function ctorObj, boolean inNewExpr) "
1339 "to define a variable arguments constructor.")
1340
1341 (js2-msg "msg.varargs.fun"
1342 "Method '%s' must be static with the signature "
1343 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1344 "to define a variable arguments function.")
1345
1346 (js2-msg "msg.incompat.call"
1347 "Method '%s' called on incompatible object.")
1348
1349 (js2-msg "msg.bad.parms"
1350 "Unsupported parameter type '%s' in method '%s'.")
1351
1352 (js2-msg "msg.bad.method.return"
1353 "Unsupported return type '%s' in method '%s'.")
1354
1355 (js2-msg "msg.bad.ctor.return"
1356 "Construction of objects of type '%s' is not supported.")
1357
1358 (js2-msg "msg.no.overload"
1359 "Method '%s' occurs multiple times in class '%s'.")
1360
1361 (js2-msg "msg.method.not.found"
1362 "Method '%s' not found in '%s'.")
1363
1364 ;; IRFactory
1365
1366 (js2-msg "msg.bad.for.in.lhs"
1367 "Invalid left-hand side of for..in loop.")
1368
1369 (js2-msg "msg.mult.index"
1370 "Only one variable allowed in for..in loop.")
1371
1372 (js2-msg "msg.bad.for.in.destruct"
1373 "Left hand side of for..in loop must be an array of "
1374 "length 2 to accept key/value pair.")
1375
1376 (js2-msg "msg.cant.convert"
1377 "Can't convert to type '%s'.")
1378
1379 (js2-msg "msg.bad.assign.left"
1380 "Invalid assignment left-hand side.")
1381
1382 (js2-msg "msg.bad.decr"
1383 "Invalid decerement operand.")
1384
1385 (js2-msg "msg.bad.incr"
1386 "Invalid increment operand.")
1387
1388 (js2-msg "msg.bad.yield"
1389 "yield must be in a function.")
1390
1391 (js2-msg "msg.yield.parenthesized"
1392 "yield expression must be parenthesized.")
1393
1394 ;; NativeGlobal
1395 (js2-msg "msg.cant.call.indirect"
1396 "Function '%s' must be called directly, and not by way of a "
1397 "function of another name.")
1398
1399 (js2-msg "msg.eval.nonstring"
1400 "Calling eval() with anything other than a primitive "
1401 "string value will simply return the value. "
1402 "Is this what you intended?")
1403
1404 (js2-msg "msg.eval.nonstring.strict"
1405 "Calling eval() with anything other than a primitive "
1406 "string value is not allowed in strict mode.")
1407
1408 (js2-msg "msg.bad.destruct.op"
1409 "Invalid destructuring assignment operator")
1410
1411 ;; NativeCall
1412 (js2-msg "msg.only.from.new"
1413 "'%s' may only be invoked from a `new' expression.")
1414
1415 (js2-msg "msg.deprec.ctor"
1416 "The '%s' constructor is deprecated.")
1417
1418 ;; NativeFunction
1419 (js2-msg "msg.no.function.ref.found"
1420 "no source found to decompile function reference %s")
1421
1422 (js2-msg "msg.arg.isnt.array"
1423 "second argument to Function.prototype.apply must be an array")
1424
1425 ;; NativeGlobal
1426 (js2-msg "msg.bad.esc.mask"
1427 "invalid string escape mask")
1428
1429 ;; NativeRegExp
1430 (js2-msg "msg.bad.quant"
1431 "Invalid quantifier %s")
1432
1433 (js2-msg "msg.overlarge.backref"
1434 "Overly large back reference %s")
1435
1436 (js2-msg "msg.overlarge.min"
1437 "Overly large minimum %s")
1438
1439 (js2-msg "msg.overlarge.max"
1440 "Overly large maximum %s")
1441
1442 (js2-msg "msg.zero.quant"
1443 "Zero quantifier %s")
1444
1445 (js2-msg "msg.max.lt.min"
1446 "Maximum %s less than minimum")
1447
1448 (js2-msg "msg.unterm.quant"
1449 "Unterminated quantifier %s")
1450
1451 (js2-msg "msg.unterm.paren"
1452 "Unterminated parenthetical %s")
1453
1454 (js2-msg "msg.unterm.class"
1455 "Unterminated character class %s")
1456
1457 (js2-msg "msg.bad.range"
1458 "Invalid range in character class.")
1459
1460 (js2-msg "msg.trail.backslash"
1461 "Trailing \\ in regular expression.")
1462
1463 (js2-msg "msg.re.unmatched.right.paren"
1464 "unmatched ) in regular expression.")
1465
1466 (js2-msg "msg.no.regexp"
1467 "Regular expressions are not available.")
1468
1469 (js2-msg "msg.bad.backref"
1470 "back-reference exceeds number of capturing parentheses.")
1471
1472 (js2-msg "msg.bad.regexp.compile"
1473 "Only one argument may be specified if the first "
1474 "argument to RegExp.prototype.compile is a RegExp object.")
1475
1476 ;; Parser
1477 (js2-msg "msg.got.syntax.errors"
1478 "Compilation produced %s syntax errors.")
1479
1480 (js2-msg "msg.var.redecl"
1481 "TypeError: redeclaration of var %s.")
1482
1483 (js2-msg "msg.const.redecl"
1484 "TypeError: redeclaration of const %s.")
1485
1486 (js2-msg "msg.let.redecl"
1487 "TypeError: redeclaration of variable %s.")
1488
1489 (js2-msg "msg.parm.redecl"
1490 "TypeError: redeclaration of formal parameter %s.")
1491
1492 (js2-msg "msg.fn.redecl"
1493 "TypeError: redeclaration of function %s.")
1494
1495 (js2-msg "msg.let.decl.not.in.block"
1496 "SyntaxError: let declaration not directly within block")
1497
1498 ;; NodeTransformer
1499 (js2-msg "msg.dup.label"
1500 "duplicated label")
1501
1502 (js2-msg "msg.undef.label"
1503 "undefined label")
1504
1505 (js2-msg "msg.bad.break"
1506 "unlabelled break must be inside loop or switch")
1507
1508 (js2-msg "msg.continue.outside"
1509 "continue must be inside loop")
1510
1511 (js2-msg "msg.continue.nonloop"
1512 "continue can only use labels of iteration statements")
1513
1514 (js2-msg "msg.bad.throw.eol"
1515 "Line terminator is not allowed between the throw "
1516 "keyword and throw expression.")
1517
1518 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1519 "function statement requires a name")
1520
1521 (js2-msg "msg.no.paren.parms"
1522 "missing ( before function parameters.")
1523
1524 (js2-msg "msg.no.parm"
1525 "missing formal parameter")
1526
1527 (js2-msg "msg.no.paren.after.parms"
1528 "missing ) after formal parameters")
1529
1530 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1531 "parameter without default follows parameter with default")
1532
1533 (js2-msg "msg.param.after.rest" ; added by js2-mode
1534 "parameter after rest parameter")
1535
1536 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1537 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1538
1539 (js2-msg "msg.no.brace.body"
1540 "missing '{' before function body")
1541
1542 (js2-msg "msg.no.brace.after.body"
1543 "missing } after function body")
1544
1545 (js2-msg "msg.no.paren.cond"
1546 "missing ( before condition")
1547
1548 (js2-msg "msg.no.paren.after.cond"
1549 "missing ) after condition")
1550
1551 (js2-msg "msg.no.semi.stmt"
1552 "missing ; before statement")
1553
1554 (js2-msg "msg.missing.semi"
1555 "missing ; after statement")
1556
1557 (js2-msg "msg.no.name.after.dot"
1558 "missing name after . operator")
1559
1560 (js2-msg "msg.no.name.after.coloncolon"
1561 "missing name after :: operator")
1562
1563 (js2-msg "msg.no.name.after.dotdot"
1564 "missing name after .. operator")
1565
1566 (js2-msg "msg.no.name.after.xmlAttr"
1567 "missing name after .@")
1568
1569 (js2-msg "msg.no.bracket.index"
1570 "missing ] in index expression")
1571
1572 (js2-msg "msg.no.paren.switch"
1573 "missing ( before switch expression")
1574
1575 (js2-msg "msg.no.paren.after.switch"
1576 "missing ) after switch expression")
1577
1578 (js2-msg "msg.no.brace.switch"
1579 "missing '{' before switch body")
1580
1581 (js2-msg "msg.bad.switch"
1582 "invalid switch statement")
1583
1584 (js2-msg "msg.no.colon.case"
1585 "missing : after case expression")
1586
1587 (js2-msg "msg.double.switch.default"
1588 "double default label in the switch statement")
1589
1590 (js2-msg "msg.no.while.do"
1591 "missing while after do-loop body")
1592
1593 (js2-msg "msg.no.paren.for"
1594 "missing ( after for")
1595
1596 (js2-msg "msg.no.semi.for"
1597 "missing ; after for-loop initializer")
1598
1599 (js2-msg "msg.no.semi.for.cond"
1600 "missing ; after for-loop condition")
1601
1602 (js2-msg "msg.in.after.for.name"
1603 "missing in or of after for")
1604
1605 (js2-msg "msg.no.paren.for.ctrl"
1606 "missing ) after for-loop control")
1607
1608 (js2-msg "msg.no.paren.with"
1609 "missing ( before with-statement object")
1610
1611 (js2-msg "msg.no.paren.after.with"
1612 "missing ) after with-statement object")
1613
1614 (js2-msg "msg.no.paren.after.let"
1615 "missing ( after let")
1616
1617 (js2-msg "msg.no.paren.let"
1618 "missing ) after variable list")
1619
1620 (js2-msg "msg.no.curly.let"
1621 "missing } after let statement")
1622
1623 (js2-msg "msg.bad.return"
1624 "invalid return")
1625
1626 (js2-msg "msg.no.brace.block"
1627 "missing } in compound statement")
1628
1629 (js2-msg "msg.bad.label"
1630 "invalid label")
1631
1632 (js2-msg "msg.bad.var"
1633 "missing variable name")
1634
1635 (js2-msg "msg.bad.var.init"
1636 "invalid variable initialization")
1637
1638 (js2-msg "msg.no.colon.cond"
1639 "missing : in conditional expression")
1640
1641 (js2-msg "msg.no.paren.arg"
1642 "missing ) after argument list")
1643
1644 (js2-msg "msg.no.bracket.arg"
1645 "missing ] after element list")
1646
1647 (js2-msg "msg.bad.prop"
1648 "invalid property id")
1649
1650 (js2-msg "msg.no.colon.prop"
1651 "missing : after property id")
1652
1653 (js2-msg "msg.no.brace.prop"
1654 "missing } after property list")
1655
1656 (js2-msg "msg.no.paren"
1657 "missing ) in parenthetical")
1658
1659 (js2-msg "msg.reserved.id"
1660 "'%s' is a reserved identifier")
1661
1662 (js2-msg "msg.no.paren.catch"
1663 "missing ( before catch-block condition")
1664
1665 (js2-msg "msg.bad.catchcond"
1666 "invalid catch block condition")
1667
1668 (js2-msg "msg.catch.unreachable"
1669 "any catch clauses following an unqualified catch are unreachable")
1670
1671 (js2-msg "msg.no.brace.try"
1672 "missing '{' before try block")
1673
1674 (js2-msg "msg.no.brace.catchblock"
1675 "missing '{' before catch-block body")
1676
1677 (js2-msg "msg.try.no.catchfinally"
1678 "'try' without 'catch' or 'finally'")
1679
1680 (js2-msg "msg.no.return.value"
1681 "function %s does not always return a value")
1682
1683 (js2-msg "msg.anon.no.return.value"
1684 "anonymous function does not always return a value")
1685
1686 (js2-msg "msg.return.inconsistent"
1687 "return statement is inconsistent with previous usage")
1688
1689 (js2-msg "msg.generator.returns"
1690 "TypeError: legacy generator function '%s' returns a value")
1691
1692 (js2-msg "msg.anon.generator.returns"
1693 "TypeError: anonymous legacy generator function returns a value")
1694
1695 (js2-msg "msg.syntax"
1696 "syntax error")
1697
1698 (js2-msg "msg.unexpected.eof"
1699 "Unexpected end of file")
1700
1701 (js2-msg "msg.XML.bad.form"
1702 "illegally formed XML syntax")
1703
1704 (js2-msg "msg.XML.not.available"
1705 "XML runtime not available")
1706
1707 (js2-msg "msg.too.deep.parser.recursion"
1708 "Too deep recursion while parsing")
1709
1710 (js2-msg "msg.no.side.effects"
1711 "Code has no side effects")
1712
1713 (js2-msg "msg.extra.trailing.comma"
1714 "Trailing comma is not supported in some browsers")
1715
1716 (js2-msg "msg.array.trailing.comma"
1717 "Trailing comma yields different behavior across browsers")
1718
1719 (js2-msg "msg.equal.as.assign"
1720 (concat "Test for equality (==) mistyped as assignment (=)?"
1721 " (parenthesize to suppress warning)"))
1722
1723 (js2-msg "msg.var.hides.arg"
1724 "Variable %s hides argument")
1725
1726 (js2-msg "msg.destruct.assign.no.init"
1727 "Missing = in destructuring declaration")
1728
1729 ;; ScriptRuntime
1730 (js2-msg "msg.no.properties"
1731 "%s has no properties.")
1732
1733 (js2-msg "msg.invalid.iterator"
1734 "Invalid iterator value")
1735
1736 (js2-msg "msg.iterator.primitive"
1737 "__iterator__ returned a primitive value")
1738
1739 (js2-msg "msg.assn.create.strict"
1740 "Assignment to undeclared variable %s")
1741
1742 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1743 "Undeclared variable or function '%s'")
1744
1745 (js2-msg "msg.ref.undefined.prop"
1746 "Reference to undefined property '%s'")
1747
1748 (js2-msg "msg.prop.not.found"
1749 "Property %s not found.")
1750
1751 (js2-msg "msg.invalid.type"
1752 "Invalid JavaScript value of type %s")
1753
1754 (js2-msg "msg.primitive.expected"
1755 "Primitive type expected (had %s instead)")
1756
1757 (js2-msg "msg.namespace.expected"
1758 "Namespace object expected to left of :: (found %s instead)")
1759
1760 (js2-msg "msg.null.to.object"
1761 "Cannot convert null to an object.")
1762
1763 (js2-msg "msg.undef.to.object"
1764 "Cannot convert undefined to an object.")
1765
1766 (js2-msg "msg.cyclic.value"
1767 "Cyclic %s value not allowed.")
1768
1769 (js2-msg "msg.is.not.defined"
1770 "'%s' is not defined.")
1771
1772 (js2-msg "msg.undef.prop.read"
1773 "Cannot read property '%s' from %s")
1774
1775 (js2-msg "msg.undef.prop.write"
1776 "Cannot set property '%s' of %s to '%s'")
1777
1778 (js2-msg "msg.undef.prop.delete"
1779 "Cannot delete property '%s' of %s")
1780
1781 (js2-msg "msg.undef.method.call"
1782 "Cannot call method '%s' of %s")
1783
1784 (js2-msg "msg.undef.with"
1785 "Cannot apply 'with' to %s")
1786
1787 (js2-msg "msg.isnt.function"
1788 "%s is not a function, it is %s.")
1789
1790 (js2-msg "msg.isnt.function.in"
1791 "Cannot call property %s in object %s. "
1792 "It is not a function, it is '%s'.")
1793
1794 (js2-msg "msg.function.not.found"
1795 "Cannot find function %s.")
1796
1797 (js2-msg "msg.function.not.found.in"
1798 "Cannot find function %s in object %s.")
1799
1800 (js2-msg "msg.isnt.xml.object"
1801 "%s is not an xml object.")
1802
1803 (js2-msg "msg.no.ref.to.get"
1804 "%s is not a reference to read reference value.")
1805
1806 (js2-msg "msg.no.ref.to.set"
1807 "%s is not a reference to set reference value to %s.")
1808
1809 (js2-msg "msg.no.ref.from.function"
1810 "Function %s can not be used as the left-hand "
1811 "side of assignment or as an operand of ++ or -- operator.")
1812
1813 (js2-msg "msg.bad.default.value"
1814 "Object's getDefaultValue() method returned an object.")
1815
1816 (js2-msg "msg.instanceof.not.object"
1817 "Can't use instanceof on a non-object.")
1818
1819 (js2-msg "msg.instanceof.bad.prototype"
1820 "'prototype' property of %s is not an object.")
1821
1822 (js2-msg "msg.bad.radix"
1823 "illegal radix %s.")
1824
1825 ;; ScriptableObject
1826 (js2-msg "msg.default.value"
1827 "Cannot find default value for object.")
1828
1829 (js2-msg "msg.zero.arg.ctor"
1830 "Cannot load class '%s' which has no zero-parameter constructor.")
1831
1832 (js2-msg "msg.ctor.multiple.parms"
1833 "Can't define constructor or class %s since more than "
1834 "one constructor has multiple parameters.")
1835
1836 (js2-msg "msg.extend.scriptable"
1837 "%s must extend ScriptableObject in order to define property %s.")
1838
1839 (js2-msg "msg.bad.getter.parms"
1840 "In order to define a property, getter %s must have zero "
1841 "parameters or a single ScriptableObject parameter.")
1842
1843 (js2-msg "msg.obj.getter.parms"
1844 "Expected static or delegated getter %s to take "
1845 "a ScriptableObject parameter.")
1846
1847 (js2-msg "msg.getter.static"
1848 "Getter and setter must both be static or neither be static.")
1849
1850 (js2-msg "msg.setter.return"
1851 "Setter must have void return type: %s")
1852
1853 (js2-msg "msg.setter2.parms"
1854 "Two-parameter setter must take a ScriptableObject as "
1855 "its first parameter.")
1856
1857 (js2-msg "msg.setter1.parms"
1858 "Expected single parameter setter for %s")
1859
1860 (js2-msg "msg.setter2.expected"
1861 "Expected static or delegated setter %s to take two parameters.")
1862
1863 (js2-msg "msg.setter.parms"
1864 "Expected either one or two parameters for setter.")
1865
1866 (js2-msg "msg.setter.bad.type"
1867 "Unsupported parameter type '%s' in setter '%s'.")
1868
1869 (js2-msg "msg.add.sealed"
1870 "Cannot add a property to a sealed object: %s.")
1871
1872 (js2-msg "msg.remove.sealed"
1873 "Cannot remove a property from a sealed object: %s.")
1874
1875 (js2-msg "msg.modify.sealed"
1876 "Cannot modify a property of a sealed object: %s.")
1877
1878 (js2-msg "msg.modify.readonly"
1879 "Cannot modify readonly property: %s.")
1880
1881 ;; TokenStream
1882 (js2-msg "msg.missing.exponent"
1883 "missing exponent")
1884
1885 (js2-msg "msg.caught.nfe"
1886 "number format error")
1887
1888 (js2-msg "msg.unterminated.string.lit"
1889 "unterminated string literal")
1890
1891 (js2-msg "msg.unterminated.comment"
1892 "unterminated comment")
1893
1894 (js2-msg "msg.unterminated.re.lit"
1895 "unterminated regular expression literal")
1896
1897 (js2-msg "msg.invalid.re.flag"
1898 "invalid flag after regular expression")
1899
1900 (js2-msg "msg.no.re.input.for"
1901 "no input for %s")
1902
1903 (js2-msg "msg.illegal.character"
1904 "illegal character")
1905
1906 (js2-msg "msg.invalid.escape"
1907 "invalid Unicode escape sequence")
1908
1909 (js2-msg "msg.bad.namespace"
1910 "not a valid default namespace statement. "
1911 "Syntax is: default xml namespace = EXPRESSION;")
1912
1913 ;; TokensStream warnings
1914 (js2-msg "msg.bad.octal.literal"
1915 "illegal octal literal digit %s; "
1916 "interpreting it as a decimal digit")
1917
1918 (js2-msg "msg.missing.hex.digits"
1919 "missing hexadecimal digits after '0x'")
1920
1921 (js2-msg "msg.missing.binary.digits"
1922 "missing binary digits after '0b'")
1923
1924 (js2-msg "msg.missing.octal.digits"
1925 "missing octal digits after '0o'")
1926
1927 (js2-msg "msg.script.is.not.constructor"
1928 "Script objects are not constructors.")
1929
1930 ;; Arrays
1931 (js2-msg "msg.arraylength.bad"
1932 "Inappropriate array length.")
1933
1934 ;; Arrays
1935 (js2-msg "msg.arraylength.too.big"
1936 "Array length %s exceeds supported capacity limit.")
1937
1938 ;; URI
1939 (js2-msg "msg.bad.uri"
1940 "Malformed URI sequence.")
1941
1942 ;; Number
1943 (js2-msg "msg.bad.precision"
1944 "Precision %s out of range.")
1945
1946 ;; NativeGenerator
1947 (js2-msg "msg.send.newborn"
1948 "Attempt to send value to newborn generator")
1949
1950 (js2-msg "msg.already.exec.gen"
1951 "Already executing generator")
1952
1953 (js2-msg "msg.StopIteration.invalid"
1954 "StopIteration may not be changed to an arbitrary object.")
1955
1956 ;; Interpreter
1957 (js2-msg "msg.yield.closing"
1958 "Yield from closing generator")
1959
1960 ;; Classes
1961 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1962 "class statement requires a name")
1963
1964 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1965 "unexpected ',' between class properties")
1966
1967 (js2-msg "msg.missing.extends" ; added by js2-mode
1968 "name is required after extends")
1969
1970 (js2-msg "msg.no.brace.class" ; added by js2-mode
1971 "missing '{' before class body")
1972
1973 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1974 "missing ']' after computed property expression")
1975
1976 ;;; Tokens Buffer
1977
1978 (defconst js2-ti-max-lookahead 2)
1979 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1980
1981 ;; Have to call `js2-init-scanner' to initialize the values.
1982 (js2-deflocal js2-ti-tokens nil)
1983 (js2-deflocal js2-ti-tokens-cursor nil)
1984 (js2-deflocal js2-ti-lookahead nil)
1985
1986 (defun js2-new-token (offset)
1987 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1988 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1989 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1990 token))
1991
1992 (defsubst js2-current-token ()
1993 (aref js2-ti-tokens js2-ti-tokens-cursor))
1994
1995 (defsubst js2-current-token-string ()
1996 (js2-token-string (js2-current-token)))
1997
1998 (defsubst js2-current-token-type ()
1999 (js2-token-type (js2-current-token)))
2000
2001 (defsubst js2-current-token-beg ()
2002 (js2-token-beg (js2-current-token)))
2003
2004 (defsubst js2-current-token-end ()
2005 (js2-token-end (js2-current-token)))
2006
2007 (defun js2-current-token-len ()
2008 (let ((token (js2-current-token)))
2009 (- (js2-token-end token)
2010 (js2-token-beg token))))
2011
2012 (defun js2-ts-seek (state)
2013 (setq js2-ts-lineno (js2-ts-state-lineno state)
2014 js2-ts-cursor (js2-ts-state-cursor state)
2015 js2-ti-tokens (js2-ts-state-tokens state)
2016 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2017 js2-ti-lookahead (js2-ts-state-lookahead state)))
2018
2019 ;;; Utilities
2020
2021 (defun js2-delete-if (predicate list)
2022 "Remove all items satisfying PREDICATE in LIST."
2023 (loop for item in list
2024 if (not (funcall predicate item))
2025 collect item))
2026
2027 (defun js2-position (element list)
2028 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2029 Returns nil if element is not found in the list."
2030 (let ((count 0)
2031 found)
2032 (while (and list (not found))
2033 (if (eq element (car list))
2034 (setq found t)
2035 (setq count (1+ count)
2036 list (cdr list))))
2037 (if found count)))
2038
2039 (defun js2-find-if (predicate list)
2040 "Find first item satisfying PREDICATE in LIST."
2041 (let (result)
2042 (while (and list (not result))
2043 (if (funcall predicate (car list))
2044 (setq result (car list)))
2045 (setq list (cdr list)))
2046 result))
2047
2048 (defmacro js2-time (form)
2049 "Evaluate FORM, discard result, and return elapsed time in sec."
2050 (declare (debug t))
2051 (let ((beg (make-symbol "--js2-time-beg--"))
2052 (delta (make-symbol "--js2-time-end--")))
2053 `(let ((,beg (current-time))
2054 ,delta)
2055 ,form
2056 (/ (truncate (* (- (float-time (current-time))
2057 (float-time ,beg))
2058 10000))
2059 10000.0))))
2060
2061 (defsubst js2-same-line (pos)
2062 "Return t if POS is on the same line as current point."
2063 (and (>= pos (point-at-bol))
2064 (<= pos (point-at-eol))))
2065
2066 (defun js2-code-bug ()
2067 "Signal an error when we encounter an unexpected code path."
2068 (error "failed assertion"))
2069
2070 (defsubst js2-record-text-property (beg end prop value)
2071 "Record a text property to set when parsing finishes."
2072 (push (list beg end prop value) js2-mode-deferred-properties))
2073
2074 ;; I'd like to associate errors with nodes, but for now the
2075 ;; easiest thing to do is get the context info from the last token.
2076 (defun js2-record-parse-error (msg &optional arg pos len)
2077 (push (list (list msg arg)
2078 (or pos (js2-current-token-beg))
2079 (or len (js2-current-token-len)))
2080 js2-parsed-errors))
2081
2082 (defun js2-report-error (msg &optional msg-arg pos len)
2083 "Signal a syntax error or record a parse error."
2084 (if js2-recover-from-parse-errors
2085 (js2-record-parse-error msg msg-arg pos len)
2086 (signal 'js2-syntax-error
2087 (list msg
2088 js2-ts-lineno
2089 (save-excursion
2090 (goto-char js2-ts-cursor)
2091 (current-column))
2092 js2-ts-hit-eof))))
2093
2094 (defun js2-report-warning (msg &optional msg-arg pos len face)
2095 (if js2-compiler-report-warning-as-error
2096 (js2-report-error msg msg-arg pos len)
2097 (push (list (list msg msg-arg)
2098 (or pos (js2-current-token-beg))
2099 (or len (js2-current-token-len))
2100 face)
2101 js2-parsed-warnings)))
2102
2103 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2104 (if js2-compiler-strict-mode
2105 (js2-report-warning msg-id msg-arg beg
2106 (and beg end (- end beg)))))
2107
2108 (put 'js2-syntax-error 'error-conditions
2109 '(error syntax-error js2-syntax-error))
2110 (put 'js2-syntax-error 'error-message "Syntax error")
2111
2112 (put 'js2-parse-error 'error-conditions
2113 '(error parse-error js2-parse-error))
2114 (put 'js2-parse-error 'error-message "Parse error")
2115
2116 (defmacro js2-clear-flag (flags flag)
2117 `(setq ,flags (logand ,flags (lognot ,flag))))
2118
2119 (defmacro js2-set-flag (flags flag)
2120 "Logical-or FLAG into FLAGS."
2121 `(setq ,flags (logior ,flags ,flag)))
2122
2123 (defsubst js2-flag-set-p (flags flag)
2124 (/= 0 (logand flags flag)))
2125
2126 (defsubst js2-flag-not-set-p (flags flag)
2127 (zerop (logand flags flag)))
2128
2129 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2130 "Evaluate BODY with the _ character set to be word-syntax."
2131 (declare (indent 0) (debug t))
2132 (let ((old-syntax (make-symbol "old-syntax")))
2133 `(let ((,old-syntax (string (char-syntax ?_))))
2134 (unwind-protect
2135 (progn
2136 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2137 ,@body)
2138 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2139
2140 ;;; AST struct and function definitions
2141
2142 ;; flags for ast node property 'member-type (used for e4x operators)
2143 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2144 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2145 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2146
2147 (defsubst js2-relpos (pos anchor)
2148 "Convert POS to be relative to ANCHOR.
2149 If POS is nil, returns nil."
2150 (and pos (- pos anchor)))
2151
2152 (defun js2-make-pad (indent)
2153 (if (zerop indent)
2154 ""
2155 (make-string (* indent js2-basic-offset) ? )))
2156
2157 (defun js2-visit-ast (node callback)
2158 "Visit every node in ast NODE with visitor CALLBACK.
2159
2160 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2161 called twice: once to visit the node, and again after all the node's
2162 children have been processed. The END-P argument is nil on the first
2163 call and non-nil on the second call. The return value of the callback
2164 affects the traversal: if non-nil, the children of NODE are processed.
2165 If the callback returns nil, or if the node has no children, then the
2166 callback is called immediately with a non-nil END-P argument.
2167
2168 The node traversal is approximately lexical-order, although there
2169 are currently no guarantees around this."
2170 (when node
2171 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2172 ;; visit the node
2173 (when (funcall callback node nil)
2174 ;; visit the kids
2175 (cond
2176 ((eq vfunc 'js2-visit-none)
2177 nil) ; don't even bother calling it
2178 ;; Each AST node type has to define a `js2-visitor' function
2179 ;; that takes a node and a callback, and calls `js2-visit-ast'
2180 ;; on each child of the node.
2181 (vfunc
2182 (funcall vfunc node callback))
2183 (t
2184 (error "%s does not define a visitor-traversal function"
2185 (aref node 0)))))
2186 ;; call the end-visit
2187 (funcall callback node t))))
2188
2189 (defstruct (js2-node
2190 (:constructor nil)) ; abstract
2191 "Base AST node type."
2192 (type -1) ; token type
2193 (pos -1) ; start position of this AST node in parsed input
2194 (len 1) ; num characters spanned by the node
2195 props ; optional node property list (an alist)
2196 parent) ; link to parent node; null for root
2197
2198 (defsubst js2-node-get-prop (node prop &optional default)
2199 (or (cadr (assoc prop (js2-node-props node))) default))
2200
2201 (defsubst js2-node-set-prop (node prop value)
2202 (setf (js2-node-props node)
2203 (cons (list prop value) (js2-node-props node))))
2204
2205 (defun js2-fixup-starts (n nodes)
2206 "Adjust the start positions of NODES to be relative to N.
2207 Any node in the list may be nil, for convenience."
2208 (dolist (node nodes)
2209 (when node
2210 (setf (js2-node-pos node) (- (js2-node-pos node)
2211 (js2-node-pos n))))))
2212
2213 (defun js2-node-add-children (parent &rest nodes)
2214 "Set parent node of NODES to PARENT, and return PARENT.
2215 Does nothing if we're not recording parent links.
2216 If any given node in NODES is nil, doesn't record that link."
2217 (js2-fixup-starts parent nodes)
2218 (dolist (node nodes)
2219 (and node
2220 (setf (js2-node-parent node) parent))))
2221
2222 ;; Non-recursive since it's called a frightening number of times.
2223 (defun js2-node-abs-pos (n)
2224 (let ((pos (js2-node-pos n)))
2225 (while (setq n (js2-node-parent n))
2226 (setq pos (+ pos (js2-node-pos n))))
2227 pos))
2228
2229 (defsubst js2-node-abs-end (n)
2230 "Return absolute buffer position of end of N."
2231 (+ (js2-node-abs-pos n) (js2-node-len n)))
2232
2233 ;; It's important to make sure block nodes have a Lisp list for the
2234 ;; child nodes, to limit printing recursion depth in an AST that
2235 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2236 ;; a sufficiently large vector tree.
2237
2238 (defstruct (js2-block-node
2239 (:include js2-node)
2240 (:constructor nil)
2241 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2242 (pos (js2-current-token-beg))
2243 len
2244 props
2245 kids)))
2246 "A block of statements."
2247 kids) ; a Lisp list of the child statement nodes
2248
2249 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2250 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2251
2252 (defun js2-visit-block (ast callback)
2253 "Visit the `js2-block-node' children of AST."
2254 (dolist (kid (js2-block-node-kids ast))
2255 (js2-visit-ast kid callback)))
2256
2257 (defun js2-print-block (n i)
2258 (let ((pad (js2-make-pad i)))
2259 (insert pad "{\n")
2260 (dolist (kid (js2-block-node-kids n))
2261 (js2-print-ast kid (1+ i)))
2262 (insert pad "}")))
2263
2264 (defstruct (js2-scope
2265 (:include js2-block-node)
2266 (:constructor nil)
2267 (:constructor make-js2-scope (&key (type js2-BLOCK)
2268 (pos (js2-current-token-beg))
2269 len
2270 kids)))
2271 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2272 ;; I don't have one of those handy, so I'll use an alist for now.
2273 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2274 ;; and is much lighter-weight to construct (both CPU and mem).
2275 ;; The keys are interned strings (symbols) for faster lookup.
2276 ;; Should switch to hybrid alist/hashtable eventually.
2277 symbol-table ; an alist of (symbol . js2-symbol)
2278 parent-scope ; a `js2-scope'
2279 top) ; top-level `js2-scope' (script/function)
2280
2281 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2282 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2283
2284 (defun js2-node-get-enclosing-scope (node)
2285 "Return the innermost `js2-scope' node surrounding NODE.
2286 Returns nil if there is no enclosing scope node."
2287 (let ((parent (js2-node-parent node)))
2288 (while (not (js2-scope-p parent))
2289 (setq parent (js2-node-parent parent)))
2290 parent))
2291
2292 (defun js2-get-defining-scope (scope name)
2293 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2294 Returns `js2-scope' in which NAME is defined, or nil if not found."
2295 (let ((sym (if (symbolp name)
2296 name
2297 (intern name)))
2298 table
2299 result
2300 (continue t))
2301 (while (and scope continue)
2302 (if (and (setq table (js2-scope-symbol-table scope))
2303 (assq sym table))
2304 (setq continue nil
2305 result scope)
2306 (setq scope (js2-scope-parent-scope scope))))
2307 result))
2308
2309 (defun js2-scope-get-symbol (scope name)
2310 "Return symbol table entry for NAME in SCOPE.
2311 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2312 (and (js2-scope-symbol-table scope)
2313 (cdr (assq (if (symbolp name)
2314 name
2315 (intern name))
2316 (js2-scope-symbol-table scope)))))
2317
2318 (defun js2-scope-put-symbol (scope name symbol)
2319 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2320 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2321 (let* ((table (js2-scope-symbol-table scope))
2322 (sym (if (symbolp name) name (intern name)))
2323 (entry (assq sym table)))
2324 (if entry
2325 (setcdr entry symbol)
2326 (push (cons sym symbol)
2327 (js2-scope-symbol-table scope)))))
2328
2329 (defstruct (js2-symbol
2330 (:constructor nil)
2331 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2332 "A symbol table entry."
2333 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2334 ;; js2-LET, or js2-CONST
2335 decl-type
2336 name ; string
2337 ast-node) ; a `js2-node'
2338
2339 (defstruct (js2-error-node
2340 (:include js2-node)
2341 (:constructor nil) ; silence emacs21 byte-compiler
2342 (:constructor make-js2-error-node (&key (type js2-ERROR)
2343 (pos (js2-current-token-beg))
2344 len)))
2345 "AST node representing a parse error.")
2346
2347 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2348 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2349
2350 (defstruct (js2-script-node
2351 (:include js2-scope)
2352 (:constructor nil)
2353 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2354 (pos (js2-current-token-beg))
2355 len
2356 ;; FIXME: What are those?
2357 var-decls
2358 fun-decls)))
2359 functions ; Lisp list of nested functions
2360 regexps ; Lisp list of (string . flags)
2361 symbols ; alist (every symbol gets unique index)
2362 (param-count 0)
2363 var-names ; vector of string names
2364 consts ; bool-vector matching var-decls
2365 (temp-number 0)) ; for generating temp variables
2366
2367 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2368 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2369
2370 (defun js2-print-script (node indent)
2371 (dolist (kid (js2-block-node-kids node))
2372 (js2-print-ast kid indent)))
2373
2374 (defstruct (js2-ast-root
2375 (:include js2-script-node)
2376 (:constructor nil)
2377 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2378 (pos (js2-current-token-beg))
2379 len
2380 buffer)))
2381 "The root node of a js2 AST."
2382 buffer ; the source buffer from which the code was parsed
2383 comments ; a Lisp list of comments, ordered by start position
2384 errors ; a Lisp list of errors found during parsing
2385 warnings ; a Lisp list of warnings found during parsing
2386 node-count) ; number of nodes in the tree, including the root
2387
2388 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2389 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2390
2391 (defun js2-visit-ast-root (ast callback)
2392 (dolist (kid (js2-ast-root-kids ast))
2393 (js2-visit-ast kid callback))
2394 (dolist (comment (js2-ast-root-comments ast))
2395 (js2-visit-ast comment callback)))
2396
2397 (defstruct (js2-comment-node
2398 (:include js2-node)
2399 (:constructor nil)
2400 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2401 (pos (js2-current-token-beg))
2402 len
2403 format)))
2404 format) ; 'line, 'block, 'jsdoc or 'html
2405
2406 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2407 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2408
2409 (defun js2-print-comment (n i)
2410 ;; We really ought to link end-of-line comments to their nodes.
2411 ;; Or maybe we could add a new comment type, 'endline.
2412 (insert (js2-make-pad i)
2413 (js2-node-string n)))
2414
2415 (defstruct (js2-expr-stmt-node
2416 (:include js2-node)
2417 (:constructor nil)
2418 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2419 (pos js2-ts-cursor)
2420 len
2421 expr)))
2422 "An expression statement."
2423 expr)
2424
2425 (defsubst js2-expr-stmt-node-set-has-result (node)
2426 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2427 (setf (js2-node-type node) js2-EXPR_RESULT))
2428
2429 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2430 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2431
2432 (defun js2-visit-expr-stmt-node (n v)
2433 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2434
2435 (defun js2-print-expr-stmt-node (n indent)
2436 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2437 (insert ";\n"))
2438
2439 (defstruct (js2-loop-node
2440 (:include js2-scope)
2441 (:constructor nil))
2442 "Abstract supertype of loop nodes."
2443 body ; a `js2-block-node'
2444 lp ; position of left-paren, nil if omitted
2445 rp) ; position of right-paren, nil if omitted
2446
2447 (defstruct (js2-do-node
2448 (:include js2-loop-node)
2449 (:constructor nil)
2450 (:constructor make-js2-do-node (&key (type js2-DO)
2451 (pos (js2-current-token-beg))
2452 len
2453 body
2454 condition
2455 while-pos
2456 lp
2457 rp)))
2458 "AST node for do-loop."
2459 condition ; while (expression)
2460 while-pos) ; buffer position of 'while' keyword
2461
2462 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2463 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2464
2465 (defun js2-visit-do-node (n v)
2466 (js2-visit-ast (js2-do-node-body n) v)
2467 (js2-visit-ast (js2-do-node-condition n) v))
2468
2469 (defun js2-print-do-node (n i)
2470 (let ((pad (js2-make-pad i)))
2471 (insert pad "do {\n")
2472 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2473 (js2-print-ast kid (1+ i)))
2474 (insert pad "} while (")
2475 (js2-print-ast (js2-do-node-condition n) 0)
2476 (insert ");\n")))
2477
2478 (defstruct (js2-while-node
2479 (:include js2-loop-node)
2480 (:constructor nil)
2481 (:constructor make-js2-while-node (&key (type js2-WHILE)
2482 (pos (js2-current-token-beg))
2483 len body
2484 condition lp
2485 rp)))
2486 "AST node for while-loop."
2487 condition) ; while-condition
2488
2489 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2490 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2491
2492 (defun js2-visit-while-node (n v)
2493 (js2-visit-ast (js2-while-node-condition n) v)
2494 (js2-visit-ast (js2-while-node-body n) v))
2495
2496 (defun js2-print-while-node (n i)
2497 (let ((pad (js2-make-pad i)))
2498 (insert pad "while (")
2499 (js2-print-ast (js2-while-node-condition n) 0)
2500 (insert ") {\n")
2501 (js2-print-body (js2-while-node-body n) (1+ i))
2502 (insert pad "}\n")))
2503
2504 (defstruct (js2-for-node
2505 (:include js2-loop-node)
2506 (:constructor nil)
2507 (:constructor make-js2-for-node (&key (type js2-FOR)
2508 (pos js2-ts-cursor)
2509 len body init
2510 condition
2511 update lp rp)))
2512 "AST node for a C-style for-loop."
2513 init ; initialization expression
2514 condition ; loop condition
2515 update) ; update clause
2516
2517 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2518 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2519
2520 (defun js2-visit-for-node (n v)
2521 (js2-visit-ast (js2-for-node-init n) v)
2522 (js2-visit-ast (js2-for-node-condition n) v)
2523 (js2-visit-ast (js2-for-node-update n) v)
2524 (js2-visit-ast (js2-for-node-body n) v))
2525
2526 (defun js2-print-for-node (n i)
2527 (let ((pad (js2-make-pad i)))
2528 (insert pad "for (")
2529 (js2-print-ast (js2-for-node-init n) 0)
2530 (insert "; ")
2531 (js2-print-ast (js2-for-node-condition n) 0)
2532 (insert "; ")
2533 (js2-print-ast (js2-for-node-update n) 0)
2534 (insert ") {\n")
2535 (js2-print-body (js2-for-node-body n) (1+ i))
2536 (insert pad "}\n")))
2537
2538 (defstruct (js2-for-in-node
2539 (:include js2-loop-node)
2540 (:constructor nil)
2541 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2542 (pos js2-ts-cursor)
2543 len body
2544 iterator
2545 object
2546 in-pos
2547 each-pos
2548 foreach-p forof-p
2549 lp rp)))
2550 "AST node for a for..in loop."
2551 iterator ; [var] foo in ...
2552 object ; object over which we're iterating
2553 in-pos ; buffer position of 'in' keyword
2554 each-pos ; buffer position of 'each' keyword, if foreach-p
2555 foreach-p ; t if it's a for-each loop
2556 forof-p) ; t if it's a for-of loop
2557
2558 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2559 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2560
2561 (defun js2-visit-for-in-node (n v)
2562 (js2-visit-ast (js2-for-in-node-iterator n) v)
2563 (js2-visit-ast (js2-for-in-node-object n) v)
2564 (js2-visit-ast (js2-for-in-node-body n) v))
2565
2566 (defun js2-print-for-in-node (n i)
2567 (let ((pad (js2-make-pad i))
2568 (foreach (js2-for-in-node-foreach-p n))
2569 (forof (js2-for-in-node-forof-p n)))
2570 (insert pad "for ")
2571 (if foreach
2572 (insert "each "))
2573 (insert "(")
2574 (js2-print-ast (js2-for-in-node-iterator n) 0)
2575 (insert (if forof " of " " in "))
2576 (js2-print-ast (js2-for-in-node-object n) 0)
2577 (insert ") {\n")
2578 (js2-print-body (js2-for-in-node-body n) (1+ i))
2579 (insert pad "}\n")))
2580
2581 (defstruct (js2-return-node
2582 (:include js2-node)
2583 (:constructor nil)
2584 (:constructor make-js2-return-node (&key (type js2-RETURN)
2585 (pos js2-ts-cursor)
2586 len
2587 retval)))
2588 "AST node for a return statement."
2589 retval) ; expression to return, or 'undefined
2590
2591 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2592 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2593
2594 (defun js2-visit-return-node (n v)
2595 (js2-visit-ast (js2-return-node-retval n) v))
2596
2597 (defun js2-print-return-node (n i)
2598 (insert (js2-make-pad i) "return")
2599 (when (js2-return-node-retval n)
2600 (insert " ")
2601 (js2-print-ast (js2-return-node-retval n) 0))
2602 (insert ";\n"))
2603
2604 (defstruct (js2-if-node
2605 (:include js2-node)
2606 (:constructor nil)
2607 (:constructor make-js2-if-node (&key (type js2-IF)
2608 (pos js2-ts-cursor)
2609 len condition
2610 then-part
2611 else-pos
2612 else-part lp
2613 rp)))
2614 "AST node for an if-statement."
2615 condition ; expression
2616 then-part ; statement or block
2617 else-pos ; optional buffer position of 'else' keyword
2618 else-part ; optional statement or block
2619 lp ; position of left-paren, nil if omitted
2620 rp) ; position of right-paren, nil if omitted
2621
2622 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2623 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2624
2625 (defun js2-visit-if-node (n v)
2626 (js2-visit-ast (js2-if-node-condition n) v)
2627 (js2-visit-ast (js2-if-node-then-part n) v)
2628 (js2-visit-ast (js2-if-node-else-part n) v))
2629
2630 (defun js2-print-if-node (n i)
2631 (let ((pad (js2-make-pad i))
2632 (then-part (js2-if-node-then-part n))
2633 (else-part (js2-if-node-else-part n)))
2634 (insert pad "if (")
2635 (js2-print-ast (js2-if-node-condition n) 0)
2636 (insert ") {\n")
2637 (js2-print-body then-part (1+ i))
2638 (insert pad "}")
2639 (cond
2640 ((not else-part)
2641 (insert "\n"))
2642 ((js2-if-node-p else-part)
2643 (insert " else ")
2644 (js2-print-body else-part i))
2645 (t
2646 (insert " else {\n")
2647 (js2-print-body else-part (1+ i))
2648 (insert pad "}\n")))))
2649
2650 (defstruct (js2-try-node
2651 (:include js2-node)
2652 (:constructor nil)
2653 (:constructor make-js2-try-node (&key (type js2-TRY)
2654 (pos js2-ts-cursor)
2655 len
2656 try-block
2657 catch-clauses
2658 finally-block)))
2659 "AST node for a try-statement."
2660 try-block
2661 catch-clauses ; a Lisp list of `js2-catch-node'
2662 finally-block) ; a `js2-finally-node'
2663
2664 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2665 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2666
2667 (defun js2-visit-try-node (n v)
2668 (js2-visit-ast (js2-try-node-try-block n) v)
2669 (dolist (clause (js2-try-node-catch-clauses n))
2670 (js2-visit-ast clause v))
2671 (js2-visit-ast (js2-try-node-finally-block n) v))
2672
2673 (defun js2-print-try-node (n i)
2674 (let ((pad (js2-make-pad i))
2675 (catches (js2-try-node-catch-clauses n))
2676 (finally (js2-try-node-finally-block n)))
2677 (insert pad "try {\n")
2678 (js2-print-body (js2-try-node-try-block n) (1+ i))
2679 (insert pad "}")
2680 (when catches
2681 (dolist (catch catches)
2682 (js2-print-ast catch i)))
2683 (if finally
2684 (js2-print-ast finally i)
2685 (insert "\n"))))
2686
2687 (defstruct (js2-catch-node
2688 (:include js2-node)
2689 (:constructor nil)
2690 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2691 (pos js2-ts-cursor)
2692 len
2693 param
2694 guard-kwd
2695 guard-expr
2696 block lp
2697 rp)))
2698 "AST node for a catch clause."
2699 param ; destructuring form or simple name node
2700 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2701 guard-expr ; catch condition, a `js2-node'
2702 block ; statements, a `js2-block-node'
2703 lp ; buffer position of left-paren, nil if omitted
2704 rp) ; buffer position of right-paren, nil if omitted
2705
2706 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2707 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2708
2709 (defun js2-visit-catch-node (n v)
2710 (js2-visit-ast (js2-catch-node-param n) v)
2711 (when (js2-catch-node-guard-kwd n)
2712 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2713 (js2-visit-ast (js2-catch-node-block n) v))
2714
2715 (defun js2-print-catch-node (n i)
2716 (let ((pad (js2-make-pad i))
2717 (guard-kwd (js2-catch-node-guard-kwd n))
2718 (guard-expr (js2-catch-node-guard-expr n)))
2719 (insert " catch (")
2720 (js2-print-ast (js2-catch-node-param n) 0)
2721 (when guard-kwd
2722 (insert " if ")
2723 (js2-print-ast guard-expr 0))
2724 (insert ") {\n")
2725 (js2-print-body (js2-catch-node-block n) (1+ i))
2726 (insert pad "}")))
2727
2728 (defstruct (js2-finally-node
2729 (:include js2-node)
2730 (:constructor nil)
2731 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2732 (pos js2-ts-cursor)
2733 len body)))
2734 "AST node for a finally clause."
2735 body) ; a `js2-node', often but not always a block node
2736
2737 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2738 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2739
2740 (defun js2-visit-finally-node (n v)
2741 (js2-visit-ast (js2-finally-node-body n) v))
2742
2743 (defun js2-print-finally-node (n i)
2744 (let ((pad (js2-make-pad i)))
2745 (insert " finally {\n")
2746 (js2-print-body (js2-finally-node-body n) (1+ i))
2747 (insert pad "}\n")))
2748
2749 (defstruct (js2-switch-node
2750 (:include js2-node)
2751 (:constructor nil)
2752 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2753 (pos js2-ts-cursor)
2754 len
2755 discriminant
2756 cases lp
2757 rp)))
2758 "AST node for a switch statement."
2759 discriminant ; a `js2-node' (switch expression)
2760 cases ; a Lisp list of `js2-case-node'
2761 lp ; position of open-paren for discriminant, nil if omitted
2762 rp) ; position of close-paren for discriminant, nil if omitted
2763
2764 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2765 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2766
2767 (defun js2-visit-switch-node (n v)
2768 (js2-visit-ast (js2-switch-node-discriminant n) v)
2769 (dolist (c (js2-switch-node-cases n))
2770 (js2-visit-ast c v)))
2771
2772 (defun js2-print-switch-node (n i)
2773 (let ((pad (js2-make-pad i))
2774 (cases (js2-switch-node-cases n)))
2775 (insert pad "switch (")
2776 (js2-print-ast (js2-switch-node-discriminant n) 0)
2777 (insert ") {\n")
2778 (dolist (case cases)
2779 (js2-print-ast case i))
2780 (insert pad "}\n")))
2781
2782 (defstruct (js2-case-node
2783 (:include js2-block-node)
2784 (:constructor nil)
2785 (:constructor make-js2-case-node (&key (type js2-CASE)
2786 (pos js2-ts-cursor)
2787 len kids expr)))
2788 "AST node for a case clause of a switch statement."
2789 expr) ; the case expression (nil for default)
2790
2791 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2792 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2793
2794 (defun js2-visit-case-node (n v)
2795 (js2-visit-ast (js2-case-node-expr n) v)
2796 (js2-visit-block n v))
2797
2798 (defun js2-print-case-node (n i)
2799 (let ((pad (js2-make-pad i))
2800 (expr (js2-case-node-expr n)))
2801 (insert pad)
2802 (if (null expr)
2803 (insert "default:\n")
2804 (insert "case ")
2805 (js2-print-ast expr 0)
2806 (insert ":\n"))
2807 (dolist (kid (js2-case-node-kids n))
2808 (js2-print-ast kid (1+ i)))))
2809
2810 (defstruct (js2-throw-node
2811 (:include js2-node)
2812 (:constructor nil)
2813 (:constructor make-js2-throw-node (&key (type js2-THROW)
2814 (pos js2-ts-cursor)
2815 len expr)))
2816 "AST node for a throw statement."
2817 expr) ; the expression to throw
2818
2819 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2820 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2821
2822 (defun js2-visit-throw-node (n v)
2823 (js2-visit-ast (js2-throw-node-expr n) v))
2824
2825 (defun js2-print-throw-node (n i)
2826 (insert (js2-make-pad i) "throw ")
2827 (js2-print-ast (js2-throw-node-expr n) 0)
2828 (insert ";\n"))
2829
2830 (defstruct (js2-with-node
2831 (:include js2-node)
2832 (:constructor nil)
2833 (:constructor make-js2-with-node (&key (type js2-WITH)
2834 (pos js2-ts-cursor)
2835 len object
2836 body lp rp)))
2837 "AST node for a with-statement."
2838 object
2839 body
2840 lp ; buffer position of left-paren around object, nil if omitted
2841 rp) ; buffer position of right-paren around object, nil if omitted
2842
2843 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2844 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2845
2846 (defun js2-visit-with-node (n v)
2847 (js2-visit-ast (js2-with-node-object n) v)
2848 (js2-visit-ast (js2-with-node-body n) v))
2849
2850 (defun js2-print-with-node (n i)
2851 (let ((pad (js2-make-pad i)))
2852 (insert pad "with (")
2853 (js2-print-ast (js2-with-node-object n) 0)
2854 (insert ") {\n")
2855 (js2-print-body (js2-with-node-body n) (1+ i))
2856 (insert pad "}\n")))
2857
2858 (defstruct (js2-label-node
2859 (:include js2-node)
2860 (:constructor nil)
2861 (:constructor make-js2-label-node (&key (type js2-LABEL)
2862 (pos js2-ts-cursor)
2863 len name)))
2864 "AST node for a statement label or case label."
2865 name ; a string
2866 loop) ; for validating and code-generating continue-to-label
2867
2868 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2869 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2870
2871 (defun js2-print-label (n i)
2872 (insert (js2-make-pad i)
2873 (js2-label-node-name n)
2874 ":\n"))
2875
2876 (defstruct (js2-labeled-stmt-node
2877 (:include js2-node)
2878 (:constructor nil)
2879 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2880 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2881 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2882 (pos js2-ts-cursor)
2883 len labels stmt)))
2884 "AST node for a statement with one or more labels.
2885 Multiple labels for a statement are collapsed into the labels field."
2886 labels ; Lisp list of `js2-label-node'
2887 stmt) ; the statement these labels are for
2888
2889 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2890 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2891
2892 (defun js2-get-label-by-name (lbl-stmt name)
2893 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2894 Returns nil if no such label is in the list."
2895 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2896 result)
2897 (while (and label-list (not result))
2898 (if (string= (js2-label-node-name (car label-list)) name)
2899 (setq result (car label-list))
2900 (setq label-list (cdr label-list))))
2901 result))
2902
2903 (defun js2-visit-labeled-stmt (n v)
2904 (dolist (label (js2-labeled-stmt-node-labels n))
2905 (js2-visit-ast label v))
2906 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2907
2908 (defun js2-print-labeled-stmt (n i)
2909 (dolist (label (js2-labeled-stmt-node-labels n))
2910 (js2-print-ast label i))
2911 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2912
2913 (defun js2-labeled-stmt-node-contains (node label)
2914 "Return t if NODE contains LABEL in its label set.
2915 NODE is a `js2-labels-node'. LABEL is an identifier."
2916 (loop for nl in (js2-labeled-stmt-node-labels node)
2917 if (string= label (js2-label-node-name nl))
2918 return t
2919 finally return nil))
2920
2921 (defsubst js2-labeled-stmt-node-add-label (node label)
2922 "Add a `js2-label-node' to the label set for this statement."
2923 (setf (js2-labeled-stmt-node-labels node)
2924 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2925
2926 (defstruct (js2-jump-node
2927 (:include js2-node)
2928 (:constructor nil))
2929 "Abstract supertype of break and continue nodes."
2930 label ; `js2-name-node' for location of label identifier, if present
2931 target) ; target js2-labels-node or loop/switch statement
2932
2933 (defun js2-visit-jump-node (n v)
2934 ;; We don't visit the target, since it's a back-link.
2935 (js2-visit-ast (js2-jump-node-label n) v))
2936
2937 (defstruct (js2-break-node
2938 (:include js2-jump-node)
2939 (:constructor nil)
2940 (:constructor make-js2-break-node (&key (type js2-BREAK)
2941 (pos js2-ts-cursor)
2942 len label target)))
2943 "AST node for a break statement.
2944 The label field is a `js2-name-node', possibly nil, for the named label
2945 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2946 is the target of the break - a label node or enclosing loop/switch statement.")
2947
2948 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2949 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2950
2951 (defun js2-print-break-node (n i)
2952 (insert (js2-make-pad i) "break")
2953 (when (js2-break-node-label n)
2954 (insert " ")
2955 (js2-print-ast (js2-break-node-label n) 0))
2956 (insert ";\n"))
2957
2958 (defstruct (js2-continue-node
2959 (:include js2-jump-node)
2960 (:constructor nil)
2961 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2962 (pos js2-ts-cursor)
2963 len label target)))
2964 "AST node for a continue statement.
2965 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2966 It is nil if continue specifies no label. The target field is the jump target:
2967 a `js2-label-node' or the innermost enclosing loop.")
2968
2969 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2970 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2971
2972 (defun js2-print-continue-node (n i)
2973 (insert (js2-make-pad i) "continue")
2974 (when (js2-continue-node-label n)
2975 (insert " ")
2976 (js2-print-ast (js2-continue-node-label n) 0))
2977 (insert ";\n"))
2978
2979 (defstruct (js2-function-node
2980 (:include js2-script-node)
2981 (:constructor nil)
2982 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2983 (pos js2-ts-cursor)
2984 len
2985 (ftype 'FUNCTION)
2986 (form 'FUNCTION_STATEMENT)
2987 (name "")
2988 params rest-p
2989 body
2990 generator-type
2991 lp rp)))
2992 "AST node for a function declaration.
2993 The `params' field is a Lisp list of nodes. Each node is either a simple
2994 `js2-name-node', or if it's a destructuring-assignment parameter, a
2995 `js2-array-node' or `js2-object-node'."
2996 ftype ; FUNCTION, GETTER or SETTER
2997 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2998 name ; function name (a `js2-name-node', or nil if anonymous)
2999 params ; a Lisp list of destructuring forms or simple name nodes
3000 rest-p ; if t, the last parameter is rest parameter
3001 body ; a `js2-block-node' or expression node (1.8 only)
3002 lp ; position of arg-list open-paren, or nil if omitted
3003 rp ; position of arg-list close-paren, or nil if omitted
3004 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3005 needs-activation ; t if we need an activation object for this frame
3006 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3007 member-expr) ; nonstandard Ecma extension from Rhino
3008
3009 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3010 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3011
3012 (defun js2-visit-function-node (n v)
3013 (js2-visit-ast (js2-function-node-name n) v)
3014 (dolist (p (js2-function-node-params n))
3015 (js2-visit-ast p v))
3016 (js2-visit-ast (js2-function-node-body n) v))
3017
3018 (defun js2-print-function-node (n i)
3019 (let* ((pad (js2-make-pad i))
3020 (getter (js2-node-get-prop n 'GETTER_SETTER))
3021 (name (or (js2-function-node-name n)
3022 (js2-function-node-member-expr n)))
3023 (params (js2-function-node-params n))
3024 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3025 (rest-p (js2-function-node-rest-p n))
3026 (body (js2-function-node-body n))
3027 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3028 (unless (or getter arrow)
3029 (insert pad "function")
3030 (when (eq (js2-function-node-generator-type n) 'STAR)
3031 (insert "*")))
3032 (when name
3033 (insert " ")
3034 (js2-print-ast name 0))
3035 (insert "(")
3036 (loop with len = (length params)
3037 for param in params
3038 for count from 1
3039 do
3040 (when (and rest-p (= count len))
3041 (insert "..."))
3042 (js2-print-ast param 0)
3043 (when (< count len)
3044 (insert ", ")))
3045 (insert ") ")
3046 (when arrow
3047 (insert "=> "))
3048 (insert "{")
3049 ;; TODO: fix this to be smarter about indenting, etc.
3050 (unless expr
3051 (insert "\n"))
3052 (if (js2-block-node-p body)
3053 (js2-print-body body (1+ i))
3054 (js2-print-ast body 0))
3055 (insert pad "}")
3056 (unless expr
3057 (insert "\n"))))
3058
3059 (defun js2-function-name (node)
3060 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3061 (and (js2-function-node-name node)
3062 (js2-name-node-name (js2-function-node-name node))))
3063
3064 ;; Having this be an expression node makes it more flexible.
3065 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3066 ;; that work better if you assume it's an expression. Whenever we have
3067 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3068 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3069 (defstruct (js2-var-decl-node
3070 (:include js2-node)
3071 (:constructor nil)
3072 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3073 (pos (js2-current-token-beg))
3074 len kids
3075 decl-type)))
3076 "AST node for a variable declaration list (VAR, CONST or LET).
3077 The node bounds differ depending on the declaration type. For VAR or
3078 CONST declarations, the bounds include the var/const keyword. For LET
3079 declarations, the node begins at the position of the first child."
3080 kids ; a Lisp list of `js2-var-init-node' structs.
3081 decl-type) ; js2-VAR, js2-CONST or js2-LET
3082
3083 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3084 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3085
3086 (defun js2-visit-var-decl (n v)
3087 (dolist (kid (js2-var-decl-node-kids n))
3088 (js2-visit-ast kid v)))
3089
3090 (defun js2-print-var-decl (n i)
3091 (let ((pad (js2-make-pad i))
3092 (tt (js2-var-decl-node-decl-type n)))
3093 (insert pad)
3094 (insert (cond
3095 ((= tt js2-VAR) "var ")
3096 ((= tt js2-LET) "let ")
3097 ((= tt js2-CONST) "const ")
3098 (t
3099 (error "malformed var-decl node"))))
3100 (loop with kids = (js2-var-decl-node-kids n)
3101 with len = (length kids)
3102 for kid in kids
3103 for count from 1
3104 do
3105 (js2-print-ast kid 0)
3106 (if (< count len)
3107 (insert ", ")))))
3108
3109 (defstruct (js2-var-init-node
3110 (:include js2-node)
3111 (:constructor nil)
3112 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3113 (pos js2-ts-cursor)
3114 len target
3115 initializer)))
3116 "AST node for a variable declaration.
3117 The type field will be js2-CONST for a const decl."
3118 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3119 initializer) ; initializer expression, a `js2-node'
3120
3121 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3122 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3123
3124 (defun js2-visit-var-init-node (n v)
3125 (js2-visit-ast (js2-var-init-node-target n) v)
3126 (js2-visit-ast (js2-var-init-node-initializer n) v))
3127
3128 (defun js2-print-var-init-node (n i)
3129 (let ((pad (js2-make-pad i))
3130 (name (js2-var-init-node-target n))
3131 (init (js2-var-init-node-initializer n)))
3132 (insert pad)
3133 (js2-print-ast name 0)
3134 (when init
3135 (insert " = ")
3136 (js2-print-ast init 0))))
3137
3138 (defstruct (js2-cond-node
3139 (:include js2-node)
3140 (:constructor nil)
3141 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3142 (pos js2-ts-cursor)
3143 len
3144 test-expr
3145 true-expr
3146 false-expr
3147 q-pos c-pos)))
3148 "AST node for the ternary operator"
3149 test-expr
3150 true-expr
3151 false-expr
3152 q-pos ; buffer position of ?
3153 c-pos) ; buffer position of :
3154
3155 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3156 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3157
3158 (defun js2-visit-cond-node (n v)
3159 (js2-visit-ast (js2-cond-node-test-expr n) v)
3160 (js2-visit-ast (js2-cond-node-true-expr n) v)
3161 (js2-visit-ast (js2-cond-node-false-expr n) v))
3162
3163 (defun js2-print-cond-node (n i)
3164 (let ((pad (js2-make-pad i)))
3165 (insert pad)
3166 (js2-print-ast (js2-cond-node-test-expr n) 0)
3167 (insert " ? ")
3168 (js2-print-ast (js2-cond-node-true-expr n) 0)
3169 (insert " : ")
3170 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3171
3172 (defstruct (js2-infix-node
3173 (:include js2-node)
3174 (:constructor nil)
3175 (:constructor make-js2-infix-node (&key type
3176 (pos js2-ts-cursor)
3177 len op-pos
3178 left right)))
3179 "Represents infix expressions.
3180 Includes assignment ops like `|=', and the comma operator.
3181 The type field inherited from `js2-node' holds the operator."
3182 op-pos ; buffer position where operator begins
3183 left ; any `js2-node'
3184 right) ; any `js2-node'
3185
3186 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3187 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3188
3189 (defun js2-visit-infix-node (n v)
3190 (js2-visit-ast (js2-infix-node-left n) v)
3191 (js2-visit-ast (js2-infix-node-right n) v))
3192
3193 (defconst js2-operator-tokens
3194 (let ((table (make-hash-table :test 'eq))
3195 (tokens
3196 (list (cons js2-IN "in")
3197 (cons js2-TYPEOF "typeof")
3198 (cons js2-INSTANCEOF "instanceof")
3199 (cons js2-DELPROP "delete")
3200 (cons js2-COMMA ",")
3201 (cons js2-COLON ":")
3202 (cons js2-OR "||")
3203 (cons js2-AND "&&")
3204 (cons js2-INC "++")
3205 (cons js2-DEC "--")
3206 (cons js2-BITOR "|")
3207 (cons js2-BITXOR "^")
3208 (cons js2-BITAND "&")
3209 (cons js2-EQ "==")
3210 (cons js2-NE "!=")
3211 (cons js2-LT "<")
3212 (cons js2-LE "<=")
3213 (cons js2-GT ">")
3214 (cons js2-GE ">=")
3215 (cons js2-LSH "<<")
3216 (cons js2-RSH ">>")
3217 (cons js2-URSH ">>>")
3218 (cons js2-ADD "+") ; infix plus
3219 (cons js2-SUB "-") ; infix minus
3220 (cons js2-MUL "*")
3221 (cons js2-DIV "/")
3222 (cons js2-MOD "%")
3223 (cons js2-NOT "!")
3224 (cons js2-BITNOT "~")
3225 (cons js2-POS "+") ; unary plus
3226 (cons js2-NEG "-") ; unary minus
3227 (cons js2-TRIPLEDOT "...")
3228 (cons js2-SHEQ "===") ; shallow equality
3229 (cons js2-SHNE "!==") ; shallow inequality
3230 (cons js2-ASSIGN "=")
3231 (cons js2-ASSIGN_BITOR "|=")
3232 (cons js2-ASSIGN_BITXOR "^=")
3233 (cons js2-ASSIGN_BITAND "&=")
3234 (cons js2-ASSIGN_LSH "<<=")
3235 (cons js2-ASSIGN_RSH ">>=")
3236 (cons js2-ASSIGN_URSH ">>>=")
3237 (cons js2-ASSIGN_ADD "+=")
3238 (cons js2-ASSIGN_SUB "-=")
3239 (cons js2-ASSIGN_MUL "*=")
3240 (cons js2-ASSIGN_DIV "/=")
3241 (cons js2-ASSIGN_MOD "%="))))
3242 (loop for (k . v) in tokens do
3243 (puthash k v table))
3244 table))
3245
3246 (defun js2-print-infix-node (n i)
3247 (let* ((tt (js2-node-type n))
3248 (op (gethash tt js2-operator-tokens)))
3249 (unless op
3250 (error "unrecognized infix operator %s" (js2-node-type n)))
3251 (insert (js2-make-pad i))
3252 (js2-print-ast (js2-infix-node-left n) 0)
3253 (unless (= tt js2-COMMA)
3254 (insert " "))
3255 (insert op)
3256 (insert " ")
3257 (js2-print-ast (js2-infix-node-right n) 0)))
3258
3259 (defstruct (js2-assign-node
3260 (:include js2-infix-node)
3261 (:constructor nil)
3262 (:constructor make-js2-assign-node (&key type
3263 (pos js2-ts-cursor)
3264 len op-pos
3265 left right)))
3266 "Represents any assignment.
3267 The type field holds the actual assignment operator.")
3268
3269 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3270 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3271
3272 (defstruct (js2-unary-node
3273 (:include js2-node)
3274 (:constructor nil)
3275 (:constructor make-js2-unary-node (&key type ; required
3276 (pos js2-ts-cursor)
3277 len operand)))
3278 "AST node type for unary operator nodes.
3279 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3280 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3281 property is added if the operator follows the operand."
3282 operand) ; a `js2-node' expression
3283
3284 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3285 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3286
3287 (defun js2-visit-unary-node (n v)
3288 (js2-visit-ast (js2-unary-node-operand n) v))
3289
3290 (defun js2-print-unary-node (n i)
3291 (let* ((tt (js2-node-type n))
3292 (op (gethash tt js2-operator-tokens))
3293 (postfix (js2-node-get-prop n 'postfix)))
3294 (unless op
3295 (error "unrecognized unary operator %s" tt))
3296 (insert (js2-make-pad i))
3297 (unless postfix
3298 (insert op))
3299 (if (or (= tt js2-TYPEOF)
3300 (= tt js2-DELPROP))
3301 (insert " "))
3302 (js2-print-ast (js2-unary-node-operand n) 0)
3303 (when postfix
3304 (insert op))))
3305
3306 (defstruct (js2-let-node
3307 (:include js2-scope)
3308 (:constructor nil)
3309 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3310 (pos (js2-current-token-beg))
3311 len vars body
3312 lp rp)))
3313 "AST node for a let expression or a let statement.
3314 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3315 vars ; a `js2-var-decl-node'
3316 body ; a `js2-node' representing the expression or body block
3317 lp
3318 rp)
3319
3320 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3321 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3322
3323 (defun js2-visit-let-node (n v)
3324 (js2-visit-ast (js2-let-node-vars n) v)
3325 (js2-visit-ast (js2-let-node-body n) v))
3326
3327 (defun js2-print-let-node (n i)
3328 (insert (js2-make-pad i) "let (")
3329 (let ((p (point)))
3330 (js2-print-ast (js2-let-node-vars n) 0)
3331 (delete-region p (+ p 4)))
3332 (insert ") ")
3333 (js2-print-ast (js2-let-node-body n) i))
3334
3335 (defstruct (js2-keyword-node
3336 (:include js2-node)
3337 (:constructor nil)
3338 (:constructor make-js2-keyword-node (&key type
3339 (pos (js2-current-token-beg))
3340 (len (- js2-ts-cursor pos)))))
3341 "AST node representing a literal keyword such as `null'.
3342 Used for `null', `this', `true', `false' and `debugger'.
3343 The node type is set to js2-NULL, js2-THIS, etc.")
3344
3345 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3346 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3347
3348 (defun js2-print-keyword-node (n i)
3349 (insert (js2-make-pad i)
3350 (let ((tt (js2-node-type n)))
3351 (cond
3352 ((= tt js2-THIS) "this")
3353 ((= tt js2-NULL) "null")
3354 ((= tt js2-TRUE) "true")
3355 ((= tt js2-FALSE) "false")
3356 ((= tt js2-DEBUGGER) "debugger")
3357 (t (error "Invalid keyword literal type: %d" tt))))))
3358
3359 (defsubst js2-this-node-p (node)
3360 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3361 (eq (js2-node-type node) js2-THIS))
3362
3363 (defstruct (js2-new-node
3364 (:include js2-node)
3365 (:constructor nil)
3366 (:constructor make-js2-new-node (&key (type js2-NEW)
3367 (pos (js2-current-token-beg))
3368 len target
3369 args initializer
3370 lp rp)))
3371 "AST node for new-expression such as new Foo()."
3372 target ; an identifier or reference
3373 args ; a Lisp list of argument nodes
3374 lp ; position of left-paren, nil if omitted
3375 rp ; position of right-paren, nil if omitted
3376 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3377
3378 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3379 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3380
3381 (defun js2-visit-new-node (n v)
3382 (js2-visit-ast (js2-new-node-target n) v)
3383 (dolist (arg (js2-new-node-args n))
3384 (js2-visit-ast arg v))
3385 (js2-visit-ast (js2-new-node-initializer n) v))
3386
3387 (defun js2-print-new-node (n i)
3388 (insert (js2-make-pad i) "new ")
3389 (js2-print-ast (js2-new-node-target n))
3390 (insert "(")
3391 (js2-print-list (js2-new-node-args n))
3392 (insert ")")
3393 (when (js2-new-node-initializer n)
3394 (insert " ")
3395 (js2-print-ast (js2-new-node-initializer n))))
3396
3397 (defstruct (js2-name-node
3398 (:include js2-node)
3399 (:constructor nil)
3400 (:constructor make-js2-name-node (&key (type js2-NAME)
3401 (pos (js2-current-token-beg))
3402 (len (- js2-ts-cursor
3403 (js2-current-token-beg)))
3404 (name (js2-current-token-string)))))
3405 "AST node for a JavaScript identifier"
3406 name ; a string
3407 scope) ; a `js2-scope' (optional, used for codegen)
3408
3409 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3410 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3411
3412 (defun js2-print-name-node (n i)
3413 (insert (js2-make-pad i)
3414 (js2-name-node-name n)))
3415
3416 (defsubst js2-name-node-length (node)
3417 "Return identifier length of NODE, a `js2-name-node'.
3418 Returns 0 if NODE is nil or its identifier field is nil."
3419 (if node
3420 (length (js2-name-node-name node))
3421 0))
3422
3423 (defstruct (js2-number-node
3424 (:include js2-node)
3425 (:constructor nil)
3426 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3427 (pos (js2-current-token-beg))
3428 (len (- js2-ts-cursor
3429 (js2-current-token-beg)))
3430 (value (js2-current-token-string))
3431 (num-value (js2-token-number
3432 (js2-current-token))))))
3433 "AST node for a number literal."
3434 value ; the original string, e.g. "6.02e23"
3435 num-value) ; the parsed number value
3436
3437 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3438 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3439
3440 (defun js2-print-number-node (n i)
3441 (insert (js2-make-pad i)
3442 (number-to-string (js2-number-node-num-value n))))
3443
3444 (defstruct (js2-regexp-node
3445 (:include js2-node)
3446 (:constructor nil)
3447 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3448 (pos (js2-current-token-beg))
3449 (len (- js2-ts-cursor
3450 (js2-current-token-beg)))
3451 value flags)))
3452 "AST node for a regular expression literal."
3453 value ; the regexp string, without // delimiters
3454 flags) ; a string of flags, e.g. `mi'.
3455
3456 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3457 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3458
3459 (defun js2-print-regexp (n i)
3460 (insert (js2-make-pad i)
3461 "/"
3462 (js2-regexp-node-value n)
3463 "/")
3464 (if (js2-regexp-node-flags n)
3465 (insert (js2-regexp-node-flags n))))
3466
3467 (defstruct (js2-string-node
3468 (:include js2-node)
3469 (:constructor nil)
3470 (:constructor make-js2-string-node (&key (type js2-STRING)
3471 (pos (js2-current-token-beg))
3472 (len (- js2-ts-cursor
3473 (js2-current-token-beg)))
3474 (value (js2-current-token-string)))))
3475 "String literal.
3476 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3477 You can tell the quote type by looking at the first character."
3478 value) ; the characters of the string, including the quotes
3479
3480 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3481 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3482
3483 (defun js2-print-string-node (n i)
3484 (insert (js2-make-pad i)
3485 (js2-node-string n)))
3486
3487 (defstruct (js2-array-node
3488 (:include js2-node)
3489 (:constructor nil)
3490 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3491 (pos js2-ts-cursor)
3492 len elems)))
3493 "AST node for an array literal."
3494 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3495
3496 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3497 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3498
3499 (defun js2-visit-array-node (n v)
3500 (dolist (e (js2-array-node-elems n))
3501 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3502
3503 (defun js2-print-array-node (n i)
3504 (insert (js2-make-pad i) "[")
3505 (let ((elems (js2-array-node-elems n)))
3506 (js2-print-list elems)
3507 (when (and elems (null (car (last elems))))
3508 (insert ",")))
3509 (insert "]"))
3510
3511 (defstruct (js2-class-node
3512 (:include js2-node)
3513 (:constructor nil)
3514 (:constructor make-js2-class-node (&key (type js2-CLASS)
3515 (pos js2-ts-cursor)
3516 (form 'CLASS_STATEMENT)
3517 (name "")
3518 extends len elems)))
3519 "AST node for an class expression.
3520 `elems' is a list of `js2-object-prop-node', and `extends' is an
3521 optional `js2-expr-node'"
3522 form ; CLASS_{STATEMENT|EXPRESSION}
3523 name ; class name (a `js2-node-name', or nil if anonymous)
3524 extends ; class heritage (a `js2-expr-node', or nil if none)
3525 elems)
3526
3527 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3528 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3529
3530 (defun js2-visit-class-node (n v)
3531 (js2-visit-ast (js2-class-node-name n) v)
3532 (js2-visit-ast (js2-class-node-extends n) v)
3533 (dolist (e (js2-class-node-elems n))
3534 (js2-visit-ast e v)))
3535
3536 (defun js2-print-class-node (n i)
3537 (let* ((pad (js2-make-pad i))
3538 (name (js2-class-node-name n))
3539 (extends (js2-class-node-extends n))
3540 (elems (js2-class-node-elems n)))
3541 (insert pad "class")
3542 (when name
3543 (insert " ")
3544 (js2-print-ast name 0))
3545 (when extends
3546 (insert " extends ")
3547 (js2-print-ast extends))
3548 (insert " {")
3549 (dolist (elem elems)
3550 (insert "\n")
3551 (js2-print-ast elem (1+ i)))
3552 (insert "\n" pad "}")))
3553
3554 (defstruct (js2-object-node
3555 (:include js2-node)
3556 (:constructor nil)
3557 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3558 (pos js2-ts-cursor)
3559 len
3560 elems)))
3561 "AST node for an object literal expression.
3562 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3563 The latter represents abbreviation in destructuring expressions."
3564 elems)
3565
3566 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3567 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3568
3569 (defun js2-visit-object-node (n v)
3570 (dolist (e (js2-object-node-elems n))
3571 (js2-visit-ast e v)))
3572
3573 (defun js2-print-object-node (n i)
3574 (insert (js2-make-pad i) "{")
3575 (js2-print-list (js2-object-node-elems n))
3576 (insert "}"))
3577
3578 (defstruct (js2-object-prop-node
3579 (:include js2-infix-node)
3580 (:constructor nil)
3581 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3582 (pos js2-ts-cursor)
3583 len left
3584 right op-pos)))
3585 "AST node for an object literal prop:value entry.
3586 The `left' field is the property: a name node, string node or number node.
3587 The `right' field is a `js2-node' representing the initializer value.")
3588
3589 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3590 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3591
3592 (defun js2-print-object-prop-node (n i)
3593 (let* ((left (js2-object-prop-node-left n))
3594 (computed (not (or (js2-string-node-p left)
3595 (js2-number-node-p left)
3596 (js2-name-node-p left)))))
3597 (insert (js2-make-pad i))
3598 (if computed
3599 (insert "["))
3600 (js2-print-ast left 0)
3601 (if computed
3602 (insert "]"))
3603 (if (not (js2-node-get-prop n 'SHORTHAND))
3604 (progn
3605 (insert ": ")
3606 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3607
3608 (defstruct (js2-getter-setter-node
3609 (:include js2-infix-node)
3610 (:constructor nil)
3611 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3612 (pos js2-ts-cursor)
3613 len left right)))
3614 "AST node for a getter/setter property in an object literal.
3615 The `left' field is the `js2-name-node' naming the getter/setter prop.
3616 The `right' field is always an anonymous `js2-function-node' with a node
3617 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3618
3619 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3620 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3621
3622 (defun js2-print-getter-setter (n i)
3623 (let ((pad (js2-make-pad i))
3624 (left (js2-getter-setter-node-left n))
3625 (right (js2-getter-setter-node-right n)))
3626 (insert pad)
3627 (if (/= (js2-node-type n) js2-FUNCTION)
3628 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3629 (js2-print-ast left 0)
3630 (js2-print-ast right 0)))
3631
3632 (defstruct (js2-prop-get-node
3633 (:include js2-infix-node)
3634 (:constructor nil)
3635 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3636 (pos js2-ts-cursor)
3637 len left right)))
3638 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3639
3640 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3641 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3642
3643 (defun js2-visit-prop-get-node (n v)
3644 (js2-visit-ast (js2-prop-get-node-left n) v)
3645 (js2-visit-ast (js2-prop-get-node-right n) v))
3646
3647 (defun js2-print-prop-get-node (n i)
3648 (insert (js2-make-pad i))
3649 (js2-print-ast (js2-prop-get-node-left n) 0)
3650 (insert ".")
3651 (js2-print-ast (js2-prop-get-node-right n) 0))
3652
3653 (defstruct (js2-elem-get-node
3654 (:include js2-node)
3655 (:constructor nil)
3656 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3657 (pos js2-ts-cursor)
3658 len target element
3659 lb rb)))
3660 "AST node for an array index expression such as foo[bar]."
3661 target ; a `js2-node' - the expression preceding the "."
3662 element ; a `js2-node' - the expression in brackets
3663 lb ; position of left-bracket, nil if omitted
3664 rb) ; position of right-bracket, nil if omitted
3665
3666 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3667 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3668
3669 (defun js2-visit-elem-get-node (n v)
3670 (js2-visit-ast (js2-elem-get-node-target n) v)
3671 (js2-visit-ast (js2-elem-get-node-element n) v))
3672
3673 (defun js2-print-elem-get-node (n i)
3674 (insert (js2-make-pad i))
3675 (js2-print-ast (js2-elem-get-node-target n) 0)
3676 (insert "[")
3677 (js2-print-ast (js2-elem-get-node-element n) 0)
3678 (insert "]"))
3679
3680 (defstruct (js2-call-node
3681 (:include js2-node)
3682 (:constructor nil)
3683 (:constructor make-js2-call-node (&key (type js2-CALL)
3684 (pos js2-ts-cursor)
3685 len target args
3686 lp rp)))
3687 "AST node for a JavaScript function call."
3688 target ; a `js2-node' evaluating to the function to call
3689 args ; a Lisp list of `js2-node' arguments
3690 lp ; position of open-paren, or nil if missing
3691 rp) ; position of close-paren, or nil if missing
3692
3693 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3694 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3695
3696 (defun js2-visit-call-node (n v)
3697 (js2-visit-ast (js2-call-node-target n) v)
3698 (dolist (arg (js2-call-node-args n))
3699 (js2-visit-ast arg v)))
3700
3701 (defun js2-print-call-node (n i)
3702 (insert (js2-make-pad i))
3703 (js2-print-ast (js2-call-node-target n) 0)
3704 (insert "(")
3705 (js2-print-list (js2-call-node-args n))
3706 (insert ")"))
3707
3708 (defstruct (js2-yield-node
3709 (:include js2-node)
3710 (:constructor nil)
3711 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3712 (pos js2-ts-cursor)
3713 len value star-p)))
3714 "AST node for yield statement or expression."
3715 star-p ; whether it's yield*
3716 value) ; optional: value to be yielded
3717
3718 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3719 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3720
3721 (defun js2-visit-yield-node (n v)
3722 (js2-visit-ast (js2-yield-node-value n) v))
3723
3724 (defun js2-print-yield-node (n i)
3725 (insert (js2-make-pad i))
3726 (insert "yield")
3727 (when (js2-yield-node-star-p n)
3728 (insert "*"))
3729 (when (js2-yield-node-value n)
3730 (insert " ")
3731 (js2-print-ast (js2-yield-node-value n) 0)))
3732
3733 (defstruct (js2-paren-node
3734 (:include js2-node)
3735 (:constructor nil)
3736 (:constructor make-js2-paren-node (&key (type js2-LP)
3737 (pos js2-ts-cursor)
3738 len expr)))
3739 "AST node for a parenthesized expression.
3740 In particular, used when the parens are syntactically optional,
3741 as opposed to required parens such as those enclosing an if-conditional."
3742 expr) ; `js2-node'
3743
3744 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3745 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3746
3747 (defun js2-visit-paren-node (n v)
3748 (js2-visit-ast (js2-paren-node-expr n) v))
3749
3750 (defun js2-print-paren-node (n i)
3751 (insert (js2-make-pad i))
3752 (insert "(")
3753 (js2-print-ast (js2-paren-node-expr n) 0)
3754 (insert ")"))
3755
3756 (defstruct (js2-comp-node
3757 (:include js2-scope)
3758 (:constructor nil)
3759 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3760 (pos js2-ts-cursor)
3761 len result
3762 loops filters
3763 form)))
3764 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3765 result ; result expression (just after left-bracket)
3766 loops ; a Lisp list of `js2-comp-loop-node'
3767 filters ; a Lisp list of guard/filter expressions
3768 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3769 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3770 )
3771
3772 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3773 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3774
3775 (defun js2-visit-comp-node (n v)
3776 (js2-visit-ast (js2-comp-node-result n) v)
3777 (dolist (l (js2-comp-node-loops n))
3778 (js2-visit-ast l v))
3779 (dolist (f (js2-comp-node-filters n))
3780 (js2-visit-ast f v)))
3781
3782 (defun js2-print-comp-node (n i)
3783 (let ((pad (js2-make-pad i))
3784 (result (js2-comp-node-result n))
3785 (loops (js2-comp-node-loops n))
3786 (filters (js2-comp-node-filters n))
3787 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3788 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3789 (insert pad (if gen-p "(" "["))
3790 (when legacy-p
3791 (js2-print-ast result 0))
3792 (dolist (l loops)
3793 (when legacy-p
3794 (insert " "))
3795 (js2-print-ast l 0)
3796 (unless legacy-p
3797 (insert " ")))
3798 (dolist (f filters)
3799 (when legacy-p
3800 (insert " "))
3801 (insert "if (")
3802 (js2-print-ast f 0)
3803 (insert ")")
3804 (unless legacy-p
3805 (insert " ")))
3806 (unless legacy-p
3807 (js2-print-ast result 0))
3808 (insert (if gen-p ")" "]"))))
3809
3810 (defstruct (js2-comp-loop-node
3811 (:include js2-for-in-node)
3812 (:constructor nil)
3813 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3814 (pos js2-ts-cursor)
3815 len iterator
3816 object in-pos
3817 foreach-p
3818 each-pos
3819 forof-p
3820 lp rp)))
3821 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3822
3823 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3824 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3825
3826 (defun js2-visit-comp-loop (n v)
3827 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3828 (js2-visit-ast (js2-comp-loop-node-object n) v))
3829
3830 (defun js2-print-comp-loop (n _i)
3831 (insert "for ")
3832 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3833 (insert "(")
3834 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3835 (insert (if (js2-comp-loop-node-forof-p n)
3836 " of " " in "))
3837 (js2-print-ast (js2-comp-loop-node-object n) 0)
3838 (insert ")"))
3839
3840 (defstruct (js2-empty-expr-node
3841 (:include js2-node)
3842 (:constructor nil)
3843 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3844 (pos (js2-current-token-beg))
3845 len)))
3846 "AST node for an empty expression.")
3847
3848 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3849 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3850
3851 (defstruct (js2-xml-node
3852 (:include js2-block-node)
3853 (:constructor nil)
3854 (:constructor make-js2-xml-node (&key (type js2-XML)
3855 (pos (js2-current-token-beg))
3856 len kids)))
3857 "AST node for initial parse of E4X literals.
3858 The kids field is a list of XML fragments, each a `js2-string-node' or
3859 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3860
3861 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3862 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3863
3864 (defun js2-print-xml-node (n i)
3865 (dolist (kid (js2-xml-node-kids n))
3866 (js2-print-ast kid i)))
3867
3868 (defstruct (js2-xml-js-expr-node
3869 (:include js2-xml-node)
3870 (:constructor nil)
3871 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3872 (pos js2-ts-cursor)
3873 len expr)))
3874 "AST node for an embedded JavaScript {expression} in an E4X literal.
3875 The start and end fields correspond to the curly-braces."
3876 expr) ; a `js2-expr-node' of some sort
3877
3878 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3879 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3880
3881 (defun js2-visit-xml-js-expr (n v)
3882 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3883
3884 (defun js2-print-xml-js-expr (n i)
3885 (insert (js2-make-pad i))
3886 (insert "{")
3887 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3888 (insert "}"))
3889
3890 (defstruct (js2-xml-dot-query-node
3891 (:include js2-infix-node)
3892 (:constructor nil)
3893 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3894 (pos js2-ts-cursor)
3895 op-pos len left
3896 right rp)))
3897 "AST node for an E4X foo.(bar) filter expression.
3898 Note that the left-paren is automatically the character immediately
3899 following the dot (.) in the operator. No whitespace is permitted
3900 between the dot and the lp by the scanner."
3901 rp)
3902
3903 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3904 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3905
3906 (defun js2-print-xml-dot-query (n i)
3907 (insert (js2-make-pad i))
3908 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3909 (insert ".(")
3910 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3911 (insert ")"))
3912
3913 (defstruct (js2-xml-ref-node
3914 (:include js2-node)
3915 (:constructor nil)) ; abstract
3916 "Base type for E4X XML attribute-access or property-get expressions.
3917 Such expressions can take a variety of forms. The general syntax has
3918 three parts:
3919
3920 - (optional) an @ (specifying an attribute access)
3921 - (optional) a namespace (a `js2-name-node') and double-colon
3922 - (required) either a `js2-name-node' or a bracketed [expression]
3923
3924 The property-name expressions (examples: ns::name, @name) are
3925 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3926 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3927
3928 This node type (or more specifically, its subclasses) will sometimes
3929 be the right-hand child of a `js2-prop-get-node' or a
3930 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3931 The `js2-xml-ref-node' may also be a standalone primary expression with
3932 no explicit target, which is valid in certain expression contexts such as
3933
3934 company..employee.(@id < 100)
3935
3936 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3937 expression whose parent is a `js2-xml-dot-query-node'."
3938 namespace
3939 at-pos
3940 colon-pos)
3941
3942 (defsubst js2-xml-ref-node-attr-access-p (node)
3943 "Return non-nil if this expression began with an @-token."
3944 (and (numberp (js2-xml-ref-node-at-pos node))
3945 (plusp (js2-xml-ref-node-at-pos node))))
3946
3947 (defstruct (js2-xml-prop-ref-node
3948 (:include js2-xml-ref-node)
3949 (:constructor nil)
3950 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3951 (pos (js2-current-token-beg))
3952 len propname
3953 namespace at-pos
3954 colon-pos)))
3955 "AST node for an E4X XML [expr] property-ref expression.
3956 The JavaScript syntax is an optional @, an optional ns::, and a name.
3957
3958 [ '@' ] [ name '::' ] name
3959
3960 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3961 @ns::*, @*::attr, @*::*, and @*.
3962
3963 The node starts at the @ token, if present. Otherwise it starts at the
3964 namespace name. The node bounds extend through the closing right-bracket,
3965 or if it is missing due to a syntax error, through the end of the index
3966 expression."
3967 propname)
3968
3969 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3970 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3971
3972 (defun js2-visit-xml-prop-ref-node (n v)
3973 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3974 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3975
3976 (defun js2-print-xml-prop-ref-node (n i)
3977 (insert (js2-make-pad i))
3978 (if (js2-xml-ref-node-attr-access-p n)
3979 (insert "@"))
3980 (when (js2-xml-prop-ref-node-namespace n)
3981 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3982 (insert "::"))
3983 (if (js2-xml-prop-ref-node-propname n)
3984 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3985
3986 (defstruct (js2-xml-elem-ref-node
3987 (:include js2-xml-ref-node)
3988 (:constructor nil)
3989 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3990 (pos (js2-current-token-beg))
3991 len expr lb rb
3992 namespace at-pos
3993 colon-pos)))
3994 "AST node for an E4X XML [expr] member-ref expression.
3995 Syntax:
3996
3997 [ '@' ] [ name '::' ] '[' expr ']'
3998
3999 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4000
4001 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4002 is not a legal E4X XML element-ref expression, since it's already used
4003 for standard JavaScript element-get array indexing. Hence, a
4004 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4005 non-nil namespace node, or both.
4006
4007 The node starts at the @ token, if present. Otherwise it starts
4008 at the namespace name. The node bounds extend through the closing
4009 right-bracket, or if it is missing due to a syntax error, through the
4010 end of the index expression."
4011 expr ; the bracketed index expression
4012 lb
4013 rb)
4014
4015 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4016 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4017
4018 (defun js2-visit-xml-elem-ref-node (n v)
4019 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4020 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4021
4022 (defun js2-print-xml-elem-ref-node (n i)
4023 (insert (js2-make-pad i))
4024 (if (js2-xml-ref-node-attr-access-p n)
4025 (insert "@"))
4026 (when (js2-xml-elem-ref-node-namespace n)
4027 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4028 (insert "::"))
4029 (insert "[")
4030 (if (js2-xml-elem-ref-node-expr n)
4031 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4032 (insert "]"))
4033
4034 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4035
4036 (defstruct (js2-xml-start-tag-node
4037 (:include js2-xml-node)
4038 (:constructor nil)
4039 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4040 (pos js2-ts-cursor)
4041 len name attrs kids
4042 empty-p)))
4043 "AST node for an XML start-tag. Not currently used.
4044 The `kids' field is a Lisp list of child content nodes."
4045 name ; a `js2-xml-name-node'
4046 attrs ; a Lisp list of `js2-xml-attr-node'
4047 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4048
4049 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4050 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4051
4052 (defun js2-visit-xml-start-tag (n v)
4053 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4054 (dolist (attr (js2-xml-start-tag-node-attrs n))
4055 (js2-visit-ast attr v))
4056 (js2-visit-block n v))
4057
4058 (defun js2-print-xml-start-tag (n i)
4059 (insert (js2-make-pad i) "<")
4060 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4061 (when (js2-xml-start-tag-node-attrs n)
4062 (insert " ")
4063 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4064 (insert ">"))
4065
4066 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4067 ;; and add the end-tag to the kids list of the parent as well.
4068 (defstruct (js2-xml-end-tag-node
4069 (:include js2-xml-node)
4070 (:constructor nil)
4071 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4072 (pos js2-ts-cursor)
4073 len name)))
4074 "AST node for an XML end-tag. Not currently used."
4075 name) ; a `js2-xml-name-node'
4076
4077 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4078 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4079
4080 (defun js2-visit-xml-end-tag (n v)
4081 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4082
4083 (defun js2-print-xml-end-tag (n i)
4084 (insert (js2-make-pad i))
4085 (insert "</")
4086 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4087 (insert ">"))
4088
4089 (defstruct (js2-xml-name-node
4090 (:include js2-xml-node)
4091 (:constructor nil)
4092 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4093 (pos js2-ts-cursor)
4094 len namespace kids)))
4095 "AST node for an E4X XML name. Not currently used.
4096 Any XML name can be qualified with a namespace, hence the namespace field.
4097 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4098 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4099 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4100 namespace) ; a `js2-string-node'
4101
4102 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4103 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4104
4105 (defun js2-visit-xml-name-node (n v)
4106 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4107
4108 (defun js2-print-xml-name-node (n i)
4109 (insert (js2-make-pad i))
4110 (when (js2-xml-name-node-namespace n)
4111 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4112 (insert "::"))
4113 (dolist (kid (js2-xml-name-node-kids n))
4114 (js2-print-ast kid 0)))
4115
4116 (defstruct (js2-xml-pi-node
4117 (:include js2-xml-node)
4118 (:constructor nil)
4119 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4120 (pos js2-ts-cursor)
4121 len name attrs)))
4122 "AST node for an E4X XML processing instruction. Not currently used."
4123 name ; a `js2-xml-name-node'
4124 attrs) ; a list of `js2-xml-attr-node'
4125
4126 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4127 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4128
4129 (defun js2-visit-xml-pi-node (n v)
4130 (js2-visit-ast (js2-xml-pi-node-name n) v)
4131 (dolist (attr (js2-xml-pi-node-attrs n))
4132 (js2-visit-ast attr v)))
4133
4134 (defun js2-print-xml-pi-node (n i)
4135 (insert (js2-make-pad i) "<?")
4136 (js2-print-ast (js2-xml-pi-node-name n))
4137 (when (js2-xml-pi-node-attrs n)
4138 (insert " ")
4139 (js2-print-list (js2-xml-pi-node-attrs n)))
4140 (insert "?>"))
4141
4142 (defstruct (js2-xml-cdata-node
4143 (:include js2-xml-node)
4144 (:constructor nil)
4145 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4146 (pos js2-ts-cursor)
4147 len content)))
4148 "AST node for a CDATA escape section. Not currently used."
4149 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4150
4151 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4152 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4153
4154 (defun js2-visit-xml-cdata-node (n v)
4155 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4156
4157 (defun js2-print-xml-cdata-node (n i)
4158 (insert (js2-make-pad i))
4159 (js2-print-ast (js2-xml-cdata-node-content n)))
4160
4161 (defstruct (js2-xml-attr-node
4162 (:include js2-xml-node)
4163 (:constructor nil)
4164 (:constructor make-js2-attr-node (&key (type js2-XML)
4165 (pos js2-ts-cursor)
4166 len name value
4167 eq-pos quote-type)))
4168 "AST node representing a foo='bar' XML attribute value. Not yet used."
4169 name ; a `js2-xml-name-node'
4170 value ; a `js2-xml-name-node'
4171 eq-pos ; buffer position of "=" sign
4172 quote-type) ; 'single or 'double
4173
4174 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4175 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4176
4177 (defun js2-visit-xml-attr-node (n v)
4178 (js2-visit-ast (js2-xml-attr-node-name n) v)
4179 (js2-visit-ast (js2-xml-attr-node-value n) v))
4180
4181 (defun js2-print-xml-attr-node (n i)
4182 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4183 "'"
4184 "\"")))
4185 (insert (js2-make-pad i))
4186 (js2-print-ast (js2-xml-attr-node-name n) 0)
4187 (insert "=" quote)
4188 (js2-print-ast (js2-xml-attr-node-value n) 0)
4189 (insert quote)))
4190
4191 (defstruct (js2-xml-text-node
4192 (:include js2-xml-node)
4193 (:constructor nil)
4194 (:constructor make-js2-text-node (&key (type js2-XML)
4195 (pos js2-ts-cursor)
4196 len content)))
4197 "AST node for an E4X XML text node. Not currently used."
4198 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4199
4200 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4201 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4202
4203 (defun js2-visit-xml-text-node (n v)
4204 (js2-visit-ast (js2-xml-text-node-content n) v))
4205
4206 (defun js2-print-xml-text-node (n i)
4207 (insert (js2-make-pad i))
4208 (dolist (kid (js2-xml-text-node-content n))
4209 (js2-print-ast kid)))
4210
4211 (defstruct (js2-xml-comment-node
4212 (:include js2-xml-node)
4213 (:constructor nil)
4214 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4215 (pos js2-ts-cursor)
4216 len)))
4217 "AST node for E4X XML comment. Not currently used.")
4218
4219 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4220 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4221
4222 (defun js2-print-xml-comment (n i)
4223 (insert (js2-make-pad i)
4224 (js2-node-string n)))
4225
4226 ;;; Node utilities
4227
4228 (defsubst js2-node-line (n)
4229 "Fetch the source line number at the start of node N.
4230 This is O(n) in the length of the source buffer; use prudently."
4231 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4232
4233 (defsubst js2-block-node-kid (n i)
4234 "Return child I of node N, or nil if there aren't that many."
4235 (nth i (js2-block-node-kids n)))
4236
4237 (defsubst js2-block-node-first (n)
4238 "Return first child of block node N, or nil if there is none."
4239 (first (js2-block-node-kids n)))
4240
4241 (defun js2-node-root (n)
4242 "Return the root of the AST containing N.
4243 If N has no parent pointer, returns N."
4244 (let ((parent (js2-node-parent n)))
4245 (if parent
4246 (js2-node-root parent)
4247 n)))
4248
4249 (defsubst js2-node-short-name (n)
4250 "Return the short name of node N as a string, e.g. `js2-if-node'."
4251 (substring (symbol-name (aref n 0))
4252 (length "cl-struct-")))
4253
4254 (defun js2-node-child-list (node)
4255 "Return the child list for NODE, a Lisp list of nodes.
4256 Works for block nodes, array nodes, obj literals, funarg lists,
4257 var decls and try nodes (for catch clauses). Note that you should call
4258 `js2-block-node-kids' on the function body for the body statements.
4259 Returns nil for zero-length child lists or unsupported nodes."
4260 (cond
4261 ((js2-function-node-p node)
4262 (js2-function-node-params node))
4263 ((js2-block-node-p node)
4264 (js2-block-node-kids node))
4265 ((js2-try-node-p node)
4266 (js2-try-node-catch-clauses node))
4267 ((js2-array-node-p node)
4268 (js2-array-node-elems node))
4269 ((js2-object-node-p node)
4270 (js2-object-node-elems node))
4271 ((js2-call-node-p node)
4272 (js2-call-node-args node))
4273 ((js2-new-node-p node)
4274 (js2-new-node-args node))
4275 ((js2-var-decl-node-p node)
4276 (js2-var-decl-node-kids node))
4277 (t
4278 nil)))
4279
4280 (defun js2-node-set-child-list (node kids)
4281 "Set the child list for NODE to KIDS."
4282 (cond
4283 ((js2-function-node-p node)
4284 (setf (js2-function-node-params node) kids))
4285 ((js2-block-node-p node)
4286 (setf (js2-block-node-kids node) kids))
4287 ((js2-try-node-p node)
4288 (setf (js2-try-node-catch-clauses node) kids))
4289 ((js2-array-node-p node)
4290 (setf (js2-array-node-elems node) kids))
4291 ((js2-object-node-p node)
4292 (setf (js2-object-node-elems node) kids))
4293 ((js2-call-node-p node)
4294 (setf (js2-call-node-args node) kids))
4295 ((js2-new-node-p node)
4296 (setf (js2-new-node-args node) kids))
4297 ((js2-var-decl-node-p node)
4298 (setf (js2-var-decl-node-kids node) kids))
4299 (t
4300 (error "Unsupported node type: %s" (js2-node-short-name node))))
4301 kids)
4302
4303 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4304 (defconst js2-paren-expr-nodes
4305 '(cl-struct-js2-comp-loop-node
4306 cl-struct-js2-comp-node
4307 cl-struct-js2-call-node
4308 cl-struct-js2-catch-node
4309 cl-struct-js2-do-node
4310 cl-struct-js2-elem-get-node
4311 cl-struct-js2-for-in-node
4312 cl-struct-js2-for-node
4313 cl-struct-js2-function-node
4314 cl-struct-js2-if-node
4315 cl-struct-js2-let-node
4316 cl-struct-js2-new-node
4317 cl-struct-js2-paren-node
4318 cl-struct-js2-switch-node
4319 cl-struct-js2-while-node
4320 cl-struct-js2-with-node
4321 cl-struct-js2-xml-dot-query-node)
4322 "Node types that can have a parenthesized child expression.
4323 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4324
4325 (defsubst js2-paren-expr-node-p (node)
4326 "Return t for nodes that typically have a parenthesized child expression.
4327 Useful for computing the indentation anchors for arg-lists and conditions.
4328 Note that it may return a false positive, for instance when NODE is
4329 a `js2-new-node' and there are no arguments or parentheses."
4330 (memq (aref node 0) js2-paren-expr-nodes))
4331
4332 ;; Fake polymorphism... yech.
4333 (defun js2-node-lp (node)
4334 "Return relative left-paren position for NODE, if applicable.
4335 For `js2-elem-get-node' structs, returns left-bracket position.
4336 Note that the position may be nil in the case of a parse error."
4337 (cond
4338 ((js2-elem-get-node-p node)
4339 (js2-elem-get-node-lb node))
4340 ((js2-loop-node-p node)
4341 (js2-loop-node-lp node))
4342 ((js2-function-node-p node)
4343 (js2-function-node-lp node))
4344 ((js2-if-node-p node)
4345 (js2-if-node-lp node))
4346 ((js2-new-node-p node)
4347 (js2-new-node-lp node))
4348 ((js2-call-node-p node)
4349 (js2-call-node-lp node))
4350 ((js2-paren-node-p node)
4351 0)
4352 ((js2-switch-node-p node)
4353 (js2-switch-node-lp node))
4354 ((js2-catch-node-p node)
4355 (js2-catch-node-lp node))
4356 ((js2-let-node-p node)
4357 (js2-let-node-lp node))
4358 ((js2-comp-node-p node)
4359 0)
4360 ((js2-with-node-p node)
4361 (js2-with-node-lp node))
4362 ((js2-xml-dot-query-node-p node)
4363 (1+ (js2-infix-node-op-pos node)))
4364 (t
4365 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4366
4367 ;; Fake polymorphism... blech.
4368 (defun js2-node-rp (node)
4369 "Return relative right-paren position for NODE, if applicable.
4370 For `js2-elem-get-node' structs, returns right-bracket position.
4371 Note that the position may be nil in the case of a parse error."
4372 (cond
4373 ((js2-elem-get-node-p node)
4374 (js2-elem-get-node-rb node))
4375 ((js2-loop-node-p node)
4376 (js2-loop-node-rp node))
4377 ((js2-function-node-p node)
4378 (js2-function-node-rp node))
4379 ((js2-if-node-p node)
4380 (js2-if-node-rp node))
4381 ((js2-new-node-p node)
4382 (js2-new-node-rp node))
4383 ((js2-call-node-p node)
4384 (js2-call-node-rp node))
4385 ((js2-paren-node-p node)
4386 (1- (js2-node-len node)))
4387 ((js2-switch-node-p node)
4388 (js2-switch-node-rp node))
4389 ((js2-catch-node-p node)
4390 (js2-catch-node-rp node))
4391 ((js2-let-node-p node)
4392 (js2-let-node-rp node))
4393 ((js2-comp-node-p node)
4394 (1- (js2-node-len node)))
4395 ((js2-with-node-p node)
4396 (js2-with-node-rp node))
4397 ((js2-xml-dot-query-node-p node)
4398 (1+ (js2-xml-dot-query-node-rp node)))
4399 (t
4400 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4401
4402 (defsubst js2-node-first-child (node)
4403 "Return the first element of `js2-node-child-list' for NODE."
4404 (car (js2-node-child-list node)))
4405
4406 (defsubst js2-node-last-child (node)
4407 "Return the last element of `js2-node-last-child' for NODE."
4408 (car (last (js2-node-child-list node))))
4409
4410 (defun js2-node-prev-sibling (node)
4411 "Return the previous statement in parent.
4412 Works for parents supported by `js2-node-child-list'.
4413 Returns nil if NODE is not in the parent, or PARENT is
4414 not a supported node, or if NODE is the first child."
4415 (let* ((p (js2-node-parent node))
4416 (kids (js2-node-child-list p))
4417 (sib (car kids)))
4418 (while (and kids
4419 (not (eq node (cadr kids))))
4420 (setq kids (cdr kids)
4421 sib (car kids)))
4422 sib))
4423
4424 (defun js2-node-next-sibling (node)
4425 "Return the next statement in parent block.
4426 Returns nil if NODE is not in the block, or PARENT is not
4427 a block node, or if NODE is the last statement."
4428 (let* ((p (js2-node-parent node))
4429 (kids (js2-node-child-list p)))
4430 (while (and kids
4431 (not (eq node (car kids))))
4432 (setq kids (cdr kids)))
4433 (cadr kids)))
4434
4435 (defun js2-node-find-child-before (pos parent &optional after)
4436 "Find the last child that starts before POS in parent.
4437 If AFTER is non-nil, returns first child starting after POS.
4438 POS is an absolute buffer position. PARENT is any node
4439 supported by `js2-node-child-list'.
4440 Returns nil if no applicable child is found."
4441 (let ((kids (if (js2-function-node-p parent)
4442 (js2-block-node-kids (js2-function-node-body parent))
4443 (js2-node-child-list parent)))
4444 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4445 (js2-function-node-body parent)
4446 parent)))
4447 kid result fn
4448 (continue t))
4449 (setq fn (if after '>= '<))
4450 (while (and kids continue)
4451 (setq kid (car kids))
4452 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4453 (setq result kid
4454 continue (not after))
4455 (setq continue after))
4456 (setq kids (cdr kids)))
4457 result))
4458
4459 (defun js2-node-find-child-after (pos parent)
4460 "Find first child that starts after POS in parent.
4461 POS is an absolute buffer position. PARENT is any node
4462 supported by `js2-node-child-list'.
4463 Returns nil if no applicable child is found."
4464 (js2-node-find-child-before pos parent 'after))
4465
4466 (defun js2-node-replace-child (pos parent new-node)
4467 "Replace node at index POS in PARENT with NEW-NODE.
4468 Only works for parents supported by `js2-node-child-list'."
4469 (let ((kids (js2-node-child-list parent))
4470 (i 0))
4471 (while (< i pos)
4472 (setq kids (cdr kids)
4473 i (1+ i)))
4474 (setcar kids new-node)
4475 (js2-node-add-children parent new-node)))
4476
4477 (defun js2-node-buffer (n)
4478 "Return the buffer associated with AST N.
4479 Returns nil if the buffer is not set as a property on the root
4480 node, or if parent links were not recorded during parsing."
4481 (let ((root (js2-node-root n)))
4482 (and root
4483 (js2-ast-root-p root)
4484 (js2-ast-root-buffer root))))
4485
4486 (defun js2-block-node-push (n kid)
4487 "Push js2-node KID onto the end of js2-block-node N's child list.
4488 KID is always added to the -end- of the kids list.
4489 Function also calls `js2-node-add-children' to add the parent link."
4490 (let ((kids (js2-node-child-list n)))
4491 (if kids
4492 (setcdr kids (nconc (cdr kids) (list kid)))
4493 (js2-node-set-child-list n (list kid)))
4494 (js2-node-add-children n kid)))
4495
4496 (defun js2-node-string (node)
4497 (with-current-buffer (or (js2-node-buffer node)
4498 (error "No buffer available for node %s" node))
4499 (let ((pos (js2-node-abs-pos node)))
4500 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4501
4502 ;; Container for storing the node we're looking for in a traversal.
4503 (js2-deflocal js2-discovered-node nil)
4504
4505 ;; Keep track of absolute node position during traversals.
4506 (js2-deflocal js2-visitor-offset nil)
4507
4508 (js2-deflocal js2-node-search-point nil)
4509
4510 (when js2-mode-dev-mode-p
4511 (defun js2-find-node-at-point ()
4512 (interactive)
4513 (let ((node (js2-node-at-point)))
4514 (message "%s" (or node "No node found at point"))))
4515 (defun js2-node-name-at-point ()
4516 (interactive)
4517 (let ((node (js2-node-at-point)))
4518 (message "%s" (if node
4519 (js2-node-short-name node)
4520 "No node found at point.")))))
4521
4522 (defun js2-node-at-point (&optional pos skip-comments)
4523 "Return AST node at POS, a buffer position, defaulting to current point.
4524 The `js2-mode-ast' variable must be set to the current parse tree.
4525 Signals an error if the AST (`js2-mode-ast') is nil.
4526 Always returns a node - if it can't find one, it returns the root.
4527 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4528 (let ((ast js2-mode-ast)
4529 result)
4530 (unless ast
4531 (error "No JavaScript AST available"))
4532 ;; Look through comments first, since they may be inside nodes that
4533 ;; would otherwise report a match.
4534 (setq pos (or pos (point))
4535 result (if (> pos (js2-node-abs-end ast))
4536 ast
4537 (if (not skip-comments)
4538 (js2-comment-at-point pos))))
4539 (unless result
4540 (setq js2-discovered-node nil
4541 js2-visitor-offset 0
4542 js2-node-search-point pos)
4543 (unwind-protect
4544 (catch 'js2-visit-done
4545 (js2-visit-ast ast #'js2-node-at-point-visitor))
4546 (setq js2-visitor-offset nil
4547 js2-node-search-point nil))
4548 (setq result js2-discovered-node))
4549 ;; may have found a comment beyond end of last child node,
4550 ;; since visiting the ast-root looks at the comment-list last.
4551 (if (and skip-comments
4552 (js2-comment-node-p result))
4553 (setq result nil))
4554 (or result js2-mode-ast)))
4555
4556 (defun js2-node-at-point-visitor (node end-p)
4557 (let ((rel-pos (js2-node-pos node))
4558 abs-pos
4559 abs-end
4560 (point js2-node-search-point))
4561 (cond
4562 (end-p
4563 ;; this evaluates to a non-nil return value, even if it's zero
4564 (decf js2-visitor-offset rel-pos))
4565 ;; we already looked for comments before visiting, and don't want them now
4566 ((js2-comment-node-p node)
4567 nil)
4568 (t
4569 (setq abs-pos (incf js2-visitor-offset rel-pos)
4570 ;; we only want to use the node if the point is before
4571 ;; the last character position in the node, so we decrement
4572 ;; the absolute end by 1.
4573 abs-end (+ abs-pos (js2-node-len node) -1))
4574 (cond
4575 ;; If this node starts after search-point, stop the search.
4576 ((> abs-pos point)
4577 (throw 'js2-visit-done nil))
4578 ;; If this node ends before the search-point, don't check kids.
4579 ((> point abs-end)
4580 nil)
4581 (t
4582 ;; Otherwise point is within this node, possibly in a child.
4583 (setq js2-discovered-node node)
4584 t)))))) ; keep processing kids to look for more specific match
4585
4586 (defsubst js2-block-comment-p (node)
4587 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4588 (and (js2-comment-node-p node)
4589 (memq (js2-comment-node-format node) '(jsdoc block))))
4590
4591 ;; TODO: put the comments in a vector and binary-search them instead
4592 (defun js2-comment-at-point (&optional pos)
4593 "Look through scanned comment nodes for one containing POS.
4594 POS is a buffer position that defaults to current point.
4595 Function returns nil if POS was not in any comment node."
4596 (let ((ast js2-mode-ast)
4597 (x (or pos (point)))
4598 beg end)
4599 (unless ast
4600 (error "No JavaScript AST available"))
4601 (catch 'done
4602 ;; Comments are stored in lexical order.
4603 (dolist (comment (js2-ast-root-comments ast) nil)
4604 (setq beg (js2-node-abs-pos comment)
4605 end (+ beg (js2-node-len comment)))
4606 (if (and (>= x beg)
4607 (<= x end))
4608 (throw 'done comment))))))
4609
4610 (defun js2-mode-find-parent-fn (node)
4611 "Find function enclosing NODE.
4612 Returns nil if NODE is not inside a function."
4613 (setq node (js2-node-parent node))
4614 (while (and node (not (js2-function-node-p node)))
4615 (setq node (js2-node-parent node)))
4616 (and (js2-function-node-p node) node))
4617
4618 (defun js2-mode-find-enclosing-fn (node)
4619 "Find function or root enclosing NODE."
4620 (if (js2-ast-root-p node)
4621 node
4622 (setq node (js2-node-parent node))
4623 (while (not (or (js2-ast-root-p node)
4624 (js2-function-node-p node)))
4625 (setq node (js2-node-parent node)))
4626 node))
4627
4628 (defun js2-mode-find-enclosing-node (beg end)
4629 "Find node fully enclosing BEG and END."
4630 (let ((node (js2-node-at-point beg))
4631 pos
4632 (continue t))
4633 (while continue
4634 (if (or (js2-ast-root-p node)
4635 (and
4636 (<= (setq pos (js2-node-abs-pos node)) beg)
4637 (>= (+ pos (js2-node-len node)) end)))
4638 (setq continue nil)
4639 (setq node (js2-node-parent node))))
4640 node))
4641
4642 (defun js2-node-parent-script-or-fn (node)
4643 "Find script or function immediately enclosing NODE.
4644 If NODE is the ast-root, returns nil."
4645 (if (js2-ast-root-p node)
4646 nil
4647 (setq node (js2-node-parent node))
4648 (while (and node (not (or (js2-function-node-p node)
4649 (js2-script-node-p node))))
4650 (setq node (js2-node-parent node)))
4651 node))
4652
4653 (defun js2-node-is-descendant (node ancestor)
4654 "Return t if NODE is a descendant of ANCESTOR."
4655 (while (and node
4656 (not (eq node ancestor)))
4657 (setq node (js2-node-parent node)))
4658 node)
4659
4660 ;;; visitor infrastructure
4661
4662 (defun js2-visit-none (_node _callback)
4663 "Visitor for AST node that have no node children."
4664 nil)
4665
4666 (defun js2-print-none (_node _indent)
4667 "Visitor for AST node with no printed representation.")
4668
4669 (defun js2-print-body (node indent)
4670 "Print a statement, or a block without braces."
4671 (if (js2-block-node-p node)
4672 (dolist (kid (js2-block-node-kids node))
4673 (js2-print-ast kid indent))
4674 (js2-print-ast node indent)))
4675
4676 (defun js2-print-list (args &optional delimiter)
4677 (loop with len = (length args)
4678 for arg in args
4679 for count from 1
4680 do
4681 (when arg (js2-print-ast arg 0))
4682 (if (< count len)
4683 (insert (or delimiter ", ")))))
4684
4685 (defun js2-print-tree (ast)
4686 "Prints an AST to the current buffer.
4687 Makes `js2-ast-parent-nodes' available to the printer functions."
4688 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4689 (js2-print-ast ast)))
4690
4691 (defun js2-print-ast (node &optional indent)
4692 "Helper function for printing AST nodes.
4693 Requires `js2-ast-parent-nodes' to be non-nil.
4694 You should use `js2-print-tree' instead of this function."
4695 (let ((printer (get (aref node 0) 'js2-printer))
4696 (i (or indent 0)))
4697 ;; TODO: wedge comments in here somewhere
4698 (if printer
4699 (funcall printer node i))))
4700
4701 (defconst js2-side-effecting-tokens
4702 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4703 (dolist (tt (list js2-ASSIGN
4704 js2-ASSIGN_ADD
4705 js2-ASSIGN_BITAND
4706 js2-ASSIGN_BITOR
4707 js2-ASSIGN_BITXOR
4708 js2-ASSIGN_DIV
4709 js2-ASSIGN_LSH
4710 js2-ASSIGN_MOD
4711 js2-ASSIGN_MUL
4712 js2-ASSIGN_RSH
4713 js2-ASSIGN_SUB
4714 js2-ASSIGN_URSH
4715 js2-BLOCK
4716 js2-BREAK
4717 js2-CALL
4718 js2-CATCH
4719 js2-CATCH_SCOPE
4720 js2-CLASS
4721 js2-CONST
4722 js2-CONTINUE
4723 js2-DEBUGGER
4724 js2-DEC
4725 js2-DELPROP
4726 js2-DEL_REF
4727 js2-DO
4728 js2-ELSE
4729 js2-EMPTY
4730 js2-ENTERWITH
4731 js2-EXPORT
4732 js2-EXPR_RESULT
4733 js2-FINALLY
4734 js2-FOR
4735 js2-FUNCTION
4736 js2-GOTO
4737 js2-IF
4738 js2-IFEQ
4739 js2-IFNE
4740 js2-IMPORT
4741 js2-INC
4742 js2-JSR
4743 js2-LABEL
4744 js2-LEAVEWITH
4745 js2-LET
4746 js2-LETEXPR
4747 js2-LOCAL_BLOCK
4748 js2-LOOP
4749 js2-NEW
4750 js2-REF_CALL
4751 js2-RETHROW
4752 js2-RETURN
4753 js2-RETURN_RESULT
4754 js2-SEMI
4755 js2-SETELEM
4756 js2-SETELEM_OP
4757 js2-SETNAME
4758 js2-SETPROP
4759 js2-SETPROP_OP
4760 js2-SETVAR
4761 js2-SET_REF
4762 js2-SET_REF_OP
4763 js2-SWITCH
4764 js2-TARGET
4765 js2-THROW
4766 js2-TRY
4767 js2-VAR
4768 js2-WHILE
4769 js2-WITH
4770 js2-WITHEXPR
4771 js2-YIELD))
4772 (aset tokens tt t))
4773 (if js2-instanceof-has-side-effects
4774 (aset tokens js2-INSTANCEOF t))
4775 tokens))
4776
4777 (defun js2-node-has-side-effects (node)
4778 "Return t if NODE has side effects."
4779 (when node ; makes it easier to handle malformed expressions
4780 (let ((tt (js2-node-type node)))
4781 (cond
4782 ;; This doubtless needs some work, since EXPR_VOID is used
4783 ;; in several ways in Rhino and I may not have caught them all.
4784 ;; I'll wait for people to notice incorrect warnings.
4785 ((and (= tt js2-EXPR_VOID)
4786 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4787 (let ((expr (js2-expr-stmt-node-expr node)))
4788 (or (js2-node-has-side-effects expr)
4789 (when (js2-string-node-p expr)
4790 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4791 ((= tt js2-COMMA)
4792 (js2-node-has-side-effects (js2-infix-node-right node)))
4793 ((or (= tt js2-AND)
4794 (= tt js2-OR))
4795 (or (js2-node-has-side-effects (js2-infix-node-right node))
4796 (js2-node-has-side-effects (js2-infix-node-left node))))
4797 ((= tt js2-HOOK)
4798 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4799 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4800 ((js2-paren-node-p node)
4801 (js2-node-has-side-effects (js2-paren-node-expr node)))
4802 ((= tt js2-ERROR) ; avoid cascaded error messages
4803 nil)
4804 (t
4805 (aref js2-side-effecting-tokens tt))))))
4806
4807 (defconst js2-stmt-node-types
4808 (list js2-BLOCK
4809 js2-BREAK
4810 js2-CONTINUE
4811 js2-DEFAULT ; e4x "default xml namespace" statement
4812 js2-DO
4813 js2-EXPR_RESULT
4814 js2-EXPR_VOID
4815 js2-FOR
4816 js2-IF
4817 js2-RETURN
4818 js2-SWITCH
4819 js2-THROW
4820 js2-TRY
4821 js2-WHILE
4822 js2-WITH)
4823 "Node types that only appear in statement contexts.
4824 The list does not include nodes that always appear as the child
4825 of another specific statement type, such as switch-cases,
4826 catch and finally blocks, and else-clauses. The list also excludes
4827 nodes like yield, let and var, which may appear in either expression
4828 or statement context, and in the latter context always have a
4829 `js2-expr-stmt-node' parent. Finally, the list does not include
4830 functions or scripts, which are treated separately from statements
4831 by the JavaScript parser and runtime.")
4832
4833 (defun js2-stmt-node-p (node)
4834 "Heuristic for figuring out if NODE is a statement.
4835 Some node types can appear in either an expression context or a
4836 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4837 For these node types in a statement context, the parent will be a
4838 `js2-expr-stmt-node'.
4839 Functions aren't included in the check."
4840 (memq (js2-node-type node) js2-stmt-node-types))
4841
4842 (defun js2-mode-find-first-stmt (node)
4843 "Search upward starting from NODE looking for a statement.
4844 For purposes of this function, a `js2-function-node' counts."
4845 (while (not (or (js2-stmt-node-p node)
4846 (js2-function-node-p node)))
4847 (setq node (js2-node-parent node)))
4848 node)
4849
4850 (defun js2-node-parent-stmt (node)
4851 "Return the node's first ancestor that is a statement.
4852 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4853 appearing in a statement context will have a parent that is a
4854 `js2-expr-stmt-node' that will be returned by this function."
4855 (let ((parent (js2-node-parent node)))
4856 (if (or (null parent)
4857 (js2-stmt-node-p parent)
4858 (and (js2-function-node-p parent)
4859 (not (eq (js2-function-node-form parent)
4860 'FUNCTION_EXPRESSION))))
4861 parent
4862 (js2-node-parent-stmt parent))))
4863
4864 ;; In the Mozilla Rhino sources, Roshan James writes:
4865 ;; Does consistent-return analysis on the function body when strict mode is
4866 ;; enabled.
4867 ;;
4868 ;; function (x) { return (x+1) }
4869 ;;
4870 ;; is ok, but
4871 ;;
4872 ;; function (x) { if (x < 0) return (x+1); }
4873 ;;
4874 ;; is not because the function can potentially return a value when the
4875 ;; condition is satisfied and if not, the function does not explicitly
4876 ;; return a value.
4877 ;;
4878 ;; This extends to checking mismatches such as "return" and "return <value>"
4879 ;; used in the same function. Warnings are not emitted if inconsistent
4880 ;; returns exist in code that can be statically shown to be unreachable.
4881 ;; Ex.
4882 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4883 ;;
4884 ;; emits no warning. However if the loop had a break statement, then a
4885 ;; warning would be emitted.
4886 ;;
4887 ;; The consistency analysis looks at control structures such as loops, ifs,
4888 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4889 ;; warns the user about an inconsistent set of termination possibilities.
4890 ;;
4891 ;; These flags enumerate the possible ways a statement/function can
4892 ;; terminate. These flags are used by endCheck() and by the Parser to
4893 ;; detect inconsistent return usage.
4894 ;;
4895 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4896 ;; able to execute (example: throw, continue)
4897 ;;
4898 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4899 ;; next one. Statement such as return dont. A compound statement may have
4900 ;; some branch that drops off control to the next statement.
4901 ;;
4902 ;; END_RETURNS indicates that the statement can return with no value.
4903 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4904 ;;
4905 ;; A compound statement such as
4906 ;; if (condition) {
4907 ;; return value;
4908 ;; }
4909 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4910
4911 (defconst js2-END_UNREACHED 0)
4912 (defconst js2-END_DROPS_OFF 1)
4913 (defconst js2-END_RETURNS 2)
4914 (defconst js2-END_RETURNS_VALUE 4)
4915 (defconst js2-END_YIELDS 8)
4916
4917 (defun js2-has-consistent-return-usage (node)
4918 "Check that every return usage in a function body is consistent.
4919 Returns t if the function satisfies strict mode requirement."
4920 (let ((n (js2-end-check node)))
4921 ;; either it doesn't return a value in any branch...
4922 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4923 ;; or it returns a value (or is unreached) at every branch
4924 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4925 js2-END_RETURNS
4926 js2-END_YIELDS)))))
4927
4928 (defun js2-end-check-if (node)
4929 "Ensure that return usage in then/else blocks is consistent.
4930 If there is no else block, then the return statement can fall through.
4931 Returns logical OR of END_* flags"
4932 (let ((th (js2-if-node-then-part node))
4933 (el (js2-if-node-else-part node)))
4934 (if (null th)
4935 js2-END_UNREACHED
4936 (logior (js2-end-check th) (if el
4937 (js2-end-check el)
4938 js2-END_DROPS_OFF)))))
4939
4940 (defun js2-end-check-switch (node)
4941 "Consistency of return statements is checked between the case statements.
4942 If there is no default, then the switch can fall through. If there is a
4943 default, we check to see if all code paths in the default return or if
4944 there is a code path that can fall through.
4945 Returns logical OR of END_* flags."
4946 (let ((rv js2-END_UNREACHED)
4947 default-case)
4948 ;; examine the cases
4949 (catch 'break
4950 (dolist (c (js2-switch-node-cases node))
4951 (if (js2-case-node-expr c)
4952 (js2-set-flag rv (js2-end-check-block c))
4953 (setq default-case c)
4954 (throw 'break nil))))
4955 ;; we don't care how the cases drop into each other
4956 (js2-clear-flag rv js2-END_DROPS_OFF)
4957 ;; examine the default
4958 (js2-set-flag rv (if default-case
4959 (js2-end-check default-case)
4960 js2-END_DROPS_OFF))
4961 rv))
4962
4963 (defun js2-end-check-try (node)
4964 "If the block has a finally, return consistency is checked in the
4965 finally block. If all code paths in the finally return, then the
4966 returns in the try-catch blocks don't matter. If there is a code path
4967 that does not return or if there is no finally block, the returns
4968 of the try and catch blocks are checked for mismatch.
4969 Returns logical OR of END_* flags."
4970 (let ((finally (js2-try-node-finally-block node))
4971 rv)
4972 ;; check the finally if it exists
4973 (setq rv (if finally
4974 (js2-end-check (js2-finally-node-body finally))
4975 js2-END_DROPS_OFF))
4976 ;; If the finally block always returns, then none of the returns
4977 ;; in the try or catch blocks matter.
4978 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4979 (js2-clear-flag rv js2-END_DROPS_OFF)
4980 ;; examine the try block
4981 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4982 ;; check each catch block
4983 (dolist (cb (js2-try-node-catch-clauses node))
4984 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4985 rv))
4986
4987 (defun js2-end-check-loop (node)
4988 "Return statement in the loop body must be consistent.
4989 The default assumption for any kind of a loop is that it will eventually
4990 terminate. The only exception is a loop with a constant true condition.
4991 Code that follows such a loop is examined only if one can determine
4992 statically that there is a break out of the loop.
4993
4994 for(... ; ... ; ...) {}
4995 for(... in ... ) {}
4996 while(...) { }
4997 do { } while(...)
4998
4999 Returns logical OR of END_* flags."
5000 (let ((rv (js2-end-check (js2-loop-node-body node)))
5001 (condition (cond
5002 ((js2-while-node-p node)
5003 (js2-while-node-condition node))
5004 ((js2-do-node-p node)
5005 (js2-do-node-condition node))
5006 ((js2-for-node-p node)
5007 (js2-for-node-condition node)))))
5008
5009 ;; check to see if the loop condition is always true
5010 (if (and condition
5011 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5012 (js2-clear-flag rv js2-END_DROPS_OFF))
5013
5014 ;; look for effect of breaks
5015 (js2-set-flag rv (js2-node-get-prop node
5016 'CONTROL_BLOCK_PROP
5017 js2-END_UNREACHED))
5018 rv))
5019
5020 (defun js2-end-check-block (node)
5021 "A general block of code is examined statement by statement.
5022 If any statement (even a compound one) returns in all branches, then
5023 subsequent statements are not examined.
5024 Returns logical OR of END_* flags."
5025 (let* ((rv js2-END_DROPS_OFF)
5026 (kids (js2-block-node-kids node))
5027 (n (car kids)))
5028 ;; Check each statment. If the statement can continue onto the next
5029 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5030 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5031 (js2-clear-flag rv js2-END_DROPS_OFF)
5032 (js2-set-flag rv (js2-end-check n))
5033 (setq kids (cdr kids)
5034 n (car kids)))
5035 rv))
5036
5037 (defun js2-end-check-label (node)
5038 "A labeled statement implies that there may be a break to the label.
5039 The function processes the labeled statement and then checks the
5040 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5041 particular label.
5042 Returns logical OR of END_* flags."
5043 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5044 (logior rv (js2-node-get-prop node
5045 'CONTROL_BLOCK_PROP
5046 js2-END_UNREACHED))))
5047
5048 (defun js2-end-check-break (node)
5049 "When a break is encountered annotate the statement being broken
5050 out of by setting its CONTROL_BLOCK_PROP property.
5051 Returns logical OR of END_* flags."
5052 (and (js2-break-node-target node)
5053 (js2-node-set-prop (js2-break-node-target node)
5054 'CONTROL_BLOCK_PROP
5055 js2-END_DROPS_OFF))
5056 js2-END_UNREACHED)
5057
5058 (defun js2-end-check (node)
5059 "Examine the body of a function, doing a basic reachability analysis.
5060 Returns a combination of flags END_* flags that indicate
5061 how the function execution can terminate. These constitute only the
5062 pessimistic set of termination conditions. It is possible that at
5063 runtime certain code paths will never be actually taken. Hence this
5064 analysis will flag errors in cases where there may not be errors.
5065 Returns logical OR of END_* flags"
5066 (let (kid)
5067 (cond
5068 ((js2-break-node-p node)
5069 (js2-end-check-break node))
5070 ((js2-expr-stmt-node-p node)
5071 (if (setq kid (js2-expr-stmt-node-expr node))
5072 (js2-end-check kid)
5073 js2-END_DROPS_OFF))
5074 ((or (js2-continue-node-p node)
5075 (js2-throw-node-p node))
5076 js2-END_UNREACHED)
5077 ((js2-return-node-p node)
5078 (if (setq kid (js2-return-node-retval node))
5079 js2-END_RETURNS_VALUE
5080 js2-END_RETURNS))
5081 ((js2-loop-node-p node)
5082 (js2-end-check-loop node))
5083 ((js2-switch-node-p node)
5084 (js2-end-check-switch node))
5085 ((js2-labeled-stmt-node-p node)
5086 (js2-end-check-label node))
5087 ((js2-if-node-p node)
5088 (js2-end-check-if node))
5089 ((js2-try-node-p node)
5090 (js2-end-check-try node))
5091 ((js2-block-node-p node)
5092 (if (null (js2-block-node-kids node))
5093 js2-END_DROPS_OFF
5094 (js2-end-check-block node)))
5095 ((js2-yield-node-p node)
5096 js2-END_YIELDS)
5097 (t
5098 js2-END_DROPS_OFF))))
5099
5100 (defun js2-always-defined-boolean-p (node)
5101 "Check if NODE always evaluates to true or false in boolean context.
5102 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5103 nor always false."
5104 (let ((tt (js2-node-type node))
5105 num)
5106 (cond
5107 ((or (= tt js2-FALSE) (= tt js2-NULL))
5108 'ALWAYS_FALSE)
5109 ((= tt js2-TRUE)
5110 'ALWAYS_TRUE)
5111 ((= tt js2-NUMBER)
5112 (setq num (js2-number-node-num-value node))
5113 (if (and (not (eq num 0.0e+NaN))
5114 (not (zerop num)))
5115 'ALWAYS_TRUE
5116 'ALWAYS_FALSE))
5117 (t
5118 nil))))
5119
5120 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5121 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5122
5123 (defvar js2-tokens nil
5124 "List of all defined token names.") ; initialized in `js2-token-names'
5125
5126 (defconst js2-token-names
5127 (let* ((names (make-vector js2-num-tokens -1))
5128 (case-fold-search nil) ; only match js2-UPPER_CASE
5129 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5130 (loop for sym in syms
5131 for i from 0
5132 do
5133 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5134 (not (boundp sym)))
5135 (aset names (symbol-value sym) ; code, e.g. 152
5136 (downcase
5137 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5138 (push sym js2-tokens)))
5139 names)
5140 "Vector mapping int values to token string names, sans `js2-' prefix.")
5141
5142 (defun js2-tt-name (tok)
5143 "Return a string name for TOK, a token symbol or code.
5144 Signals an error if it's not a recognized token."
5145 (let ((code tok))
5146 (if (symbolp tok)
5147 (setq code (symbol-value tok)))
5148 (if (eq code -1)
5149 "ERROR"
5150 (if (and (numberp code)
5151 (not (minusp code))
5152 (< code js2-num-tokens))
5153 (aref js2-token-names code)
5154 (error "Invalid token: %s" code)))))
5155
5156 (defsubst js2-tt-sym (tok)
5157 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5158 (intern (js2-tt-name tok)))
5159
5160 (defconst js2-token-codes
5161 (let ((table (make-hash-table :test 'eq :size 256)))
5162 (loop for name across js2-token-names
5163 for sym = (intern (concat "js2-" (upcase name)))
5164 do
5165 (puthash sym (symbol-value sym) table))
5166 ;; clean up a few that are "wrong" in Rhino's token codes
5167 (puthash 'js2-DELETE js2-DELPROP table)
5168 table)
5169 "Hashtable mapping token type symbols to their bytecodes.")
5170
5171 (defsubst js2-tt-code (sym)
5172 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5173 (or (gethash sym js2-token-codes)
5174 (error "Invalid token symbol: %s " sym))) ; signal code bug
5175
5176 (defun js2-report-scan-error (msg &optional no-throw beg len)
5177 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5178 (js2-report-error msg nil
5179 (or beg (js2-current-token-beg))
5180 (or len (js2-current-token-len)))
5181 (unless no-throw
5182 (throw 'return js2-ERROR)))
5183
5184 (defun js2-set-string-from-buffer (token)
5185 "Set `string' and `end' slots for TOKEN, return the string."
5186 (setf (js2-token-end token) js2-ts-cursor
5187 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5188
5189 ;; TODO: could potentially avoid a lot of consing by allocating a
5190 ;; char buffer the way Rhino does.
5191 (defsubst js2-add-to-string (c)
5192 (push c js2-ts-string-buffer))
5193
5194 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5195 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5196 ;; any other character: when it's not part of the current token, we
5197 ;; unget it, allowing it to be read again by the following call.
5198 (defsubst js2-unget-char ()
5199 (decf js2-ts-cursor))
5200
5201 ;; Rhino distinguishes \r and \n line endings. We don't need to
5202 ;; because we only scan from Emacs buffers, which always use \n.
5203 (defun js2-get-char ()
5204 "Read and return the next character from the input buffer.
5205 Increments `js2-ts-lineno' if the return value is a newline char.
5206 Updates `js2-ts-cursor' to the point after the returned char.
5207 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5208 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5209 (let (c)
5210 ;; check for end of buffer
5211 (if (>= js2-ts-cursor (point-max))
5212 (setq js2-ts-hit-eof t
5213 js2-ts-cursor (1+ js2-ts-cursor)
5214 c js2-EOF_CHAR) ; return value
5215 ;; otherwise read next char
5216 (setq c (char-before (incf js2-ts-cursor)))
5217 ;; if we read a newline, update counters
5218 (if (= c ?\n)
5219 (setq js2-ts-line-start js2-ts-cursor
5220 js2-ts-lineno (1+ js2-ts-lineno)))
5221 ;; TODO: skip over format characters
5222 c)))
5223
5224 (defun js2-read-unicode-escape ()
5225 "Read a \\uNNNN sequence from the input.
5226 Assumes the ?\ and ?u have already been read.
5227 Returns the unicode character, or nil if it wasn't a valid character.
5228 Doesn't change the values of any scanner variables."
5229 ;; I really wish I knew a better way to do this, but I can't
5230 ;; find the Emacs function that takes a 16-bit int and converts
5231 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5232 ;; Have to first check that it's 4 hex characters or it may stop
5233 ;; the read early.
5234 (ignore-errors
5235 (let ((s (buffer-substring-no-properties js2-ts-cursor
5236 (+ 4 js2-ts-cursor))))
5237 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5238 (read (concat "?\\u" s))))))
5239
5240 (defun js2-match-char (test)
5241 "Consume and return next character if it matches TEST, a character.
5242 Returns nil and consumes nothing if TEST is not the next character."
5243 (let ((c (js2-get-char)))
5244 (if (eq c test)
5245 t
5246 (js2-unget-char)
5247 nil)))
5248
5249 (defun js2-peek-char ()
5250 (prog1
5251 (js2-get-char)
5252 (js2-unget-char)))
5253
5254 (defun js2-identifier-start-p (c)
5255 "Is C a valid start to an ES5 Identifier?
5256 See http://es5.github.io/#x7.6"
5257 (or
5258 (memq c '(?$ ?_))
5259 (memq (get-char-code-property c 'general-category)
5260 ;; Letters
5261 '(Lu Ll Lt Lm Lo Nl))))
5262
5263 (defun js2-identifier-part-p (c)
5264 "Is C a valid part of an ES5 Identifier?
5265 See http://es5.github.io/#x7.6"
5266 (or
5267 (memq c '(?$ ?_ ?\u200c ?\u200d))
5268 (memq (get-char-code-property c 'general-category)
5269 '(;; Letters
5270 Lu Ll Lt Lm Lo Nl
5271 ;; Combining Marks
5272 Mn Mc
5273 ;; Digits
5274 Nd
5275 ;; Connector Punctuation
5276 Pc))))
5277
5278 (defun js2-alpha-p (c)
5279 (cond ((and (<= ?A c) (<= c ?Z)) t)
5280 ((and (<= ?a c) (<= c ?z)) t)
5281 (t nil)))
5282
5283 (defsubst js2-digit-p (c)
5284 (and (<= ?0 c) (<= c ?9)))
5285
5286 (defun js2-js-space-p (c)
5287 (if (<= c 127)
5288 (memq c '(#x20 #x9 #xB #xC #xD))
5289 (or
5290 (eq c #xA0)
5291 ;; TODO: change this nil to check for Unicode space character
5292 nil)))
5293
5294 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5295
5296 (defun js2-skip-line ()
5297 "Skip to end of line."
5298 (while (not (memq (js2-get-char) js2-eol-chars)))
5299 (js2-unget-char)
5300 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5301 (setq js2-token-end js2-ts-cursor))
5302
5303 (defun js2-init-scanner (&optional buf line)
5304 "Create token stream for BUF starting on LINE.
5305 BUF defaults to `current-buffer' and LINE defaults to 1.
5306
5307 A buffer can only have one scanner active at a time, which yields
5308 dramatically simpler code than using a defstruct. If you need to
5309 have simultaneous scanners in a buffer, copy the regions to scan
5310 into temp buffers."
5311 (with-current-buffer (or buf (current-buffer))
5312 (setq js2-ts-dirty-line nil
5313 js2-ts-hit-eof nil
5314 js2-ts-line-start 0
5315 js2-ts-lineno (or line 1)
5316 js2-ts-line-end-char -1
5317 js2-ts-cursor (point-min)
5318 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5319 js2-ti-tokens-cursor 0
5320 js2-ti-lookahead 0
5321 js2-ts-is-xml-attribute nil
5322 js2-ts-xml-is-tag-content nil
5323 js2-ts-xml-open-tags-count 0
5324 js2-ts-string-buffer nil)))
5325
5326 ;; This function uses the cached op, string and number fields in
5327 ;; TokenStream; if getToken has been called since the passed token
5328 ;; was scanned, the op or string printed may be incorrect.
5329 (defun js2-token-to-string (token)
5330 ;; Not sure where this function is used in Rhino. Not tested.
5331 (if (not js2-debug-print-trees)
5332 ""
5333 (let ((name (js2-tt-name token)))
5334 (cond
5335 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5336 (concat name " `" (js2-current-token-string) "'"))
5337 ((eq token js2-NUMBER)
5338 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5339 (t
5340 name)))))
5341
5342 (defconst js2-keywords
5343 '(break
5344 case catch class const continue
5345 debugger default delete do
5346 else enum extends
5347 false finally for function
5348 if in instanceof import
5349 let
5350 new null
5351 return
5352 switch
5353 this throw true try typeof
5354 var void
5355 while with
5356 yield))
5357
5358 ;; Token names aren't exactly the same as the keywords, unfortunately.
5359 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5360 (defconst js2-kwd-tokens
5361 (let ((table (make-vector js2-num-tokens nil))
5362 (tokens
5363 (list js2-BREAK
5364 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5365 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5366 js2-ELSE js2-EXTENDS
5367 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5368 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5369 js2-LET
5370 js2-NEW js2-NULL
5371 js2-RETURN
5372 js2-SWITCH
5373 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5374 js2-VAR
5375 js2-WHILE js2-WITH
5376 js2-YIELD)))
5377 (dolist (i tokens)
5378 (aset table i 'font-lock-keyword-face))
5379 (aset table js2-STRING 'font-lock-string-face)
5380 (aset table js2-REGEXP 'font-lock-string-face)
5381 (aset table js2-COMMENT 'font-lock-comment-face)
5382 (aset table js2-THIS 'font-lock-builtin-face)
5383 (aset table js2-VOID 'font-lock-constant-face)
5384 (aset table js2-NULL 'font-lock-constant-face)
5385 (aset table js2-TRUE 'font-lock-constant-face)
5386 (aset table js2-FALSE 'font-lock-constant-face)
5387 (aset table js2-NOT 'font-lock-negation-char-face)
5388 table)
5389 "Vector whose values are non-nil for tokens that are keywords.
5390 The values are default faces to use for highlighting the keywords.")
5391
5392 ;; FIXME: Support strict mode-only future reserved words, after we know
5393 ;; which parts scopes are in strict mode, and which are not.
5394 (defconst js2-reserved-words '(class export extends import super)
5395 "Future reserved keywords in ECMAScript 5.")
5396
5397 (defconst js2-keyword-names
5398 (let ((table (make-hash-table :test 'equal)))
5399 (loop for k in js2-keywords
5400 do (puthash
5401 (symbol-name k) ; instanceof
5402 (intern (concat "js2-"
5403 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5404 table))
5405 table)
5406 "JavaScript keywords by name, mapped to their symbols.")
5407
5408 (defconst js2-reserved-word-names
5409 (let ((table (make-hash-table :test 'equal)))
5410 (loop for k in js2-reserved-words
5411 do
5412 (puthash (symbol-name k) 'js2-RESERVED table))
5413 table)
5414 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5415
5416 (defun js2-collect-string (buf)
5417 "Convert BUF, a list of chars, to a string.
5418 Reverses BUF before converting."
5419 (if buf
5420 (apply #'string (nreverse buf))
5421 ""))
5422
5423 (defun js2-string-to-keyword (s)
5424 "Return token for S, a string, if S is a keyword or reserved word.
5425 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5426 (or (gethash s js2-keyword-names)
5427 (gethash s js2-reserved-word-names)))
5428
5429 (defsubst js2-ts-set-char-token-bounds (token)
5430 "Used when next token is one character."
5431 (setf (js2-token-beg token) (1- js2-ts-cursor)
5432 (js2-token-end token) js2-ts-cursor))
5433
5434 (defsubst js2-ts-return (token type)
5435 "Update the `end' and `type' slots of TOKEN,
5436 then throw `return' with value TYPE."
5437 (setf (js2-token-end token) js2-ts-cursor
5438 (js2-token-type token) type)
5439 (throw 'return type))
5440
5441 (defun js2-x-digit-to-int (c accumulator)
5442 "Build up a hex number.
5443 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5444 corresponding number. Otherwise return -1."
5445 (catch 'return
5446 (catch 'check
5447 ;; Use 0..9 < A..Z < a..z
5448 (cond
5449 ((<= c ?9)
5450 (decf c ?0)
5451 (if (<= 0 c)
5452 (throw 'check nil)))
5453 ((<= c ?F)
5454 (when (<= ?A c)
5455 (decf c (- ?A 10))
5456 (throw 'check nil)))
5457 ((<= c ?f)
5458 (when (<= ?a c)
5459 (decf c (- ?a 10))
5460 (throw 'check nil))))
5461 (throw 'return -1))
5462 (logior c (lsh accumulator 4))))
5463
5464 (defun js2-get-token ()
5465 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5466 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5467 next saved token.
5468
5469 This function will not return a newline (js2-EOL) - instead, it
5470 gobbles newlines until it finds a non-newline token. Call
5471 `js2-peek-token-or-eol' when you care about newlines.
5472
5473 This function will also not return a js2-COMMENT. Instead, it
5474 records comments found in `js2-scanned-comments'. If the token
5475 returned by this function immediately follows a jsdoc comment,
5476 the token is flagged as such."
5477 (if (zerop js2-ti-lookahead)
5478 (js2-get-token-internal)
5479 (decf js2-ti-lookahead)
5480 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5481 (let ((tt (js2-current-token-type)))
5482 (assert (not (= tt js2-EOL)))
5483 tt)))
5484
5485 (defun js2-unget-token ()
5486 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5487 (incf js2-ti-lookahead)
5488 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5489
5490 (defun js2-get-token-internal ()
5491 (let* ((token (js2-get-token-internal-1)) ; call scanner
5492 (tt (js2-token-type token))
5493 saw-eol
5494 face)
5495 ;; process comments
5496 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5497 (if (= tt js2-EOL)
5498 (setq saw-eol t)
5499 (setq saw-eol nil)
5500 (when js2-record-comments
5501 (js2-record-comment token)))
5502 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5503 (setq token (js2-get-token-internal-1) ; call scanner again
5504 tt (js2-token-type token)))
5505
5506 (when saw-eol
5507 (setf (js2-token-follows-eol-p token) t))
5508
5509 ;; perform lexical fontification as soon as token is scanned
5510 (when js2-parse-ide-mode
5511 (cond
5512 ((minusp tt)
5513 (js2-record-face 'js2-error token))
5514 ((setq face (aref js2-kwd-tokens tt))
5515 (js2-record-face face token))
5516 ((and (= tt js2-NAME)
5517 (equal (js2-token-string token) "undefined"))
5518 (js2-record-face 'font-lock-constant-face token))))
5519 tt))
5520
5521 (defun js2-get-token-internal-1 ()
5522 "Return next JavaScript token type, an int such as js2-RETURN.
5523 During operation, creates an instance of `js2-token' struct, sets
5524 its relevant fields and puts it into `js2-ti-tokens'."
5525 (let (c c1 identifier-start is-unicode-escape-start
5526 contains-escape escape-val str result base
5527 quote-char val look-for-slash continue tt
5528 (token (js2-new-token 0)))
5529 (setq
5530 tt
5531 (catch 'return
5532 (while t
5533 ;; Eat whitespace, possibly sensitive to newlines.
5534 (setq continue t)
5535 (while continue
5536 (setq c (js2-get-char))
5537 (cond
5538 ((eq c js2-EOF_CHAR)
5539 (js2-unget-char)
5540 (js2-ts-set-char-token-bounds token)
5541 (throw 'return js2-EOF))
5542 ((eq c ?\n)
5543 (js2-ts-set-char-token-bounds token)
5544 (setq js2-ts-dirty-line nil)
5545 (throw 'return js2-EOL))
5546 ((not (js2-js-space-p c))
5547 (if (/= c ?-) ; in case end of HTML comment
5548 (setq js2-ts-dirty-line t))
5549 (setq continue nil))))
5550 ;; Assume the token will be 1 char - fixed up below.
5551 (js2-ts-set-char-token-bounds token)
5552 (when (eq c ?@)
5553 (throw 'return js2-XMLATTR))
5554 ;; identifier/keyword/instanceof?
5555 ;; watch out for starting with a <backslash>
5556 (cond
5557 ((eq c ?\\)
5558 (setq c (js2-get-char))
5559 (if (eq c ?u)
5560 (setq identifier-start t
5561 is-unicode-escape-start t
5562 js2-ts-string-buffer nil)
5563 (setq identifier-start nil)
5564 (js2-unget-char)
5565 (setq c ?\\)))
5566 (t
5567 (when (setq identifier-start (js2-identifier-start-p c))
5568 (setq js2-ts-string-buffer nil)
5569 (js2-add-to-string c))))
5570 (when identifier-start
5571 (setq contains-escape is-unicode-escape-start)
5572 (catch 'break
5573 (while t
5574 (if is-unicode-escape-start
5575 ;; strictly speaking we should probably push-back
5576 ;; all the bad characters if the <backslash>uXXXX
5577 ;; sequence is malformed. But since there isn't a
5578 ;; correct context(is there?) for a bad Unicode
5579 ;; escape sequence in an identifier, we can report
5580 ;; an error here.
5581 (progn
5582 (setq escape-val 0)
5583 (dotimes (_ 4)
5584 (setq c (js2-get-char)
5585 escape-val (js2-x-digit-to-int c escape-val))
5586 ;; Next check takes care of c < 0 and bad escape
5587 (if (minusp escape-val)
5588 (throw 'break nil)))
5589 (if (minusp escape-val)
5590 (js2-report-scan-error "msg.invalid.escape" t))
5591 (js2-add-to-string escape-val)
5592 (setq is-unicode-escape-start nil))
5593 (setq c (js2-get-char))
5594 (cond
5595 ((eq c ?\\)
5596 (setq c (js2-get-char))
5597 (if (eq c ?u)
5598 (setq is-unicode-escape-start t
5599 contains-escape t)
5600 (js2-report-scan-error "msg.illegal.character" t)))
5601 (t
5602 (if (or (eq c js2-EOF_CHAR)
5603 (not (js2-identifier-part-p c)))
5604 (throw 'break nil))
5605 (js2-add-to-string c))))))
5606 (js2-unget-char)
5607 (setf str (js2-collect-string js2-ts-string-buffer)
5608 (js2-token-end token) js2-ts-cursor)
5609 ;; FIXME: Invalid in ES5 and ES6, see
5610 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5611 ;; Probably should just drop this conditional.
5612 (unless contains-escape
5613 ;; OPT we shouldn't have to make a string (object!) to
5614 ;; check if it's a keyword.
5615 ;; Return the corresponding token if it's a keyword
5616 (when (setq result (js2-string-to-keyword str))
5617 (if (and (< js2-language-version 170)
5618 (memq result '(js2-LET js2-YIELD)))
5619 ;; LET and YIELD are tokens only in 1.7 and later
5620 (setq result 'js2-NAME))
5621 (when (eq result 'js2-RESERVED)
5622 (setf (js2-token-string token) str))
5623 (throw 'return (js2-tt-code result))))
5624 ;; If we want to intern these as Rhino does, just use (intern str)
5625 (setf (js2-token-string token) str)
5626 (throw 'return js2-NAME)) ; end identifier/kwd check
5627 ;; is it a number?
5628 (when (or (js2-digit-p c)
5629 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5630 (setq js2-ts-string-buffer nil
5631 base 10)
5632 (when (eq c ?0)
5633 (setq c (js2-get-char))
5634 (cond
5635 ((or (eq c ?x) (eq c ?X))
5636 (setq base 16)
5637 (setq c (js2-get-char)))
5638 ((and (or (eq c ?b) (eq c ?B))
5639 (>= js2-language-version 200))
5640 (setq base 2)
5641 (setq c (js2-get-char)))
5642 ((and (or (eq c ?o) (eq c ?O))
5643 (>= js2-language-version 200))
5644 (setq base 8)
5645 (setq c (js2-get-char)))
5646 ((js2-digit-p c)
5647 (setq base 'maybe-8))
5648 (t
5649 (js2-add-to-string ?0))))
5650 (cond
5651 ((eq base 16)
5652 (if (> 0 (js2-x-digit-to-int c 0))
5653 (js2-report-scan-error "msg.missing.hex.digits")
5654 (while (<= 0 (js2-x-digit-to-int c 0))
5655 (js2-add-to-string c)
5656 (setq c (js2-get-char)))))
5657 ((eq base 2)
5658 (if (not (memq c '(?0 ?1)))
5659 (js2-report-scan-error "msg.missing.binary.digits")
5660 (while (memq c '(?0 ?1))
5661 (js2-add-to-string c)
5662 (setq c (js2-get-char)))))
5663 ((eq base 8)
5664 (if (or (> ?0 c) (< ?7 c))
5665 (js2-report-scan-error "msg.missing.octal.digits")
5666 (while (and (<= ?0 c) (>= ?7 c))
5667 (js2-add-to-string c)
5668 (setq c (js2-get-char)))))
5669 (t
5670 (while (and (<= ?0 c) (<= c ?9))
5671 ;; We permit 08 and 09 as decimal numbers, which
5672 ;; makes our behavior a superset of the ECMA
5673 ;; numeric grammar. We might not always be so
5674 ;; permissive, so we warn about it.
5675 (when (and (eq base 'maybe-8) (>= c ?8))
5676 (js2-report-warning "msg.bad.octal.literal"
5677 (if (eq c ?8) "8" "9"))
5678 (setq base 10))
5679 (js2-add-to-string c)
5680 (setq c (js2-get-char)))
5681 (when (eq base 'maybe-8)
5682 (setq base 8))))
5683 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5684 (when (eq c ?.)
5685 (loop do
5686 (js2-add-to-string c)
5687 (setq c (js2-get-char))
5688 while (js2-digit-p c)))
5689 (when (memq c '(?e ?E))
5690 (js2-add-to-string c)
5691 (setq c (js2-get-char))
5692 (when (memq c '(?+ ?-))
5693 (js2-add-to-string c)
5694 (setq c (js2-get-char)))
5695 (unless (js2-digit-p c)
5696 (js2-report-scan-error "msg.missing.exponent" t))
5697 (loop do
5698 (js2-add-to-string c)
5699 (setq c (js2-get-char))
5700 while (js2-digit-p c))))
5701 (js2-unget-char)
5702 (let ((str (js2-set-string-from-buffer token)))
5703 (setf (js2-token-number token)
5704 (js2-string-to-number str base)))
5705 (throw 'return js2-NUMBER))
5706 ;; is it a string?
5707 (when (memq c '(?\" ?\'))
5708 ;; We attempt to accumulate a string the fast way, by
5709 ;; building it directly out of the reader. But if there
5710 ;; are any escaped characters in the string, we revert to
5711 ;; building it out of a string buffer.
5712 (setq quote-char c
5713 js2-ts-string-buffer nil
5714 c (js2-get-char))
5715 (catch 'break
5716 (while (/= c quote-char)
5717 (catch 'continue
5718 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5719 (js2-unget-char)
5720 (setf (js2-token-end token) js2-ts-cursor)
5721 (js2-report-error "msg.unterminated.string.lit")
5722 (throw 'return js2-STRING))
5723 (when (eq c ?\\)
5724 ;; We've hit an escaped character
5725 (setq c (js2-get-char))
5726 (case c
5727 (?b (setq c ?\b))
5728 (?f (setq c ?\f))
5729 (?n (setq c ?\n))
5730 (?r (setq c ?\r))
5731 (?t (setq c ?\t))
5732 (?v (setq c ?\v))
5733 (?u
5734 (setq c1 (js2-read-unicode-escape))
5735 (if js2-parse-ide-mode
5736 (if c1
5737 (progn
5738 ;; just copy the string in IDE-mode
5739 (js2-add-to-string ?\\)
5740 (js2-add-to-string ?u)
5741 (dotimes (_ 3)
5742 (js2-add-to-string (js2-get-char)))
5743 (setq c (js2-get-char))) ; added at end of loop
5744 ;; flag it as an invalid escape
5745 (js2-report-warning "msg.invalid.escape"
5746 nil (- js2-ts-cursor 2) 6))
5747 ;; Get 4 hex digits; if the u escape is not
5748 ;; followed by 4 hex digits, use 'u' + the
5749 ;; literal character sequence that follows.
5750 (js2-add-to-string ?u)
5751 (setq escape-val 0)
5752 (dotimes (_ 4)
5753 (setq c (js2-get-char)
5754 escape-val (js2-x-digit-to-int c escape-val))
5755 (if (minusp escape-val)
5756 (throw 'continue nil))
5757 (js2-add-to-string c))
5758 ;; prepare for replace of stored 'u' sequence by escape value
5759 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5760 c escape-val)))
5761 (?x
5762 ;; Get 2 hex digits, defaulting to 'x'+literal
5763 ;; sequence, as above.
5764 (setq c (js2-get-char)
5765 escape-val (js2-x-digit-to-int c 0))
5766 (if (minusp escape-val)
5767 (progn
5768 (js2-add-to-string ?x)
5769 (throw 'continue nil))
5770 (setq c1 c
5771 c (js2-get-char)
5772 escape-val (js2-x-digit-to-int c escape-val))
5773 (if (minusp escape-val)
5774 (progn
5775 (js2-add-to-string ?x)
5776 (js2-add-to-string c1)
5777 (throw 'continue nil))
5778 ;; got 2 hex digits
5779 (setq c escape-val))))
5780 (?\n
5781 ;; Remove line terminator after escape to follow
5782 ;; SpiderMonkey and C/C++
5783 (setq c (js2-get-char))
5784 (throw 'continue nil))
5785 (t
5786 (when (and (<= ?0 c) (< c ?8))
5787 (setq val (- c ?0)
5788 c (js2-get-char))
5789 (when (and (<= ?0 c) (< c ?8))
5790 (setq val (- (+ (* 8 val) c) ?0)
5791 c (js2-get-char))
5792 (when (and (<= ?0 c)
5793 (< c ?8)
5794 (< val #o37))
5795 ;; c is 3rd char of octal sequence only
5796 ;; if the resulting val <= 0377
5797 (setq val (- (+ (* 8 val) c) ?0)
5798 c (js2-get-char))))
5799 (js2-unget-char)
5800 (setq c val)))))
5801 (js2-add-to-string c)
5802 (setq c (js2-get-char)))))
5803 (js2-set-string-from-buffer token)
5804 (throw 'return js2-STRING))
5805 (js2-ts-return token
5806 (case c
5807 (?\;
5808 (throw 'return js2-SEMI))
5809 (?\[
5810 (throw 'return js2-LB))
5811 (?\]
5812 (throw 'return js2-RB))
5813 (?{
5814 (throw 'return js2-LC))
5815 (?}
5816 (throw 'return js2-RC))
5817 (?\(
5818 (throw 'return js2-LP))
5819 (?\)
5820 (throw 'return js2-RP))
5821 (?,
5822 (throw 'return js2-COMMA))
5823 (??
5824 (throw 'return js2-HOOK))
5825 (?:
5826 (if (js2-match-char ?:)
5827 js2-COLONCOLON
5828 (throw 'return js2-COLON)))
5829 (?.
5830 (if (js2-match-char ?.)
5831 (if (js2-match-char ?.)
5832 js2-TRIPLEDOT js2-DOTDOT)
5833 (if (js2-match-char ?\()
5834 js2-DOTQUERY
5835 (throw 'return js2-DOT))))
5836 (?|
5837 (if (js2-match-char ?|)
5838 (throw 'return js2-OR)
5839 (if (js2-match-char ?=)
5840 js2-ASSIGN_BITOR
5841 (throw 'return js2-BITOR))))
5842 (?^
5843 (if (js2-match-char ?=)
5844 js2-ASSIGN_BITOR
5845 (throw 'return js2-BITXOR)))
5846 (?&
5847 (if (js2-match-char ?&)
5848 (throw 'return js2-AND)
5849 (if (js2-match-char ?=)
5850 js2-ASSIGN_BITAND
5851 (throw 'return js2-BITAND))))
5852 (?=
5853 (if (js2-match-char ?=)
5854 (if (js2-match-char ?=)
5855 js2-SHEQ
5856 (throw 'return js2-EQ))
5857 (if (js2-match-char ?>)
5858 (js2-ts-return token js2-ARROW)
5859 (throw 'return js2-ASSIGN))))
5860 (?!
5861 (if (js2-match-char ?=)
5862 (if (js2-match-char ?=)
5863 js2-SHNE
5864 js2-NE)
5865 (throw 'return js2-NOT)))
5866 (?<
5867 ;; NB:treat HTML begin-comment as comment-till-eol
5868 (when (js2-match-char ?!)
5869 (when (js2-match-char ?-)
5870 (when (js2-match-char ?-)
5871 (js2-skip-line)
5872 (setf (js2-token-comment-type (js2-current-token)) 'html)
5873 (throw 'return js2-COMMENT)))
5874 (js2-unget-char))
5875 (if (js2-match-char ?<)
5876 (if (js2-match-char ?=)
5877 js2-ASSIGN_LSH
5878 js2-LSH)
5879 (if (js2-match-char ?=)
5880 js2-LE
5881 (throw 'return js2-LT))))
5882 (?>
5883 (if (js2-match-char ?>)
5884 (if (js2-match-char ?>)
5885 (if (js2-match-char ?=)
5886 js2-ASSIGN_URSH
5887 js2-URSH)
5888 (if (js2-match-char ?=)
5889 js2-ASSIGN_RSH
5890 js2-RSH))
5891 (if (js2-match-char ?=)
5892 js2-GE
5893 (throw 'return js2-GT))))
5894 (?*
5895 (if (js2-match-char ?=)
5896 js2-ASSIGN_MUL
5897 (throw 'return js2-MUL)))
5898 (?/
5899 ;; is it a // comment?
5900 (when (js2-match-char ?/)
5901 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5902 (js2-skip-line)
5903 (setf (js2-token-comment-type token) 'line)
5904 ;; include newline so highlighting goes to end of window
5905 (incf (js2-token-end token))
5906 (throw 'return js2-COMMENT))
5907 ;; is it a /* comment?
5908 (when (js2-match-char ?*)
5909 (setf look-for-slash nil
5910 (js2-token-beg token) (- js2-ts-cursor 2)
5911 (js2-token-comment-type token)
5912 (if (js2-match-char ?*)
5913 (progn
5914 (setq look-for-slash t)
5915 'jsdoc)
5916 'block))
5917 (while t
5918 (setq c (js2-get-char))
5919 (cond
5920 ((eq c js2-EOF_CHAR)
5921 (setf (js2-token-end token) (1- js2-ts-cursor))
5922 (js2-report-error "msg.unterminated.comment")
5923 (throw 'return js2-COMMENT))
5924 ((eq c ?*)
5925 (setq look-for-slash t))
5926 ((eq c ?/)
5927 (if look-for-slash
5928 (js2-ts-return token js2-COMMENT)))
5929 (t
5930 (setf look-for-slash nil
5931 (js2-token-end token) js2-ts-cursor)))))
5932 (if (js2-match-char ?=)
5933 js2-ASSIGN_DIV
5934 (throw 'return js2-DIV)))
5935 (?#
5936 (when js2-skip-preprocessor-directives
5937 (js2-skip-line)
5938 (setf (js2-token-comment-type token) 'preprocessor
5939 (js2-token-end token) js2-ts-cursor)
5940 (throw 'return js2-COMMENT))
5941 (throw 'return js2-ERROR))
5942 (?%
5943 (if (js2-match-char ?=)
5944 js2-ASSIGN_MOD
5945 (throw 'return js2-MOD)))
5946 (?~
5947 (throw 'return js2-BITNOT))
5948 (?+
5949 (if (js2-match-char ?=)
5950 js2-ASSIGN_ADD
5951 (if (js2-match-char ?+)
5952 js2-INC
5953 (throw 'return js2-ADD))))
5954 (?-
5955 (cond
5956 ((js2-match-char ?=)
5957 (setq c js2-ASSIGN_SUB))
5958 ((js2-match-char ?-)
5959 (unless js2-ts-dirty-line
5960 ;; treat HTML end-comment after possible whitespace
5961 ;; after line start as comment-until-eol
5962 (when (js2-match-char ?>)
5963 (js2-skip-line)
5964 (setf (js2-token-comment-type (js2-current-token)) 'html)
5965 (throw 'return js2-COMMENT)))
5966 (setq c js2-DEC))
5967 (t
5968 (setq c js2-SUB)))
5969 (setq js2-ts-dirty-line t)
5970 c)
5971 (otherwise
5972 (js2-report-scan-error "msg.illegal.character")))))))
5973 (setf (js2-token-type token) tt)
5974 token))
5975
5976 (defsubst js2-string-to-number (str base)
5977 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5978 (condition-case nil
5979 (string-to-number str base)
5980 (overflow-error -1)))
5981
5982 (defun js2-read-regexp (start-tt)
5983 "Called by parser when it gets / or /= in literal context."
5984 (let (c err
5985 in-class ; inside a '[' .. ']' character-class
5986 flags
5987 (continue t)
5988 (token (js2-new-token 0)))
5989 (setq js2-ts-string-buffer nil)
5990 (if (eq start-tt js2-ASSIGN_DIV)
5991 ;; mis-scanned /=
5992 (js2-add-to-string ?=)
5993 (if (not (eq start-tt js2-DIV))
5994 (error "failed assertion")))
5995 (while (and (not err)
5996 (or (/= (setq c (js2-get-char)) ?/)
5997 in-class))
5998 (cond
5999 ((or (= c ?\n)
6000 (= c js2-EOF_CHAR))
6001 (setf (js2-token-end token) (1- js2-ts-cursor)
6002 err t
6003 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6004 (js2-report-error "msg.unterminated.re.lit"))
6005 (t (cond
6006 ((= c ?\\)
6007 (js2-add-to-string c)
6008 (setq c (js2-get-char)))
6009 ((= c ?\[)
6010 (setq in-class t))
6011 ((= c ?\])
6012 (setq in-class nil)))
6013 (js2-add-to-string c))))
6014 (unless err
6015 (while continue
6016 (cond
6017 ((js2-match-char ?g)
6018 (push ?g flags))
6019 ((js2-match-char ?i)
6020 (push ?i flags))
6021 ((js2-match-char ?m)
6022 (push ?m flags))
6023 ((and (js2-match-char ?u)
6024 (>= js2-language-version 200))
6025 (push ?u flags))
6026 ((and (js2-match-char ?y)
6027 (>= js2-language-version 200))
6028 (push ?y flags))
6029 (t
6030 (setq continue nil))))
6031 (if (js2-alpha-p (js2-peek-char))
6032 (js2-report-scan-error "msg.invalid.re.flag" t
6033 js2-ts-cursor 1))
6034 (js2-set-string-from-buffer token))
6035 (js2-collect-string flags)))
6036
6037 (defun js2-get-first-xml-token ()
6038 (setq js2-ts-xml-open-tags-count 0
6039 js2-ts-is-xml-attribute nil
6040 js2-ts-xml-is-tag-content nil)
6041 (js2-unget-char)
6042 (js2-get-next-xml-token))
6043
6044 (defun js2-xml-discard-string (token)
6045 "Throw away the string in progress and flag an XML parse error."
6046 (setf js2-ts-string-buffer nil
6047 (js2-token-string token) nil)
6048 (js2-report-scan-error "msg.XML.bad.form" t))
6049
6050 (defun js2-get-next-xml-token ()
6051 (setq js2-ts-string-buffer nil) ; for recording the XML
6052 (let ((token (js2-new-token 0))
6053 c result)
6054 (setq result
6055 (catch 'return
6056 (while t
6057 (setq c (js2-get-char))
6058 (cond
6059 ((= c js2-EOF_CHAR)
6060 (throw 'return js2-ERROR))
6061 (js2-ts-xml-is-tag-content
6062 (case c
6063 (?>
6064 (js2-add-to-string c)
6065 (setq js2-ts-xml-is-tag-content nil
6066 js2-ts-is-xml-attribute nil))
6067 (?/
6068 (js2-add-to-string c)
6069 (when (eq ?> (js2-peek-char))
6070 (setq c (js2-get-char))
6071 (js2-add-to-string c)
6072 (setq js2-ts-xml-is-tag-content nil)
6073 (decf js2-ts-xml-open-tags-count)))
6074 (?{
6075 (js2-unget-char)
6076 (js2-set-string-from-buffer token)
6077 (throw 'return js2-XML))
6078 ((?\' ?\")
6079 (js2-add-to-string c)
6080 (unless (js2-read-quoted-string c token)
6081 (throw 'return js2-ERROR)))
6082 (?=
6083 (js2-add-to-string c)
6084 (setq js2-ts-is-xml-attribute t))
6085 ((? ?\t ?\r ?\n)
6086 (js2-add-to-string c))
6087 (t
6088 (js2-add-to-string c)
6089 (setq js2-ts-is-xml-attribute nil)))
6090 (when (and (not js2-ts-xml-is-tag-content)
6091 (zerop js2-ts-xml-open-tags-count))
6092 (js2-set-string-from-buffer token)
6093 (throw 'return js2-XMLEND)))
6094 (t
6095 ;; else not tag content
6096 (case c
6097 (?<
6098 (js2-add-to-string c)
6099 (setq c (js2-peek-char))
6100 (case c
6101 (?!
6102 (setq c (js2-get-char)) ;; skip !
6103 (js2-add-to-string c)
6104 (setq c (js2-peek-char))
6105 (case c
6106 (?-
6107 (setq c (js2-get-char)) ;; skip -
6108 (js2-add-to-string c)
6109 (if (eq c ?-)
6110 (progn
6111 (js2-add-to-string c)
6112 (unless (js2-read-xml-comment token)
6113 (throw 'return js2-ERROR)))
6114 (js2-xml-discard-string token)
6115 (throw 'return js2-ERROR)))
6116 (?\[
6117 (setq c (js2-get-char)) ;; skip [
6118 (js2-add-to-string c)
6119 (if (and (= (js2-get-char) ?C)
6120 (= (js2-get-char) ?D)
6121 (= (js2-get-char) ?A)
6122 (= (js2-get-char) ?T)
6123 (= (js2-get-char) ?A)
6124 (= (js2-get-char) ?\[))
6125 (progn
6126 (js2-add-to-string ?C)
6127 (js2-add-to-string ?D)
6128 (js2-add-to-string ?A)
6129 (js2-add-to-string ?T)
6130 (js2-add-to-string ?A)
6131 (js2-add-to-string ?\[)
6132 (unless (js2-read-cdata token)
6133 (throw 'return js2-ERROR)))
6134 (js2-xml-discard-string token)
6135 (throw 'return js2-ERROR)))
6136 (t
6137 (unless (js2-read-entity token)
6138 (throw 'return js2-ERROR))))
6139 ;; Allow bare CDATA section, e.g.:
6140 ;; let xml = <![CDATA[ foo bar baz ]]>;
6141 (when (zerop js2-ts-xml-open-tags-count)
6142 (throw 'return js2-XMLEND)))
6143 (??
6144 (setq c (js2-get-char)) ;; skip ?
6145 (js2-add-to-string c)
6146 (unless (js2-read-PI token)
6147 (throw 'return js2-ERROR)))
6148 (?/
6149 ;; end tag
6150 (setq c (js2-get-char)) ;; skip /
6151 (js2-add-to-string c)
6152 (when (zerop js2-ts-xml-open-tags-count)
6153 (js2-xml-discard-string token)
6154 (throw 'return js2-ERROR))
6155 (setq js2-ts-xml-is-tag-content t)
6156 (decf js2-ts-xml-open-tags-count))
6157 (t
6158 ;; start tag
6159 (setq js2-ts-xml-is-tag-content t)
6160 (incf js2-ts-xml-open-tags-count))))
6161 (?{
6162 (js2-unget-char)
6163 (js2-set-string-from-buffer token)
6164 (throw 'return js2-XML))
6165 (t
6166 (js2-add-to-string c))))))))
6167 (setf (js2-token-end token) js2-ts-cursor)
6168 (setf (js2-token-type token) result)
6169 result))
6170
6171 (defun js2-read-quoted-string (quote token)
6172 (let (c)
6173 (catch 'return
6174 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6175 (js2-add-to-string c)
6176 (if (eq c quote)
6177 (throw 'return t)))
6178 (js2-xml-discard-string token) ;; throw away string in progress
6179 nil)))
6180
6181 (defun js2-read-xml-comment (token)
6182 (let ((c (js2-get-char)))
6183 (catch 'return
6184 (while (/= c js2-EOF_CHAR)
6185 (catch 'continue
6186 (js2-add-to-string c)
6187 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6188 (setq c (js2-get-char))
6189 (js2-add-to-string c)
6190 (if (eq (js2-peek-char) ?>)
6191 (progn
6192 (setq c (js2-get-char)) ;; skip >
6193 (js2-add-to-string c)
6194 (throw 'return t))
6195 (throw 'continue nil)))
6196 (setq c (js2-get-char))))
6197 (js2-xml-discard-string token)
6198 nil)))
6199
6200 (defun js2-read-cdata (token)
6201 (let ((c (js2-get-char)))
6202 (catch 'return
6203 (while (/= c js2-EOF_CHAR)
6204 (catch 'continue
6205 (js2-add-to-string c)
6206 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6207 (setq c (js2-get-char))
6208 (js2-add-to-string c)
6209 (if (eq (js2-peek-char) ?>)
6210 (progn
6211 (setq c (js2-get-char)) ;; Skip >
6212 (js2-add-to-string c)
6213 (throw 'return t))
6214 (throw 'continue nil)))
6215 (setq c (js2-get-char))))
6216 (js2-xml-discard-string token)
6217 nil)))
6218
6219 (defun js2-read-entity (token)
6220 (let ((decl-tags 1)
6221 c)
6222 (catch 'return
6223 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6224 (js2-add-to-string c)
6225 (case c
6226 (?<
6227 (incf decl-tags))
6228 (?>
6229 (decf decl-tags)
6230 (if (zerop decl-tags)
6231 (throw 'return t)))))
6232 (js2-xml-discard-string token)
6233 nil)))
6234
6235 (defun js2-read-PI (token)
6236 "Scan an XML processing instruction."
6237 (let (c)
6238 (catch 'return
6239 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6240 (js2-add-to-string c)
6241 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6242 (setq c (js2-get-char)) ;; Skip >
6243 (js2-add-to-string c)
6244 (throw 'return t)))
6245 (js2-xml-discard-string token)
6246 nil)))
6247
6248 ;;; Highlighting
6249
6250 (defun js2-set-face (beg end face &optional record)
6251 "Fontify a region. If RECORD is non-nil, record for later."
6252 (when (plusp js2-highlight-level)
6253 (setq beg (min (point-max) beg)
6254 beg (max (point-min) beg)
6255 end (min (point-max) end)
6256 end (max (point-min) end))
6257 (if record
6258 (push (list beg end face) js2-mode-fontifications)
6259 (put-text-property beg end 'font-lock-face face))))
6260
6261 (defsubst js2-clear-face (beg end)
6262 (remove-text-properties beg end '(font-lock-face nil
6263 help-echo nil
6264 point-entered nil
6265 c-in-sws nil)))
6266
6267 (defconst js2-ecma-global-props
6268 (concat "^"
6269 (regexp-opt
6270 '("Infinity" "NaN" "undefined" "arguments") t)
6271 "$")
6272 "Value properties of the Ecma-262 Global Object.
6273 Shown at or above `js2-highlight-level' 2.")
6274
6275 ;; might want to add the name "arguments" to this list?
6276 (defconst js2-ecma-object-props
6277 (concat "^"
6278 (regexp-opt
6279 '("prototype" "__proto__" "__parent__") t)
6280 "$")
6281 "Value properties of the Ecma-262 Object constructor.
6282 Shown at or above `js2-highlight-level' 2.")
6283
6284 (defconst js2-ecma-global-funcs
6285 (concat
6286 "^"
6287 (regexp-opt
6288 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6289 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6290 "$")
6291 "Function properties of the Ecma-262 Global object.
6292 Shown at or above `js2-highlight-level' 2.")
6293
6294 (defconst js2-ecma-number-props
6295 (concat "^"
6296 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6297 "NEGATIVE_INFINITY"
6298 "POSITIVE_INFINITY") t)
6299 "$")
6300 "Properties of the Ecma-262 Number constructor.
6301 Shown at or above `js2-highlight-level' 2.")
6302
6303 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6304 "Properties of the Ecma-262 Date constructor.
6305 Shown at or above `js2-highlight-level' 2.")
6306
6307 (defconst js2-ecma-math-props
6308 (concat "^"
6309 (regexp-opt
6310 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6311 t)
6312 "$")
6313 "Properties of the Ecma-262 Math object.
6314 Shown at or above `js2-highlight-level' 2.")
6315
6316 (defconst js2-ecma-math-funcs
6317 (concat "^"
6318 (regexp-opt
6319 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6320 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6321 "$")
6322 "Function properties of the Ecma-262 Math object.
6323 Shown at or above `js2-highlight-level' 2.")
6324
6325 (defconst js2-ecma-function-props
6326 (concat
6327 "^"
6328 (regexp-opt
6329 '(;; properties of the Object prototype object
6330 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6331 "toLocaleString" "toString" "valueOf"
6332 ;; properties of the Function prototype object
6333 "apply" "call"
6334 ;; properties of the Array prototype object
6335 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6336 "splice" "unshift"
6337 ;; properties of the String prototype object
6338 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6339 "localeCompare" "match" "replace" "search" "split" "substring"
6340 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6341 "toUpperCase"
6342 ;; properties of the Number prototype object
6343 "toExponential" "toFixed" "toPrecision"
6344 ;; properties of the Date prototype object
6345 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6346 "getMinutes" "getMonth" "getSeconds" "getTime"
6347 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6348 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6349 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6350 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6351 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6352 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6353 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6354 "toTimeString" "toUTCString"
6355 ;; properties of the RegExp prototype object
6356 "exec" "test"
6357 ;; properties of the JSON prototype object
6358 "parse" "stringify"
6359 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6360 "toSource" "__defineGetter__" "__defineSetter__"
6361 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6362 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6363 t)
6364 "$")
6365 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6366 Shown at or above `js2-highlight-level' 3.")
6367
6368 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6369 (let ((target-name (and target
6370 (js2-name-node-p target)
6371 (js2-name-node-name target)))
6372 (prop-name (if prop (js2-name-node-name prop)))
6373 (level2 (>= js2-highlight-level 2))
6374 (level3 (>= js2-highlight-level 3)))
6375 (when level2
6376 (let ((face
6377 (if call-p
6378 (cond
6379 ((and target prop)
6380 (cond
6381 ((and level3 (string-match js2-ecma-function-props prop-name))
6382 'font-lock-builtin-face)
6383 ((and target-name prop)
6384 (cond
6385 ((string= target-name "Date")
6386 (if (string-match js2-ecma-date-props prop-name)
6387 'font-lock-builtin-face))
6388 ((string= target-name "Math")
6389 (if (string-match js2-ecma-math-funcs prop-name)
6390 'font-lock-builtin-face))))))
6391 (prop
6392 (if (string-match js2-ecma-global-funcs prop-name)
6393 'font-lock-builtin-face)))
6394 (cond
6395 ((and target prop)
6396 (cond
6397 ((string= target-name "Number")
6398 (if (string-match js2-ecma-number-props prop-name)
6399 'font-lock-constant-face))
6400 ((string= target-name "Math")
6401 (if (string-match js2-ecma-math-props prop-name)
6402 'font-lock-constant-face))))
6403 (prop
6404 (if (string-match js2-ecma-object-props prop-name)
6405 'font-lock-constant-face))))))
6406 (when face
6407 (let ((pos (+ (js2-node-pos parent) ; absolute
6408 (js2-node-pos prop)))) ; relative
6409 (js2-set-face pos
6410 (+ pos (js2-node-len prop))
6411 face 'record)))))))
6412
6413 (defun js2-parse-highlight-member-expr-node (node)
6414 "Perform syntax highlighting of EcmaScript built-in properties.
6415 The variable `js2-highlight-level' governs this highighting."
6416 (let (face target prop name pos end parent call-p callee)
6417 (cond
6418 ;; case 1: simple name, e.g. foo
6419 ((js2-name-node-p node)
6420 (setq name (js2-name-node-name node))
6421 ;; possible for name to be nil in rare cases - saw it when
6422 ;; running js2-mode on an elisp buffer. Might as well try to
6423 ;; make it so js2-mode never barfs.
6424 (when name
6425 (setq face (if (string-match js2-ecma-global-props name)
6426 'font-lock-constant-face))
6427 (when face
6428 (setq pos (js2-node-pos node)
6429 end (+ pos (js2-node-len node)))
6430 (js2-set-face pos end face 'record))))
6431 ;; case 2: property access or function call
6432 ((or (js2-prop-get-node-p node)
6433 ;; highlight function call if expr is a prop-get node
6434 ;; or a plain name (i.e. unqualified function call)
6435 (and (setq call-p (js2-call-node-p node))
6436 (setq callee (js2-call-node-target node)) ; separate setq!
6437 (or (js2-prop-get-node-p callee)
6438 (js2-name-node-p callee))))
6439 (setq parent node
6440 node (if call-p callee node))
6441 (if (and call-p (js2-name-node-p callee))
6442 (setq prop callee)
6443 (setq target (js2-prop-get-node-left node)
6444 prop (js2-prop-get-node-right node)))
6445 (cond
6446 ((js2-name-node-p prop)
6447 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6448 (js2-parse-highlight-prop-get parent target prop call-p))
6449 ((js2-name-node-p target)
6450 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6451 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6452
6453 (defun js2-parse-highlight-member-expr-fn-name (expr)
6454 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6455 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6456 We currently only handle the case where the last component is a prop-get
6457 of a simple name. Called before EXPR has a parent node."
6458 (let (pos
6459 (name (and (js2-prop-get-node-p expr)
6460 (js2-prop-get-node-right expr))))
6461 (when (js2-name-node-p name)
6462 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6463 (js2-node-pos name)))
6464 (+ pos (js2-node-len name))
6465 'font-lock-function-name-face
6466 'record))))
6467
6468 ;; source: http://jsdoc.sourceforge.net/
6469 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6470 ;; allows type specifications, and needs work before entering the wild.
6471
6472 (defconst js2-jsdoc-param-tag-regexp
6473 (concat "^\\s-*\\*+\\s-*\\(@"
6474 "\\(?:param\\|argument\\)"
6475 "\\)"
6476 "\\s-*\\({[^}]+}\\)?" ; optional type
6477 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6478 "\\>")
6479 "Matches jsdoc tags with optional type and optional param name.")
6480
6481 (defconst js2-jsdoc-typed-tag-regexp
6482 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6483 (regexp-opt
6484 '("enum"
6485 "extends"
6486 "field"
6487 "id"
6488 "implements"
6489 "lends"
6490 "mods"
6491 "requires"
6492 "return"
6493 "returns"
6494 "throw"
6495 "throws"))
6496 "\\)\\)\\s-*\\({[^}]+}\\)?")
6497 "Matches jsdoc tags with optional type.")
6498
6499 (defconst js2-jsdoc-arg-tag-regexp
6500 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6501 (regexp-opt
6502 '("alias"
6503 "augments"
6504 "borrows"
6505 "bug"
6506 "base"
6507 "config"
6508 "default"
6509 "define"
6510 "exception"
6511 "function"
6512 "member"
6513 "memberOf"
6514 "name"
6515 "namespace"
6516 "property"
6517 "since"
6518 "suppress"
6519 "this"
6520 "throws"
6521 "type"
6522 "version"))
6523 "\\)\\)\\s-+\\([^ \t]+\\)")
6524 "Matches jsdoc tags with a single argument.")
6525
6526 (defconst js2-jsdoc-empty-tag-regexp
6527 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6528 (regexp-opt
6529 '("addon"
6530 "author"
6531 "class"
6532 "const"
6533 "constant"
6534 "constructor"
6535 "constructs"
6536 "deprecated"
6537 "desc"
6538 "description"
6539 "event"
6540 "example"
6541 "exec"
6542 "export"
6543 "fileoverview"
6544 "final"
6545 "function"
6546 "hidden"
6547 "ignore"
6548 "implicitCast"
6549 "inheritDoc"
6550 "inner"
6551 "interface"
6552 "license"
6553 "noalias"
6554 "noshadow"
6555 "notypecheck"
6556 "override"
6557 "owner"
6558 "preserve"
6559 "preserveTry"
6560 "private"
6561 "protected"
6562 "public"
6563 "static"
6564 "supported"
6565 ))
6566 "\\)\\)\\s-*")
6567 "Matches empty jsdoc tags.")
6568
6569 (defconst js2-jsdoc-link-tag-regexp
6570 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6571 "Matches a jsdoc link or code tag.")
6572
6573 (defconst js2-jsdoc-see-tag-regexp
6574 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6575 "Matches a jsdoc @see tag.")
6576
6577 (defconst js2-jsdoc-html-tag-regexp
6578 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6579 "Matches a simple (no attributes) html start- or end-tag.")
6580
6581 (defun js2-jsdoc-highlight-helper ()
6582 (js2-set-face (match-beginning 1)
6583 (match-end 1)
6584 'js2-jsdoc-tag)
6585 (if (match-beginning 2)
6586 (if (save-excursion
6587 (goto-char (match-beginning 2))
6588 (= (char-after) ?{))
6589 (js2-set-face (1+ (match-beginning 2))
6590 (1- (match-end 2))
6591 'js2-jsdoc-type)
6592 (js2-set-face (match-beginning 2)
6593 (match-end 2)
6594 'js2-jsdoc-value)))
6595 (if (match-beginning 3)
6596 (js2-set-face (match-beginning 3)
6597 (match-end 3)
6598 'js2-jsdoc-value)))
6599
6600 (defun js2-highlight-jsdoc (ast)
6601 "Highlight doc comment tags."
6602 (let ((comments (js2-ast-root-comments ast))
6603 beg end)
6604 (save-excursion
6605 (dolist (node comments)
6606 (when (eq (js2-comment-node-format node) 'jsdoc)
6607 (setq beg (js2-node-abs-pos node)
6608 end (+ beg (js2-node-len node)))
6609 (save-restriction
6610 (narrow-to-region beg end)
6611 (dolist (re (list js2-jsdoc-param-tag-regexp
6612 js2-jsdoc-typed-tag-regexp
6613 js2-jsdoc-arg-tag-regexp
6614 js2-jsdoc-link-tag-regexp
6615 js2-jsdoc-see-tag-regexp
6616 js2-jsdoc-empty-tag-regexp))
6617 (goto-char beg)
6618 (while (re-search-forward re nil t)
6619 (js2-jsdoc-highlight-helper)))
6620 ;; simple highlighting for html tags
6621 (goto-char beg)
6622 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6623 (js2-set-face (match-beginning 1)
6624 (match-end 1)
6625 'js2-jsdoc-html-tag-delimiter)
6626 (js2-set-face (match-beginning 2)
6627 (match-end 2)
6628 'js2-jsdoc-html-tag-name)
6629 (js2-set-face (match-beginning 3)
6630 (match-end 3)
6631 'js2-jsdoc-html-tag-delimiter))))))))
6632
6633 (defun js2-highlight-assign-targets (_node left right)
6634 "Highlight function properties and external variables."
6635 (let (leftpos name)
6636 ;; highlight vars and props assigned function values
6637 (when (or (js2-function-node-p right)
6638 (js2-class-node-p right))
6639 (cond
6640 ;; var foo = function() {...}
6641 ((js2-name-node-p left)
6642 (setq name left))
6643 ;; foo.bar.baz = function() {...}
6644 ((and (js2-prop-get-node-p left)
6645 (js2-name-node-p (js2-prop-get-node-right left)))
6646 (setq name (js2-prop-get-node-right left))))
6647 (when name
6648 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6649 (+ leftpos (js2-node-len name))
6650 'font-lock-function-name-face
6651 'record)))))
6652
6653 (defun js2-record-name-node (node)
6654 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6655 later. NODE must be a name node."
6656 (let ((leftpos (js2-node-abs-pos node)))
6657 (push (list node js2-current-scope
6658 leftpos
6659 (+ leftpos (js2-node-len node)))
6660 js2-recorded-identifiers)))
6661
6662 (defun js2-highlight-undeclared-vars ()
6663 "After entire parse is finished, look for undeclared variable references.
6664 We have to wait until entire buffer is parsed, since JavaScript permits var
6665 decls to occur after they're used.
6666
6667 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6668 it is considered declared."
6669 (let (name)
6670 (dolist (entry js2-recorded-identifiers)
6671 (destructuring-bind (name-node scope pos end) entry
6672 (setq name (js2-name-node-name name-node))
6673 (unless (or (member name js2-global-externs)
6674 (member name js2-default-externs)
6675 (member name js2-additional-externs)
6676 (js2-get-defining-scope scope name))
6677 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6678 'js2-external-variable))))
6679 (setq js2-recorded-identifiers nil)))
6680
6681 (defun js2-set-default-externs ()
6682 "Set the value of `js2-default-externs' based on the various
6683 `js2-include-?-externs' variables."
6684 (setq js2-default-externs
6685 (append js2-ecma-262-externs
6686 (if js2-include-browser-externs js2-browser-externs)
6687 (if (and js2-include-browser-externs
6688 (>= js2-language-version 200)) js2-harmony-externs)
6689 (if js2-include-rhino-externs js2-rhino-externs)
6690 (if js2-include-node-externs js2-node-externs)
6691 (if (or js2-include-browser-externs js2-include-node-externs)
6692 js2-typed-array-externs))))
6693
6694 (defun js2-apply-jslint-globals ()
6695 (setq js2-additional-externs
6696 (nconc (js2-get-jslint-globals)
6697 js2-additional-externs)))
6698
6699 (defun js2-get-jslint-globals ()
6700 (loop for node in (js2-ast-root-comments js2-mode-ast)
6701 when (and (eq 'block (js2-comment-node-format node))
6702 (save-excursion
6703 (goto-char (js2-node-abs-pos node))
6704 (looking-at "/\\*global ")))
6705 append (js2-get-jslint-globals-in
6706 (match-end 0)
6707 (js2-node-abs-end node))))
6708
6709 (defun js2-get-jslint-globals-in (beg end)
6710 (let (res)
6711 (save-excursion
6712 (goto-char beg)
6713 (while (re-search-forward js2-mode-identifier-re end t)
6714 (let ((match (match-string 0)))
6715 (unless (member match '("true" "false"))
6716 (push match res)))))
6717 (nreverse res)))
6718
6719 ;;; IMenu support
6720
6721 ;; We currently only support imenu, but eventually should support speedbar and
6722 ;; possibly other browsing mechanisms.
6723
6724 ;; The basic strategy is to identify function assignment targets of the form
6725 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6726 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6727 ;; for imenu after parsing is finished.
6728
6729 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6730 ;; JavaScript, and the general problem is undecidable. However, several forms
6731 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6732 ;; include:
6733
6734 ;; function foo() -- function declaration
6735 ;; foo = function() -- function expression assigned to variable
6736 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6737 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6738 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6739 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6740 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6741 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6742 ;; function foo() {function bar() {...}} -- nested function
6743 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6744
6745 ;; This list boils down to a few forms that can be combined recursively.
6746 ;; Top-level named function declarations include both the left-hand (name)
6747 ;; and the right-hand (function value) expressions needed to produce an imenu
6748 ;; entry. The other "right-hand" forms we need to look for are:
6749 ;; - functions declared as props/getters/setters in object literals
6750 ;; - nested named function declarations
6751 ;; The "left-hand" expressions that functions can be assigned to include:
6752 ;; - local/global variables
6753 ;; - nested property-get expressions like a.b.c.d
6754 ;; - element gets like foo[10] or foo['bar'] where the index
6755 ;; expression can be trivially converted to a property name. They
6756 ;; effectively then become property gets.
6757
6758 ;; All the different definition types are canonicalized into the form
6759 ;; foo.bar.baz = position-of-function-keyword
6760
6761 ;; We need to build a trie-like structure for imenu. As an example,
6762 ;; consider the following JavaScript code:
6763
6764 ;; a = function() {...} // function at position 5
6765 ;; b = function() {...} // function at position 25
6766 ;; foo = function() {...} // function at position 100
6767 ;; foo.bar = function() {...} // function at position 200
6768 ;; foo.bar.baz = function() {...} // function at position 300
6769 ;; foo.bar.zab = function() {...} // function at position 400
6770
6771 ;; During parsing we accumulate an entry for each definition in
6772 ;; the variable `js2-imenu-recorder', like so:
6773
6774 ;; '((fn a 5)
6775 ;; (fn b 25)
6776 ;; (fn foo 100)
6777 ;; (fn foo bar 200)
6778 ;; (fn foo bar baz 300)
6779 ;; (fn foo bar zab 400))
6780
6781 ;; Where 'fn' is the respective function node.
6782 ;; After parsing these entries are merged into this alist-trie:
6783
6784 ;; '((a . 1)
6785 ;; (b . 2)
6786 ;; (foo (<definition> . 3)
6787 ;; (bar (<definition> . 6)
6788 ;; (baz . 100)
6789 ;; (zab . 200))))
6790
6791 ;; Note the wacky need for a <definition> name. The token can be anything
6792 ;; that isn't a valid JavaScript identifier, because you might make foo
6793 ;; a function and then start setting properties on it that are also functions.
6794
6795 (defun js2-prop-node-name (node)
6796 "Return the name of a node that may be a property-get/property-name.
6797 If NODE is not a valid name-node, string-node or integral number-node,
6798 returns nil. Otherwise returns the string name/value of the node."
6799 (cond
6800 ((js2-name-node-p node)
6801 (js2-name-node-name node))
6802 ((js2-string-node-p node)
6803 (js2-string-node-value node))
6804 ((and (js2-number-node-p node)
6805 (string-match "^[0-9]+$" (js2-number-node-value node)))
6806 (js2-number-node-value node))
6807 ((js2-this-node-p node)
6808 "this")))
6809
6810 (defun js2-node-qname-component (node)
6811 "Return the name of this node, if it contributes to a qname.
6812 Returns nil if the node doesn't contribute."
6813 (copy-sequence
6814 (or (js2-prop-node-name node)
6815 (if (and (js2-function-node-p node)
6816 (js2-function-node-name node))
6817 (js2-name-node-name (js2-function-node-name node))))))
6818
6819 (defun js2-record-imenu-entry (fn-node qname pos)
6820 "Add an entry to `js2-imenu-recorder'.
6821 FN-NODE should be the current item's function node.
6822
6823 Associate FN-NODE with its QNAME for later lookup.
6824 This is used in postprocessing the chain list. For each chain, we find
6825 the parent function, look up its qname, then prepend a copy of it to the chain."
6826 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6827 (unless js2-imenu-function-map
6828 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6829 (puthash fn-node qname js2-imenu-function-map))
6830
6831 (defun js2-record-imenu-functions (node &optional var)
6832 "Record function definitions for imenu.
6833 NODE is a function node or an object literal.
6834 VAR, if non-nil, is the expression that NODE is being assigned to.
6835 When passed arguments of wrong type, does nothing."
6836 (when js2-parse-ide-mode
6837 (let ((fun-p (js2-function-node-p node))
6838 qname fname-node)
6839 (cond
6840 ;; non-anonymous function declaration?
6841 ((and fun-p
6842 (not var)
6843 (setq fname-node (js2-function-node-name node)))
6844 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6845 ;; for remaining forms, compute left-side tree branch first
6846 ((and var (setq qname (js2-compute-nested-prop-get var)))
6847 (cond
6848 ;; foo.bar.baz = function
6849 (fun-p
6850 (js2-record-imenu-entry node qname (js2-node-pos node)))
6851 ;; foo.bar.baz = object-literal
6852 ;; look for nested functions: {a: {b: function() {...} }}
6853 ((js2-object-node-p node)
6854 ;; Node position here is still absolute, since the parser
6855 ;; passes the assignment target and value expressions
6856 ;; to us before they are added as children of the assignment node.
6857 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6858
6859 (defun js2-compute-nested-prop-get (node)
6860 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6861 component nodes as a list. Otherwise return nil. Element-gets are treated
6862 as property-gets if the index expression is a string, or a positive integer."
6863 (let (left right head)
6864 (cond
6865 ((or (js2-name-node-p node)
6866 (js2-this-node-p node))
6867 (list node))
6868 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6869 ((js2-prop-get-node-p node) ; foo.bar
6870 (setq left (js2-prop-get-node-left node)
6871 right (js2-prop-get-node-right node))
6872 (if (setq head (js2-compute-nested-prop-get left))
6873 (nconc head (list right))))
6874 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6875 (setq left (js2-elem-get-node-target node)
6876 right (js2-elem-get-node-element node))
6877 (if (or (js2-string-node-p right) ; ['bar']
6878 (and (js2-number-node-p right) ; [10]
6879 (string-match "^[0-9]+$"
6880 (js2-number-node-value right))))
6881 (if (setq head (js2-compute-nested-prop-get left))
6882 (nconc head (list right))))))))
6883
6884 (defun js2-record-object-literal (node qname pos)
6885 "Recursively process an object literal looking for functions.
6886 NODE is an object literal that is the right-hand child of an assignment
6887 expression. QNAME is a list of nodes representing the assignment target,
6888 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6889 POS is the absolute position of the node.
6890 We do a depth-first traversal of NODE. For any functions we find,
6891 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6892 (let (right)
6893 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6894 (let ((left (js2-infix-node-left e))
6895 ;; Element positions are relative to the parent position.
6896 (pos (+ pos (js2-node-pos e))))
6897 (cond
6898 ;; foo: function() {...}
6899 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6900 (when (js2-prop-node-name left)
6901 ;; As a policy decision, we record the position of the property,
6902 ;; not the position of the `function' keyword, since the property
6903 ;; is effectively the name of the function.
6904 (js2-record-imenu-entry right (append qname (list left)) pos)))
6905 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6906 ((js2-object-node-p right)
6907 (js2-record-object-literal right
6908 (append qname (list (js2-infix-node-left e)))
6909 (+ pos (js2-node-pos right)))))))))
6910
6911 (defun js2-node-top-level-decl-p (node)
6912 "Return t if NODE's name is defined in the top-level scope.
6913 Also returns t if NODE's name is not defined in any scope, since it implies
6914 that it's an external variable, which must also be in the top-level scope."
6915 (let* ((name (js2-prop-node-name node))
6916 (this-scope (js2-node-get-enclosing-scope node))
6917 defining-scope)
6918 (cond
6919 ((js2-this-node-p node)
6920 nil)
6921 ((null this-scope)
6922 t)
6923 ((setq defining-scope (js2-get-defining-scope this-scope name))
6924 (js2-ast-root-p defining-scope))
6925 (t t))))
6926
6927 (defun js2-wrapper-function-p (node)
6928 "Return t if NODE is a function expression that's immediately invoked.
6929 NODE must be `js2-function-node'."
6930 (let ((parent (js2-node-parent node)))
6931 (or
6932 ;; function(){...}();
6933 (js2-call-node-p parent)
6934 (and (js2-paren-node-p parent)
6935 ;; (function(){...})();
6936 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6937 ;; (function(){...}).call(this);
6938 (and (js2-prop-get-node-p parent)
6939 (member (js2-name-node-name (js2-prop-get-node-right parent))
6940 '("call" "apply"))
6941 (js2-call-node-p (js2-node-parent parent))))))))
6942
6943 (defun js2-browse-postprocess-chains (entries)
6944 "Modify function-declaration name chains after parsing finishes.
6945 Some of the information is only available after the parse tree is complete.
6946 For instance, processing a nested scope requires a parent function node."
6947 (let (result fn parent-qname p elem)
6948 (dolist (entry entries)
6949 ;; function node goes first
6950 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6951 ;; Examine head's defining scope:
6952 ;; Pre-processed chain, or top-level/external, keep as-is.
6953 (if (or (stringp head) (js2-node-top-level-decl-p head))
6954 (push chain result)
6955 (when (js2-this-node-p head)
6956 (setq chain (cdr chain))) ; discard this-node
6957 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6958 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6959 (when (eq parent-qname 'not-found)
6960 ;; anonymous function expressions are not recorded
6961 ;; during the parse, so we need to handle this case here
6962 (setq parent-qname
6963 (if (js2-wrapper-function-p fn)
6964 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6965 (if (js2-ast-root-p grandparent)
6966 nil
6967 (gethash grandparent js2-imenu-function-map 'skip)))
6968 'skip))
6969 (puthash fn parent-qname js2-imenu-function-map))
6970 (unless (eq parent-qname 'skip)
6971 ;; prefix parent fn qname to this chain.
6972 (let ((qname (append parent-qname chain)))
6973 (puthash current-fn (butlast qname) js2-imenu-function-map)
6974 (push qname result)))))))
6975 ;; finally replace each node in each chain with its name.
6976 (dolist (chain result)
6977 (setq p chain)
6978 (while p
6979 (if (js2-node-p (setq elem (car p)))
6980 (setcar p (js2-node-qname-component elem)))
6981 (setq p (cdr p))))
6982 result))
6983
6984 ;; Merge name chains into a trie-like tree structure of nested lists.
6985 ;; To simplify construction of the trie, we first build it out using the rule
6986 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6987 ;; [key, num-or-list]. The second element can be a number; if so, this key
6988 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6989 ;; associated with the key at this level.) Otherwise the second element is
6990 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6991 ;; a simple recursive formulation.
6992 ;;
6993 ;; js2-mode is building the data structure for imenu. The imenu documentation
6994 ;; claims that it's the structure above, but in practice it wants the children
6995 ;; at the same list level as the key for that level, which is how I've drawn
6996 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6997 ;; list wrapper around the children at each level.
6998 ;;
6999 ;; A completed nested imenu-alist entry looks like this:
7000 ;; '(("foo"
7001 ;; ("<definition>" . 7)
7002 ;; ("bar"
7003 ;; ("a" . 40)
7004 ;; ("b" . 60))))
7005 ;;
7006 ;; In particular, the documentation for `imenu--index-alist' says that
7007 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7008 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7009
7010 (defun js2-treeify (lst)
7011 "Convert (a b c d) to (a ((b ((c d)))))."
7012 (if (null (cddr lst)) ; list length <= 2
7013 lst
7014 (list (car lst) (list (js2-treeify (cdr lst))))))
7015
7016 (defun js2-build-alist-trie (chains trie)
7017 "Merge declaration name chains into a trie-like alist structure for imenu.
7018 CHAINS is the qname chain list produced during parsing. TRIE is a
7019 list of elements built up so far."
7020 (let (head tail pos branch kids)
7021 (dolist (chain chains)
7022 (setq head (car chain)
7023 tail (cdr chain)
7024 pos (if (numberp (car tail)) (car tail))
7025 branch (js2-find-if (lambda (n)
7026 (string= (car n) head))
7027 trie)
7028 kids (second branch))
7029 (cond
7030 ;; case 1: this key isn't in the trie yet
7031 ((null branch)
7032 (if trie
7033 (setcdr (last trie) (list (js2-treeify chain)))
7034 (setq trie (list (js2-treeify chain)))))
7035 ;; case 2: key is present with a single number entry: replace w/ list
7036 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7037 ;; ("<definition>" 20)))
7038 ((numberp kids)
7039 (setcar (cdr branch)
7040 (list (list "<definition-1>" kids)
7041 (if pos
7042 (list "<definition-2>" pos)
7043 (js2-treeify tail)))))
7044 ;; case 3: key is there (with kids), and we're a number entry
7045 (pos
7046 (setcdr (last kids)
7047 (list
7048 (list (format "<definition-%d>"
7049 (1+ (loop for kid in kids
7050 count (eq ?< (aref (car kid) 0)))))
7051 pos))))
7052 ;; case 4: key is there with kids, need to merge in our chain
7053 (t
7054 (js2-build-alist-trie (list tail) kids))))
7055 trie))
7056
7057 (defun js2-flatten-trie (trie)
7058 "Convert TRIE to imenu-format.
7059 Recurses through nodes, and for each one whose second element is a list,
7060 appends the list's flattened elements to the current element. Also
7061 changes the tails into conses. For instance, this pre-flattened trie
7062
7063 '(a ((b 20)
7064 (c ((d 30)
7065 (e 40)))))
7066
7067 becomes
7068
7069 '(a (b . 20)
7070 (c (d . 30)
7071 (e . 40)))
7072
7073 Note that the root of the trie has no key, just a list of chains.
7074 This is also true for the value of any key with multiple children,
7075 e.g. key 'c' in the example above."
7076 (cond
7077 ((listp (car trie))
7078 (mapcar #'js2-flatten-trie trie))
7079 (t
7080 (if (numberp (second trie))
7081 (cons (car trie) (second trie))
7082 ;; else pop list and append its kids
7083 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7084
7085 (defun js2-build-imenu-index ()
7086 "Turn `js2-imenu-recorder' into an imenu data structure."
7087 (unless (eq js2-imenu-recorder 'empty)
7088 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7089 (result (js2-build-alist-trie chains nil)))
7090 (js2-flatten-trie result))))
7091
7092 (defun js2-test-print-chains (chains)
7093 "Print a list of qname chains.
7094 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7095 i.e. one or more nodes, and an integer position as the list tail."
7096 (mapconcat (lambda (chain)
7097 (concat "("
7098 (mapconcat (lambda (elem)
7099 (if (js2-node-p elem)
7100 (or (js2-node-qname-component elem)
7101 "nil")
7102 (number-to-string elem)))
7103 chain
7104 " ")
7105 ")"))
7106 chains
7107 "\n"))
7108
7109 ;;; Parser
7110
7111 (defconst js2-version "1.8.5"
7112 "Version of JavaScript supported.")
7113
7114 (defun js2-record-face (face &optional token)
7115 "Record a style run of FACE for TOKEN or the current token."
7116 (unless token (setq token (js2-current-token)))
7117 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7118
7119 (defsubst js2-node-end (n)
7120 "Computes the absolute end of node N.
7121 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7122 is only true until the node is added to its parent; i.e., while parsing."
7123 (+ (js2-node-pos n)
7124 (js2-node-len n)))
7125
7126 (defun js2-record-comment (token)
7127 "Record a comment in `js2-scanned-comments'."
7128 (let ((ct (js2-token-comment-type token))
7129 (beg (js2-token-beg token))
7130 (end (js2-token-end token)))
7131 (push (make-js2-comment-node :len (- end beg)
7132 :format ct)
7133 js2-scanned-comments)
7134 (when js2-parse-ide-mode
7135 (js2-record-face (if (eq ct 'jsdoc)
7136 'font-lock-doc-face
7137 'font-lock-comment-face)
7138 token)
7139 (when (memq ct '(html preprocessor))
7140 ;; Tell cc-engine the bounds of the comment.
7141 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7142
7143 (defun js2-peek-token ()
7144 "Return the next token type without consuming it.
7145 If `js2-ti-lookahead' is positive, return the type of next token
7146 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7147 (if (not (zerop js2-ti-lookahead))
7148 (js2-token-type
7149 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7150 (let ((tt (js2-get-token-internal)))
7151 (js2-unget-token)
7152 tt)))
7153
7154 (defalias 'js2-next-token 'js2-get-token)
7155
7156 (defun js2-match-token (match &optional dont-unget)
7157 "Get next token and return t if it matches MATCH, a bytecode.
7158 Returns nil and consumes nothing if MATCH is not the next token."
7159 (if (/= (js2-get-token) match)
7160 (ignore (unless dont-unget (js2-unget-token)))
7161 t))
7162
7163 (defun js2-match-contextual-kwd (name)
7164 "Consume and return t if next token is `js2-NAME', and its
7165 string is NAME. Returns nil and keeps current token otherwise."
7166 (if (or (/= (js2-get-token) js2-NAME)
7167 (not (string= (js2-current-token-string) name)))
7168 (progn
7169 (js2-unget-token)
7170 nil)
7171 (js2-record-face 'font-lock-keyword-face)
7172 t))
7173
7174 (defun js2-valid-prop-name-token (tt)
7175 (or (= tt js2-NAME)
7176 (and js2-allow-keywords-as-property-names
7177 (plusp tt)
7178 (or (= tt js2-RESERVED)
7179 (aref js2-kwd-tokens tt)))))
7180
7181 (defun js2-match-prop-name ()
7182 "Consume token and return t if next token is a valid property name.
7183 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7184 is non-nil and it's a keyword token."
7185 (if (js2-valid-prop-name-token (js2-get-token))
7186 t
7187 (js2-unget-token)
7188 nil))
7189
7190 (defun js2-must-match-prop-name (msg-id &optional pos len)
7191 (if (js2-match-prop-name)
7192 t
7193 (js2-report-error msg-id nil pos len)
7194 nil))
7195
7196 (defun js2-peek-token-or-eol ()
7197 "Return js2-EOL if the next token immediately follows a newline.
7198 Else returns the next token. Used in situations where we don't
7199 consider certain token types valid if they are preceded by a newline.
7200 One example is the postfix ++ or -- operator, which has to be on the
7201 same line as its operand."
7202 (let ((tt (js2-get-token))
7203 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7204 (js2-unget-token)
7205 (if follows-eol
7206 js2-EOL
7207 tt)))
7208
7209 (defun js2-must-match (token msg-id &optional pos len)
7210 "Match next token to token code TOKEN, or record a syntax error.
7211 MSG-ID is the error message to report if the match fails.
7212 Returns t on match, nil if no match."
7213 (if (js2-match-token token t)
7214 t
7215 (js2-report-error msg-id nil pos len)
7216 (js2-unget-token)
7217 nil))
7218
7219 (defun js2-must-match-name (msg-id)
7220 (if (js2-match-token js2-NAME t)
7221 t
7222 (if (eq (js2-current-token-type) js2-RESERVED)
7223 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7224 (js2-report-error msg-id)
7225 (js2-unget-token))
7226 nil))
7227
7228 (defsubst js2-inside-function ()
7229 (plusp js2-nesting-of-function))
7230
7231 (defun js2-set-requires-activation ()
7232 (if (js2-function-node-p js2-current-script-or-fn)
7233 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7234
7235 (defun js2-check-activation-name (name _token)
7236 (when (js2-inside-function)
7237 ;; skip language-version 1.2 check from Rhino
7238 (if (or (string= "arguments" name)
7239 (and js2-compiler-activation-names ; only used in codegen
7240 (gethash name js2-compiler-activation-names)))
7241 (js2-set-requires-activation))))
7242
7243 (defun js2-set-is-generator ()
7244 (let ((fn-node js2-current-script-or-fn))
7245 (when (and (js2-function-node-p fn-node)
7246 (not (js2-function-node-generator-type fn-node)))
7247 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7248
7249 (defun js2-must-have-xml ()
7250 (unless js2-compiler-xml-available
7251 (js2-report-error "msg.XML.not.available")))
7252
7253 (defun js2-push-scope (scope)
7254 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7255 (assert (js2-scope-p scope))
7256 (assert (null (js2-scope-parent-scope scope)))
7257 (assert (not (eq js2-current-scope scope)))
7258 (setf (js2-scope-parent-scope scope) js2-current-scope
7259 js2-current-scope scope))
7260
7261 (defsubst js2-pop-scope ()
7262 (setq js2-current-scope
7263 (js2-scope-parent-scope js2-current-scope)))
7264
7265 (defun js2-enter-loop (loop-node)
7266 (push loop-node js2-loop-set)
7267 (push loop-node js2-loop-and-switch-set)
7268 (js2-push-scope loop-node)
7269 ;; Tell the current labeled statement (if any) its statement,
7270 ;; and set the jump target of the first label to the loop.
7271 ;; These are used in `js2-parse-continue' to verify that the
7272 ;; continue target is an actual labeled loop. (And for codegen.)
7273 (when js2-labeled-stmt
7274 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7275 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7276 js2-labeled-stmt))) loop-node)))
7277
7278 (defun js2-exit-loop ()
7279 (pop js2-loop-set)
7280 (pop js2-loop-and-switch-set)
7281 (js2-pop-scope))
7282
7283 (defsubst js2-enter-switch (switch-node)
7284 (push switch-node js2-loop-and-switch-set))
7285
7286 (defsubst js2-exit-switch ()
7287 (pop js2-loop-and-switch-set))
7288
7289 (defun js2-parse (&optional buf cb)
7290 "Tell the js2 parser to parse a region of JavaScript.
7291
7292 BUF is a buffer or buffer name containing the code to parse.
7293 Call `narrow-to-region' first to parse only part of the buffer.
7294
7295 The returned AST root node is given some additional properties:
7296 `node-count' - total number of nodes in the AST
7297 `buffer' - BUF. The buffer it refers to may change or be killed,
7298 so the value is not necessarily reliable.
7299
7300 An optional callback CB can be specified to report parsing
7301 progress. If `(functionp CB)' returns t, it will be called with
7302 the current line number once before parsing begins, then again
7303 each time the lexer reaches a new line number.
7304
7305 CB can also be a list of the form `(symbol cb ...)' to specify
7306 multiple callbacks with different criteria. Each symbol is a
7307 criterion keyword, and the following element is the callback to
7308 call
7309
7310 :line - called whenever the line number changes
7311 :token - called for each new token consumed
7312
7313 The list of criteria could be extended to include entering or
7314 leaving a statement, an expression, or a function definition."
7315 (if (and cb (not (functionp cb)))
7316 (error "criteria callbacks not yet implemented"))
7317 (let ((inhibit-point-motion-hooks t)
7318 (js2-compiler-xml-available (>= js2-language-version 160))
7319 ;; This is a recursive-descent parser, so give it a big stack.
7320 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7321 (max-specpdl-size (max max-specpdl-size 3000))
7322 (case-fold-search nil)
7323 ast)
7324 (with-current-buffer (or buf (current-buffer))
7325 (setq js2-scanned-comments nil
7326 js2-parsed-errors nil
7327 js2-parsed-warnings nil
7328 js2-imenu-recorder nil
7329 js2-imenu-function-map nil
7330 js2-label-set nil)
7331 (js2-init-scanner)
7332 (setq ast (with-silent-modifications
7333 (js2-do-parse)))
7334 (unless js2-ts-hit-eof
7335 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7336 (setf (js2-ast-root-errors ast) js2-parsed-errors
7337 (js2-ast-root-warnings ast) js2-parsed-warnings)
7338 ;; if we didn't find any declarations, put a dummy in this list so we
7339 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7340 (unless js2-imenu-recorder
7341 (setq js2-imenu-recorder 'empty))
7342 (run-hooks 'js2-parse-finished-hook)
7343 ast)))
7344
7345 ;; Corresponds to Rhino's Parser.parse() method.
7346 (defun js2-do-parse ()
7347 "Parse current buffer starting from current point.
7348 Scanner should be initialized."
7349 (let ((pos js2-ts-cursor)
7350 (end js2-ts-cursor) ; in case file is empty
7351 root n tt)
7352 ;; initialize buffer-local parsing vars
7353 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7354 js2-current-script-or-fn root
7355 js2-current-scope root
7356 js2-nesting-of-function 0
7357 js2-labeled-stmt nil
7358 js2-recorded-identifiers nil) ; for js2-highlight
7359 (while (/= (setq tt (js2-get-token)) js2-EOF)
7360 (if (= tt js2-FUNCTION)
7361 (progn
7362 (setq n (if js2-called-by-compile-function
7363 (js2-parse-function-expr)
7364 (js2-parse-function-stmt))))
7365 ;; not a function - parse a statement
7366 (js2-unget-token)
7367 (setq n (js2-parse-statement)))
7368 ;; add function or statement to script
7369 (setq end (js2-node-end n))
7370 (js2-block-node-push root n))
7371 ;; add comments to root in lexical order
7372 (when js2-scanned-comments
7373 ;; if we find a comment beyond end of normal kids, use its end
7374 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7375 (dolist (comment js2-scanned-comments)
7376 (push comment (js2-ast-root-comments root))
7377 (js2-node-add-children root comment)))
7378 (setf (js2-node-len root) (- end pos))
7379 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7380 ;; Give extensions a chance to muck with things before highlighting starts.
7381 (let ((js2-additional-externs js2-additional-externs))
7382 (save-excursion
7383 (run-hooks 'js2-post-parse-callbacks))
7384 (js2-highlight-undeclared-vars))
7385 root))
7386
7387 (defun js2-parse-function-closure-body (fn-node)
7388 "Parse a JavaScript 1.8 function closure body."
7389 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7390 (if js2-ts-hit-eof
7391 (js2-report-error "msg.no.brace.body" nil
7392 (js2-node-pos fn-node)
7393 (- js2-ts-cursor (js2-node-pos fn-node)))
7394 (js2-node-add-children fn-node
7395 (setf (js2-function-node-body fn-node)
7396 (js2-parse-expr t))))))
7397
7398 (defun js2-parse-function-body (fn-node)
7399 (js2-must-match js2-LC "msg.no.brace.body"
7400 (js2-node-pos fn-node)
7401 (- js2-ts-cursor (js2-node-pos fn-node)))
7402 (let ((pos (js2-current-token-beg)) ; LC position
7403 (pn (make-js2-block-node)) ; starts at LC position
7404 tt
7405 end)
7406 (incf js2-nesting-of-function)
7407 (unwind-protect
7408 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7409 (= tt js2-EOF)
7410 (= tt js2-RC)))
7411 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7412 (js2-parse-statement)
7413 (js2-get-token)
7414 (js2-parse-function-stmt))))
7415 (decf js2-nesting-of-function))
7416 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7417 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7418 (setq end (js2-current-token-end)))
7419 (setf (js2-node-pos pn) pos
7420 (js2-node-len pn) (- end pos))
7421 (setf (js2-function-node-body fn-node) pn)
7422 (js2-node-add-children fn-node pn)
7423 pn))
7424
7425 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7426 "Declare and fontify destructuring parameters inside NODE.
7427 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7428 (cond
7429 ((js2-name-node-p node)
7430 (let (leftpos)
7431 (js2-define-symbol decl-type (js2-name-node-name node)
7432 node ignore-not-in-block)
7433 (when face
7434 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7435 (+ leftpos (js2-node-len node))
7436 face 'record))))
7437 ((js2-object-node-p node)
7438 (dolist (elem (js2-object-node-elems node))
7439 (js2-define-destruct-symbols
7440 (if (js2-object-prop-node-p elem)
7441 (js2-object-prop-node-right elem)
7442 ;; abbreviated destructuring {a, b}
7443 elem)
7444 decl-type face ignore-not-in-block)))
7445 ((js2-array-node-p node)
7446 (dolist (elem (js2-array-node-elems node))
7447 (when elem
7448 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7449 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7450 (js2-node-len node)))))
7451
7452 (defun js2-parse-function-params (function-type fn-node pos)
7453 (if (js2-match-token js2-RP)
7454 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7455 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7456 (eq (js2-current-token-type) js2-NAME)))
7457 params param default-found rest-param-at)
7458 (when paren-free-arrow
7459 (js2-unget-token))
7460 (loop for tt = (js2-peek-token)
7461 do
7462 (cond
7463 ;; destructuring param
7464 ((and (not paren-free-arrow)
7465 (or (= tt js2-LB) (= tt js2-LC)))
7466 (js2-get-token)
7467 (when default-found
7468 (js2-report-error "msg.no.default.after.default.param"))
7469 (setq param (js2-parse-destruct-primary-expr))
7470 (js2-define-destruct-symbols param
7471 js2-LP
7472 'js2-function-param)
7473 (push param params))
7474 ;; variable name
7475 (t
7476 (when (and (>= js2-language-version 200)
7477 (not paren-free-arrow)
7478 (js2-match-token js2-TRIPLEDOT)
7479 (not rest-param-at))
7480 ;; to report errors if there are more parameters
7481 (setq rest-param-at (length params)))
7482 (js2-must-match-name "msg.no.parm")
7483 (js2-record-face 'js2-function-param)
7484 (setq param (js2-create-name-node))
7485 (js2-define-symbol js2-LP (js2-current-token-string) param)
7486 ;; default parameter value
7487 (when (or (and default-found
7488 (not rest-param-at)
7489 (js2-must-match js2-ASSIGN
7490 "msg.no.default.after.default.param"
7491 (js2-node-pos param)
7492 (js2-node-len param)))
7493 (and (>= js2-language-version 200)
7494 (js2-match-token js2-ASSIGN)))
7495 (assert (not paren-free-arrow))
7496 (let* ((pos (js2-node-pos param))
7497 (tt (js2-current-token-type))
7498 (op-pos (- (js2-current-token-beg) pos))
7499 (left param)
7500 (right (js2-parse-assign-expr))
7501 (len (- (js2-node-end right) pos)))
7502 (setq param (make-js2-assign-node
7503 :type tt :pos pos :len len :op-pos op-pos
7504 :left left :right right)
7505 default-found t)
7506 (js2-node-add-children param left right)))
7507 (push param params)))
7508 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7509 (js2-report-error "msg.param.after.rest" nil
7510 (js2-node-pos param) (js2-node-len param)))
7511 while
7512 (js2-match-token js2-COMMA))
7513 (when (and (not paren-free-arrow)
7514 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7515 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7516 (when rest-param-at
7517 (setf (js2-function-node-rest-p fn-node) t))
7518 (dolist (p params)
7519 (js2-node-add-children fn-node p)
7520 (push p (js2-function-node-params fn-node))))))
7521
7522 (defun js2-check-inconsistent-return-warning (fn-node name)
7523 "Possibly show inconsistent-return warning.
7524 Last token scanned is the close-curly for the function body."
7525 (when (and js2-mode-show-strict-warnings
7526 js2-strict-inconsistent-return-warning
7527 (not (js2-has-consistent-return-usage
7528 (js2-function-node-body fn-node))))
7529 ;; Have it extend from close-curly to bol or beginning of block.
7530 (let ((pos (save-excursion
7531 (goto-char (js2-current-token-end))
7532 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7533 (point-at-bol))))
7534 (end (js2-current-token-end)))
7535 (if (plusp (js2-name-node-length name))
7536 (js2-add-strict-warning "msg.no.return.value"
7537 (js2-name-node-name name) pos end)
7538 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7539
7540 (defun js2-parse-function-stmt ()
7541 (let ((pos (js2-current-token-beg))
7542 (star-p (js2-match-token js2-MUL)))
7543 (js2-must-match-name "msg.unnamed.function.stmt")
7544 (let ((name (js2-create-name-node t))
7545 pn member-expr)
7546 (cond
7547 ((js2-match-token js2-LP)
7548 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7549 (js2-allow-member-expr-as-function-name
7550 (setq member-expr (js2-parse-member-expr-tail nil name))
7551 (js2-parse-highlight-member-expr-fn-name member-expr)
7552 (js2-must-match js2-LP "msg.no.paren.parms")
7553 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7554 (js2-function-node-member-expr pn) member-expr)
7555 pn)
7556 (t
7557 (js2-report-error "msg.no.paren.parms")
7558 (make-js2-error-node))))))
7559
7560 (defun js2-parse-function-expr ()
7561 (let ((pos (js2-current-token-beg))
7562 (star-p (js2-match-token js2-MUL))
7563 name)
7564 (when (js2-match-token js2-NAME)
7565 (setq name (js2-create-name-node t)))
7566 (js2-must-match js2-LP "msg.no.paren.parms")
7567 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7568
7569 (defun js2-parse-function (function-type pos star-p &optional name)
7570 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7571 beginning of the first token (function keyword, unless it's an
7572 arrow function), NAME is js2-name-node."
7573 (let (fn-node lp)
7574 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7575 (setq lp (js2-current-token-beg)))
7576 (setf fn-node (make-js2-function-node :pos pos
7577 :name name
7578 :form function-type
7579 :lp (if lp (- lp pos))
7580 :generator-type (and star-p 'STAR)))
7581 (when name
7582 (js2-set-face (js2-node-pos name) (js2-node-end name)
7583 'font-lock-function-name-face 'record)
7584 (when (plusp (js2-name-node-length name))
7585 ;; Function statements define a symbol in the enclosing scope
7586 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7587 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7588 ;; 1. Nested functions are not affected by the dynamic scope flag
7589 ;; as dynamic scope is already a parent of their scope.
7590 ;; 2. Functions defined under the with statement also immune to
7591 ;; this setup, in which case dynamic scope is ignored in favor
7592 ;; of the with object.
7593 (setf (js2-function-node-ignore-dynamic fn-node) t))
7594 ;; dynamically bind all the per-function variables
7595 (let ((js2-current-script-or-fn fn-node)
7596 (js2-current-scope fn-node)
7597 (js2-nesting-of-with 0)
7598 (js2-end-flags 0)
7599 js2-label-set
7600 js2-loop-set
7601 js2-loop-and-switch-set)
7602 (js2-parse-function-params function-type fn-node pos)
7603 (when (eq function-type 'FUNCTION_ARROW)
7604 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7605 (if (and (>= js2-language-version 180)
7606 (/= (js2-peek-token) js2-LC))
7607 (js2-parse-function-closure-body fn-node)
7608 (js2-parse-function-body fn-node))
7609 (js2-check-inconsistent-return-warning fn-node name)
7610
7611 (when name
7612 (js2-node-add-children fn-node name)
7613 ;; Function expressions define a name only in the body of the
7614 ;; function, and only if not hidden by a parameter name
7615 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7616 (null (js2-scope-get-symbol js2-current-scope
7617 (js2-name-node-name name))))
7618 (js2-define-symbol js2-FUNCTION
7619 (js2-name-node-name name)
7620 fn-node))
7621 (when (eq function-type 'FUNCTION_STATEMENT)
7622 (js2-record-imenu-functions fn-node))))
7623
7624 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7625 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7626 ;; We wait until after parsing the function to set its parent scope,
7627 ;; since `js2-define-symbol' needs the defining-scope check to stop
7628 ;; at the function boundary when checking for redeclarations.
7629 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7630 fn-node))
7631
7632 (defun js2-parse-statements (&optional parent)
7633 "Parse a statement list. Last token consumed must be js2-LC.
7634
7635 PARENT can be a `js2-block-node', in which case the statements are
7636 appended to PARENT. Otherwise a new `js2-block-node' is created
7637 and returned.
7638
7639 This function does not match the closing js2-RC: the caller
7640 matches the RC so it can provide a suitable error message if not
7641 matched. This means it's up to the caller to set the length of
7642 the node to include the closing RC. The node start pos is set to
7643 the absolute buffer start position, and the caller should fix it
7644 up to be relative to the parent node. All children of this block
7645 node are given relative start positions and correct lengths."
7646 (let ((pn (or parent (make-js2-block-node)))
7647 tt)
7648 (setf (js2-node-pos pn) (js2-current-token-beg))
7649 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7650 (/= tt js2-RC))
7651 (js2-block-node-push pn (js2-parse-statement)))
7652 pn))
7653
7654 (defun js2-parse-statement ()
7655 (let (pn beg end)
7656 ;; coarse-grained user-interrupt check - needs work
7657 (and js2-parse-interruptable-p
7658 (zerop (% (incf js2-parse-stmt-count)
7659 js2-statements-per-pause))
7660 (input-pending-p)
7661 (throw 'interrupted t))
7662 (setq pn (js2-statement-helper))
7663 ;; no-side-effects warning check
7664 (unless (js2-node-has-side-effects pn)
7665 (setq end (js2-node-end pn))
7666 (save-excursion
7667 (goto-char end)
7668 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7669 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7670 pn))
7671
7672 ;; These correspond to the switch cases in Parser.statementHelper
7673 (defconst js2-parsers
7674 (let ((parsers (make-vector js2-num-tokens
7675 #'js2-parse-expr-stmt)))
7676 (aset parsers js2-BREAK #'js2-parse-break)
7677 (aset parsers js2-CLASS #'js2-parse-class-stmt)
7678 (aset parsers js2-CONST #'js2-parse-const-var)
7679 (aset parsers js2-CONTINUE #'js2-parse-continue)
7680 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7681 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7682 (aset parsers js2-DO #'js2-parse-do)
7683 (aset parsers js2-FOR #'js2-parse-for)
7684 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7685 (aset parsers js2-IF #'js2-parse-if)
7686 (aset parsers js2-LC #'js2-parse-block)
7687 (aset parsers js2-LET #'js2-parse-let-stmt)
7688 (aset parsers js2-NAME #'js2-parse-name-or-label)
7689 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7690 (aset parsers js2-SEMI #'js2-parse-semi)
7691 (aset parsers js2-SWITCH #'js2-parse-switch)
7692 (aset parsers js2-THROW #'js2-parse-throw)
7693 (aset parsers js2-TRY #'js2-parse-try)
7694 (aset parsers js2-VAR #'js2-parse-const-var)
7695 (aset parsers js2-WHILE #'js2-parse-while)
7696 (aset parsers js2-WITH #'js2-parse-with)
7697 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7698 parsers)
7699 "A vector mapping token types to parser functions.")
7700
7701 (defun js2-parse-warn-missing-semi (beg end)
7702 (and js2-mode-show-strict-warnings
7703 js2-strict-missing-semi-warning
7704 (js2-add-strict-warning
7705 "msg.missing.semi" nil
7706 ;; back up to beginning of statement or line
7707 (max beg (save-excursion
7708 (goto-char end)
7709 (point-at-bol)))
7710 end)))
7711
7712 (defconst js2-no-semi-insertion
7713 (list js2-IF
7714 js2-SWITCH
7715 js2-WHILE
7716 js2-DO
7717 js2-FOR
7718 js2-TRY
7719 js2-WITH
7720 js2-LC
7721 js2-ERROR
7722 js2-SEMI
7723 js2-CLASS
7724 js2-FUNCTION)
7725 "List of tokens that don't do automatic semicolon insertion.")
7726
7727 (defconst js2-autoinsert-semi-and-warn
7728 (list js2-ERROR js2-EOF js2-RC))
7729
7730 (defun js2-statement-helper ()
7731 (let* ((tt (js2-get-token))
7732 (first-tt tt)
7733 (parser (if (= tt js2-ERROR)
7734 #'js2-parse-semi
7735 (aref js2-parsers tt)))
7736 pn)
7737 ;; If the statement is set, then it's been told its label by now.
7738 (and js2-labeled-stmt
7739 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7740 (setq js2-labeled-stmt nil))
7741 (setq pn (funcall parser))
7742 ;; Don't do auto semi insertion for certain statement types.
7743 (unless (or (memq first-tt js2-no-semi-insertion)
7744 (js2-labeled-stmt-node-p pn))
7745 (js2-auto-insert-semicolon pn))
7746 pn))
7747
7748 (defun js2-auto-insert-semicolon (pn)
7749 (let* ((tt (js2-get-token))
7750 (pos (js2-node-pos pn)))
7751 (cond
7752 ((= tt js2-SEMI)
7753 ;; extend the node bounds to include the semicolon.
7754 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7755 ((memq tt js2-autoinsert-semi-and-warn)
7756 (js2-unget-token) ; Not ';', do not consume.
7757 ;; Autoinsert ;
7758 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7759 (t
7760 (if (not (js2-token-follows-eol-p (js2-current-token)))
7761 ;; Report error if no EOL or autoinsert ';' otherwise
7762 (js2-report-error "msg.no.semi.stmt")
7763 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7764 (js2-unget-token) ; Not ';', do not consume.
7765 ))))
7766
7767 (defun js2-parse-condition ()
7768 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7769 The parens are discarded and the expression node is returned.
7770 The `pos' field of the return value is set to an absolute position
7771 that must be fixed up by the caller.
7772 Return value is a list (EXPR LP RP), with absolute paren positions."
7773 (let (pn lp rp)
7774 (if (js2-must-match js2-LP "msg.no.paren.cond")
7775 (setq lp (js2-current-token-beg)))
7776 (setq pn (js2-parse-expr))
7777 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7778 (setq rp (js2-current-token-beg)))
7779 ;; Report strict warning on code like "if (a = 7) ..."
7780 (if (and js2-strict-cond-assign-warning
7781 (js2-assign-node-p pn))
7782 (js2-add-strict-warning "msg.equal.as.assign" nil
7783 (js2-node-pos pn)
7784 (+ (js2-node-pos pn)
7785 (js2-node-len pn))))
7786 (list pn lp rp)))
7787
7788 (defun js2-parse-if ()
7789 "Parser for if-statement. Last matched token must be js2-IF."
7790 (let ((pos (js2-current-token-beg))
7791 cond if-true if-false else-pos end pn)
7792 (setq cond (js2-parse-condition)
7793 if-true (js2-parse-statement)
7794 if-false (if (js2-match-token js2-ELSE)
7795 (progn
7796 (setq else-pos (- (js2-current-token-beg) pos))
7797 (js2-parse-statement)))
7798 end (js2-node-end (or if-false if-true))
7799 pn (make-js2-if-node :pos pos
7800 :len (- end pos)
7801 :condition (car cond)
7802 :then-part if-true
7803 :else-part if-false
7804 :else-pos else-pos
7805 :lp (js2-relpos (second cond) pos)
7806 :rp (js2-relpos (third cond) pos)))
7807 (js2-node-add-children pn (car cond) if-true if-false)
7808 pn))
7809
7810 (defun js2-parse-switch ()
7811 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7812 (let ((pos (js2-current-token-beg))
7813 tt pn discriminant has-default case-expr case-node
7814 case-pos cases stmt lp)
7815 (if (js2-must-match js2-LP "msg.no.paren.switch")
7816 (setq lp (js2-current-token-beg)))
7817 (setq discriminant (js2-parse-expr)
7818 pn (make-js2-switch-node :discriminant discriminant
7819 :pos pos
7820 :lp (js2-relpos lp pos)))
7821 (js2-node-add-children pn discriminant)
7822 (js2-enter-switch pn)
7823 (unwind-protect
7824 (progn
7825 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7826 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7827 (js2-must-match js2-LC "msg.no.brace.switch")
7828 (catch 'break
7829 (while t
7830 (setq tt (js2-next-token)
7831 case-pos (js2-current-token-beg))
7832 (cond
7833 ((= tt js2-RC)
7834 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7835 (throw 'break nil)) ; done
7836 ((= tt js2-CASE)
7837 (setq case-expr (js2-parse-expr))
7838 (js2-must-match js2-COLON "msg.no.colon.case"))
7839 ((= tt js2-DEFAULT)
7840 (if has-default
7841 (js2-report-error "msg.double.switch.default"))
7842 (setq has-default t
7843 case-expr nil)
7844 (js2-must-match js2-COLON "msg.no.colon.case"))
7845 (t
7846 (js2-report-error "msg.bad.switch")
7847 (throw 'break nil)))
7848 (setq case-node (make-js2-case-node :pos case-pos
7849 :len (- (js2-current-token-end) case-pos)
7850 :expr case-expr))
7851 (js2-node-add-children case-node case-expr)
7852 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7853 (/= tt js2-CASE)
7854 (/= tt js2-DEFAULT)
7855 (/= tt js2-EOF))
7856 (setf stmt (js2-parse-statement)
7857 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7858 (js2-block-node-push case-node stmt))
7859 (push case-node cases)))
7860 ;; add cases last, as pushing reverses the order to be correct
7861 (dolist (kid cases)
7862 (js2-node-add-children pn kid)
7863 (push kid (js2-switch-node-cases pn)))
7864 pn) ; return value
7865 (js2-exit-switch))))
7866
7867 (defun js2-parse-while ()
7868 "Parser for while-statement. Last matched token must be js2-WHILE."
7869 (let ((pos (js2-current-token-beg))
7870 (pn (make-js2-while-node))
7871 cond body)
7872 (js2-enter-loop pn)
7873 (unwind-protect
7874 (progn
7875 (setf cond (js2-parse-condition)
7876 (js2-while-node-condition pn) (car cond)
7877 body (js2-parse-statement)
7878 (js2-while-node-body pn) body
7879 (js2-node-len pn) (- (js2-node-end body) pos)
7880 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7881 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7882 (js2-node-add-children pn body (car cond)))
7883 (js2-exit-loop))
7884 pn))
7885
7886 (defun js2-parse-do ()
7887 "Parser for do-statement. Last matched token must be js2-DO."
7888 (let ((pos (js2-current-token-beg))
7889 (pn (make-js2-do-node))
7890 cond body end)
7891 (js2-enter-loop pn)
7892 (unwind-protect
7893 (progn
7894 (setq body (js2-parse-statement))
7895 (js2-must-match js2-WHILE "msg.no.while.do")
7896 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7897 cond (js2-parse-condition)
7898 (js2-do-node-condition pn) (car cond)
7899 (js2-do-node-body pn) body
7900 end js2-ts-cursor
7901 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7902 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7903 (js2-node-add-children pn (car cond) body))
7904 (js2-exit-loop))
7905 ;; Always auto-insert semicolon to follow SpiderMonkey:
7906 ;; It is required by ECMAScript but is ignored by the rest of
7907 ;; world; see bug 238945
7908 (if (js2-match-token js2-SEMI)
7909 (setq end js2-ts-cursor))
7910 (setf (js2-node-len pn) (- end pos))
7911 pn))
7912
7913 (defun js2-parse-for ()
7914 "Parser for for-statement. Last matched token must be js2-FOR.
7915 Parses for, for-in, and for each-in statements."
7916 (let ((for-pos (js2-current-token-beg))
7917 pn is-for-each is-for-in-or-of is-for-of
7918 in-pos each-pos tmp-pos
7919 init ; Node init is also foo in 'foo in object'
7920 cond ; Node cond is also object in 'foo in object'
7921 incr ; 3rd section of for-loop initializer
7922 body tt lp rp)
7923 ;; See if this is a for each () instead of just a for ()
7924 (when (js2-match-token js2-NAME)
7925 (if (string= "each" (js2-current-token-string))
7926 (progn
7927 (setq is-for-each t
7928 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7929 (js2-record-face 'font-lock-keyword-face))
7930 (js2-report-error "msg.no.paren.for")))
7931 (if (js2-must-match js2-LP "msg.no.paren.for")
7932 (setq lp (- (js2-current-token-beg) for-pos)))
7933 (setq tt (js2-get-token))
7934 ;; 'for' makes local scope
7935 (js2-push-scope (make-js2-scope))
7936 (unwind-protect
7937 ;; parse init clause
7938 (let ((js2-in-for-init t)) ; set as dynamic variable
7939 (cond
7940 ((= tt js2-SEMI)
7941 (js2-unget-token)
7942 (setq init (make-js2-empty-expr-node)))
7943 ((or (= tt js2-VAR) (= tt js2-LET))
7944 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7945 (t
7946 (js2-unget-token)
7947 (setq init (js2-parse-expr)))))
7948 (if (or (js2-match-token js2-IN)
7949 (and (>= js2-language-version 200)
7950 (js2-match-contextual-kwd "of")
7951 (setq is-for-of t)))
7952 (setq is-for-in-or-of t
7953 in-pos (- (js2-current-token-beg) for-pos)
7954 ;; scope of iteration target object is not the scope we've created above.
7955 ;; stash current scope temporary.
7956 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7957 (js2-parse-expr))) ; object over which we're iterating
7958 ;; else ordinary for loop - parse cond and incr
7959 (js2-must-match js2-SEMI "msg.no.semi.for")
7960 (setq cond (if (= (js2-peek-token) js2-SEMI)
7961 (make-js2-empty-expr-node) ; no loop condition
7962 (js2-parse-expr)))
7963 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7964 (setq tmp-pos (js2-current-token-end)
7965 incr (if (= (js2-peek-token) js2-RP)
7966 (make-js2-empty-expr-node :pos tmp-pos)
7967 (js2-parse-expr))))
7968 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7969 (setq rp (- (js2-current-token-beg) for-pos)))
7970 (if (not is-for-in-or-of)
7971 (setq pn (make-js2-for-node :init init
7972 :condition cond
7973 :update incr
7974 :lp lp
7975 :rp rp))
7976 ;; cond could be null if 'in obj' got eaten by the init node.
7977 (if (js2-infix-node-p init)
7978 ;; it was (foo in bar) instead of (var foo in bar)
7979 (setq cond (js2-infix-node-right init)
7980 init (js2-infix-node-left init))
7981 (if (and (js2-var-decl-node-p init)
7982 (> (length (js2-var-decl-node-kids init)) 1))
7983 (js2-report-error "msg.mult.index")))
7984 (setq pn (make-js2-for-in-node :iterator init
7985 :object cond
7986 :in-pos in-pos
7987 :foreach-p is-for-each
7988 :each-pos each-pos
7989 :forof-p is-for-of
7990 :lp lp
7991 :rp rp)))
7992 (unwind-protect
7993 (progn
7994 (js2-enter-loop pn)
7995 ;; We have to parse the body -after- creating the loop node,
7996 ;; so that the loop node appears in the js2-loop-set, allowing
7997 ;; break/continue statements to find the enclosing loop.
7998 (setf body (js2-parse-statement)
7999 (js2-loop-node-body pn) body
8000 (js2-node-pos pn) for-pos
8001 (js2-node-len pn) (- (js2-node-end body) for-pos))
8002 (js2-node-add-children pn init cond incr body))
8003 ;; finally
8004 (js2-exit-loop))
8005 (js2-pop-scope))
8006 pn))
8007
8008 (defun js2-parse-try ()
8009 "Parser for try-statement. Last matched token must be js2-TRY."
8010 (let ((try-pos (js2-current-token-beg))
8011 try-end
8012 try-block
8013 catch-blocks
8014 finally-block
8015 saw-default-catch
8016 peek
8017 param
8018 catch-cond
8019 catch-node
8020 guard-kwd
8021 catch-pos
8022 finally-pos
8023 pn
8024 block
8025 lp
8026 rp)
8027 (if (/= (js2-peek-token) js2-LC)
8028 (js2-report-error "msg.no.brace.try"))
8029 (setq try-block (js2-parse-statement)
8030 try-end (js2-node-end try-block)
8031 peek (js2-peek-token))
8032 (cond
8033 ((= peek js2-CATCH)
8034 (while (js2-match-token js2-CATCH)
8035 (setq catch-pos (js2-current-token-beg)
8036 guard-kwd nil
8037 catch-cond nil
8038 lp nil
8039 rp nil)
8040 (if saw-default-catch
8041 (js2-report-error "msg.catch.unreachable"))
8042 (if (js2-must-match js2-LP "msg.no.paren.catch")
8043 (setq lp (- (js2-current-token-beg) catch-pos)))
8044 (js2-push-scope (make-js2-scope))
8045 (let ((tt (js2-peek-token)))
8046 (cond
8047 ;; destructuring pattern
8048 ;; catch ({ message, file }) { ... }
8049 ((or (= tt js2-LB) (= tt js2-LC))
8050 (js2-get-token)
8051 (setq param (js2-parse-destruct-primary-expr))
8052 (js2-define-destruct-symbols param js2-LET nil))
8053 ;; simple name
8054 (t
8055 (js2-must-match-name "msg.bad.catchcond")
8056 (setq param (js2-create-name-node))
8057 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8058 ;; pattern guard
8059 (if (js2-match-token js2-IF)
8060 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8061 catch-cond (js2-parse-expr))
8062 (setq saw-default-catch t))
8063 (if (js2-must-match js2-RP "msg.bad.catchcond")
8064 (setq rp (- (js2-current-token-beg) catch-pos)))
8065 (js2-must-match js2-LC "msg.no.brace.catchblock")
8066 (setq block (js2-parse-statements)
8067 try-end (js2-node-end block)
8068 catch-node (make-js2-catch-node :pos catch-pos
8069 :param param
8070 :guard-expr catch-cond
8071 :guard-kwd guard-kwd
8072 :block block
8073 :lp lp
8074 :rp rp))
8075 (js2-pop-scope)
8076 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8077 (setq try-end (js2-current-token-beg)))
8078 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8079 (js2-node-len catch-node) (- try-end catch-pos))
8080 (js2-node-add-children catch-node param catch-cond block)
8081 (push catch-node catch-blocks)))
8082 ((/= peek js2-FINALLY)
8083 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8084 (js2-node-pos try-block)
8085 (- (setq try-end (js2-node-end try-block))
8086 (js2-node-pos try-block)))))
8087 (when (js2-match-token js2-FINALLY)
8088 (setq finally-pos (js2-current-token-beg)
8089 block (js2-parse-statement)
8090 try-end (js2-node-end block)
8091 finally-block (make-js2-finally-node :pos finally-pos
8092 :len (- try-end finally-pos)
8093 :body block))
8094 (js2-node-add-children finally-block block))
8095 (setq pn (make-js2-try-node :pos try-pos
8096 :len (- try-end try-pos)
8097 :try-block try-block
8098 :finally-block finally-block))
8099 (js2-node-add-children pn try-block finally-block)
8100 ;; push them onto the try-node, which reverses and corrects their order
8101 (dolist (cb catch-blocks)
8102 (js2-node-add-children pn cb)
8103 (push cb (js2-try-node-catch-clauses pn)))
8104 pn))
8105
8106 (defun js2-parse-throw ()
8107 "Parser for throw-statement. Last matched token must be js2-THROW."
8108 (let ((pos (js2-current-token-beg))
8109 expr pn)
8110 (if (= (js2-peek-token-or-eol) js2-EOL)
8111 ;; ECMAScript does not allow new lines before throw expression,
8112 ;; see bug 256617
8113 (js2-report-error "msg.bad.throw.eol"))
8114 (setq expr (js2-parse-expr)
8115 pn (make-js2-throw-node :pos pos
8116 :len (- (js2-node-end expr) pos)
8117 :expr expr))
8118 (js2-node-add-children pn expr)
8119 pn))
8120
8121 (defun js2-match-jump-label-name (label-name)
8122 "If break/continue specified a label, return that label's labeled stmt.
8123 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8124 does not match an existing label, reports an error and returns nil."
8125 (let ((bundle (cdr (assoc label-name js2-label-set))))
8126 (if (null bundle)
8127 (js2-report-error "msg.undef.label"))
8128 bundle))
8129
8130 (defun js2-parse-break ()
8131 "Parser for break-statement. Last matched token must be js2-BREAK."
8132 (let ((pos (js2-current-token-beg))
8133 (end (js2-current-token-end))
8134 break-target ; statement to break from
8135 break-label ; in "break foo", name-node representing the foo
8136 labels ; matching labeled statement to break to
8137 pn)
8138 (when (eq (js2-peek-token-or-eol) js2-NAME)
8139 (js2-get-token)
8140 (setq break-label (js2-create-name-node)
8141 end (js2-node-end break-label)
8142 ;; matchJumpLabelName only matches if there is one
8143 labels (js2-match-jump-label-name (js2-current-token-string))
8144 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8145 (unless (or break-target break-label)
8146 ;; no break target specified - try for innermost enclosing loop/switch
8147 (if (null js2-loop-and-switch-set)
8148 (unless break-label
8149 (js2-report-error "msg.bad.break" nil pos (length "break")))
8150 (setq break-target (car js2-loop-and-switch-set))))
8151 (setq pn (make-js2-break-node :pos pos
8152 :len (- end pos)
8153 :label break-label
8154 :target break-target))
8155 (js2-node-add-children pn break-label) ; but not break-target
8156 pn))
8157
8158 (defun js2-parse-continue ()
8159 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8160 (let ((pos (js2-current-token-beg))
8161 (end (js2-current-token-end))
8162 label ; optional user-specified label, a `js2-name-node'
8163 labels ; current matching labeled stmt, if any
8164 target ; the `js2-loop-node' target of this continue stmt
8165 pn)
8166 (when (= (js2-peek-token-or-eol) js2-NAME)
8167 (js2-get-token)
8168 (setq label (js2-create-name-node)
8169 end (js2-node-end label)
8170 ;; matchJumpLabelName only matches if there is one
8171 labels (js2-match-jump-label-name (js2-current-token-string))))
8172 (cond
8173 ((null labels) ; no current label to go to
8174 (if (null js2-loop-set) ; no loop to continue to
8175 (js2-report-error "msg.continue.outside" nil pos
8176 (length "continue"))
8177 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8178 (t
8179 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8180 (setq target (js2-labeled-stmt-node-stmt labels))
8181 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8182 (setq pn (make-js2-continue-node :pos pos
8183 :len (- end pos)
8184 :label label
8185 :target target))
8186 (js2-node-add-children pn label) ; but not target - it's not our child
8187 pn))
8188
8189 (defun js2-parse-with ()
8190 "Parser for with-statement. Last matched token must be js2-WITH."
8191 (let ((pos (js2-current-token-beg))
8192 obj body pn lp rp)
8193 (if (js2-must-match js2-LP "msg.no.paren.with")
8194 (setq lp (js2-current-token-beg)))
8195 (setq obj (js2-parse-expr))
8196 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8197 (setq rp (js2-current-token-beg)))
8198 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8199 (setq body (js2-parse-statement)))
8200 (setq pn (make-js2-with-node :pos pos
8201 :len (- (js2-node-end body) pos)
8202 :object obj
8203 :body body
8204 :lp (js2-relpos lp pos)
8205 :rp (js2-relpos rp pos)))
8206 (js2-node-add-children pn obj body)
8207 pn))
8208
8209 (defun js2-parse-const-var ()
8210 "Parser for var- or const-statement.
8211 Last matched token must be js2-CONST or js2-VAR."
8212 (let ((tt (js2-current-token-type))
8213 (pos (js2-current-token-beg))
8214 expr pn)
8215 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8216 pn (make-js2-expr-stmt-node :pos pos
8217 :len (- (js2-node-end expr) pos)
8218 :expr expr))
8219 (js2-node-add-children pn expr)
8220 pn))
8221
8222 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8223 (let ((pn (make-js2-expr-stmt-node :pos pos
8224 :len (js2-node-len expr)
8225 :type (if (js2-inside-function)
8226 js2-EXPR_VOID
8227 js2-EXPR_RESULT)
8228 :expr expr)))
8229 (if add-child
8230 (js2-node-add-children pn expr))
8231 pn))
8232
8233 (defun js2-parse-let-stmt ()
8234 "Parser for let-statement. Last matched token must be js2-LET."
8235 (let ((pos (js2-current-token-beg))
8236 expr pn)
8237 (if (= (js2-peek-token) js2-LP)
8238 ;; let expression in statement context
8239 (setq expr (js2-parse-let pos 'statement)
8240 pn (js2-wrap-with-expr-stmt pos expr t))
8241 ;; else we're looking at a statement like let x=6, y=7;
8242 (setf expr (js2-parse-variables js2-LET pos)
8243 pn (js2-wrap-with-expr-stmt pos expr t)
8244 (js2-node-type pn) js2-EXPR_RESULT))
8245 pn))
8246
8247 (defun js2-parse-ret-yield ()
8248 (js2-parse-return-or-yield (js2-current-token-type) nil))
8249
8250 (defconst js2-parse-return-stmt-enders
8251 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8252
8253 (defsubst js2-now-all-set (before after mask)
8254 "Return whether or not the bits in the mask have changed to all set.
8255 BEFORE is bits before change, AFTER is bits after change, and MASK is
8256 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8257 but not BEFORE."
8258 (and (/= (logand before mask) mask)
8259 (= (logand after mask) mask)))
8260
8261 (defun js2-parse-return-or-yield (tt expr-context)
8262 (let* ((pos (js2-current-token-beg))
8263 (end (js2-current-token-end))
8264 (before js2-end-flags)
8265 (inside-function (js2-inside-function))
8266 (gen-type (and inside-function (js2-function-node-generator-type
8267 js2-current-script-or-fn)))
8268 e ret name yield-star-p)
8269 (unless inside-function
8270 (js2-report-error (if (eq tt js2-RETURN)
8271 "msg.bad.return"
8272 "msg.bad.yield")))
8273 (when (and inside-function
8274 (eq gen-type 'STAR)
8275 (js2-match-token js2-MUL))
8276 (setq yield-star-p t))
8277 ;; This is ugly, but we don't want to require a semicolon.
8278 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8279 (setq e (js2-parse-expr)
8280 end (js2-node-end e)))
8281 (cond
8282 ((eq tt js2-RETURN)
8283 (js2-set-flag js2-end-flags (if (null e)
8284 js2-end-returns
8285 js2-end-returns-value))
8286 (setq ret (make-js2-return-node :pos pos
8287 :len (- end pos)
8288 :retval e))
8289 (js2-node-add-children ret e)
8290 ;; See if we need a strict mode warning.
8291 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8292 ;; more thorough and accurate than this before/after flag check.
8293 ;; E.g. if there's a finally-block that always returns, we shouldn't
8294 ;; show a warning generated by inconsistent returns in the catch blocks.
8295 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8296 ;; so we know which returns/yields to highlight, and we should get rid of
8297 ;; all the checking in `js2-parse-return-or-yield'.
8298 (if (and js2-strict-inconsistent-return-warning
8299 (js2-now-all-set before js2-end-flags
8300 (logior js2-end-returns js2-end-returns-value)))
8301 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8302 ((eq gen-type 'COMPREHENSION)
8303 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8304 ;; like SpiderMonkey does.
8305 (js2-report-error "msg.syntax" nil pos 5))
8306 (t
8307 (setq ret (make-js2-yield-node :pos pos
8308 :len (- end pos)
8309 :value e
8310 :star-p yield-star-p))
8311 (js2-node-add-children ret e)
8312 (unless expr-context
8313 (setq e ret
8314 ret (js2-wrap-with-expr-stmt pos e t))
8315 (js2-set-requires-activation)
8316 (js2-set-is-generator))))
8317 ;; see if we are mixing yields and value returns.
8318 (when (and inside-function
8319 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8320 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8321 'LEGACY))
8322 (setq name (js2-function-name js2-current-script-or-fn))
8323 (if (zerop (length name))
8324 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8325 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8326 ret))
8327
8328 (defun js2-parse-debugger ()
8329 (make-js2-keyword-node :type js2-DEBUGGER))
8330
8331 (defun js2-parse-block ()
8332 "Parser for a curly-delimited statement block.
8333 Last token matched must be `js2-LC'."
8334 (let ((pos (js2-current-token-beg))
8335 (pn (make-js2-scope)))
8336 (js2-push-scope pn)
8337 (unwind-protect
8338 (progn
8339 (js2-parse-statements pn)
8340 (js2-must-match js2-RC "msg.no.brace.block")
8341 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8342 (js2-pop-scope))
8343 pn))
8344
8345 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8346 (defun js2-parse-semi ()
8347 "Parse a statement or handle an error.
8348 Current token type is `js2-SEMI' or `js2-ERROR'."
8349 (let ((tt (js2-current-token-type)) pos len)
8350 (if (eq tt js2-SEMI)
8351 (make-js2-empty-expr-node :len 1)
8352 (setq pos (js2-current-token-beg)
8353 len (- (js2-current-token-end) pos))
8354 (js2-report-error "msg.syntax" nil pos len)
8355 (make-js2-error-node :pos pos :len len))))
8356
8357 (defun js2-parse-default-xml-namespace ()
8358 "Parse a `default xml namespace = <expr>' e4x statement."
8359 (let ((pos (js2-current-token-beg))
8360 end len expr unary)
8361 (js2-must-have-xml)
8362 (js2-set-requires-activation)
8363 (setq len (- js2-ts-cursor pos))
8364 (unless (and (js2-match-token js2-NAME)
8365 (string= (js2-current-token-string) "xml"))
8366 (js2-report-error "msg.bad.namespace" nil pos len))
8367 (unless (and (js2-match-token js2-NAME)
8368 (string= (js2-current-token-string) "namespace"))
8369 (js2-report-error "msg.bad.namespace" nil pos len))
8370 (unless (js2-match-token js2-ASSIGN)
8371 (js2-report-error "msg.bad.namespace" nil pos len))
8372 (setq expr (js2-parse-expr)
8373 end (js2-node-end expr)
8374 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8375 :pos pos
8376 :len (- end pos)
8377 :operand expr))
8378 (js2-node-add-children unary expr)
8379 (make-js2-expr-stmt-node :pos pos
8380 :len (- end pos)
8381 :expr unary)))
8382
8383 (defun js2-record-label (label bundle)
8384 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8385 (js2-get-token)
8386 (let ((name (js2-label-node-name label))
8387 labeled-stmt
8388 dup)
8389 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8390 ;; flag both labels if possible when used in editing mode
8391 (if (and js2-parse-ide-mode
8392 (setq dup (js2-get-label-by-name labeled-stmt name)))
8393 (js2-report-error "msg.dup.label" nil
8394 (js2-node-abs-pos dup) (js2-node-len dup)))
8395 (js2-report-error "msg.dup.label" nil
8396 (js2-node-pos label) (js2-node-len label)))
8397 (js2-labeled-stmt-node-add-label bundle label)
8398 (js2-node-add-children bundle label)
8399 ;; Add one reference to the bundle per label in `js2-label-set'
8400 (push (cons name bundle) js2-label-set)))
8401
8402 (defun js2-parse-name-or-label ()
8403 "Parser for identifier or label. Last token matched must be js2-NAME.
8404 Called when we found a name in a statement context. If it's a label, we gather
8405 up any following labels and the next non-label statement into a
8406 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8407 expression and return it wrapped in a `js2-expr-stmt-node'."
8408 (let ((pos (js2-current-token-beg))
8409 expr stmt bundle
8410 (continue t))
8411 ;; set check for label and call down to `js2-parse-primary-expr'
8412 (setq expr (js2-maybe-parse-label))
8413 (if (null expr)
8414 ;; Parse the non-label expression and wrap with expression stmt.
8415 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8416 ;; else parsed a label
8417 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8418 (js2-record-label expr bundle)
8419 ;; look for more labels
8420 (while (and continue (= (js2-get-token) js2-NAME))
8421 (if (setq expr (js2-maybe-parse-label))
8422 (js2-record-label expr bundle)
8423 (setq expr (js2-parse-expr)
8424 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8425 continue nil)
8426 (js2-auto-insert-semicolon stmt)))
8427 ;; no more labels; now parse the labeled statement
8428 (unwind-protect
8429 (unless stmt
8430 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8431 (js2-unget-token)
8432 (setq stmt (js2-statement-helper))))
8433 ;; remove the labels for this statement from the global set
8434 (dolist (label (js2-labeled-stmt-node-labels bundle))
8435 (setq js2-label-set (remove label js2-label-set))))
8436 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8437 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8438 (js2-node-add-children bundle stmt)
8439 bundle)))
8440
8441 (defun js2-maybe-parse-label ()
8442 (assert (= (js2-current-token-type) js2-NAME))
8443 (let (label-pos
8444 (next-tt (js2-get-token))
8445 (label-end (js2-current-token-end)))
8446 ;; Do not consume colon, it is used as unwind indicator
8447 ;; to return to statementHelper.
8448 (js2-unget-token)
8449 (if (= next-tt js2-COLON)
8450 (prog2
8451 (setq label-pos (js2-current-token-beg))
8452 (make-js2-label-node :pos label-pos
8453 :len (- label-end label-pos)
8454 :name (js2-current-token-string))
8455 (js2-set-face label-pos
8456 label-end
8457 'font-lock-variable-name-face 'record))
8458 ;; Backtrack from the name token, too.
8459 (js2-unget-token)
8460 nil)))
8461
8462 (defun js2-parse-expr-stmt ()
8463 "Default parser in statement context, if no recognized statement found."
8464 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8465 (progn
8466 (js2-unget-token)
8467 (js2-parse-expr)) t))
8468
8469 (defun js2-parse-variables (decl-type pos)
8470 "Parse a comma-separated list of variable declarations.
8471 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8472
8473 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8474 For 'var' or 'const', the keyword should be the token last scanned.
8475
8476 POS is the position where the node should start. It's sometimes the
8477 var/const/let keyword, and other times the beginning of the first token
8478 in the first variable declaration.
8479
8480 Returns the parsed `js2-var-decl-node' expression node."
8481 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8482 :pos pos))
8483 destructuring kid-pos tt init name end nbeg nend vi
8484 (continue t))
8485 ;; Example:
8486 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8487 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8488 ;; var {a, b} = baz;
8489 (while continue
8490 (setq destructuring nil
8491 name nil
8492 tt (js2-get-token)
8493 kid-pos (js2-current-token-beg)
8494 end (js2-current-token-end)
8495 init nil)
8496 (if (or (= tt js2-LB) (= tt js2-LC))
8497 ;; Destructuring assignment, e.g., var [a, b] = ...
8498 (setq destructuring (js2-parse-destruct-primary-expr)
8499 end (js2-node-end destructuring))
8500 ;; Simple variable name
8501 (js2-unget-token)
8502 (when (js2-must-match-name "msg.bad.var")
8503 (setq name (js2-create-name-node)
8504 nbeg (js2-current-token-beg)
8505 nend (js2-current-token-end)
8506 end nend)
8507 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8508 (when (js2-match-token js2-ASSIGN)
8509 (setq init (js2-parse-assign-expr)
8510 end (js2-node-end init))
8511 (js2-record-imenu-functions init name))
8512 (when name
8513 (js2-set-face nbeg nend (if (js2-function-node-p init)
8514 'font-lock-function-name-face
8515 'font-lock-variable-name-face)
8516 'record))
8517 (setq vi (make-js2-var-init-node :pos kid-pos
8518 :len (- end kid-pos)
8519 :type decl-type))
8520 (if destructuring
8521 (progn
8522 (if (and (null init) (not js2-in-for-init))
8523 (js2-report-error "msg.destruct.assign.no.init"))
8524 (js2-define-destruct-symbols destructuring
8525 decl-type
8526 'font-lock-variable-name-face)
8527 (setf (js2-var-init-node-target vi) destructuring))
8528 (setf (js2-var-init-node-target vi) name))
8529 (setf (js2-var-init-node-initializer vi) init)
8530 (js2-node-add-children vi name destructuring init)
8531 (js2-block-node-push result vi)
8532 (unless (js2-match-token js2-COMMA)
8533 (setq continue nil)))
8534 (setf (js2-node-len result) (- end pos))
8535 result))
8536
8537 (defun js2-parse-let (pos &optional stmt-p)
8538 "Parse a let expression or statement.
8539 A let-expression is of the form `let (vars) expr'.
8540 A let-statment is of the form `let (vars) {statements}'.
8541 The third form of let is a variable declaration list, handled
8542 by `js2-parse-variables'."
8543 (let ((pn (make-js2-let-node :pos pos))
8544 beg vars body)
8545 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8546 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8547 (js2-push-scope pn)
8548 (unwind-protect
8549 (progn
8550 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8551 (if (js2-must-match js2-RP "msg.no.paren.let")
8552 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8553 (if (and stmt-p (js2-match-token js2-LC))
8554 ;; let statement
8555 (progn
8556 (setf beg (js2-current-token-beg) ; position stmt at LC
8557 body (js2-parse-statements))
8558 (js2-must-match js2-RC "msg.no.curly.let")
8559 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8560 (js2-node-len pn) (- (js2-current-token-end) pos)
8561 (js2-let-node-body pn) body
8562 (js2-node-type pn) js2-LET))
8563 ;; let expression
8564 (setf body (js2-parse-expr)
8565 (js2-node-len pn) (- (js2-node-end body) pos)
8566 (js2-let-node-body pn) body))
8567 (setf (js2-let-node-vars pn) vars)
8568 (js2-node-add-children pn vars body))
8569 (js2-pop-scope))
8570 pn))
8571
8572 (defun js2-define-new-symbol (decl-type name node &optional scope)
8573 (js2-scope-put-symbol (or scope js2-current-scope)
8574 name
8575 (make-js2-symbol decl-type name node)))
8576
8577 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8578 "Define a symbol in the current scope.
8579 If NODE is non-nil, it is the AST node associated with the symbol."
8580 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8581 (symbol (if defining-scope
8582 (js2-scope-get-symbol defining-scope name)))
8583 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8584 (cond
8585 ((and symbol ; already defined
8586 (or (= sdt js2-CONST) ; old version is const
8587 (= decl-type js2-CONST) ; new version is const
8588 ;; two let-bound vars in this block have same name
8589 (and (= sdt js2-LET)
8590 (eq defining-scope js2-current-scope))))
8591 (js2-report-error
8592 (cond
8593 ((= sdt js2-CONST) "msg.const.redecl")
8594 ((= sdt js2-LET) "msg.let.redecl")
8595 ((= sdt js2-VAR) "msg.var.redecl")
8596 ((= sdt js2-FUNCTION) "msg.function.redecl")
8597 (t "msg.parm.redecl"))
8598 name))
8599 ((= decl-type js2-LET)
8600 (if (and (not ignore-not-in-block)
8601 (or (= (js2-node-type js2-current-scope) js2-IF)
8602 (js2-loop-node-p js2-current-scope)))
8603 (js2-report-error "msg.let.decl.not.in.block")
8604 (js2-define-new-symbol decl-type name node)))
8605 ((or (= decl-type js2-VAR)
8606 (= decl-type js2-CONST)
8607 (= decl-type js2-FUNCTION))
8608 (if symbol
8609 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8610 (js2-add-strict-warning "msg.var.redecl" name)
8611 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8612 (js2-add-strict-warning "msg.var.hides.arg" name)))
8613 (js2-define-new-symbol decl-type name node
8614 js2-current-script-or-fn)))
8615 ((= decl-type js2-LP)
8616 (if symbol
8617 ;; must be duplicate parameter. Second parameter hides the
8618 ;; first, so go ahead and add the second pararameter
8619 (js2-report-warning "msg.dup.parms" name))
8620 (js2-define-new-symbol decl-type name node))
8621 (t (js2-code-bug)))))
8622
8623 (defun js2-parse-paren-expr-or-generator-comp ()
8624 (let ((px-pos (js2-current-token-beg)))
8625 (if (and (>= js2-language-version 200)
8626 (js2-match-token js2-FOR))
8627 (js2-parse-generator-comp px-pos)
8628 (let* ((js2-in-for-init nil)
8629 (expr (js2-parse-expr))
8630 (pn (make-js2-paren-node :pos px-pos
8631 :expr expr
8632 :len (- (js2-current-token-end)
8633 px-pos))))
8634 (js2-node-add-children pn (js2-paren-node-expr pn))
8635 (js2-must-match js2-RP "msg.no.paren")
8636 pn))))
8637
8638 (defun js2-parse-expr (&optional oneshot)
8639 (let* ((pn (js2-parse-assign-expr))
8640 (pos (js2-node-pos pn))
8641 left
8642 right
8643 op-pos)
8644 (while (and (not oneshot)
8645 (js2-match-token js2-COMMA))
8646 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8647 (if (= (js2-peek-token) js2-YIELD)
8648 (js2-report-error "msg.yield.parenthesized"))
8649 (setq right (js2-parse-assign-expr)
8650 left pn
8651 pn (make-js2-infix-node :type js2-COMMA
8652 :pos pos
8653 :len (- js2-ts-cursor pos)
8654 :op-pos op-pos
8655 :left left
8656 :right right))
8657 (js2-node-add-children pn left right))
8658 pn))
8659
8660 (defun js2-parse-assign-expr ()
8661 (let ((tt (js2-get-token))
8662 (pos (js2-current-token-beg))
8663 pn left right op-pos
8664 ts-state recorded-identifiers parsed-errors)
8665 (if (= tt js2-YIELD)
8666 (js2-parse-return-or-yield tt t)
8667 ;; Save the tokenizer state in case we find an arrow function
8668 ;; and have to rewind.
8669 (setq ts-state (make-js2-ts-state)
8670 recorded-identifiers js2-recorded-identifiers
8671 parsed-errors js2-parsed-errors)
8672 ;; not yield - parse assignment expression
8673 (setq pn (js2-parse-cond-expr)
8674 tt (js2-get-token))
8675 (cond
8676 ((and (<= js2-first-assign tt)
8677 (<= tt js2-last-assign))
8678 ;; tt express assignment (=, |=, ^=, ..., %=)
8679 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8680 left pn)
8681 (setq right (js2-parse-assign-expr)
8682 pn (make-js2-assign-node :type tt
8683 :pos pos
8684 :len (- (js2-node-end right) pos)
8685 :op-pos op-pos
8686 :left left
8687 :right right))
8688 (when js2-parse-ide-mode
8689 (js2-highlight-assign-targets pn left right)
8690 (js2-record-imenu-functions right left))
8691 ;; do this last so ide checks above can use absolute positions
8692 (js2-node-add-children pn left right))
8693 ((and (= tt js2-ARROW)
8694 (>= js2-language-version 200))
8695 (js2-ts-seek ts-state)
8696 (setq js2-recorded-identifiers recorded-identifiers
8697 js2-parsed-errors parsed-errors)
8698 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8699 (t
8700 (js2-unget-token)))
8701 pn)))
8702
8703 (defun js2-parse-cond-expr ()
8704 (let ((pos (js2-current-token-beg))
8705 (pn (js2-parse-or-expr))
8706 test-expr
8707 if-true
8708 if-false
8709 q-pos
8710 c-pos)
8711 (when (js2-match-token js2-HOOK)
8712 (setq q-pos (- (js2-current-token-beg) pos)
8713 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8714 (js2-must-match js2-COLON "msg.no.colon.cond")
8715 (setq c-pos (- (js2-current-token-beg) pos)
8716 if-false (js2-parse-assign-expr)
8717 test-expr pn
8718 pn (make-js2-cond-node :pos pos
8719 :len (- (js2-node-end if-false) pos)
8720 :test-expr test-expr
8721 :true-expr if-true
8722 :false-expr if-false
8723 :q-pos q-pos
8724 :c-pos c-pos))
8725 (js2-node-add-children pn test-expr if-true if-false))
8726 pn))
8727
8728 (defun js2-make-binary (type left parser)
8729 "Helper for constructing a binary-operator AST node.
8730 LEFT is the left-side-expression, already parsed, and the
8731 binary operator should have just been matched.
8732 PARSER is a function to call to parse the right operand,
8733 or a `js2-node' struct if it has already been parsed.
8734 FIXME: The latter option is unused?"
8735 (let* ((pos (js2-node-pos left))
8736 (op-pos (- (js2-current-token-beg) pos))
8737 (right (if (js2-node-p parser)
8738 parser
8739 (js2-get-token)
8740 (funcall parser)))
8741 (pn (make-js2-infix-node :type type
8742 :pos pos
8743 :len (- (js2-node-end right) pos)
8744 :op-pos op-pos
8745 :left left
8746 :right right)))
8747 (js2-node-add-children pn left right)
8748 pn))
8749
8750 (defun js2-parse-or-expr ()
8751 (let ((pn (js2-parse-and-expr)))
8752 (when (js2-match-token js2-OR)
8753 (setq pn (js2-make-binary js2-OR
8754 pn
8755 'js2-parse-or-expr)))
8756 pn))
8757
8758 (defun js2-parse-and-expr ()
8759 (let ((pn (js2-parse-bit-or-expr)))
8760 (when (js2-match-token js2-AND)
8761 (setq pn (js2-make-binary js2-AND
8762 pn
8763 'js2-parse-and-expr)))
8764 pn))
8765
8766 (defun js2-parse-bit-or-expr ()
8767 (let ((pn (js2-parse-bit-xor-expr)))
8768 (while (js2-match-token js2-BITOR)
8769 (setq pn (js2-make-binary js2-BITOR
8770 pn
8771 'js2-parse-bit-xor-expr)))
8772 pn))
8773
8774 (defun js2-parse-bit-xor-expr ()
8775 (let ((pn (js2-parse-bit-and-expr)))
8776 (while (js2-match-token js2-BITXOR)
8777 (setq pn (js2-make-binary js2-BITXOR
8778 pn
8779 'js2-parse-bit-and-expr)))
8780 pn))
8781
8782 (defun js2-parse-bit-and-expr ()
8783 (let ((pn (js2-parse-eq-expr)))
8784 (while (js2-match-token js2-BITAND)
8785 (setq pn (js2-make-binary js2-BITAND
8786 pn
8787 'js2-parse-eq-expr)))
8788 pn))
8789
8790 (defconst js2-parse-eq-ops
8791 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8792
8793 (defun js2-parse-eq-expr ()
8794 (let ((pn (js2-parse-rel-expr))
8795 tt)
8796 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8797 (setq pn (js2-make-binary tt
8798 pn
8799 'js2-parse-rel-expr)))
8800 (js2-unget-token)
8801 pn))
8802
8803 (defconst js2-parse-rel-ops
8804 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8805
8806 (defun js2-parse-rel-expr ()
8807 (let ((pn (js2-parse-shift-expr))
8808 (continue t)
8809 tt)
8810 (while continue
8811 (setq tt (js2-get-token))
8812 (cond
8813 ((and js2-in-for-init (= tt js2-IN))
8814 (js2-unget-token)
8815 (setq continue nil))
8816 ((memq tt js2-parse-rel-ops)
8817 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8818 (t
8819 (js2-unget-token)
8820 (setq continue nil))))
8821 pn))
8822
8823 (defconst js2-parse-shift-ops
8824 (list js2-LSH js2-URSH js2-RSH))
8825
8826 (defun js2-parse-shift-expr ()
8827 (let ((pn (js2-parse-add-expr))
8828 tt
8829 (continue t))
8830 (while continue
8831 (setq tt (js2-get-token))
8832 (if (memq tt js2-parse-shift-ops)
8833 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8834 (js2-unget-token)
8835 (setq continue nil)))
8836 pn))
8837
8838 (defun js2-parse-add-expr ()
8839 (let ((pn (js2-parse-mul-expr))
8840 tt
8841 (continue t))
8842 (while continue
8843 (setq tt (js2-get-token))
8844 (if (or (= tt js2-ADD) (= tt js2-SUB))
8845 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8846 (js2-unget-token)
8847 (setq continue nil)))
8848 pn))
8849
8850 (defconst js2-parse-mul-ops
8851 (list js2-MUL js2-DIV js2-MOD))
8852
8853 (defun js2-parse-mul-expr ()
8854 (let ((pn (js2-parse-unary-expr))
8855 tt
8856 (continue t))
8857 (while continue
8858 (setq tt (js2-get-token))
8859 (if (memq tt js2-parse-mul-ops)
8860 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8861 (js2-unget-token)
8862 (setq continue nil)))
8863 pn))
8864
8865 (defun js2-make-unary (type parser &rest args)
8866 "Make a unary node of type TYPE.
8867 PARSER is either a node (for postfix operators) or a function to call
8868 to parse the operand (for prefix operators)."
8869 (let* ((pos (js2-current-token-beg))
8870 (postfix (js2-node-p parser))
8871 (expr (if postfix
8872 parser
8873 (apply parser args)))
8874 end
8875 pn)
8876 (if postfix ; e.g. i++
8877 (setq pos (js2-node-pos expr)
8878 end (js2-current-token-end))
8879 (setq end (js2-node-end expr)))
8880 (setq pn (make-js2-unary-node :type type
8881 :pos pos
8882 :len (- end pos)
8883 :operand expr))
8884 (js2-node-add-children pn expr)
8885 pn))
8886
8887 (defconst js2-incrementable-node-types
8888 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8889 "Node types that can be the operand of a ++ or -- operator.")
8890
8891 (defun js2-check-bad-inc-dec (tt beg end unary)
8892 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8893 js2-incrementable-node-types)
8894 (js2-report-error (if (= tt js2-INC)
8895 "msg.bad.incr"
8896 "msg.bad.decr")
8897 nil beg (- end beg))))
8898
8899 (defun js2-parse-unary-expr ()
8900 (let ((tt (js2-current-token-type))
8901 pn expr beg end)
8902 (cond
8903 ((or (= tt js2-VOID)
8904 (= tt js2-NOT)
8905 (= tt js2-BITNOT)
8906 (= tt js2-TYPEOF))
8907 (js2-get-token)
8908 (js2-make-unary tt 'js2-parse-unary-expr))
8909 ((= tt js2-ADD)
8910 (js2-get-token)
8911 ;; Convert to special POS token in decompiler and parse tree
8912 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8913 ((= tt js2-SUB)
8914 (js2-get-token)
8915 ;; Convert to special NEG token in decompiler and parse tree
8916 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8917 ((or (= tt js2-INC)
8918 (= tt js2-DEC))
8919 (js2-get-token)
8920 (prog1
8921 (setq beg (js2-current-token-beg)
8922 end (js2-current-token-end)
8923 expr (js2-make-unary tt 'js2-parse-member-expr t))
8924 (js2-check-bad-inc-dec tt beg end expr)))
8925 ((= tt js2-DELPROP)
8926 (js2-get-token)
8927 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8928 ((= tt js2-ERROR)
8929 (js2-get-token)
8930 (make-js2-error-node)) ; try to continue
8931 ((and (= tt js2-LT)
8932 js2-compiler-xml-available)
8933 ;; XML stream encountered in expression.
8934 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8935 (t
8936 (setq pn (js2-parse-member-expr t)
8937 ;; Don't look across a newline boundary for a postfix incop.
8938 tt (js2-peek-token-or-eol))
8939 (when (or (= tt js2-INC) (= tt js2-DEC))
8940 (js2-get-token)
8941 (setf expr pn
8942 pn (js2-make-unary tt expr))
8943 (js2-node-set-prop pn 'postfix t)
8944 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8945 pn))))
8946
8947 (defun js2-parse-xml-initializer ()
8948 "Parse an E4X XML initializer.
8949 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8950 Then I'll postprocess the result, depending on whether we're in IDE
8951 mode or codegen mode, and generate the appropriate rewritten AST.
8952 IDE mode uses a rich AST that models the XML structure. Codegen mode
8953 just concatenates everything and makes a new XML or XMLList out of it."
8954 (let ((tt (js2-get-first-xml-token))
8955 pn-xml pn expr kids expr-pos
8956 (continue t)
8957 (first-token t))
8958 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8959 (js2-report-error "msg.syntax"))
8960 (setq pn-xml (make-js2-xml-node))
8961 (while continue
8962 (if first-token
8963 (setq first-token nil)
8964 (setq tt (js2-get-next-xml-token)))
8965 (cond
8966 ;; js2-XML means we found a {expr} in the XML stream.
8967 ;; The token string is the XML up to the left-curly.
8968 ((= tt js2-XML)
8969 (push (make-js2-string-node :pos (js2-current-token-beg)
8970 :len (- js2-ts-cursor (js2-current-token-beg)))
8971 kids)
8972 (js2-must-match js2-LC "msg.syntax")
8973 (setq expr-pos js2-ts-cursor
8974 expr (if (eq (js2-peek-token) js2-RC)
8975 (make-js2-empty-expr-node :pos expr-pos)
8976 (js2-parse-expr)))
8977 (js2-must-match js2-RC "msg.syntax")
8978 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8979 :len (js2-node-len expr)
8980 :expr expr))
8981 (js2-node-add-children pn expr)
8982 (push pn kids))
8983 ;; a js2-XMLEND token means we hit the final close-tag.
8984 ((= tt js2-XMLEND)
8985 (push (make-js2-string-node :pos (js2-current-token-beg)
8986 :len (- js2-ts-cursor (js2-current-token-beg)))
8987 kids)
8988 (dolist (kid (nreverse kids))
8989 (js2-block-node-push pn-xml kid))
8990 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8991 (js2-node-pos pn-xml))
8992 continue nil))
8993 (t
8994 (js2-report-error "msg.syntax")
8995 (setq continue nil))))
8996 pn-xml))
8997
8998
8999 (defun js2-parse-argument-list ()
9000 "Parse an argument list and return it as a Lisp list of nodes.
9001 Returns the list in reverse order. Consumes the right-paren token."
9002 (let (result)
9003 (unless (js2-match-token js2-RP)
9004 (loop do
9005 (let ((tt (js2-get-token)))
9006 (if (= tt js2-YIELD)
9007 (js2-report-error "msg.yield.parenthesized"))
9008 (if (and (= tt js2-TRIPLEDOT)
9009 (>= js2-language-version 200))
9010 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9011 (js2-unget-token)
9012 (push (js2-parse-assign-expr) result)))
9013 while
9014 (js2-match-token js2-COMMA))
9015 (js2-must-match js2-RP "msg.no.paren.arg")
9016 result)))
9017
9018 (defun js2-parse-member-expr (&optional allow-call-syntax)
9019 (let ((tt (js2-current-token-type))
9020 pn pos target args beg end init)
9021 (if (/= tt js2-NEW)
9022 (setq pn (js2-parse-primary-expr))
9023 ;; parse a 'new' expression
9024 (js2-get-token)
9025 (setq pos (js2-current-token-beg)
9026 beg pos
9027 target (js2-parse-member-expr)
9028 end (js2-node-end target)
9029 pn (make-js2-new-node :pos pos
9030 :target target
9031 :len (- end pos)))
9032 (js2-highlight-function-call (js2-current-token))
9033 (js2-node-add-children pn target)
9034 (when (js2-match-token js2-LP)
9035 ;; Add the arguments to pn, if any are supplied.
9036 (setf beg pos ; start of "new" keyword
9037 pos (js2-current-token-beg)
9038 args (nreverse (js2-parse-argument-list))
9039 (js2-new-node-args pn) args
9040 end (js2-current-token-end)
9041 (js2-new-node-lp pn) (- pos beg)
9042 (js2-new-node-rp pn) (- end 1 beg))
9043 (apply #'js2-node-add-children pn args))
9044 (when (and js2-allow-rhino-new-expr-initializer
9045 (js2-match-token js2-LC))
9046 (setf init (js2-parse-object-literal)
9047 end (js2-node-end init)
9048 (js2-new-node-initializer pn) init)
9049 (js2-node-add-children pn init))
9050 (setf (js2-node-len pn) (- end beg))) ; end outer if
9051 (js2-parse-member-expr-tail allow-call-syntax pn)))
9052
9053 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9054 "Parse a chain of property/array accesses or function calls.
9055 Includes parsing for E4X operators like `..' and `.@'.
9056 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9057 Returns an expression tree that includes PN, the parent node."
9058 (let (tt
9059 (continue t))
9060 (while continue
9061 (setq tt (js2-get-token))
9062 (cond
9063 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9064 (setq pn (js2-parse-property-access tt pn)))
9065 ((= tt js2-DOTQUERY)
9066 (setq pn (js2-parse-dot-query pn)))
9067 ((= tt js2-LB)
9068 (setq pn (js2-parse-element-get pn)))
9069 ((= tt js2-LP)
9070 (js2-unget-token)
9071 (if allow-call-syntax
9072 (setq pn (js2-parse-function-call pn))
9073 (setq continue nil)))
9074 (t
9075 (js2-unget-token)
9076 (setq continue nil))))
9077 (if (>= js2-highlight-level 2)
9078 (js2-parse-highlight-member-expr-node pn))
9079 pn))
9080
9081 (defun js2-parse-dot-query (pn)
9082 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9083 Last token parsed must be `js2-DOTQUERY'."
9084 (let ((pos (js2-node-pos pn))
9085 op-pos expr end)
9086 (js2-must-have-xml)
9087 (js2-set-requires-activation)
9088 (setq op-pos (js2-current-token-beg)
9089 expr (js2-parse-expr)
9090 end (js2-node-end expr)
9091 pn (make-js2-xml-dot-query-node :left pn
9092 :pos pos
9093 :op-pos op-pos
9094 :right expr))
9095 (js2-node-add-children pn
9096 (js2-xml-dot-query-node-left pn)
9097 (js2-xml-dot-query-node-right pn))
9098 (if (js2-must-match js2-RP "msg.no.paren")
9099 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9100 end (js2-current-token-end)))
9101 (setf (js2-node-len pn) (- end pos))
9102 pn))
9103
9104 (defun js2-parse-element-get (pn)
9105 "Parse an element-get expression, e.g. foo[bar].
9106 Last token parsed must be `js2-RB'."
9107 (let ((lb (js2-current-token-beg))
9108 (pos (js2-node-pos pn))
9109 rb expr)
9110 (setq expr (js2-parse-expr))
9111 (if (js2-must-match js2-RB "msg.no.bracket.index")
9112 (setq rb (js2-current-token-beg)))
9113 (setq pn (make-js2-elem-get-node :target pn
9114 :pos pos
9115 :element expr
9116 :lb (js2-relpos lb pos)
9117 :rb (js2-relpos rb pos)
9118 :len (- (js2-current-token-end) pos)))
9119 (js2-node-add-children pn
9120 (js2-elem-get-node-target pn)
9121 (js2-elem-get-node-element pn))
9122 pn))
9123
9124 (defun js2-highlight-function-call (token)
9125 (when (eq (js2-token-type token) js2-NAME)
9126 (js2-record-face 'js2-function-call token)))
9127
9128 (defun js2-parse-function-call (pn)
9129 (js2-highlight-function-call (js2-current-token))
9130 (js2-get-token)
9131 (let (args
9132 (pos (js2-node-pos pn)))
9133 (setq pn (make-js2-call-node :pos pos
9134 :target pn
9135 :lp (- (js2-current-token-beg) pos)))
9136 (js2-node-add-children pn (js2-call-node-target pn))
9137 ;; Add the arguments to pn, if any are supplied.
9138 (setf args (nreverse (js2-parse-argument-list))
9139 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9140 (js2-call-node-args pn) args)
9141 (apply #'js2-node-add-children pn args)
9142 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9143 pn))
9144
9145 (defun js2-parse-property-access (tt pn)
9146 "Parse a property access, XML descendants access, or XML attr access."
9147 (let ((member-type-flags 0)
9148 (dot-pos (js2-current-token-beg))
9149 (dot-len (if (= tt js2-DOTDOT) 2 1))
9150 name
9151 ref ; right side of . or .. operator
9152 result)
9153 (when (= tt js2-DOTDOT)
9154 (js2-must-have-xml)
9155 (setq member-type-flags js2-descendants-flag))
9156 (if (not js2-compiler-xml-available)
9157 (progn
9158 (js2-must-match-prop-name "msg.no.name.after.dot")
9159 (setq name (js2-create-name-node t js2-GETPROP)
9160 result (make-js2-prop-get-node :left pn
9161 :pos (js2-current-token-beg)
9162 :right name
9163 :len (js2-current-token-len)))
9164 (js2-node-add-children result pn name)
9165 result)
9166 ;; otherwise look for XML operators
9167 (setf result (if (= tt js2-DOT)
9168 (make-js2-prop-get-node)
9169 (make-js2-infix-node :type js2-DOTDOT))
9170 (js2-node-pos result) (js2-node-pos pn)
9171 (js2-infix-node-op-pos result) dot-pos
9172 (js2-infix-node-left result) pn ; do this after setting position
9173 tt (js2-next-token))
9174 (cond
9175 ;; needed for generator.throw()
9176 ((= tt js2-THROW)
9177 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9178 ;; handles: name, ns::name, ns::*, ns::[expr]
9179 ((js2-valid-prop-name-token tt)
9180 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9181 ;; handles: *, *::name, *::*, *::[expr]
9182 ((= tt js2-MUL)
9183 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9184 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9185 ((= tt js2-XMLATTR)
9186 (setq result (js2-parse-attribute-access)))
9187 (t
9188 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9189 (if ref
9190 (setf (js2-node-len result) (- (js2-node-end ref)
9191 (js2-node-pos result))
9192 (js2-infix-node-right result) ref))
9193 (if (js2-infix-node-p result)
9194 (js2-node-add-children result
9195 (js2-infix-node-left result)
9196 (js2-infix-node-right result)))
9197 result)))
9198
9199 (defun js2-parse-attribute-access ()
9200 "Parse an E4X XML attribute expression.
9201 This includes expressions of the forms:
9202
9203 @attr @ns::attr @ns::*
9204 @* @*::attr @*::*
9205 @[expr] @*::[expr] @ns::[expr]
9206
9207 Called if we peeked an '@' token."
9208 (let ((tt (js2-next-token))
9209 (at-pos (js2-current-token-beg)))
9210 (cond
9211 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9212 ((js2-valid-prop-name-token tt)
9213 (js2-parse-property-name at-pos nil 0))
9214 ;; handles: @*, @*::name, @*::*, @*::[expr]
9215 ((= tt js2-MUL)
9216 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9217 ;; handles @[expr]
9218 ((= tt js2-LB)
9219 (js2-parse-xml-elem-ref at-pos))
9220 (t
9221 (js2-report-error "msg.no.name.after.xmlAttr")
9222 ;; Avoid cascaded errors that happen if we make an error node here.
9223 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9224
9225 (defun js2-parse-property-name (at-pos s member-type-flags)
9226 "Check if :: follows name in which case it becomes qualified name.
9227
9228 AT-POS is a natural number if we just read an '@' token, else nil.
9229 S is the name or string that was matched: an identifier, 'throw' or '*'.
9230 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9231
9232 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9233 operator, or the name is followed by ::. For a plain name, returns a
9234 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9235 (let ((pos (or at-pos (js2-current-token-beg)))
9236 colon-pos
9237 (name (js2-create-name-node t (js2-current-token-type) s))
9238 ns tt pn)
9239 (catch 'return
9240 (when (js2-match-token js2-COLONCOLON)
9241 (setq ns name
9242 colon-pos (js2-current-token-beg)
9243 tt (js2-next-token))
9244 (cond
9245 ;; handles name::name
9246 ((js2-valid-prop-name-token tt)
9247 (setq name (js2-create-name-node)))
9248 ;; handles name::*
9249 ((= tt js2-MUL)
9250 (setq name (js2-create-name-node nil nil "*")))
9251 ;; handles name::[expr]
9252 ((= tt js2-LB)
9253 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9254 (t
9255 (js2-report-error "msg.no.name.after.coloncolon"))))
9256 (if (and (null ns) (zerop member-type-flags))
9257 name
9258 (prog1
9259 (setq pn
9260 (make-js2-xml-prop-ref-node :pos pos
9261 :len (- (js2-node-end name) pos)
9262 :at-pos at-pos
9263 :colon-pos colon-pos
9264 :propname name))
9265 (js2-node-add-children pn name))))))
9266
9267 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9268 "Parse the [expr] portion of an xml element reference.
9269 For instance, @[expr], @*::[expr], or ns::[expr]."
9270 (let* ((lb (js2-current-token-beg))
9271 (pos (or at-pos lb))
9272 rb
9273 (expr (js2-parse-expr))
9274 (end (js2-node-end expr))
9275 pn)
9276 (if (js2-must-match js2-RB "msg.no.bracket.index")
9277 (setq rb (js2-current-token-beg)
9278 end (js2-current-token-end)))
9279 (prog1
9280 (setq pn
9281 (make-js2-xml-elem-ref-node :pos pos
9282 :len (- end pos)
9283 :namespace namespace
9284 :colon-pos colon-pos
9285 :at-pos at-pos
9286 :expr expr
9287 :lb (js2-relpos lb pos)
9288 :rb (js2-relpos rb pos)))
9289 (js2-node-add-children pn namespace expr))))
9290
9291 (defun js2-parse-destruct-primary-expr ()
9292 (let ((js2-is-in-destructuring t))
9293 (js2-parse-primary-expr)))
9294
9295 (defun js2-parse-primary-expr ()
9296 "Parse a literal (leaf) expression of some sort.
9297 Includes complex literals such as functions, object-literals,
9298 array-literals, array comprehensions and regular expressions."
9299 (let (pn ; parent node (usually return value)
9300 tt)
9301 (setq tt (js2-current-token-type))
9302 (cond
9303 ((= tt js2-CLASS)
9304 (js2-parse-class-expr))
9305 ((= tt js2-FUNCTION)
9306 (js2-parse-function-expr))
9307 ((= tt js2-LB)
9308 (js2-parse-array-comp-or-literal))
9309 ((= tt js2-LC)
9310 (js2-parse-object-literal))
9311 ((= tt js2-LET)
9312 (js2-parse-let (js2-current-token-beg)))
9313 ((= tt js2-LP)
9314 (js2-parse-paren-expr-or-generator-comp))
9315 ((= tt js2-XMLATTR)
9316 (js2-must-have-xml)
9317 (js2-parse-attribute-access))
9318 ((= tt js2-NAME)
9319 (js2-parse-name tt))
9320 ((= tt js2-NUMBER)
9321 (make-js2-number-node))
9322 ((= tt js2-STRING)
9323 (prog1
9324 (make-js2-string-node)
9325 (js2-record-face 'font-lock-string-face)))
9326 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9327 ;; Got / or /= which in this context means a regexp literal
9328 (let ((px-pos (js2-current-token-beg))
9329 (flags (js2-read-regexp tt))
9330 (end (js2-current-token-end)))
9331 (prog1
9332 (make-js2-regexp-node :pos px-pos
9333 :len (- end px-pos)
9334 :value (js2-current-token-string)
9335 :flags flags)
9336 (js2-set-face px-pos end 'font-lock-string-face 'record)
9337 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9338 ((or (= tt js2-NULL)
9339 (= tt js2-THIS)
9340 (= tt js2-FALSE)
9341 (= tt js2-TRUE))
9342 (make-js2-keyword-node :type tt))
9343 ((= tt js2-RP)
9344 ;; Not valid expression syntax, but this is valid in an arrow
9345 ;; function with no params: () => body.
9346 (if (eq (js2-peek-token) js2-ARROW)
9347 (progn
9348 (js2-unget-token) ; Put back the right paren.
9349 ;; Return whatever, it will hopefully be rewinded and
9350 ;; reparsed when we reach the =>.
9351 (make-js2-keyword-node :type js2-NULL))
9352 (js2-report-error "msg.syntax")
9353 (make-js2-error-node)))
9354 ((= tt js2-TRIPLEDOT)
9355 ;; Likewise, only valid in an arrow function with a rest param.
9356 (if (and (js2-match-token js2-NAME)
9357 (js2-match-token js2-RP)
9358 (eq (js2-peek-token) js2-ARROW))
9359 (progn
9360 (js2-unget-token) ; Put back the right paren.
9361 ;; See the previous case.
9362 (make-js2-keyword-node :type js2-NULL))
9363 (js2-report-error "msg.syntax")
9364 (make-js2-error-node)))
9365 ((= tt js2-RESERVED)
9366 (js2-report-error "msg.reserved.id")
9367 (make-js2-name-node))
9368 ((= tt js2-ERROR)
9369 ;; the scanner or one of its subroutines reported the error.
9370 (make-js2-error-node))
9371 ((= tt js2-EOF)
9372 (let* ((px-pos (point-at-bol))
9373 (len (- js2-ts-cursor px-pos)))
9374 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9375 (make-js2-error-node :pos (1- js2-ts-cursor)))
9376 (t
9377 (js2-report-error "msg.syntax")
9378 (make-js2-error-node)))))
9379
9380 (defun js2-parse-name (_tt)
9381 (let ((name (js2-current-token-string))
9382 node)
9383 (setq node (if js2-compiler-xml-available
9384 (js2-parse-property-name nil name 0)
9385 (js2-create-name-node 'check-activation nil name)))
9386 (if js2-highlight-external-variables
9387 (js2-record-name-node node))
9388 node))
9389
9390 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9391 (js2-add-strict-warning
9392 msg nil
9393 ;; back up from comma to beginning of line or array/objlit
9394 (max (if elems
9395 (js2-node-pos (car elems))
9396 pos)
9397 (save-excursion
9398 (goto-char comma-pos)
9399 (back-to-indentation)
9400 (point)))
9401 comma-pos))
9402
9403 (defun js2-parse-array-comp-or-literal ()
9404 (let ((pos (js2-current-token-beg)))
9405 (if (and (>= js2-language-version 200)
9406 (js2-match-token js2-FOR))
9407 (js2-parse-array-comp pos)
9408 (js2-parse-array-literal pos))))
9409
9410 (defun js2-parse-array-literal (pos)
9411 (let ((after-lb-or-comma t)
9412 after-comma tt elems pn
9413 (continue t))
9414 (unless js2-is-in-destructuring
9415 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9416 (while continue
9417 (setq tt (js2-get-token))
9418 (cond
9419 ;; comma
9420 ((= tt js2-COMMA)
9421 (setq after-comma (js2-current-token-end))
9422 (if (not after-lb-or-comma)
9423 (setq after-lb-or-comma t)
9424 (push nil elems)))
9425 ;; end of array
9426 ((or (= tt js2-RB)
9427 (= tt js2-EOF)) ; prevent infinite loop
9428 (if (= tt js2-EOF)
9429 (js2-report-error "msg.no.bracket.arg" nil pos))
9430 (when (and after-comma (< js2-language-version 170))
9431 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9432 pos (remove nil elems) after-comma))
9433 (setq continue nil
9434 pn (make-js2-array-node :pos pos
9435 :len (- js2-ts-cursor pos)
9436 :elems (nreverse elems)))
9437 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9438 ;; destructuring binding
9439 (js2-is-in-destructuring
9440 (push (if (or (= tt js2-LC)
9441 (= tt js2-LB)
9442 (= tt js2-NAME))
9443 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9444 (js2-parse-destruct-primary-expr)
9445 ;; invalid pattern
9446 (js2-report-error "msg.bad.var")
9447 (make-js2-error-node))
9448 elems)
9449 (setq after-lb-or-comma nil
9450 after-comma nil))
9451 ;; array comp
9452 ((and (>= js2-language-version 170)
9453 (= tt js2-FOR) ; check for array comprehension
9454 (not after-lb-or-comma) ; "for" can't follow a comma
9455 elems ; must have at least 1 element
9456 (not (cdr elems))) ; but no 2nd element
9457 (js2-unget-token)
9458 (setf continue nil
9459 pn (js2-parse-legacy-array-comp (car elems) pos)))
9460 ;; another element
9461 (t
9462 (unless after-lb-or-comma
9463 (js2-report-error "msg.no.bracket.arg"))
9464 (if (and (= tt js2-TRIPLEDOT)
9465 (>= js2-language-version 200))
9466 ;; spread operator
9467 (push (js2-make-unary tt 'js2-parse-assign-expr)
9468 elems)
9469 (js2-unget-token)
9470 (push (js2-parse-assign-expr) elems))
9471 (setq after-lb-or-comma nil
9472 after-comma nil))))
9473 (unless js2-is-in-destructuring
9474 (js2-pop-scope))
9475 pn))
9476
9477 (defun js2-parse-legacy-array-comp (expr pos)
9478 "Parse a legacy array comprehension (JavaScript 1.7).
9479 EXPR is the first expression after the opening left-bracket.
9480 POS is the beginning of the LB token preceding EXPR.
9481 We should have just parsed the 'for' keyword before calling this function."
9482 (let ((current-scope js2-current-scope)
9483 loops first filter result)
9484 (unwind-protect
9485 (progn
9486 (while (js2-match-token js2-FOR)
9487 (let ((loop (make-js2-comp-loop-node)))
9488 (js2-push-scope loop)
9489 (push loop loops)
9490 (js2-parse-comp-loop loop)))
9491 ;; First loop takes expr scope's parent.
9492 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9493 (js2-scope-parent-scope current-scope))
9494 ;; Set expr scope's parent to the last loop.
9495 (setf (js2-scope-parent-scope current-scope) (car loops))
9496 (if (/= (js2-get-token) js2-IF)
9497 (js2-unget-token)
9498 (setq filter (js2-parse-condition))))
9499 (dotimes (_ (1- (length loops)))
9500 (js2-pop-scope)))
9501 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9502 (setq result (make-js2-comp-node :pos pos
9503 :len (- js2-ts-cursor pos)
9504 :result expr
9505 :loops (nreverse loops)
9506 :filters (and filter (list (car filter)))
9507 :form 'LEGACY_ARRAY))
9508 (apply #'js2-node-add-children result expr (car filter)
9509 (js2-comp-node-loops result))
9510 result))
9511
9512 (defun js2-parse-array-comp (pos)
9513 "Parse an ES6 array comprehension.
9514 POS is the beginning of the LB token.
9515 We should have just parsed the 'for' keyword before calling this function."
9516 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9517 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9518 pn))
9519
9520 (defun js2-parse-generator-comp (pos)
9521 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9522 (js2-current-script-or-fn
9523 (make-js2-function-node :generator-type 'COMPREHENSION))
9524 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9525 (js2-must-match js2-RP "msg.no.paren" pos)
9526 pn))
9527
9528 (defun js2-parse-comprehension (pos form)
9529 (let (loops filters expr result)
9530 (unwind-protect
9531 (progn
9532 (js2-unget-token)
9533 (while (js2-match-token js2-FOR)
9534 (let ((loop (make-js2-comp-loop-node)))
9535 (js2-push-scope loop)
9536 (push loop loops)
9537 (js2-parse-comp-loop loop)))
9538 (while (js2-match-token js2-IF)
9539 (push (car (js2-parse-condition)) filters))
9540 (setq expr (js2-parse-assign-expr)))
9541 (dolist (_ loops)
9542 (js2-pop-scope)))
9543 (setq result (make-js2-comp-node :pos pos
9544 :len (- js2-ts-cursor pos)
9545 :result expr
9546 :loops (nreverse loops)
9547 :filters (nreverse filters)
9548 :form form))
9549 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9550 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9551 result))
9552
9553 (defun js2-parse-comp-loop (pn &optional only-of-p)
9554 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9555 The current token should be the initial FOR.
9556 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9557 (let ((pos (js2-comp-loop-node-pos pn))
9558 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9559 (when (and (not only-of-p) (js2-match-token js2-NAME))
9560 (if (string= (js2-current-token-string) "each")
9561 (progn
9562 (setq foreach-p t
9563 each-pos (- (js2-current-token-beg) pos)) ; relative
9564 (js2-record-face 'font-lock-keyword-face))
9565 (js2-report-error "msg.no.paren.for")))
9566 (if (js2-must-match js2-LP "msg.no.paren.for")
9567 (setq lp (- (js2-current-token-beg) pos)))
9568 (setq tt (js2-peek-token))
9569 (cond
9570 ((or (= tt js2-LB)
9571 (= tt js2-LC))
9572 (js2-get-token)
9573 (setq iter (js2-parse-destruct-primary-expr))
9574 (js2-define-destruct-symbols iter js2-LET
9575 'font-lock-variable-name-face t))
9576 ((js2-match-token js2-NAME)
9577 (setq iter (js2-create-name-node)))
9578 (t
9579 (js2-report-error "msg.bad.var")))
9580 ;; Define as a let since we want the scope of the variable to
9581 ;; be restricted to the array comprehension
9582 (if (js2-name-node-p iter)
9583 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9584 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9585 (and (>= js2-language-version 200)
9586 (js2-match-contextual-kwd "of")
9587 (setq forof-p t)))
9588 (setq in-pos (- (js2-current-token-beg) pos))
9589 (js2-report-error "msg.in.after.for.name"))
9590 (setq obj (js2-parse-expr))
9591 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9592 (setq rp (- (js2-current-token-beg) pos)))
9593 (setf (js2-node-pos pn) pos
9594 (js2-node-len pn) (- js2-ts-cursor pos)
9595 (js2-comp-loop-node-iterator pn) iter
9596 (js2-comp-loop-node-object pn) obj
9597 (js2-comp-loop-node-in-pos pn) in-pos
9598 (js2-comp-loop-node-each-pos pn) each-pos
9599 (js2-comp-loop-node-foreach-p pn) foreach-p
9600 (js2-comp-loop-node-forof-p pn) forof-p
9601 (js2-comp-loop-node-lp pn) lp
9602 (js2-comp-loop-node-rp pn) rp)
9603 (js2-node-add-children pn iter obj)
9604 pn))
9605
9606 (defun js2-parse-class-stmt ()
9607 (let ((pos (js2-current-token-beg)))
9608 (js2-must-match-name "msg.unnamed.class.stmt")
9609 (js2-parse-class pos 'CLASS_STATEMENT (js2-create-name-node t))))
9610
9611 (defun js2-parse-class-expr ()
9612 (let ((pos (js2-current-token-beg))
9613 name)
9614 (when (js2-match-token js2-NAME)
9615 (setq name (js2-create-name-node t)))
9616 (js2-parse-class pos 'CLASS_EXPRESSION name)))
9617
9618 (defun js2-parse-class (pos form name)
9619 ;; class X [extends ...] {
9620 (let (pn elems extends)
9621 (when name
9622 (js2-set-face (js2-node-pos name) (js2-node-end name)
9623 'font-lock-function-name-face 'record))
9624 (if (js2-match-token js2-EXTENDS)
9625 (if (= (js2-peek-token) js2-LC)
9626 (js2-report-error "msg.missing.extends")
9627 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
9628 (setq extends (js2-parse-assign-expr))
9629 (if (not extends)
9630 (js2-report-error "msg.bad.extends"))))
9631 (js2-must-match js2-LC "msg.no.brace.class")
9632 (setq elems (js2-parse-object-literal-elems t)
9633 pn (make-js2-class-node :pos pos
9634 :len (- js2-ts-cursor pos)
9635 :form form
9636 :name name
9637 :extends extends
9638 :elems elems))
9639 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
9640 pn))
9641
9642 (defun js2-parse-object-literal ()
9643 (let* ((pos (js2-current-token-beg))
9644 (elems (js2-parse-object-literal-elems))
9645 (result (make-js2-object-node :pos pos
9646 :len (- js2-ts-cursor pos)
9647 :elems elems)))
9648 (apply #'js2-node-add-children result (js2-object-node-elems result))
9649 result))
9650
9651 (defun js2-parse-object-literal-elems (&optional class-p)
9652 (let ((pos (js2-current-token-beg))
9653 tt elems result after-comma
9654 (continue t))
9655 (while continue
9656 (setq tt (js2-get-token))
9657 (cond
9658 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9659 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
9660 ;; TODO(sdh): support *foo() {...}
9661 ((or (js2-valid-prop-name-token tt)
9662 (= tt js2-STRING))
9663 (setq after-comma nil
9664 result (js2-parse-named-prop tt))
9665 (if (and (null result)
9666 (not js2-recover-from-parse-errors))
9667 (setq continue nil)
9668 (push result elems)))
9669 ;; {[Symbol.iterator]: ...}
9670 ((and (= tt js2-LB)
9671 (>= js2-language-version 200))
9672 (let ((expr (js2-parse-expr)))
9673 (js2-must-match js2-RB "msg.missing.computed.rb")
9674 (setq after-comma nil)
9675 (push (js2-parse-plain-property expr) elems)))
9676 ;; {12: x} or {10.7: x}
9677 ((= tt js2-NUMBER)
9678 (setq after-comma nil)
9679 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9680 ;; break out of loop, trailing comma
9681 ((or (= tt js2-RC)
9682 (= tt js2-EOF))
9683 (js2-unget-token)
9684 (setq continue nil)
9685 (if after-comma
9686 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9687 pos elems after-comma)))
9688 (t
9689 (js2-report-error "msg.bad.prop")
9690 (unless js2-recover-from-parse-errors
9691 (setq continue nil)))) ; end switch
9692 ;; handle commas, depending on class-p
9693 (let ((comma (js2-match-token js2-COMMA)))
9694 (if class-p
9695 (if comma
9696 (js2-report-error "msg.class.unexpected.comma"))
9697 (if comma
9698 (setq after-comma (js2-current-token-end))
9699 (setq continue nil))))) ; end loop
9700 (js2-must-match js2-RC "msg.no.brace.prop")
9701 (nreverse elems)))
9702
9703 (defun js2-parse-named-prop (tt)
9704 "Parse a name, string, or getter/setter object property.
9705 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9706 (let ((string-prop (and (= tt js2-STRING)
9707 (make-js2-string-node)))
9708 expr
9709 (ppos (js2-current-token-beg))
9710 (pend (js2-current-token-end))
9711 (name (js2-create-name-node))
9712 (prop (js2-current-token-string)))
9713 (cond
9714 ;; getter/setter prop
9715 ((and (= tt js2-NAME)
9716 (= (js2-peek-token) js2-NAME)
9717 (or (string= prop "get")
9718 (string= prop "set")))
9719 (js2-get-token)
9720 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9721 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9722 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9723 (js2-parse-getter-setter-prop ppos name prop))
9724 ;; method definition: {f() {...}}
9725 ((and (= (js2-peek-token) js2-LP)
9726 (>= js2-language-version 200))
9727 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; name
9728 (js2-parse-getter-setter-prop ppos name ""))
9729 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9730 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9731 ;; when patterns are used in variable declarations, function parameters,
9732 ;; catch-clause, and iterators.
9733 ;; We have to set `js2-is-in-destructuring' to t when the current
9734 ;; expressions are on the left side of any assignment, but it's difficult
9735 ;; because it requires looking ahead of expression.
9736 ((and js2-is-in-destructuring
9737 (= tt js2-NAME)
9738 (let ((ctk (js2-peek-token)))
9739 (or (= ctk js2-COMMA)
9740 (= ctk js2-RC)
9741 (js2-valid-prop-name-token ctk))))
9742 name)
9743 ;; regular prop
9744 (t
9745 (prog1
9746 (setq expr (js2-parse-plain-property (or string-prop name)))
9747 (js2-set-face ppos pend
9748 (if (js2-function-node-p
9749 (js2-object-prop-node-right expr))
9750 'font-lock-function-name-face
9751 'font-lock-variable-name-face)
9752 'record))))))
9753
9754 (defun js2-parse-plain-property (prop)
9755 "Parse a non-getter/setter property in an object literal.
9756 PROP is the node representing the property: a number, name or string."
9757 (let* ((tt (js2-get-token))
9758 (pos (js2-node-pos prop))
9759 colon expr result)
9760 (cond
9761 ;; Abbreviated property, as in {foo, bar}
9762 ((and (>= js2-language-version 200)
9763 (or (= tt js2-COMMA)
9764 (= tt js2-RC)))
9765 (js2-unget-token)
9766 (setq result (make-js2-object-prop-node
9767 :pos pos
9768 :left prop
9769 :right prop
9770 :op-pos (js2-current-token-len)))
9771 (js2-node-add-children result prop)
9772 (js2-node-set-prop result 'SHORTHAND t)
9773 result)
9774 ;; Normal property
9775 (t
9776 (if (= tt js2-COLON)
9777 (setq colon (- (js2-current-token-beg) pos)
9778 expr (js2-parse-assign-expr))
9779 (js2-report-error "msg.no.colon.prop")
9780 (setq expr (make-js2-error-node)))
9781 (setq result (make-js2-object-prop-node
9782 :pos pos
9783 ;; don't include last consumed token in length
9784 :len (- (+ (js2-node-pos expr)
9785 (js2-node-len expr))
9786 pos)
9787 :left prop
9788 :right expr
9789 :op-pos colon))
9790 (js2-node-add-children result prop expr)
9791 result))))
9792
9793 (defun js2-parse-getter-setter-prop (pos prop type-string)
9794 "Parse getter or setter property in an object literal.
9795 JavaScript syntax is:
9796
9797 { get foo() {...}, set foo(x) {...} }
9798
9799 and expression closure style is also supported
9800
9801 { get foo() x, set foo(x) _x = x }
9802
9803 POS is the start position of the `get' or `set' keyword.
9804 PROP is the `js2-name-node' representing the property name.
9805 GET-P is non-nil if the keyword was `get'."
9806 (let ((type (cond
9807 ((string= "get" type-string) js2-GET)
9808 ((string= "set" type-string) js2-SET)
9809 (t js2-FUNCTION)))
9810 result end
9811 (fn (js2-parse-function-expr)))
9812 ;; it has to be an anonymous function, as we already parsed the name
9813 (if (/= (js2-node-type fn) js2-FUNCTION)
9814 (js2-report-error "msg.bad.prop")
9815 (if (plusp (length (js2-function-name fn)))
9816 (js2-report-error "msg.bad.prop")))
9817 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9818 (setq end (js2-node-end fn)
9819 result (make-js2-getter-setter-node :type type
9820 :pos pos
9821 :len (- end pos)
9822 :left prop
9823 :right fn))
9824 (js2-node-add-children result prop fn)
9825 result))
9826
9827 (defun js2-create-name-node (&optional check-activation-p token string)
9828 "Create a name node using the current token and, optionally, STRING.
9829 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9830 (let* ((beg (js2-current-token-beg))
9831 (tt (js2-current-token-type))
9832 (s (or string
9833 (if (= js2-NAME tt)
9834 (js2-current-token-string)
9835 (js2-tt-name tt))))
9836 name)
9837 (setq name (make-js2-name-node :pos beg
9838 :name s
9839 :len (length s)))
9840 (if check-activation-p
9841 (js2-check-activation-name s (or token js2-NAME)))
9842 name))
9843
9844 ;;; Indentation support
9845
9846 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9847 ;; Karl cleverly deduces that the desired indentation level is often a
9848 ;; function of paren/bracket/brace nesting depth, which can be determined
9849 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9850 ;; then does some equally clever checks to see if we're in the context of a
9851 ;; substatement of a possibly braceless statement keyword such as if, while,
9852 ;; or finally. This approach yields pretty good results.
9853
9854 ;; The indenter is often "wrong", however, and needs to be overridden.
9855 ;; The right long-term solution is probably to emulate (or integrate
9856 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9857 ;; parse tree from `js2-parse' is present, which is not true at the
9858 ;; moment the user is typing, computing indentation is still thousands
9859 ;; of lines of code to handle every possible syntactic edge case.
9860
9861 ;; In the meantime, the compromise solution is that we offer a "bounce
9862 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9863 ;; current line indent among various likely guess points. This approach
9864 ;; is far from perfect, but should at least make it slightly easier to
9865 ;; move the line towards its desired indentation when manually
9866 ;; overriding Karl's heuristic nesting guesser.
9867
9868 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9869 ;; extensions such as `let' and Array comprehensions. Major kudos to
9870 ;; Karl for coming up with the initial approach, which packs a lot of
9871 ;; punch for so little code.
9872
9873 (defconst js2-possibly-braceless-keywords-re
9874 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9875 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9876 "try" "while" "with" "let")))
9877 "Regular expression matching keywords that are optionally
9878 followed by an opening brace.")
9879
9880 (defconst js2-indent-operator-re
9881 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9882 (regexp-opt '("in" "instanceof") 'words))
9883 "Regular expression matching operators that affect indentation
9884 of continued expressions.")
9885
9886 (defconst js2-declaration-keyword-re
9887 (regexp-opt '("var" "let" "const") 'words)
9888 "Regular expression matching variable declaration keywords.")
9889
9890 (defun js2-re-search-forward-inner (regexp &optional bound count)
9891 "Auxiliary function for `js2-re-search-forward'."
9892 (let (parse saved-point)
9893 (while (> count 0)
9894 (re-search-forward regexp bound)
9895 (setq parse (if saved-point
9896 (parse-partial-sexp saved-point (point))
9897 (syntax-ppss (point))))
9898 (cond ((nth 3 parse)
9899 (re-search-forward
9900 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9901 (save-excursion (end-of-line) (point)) t))
9902 ((nth 7 parse)
9903 (forward-line))
9904 ((or (nth 4 parse)
9905 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9906 (re-search-forward "\\*/"))
9907 (t
9908 (setq count (1- count))))
9909 (setq saved-point (point))))
9910 (point))
9911
9912 (defun js2-re-search-forward (regexp &optional bound noerror count)
9913 "Search forward but ignore strings and comments.
9914 Invokes `re-search-forward' but treats the buffer as if strings
9915 and comments have been removed."
9916 (let ((saved-point (point)))
9917 (condition-case err
9918 (cond ((null count)
9919 (js2-re-search-forward-inner regexp bound 1))
9920 ((< count 0)
9921 (js2-re-search-backward-inner regexp bound (- count)))
9922 ((> count 0)
9923 (js2-re-search-forward-inner regexp bound count)))
9924 (search-failed
9925 (goto-char saved-point)
9926 (unless noerror
9927 (error (error-message-string err)))))))
9928
9929 (defun js2-re-search-backward-inner (regexp &optional bound count)
9930 "Auxiliary function for `js2-re-search-backward'."
9931 (let (parse)
9932 (while (> count 0)
9933 (re-search-backward regexp bound)
9934 (setq parse (syntax-ppss (point)))
9935 (cond ((nth 3 parse)
9936 (re-search-backward
9937 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9938 (line-beginning-position) t))
9939 ((nth 7 parse)
9940 (goto-char (nth 8 parse)))
9941 ((or (nth 4 parse)
9942 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9943 (re-search-backward "/\\*"))
9944 (t
9945 (setq count (1- count))))))
9946 (point))
9947
9948 (defun js2-re-search-backward (regexp &optional bound noerror count)
9949 "Search backward but ignore strings and comments.
9950 Invokes `re-search-backward' but treats the buffer as if strings
9951 and comments have been removed."
9952 (let ((saved-point (point)))
9953 (condition-case err
9954 (cond ((null count)
9955 (js2-re-search-backward-inner regexp bound 1))
9956 ((< count 0)
9957 (js2-re-search-forward-inner regexp bound (- count)))
9958 ((> count 0)
9959 (js2-re-search-backward-inner regexp bound count)))
9960 (search-failed
9961 (goto-char saved-point)
9962 (unless noerror
9963 (error (error-message-string err)))))))
9964
9965 (defun js2-looking-at-operator-p ()
9966 "Return non-nil if text after point is a non-comma operator."
9967 (and (looking-at js2-indent-operator-re)
9968 (or (not (looking-at ":"))
9969 (save-excursion
9970 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9971 (looking-at "?"))))))
9972
9973 (defun js2-continued-expression-p ()
9974 "Return non-nil if the current line continues an expression."
9975 (save-excursion
9976 (back-to-indentation)
9977 (or (js2-looking-at-operator-p)
9978 (when (catch 'found
9979 (while (and (re-search-backward "\n" nil t)
9980 (let ((state (syntax-ppss)))
9981 (when (nth 4 state)
9982 (goto-char (nth 8 state))) ;; skip comments
9983 (skip-chars-backward " \t")
9984 (if (bolp)
9985 t
9986 (throw 'found t))))))
9987 (backward-char)
9988 (when (js2-looking-at-operator-p)
9989 (backward-char)
9990 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
9991
9992 (defun js2-end-of-do-while-loop-p ()
9993 "Return non-nil if word after point is `while' of a do-while
9994 statement, else returns nil. A braceless do-while statement
9995 spanning several lines requires that the start of the loop is
9996 indented to the same column as the current line."
9997 (interactive)
9998 (save-excursion
9999 (when (looking-at "\\s-*\\<while\\>")
10000 (if (save-excursion
10001 (skip-chars-backward "[ \t\n]*}")
10002 (looking-at "[ \t\n]*}"))
10003 (save-excursion
10004 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10005 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10006 (or (looking-at "\\<do\\>")
10007 (let ((saved-indent (current-indentation)))
10008 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10009 (/= (current-indentation) saved-indent)))
10010 (and (looking-at "[ \t]*\\<do\\>")
10011 (not (js2-re-search-forward
10012 "\\<while\\>" (point-at-eol) t))
10013 (= (current-indentation) saved-indent))))))))
10014
10015 (defun js2-multiline-decl-indentation ()
10016 "Return the declaration indentation column if the current line belongs
10017 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10018 (let (forward-sexp-function ; use Lisp version
10019 at-opening-bracket)
10020 (save-excursion
10021 (back-to-indentation)
10022 (when (not (looking-at js2-declaration-keyword-re))
10023 (when (looking-at js2-indent-operator-re)
10024 (goto-char (match-end 0))) ; continued expressions are ok
10025 (while (and (not at-opening-bracket)
10026 (not (bobp))
10027 (let ((pos (point)))
10028 (save-excursion
10029 (js2-backward-sws)
10030 (or (eq (char-before) ?,)
10031 (and (not (eq (char-before) ?\;))
10032 (prog2 (skip-syntax-backward ".")
10033 (looking-at js2-indent-operator-re)
10034 (js2-backward-sws))
10035 (not (eq (char-before) ?\;)))
10036 (js2-same-line pos)))))
10037 (condition-case _
10038 (backward-sexp)
10039 (scan-error (setq at-opening-bracket t))))
10040 (when (looking-at js2-declaration-keyword-re)
10041 (goto-char (match-end 0))
10042 (1+ (current-column)))))))
10043
10044 (defun js2-ctrl-statement-indentation ()
10045 "Return the proper indentation of current line if it is a control statement.
10046 Returns an indentation if this line starts the body of a control
10047 statement without braces, else returns nil."
10048 (let (forward-sexp-function)
10049 (save-excursion
10050 (back-to-indentation)
10051 (when (and (not (js2-same-line (point-min)))
10052 (not (looking-at "{"))
10053 (js2-re-search-backward "[[:graph:]]" nil t)
10054 (not (looking-at "[{([]"))
10055 (progn
10056 (forward-char)
10057 (when (= (char-before) ?\))
10058 ;; scan-sexps sometimes throws an error
10059 (ignore-errors (backward-sexp))
10060 (skip-chars-backward " \t" (point-at-bol)))
10061 (let ((pt (point)))
10062 (back-to-indentation)
10063 (when (looking-at "}[ \t]*")
10064 (goto-char (match-end 0)))
10065 (and (looking-at js2-possibly-braceless-keywords-re)
10066 (= (match-end 0) pt)
10067 (not (js2-end-of-do-while-loop-p))))))
10068 (+ (current-indentation) js2-basic-offset)))))
10069
10070 (defun js2-indent-in-array-comp (parse-status)
10071 "Return non-nil if we think we're in an array comprehension.
10072 In particular, return the buffer position of the first `for' kwd."
10073 (let ((bracket (nth 1 parse-status))
10074 (end (point)))
10075 (when bracket
10076 (save-excursion
10077 (goto-char bracket)
10078 (when (looking-at "\\[")
10079 (forward-char 1)
10080 (js2-forward-sws)
10081 (if (looking-at "[[{]")
10082 (let (forward-sexp-function) ; use Lisp version
10083 (forward-sexp) ; skip destructuring form
10084 (js2-forward-sws)
10085 (if (and (/= (char-after) ?,) ; regular array
10086 (looking-at "for"))
10087 (match-beginning 0)))
10088 ;; to skip arbitrary expressions we need the parser,
10089 ;; so we'll just guess at it.
10090 (if (and (> end (point)) ; not empty literal
10091 (re-search-forward "[^,]]* \\(for\\) " end t)
10092 ;; not inside comment or string literal
10093 (let ((state (parse-partial-sexp bracket (point))))
10094 (not (or (nth 3 state) (nth 4 state)))))
10095 (match-beginning 1))))))))
10096
10097 (defun js2-array-comp-indentation (parse-status for-kwd)
10098 (if (js2-same-line for-kwd)
10099 ;; first continuation line
10100 (save-excursion
10101 (goto-char (nth 1 parse-status))
10102 (forward-char 1)
10103 (skip-chars-forward " \t")
10104 (current-column))
10105 (save-excursion
10106 (goto-char for-kwd)
10107 (current-column))))
10108
10109 (defun js2-proper-indentation (parse-status)
10110 "Return the proper indentation for the current line."
10111 (save-excursion
10112 (back-to-indentation)
10113 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10114 (at-closing-bracket (looking-at "[]})]"))
10115 (same-indent-p (or at-closing-bracket
10116 (looking-at "\\<case\\>[^:]")
10117 (and (looking-at "\\<default:")
10118 (save-excursion
10119 (js2-backward-sws)
10120 (not (memq (char-before) '(?, ?{)))))))
10121 (continued-expr-p (js2-continued-expression-p))
10122 (declaration-indent (and js2-pretty-multiline-declarations
10123 (js2-multiline-decl-indentation)))
10124 (bracket (nth 1 parse-status))
10125 beg indent)
10126 (cond
10127 ;; indent array comprehension continuation lines specially
10128 ((and bracket
10129 (>= js2-language-version 170)
10130 (not (js2-same-line bracket))
10131 (setq beg (js2-indent-in-array-comp parse-status))
10132 (>= (point) (save-excursion
10133 (goto-char beg)
10134 (point-at-bol)))) ; at or after first loop?
10135 (js2-array-comp-indentation parse-status beg))
10136
10137 (ctrl-stmt-indent)
10138
10139 ((and declaration-indent continued-expr-p)
10140 (+ declaration-indent js2-basic-offset))
10141
10142 (declaration-indent)
10143
10144 (bracket
10145 (goto-char bracket)
10146 (cond
10147 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10148 (when (save-excursion (skip-chars-backward " \t)")
10149 (looking-at ")"))
10150 (backward-list))
10151 (back-to-indentation)
10152 (and (eq js2-pretty-multiline-declarations 'all)
10153 (looking-at js2-declaration-keyword-re)
10154 (goto-char (1+ (match-end 0))))
10155 (setq indent
10156 (cond (same-indent-p
10157 (current-column))
10158 (continued-expr-p
10159 (+ (current-column) (* 2 js2-basic-offset)))
10160 (t
10161 (+ (current-column) js2-basic-offset))))
10162 (if (and js2-indent-switch-body
10163 (not at-closing-bracket)
10164 (looking-at "\\_<switch\\_>"))
10165 (+ indent js2-basic-offset)
10166 indent))
10167 (t
10168 (unless same-indent-p
10169 (forward-char)
10170 (skip-chars-forward " \t"))
10171 (current-column))))
10172
10173 (continued-expr-p js2-basic-offset)
10174
10175 (t 0)))))
10176
10177 (defun js2-lineup-comment (parse-status)
10178 "Indent a multi-line block comment continuation line."
10179 (let* ((beg (nth 8 parse-status))
10180 (first-line (js2-same-line beg))
10181 (offset (save-excursion
10182 (goto-char beg)
10183 (if (looking-at "/\\*")
10184 (+ 1 (current-column))
10185 0))))
10186 (unless first-line
10187 (indent-line-to offset))))
10188
10189 (defun js2-backward-sws ()
10190 "Move backward through whitespace and comments."
10191 (interactive)
10192 (while (forward-comment -1)))
10193
10194 (defun js2-forward-sws ()
10195 "Move forward through whitespace and comments."
10196 (interactive)
10197 (while (forward-comment 1)))
10198
10199 (defun js2-current-indent (&optional pos)
10200 "Return column of indentation on current line.
10201 If POS is non-nil, go to that point and return indentation for that line."
10202 (save-excursion
10203 (if pos
10204 (goto-char pos))
10205 (back-to-indentation)
10206 (current-column)))
10207
10208 (defun js2-arglist-close ()
10209 "Return non-nil if we're on a line beginning with a close-paren/brace."
10210 (save-excursion
10211 (goto-char (point-at-bol))
10212 (js2-forward-sws)
10213 (looking-at "[])}]")))
10214
10215 (defun js2-indent-looks-like-label-p ()
10216 (goto-char (point-at-bol))
10217 (js2-forward-sws)
10218 (looking-at (concat js2-mode-identifier-re ":")))
10219
10220 (defun js2-indent-in-objlit-p (parse-status)
10221 "Return non-nil if this looks like an object-literal entry."
10222 (let ((start (nth 1 parse-status)))
10223 (and
10224 start
10225 (save-excursion
10226 (and (zerop (forward-line -1))
10227 (not (< (point) start)) ; crossed a {} boundary
10228 (js2-indent-looks-like-label-p)))
10229 (save-excursion
10230 (js2-indent-looks-like-label-p)))))
10231
10232 ;; If prev line looks like foobar({ then we're passing an object
10233 ;; literal to a function call, and people pretty much always want to
10234 ;; de-dent back to the previous line, so move the 'basic-offset'
10235 ;; position to the front.
10236 (defun js2-indent-objlit-arg-p (parse-status)
10237 (save-excursion
10238 (back-to-indentation)
10239 (js2-backward-sws)
10240 (and (eq (1- (point)) (nth 1 parse-status))
10241 (eq (char-before) ?{)
10242 (progn
10243 (forward-char -1)
10244 (skip-chars-backward " \t")
10245 (eq (char-before) ?\()))))
10246
10247 (defun js2-indent-case-block-p ()
10248 (save-excursion
10249 (back-to-indentation)
10250 (js2-backward-sws)
10251 (goto-char (point-at-bol))
10252 (skip-chars-forward " \t")
10253 (looking-at "case\\s-.+:")))
10254
10255 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10256 "Cycle among alternate computed indentation positions.
10257 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10258 of the buffer to the current point. NORMAL-COL is the indentation
10259 column computed by the heuristic guesser based on current paren,
10260 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10261 in reverse."
10262 (let ((cur-indent (js2-current-indent))
10263 (old-buffer-undo-list buffer-undo-list)
10264 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10265 (current-line (save-excursion
10266 (forward-line 0) ; move to bol
10267 (1+ (count-lines (point-min) (point)))))
10268 positions pos main-pos anchor arglist-cont same-indent
10269 basic-offset computed-pos)
10270 ;; temporarily don't record undo info, if user requested this
10271 (when js2-mode-indent-inhibit-undo
10272 (setq buffer-undo-list t))
10273 (unwind-protect
10274 (progn
10275 ;; First likely point: indent from beginning of previous code line
10276 (push (setq basic-offset
10277 (+ (save-excursion
10278 (back-to-indentation)
10279 (js2-backward-sws)
10280 (back-to-indentation)
10281 (current-column))
10282 js2-basic-offset))
10283 positions)
10284
10285 ;; (First + epsilon) likely point: indent 2x from beginning of
10286 ;; previous code line. Google does it this way.
10287 (push (setq basic-offset
10288 (+ (save-excursion
10289 (back-to-indentation)
10290 (js2-backward-sws)
10291 (back-to-indentation)
10292 (current-column))
10293 (* 2 js2-basic-offset)))
10294 positions)
10295
10296 ;; Second likely point: indent from assign-expr RHS. This
10297 ;; is just a crude guess based on finding " = " on the previous
10298 ;; line containing actual code.
10299 (setq pos (save-excursion
10300 (forward-line -1)
10301 (goto-char (point-at-bol))
10302 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10303 (point-at-eol) t)
10304 (goto-char (match-end 1))
10305 (skip-chars-forward " \t\r\n")
10306 (current-column))))
10307 (when pos
10308 (incf pos js2-basic-offset)
10309 (push pos positions))
10310
10311 ;; Third likely point: same indent as previous line of code.
10312 ;; Make it the first likely point if we're not on an
10313 ;; arglist-close line and previous line ends in a comma, or
10314 ;; both this line and prev line look like object-literal
10315 ;; elements.
10316 (setq pos (save-excursion
10317 (goto-char (point-at-bol))
10318 (js2-backward-sws)
10319 (back-to-indentation)
10320 (prog1
10321 (current-column)
10322 ;; while we're here, look for trailing comma
10323 (if (save-excursion
10324 (goto-char (point-at-eol))
10325 (js2-backward-sws)
10326 (eq (char-before) ?,))
10327 (setq arglist-cont (1- (point)))))))
10328 (when pos
10329 (if (and (or arglist-cont
10330 (js2-indent-in-objlit-p parse-status))
10331 (not (js2-arglist-close)))
10332 (setq same-indent pos))
10333 (push pos positions))
10334
10335 ;; Fourth likely point: first preceding code with less indentation.
10336 ;; than the immediately preceding code line.
10337 (setq pos (save-excursion
10338 (back-to-indentation)
10339 (js2-backward-sws)
10340 (back-to-indentation)
10341 (setq anchor (current-column))
10342 (while (and (zerop (forward-line -1))
10343 (>= (progn
10344 (back-to-indentation)
10345 (current-column))
10346 anchor)))
10347 (setq pos (current-column))))
10348 (push pos positions)
10349
10350 ;; nesting-heuristic position, main by default
10351 (push (setq main-pos normal-col) positions)
10352
10353 ;; delete duplicates and sort positions list
10354 (setq positions (sort (delete-dups positions) '<))
10355
10356 ;; comma-list continuation lines: prev line indent takes precedence
10357 (if same-indent
10358 (setq main-pos same-indent))
10359
10360 ;; common special cases where we want to indent in from previous line
10361 (if (or (js2-indent-case-block-p)
10362 (js2-indent-objlit-arg-p parse-status))
10363 (setq main-pos basic-offset))
10364
10365 ;; if bouncing backwards, reverse positions list
10366 (if backwards
10367 (setq positions (reverse positions)))
10368
10369 ;; record whether we're already sitting on one of the alternatives
10370 (setq pos (member cur-indent positions))
10371
10372 (cond
10373 ;; case 0: we're one one of the alternatives and this is the
10374 ;; first time they've pressed TAB on this line (best-guess).
10375 ((and js2-mode-indent-ignore-first-tab
10376 pos
10377 ;; first time pressing TAB on this line?
10378 (not (eq js2-mode-last-indented-line current-line)))
10379 ;; do nothing
10380 (setq computed-pos nil))
10381 ;; case 1: only one computed position => use it
10382 ((null (cdr positions))
10383 (setq computed-pos 0))
10384 ;; case 2: not on any of the computed spots => use main spot
10385 ((not pos)
10386 (setq computed-pos (js2-position main-pos positions)))
10387 ;; case 3: on last position: cycle to first position
10388 ((null (cdr pos))
10389 (setq computed-pos 0))
10390 ;; case 4: on intermediate position: cycle to next position
10391 (t
10392 (setq computed-pos (js2-position (second pos) positions))))
10393
10394 ;; see if any hooks want to indent; otherwise we do it
10395 (loop with result = nil
10396 for hook in js2-indent-hook
10397 while (null result)
10398 do
10399 (setq result (funcall hook positions computed-pos))
10400 finally do
10401 (unless (or result (null computed-pos))
10402 (indent-line-to (nth computed-pos positions)))))
10403
10404 ;; finally
10405 (if js2-mode-indent-inhibit-undo
10406 (setq buffer-undo-list old-buffer-undo-list))
10407 ;; see commentary for `js2-mode-last-indented-line'
10408 (setq js2-mode-last-indented-line current-line))))
10409
10410 (defun js2-indent-bounce-backwards ()
10411 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10412 cycles between the computed indentation positions in reverse order."
10413 (interactive)
10414 (js2-indent-line t))
10415
10416 (defun js2-1-line-comment-continuation-p ()
10417 "Return t if we're in a 1-line comment continuation.
10418 If so, we don't ever want to use bounce-indent."
10419 (save-excursion
10420 (and (progn
10421 (forward-line 0)
10422 (looking-at "\\s-*//"))
10423 (progn
10424 (forward-line -1)
10425 (forward-line 0)
10426 (when (looking-at "\\s-*$")
10427 (js2-backward-sws)
10428 (forward-line 0))
10429 (looking-at "\\s-*//")))))
10430
10431 (defun js2-indent-line (&optional bounce-backwards)
10432 "Indent the current line as JavaScript source text."
10433 (interactive)
10434 (let (parse-status offset indent-col
10435 ;; Don't whine about errors/warnings when we're indenting.
10436 ;; This has to be set before calling parse-partial-sexp below.
10437 (inhibit-point-motion-hooks t))
10438 (setq parse-status (save-excursion
10439 (syntax-ppss (point-at-bol)))
10440 offset (- (point) (save-excursion
10441 (back-to-indentation)
10442 (point))))
10443 (js2-with-underscore-as-word-syntax
10444 (if (nth 4 parse-status)
10445 (js2-lineup-comment parse-status)
10446 (setq indent-col (js2-proper-indentation parse-status))
10447 ;; See comments below about `js2-mode-last-indented-line'.
10448 (cond
10449 ;; bounce-indenting is disabled during electric-key indent.
10450 ;; It doesn't work well on first line of buffer.
10451 ((and js2-bounce-indent-p
10452 (not (js2-same-line (point-min)))
10453 (not (js2-1-line-comment-continuation-p)))
10454 (js2-bounce-indent indent-col parse-status bounce-backwards))
10455 ;; just indent to the guesser's likely spot
10456 (t (indent-line-to indent-col))))
10457 (when (plusp offset)
10458 (forward-char offset)))))
10459
10460 (defun js2-indent-region (start end)
10461 "Indent the region, but don't use bounce indenting."
10462 (let ((js2-bounce-indent-p nil)
10463 (indent-region-function nil)
10464 (after-change-functions (remq 'js2-mode-edit
10465 after-change-functions)))
10466 (indent-region start end nil) ; nil for byte-compiler
10467 (js2-mode-edit start end (- end start))))
10468
10469 (defvar js2-minor-mode-map
10470 (let ((map (make-sparse-keymap)))
10471 (define-key map (kbd "C-c C-`") #'js2-next-error)
10472 (define-key map [mouse-1] #'js2-mode-show-node)
10473 map)
10474 "Keymap used when `js2-minor-mode' is active.")
10475
10476 ;;;###autoload
10477 (define-minor-mode js2-minor-mode
10478 "Minor mode for running js2 as a background linter.
10479 This allows you to use a different major mode for JavaScript editing,
10480 such as `js-mode', while retaining the asynchronous error/warning
10481 highlighting features of `js2-mode'."
10482 :group 'js2-mode
10483 :lighter " js-lint"
10484 (if js2-minor-mode
10485 (js2-minor-mode-enter)
10486 (js2-minor-mode-exit)))
10487
10488 (defun js2-minor-mode-enter ()
10489 "Initialization for `js2-minor-mode'."
10490 (set (make-local-variable 'max-lisp-eval-depth)
10491 (max max-lisp-eval-depth 3000))
10492 (setq next-error-function #'js2-next-error)
10493 (js2-set-default-externs)
10494 ;; Experiment: make reparse-delay longer for longer files.
10495 (if (plusp js2-dynamic-idle-timer-adjust)
10496 (setq js2-idle-timer-delay
10497 (* js2-idle-timer-delay
10498 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10499 (setq js2-mode-buffer-dirty-p t
10500 js2-mode-parsing nil)
10501 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10502 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10503 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10504 (when js2-include-jslint-globals
10505 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10506 (run-hooks 'js2-init-hook)
10507 (js2-reparse))
10508
10509 (defun js2-minor-mode-exit ()
10510 "Turn off `js2-minor-mode'."
10511 (setq next-error-function nil)
10512 (remove-hook 'after-change-functions #'js2-mode-edit t)
10513 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10514 (when js2-mode-node-overlay
10515 (delete-overlay js2-mode-node-overlay)
10516 (setq js2-mode-node-overlay nil))
10517 (js2-remove-overlays)
10518 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10519 (setq js2-mode-ast nil))
10520
10521 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10522 (make-variable-buffer-local 'js2-source-buffer)
10523
10524 (defun* js2-display-error-list ()
10525 "Display a navigable buffer listing parse errors/warnings."
10526 (interactive)
10527 (unless (js2-have-errors-p)
10528 (message "No errors")
10529 (return-from js2-display-error-list))
10530 (labels ((annotate-list
10531 (lst type)
10532 "Add diagnostic TYPE and line number to errs list"
10533 (mapcar (lambda (err)
10534 (list err type (line-number-at-pos (nth 1 err))))
10535 lst)))
10536 (let* ((srcbuf (current-buffer))
10537 (errbuf (get-buffer-create "*js-lint*"))
10538 (errors (annotate-list
10539 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10540 'js2-error)) ; must be a valid face name
10541 (warnings (annotate-list
10542 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10543 'js2-warning)) ; must be a valid face name
10544 (all-errs (sort (append errors warnings)
10545 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10546 (with-current-buffer errbuf
10547 (let ((inhibit-read-only t))
10548 (erase-buffer)
10549 (dolist (err all-errs)
10550 (destructuring-bind ((msg-key beg _end &rest) type line) err
10551 (insert-text-button
10552 (format "line %d: %s" line (js2-get-msg msg-key))
10553 'face type
10554 'follow-link "\C-m"
10555 'action 'js2-error-buffer-jump
10556 'js2-msg (js2-get-msg msg-key)
10557 'js2-pos beg)
10558 (insert "\n"))))
10559 (js2-error-buffer-mode)
10560 (setq js2-source-buffer srcbuf)
10561 (pop-to-buffer errbuf)
10562 (goto-char (point-min))
10563 (unless (eobp)
10564 (js2-error-buffer-view))))))
10565
10566 (defvar js2-error-buffer-mode-map
10567 (let ((map (make-sparse-keymap)))
10568 (define-key map "n" #'js2-error-buffer-next)
10569 (define-key map "p" #'js2-error-buffer-prev)
10570 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10571 (define-key map "o" #'js2-error-buffer-view)
10572 (define-key map "q" #'js2-error-buffer-quit)
10573 map)
10574 "Keymap used for js2 diagnostics buffers.")
10575
10576 (defun js2-error-buffer-mode ()
10577 "Major mode for js2 diagnostics buffers.
10578 Selecting an error will jump it to the corresponding source-buffer error.
10579 \\{js2-error-buffer-mode-map}"
10580 (interactive)
10581 (setq major-mode 'js2-error-buffer-mode
10582 mode-name "JS Lint Diagnostics")
10583 (use-local-map js2-error-buffer-mode-map)
10584 (setq truncate-lines t)
10585 (set-buffer-modified-p nil)
10586 (setq buffer-read-only t)
10587 (run-hooks 'js2-error-buffer-mode-hook))
10588
10589 (defun js2-error-buffer-next ()
10590 "Move to next error and view it."
10591 (interactive)
10592 (when (zerop (forward-line 1))
10593 (js2-error-buffer-view)))
10594
10595 (defun js2-error-buffer-prev ()
10596 "Move to previous error and view it."
10597 (interactive)
10598 (when (zerop (forward-line -1))
10599 (js2-error-buffer-view)))
10600
10601 (defun js2-error-buffer-quit ()
10602 "Kill the current buffer."
10603 (interactive)
10604 (kill-buffer))
10605
10606 (defun js2-error-buffer-jump (&rest ignored)
10607 "Jump cursor to current error in source buffer."
10608 (interactive)
10609 (when (js2-error-buffer-view)
10610 (pop-to-buffer js2-source-buffer)))
10611
10612 (defun js2-error-buffer-view ()
10613 "Scroll source buffer to show error at current line."
10614 (interactive)
10615 (cond
10616 ((not (eq major-mode 'js2-error-buffer-mode))
10617 (message "Not in a js2 errors buffer"))
10618 ((not (buffer-live-p js2-source-buffer))
10619 (message "Source buffer has been killed"))
10620 ((not (wholenump (get-text-property (point) 'js2-pos)))
10621 (message "There does not seem to be an error here"))
10622 (t
10623 (let ((pos (get-text-property (point) 'js2-pos))
10624 (msg (get-text-property (point) 'js2-msg)))
10625 (save-selected-window
10626 (pop-to-buffer js2-source-buffer)
10627 (goto-char pos)
10628 (message msg))))))
10629
10630 ;;;###autoload
10631 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10632 ;; FIXME: Should derive from js-mode.
10633 "Major mode for editing JavaScript code."
10634 ;; Used by comment-region; don't change it.
10635 (set (make-local-variable 'comment-start) "//")
10636 (set (make-local-variable 'comment-end) "")
10637 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10638 (set (make-local-variable 'max-lisp-eval-depth)
10639 (max max-lisp-eval-depth 3000))
10640 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10641 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10642 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10643 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10644 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10645 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10646 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10647 ;; for characters inside regexp literals.
10648 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10649 ;; this is necessary to make `show-paren-function' work properly
10650 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10651 ;; needed for M-x rgrep, among other things
10652 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10653
10654 (set (make-local-variable 'electric-indent-chars)
10655 (append "{}()[]:;,*." electric-indent-chars))
10656 (set (make-local-variable 'electric-layout-rules)
10657 '((?\; . after) (?\{ . after) (?\} . before)))
10658
10659 ;; some variables needed by cc-engine for paragraph-fill, etc.
10660 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10661 c-comment-start-regexp "/[*/]\\|\\s|"
10662 c-line-comment-starter "//"
10663 c-paragraph-start js2-paragraph-start
10664 c-paragraph-separate "$"
10665 c-syntactic-ws-start js2-syntactic-ws-start
10666 c-syntactic-ws-end js2-syntactic-ws-end
10667 c-syntactic-eol js2-syntactic-eol)
10668
10669 (let ((c-buffer-is-cc-mode t))
10670 ;; Copied from `js-mode'. Also see Bug#6071.
10671 (make-local-variable 'paragraph-start)
10672 (make-local-variable 'paragraph-separate)
10673 (make-local-variable 'paragraph-ignore-fill-prefix)
10674 (make-local-variable 'adaptive-fill-mode)
10675 (make-local-variable 'adaptive-fill-regexp)
10676 (c-setup-paragraph-variables))
10677
10678 (setq font-lock-defaults '(nil t))
10679
10680 ;; Experiment: make reparse-delay longer for longer files.
10681 (when (plusp js2-dynamic-idle-timer-adjust)
10682 (setq js2-idle-timer-delay
10683 (* js2-idle-timer-delay
10684 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10685
10686 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10687 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10688 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10689 (setq next-error-function #'js2-next-error)
10690 (imenu-add-to-menubar (concat "IM-" mode-name))
10691 (add-to-invisibility-spec '(js2-outline . t))
10692 (set (make-local-variable 'line-move-ignore-invisible) t)
10693 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10694
10695 (setq js2-mode-functions-hidden nil
10696 js2-mode-comments-hidden nil
10697 js2-mode-buffer-dirty-p t
10698 js2-mode-parsing nil)
10699
10700 (js2-set-default-externs)
10701
10702 (when js2-include-jslint-globals
10703 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10704
10705 (run-hooks 'js2-init-hook)
10706
10707 (js2-reparse))
10708
10709 (defun js2-mode-exit ()
10710 "Exit `js2-mode' and clean up."
10711 (interactive)
10712 (when js2-mode-node-overlay
10713 (delete-overlay js2-mode-node-overlay)
10714 (setq js2-mode-node-overlay nil))
10715 (js2-remove-overlays)
10716 (setq js2-mode-ast nil)
10717 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10718 (remove-from-invisibility-spec '(js2-outline . t))
10719 (js2-mode-show-all)
10720 (with-silent-modifications
10721 (js2-clear-face (point-min) (point-max))))
10722
10723 (defun js2-mode-reset-timer ()
10724 "Cancel any existing parse timer and schedule a new one."
10725 (if js2-mode-parse-timer
10726 (cancel-timer js2-mode-parse-timer))
10727 (setq js2-mode-parsing nil)
10728 (let ((timer (timer-create)))
10729 (setq js2-mode-parse-timer timer)
10730 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10731 (timer-set-idle-time timer js2-idle-timer-delay)
10732 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10733 (timer-activate-when-idle timer nil)))
10734
10735 (defun js2-mode-idle-reparse (buffer)
10736 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10737 it to be reparsed when the buffer is selected."
10738 (cond ((eq buffer (current-buffer))
10739 (js2-reparse))
10740 ((buffer-live-p buffer)
10741 ;; reparse when the buffer is selected again
10742 (with-current-buffer buffer
10743 (add-hook 'window-configuration-change-hook
10744 #'js2-mode-idle-reparse-inner
10745 nil t)))))
10746
10747 (defun js2-mode-idle-reparse-inner ()
10748 (remove-hook 'window-configuration-change-hook
10749 #'js2-mode-idle-reparse-inner
10750 t)
10751 (js2-reparse))
10752
10753 (defun js2-mode-edit (_beg _end _len)
10754 "Schedule a new parse after buffer is edited.
10755 Buffer edit spans from BEG to END and is of length LEN."
10756 (setq js2-mode-buffer-dirty-p t)
10757 (js2-mode-hide-overlay)
10758 (js2-mode-reset-timer))
10759
10760 (defun js2-minor-mode-edit (_beg _end _len)
10761 "Callback for buffer edits in `js2-mode'.
10762 Schedules a new parse after buffer is edited.
10763 Buffer edit spans from BEG to END and is of length LEN."
10764 (setq js2-mode-buffer-dirty-p t)
10765 (js2-mode-hide-overlay)
10766 (js2-mode-reset-timer))
10767
10768 (defun js2-reparse (&optional force)
10769 "Re-parse current buffer after user finishes some data entry.
10770 If we get any user input while parsing, including cursor motion,
10771 we discard the parse and reschedule it. If FORCE is nil, then the
10772 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10773 (let (time
10774 interrupted-p
10775 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10776 (unless js2-mode-parsing
10777 (setq js2-mode-parsing t)
10778 (unwind-protect
10779 (when (or js2-mode-buffer-dirty-p force)
10780 (js2-remove-overlays)
10781 (with-silent-modifications
10782 (setq js2-mode-buffer-dirty-p nil
10783 js2-mode-fontifications nil
10784 js2-mode-deferred-properties nil)
10785 (if js2-mode-verbose-parse-p
10786 (message "parsing..."))
10787 (setq time
10788 (js2-time
10789 (setq interrupted-p
10790 (catch 'interrupted
10791 (js2-parse)
10792 ;; if parsing is interrupted, comments and regex
10793 ;; literals stay ignored by `parse-partial-sexp'
10794 (remove-text-properties (point-min) (point-max)
10795 '(syntax-table))
10796 (js2-mode-apply-deferred-properties)
10797 (js2-mode-remove-suppressed-warnings)
10798 (js2-mode-show-warnings)
10799 (js2-mode-show-errors)
10800 (if (>= js2-highlight-level 1)
10801 (js2-highlight-jsdoc js2-mode-ast))
10802 nil))))
10803 (if interrupted-p
10804 (progn
10805 ;; unfinished parse => try again
10806 (setq js2-mode-buffer-dirty-p t)
10807 (js2-mode-reset-timer))
10808 (if js2-mode-verbose-parse-p
10809 (message "Parse time: %s" time)))))
10810 (setq js2-mode-parsing nil)
10811 (unless interrupted-p
10812 (setq js2-mode-parse-timer nil))))))
10813
10814 (defun js2-mode-show-node (event)
10815 "Debugging aid: highlight selected AST node on mouse click."
10816 (interactive "e")
10817 (mouse-set-point event)
10818 (setq deactivate-mark t)
10819 (when js2-mode-show-overlay
10820 (let ((node (js2-node-at-point))
10821 beg end)
10822 (if (null node)
10823 (message "No node found at location %s" (point))
10824 (setq beg (js2-node-abs-pos node)
10825 end (+ beg (js2-node-len node)))
10826 (if js2-mode-node-overlay
10827 (move-overlay js2-mode-node-overlay beg end)
10828 (setq js2-mode-node-overlay (make-overlay beg end))
10829 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10830 (with-silent-modifications
10831 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10832 (message "%s, parent: %s"
10833 (js2-node-short-name node)
10834 (if (js2-node-parent node)
10835 (js2-node-short-name (js2-node-parent node))
10836 "nil"))))))
10837
10838 (defun js2-mode-hide-overlay (&optional _p1 p2)
10839 "Remove the debugging overlay when the point moves.
10840 P1 and P2 are the old and new values of point, respectively."
10841 (when js2-mode-node-overlay
10842 (let ((beg (overlay-start js2-mode-node-overlay))
10843 (end (overlay-end js2-mode-node-overlay)))
10844 ;; Sometimes we're called spuriously.
10845 (unless (and p2
10846 (>= p2 beg)
10847 (<= p2 end))
10848 (with-silent-modifications
10849 (remove-text-properties beg end '(point-left nil)))
10850 (delete-overlay js2-mode-node-overlay)
10851 (setq js2-mode-node-overlay nil)))))
10852
10853 (defun js2-mode-reset ()
10854 "Debugging helper: reset everything."
10855 (interactive)
10856 (js2-mode-exit)
10857 (js2-mode))
10858
10859 (defun js2-mode-show-warn-or-err (e face)
10860 "Highlight a warning or error E with FACE.
10861 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10862 The last element is optional. When present, use instead of FACE."
10863 (let* ((key (first e))
10864 (beg (second e))
10865 (end (+ beg (third e)))
10866 ;; Don't inadvertently go out of bounds.
10867 (beg (max (point-min) (min beg (point-max))))
10868 (end (max (point-min) (min end (point-max))))
10869 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10870 (ovl (make-overlay beg end)))
10871 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10872 (overlay-put ovl 'js2-error t)
10873 (put-text-property beg end 'help-echo (js2-get-msg key))
10874 (put-text-property beg end 'point-entered #'js2-echo-error)))
10875
10876 (defun js2-remove-overlays ()
10877 "Remove overlays from buffer that have a `js2-error' property."
10878 (let ((beg (point-min))
10879 (end (point-max)))
10880 (save-excursion
10881 (dolist (o (overlays-in beg end))
10882 (when (overlay-get o 'js2-error)
10883 (delete-overlay o))))))
10884
10885 (defun js2-error-at-point (&optional pos)
10886 "Return non-nil if there's an error overlay at POS.
10887 Defaults to point."
10888 (loop with pos = (or pos (point))
10889 for o in (overlays-at pos)
10890 thereis (overlay-get o 'js2-error)))
10891
10892 (defun js2-mode-apply-deferred-properties ()
10893 "Apply fontifications and other text properties recorded during parsing."
10894 (when (plusp js2-highlight-level)
10895 ;; We defer clearing faces as long as possible to eliminate flashing.
10896 (js2-clear-face (point-min) (point-max))
10897 ;; Have to reverse the recorded fontifications list so that errors
10898 ;; and warnings overwrite the normal fontifications.
10899 (dolist (f (nreverse js2-mode-fontifications))
10900 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10901 (setq js2-mode-fontifications nil))
10902 (dolist (p js2-mode-deferred-properties)
10903 (apply #'put-text-property p))
10904 (setq js2-mode-deferred-properties nil))
10905
10906 (defun js2-mode-show-errors ()
10907 "Highlight syntax errors."
10908 (when js2-mode-show-parse-errors
10909 (dolist (e (js2-ast-root-errors js2-mode-ast))
10910 (js2-mode-show-warn-or-err e 'js2-error))))
10911
10912 (defun js2-mode-remove-suppressed-warnings ()
10913 "Take suppressed warnings out of the AST warnings list.
10914 This ensures that the counts and `next-error' are correct."
10915 (setf (js2-ast-root-warnings js2-mode-ast)
10916 (js2-delete-if
10917 (lambda (e)
10918 (let ((key (caar e)))
10919 (or
10920 (and (not js2-strict-trailing-comma-warning)
10921 (string-match "trailing\\.comma" key))
10922 (and (not js2-strict-cond-assign-warning)
10923 (string= key "msg.equal.as.assign"))
10924 (and js2-missing-semi-one-line-override
10925 (string= key "msg.missing.semi")
10926 (let* ((beg (second e))
10927 (node (js2-node-at-point beg))
10928 (fn (js2-mode-find-parent-fn node))
10929 (body (and fn (js2-function-node-body fn)))
10930 (lc (and body (js2-node-abs-pos body)))
10931 (rc (and lc (+ lc (js2-node-len body)))))
10932 (and fn
10933 (or (null body)
10934 (save-excursion
10935 (goto-char beg)
10936 (and (js2-same-line lc)
10937 (js2-same-line rc))))))))))
10938 (js2-ast-root-warnings js2-mode-ast))))
10939
10940 (defun js2-mode-show-warnings ()
10941 "Highlight strict-mode warnings."
10942 (when js2-mode-show-strict-warnings
10943 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10944 (js2-mode-show-warn-or-err e 'js2-warning))))
10945
10946 (defun js2-echo-error (_old-point new-point)
10947 "Called by point-motion hooks."
10948 (let ((msg (get-text-property new-point 'help-echo)))
10949 (when (and (stringp msg)
10950 (not (active-minibuffer-window))
10951 (not (current-message)))
10952 (message msg))))
10953
10954 (defalias 'js2-echo-help #'js2-echo-error)
10955
10956 (defun js2-line-break (&optional _soft)
10957 "Break line at point and indent, continuing comment if within one.
10958 If inside a string, and `js2-concat-multiline-strings' is not
10959 nil, turn it into concatenation."
10960 (interactive)
10961 (let ((parse-status (syntax-ppss)))
10962 (cond
10963 ;; Check if we're inside a string.
10964 ((nth 3 parse-status)
10965 (if js2-concat-multiline-strings
10966 (js2-mode-split-string parse-status)
10967 (insert "\n")))
10968 ;; Check if inside a block comment.
10969 ((nth 4 parse-status)
10970 (js2-mode-extend-comment (nth 8 parse-status)))
10971 (t
10972 (newline-and-indent)))))
10973
10974 (defun js2-mode-split-string (parse-status)
10975 "Turn a newline in mid-string into a string concatenation.
10976 PARSE-STATUS is as documented in `parse-partial-sexp'."
10977 (let* ((quote-char (nth 3 parse-status))
10978 (at-eol (eq js2-concat-multiline-strings 'eol)))
10979 (insert quote-char)
10980 (insert (if at-eol " +\n" "\n"))
10981 (unless at-eol
10982 (insert "+ "))
10983 (js2-indent-line)
10984 (insert quote-char)
10985 (when (eolp)
10986 (insert quote-char)
10987 (backward-char 1))))
10988
10989 (defun js2-mode-extend-comment (start-pos)
10990 "Indent the line and, when inside a comment block, add comment prefix."
10991 (let (star single col first-line needs-close)
10992 (save-excursion
10993 (back-to-indentation)
10994 (when (< (point) start-pos)
10995 (goto-char start-pos))
10996 (cond
10997 ((looking-at "\\*[^/]")
10998 (setq star t
10999 col (current-column)))
11000 ((looking-at "/\\*")
11001 (setq star t
11002 first-line t
11003 col (1+ (current-column))))
11004 ((looking-at "//")
11005 (setq single t
11006 col (current-column)))))
11007 ;; Heuristic for whether we need to close the comment:
11008 ;; if we've got a parse error here, assume it's an unterminated
11009 ;; comment.
11010 (setq needs-close
11011 (or
11012 (eq (get-text-property (1- (point)) 'point-entered)
11013 'js2-echo-error)
11014 ;; The heuristic above doesn't work well when we're
11015 ;; creating a comment and there's another one downstream,
11016 ;; as our parser thinks this one ends at the end of the
11017 ;; next one. (You can have a /* inside a js block comment.)
11018 ;; So just close it if the next non-ws char isn't a *.
11019 (and first-line
11020 (eolp)
11021 (save-excursion
11022 (skip-chars-forward " \t\r\n")
11023 (not (eq (char-after) ?*))))))
11024 (delete-horizontal-space)
11025 (insert "\n")
11026 (cond
11027 (star
11028 (indent-to col)
11029 (insert "* ")
11030 (if (and first-line needs-close)
11031 (save-excursion
11032 (insert "\n")
11033 (indent-to col)
11034 (insert "*/"))))
11035 ((and single
11036 (save-excursion
11037 (and (zerop (forward-line 1))
11038 (looking-at "\\s-*//"))))
11039 (indent-to col)
11040 (insert "// ")))
11041 ;; Don't need to extend the comment after all.
11042 (js2-indent-line)))
11043
11044 (defun js2-beginning-of-line ()
11045 "Toggle point between bol and first non-whitespace char in line.
11046 Also moves past comment delimiters when inside comments."
11047 (interactive)
11048 (let (node)
11049 (cond
11050 ((bolp)
11051 (back-to-indentation))
11052 ((looking-at "//")
11053 (skip-chars-forward "/ \t"))
11054 ((and (eq (char-after) ?*)
11055 (setq node (js2-comment-at-point))
11056 (memq (js2-comment-node-format node) '(jsdoc block))
11057 (save-excursion
11058 (skip-chars-backward " \t")
11059 (bolp)))
11060 (skip-chars-forward "\* \t"))
11061 (t
11062 (goto-char (point-at-bol))))))
11063
11064 (defun js2-end-of-line ()
11065 "Toggle point between eol and last non-whitespace char in line."
11066 (interactive)
11067 (if (eolp)
11068 (skip-chars-backward " \t")
11069 (goto-char (point-at-eol))))
11070
11071 (defun js2-mode-wait-for-parse (callback)
11072 "Invoke CALLBACK when parsing is finished.
11073 If parsing is already finished, calls CALLBACK immediately."
11074 (if (not js2-mode-buffer-dirty-p)
11075 (funcall callback)
11076 (push callback js2-mode-pending-parse-callbacks)
11077 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11078
11079 (defun js2-mode-parse-finished ()
11080 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11081 ;; We can't let errors propagate up, since it prevents the
11082 ;; `js2-parse' method from completing normally and returning
11083 ;; the ast, which makes things mysteriously not work right.
11084 (unwind-protect
11085 (dolist (cb js2-mode-pending-parse-callbacks)
11086 (condition-case err
11087 (funcall cb)
11088 (error (message "%s" err))))
11089 (setq js2-mode-pending-parse-callbacks nil)))
11090
11091 (defun js2-mode-flag-region (from to flag)
11092 "Hide or show text from FROM to TO, according to FLAG.
11093 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11094 Returns the created overlay if FLAG is non-nil."
11095 (remove-overlays from to 'invisible 'js2-outline)
11096 (when flag
11097 (let ((o (make-overlay from to)))
11098 (overlay-put o 'invisible 'js2-outline)
11099 (overlay-put o 'isearch-open-invisible
11100 'js2-isearch-open-invisible)
11101 o)))
11102
11103 ;; Function to be set as an outline-isearch-open-invisible' property
11104 ;; to the overlay that makes the outline invisible (see
11105 ;; `js2-mode-flag-region').
11106 (defun js2-isearch-open-invisible (_overlay)
11107 ;; We rely on the fact that isearch places point on the matched text.
11108 (js2-mode-show-element))
11109
11110 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11111 "Return cons cell of bounds of folding overlay at POS.
11112 Returns nil if not found."
11113 (let ((overlays (overlays-at (or pos (point))))
11114 o)
11115 (while (and overlays
11116 (not o))
11117 (if (overlay-get (car overlays) 'invisible)
11118 (setq o (car overlays))
11119 (setq overlays (cdr overlays))))
11120 (if o
11121 (cons (overlay-start o) (overlay-end o)))))
11122
11123 (defun js2-mode-function-at-point (&optional pos)
11124 "Return the innermost function node enclosing current point.
11125 Returns nil if point is not in a function."
11126 (let ((node (js2-node-at-point pos)))
11127 (while (and node (not (js2-function-node-p node)))
11128 (setq node (js2-node-parent node)))
11129 (if (js2-function-node-p node)
11130 node)))
11131
11132 (defun js2-mode-toggle-element ()
11133 "Hide or show the foldable element at the point."
11134 (interactive)
11135 (let (comment fn pos)
11136 (save-excursion
11137 (cond
11138 ;; /* ... */ comment?
11139 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11140 (if (js2-mode-invisible-overlay-bounds
11141 (setq pos (+ 3 (js2-node-abs-pos comment))))
11142 (progn
11143 (goto-char pos)
11144 (js2-mode-show-element))
11145 (js2-mode-hide-element)))
11146 ;; //-comment?
11147 ((save-excursion
11148 (back-to-indentation)
11149 (looking-at js2-mode-//-comment-re))
11150 (js2-mode-toggle-//-comment))
11151 ;; function?
11152 ((setq fn (js2-mode-function-at-point))
11153 (setq pos (and (js2-function-node-body fn)
11154 (js2-node-abs-pos (js2-function-node-body fn))))
11155 (goto-char (1+ pos))
11156 (if (js2-mode-invisible-overlay-bounds)
11157 (js2-mode-show-element)
11158 (js2-mode-hide-element)))
11159 (t
11160 (message "Nothing at point to hide or show"))))))
11161
11162 (defun js2-mode-hide-element ()
11163 "Fold/hide contents of a block, showing ellipses.
11164 Show the hidden text with \\[js2-mode-show-element]."
11165 (interactive)
11166 (if js2-mode-buffer-dirty-p
11167 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11168 (let (node body beg end)
11169 (cond
11170 ((js2-mode-invisible-overlay-bounds)
11171 (message "already hidden"))
11172 (t
11173 (setq node (js2-node-at-point))
11174 (cond
11175 ((js2-block-comment-p node)
11176 (js2-mode-hide-comment node))
11177 (t
11178 (while (and node (not (js2-function-node-p node)))
11179 (setq node (js2-node-parent node)))
11180 (if (and node
11181 (setq body (js2-function-node-body node)))
11182 (progn
11183 (setq beg (js2-node-abs-pos body)
11184 end (+ beg (js2-node-len body)))
11185 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11186 (message "No collapsable element found at point"))))))))
11187
11188 (defun js2-mode-show-element ()
11189 "Show the hidden element at current point."
11190 (interactive)
11191 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11192 (if bounds
11193 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11194 (message "Nothing to un-hide"))))
11195
11196 (defun js2-mode-show-all ()
11197 "Show all of the text in the buffer."
11198 (interactive)
11199 (js2-mode-flag-region (point-min) (point-max) nil))
11200
11201 (defun js2-mode-toggle-hide-functions ()
11202 (interactive)
11203 (if js2-mode-functions-hidden
11204 (js2-mode-show-functions)
11205 (js2-mode-hide-functions)))
11206
11207 (defun js2-mode-hide-functions ()
11208 "Hides all non-nested function bodies in the buffer.
11209 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11210 to open an individual entry."
11211 (interactive)
11212 (if js2-mode-buffer-dirty-p
11213 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11214 (if (null js2-mode-ast)
11215 (message "Oops - parsing failed")
11216 (setq js2-mode-functions-hidden t)
11217 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11218
11219 (defun js2-mode-function-hider (n endp)
11220 (when (not endp)
11221 (let ((tt (js2-node-type n))
11222 body beg end)
11223 (cond
11224 ((and (= tt js2-FUNCTION)
11225 (setq body (js2-function-node-body n)))
11226 (setq beg (js2-node-abs-pos body)
11227 end (+ beg (js2-node-len body)))
11228 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11229 nil) ; don't process children of function
11230 (t
11231 t))))) ; keep processing other AST nodes
11232
11233 (defun js2-mode-show-functions ()
11234 "Un-hide any folded function bodies in the buffer."
11235 (interactive)
11236 (setq js2-mode-functions-hidden nil)
11237 (save-excursion
11238 (goto-char (point-min))
11239 (while (/= (goto-char (next-overlay-change (point)))
11240 (point-max))
11241 (dolist (o (overlays-at (point)))
11242 (when (and (overlay-get o 'invisible)
11243 (not (overlay-get o 'comment)))
11244 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11245
11246 (defun js2-mode-hide-comment (n)
11247 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11248 3 ; /**
11249 2)) ; /*
11250 (beg (+ (js2-node-abs-pos n) head))
11251 (end (- (+ beg (js2-node-len n)) head 2))
11252 (o (js2-mode-flag-region beg end 'hide)))
11253 (overlay-put o 'comment t)))
11254
11255 (defun js2-mode-toggle-hide-comments ()
11256 "Folds all block comments in the buffer.
11257 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11258 to open an individual entry."
11259 (interactive)
11260 (if js2-mode-comments-hidden
11261 (js2-mode-show-comments)
11262 (js2-mode-hide-comments)))
11263
11264 (defun js2-mode-hide-comments ()
11265 (interactive)
11266 (if js2-mode-buffer-dirty-p
11267 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11268 (if (null js2-mode-ast)
11269 (message "Oops - parsing failed")
11270 (setq js2-mode-comments-hidden t)
11271 (dolist (n (js2-ast-root-comments js2-mode-ast))
11272 (when (js2-block-comment-p n)
11273 (js2-mode-hide-comment n)))
11274 (js2-mode-hide-//-comments)))
11275
11276 (defun js2-mode-extend-//-comment (direction)
11277 "Find start or end of a block of similar //-comment lines.
11278 DIRECTION is -1 to look back, 1 to look forward.
11279 INDENT is the indentation level to match.
11280 Returns the end-of-line position of the furthest adjacent
11281 //-comment line with the same indentation as the current line.
11282 If there is no such matching line, returns current end of line."
11283 (let ((pos (point-at-eol))
11284 (indent (current-indentation)))
11285 (save-excursion
11286 (while (and (zerop (forward-line direction))
11287 (looking-at js2-mode-//-comment-re)
11288 (eq indent (length (match-string 1))))
11289 (setq pos (point-at-eol))
11290 pos))))
11291
11292 (defun js2-mode-hide-//-comments ()
11293 "Fold adjacent 1-line comments, showing only snippet of first one."
11294 (let (beg end)
11295 (save-excursion
11296 (goto-char (point-min))
11297 (while (re-search-forward js2-mode-//-comment-re nil t)
11298 (setq beg (point)
11299 end (js2-mode-extend-//-comment 1))
11300 (unless (eq beg end)
11301 (overlay-put (js2-mode-flag-region beg end 'hide)
11302 'comment t))
11303 (goto-char end)
11304 (forward-char 1)))))
11305
11306 (defun js2-mode-toggle-//-comment ()
11307 "Fold or un-fold any multi-line //-comment at point.
11308 Caller should have determined that this line starts with a //-comment."
11309 (let* ((beg (point-at-eol))
11310 (end beg))
11311 (save-excursion
11312 (goto-char end)
11313 (if (js2-mode-invisible-overlay-bounds)
11314 (js2-mode-show-element)
11315 ;; else hide the comment
11316 (setq beg (js2-mode-extend-//-comment -1)
11317 end (js2-mode-extend-//-comment 1))
11318 (unless (eq beg end)
11319 (overlay-put (js2-mode-flag-region beg end 'hide)
11320 'comment t))))))
11321
11322 (defun js2-mode-show-comments ()
11323 "Un-hide any hidden comments, leaving other hidden elements alone."
11324 (interactive)
11325 (setq js2-mode-comments-hidden nil)
11326 (save-excursion
11327 (goto-char (point-min))
11328 (while (/= (goto-char (next-overlay-change (point)))
11329 (point-max))
11330 (dolist (o (overlays-at (point)))
11331 (when (overlay-get o 'comment)
11332 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11333
11334 (defun js2-mode-display-warnings-and-errors ()
11335 "Turn on display of warnings and errors."
11336 (interactive)
11337 (setq js2-mode-show-parse-errors t
11338 js2-mode-show-strict-warnings t)
11339 (js2-reparse 'force))
11340
11341 (defun js2-mode-hide-warnings-and-errors ()
11342 "Turn off display of warnings and errors."
11343 (interactive)
11344 (setq js2-mode-show-parse-errors nil
11345 js2-mode-show-strict-warnings nil)
11346 (js2-reparse 'force))
11347
11348 (defun js2-mode-toggle-warnings-and-errors ()
11349 "Toggle the display of warnings and errors.
11350 Some users don't like having warnings/errors reported while they type."
11351 (interactive)
11352 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11353 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11354 (if (called-interactively-p 'any)
11355 (message "warnings and errors %s"
11356 (if js2-mode-show-parse-errors
11357 "enabled"
11358 "disabled")))
11359 (js2-reparse 'force))
11360
11361 (defun js2-mode-customize ()
11362 (interactive)
11363 (customize-group 'js2-mode))
11364
11365 (defun js2-mode-forward-sexp (&optional arg)
11366 "Move forward across one statement or balanced expression.
11367 With ARG, do it that many times. Negative arg -N means
11368 move backward across N balanced expressions."
11369 (interactive "p")
11370 (setq arg (or arg 1))
11371 (save-restriction
11372 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11373 (js2-reparse)
11374 (let (forward-sexp-function
11375 node (start (point)) pos lp rp child)
11376 (cond
11377 ;; backward-sexp
11378 ;; could probably make this better for some cases:
11379 ;; - if in statement block (e.g. function body), go to parent
11380 ;; - infix exprs like (foo in bar) - maybe go to beginning
11381 ;; of infix expr if in the right-side expression?
11382 ((and arg (minusp arg))
11383 (dotimes (_ (- arg))
11384 (js2-backward-sws)
11385 (forward-char -1) ; Enter the node we backed up to.
11386 (when (setq node (js2-node-at-point (point) t))
11387 (setq pos (js2-node-abs-pos node))
11388 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11389 (setq lp (car parens)
11390 rp (cdr parens)))
11391 (when (and lp (> start lp))
11392 (if (and rp (<= start rp))
11393 ;; Between parens, check if there's a child node we can jump.
11394 (when (setq child (js2-node-closest-child node (point) lp t))
11395 (setq pos (js2-node-abs-pos child)))
11396 ;; Before both parens.
11397 (setq pos lp)))
11398 (let ((state (parse-partial-sexp start pos)))
11399 (goto-char (if (not (zerop (car state)))
11400 ;; Stumble at the unbalanced paren if < 0, or
11401 ;; jump a bit further if > 0.
11402 (scan-sexps start -1)
11403 pos))))
11404 (unless pos (goto-char (point-min)))))
11405 (t
11406 ;; forward-sexp
11407 (dotimes (_ arg)
11408 (js2-forward-sws)
11409 (when (setq node (js2-node-at-point (point) t))
11410 (setq pos (js2-node-abs-pos node))
11411 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11412 (setq lp (car parens)
11413 rp (cdr parens)))
11414 (or
11415 (when (and rp (<= start rp))
11416 (if (> start lp)
11417 (when (setq child (js2-node-closest-child node (point) rp))
11418 (setq pos (js2-node-abs-end child)))
11419 (setq pos (1+ rp))))
11420 ;; No parens or child nodes, looks for the end of the curren node.
11421 (incf pos (js2-node-len
11422 (if (js2-expr-stmt-node-p (js2-node-parent node))
11423 ;; Stop after the semicolon.
11424 (js2-node-parent node)
11425 node))))
11426 (let ((state (save-excursion (parse-partial-sexp start pos))))
11427 (goto-char (if (not (zerop (car state)))
11428 (scan-sexps start 1)
11429 pos))))
11430 (unless pos (goto-char (point-max)))))))))
11431
11432 (defun js2-mode-forward-sexp-parens (node abs-pos)
11433 "Return a cons cell with positions of main parens in NODE."
11434 (cond
11435 ((or (js2-array-node-p node)
11436 (js2-object-node-p node)
11437 (js2-comp-node-p node)
11438 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11439 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11440 ((js2-paren-expr-node-p node)
11441 (let ((lp (js2-node-lp node))
11442 (rp (js2-node-rp node)))
11443 (cons (when lp (+ abs-pos lp))
11444 (when rp (+ abs-pos rp)))))))
11445
11446 (defun js2-node-closest-child (parent point limit &optional before)
11447 (let* ((parent-pos (js2-node-abs-pos parent))
11448 (rpoint (- point parent-pos))
11449 (rlimit (- limit parent-pos))
11450 (min (min rpoint rlimit))
11451 (max (max rpoint rlimit))
11452 found)
11453 (catch 'done
11454 (js2-visit-ast
11455 parent
11456 (lambda (node _end-p)
11457 (if (eq node parent)
11458 t
11459 (let ((pos (js2-node-pos node)) ;; Both relative values.
11460 (end (+ (js2-node-pos node) (js2-node-len node))))
11461 (when (and (>= pos min) (<= end max)
11462 (if before (< pos rpoint) (> end rpoint)))
11463 (setq found node))
11464 (when (> end rpoint)
11465 (throw 'done nil)))
11466 nil))))
11467 found))
11468
11469 (defun js2-errors ()
11470 "Return a list of errors found."
11471 (and js2-mode-ast
11472 (js2-ast-root-errors js2-mode-ast)))
11473
11474 (defun js2-warnings ()
11475 "Return a list of warnings found."
11476 (and js2-mode-ast
11477 (js2-ast-root-warnings js2-mode-ast)))
11478
11479 (defun js2-have-errors-p ()
11480 "Return non-nil if any parse errors or warnings were found."
11481 (or (js2-errors) (js2-warnings)))
11482
11483 (defun js2-errors-and-warnings ()
11484 "Return a copy of the concatenated errors and warnings lists.
11485 They are appended: first the errors, then the warnings.
11486 Entries are of the form (MSG BEG END)."
11487 (when js2-mode-ast
11488 (append (js2-ast-root-errors js2-mode-ast)
11489 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11490
11491 (defun js2-next-error (&optional arg reset)
11492 "Move to next parse error.
11493 Typically invoked via \\[next-error].
11494 ARG is the number of errors, forward or backward, to move.
11495 RESET means start over from the beginning."
11496 (interactive "p")
11497 (if (not (or (js2-errors) (js2-warnings)))
11498 (message "No errors")
11499 (when reset
11500 (goto-char (point-min)))
11501 (let* ((errs (js2-errors-and-warnings))
11502 (continue t)
11503 (start (point))
11504 (count (or arg 1))
11505 (backward (minusp count))
11506 (sorter (if backward '> '<))
11507 (stopper (if backward '< '>))
11508 (count (abs count))
11509 all-errs err)
11510 ;; Sort by start position.
11511 (setq errs (sort errs (lambda (e1 e2)
11512 (funcall sorter (second e1) (second e2))))
11513 all-errs errs)
11514 ;; Find nth error with pos > start.
11515 (while (and errs continue)
11516 (when (funcall stopper (cadar errs) start)
11517 (setq err (car errs))
11518 (if (zerop (decf count))
11519 (setq continue nil)))
11520 (setq errs (cdr errs)))
11521 ;; Clear for `js2-echo-error'.
11522 (message nil)
11523 (if err
11524 (goto-char (second err))
11525 ;; Wrap around to first error.
11526 (goto-char (second (car all-errs)))
11527 ;; If we were already on it, echo msg again.
11528 (if (= (point) start)
11529 (js2-echo-error (point) (point)))))))
11530
11531 (defun js2-down-mouse-3 ()
11532 "Make right-click move the point to the click location.
11533 This makes right-click context menu operations a bit more intuitive.
11534 The point will not move if the region is active, however, to avoid
11535 destroying the region selection."
11536 (interactive)
11537 (when (and js2-move-point-on-right-click
11538 (not mark-active))
11539 (let ((e last-input-event))
11540 (ignore-errors
11541 (goto-char (cadadr e))))))
11542
11543 (defun js2-mode-create-imenu-index ()
11544 "Return an alist for `imenu--index-alist'."
11545 ;; This is built up in `js2-parse-record-imenu' during parsing.
11546 (when js2-mode-ast
11547 ;; if we have an ast but no recorder, they're requesting a rescan
11548 (unless js2-imenu-recorder
11549 (js2-reparse 'force))
11550 (prog1
11551 (js2-build-imenu-index)
11552 (setq js2-imenu-recorder nil
11553 js2-imenu-function-map nil))))
11554
11555 (defun js2-mode-find-tag ()
11556 "Replacement for `find-tag-default'.
11557 `find-tag-default' returns a ridiculous answer inside comments."
11558 (let (beg end)
11559 (js2-with-underscore-as-word-syntax
11560 (save-excursion
11561 (if (and (not (looking-at "[[:alnum:]_$]"))
11562 (looking-back "[[:alnum:]_$]"))
11563 (setq beg (progn (forward-word -1) (point))
11564 end (progn (forward-word 1) (point)))
11565 (setq beg (progn (forward-word 1) (point))
11566 end (progn (forward-word -1) (point))))
11567 (replace-regexp-in-string
11568 "[\"']" ""
11569 (buffer-substring-no-properties beg end))))))
11570
11571 (defun js2-mode-forward-sibling ()
11572 "Move to the end of the sibling following point in parent.
11573 Returns non-nil if successful, or nil if there was no following sibling."
11574 (let* ((node (js2-node-at-point))
11575 (parent (js2-mode-find-enclosing-fn node))
11576 sib)
11577 (when (setq sib (js2-node-find-child-after (point) parent))
11578 (goto-char (+ (js2-node-abs-pos sib)
11579 (js2-node-len sib))))))
11580
11581 (defun js2-mode-backward-sibling ()
11582 "Move to the beginning of the sibling node preceding point in parent.
11583 Parent is defined as the enclosing script or function."
11584 (let* ((node (js2-node-at-point))
11585 (parent (js2-mode-find-enclosing-fn node))
11586 sib)
11587 (when (setq sib (js2-node-find-child-before (point) parent))
11588 (goto-char (js2-node-abs-pos sib)))))
11589
11590 (defun js2-beginning-of-defun (&optional arg)
11591 "Go to line on which current function starts, and return t on success.
11592 If we're not in a function or already at the beginning of one, go
11593 to beginning of previous script-level element.
11594 With ARG N, do that N times. If N is negative, move forward."
11595 (setq arg (or arg 1))
11596 (if (plusp arg)
11597 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11598 (when (cond
11599 ((js2-function-node-p parent)
11600 (goto-char (js2-node-abs-pos parent)))
11601 (t
11602 (js2-mode-backward-sibling)))
11603 (if (> arg 1)
11604 (js2-beginning-of-defun (1- arg))
11605 t)))
11606 (when (js2-end-of-defun)
11607 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11608
11609 (defun js2-end-of-defun ()
11610 "Go to the char after the last position of the current function
11611 or script-level element."
11612 (let* ((node (js2-node-at-point))
11613 (parent (or (and (js2-function-node-p node) node)
11614 (js2-node-parent-script-or-fn node)))
11615 script)
11616 (unless (js2-function-node-p parent)
11617 ;; Use current script-level node, or, if none, the next one.
11618 (setq script (or parent node)
11619 parent (js2-node-find-child-before (point) script))
11620 (when (or (null parent)
11621 (>= (point) (+ (js2-node-abs-pos parent)
11622 (js2-node-len parent))))
11623 (setq parent (js2-node-find-child-after (point) script))))
11624 (when parent
11625 (goto-char (+ (js2-node-abs-pos parent)
11626 (js2-node-len parent))))))
11627
11628 (defun js2-mark-defun (&optional allow-extend)
11629 "Put mark at end of this function, point at beginning.
11630 The function marked is the one that contains point.
11631
11632 Interactively, if this command is repeated,
11633 or (in Transient Mark mode) if the mark is active,
11634 it marks the next defun after the ones already marked."
11635 (interactive "p")
11636 (let (extended)
11637 (when (and allow-extend
11638 (or (and (eq last-command this-command) (mark t))
11639 (and transient-mark-mode mark-active)))
11640 (let ((sib (save-excursion
11641 (goto-char (mark))
11642 (if (js2-mode-forward-sibling)
11643 (point)))))
11644 (if sib
11645 (progn
11646 (set-mark sib)
11647 (setq extended t))
11648 ;; no more siblings - try extending to enclosing node
11649 (goto-char (mark t)))))
11650 (when (not extended)
11651 (let ((node (js2-node-at-point (point) t)) ; skip comments
11652 ast fn stmt parent beg end)
11653 (when (js2-ast-root-p node)
11654 (setq ast node
11655 node (or (js2-node-find-child-after (point) node)
11656 (js2-node-find-child-before (point) node))))
11657 ;; only mark whole buffer if we can't find any children
11658 (if (null node)
11659 (setq node ast))
11660 (if (js2-function-node-p node)
11661 (setq parent node)
11662 (setq fn (js2-mode-find-enclosing-fn node)
11663 stmt (if (or (null fn)
11664 (js2-ast-root-p fn))
11665 (js2-mode-find-first-stmt node))
11666 parent (or stmt fn)))
11667 (setq beg (js2-node-abs-pos parent)
11668 end (+ beg (js2-node-len parent)))
11669 (push-mark beg)
11670 (goto-char end)
11671 (exchange-point-and-mark)))))
11672
11673 (defun js2-narrow-to-defun ()
11674 "Narrow to the function enclosing point."
11675 (interactive)
11676 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11677 (fn (if (js2-script-node-p node)
11678 node
11679 (js2-mode-find-enclosing-fn node)))
11680 (beg (js2-node-abs-pos fn)))
11681 (unless (js2-ast-root-p fn)
11682 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11683
11684 (provide 'js2-mode)
11685
11686 ;;; js2-mode.el ends here