]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Make catch-node inherit from scope
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2014 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20141118
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 (defvar js2-harmony-externs
207 (mapcar 'symbol-name
208 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
209 "ES6 externs. If `js2-include-browser-externs' is enabled and
210 `js2-language-version' is sufficiently high, these will be included.")
211
212 ;;; Variables
213
214 (defun js2-mark-safe-local (name pred)
215 "Make the variable NAME buffer-local and mark it as safe file-local
216 variable with predicate PRED."
217 (make-variable-buffer-local name)
218 (put name 'safe-local-variable pred))
219
220 (defcustom js2-highlight-level 2
221 "Amount of syntax highlighting to perform.
222 0 or a negative value means none.
223 1 adds basic syntax highlighting.
224 2 adds highlighting of some Ecma built-in properties.
225 3 adds highlighting of many Ecma built-in functions."
226 :group 'js2-mode
227 :type '(choice (const :tag "None" 0)
228 (const :tag "Basic" 1)
229 (const :tag "Include Properties" 2)
230 (const :tag "Include Functions" 3)))
231
232 (defvar js2-mode-dev-mode-p nil
233 "Non-nil if running in development mode. Normally nil.")
234
235 (defgroup js2-mode nil
236 "An improved JavaScript mode."
237 :group 'languages)
238
239 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
240 (numberp c-basic-offset))
241 c-basic-offset
242 4)
243 "Number of spaces to indent nested statements.
244 Similar to `c-basic-offset'."
245 :group 'js2-mode
246 :type 'integer)
247 (js2-mark-safe-local 'js2-basic-offset 'integerp)
248
249 (defcustom js2-bounce-indent-p nil
250 "Non-nil to have indent-line function choose among alternatives.
251 If nil, the indent-line function will indent to a predetermined column
252 based on heuristic guessing. If non-nil, then if the current line is
253 already indented to that predetermined column, indenting will choose
254 another likely column and indent to that spot. Repeated invocation of
255 the indent-line function will cycle among the computed alternatives.
256 See the function `js2-bounce-indent' for details. When it is non-nil,
257 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
258 :type 'boolean
259 :group 'js2-mode)
260
261 (defcustom js2-pretty-multiline-declarations t
262 "Non-nil to line up multiline declarations vertically:
263
264 var a = 10,
265 b = 20,
266 c = 30;
267
268 If the value is not `all', and the first assigned value in
269 declaration is a function/array/object literal spanning several
270 lines, it won't be indented additionally:
271
272 var o = { var bar = 2,
273 foo: 3 vs. o = {
274 }, foo: 3
275 bar = 2; };"
276 :group 'js2-mode
277 :type 'symbol)
278 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
279
280 (defcustom js2-indent-switch-body nil
281 "When nil, case labels are indented on the same level as the
282 containing switch statement. Otherwise, all lines inside
283 switch statement body are indented one additional level."
284 :type 'boolean
285 :group 'js2-mode)
286 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
287
288 (defcustom js2-idle-timer-delay 0.2
289 "Delay in secs before re-parsing after user makes changes.
290 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
291 :type 'number
292 :group 'js2-mode)
293 (make-variable-buffer-local 'js2-idle-timer-delay)
294
295 (defcustom js2-dynamic-idle-timer-adjust 0
296 "Positive to adjust `js2-idle-timer-delay' based on file size.
297 The idea is that for short files, parsing is faster so we can be
298 more responsive to user edits without interfering with editing.
299 The buffer length in characters (typically bytes) is divided by
300 this value and used to multiply `js2-idle-timer-delay' for the
301 buffer. For example, a 21k file and 10k adjust yields 21k/10k
302 == 2, so js2-idle-timer-delay is multiplied by 2.
303 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
304 `js2-idle-timer-delay' is not dependent on the file size."
305 :type 'number
306 :group 'js2-mode)
307
308 (defcustom js2-concat-multiline-strings t
309 "When non-nil, `js2-line-break' in mid-string will make it a
310 string concatenation. When `eol', the '+' will be inserted at the
311 end of the line, otherwise, at the beginning of the next line."
312 :type '(choice (const t) (const eol) (const nil))
313 :group 'js2-mode)
314
315 (defcustom js2-mode-show-parse-errors t
316 "True to highlight parse errors."
317 :type 'boolean
318 :group 'js2-mode)
319
320 (defcustom js2-mode-show-strict-warnings t
321 "Non-nil to emit Ecma strict-mode warnings.
322 Some of the warnings can be individually disabled by other flags,
323 even if this flag is non-nil."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-trailing-comma-warning t
328 "Non-nil to warn about trailing commas in array literals.
329 Ecma-262-5.1 allows them, but older versions of IE raise an error."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-var-redeclaration-warning t
366 "Non-nil to warn about redeclaring variables in a script or function."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-strict-var-hides-function-arg-warning t
371 "Non-nil to warn about a var decl hiding a function argument."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-skip-preprocessor-directives nil
376 "Non-nil to treat lines beginning with # as comments.
377 Useful for viewing Mozilla JavaScript source code."
378 :type 'boolean
379 :group 'js2-mode)
380
381 (defcustom js2-language-version 200
382 "Configures what JavaScript language version to recognize.
383 Currently versions 150, 160, 170, 180 and 200 are supported,
384 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
385 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
386 yield, and Array comprehensions, and 1.8 adds function closures."
387 :type 'integer
388 :group 'js2-mode)
389
390 (defcustom js2-instanceof-has-side-effects nil
391 "If non-nil, treats the instanceof operator as having side effects.
392 This is useful for xulrunner apps."
393 :type 'boolean
394 :group 'js2-mode)
395
396 (defcustom js2-move-point-on-right-click t
397 "Non-nil to move insertion point when you right-click.
398 This makes right-click context menu behavior a bit more intuitive,
399 since menu operations generally apply to the point. The exception
400 is if there is a region selection, in which case the point does -not-
401 move, so cut/copy/paste can work properly.
402
403 Note that IntelliJ moves the point, and Eclipse leaves it alone,
404 so this behavior is customizable."
405 :group 'js2-mode
406 :type 'boolean)
407
408 (defcustom js2-allow-rhino-new-expr-initializer t
409 "Non-nil to support a Rhino's experimental syntactic construct.
410
411 Rhino supports the ability to follow a `new' expression with an object
412 literal, which is used to set additional properties on the new object
413 after calling its constructor. Syntax:
414
415 new <expr> [ ( arglist ) ] [initializer]
416
417 Hence, this expression:
418
419 new Object {a: 1, b: 2}
420
421 results in an Object with properties a=1 and b=2. This syntax is
422 apparently not configurable in Rhino - it's currently always enabled,
423 as of Rhino version 1.7R2."
424 :type 'boolean
425 :group 'js2-mode)
426
427 (defcustom js2-allow-member-expr-as-function-name nil
428 "Non-nil to support experimental Rhino syntax for function names.
429
430 Rhino supports an experimental syntax configured via the Rhino Context
431 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
432
433 function <member-expr> ( [ arg-list ] ) { <body> }
434
435 Where member-expr is a non-parenthesized 'member expression', which
436 is anything at the grammar level of a new-expression or lower, meaning
437 any expression that does not involve infix or unary operators.
438
439 When <member-expr> is not a simple identifier, then it is syntactic
440 sugar for assigning the anonymous function to the <member-expr>. Hence,
441 this code:
442
443 function a.b().c[2] (x, y) { ... }
444
445 is rewritten as:
446
447 a.b().c[2] = function(x, y) {...}
448
449 which doesn't seem particularly useful, but Rhino permits it."
450 :type 'boolean
451 :group 'js2-mode)
452
453 ;; scanner variables
454
455 (defmacro js2-deflocal (name value &optional comment)
456 "Define a buffer-local variable NAME with VALUE and COMMENT."
457 `(progn
458 (defvar ,name ,value ,comment)
459 (make-variable-buffer-local ',name)))
460
461 (defvar js2-EOF_CHAR -1
462 "Represents end of stream. Distinct from js2-EOF token type.")
463
464 ;; I originally used symbols to represent tokens, but Rhino uses
465 ;; ints and then sets various flag bits in them, so ints it is.
466 ;; The upshot is that we need a `js2-' prefix in front of each name.
467 (defvar js2-ERROR -1)
468 (defvar js2-EOF 0)
469 (defvar js2-EOL 1)
470 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
471 (defvar js2-LEAVEWITH 3)
472 (defvar js2-RETURN 4)
473 (defvar js2-GOTO 5)
474 (defvar js2-IFEQ 6)
475 (defvar js2-IFNE 7)
476 (defvar js2-SETNAME 8)
477 (defvar js2-BITOR 9)
478 (defvar js2-BITXOR 10)
479 (defvar js2-BITAND 11)
480 (defvar js2-EQ 12)
481 (defvar js2-NE 13)
482 (defvar js2-LT 14)
483 (defvar js2-LE 15)
484 (defvar js2-GT 16)
485 (defvar js2-GE 17)
486 (defvar js2-LSH 18)
487 (defvar js2-RSH 19)
488 (defvar js2-URSH 20)
489 (defvar js2-ADD 21) ; infix plus
490 (defvar js2-SUB 22) ; infix minus
491 (defvar js2-MUL 23)
492 (defvar js2-DIV 24)
493 (defvar js2-MOD 25)
494 (defvar js2-NOT 26)
495 (defvar js2-BITNOT 27)
496 (defvar js2-POS 28) ; unary plus
497 (defvar js2-NEG 29) ; unary minus
498 (defvar js2-NEW 30)
499 (defvar js2-DELPROP 31)
500 (defvar js2-TYPEOF 32)
501 (defvar js2-GETPROP 33)
502 (defvar js2-GETPROPNOWARN 34)
503 (defvar js2-SETPROP 35)
504 (defvar js2-GETELEM 36)
505 (defvar js2-SETELEM 37)
506 (defvar js2-CALL 38)
507 (defvar js2-NAME 39) ; an identifier
508 (defvar js2-NUMBER 40)
509 (defvar js2-STRING 41)
510 (defvar js2-NULL 42)
511 (defvar js2-THIS 43)
512 (defvar js2-FALSE 44)
513 (defvar js2-TRUE 45)
514 (defvar js2-SHEQ 46) ; shallow equality (===)
515 (defvar js2-SHNE 47) ; shallow inequality (!==)
516 (defvar js2-REGEXP 48)
517 (defvar js2-BINDNAME 49)
518 (defvar js2-THROW 50)
519 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
520 (defvar js2-IN 52)
521 (defvar js2-INSTANCEOF 53)
522 (defvar js2-LOCAL_LOAD 54)
523 (defvar js2-GETVAR 55)
524 (defvar js2-SETVAR 56)
525 (defvar js2-CATCH_SCOPE 57)
526 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
527 (defvar js2-ENUM_INIT_VALUES 59)
528 (defvar js2-ENUM_INIT_ARRAY 60)
529 (defvar js2-ENUM_NEXT 61)
530 (defvar js2-ENUM_ID 62)
531 (defvar js2-THISFN 63)
532 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
533 (defvar js2-ARRAYLIT 65) ; array literal
534 (defvar js2-OBJECTLIT 66) ; object literal
535 (defvar js2-GET_REF 67) ; *reference
536 (defvar js2-SET_REF 68) ; *reference = something
537 (defvar js2-DEL_REF 69) ; delete reference
538 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
539 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
540 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
541
542 ;; XML support
543 (defvar js2-DEFAULTNAMESPACE 73)
544 (defvar js2-ESCXMLATTR 74)
545 (defvar js2-ESCXMLTEXT 75)
546 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
547 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
548 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
549 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
550
551 (defvar js2-first-bytecode js2-ENTERWITH)
552 (defvar js2-last-bytecode js2-REF_NS_NAME)
553
554 (defvar js2-TRY 80)
555 (defvar js2-SEMI 81) ; semicolon
556 (defvar js2-LB 82) ; left and right brackets
557 (defvar js2-RB 83)
558 (defvar js2-LC 84) ; left and right curly-braces
559 (defvar js2-RC 85)
560 (defvar js2-LP 86) ; left and right parens
561 (defvar js2-RP 87)
562 (defvar js2-COMMA 88) ; comma operator
563
564 (defvar js2-ASSIGN 89) ; simple assignment (=)
565 (defvar js2-ASSIGN_BITOR 90) ; |=
566 (defvar js2-ASSIGN_BITXOR 91) ; ^=
567 (defvar js2-ASSIGN_BITAND 92) ; &=
568 (defvar js2-ASSIGN_LSH 93) ; <<=
569 (defvar js2-ASSIGN_RSH 94) ; >>=
570 (defvar js2-ASSIGN_URSH 95) ; >>>=
571 (defvar js2-ASSIGN_ADD 96) ; +=
572 (defvar js2-ASSIGN_SUB 97) ; -=
573 (defvar js2-ASSIGN_MUL 98) ; *=
574 (defvar js2-ASSIGN_DIV 99) ; /=
575 (defvar js2-ASSIGN_MOD 100) ; %=
576
577 (defvar js2-first-assign js2-ASSIGN)
578 (defvar js2-last-assign js2-ASSIGN_MOD)
579
580 (defvar js2-HOOK 101) ; conditional (?:)
581 (defvar js2-COLON 102)
582 (defvar js2-OR 103) ; logical or (||)
583 (defvar js2-AND 104) ; logical and (&&)
584 (defvar js2-INC 105) ; increment/decrement (++ --)
585 (defvar js2-DEC 106)
586 (defvar js2-DOT 107) ; member operator (.)
587 (defvar js2-FUNCTION 108) ; function keyword
588 (defvar js2-EXPORT 109) ; export keyword
589 (defvar js2-IMPORT 110) ; import keyword
590 (defvar js2-IF 111) ; if keyword
591 (defvar js2-ELSE 112) ; else keyword
592 (defvar js2-SWITCH 113) ; switch keyword
593 (defvar js2-CASE 114) ; case keyword
594 (defvar js2-DEFAULT 115) ; default keyword
595 (defvar js2-WHILE 116) ; while keyword
596 (defvar js2-DO 117) ; do keyword
597 (defvar js2-FOR 118) ; for keyword
598 (defvar js2-BREAK 119) ; break keyword
599 (defvar js2-CONTINUE 120) ; continue keyword
600 (defvar js2-VAR 121) ; var keyword
601 (defvar js2-WITH 122) ; with keyword
602 (defvar js2-CATCH 123) ; catch keyword
603 (defvar js2-FINALLY 124) ; finally keyword
604 (defvar js2-VOID 125) ; void keyword
605 (defvar js2-RESERVED 126) ; reserved keywords
606
607 (defvar js2-EMPTY 127)
608
609 ;; Types used for the parse tree - never returned by scanner.
610
611 (defvar js2-BLOCK 128) ; statement block
612 (defvar js2-LABEL 129) ; label
613 (defvar js2-TARGET 130)
614 (defvar js2-LOOP 131)
615 (defvar js2-EXPR_VOID 132) ; expression statement in functions
616 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
617 (defvar js2-JSR 134)
618 (defvar js2-SCRIPT 135) ; top-level node for entire script
619 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
620 (defvar js2-USE_STACK 137)
621 (defvar js2-SETPROP_OP 138) ; x.y op= something
622 (defvar js2-SETELEM_OP 139) ; x[y] op= something
623 (defvar js2-LOCAL_BLOCK 140)
624 (defvar js2-SET_REF_OP 141) ; *reference op= something
625
626 ;; For XML support:
627 (defvar js2-DOTDOT 142) ; member operator (..)
628 (defvar js2-COLONCOLON 143) ; namespace::name
629 (defvar js2-XML 144) ; XML type
630 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
631 (defvar js2-XMLATTR 146) ; @
632 (defvar js2-XMLEND 147)
633
634 ;; Optimizer-only tokens
635 (defvar js2-TO_OBJECT 148)
636 (defvar js2-TO_DOUBLE 149)
637
638 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
639 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
640 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
641 (defvar js2-CONST 153)
642 (defvar js2-SETCONST 154)
643 (defvar js2-SETCONSTVAR 155)
644 (defvar js2-ARRAYCOMP 156)
645 (defvar js2-LETEXPR 157)
646 (defvar js2-WITHEXPR 158)
647 (defvar js2-DEBUGGER 159)
648
649 (defvar js2-COMMENT 160)
650 (defvar js2-TRIPLEDOT 161) ; for rest parameter
651 (defvar js2-ARROW 162) ; function arrow (=>)
652 (defvar js2-CLASS 163)
653 (defvar js2-EXTENDS 164)
654 (defvar js2-STATIC 165)
655 (defvar js2-SUPER 166)
656 (defvar js2-TEMPLATE_HEAD 167) ; part of template literal before substitution
657 (defvar js2-NO_SUBS_TEMPLATE 168) ; template literal without substitutions
658 (defvar js2-TAGGED_TEMPLATE 169) ; tagged template literal
659
660 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
661
662 (defconst js2-debug-print-trees nil)
663
664 ;; Rhino accepts any string or stream as input. Emacs character
665 ;; processing works best in buffers, so we'll assume the input is a
666 ;; buffer. JavaScript strings can be copied into temp buffers before
667 ;; scanning them.
668
669 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
670 ;; They're the Emacs equivalent of instance variables, more or less.
671
672 (js2-deflocal js2-ts-dirty-line nil
673 "Token stream buffer-local variable.
674 Indicates stuff other than whitespace since start of line.")
675
676 (js2-deflocal js2-ts-hit-eof nil
677 "Token stream buffer-local variable.")
678
679 ;; FIXME: Unused.
680 (js2-deflocal js2-ts-line-start 0
681 "Token stream buffer-local variable.")
682
683 (js2-deflocal js2-ts-lineno 1
684 "Token stream buffer-local variable.")
685
686 ;; FIXME: Unused.
687 (js2-deflocal js2-ts-line-end-char -1
688 "Token stream buffer-local variable.")
689
690 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
691 "Token stream buffer-local variable.
692 Current scan position.")
693
694 ;; FIXME: Unused.
695 (js2-deflocal js2-ts-is-xml-attribute nil
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-xml-is-tag-content nil
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-xml-open-tags-count 0
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-string-buffer nil
705 "Token stream buffer-local variable.
706 List of chars built up while scanning various tokens.")
707
708 (defstruct (js2-token
709 (:constructor nil)
710 (:constructor make-js2-token (beg)))
711 "Value returned from the token stream."
712 (type js2-EOF)
713 (beg 1)
714 (end -1)
715 (string "")
716 number
717 regexp-flags
718 comment-type
719 follows-eol-p)
720
721 (defstruct (js2-ts-state
722 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
723 (cursor js2-ts-cursor)
724 (tokens (copy-sequence js2-ti-tokens))
725 (tokens-cursor js2-ti-tokens-cursor)
726 (lookahead js2-ti-lookahead))))
727 lineno
728 cursor
729 tokens
730 tokens-cursor
731 lookahead)
732
733 ;;; Parser variables
734
735 (js2-deflocal js2-parsed-errors nil
736 "List of errors produced during scanning/parsing.")
737
738 (js2-deflocal js2-parsed-warnings nil
739 "List of warnings produced during scanning/parsing.")
740
741 (js2-deflocal js2-recover-from-parse-errors t
742 "Non-nil to continue parsing after a syntax error.
743
744 In recovery mode, the AST will be built in full, and any error
745 nodes will be flagged with appropriate error information. If
746 this flag is nil, a syntax error will result in an error being
747 signaled.
748
749 The variable is automatically buffer-local, because different
750 modes that use the parser will need different settings.")
751
752 (js2-deflocal js2-parse-hook nil
753 "List of callbacks for receiving parsing progress.")
754
755 (defvar js2-parse-finished-hook nil
756 "List of callbacks to notify when parsing finishes.
757 Not called if parsing was interrupted.")
758
759 (js2-deflocal js2-is-eval-code nil
760 "True if we're evaluating code in a string.
761 If non-nil, the tokenizer will record the token text, and the AST nodes
762 will record their source text. Off by default for IDE modes, since the
763 text is available in the buffer.")
764
765 (defvar js2-parse-ide-mode t
766 "Non-nil if the parser is being used for `js2-mode'.
767 If non-nil, the parser will set text properties for fontification
768 and the syntax table. The value should be nil when using the
769 parser as a frontend to an interpreter or byte compiler.")
770
771 ;;; Parser instance variables (buffer-local vars for js2-parse)
772
773 (defconst js2-ti-after-eol (lsh 1 16)
774 "Flag: first token of the source line.")
775
776 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
777
778 (js2-deflocal js2-compiler-generate-debug-info t)
779 (js2-deflocal js2-compiler-use-dynamic-scope nil)
780 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
781 (js2-deflocal js2-compiler-xml-available t)
782 (js2-deflocal js2-compiler-optimization-level 0)
783 (js2-deflocal js2-compiler-generating-source t)
784 (js2-deflocal js2-compiler-strict-mode nil)
785 (js2-deflocal js2-compiler-report-warning-as-error nil)
786 (js2-deflocal js2-compiler-generate-observer-count nil)
787 (js2-deflocal js2-compiler-activation-names nil)
788
789 ;; SKIP: sourceURI
790
791 ;; There's a compileFunction method in Context.java - may need it.
792 (js2-deflocal js2-called-by-compile-function nil
793 "True if `js2-parse' was called by `js2-compile-function'.
794 Will only be used when we finish implementing the interpreter.")
795
796 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
797
798 ;; SKIP: node factory - we're going to just call functions directly,
799 ;; and eventually go to a unified AST format.
800
801 (js2-deflocal js2-nesting-of-function 0)
802
803 (js2-deflocal js2-recorded-identifiers nil
804 "Tracks identifiers found during parsing.")
805
806 (js2-deflocal js2-is-in-destructuring nil
807 "True while parsing destructuring expression.")
808
809 (defcustom js2-global-externs nil
810 "A list of any extern names you'd like to consider always declared.
811 This list is global and is used by all `js2-mode' files.
812 You can create buffer-local externs list using `js2-additional-externs'.
813
814 There is also a buffer-local variable `js2-default-externs',
815 which is initialized by default to include the Ecma-262 externs
816 and the standard browser externs. The three lists are all
817 checked during highlighting."
818 :type 'list
819 :group 'js2-mode)
820
821 (js2-deflocal js2-default-externs nil
822 "Default external declarations.
823
824 These are currently only used for highlighting undeclared variables,
825 which only worries about top-level (unqualified) references.
826 As js2-mode's processing improves, we will flesh out this list.
827
828 The initial value is set to `js2-ecma-262-externs', unless some
829 of the `js2-include-?-externs' variables are set to t, in which
830 case the browser, Rhino and/or Node.js externs are also included.
831
832 See `js2-additional-externs' for more information.")
833
834 (defcustom js2-include-browser-externs t
835 "Non-nil to include browser externs in the master externs list.
836 If you work on JavaScript files that are not intended for browsers,
837 such as Mozilla Rhino server-side JavaScript, set this to nil.
838 See `js2-additional-externs' for more information about externs."
839 :type 'boolean
840 :group 'js2-mode)
841
842 (defcustom js2-include-rhino-externs nil
843 "Non-nil to include Mozilla Rhino externs in the master externs list.
844 See `js2-additional-externs' for more information about externs."
845 :type 'boolean
846 :group 'js2-mode)
847
848 (defcustom js2-include-node-externs nil
849 "Non-nil to include Node.js externs in the master externs list.
850 See `js2-additional-externs' for more information about externs."
851 :type 'boolean
852 :group 'js2-mode)
853
854 (js2-deflocal js2-additional-externs nil
855 "A buffer-local list of additional external declarations.
856 It is used to decide whether variables are considered undeclared
857 for purposes of highlighting.
858
859 Each entry is a Lisp string. The string should be the fully qualified
860 name of an external entity. All externs should be added to this list,
861 so that as js2-mode's processing improves it can take advantage of them.
862
863 You may want to declare your externs in three ways.
864 First, you can add externs that are valid for all your JavaScript files.
865 You should probably do this by adding them to `js2-global-externs', which
866 is a global list used for all js2-mode files.
867
868 Next, you can add a function to `js2-init-hook' that adds additional
869 externs appropriate for the specific file, perhaps based on its path.
870 These should go in `js2-additional-externs', which is buffer-local.
871
872 Third, you can use JSLint's global declaration, as long as
873 `js2-include-jslint-globals' is non-nil, which see.
874
875 Finally, you can add a function to `js2-post-parse-callbacks',
876 which is called after parsing completes, and `js2-mode-ast' is bound to
877 the root of the parse tree. At this stage you can set up an AST
878 node visitor using `js2-visit-ast' and examine the parse tree
879 for specific import patterns that may imply the existence of
880 other externs, possibly tied to your build system. These should also
881 be added to `js2-additional-externs'.
882
883 Your post-parse callback may of course also use the simpler and
884 faster (but perhaps less robust) approach of simply scanning the
885 buffer text for your imports, using regular expressions.")
886
887 ;; SKIP: decompiler
888 ;; SKIP: encoded-source
889
890 ;;; The following variables are per-function and should be saved/restored
891 ;;; during function parsing...
892
893 (js2-deflocal js2-current-script-or-fn nil)
894 (js2-deflocal js2-current-scope nil)
895 (js2-deflocal js2-nesting-of-with 0)
896 (js2-deflocal js2-label-set nil
897 "An alist mapping label names to nodes.")
898
899 (js2-deflocal js2-loop-set nil)
900 (js2-deflocal js2-loop-and-switch-set nil)
901 (js2-deflocal js2-has-return-value nil)
902 (js2-deflocal js2-end-flags 0)
903
904 ;;; ...end of per function variables
905
906 ;; These flags enumerate the possible ways a statement/function can
907 ;; terminate. These flags are used by endCheck() and by the Parser to
908 ;; detect inconsistent return usage.
909 ;;
910 ;; END_UNREACHED is reserved for code paths that are assumed to always be
911 ;; able to execute (example: throw, continue)
912 ;;
913 ;; END_DROPS_OFF indicates if the statement can transfer control to the
914 ;; next one. Statement such as return dont. A compound statement may have
915 ;; some branch that drops off control to the next statement.
916 ;;
917 ;; END_RETURNS indicates that the statement can return (without arguments)
918 ;; END_RETURNS_VALUE indicates that the statement can return a value.
919 ;;
920 ;; A compound statement such as
921 ;; if (condition) {
922 ;; return value;
923 ;; }
924 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
925
926 (defconst js2-end-unreached #x0)
927 (defconst js2-end-drops-off #x1)
928 (defconst js2-end-returns #x2)
929 (defconst js2-end-returns-value #x4)
930
931 ;; Rhino awkwardly passes a statementLabel parameter to the
932 ;; statementHelper() function, the main statement parser, which
933 ;; is then used by quite a few of the sub-parsers. We just make
934 ;; it a buffer-local variable and make sure it's cleaned up properly.
935 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
936
937 ;; Similarly, Rhino passes an inForInit boolean through about half
938 ;; the expression parsers. We use a dynamically-scoped variable,
939 ;; which makes it easier to funcall the parsers individually without
940 ;; worrying about whether they take the parameter or not.
941 (js2-deflocal js2-in-for-init nil)
942 (js2-deflocal js2-temp-name-counter 0)
943 (js2-deflocal js2-parse-stmt-count 0)
944
945 (defsubst js2-get-next-temp-name ()
946 (format "$%d" (incf js2-temp-name-counter)))
947
948 (defvar js2-parse-interruptable-p t
949 "Set this to nil to force parse to continue until finished.
950 This will mostly be useful for interpreters.")
951
952 (defvar js2-statements-per-pause 50
953 "Pause after this many statements to check for user input.
954 If user input is pending, stop the parse and discard the tree.
955 This makes for a smoother user experience for large files.
956 You may have to wait a second or two before the highlighting
957 and error-reporting appear, but you can always type ahead if
958 you wish. This appears to be more or less how Eclipse, IntelliJ
959 and other editors work.")
960
961 (js2-deflocal js2-record-comments t
962 "Instructs the scanner to record comments in `js2-scanned-comments'.")
963
964 (js2-deflocal js2-scanned-comments nil
965 "List of all comments from the current parse.")
966
967 (defcustom js2-mode-indent-inhibit-undo nil
968 "Non-nil to disable collection of Undo information when indenting lines.
969 Some users have requested this behavior. It's nil by default because
970 other Emacs modes don't work this way."
971 :type 'boolean
972 :group 'js2-mode)
973
974 (defcustom js2-mode-indent-ignore-first-tab nil
975 "If non-nil, ignore first TAB keypress if we look indented properly.
976 It's fairly common for users to navigate to an already-indented line
977 and press TAB for reassurance that it's been indented. For this class
978 of users, we want the first TAB press on a line to be ignored if the
979 line is already indented to one of the precomputed alternatives.
980
981 This behavior is only partly implemented. If you TAB-indent a line,
982 navigate to another line, and then navigate back, it fails to clear
983 the last-indented variable, so it thinks you've already hit TAB once,
984 and performs the indent. A full solution would involve getting on the
985 point-motion hooks for the entire buffer. If we come across another
986 use cases that requires watching point motion, I'll consider doing it.
987
988 If you set this variable to nil, then the TAB key will always change
989 the indentation of the current line, if more than one alternative
990 indentation spot exists."
991 :type 'boolean
992 :group 'js2-mode)
993
994 (defvar js2-indent-hook nil
995 "A hook for user-defined indentation rules.
996
997 Functions on this hook should expect two arguments: (LIST INDEX)
998 The LIST argument is the list of computed indentation points for
999 the current line. INDEX is the list index of the indentation point
1000 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1001 indent function is not going to change the current line indentation.
1002
1003 If a hook function on this list returns a non-nil value, then
1004 `js2-bounce-indent' assumes the hook function has performed its own
1005 indentation, and will do nothing. If all hook functions on the list
1006 return nil, then `js2-bounce-indent' will use its computed indentation
1007 and reindent the line.
1008
1009 When hook functions on this hook list are called, the variable
1010 `js2-mode-ast' may or may not be set, depending on whether the
1011 parse tree is available. If the variable is nil, you can pass a
1012 callback to `js2-mode-wait-for-parse', and your callback will be
1013 called after the new parse tree is built. This can take some time
1014 in large files.")
1015
1016 (defface js2-warning
1017 `((((class color) (background light))
1018 (:underline "orange"))
1019 (((class color) (background dark))
1020 (:underline "orange"))
1021 (t (:underline t)))
1022 "Face for JavaScript warnings."
1023 :group 'js2-mode)
1024
1025 (defface js2-error
1026 `((((class color) (background light))
1027 (:foreground "red"))
1028 (((class color) (background dark))
1029 (:foreground "red"))
1030 (t (:foreground "red")))
1031 "Face for JavaScript errors."
1032 :group 'js2-mode)
1033
1034 (defface js2-jsdoc-tag
1035 '((t :foreground "SlateGray"))
1036 "Face used to highlight @whatever tags in jsdoc comments."
1037 :group 'js2-mode)
1038
1039 (defface js2-jsdoc-type
1040 '((t :foreground "SteelBlue"))
1041 "Face used to highlight {FooBar} types in jsdoc comments."
1042 :group 'js2-mode)
1043
1044 (defface js2-jsdoc-value
1045 '((t :foreground "PeachPuff3"))
1046 "Face used to highlight tag values in jsdoc comments."
1047 :group 'js2-mode)
1048
1049 (defface js2-function-param
1050 '((t :foreground "SeaGreen"))
1051 "Face used to highlight function parameters in javascript."
1052 :group 'js2-mode)
1053
1054 (defface js2-function-call
1055 '((t :inherit default))
1056 "Face used to highlight function name in calls."
1057 :group 'js2-mode)
1058
1059 (defface js2-instance-member
1060 '((t :foreground "DarkOrchid"))
1061 "Face used to highlight instance variables in javascript.
1062 Not currently used."
1063 :group 'js2-mode)
1064
1065 (defface js2-private-member
1066 '((t :foreground "PeachPuff3"))
1067 "Face used to highlight calls to private methods in javascript.
1068 Not currently used."
1069 :group 'js2-mode)
1070
1071 (defface js2-private-function-call
1072 '((t :foreground "goldenrod"))
1073 "Face used to highlight calls to private functions in javascript.
1074 Not currently used."
1075 :group 'js2-mode)
1076
1077 (defface js2-jsdoc-html-tag-name
1078 '((((class color) (min-colors 88) (background light))
1079 (:foreground "rosybrown"))
1080 (((class color) (min-colors 8) (background dark))
1081 (:foreground "yellow"))
1082 (((class color) (min-colors 8) (background light))
1083 (:foreground "magenta")))
1084 "Face used to highlight jsdoc html tag names"
1085 :group 'js2-mode)
1086
1087 (defface js2-jsdoc-html-tag-delimiter
1088 '((((class color) (min-colors 88) (background light))
1089 (:foreground "dark khaki"))
1090 (((class color) (min-colors 8) (background dark))
1091 (:foreground "green"))
1092 (((class color) (min-colors 8) (background light))
1093 (:foreground "green")))
1094 "Face used to highlight brackets in jsdoc html tags."
1095 :group 'js2-mode)
1096
1097 (defface js2-external-variable
1098 '((t :foreground "orange"))
1099 "Face used to highlight undeclared variable identifiers.")
1100
1101 (defcustom js2-init-hook nil
1102 "List of functions to be called after `js2-mode' or
1103 `js2-minor-mode' has initialized all variables, before parsing
1104 the buffer for the first time."
1105 :type 'hook
1106 :group 'js2-mode
1107 :version "20130608")
1108
1109 (defcustom js2-post-parse-callbacks nil
1110 "List of callback functions invoked after parsing finishes.
1111 Currently, the main use for this function is to add synthetic
1112 declarations to `js2-recorded-identifiers', which see."
1113 :type 'hook
1114 :group 'js2-mode)
1115
1116 (defcustom js2-build-imenu-callbacks nil
1117 "List of functions called during Imenu index generation.
1118 It's a good place to add additional entries to it, using
1119 `js2-record-imenu-entry'."
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.unexpected.static" ; added by js2-mode
1968 "unexpected 'static'")
1969
1970 (js2-msg "msg.missing.extends" ; added by js2-mode
1971 "name is required after extends")
1972
1973 (js2-msg "msg.no.brace.class" ; added by js2-mode
1974 "missing '{' before class body")
1975
1976 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1977 "missing ']' after computed property expression")
1978
1979 ;;; Tokens Buffer
1980
1981 (defconst js2-ti-max-lookahead 2)
1982 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1983
1984 ;; Have to call `js2-init-scanner' to initialize the values.
1985 (js2-deflocal js2-ti-tokens nil)
1986 (js2-deflocal js2-ti-tokens-cursor nil)
1987 (js2-deflocal js2-ti-lookahead nil)
1988
1989 (defun js2-new-token (offset)
1990 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1991 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1992 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1993 token))
1994
1995 (defsubst js2-current-token ()
1996 (aref js2-ti-tokens js2-ti-tokens-cursor))
1997
1998 (defsubst js2-current-token-string ()
1999 (js2-token-string (js2-current-token)))
2000
2001 (defsubst js2-current-token-type ()
2002 (js2-token-type (js2-current-token)))
2003
2004 (defsubst js2-current-token-beg ()
2005 (js2-token-beg (js2-current-token)))
2006
2007 (defsubst js2-current-token-end ()
2008 (js2-token-end (js2-current-token)))
2009
2010 (defun js2-current-token-len ()
2011 (let ((token (js2-current-token)))
2012 (- (js2-token-end token)
2013 (js2-token-beg token))))
2014
2015 (defun js2-ts-seek (state)
2016 (setq js2-ts-lineno (js2-ts-state-lineno state)
2017 js2-ts-cursor (js2-ts-state-cursor state)
2018 js2-ti-tokens (js2-ts-state-tokens state)
2019 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2020 js2-ti-lookahead (js2-ts-state-lookahead state)))
2021
2022 ;;; Utilities
2023
2024 (defun js2-delete-if (predicate list)
2025 "Remove all items satisfying PREDICATE in LIST."
2026 (loop for item in list
2027 if (not (funcall predicate item))
2028 collect item))
2029
2030 (defun js2-position (element list)
2031 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2032 Returns nil if element is not found in the list."
2033 (let ((count 0)
2034 found)
2035 (while (and list (not found))
2036 (if (eq element (car list))
2037 (setq found t)
2038 (setq count (1+ count)
2039 list (cdr list))))
2040 (if found count)))
2041
2042 (defun js2-find-if (predicate list)
2043 "Find first item satisfying PREDICATE in LIST."
2044 (let (result)
2045 (while (and list (not result))
2046 (if (funcall predicate (car list))
2047 (setq result (car list)))
2048 (setq list (cdr list)))
2049 result))
2050
2051 (defmacro js2-time (form)
2052 "Evaluate FORM, discard result, and return elapsed time in sec."
2053 (declare (debug t))
2054 (let ((beg (make-symbol "--js2-time-beg--"))
2055 (delta (make-symbol "--js2-time-end--")))
2056 `(let ((,beg (current-time))
2057 ,delta)
2058 ,form
2059 (/ (truncate (* (- (float-time (current-time))
2060 (float-time ,beg))
2061 10000))
2062 10000.0))))
2063
2064 (defsubst js2-same-line (pos)
2065 "Return t if POS is on the same line as current point."
2066 (and (>= pos (point-at-bol))
2067 (<= pos (point-at-eol))))
2068
2069 (defun js2-code-bug ()
2070 "Signal an error when we encounter an unexpected code path."
2071 (error "failed assertion"))
2072
2073 (defsubst js2-record-text-property (beg end prop value)
2074 "Record a text property to set when parsing finishes."
2075 (push (list beg end prop value) js2-mode-deferred-properties))
2076
2077 ;; I'd like to associate errors with nodes, but for now the
2078 ;; easiest thing to do is get the context info from the last token.
2079 (defun js2-record-parse-error (msg &optional arg pos len)
2080 (push (list (list msg arg)
2081 (or pos (js2-current-token-beg))
2082 (or len (js2-current-token-len)))
2083 js2-parsed-errors))
2084
2085 (defun js2-report-error (msg &optional msg-arg pos len)
2086 "Signal a syntax error or record a parse error."
2087 (if js2-recover-from-parse-errors
2088 (js2-record-parse-error msg msg-arg pos len)
2089 (signal 'js2-syntax-error
2090 (list msg
2091 js2-ts-lineno
2092 (save-excursion
2093 (goto-char js2-ts-cursor)
2094 (current-column))
2095 js2-ts-hit-eof))))
2096
2097 (defun js2-report-warning (msg &optional msg-arg pos len face)
2098 (if js2-compiler-report-warning-as-error
2099 (js2-report-error msg msg-arg pos len)
2100 (push (list (list msg msg-arg)
2101 (or pos (js2-current-token-beg))
2102 (or len (js2-current-token-len))
2103 face)
2104 js2-parsed-warnings)))
2105
2106 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2107 (if js2-compiler-strict-mode
2108 (js2-report-warning msg-id msg-arg beg
2109 (and beg end (- end beg)))))
2110
2111 (put 'js2-syntax-error 'error-conditions
2112 '(error syntax-error js2-syntax-error))
2113 (put 'js2-syntax-error 'error-message "Syntax error")
2114
2115 (put 'js2-parse-error 'error-conditions
2116 '(error parse-error js2-parse-error))
2117 (put 'js2-parse-error 'error-message "Parse error")
2118
2119 (defmacro js2-clear-flag (flags flag)
2120 `(setq ,flags (logand ,flags (lognot ,flag))))
2121
2122 (defmacro js2-set-flag (flags flag)
2123 "Logical-or FLAG into FLAGS."
2124 `(setq ,flags (logior ,flags ,flag)))
2125
2126 (defsubst js2-flag-set-p (flags flag)
2127 (/= 0 (logand flags flag)))
2128
2129 (defsubst js2-flag-not-set-p (flags flag)
2130 (zerop (logand flags flag)))
2131
2132 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2133 "Evaluate BODY with the _ character set to be word-syntax."
2134 (declare (indent 0) (debug t))
2135 (let ((old-syntax (make-symbol "old-syntax")))
2136 `(let ((,old-syntax (string (char-syntax ?_))))
2137 (unwind-protect
2138 (progn
2139 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2140 ,@body)
2141 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2142
2143 ;;; AST struct and function definitions
2144
2145 ;; flags for ast node property 'member-type (used for e4x operators)
2146 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2147 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2148 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2149
2150 (defsubst js2-relpos (pos anchor)
2151 "Convert POS to be relative to ANCHOR.
2152 If POS is nil, returns nil."
2153 (and pos (- pos anchor)))
2154
2155 (defun js2-make-pad (indent)
2156 (if (zerop indent)
2157 ""
2158 (make-string (* indent js2-basic-offset) ? )))
2159
2160 (defun js2-visit-ast (node callback)
2161 "Visit every node in ast NODE with visitor CALLBACK.
2162
2163 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2164 called twice: once to visit the node, and again after all the node's
2165 children have been processed. The END-P argument is nil on the first
2166 call and non-nil on the second call. The return value of the callback
2167 affects the traversal: if non-nil, the children of NODE are processed.
2168 If the callback returns nil, or if the node has no children, then the
2169 callback is called immediately with a non-nil END-P argument.
2170
2171 The node traversal is approximately lexical-order, although there
2172 are currently no guarantees around this."
2173 (when node
2174 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2175 ;; visit the node
2176 (when (funcall callback node nil)
2177 ;; visit the kids
2178 (cond
2179 ((eq vfunc 'js2-visit-none)
2180 nil) ; don't even bother calling it
2181 ;; Each AST node type has to define a `js2-visitor' function
2182 ;; that takes a node and a callback, and calls `js2-visit-ast'
2183 ;; on each child of the node.
2184 (vfunc
2185 (funcall vfunc node callback))
2186 (t
2187 (error "%s does not define a visitor-traversal function"
2188 (aref node 0)))))
2189 ;; call the end-visit
2190 (funcall callback node t))))
2191
2192 (defstruct (js2-node
2193 (:constructor nil)) ; abstract
2194 "Base AST node type."
2195 (type -1) ; token type
2196 (pos -1) ; start position of this AST node in parsed input
2197 (len 1) ; num characters spanned by the node
2198 props ; optional node property list (an alist)
2199 parent) ; link to parent node; null for root
2200
2201 (defsubst js2-node-get-prop (node prop &optional default)
2202 (or (cadr (assoc prop (js2-node-props node))) default))
2203
2204 (defsubst js2-node-set-prop (node prop value)
2205 (setf (js2-node-props node)
2206 (cons (list prop value) (js2-node-props node))))
2207
2208 (defun js2-fixup-starts (n nodes)
2209 "Adjust the start positions of NODES to be relative to N.
2210 Any node in the list may be nil, for convenience."
2211 (dolist (node nodes)
2212 (when node
2213 (setf (js2-node-pos node) (- (js2-node-pos node)
2214 (js2-node-pos n))))))
2215
2216 (defun js2-node-add-children (parent &rest nodes)
2217 "Set parent node of NODES to PARENT, and return PARENT.
2218 Does nothing if we're not recording parent links.
2219 If any given node in NODES is nil, doesn't record that link."
2220 (js2-fixup-starts parent nodes)
2221 (dolist (node nodes)
2222 (and node
2223 (setf (js2-node-parent node) parent))))
2224
2225 ;; Non-recursive since it's called a frightening number of times.
2226 (defun js2-node-abs-pos (n)
2227 (let ((pos (js2-node-pos n)))
2228 (while (setq n (js2-node-parent n))
2229 (setq pos (+ pos (js2-node-pos n))))
2230 pos))
2231
2232 (defsubst js2-node-abs-end (n)
2233 "Return absolute buffer position of end of N."
2234 (+ (js2-node-abs-pos n) (js2-node-len n)))
2235
2236 ;; It's important to make sure block nodes have a Lisp list for the
2237 ;; child nodes, to limit printing recursion depth in an AST that
2238 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2239 ;; a sufficiently large vector tree.
2240
2241 (defstruct (js2-block-node
2242 (:include js2-node)
2243 (:constructor nil)
2244 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2245 (pos (js2-current-token-beg))
2246 len
2247 props
2248 kids)))
2249 "A block of statements."
2250 kids) ; a Lisp list of the child statement nodes
2251
2252 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2253 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2254
2255 (defun js2-visit-block (ast callback)
2256 "Visit the `js2-block-node' children of AST."
2257 (dolist (kid (js2-block-node-kids ast))
2258 (js2-visit-ast kid callback)))
2259
2260 (defun js2-print-block (n i)
2261 (let ((pad (js2-make-pad i)))
2262 (insert pad "{\n")
2263 (dolist (kid (js2-block-node-kids n))
2264 (js2-print-ast kid (1+ i)))
2265 (insert pad "}")))
2266
2267 (defstruct (js2-scope
2268 (:include js2-block-node)
2269 (:constructor nil)
2270 (:constructor make-js2-scope (&key (type js2-BLOCK)
2271 (pos (js2-current-token-beg))
2272 len
2273 kids)))
2274 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2275 ;; I don't have one of those handy, so I'll use an alist for now.
2276 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2277 ;; and is much lighter-weight to construct (both CPU and mem).
2278 ;; The keys are interned strings (symbols) for faster lookup.
2279 ;; Should switch to hybrid alist/hashtable eventually.
2280 symbol-table ; an alist of (symbol . js2-symbol)
2281 parent-scope ; a `js2-scope'
2282 top) ; top-level `js2-scope' (script/function)
2283
2284 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2285 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2286
2287 (defun js2-node-get-enclosing-scope (node)
2288 "Return the innermost `js2-scope' node surrounding NODE.
2289 Returns nil if there is no enclosing scope node."
2290 (let ((parent (js2-node-parent node)))
2291 (while (not (js2-scope-p parent))
2292 (setq parent (js2-node-parent parent)))
2293 parent))
2294
2295 (defun js2-get-defining-scope (scope name)
2296 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2297 Returns `js2-scope' in which NAME is defined, or nil if not found."
2298 (let ((sym (if (symbolp name)
2299 name
2300 (intern name)))
2301 table
2302 result
2303 (continue t))
2304 (while (and scope continue)
2305 (if (and (setq table (js2-scope-symbol-table scope))
2306 (assq sym table))
2307 (setq continue nil
2308 result scope)
2309 (setq scope (js2-scope-parent-scope scope))))
2310 result))
2311
2312 (defun js2-scope-get-symbol (scope name)
2313 "Return symbol table entry for NAME in SCOPE.
2314 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2315 (and (js2-scope-symbol-table scope)
2316 (cdr (assq (if (symbolp name)
2317 name
2318 (intern name))
2319 (js2-scope-symbol-table scope)))))
2320
2321 (defun js2-scope-put-symbol (scope name symbol)
2322 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2323 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2324 (let* ((table (js2-scope-symbol-table scope))
2325 (sym (if (symbolp name) name (intern name)))
2326 (entry (assq sym table)))
2327 (if entry
2328 (setcdr entry symbol)
2329 (push (cons sym symbol)
2330 (js2-scope-symbol-table scope)))))
2331
2332 (defstruct (js2-symbol
2333 (:constructor nil)
2334 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2335 "A symbol table entry."
2336 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2337 ;; js2-LET, or js2-CONST
2338 decl-type
2339 name ; string
2340 ast-node) ; a `js2-node'
2341
2342 (defstruct (js2-error-node
2343 (:include js2-node)
2344 (:constructor nil) ; silence emacs21 byte-compiler
2345 (:constructor make-js2-error-node (&key (type js2-ERROR)
2346 (pos (js2-current-token-beg))
2347 len)))
2348 "AST node representing a parse error.")
2349
2350 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2351 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2352
2353 (defstruct (js2-script-node
2354 (:include js2-scope)
2355 (:constructor nil)
2356 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2357 (pos (js2-current-token-beg))
2358 len
2359 ;; FIXME: What are those?
2360 var-decls
2361 fun-decls)))
2362 functions ; Lisp list of nested functions
2363 regexps ; Lisp list of (string . flags)
2364 symbols ; alist (every symbol gets unique index)
2365 (param-count 0)
2366 var-names ; vector of string names
2367 consts ; bool-vector matching var-decls
2368 (temp-number 0)) ; for generating temp variables
2369
2370 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2371 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2372
2373 (defun js2-print-script (node indent)
2374 (dolist (kid (js2-block-node-kids node))
2375 (js2-print-ast kid indent)))
2376
2377 (defstruct (js2-ast-root
2378 (:include js2-script-node)
2379 (:constructor nil)
2380 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2381 (pos (js2-current-token-beg))
2382 len
2383 buffer)))
2384 "The root node of a js2 AST."
2385 buffer ; the source buffer from which the code was parsed
2386 comments ; a Lisp list of comments, ordered by start position
2387 errors ; a Lisp list of errors found during parsing
2388 warnings ; a Lisp list of warnings found during parsing
2389 node-count) ; number of nodes in the tree, including the root
2390
2391 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2392 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2393
2394 (defun js2-visit-ast-root (ast callback)
2395 (dolist (kid (js2-ast-root-kids ast))
2396 (js2-visit-ast kid callback))
2397 (dolist (comment (js2-ast-root-comments ast))
2398 (js2-visit-ast comment callback)))
2399
2400 (defstruct (js2-comment-node
2401 (:include js2-node)
2402 (:constructor nil)
2403 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2404 (pos (js2-current-token-beg))
2405 len
2406 format)))
2407 format) ; 'line, 'block, 'jsdoc or 'html
2408
2409 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2410 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2411
2412 (defun js2-print-comment (n i)
2413 ;; We really ought to link end-of-line comments to their nodes.
2414 ;; Or maybe we could add a new comment type, 'endline.
2415 (insert (js2-make-pad i)
2416 (js2-node-string n)))
2417
2418 (defstruct (js2-expr-stmt-node
2419 (:include js2-node)
2420 (:constructor nil)
2421 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2422 (pos js2-ts-cursor)
2423 len
2424 expr)))
2425 "An expression statement."
2426 expr)
2427
2428 (defsubst js2-expr-stmt-node-set-has-result (node)
2429 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2430 (setf (js2-node-type node) js2-EXPR_RESULT))
2431
2432 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2433 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2434
2435 (defun js2-visit-expr-stmt-node (n v)
2436 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2437
2438 (defun js2-print-expr-stmt-node (n indent)
2439 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2440 (insert ";\n"))
2441
2442 (defstruct (js2-loop-node
2443 (:include js2-scope)
2444 (:constructor nil))
2445 "Abstract supertype of loop nodes."
2446 body ; a `js2-block-node'
2447 lp ; position of left-paren, nil if omitted
2448 rp) ; position of right-paren, nil if omitted
2449
2450 (defstruct (js2-do-node
2451 (:include js2-loop-node)
2452 (:constructor nil)
2453 (:constructor make-js2-do-node (&key (type js2-DO)
2454 (pos (js2-current-token-beg))
2455 len
2456 body
2457 condition
2458 while-pos
2459 lp
2460 rp)))
2461 "AST node for do-loop."
2462 condition ; while (expression)
2463 while-pos) ; buffer position of 'while' keyword
2464
2465 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2466 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2467
2468 (defun js2-visit-do-node (n v)
2469 (js2-visit-ast (js2-do-node-body n) v)
2470 (js2-visit-ast (js2-do-node-condition n) v))
2471
2472 (defun js2-print-do-node (n i)
2473 (let ((pad (js2-make-pad i)))
2474 (insert pad "do {\n")
2475 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2476 (js2-print-ast kid (1+ i)))
2477 (insert pad "} while (")
2478 (js2-print-ast (js2-do-node-condition n) 0)
2479 (insert ");\n")))
2480
2481 (defstruct (js2-while-node
2482 (:include js2-loop-node)
2483 (:constructor nil)
2484 (:constructor make-js2-while-node (&key (type js2-WHILE)
2485 (pos (js2-current-token-beg))
2486 len body
2487 condition lp
2488 rp)))
2489 "AST node for while-loop."
2490 condition) ; while-condition
2491
2492 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2493 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2494
2495 (defun js2-visit-while-node (n v)
2496 (js2-visit-ast (js2-while-node-condition n) v)
2497 (js2-visit-ast (js2-while-node-body n) v))
2498
2499 (defun js2-print-while-node (n i)
2500 (let ((pad (js2-make-pad i)))
2501 (insert pad "while (")
2502 (js2-print-ast (js2-while-node-condition n) 0)
2503 (insert ") {\n")
2504 (js2-print-body (js2-while-node-body n) (1+ i))
2505 (insert pad "}\n")))
2506
2507 (defstruct (js2-for-node
2508 (:include js2-loop-node)
2509 (:constructor nil)
2510 (:constructor make-js2-for-node (&key (type js2-FOR)
2511 (pos js2-ts-cursor)
2512 len body init
2513 condition
2514 update lp rp)))
2515 "AST node for a C-style for-loop."
2516 init ; initialization expression
2517 condition ; loop condition
2518 update) ; update clause
2519
2520 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2521 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2522
2523 (defun js2-visit-for-node (n v)
2524 (js2-visit-ast (js2-for-node-init n) v)
2525 (js2-visit-ast (js2-for-node-condition n) v)
2526 (js2-visit-ast (js2-for-node-update n) v)
2527 (js2-visit-ast (js2-for-node-body n) v))
2528
2529 (defun js2-print-for-node (n i)
2530 (let ((pad (js2-make-pad i)))
2531 (insert pad "for (")
2532 (js2-print-ast (js2-for-node-init n) 0)
2533 (insert "; ")
2534 (js2-print-ast (js2-for-node-condition n) 0)
2535 (insert "; ")
2536 (js2-print-ast (js2-for-node-update n) 0)
2537 (insert ") {\n")
2538 (js2-print-body (js2-for-node-body n) (1+ i))
2539 (insert pad "}\n")))
2540
2541 (defstruct (js2-for-in-node
2542 (:include js2-loop-node)
2543 (:constructor nil)
2544 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2545 (pos js2-ts-cursor)
2546 len body
2547 iterator
2548 object
2549 in-pos
2550 each-pos
2551 foreach-p forof-p
2552 lp rp)))
2553 "AST node for a for..in loop."
2554 iterator ; [var] foo in ...
2555 object ; object over which we're iterating
2556 in-pos ; buffer position of 'in' keyword
2557 each-pos ; buffer position of 'each' keyword, if foreach-p
2558 foreach-p ; t if it's a for-each loop
2559 forof-p) ; t if it's a for-of loop
2560
2561 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2562 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2563
2564 (defun js2-visit-for-in-node (n v)
2565 (js2-visit-ast (js2-for-in-node-iterator n) v)
2566 (js2-visit-ast (js2-for-in-node-object n) v)
2567 (js2-visit-ast (js2-for-in-node-body n) v))
2568
2569 (defun js2-print-for-in-node (n i)
2570 (let ((pad (js2-make-pad i))
2571 (foreach (js2-for-in-node-foreach-p n))
2572 (forof (js2-for-in-node-forof-p n)))
2573 (insert pad "for ")
2574 (if foreach
2575 (insert "each "))
2576 (insert "(")
2577 (js2-print-ast (js2-for-in-node-iterator n) 0)
2578 (insert (if forof " of " " in "))
2579 (js2-print-ast (js2-for-in-node-object n) 0)
2580 (insert ") {\n")
2581 (js2-print-body (js2-for-in-node-body n) (1+ i))
2582 (insert pad "}\n")))
2583
2584 (defstruct (js2-return-node
2585 (:include js2-node)
2586 (:constructor nil)
2587 (:constructor make-js2-return-node (&key (type js2-RETURN)
2588 (pos js2-ts-cursor)
2589 len
2590 retval)))
2591 "AST node for a return statement."
2592 retval) ; expression to return, or 'undefined
2593
2594 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2595 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2596
2597 (defun js2-visit-return-node (n v)
2598 (js2-visit-ast (js2-return-node-retval n) v))
2599
2600 (defun js2-print-return-node (n i)
2601 (insert (js2-make-pad i) "return")
2602 (when (js2-return-node-retval n)
2603 (insert " ")
2604 (js2-print-ast (js2-return-node-retval n) 0))
2605 (insert ";\n"))
2606
2607 (defstruct (js2-if-node
2608 (:include js2-node)
2609 (:constructor nil)
2610 (:constructor make-js2-if-node (&key (type js2-IF)
2611 (pos js2-ts-cursor)
2612 len condition
2613 then-part
2614 else-pos
2615 else-part lp
2616 rp)))
2617 "AST node for an if-statement."
2618 condition ; expression
2619 then-part ; statement or block
2620 else-pos ; optional buffer position of 'else' keyword
2621 else-part ; optional statement or block
2622 lp ; position of left-paren, nil if omitted
2623 rp) ; position of right-paren, nil if omitted
2624
2625 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2626 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2627
2628 (defun js2-visit-if-node (n v)
2629 (js2-visit-ast (js2-if-node-condition n) v)
2630 (js2-visit-ast (js2-if-node-then-part n) v)
2631 (js2-visit-ast (js2-if-node-else-part n) v))
2632
2633 (defun js2-print-if-node (n i)
2634 (let ((pad (js2-make-pad i))
2635 (then-part (js2-if-node-then-part n))
2636 (else-part (js2-if-node-else-part n)))
2637 (insert pad "if (")
2638 (js2-print-ast (js2-if-node-condition n) 0)
2639 (insert ") {\n")
2640 (js2-print-body then-part (1+ i))
2641 (insert pad "}")
2642 (cond
2643 ((not else-part)
2644 (insert "\n"))
2645 ((js2-if-node-p else-part)
2646 (insert " else ")
2647 (js2-print-body else-part i))
2648 (t
2649 (insert " else {\n")
2650 (js2-print-body else-part (1+ i))
2651 (insert pad "}\n")))))
2652
2653 (defstruct (js2-try-node
2654 (:include js2-node)
2655 (:constructor nil)
2656 (:constructor make-js2-try-node (&key (type js2-TRY)
2657 (pos js2-ts-cursor)
2658 len
2659 try-block
2660 catch-clauses
2661 finally-block)))
2662 "AST node for a try-statement."
2663 try-block
2664 catch-clauses ; a Lisp list of `js2-catch-node'
2665 finally-block) ; a `js2-finally-node'
2666
2667 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2668 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2669
2670 (defun js2-visit-try-node (n v)
2671 (js2-visit-ast (js2-try-node-try-block n) v)
2672 (dolist (clause (js2-try-node-catch-clauses n))
2673 (js2-visit-ast clause v))
2674 (js2-visit-ast (js2-try-node-finally-block n) v))
2675
2676 (defun js2-print-try-node (n i)
2677 (let ((pad (js2-make-pad i))
2678 (catches (js2-try-node-catch-clauses n))
2679 (finally (js2-try-node-finally-block n)))
2680 (insert pad "try {\n")
2681 (js2-print-body (js2-try-node-try-block n) (1+ i))
2682 (insert pad "}")
2683 (when catches
2684 (dolist (catch catches)
2685 (js2-print-ast catch i)))
2686 (if finally
2687 (js2-print-ast finally i)
2688 (insert "\n"))))
2689
2690 (defstruct (js2-catch-node
2691 (:include js2-scope)
2692 (:constructor nil)
2693 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2694 (pos js2-ts-cursor)
2695 len
2696 param
2697 guard-kwd
2698 guard-expr
2699 lp rp)))
2700 "AST node for a catch clause."
2701 param ; destructuring form or simple name node
2702 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2703 guard-expr ; catch condition, a `js2-node'
2704 lp ; buffer position of left-paren, nil if omitted
2705 rp) ; buffer position of right-paren, nil if omitted
2706
2707 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2708 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2709
2710 (defun js2-visit-catch-node (n v)
2711 (js2-visit-ast (js2-catch-node-param n) v)
2712 (when (js2-catch-node-guard-kwd n)
2713 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2714 (js2-visit-block n v))
2715
2716 (defun js2-print-catch-node (n i)
2717 (let ((pad (js2-make-pad i))
2718 (guard-kwd (js2-catch-node-guard-kwd n))
2719 (guard-expr (js2-catch-node-guard-expr n)))
2720 (insert " catch (")
2721 (js2-print-ast (js2-catch-node-param n) 0)
2722 (when guard-kwd
2723 (insert " if ")
2724 (js2-print-ast guard-expr 0))
2725 (insert ") {\n")
2726 (js2-print-body n (1+ i))
2727 (insert pad "}")))
2728
2729 (defstruct (js2-finally-node
2730 (:include js2-node)
2731 (:constructor nil)
2732 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2733 (pos js2-ts-cursor)
2734 len body)))
2735 "AST node for a finally clause."
2736 body) ; a `js2-node', often but not always a block node
2737
2738 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2739 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2740
2741 (defun js2-visit-finally-node (n v)
2742 (js2-visit-ast (js2-finally-node-body n) v))
2743
2744 (defun js2-print-finally-node (n i)
2745 (let ((pad (js2-make-pad i)))
2746 (insert " finally {\n")
2747 (js2-print-body (js2-finally-node-body n) (1+ i))
2748 (insert pad "}\n")))
2749
2750 (defstruct (js2-switch-node
2751 (:include js2-node)
2752 (:constructor nil)
2753 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2754 (pos js2-ts-cursor)
2755 len
2756 discriminant
2757 cases lp
2758 rp)))
2759 "AST node for a switch statement."
2760 discriminant ; a `js2-node' (switch expression)
2761 cases ; a Lisp list of `js2-case-node'
2762 lp ; position of open-paren for discriminant, nil if omitted
2763 rp) ; position of close-paren for discriminant, nil if omitted
2764
2765 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2766 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2767
2768 (defun js2-visit-switch-node (n v)
2769 (js2-visit-ast (js2-switch-node-discriminant n) v)
2770 (dolist (c (js2-switch-node-cases n))
2771 (js2-visit-ast c v)))
2772
2773 (defun js2-print-switch-node (n i)
2774 (let ((pad (js2-make-pad i))
2775 (cases (js2-switch-node-cases n)))
2776 (insert pad "switch (")
2777 (js2-print-ast (js2-switch-node-discriminant n) 0)
2778 (insert ") {\n")
2779 (dolist (case cases)
2780 (js2-print-ast case i))
2781 (insert pad "}\n")))
2782
2783 (defstruct (js2-case-node
2784 (:include js2-block-node)
2785 (:constructor nil)
2786 (:constructor make-js2-case-node (&key (type js2-CASE)
2787 (pos js2-ts-cursor)
2788 len kids expr)))
2789 "AST node for a case clause of a switch statement."
2790 expr) ; the case expression (nil for default)
2791
2792 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2793 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2794
2795 (defun js2-visit-case-node (n v)
2796 (js2-visit-ast (js2-case-node-expr n) v)
2797 (js2-visit-block n v))
2798
2799 (defun js2-print-case-node (n i)
2800 (let ((pad (js2-make-pad i))
2801 (expr (js2-case-node-expr n)))
2802 (insert pad)
2803 (if (null expr)
2804 (insert "default:\n")
2805 (insert "case ")
2806 (js2-print-ast expr 0)
2807 (insert ":\n"))
2808 (dolist (kid (js2-case-node-kids n))
2809 (js2-print-ast kid (1+ i)))))
2810
2811 (defstruct (js2-throw-node
2812 (:include js2-node)
2813 (:constructor nil)
2814 (:constructor make-js2-throw-node (&key (type js2-THROW)
2815 (pos js2-ts-cursor)
2816 len expr)))
2817 "AST node for a throw statement."
2818 expr) ; the expression to throw
2819
2820 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2821 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2822
2823 (defun js2-visit-throw-node (n v)
2824 (js2-visit-ast (js2-throw-node-expr n) v))
2825
2826 (defun js2-print-throw-node (n i)
2827 (insert (js2-make-pad i) "throw ")
2828 (js2-print-ast (js2-throw-node-expr n) 0)
2829 (insert ";\n"))
2830
2831 (defstruct (js2-with-node
2832 (:include js2-node)
2833 (:constructor nil)
2834 (:constructor make-js2-with-node (&key (type js2-WITH)
2835 (pos js2-ts-cursor)
2836 len object
2837 body lp rp)))
2838 "AST node for a with-statement."
2839 object
2840 body
2841 lp ; buffer position of left-paren around object, nil if omitted
2842 rp) ; buffer position of right-paren around object, nil if omitted
2843
2844 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2845 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2846
2847 (defun js2-visit-with-node (n v)
2848 (js2-visit-ast (js2-with-node-object n) v)
2849 (js2-visit-ast (js2-with-node-body n) v))
2850
2851 (defun js2-print-with-node (n i)
2852 (let ((pad (js2-make-pad i)))
2853 (insert pad "with (")
2854 (js2-print-ast (js2-with-node-object n) 0)
2855 (insert ") {\n")
2856 (js2-print-body (js2-with-node-body n) (1+ i))
2857 (insert pad "}\n")))
2858
2859 (defstruct (js2-label-node
2860 (:include js2-node)
2861 (:constructor nil)
2862 (:constructor make-js2-label-node (&key (type js2-LABEL)
2863 (pos js2-ts-cursor)
2864 len name)))
2865 "AST node for a statement label or case label."
2866 name ; a string
2867 loop) ; for validating and code-generating continue-to-label
2868
2869 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2870 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2871
2872 (defun js2-print-label (n i)
2873 (insert (js2-make-pad i)
2874 (js2-label-node-name n)
2875 ":\n"))
2876
2877 (defstruct (js2-labeled-stmt-node
2878 (:include js2-node)
2879 (:constructor nil)
2880 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2881 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2882 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2883 (pos js2-ts-cursor)
2884 len labels stmt)))
2885 "AST node for a statement with one or more labels.
2886 Multiple labels for a statement are collapsed into the labels field."
2887 labels ; Lisp list of `js2-label-node'
2888 stmt) ; the statement these labels are for
2889
2890 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2891 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2892
2893 (defun js2-get-label-by-name (lbl-stmt name)
2894 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2895 Returns nil if no such label is in the list."
2896 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2897 result)
2898 (while (and label-list (not result))
2899 (if (string= (js2-label-node-name (car label-list)) name)
2900 (setq result (car label-list))
2901 (setq label-list (cdr label-list))))
2902 result))
2903
2904 (defun js2-visit-labeled-stmt (n v)
2905 (dolist (label (js2-labeled-stmt-node-labels n))
2906 (js2-visit-ast label v))
2907 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2908
2909 (defun js2-print-labeled-stmt (n i)
2910 (dolist (label (js2-labeled-stmt-node-labels n))
2911 (js2-print-ast label i))
2912 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2913
2914 (defun js2-labeled-stmt-node-contains (node label)
2915 "Return t if NODE contains LABEL in its label set.
2916 NODE is a `js2-labels-node'. LABEL is an identifier."
2917 (loop for nl in (js2-labeled-stmt-node-labels node)
2918 if (string= label (js2-label-node-name nl))
2919 return t
2920 finally return nil))
2921
2922 (defsubst js2-labeled-stmt-node-add-label (node label)
2923 "Add a `js2-label-node' to the label set for this statement."
2924 (setf (js2-labeled-stmt-node-labels node)
2925 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2926
2927 (defstruct (js2-jump-node
2928 (:include js2-node)
2929 (:constructor nil))
2930 "Abstract supertype of break and continue nodes."
2931 label ; `js2-name-node' for location of label identifier, if present
2932 target) ; target js2-labels-node or loop/switch statement
2933
2934 (defun js2-visit-jump-node (n v)
2935 ;; We don't visit the target, since it's a back-link.
2936 (js2-visit-ast (js2-jump-node-label n) v))
2937
2938 (defstruct (js2-break-node
2939 (:include js2-jump-node)
2940 (:constructor nil)
2941 (:constructor make-js2-break-node (&key (type js2-BREAK)
2942 (pos js2-ts-cursor)
2943 len label target)))
2944 "AST node for a break statement.
2945 The label field is a `js2-name-node', possibly nil, for the named label
2946 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2947 is the target of the break - a label node or enclosing loop/switch statement.")
2948
2949 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2950 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2951
2952 (defun js2-print-break-node (n i)
2953 (insert (js2-make-pad i) "break")
2954 (when (js2-break-node-label n)
2955 (insert " ")
2956 (js2-print-ast (js2-break-node-label n) 0))
2957 (insert ";\n"))
2958
2959 (defstruct (js2-continue-node
2960 (:include js2-jump-node)
2961 (:constructor nil)
2962 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2963 (pos js2-ts-cursor)
2964 len label target)))
2965 "AST node for a continue statement.
2966 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2967 It is nil if continue specifies no label. The target field is the jump target:
2968 a `js2-label-node' or the innermost enclosing loop.")
2969
2970 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2971 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2972
2973 (defun js2-print-continue-node (n i)
2974 (insert (js2-make-pad i) "continue")
2975 (when (js2-continue-node-label n)
2976 (insert " ")
2977 (js2-print-ast (js2-continue-node-label n) 0))
2978 (insert ";\n"))
2979
2980 (defstruct (js2-function-node
2981 (:include js2-script-node)
2982 (:constructor nil)
2983 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2984 (pos js2-ts-cursor)
2985 len
2986 (ftype 'FUNCTION)
2987 (form 'FUNCTION_STATEMENT)
2988 (name "")
2989 params rest-p
2990 body
2991 generator-type
2992 lp rp)))
2993 "AST node for a function declaration.
2994 The `params' field is a Lisp list of nodes. Each node is either a simple
2995 `js2-name-node', or if it's a destructuring-assignment parameter, a
2996 `js2-array-node' or `js2-object-node'."
2997 ftype ; FUNCTION, GETTER or SETTER
2998 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2999 name ; function name (a `js2-name-node', or nil if anonymous)
3000 params ; a Lisp list of destructuring forms or simple name nodes
3001 rest-p ; if t, the last parameter is rest parameter
3002 body ; a `js2-block-node' or expression node (1.8 only)
3003 lp ; position of arg-list open-paren, or nil if omitted
3004 rp ; position of arg-list close-paren, or nil if omitted
3005 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3006 needs-activation ; t if we need an activation object for this frame
3007 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3008 member-expr) ; nonstandard Ecma extension from Rhino
3009
3010 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3011 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3012
3013 (defun js2-visit-function-node (n v)
3014 (js2-visit-ast (js2-function-node-name n) v)
3015 (dolist (p (js2-function-node-params n))
3016 (js2-visit-ast p v))
3017 (js2-visit-ast (js2-function-node-body n) v))
3018
3019 (defun js2-print-function-node (n i)
3020 (let* ((pad (js2-make-pad i))
3021 (getter (js2-node-get-prop n 'GETTER_SETTER))
3022 (name (or (js2-function-node-name n)
3023 (js2-function-node-member-expr n)))
3024 (params (js2-function-node-params n))
3025 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3026 (rest-p (js2-function-node-rest-p n))
3027 (body (js2-function-node-body n))
3028 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3029 (unless (or getter arrow)
3030 (insert pad "function")
3031 (when (eq (js2-function-node-generator-type n) 'STAR)
3032 (insert "*")))
3033 (when name
3034 (insert " ")
3035 (js2-print-ast name 0))
3036 (insert "(")
3037 (loop with len = (length params)
3038 for param in params
3039 for count from 1
3040 do
3041 (when (and rest-p (= count len))
3042 (insert "..."))
3043 (js2-print-ast param 0)
3044 (when (< count len)
3045 (insert ", ")))
3046 (insert ") ")
3047 (when arrow
3048 (insert "=> "))
3049 (insert "{")
3050 ;; TODO: fix this to be smarter about indenting, etc.
3051 (unless expr
3052 (insert "\n"))
3053 (if (js2-block-node-p body)
3054 (js2-print-body body (1+ i))
3055 (js2-print-ast body 0))
3056 (insert pad "}")
3057 (unless expr
3058 (insert "\n"))))
3059
3060 (defun js2-function-name (node)
3061 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3062 (and (js2-function-node-name node)
3063 (js2-name-node-name (js2-function-node-name node))))
3064
3065 ;; Having this be an expression node makes it more flexible.
3066 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3067 ;; that work better if you assume it's an expression. Whenever we have
3068 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3069 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3070 (defstruct (js2-var-decl-node
3071 (:include js2-node)
3072 (:constructor nil)
3073 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3074 (pos (js2-current-token-beg))
3075 len kids
3076 decl-type)))
3077 "AST node for a variable declaration list (VAR, CONST or LET).
3078 The node bounds differ depending on the declaration type. For VAR or
3079 CONST declarations, the bounds include the var/const keyword. For LET
3080 declarations, the node begins at the position of the first child."
3081 kids ; a Lisp list of `js2-var-init-node' structs.
3082 decl-type) ; js2-VAR, js2-CONST or js2-LET
3083
3084 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3085 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3086
3087 (defun js2-visit-var-decl (n v)
3088 (dolist (kid (js2-var-decl-node-kids n))
3089 (js2-visit-ast kid v)))
3090
3091 (defun js2-print-var-decl (n i)
3092 (let ((pad (js2-make-pad i))
3093 (tt (js2-var-decl-node-decl-type n)))
3094 (insert pad)
3095 (insert (cond
3096 ((= tt js2-VAR) "var ")
3097 ((= tt js2-LET) "let ")
3098 ((= tt js2-CONST) "const ")
3099 (t
3100 (error "malformed var-decl node"))))
3101 (loop with kids = (js2-var-decl-node-kids n)
3102 with len = (length kids)
3103 for kid in kids
3104 for count from 1
3105 do
3106 (js2-print-ast kid 0)
3107 (if (< count len)
3108 (insert ", ")))))
3109
3110 (defstruct (js2-var-init-node
3111 (:include js2-node)
3112 (:constructor nil)
3113 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3114 (pos js2-ts-cursor)
3115 len target
3116 initializer)))
3117 "AST node for a variable declaration.
3118 The type field will be js2-CONST for a const decl."
3119 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3120 initializer) ; initializer expression, a `js2-node'
3121
3122 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3123 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3124
3125 (defun js2-visit-var-init-node (n v)
3126 (js2-visit-ast (js2-var-init-node-target n) v)
3127 (js2-visit-ast (js2-var-init-node-initializer n) v))
3128
3129 (defun js2-print-var-init-node (n i)
3130 (let ((pad (js2-make-pad i))
3131 (name (js2-var-init-node-target n))
3132 (init (js2-var-init-node-initializer n)))
3133 (insert pad)
3134 (js2-print-ast name 0)
3135 (when init
3136 (insert " = ")
3137 (js2-print-ast init 0))))
3138
3139 (defstruct (js2-cond-node
3140 (:include js2-node)
3141 (:constructor nil)
3142 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3143 (pos js2-ts-cursor)
3144 len
3145 test-expr
3146 true-expr
3147 false-expr
3148 q-pos c-pos)))
3149 "AST node for the ternary operator"
3150 test-expr
3151 true-expr
3152 false-expr
3153 q-pos ; buffer position of ?
3154 c-pos) ; buffer position of :
3155
3156 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3157 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3158
3159 (defun js2-visit-cond-node (n v)
3160 (js2-visit-ast (js2-cond-node-test-expr n) v)
3161 (js2-visit-ast (js2-cond-node-true-expr n) v)
3162 (js2-visit-ast (js2-cond-node-false-expr n) v))
3163
3164 (defun js2-print-cond-node (n i)
3165 (let ((pad (js2-make-pad i)))
3166 (insert pad)
3167 (js2-print-ast (js2-cond-node-test-expr n) 0)
3168 (insert " ? ")
3169 (js2-print-ast (js2-cond-node-true-expr n) 0)
3170 (insert " : ")
3171 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3172
3173 (defstruct (js2-infix-node
3174 (:include js2-node)
3175 (:constructor nil)
3176 (:constructor make-js2-infix-node (&key type
3177 (pos js2-ts-cursor)
3178 len op-pos
3179 left right)))
3180 "Represents infix expressions.
3181 Includes assignment ops like `|=', and the comma operator.
3182 The type field inherited from `js2-node' holds the operator."
3183 op-pos ; buffer position where operator begins
3184 left ; any `js2-node'
3185 right) ; any `js2-node'
3186
3187 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3188 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3189
3190 (defun js2-visit-infix-node (n v)
3191 (js2-visit-ast (js2-infix-node-left n) v)
3192 (js2-visit-ast (js2-infix-node-right n) v))
3193
3194 (defconst js2-operator-tokens
3195 (let ((table (make-hash-table :test 'eq))
3196 (tokens
3197 (list (cons js2-IN "in")
3198 (cons js2-TYPEOF "typeof")
3199 (cons js2-INSTANCEOF "instanceof")
3200 (cons js2-DELPROP "delete")
3201 (cons js2-COMMA ",")
3202 (cons js2-COLON ":")
3203 (cons js2-OR "||")
3204 (cons js2-AND "&&")
3205 (cons js2-INC "++")
3206 (cons js2-DEC "--")
3207 (cons js2-BITOR "|")
3208 (cons js2-BITXOR "^")
3209 (cons js2-BITAND "&")
3210 (cons js2-EQ "==")
3211 (cons js2-NE "!=")
3212 (cons js2-LT "<")
3213 (cons js2-LE "<=")
3214 (cons js2-GT ">")
3215 (cons js2-GE ">=")
3216 (cons js2-LSH "<<")
3217 (cons js2-RSH ">>")
3218 (cons js2-URSH ">>>")
3219 (cons js2-ADD "+") ; infix plus
3220 (cons js2-SUB "-") ; infix minus
3221 (cons js2-MUL "*")
3222 (cons js2-DIV "/")
3223 (cons js2-MOD "%")
3224 (cons js2-NOT "!")
3225 (cons js2-BITNOT "~")
3226 (cons js2-POS "+") ; unary plus
3227 (cons js2-NEG "-") ; unary minus
3228 (cons js2-TRIPLEDOT "...")
3229 (cons js2-SHEQ "===") ; shallow equality
3230 (cons js2-SHNE "!==") ; shallow inequality
3231 (cons js2-ASSIGN "=")
3232 (cons js2-ASSIGN_BITOR "|=")
3233 (cons js2-ASSIGN_BITXOR "^=")
3234 (cons js2-ASSIGN_BITAND "&=")
3235 (cons js2-ASSIGN_LSH "<<=")
3236 (cons js2-ASSIGN_RSH ">>=")
3237 (cons js2-ASSIGN_URSH ">>>=")
3238 (cons js2-ASSIGN_ADD "+=")
3239 (cons js2-ASSIGN_SUB "-=")
3240 (cons js2-ASSIGN_MUL "*=")
3241 (cons js2-ASSIGN_DIV "/=")
3242 (cons js2-ASSIGN_MOD "%="))))
3243 (loop for (k . v) in tokens do
3244 (puthash k v table))
3245 table))
3246
3247 (defun js2-print-infix-node (n i)
3248 (let* ((tt (js2-node-type n))
3249 (op (gethash tt js2-operator-tokens)))
3250 (unless op
3251 (error "unrecognized infix operator %s" (js2-node-type n)))
3252 (insert (js2-make-pad i))
3253 (js2-print-ast (js2-infix-node-left n) 0)
3254 (unless (= tt js2-COMMA)
3255 (insert " "))
3256 (insert op)
3257 (insert " ")
3258 (js2-print-ast (js2-infix-node-right n) 0)))
3259
3260 (defstruct (js2-assign-node
3261 (:include js2-infix-node)
3262 (:constructor nil)
3263 (:constructor make-js2-assign-node (&key type
3264 (pos js2-ts-cursor)
3265 len op-pos
3266 left right)))
3267 "Represents any assignment.
3268 The type field holds the actual assignment operator.")
3269
3270 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3271 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3272
3273 (defstruct (js2-unary-node
3274 (:include js2-node)
3275 (:constructor nil)
3276 (:constructor make-js2-unary-node (&key type ; required
3277 (pos js2-ts-cursor)
3278 len operand)))
3279 "AST node type for unary operator nodes.
3280 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3281 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3282 property is added if the operator follows the operand."
3283 operand) ; a `js2-node' expression
3284
3285 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3286 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3287
3288 (defun js2-visit-unary-node (n v)
3289 (js2-visit-ast (js2-unary-node-operand n) v))
3290
3291 (defun js2-print-unary-node (n i)
3292 (let* ((tt (js2-node-type n))
3293 (op (gethash tt js2-operator-tokens))
3294 (postfix (js2-node-get-prop n 'postfix)))
3295 (unless op
3296 (error "unrecognized unary operator %s" tt))
3297 (insert (js2-make-pad i))
3298 (unless postfix
3299 (insert op))
3300 (if (or (= tt js2-TYPEOF)
3301 (= tt js2-DELPROP))
3302 (insert " "))
3303 (js2-print-ast (js2-unary-node-operand n) 0)
3304 (when postfix
3305 (insert op))))
3306
3307 (defstruct (js2-let-node
3308 (:include js2-scope)
3309 (:constructor nil)
3310 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3311 (pos (js2-current-token-beg))
3312 len vars body
3313 lp rp)))
3314 "AST node for a let expression or a let statement.
3315 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3316 vars ; a `js2-var-decl-node'
3317 body ; a `js2-node' representing the expression or body block
3318 lp
3319 rp)
3320
3321 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3322 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3323
3324 (defun js2-visit-let-node (n v)
3325 (js2-visit-ast (js2-let-node-vars n) v)
3326 (js2-visit-ast (js2-let-node-body n) v))
3327
3328 (defun js2-print-let-node (n i)
3329 (insert (js2-make-pad i) "let (")
3330 (let ((p (point)))
3331 (js2-print-ast (js2-let-node-vars n) 0)
3332 (delete-region p (+ p 4)))
3333 (insert ") ")
3334 (js2-print-ast (js2-let-node-body n) i))
3335
3336 (defstruct (js2-keyword-node
3337 (:include js2-node)
3338 (:constructor nil)
3339 (:constructor make-js2-keyword-node (&key type
3340 (pos (js2-current-token-beg))
3341 (len (- js2-ts-cursor pos)))))
3342 "AST node representing a literal keyword such as `null'.
3343 Used for `null', `this', `true', `false' and `debugger'.
3344 The node type is set to js2-NULL, js2-THIS, etc.")
3345
3346 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3347 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3348
3349 (defun js2-print-keyword-node (n i)
3350 (insert (js2-make-pad i)
3351 (let ((tt (js2-node-type n)))
3352 (cond
3353 ((= tt js2-THIS) "this")
3354 ((= tt js2-SUPER) "super")
3355 ((= tt js2-NULL) "null")
3356 ((= tt js2-TRUE) "true")
3357 ((= tt js2-FALSE) "false")
3358 ((= tt js2-DEBUGGER) "debugger")
3359 (t (error "Invalid keyword literal type: %d" tt))))))
3360
3361 (defsubst js2-this-or-super-node-p (node)
3362 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3363 (let ((type (js2-node-type node)))
3364 (or (eq type js2-THIS) (eq type js2-SUPER))))
3365
3366 (defstruct (js2-new-node
3367 (:include js2-node)
3368 (:constructor nil)
3369 (:constructor make-js2-new-node (&key (type js2-NEW)
3370 (pos (js2-current-token-beg))
3371 len target
3372 args initializer
3373 lp rp)))
3374 "AST node for new-expression such as new Foo()."
3375 target ; an identifier or reference
3376 args ; a Lisp list of argument nodes
3377 lp ; position of left-paren, nil if omitted
3378 rp ; position of right-paren, nil if omitted
3379 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3380
3381 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3382 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3383
3384 (defun js2-visit-new-node (n v)
3385 (js2-visit-ast (js2-new-node-target n) v)
3386 (dolist (arg (js2-new-node-args n))
3387 (js2-visit-ast arg v))
3388 (js2-visit-ast (js2-new-node-initializer n) v))
3389
3390 (defun js2-print-new-node (n i)
3391 (insert (js2-make-pad i) "new ")
3392 (js2-print-ast (js2-new-node-target n))
3393 (insert "(")
3394 (js2-print-list (js2-new-node-args n))
3395 (insert ")")
3396 (when (js2-new-node-initializer n)
3397 (insert " ")
3398 (js2-print-ast (js2-new-node-initializer n))))
3399
3400 (defstruct (js2-name-node
3401 (:include js2-node)
3402 (:constructor nil)
3403 (:constructor make-js2-name-node (&key (type js2-NAME)
3404 (pos (js2-current-token-beg))
3405 (len (- js2-ts-cursor
3406 (js2-current-token-beg)))
3407 (name (js2-current-token-string)))))
3408 "AST node for a JavaScript identifier"
3409 name ; a string
3410 scope) ; a `js2-scope' (optional, used for codegen)
3411
3412 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3413 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3414
3415 (defun js2-print-name-node (n i)
3416 (insert (js2-make-pad i)
3417 (js2-name-node-name n)))
3418
3419 (defsubst js2-name-node-length (node)
3420 "Return identifier length of NODE, a `js2-name-node'.
3421 Returns 0 if NODE is nil or its identifier field is nil."
3422 (if node
3423 (length (js2-name-node-name node))
3424 0))
3425
3426 (defstruct (js2-number-node
3427 (:include js2-node)
3428 (:constructor nil)
3429 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3430 (pos (js2-current-token-beg))
3431 (len (- js2-ts-cursor
3432 (js2-current-token-beg)))
3433 (value (js2-current-token-string))
3434 (num-value (js2-token-number
3435 (js2-current-token))))))
3436 "AST node for a number literal."
3437 value ; the original string, e.g. "6.02e23"
3438 num-value) ; the parsed number value
3439
3440 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3441 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3442
3443 (defun js2-print-number-node (n i)
3444 (insert (js2-make-pad i)
3445 (number-to-string (js2-number-node-num-value n))))
3446
3447 (defstruct (js2-regexp-node
3448 (:include js2-node)
3449 (:constructor nil)
3450 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3451 (pos (js2-current-token-beg))
3452 (len (- js2-ts-cursor
3453 (js2-current-token-beg)))
3454 value flags)))
3455 "AST node for a regular expression literal."
3456 value ; the regexp string, without // delimiters
3457 flags) ; a string of flags, e.g. `mi'.
3458
3459 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3460 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3461
3462 (defun js2-print-regexp (n i)
3463 (insert (js2-make-pad i)
3464 "/"
3465 (js2-regexp-node-value n)
3466 "/")
3467 (if (js2-regexp-node-flags n)
3468 (insert (js2-regexp-node-flags n))))
3469
3470 (defstruct (js2-string-node
3471 (:include js2-node)
3472 (:constructor nil)
3473 (:constructor make-js2-string-node (&key (type js2-STRING)
3474 (pos (js2-current-token-beg))
3475 (len (- js2-ts-cursor
3476 (js2-current-token-beg)))
3477 (value (js2-current-token-string)))))
3478 "String literal.
3479 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3480 You can tell the quote type by looking at the first character."
3481 value) ; the characters of the string, including the quotes
3482
3483 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3484 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3485
3486 (defun js2-print-string-node (n i)
3487 (insert (js2-make-pad i)
3488 (js2-node-string n)))
3489
3490 (defstruct (js2-template-node
3491 (:include js2-node)
3492 (:constructor nil)
3493 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3494 beg len kids)))
3495 "Template literal."
3496 kids) ; `js2-string-node' is used for string segments, other nodes
3497 ; for substitutions inside.
3498
3499 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3500 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3501
3502 (defun js2-visit-template (n callback)
3503 (dolist (kid (js2-template-node-kids n))
3504 (js2-visit-ast kid callback)))
3505
3506 (defun js2-print-template (n i)
3507 (insert (js2-make-pad i))
3508 (dolist (kid (js2-template-node-kids n))
3509 (if (js2-string-node-p kid)
3510 (insert (js2-node-string kid))
3511 (js2-print-ast kid))))
3512
3513 (defstruct (js2-tagged-template-node
3514 (:include js2-node)
3515 (:constructor nil)
3516 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3517 beg len tag template)))
3518 "Tagged template literal."
3519 tag ; `js2-node' with the tag expression.
3520 template) ; `js2-template-node' with the template.
3521
3522 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3523 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3524
3525 (defun js2-visit-tagged-template (n callback)
3526 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3527 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3528
3529 (defun js2-print-tagged-template (n i)
3530 (insert (js2-make-pad i))
3531 (js2-print-ast (js2-tagged-template-node-tag n))
3532 (js2-print-ast (js2-tagged-template-node-template n)))
3533
3534 (defstruct (js2-array-node
3535 (:include js2-node)
3536 (:constructor nil)
3537 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3538 (pos js2-ts-cursor)
3539 len elems)))
3540 "AST node for an array literal."
3541 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3542
3543 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3544 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3545
3546 (defun js2-visit-array-node (n v)
3547 (dolist (e (js2-array-node-elems n))
3548 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3549
3550 (defun js2-print-array-node (n i)
3551 (insert (js2-make-pad i) "[")
3552 (let ((elems (js2-array-node-elems n)))
3553 (js2-print-list elems)
3554 (when (and elems (null (car (last elems))))
3555 (insert ",")))
3556 (insert "]"))
3557
3558 (defstruct (js2-class-node
3559 (:include js2-node)
3560 (:constructor nil)
3561 (:constructor make-js2-class-node (&key (type js2-CLASS)
3562 (pos js2-ts-cursor)
3563 (form 'CLASS_STATEMENT)
3564 (name "")
3565 extends len elems)))
3566 "AST node for an class expression.
3567 `elems' is a list of `js2-object-prop-node', and `extends' is an
3568 optional `js2-expr-node'"
3569 form ; CLASS_{STATEMENT|EXPRESSION}
3570 name ; class name (a `js2-node-name', or nil if anonymous)
3571 extends ; class heritage (a `js2-expr-node', or nil if none)
3572 elems)
3573
3574 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3575 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3576
3577 (defun js2-visit-class-node (n v)
3578 (js2-visit-ast (js2-class-node-name n) v)
3579 (js2-visit-ast (js2-class-node-extends n) v)
3580 (dolist (e (js2-class-node-elems n))
3581 (js2-visit-ast e v)))
3582
3583 (defun js2-print-class-node (n i)
3584 (let* ((pad (js2-make-pad i))
3585 (name (js2-class-node-name n))
3586 (extends (js2-class-node-extends n))
3587 (elems (js2-class-node-elems n)))
3588 (insert pad "class")
3589 (when name
3590 (insert " ")
3591 (js2-print-ast name 0))
3592 (when extends
3593 (insert " extends ")
3594 (js2-print-ast extends))
3595 (insert " {")
3596 (dolist (elem elems)
3597 (insert "\n")
3598 (if (js2-node-get-prop elem 'STATIC)
3599 (progn (insert (js2-make-pad (1+ i)) "static ")
3600 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3601 (js2-print-ast elem (1+ i))))
3602 (insert "\n" pad "}")))
3603
3604 (defstruct (js2-object-node
3605 (:include js2-node)
3606 (:constructor nil)
3607 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3608 (pos js2-ts-cursor)
3609 len
3610 elems)))
3611 "AST node for an object literal expression.
3612 `elems' is a list of `js2-object-prop-node'."
3613 elems)
3614
3615 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3616 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3617
3618 (defun js2-visit-object-node (n v)
3619 (dolist (e (js2-object-node-elems n))
3620 (js2-visit-ast e v)))
3621
3622 (defun js2-print-object-node (n i)
3623 (insert (js2-make-pad i) "{")
3624 (js2-print-list (js2-object-node-elems n))
3625 (insert "}"))
3626
3627 (defstruct (js2-object-prop-node
3628 (:include js2-infix-node)
3629 (:constructor nil)
3630 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3631 (pos js2-ts-cursor)
3632 len left
3633 right op-pos)))
3634 "AST node for an object literal prop:value entry.
3635 The `left' field is the property: a name node, string node or number node.
3636 The `right' field is a `js2-node' representing the initializer value.
3637 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3638 and both fields have the same value.")
3639
3640 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3641 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3642
3643 (defun js2-print-object-prop-node (n i)
3644 (let* ((left (js2-object-prop-node-left n))
3645 (computed (not (or (js2-string-node-p left)
3646 (js2-number-node-p left)
3647 (js2-name-node-p left)))))
3648 (insert (js2-make-pad i))
3649 (if computed
3650 (insert "["))
3651 (js2-print-ast left 0)
3652 (if computed
3653 (insert "]"))
3654 (if (not (js2-node-get-prop n 'SHORTHAND))
3655 (progn
3656 (insert ": ")
3657 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3658
3659 (defstruct (js2-getter-setter-node
3660 (:include js2-infix-node)
3661 (:constructor nil)
3662 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3663 (pos js2-ts-cursor)
3664 len left right)))
3665 "AST node for a getter/setter property in an object literal.
3666 The `left' field is the `js2-name-node' naming the getter/setter prop.
3667 The `right' field is always an anonymous `js2-function-node' with a node
3668 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3669
3670 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3671 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3672
3673 (defun js2-print-getter-setter (n i)
3674 (let ((pad (js2-make-pad i))
3675 (left (js2-getter-setter-node-left n))
3676 (right (js2-getter-setter-node-right n)))
3677 (insert pad)
3678 (if (/= (js2-node-type n) js2-FUNCTION)
3679 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3680 (js2-print-ast left 0)
3681 (js2-print-ast right 0)))
3682
3683 (defstruct (js2-prop-get-node
3684 (:include js2-infix-node)
3685 (:constructor nil)
3686 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3687 (pos js2-ts-cursor)
3688 len left right)))
3689 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3690
3691 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3692 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3693
3694 (defun js2-visit-prop-get-node (n v)
3695 (js2-visit-ast (js2-prop-get-node-left n) v)
3696 (js2-visit-ast (js2-prop-get-node-right n) v))
3697
3698 (defun js2-print-prop-get-node (n i)
3699 (insert (js2-make-pad i))
3700 (js2-print-ast (js2-prop-get-node-left n) 0)
3701 (insert ".")
3702 (js2-print-ast (js2-prop-get-node-right n) 0))
3703
3704 (defstruct (js2-elem-get-node
3705 (:include js2-node)
3706 (:constructor nil)
3707 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3708 (pos js2-ts-cursor)
3709 len target element
3710 lb rb)))
3711 "AST node for an array index expression such as foo[bar]."
3712 target ; a `js2-node' - the expression preceding the "."
3713 element ; a `js2-node' - the expression in brackets
3714 lb ; position of left-bracket, nil if omitted
3715 rb) ; position of right-bracket, nil if omitted
3716
3717 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3718 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3719
3720 (defun js2-visit-elem-get-node (n v)
3721 (js2-visit-ast (js2-elem-get-node-target n) v)
3722 (js2-visit-ast (js2-elem-get-node-element n) v))
3723
3724 (defun js2-print-elem-get-node (n i)
3725 (insert (js2-make-pad i))
3726 (js2-print-ast (js2-elem-get-node-target n) 0)
3727 (insert "[")
3728 (js2-print-ast (js2-elem-get-node-element n) 0)
3729 (insert "]"))
3730
3731 (defstruct (js2-call-node
3732 (:include js2-node)
3733 (:constructor nil)
3734 (:constructor make-js2-call-node (&key (type js2-CALL)
3735 (pos js2-ts-cursor)
3736 len target args
3737 lp rp)))
3738 "AST node for a JavaScript function call."
3739 target ; a `js2-node' evaluating to the function to call
3740 args ; a Lisp list of `js2-node' arguments
3741 lp ; position of open-paren, or nil if missing
3742 rp) ; position of close-paren, or nil if missing
3743
3744 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3745 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3746
3747 (defun js2-visit-call-node (n v)
3748 (js2-visit-ast (js2-call-node-target n) v)
3749 (dolist (arg (js2-call-node-args n))
3750 (js2-visit-ast arg v)))
3751
3752 (defun js2-print-call-node (n i)
3753 (insert (js2-make-pad i))
3754 (js2-print-ast (js2-call-node-target n) 0)
3755 (insert "(")
3756 (js2-print-list (js2-call-node-args n))
3757 (insert ")"))
3758
3759 (defstruct (js2-yield-node
3760 (:include js2-node)
3761 (:constructor nil)
3762 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3763 (pos js2-ts-cursor)
3764 len value star-p)))
3765 "AST node for yield statement or expression."
3766 star-p ; whether it's yield*
3767 value) ; optional: value to be yielded
3768
3769 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3770 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3771
3772 (defun js2-visit-yield-node (n v)
3773 (js2-visit-ast (js2-yield-node-value n) v))
3774
3775 (defun js2-print-yield-node (n i)
3776 (insert (js2-make-pad i))
3777 (insert "yield")
3778 (when (js2-yield-node-star-p n)
3779 (insert "*"))
3780 (when (js2-yield-node-value n)
3781 (insert " ")
3782 (js2-print-ast (js2-yield-node-value n) 0)))
3783
3784 (defstruct (js2-paren-node
3785 (:include js2-node)
3786 (:constructor nil)
3787 (:constructor make-js2-paren-node (&key (type js2-LP)
3788 (pos js2-ts-cursor)
3789 len expr)))
3790 "AST node for a parenthesized expression.
3791 In particular, used when the parens are syntactically optional,
3792 as opposed to required parens such as those enclosing an if-conditional."
3793 expr) ; `js2-node'
3794
3795 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3796 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3797
3798 (defun js2-visit-paren-node (n v)
3799 (js2-visit-ast (js2-paren-node-expr n) v))
3800
3801 (defun js2-print-paren-node (n i)
3802 (insert (js2-make-pad i))
3803 (insert "(")
3804 (js2-print-ast (js2-paren-node-expr n) 0)
3805 (insert ")"))
3806
3807 (defstruct (js2-comp-node
3808 (:include js2-scope)
3809 (:constructor nil)
3810 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3811 (pos js2-ts-cursor)
3812 len result
3813 loops filters
3814 form)))
3815 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3816 result ; result expression (just after left-bracket)
3817 loops ; a Lisp list of `js2-comp-loop-node'
3818 filters ; a Lisp list of guard/filter expressions
3819 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3820 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3821 )
3822
3823 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3824 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3825
3826 (defun js2-visit-comp-node (n v)
3827 (js2-visit-ast (js2-comp-node-result n) v)
3828 (dolist (l (js2-comp-node-loops n))
3829 (js2-visit-ast l v))
3830 (dolist (f (js2-comp-node-filters n))
3831 (js2-visit-ast f v)))
3832
3833 (defun js2-print-comp-node (n i)
3834 (let ((pad (js2-make-pad i))
3835 (result (js2-comp-node-result n))
3836 (loops (js2-comp-node-loops n))
3837 (filters (js2-comp-node-filters n))
3838 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3839 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3840 (insert pad (if gen-p "(" "["))
3841 (when legacy-p
3842 (js2-print-ast result 0))
3843 (dolist (l loops)
3844 (when legacy-p
3845 (insert " "))
3846 (js2-print-ast l 0)
3847 (unless legacy-p
3848 (insert " ")))
3849 (dolist (f filters)
3850 (when legacy-p
3851 (insert " "))
3852 (insert "if (")
3853 (js2-print-ast f 0)
3854 (insert ")")
3855 (unless legacy-p
3856 (insert " ")))
3857 (unless legacy-p
3858 (js2-print-ast result 0))
3859 (insert (if gen-p ")" "]"))))
3860
3861 (defstruct (js2-comp-loop-node
3862 (:include js2-for-in-node)
3863 (:constructor nil)
3864 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3865 (pos js2-ts-cursor)
3866 len iterator
3867 object in-pos
3868 foreach-p
3869 each-pos
3870 forof-p
3871 lp rp)))
3872 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3873
3874 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3875 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3876
3877 (defun js2-visit-comp-loop (n v)
3878 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3879 (js2-visit-ast (js2-comp-loop-node-object n) v))
3880
3881 (defun js2-print-comp-loop (n _i)
3882 (insert "for ")
3883 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3884 (insert "(")
3885 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3886 (insert (if (js2-comp-loop-node-forof-p n)
3887 " of " " in "))
3888 (js2-print-ast (js2-comp-loop-node-object n) 0)
3889 (insert ")"))
3890
3891 (defstruct (js2-empty-expr-node
3892 (:include js2-node)
3893 (:constructor nil)
3894 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3895 (pos (js2-current-token-beg))
3896 len)))
3897 "AST node for an empty expression.")
3898
3899 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3900 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3901
3902 (defstruct (js2-xml-node
3903 (:include js2-block-node)
3904 (:constructor nil)
3905 (:constructor make-js2-xml-node (&key (type js2-XML)
3906 (pos (js2-current-token-beg))
3907 len kids)))
3908 "AST node for initial parse of E4X literals.
3909 The kids field is a list of XML fragments, each a `js2-string-node' or
3910 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3911
3912 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3913 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3914
3915 (defun js2-print-xml-node (n i)
3916 (dolist (kid (js2-xml-node-kids n))
3917 (js2-print-ast kid i)))
3918
3919 (defstruct (js2-xml-js-expr-node
3920 (:include js2-xml-node)
3921 (:constructor nil)
3922 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3923 (pos js2-ts-cursor)
3924 len expr)))
3925 "AST node for an embedded JavaScript {expression} in an E4X literal.
3926 The start and end fields correspond to the curly-braces."
3927 expr) ; a `js2-expr-node' of some sort
3928
3929 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3930 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3931
3932 (defun js2-visit-xml-js-expr (n v)
3933 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3934
3935 (defun js2-print-xml-js-expr (n i)
3936 (insert (js2-make-pad i))
3937 (insert "{")
3938 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3939 (insert "}"))
3940
3941 (defstruct (js2-xml-dot-query-node
3942 (:include js2-infix-node)
3943 (:constructor nil)
3944 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3945 (pos js2-ts-cursor)
3946 op-pos len left
3947 right rp)))
3948 "AST node for an E4X foo.(bar) filter expression.
3949 Note that the left-paren is automatically the character immediately
3950 following the dot (.) in the operator. No whitespace is permitted
3951 between the dot and the lp by the scanner."
3952 rp)
3953
3954 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3955 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3956
3957 (defun js2-print-xml-dot-query (n i)
3958 (insert (js2-make-pad i))
3959 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3960 (insert ".(")
3961 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3962 (insert ")"))
3963
3964 (defstruct (js2-xml-ref-node
3965 (:include js2-node)
3966 (:constructor nil)) ; abstract
3967 "Base type for E4X XML attribute-access or property-get expressions.
3968 Such expressions can take a variety of forms. The general syntax has
3969 three parts:
3970
3971 - (optional) an @ (specifying an attribute access)
3972 - (optional) a namespace (a `js2-name-node') and double-colon
3973 - (required) either a `js2-name-node' or a bracketed [expression]
3974
3975 The property-name expressions (examples: ns::name, @name) are
3976 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3977 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3978
3979 This node type (or more specifically, its subclasses) will sometimes
3980 be the right-hand child of a `js2-prop-get-node' or a
3981 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3982 The `js2-xml-ref-node' may also be a standalone primary expression with
3983 no explicit target, which is valid in certain expression contexts such as
3984
3985 company..employee.(@id < 100)
3986
3987 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3988 expression whose parent is a `js2-xml-dot-query-node'."
3989 namespace
3990 at-pos
3991 colon-pos)
3992
3993 (defsubst js2-xml-ref-node-attr-access-p (node)
3994 "Return non-nil if this expression began with an @-token."
3995 (and (numberp (js2-xml-ref-node-at-pos node))
3996 (plusp (js2-xml-ref-node-at-pos node))))
3997
3998 (defstruct (js2-xml-prop-ref-node
3999 (:include js2-xml-ref-node)
4000 (:constructor nil)
4001 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4002 (pos (js2-current-token-beg))
4003 len propname
4004 namespace at-pos
4005 colon-pos)))
4006 "AST node for an E4X XML [expr] property-ref expression.
4007 The JavaScript syntax is an optional @, an optional ns::, and a name.
4008
4009 [ '@' ] [ name '::' ] name
4010
4011 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4012 @ns::*, @*::attr, @*::*, and @*.
4013
4014 The node starts at the @ token, if present. Otherwise it starts at the
4015 namespace name. The node bounds extend through the closing right-bracket,
4016 or if it is missing due to a syntax error, through the end of the index
4017 expression."
4018 propname)
4019
4020 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4021 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4022
4023 (defun js2-visit-xml-prop-ref-node (n v)
4024 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4025 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4026
4027 (defun js2-print-xml-prop-ref-node (n i)
4028 (insert (js2-make-pad i))
4029 (if (js2-xml-ref-node-attr-access-p n)
4030 (insert "@"))
4031 (when (js2-xml-prop-ref-node-namespace n)
4032 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4033 (insert "::"))
4034 (if (js2-xml-prop-ref-node-propname n)
4035 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4036
4037 (defstruct (js2-xml-elem-ref-node
4038 (:include js2-xml-ref-node)
4039 (:constructor nil)
4040 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4041 (pos (js2-current-token-beg))
4042 len expr lb rb
4043 namespace at-pos
4044 colon-pos)))
4045 "AST node for an E4X XML [expr] member-ref expression.
4046 Syntax:
4047
4048 [ '@' ] [ name '::' ] '[' expr ']'
4049
4050 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4051
4052 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4053 is not a legal E4X XML element-ref expression, since it's already used
4054 for standard JavaScript element-get array indexing. Hence, a
4055 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4056 non-nil namespace node, or both.
4057
4058 The node starts at the @ token, if present. Otherwise it starts
4059 at the namespace name. The node bounds extend through the closing
4060 right-bracket, or if it is missing due to a syntax error, through the
4061 end of the index expression."
4062 expr ; the bracketed index expression
4063 lb
4064 rb)
4065
4066 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4067 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4068
4069 (defun js2-visit-xml-elem-ref-node (n v)
4070 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4071 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4072
4073 (defun js2-print-xml-elem-ref-node (n i)
4074 (insert (js2-make-pad i))
4075 (if (js2-xml-ref-node-attr-access-p n)
4076 (insert "@"))
4077 (when (js2-xml-elem-ref-node-namespace n)
4078 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4079 (insert "::"))
4080 (insert "[")
4081 (if (js2-xml-elem-ref-node-expr n)
4082 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4083 (insert "]"))
4084
4085 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4086
4087 (defstruct (js2-xml-start-tag-node
4088 (:include js2-xml-node)
4089 (:constructor nil)
4090 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4091 (pos js2-ts-cursor)
4092 len name attrs kids
4093 empty-p)))
4094 "AST node for an XML start-tag. Not currently used.
4095 The `kids' field is a Lisp list of child content nodes."
4096 name ; a `js2-xml-name-node'
4097 attrs ; a Lisp list of `js2-xml-attr-node'
4098 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4099
4100 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4101 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4102
4103 (defun js2-visit-xml-start-tag (n v)
4104 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4105 (dolist (attr (js2-xml-start-tag-node-attrs n))
4106 (js2-visit-ast attr v))
4107 (js2-visit-block n v))
4108
4109 (defun js2-print-xml-start-tag (n i)
4110 (insert (js2-make-pad i) "<")
4111 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4112 (when (js2-xml-start-tag-node-attrs n)
4113 (insert " ")
4114 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4115 (insert ">"))
4116
4117 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4118 ;; and add the end-tag to the kids list of the parent as well.
4119 (defstruct (js2-xml-end-tag-node
4120 (:include js2-xml-node)
4121 (:constructor nil)
4122 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4123 (pos js2-ts-cursor)
4124 len name)))
4125 "AST node for an XML end-tag. Not currently used."
4126 name) ; a `js2-xml-name-node'
4127
4128 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4129 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4130
4131 (defun js2-visit-xml-end-tag (n v)
4132 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4133
4134 (defun js2-print-xml-end-tag (n i)
4135 (insert (js2-make-pad i))
4136 (insert "</")
4137 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4138 (insert ">"))
4139
4140 (defstruct (js2-xml-name-node
4141 (:include js2-xml-node)
4142 (:constructor nil)
4143 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4144 (pos js2-ts-cursor)
4145 len namespace kids)))
4146 "AST node for an E4X XML name. Not currently used.
4147 Any XML name can be qualified with a namespace, hence the namespace field.
4148 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4149 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4150 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4151 namespace) ; a `js2-string-node'
4152
4153 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4154 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4155
4156 (defun js2-visit-xml-name-node (n v)
4157 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4158
4159 (defun js2-print-xml-name-node (n i)
4160 (insert (js2-make-pad i))
4161 (when (js2-xml-name-node-namespace n)
4162 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4163 (insert "::"))
4164 (dolist (kid (js2-xml-name-node-kids n))
4165 (js2-print-ast kid 0)))
4166
4167 (defstruct (js2-xml-pi-node
4168 (:include js2-xml-node)
4169 (:constructor nil)
4170 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4171 (pos js2-ts-cursor)
4172 len name attrs)))
4173 "AST node for an E4X XML processing instruction. Not currently used."
4174 name ; a `js2-xml-name-node'
4175 attrs) ; a list of `js2-xml-attr-node'
4176
4177 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4178 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4179
4180 (defun js2-visit-xml-pi-node (n v)
4181 (js2-visit-ast (js2-xml-pi-node-name n) v)
4182 (dolist (attr (js2-xml-pi-node-attrs n))
4183 (js2-visit-ast attr v)))
4184
4185 (defun js2-print-xml-pi-node (n i)
4186 (insert (js2-make-pad i) "<?")
4187 (js2-print-ast (js2-xml-pi-node-name n))
4188 (when (js2-xml-pi-node-attrs n)
4189 (insert " ")
4190 (js2-print-list (js2-xml-pi-node-attrs n)))
4191 (insert "?>"))
4192
4193 (defstruct (js2-xml-cdata-node
4194 (:include js2-xml-node)
4195 (:constructor nil)
4196 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4197 (pos js2-ts-cursor)
4198 len content)))
4199 "AST node for a CDATA escape section. Not currently used."
4200 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4201
4202 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4203 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4204
4205 (defun js2-visit-xml-cdata-node (n v)
4206 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4207
4208 (defun js2-print-xml-cdata-node (n i)
4209 (insert (js2-make-pad i))
4210 (js2-print-ast (js2-xml-cdata-node-content n)))
4211
4212 (defstruct (js2-xml-attr-node
4213 (:include js2-xml-node)
4214 (:constructor nil)
4215 (:constructor make-js2-attr-node (&key (type js2-XML)
4216 (pos js2-ts-cursor)
4217 len name value
4218 eq-pos quote-type)))
4219 "AST node representing a foo='bar' XML attribute value. Not yet used."
4220 name ; a `js2-xml-name-node'
4221 value ; a `js2-xml-name-node'
4222 eq-pos ; buffer position of "=" sign
4223 quote-type) ; 'single or 'double
4224
4225 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4226 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4227
4228 (defun js2-visit-xml-attr-node (n v)
4229 (js2-visit-ast (js2-xml-attr-node-name n) v)
4230 (js2-visit-ast (js2-xml-attr-node-value n) v))
4231
4232 (defun js2-print-xml-attr-node (n i)
4233 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4234 "'"
4235 "\"")))
4236 (insert (js2-make-pad i))
4237 (js2-print-ast (js2-xml-attr-node-name n) 0)
4238 (insert "=" quote)
4239 (js2-print-ast (js2-xml-attr-node-value n) 0)
4240 (insert quote)))
4241
4242 (defstruct (js2-xml-text-node
4243 (:include js2-xml-node)
4244 (:constructor nil)
4245 (:constructor make-js2-text-node (&key (type js2-XML)
4246 (pos js2-ts-cursor)
4247 len content)))
4248 "AST node for an E4X XML text node. Not currently used."
4249 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4250
4251 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4252 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4253
4254 (defun js2-visit-xml-text-node (n v)
4255 (js2-visit-ast (js2-xml-text-node-content n) v))
4256
4257 (defun js2-print-xml-text-node (n i)
4258 (insert (js2-make-pad i))
4259 (dolist (kid (js2-xml-text-node-content n))
4260 (js2-print-ast kid)))
4261
4262 (defstruct (js2-xml-comment-node
4263 (:include js2-xml-node)
4264 (:constructor nil)
4265 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4266 (pos js2-ts-cursor)
4267 len)))
4268 "AST node for E4X XML comment. Not currently used.")
4269
4270 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4271 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4272
4273 (defun js2-print-xml-comment (n i)
4274 (insert (js2-make-pad i)
4275 (js2-node-string n)))
4276
4277 ;;; Node utilities
4278
4279 (defsubst js2-node-line (n)
4280 "Fetch the source line number at the start of node N.
4281 This is O(n) in the length of the source buffer; use prudently."
4282 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4283
4284 (defsubst js2-block-node-kid (n i)
4285 "Return child I of node N, or nil if there aren't that many."
4286 (nth i (js2-block-node-kids n)))
4287
4288 (defsubst js2-block-node-first (n)
4289 "Return first child of block node N, or nil if there is none."
4290 (first (js2-block-node-kids n)))
4291
4292 (defun js2-node-root (n)
4293 "Return the root of the AST containing N.
4294 If N has no parent pointer, returns N."
4295 (let ((parent (js2-node-parent n)))
4296 (if parent
4297 (js2-node-root parent)
4298 n)))
4299
4300 (defsubst js2-node-short-name (n)
4301 "Return the short name of node N as a string, e.g. `js2-if-node'."
4302 (substring (symbol-name (aref n 0))
4303 (length "cl-struct-")))
4304
4305 (defun js2-node-child-list (node)
4306 "Return the child list for NODE, a Lisp list of nodes.
4307 Works for block nodes, array nodes, obj literals, funarg lists,
4308 var decls and try nodes (for catch clauses). Note that you should call
4309 `js2-block-node-kids' on the function body for the body statements.
4310 Returns nil for zero-length child lists or unsupported nodes."
4311 (cond
4312 ((js2-function-node-p node)
4313 (js2-function-node-params node))
4314 ((js2-block-node-p node)
4315 (js2-block-node-kids node))
4316 ((js2-try-node-p node)
4317 (js2-try-node-catch-clauses node))
4318 ((js2-array-node-p node)
4319 (js2-array-node-elems node))
4320 ((js2-object-node-p node)
4321 (js2-object-node-elems node))
4322 ((js2-call-node-p node)
4323 (js2-call-node-args node))
4324 ((js2-new-node-p node)
4325 (js2-new-node-args node))
4326 ((js2-var-decl-node-p node)
4327 (js2-var-decl-node-kids node))
4328 (t
4329 nil)))
4330
4331 (defun js2-node-set-child-list (node kids)
4332 "Set the child list for NODE to KIDS."
4333 (cond
4334 ((js2-function-node-p node)
4335 (setf (js2-function-node-params node) kids))
4336 ((js2-block-node-p node)
4337 (setf (js2-block-node-kids node) kids))
4338 ((js2-try-node-p node)
4339 (setf (js2-try-node-catch-clauses node) kids))
4340 ((js2-array-node-p node)
4341 (setf (js2-array-node-elems node) kids))
4342 ((js2-object-node-p node)
4343 (setf (js2-object-node-elems node) kids))
4344 ((js2-call-node-p node)
4345 (setf (js2-call-node-args node) kids))
4346 ((js2-new-node-p node)
4347 (setf (js2-new-node-args node) kids))
4348 ((js2-var-decl-node-p node)
4349 (setf (js2-var-decl-node-kids node) kids))
4350 (t
4351 (error "Unsupported node type: %s" (js2-node-short-name node))))
4352 kids)
4353
4354 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4355 (defconst js2-paren-expr-nodes
4356 '(cl-struct-js2-comp-loop-node
4357 cl-struct-js2-comp-node
4358 cl-struct-js2-call-node
4359 cl-struct-js2-catch-node
4360 cl-struct-js2-do-node
4361 cl-struct-js2-elem-get-node
4362 cl-struct-js2-for-in-node
4363 cl-struct-js2-for-node
4364 cl-struct-js2-function-node
4365 cl-struct-js2-if-node
4366 cl-struct-js2-let-node
4367 cl-struct-js2-new-node
4368 cl-struct-js2-paren-node
4369 cl-struct-js2-switch-node
4370 cl-struct-js2-while-node
4371 cl-struct-js2-with-node
4372 cl-struct-js2-xml-dot-query-node)
4373 "Node types that can have a parenthesized child expression.
4374 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4375
4376 (defsubst js2-paren-expr-node-p (node)
4377 "Return t for nodes that typically have a parenthesized child expression.
4378 Useful for computing the indentation anchors for arg-lists and conditions.
4379 Note that it may return a false positive, for instance when NODE is
4380 a `js2-new-node' and there are no arguments or parentheses."
4381 (memq (aref node 0) js2-paren-expr-nodes))
4382
4383 ;; Fake polymorphism... yech.
4384 (defun js2-node-lp (node)
4385 "Return relative left-paren position for NODE, if applicable.
4386 For `js2-elem-get-node' structs, returns left-bracket position.
4387 Note that the position may be nil in the case of a parse error."
4388 (cond
4389 ((js2-elem-get-node-p node)
4390 (js2-elem-get-node-lb node))
4391 ((js2-loop-node-p node)
4392 (js2-loop-node-lp node))
4393 ((js2-function-node-p node)
4394 (js2-function-node-lp node))
4395 ((js2-if-node-p node)
4396 (js2-if-node-lp node))
4397 ((js2-new-node-p node)
4398 (js2-new-node-lp node))
4399 ((js2-call-node-p node)
4400 (js2-call-node-lp node))
4401 ((js2-paren-node-p node)
4402 0)
4403 ((js2-switch-node-p node)
4404 (js2-switch-node-lp node))
4405 ((js2-catch-node-p node)
4406 (js2-catch-node-lp node))
4407 ((js2-let-node-p node)
4408 (js2-let-node-lp node))
4409 ((js2-comp-node-p node)
4410 0)
4411 ((js2-with-node-p node)
4412 (js2-with-node-lp node))
4413 ((js2-xml-dot-query-node-p node)
4414 (1+ (js2-infix-node-op-pos node)))
4415 (t
4416 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4417
4418 ;; Fake polymorphism... blech.
4419 (defun js2-node-rp (node)
4420 "Return relative right-paren position for NODE, if applicable.
4421 For `js2-elem-get-node' structs, returns right-bracket position.
4422 Note that the position may be nil in the case of a parse error."
4423 (cond
4424 ((js2-elem-get-node-p node)
4425 (js2-elem-get-node-rb node))
4426 ((js2-loop-node-p node)
4427 (js2-loop-node-rp node))
4428 ((js2-function-node-p node)
4429 (js2-function-node-rp node))
4430 ((js2-if-node-p node)
4431 (js2-if-node-rp node))
4432 ((js2-new-node-p node)
4433 (js2-new-node-rp node))
4434 ((js2-call-node-p node)
4435 (js2-call-node-rp node))
4436 ((js2-paren-node-p node)
4437 (1- (js2-node-len node)))
4438 ((js2-switch-node-p node)
4439 (js2-switch-node-rp node))
4440 ((js2-catch-node-p node)
4441 (js2-catch-node-rp node))
4442 ((js2-let-node-p node)
4443 (js2-let-node-rp node))
4444 ((js2-comp-node-p node)
4445 (1- (js2-node-len node)))
4446 ((js2-with-node-p node)
4447 (js2-with-node-rp node))
4448 ((js2-xml-dot-query-node-p node)
4449 (1+ (js2-xml-dot-query-node-rp node)))
4450 (t
4451 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4452
4453 (defsubst js2-node-first-child (node)
4454 "Return the first element of `js2-node-child-list' for NODE."
4455 (car (js2-node-child-list node)))
4456
4457 (defsubst js2-node-last-child (node)
4458 "Return the last element of `js2-node-last-child' for NODE."
4459 (car (last (js2-node-child-list node))))
4460
4461 (defun js2-node-prev-sibling (node)
4462 "Return the previous statement in parent.
4463 Works for parents supported by `js2-node-child-list'.
4464 Returns nil if NODE is not in the parent, or PARENT is
4465 not a supported node, or if NODE is the first child."
4466 (let* ((p (js2-node-parent node))
4467 (kids (js2-node-child-list p))
4468 (sib (car kids)))
4469 (while (and kids
4470 (not (eq node (cadr kids))))
4471 (setq kids (cdr kids)
4472 sib (car kids)))
4473 sib))
4474
4475 (defun js2-node-next-sibling (node)
4476 "Return the next statement in parent block.
4477 Returns nil if NODE is not in the block, or PARENT is not
4478 a block node, or if NODE is the last statement."
4479 (let* ((p (js2-node-parent node))
4480 (kids (js2-node-child-list p)))
4481 (while (and kids
4482 (not (eq node (car kids))))
4483 (setq kids (cdr kids)))
4484 (cadr kids)))
4485
4486 (defun js2-node-find-child-before (pos parent &optional after)
4487 "Find the last child that starts before POS in parent.
4488 If AFTER is non-nil, returns first child starting after POS.
4489 POS is an absolute buffer position. PARENT is any node
4490 supported by `js2-node-child-list'.
4491 Returns nil if no applicable child is found."
4492 (let ((kids (if (js2-function-node-p parent)
4493 (js2-block-node-kids (js2-function-node-body parent))
4494 (js2-node-child-list parent)))
4495 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4496 (js2-function-node-body parent)
4497 parent)))
4498 kid result fn
4499 (continue t))
4500 (setq fn (if after '>= '<))
4501 (while (and kids continue)
4502 (setq kid (car kids))
4503 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4504 (setq result kid
4505 continue (not after))
4506 (setq continue after))
4507 (setq kids (cdr kids)))
4508 result))
4509
4510 (defun js2-node-find-child-after (pos parent)
4511 "Find first child that starts after POS in parent.
4512 POS is an absolute buffer position. PARENT is any node
4513 supported by `js2-node-child-list'.
4514 Returns nil if no applicable child is found."
4515 (js2-node-find-child-before pos parent 'after))
4516
4517 (defun js2-node-replace-child (pos parent new-node)
4518 "Replace node at index POS in PARENT with NEW-NODE.
4519 Only works for parents supported by `js2-node-child-list'."
4520 (let ((kids (js2-node-child-list parent))
4521 (i 0))
4522 (while (< i pos)
4523 (setq kids (cdr kids)
4524 i (1+ i)))
4525 (setcar kids new-node)
4526 (js2-node-add-children parent new-node)))
4527
4528 (defun js2-node-buffer (n)
4529 "Return the buffer associated with AST N.
4530 Returns nil if the buffer is not set as a property on the root
4531 node, or if parent links were not recorded during parsing."
4532 (let ((root (js2-node-root n)))
4533 (and root
4534 (js2-ast-root-p root)
4535 (js2-ast-root-buffer root))))
4536
4537 (defun js2-block-node-push (n kid)
4538 "Push js2-node KID onto the end of js2-block-node N's child list.
4539 KID is always added to the -end- of the kids list.
4540 Function also calls `js2-node-add-children' to add the parent link."
4541 (let ((kids (js2-node-child-list n)))
4542 (if kids
4543 (setcdr kids (nconc (cdr kids) (list kid)))
4544 (js2-node-set-child-list n (list kid)))
4545 (js2-node-add-children n kid)))
4546
4547 (defun js2-node-string (node)
4548 (with-current-buffer (or (js2-node-buffer node)
4549 (error "No buffer available for node %s" node))
4550 (let ((pos (js2-node-abs-pos node)))
4551 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4552
4553 ;; Container for storing the node we're looking for in a traversal.
4554 (js2-deflocal js2-discovered-node nil)
4555
4556 ;; Keep track of absolute node position during traversals.
4557 (js2-deflocal js2-visitor-offset nil)
4558
4559 (js2-deflocal js2-node-search-point nil)
4560
4561 (when js2-mode-dev-mode-p
4562 (defun js2-find-node-at-point ()
4563 (interactive)
4564 (let ((node (js2-node-at-point)))
4565 (message "%s" (or node "No node found at point"))))
4566 (defun js2-node-name-at-point ()
4567 (interactive)
4568 (let ((node (js2-node-at-point)))
4569 (message "%s" (if node
4570 (js2-node-short-name node)
4571 "No node found at point.")))))
4572
4573 (defun js2-node-at-point (&optional pos skip-comments)
4574 "Return AST node at POS, a buffer position, defaulting to current point.
4575 The `js2-mode-ast' variable must be set to the current parse tree.
4576 Signals an error if the AST (`js2-mode-ast') is nil.
4577 Always returns a node - if it can't find one, it returns the root.
4578 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4579 (let ((ast js2-mode-ast)
4580 result)
4581 (unless ast
4582 (error "No JavaScript AST available"))
4583 ;; Look through comments first, since they may be inside nodes that
4584 ;; would otherwise report a match.
4585 (setq pos (or pos (point))
4586 result (if (> pos (js2-node-abs-end ast))
4587 ast
4588 (if (not skip-comments)
4589 (js2-comment-at-point pos))))
4590 (unless result
4591 (setq js2-discovered-node nil
4592 js2-visitor-offset 0
4593 js2-node-search-point pos)
4594 (unwind-protect
4595 (catch 'js2-visit-done
4596 (js2-visit-ast ast #'js2-node-at-point-visitor))
4597 (setq js2-visitor-offset nil
4598 js2-node-search-point nil))
4599 (setq result js2-discovered-node))
4600 ;; may have found a comment beyond end of last child node,
4601 ;; since visiting the ast-root looks at the comment-list last.
4602 (if (and skip-comments
4603 (js2-comment-node-p result))
4604 (setq result nil))
4605 (or result js2-mode-ast)))
4606
4607 (defun js2-node-at-point-visitor (node end-p)
4608 (let ((rel-pos (js2-node-pos node))
4609 abs-pos
4610 abs-end
4611 (point js2-node-search-point))
4612 (cond
4613 (end-p
4614 ;; this evaluates to a non-nil return value, even if it's zero
4615 (decf js2-visitor-offset rel-pos))
4616 ;; we already looked for comments before visiting, and don't want them now
4617 ((js2-comment-node-p node)
4618 nil)
4619 (t
4620 (setq abs-pos (incf js2-visitor-offset rel-pos)
4621 ;; we only want to use the node if the point is before
4622 ;; the last character position in the node, so we decrement
4623 ;; the absolute end by 1.
4624 abs-end (+ abs-pos (js2-node-len node) -1))
4625 (cond
4626 ;; If this node starts after search-point, stop the search.
4627 ((> abs-pos point)
4628 (throw 'js2-visit-done nil))
4629 ;; If this node ends before the search-point, don't check kids.
4630 ((> point abs-end)
4631 nil)
4632 (t
4633 ;; Otherwise point is within this node, possibly in a child.
4634 (setq js2-discovered-node node)
4635 t)))))) ; keep processing kids to look for more specific match
4636
4637 (defsubst js2-block-comment-p (node)
4638 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4639 (and (js2-comment-node-p node)
4640 (memq (js2-comment-node-format node) '(jsdoc block))))
4641
4642 ;; TODO: put the comments in a vector and binary-search them instead
4643 (defun js2-comment-at-point (&optional pos)
4644 "Look through scanned comment nodes for one containing POS.
4645 POS is a buffer position that defaults to current point.
4646 Function returns nil if POS was not in any comment node."
4647 (let ((ast js2-mode-ast)
4648 (x (or pos (point)))
4649 beg end)
4650 (unless ast
4651 (error "No JavaScript AST available"))
4652 (catch 'done
4653 ;; Comments are stored in lexical order.
4654 (dolist (comment (js2-ast-root-comments ast) nil)
4655 (setq beg (js2-node-abs-pos comment)
4656 end (+ beg (js2-node-len comment)))
4657 (if (and (>= x beg)
4658 (<= x end))
4659 (throw 'done comment))))))
4660
4661 (defun js2-mode-find-parent-fn (node)
4662 "Find function enclosing NODE.
4663 Returns nil if NODE is not inside a function."
4664 (setq node (js2-node-parent node))
4665 (while (and node (not (js2-function-node-p node)))
4666 (setq node (js2-node-parent node)))
4667 (and (js2-function-node-p node) node))
4668
4669 (defun js2-mode-find-enclosing-fn (node)
4670 "Find function or root enclosing NODE."
4671 (if (js2-ast-root-p node)
4672 node
4673 (setq node (js2-node-parent node))
4674 (while (not (or (js2-ast-root-p node)
4675 (js2-function-node-p node)))
4676 (setq node (js2-node-parent node)))
4677 node))
4678
4679 (defun js2-mode-find-enclosing-node (beg end)
4680 "Find node fully enclosing BEG and END."
4681 (let ((node (js2-node-at-point beg))
4682 pos
4683 (continue t))
4684 (while continue
4685 (if (or (js2-ast-root-p node)
4686 (and
4687 (<= (setq pos (js2-node-abs-pos node)) beg)
4688 (>= (+ pos (js2-node-len node)) end)))
4689 (setq continue nil)
4690 (setq node (js2-node-parent node))))
4691 node))
4692
4693 (defun js2-node-parent-script-or-fn (node)
4694 "Find script or function immediately enclosing NODE.
4695 If NODE is the ast-root, returns nil."
4696 (if (js2-ast-root-p node)
4697 nil
4698 (setq node (js2-node-parent node))
4699 (while (and node (not (or (js2-function-node-p node)
4700 (js2-script-node-p node))))
4701 (setq node (js2-node-parent node)))
4702 node))
4703
4704 (defun js2-node-is-descendant (node ancestor)
4705 "Return t if NODE is a descendant of ANCESTOR."
4706 (while (and node
4707 (not (eq node ancestor)))
4708 (setq node (js2-node-parent node)))
4709 node)
4710
4711 ;;; visitor infrastructure
4712
4713 (defun js2-visit-none (_node _callback)
4714 "Visitor for AST node that have no node children."
4715 nil)
4716
4717 (defun js2-print-none (_node _indent)
4718 "Visitor for AST node with no printed representation.")
4719
4720 (defun js2-print-body (node indent)
4721 "Print a statement, or a block without braces."
4722 (if (js2-block-node-p node)
4723 (dolist (kid (js2-block-node-kids node))
4724 (js2-print-ast kid indent))
4725 (js2-print-ast node indent)))
4726
4727 (defun js2-print-list (args &optional delimiter)
4728 (loop with len = (length args)
4729 for arg in args
4730 for count from 1
4731 do
4732 (when arg (js2-print-ast arg 0))
4733 (if (< count len)
4734 (insert (or delimiter ", ")))))
4735
4736 (defun js2-print-tree (ast)
4737 "Prints an AST to the current buffer.
4738 Makes `js2-ast-parent-nodes' available to the printer functions."
4739 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4740 (js2-print-ast ast)))
4741
4742 (defun js2-print-ast (node &optional indent)
4743 "Helper function for printing AST nodes.
4744 Requires `js2-ast-parent-nodes' to be non-nil.
4745 You should use `js2-print-tree' instead of this function."
4746 (let ((printer (get (aref node 0) 'js2-printer))
4747 (i (or indent 0)))
4748 ;; TODO: wedge comments in here somewhere
4749 (if printer
4750 (funcall printer node i))))
4751
4752 (defconst js2-side-effecting-tokens
4753 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4754 (dolist (tt (list js2-ASSIGN
4755 js2-ASSIGN_ADD
4756 js2-ASSIGN_BITAND
4757 js2-ASSIGN_BITOR
4758 js2-ASSIGN_BITXOR
4759 js2-ASSIGN_DIV
4760 js2-ASSIGN_LSH
4761 js2-ASSIGN_MOD
4762 js2-ASSIGN_MUL
4763 js2-ASSIGN_RSH
4764 js2-ASSIGN_SUB
4765 js2-ASSIGN_URSH
4766 js2-BLOCK
4767 js2-BREAK
4768 js2-CALL
4769 js2-CATCH
4770 js2-CATCH_SCOPE
4771 js2-CLASS
4772 js2-CONST
4773 js2-CONTINUE
4774 js2-DEBUGGER
4775 js2-DEC
4776 js2-DELPROP
4777 js2-DEL_REF
4778 js2-DO
4779 js2-ELSE
4780 js2-EMPTY
4781 js2-ENTERWITH
4782 js2-EXPORT
4783 js2-EXPR_RESULT
4784 js2-FINALLY
4785 js2-FOR
4786 js2-FUNCTION
4787 js2-GOTO
4788 js2-IF
4789 js2-IFEQ
4790 js2-IFNE
4791 js2-IMPORT
4792 js2-INC
4793 js2-JSR
4794 js2-LABEL
4795 js2-LEAVEWITH
4796 js2-LET
4797 js2-LETEXPR
4798 js2-LOCAL_BLOCK
4799 js2-LOOP
4800 js2-NEW
4801 js2-REF_CALL
4802 js2-RETHROW
4803 js2-RETURN
4804 js2-RETURN_RESULT
4805 js2-SEMI
4806 js2-SETELEM
4807 js2-SETELEM_OP
4808 js2-SETNAME
4809 js2-SETPROP
4810 js2-SETPROP_OP
4811 js2-SETVAR
4812 js2-SET_REF
4813 js2-SET_REF_OP
4814 js2-SWITCH
4815 js2-TARGET
4816 js2-THROW
4817 js2-TRY
4818 js2-VAR
4819 js2-WHILE
4820 js2-WITH
4821 js2-WITHEXPR
4822 js2-YIELD))
4823 (aset tokens tt t))
4824 (if js2-instanceof-has-side-effects
4825 (aset tokens js2-INSTANCEOF t))
4826 tokens))
4827
4828 (defun js2-node-has-side-effects (node)
4829 "Return t if NODE has side effects."
4830 (when node ; makes it easier to handle malformed expressions
4831 (let ((tt (js2-node-type node)))
4832 (cond
4833 ;; This doubtless needs some work, since EXPR_VOID is used
4834 ;; in several ways in Rhino and I may not have caught them all.
4835 ;; I'll wait for people to notice incorrect warnings.
4836 ((and (= tt js2-EXPR_VOID)
4837 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4838 (let ((expr (js2-expr-stmt-node-expr node)))
4839 (or (js2-node-has-side-effects expr)
4840 (when (js2-string-node-p expr)
4841 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4842 ((= tt js2-COMMA)
4843 (js2-node-has-side-effects (js2-infix-node-right node)))
4844 ((or (= tt js2-AND)
4845 (= tt js2-OR))
4846 (or (js2-node-has-side-effects (js2-infix-node-right node))
4847 (js2-node-has-side-effects (js2-infix-node-left node))))
4848 ((= tt js2-HOOK)
4849 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4850 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4851 ((js2-paren-node-p node)
4852 (js2-node-has-side-effects (js2-paren-node-expr node)))
4853 ((= tt js2-ERROR) ; avoid cascaded error messages
4854 nil)
4855 (t
4856 (aref js2-side-effecting-tokens tt))))))
4857
4858 (defconst js2-stmt-node-types
4859 (list js2-BLOCK
4860 js2-BREAK
4861 js2-CONTINUE
4862 js2-DEFAULT ; e4x "default xml namespace" statement
4863 js2-DO
4864 js2-EXPR_RESULT
4865 js2-EXPR_VOID
4866 js2-FOR
4867 js2-IF
4868 js2-RETURN
4869 js2-SWITCH
4870 js2-THROW
4871 js2-TRY
4872 js2-WHILE
4873 js2-WITH)
4874 "Node types that only appear in statement contexts.
4875 The list does not include nodes that always appear as the child
4876 of another specific statement type, such as switch-cases,
4877 catch and finally blocks, and else-clauses. The list also excludes
4878 nodes like yield, let and var, which may appear in either expression
4879 or statement context, and in the latter context always have a
4880 `js2-expr-stmt-node' parent. Finally, the list does not include
4881 functions or scripts, which are treated separately from statements
4882 by the JavaScript parser and runtime.")
4883
4884 (defun js2-stmt-node-p (node)
4885 "Heuristic for figuring out if NODE is a statement.
4886 Some node types can appear in either an expression context or a
4887 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4888 For these node types in a statement context, the parent will be a
4889 `js2-expr-stmt-node'.
4890 Functions aren't included in the check."
4891 (memq (js2-node-type node) js2-stmt-node-types))
4892
4893 (defun js2-mode-find-first-stmt (node)
4894 "Search upward starting from NODE looking for a statement.
4895 For purposes of this function, a `js2-function-node' counts."
4896 (while (not (or (js2-stmt-node-p node)
4897 (js2-function-node-p node)))
4898 (setq node (js2-node-parent node)))
4899 node)
4900
4901 (defun js2-node-parent-stmt (node)
4902 "Return the node's first ancestor that is a statement.
4903 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4904 appearing in a statement context will have a parent that is a
4905 `js2-expr-stmt-node' that will be returned by this function."
4906 (let ((parent (js2-node-parent node)))
4907 (if (or (null parent)
4908 (js2-stmt-node-p parent)
4909 (and (js2-function-node-p parent)
4910 (not (eq (js2-function-node-form parent)
4911 'FUNCTION_EXPRESSION))))
4912 parent
4913 (js2-node-parent-stmt parent))))
4914
4915 ;; In the Mozilla Rhino sources, Roshan James writes:
4916 ;; Does consistent-return analysis on the function body when strict mode is
4917 ;; enabled.
4918 ;;
4919 ;; function (x) { return (x+1) }
4920 ;;
4921 ;; is ok, but
4922 ;;
4923 ;; function (x) { if (x < 0) return (x+1); }
4924 ;;
4925 ;; is not because the function can potentially return a value when the
4926 ;; condition is satisfied and if not, the function does not explicitly
4927 ;; return a value.
4928 ;;
4929 ;; This extends to checking mismatches such as "return" and "return <value>"
4930 ;; used in the same function. Warnings are not emitted if inconsistent
4931 ;; returns exist in code that can be statically shown to be unreachable.
4932 ;; Ex.
4933 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4934 ;;
4935 ;; emits no warning. However if the loop had a break statement, then a
4936 ;; warning would be emitted.
4937 ;;
4938 ;; The consistency analysis looks at control structures such as loops, ifs,
4939 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4940 ;; warns the user about an inconsistent set of termination possibilities.
4941 ;;
4942 ;; These flags enumerate the possible ways a statement/function can
4943 ;; terminate. These flags are used by endCheck() and by the Parser to
4944 ;; detect inconsistent return usage.
4945 ;;
4946 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4947 ;; able to execute (example: throw, continue)
4948 ;;
4949 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4950 ;; next one. Statement such as return dont. A compound statement may have
4951 ;; some branch that drops off control to the next statement.
4952 ;;
4953 ;; END_RETURNS indicates that the statement can return with no value.
4954 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4955 ;;
4956 ;; A compound statement such as
4957 ;; if (condition) {
4958 ;; return value;
4959 ;; }
4960 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4961
4962 (defconst js2-END_UNREACHED 0)
4963 (defconst js2-END_DROPS_OFF 1)
4964 (defconst js2-END_RETURNS 2)
4965 (defconst js2-END_RETURNS_VALUE 4)
4966 (defconst js2-END_YIELDS 8)
4967
4968 (defun js2-has-consistent-return-usage (node)
4969 "Check that every return usage in a function body is consistent.
4970 Returns t if the function satisfies strict mode requirement."
4971 (let ((n (js2-end-check node)))
4972 ;; either it doesn't return a value in any branch...
4973 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4974 ;; or it returns a value (or is unreached) at every branch
4975 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4976 js2-END_RETURNS
4977 js2-END_YIELDS)))))
4978
4979 (defun js2-end-check-if (node)
4980 "Ensure that return usage in then/else blocks is consistent.
4981 If there is no else block, then the return statement can fall through.
4982 Returns logical OR of END_* flags"
4983 (let ((th (js2-if-node-then-part node))
4984 (el (js2-if-node-else-part node)))
4985 (if (null th)
4986 js2-END_UNREACHED
4987 (logior (js2-end-check th) (if el
4988 (js2-end-check el)
4989 js2-END_DROPS_OFF)))))
4990
4991 (defun js2-end-check-switch (node)
4992 "Consistency of return statements is checked between the case statements.
4993 If there is no default, then the switch can fall through. If there is a
4994 default, we check to see if all code paths in the default return or if
4995 there is a code path that can fall through.
4996 Returns logical OR of END_* flags."
4997 (let ((rv js2-END_UNREACHED)
4998 default-case)
4999 ;; examine the cases
5000 (catch 'break
5001 (dolist (c (js2-switch-node-cases node))
5002 (if (js2-case-node-expr c)
5003 (js2-set-flag rv (js2-end-check-block c))
5004 (setq default-case c)
5005 (throw 'break nil))))
5006 ;; we don't care how the cases drop into each other
5007 (js2-clear-flag rv js2-END_DROPS_OFF)
5008 ;; examine the default
5009 (js2-set-flag rv (if default-case
5010 (js2-end-check default-case)
5011 js2-END_DROPS_OFF))
5012 rv))
5013
5014 (defun js2-end-check-try (node)
5015 "If the block has a finally, return consistency is checked in the
5016 finally block. If all code paths in the finally return, then the
5017 returns in the try-catch blocks don't matter. If there is a code path
5018 that does not return or if there is no finally block, the returns
5019 of the try and catch blocks are checked for mismatch.
5020 Returns logical OR of END_* flags."
5021 (let ((finally (js2-try-node-finally-block node))
5022 rv)
5023 ;; check the finally if it exists
5024 (setq rv (if finally
5025 (js2-end-check (js2-finally-node-body finally))
5026 js2-END_DROPS_OFF))
5027 ;; If the finally block always returns, then none of the returns
5028 ;; in the try or catch blocks matter.
5029 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5030 (js2-clear-flag rv js2-END_DROPS_OFF)
5031 ;; examine the try block
5032 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5033 ;; check each catch block
5034 (dolist (cb (js2-try-node-catch-clauses node))
5035 (js2-set-flag rv (js2-end-check cb))))
5036 rv))
5037
5038 (defun js2-end-check-loop (node)
5039 "Return statement in the loop body must be consistent.
5040 The default assumption for any kind of a loop is that it will eventually
5041 terminate. The only exception is a loop with a constant true condition.
5042 Code that follows such a loop is examined only if one can determine
5043 statically that there is a break out of the loop.
5044
5045 for(... ; ... ; ...) {}
5046 for(... in ... ) {}
5047 while(...) { }
5048 do { } while(...)
5049
5050 Returns logical OR of END_* flags."
5051 (let ((rv (js2-end-check (js2-loop-node-body node)))
5052 (condition (cond
5053 ((js2-while-node-p node)
5054 (js2-while-node-condition node))
5055 ((js2-do-node-p node)
5056 (js2-do-node-condition node))
5057 ((js2-for-node-p node)
5058 (js2-for-node-condition node)))))
5059
5060 ;; check to see if the loop condition is always true
5061 (if (and condition
5062 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5063 (js2-clear-flag rv js2-END_DROPS_OFF))
5064
5065 ;; look for effect of breaks
5066 (js2-set-flag rv (js2-node-get-prop node
5067 'CONTROL_BLOCK_PROP
5068 js2-END_UNREACHED))
5069 rv))
5070
5071 (defun js2-end-check-block (node)
5072 "A general block of code is examined statement by statement.
5073 If any statement (even a compound one) returns in all branches, then
5074 subsequent statements are not examined.
5075 Returns logical OR of END_* flags."
5076 (let* ((rv js2-END_DROPS_OFF)
5077 (kids (js2-block-node-kids node))
5078 (n (car kids)))
5079 ;; Check each statment. If the statement can continue onto the next
5080 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5081 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5082 (js2-clear-flag rv js2-END_DROPS_OFF)
5083 (js2-set-flag rv (js2-end-check n))
5084 (setq kids (cdr kids)
5085 n (car kids)))
5086 rv))
5087
5088 (defun js2-end-check-label (node)
5089 "A labeled statement implies that there may be a break to the label.
5090 The function processes the labeled statement and then checks the
5091 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5092 particular label.
5093 Returns logical OR of END_* flags."
5094 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5095 (logior rv (js2-node-get-prop node
5096 'CONTROL_BLOCK_PROP
5097 js2-END_UNREACHED))))
5098
5099 (defun js2-end-check-break (node)
5100 "When a break is encountered annotate the statement being broken
5101 out of by setting its CONTROL_BLOCK_PROP property.
5102 Returns logical OR of END_* flags."
5103 (and (js2-break-node-target node)
5104 (js2-node-set-prop (js2-break-node-target node)
5105 'CONTROL_BLOCK_PROP
5106 js2-END_DROPS_OFF))
5107 js2-END_UNREACHED)
5108
5109 (defun js2-end-check (node)
5110 "Examine the body of a function, doing a basic reachability analysis.
5111 Returns a combination of flags END_* flags that indicate
5112 how the function execution can terminate. These constitute only the
5113 pessimistic set of termination conditions. It is possible that at
5114 runtime certain code paths will never be actually taken. Hence this
5115 analysis will flag errors in cases where there may not be errors.
5116 Returns logical OR of END_* flags"
5117 (let (kid)
5118 (cond
5119 ((js2-break-node-p node)
5120 (js2-end-check-break node))
5121 ((js2-expr-stmt-node-p node)
5122 (if (setq kid (js2-expr-stmt-node-expr node))
5123 (js2-end-check kid)
5124 js2-END_DROPS_OFF))
5125 ((or (js2-continue-node-p node)
5126 (js2-throw-node-p node))
5127 js2-END_UNREACHED)
5128 ((js2-return-node-p node)
5129 (if (setq kid (js2-return-node-retval node))
5130 js2-END_RETURNS_VALUE
5131 js2-END_RETURNS))
5132 ((js2-loop-node-p node)
5133 (js2-end-check-loop node))
5134 ((js2-switch-node-p node)
5135 (js2-end-check-switch node))
5136 ((js2-labeled-stmt-node-p node)
5137 (js2-end-check-label node))
5138 ((js2-if-node-p node)
5139 (js2-end-check-if node))
5140 ((js2-try-node-p node)
5141 (js2-end-check-try node))
5142 ((js2-block-node-p node)
5143 (if (null (js2-block-node-kids node))
5144 js2-END_DROPS_OFF
5145 (js2-end-check-block node)))
5146 ((js2-yield-node-p node)
5147 js2-END_YIELDS)
5148 (t
5149 js2-END_DROPS_OFF))))
5150
5151 (defun js2-always-defined-boolean-p (node)
5152 "Check if NODE always evaluates to true or false in boolean context.
5153 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5154 nor always false."
5155 (let ((tt (js2-node-type node))
5156 num)
5157 (cond
5158 ((or (= tt js2-FALSE) (= tt js2-NULL))
5159 'ALWAYS_FALSE)
5160 ((= tt js2-TRUE)
5161 'ALWAYS_TRUE)
5162 ((= tt js2-NUMBER)
5163 (setq num (js2-number-node-num-value node))
5164 (if (and (not (eq num 0.0e+NaN))
5165 (not (zerop num)))
5166 'ALWAYS_TRUE
5167 'ALWAYS_FALSE))
5168 (t
5169 nil))))
5170
5171 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5172 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5173
5174 (defvar js2-tokens nil
5175 "List of all defined token names.") ; initialized in `js2-token-names'
5176
5177 (defconst js2-token-names
5178 (let* ((names (make-vector js2-num-tokens -1))
5179 (case-fold-search nil) ; only match js2-UPPER_CASE
5180 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5181 (loop for sym in syms
5182 for i from 0
5183 do
5184 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5185 (not (boundp sym)))
5186 (aset names (symbol-value sym) ; code, e.g. 152
5187 (downcase
5188 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5189 (push sym js2-tokens)))
5190 names)
5191 "Vector mapping int values to token string names, sans `js2-' prefix.")
5192
5193 (defun js2-tt-name (tok)
5194 "Return a string name for TOK, a token symbol or code.
5195 Signals an error if it's not a recognized token."
5196 (let ((code tok))
5197 (if (symbolp tok)
5198 (setq code (symbol-value tok)))
5199 (if (eq code -1)
5200 "ERROR"
5201 (if (and (numberp code)
5202 (not (minusp code))
5203 (< code js2-num-tokens))
5204 (aref js2-token-names code)
5205 (error "Invalid token: %s" code)))))
5206
5207 (defsubst js2-tt-sym (tok)
5208 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5209 (intern (js2-tt-name tok)))
5210
5211 (defconst js2-token-codes
5212 (let ((table (make-hash-table :test 'eq :size 256)))
5213 (loop for name across js2-token-names
5214 for sym = (intern (concat "js2-" (upcase name)))
5215 do
5216 (puthash sym (symbol-value sym) table))
5217 ;; clean up a few that are "wrong" in Rhino's token codes
5218 (puthash 'js2-DELETE js2-DELPROP table)
5219 table)
5220 "Hashtable mapping token type symbols to their bytecodes.")
5221
5222 (defsubst js2-tt-code (sym)
5223 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5224 (or (gethash sym js2-token-codes)
5225 (error "Invalid token symbol: %s " sym))) ; signal code bug
5226
5227 (defun js2-report-scan-error (msg &optional no-throw beg len)
5228 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5229 (js2-report-error msg nil
5230 (or beg (js2-current-token-beg))
5231 (or len (js2-current-token-len)))
5232 (unless no-throw
5233 (throw 'return js2-ERROR)))
5234
5235 (defun js2-set-string-from-buffer (token)
5236 "Set `string' and `end' slots for TOKEN, return the string."
5237 (setf (js2-token-end token) js2-ts-cursor
5238 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5239
5240 ;; TODO: could potentially avoid a lot of consing by allocating a
5241 ;; char buffer the way Rhino does.
5242 (defsubst js2-add-to-string (c)
5243 (push c js2-ts-string-buffer))
5244
5245 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5246 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5247 ;; any other character: when it's not part of the current token, we
5248 ;; unget it, allowing it to be read again by the following call.
5249 (defsubst js2-unget-char ()
5250 (decf js2-ts-cursor))
5251
5252 ;; Rhino distinguishes \r and \n line endings. We don't need to
5253 ;; because we only scan from Emacs buffers, which always use \n.
5254 (defun js2-get-char ()
5255 "Read and return the next character from the input buffer.
5256 Increments `js2-ts-lineno' if the return value is a newline char.
5257 Updates `js2-ts-cursor' to the point after the returned char.
5258 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5259 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5260 (let (c)
5261 ;; check for end of buffer
5262 (if (>= js2-ts-cursor (point-max))
5263 (setq js2-ts-hit-eof t
5264 js2-ts-cursor (1+ js2-ts-cursor)
5265 c js2-EOF_CHAR) ; return value
5266 ;; otherwise read next char
5267 (setq c (char-before (incf js2-ts-cursor)))
5268 ;; if we read a newline, update counters
5269 (if (= c ?\n)
5270 (setq js2-ts-line-start js2-ts-cursor
5271 js2-ts-lineno (1+ js2-ts-lineno)))
5272 ;; TODO: skip over format characters
5273 c)))
5274
5275 (defun js2-read-unicode-escape ()
5276 "Read a \\uNNNN sequence from the input.
5277 Assumes the ?\ and ?u have already been read.
5278 Returns the unicode character, or nil if it wasn't a valid character.
5279 Doesn't change the values of any scanner variables."
5280 ;; I really wish I knew a better way to do this, but I can't
5281 ;; find the Emacs function that takes a 16-bit int and converts
5282 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5283 ;; Have to first check that it's 4 hex characters or it may stop
5284 ;; the read early.
5285 (ignore-errors
5286 (let ((s (buffer-substring-no-properties js2-ts-cursor
5287 (+ 4 js2-ts-cursor))))
5288 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5289 (read (concat "?\\u" s))))))
5290
5291 (defun js2-match-char (test)
5292 "Consume and return next character if it matches TEST, a character.
5293 Returns nil and consumes nothing if TEST is not the next character."
5294 (let ((c (js2-get-char)))
5295 (if (eq c test)
5296 t
5297 (js2-unget-char)
5298 nil)))
5299
5300 (defun js2-peek-char ()
5301 (prog1
5302 (js2-get-char)
5303 (js2-unget-char)))
5304
5305 (defun js2-identifier-start-p (c)
5306 "Is C a valid start to an ES5 Identifier?
5307 See http://es5.github.io/#x7.6"
5308 (or
5309 (memq c '(?$ ?_))
5310 (memq (get-char-code-property c 'general-category)
5311 ;; Letters
5312 '(Lu Ll Lt Lm Lo Nl))))
5313
5314 (defun js2-identifier-part-p (c)
5315 "Is C a valid part of an ES5 Identifier?
5316 See http://es5.github.io/#x7.6"
5317 (or
5318 (memq c '(?$ ?_ ?\u200c ?\u200d))
5319 (memq (get-char-code-property c 'general-category)
5320 '(;; Letters
5321 Lu Ll Lt Lm Lo Nl
5322 ;; Combining Marks
5323 Mn Mc
5324 ;; Digits
5325 Nd
5326 ;; Connector Punctuation
5327 Pc))))
5328
5329 (defun js2-alpha-p (c)
5330 (cond ((and (<= ?A c) (<= c ?Z)) t)
5331 ((and (<= ?a c) (<= c ?z)) t)
5332 (t nil)))
5333
5334 (defsubst js2-digit-p (c)
5335 (and (<= ?0 c) (<= c ?9)))
5336
5337 (defun js2-js-space-p (c)
5338 (if (<= c 127)
5339 (memq c '(#x20 #x9 #xB #xC #xD))
5340 (or
5341 (eq c #xA0)
5342 ;; TODO: change this nil to check for Unicode space character
5343 nil)))
5344
5345 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5346
5347 (defun js2-skip-line ()
5348 "Skip to end of line."
5349 (while (not (memq (js2-get-char) js2-eol-chars)))
5350 (js2-unget-char)
5351 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5352 (setq js2-token-end js2-ts-cursor))
5353
5354 (defun js2-init-scanner (&optional buf line)
5355 "Create token stream for BUF starting on LINE.
5356 BUF defaults to `current-buffer' and LINE defaults to 1.
5357
5358 A buffer can only have one scanner active at a time, which yields
5359 dramatically simpler code than using a defstruct. If you need to
5360 have simultaneous scanners in a buffer, copy the regions to scan
5361 into temp buffers."
5362 (with-current-buffer (or buf (current-buffer))
5363 (setq js2-ts-dirty-line nil
5364 js2-ts-hit-eof nil
5365 js2-ts-line-start 0
5366 js2-ts-lineno (or line 1)
5367 js2-ts-line-end-char -1
5368 js2-ts-cursor (point-min)
5369 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5370 js2-ti-tokens-cursor 0
5371 js2-ti-lookahead 0
5372 js2-ts-is-xml-attribute nil
5373 js2-ts-xml-is-tag-content nil
5374 js2-ts-xml-open-tags-count 0
5375 js2-ts-string-buffer nil)))
5376
5377 ;; This function uses the cached op, string and number fields in
5378 ;; TokenStream; if getToken has been called since the passed token
5379 ;; was scanned, the op or string printed may be incorrect.
5380 (defun js2-token-to-string (token)
5381 ;; Not sure where this function is used in Rhino. Not tested.
5382 (if (not js2-debug-print-trees)
5383 ""
5384 (let ((name (js2-tt-name token)))
5385 (cond
5386 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5387 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5388 (concat name " `" (js2-current-token-string) "'"))
5389 ((eq token js2-NUMBER)
5390 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5391 (t
5392 name)))))
5393
5394 (defconst js2-keywords
5395 '(break
5396 case catch class const continue
5397 debugger default delete do
5398 else extends
5399 false finally for function
5400 if in instanceof import
5401 let
5402 new null
5403 return
5404 static super switch
5405 this throw true try typeof
5406 var void
5407 while with
5408 yield))
5409
5410 ;; Token names aren't exactly the same as the keywords, unfortunately.
5411 ;; E.g. delete is js2-DELPROP.
5412 (defconst js2-kwd-tokens
5413 (let ((table (make-vector js2-num-tokens nil))
5414 (tokens
5415 (list js2-BREAK
5416 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5417 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5418 js2-ELSE js2-EXTENDS
5419 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5420 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5421 js2-LET
5422 js2-NEW js2-NULL
5423 js2-RETURN
5424 js2-STATIC js2-SUPER js2-SWITCH
5425 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5426 js2-VAR
5427 js2-WHILE js2-WITH
5428 js2-YIELD)))
5429 (dolist (i tokens)
5430 (aset table i 'font-lock-keyword-face))
5431 (aset table js2-STRING 'font-lock-string-face)
5432 (aset table js2-REGEXP 'font-lock-string-face)
5433 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5434 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5435 (aset table js2-COMMENT 'font-lock-comment-face)
5436 (aset table js2-THIS 'font-lock-builtin-face)
5437 (aset table js2-SUPER 'font-lock-builtin-face)
5438 (aset table js2-VOID 'font-lock-constant-face)
5439 (aset table js2-NULL 'font-lock-constant-face)
5440 (aset table js2-TRUE 'font-lock-constant-face)
5441 (aset table js2-FALSE 'font-lock-constant-face)
5442 (aset table js2-NOT 'font-lock-negation-char-face)
5443 table)
5444 "Vector whose values are non-nil for tokens that are keywords.
5445 The values are default faces to use for highlighting the keywords.")
5446
5447 ;; FIXME: Support strict mode-only future reserved words, after we know
5448 ;; which parts scopes are in strict mode, and which are not.
5449 (defconst js2-reserved-words '(class enum export extends import super)
5450 "Future reserved keywords in ECMAScript 5.1.")
5451
5452 (defconst js2-keyword-names
5453 (let ((table (make-hash-table :test 'equal)))
5454 (loop for k in js2-keywords
5455 do (puthash
5456 (symbol-name k) ; instanceof
5457 (intern (concat "js2-"
5458 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5459 table))
5460 table)
5461 "JavaScript keywords by name, mapped to their symbols.")
5462
5463 (defconst js2-reserved-word-names
5464 (let ((table (make-hash-table :test 'equal)))
5465 (loop for k in js2-reserved-words
5466 do
5467 (puthash (symbol-name k) 'js2-RESERVED table))
5468 table)
5469 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5470
5471 (defun js2-collect-string (buf)
5472 "Convert BUF, a list of chars, to a string.
5473 Reverses BUF before converting."
5474 (if buf
5475 (apply #'string (nreverse buf))
5476 ""))
5477
5478 (defun js2-string-to-keyword (s)
5479 "Return token for S, a string, if S is a keyword or reserved word.
5480 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5481 (or (gethash s js2-keyword-names)
5482 (gethash s js2-reserved-word-names)))
5483
5484 (defsubst js2-ts-set-char-token-bounds (token)
5485 "Used when next token is one character."
5486 (setf (js2-token-beg token) (1- js2-ts-cursor)
5487 (js2-token-end token) js2-ts-cursor))
5488
5489 (defsubst js2-ts-return (token type)
5490 "Update the `end' and `type' slots of TOKEN,
5491 then throw `return' with value TYPE."
5492 (setf (js2-token-end token) js2-ts-cursor
5493 (js2-token-type token) type)
5494 (throw 'return type))
5495
5496 (defun js2-x-digit-to-int (c accumulator)
5497 "Build up a hex number.
5498 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5499 corresponding number. Otherwise return -1."
5500 (catch 'return
5501 (catch 'check
5502 ;; Use 0..9 < A..Z < a..z
5503 (cond
5504 ((<= c ?9)
5505 (decf c ?0)
5506 (if (<= 0 c)
5507 (throw 'check nil)))
5508 ((<= c ?F)
5509 (when (<= ?A c)
5510 (decf c (- ?A 10))
5511 (throw 'check nil)))
5512 ((<= c ?f)
5513 (when (<= ?a c)
5514 (decf c (- ?a 10))
5515 (throw 'check nil))))
5516 (throw 'return -1))
5517 (logior c (lsh accumulator 4))))
5518
5519 (defun js2-get-token (&optional modifier)
5520 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5521 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5522 next saved token.
5523
5524 This function will not return a newline (js2-EOL) - instead, it
5525 gobbles newlines until it finds a non-newline token. Call
5526 `js2-peek-token-or-eol' when you care about newlines.
5527
5528 This function will also not return a js2-COMMENT. Instead, it
5529 records comments found in `js2-scanned-comments'. If the token
5530 returned by this function immediately follows a jsdoc comment,
5531 the token is flagged as such."
5532 (if (zerop js2-ti-lookahead)
5533 (js2-get-token-internal modifier)
5534 (decf js2-ti-lookahead)
5535 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5536 (let ((tt (js2-current-token-type)))
5537 (assert (not (= tt js2-EOL)))
5538 tt)))
5539
5540 (defun js2-unget-token ()
5541 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5542 (incf js2-ti-lookahead)
5543 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5544
5545 (defun js2-get-token-internal (modifier)
5546 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5547 (tt (js2-token-type token))
5548 saw-eol
5549 face)
5550 ;; process comments
5551 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5552 (if (= tt js2-EOL)
5553 (setq saw-eol t)
5554 (setq saw-eol nil)
5555 (when js2-record-comments
5556 (js2-record-comment token)))
5557 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5558 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5559 tt (js2-token-type token)))
5560
5561 (when saw-eol
5562 (setf (js2-token-follows-eol-p token) t))
5563
5564 ;; perform lexical fontification as soon as token is scanned
5565 (when js2-parse-ide-mode
5566 (cond
5567 ((minusp tt)
5568 (js2-record-face 'js2-error token))
5569 ((setq face (aref js2-kwd-tokens tt))
5570 (js2-record-face face token))
5571 ((and (= tt js2-NAME)
5572 (equal (js2-token-string token) "undefined"))
5573 (js2-record-face 'font-lock-constant-face token))))
5574 tt))
5575
5576 (defun js2-get-token-internal-1 (modifier)
5577 "Return next JavaScript token type, an int such as js2-RETURN.
5578 During operation, creates an instance of `js2-token' struct, sets
5579 its relevant fields and puts it into `js2-ti-tokens'."
5580 (let (c c1 identifier-start is-unicode-escape-start
5581 contains-escape escape-val str result base
5582 quote-char val look-for-slash continue tt
5583 (token (js2-new-token 0)))
5584 (setq
5585 tt
5586 (catch 'return
5587 (when (eq modifier 'TEMPLATE_TAIL)
5588 (setf (js2-token-beg token) (1- js2-ts-cursor))
5589 (throw 'return (js2-get-string-or-template-token ?` token)))
5590 (while t
5591 ;; Eat whitespace, possibly sensitive to newlines.
5592 (setq continue t)
5593 (while continue
5594 (setq c (js2-get-char))
5595 (cond
5596 ((eq c js2-EOF_CHAR)
5597 (js2-unget-char)
5598 (js2-ts-set-char-token-bounds token)
5599 (throw 'return js2-EOF))
5600 ((eq c ?\n)
5601 (js2-ts-set-char-token-bounds token)
5602 (setq js2-ts-dirty-line nil)
5603 (throw 'return js2-EOL))
5604 ((not (js2-js-space-p c))
5605 (if (/= c ?-) ; in case end of HTML comment
5606 (setq js2-ts-dirty-line t))
5607 (setq continue nil))))
5608 ;; Assume the token will be 1 char - fixed up below.
5609 (js2-ts-set-char-token-bounds token)
5610 (when (eq c ?@)
5611 (throw 'return js2-XMLATTR))
5612 ;; identifier/keyword/instanceof?
5613 ;; watch out for starting with a <backslash>
5614 (cond
5615 ((eq c ?\\)
5616 (setq c (js2-get-char))
5617 (if (eq c ?u)
5618 (setq identifier-start t
5619 is-unicode-escape-start t
5620 js2-ts-string-buffer nil)
5621 (setq identifier-start nil)
5622 (js2-unget-char)
5623 (setq c ?\\)))
5624 (t
5625 (when (setq identifier-start (js2-identifier-start-p c))
5626 (setq js2-ts-string-buffer nil)
5627 (js2-add-to-string c))))
5628 (when identifier-start
5629 (setq contains-escape is-unicode-escape-start)
5630 (catch 'break
5631 (while t
5632 (if is-unicode-escape-start
5633 ;; strictly speaking we should probably push-back
5634 ;; all the bad characters if the <backslash>uXXXX
5635 ;; sequence is malformed. But since there isn't a
5636 ;; correct context(is there?) for a bad Unicode
5637 ;; escape sequence in an identifier, we can report
5638 ;; an error here.
5639 (progn
5640 (setq escape-val 0)
5641 (dotimes (_ 4)
5642 (setq c (js2-get-char)
5643 escape-val (js2-x-digit-to-int c escape-val))
5644 ;; Next check takes care of c < 0 and bad escape
5645 (if (minusp escape-val)
5646 (throw 'break nil)))
5647 (if (minusp escape-val)
5648 (js2-report-scan-error "msg.invalid.escape" t))
5649 (js2-add-to-string escape-val)
5650 (setq is-unicode-escape-start nil))
5651 (setq c (js2-get-char))
5652 (cond
5653 ((eq c ?\\)
5654 (setq c (js2-get-char))
5655 (if (eq c ?u)
5656 (setq is-unicode-escape-start t
5657 contains-escape t)
5658 (js2-report-scan-error "msg.illegal.character" t)))
5659 (t
5660 (if (or (eq c js2-EOF_CHAR)
5661 (not (js2-identifier-part-p c)))
5662 (throw 'break nil))
5663 (js2-add-to-string c))))))
5664 (js2-unget-char)
5665 (setf str (js2-collect-string js2-ts-string-buffer)
5666 (js2-token-end token) js2-ts-cursor)
5667 ;; FIXME: Invalid in ES5 and ES6, see
5668 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5669 ;; Probably should just drop this conditional.
5670 (unless contains-escape
5671 ;; OPT we shouldn't have to make a string (object!) to
5672 ;; check if it's a keyword.
5673 ;; Return the corresponding token if it's a keyword
5674 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5675 (setq result (js2-string-to-keyword str)))
5676 (if (and (< js2-language-version 170)
5677 (memq result '(js2-LET js2-YIELD)))
5678 ;; LET and YIELD are tokens only in 1.7 and later
5679 (setq result 'js2-NAME))
5680 (when (eq result 'js2-RESERVED)
5681 (setf (js2-token-string token) str))
5682 (throw 'return (js2-tt-code result))))
5683 ;; If we want to intern these as Rhino does, just use (intern str)
5684 (setf (js2-token-string token) str)
5685 (throw 'return js2-NAME)) ; end identifier/kwd check
5686 ;; is it a number?
5687 (when (or (js2-digit-p c)
5688 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5689 (setq js2-ts-string-buffer nil
5690 base 10)
5691 (when (eq c ?0)
5692 (setq c (js2-get-char))
5693 (cond
5694 ((or (eq c ?x) (eq c ?X))
5695 (setq base 16)
5696 (setq c (js2-get-char)))
5697 ((and (or (eq c ?b) (eq c ?B))
5698 (>= js2-language-version 200))
5699 (setq base 2)
5700 (setq c (js2-get-char)))
5701 ((and (or (eq c ?o) (eq c ?O))
5702 (>= js2-language-version 200))
5703 (setq base 8)
5704 (setq c (js2-get-char)))
5705 ((js2-digit-p c)
5706 (setq base 'maybe-8))
5707 (t
5708 (js2-add-to-string ?0))))
5709 (cond
5710 ((eq base 16)
5711 (if (> 0 (js2-x-digit-to-int c 0))
5712 (js2-report-scan-error "msg.missing.hex.digits")
5713 (while (<= 0 (js2-x-digit-to-int c 0))
5714 (js2-add-to-string c)
5715 (setq c (js2-get-char)))))
5716 ((eq base 2)
5717 (if (not (memq c '(?0 ?1)))
5718 (js2-report-scan-error "msg.missing.binary.digits")
5719 (while (memq c '(?0 ?1))
5720 (js2-add-to-string c)
5721 (setq c (js2-get-char)))))
5722 ((eq base 8)
5723 (if (or (> ?0 c) (< ?7 c))
5724 (js2-report-scan-error "msg.missing.octal.digits")
5725 (while (and (<= ?0 c) (>= ?7 c))
5726 (js2-add-to-string c)
5727 (setq c (js2-get-char)))))
5728 (t
5729 (while (and (<= ?0 c) (<= c ?9))
5730 ;; We permit 08 and 09 as decimal numbers, which
5731 ;; makes our behavior a superset of the ECMA
5732 ;; numeric grammar. We might not always be so
5733 ;; permissive, so we warn about it.
5734 (when (and (eq base 'maybe-8) (>= c ?8))
5735 (js2-report-warning "msg.bad.octal.literal"
5736 (if (eq c ?8) "8" "9"))
5737 (setq base 10))
5738 (js2-add-to-string c)
5739 (setq c (js2-get-char)))
5740 (when (eq base 'maybe-8)
5741 (setq base 8))))
5742 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5743 (when (eq c ?.)
5744 (loop do
5745 (js2-add-to-string c)
5746 (setq c (js2-get-char))
5747 while (js2-digit-p c)))
5748 (when (memq c '(?e ?E))
5749 (js2-add-to-string c)
5750 (setq c (js2-get-char))
5751 (when (memq c '(?+ ?-))
5752 (js2-add-to-string c)
5753 (setq c (js2-get-char)))
5754 (unless (js2-digit-p c)
5755 (js2-report-scan-error "msg.missing.exponent" t))
5756 (loop do
5757 (js2-add-to-string c)
5758 (setq c (js2-get-char))
5759 while (js2-digit-p c))))
5760 (js2-unget-char)
5761 (let ((str (js2-set-string-from-buffer token)))
5762 (setf (js2-token-number token)
5763 (js2-string-to-number str base)))
5764 (throw 'return js2-NUMBER))
5765 ;; is it a string?
5766 (when (or (memq c '(?\" ?\'))
5767 (and (>= js2-language-version 200)
5768 (= c ?`)))
5769 (throw 'return
5770 (js2-get-string-or-template-token c token)))
5771 (js2-ts-return token
5772 (case c
5773 (?\;
5774 (throw 'return js2-SEMI))
5775 (?\[
5776 (throw 'return js2-LB))
5777 (?\]
5778 (throw 'return js2-RB))
5779 (?{
5780 (throw 'return js2-LC))
5781 (?}
5782 (throw 'return js2-RC))
5783 (?\(
5784 (throw 'return js2-LP))
5785 (?\)
5786 (throw 'return js2-RP))
5787 (?,
5788 (throw 'return js2-COMMA))
5789 (??
5790 (throw 'return js2-HOOK))
5791 (?:
5792 (if (js2-match-char ?:)
5793 js2-COLONCOLON
5794 (throw 'return js2-COLON)))
5795 (?.
5796 (if (js2-match-char ?.)
5797 (if (js2-match-char ?.)
5798 js2-TRIPLEDOT js2-DOTDOT)
5799 (if (js2-match-char ?\()
5800 js2-DOTQUERY
5801 (throw 'return js2-DOT))))
5802 (?|
5803 (if (js2-match-char ?|)
5804 (throw 'return js2-OR)
5805 (if (js2-match-char ?=)
5806 js2-ASSIGN_BITOR
5807 (throw 'return js2-BITOR))))
5808 (?^
5809 (if (js2-match-char ?=)
5810 js2-ASSIGN_BITOR
5811 (throw 'return js2-BITXOR)))
5812 (?&
5813 (if (js2-match-char ?&)
5814 (throw 'return js2-AND)
5815 (if (js2-match-char ?=)
5816 js2-ASSIGN_BITAND
5817 (throw 'return js2-BITAND))))
5818 (?=
5819 (if (js2-match-char ?=)
5820 (if (js2-match-char ?=)
5821 js2-SHEQ
5822 (throw 'return js2-EQ))
5823 (if (js2-match-char ?>)
5824 (js2-ts-return token js2-ARROW)
5825 (throw 'return js2-ASSIGN))))
5826 (?!
5827 (if (js2-match-char ?=)
5828 (if (js2-match-char ?=)
5829 js2-SHNE
5830 js2-NE)
5831 (throw 'return js2-NOT)))
5832 (?<
5833 ;; NB:treat HTML begin-comment as comment-till-eol
5834 (when (js2-match-char ?!)
5835 (when (js2-match-char ?-)
5836 (when (js2-match-char ?-)
5837 (js2-skip-line)
5838 (setf (js2-token-comment-type (js2-current-token)) 'html)
5839 (throw 'return js2-COMMENT)))
5840 (js2-unget-char))
5841 (if (js2-match-char ?<)
5842 (if (js2-match-char ?=)
5843 js2-ASSIGN_LSH
5844 js2-LSH)
5845 (if (js2-match-char ?=)
5846 js2-LE
5847 (throw 'return js2-LT))))
5848 (?>
5849 (if (js2-match-char ?>)
5850 (if (js2-match-char ?>)
5851 (if (js2-match-char ?=)
5852 js2-ASSIGN_URSH
5853 js2-URSH)
5854 (if (js2-match-char ?=)
5855 js2-ASSIGN_RSH
5856 js2-RSH))
5857 (if (js2-match-char ?=)
5858 js2-GE
5859 (throw 'return js2-GT))))
5860 (?*
5861 (if (js2-match-char ?=)
5862 js2-ASSIGN_MUL
5863 (throw 'return js2-MUL)))
5864 (?/
5865 ;; is it a // comment?
5866 (when (js2-match-char ?/)
5867 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5868 (js2-skip-line)
5869 (setf (js2-token-comment-type token) 'line)
5870 ;; include newline so highlighting goes to end of window
5871 (incf (js2-token-end token))
5872 (throw 'return js2-COMMENT))
5873 ;; is it a /* comment?
5874 (when (js2-match-char ?*)
5875 (setf look-for-slash nil
5876 (js2-token-beg token) (- js2-ts-cursor 2)
5877 (js2-token-comment-type token)
5878 (if (js2-match-char ?*)
5879 (progn
5880 (setq look-for-slash t)
5881 'jsdoc)
5882 'block))
5883 (while t
5884 (setq c (js2-get-char))
5885 (cond
5886 ((eq c js2-EOF_CHAR)
5887 (setf (js2-token-end token) (1- js2-ts-cursor))
5888 (js2-report-error "msg.unterminated.comment")
5889 (throw 'return js2-COMMENT))
5890 ((eq c ?*)
5891 (setq look-for-slash t))
5892 ((eq c ?/)
5893 (if look-for-slash
5894 (js2-ts-return token js2-COMMENT)))
5895 (t
5896 (setf look-for-slash nil
5897 (js2-token-end token) js2-ts-cursor)))))
5898 (if (js2-match-char ?=)
5899 js2-ASSIGN_DIV
5900 (throw 'return js2-DIV)))
5901 (?#
5902 (when js2-skip-preprocessor-directives
5903 (js2-skip-line)
5904 (setf (js2-token-comment-type token) 'preprocessor
5905 (js2-token-end token) js2-ts-cursor)
5906 (throw 'return js2-COMMENT))
5907 (throw 'return js2-ERROR))
5908 (?%
5909 (if (js2-match-char ?=)
5910 js2-ASSIGN_MOD
5911 (throw 'return js2-MOD)))
5912 (?~
5913 (throw 'return js2-BITNOT))
5914 (?+
5915 (if (js2-match-char ?=)
5916 js2-ASSIGN_ADD
5917 (if (js2-match-char ?+)
5918 js2-INC
5919 (throw 'return js2-ADD))))
5920 (?-
5921 (cond
5922 ((js2-match-char ?=)
5923 (setq c js2-ASSIGN_SUB))
5924 ((js2-match-char ?-)
5925 (unless js2-ts-dirty-line
5926 ;; treat HTML end-comment after possible whitespace
5927 ;; after line start as comment-until-eol
5928 (when (js2-match-char ?>)
5929 (js2-skip-line)
5930 (setf (js2-token-comment-type (js2-current-token)) 'html)
5931 (throw 'return js2-COMMENT)))
5932 (setq c js2-DEC))
5933 (t
5934 (setq c js2-SUB)))
5935 (setq js2-ts-dirty-line t)
5936 c)
5937 (otherwise
5938 (js2-report-scan-error "msg.illegal.character")))))))
5939 (setf (js2-token-type token) tt)
5940 token))
5941
5942 (defun js2-get-string-or-template-token (quote-char token)
5943 ;; We attempt to accumulate a string the fast way, by
5944 ;; building it directly out of the reader. But if there
5945 ;; are any escaped characters in the string, we revert to
5946 ;; building it out of a string buffer.
5947 (let ((c (js2-get-char))
5948 js2-ts-string-buffer
5949 nc)
5950 (catch 'break
5951 (while (/= c quote-char)
5952 (catch 'continue
5953 (when (eq c js2-EOF_CHAR)
5954 (js2-unget-char)
5955 (js2-report-error "msg.unterminated.string.lit")
5956 (throw 'break nil))
5957 (when (and (eq c ?\n) (not (eq quote-char ?`)))
5958 (js2-unget-char)
5959 (js2-report-error "msg.unterminated.string.lit")
5960 (throw 'break nil))
5961 (when (eq c ?\\)
5962 ;; We've hit an escaped character
5963 (setq c (js2-get-char))
5964 (case c
5965 (?b (setq c ?\b))
5966 (?f (setq c ?\f))
5967 (?n (setq c ?\n))
5968 (?r (setq c ?\r))
5969 (?t (setq c ?\t))
5970 (?v (setq c ?\v))
5971 (?u
5972 (setq c1 (js2-read-unicode-escape))
5973 (if js2-parse-ide-mode
5974 (if c1
5975 (progn
5976 ;; just copy the string in IDE-mode
5977 (js2-add-to-string ?\\)
5978 (js2-add-to-string ?u)
5979 (dotimes (_ 3)
5980 (js2-add-to-string (js2-get-char)))
5981 (setq c (js2-get-char))) ; added at end of loop
5982 ;; flag it as an invalid escape
5983 (js2-report-warning "msg.invalid.escape"
5984 nil (- js2-ts-cursor 2) 6))
5985 ;; Get 4 hex digits; if the u escape is not
5986 ;; followed by 4 hex digits, use 'u' + the
5987 ;; literal character sequence that follows.
5988 (js2-add-to-string ?u)
5989 (setq escape-val 0)
5990 (dotimes (_ 4)
5991 (setq c (js2-get-char)
5992 escape-val (js2-x-digit-to-int c escape-val))
5993 (if (minusp escape-val)
5994 (throw 'continue nil))
5995 (js2-add-to-string c))
5996 ;; prepare for replace of stored 'u' sequence by escape value
5997 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5998 c escape-val)))
5999 (?x
6000 ;; Get 2 hex digits, defaulting to 'x'+literal
6001 ;; sequence, as above.
6002 (setq c (js2-get-char)
6003 escape-val (js2-x-digit-to-int c 0))
6004 (if (minusp escape-val)
6005 (progn
6006 (js2-add-to-string ?x)
6007 (throw 'continue nil))
6008 (setq c1 c
6009 c (js2-get-char)
6010 escape-val (js2-x-digit-to-int c escape-val))
6011 (if (minusp escape-val)
6012 (progn
6013 (js2-add-to-string ?x)
6014 (js2-add-to-string c1)
6015 (throw 'continue nil))
6016 ;; got 2 hex digits
6017 (setq c escape-val))))
6018 (?\n
6019 ;; Remove line terminator after escape to follow
6020 ;; SpiderMonkey and C/C++
6021 (setq c (js2-get-char))
6022 (throw 'continue nil))
6023 (t
6024 (when (and (<= ?0 c) (< c ?8))
6025 (setq val (- c ?0)
6026 c (js2-get-char))
6027 (when (and (<= ?0 c) (< c ?8))
6028 (setq val (- (+ (* 8 val) c) ?0)
6029 c (js2-get-char))
6030 (when (and (<= ?0 c)
6031 (< c ?8)
6032 (< val #o37))
6033 ;; c is 3rd char of octal sequence only
6034 ;; if the resulting val <= 0377
6035 (setq val (- (+ (* 8 val) c) ?0)
6036 c (js2-get-char))))
6037 (js2-unget-char)
6038 (setq c val)))))
6039 (when (and (eq quote-char ?`) (eq c ?$))
6040 (when (eq (setq nc (js2-get-char)) ?\{)
6041 (throw 'break nil))
6042 (js2-unget-char))
6043 (js2-add-to-string c)
6044 (setq c (js2-get-char)))))
6045 (js2-set-string-from-buffer token)
6046 (if (not (eq quote-char ?`))
6047 js2-STRING
6048 (if (and (eq c ?$) (eq nc ?\{))
6049 js2-TEMPLATE_HEAD
6050 js2-NO_SUBS_TEMPLATE))))
6051
6052 (defsubst js2-string-to-number (str base)
6053 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
6054 (condition-case nil
6055 (string-to-number str base)
6056 (overflow-error -1)))
6057
6058 (defun js2-read-regexp (start-tt)
6059 "Called by parser when it gets / or /= in literal context."
6060 (let (c err
6061 in-class ; inside a '[' .. ']' character-class
6062 flags
6063 (continue t)
6064 (token (js2-new-token 0)))
6065 (setq js2-ts-string-buffer nil)
6066 (if (eq start-tt js2-ASSIGN_DIV)
6067 ;; mis-scanned /=
6068 (js2-add-to-string ?=)
6069 (if (not (eq start-tt js2-DIV))
6070 (error "failed assertion")))
6071 (while (and (not err)
6072 (or (/= (setq c (js2-get-char)) ?/)
6073 in-class))
6074 (cond
6075 ((or (= c ?\n)
6076 (= c js2-EOF_CHAR))
6077 (setf (js2-token-end token) (1- js2-ts-cursor)
6078 err t
6079 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6080 (js2-report-error "msg.unterminated.re.lit"))
6081 (t (cond
6082 ((= c ?\\)
6083 (js2-add-to-string c)
6084 (setq c (js2-get-char)))
6085 ((= c ?\[)
6086 (setq in-class t))
6087 ((= c ?\])
6088 (setq in-class nil)))
6089 (js2-add-to-string c))))
6090 (unless err
6091 (while continue
6092 (cond
6093 ((js2-match-char ?g)
6094 (push ?g flags))
6095 ((js2-match-char ?i)
6096 (push ?i flags))
6097 ((js2-match-char ?m)
6098 (push ?m flags))
6099 ((and (js2-match-char ?u)
6100 (>= js2-language-version 200))
6101 (push ?u flags))
6102 ((and (js2-match-char ?y)
6103 (>= js2-language-version 200))
6104 (push ?y flags))
6105 (t
6106 (setq continue nil))))
6107 (if (js2-alpha-p (js2-peek-char))
6108 (js2-report-scan-error "msg.invalid.re.flag" t
6109 js2-ts-cursor 1))
6110 (js2-set-string-from-buffer token))
6111 (js2-collect-string flags)))
6112
6113 (defun js2-get-first-xml-token ()
6114 (setq js2-ts-xml-open-tags-count 0
6115 js2-ts-is-xml-attribute nil
6116 js2-ts-xml-is-tag-content nil)
6117 (js2-unget-char)
6118 (js2-get-next-xml-token))
6119
6120 (defun js2-xml-discard-string (token)
6121 "Throw away the string in progress and flag an XML parse error."
6122 (setf js2-ts-string-buffer nil
6123 (js2-token-string token) nil)
6124 (js2-report-scan-error "msg.XML.bad.form" t))
6125
6126 (defun js2-get-next-xml-token ()
6127 (setq js2-ts-string-buffer nil) ; for recording the XML
6128 (let ((token (js2-new-token 0))
6129 c result)
6130 (setq result
6131 (catch 'return
6132 (while t
6133 (setq c (js2-get-char))
6134 (cond
6135 ((= c js2-EOF_CHAR)
6136 (throw 'return js2-ERROR))
6137 (js2-ts-xml-is-tag-content
6138 (case c
6139 (?>
6140 (js2-add-to-string c)
6141 (setq js2-ts-xml-is-tag-content nil
6142 js2-ts-is-xml-attribute nil))
6143 (?/
6144 (js2-add-to-string c)
6145 (when (eq ?> (js2-peek-char))
6146 (setq c (js2-get-char))
6147 (js2-add-to-string c)
6148 (setq js2-ts-xml-is-tag-content nil)
6149 (decf js2-ts-xml-open-tags-count)))
6150 (?{
6151 (js2-unget-char)
6152 (js2-set-string-from-buffer token)
6153 (throw 'return js2-XML))
6154 ((?\' ?\")
6155 (js2-add-to-string c)
6156 (unless (js2-read-quoted-string c token)
6157 (throw 'return js2-ERROR)))
6158 (?=
6159 (js2-add-to-string c)
6160 (setq js2-ts-is-xml-attribute t))
6161 ((? ?\t ?\r ?\n)
6162 (js2-add-to-string c))
6163 (t
6164 (js2-add-to-string c)
6165 (setq js2-ts-is-xml-attribute nil)))
6166 (when (and (not js2-ts-xml-is-tag-content)
6167 (zerop js2-ts-xml-open-tags-count))
6168 (js2-set-string-from-buffer token)
6169 (throw 'return js2-XMLEND)))
6170 (t
6171 ;; else not tag content
6172 (case c
6173 (?<
6174 (js2-add-to-string c)
6175 (setq c (js2-peek-char))
6176 (case c
6177 (?!
6178 (setq c (js2-get-char)) ;; skip !
6179 (js2-add-to-string c)
6180 (setq c (js2-peek-char))
6181 (case c
6182 (?-
6183 (setq c (js2-get-char)) ;; skip -
6184 (js2-add-to-string c)
6185 (if (eq c ?-)
6186 (progn
6187 (js2-add-to-string c)
6188 (unless (js2-read-xml-comment token)
6189 (throw 'return js2-ERROR)))
6190 (js2-xml-discard-string token)
6191 (throw 'return js2-ERROR)))
6192 (?\[
6193 (setq c (js2-get-char)) ;; skip [
6194 (js2-add-to-string c)
6195 (if (and (= (js2-get-char) ?C)
6196 (= (js2-get-char) ?D)
6197 (= (js2-get-char) ?A)
6198 (= (js2-get-char) ?T)
6199 (= (js2-get-char) ?A)
6200 (= (js2-get-char) ?\[))
6201 (progn
6202 (js2-add-to-string ?C)
6203 (js2-add-to-string ?D)
6204 (js2-add-to-string ?A)
6205 (js2-add-to-string ?T)
6206 (js2-add-to-string ?A)
6207 (js2-add-to-string ?\[)
6208 (unless (js2-read-cdata token)
6209 (throw 'return js2-ERROR)))
6210 (js2-xml-discard-string token)
6211 (throw 'return js2-ERROR)))
6212 (t
6213 (unless (js2-read-entity token)
6214 (throw 'return js2-ERROR))))
6215 ;; Allow bare CDATA section, e.g.:
6216 ;; let xml = <![CDATA[ foo bar baz ]]>;
6217 (when (zerop js2-ts-xml-open-tags-count)
6218 (throw 'return js2-XMLEND)))
6219 (??
6220 (setq c (js2-get-char)) ;; skip ?
6221 (js2-add-to-string c)
6222 (unless (js2-read-PI token)
6223 (throw 'return js2-ERROR)))
6224 (?/
6225 ;; end tag
6226 (setq c (js2-get-char)) ;; skip /
6227 (js2-add-to-string c)
6228 (when (zerop js2-ts-xml-open-tags-count)
6229 (js2-xml-discard-string token)
6230 (throw 'return js2-ERROR))
6231 (setq js2-ts-xml-is-tag-content t)
6232 (decf js2-ts-xml-open-tags-count))
6233 (t
6234 ;; start tag
6235 (setq js2-ts-xml-is-tag-content t)
6236 (incf js2-ts-xml-open-tags-count))))
6237 (?{
6238 (js2-unget-char)
6239 (js2-set-string-from-buffer token)
6240 (throw 'return js2-XML))
6241 (t
6242 (js2-add-to-string c))))))))
6243 (setf (js2-token-end token) js2-ts-cursor)
6244 (setf (js2-token-type token) result)
6245 result))
6246
6247 (defun js2-read-quoted-string (quote token)
6248 (let (c)
6249 (catch 'return
6250 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6251 (js2-add-to-string c)
6252 (if (eq c quote)
6253 (throw 'return t)))
6254 (js2-xml-discard-string token) ;; throw away string in progress
6255 nil)))
6256
6257 (defun js2-read-xml-comment (token)
6258 (let ((c (js2-get-char)))
6259 (catch 'return
6260 (while (/= c js2-EOF_CHAR)
6261 (catch 'continue
6262 (js2-add-to-string c)
6263 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6264 (setq c (js2-get-char))
6265 (js2-add-to-string c)
6266 (if (eq (js2-peek-char) ?>)
6267 (progn
6268 (setq c (js2-get-char)) ;; skip >
6269 (js2-add-to-string c)
6270 (throw 'return t))
6271 (throw 'continue nil)))
6272 (setq c (js2-get-char))))
6273 (js2-xml-discard-string token)
6274 nil)))
6275
6276 (defun js2-read-cdata (token)
6277 (let ((c (js2-get-char)))
6278 (catch 'return
6279 (while (/= c js2-EOF_CHAR)
6280 (catch 'continue
6281 (js2-add-to-string c)
6282 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6283 (setq c (js2-get-char))
6284 (js2-add-to-string c)
6285 (if (eq (js2-peek-char) ?>)
6286 (progn
6287 (setq c (js2-get-char)) ;; Skip >
6288 (js2-add-to-string c)
6289 (throw 'return t))
6290 (throw 'continue nil)))
6291 (setq c (js2-get-char))))
6292 (js2-xml-discard-string token)
6293 nil)))
6294
6295 (defun js2-read-entity (token)
6296 (let ((decl-tags 1)
6297 c)
6298 (catch 'return
6299 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6300 (js2-add-to-string c)
6301 (case c
6302 (?<
6303 (incf decl-tags))
6304 (?>
6305 (decf decl-tags)
6306 (if (zerop decl-tags)
6307 (throw 'return t)))))
6308 (js2-xml-discard-string token)
6309 nil)))
6310
6311 (defun js2-read-PI (token)
6312 "Scan an XML processing instruction."
6313 (let (c)
6314 (catch 'return
6315 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6316 (js2-add-to-string c)
6317 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6318 (setq c (js2-get-char)) ;; Skip >
6319 (js2-add-to-string c)
6320 (throw 'return t)))
6321 (js2-xml-discard-string token)
6322 nil)))
6323
6324 ;;; Highlighting
6325
6326 (defun js2-set-face (beg end face &optional record)
6327 "Fontify a region. If RECORD is non-nil, record for later."
6328 (when (plusp js2-highlight-level)
6329 (setq beg (min (point-max) beg)
6330 beg (max (point-min) beg)
6331 end (min (point-max) end)
6332 end (max (point-min) end))
6333 (if record
6334 (push (list beg end face) js2-mode-fontifications)
6335 (put-text-property beg end 'font-lock-face face))))
6336
6337 (defsubst js2-clear-face (beg end)
6338 (remove-text-properties beg end '(font-lock-face nil
6339 help-echo nil
6340 point-entered nil
6341 c-in-sws nil)))
6342
6343 (defconst js2-ecma-global-props
6344 (concat "^"
6345 (regexp-opt
6346 '("Infinity" "NaN" "undefined" "arguments") t)
6347 "$")
6348 "Value properties of the Ecma-262 Global Object.
6349 Shown at or above `js2-highlight-level' 2.")
6350
6351 ;; might want to add the name "arguments" to this list?
6352 (defconst js2-ecma-object-props
6353 (concat "^"
6354 (regexp-opt
6355 '("prototype" "__proto__" "__parent__") t)
6356 "$")
6357 "Value properties of the Ecma-262 Object constructor.
6358 Shown at or above `js2-highlight-level' 2.")
6359
6360 (defconst js2-ecma-global-funcs
6361 (concat
6362 "^"
6363 (regexp-opt
6364 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6365 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6366 "$")
6367 "Function properties of the Ecma-262 Global object.
6368 Shown at or above `js2-highlight-level' 2.")
6369
6370 (defconst js2-ecma-number-props
6371 (concat "^"
6372 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6373 "NEGATIVE_INFINITY"
6374 "POSITIVE_INFINITY") t)
6375 "$")
6376 "Properties of the Ecma-262 Number constructor.
6377 Shown at or above `js2-highlight-level' 2.")
6378
6379 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6380 "Properties of the Ecma-262 Date constructor.
6381 Shown at or above `js2-highlight-level' 2.")
6382
6383 (defconst js2-ecma-math-props
6384 (concat "^"
6385 (regexp-opt
6386 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6387 t)
6388 "$")
6389 "Properties of the Ecma-262 Math object.
6390 Shown at or above `js2-highlight-level' 2.")
6391
6392 (defconst js2-ecma-math-funcs
6393 (concat "^"
6394 (regexp-opt
6395 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6396 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6397 "$")
6398 "Function properties of the Ecma-262 Math object.
6399 Shown at or above `js2-highlight-level' 2.")
6400
6401 (defconst js2-ecma-function-props
6402 (concat
6403 "^"
6404 (regexp-opt
6405 '(;; properties of the Object prototype object
6406 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6407 "toLocaleString" "toString" "valueOf"
6408 ;; properties of the Function prototype object
6409 "apply" "call"
6410 ;; properties of the Array prototype object
6411 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6412 "splice" "unshift"
6413 ;; properties of the String prototype object
6414 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6415 "localeCompare" "match" "replace" "search" "split" "substring"
6416 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6417 "toUpperCase"
6418 ;; properties of the Number prototype object
6419 "toExponential" "toFixed" "toPrecision"
6420 ;; properties of the Date prototype object
6421 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6422 "getMinutes" "getMonth" "getSeconds" "getTime"
6423 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6424 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6425 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6426 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6427 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6428 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6429 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6430 "toTimeString" "toUTCString"
6431 ;; properties of the RegExp prototype object
6432 "exec" "test"
6433 ;; properties of the JSON prototype object
6434 "parse" "stringify"
6435 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6436 "toSource" "__defineGetter__" "__defineSetter__"
6437 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6438 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6439 t)
6440 "$")
6441 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6442 Shown at or above `js2-highlight-level' 3.")
6443
6444 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6445 (let ((target-name (and target
6446 (js2-name-node-p target)
6447 (js2-name-node-name target)))
6448 (prop-name (if prop (js2-name-node-name prop)))
6449 (level2 (>= js2-highlight-level 2))
6450 (level3 (>= js2-highlight-level 3)))
6451 (when level2
6452 (let ((face
6453 (if call-p
6454 (cond
6455 ((and target prop)
6456 (cond
6457 ((and level3 (string-match js2-ecma-function-props prop-name))
6458 'font-lock-builtin-face)
6459 ((and target-name prop)
6460 (cond
6461 ((string= target-name "Date")
6462 (if (string-match js2-ecma-date-props prop-name)
6463 'font-lock-builtin-face))
6464 ((string= target-name "Math")
6465 (if (string-match js2-ecma-math-funcs prop-name)
6466 'font-lock-builtin-face))))))
6467 (prop
6468 (if (string-match js2-ecma-global-funcs prop-name)
6469 'font-lock-builtin-face)))
6470 (cond
6471 ((and target prop)
6472 (cond
6473 ((string= target-name "Number")
6474 (if (string-match js2-ecma-number-props prop-name)
6475 'font-lock-constant-face))
6476 ((string= target-name "Math")
6477 (if (string-match js2-ecma-math-props prop-name)
6478 'font-lock-constant-face))))
6479 (prop
6480 (if (string-match js2-ecma-object-props prop-name)
6481 'font-lock-constant-face))))))
6482 (when face
6483 (let ((pos (+ (js2-node-pos parent) ; absolute
6484 (js2-node-pos prop)))) ; relative
6485 (js2-set-face pos
6486 (+ pos (js2-node-len prop))
6487 face 'record)))))))
6488
6489 (defun js2-parse-highlight-member-expr-node (node)
6490 "Perform syntax highlighting of EcmaScript built-in properties.
6491 The variable `js2-highlight-level' governs this highighting."
6492 (let (face target prop name pos end parent call-p callee)
6493 (cond
6494 ;; case 1: simple name, e.g. foo
6495 ((js2-name-node-p node)
6496 (setq name (js2-name-node-name node))
6497 ;; possible for name to be nil in rare cases - saw it when
6498 ;; running js2-mode on an elisp buffer. Might as well try to
6499 ;; make it so js2-mode never barfs.
6500 (when name
6501 (setq face (if (string-match js2-ecma-global-props name)
6502 'font-lock-constant-face))
6503 (when face
6504 (setq pos (js2-node-pos node)
6505 end (+ pos (js2-node-len node)))
6506 (js2-set-face pos end face 'record))))
6507 ;; case 2: property access or function call
6508 ((or (js2-prop-get-node-p node)
6509 ;; highlight function call if expr is a prop-get node
6510 ;; or a plain name (i.e. unqualified function call)
6511 (and (setq call-p (js2-call-node-p node))
6512 (setq callee (js2-call-node-target node)) ; separate setq!
6513 (or (js2-prop-get-node-p callee)
6514 (js2-name-node-p callee))))
6515 (setq parent node
6516 node (if call-p callee node))
6517 (if (and call-p (js2-name-node-p callee))
6518 (setq prop callee)
6519 (setq target (js2-prop-get-node-left node)
6520 prop (js2-prop-get-node-right node)))
6521 (cond
6522 ((js2-name-node-p prop)
6523 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6524 (js2-parse-highlight-prop-get parent target prop call-p))
6525 ((js2-name-node-p target)
6526 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6527 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6528
6529 (defun js2-parse-highlight-member-expr-fn-name (expr)
6530 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6531 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6532 We currently only handle the case where the last component is a prop-get
6533 of a simple name. Called before EXPR has a parent node."
6534 (let (pos
6535 (name (and (js2-prop-get-node-p expr)
6536 (js2-prop-get-node-right expr))))
6537 (when (js2-name-node-p name)
6538 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6539 (js2-node-pos name)))
6540 (+ pos (js2-node-len name))
6541 'font-lock-function-name-face
6542 'record))))
6543
6544 ;; source: http://jsdoc.sourceforge.net/
6545 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6546 ;; allows type specifications, and needs work before entering the wild.
6547
6548 (defconst js2-jsdoc-param-tag-regexp
6549 (concat "^\\s-*\\*+\\s-*\\(@"
6550 "\\(?:param\\|argument\\)"
6551 "\\)"
6552 "\\s-*\\({[^}]+}\\)?" ; optional type
6553 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6554 "\\>")
6555 "Matches jsdoc tags with optional type and optional param name.")
6556
6557 (defconst js2-jsdoc-typed-tag-regexp
6558 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6559 (regexp-opt
6560 '("enum"
6561 "extends"
6562 "field"
6563 "id"
6564 "implements"
6565 "lends"
6566 "mods"
6567 "requires"
6568 "return"
6569 "returns"
6570 "throw"
6571 "throws"))
6572 "\\)\\)\\s-*\\({[^}]+}\\)?")
6573 "Matches jsdoc tags with optional type.")
6574
6575 (defconst js2-jsdoc-arg-tag-regexp
6576 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6577 (regexp-opt
6578 '("alias"
6579 "augments"
6580 "borrows"
6581 "bug"
6582 "base"
6583 "config"
6584 "default"
6585 "define"
6586 "exception"
6587 "function"
6588 "member"
6589 "memberOf"
6590 "name"
6591 "namespace"
6592 "property"
6593 "since"
6594 "suppress"
6595 "this"
6596 "throws"
6597 "type"
6598 "version"))
6599 "\\)\\)\\s-+\\([^ \t]+\\)")
6600 "Matches jsdoc tags with a single argument.")
6601
6602 (defconst js2-jsdoc-empty-tag-regexp
6603 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6604 (regexp-opt
6605 '("addon"
6606 "author"
6607 "class"
6608 "const"
6609 "constant"
6610 "constructor"
6611 "constructs"
6612 "deprecated"
6613 "desc"
6614 "description"
6615 "event"
6616 "example"
6617 "exec"
6618 "export"
6619 "fileoverview"
6620 "final"
6621 "function"
6622 "hidden"
6623 "ignore"
6624 "implicitCast"
6625 "inheritDoc"
6626 "inner"
6627 "interface"
6628 "license"
6629 "noalias"
6630 "noshadow"
6631 "notypecheck"
6632 "override"
6633 "owner"
6634 "preserve"
6635 "preserveTry"
6636 "private"
6637 "protected"
6638 "public"
6639 "static"
6640 "supported"
6641 ))
6642 "\\)\\)\\s-*")
6643 "Matches empty jsdoc tags.")
6644
6645 (defconst js2-jsdoc-link-tag-regexp
6646 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6647 "Matches a jsdoc link or code tag.")
6648
6649 (defconst js2-jsdoc-see-tag-regexp
6650 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6651 "Matches a jsdoc @see tag.")
6652
6653 (defconst js2-jsdoc-html-tag-regexp
6654 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6655 "Matches a simple (no attributes) html start- or end-tag.")
6656
6657 (defun js2-jsdoc-highlight-helper ()
6658 (js2-set-face (match-beginning 1)
6659 (match-end 1)
6660 'js2-jsdoc-tag)
6661 (if (match-beginning 2)
6662 (if (save-excursion
6663 (goto-char (match-beginning 2))
6664 (= (char-after) ?{))
6665 (js2-set-face (1+ (match-beginning 2))
6666 (1- (match-end 2))
6667 'js2-jsdoc-type)
6668 (js2-set-face (match-beginning 2)
6669 (match-end 2)
6670 'js2-jsdoc-value)))
6671 (if (match-beginning 3)
6672 (js2-set-face (match-beginning 3)
6673 (match-end 3)
6674 'js2-jsdoc-value)))
6675
6676 (defun js2-highlight-jsdoc (ast)
6677 "Highlight doc comment tags."
6678 (let ((comments (js2-ast-root-comments ast))
6679 beg end)
6680 (save-excursion
6681 (dolist (node comments)
6682 (when (eq (js2-comment-node-format node) 'jsdoc)
6683 (setq beg (js2-node-abs-pos node)
6684 end (+ beg (js2-node-len node)))
6685 (save-restriction
6686 (narrow-to-region beg end)
6687 (dolist (re (list js2-jsdoc-param-tag-regexp
6688 js2-jsdoc-typed-tag-regexp
6689 js2-jsdoc-arg-tag-regexp
6690 js2-jsdoc-link-tag-regexp
6691 js2-jsdoc-see-tag-regexp
6692 js2-jsdoc-empty-tag-regexp))
6693 (goto-char beg)
6694 (while (re-search-forward re nil t)
6695 (js2-jsdoc-highlight-helper)))
6696 ;; simple highlighting for html tags
6697 (goto-char beg)
6698 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6699 (js2-set-face (match-beginning 1)
6700 (match-end 1)
6701 'js2-jsdoc-html-tag-delimiter)
6702 (js2-set-face (match-beginning 2)
6703 (match-end 2)
6704 'js2-jsdoc-html-tag-name)
6705 (js2-set-face (match-beginning 3)
6706 (match-end 3)
6707 'js2-jsdoc-html-tag-delimiter))))))))
6708
6709 (defun js2-highlight-assign-targets (_node left right)
6710 "Highlight function properties and external variables."
6711 (let (leftpos name)
6712 ;; highlight vars and props assigned function values
6713 (when (or (js2-function-node-p right)
6714 (js2-class-node-p right))
6715 (cond
6716 ;; var foo = function() {...}
6717 ((js2-name-node-p left)
6718 (setq name left))
6719 ;; foo.bar.baz = function() {...}
6720 ((and (js2-prop-get-node-p left)
6721 (js2-name-node-p (js2-prop-get-node-right left)))
6722 (setq name (js2-prop-get-node-right left))))
6723 (when name
6724 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6725 (+ leftpos (js2-node-len name))
6726 'font-lock-function-name-face
6727 'record)))))
6728
6729 (defun js2-record-name-node (node)
6730 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6731 later. NODE must be a name node."
6732 (let ((leftpos (js2-node-abs-pos node)))
6733 (push (list node js2-current-scope
6734 leftpos
6735 (+ leftpos (js2-node-len node)))
6736 js2-recorded-identifiers)))
6737
6738 (defun js2-highlight-undeclared-vars ()
6739 "After entire parse is finished, look for undeclared variable references.
6740 We have to wait until entire buffer is parsed, since JavaScript permits var
6741 decls to occur after they're used.
6742
6743 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6744 it is considered declared."
6745 (let (name)
6746 (dolist (entry js2-recorded-identifiers)
6747 (destructuring-bind (name-node scope pos end) entry
6748 (setq name (js2-name-node-name name-node))
6749 (unless (or (member name js2-global-externs)
6750 (member name js2-default-externs)
6751 (member name js2-additional-externs)
6752 (js2-get-defining-scope scope name))
6753 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6754 'js2-external-variable))))
6755 (setq js2-recorded-identifiers nil)))
6756
6757 (defun js2-set-default-externs ()
6758 "Set the value of `js2-default-externs' based on the various
6759 `js2-include-?-externs' variables."
6760 (setq js2-default-externs
6761 (append js2-ecma-262-externs
6762 (if js2-include-browser-externs js2-browser-externs)
6763 (if (and js2-include-browser-externs
6764 (>= js2-language-version 200)) js2-harmony-externs)
6765 (if js2-include-rhino-externs js2-rhino-externs)
6766 (if js2-include-node-externs js2-node-externs)
6767 (if (or js2-include-browser-externs js2-include-node-externs)
6768 js2-typed-array-externs))))
6769
6770 (defun js2-apply-jslint-globals ()
6771 (setq js2-additional-externs
6772 (nconc (js2-get-jslint-globals)
6773 js2-additional-externs)))
6774
6775 (defun js2-get-jslint-globals ()
6776 (loop for node in (js2-ast-root-comments js2-mode-ast)
6777 when (and (eq 'block (js2-comment-node-format node))
6778 (save-excursion
6779 (goto-char (js2-node-abs-pos node))
6780 (looking-at "/\\*global ")))
6781 append (js2-get-jslint-globals-in
6782 (match-end 0)
6783 (js2-node-abs-end node))))
6784
6785 (defun js2-get-jslint-globals-in (beg end)
6786 (let (res)
6787 (save-excursion
6788 (goto-char beg)
6789 (while (re-search-forward js2-mode-identifier-re end t)
6790 (let ((match (match-string 0)))
6791 (unless (member match '("true" "false"))
6792 (push match res)))))
6793 (nreverse res)))
6794
6795 ;;; IMenu support
6796
6797 ;; We currently only support imenu, but eventually should support speedbar and
6798 ;; possibly other browsing mechanisms.
6799
6800 ;; The basic strategy is to identify function assignment targets of the form
6801 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6802 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6803 ;; for imenu after parsing is finished.
6804
6805 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6806 ;; JavaScript, and the general problem is undecidable. However, several forms
6807 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6808 ;; include:
6809
6810 ;; function foo() -- function declaration
6811 ;; foo = function() -- function expression assigned to variable
6812 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6813 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6814 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6815 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6816 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6817 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6818 ;; function foo() {function bar() {...}} -- nested function
6819 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6820
6821 ;; This list boils down to a few forms that can be combined recursively.
6822 ;; Top-level named function declarations include both the left-hand (name)
6823 ;; and the right-hand (function value) expressions needed to produce an imenu
6824 ;; entry. The other "right-hand" forms we need to look for are:
6825 ;; - functions declared as props/getters/setters in object literals
6826 ;; - nested named function declarations
6827 ;; The "left-hand" expressions that functions can be assigned to include:
6828 ;; - local/global variables
6829 ;; - nested property-get expressions like a.b.c.d
6830 ;; - element gets like foo[10] or foo['bar'] where the index
6831 ;; expression can be trivially converted to a property name. They
6832 ;; effectively then become property gets.
6833
6834 ;; All the different definition types are canonicalized into the form
6835 ;; foo.bar.baz = position-of-function-keyword
6836
6837 ;; We need to build a trie-like structure for imenu. As an example,
6838 ;; consider the following JavaScript code:
6839
6840 ;; a = function() {...} // function at position 5
6841 ;; b = function() {...} // function at position 25
6842 ;; foo = function() {...} // function at position 100
6843 ;; foo.bar = function() {...} // function at position 200
6844 ;; foo.bar.baz = function() {...} // function at position 300
6845 ;; foo.bar.zab = function() {...} // function at position 400
6846
6847 ;; During parsing we accumulate an entry for each definition in
6848 ;; the variable `js2-imenu-recorder', like so:
6849
6850 ;; '((fn a 5)
6851 ;; (fn b 25)
6852 ;; (fn foo 100)
6853 ;; (fn foo bar 200)
6854 ;; (fn foo bar baz 300)
6855 ;; (fn foo bar zab 400))
6856
6857 ;; Where 'fn' is the respective function node.
6858 ;; After parsing these entries are merged into this alist-trie:
6859
6860 ;; '((a . 1)
6861 ;; (b . 2)
6862 ;; (foo (<definition> . 3)
6863 ;; (bar (<definition> . 6)
6864 ;; (baz . 100)
6865 ;; (zab . 200))))
6866
6867 ;; Note the wacky need for a <definition> name. The token can be anything
6868 ;; that isn't a valid JavaScript identifier, because you might make foo
6869 ;; a function and then start setting properties on it that are also functions.
6870
6871 (defun js2-prop-node-name (node)
6872 "Return the name of a node that may be a property-get/property-name.
6873 If NODE is not a valid name-node, string-node or integral number-node,
6874 returns nil. Otherwise returns the string name/value of the node."
6875 (cond
6876 ((js2-name-node-p node)
6877 (js2-name-node-name node))
6878 ((js2-string-node-p node)
6879 (js2-string-node-value node))
6880 ((and (js2-number-node-p node)
6881 (string-match "^[0-9]+$" (js2-number-node-value node)))
6882 (js2-number-node-value node))
6883 ((eq (js2-node-type node) js2-THIS)
6884 "this")
6885 ((eq (js2-node-type node) js2-SUPER)
6886 "super")))
6887
6888 (defun js2-node-qname-component (node)
6889 "Return the name of this node, if it contributes to a qname.
6890 Returns nil if the node doesn't contribute."
6891 (copy-sequence
6892 (or (js2-prop-node-name node)
6893 (if (and (js2-function-node-p node)
6894 (js2-function-node-name node))
6895 (js2-name-node-name (js2-function-node-name node))))))
6896
6897 (defun js2-record-imenu-entry (fn-node qname pos)
6898 "Add an entry to `js2-imenu-recorder'.
6899 FN-NODE should be the current item's function node.
6900
6901 Associate FN-NODE with its QNAME for later lookup.
6902 This is used in postprocessing the chain list. For each chain, we find
6903 the parent function, look up its qname, then prepend a copy of it to the chain."
6904 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6905 (unless js2-imenu-function-map
6906 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6907 (puthash fn-node qname js2-imenu-function-map))
6908
6909 (defun js2-record-imenu-functions (node &optional var)
6910 "Record function definitions for imenu.
6911 NODE is a function node or an object literal.
6912 VAR, if non-nil, is the expression that NODE is being assigned to.
6913 When passed arguments of wrong type, does nothing."
6914 (when js2-parse-ide-mode
6915 (let ((fun-p (js2-function-node-p node))
6916 qname fname-node)
6917 (cond
6918 ;; non-anonymous function declaration?
6919 ((and fun-p
6920 (not var)
6921 (setq fname-node (js2-function-node-name node)))
6922 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6923 ;; for remaining forms, compute left-side tree branch first
6924 ((and var (setq qname (js2-compute-nested-prop-get var)))
6925 (cond
6926 ;; foo.bar.baz = function
6927 (fun-p
6928 (js2-record-imenu-entry node qname (js2-node-pos node)))
6929 ;; foo.bar.baz = object-literal
6930 ;; look for nested functions: {a: {b: function() {...} }}
6931 ((js2-object-node-p node)
6932 ;; Node position here is still absolute, since the parser
6933 ;; passes the assignment target and value expressions
6934 ;; to us before they are added as children of the assignment node.
6935 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6936
6937 (defun js2-compute-nested-prop-get (node)
6938 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6939 component nodes as a list. Otherwise return nil. Element-gets are treated
6940 as property-gets if the index expression is a string, or a positive integer."
6941 (let (left right head)
6942 (cond
6943 ((or (js2-name-node-p node)
6944 (js2-this-or-super-node-p node))
6945 (list node))
6946 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6947 ((js2-prop-get-node-p node) ; foo.bar
6948 (setq left (js2-prop-get-node-left node)
6949 right (js2-prop-get-node-right node))
6950 (if (setq head (js2-compute-nested-prop-get left))
6951 (nconc head (list right))))
6952 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6953 (setq left (js2-elem-get-node-target node)
6954 right (js2-elem-get-node-element node))
6955 (if (or (js2-string-node-p right) ; ['bar']
6956 (and (js2-number-node-p right) ; [10]
6957 (string-match "^[0-9]+$"
6958 (js2-number-node-value right))))
6959 (if (setq head (js2-compute-nested-prop-get left))
6960 (nconc head (list right))))))))
6961
6962 (defun js2-record-object-literal (node qname pos)
6963 "Recursively process an object literal looking for functions.
6964 NODE is an object literal that is the right-hand child of an assignment
6965 expression. QNAME is a list of nodes representing the assignment target,
6966 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6967 POS is the absolute position of the node.
6968 We do a depth-first traversal of NODE. For any functions we find,
6969 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6970 (let (right)
6971 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6972 (let ((left (js2-infix-node-left e))
6973 ;; Element positions are relative to the parent position.
6974 (pos (+ pos (js2-node-pos e))))
6975 (cond
6976 ;; foo: function() {...}
6977 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6978 (when (js2-prop-node-name left)
6979 ;; As a policy decision, we record the position of the property,
6980 ;; not the position of the `function' keyword, since the property
6981 ;; is effectively the name of the function.
6982 (js2-record-imenu-entry right (append qname (list left)) pos)))
6983 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6984 ((js2-object-node-p right)
6985 (js2-record-object-literal right
6986 (append qname (list (js2-infix-node-left e)))
6987 (+ pos (js2-node-pos right)))))))))
6988
6989 (defun js2-node-top-level-decl-p (node)
6990 "Return t if NODE's name is defined in the top-level scope.
6991 Also returns t if NODE's name is not defined in any scope, since it implies
6992 that it's an external variable, which must also be in the top-level scope."
6993 (let* ((name (js2-prop-node-name node))
6994 (this-scope (js2-node-get-enclosing-scope node))
6995 defining-scope)
6996 (cond
6997 ((js2-this-or-super-node-p node)
6998 nil)
6999 ((null this-scope)
7000 t)
7001 ((setq defining-scope (js2-get-defining-scope this-scope name))
7002 (js2-ast-root-p defining-scope))
7003 (t t))))
7004
7005 (defun js2-wrapper-function-p (node)
7006 "Return t if NODE is a function expression that's immediately invoked.
7007 NODE must be `js2-function-node'."
7008 (let ((parent (js2-node-parent node)))
7009 (or
7010 ;; function(){...}();
7011 (and (js2-call-node-p parent)
7012 (eq node (js2-call-node-target parent)))
7013 (and (js2-paren-node-p parent)
7014 ;; (function(){...})();
7015 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7016 ;; (function(){...}).call(this);
7017 (and (js2-prop-get-node-p parent)
7018 (member (js2-name-node-name (js2-prop-get-node-right parent))
7019 '("call" "apply"))
7020 (js2-call-node-p (js2-node-parent parent))))))))
7021
7022 (defun js2-browse-postprocess-chains ()
7023 "Modify function-declaration name chains after parsing finishes.
7024 Some of the information is only available after the parse tree is complete.
7025 For instance, processing a nested scope requires a parent function node."
7026 (let (result fn parent-qname p elem)
7027 (dolist (entry js2-imenu-recorder)
7028 ;; function node goes first
7029 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7030 ;; Examine head's defining scope:
7031 ;; Pre-processed chain, or top-level/external, keep as-is.
7032 (if (or (stringp head) (js2-node-top-level-decl-p head))
7033 (push chain result)
7034 (when (js2-this-or-super-node-p head)
7035 (setq chain (cdr chain))) ; discard this-node
7036 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7037 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7038 (when (eq parent-qname 'not-found)
7039 ;; anonymous function expressions are not recorded
7040 ;; during the parse, so we need to handle this case here
7041 (setq parent-qname
7042 (if (js2-wrapper-function-p fn)
7043 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7044 (if (js2-ast-root-p grandparent)
7045 nil
7046 (gethash grandparent js2-imenu-function-map 'skip)))
7047 'skip))
7048 (puthash fn parent-qname js2-imenu-function-map))
7049 (if (eq parent-qname 'skip)
7050 ;; We don't show it, let's record that fact.
7051 (remhash current-fn js2-imenu-function-map)
7052 ;; Prepend parent fn qname to this chain.
7053 (let ((qname (append parent-qname chain)))
7054 (puthash current-fn (butlast qname) js2-imenu-function-map)
7055 (push qname result)))))))
7056 ;; Collect chains obtained by third-party code.
7057 (let (js2-imenu-recorder)
7058 (run-hooks 'js2-build-imenu-callbacks)
7059 (dolist (entry js2-imenu-recorder)
7060 (push (cdr entry) result)))
7061 ;; Finally replace each node in each chain with its name.
7062 (dolist (chain result)
7063 (setq p chain)
7064 (while p
7065 (if (js2-node-p (setq elem (car p)))
7066 (setcar p (js2-node-qname-component elem)))
7067 (setq p (cdr p))))
7068 result))
7069
7070 ;; Merge name chains into a trie-like tree structure of nested lists.
7071 ;; To simplify construction of the trie, we first build it out using the rule
7072 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7073 ;; [key, num-or-list]. The second element can be a number; if so, this key
7074 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7075 ;; associated with the key at this level.) Otherwise the second element is
7076 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7077 ;; a simple recursive formulation.
7078 ;;
7079 ;; js2-mode is building the data structure for imenu. The imenu documentation
7080 ;; claims that it's the structure above, but in practice it wants the children
7081 ;; at the same list level as the key for that level, which is how I've drawn
7082 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7083 ;; list wrapper around the children at each level.
7084 ;;
7085 ;; A completed nested imenu-alist entry looks like this:
7086 ;; '(("foo"
7087 ;; ("<definition>" . 7)
7088 ;; ("bar"
7089 ;; ("a" . 40)
7090 ;; ("b" . 60))))
7091 ;;
7092 ;; In particular, the documentation for `imenu--index-alist' says that
7093 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7094 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7095
7096 (defun js2-treeify (lst)
7097 "Convert (a b c d) to (a ((b ((c d)))))."
7098 (if (null (cddr lst)) ; list length <= 2
7099 lst
7100 (list (car lst) (list (js2-treeify (cdr lst))))))
7101
7102 (defun js2-build-alist-trie (chains trie)
7103 "Merge declaration name chains into a trie-like alist structure for imenu.
7104 CHAINS is the qname chain list produced during parsing. TRIE is a
7105 list of elements built up so far."
7106 (let (head tail pos branch kids)
7107 (dolist (chain chains)
7108 (setq head (car chain)
7109 tail (cdr chain)
7110 pos (if (numberp (car tail)) (car tail))
7111 branch (js2-find-if (lambda (n)
7112 (string= (car n) head))
7113 trie)
7114 kids (second branch))
7115 (cond
7116 ;; case 1: this key isn't in the trie yet
7117 ((null branch)
7118 (if trie
7119 (setcdr (last trie) (list (js2-treeify chain)))
7120 (setq trie (list (js2-treeify chain)))))
7121 ;; case 2: key is present with a single number entry: replace w/ list
7122 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7123 ;; ("<definition>" 20)))
7124 ((numberp kids)
7125 (setcar (cdr branch)
7126 (list (list "<definition-1>" kids)
7127 (if pos
7128 (list "<definition-2>" pos)
7129 (js2-treeify tail)))))
7130 ;; case 3: key is there (with kids), and we're a number entry
7131 (pos
7132 (setcdr (last kids)
7133 (list
7134 (list (format "<definition-%d>"
7135 (1+ (loop for kid in kids
7136 count (eq ?< (aref (car kid) 0)))))
7137 pos))))
7138 ;; case 4: key is there with kids, need to merge in our chain
7139 (t
7140 (js2-build-alist-trie (list tail) kids))))
7141 trie))
7142
7143 (defun js2-flatten-trie (trie)
7144 "Convert TRIE to imenu-format.
7145 Recurses through nodes, and for each one whose second element is a list,
7146 appends the list's flattened elements to the current element. Also
7147 changes the tails into conses. For instance, this pre-flattened trie
7148
7149 '(a ((b 20)
7150 (c ((d 30)
7151 (e 40)))))
7152
7153 becomes
7154
7155 '(a (b . 20)
7156 (c (d . 30)
7157 (e . 40)))
7158
7159 Note that the root of the trie has no key, just a list of chains.
7160 This is also true for the value of any key with multiple children,
7161 e.g. key 'c' in the example above."
7162 (cond
7163 ((listp (car trie))
7164 (mapcar #'js2-flatten-trie trie))
7165 (t
7166 (if (numberp (second trie))
7167 (cons (car trie) (second trie))
7168 ;; else pop list and append its kids
7169 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7170
7171 (defun js2-build-imenu-index ()
7172 "Turn `js2-imenu-recorder' into an imenu data structure."
7173 (when (eq js2-imenu-recorder 'empty)
7174 (setq js2-imenu-recorder nil))
7175 (let* ((chains (js2-browse-postprocess-chains))
7176 (result (js2-build-alist-trie chains nil)))
7177 (js2-flatten-trie result)))
7178
7179 (defun js2-test-print-chains (chains)
7180 "Print a list of qname chains.
7181 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7182 i.e. one or more nodes, and an integer position as the list tail."
7183 (mapconcat (lambda (chain)
7184 (concat "("
7185 (mapconcat (lambda (elem)
7186 (if (js2-node-p elem)
7187 (or (js2-node-qname-component elem)
7188 "nil")
7189 (number-to-string elem)))
7190 chain
7191 " ")
7192 ")"))
7193 chains
7194 "\n"))
7195
7196 ;;; Parser
7197
7198 (defconst js2-version "1.8.5"
7199 "Version of JavaScript supported.")
7200
7201 (defun js2-record-face (face &optional token)
7202 "Record a style run of FACE for TOKEN or the current token."
7203 (unless token (setq token (js2-current-token)))
7204 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7205
7206 (defsubst js2-node-end (n)
7207 "Computes the absolute end of node N.
7208 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7209 is only true until the node is added to its parent; i.e., while parsing."
7210 (+ (js2-node-pos n)
7211 (js2-node-len n)))
7212
7213 (defun js2-record-comment (token)
7214 "Record a comment in `js2-scanned-comments'."
7215 (let ((ct (js2-token-comment-type token))
7216 (beg (js2-token-beg token))
7217 (end (js2-token-end token)))
7218 (push (make-js2-comment-node :len (- end beg)
7219 :format ct)
7220 js2-scanned-comments)
7221 (when js2-parse-ide-mode
7222 (js2-record-face (if (eq ct 'jsdoc)
7223 'font-lock-doc-face
7224 'font-lock-comment-face)
7225 token)
7226 (when (memq ct '(html preprocessor))
7227 ;; Tell cc-engine the bounds of the comment.
7228 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7229
7230 (defun js2-peek-token ()
7231 "Return the next token type without consuming it.
7232 If `js2-ti-lookahead' is positive, return the type of next token
7233 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7234 (if (not (zerop js2-ti-lookahead))
7235 (js2-token-type
7236 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7237 (let ((tt (js2-get-token-internal nil)))
7238 (js2-unget-token)
7239 tt)))
7240
7241 (defalias 'js2-next-token 'js2-get-token)
7242
7243 (defun js2-match-token (match &optional dont-unget)
7244 "Get next token and return t if it matches MATCH, a bytecode.
7245 Returns nil and consumes nothing if MATCH is not the next token."
7246 (if (/= (js2-get-token) match)
7247 (ignore (unless dont-unget (js2-unget-token)))
7248 t))
7249
7250 (defun js2-match-contextual-kwd (name)
7251 "Consume and return t if next token is `js2-NAME', and its
7252 string is NAME. Returns nil and keeps current token otherwise."
7253 (if (or (/= (js2-get-token) js2-NAME)
7254 (not (string= (js2-current-token-string) name)))
7255 (progn
7256 (js2-unget-token)
7257 nil)
7258 (js2-record-face 'font-lock-keyword-face)
7259 t))
7260
7261 (defun js2-get-prop-name-token ()
7262 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7263
7264 (defun js2-match-prop-name ()
7265 "Consume token and return t if next token is a valid property name.
7266 If `js2-language-version' is >= 180, a keyword or reserved word
7267 is considered valid name as well."
7268 (if (eq js2-NAME (js2-get-prop-name-token))
7269 t
7270 (js2-unget-token)
7271 nil))
7272
7273 (defun js2-must-match-prop-name (msg-id &optional pos len)
7274 (if (js2-match-prop-name)
7275 t
7276 (js2-report-error msg-id nil pos len)
7277 nil))
7278
7279 (defun js2-peek-token-or-eol ()
7280 "Return js2-EOL if the next token immediately follows a newline.
7281 Else returns the next token. Used in situations where we don't
7282 consider certain token types valid if they are preceded by a newline.
7283 One example is the postfix ++ or -- operator, which has to be on the
7284 same line as its operand."
7285 (let ((tt (js2-get-token))
7286 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7287 (js2-unget-token)
7288 (if follows-eol
7289 js2-EOL
7290 tt)))
7291
7292 (defun js2-must-match (token msg-id &optional pos len)
7293 "Match next token to token code TOKEN, or record a syntax error.
7294 MSG-ID is the error message to report if the match fails.
7295 Returns t on match, nil if no match."
7296 (if (js2-match-token token t)
7297 t
7298 (js2-report-error msg-id nil pos len)
7299 (js2-unget-token)
7300 nil))
7301
7302 (defun js2-must-match-name (msg-id)
7303 (if (js2-match-token js2-NAME t)
7304 t
7305 (if (eq (js2-current-token-type) js2-RESERVED)
7306 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7307 (js2-report-error msg-id)
7308 (js2-unget-token))
7309 nil))
7310
7311 (defsubst js2-inside-function ()
7312 (plusp js2-nesting-of-function))
7313
7314 (defun js2-set-requires-activation ()
7315 (if (js2-function-node-p js2-current-script-or-fn)
7316 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7317
7318 (defun js2-check-activation-name (name _token)
7319 (when (js2-inside-function)
7320 ;; skip language-version 1.2 check from Rhino
7321 (if (or (string= "arguments" name)
7322 (and js2-compiler-activation-names ; only used in codegen
7323 (gethash name js2-compiler-activation-names)))
7324 (js2-set-requires-activation))))
7325
7326 (defun js2-set-is-generator ()
7327 (let ((fn-node js2-current-script-or-fn))
7328 (when (and (js2-function-node-p fn-node)
7329 (not (js2-function-node-generator-type fn-node)))
7330 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7331
7332 (defun js2-must-have-xml ()
7333 (unless js2-compiler-xml-available
7334 (js2-report-error "msg.XML.not.available")))
7335
7336 (defun js2-push-scope (scope)
7337 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7338 (assert (js2-scope-p scope))
7339 (assert (null (js2-scope-parent-scope scope)))
7340 (assert (not (eq js2-current-scope scope)))
7341 (setf (js2-scope-parent-scope scope) js2-current-scope
7342 js2-current-scope scope))
7343
7344 (defsubst js2-pop-scope ()
7345 (setq js2-current-scope
7346 (js2-scope-parent-scope js2-current-scope)))
7347
7348 (defun js2-enter-loop (loop-node)
7349 (push loop-node js2-loop-set)
7350 (push loop-node js2-loop-and-switch-set)
7351 (js2-push-scope loop-node)
7352 ;; Tell the current labeled statement (if any) its statement,
7353 ;; and set the jump target of the first label to the loop.
7354 ;; These are used in `js2-parse-continue' to verify that the
7355 ;; continue target is an actual labeled loop. (And for codegen.)
7356 (when js2-labeled-stmt
7357 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7358 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7359 js2-labeled-stmt))) loop-node)))
7360
7361 (defun js2-exit-loop ()
7362 (pop js2-loop-set)
7363 (pop js2-loop-and-switch-set)
7364 (js2-pop-scope))
7365
7366 (defsubst js2-enter-switch (switch-node)
7367 (push switch-node js2-loop-and-switch-set))
7368
7369 (defsubst js2-exit-switch ()
7370 (pop js2-loop-and-switch-set))
7371
7372 (defun js2-parse (&optional buf cb)
7373 "Tell the js2 parser to parse a region of JavaScript.
7374
7375 BUF is a buffer or buffer name containing the code to parse.
7376 Call `narrow-to-region' first to parse only part of the buffer.
7377
7378 The returned AST root node is given some additional properties:
7379 `node-count' - total number of nodes in the AST
7380 `buffer' - BUF. The buffer it refers to may change or be killed,
7381 so the value is not necessarily reliable.
7382
7383 An optional callback CB can be specified to report parsing
7384 progress. If `(functionp CB)' returns t, it will be called with
7385 the current line number once before parsing begins, then again
7386 each time the lexer reaches a new line number.
7387
7388 CB can also be a list of the form `(symbol cb ...)' to specify
7389 multiple callbacks with different criteria. Each symbol is a
7390 criterion keyword, and the following element is the callback to
7391 call
7392
7393 :line - called whenever the line number changes
7394 :token - called for each new token consumed
7395
7396 The list of criteria could be extended to include entering or
7397 leaving a statement, an expression, or a function definition."
7398 (if (and cb (not (functionp cb)))
7399 (error "criteria callbacks not yet implemented"))
7400 (let ((inhibit-point-motion-hooks t)
7401 (js2-compiler-xml-available (>= js2-language-version 160))
7402 ;; This is a recursive-descent parser, so give it a big stack.
7403 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7404 (max-specpdl-size (max max-specpdl-size 3000))
7405 (case-fold-search nil)
7406 ast)
7407 (with-current-buffer (or buf (current-buffer))
7408 (setq js2-scanned-comments nil
7409 js2-parsed-errors nil
7410 js2-parsed-warnings nil
7411 js2-imenu-recorder nil
7412 js2-imenu-function-map nil
7413 js2-label-set nil)
7414 (js2-init-scanner)
7415 (setq ast (js2-do-parse))
7416 (unless js2-ts-hit-eof
7417 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7418 (setf (js2-ast-root-errors ast) js2-parsed-errors
7419 (js2-ast-root-warnings ast) js2-parsed-warnings)
7420 ;; if we didn't find any declarations, put a dummy in this list so we
7421 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7422 (unless js2-imenu-recorder
7423 (setq js2-imenu-recorder 'empty))
7424 (run-hooks 'js2-parse-finished-hook)
7425 ast)))
7426
7427 ;; Corresponds to Rhino's Parser.parse() method.
7428 (defun js2-do-parse ()
7429 "Parse current buffer starting from current point.
7430 Scanner should be initialized."
7431 (let ((pos js2-ts-cursor)
7432 (end js2-ts-cursor) ; in case file is empty
7433 root n tt)
7434 ;; initialize buffer-local parsing vars
7435 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7436 js2-current-script-or-fn root
7437 js2-current-scope root
7438 js2-nesting-of-function 0
7439 js2-labeled-stmt nil
7440 js2-recorded-identifiers nil) ; for js2-highlight
7441 (while (/= (setq tt (js2-get-token)) js2-EOF)
7442 (if (= tt js2-FUNCTION)
7443 (progn
7444 (setq n (if js2-called-by-compile-function
7445 (js2-parse-function-expr)
7446 (js2-parse-function-stmt))))
7447 ;; not a function - parse a statement
7448 (js2-unget-token)
7449 (setq n (js2-parse-statement)))
7450 ;; add function or statement to script
7451 (setq end (js2-node-end n))
7452 (js2-block-node-push root n))
7453 ;; add comments to root in lexical order
7454 (when js2-scanned-comments
7455 ;; if we find a comment beyond end of normal kids, use its end
7456 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7457 (dolist (comment js2-scanned-comments)
7458 (push comment (js2-ast-root-comments root))
7459 (js2-node-add-children root comment)))
7460 (setf (js2-node-len root) (- end pos))
7461 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7462 ;; Give extensions a chance to muck with things before highlighting starts.
7463 (let ((js2-additional-externs js2-additional-externs))
7464 (save-excursion
7465 (run-hooks 'js2-post-parse-callbacks))
7466 (js2-highlight-undeclared-vars))
7467 root))
7468
7469 (defun js2-parse-function-closure-body (fn-node)
7470 "Parse a JavaScript 1.8 function closure body."
7471 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7472 (if js2-ts-hit-eof
7473 (js2-report-error "msg.no.brace.body" nil
7474 (js2-node-pos fn-node)
7475 (- js2-ts-cursor (js2-node-pos fn-node)))
7476 (js2-node-add-children fn-node
7477 (setf (js2-function-node-body fn-node)
7478 (js2-parse-expr t))))))
7479
7480 (defun js2-parse-function-body (fn-node)
7481 (js2-must-match js2-LC "msg.no.brace.body"
7482 (js2-node-pos fn-node)
7483 (- js2-ts-cursor (js2-node-pos fn-node)))
7484 (let ((pos (js2-current-token-beg)) ; LC position
7485 (pn (make-js2-block-node)) ; starts at LC position
7486 tt
7487 end)
7488 (incf js2-nesting-of-function)
7489 (unwind-protect
7490 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7491 (= tt js2-EOF)
7492 (= tt js2-RC)))
7493 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7494 (js2-parse-statement)
7495 (js2-get-token)
7496 (js2-parse-function-stmt))))
7497 (decf js2-nesting-of-function))
7498 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7499 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7500 (setq end (js2-current-token-end)))
7501 (setf (js2-node-pos pn) pos
7502 (js2-node-len pn) (- end pos))
7503 (setf (js2-function-node-body fn-node) pn)
7504 (js2-node-add-children fn-node pn)
7505 pn))
7506
7507 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7508 "Declare and fontify destructuring parameters inside NODE.
7509 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7510 (cond
7511 ((js2-name-node-p node)
7512 (let (leftpos)
7513 (js2-define-symbol decl-type (js2-name-node-name node)
7514 node ignore-not-in-block)
7515 (when face
7516 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7517 (+ leftpos (js2-node-len node))
7518 face 'record))))
7519 ((js2-object-node-p node)
7520 (dolist (elem (js2-object-node-elems node))
7521 (js2-define-destruct-symbols
7522 ;; In abbreviated destructuring {a, b}, right == left.
7523 (js2-object-prop-node-right elem)
7524 decl-type face ignore-not-in-block)))
7525 ((js2-array-node-p node)
7526 (dolist (elem (js2-array-node-elems node))
7527 (when elem
7528 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7529 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7530 (js2-node-len node)))))
7531
7532 (defun js2-parse-function-params (function-type fn-node pos)
7533 (if (js2-match-token js2-RP)
7534 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7535 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7536 (eq (js2-current-token-type) js2-NAME)))
7537 params param default-found rest-param-at)
7538 (when paren-free-arrow
7539 (js2-unget-token))
7540 (loop for tt = (js2-peek-token)
7541 do
7542 (cond
7543 ;; destructuring param
7544 ((and (not paren-free-arrow)
7545 (or (= tt js2-LB) (= tt js2-LC)))
7546 (js2-get-token)
7547 (when default-found
7548 (js2-report-error "msg.no.default.after.default.param"))
7549 (setq param (js2-parse-destruct-primary-expr))
7550 (js2-define-destruct-symbols param
7551 js2-LP
7552 'js2-function-param)
7553 (push param params))
7554 ;; variable name
7555 (t
7556 (when (and (>= js2-language-version 200)
7557 (not paren-free-arrow)
7558 (js2-match-token js2-TRIPLEDOT)
7559 (not rest-param-at))
7560 ;; to report errors if there are more parameters
7561 (setq rest-param-at (length params)))
7562 (js2-must-match-name "msg.no.parm")
7563 (js2-record-face 'js2-function-param)
7564 (setq param (js2-create-name-node))
7565 (js2-define-symbol js2-LP (js2-current-token-string) param)
7566 ;; default parameter value
7567 (when (or (and default-found
7568 (not rest-param-at)
7569 (js2-must-match js2-ASSIGN
7570 "msg.no.default.after.default.param"
7571 (js2-node-pos param)
7572 (js2-node-len param)))
7573 (and (>= js2-language-version 200)
7574 (js2-match-token js2-ASSIGN)))
7575 (assert (not paren-free-arrow))
7576 (let* ((pos (js2-node-pos param))
7577 (tt (js2-current-token-type))
7578 (op-pos (- (js2-current-token-beg) pos))
7579 (left param)
7580 (right (js2-parse-assign-expr))
7581 (len (- (js2-node-end right) pos)))
7582 (setq param (make-js2-assign-node
7583 :type tt :pos pos :len len :op-pos op-pos
7584 :left left :right right)
7585 default-found t)
7586 (js2-node-add-children param left right)))
7587 (push param params)))
7588 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7589 (js2-report-error "msg.param.after.rest" nil
7590 (js2-node-pos param) (js2-node-len param)))
7591 while
7592 (js2-match-token js2-COMMA))
7593 (when (and (not paren-free-arrow)
7594 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7595 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7596 (when rest-param-at
7597 (setf (js2-function-node-rest-p fn-node) t))
7598 (dolist (p params)
7599 (js2-node-add-children fn-node p)
7600 (push p (js2-function-node-params fn-node))))))
7601
7602 (defun js2-check-inconsistent-return-warning (fn-node name)
7603 "Possibly show inconsistent-return warning.
7604 Last token scanned is the close-curly for the function body."
7605 (when (and js2-mode-show-strict-warnings
7606 js2-strict-inconsistent-return-warning
7607 (not (js2-has-consistent-return-usage
7608 (js2-function-node-body fn-node))))
7609 ;; Have it extend from close-curly to bol or beginning of block.
7610 (let ((pos (save-excursion
7611 (goto-char (js2-current-token-end))
7612 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7613 (point-at-bol))))
7614 (end (js2-current-token-end)))
7615 (if (plusp (js2-name-node-length name))
7616 (js2-add-strict-warning "msg.no.return.value"
7617 (js2-name-node-name name) pos end)
7618 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7619
7620 (defun js2-parse-function-stmt ()
7621 (let ((pos (js2-current-token-beg))
7622 (star-p (js2-match-token js2-MUL)))
7623 (js2-must-match-name "msg.unnamed.function.stmt")
7624 (let ((name (js2-create-name-node t))
7625 pn member-expr)
7626 (cond
7627 ((js2-match-token js2-LP)
7628 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7629 (js2-allow-member-expr-as-function-name
7630 (setq member-expr (js2-parse-member-expr-tail nil name))
7631 (js2-parse-highlight-member-expr-fn-name member-expr)
7632 (js2-must-match js2-LP "msg.no.paren.parms")
7633 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7634 (js2-function-node-member-expr pn) member-expr)
7635 pn)
7636 (t
7637 (js2-report-error "msg.no.paren.parms")
7638 (make-js2-error-node))))))
7639
7640 (defun js2-parse-function-expr ()
7641 (let ((pos (js2-current-token-beg))
7642 (star-p (js2-match-token js2-MUL))
7643 name)
7644 (when (js2-match-token js2-NAME)
7645 (setq name (js2-create-name-node t)))
7646 (js2-must-match js2-LP "msg.no.paren.parms")
7647 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7648
7649 (defun js2-parse-function (function-type pos star-p &optional name)
7650 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7651 beginning of the first token (function keyword, unless it's an
7652 arrow function), NAME is js2-name-node."
7653 (let (fn-node lp)
7654 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7655 (setq lp (js2-current-token-beg)))
7656 (setf fn-node (make-js2-function-node :pos pos
7657 :name name
7658 :form function-type
7659 :lp (if lp (- lp pos))
7660 :generator-type (and star-p 'STAR)))
7661 (when name
7662 (js2-set-face (js2-node-pos name) (js2-node-end name)
7663 'font-lock-function-name-face 'record)
7664 (when (and (eq function-type 'FUNCTION_STATEMENT)
7665 (plusp (js2-name-node-length name)))
7666 ;; Function statements define a symbol in the enclosing scope
7667 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7668 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7669 ;; 1. Nested functions are not affected by the dynamic scope flag
7670 ;; as dynamic scope is already a parent of their scope.
7671 ;; 2. Functions defined under the with statement also immune to
7672 ;; this setup, in which case dynamic scope is ignored in favor
7673 ;; of the with object.
7674 (setf (js2-function-node-ignore-dynamic fn-node) t))
7675 ;; dynamically bind all the per-function variables
7676 (let ((js2-current-script-or-fn fn-node)
7677 (js2-current-scope fn-node)
7678 (js2-nesting-of-with 0)
7679 (js2-end-flags 0)
7680 js2-label-set
7681 js2-loop-set
7682 js2-loop-and-switch-set)
7683 (js2-parse-function-params function-type fn-node pos)
7684 (when (eq function-type 'FUNCTION_ARROW)
7685 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7686 (if (and (>= js2-language-version 180)
7687 (/= (js2-peek-token) js2-LC))
7688 (js2-parse-function-closure-body fn-node)
7689 (js2-parse-function-body fn-node))
7690 (js2-check-inconsistent-return-warning fn-node name)
7691
7692 (when name
7693 (js2-node-add-children fn-node name)
7694 ;; Function expressions define a name only in the body of the
7695 ;; function, and only if not hidden by a parameter name
7696 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7697 (null (js2-scope-get-symbol js2-current-scope
7698 (js2-name-node-name name))))
7699 (js2-define-symbol js2-FUNCTION
7700 (js2-name-node-name name)
7701 fn-node))
7702 (when (eq function-type 'FUNCTION_STATEMENT)
7703 (js2-record-imenu-functions fn-node))))
7704
7705 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7706 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7707 ;; We wait until after parsing the function to set its parent scope,
7708 ;; since `js2-define-symbol' needs the defining-scope check to stop
7709 ;; at the function boundary when checking for redeclarations.
7710 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7711 fn-node))
7712
7713 (defun js2-parse-statements (&optional parent)
7714 "Parse a statement list. Last token consumed must be js2-LC.
7715
7716 PARENT can be a `js2-block-node', in which case the statements are
7717 appended to PARENT. Otherwise a new `js2-block-node' is created
7718 and returned.
7719
7720 This function does not match the closing js2-RC: the caller
7721 matches the RC so it can provide a suitable error message if not
7722 matched. This means it's up to the caller to set the length of
7723 the node to include the closing RC. The node start pos is set to
7724 the absolute buffer start position, and the caller should fix it
7725 up to be relative to the parent node. All children of this block
7726 node are given relative start positions and correct lengths."
7727 (let ((pn (or parent (make-js2-block-node)))
7728 tt)
7729 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7730 (/= tt js2-RC))
7731 (js2-block-node-push pn (js2-parse-statement)))
7732 pn))
7733
7734 (defun js2-parse-statement ()
7735 (let (pn beg end)
7736 ;; coarse-grained user-interrupt check - needs work
7737 (and js2-parse-interruptable-p
7738 (zerop (% (incf js2-parse-stmt-count)
7739 js2-statements-per-pause))
7740 (input-pending-p)
7741 (throw 'interrupted t))
7742 (setq pn (js2-statement-helper))
7743 ;; no-side-effects warning check
7744 (unless (js2-node-has-side-effects pn)
7745 (setq end (js2-node-end pn))
7746 (save-excursion
7747 (goto-char end)
7748 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7749 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7750 pn))
7751
7752 ;; These correspond to the switch cases in Parser.statementHelper
7753 (defconst js2-parsers
7754 (let ((parsers (make-vector js2-num-tokens
7755 #'js2-parse-expr-stmt)))
7756 (aset parsers js2-BREAK #'js2-parse-break)
7757 (aset parsers js2-CLASS #'js2-parse-class-stmt)
7758 (aset parsers js2-CONST #'js2-parse-const-var)
7759 (aset parsers js2-CONTINUE #'js2-parse-continue)
7760 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7761 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7762 (aset parsers js2-DO #'js2-parse-do)
7763 (aset parsers js2-FOR #'js2-parse-for)
7764 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7765 (aset parsers js2-IF #'js2-parse-if)
7766 (aset parsers js2-LC #'js2-parse-block)
7767 (aset parsers js2-LET #'js2-parse-let-stmt)
7768 (aset parsers js2-NAME #'js2-parse-name-or-label)
7769 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7770 (aset parsers js2-SEMI #'js2-parse-semi)
7771 (aset parsers js2-SWITCH #'js2-parse-switch)
7772 (aset parsers js2-THROW #'js2-parse-throw)
7773 (aset parsers js2-TRY #'js2-parse-try)
7774 (aset parsers js2-VAR #'js2-parse-const-var)
7775 (aset parsers js2-WHILE #'js2-parse-while)
7776 (aset parsers js2-WITH #'js2-parse-with)
7777 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7778 parsers)
7779 "A vector mapping token types to parser functions.")
7780
7781 (defun js2-parse-warn-missing-semi (beg end)
7782 (and js2-mode-show-strict-warnings
7783 js2-strict-missing-semi-warning
7784 (js2-add-strict-warning
7785 "msg.missing.semi" nil
7786 ;; back up to beginning of statement or line
7787 (max beg (save-excursion
7788 (goto-char end)
7789 (point-at-bol)))
7790 end)))
7791
7792 (defconst js2-no-semi-insertion
7793 (list js2-IF
7794 js2-SWITCH
7795 js2-WHILE
7796 js2-DO
7797 js2-FOR
7798 js2-TRY
7799 js2-WITH
7800 js2-LC
7801 js2-ERROR
7802 js2-SEMI
7803 js2-CLASS
7804 js2-FUNCTION)
7805 "List of tokens that don't do automatic semicolon insertion.")
7806
7807 (defconst js2-autoinsert-semi-and-warn
7808 (list js2-ERROR js2-EOF js2-RC))
7809
7810 (defun js2-statement-helper ()
7811 (let* ((tt (js2-get-token))
7812 (first-tt tt)
7813 (parser (if (= tt js2-ERROR)
7814 #'js2-parse-semi
7815 (aref js2-parsers tt)))
7816 pn)
7817 ;; If the statement is set, then it's been told its label by now.
7818 (and js2-labeled-stmt
7819 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7820 (setq js2-labeled-stmt nil))
7821 (setq pn (funcall parser))
7822 ;; Don't do auto semi insertion for certain statement types.
7823 (unless (or (memq first-tt js2-no-semi-insertion)
7824 (js2-labeled-stmt-node-p pn))
7825 (js2-auto-insert-semicolon pn))
7826 pn))
7827
7828 (defun js2-auto-insert-semicolon (pn)
7829 (let* ((tt (js2-get-token))
7830 (pos (js2-node-pos pn)))
7831 (cond
7832 ((= tt js2-SEMI)
7833 ;; extend the node bounds to include the semicolon.
7834 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7835 ((memq tt js2-autoinsert-semi-and-warn)
7836 (js2-unget-token) ; Not ';', do not consume.
7837 ;; Autoinsert ;
7838 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7839 (t
7840 (if (not (js2-token-follows-eol-p (js2-current-token)))
7841 ;; Report error if no EOL or autoinsert ';' otherwise
7842 (js2-report-error "msg.no.semi.stmt")
7843 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7844 (js2-unget-token) ; Not ';', do not consume.
7845 ))))
7846
7847 (defun js2-parse-condition ()
7848 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7849 The parens are discarded and the expression node is returned.
7850 The `pos' field of the return value is set to an absolute position
7851 that must be fixed up by the caller.
7852 Return value is a list (EXPR LP RP), with absolute paren positions."
7853 (let (pn lp rp)
7854 (if (js2-must-match js2-LP "msg.no.paren.cond")
7855 (setq lp (js2-current-token-beg)))
7856 (setq pn (js2-parse-expr))
7857 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7858 (setq rp (js2-current-token-beg)))
7859 ;; Report strict warning on code like "if (a = 7) ..."
7860 (if (and js2-strict-cond-assign-warning
7861 (js2-assign-node-p pn))
7862 (js2-add-strict-warning "msg.equal.as.assign" nil
7863 (js2-node-pos pn)
7864 (+ (js2-node-pos pn)
7865 (js2-node-len pn))))
7866 (list pn lp rp)))
7867
7868 (defun js2-parse-if ()
7869 "Parser for if-statement. Last matched token must be js2-IF."
7870 (let ((pos (js2-current-token-beg))
7871 cond if-true if-false else-pos end pn)
7872 (setq cond (js2-parse-condition)
7873 if-true (js2-parse-statement)
7874 if-false (if (js2-match-token js2-ELSE)
7875 (progn
7876 (setq else-pos (- (js2-current-token-beg) pos))
7877 (js2-parse-statement)))
7878 end (js2-node-end (or if-false if-true))
7879 pn (make-js2-if-node :pos pos
7880 :len (- end pos)
7881 :condition (car cond)
7882 :then-part if-true
7883 :else-part if-false
7884 :else-pos else-pos
7885 :lp (js2-relpos (second cond) pos)
7886 :rp (js2-relpos (third cond) pos)))
7887 (js2-node-add-children pn (car cond) if-true if-false)
7888 pn))
7889
7890 (defun js2-parse-switch ()
7891 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7892 (let ((pos (js2-current-token-beg))
7893 tt pn discriminant has-default case-expr case-node
7894 case-pos cases stmt lp)
7895 (if (js2-must-match js2-LP "msg.no.paren.switch")
7896 (setq lp (js2-current-token-beg)))
7897 (setq discriminant (js2-parse-expr)
7898 pn (make-js2-switch-node :discriminant discriminant
7899 :pos pos
7900 :lp (js2-relpos lp pos)))
7901 (js2-node-add-children pn discriminant)
7902 (js2-enter-switch pn)
7903 (unwind-protect
7904 (progn
7905 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7906 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7907 (js2-must-match js2-LC "msg.no.brace.switch")
7908 (catch 'break
7909 (while t
7910 (setq tt (js2-next-token)
7911 case-pos (js2-current-token-beg))
7912 (cond
7913 ((= tt js2-RC)
7914 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7915 (throw 'break nil)) ; done
7916 ((= tt js2-CASE)
7917 (setq case-expr (js2-parse-expr))
7918 (js2-must-match js2-COLON "msg.no.colon.case"))
7919 ((= tt js2-DEFAULT)
7920 (if has-default
7921 (js2-report-error "msg.double.switch.default"))
7922 (setq has-default t
7923 case-expr nil)
7924 (js2-must-match js2-COLON "msg.no.colon.case"))
7925 (t
7926 (js2-report-error "msg.bad.switch")
7927 (throw 'break nil)))
7928 (setq case-node (make-js2-case-node :pos case-pos
7929 :len (- (js2-current-token-end) case-pos)
7930 :expr case-expr))
7931 (js2-node-add-children case-node case-expr)
7932 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7933 (/= tt js2-CASE)
7934 (/= tt js2-DEFAULT)
7935 (/= tt js2-EOF))
7936 (setf stmt (js2-parse-statement)
7937 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7938 (js2-block-node-push case-node stmt))
7939 (push case-node cases)))
7940 ;; add cases last, as pushing reverses the order to be correct
7941 (dolist (kid cases)
7942 (js2-node-add-children pn kid)
7943 (push kid (js2-switch-node-cases pn)))
7944 pn) ; return value
7945 (js2-exit-switch))))
7946
7947 (defun js2-parse-while ()
7948 "Parser for while-statement. Last matched token must be js2-WHILE."
7949 (let ((pos (js2-current-token-beg))
7950 (pn (make-js2-while-node))
7951 cond body)
7952 (js2-enter-loop pn)
7953 (unwind-protect
7954 (progn
7955 (setf cond (js2-parse-condition)
7956 (js2-while-node-condition pn) (car cond)
7957 body (js2-parse-statement)
7958 (js2-while-node-body pn) body
7959 (js2-node-len pn) (- (js2-node-end body) pos)
7960 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7961 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7962 (js2-node-add-children pn body (car cond)))
7963 (js2-exit-loop))
7964 pn))
7965
7966 (defun js2-parse-do ()
7967 "Parser for do-statement. Last matched token must be js2-DO."
7968 (let ((pos (js2-current-token-beg))
7969 (pn (make-js2-do-node))
7970 cond body end)
7971 (js2-enter-loop pn)
7972 (unwind-protect
7973 (progn
7974 (setq body (js2-parse-statement))
7975 (js2-must-match js2-WHILE "msg.no.while.do")
7976 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7977 cond (js2-parse-condition)
7978 (js2-do-node-condition pn) (car cond)
7979 (js2-do-node-body pn) body
7980 end js2-ts-cursor
7981 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7982 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7983 (js2-node-add-children pn (car cond) body))
7984 (js2-exit-loop))
7985 ;; Always auto-insert semicolon to follow SpiderMonkey:
7986 ;; It is required by ECMAScript but is ignored by the rest of
7987 ;; world; see bug 238945
7988 (if (js2-match-token js2-SEMI)
7989 (setq end js2-ts-cursor))
7990 (setf (js2-node-len pn) (- end pos))
7991 pn))
7992
7993 (defun js2-parse-for ()
7994 "Parser for for-statement. Last matched token must be js2-FOR.
7995 Parses for, for-in, and for each-in statements."
7996 (let ((for-pos (js2-current-token-beg))
7997 pn is-for-each is-for-in-or-of is-for-of
7998 in-pos each-pos tmp-pos
7999 init ; Node init is also foo in 'foo in object'
8000 cond ; Node cond is also object in 'foo in object'
8001 incr ; 3rd section of for-loop initializer
8002 body tt lp rp)
8003 ;; See if this is a for each () instead of just a for ()
8004 (when (js2-match-token js2-NAME)
8005 (if (string= "each" (js2-current-token-string))
8006 (progn
8007 (setq is-for-each t
8008 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8009 (js2-record-face 'font-lock-keyword-face))
8010 (js2-report-error "msg.no.paren.for")))
8011 (if (js2-must-match js2-LP "msg.no.paren.for")
8012 (setq lp (- (js2-current-token-beg) for-pos)))
8013 (setq tt (js2-get-token))
8014 ;; 'for' makes local scope
8015 (js2-push-scope (make-js2-scope))
8016 (unwind-protect
8017 ;; parse init clause
8018 (let ((js2-in-for-init t)) ; set as dynamic variable
8019 (cond
8020 ((= tt js2-SEMI)
8021 (js2-unget-token)
8022 (setq init (make-js2-empty-expr-node)))
8023 ((or (= tt js2-VAR) (= tt js2-LET))
8024 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8025 (t
8026 (js2-unget-token)
8027 (setq init (js2-parse-expr)))))
8028 (if (or (js2-match-token js2-IN)
8029 (and (>= js2-language-version 200)
8030 (js2-match-contextual-kwd "of")
8031 (setq is-for-of t)))
8032 (setq is-for-in-or-of t
8033 in-pos (- (js2-current-token-beg) for-pos)
8034 ;; scope of iteration target object is not the scope we've created above.
8035 ;; stash current scope temporary.
8036 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8037 (js2-parse-expr))) ; object over which we're iterating
8038 ;; else ordinary for loop - parse cond and incr
8039 (js2-must-match js2-SEMI "msg.no.semi.for")
8040 (setq cond (if (= (js2-peek-token) js2-SEMI)
8041 (make-js2-empty-expr-node) ; no loop condition
8042 (js2-parse-expr)))
8043 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8044 (setq tmp-pos (js2-current-token-end)
8045 incr (if (= (js2-peek-token) js2-RP)
8046 (make-js2-empty-expr-node :pos tmp-pos)
8047 (js2-parse-expr))))
8048 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8049 (setq rp (- (js2-current-token-beg) for-pos)))
8050 (if (not is-for-in-or-of)
8051 (setq pn (make-js2-for-node :init init
8052 :condition cond
8053 :update incr
8054 :lp lp
8055 :rp rp))
8056 ;; cond could be null if 'in obj' got eaten by the init node.
8057 (if (js2-infix-node-p init)
8058 ;; it was (foo in bar) instead of (var foo in bar)
8059 (setq cond (js2-infix-node-right init)
8060 init (js2-infix-node-left init))
8061 (if (and (js2-var-decl-node-p init)
8062 (> (length (js2-var-decl-node-kids init)) 1))
8063 (js2-report-error "msg.mult.index")))
8064 (setq pn (make-js2-for-in-node :iterator init
8065 :object cond
8066 :in-pos in-pos
8067 :foreach-p is-for-each
8068 :each-pos each-pos
8069 :forof-p is-for-of
8070 :lp lp
8071 :rp rp)))
8072 (unwind-protect
8073 (progn
8074 (js2-enter-loop pn)
8075 ;; We have to parse the body -after- creating the loop node,
8076 ;; so that the loop node appears in the js2-loop-set, allowing
8077 ;; break/continue statements to find the enclosing loop.
8078 (setf body (js2-parse-statement)
8079 (js2-loop-node-body pn) body
8080 (js2-node-pos pn) for-pos
8081 (js2-node-len pn) (- (js2-node-end body) for-pos))
8082 (js2-node-add-children pn init cond incr body))
8083 ;; finally
8084 (js2-exit-loop))
8085 (js2-pop-scope))
8086 pn))
8087
8088 (defun js2-parse-try ()
8089 "Parse a try statement. Last matched token must be js2-TRY."
8090 (let ((try-pos (js2-current-token-beg))
8091 try-end
8092 try-block
8093 catch-blocks
8094 finally-block
8095 saw-default-catch
8096 peek)
8097 (if (/= (js2-peek-token) js2-LC)
8098 (js2-report-error "msg.no.brace.try"))
8099 (setq try-block (js2-parse-statement)
8100 try-end (js2-node-end try-block)
8101 peek (js2-peek-token))
8102 (cond
8103 ((= peek js2-CATCH)
8104 (while (js2-match-token js2-CATCH)
8105 (let* ((catch-pos (js2-current-token-beg))
8106 (catch-node (make-js2-catch-node :pos catch-pos))
8107 param
8108 guard-kwd
8109 catch-cond
8110 lp rp)
8111 (if saw-default-catch
8112 (js2-report-error "msg.catch.unreachable"))
8113 (if (js2-must-match js2-LP "msg.no.paren.catch")
8114 (setq lp (- (js2-current-token-beg) catch-pos)))
8115 (js2-push-scope catch-node)
8116 (let ((tt (js2-peek-token)))
8117 (cond
8118 ;; Destructuring pattern:
8119 ;; catch ({ message, file }) { ... }
8120 ((or (= tt js2-LB) (= tt js2-LC))
8121 (js2-get-token)
8122 (setq param (js2-parse-destruct-primary-expr))
8123 (js2-define-destruct-symbols param js2-LET nil))
8124 ;; Simple name.
8125 (t
8126 (js2-must-match-name "msg.bad.catchcond")
8127 (setq param (js2-create-name-node))
8128 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8129 ;; Catch condition.
8130 (if (js2-match-token js2-IF)
8131 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8132 catch-cond (js2-parse-expr))
8133 (setq saw-default-catch t))
8134 (if (js2-must-match js2-RP "msg.bad.catchcond")
8135 (setq rp (- (js2-current-token-beg) catch-pos)))
8136 (js2-must-match js2-LC "msg.no.brace.catchblock")
8137 (js2-parse-statements catch-node)
8138 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8139 (setq try-end (js2-current-token-end)))
8140 (js2-pop-scope)
8141 (setf (js2-node-len catch-node) (- try-end catch-pos)
8142 (js2-catch-node-param catch-node) param
8143 (js2-catch-node-guard-expr catch-node) catch-cond
8144 (js2-catch-node-guard-kwd catch-node) guard-kwd
8145 (js2-catch-node-lp catch-node) lp
8146 (js2-catch-node-rp catch-node) rp)
8147 (js2-node-add-children catch-node param catch-cond)
8148 (push catch-node catch-blocks))))
8149 ((/= peek js2-FINALLY)
8150 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8151 (js2-node-pos try-block)
8152 (- (setq try-end (js2-node-end try-block))
8153 (js2-node-pos try-block)))))
8154 (when (js2-match-token js2-FINALLY)
8155 (let ((finally-pos (js2-current-token-beg))
8156 (block (js2-parse-statement)))
8157 (setq try-end (js2-node-end block)
8158 finally-block (make-js2-finally-node :pos finally-pos
8159 :len (- try-end finally-pos)
8160 :body block))
8161 (js2-node-add-children finally-block block)))
8162 (let ((pn (make-js2-try-node :pos try-pos
8163 :len (- try-end try-pos)
8164 :try-block try-block
8165 :finally-block finally-block)))
8166 (js2-node-add-children pn try-block finally-block)
8167 ;; Push them onto the try-node, which reverses and corrects their order.
8168 (dolist (cb catch-blocks)
8169 (js2-node-add-children pn cb)
8170 (push cb (js2-try-node-catch-clauses pn)))
8171 pn)))
8172
8173 (defun js2-parse-throw ()
8174 "Parser for throw-statement. Last matched token must be js2-THROW."
8175 (let ((pos (js2-current-token-beg))
8176 expr pn)
8177 (if (= (js2-peek-token-or-eol) js2-EOL)
8178 ;; ECMAScript does not allow new lines before throw expression,
8179 ;; see bug 256617
8180 (js2-report-error "msg.bad.throw.eol"))
8181 (setq expr (js2-parse-expr)
8182 pn (make-js2-throw-node :pos pos
8183 :len (- (js2-node-end expr) pos)
8184 :expr expr))
8185 (js2-node-add-children pn expr)
8186 pn))
8187
8188 (defun js2-match-jump-label-name (label-name)
8189 "If break/continue specified a label, return that label's labeled stmt.
8190 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8191 does not match an existing label, reports an error and returns nil."
8192 (let ((bundle (cdr (assoc label-name js2-label-set))))
8193 (if (null bundle)
8194 (js2-report-error "msg.undef.label"))
8195 bundle))
8196
8197 (defun js2-parse-break ()
8198 "Parser for break-statement. Last matched token must be js2-BREAK."
8199 (let ((pos (js2-current-token-beg))
8200 (end (js2-current-token-end))
8201 break-target ; statement to break from
8202 break-label ; in "break foo", name-node representing the foo
8203 labels ; matching labeled statement to break to
8204 pn)
8205 (when (eq (js2-peek-token-or-eol) js2-NAME)
8206 (js2-get-token)
8207 (setq break-label (js2-create-name-node)
8208 end (js2-node-end break-label)
8209 ;; matchJumpLabelName only matches if there is one
8210 labels (js2-match-jump-label-name (js2-current-token-string))
8211 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8212 (unless (or break-target break-label)
8213 ;; no break target specified - try for innermost enclosing loop/switch
8214 (if (null js2-loop-and-switch-set)
8215 (unless break-label
8216 (js2-report-error "msg.bad.break" nil pos (length "break")))
8217 (setq break-target (car js2-loop-and-switch-set))))
8218 (setq pn (make-js2-break-node :pos pos
8219 :len (- end pos)
8220 :label break-label
8221 :target break-target))
8222 (js2-node-add-children pn break-label) ; but not break-target
8223 pn))
8224
8225 (defun js2-parse-continue ()
8226 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8227 (let ((pos (js2-current-token-beg))
8228 (end (js2-current-token-end))
8229 label ; optional user-specified label, a `js2-name-node'
8230 labels ; current matching labeled stmt, if any
8231 target ; the `js2-loop-node' target of this continue stmt
8232 pn)
8233 (when (= (js2-peek-token-or-eol) js2-NAME)
8234 (js2-get-token)
8235 (setq label (js2-create-name-node)
8236 end (js2-node-end label)
8237 ;; matchJumpLabelName only matches if there is one
8238 labels (js2-match-jump-label-name (js2-current-token-string))))
8239 (cond
8240 ((null labels) ; no current label to go to
8241 (if (null js2-loop-set) ; no loop to continue to
8242 (js2-report-error "msg.continue.outside" nil pos
8243 (length "continue"))
8244 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8245 (t
8246 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8247 (setq target (js2-labeled-stmt-node-stmt labels))
8248 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8249 (setq pn (make-js2-continue-node :pos pos
8250 :len (- end pos)
8251 :label label
8252 :target target))
8253 (js2-node-add-children pn label) ; but not target - it's not our child
8254 pn))
8255
8256 (defun js2-parse-with ()
8257 "Parser for with-statement. Last matched token must be js2-WITH."
8258 (let ((pos (js2-current-token-beg))
8259 obj body pn lp rp)
8260 (if (js2-must-match js2-LP "msg.no.paren.with")
8261 (setq lp (js2-current-token-beg)))
8262 (setq obj (js2-parse-expr))
8263 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8264 (setq rp (js2-current-token-beg)))
8265 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8266 (setq body (js2-parse-statement)))
8267 (setq pn (make-js2-with-node :pos pos
8268 :len (- (js2-node-end body) pos)
8269 :object obj
8270 :body body
8271 :lp (js2-relpos lp pos)
8272 :rp (js2-relpos rp pos)))
8273 (js2-node-add-children pn obj body)
8274 pn))
8275
8276 (defun js2-parse-const-var ()
8277 "Parser for var- or const-statement.
8278 Last matched token must be js2-CONST or js2-VAR."
8279 (let ((tt (js2-current-token-type))
8280 (pos (js2-current-token-beg))
8281 expr pn)
8282 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8283 pn (make-js2-expr-stmt-node :pos pos
8284 :len (- (js2-node-end expr) pos)
8285 :expr expr))
8286 (js2-node-add-children pn expr)
8287 pn))
8288
8289 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8290 (let ((pn (make-js2-expr-stmt-node :pos pos
8291 :len (js2-node-len expr)
8292 :type (if (js2-inside-function)
8293 js2-EXPR_VOID
8294 js2-EXPR_RESULT)
8295 :expr expr)))
8296 (if add-child
8297 (js2-node-add-children pn expr))
8298 pn))
8299
8300 (defun js2-parse-let-stmt ()
8301 "Parser for let-statement. Last matched token must be js2-LET."
8302 (let ((pos (js2-current-token-beg))
8303 expr pn)
8304 (if (= (js2-peek-token) js2-LP)
8305 ;; let expression in statement context
8306 (setq expr (js2-parse-let pos 'statement)
8307 pn (js2-wrap-with-expr-stmt pos expr t))
8308 ;; else we're looking at a statement like let x=6, y=7;
8309 (setf expr (js2-parse-variables js2-LET pos)
8310 pn (js2-wrap-with-expr-stmt pos expr t)
8311 (js2-node-type pn) js2-EXPR_RESULT))
8312 pn))
8313
8314 (defun js2-parse-ret-yield ()
8315 (js2-parse-return-or-yield (js2-current-token-type) nil))
8316
8317 (defconst js2-parse-return-stmt-enders
8318 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8319
8320 (defsubst js2-now-all-set (before after mask)
8321 "Return whether or not the bits in the mask have changed to all set.
8322 BEFORE is bits before change, AFTER is bits after change, and MASK is
8323 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8324 but not BEFORE."
8325 (and (/= (logand before mask) mask)
8326 (= (logand after mask) mask)))
8327
8328 (defun js2-parse-return-or-yield (tt expr-context)
8329 (let* ((pos (js2-current-token-beg))
8330 (end (js2-current-token-end))
8331 (before js2-end-flags)
8332 (inside-function (js2-inside-function))
8333 (gen-type (and inside-function (js2-function-node-generator-type
8334 js2-current-script-or-fn)))
8335 e ret name yield-star-p)
8336 (unless inside-function
8337 (js2-report-error (if (eq tt js2-RETURN)
8338 "msg.bad.return"
8339 "msg.bad.yield")))
8340 (when (and inside-function
8341 (eq gen-type 'STAR)
8342 (js2-match-token js2-MUL))
8343 (setq yield-star-p t))
8344 ;; This is ugly, but we don't want to require a semicolon.
8345 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8346 (setq e (js2-parse-expr)
8347 end (js2-node-end e)))
8348 (cond
8349 ((eq tt js2-RETURN)
8350 (js2-set-flag js2-end-flags (if (null e)
8351 js2-end-returns
8352 js2-end-returns-value))
8353 (setq ret (make-js2-return-node :pos pos
8354 :len (- end pos)
8355 :retval e))
8356 (js2-node-add-children ret e)
8357 ;; See if we need a strict mode warning.
8358 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8359 ;; more thorough and accurate than this before/after flag check.
8360 ;; E.g. if there's a finally-block that always returns, we shouldn't
8361 ;; show a warning generated by inconsistent returns in the catch blocks.
8362 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8363 ;; so we know which returns/yields to highlight, and we should get rid of
8364 ;; all the checking in `js2-parse-return-or-yield'.
8365 (if (and js2-strict-inconsistent-return-warning
8366 (js2-now-all-set before js2-end-flags
8367 (logior js2-end-returns js2-end-returns-value)))
8368 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8369 ((eq gen-type 'COMPREHENSION)
8370 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8371 ;; like SpiderMonkey does.
8372 (js2-report-error "msg.syntax" nil pos 5))
8373 (t
8374 (setq ret (make-js2-yield-node :pos pos
8375 :len (- end pos)
8376 :value e
8377 :star-p yield-star-p))
8378 (js2-node-add-children ret e)
8379 (unless expr-context
8380 (setq e ret
8381 ret (js2-wrap-with-expr-stmt pos e t))
8382 (js2-set-requires-activation)
8383 (js2-set-is-generator))))
8384 ;; see if we are mixing yields and value returns.
8385 (when (and inside-function
8386 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8387 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8388 'LEGACY))
8389 (setq name (js2-function-name js2-current-script-or-fn))
8390 (if (zerop (length name))
8391 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8392 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8393 ret))
8394
8395 (defun js2-parse-debugger ()
8396 (make-js2-keyword-node :type js2-DEBUGGER))
8397
8398 (defun js2-parse-block ()
8399 "Parser for a curly-delimited statement block.
8400 Last token matched must be `js2-LC'."
8401 (let ((pos (js2-current-token-beg))
8402 (pn (make-js2-scope)))
8403 (js2-push-scope pn)
8404 (unwind-protect
8405 (progn
8406 (js2-parse-statements pn)
8407 (js2-must-match js2-RC "msg.no.brace.block")
8408 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8409 (js2-pop-scope))
8410 pn))
8411
8412 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8413 (defun js2-parse-semi ()
8414 "Parse a statement or handle an error.
8415 Current token type is `js2-SEMI' or `js2-ERROR'."
8416 (let ((tt (js2-current-token-type)) pos len)
8417 (if (eq tt js2-SEMI)
8418 (make-js2-empty-expr-node :len 1)
8419 (setq pos (js2-current-token-beg)
8420 len (- (js2-current-token-end) pos))
8421 (js2-report-error "msg.syntax" nil pos len)
8422 (make-js2-error-node :pos pos :len len))))
8423
8424 (defun js2-parse-default-xml-namespace ()
8425 "Parse a `default xml namespace = <expr>' e4x statement."
8426 (let ((pos (js2-current-token-beg))
8427 end len expr unary)
8428 (js2-must-have-xml)
8429 (js2-set-requires-activation)
8430 (setq len (- js2-ts-cursor pos))
8431 (unless (and (js2-match-token js2-NAME)
8432 (string= (js2-current-token-string) "xml"))
8433 (js2-report-error "msg.bad.namespace" nil pos len))
8434 (unless (and (js2-match-token js2-NAME)
8435 (string= (js2-current-token-string) "namespace"))
8436 (js2-report-error "msg.bad.namespace" nil pos len))
8437 (unless (js2-match-token js2-ASSIGN)
8438 (js2-report-error "msg.bad.namespace" nil pos len))
8439 (setq expr (js2-parse-expr)
8440 end (js2-node-end expr)
8441 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8442 :pos pos
8443 :len (- end pos)
8444 :operand expr))
8445 (js2-node-add-children unary expr)
8446 (make-js2-expr-stmt-node :pos pos
8447 :len (- end pos)
8448 :expr unary)))
8449
8450 (defun js2-record-label (label bundle)
8451 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8452 (js2-get-token)
8453 (let ((name (js2-label-node-name label))
8454 labeled-stmt
8455 dup)
8456 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8457 ;; flag both labels if possible when used in editing mode
8458 (if (and js2-parse-ide-mode
8459 (setq dup (js2-get-label-by-name labeled-stmt name)))
8460 (js2-report-error "msg.dup.label" nil
8461 (js2-node-abs-pos dup) (js2-node-len dup)))
8462 (js2-report-error "msg.dup.label" nil
8463 (js2-node-pos label) (js2-node-len label)))
8464 (js2-labeled-stmt-node-add-label bundle label)
8465 (js2-node-add-children bundle label)
8466 ;; Add one reference to the bundle per label in `js2-label-set'
8467 (push (cons name bundle) js2-label-set)))
8468
8469 (defun js2-parse-name-or-label ()
8470 "Parser for identifier or label. Last token matched must be js2-NAME.
8471 Called when we found a name in a statement context. If it's a label, we gather
8472 up any following labels and the next non-label statement into a
8473 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8474 expression and return it wrapped in a `js2-expr-stmt-node'."
8475 (let ((pos (js2-current-token-beg))
8476 expr stmt bundle
8477 (continue t))
8478 ;; set check for label and call down to `js2-parse-primary-expr'
8479 (setq expr (js2-maybe-parse-label))
8480 (if (null expr)
8481 ;; Parse the non-label expression and wrap with expression stmt.
8482 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8483 ;; else parsed a label
8484 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8485 (js2-record-label expr bundle)
8486 ;; look for more labels
8487 (while (and continue (= (js2-get-token) js2-NAME))
8488 (if (setq expr (js2-maybe-parse-label))
8489 (js2-record-label expr bundle)
8490 (setq expr (js2-parse-expr)
8491 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8492 continue nil)
8493 (js2-auto-insert-semicolon stmt)))
8494 ;; no more labels; now parse the labeled statement
8495 (unwind-protect
8496 (unless stmt
8497 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8498 (js2-unget-token)
8499 (setq stmt (js2-statement-helper))))
8500 ;; remove the labels for this statement from the global set
8501 (dolist (label (js2-labeled-stmt-node-labels bundle))
8502 (setq js2-label-set (remove label js2-label-set))))
8503 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8504 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8505 (js2-node-add-children bundle stmt)
8506 bundle)))
8507
8508 (defun js2-maybe-parse-label ()
8509 (assert (= (js2-current-token-type) js2-NAME))
8510 (let (label-pos
8511 (next-tt (js2-get-token))
8512 (label-end (js2-current-token-end)))
8513 ;; Do not consume colon, it is used as unwind indicator
8514 ;; to return to statementHelper.
8515 (js2-unget-token)
8516 (if (= next-tt js2-COLON)
8517 (prog2
8518 (setq label-pos (js2-current-token-beg))
8519 (make-js2-label-node :pos label-pos
8520 :len (- label-end label-pos)
8521 :name (js2-current-token-string))
8522 (js2-set-face label-pos
8523 label-end
8524 'font-lock-variable-name-face 'record))
8525 ;; Backtrack from the name token, too.
8526 (js2-unget-token)
8527 nil)))
8528
8529 (defun js2-parse-expr-stmt ()
8530 "Default parser in statement context, if no recognized statement found."
8531 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8532 (progn
8533 (js2-unget-token)
8534 (js2-parse-expr)) t))
8535
8536 (defun js2-parse-variables (decl-type pos)
8537 "Parse a comma-separated list of variable declarations.
8538 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8539
8540 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8541 For 'var' or 'const', the keyword should be the token last scanned.
8542
8543 POS is the position where the node should start. It's sometimes the
8544 var/const/let keyword, and other times the beginning of the first token
8545 in the first variable declaration.
8546
8547 Returns the parsed `js2-var-decl-node' expression node."
8548 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8549 :pos pos))
8550 destructuring kid-pos tt init name end nbeg nend vi
8551 (continue t))
8552 ;; Example:
8553 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8554 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8555 ;; var {a, b} = baz;
8556 (while continue
8557 (setq destructuring nil
8558 name nil
8559 tt (js2-get-token)
8560 kid-pos (js2-current-token-beg)
8561 end (js2-current-token-end)
8562 init nil)
8563 (if (or (= tt js2-LB) (= tt js2-LC))
8564 ;; Destructuring assignment, e.g., var [a, b] = ...
8565 (setq destructuring (js2-parse-destruct-primary-expr)
8566 end (js2-node-end destructuring))
8567 ;; Simple variable name
8568 (js2-unget-token)
8569 (when (js2-must-match-name "msg.bad.var")
8570 (setq name (js2-create-name-node)
8571 nbeg (js2-current-token-beg)
8572 nend (js2-current-token-end)
8573 end nend)
8574 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8575 (when (js2-match-token js2-ASSIGN)
8576 (setq init (js2-parse-assign-expr)
8577 end (js2-node-end init))
8578 (js2-record-imenu-functions init name))
8579 (when name
8580 (js2-set-face nbeg nend (if (js2-function-node-p init)
8581 'font-lock-function-name-face
8582 'font-lock-variable-name-face)
8583 'record))
8584 (setq vi (make-js2-var-init-node :pos kid-pos
8585 :len (- end kid-pos)
8586 :type decl-type))
8587 (if destructuring
8588 (progn
8589 (if (and (null init) (not js2-in-for-init))
8590 (js2-report-error "msg.destruct.assign.no.init"))
8591 (js2-define-destruct-symbols destructuring
8592 decl-type
8593 'font-lock-variable-name-face)
8594 (setf (js2-var-init-node-target vi) destructuring))
8595 (setf (js2-var-init-node-target vi) name))
8596 (setf (js2-var-init-node-initializer vi) init)
8597 (js2-node-add-children vi name destructuring init)
8598 (js2-block-node-push result vi)
8599 (unless (js2-match-token js2-COMMA)
8600 (setq continue nil)))
8601 (setf (js2-node-len result) (- end pos))
8602 result))
8603
8604 (defun js2-parse-let (pos &optional stmt-p)
8605 "Parse a let expression or statement.
8606 A let-expression is of the form `let (vars) expr'.
8607 A let-statment is of the form `let (vars) {statements}'.
8608 The third form of let is a variable declaration list, handled
8609 by `js2-parse-variables'."
8610 (let ((pn (make-js2-let-node :pos pos))
8611 beg vars body)
8612 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8613 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8614 (js2-push-scope pn)
8615 (unwind-protect
8616 (progn
8617 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8618 (if (js2-must-match js2-RP "msg.no.paren.let")
8619 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8620 (if (and stmt-p (js2-match-token js2-LC))
8621 ;; let statement
8622 (progn
8623 (setf beg (js2-current-token-beg) ; position stmt at LC
8624 body (js2-parse-statements))
8625 (js2-must-match js2-RC "msg.no.curly.let")
8626 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8627 (js2-node-len pn) (- (js2-current-token-end) pos)
8628 (js2-let-node-body pn) body
8629 (js2-node-type pn) js2-LET))
8630 ;; let expression
8631 (setf body (js2-parse-expr)
8632 (js2-node-len pn) (- (js2-node-end body) pos)
8633 (js2-let-node-body pn) body))
8634 (setf (js2-let-node-vars pn) vars)
8635 (js2-node-add-children pn vars body))
8636 (js2-pop-scope))
8637 pn))
8638
8639 (defun js2-define-new-symbol (decl-type name node &optional scope)
8640 (js2-scope-put-symbol (or scope js2-current-scope)
8641 name
8642 (make-js2-symbol decl-type name node)))
8643
8644 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8645 "Define a symbol in the current scope.
8646 If NODE is non-nil, it is the AST node associated with the symbol."
8647 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8648 (symbol (if defining-scope
8649 (js2-scope-get-symbol defining-scope name)))
8650 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8651 (cond
8652 ((and symbol ; already defined
8653 (or (= sdt js2-CONST) ; old version is const
8654 (= decl-type js2-CONST) ; new version is const
8655 ;; two let-bound vars in this block have same name
8656 (and (= sdt js2-LET)
8657 (eq defining-scope js2-current-scope))))
8658 (js2-report-error
8659 (cond
8660 ((= sdt js2-CONST) "msg.const.redecl")
8661 ((= sdt js2-LET) "msg.let.redecl")
8662 ((= sdt js2-VAR) "msg.var.redecl")
8663 ((= sdt js2-FUNCTION) "msg.function.redecl")
8664 (t "msg.parm.redecl"))
8665 name))
8666 ((= decl-type js2-LET)
8667 (if (and (not ignore-not-in-block)
8668 (or (= (js2-node-type js2-current-scope) js2-IF)
8669 (js2-loop-node-p js2-current-scope)))
8670 (js2-report-error "msg.let.decl.not.in.block")
8671 (js2-define-new-symbol decl-type name node)))
8672 ((or (= decl-type js2-VAR)
8673 (= decl-type js2-CONST)
8674 (= decl-type js2-FUNCTION))
8675 (if symbol
8676 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8677 (js2-add-strict-warning "msg.var.redecl" name)
8678 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8679 (js2-add-strict-warning "msg.var.hides.arg" name)))
8680 (js2-define-new-symbol decl-type name node
8681 js2-current-script-or-fn)))
8682 ((= decl-type js2-LP)
8683 (if symbol
8684 ;; must be duplicate parameter. Second parameter hides the
8685 ;; first, so go ahead and add the second pararameter
8686 (js2-report-warning "msg.dup.parms" name))
8687 (js2-define-new-symbol decl-type name node))
8688 (t (js2-code-bug)))))
8689
8690 (defun js2-parse-paren-expr-or-generator-comp ()
8691 (let ((px-pos (js2-current-token-beg)))
8692 (if (and (>= js2-language-version 200)
8693 (js2-match-token js2-FOR))
8694 (js2-parse-generator-comp px-pos)
8695 (let* ((js2-in-for-init nil)
8696 (expr (js2-parse-expr))
8697 (pn (make-js2-paren-node :pos px-pos
8698 :expr expr
8699 :len (- (js2-current-token-end)
8700 px-pos))))
8701 (js2-node-add-children pn (js2-paren-node-expr pn))
8702 (js2-must-match js2-RP "msg.no.paren")
8703 pn))))
8704
8705 (defun js2-parse-expr (&optional oneshot)
8706 (let* ((pn (js2-parse-assign-expr))
8707 (pos (js2-node-pos pn))
8708 left
8709 right
8710 op-pos)
8711 (while (and (not oneshot)
8712 (js2-match-token js2-COMMA))
8713 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8714 (if (= (js2-peek-token) js2-YIELD)
8715 (js2-report-error "msg.yield.parenthesized"))
8716 (setq right (js2-parse-assign-expr)
8717 left pn
8718 pn (make-js2-infix-node :type js2-COMMA
8719 :pos pos
8720 :len (- js2-ts-cursor pos)
8721 :op-pos op-pos
8722 :left left
8723 :right right))
8724 (js2-node-add-children pn left right))
8725 pn))
8726
8727 (defun js2-parse-assign-expr ()
8728 (let ((tt (js2-get-token))
8729 (pos (js2-current-token-beg))
8730 pn left right op-pos
8731 ts-state recorded-identifiers parsed-errors)
8732 (if (= tt js2-YIELD)
8733 (js2-parse-return-or-yield tt t)
8734 ;; Save the tokenizer state in case we find an arrow function
8735 ;; and have to rewind.
8736 (setq ts-state (make-js2-ts-state)
8737 recorded-identifiers js2-recorded-identifiers
8738 parsed-errors js2-parsed-errors)
8739 ;; not yield - parse assignment expression
8740 (setq pn (js2-parse-cond-expr)
8741 tt (js2-get-token))
8742 (cond
8743 ((and (<= js2-first-assign tt)
8744 (<= tt js2-last-assign))
8745 ;; tt express assignment (=, |=, ^=, ..., %=)
8746 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8747 left pn)
8748 (setq right (js2-parse-assign-expr)
8749 pn (make-js2-assign-node :type tt
8750 :pos pos
8751 :len (- (js2-node-end right) pos)
8752 :op-pos op-pos
8753 :left left
8754 :right right))
8755 (when js2-parse-ide-mode
8756 (js2-highlight-assign-targets pn left right)
8757 (js2-record-imenu-functions right left))
8758 ;; do this last so ide checks above can use absolute positions
8759 (js2-node-add-children pn left right))
8760 ((and (= tt js2-ARROW)
8761 (>= js2-language-version 200))
8762 (js2-ts-seek ts-state)
8763 (setq js2-recorded-identifiers recorded-identifiers
8764 js2-parsed-errors parsed-errors)
8765 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8766 (t
8767 (js2-unget-token)))
8768 pn)))
8769
8770 (defun js2-parse-cond-expr ()
8771 (let ((pos (js2-current-token-beg))
8772 (pn (js2-parse-or-expr))
8773 test-expr
8774 if-true
8775 if-false
8776 q-pos
8777 c-pos)
8778 (when (js2-match-token js2-HOOK)
8779 (setq q-pos (- (js2-current-token-beg) pos)
8780 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8781 (js2-must-match js2-COLON "msg.no.colon.cond")
8782 (setq c-pos (- (js2-current-token-beg) pos)
8783 if-false (js2-parse-assign-expr)
8784 test-expr pn
8785 pn (make-js2-cond-node :pos pos
8786 :len (- (js2-node-end if-false) pos)
8787 :test-expr test-expr
8788 :true-expr if-true
8789 :false-expr if-false
8790 :q-pos q-pos
8791 :c-pos c-pos))
8792 (js2-node-add-children pn test-expr if-true if-false))
8793 pn))
8794
8795 (defun js2-make-binary (type left parser)
8796 "Helper for constructing a binary-operator AST node.
8797 LEFT is the left-side-expression, already parsed, and the
8798 binary operator should have just been matched.
8799 PARSER is a function to call to parse the right operand,
8800 or a `js2-node' struct if it has already been parsed.
8801 FIXME: The latter option is unused?"
8802 (let* ((pos (js2-node-pos left))
8803 (op-pos (- (js2-current-token-beg) pos))
8804 (right (if (js2-node-p parser)
8805 parser
8806 (js2-get-token)
8807 (funcall parser)))
8808 (pn (make-js2-infix-node :type type
8809 :pos pos
8810 :len (- (js2-node-end right) pos)
8811 :op-pos op-pos
8812 :left left
8813 :right right)))
8814 (js2-node-add-children pn left right)
8815 pn))
8816
8817 (defun js2-parse-or-expr ()
8818 (let ((pn (js2-parse-and-expr)))
8819 (when (js2-match-token js2-OR)
8820 (setq pn (js2-make-binary js2-OR
8821 pn
8822 'js2-parse-or-expr)))
8823 pn))
8824
8825 (defun js2-parse-and-expr ()
8826 (let ((pn (js2-parse-bit-or-expr)))
8827 (when (js2-match-token js2-AND)
8828 (setq pn (js2-make-binary js2-AND
8829 pn
8830 'js2-parse-and-expr)))
8831 pn))
8832
8833 (defun js2-parse-bit-or-expr ()
8834 (let ((pn (js2-parse-bit-xor-expr)))
8835 (while (js2-match-token js2-BITOR)
8836 (setq pn (js2-make-binary js2-BITOR
8837 pn
8838 'js2-parse-bit-xor-expr)))
8839 pn))
8840
8841 (defun js2-parse-bit-xor-expr ()
8842 (let ((pn (js2-parse-bit-and-expr)))
8843 (while (js2-match-token js2-BITXOR)
8844 (setq pn (js2-make-binary js2-BITXOR
8845 pn
8846 'js2-parse-bit-and-expr)))
8847 pn))
8848
8849 (defun js2-parse-bit-and-expr ()
8850 (let ((pn (js2-parse-eq-expr)))
8851 (while (js2-match-token js2-BITAND)
8852 (setq pn (js2-make-binary js2-BITAND
8853 pn
8854 'js2-parse-eq-expr)))
8855 pn))
8856
8857 (defconst js2-parse-eq-ops
8858 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8859
8860 (defun js2-parse-eq-expr ()
8861 (let ((pn (js2-parse-rel-expr))
8862 tt)
8863 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8864 (setq pn (js2-make-binary tt
8865 pn
8866 'js2-parse-rel-expr)))
8867 (js2-unget-token)
8868 pn))
8869
8870 (defconst js2-parse-rel-ops
8871 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8872
8873 (defun js2-parse-rel-expr ()
8874 (let ((pn (js2-parse-shift-expr))
8875 (continue t)
8876 tt)
8877 (while continue
8878 (setq tt (js2-get-token))
8879 (cond
8880 ((and js2-in-for-init (= tt js2-IN))
8881 (js2-unget-token)
8882 (setq continue nil))
8883 ((memq tt js2-parse-rel-ops)
8884 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8885 (t
8886 (js2-unget-token)
8887 (setq continue nil))))
8888 pn))
8889
8890 (defconst js2-parse-shift-ops
8891 (list js2-LSH js2-URSH js2-RSH))
8892
8893 (defun js2-parse-shift-expr ()
8894 (let ((pn (js2-parse-add-expr))
8895 tt
8896 (continue t))
8897 (while continue
8898 (setq tt (js2-get-token))
8899 (if (memq tt js2-parse-shift-ops)
8900 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8901 (js2-unget-token)
8902 (setq continue nil)))
8903 pn))
8904
8905 (defun js2-parse-add-expr ()
8906 (let ((pn (js2-parse-mul-expr))
8907 tt
8908 (continue t))
8909 (while continue
8910 (setq tt (js2-get-token))
8911 (if (or (= tt js2-ADD) (= tt js2-SUB))
8912 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8913 (js2-unget-token)
8914 (setq continue nil)))
8915 pn))
8916
8917 (defconst js2-parse-mul-ops
8918 (list js2-MUL js2-DIV js2-MOD))
8919
8920 (defun js2-parse-mul-expr ()
8921 (let ((pn (js2-parse-unary-expr))
8922 tt
8923 (continue t))
8924 (while continue
8925 (setq tt (js2-get-token))
8926 (if (memq tt js2-parse-mul-ops)
8927 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8928 (js2-unget-token)
8929 (setq continue nil)))
8930 pn))
8931
8932 (defun js2-make-unary (type parser &rest args)
8933 "Make a unary node of type TYPE.
8934 PARSER is either a node (for postfix operators) or a function to call
8935 to parse the operand (for prefix operators)."
8936 (let* ((pos (js2-current-token-beg))
8937 (postfix (js2-node-p parser))
8938 (expr (if postfix
8939 parser
8940 (apply parser args)))
8941 end
8942 pn)
8943 (if postfix ; e.g. i++
8944 (setq pos (js2-node-pos expr)
8945 end (js2-current-token-end))
8946 (setq end (js2-node-end expr)))
8947 (setq pn (make-js2-unary-node :type type
8948 :pos pos
8949 :len (- end pos)
8950 :operand expr))
8951 (js2-node-add-children pn expr)
8952 pn))
8953
8954 (defconst js2-incrementable-node-types
8955 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8956 "Node types that can be the operand of a ++ or -- operator.")
8957
8958 (defun js2-check-bad-inc-dec (tt beg end unary)
8959 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8960 js2-incrementable-node-types)
8961 (js2-report-error (if (= tt js2-INC)
8962 "msg.bad.incr"
8963 "msg.bad.decr")
8964 nil beg (- end beg))))
8965
8966 (defun js2-parse-unary-expr ()
8967 (let ((tt (js2-current-token-type))
8968 pn expr beg end)
8969 (cond
8970 ((or (= tt js2-VOID)
8971 (= tt js2-NOT)
8972 (= tt js2-BITNOT)
8973 (= tt js2-TYPEOF))
8974 (js2-get-token)
8975 (js2-make-unary tt 'js2-parse-unary-expr))
8976 ((= tt js2-ADD)
8977 (js2-get-token)
8978 ;; Convert to special POS token in decompiler and parse tree
8979 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8980 ((= tt js2-SUB)
8981 (js2-get-token)
8982 ;; Convert to special NEG token in decompiler and parse tree
8983 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8984 ((or (= tt js2-INC)
8985 (= tt js2-DEC))
8986 (js2-get-token)
8987 (prog1
8988 (setq beg (js2-current-token-beg)
8989 end (js2-current-token-end)
8990 expr (js2-make-unary tt 'js2-parse-member-expr t))
8991 (js2-check-bad-inc-dec tt beg end expr)))
8992 ((= tt js2-DELPROP)
8993 (js2-get-token)
8994 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8995 ((= tt js2-ERROR)
8996 (js2-get-token)
8997 (make-js2-error-node)) ; try to continue
8998 ((and (= tt js2-LT)
8999 js2-compiler-xml-available)
9000 ;; XML stream encountered in expression.
9001 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9002 (t
9003 (setq pn (js2-parse-member-expr t)
9004 ;; Don't look across a newline boundary for a postfix incop.
9005 tt (js2-peek-token-or-eol))
9006 (when (or (= tt js2-INC) (= tt js2-DEC))
9007 (js2-get-token)
9008 (setf expr pn
9009 pn (js2-make-unary tt expr))
9010 (js2-node-set-prop pn 'postfix t)
9011 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9012 pn))))
9013
9014 (defun js2-parse-xml-initializer ()
9015 "Parse an E4X XML initializer.
9016 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9017 Then I'll postprocess the result, depending on whether we're in IDE
9018 mode or codegen mode, and generate the appropriate rewritten AST.
9019 IDE mode uses a rich AST that models the XML structure. Codegen mode
9020 just concatenates everything and makes a new XML or XMLList out of it."
9021 (let ((tt (js2-get-first-xml-token))
9022 pn-xml pn expr kids expr-pos
9023 (continue t)
9024 (first-token t))
9025 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9026 (js2-report-error "msg.syntax"))
9027 (setq pn-xml (make-js2-xml-node))
9028 (while continue
9029 (if first-token
9030 (setq first-token nil)
9031 (setq tt (js2-get-next-xml-token)))
9032 (cond
9033 ;; js2-XML means we found a {expr} in the XML stream.
9034 ;; The token string is the XML up to the left-curly.
9035 ((= tt js2-XML)
9036 (push (make-js2-string-node :pos (js2-current-token-beg)
9037 :len (- js2-ts-cursor (js2-current-token-beg)))
9038 kids)
9039 (js2-must-match js2-LC "msg.syntax")
9040 (setq expr-pos js2-ts-cursor
9041 expr (if (eq (js2-peek-token) js2-RC)
9042 (make-js2-empty-expr-node :pos expr-pos)
9043 (js2-parse-expr)))
9044 (js2-must-match js2-RC "msg.syntax")
9045 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9046 :len (js2-node-len expr)
9047 :expr expr))
9048 (js2-node-add-children pn expr)
9049 (push pn kids))
9050 ;; a js2-XMLEND token means we hit the final close-tag.
9051 ((= tt js2-XMLEND)
9052 (push (make-js2-string-node :pos (js2-current-token-beg)
9053 :len (- js2-ts-cursor (js2-current-token-beg)))
9054 kids)
9055 (dolist (kid (nreverse kids))
9056 (js2-block-node-push pn-xml kid))
9057 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9058 (js2-node-pos pn-xml))
9059 continue nil))
9060 (t
9061 (js2-report-error "msg.syntax")
9062 (setq continue nil))))
9063 pn-xml))
9064
9065
9066 (defun js2-parse-argument-list ()
9067 "Parse an argument list and return it as a Lisp list of nodes.
9068 Returns the list in reverse order. Consumes the right-paren token."
9069 (let (result)
9070 (unless (js2-match-token js2-RP)
9071 (loop do
9072 (let ((tt (js2-get-token)))
9073 (if (= tt js2-YIELD)
9074 (js2-report-error "msg.yield.parenthesized"))
9075 (if (and (= tt js2-TRIPLEDOT)
9076 (>= js2-language-version 200))
9077 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9078 (js2-unget-token)
9079 (push (js2-parse-assign-expr) result)))
9080 while
9081 (js2-match-token js2-COMMA))
9082 (js2-must-match js2-RP "msg.no.paren.arg")
9083 result)))
9084
9085 (defun js2-parse-member-expr (&optional allow-call-syntax)
9086 (let ((tt (js2-current-token-type))
9087 pn pos target args beg end init)
9088 (if (/= tt js2-NEW)
9089 (setq pn (js2-parse-primary-expr))
9090 ;; parse a 'new' expression
9091 (js2-get-token)
9092 (setq pos (js2-current-token-beg)
9093 beg pos
9094 target (js2-parse-member-expr)
9095 end (js2-node-end target)
9096 pn (make-js2-new-node :pos pos
9097 :target target
9098 :len (- end pos)))
9099 (js2-highlight-function-call (js2-current-token))
9100 (js2-node-add-children pn target)
9101 (when (js2-match-token js2-LP)
9102 ;; Add the arguments to pn, if any are supplied.
9103 (setf beg pos ; start of "new" keyword
9104 pos (js2-current-token-beg)
9105 args (nreverse (js2-parse-argument-list))
9106 (js2-new-node-args pn) args
9107 end (js2-current-token-end)
9108 (js2-new-node-lp pn) (- pos beg)
9109 (js2-new-node-rp pn) (- end 1 beg))
9110 (apply #'js2-node-add-children pn args))
9111 (when (and js2-allow-rhino-new-expr-initializer
9112 (js2-match-token js2-LC))
9113 (setf init (js2-parse-object-literal)
9114 end (js2-node-end init)
9115 (js2-new-node-initializer pn) init)
9116 (js2-node-add-children pn init))
9117 (setf (js2-node-len pn) (- end beg))) ; end outer if
9118 (js2-parse-member-expr-tail allow-call-syntax pn)))
9119
9120 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9121 "Parse a chain of property/array accesses or function calls.
9122 Includes parsing for E4X operators like `..' and `.@'.
9123 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9124 Returns an expression tree that includes PN, the parent node."
9125 (let (tt
9126 (continue t))
9127 (while continue
9128 (setq tt (js2-get-token))
9129 (cond
9130 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9131 (setq pn (js2-parse-property-access tt pn)))
9132 ((= tt js2-DOTQUERY)
9133 (setq pn (js2-parse-dot-query pn)))
9134 ((= tt js2-LB)
9135 (setq pn (js2-parse-element-get pn)))
9136 ((= tt js2-LP)
9137 (js2-unget-token)
9138 (if allow-call-syntax
9139 (setq pn (js2-parse-function-call pn))
9140 (setq continue nil)))
9141 ((= tt js2-TEMPLATE_HEAD)
9142 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9143 ((= tt js2-NO_SUBS_TEMPLATE)
9144 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9145 (t
9146 (js2-unget-token)
9147 (setq continue nil))))
9148 (if (>= js2-highlight-level 2)
9149 (js2-parse-highlight-member-expr-node pn))
9150 pn))
9151
9152 (defun js2-parse-tagged-template (tag-node tpl-node)
9153 "Parse tagged template expression."
9154 (let* ((beg (js2-node-pos tag-node))
9155 (pn (make-js2-tagged-template-node :beg beg
9156 :len (- (js2-current-token-end) beg)
9157 :tag tag-node
9158 :template tpl-node)))
9159 (js2-node-add-children pn tag-node tpl-node)
9160 pn))
9161
9162 (defun js2-parse-dot-query (pn)
9163 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9164 Last token parsed must be `js2-DOTQUERY'."
9165 (let ((pos (js2-node-pos pn))
9166 op-pos expr end)
9167 (js2-must-have-xml)
9168 (js2-set-requires-activation)
9169 (setq op-pos (js2-current-token-beg)
9170 expr (js2-parse-expr)
9171 end (js2-node-end expr)
9172 pn (make-js2-xml-dot-query-node :left pn
9173 :pos pos
9174 :op-pos op-pos
9175 :right expr))
9176 (js2-node-add-children pn
9177 (js2-xml-dot-query-node-left pn)
9178 (js2-xml-dot-query-node-right pn))
9179 (if (js2-must-match js2-RP "msg.no.paren")
9180 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9181 end (js2-current-token-end)))
9182 (setf (js2-node-len pn) (- end pos))
9183 pn))
9184
9185 (defun js2-parse-element-get (pn)
9186 "Parse an element-get expression, e.g. foo[bar].
9187 Last token parsed must be `js2-RB'."
9188 (let ((lb (js2-current-token-beg))
9189 (pos (js2-node-pos pn))
9190 rb expr)
9191 (setq expr (js2-parse-expr))
9192 (if (js2-must-match js2-RB "msg.no.bracket.index")
9193 (setq rb (js2-current-token-beg)))
9194 (setq pn (make-js2-elem-get-node :target pn
9195 :pos pos
9196 :element expr
9197 :lb (js2-relpos lb pos)
9198 :rb (js2-relpos rb pos)
9199 :len (- (js2-current-token-end) pos)))
9200 (js2-node-add-children pn
9201 (js2-elem-get-node-target pn)
9202 (js2-elem-get-node-element pn))
9203 pn))
9204
9205 (defun js2-highlight-function-call (token)
9206 (when (eq (js2-token-type token) js2-NAME)
9207 (js2-record-face 'js2-function-call token)))
9208
9209 (defun js2-parse-function-call (pn)
9210 (js2-highlight-function-call (js2-current-token))
9211 (js2-get-token)
9212 (let (args
9213 (pos (js2-node-pos pn)))
9214 (setq pn (make-js2-call-node :pos pos
9215 :target pn
9216 :lp (- (js2-current-token-beg) pos)))
9217 (js2-node-add-children pn (js2-call-node-target pn))
9218 ;; Add the arguments to pn, if any are supplied.
9219 (setf args (nreverse (js2-parse-argument-list))
9220 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9221 (js2-call-node-args pn) args)
9222 (apply #'js2-node-add-children pn args)
9223 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9224 pn))
9225
9226 (defun js2-parse-property-access (tt pn)
9227 "Parse a property access, XML descendants access, or XML attr access."
9228 (let ((member-type-flags 0)
9229 (dot-pos (js2-current-token-beg))
9230 (dot-len (if (= tt js2-DOTDOT) 2 1))
9231 name
9232 ref ; right side of . or .. operator
9233 result)
9234 (when (= tt js2-DOTDOT)
9235 (js2-must-have-xml)
9236 (setq member-type-flags js2-descendants-flag))
9237 (if (not js2-compiler-xml-available)
9238 (progn
9239 (js2-must-match-prop-name "msg.no.name.after.dot")
9240 (setq name (js2-create-name-node t js2-GETPROP)
9241 result (make-js2-prop-get-node :left pn
9242 :pos (js2-current-token-beg)
9243 :right name
9244 :len (js2-current-token-len)))
9245 (js2-node-add-children result pn name)
9246 result)
9247 ;; otherwise look for XML operators
9248 (setf result (if (= tt js2-DOT)
9249 (make-js2-prop-get-node)
9250 (make-js2-infix-node :type js2-DOTDOT))
9251 (js2-node-pos result) (js2-node-pos pn)
9252 (js2-infix-node-op-pos result) dot-pos
9253 (js2-infix-node-left result) pn ; do this after setting position
9254 tt (js2-get-prop-name-token))
9255 (cond
9256 ;; handles: name, ns::name, ns::*, ns::[expr]
9257 ((= tt js2-NAME)
9258 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9259 ;; handles: *, *::name, *::*, *::[expr]
9260 ((= tt js2-MUL)
9261 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9262 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9263 ((= tt js2-XMLATTR)
9264 (setq result (js2-parse-attribute-access)))
9265 (t
9266 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9267 (if ref
9268 (setf (js2-node-len result) (- (js2-node-end ref)
9269 (js2-node-pos result))
9270 (js2-infix-node-right result) ref))
9271 (if (js2-infix-node-p result)
9272 (js2-node-add-children result
9273 (js2-infix-node-left result)
9274 (js2-infix-node-right result)))
9275 result)))
9276
9277 (defun js2-parse-attribute-access ()
9278 "Parse an E4X XML attribute expression.
9279 This includes expressions of the forms:
9280
9281 @attr @ns::attr @ns::*
9282 @* @*::attr @*::*
9283 @[expr] @*::[expr] @ns::[expr]
9284
9285 Called if we peeked an '@' token."
9286 (let ((tt (js2-get-prop-name-token))
9287 (at-pos (js2-current-token-beg)))
9288 (cond
9289 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9290 ((= tt js2-NAME)
9291 (js2-parse-property-name at-pos nil 0))
9292 ;; handles: @*, @*::name, @*::*, @*::[expr]
9293 ((= tt js2-MUL)
9294 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9295 ;; handles @[expr]
9296 ((= tt js2-LB)
9297 (js2-parse-xml-elem-ref at-pos))
9298 (t
9299 (js2-report-error "msg.no.name.after.xmlAttr")
9300 ;; Avoid cascaded errors that happen if we make an error node here.
9301 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9302
9303 (defun js2-parse-property-name (at-pos s member-type-flags)
9304 "Check if :: follows name in which case it becomes qualified name.
9305
9306 AT-POS is a natural number if we just read an '@' token, else nil.
9307 S is the name or string that was matched: an identifier, 'throw' or '*'.
9308 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9309
9310 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9311 operator, or the name is followed by ::. For a plain name, returns a
9312 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9313 (let ((pos (or at-pos (js2-current-token-beg)))
9314 colon-pos
9315 (name (js2-create-name-node t (js2-current-token-type) s))
9316 ns tt pn)
9317 (catch 'return
9318 (when (js2-match-token js2-COLONCOLON)
9319 (setq ns name
9320 colon-pos (js2-current-token-beg)
9321 tt (js2-get-prop-name-token))
9322 (cond
9323 ;; handles name::name
9324 ((= tt js2-NAME)
9325 (setq name (js2-create-name-node)))
9326 ;; handles name::*
9327 ((= tt js2-MUL)
9328 (setq name (js2-create-name-node nil nil "*")))
9329 ;; handles name::[expr]
9330 ((= tt js2-LB)
9331 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9332 (t
9333 (js2-report-error "msg.no.name.after.coloncolon"))))
9334 (if (and (null ns) (zerop member-type-flags))
9335 name
9336 (prog1
9337 (setq pn
9338 (make-js2-xml-prop-ref-node :pos pos
9339 :len (- (js2-node-end name) pos)
9340 :at-pos at-pos
9341 :colon-pos colon-pos
9342 :propname name))
9343 (js2-node-add-children pn name))))))
9344
9345 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9346 "Parse the [expr] portion of an xml element reference.
9347 For instance, @[expr], @*::[expr], or ns::[expr]."
9348 (let* ((lb (js2-current-token-beg))
9349 (pos (or at-pos lb))
9350 rb
9351 (expr (js2-parse-expr))
9352 (end (js2-node-end expr))
9353 pn)
9354 (if (js2-must-match js2-RB "msg.no.bracket.index")
9355 (setq rb (js2-current-token-beg)
9356 end (js2-current-token-end)))
9357 (prog1
9358 (setq pn
9359 (make-js2-xml-elem-ref-node :pos pos
9360 :len (- end pos)
9361 :namespace namespace
9362 :colon-pos colon-pos
9363 :at-pos at-pos
9364 :expr expr
9365 :lb (js2-relpos lb pos)
9366 :rb (js2-relpos rb pos)))
9367 (js2-node-add-children pn namespace expr))))
9368
9369 (defun js2-parse-destruct-primary-expr ()
9370 (let ((js2-is-in-destructuring t))
9371 (js2-parse-primary-expr)))
9372
9373 (defun js2-parse-primary-expr ()
9374 "Parse a literal (leaf) expression of some sort.
9375 Includes complex literals such as functions, object-literals,
9376 array-literals, array comprehensions and regular expressions."
9377 (let (pn ; parent node (usually return value)
9378 tt)
9379 (setq tt (js2-current-token-type))
9380 (cond
9381 ((= tt js2-CLASS)
9382 (js2-parse-class-expr))
9383 ((= tt js2-FUNCTION)
9384 (js2-parse-function-expr))
9385 ((= tt js2-LB)
9386 (js2-parse-array-comp-or-literal))
9387 ((= tt js2-LC)
9388 (js2-parse-object-literal))
9389 ((= tt js2-LET)
9390 (js2-parse-let (js2-current-token-beg)))
9391 ((= tt js2-LP)
9392 (js2-parse-paren-expr-or-generator-comp))
9393 ((= tt js2-XMLATTR)
9394 (js2-must-have-xml)
9395 (js2-parse-attribute-access))
9396 ((= tt js2-NAME)
9397 (js2-parse-name tt))
9398 ((= tt js2-NUMBER)
9399 (make-js2-number-node))
9400 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9401 (make-js2-string-node :type tt))
9402 ((= tt js2-TEMPLATE_HEAD)
9403 (js2-parse-template-literal))
9404 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9405 ;; Got / or /= which in this context means a regexp literal
9406 (let ((px-pos (js2-current-token-beg))
9407 (flags (js2-read-regexp tt))
9408 (end (js2-current-token-end)))
9409 (prog1
9410 (make-js2-regexp-node :pos px-pos
9411 :len (- end px-pos)
9412 :value (js2-current-token-string)
9413 :flags flags)
9414 (js2-set-face px-pos end 'font-lock-string-face 'record)
9415 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9416 ((or (= tt js2-NULL)
9417 (= tt js2-THIS)
9418 (= tt js2-SUPER)
9419 (= tt js2-FALSE)
9420 (= tt js2-TRUE))
9421 (make-js2-keyword-node :type tt))
9422 ((= tt js2-RP)
9423 ;; Not valid expression syntax, but this is valid in an arrow
9424 ;; function with no params: () => body.
9425 (if (eq (js2-peek-token) js2-ARROW)
9426 (progn
9427 (js2-unget-token) ; Put back the right paren.
9428 ;; Return whatever, it will hopefully be rewinded and
9429 ;; reparsed when we reach the =>.
9430 (make-js2-keyword-node :type js2-NULL))
9431 (js2-report-error "msg.syntax")
9432 (make-js2-error-node)))
9433 ((= tt js2-TRIPLEDOT)
9434 ;; Likewise, only valid in an arrow function with a rest param.
9435 (if (and (js2-match-token js2-NAME)
9436 (js2-match-token js2-RP)
9437 (eq (js2-peek-token) js2-ARROW))
9438 (progn
9439 (js2-unget-token) ; Put back the right paren.
9440 ;; See the previous case.
9441 (make-js2-keyword-node :type js2-NULL))
9442 (js2-report-error "msg.syntax")
9443 (make-js2-error-node)))
9444 ((= tt js2-RESERVED)
9445 (js2-report-error "msg.reserved.id")
9446 (make-js2-name-node))
9447 ((= tt js2-ERROR)
9448 ;; the scanner or one of its subroutines reported the error.
9449 (make-js2-error-node))
9450 ((= tt js2-EOF)
9451 (let* ((px-pos (point-at-bol))
9452 (len (- js2-ts-cursor px-pos)))
9453 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9454 (make-js2-error-node :pos (1- js2-ts-cursor)))
9455 (t
9456 (js2-report-error "msg.syntax")
9457 (make-js2-error-node)))))
9458
9459 (defun js2-parse-template-literal ()
9460 (let ((beg (js2-current-token-beg))
9461 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
9462 (tt js2-TEMPLATE_HEAD))
9463 (while (eq tt js2-TEMPLATE_HEAD)
9464 (push (js2-parse-expr) kids)
9465 (js2-must-match js2-RC "msg.syntax")
9466 (setq tt (js2-get-token 'TEMPLATE_TAIL))
9467 (push (make-js2-string-node :type tt) kids))
9468 (setq kids (nreverse kids))
9469 (let ((tpl (make-js2-template-node :beg beg
9470 :len (- (js2-current-token-end) beg)
9471 :kids kids)))
9472 (apply #'js2-node-add-children tpl kids)
9473 tpl)))
9474
9475 (defun js2-parse-name (_tt)
9476 (let ((name (js2-current-token-string))
9477 node)
9478 (setq node (if js2-compiler-xml-available
9479 (js2-parse-property-name nil name 0)
9480 (js2-create-name-node 'check-activation nil name)))
9481 (if js2-highlight-external-variables
9482 (js2-record-name-node node))
9483 node))
9484
9485 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9486 (js2-add-strict-warning
9487 msg nil
9488 ;; back up from comma to beginning of line or array/objlit
9489 (max (if elems
9490 (js2-node-pos (car elems))
9491 pos)
9492 (save-excursion
9493 (goto-char comma-pos)
9494 (back-to-indentation)
9495 (point)))
9496 comma-pos))
9497
9498 (defun js2-parse-array-comp-or-literal ()
9499 (let ((pos (js2-current-token-beg)))
9500 (if (and (>= js2-language-version 200)
9501 (js2-match-token js2-FOR))
9502 (js2-parse-array-comp pos)
9503 (js2-parse-array-literal pos))))
9504
9505 (defun js2-parse-array-literal (pos)
9506 (let ((after-lb-or-comma t)
9507 after-comma tt elems pn
9508 (continue t))
9509 (unless js2-is-in-destructuring
9510 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9511 (while continue
9512 (setq tt (js2-get-token))
9513 (cond
9514 ;; comma
9515 ((= tt js2-COMMA)
9516 (setq after-comma (js2-current-token-end))
9517 (if (not after-lb-or-comma)
9518 (setq after-lb-or-comma t)
9519 (push nil elems)))
9520 ;; end of array
9521 ((or (= tt js2-RB)
9522 (= tt js2-EOF)) ; prevent infinite loop
9523 (if (= tt js2-EOF)
9524 (js2-report-error "msg.no.bracket.arg" nil pos))
9525 (when (and after-comma (< js2-language-version 170))
9526 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9527 pos (remove nil elems) after-comma))
9528 (setq continue nil
9529 pn (make-js2-array-node :pos pos
9530 :len (- js2-ts-cursor pos)
9531 :elems (nreverse elems)))
9532 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9533 ;; destructuring binding
9534 (js2-is-in-destructuring
9535 (push (if (or (= tt js2-LC)
9536 (= tt js2-LB)
9537 (= tt js2-NAME))
9538 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9539 (js2-parse-destruct-primary-expr)
9540 ;; invalid pattern
9541 (js2-report-error "msg.bad.var")
9542 (make-js2-error-node))
9543 elems)
9544 (setq after-lb-or-comma nil
9545 after-comma nil))
9546 ;; array comp
9547 ((and (>= js2-language-version 170)
9548 (= tt js2-FOR) ; check for array comprehension
9549 (not after-lb-or-comma) ; "for" can't follow a comma
9550 elems ; must have at least 1 element
9551 (not (cdr elems))) ; but no 2nd element
9552 (js2-unget-token)
9553 (setf continue nil
9554 pn (js2-parse-legacy-array-comp (car elems) pos)))
9555 ;; another element
9556 (t
9557 (unless after-lb-or-comma
9558 (js2-report-error "msg.no.bracket.arg"))
9559 (if (and (= tt js2-TRIPLEDOT)
9560 (>= js2-language-version 200))
9561 ;; spread operator
9562 (push (js2-make-unary tt 'js2-parse-assign-expr)
9563 elems)
9564 (js2-unget-token)
9565 (push (js2-parse-assign-expr) elems))
9566 (setq after-lb-or-comma nil
9567 after-comma nil))))
9568 (unless js2-is-in-destructuring
9569 (js2-pop-scope))
9570 pn))
9571
9572 (defun js2-parse-legacy-array-comp (expr pos)
9573 "Parse a legacy array comprehension (JavaScript 1.7).
9574 EXPR is the first expression after the opening left-bracket.
9575 POS is the beginning of the LB token preceding EXPR.
9576 We should have just parsed the 'for' keyword before calling this function."
9577 (let ((current-scope js2-current-scope)
9578 loops first filter result)
9579 (unwind-protect
9580 (progn
9581 (while (js2-match-token js2-FOR)
9582 (let ((loop (make-js2-comp-loop-node)))
9583 (js2-push-scope loop)
9584 (push loop loops)
9585 (js2-parse-comp-loop loop)))
9586 ;; First loop takes expr scope's parent.
9587 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9588 (js2-scope-parent-scope current-scope))
9589 ;; Set expr scope's parent to the last loop.
9590 (setf (js2-scope-parent-scope current-scope) (car loops))
9591 (if (/= (js2-get-token) js2-IF)
9592 (js2-unget-token)
9593 (setq filter (js2-parse-condition))))
9594 (dotimes (_ (1- (length loops)))
9595 (js2-pop-scope)))
9596 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9597 (setq result (make-js2-comp-node :pos pos
9598 :len (- js2-ts-cursor pos)
9599 :result expr
9600 :loops (nreverse loops)
9601 :filters (and filter (list (car filter)))
9602 :form 'LEGACY_ARRAY))
9603 (apply #'js2-node-add-children result expr (car filter)
9604 (js2-comp-node-loops result))
9605 result))
9606
9607 (defun js2-parse-array-comp (pos)
9608 "Parse an ES6 array comprehension.
9609 POS is the beginning of the LB token.
9610 We should have just parsed the 'for' keyword before calling this function."
9611 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9612 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9613 pn))
9614
9615 (defun js2-parse-generator-comp (pos)
9616 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9617 (js2-current-script-or-fn
9618 (make-js2-function-node :generator-type 'COMPREHENSION))
9619 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9620 (js2-must-match js2-RP "msg.no.paren" pos)
9621 pn))
9622
9623 (defun js2-parse-comprehension (pos form)
9624 (let (loops filters expr result)
9625 (unwind-protect
9626 (progn
9627 (js2-unget-token)
9628 (while (js2-match-token js2-FOR)
9629 (let ((loop (make-js2-comp-loop-node)))
9630 (js2-push-scope loop)
9631 (push loop loops)
9632 (js2-parse-comp-loop loop)))
9633 (while (js2-match-token js2-IF)
9634 (push (car (js2-parse-condition)) filters))
9635 (setq expr (js2-parse-assign-expr)))
9636 (dolist (_ loops)
9637 (js2-pop-scope)))
9638 (setq result (make-js2-comp-node :pos pos
9639 :len (- js2-ts-cursor pos)
9640 :result expr
9641 :loops (nreverse loops)
9642 :filters (nreverse filters)
9643 :form form))
9644 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9645 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9646 result))
9647
9648 (defun js2-parse-comp-loop (pn &optional only-of-p)
9649 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9650 The current token should be the initial FOR.
9651 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9652 (let ((pos (js2-comp-loop-node-pos pn))
9653 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9654 (when (and (not only-of-p) (js2-match-token js2-NAME))
9655 (if (string= (js2-current-token-string) "each")
9656 (progn
9657 (setq foreach-p t
9658 each-pos (- (js2-current-token-beg) pos)) ; relative
9659 (js2-record-face 'font-lock-keyword-face))
9660 (js2-report-error "msg.no.paren.for")))
9661 (if (js2-must-match js2-LP "msg.no.paren.for")
9662 (setq lp (- (js2-current-token-beg) pos)))
9663 (setq tt (js2-peek-token))
9664 (cond
9665 ((or (= tt js2-LB)
9666 (= tt js2-LC))
9667 (js2-get-token)
9668 (setq iter (js2-parse-destruct-primary-expr))
9669 (js2-define-destruct-symbols iter js2-LET
9670 'font-lock-variable-name-face t))
9671 ((js2-match-token js2-NAME)
9672 (setq iter (js2-create-name-node)))
9673 (t
9674 (js2-report-error "msg.bad.var")))
9675 ;; Define as a let since we want the scope of the variable to
9676 ;; be restricted to the array comprehension
9677 (if (js2-name-node-p iter)
9678 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9679 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9680 (and (>= js2-language-version 200)
9681 (js2-match-contextual-kwd "of")
9682 (setq forof-p t)))
9683 (setq in-pos (- (js2-current-token-beg) pos))
9684 (js2-report-error "msg.in.after.for.name"))
9685 (setq obj (js2-parse-expr))
9686 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9687 (setq rp (- (js2-current-token-beg) pos)))
9688 (setf (js2-node-pos pn) pos
9689 (js2-node-len pn) (- js2-ts-cursor pos)
9690 (js2-comp-loop-node-iterator pn) iter
9691 (js2-comp-loop-node-object pn) obj
9692 (js2-comp-loop-node-in-pos pn) in-pos
9693 (js2-comp-loop-node-each-pos pn) each-pos
9694 (js2-comp-loop-node-foreach-p pn) foreach-p
9695 (js2-comp-loop-node-forof-p pn) forof-p
9696 (js2-comp-loop-node-lp pn) lp
9697 (js2-comp-loop-node-rp pn) rp)
9698 (js2-node-add-children pn iter obj)
9699 pn))
9700
9701 (defun js2-parse-class-stmt ()
9702 (let ((pos (js2-current-token-beg)))
9703 (js2-must-match-name "msg.unnamed.class.stmt")
9704 (js2-parse-class pos 'CLASS_STATEMENT (js2-create-name-node t))))
9705
9706 (defun js2-parse-class-expr ()
9707 (let ((pos (js2-current-token-beg))
9708 name)
9709 (when (js2-match-token js2-NAME)
9710 (setq name (js2-create-name-node t)))
9711 (js2-parse-class pos 'CLASS_EXPRESSION name)))
9712
9713 (defun js2-parse-class (pos form name)
9714 ;; class X [extends ...] {
9715 (let (pn elems extends)
9716 (when name
9717 (js2-set-face (js2-node-pos name) (js2-node-end name)
9718 'font-lock-function-name-face 'record))
9719 (if (js2-match-token js2-EXTENDS)
9720 (if (= (js2-peek-token) js2-LC)
9721 (js2-report-error "msg.missing.extends")
9722 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
9723 (setq extends (js2-parse-assign-expr))
9724 (if (not extends)
9725 (js2-report-error "msg.bad.extends"))))
9726 (js2-must-match js2-LC "msg.no.brace.class")
9727 (setq elems (js2-parse-object-literal-elems t)
9728 pn (make-js2-class-node :pos pos
9729 :len (- js2-ts-cursor pos)
9730 :form form
9731 :name name
9732 :extends extends
9733 :elems elems))
9734 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
9735 pn))
9736
9737 (defun js2-parse-object-literal ()
9738 (let* ((pos (js2-current-token-beg))
9739 (elems (js2-parse-object-literal-elems))
9740 (result (make-js2-object-node :pos pos
9741 :len (- js2-ts-cursor pos)
9742 :elems elems)))
9743 (apply #'js2-node-add-children result (js2-object-node-elems result))
9744 result))
9745
9746 (defun js2-parse-object-literal-elems (&optional class-p)
9747 (let ((pos (js2-current-token-beg))
9748 (static nil)
9749 (continue t)
9750 tt elems elem after-comma)
9751 (while continue
9752 (setq static (and class-p (js2-match-token js2-STATIC))
9753 tt (js2-get-prop-name-token)
9754 elem nil)
9755 (cond
9756 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9757 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
9758 ;; TODO(sdh): support *foo() {...}
9759 ((or (= js2-NAME tt)
9760 (= tt js2-STRING))
9761 (setq after-comma nil
9762 elem (js2-parse-named-prop tt))
9763 (if (and (null elem)
9764 (not js2-recover-from-parse-errors))
9765 (setq continue nil)))
9766 ;; {[Symbol.iterator]: ...}
9767 ((and (= tt js2-LB)
9768 (>= js2-language-version 200))
9769 (let ((expr (js2-parse-expr)))
9770 (js2-must-match js2-RB "msg.missing.computed.rb")
9771 (setq after-comma nil
9772 elem (js2-parse-plain-property expr))))
9773 ;; {12: x} or {10.7: x}
9774 ((= tt js2-NUMBER)
9775 (setq after-comma nil
9776 elem (js2-parse-plain-property (make-js2-number-node))))
9777 ;; Break out of loop, and handle trailing commas.
9778 ((or (= tt js2-RC)
9779 (= tt js2-EOF))
9780 (js2-unget-token)
9781 (setq continue nil)
9782 (if after-comma
9783 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9784 pos elems after-comma)))
9785 (t
9786 (js2-report-error "msg.bad.prop")
9787 (unless js2-recover-from-parse-errors
9788 (setq continue nil)))) ; end switch
9789 ;; Handle static for classes' codegen.
9790 (if static
9791 (if elem (js2-node-set-prop elem 'STATIC t)
9792 (js2-report-error "msg.unexpected.static")))
9793 ;; Handle commas, depending on class-p.
9794 (let ((comma (js2-match-token js2-COMMA)))
9795 (if class-p
9796 (if comma
9797 (js2-report-error "msg.class.unexpected.comma"))
9798 (if comma
9799 (setq after-comma (js2-current-token-end))
9800 (setq continue nil))))
9801 ;; Append any parsed element.
9802 (if elem (push elem elems))) ; end loop
9803 (js2-must-match js2-RC "msg.no.brace.prop")
9804 (nreverse elems)))
9805
9806 (defun js2-parse-named-prop (tt)
9807 "Parse a name, string, or getter/setter object property.
9808 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9809 (let ((string-prop (and (= tt js2-STRING)
9810 (make-js2-string-node)))
9811 expr
9812 (ppos (js2-current-token-beg))
9813 (pend (js2-current-token-end))
9814 (name (js2-create-name-node))
9815 (prop (js2-current-token-string)))
9816 (cond
9817 ;; getter/setter prop
9818 ((and (= tt js2-NAME)
9819 (= (js2-peek-token) js2-NAME)
9820 (or (string= prop "get")
9821 (string= prop "set")))
9822 (js2-get-token)
9823 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9824 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9825 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9826 (js2-parse-getter-setter-prop ppos name prop))
9827 ;; method definition: {f() {...}}
9828 ((and (= (js2-peek-token) js2-LP)
9829 (>= js2-language-version 200))
9830 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; name
9831 (js2-parse-getter-setter-prop ppos name ""))
9832 ;; regular prop
9833 (t
9834 (prog1
9835 (setq expr (js2-parse-plain-property (or string-prop name)))
9836 (when (and (not string-prop)
9837 (not js2-is-in-destructuring)
9838 js2-highlight-external-variables
9839 (js2-node-get-prop expr 'SHORTHAND))
9840 (js2-record-name-node name))
9841 (js2-set-face ppos pend
9842 (if (js2-function-node-p
9843 (js2-object-prop-node-right expr))
9844 'font-lock-function-name-face
9845 'font-lock-variable-name-face)
9846 'record))))))
9847
9848 (defun js2-parse-plain-property (prop)
9849 "Parse a non-getter/setter property in an object literal.
9850 PROP is the node representing the property: a number, name or string."
9851 (let* ((tt (js2-get-token))
9852 (pos (js2-node-pos prop))
9853 colon expr result)
9854 (cond
9855 ;; Abbreviated property, as in {foo, bar}
9856 ((and (>= js2-language-version 200)
9857 (or (= tt js2-COMMA)
9858 (= tt js2-RC))
9859 (not (js2-number-node-p prop)))
9860 (js2-unget-token)
9861 (setq result (make-js2-object-prop-node
9862 :pos pos
9863 :left prop
9864 :right prop
9865 :op-pos (js2-current-token-len)))
9866 (js2-node-add-children result prop)
9867 (js2-node-set-prop result 'SHORTHAND t)
9868 result)
9869 ;; Normal property
9870 (t
9871 (if (= tt js2-COLON)
9872 (setq colon (- (js2-current-token-beg) pos)
9873 expr (js2-parse-assign-expr))
9874 (js2-report-error "msg.no.colon.prop")
9875 (setq expr (make-js2-error-node)))
9876 (setq result (make-js2-object-prop-node
9877 :pos pos
9878 ;; don't include last consumed token in length
9879 :len (- (+ (js2-node-pos expr)
9880 (js2-node-len expr))
9881 pos)
9882 :left prop
9883 :right expr
9884 :op-pos colon))
9885 (js2-node-add-children result prop expr)
9886 result))))
9887
9888 (defun js2-parse-getter-setter-prop (pos prop type-string)
9889 "Parse getter or setter property in an object literal.
9890 JavaScript syntax is:
9891
9892 { get foo() {...}, set foo(x) {...} }
9893
9894 and expression closure style is also supported
9895
9896 { get foo() x, set foo(x) _x = x }
9897
9898 POS is the start position of the `get' or `set' keyword.
9899 PROP is the `js2-name-node' representing the property name.
9900 GET-P is non-nil if the keyword was `get'."
9901 (let ((type (cond
9902 ((string= "get" type-string) js2-GET)
9903 ((string= "set" type-string) js2-SET)
9904 (t js2-FUNCTION)))
9905 result end
9906 (fn (js2-parse-function-expr)))
9907 ;; it has to be an anonymous function, as we already parsed the name
9908 (if (/= (js2-node-type fn) js2-FUNCTION)
9909 (js2-report-error "msg.bad.prop")
9910 (if (plusp (length (js2-function-name fn)))
9911 (js2-report-error "msg.bad.prop")))
9912 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9913 (setq end (js2-node-end fn)
9914 result (make-js2-getter-setter-node :type type
9915 :pos pos
9916 :len (- end pos)
9917 :left prop
9918 :right fn))
9919 (js2-node-add-children result prop fn)
9920 result))
9921
9922 (defun js2-create-name-node (&optional check-activation-p token string)
9923 "Create a name node using the current token and, optionally, STRING.
9924 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9925 (let* ((beg (js2-current-token-beg))
9926 (tt (js2-current-token-type))
9927 (s (or string
9928 (if (= js2-NAME tt)
9929 (js2-current-token-string)
9930 (js2-tt-name tt))))
9931 name)
9932 (setq name (make-js2-name-node :pos beg
9933 :name s
9934 :len (length s)))
9935 (if check-activation-p
9936 (js2-check-activation-name s (or token js2-NAME)))
9937 name))
9938
9939 ;;; Indentation support
9940
9941 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9942 ;; Karl cleverly deduces that the desired indentation level is often a
9943 ;; function of paren/bracket/brace nesting depth, which can be determined
9944 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9945 ;; then does some equally clever checks to see if we're in the context of a
9946 ;; substatement of a possibly braceless statement keyword such as if, while,
9947 ;; or finally. This approach yields pretty good results.
9948
9949 ;; The indenter is often "wrong", however, and needs to be overridden.
9950 ;; The right long-term solution is probably to emulate (or integrate
9951 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9952 ;; parse tree from `js2-parse' is present, which is not true at the
9953 ;; moment the user is typing, computing indentation is still thousands
9954 ;; of lines of code to handle every possible syntactic edge case.
9955
9956 ;; In the meantime, the compromise solution is that we offer a "bounce
9957 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9958 ;; current line indent among various likely guess points. This approach
9959 ;; is far from perfect, but should at least make it slightly easier to
9960 ;; move the line towards its desired indentation when manually
9961 ;; overriding Karl's heuristic nesting guesser.
9962
9963 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9964 ;; extensions such as `let' and Array comprehensions. Major kudos to
9965 ;; Karl for coming up with the initial approach, which packs a lot of
9966 ;; punch for so little code.
9967
9968 (defconst js2-possibly-braceless-keywords-re
9969 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9970 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9971 "try" "while" "with" "let")))
9972 "Regular expression matching keywords that are optionally
9973 followed by an opening brace.")
9974
9975 (defconst js2-indent-operator-re
9976 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9977 (regexp-opt '("in" "instanceof") 'words))
9978 "Regular expression matching operators that affect indentation
9979 of continued expressions.")
9980
9981 (defconst js2-declaration-keyword-re
9982 (regexp-opt '("var" "let" "const") 'words)
9983 "Regular expression matching variable declaration keywords.")
9984
9985 (defun js2-re-search-forward-inner (regexp &optional bound count)
9986 "Auxiliary function for `js2-re-search-forward'."
9987 (let (parse saved-point)
9988 (while (> count 0)
9989 (re-search-forward regexp bound)
9990 (setq parse (if saved-point
9991 (parse-partial-sexp saved-point (point))
9992 (syntax-ppss (point))))
9993 (cond ((nth 3 parse)
9994 (re-search-forward
9995 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9996 (save-excursion (end-of-line) (point)) t))
9997 ((nth 7 parse)
9998 (forward-line))
9999 ((or (nth 4 parse)
10000 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10001 (re-search-forward "\\*/"))
10002 (t
10003 (setq count (1- count))))
10004 (setq saved-point (point))))
10005 (point))
10006
10007 (defun js2-re-search-forward (regexp &optional bound noerror count)
10008 "Search forward but ignore strings and comments.
10009 Invokes `re-search-forward' but treats the buffer as if strings
10010 and comments have been removed."
10011 (let ((saved-point (point)))
10012 (condition-case err
10013 (cond ((null count)
10014 (js2-re-search-forward-inner regexp bound 1))
10015 ((< count 0)
10016 (js2-re-search-backward-inner regexp bound (- count)))
10017 ((> count 0)
10018 (js2-re-search-forward-inner regexp bound count)))
10019 (search-failed
10020 (goto-char saved-point)
10021 (unless noerror
10022 (error (error-message-string err)))))))
10023
10024 (defun js2-re-search-backward-inner (regexp &optional bound count)
10025 "Auxiliary function for `js2-re-search-backward'."
10026 (let (parse)
10027 (while (> count 0)
10028 (re-search-backward regexp bound)
10029 (setq parse (syntax-ppss (point)))
10030 (cond ((nth 3 parse)
10031 (re-search-backward
10032 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10033 (line-beginning-position) t))
10034 ((nth 7 parse)
10035 (goto-char (nth 8 parse)))
10036 ((or (nth 4 parse)
10037 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10038 (re-search-backward "/\\*"))
10039 (t
10040 (setq count (1- count))))))
10041 (point))
10042
10043 (defun js2-re-search-backward (regexp &optional bound noerror count)
10044 "Search backward but ignore strings and comments.
10045 Invokes `re-search-backward' but treats the buffer as if strings
10046 and comments have been removed."
10047 (let ((saved-point (point)))
10048 (condition-case err
10049 (cond ((null count)
10050 (js2-re-search-backward-inner regexp bound 1))
10051 ((< count 0)
10052 (js2-re-search-forward-inner regexp bound (- count)))
10053 ((> count 0)
10054 (js2-re-search-backward-inner regexp bound count)))
10055 (search-failed
10056 (goto-char saved-point)
10057 (unless noerror
10058 (error (error-message-string err)))))))
10059
10060 (defun js2-looking-at-operator-p ()
10061 "Return non-nil if text after point is a non-comma operator."
10062 (and (looking-at js2-indent-operator-re)
10063 (or (not (looking-at ":"))
10064 (save-excursion
10065 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10066 (looking-at "?"))))))
10067
10068 (defun js2-continued-expression-p ()
10069 "Return non-nil if the current line continues an expression."
10070 (save-excursion
10071 (back-to-indentation)
10072 (or (js2-looking-at-operator-p)
10073 (when (catch 'found
10074 (while (and (re-search-backward "\n" nil t)
10075 (let ((state (syntax-ppss)))
10076 (when (nth 4 state)
10077 (goto-char (nth 8 state))) ;; skip comments
10078 (skip-chars-backward " \t")
10079 (if (bolp)
10080 t
10081 (throw 'found t))))))
10082 (backward-char)
10083 (when (js2-looking-at-operator-p)
10084 (backward-char)
10085 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10086
10087 (defun js2-end-of-do-while-loop-p ()
10088 "Return non-nil if word after point is `while' of a do-while
10089 statement, else returns nil. A braceless do-while statement
10090 spanning several lines requires that the start of the loop is
10091 indented to the same column as the current line."
10092 (interactive)
10093 (save-excursion
10094 (when (looking-at "\\s-*\\<while\\>")
10095 (if (save-excursion
10096 (skip-chars-backward "[ \t\n]*}")
10097 (looking-at "[ \t\n]*}"))
10098 (save-excursion
10099 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10100 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10101 (or (looking-at "\\<do\\>")
10102 (let ((saved-indent (current-indentation)))
10103 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10104 (/= (current-indentation) saved-indent)))
10105 (and (looking-at "[ \t]*\\<do\\>")
10106 (not (js2-re-search-forward
10107 "\\<while\\>" (point-at-eol) t))
10108 (= (current-indentation) saved-indent))))))))
10109
10110 (defun js2-multiline-decl-indentation ()
10111 "Return the declaration indentation column if the current line belongs
10112 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10113 (let (forward-sexp-function ; use Lisp version
10114 at-opening-bracket)
10115 (save-excursion
10116 (back-to-indentation)
10117 (when (not (looking-at js2-declaration-keyword-re))
10118 (when (looking-at js2-indent-operator-re)
10119 (goto-char (match-end 0))) ; continued expressions are ok
10120 (while (and (not at-opening-bracket)
10121 (not (bobp))
10122 (let ((pos (point)))
10123 (save-excursion
10124 (js2-backward-sws)
10125 (or (eq (char-before) ?,)
10126 (and (not (eq (char-before) ?\;))
10127 (prog2 (skip-syntax-backward ".")
10128 (looking-at js2-indent-operator-re)
10129 (js2-backward-sws))
10130 (not (eq (char-before) ?\;)))
10131 (js2-same-line pos)))))
10132 (condition-case _
10133 (backward-sexp)
10134 (scan-error (setq at-opening-bracket t))))
10135 (when (looking-at js2-declaration-keyword-re)
10136 (goto-char (match-end 0))
10137 (1+ (current-column)))))))
10138
10139 (defun js2-ctrl-statement-indentation ()
10140 "Return the proper indentation of current line if it is a control statement.
10141 Returns an indentation if this line starts the body of a control
10142 statement without braces, else returns nil."
10143 (let (forward-sexp-function)
10144 (save-excursion
10145 (back-to-indentation)
10146 (when (and (not (js2-same-line (point-min)))
10147 (not (looking-at "{"))
10148 (js2-re-search-backward "[[:graph:]]" nil t)
10149 (not (looking-at "[{([]"))
10150 (progn
10151 (forward-char)
10152 (when (= (char-before) ?\))
10153 ;; scan-sexps sometimes throws an error
10154 (ignore-errors (backward-sexp))
10155 (skip-chars-backward " \t" (point-at-bol)))
10156 (let ((pt (point)))
10157 (back-to-indentation)
10158 (when (looking-at "}[ \t]*")
10159 (goto-char (match-end 0)))
10160 (and (looking-at js2-possibly-braceless-keywords-re)
10161 (= (match-end 0) pt)
10162 (not (js2-end-of-do-while-loop-p))))))
10163 (+ (current-indentation) js2-basic-offset)))))
10164
10165 (defun js2-indent-in-array-comp (parse-status)
10166 "Return non-nil if we think we're in an array comprehension.
10167 In particular, return the buffer position of the first `for' kwd."
10168 (let ((bracket (nth 1 parse-status))
10169 (end (point)))
10170 (when bracket
10171 (save-excursion
10172 (goto-char bracket)
10173 (when (looking-at "\\[")
10174 (forward-char 1)
10175 (js2-forward-sws)
10176 (if (looking-at "[[{]")
10177 (let (forward-sexp-function) ; use Lisp version
10178 (forward-sexp) ; skip destructuring form
10179 (js2-forward-sws)
10180 (if (and (/= (char-after) ?,) ; regular array
10181 (looking-at "for"))
10182 (match-beginning 0)))
10183 ;; to skip arbitrary expressions we need the parser,
10184 ;; so we'll just guess at it.
10185 (if (and (> end (point)) ; not empty literal
10186 (re-search-forward "[^,]]* \\(for\\) " end t)
10187 ;; not inside comment or string literal
10188 (let ((state (parse-partial-sexp bracket (point))))
10189 (not (or (nth 3 state) (nth 4 state)))))
10190 (match-beginning 1))))))))
10191
10192 (defun js2-array-comp-indentation (parse-status for-kwd)
10193 (if (js2-same-line for-kwd)
10194 ;; first continuation line
10195 (save-excursion
10196 (goto-char (nth 1 parse-status))
10197 (forward-char 1)
10198 (skip-chars-forward " \t")
10199 (current-column))
10200 (save-excursion
10201 (goto-char for-kwd)
10202 (current-column))))
10203
10204 (defun js2-proper-indentation (parse-status)
10205 "Return the proper indentation for the current line."
10206 (save-excursion
10207 (back-to-indentation)
10208 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10209 (at-closing-bracket (looking-at "[]})]"))
10210 (same-indent-p (or at-closing-bracket
10211 (looking-at "\\<case\\>[^:]")
10212 (and (looking-at "\\<default:")
10213 (save-excursion
10214 (js2-backward-sws)
10215 (not (memq (char-before) '(?, ?{)))))))
10216 (continued-expr-p (js2-continued-expression-p))
10217 (declaration-indent (and js2-pretty-multiline-declarations
10218 (js2-multiline-decl-indentation)))
10219 (bracket (nth 1 parse-status))
10220 beg indent)
10221 (cond
10222 ;; indent array comprehension continuation lines specially
10223 ((and bracket
10224 (>= js2-language-version 170)
10225 (not (js2-same-line bracket))
10226 (setq beg (js2-indent-in-array-comp parse-status))
10227 (>= (point) (save-excursion
10228 (goto-char beg)
10229 (point-at-bol)))) ; at or after first loop?
10230 (js2-array-comp-indentation parse-status beg))
10231
10232 (ctrl-stmt-indent)
10233
10234 ((and declaration-indent continued-expr-p)
10235 (+ declaration-indent js2-basic-offset))
10236
10237 (declaration-indent)
10238
10239 (bracket
10240 (goto-char bracket)
10241 (cond
10242 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10243 (when (save-excursion (skip-chars-backward " \t)")
10244 (looking-at ")"))
10245 (backward-list))
10246 (back-to-indentation)
10247 (and (eq js2-pretty-multiline-declarations 'all)
10248 (looking-at js2-declaration-keyword-re)
10249 (goto-char (1+ (match-end 0))))
10250 (setq indent
10251 (cond (same-indent-p
10252 (current-column))
10253 (continued-expr-p
10254 (+ (current-column) (* 2 js2-basic-offset)))
10255 (t
10256 (+ (current-column) js2-basic-offset))))
10257 (if (and js2-indent-switch-body
10258 (not at-closing-bracket)
10259 (looking-at "\\_<switch\\_>"))
10260 (+ indent js2-basic-offset)
10261 indent))
10262 (t
10263 (unless same-indent-p
10264 (forward-char)
10265 (skip-chars-forward " \t"))
10266 (current-column))))
10267
10268 (continued-expr-p js2-basic-offset)
10269
10270 (t 0)))))
10271
10272 (defun js2-lineup-comment (parse-status)
10273 "Indent a multi-line block comment continuation line."
10274 (let* ((beg (nth 8 parse-status))
10275 (first-line (js2-same-line beg))
10276 (offset (save-excursion
10277 (goto-char beg)
10278 (if (looking-at "/\\*")
10279 (+ 1 (current-column))
10280 0))))
10281 (unless first-line
10282 (indent-line-to offset))))
10283
10284 (defun js2-backward-sws ()
10285 "Move backward through whitespace and comments."
10286 (interactive)
10287 (while (forward-comment -1)))
10288
10289 (defun js2-forward-sws ()
10290 "Move forward through whitespace and comments."
10291 (interactive)
10292 (while (forward-comment 1)))
10293
10294 (defun js2-current-indent (&optional pos)
10295 "Return column of indentation on current line.
10296 If POS is non-nil, go to that point and return indentation for that line."
10297 (save-excursion
10298 (if pos
10299 (goto-char pos))
10300 (back-to-indentation)
10301 (current-column)))
10302
10303 (defun js2-arglist-close ()
10304 "Return non-nil if we're on a line beginning with a close-paren/brace."
10305 (save-excursion
10306 (goto-char (point-at-bol))
10307 (js2-forward-sws)
10308 (looking-at "[])}]")))
10309
10310 (defun js2-indent-looks-like-label-p ()
10311 (goto-char (point-at-bol))
10312 (js2-forward-sws)
10313 (looking-at (concat js2-mode-identifier-re ":")))
10314
10315 (defun js2-indent-in-objlit-p (parse-status)
10316 "Return non-nil if this looks like an object-literal entry."
10317 (let ((start (nth 1 parse-status)))
10318 (and
10319 start
10320 (save-excursion
10321 (and (zerop (forward-line -1))
10322 (not (< (point) start)) ; crossed a {} boundary
10323 (js2-indent-looks-like-label-p)))
10324 (save-excursion
10325 (js2-indent-looks-like-label-p)))))
10326
10327 ;; If prev line looks like foobar({ then we're passing an object
10328 ;; literal to a function call, and people pretty much always want to
10329 ;; de-dent back to the previous line, so move the 'basic-offset'
10330 ;; position to the front.
10331 (defun js2-indent-objlit-arg-p (parse-status)
10332 (save-excursion
10333 (back-to-indentation)
10334 (js2-backward-sws)
10335 (and (eq (1- (point)) (nth 1 parse-status))
10336 (eq (char-before) ?{)
10337 (progn
10338 (forward-char -1)
10339 (skip-chars-backward " \t")
10340 (eq (char-before) ?\()))))
10341
10342 (defun js2-indent-case-block-p ()
10343 (save-excursion
10344 (back-to-indentation)
10345 (js2-backward-sws)
10346 (goto-char (point-at-bol))
10347 (skip-chars-forward " \t")
10348 (looking-at "case\\s-.+:")))
10349
10350 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10351 "Cycle among alternate computed indentation positions.
10352 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10353 of the buffer to the current point. NORMAL-COL is the indentation
10354 column computed by the heuristic guesser based on current paren,
10355 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10356 in reverse."
10357 (let ((cur-indent (js2-current-indent))
10358 (old-buffer-undo-list buffer-undo-list)
10359 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10360 (current-line (save-excursion
10361 (forward-line 0) ; move to bol
10362 (1+ (count-lines (point-min) (point)))))
10363 positions pos main-pos anchor arglist-cont same-indent
10364 basic-offset computed-pos)
10365 ;; temporarily don't record undo info, if user requested this
10366 (when js2-mode-indent-inhibit-undo
10367 (setq buffer-undo-list t))
10368 (unwind-protect
10369 (progn
10370 ;; First likely point: indent from beginning of previous code line
10371 (push (setq basic-offset
10372 (+ (save-excursion
10373 (back-to-indentation)
10374 (js2-backward-sws)
10375 (back-to-indentation)
10376 (current-column))
10377 js2-basic-offset))
10378 positions)
10379
10380 ;; (First + epsilon) likely point: indent 2x from beginning of
10381 ;; previous code line. Google does it this way.
10382 (push (setq basic-offset
10383 (+ (save-excursion
10384 (back-to-indentation)
10385 (js2-backward-sws)
10386 (back-to-indentation)
10387 (current-column))
10388 (* 2 js2-basic-offset)))
10389 positions)
10390
10391 ;; Second likely point: indent from assign-expr RHS. This
10392 ;; is just a crude guess based on finding " = " on the previous
10393 ;; line containing actual code.
10394 (setq pos (save-excursion
10395 (forward-line -1)
10396 (goto-char (point-at-bol))
10397 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10398 (point-at-eol) t)
10399 (goto-char (match-end 1))
10400 (skip-chars-forward " \t\r\n")
10401 (current-column))))
10402 (when pos
10403 (incf pos js2-basic-offset)
10404 (push pos positions))
10405
10406 ;; Third likely point: same indent as previous line of code.
10407 ;; Make it the first likely point if we're not on an
10408 ;; arglist-close line and previous line ends in a comma, or
10409 ;; both this line and prev line look like object-literal
10410 ;; elements.
10411 (setq pos (save-excursion
10412 (goto-char (point-at-bol))
10413 (js2-backward-sws)
10414 (back-to-indentation)
10415 (prog1
10416 (current-column)
10417 ;; while we're here, look for trailing comma
10418 (if (save-excursion
10419 (goto-char (point-at-eol))
10420 (js2-backward-sws)
10421 (eq (char-before) ?,))
10422 (setq arglist-cont (1- (point)))))))
10423 (when pos
10424 (if (and (or arglist-cont
10425 (js2-indent-in-objlit-p parse-status))
10426 (not (js2-arglist-close)))
10427 (setq same-indent pos))
10428 (push pos positions))
10429
10430 ;; Fourth likely point: first preceding code with less indentation.
10431 ;; than the immediately preceding code line.
10432 (setq pos (save-excursion
10433 (back-to-indentation)
10434 (js2-backward-sws)
10435 (back-to-indentation)
10436 (setq anchor (current-column))
10437 (while (and (zerop (forward-line -1))
10438 (>= (progn
10439 (back-to-indentation)
10440 (current-column))
10441 anchor)))
10442 (setq pos (current-column))))
10443 (push pos positions)
10444
10445 ;; nesting-heuristic position, main by default
10446 (push (setq main-pos normal-col) positions)
10447
10448 ;; delete duplicates and sort positions list
10449 (setq positions (sort (delete-dups positions) '<))
10450
10451 ;; comma-list continuation lines: prev line indent takes precedence
10452 (if same-indent
10453 (setq main-pos same-indent))
10454
10455 ;; common special cases where we want to indent in from previous line
10456 (if (or (js2-indent-case-block-p)
10457 (js2-indent-objlit-arg-p parse-status))
10458 (setq main-pos basic-offset))
10459
10460 ;; if bouncing backwards, reverse positions list
10461 (if backwards
10462 (setq positions (reverse positions)))
10463
10464 ;; record whether we're already sitting on one of the alternatives
10465 (setq pos (member cur-indent positions))
10466
10467 (cond
10468 ;; case 0: we're one one of the alternatives and this is the
10469 ;; first time they've pressed TAB on this line (best-guess).
10470 ((and js2-mode-indent-ignore-first-tab
10471 pos
10472 ;; first time pressing TAB on this line?
10473 (not (eq js2-mode-last-indented-line current-line)))
10474 ;; do nothing
10475 (setq computed-pos nil))
10476 ;; case 1: only one computed position => use it
10477 ((null (cdr positions))
10478 (setq computed-pos 0))
10479 ;; case 2: not on any of the computed spots => use main spot
10480 ((not pos)
10481 (setq computed-pos (js2-position main-pos positions)))
10482 ;; case 3: on last position: cycle to first position
10483 ((null (cdr pos))
10484 (setq computed-pos 0))
10485 ;; case 4: on intermediate position: cycle to next position
10486 (t
10487 (setq computed-pos (js2-position (second pos) positions))))
10488
10489 ;; see if any hooks want to indent; otherwise we do it
10490 (loop with result = nil
10491 for hook in js2-indent-hook
10492 while (null result)
10493 do
10494 (setq result (funcall hook positions computed-pos))
10495 finally do
10496 (unless (or result (null computed-pos))
10497 (indent-line-to (nth computed-pos positions)))))
10498
10499 ;; finally
10500 (if js2-mode-indent-inhibit-undo
10501 (setq buffer-undo-list old-buffer-undo-list))
10502 ;; see commentary for `js2-mode-last-indented-line'
10503 (setq js2-mode-last-indented-line current-line))))
10504
10505 (defun js2-indent-bounce-backwards ()
10506 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10507 cycles between the computed indentation positions in reverse order."
10508 (interactive)
10509 (js2-indent-line t))
10510
10511 (defun js2-1-line-comment-continuation-p ()
10512 "Return t if we're in a 1-line comment continuation.
10513 If so, we don't ever want to use bounce-indent."
10514 (save-excursion
10515 (and (progn
10516 (forward-line 0)
10517 (looking-at "\\s-*//"))
10518 (progn
10519 (forward-line -1)
10520 (forward-line 0)
10521 (when (looking-at "\\s-*$")
10522 (js2-backward-sws)
10523 (forward-line 0))
10524 (looking-at "\\s-*//")))))
10525
10526 (defun js2-indent-line (&optional bounce-backwards)
10527 "Indent the current line as JavaScript source text."
10528 (interactive)
10529 (let (parse-status offset indent-col
10530 ;; Don't whine about errors/warnings when we're indenting.
10531 ;; This has to be set before calling parse-partial-sexp below.
10532 (inhibit-point-motion-hooks t))
10533 (setq parse-status (save-excursion
10534 (syntax-ppss (point-at-bol)))
10535 offset (- (point) (save-excursion
10536 (back-to-indentation)
10537 (point))))
10538 (js2-with-underscore-as-word-syntax
10539 (if (nth 4 parse-status)
10540 (js2-lineup-comment parse-status)
10541 (setq indent-col (js2-proper-indentation parse-status))
10542 ;; See comments below about `js2-mode-last-indented-line'.
10543 (cond
10544 ;; bounce-indenting is disabled during electric-key indent.
10545 ;; It doesn't work well on first line of buffer.
10546 ((and js2-bounce-indent-p
10547 (not (js2-same-line (point-min)))
10548 (not (js2-1-line-comment-continuation-p)))
10549 (js2-bounce-indent indent-col parse-status bounce-backwards))
10550 ;; just indent to the guesser's likely spot
10551 (t (indent-line-to indent-col))))
10552 (when (plusp offset)
10553 (forward-char offset)))))
10554
10555 (defun js2-indent-region (start end)
10556 "Indent the region, but don't use bounce indenting."
10557 (let ((js2-bounce-indent-p nil)
10558 (indent-region-function nil)
10559 (after-change-functions (remq 'js2-mode-edit
10560 after-change-functions)))
10561 (indent-region start end nil) ; nil for byte-compiler
10562 (js2-mode-edit start end (- end start))))
10563
10564 (defvar js2-minor-mode-map
10565 (let ((map (make-sparse-keymap)))
10566 (define-key map (kbd "C-c C-`") #'js2-next-error)
10567 (define-key map [mouse-1] #'js2-mode-show-node)
10568 map)
10569 "Keymap used when `js2-minor-mode' is active.")
10570
10571 ;;;###autoload
10572 (define-minor-mode js2-minor-mode
10573 "Minor mode for running js2 as a background linter.
10574 This allows you to use a different major mode for JavaScript editing,
10575 such as `js-mode', while retaining the asynchronous error/warning
10576 highlighting features of `js2-mode'."
10577 :group 'js2-mode
10578 :lighter " js-lint"
10579 (if js2-minor-mode
10580 (js2-minor-mode-enter)
10581 (js2-minor-mode-exit)))
10582
10583 (defun js2-minor-mode-enter ()
10584 "Initialization for `js2-minor-mode'."
10585 (set (make-local-variable 'max-lisp-eval-depth)
10586 (max max-lisp-eval-depth 3000))
10587 (setq next-error-function #'js2-next-error)
10588 (js2-set-default-externs)
10589 ;; Experiment: make reparse-delay longer for longer files.
10590 (if (plusp js2-dynamic-idle-timer-adjust)
10591 (setq js2-idle-timer-delay
10592 (* js2-idle-timer-delay
10593 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10594 (setq js2-mode-buffer-dirty-p t
10595 js2-mode-parsing nil)
10596 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10597 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10598 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10599 (when js2-include-jslint-globals
10600 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10601 (run-hooks 'js2-init-hook)
10602 (js2-reparse))
10603
10604 (defun js2-minor-mode-exit ()
10605 "Turn off `js2-minor-mode'."
10606 (setq next-error-function nil)
10607 (remove-hook 'after-change-functions #'js2-mode-edit t)
10608 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10609 (when js2-mode-node-overlay
10610 (delete-overlay js2-mode-node-overlay)
10611 (setq js2-mode-node-overlay nil))
10612 (js2-remove-overlays)
10613 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10614 (setq js2-mode-ast nil))
10615
10616 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10617 (make-variable-buffer-local 'js2-source-buffer)
10618
10619 (defun* js2-display-error-list ()
10620 "Display a navigable buffer listing parse errors/warnings."
10621 (interactive)
10622 (unless (js2-have-errors-p)
10623 (message "No errors")
10624 (return-from js2-display-error-list))
10625 (labels ((annotate-list
10626 (lst type)
10627 "Add diagnostic TYPE and line number to errs list"
10628 (mapcar (lambda (err)
10629 (list err type (line-number-at-pos (nth 1 err))))
10630 lst)))
10631 (let* ((srcbuf (current-buffer))
10632 (errbuf (get-buffer-create "*js-lint*"))
10633 (errors (annotate-list
10634 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10635 'js2-error)) ; must be a valid face name
10636 (warnings (annotate-list
10637 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10638 'js2-warning)) ; must be a valid face name
10639 (all-errs (sort (append errors warnings)
10640 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10641 (with-current-buffer errbuf
10642 (let ((inhibit-read-only t))
10643 (erase-buffer)
10644 (dolist (err all-errs)
10645 (destructuring-bind ((msg-key beg _end &rest) type line) err
10646 (insert-text-button
10647 (format "line %d: %s" line (js2-get-msg msg-key))
10648 'face type
10649 'follow-link "\C-m"
10650 'action 'js2-error-buffer-jump
10651 'js2-msg (js2-get-msg msg-key)
10652 'js2-pos beg)
10653 (insert "\n"))))
10654 (js2-error-buffer-mode)
10655 (setq js2-source-buffer srcbuf)
10656 (pop-to-buffer errbuf)
10657 (goto-char (point-min))
10658 (unless (eobp)
10659 (js2-error-buffer-view))))))
10660
10661 (defvar js2-error-buffer-mode-map
10662 (let ((map (make-sparse-keymap)))
10663 (define-key map "n" #'js2-error-buffer-next)
10664 (define-key map "p" #'js2-error-buffer-prev)
10665 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10666 (define-key map "o" #'js2-error-buffer-view)
10667 (define-key map "q" #'js2-error-buffer-quit)
10668 map)
10669 "Keymap used for js2 diagnostics buffers.")
10670
10671 (defun js2-error-buffer-mode ()
10672 "Major mode for js2 diagnostics buffers.
10673 Selecting an error will jump it to the corresponding source-buffer error.
10674 \\{js2-error-buffer-mode-map}"
10675 (interactive)
10676 (setq major-mode 'js2-error-buffer-mode
10677 mode-name "JS Lint Diagnostics")
10678 (use-local-map js2-error-buffer-mode-map)
10679 (setq truncate-lines t)
10680 (set-buffer-modified-p nil)
10681 (setq buffer-read-only t)
10682 (run-hooks 'js2-error-buffer-mode-hook))
10683
10684 (defun js2-error-buffer-next ()
10685 "Move to next error and view it."
10686 (interactive)
10687 (when (zerop (forward-line 1))
10688 (js2-error-buffer-view)))
10689
10690 (defun js2-error-buffer-prev ()
10691 "Move to previous error and view it."
10692 (interactive)
10693 (when (zerop (forward-line -1))
10694 (js2-error-buffer-view)))
10695
10696 (defun js2-error-buffer-quit ()
10697 "Kill the current buffer."
10698 (interactive)
10699 (kill-buffer))
10700
10701 (defun js2-error-buffer-jump (&rest ignored)
10702 "Jump cursor to current error in source buffer."
10703 (interactive)
10704 (when (js2-error-buffer-view)
10705 (pop-to-buffer js2-source-buffer)))
10706
10707 (defun js2-error-buffer-view ()
10708 "Scroll source buffer to show error at current line."
10709 (interactive)
10710 (cond
10711 ((not (eq major-mode 'js2-error-buffer-mode))
10712 (message "Not in a js2 errors buffer"))
10713 ((not (buffer-live-p js2-source-buffer))
10714 (message "Source buffer has been killed"))
10715 ((not (wholenump (get-text-property (point) 'js2-pos)))
10716 (message "There does not seem to be an error here"))
10717 (t
10718 (let ((pos (get-text-property (point) 'js2-pos))
10719 (msg (get-text-property (point) 'js2-msg)))
10720 (save-selected-window
10721 (pop-to-buffer js2-source-buffer)
10722 (goto-char pos)
10723 (message msg))))))
10724
10725 ;;;###autoload
10726 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10727 ;; FIXME: Should derive from js-mode.
10728 "Major mode for editing JavaScript code."
10729 ;; Used by comment-region; don't change it.
10730 (set (make-local-variable 'comment-start) "//")
10731 (set (make-local-variable 'comment-end) "")
10732 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10733 (set (make-local-variable 'max-lisp-eval-depth)
10734 (max max-lisp-eval-depth 3000))
10735 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10736 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10737 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10738 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10739 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10740 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10741 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10742 ;; for characters inside regexp literals.
10743 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10744 ;; this is necessary to make `show-paren-function' work properly
10745 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10746 ;; needed for M-x rgrep, among other things
10747 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10748
10749 (set (make-local-variable 'electric-indent-chars)
10750 (append "{}()[]:;,*." electric-indent-chars))
10751 (set (make-local-variable 'electric-layout-rules)
10752 '((?\; . after) (?\{ . after) (?\} . before)))
10753
10754 ;; some variables needed by cc-engine for paragraph-fill, etc.
10755 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10756 c-comment-start-regexp "/[*/]\\|\\s|"
10757 c-line-comment-starter "//"
10758 c-paragraph-start js2-paragraph-start
10759 c-paragraph-separate "$"
10760 c-syntactic-ws-start js2-syntactic-ws-start
10761 c-syntactic-ws-end js2-syntactic-ws-end
10762 c-syntactic-eol js2-syntactic-eol)
10763
10764 (let ((c-buffer-is-cc-mode t))
10765 ;; Copied from `js-mode'. Also see Bug#6071.
10766 (make-local-variable 'paragraph-start)
10767 (make-local-variable 'paragraph-separate)
10768 (make-local-variable 'paragraph-ignore-fill-prefix)
10769 (make-local-variable 'adaptive-fill-mode)
10770 (make-local-variable 'adaptive-fill-regexp)
10771 (c-setup-paragraph-variables))
10772
10773 (setq font-lock-defaults '(nil t))
10774
10775 ;; Experiment: make reparse-delay longer for longer files.
10776 (when (plusp js2-dynamic-idle-timer-adjust)
10777 (setq js2-idle-timer-delay
10778 (* js2-idle-timer-delay
10779 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10780
10781 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10782 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10783 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10784 (setq next-error-function #'js2-next-error)
10785 (imenu-add-to-menubar (concat "IM-" mode-name))
10786 (add-to-invisibility-spec '(js2-outline . t))
10787 (set (make-local-variable 'line-move-ignore-invisible) t)
10788 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10789
10790 (setq js2-mode-functions-hidden nil
10791 js2-mode-comments-hidden nil
10792 js2-mode-buffer-dirty-p t
10793 js2-mode-parsing nil)
10794
10795 (js2-set-default-externs)
10796
10797 (when js2-include-jslint-globals
10798 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10799
10800 (run-hooks 'js2-init-hook)
10801
10802 (js2-reparse))
10803
10804 (defun js2-mode-exit ()
10805 "Exit `js2-mode' and clean up."
10806 (interactive)
10807 (when js2-mode-node-overlay
10808 (delete-overlay js2-mode-node-overlay)
10809 (setq js2-mode-node-overlay nil))
10810 (js2-remove-overlays)
10811 (setq js2-mode-ast nil)
10812 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10813 (remove-from-invisibility-spec '(js2-outline . t))
10814 (js2-mode-show-all)
10815 (with-silent-modifications
10816 (js2-clear-face (point-min) (point-max))))
10817
10818 (defun js2-mode-reset-timer ()
10819 "Cancel any existing parse timer and schedule a new one."
10820 (if js2-mode-parse-timer
10821 (cancel-timer js2-mode-parse-timer))
10822 (setq js2-mode-parsing nil)
10823 (let ((timer (timer-create)))
10824 (setq js2-mode-parse-timer timer)
10825 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10826 (timer-set-idle-time timer js2-idle-timer-delay)
10827 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10828 (timer-activate-when-idle timer nil)))
10829
10830 (defun js2-mode-idle-reparse (buffer)
10831 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10832 it to be reparsed when the buffer is selected."
10833 (cond ((eq buffer (current-buffer))
10834 (js2-reparse))
10835 ((buffer-live-p buffer)
10836 ;; reparse when the buffer is selected again
10837 (with-current-buffer buffer
10838 (add-hook 'window-configuration-change-hook
10839 #'js2-mode-idle-reparse-inner
10840 nil t)))))
10841
10842 (defun js2-mode-idle-reparse-inner ()
10843 (remove-hook 'window-configuration-change-hook
10844 #'js2-mode-idle-reparse-inner
10845 t)
10846 (js2-reparse))
10847
10848 (defun js2-mode-edit (_beg _end _len)
10849 "Schedule a new parse after buffer is edited.
10850 Buffer edit spans from BEG to END and is of length LEN."
10851 (setq js2-mode-buffer-dirty-p t)
10852 (js2-mode-hide-overlay)
10853 (js2-mode-reset-timer))
10854
10855 (defun js2-minor-mode-edit (_beg _end _len)
10856 "Callback for buffer edits in `js2-mode'.
10857 Schedules a new parse after buffer is edited.
10858 Buffer edit spans from BEG to END and is of length LEN."
10859 (setq js2-mode-buffer-dirty-p t)
10860 (js2-mode-hide-overlay)
10861 (js2-mode-reset-timer))
10862
10863 (defun js2-reparse (&optional force)
10864 "Re-parse current buffer after user finishes some data entry.
10865 If we get any user input while parsing, including cursor motion,
10866 we discard the parse and reschedule it. If FORCE is nil, then the
10867 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10868 (let (time
10869 interrupted-p
10870 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10871 (unless js2-mode-parsing
10872 (setq js2-mode-parsing t)
10873 (unwind-protect
10874 (when (or js2-mode-buffer-dirty-p force)
10875 (js2-remove-overlays)
10876 (setq js2-mode-buffer-dirty-p nil
10877 js2-mode-fontifications nil
10878 js2-mode-deferred-properties nil)
10879 (if js2-mode-verbose-parse-p
10880 (message "parsing..."))
10881 (setq time
10882 (js2-time
10883 (setq interrupted-p
10884 (catch 'interrupted
10885 (js2-parse)
10886 (with-silent-modifications
10887 ;; if parsing is interrupted, comments and regex
10888 ;; literals stay ignored by `parse-partial-sexp'
10889 (remove-text-properties (point-min) (point-max)
10890 '(syntax-table))
10891 (js2-mode-apply-deferred-properties)
10892 (js2-mode-remove-suppressed-warnings)
10893 (js2-mode-show-warnings)
10894 (js2-mode-show-errors)
10895 (if (>= js2-highlight-level 1)
10896 (js2-highlight-jsdoc js2-mode-ast)))
10897 nil))))
10898 (if interrupted-p
10899 (progn
10900 ;; unfinished parse => try again
10901 (setq js2-mode-buffer-dirty-p t)
10902 (js2-mode-reset-timer))
10903 (if js2-mode-verbose-parse-p
10904 (message "Parse time: %s" time))))
10905 (setq js2-mode-parsing nil)
10906 (unless interrupted-p
10907 (setq js2-mode-parse-timer nil))))))
10908
10909 (defun js2-mode-show-node (event)
10910 "Debugging aid: highlight selected AST node on mouse click."
10911 (interactive "e")
10912 (mouse-set-point event)
10913 (setq deactivate-mark t)
10914 (when js2-mode-show-overlay
10915 (let ((node (js2-node-at-point))
10916 beg end)
10917 (if (null node)
10918 (message "No node found at location %s" (point))
10919 (setq beg (js2-node-abs-pos node)
10920 end (+ beg (js2-node-len node)))
10921 (if js2-mode-node-overlay
10922 (move-overlay js2-mode-node-overlay beg end)
10923 (setq js2-mode-node-overlay (make-overlay beg end))
10924 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10925 (with-silent-modifications
10926 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10927 (message "%s, parent: %s"
10928 (js2-node-short-name node)
10929 (if (js2-node-parent node)
10930 (js2-node-short-name (js2-node-parent node))
10931 "nil"))))))
10932
10933 (defun js2-mode-hide-overlay (&optional _p1 p2)
10934 "Remove the debugging overlay when the point moves.
10935 P1 and P2 are the old and new values of point, respectively."
10936 (when js2-mode-node-overlay
10937 (let ((beg (overlay-start js2-mode-node-overlay))
10938 (end (overlay-end js2-mode-node-overlay)))
10939 ;; Sometimes we're called spuriously.
10940 (unless (and p2
10941 (>= p2 beg)
10942 (<= p2 end))
10943 (with-silent-modifications
10944 (remove-text-properties beg end '(point-left nil)))
10945 (delete-overlay js2-mode-node-overlay)
10946 (setq js2-mode-node-overlay nil)))))
10947
10948 (defun js2-mode-reset ()
10949 "Debugging helper: reset everything."
10950 (interactive)
10951 (js2-mode-exit)
10952 (js2-mode))
10953
10954 (defun js2-mode-show-warn-or-err (e face)
10955 "Highlight a warning or error E with FACE.
10956 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10957 The last element is optional. When present, use instead of FACE."
10958 (let* ((key (first e))
10959 (beg (second e))
10960 (end (+ beg (third e)))
10961 ;; Don't inadvertently go out of bounds.
10962 (beg (max (point-min) (min beg (point-max))))
10963 (end (max (point-min) (min end (point-max))))
10964 (ovl (make-overlay beg end)))
10965 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10966 (overlay-put ovl 'js2-error t)
10967 (put-text-property beg end 'help-echo (js2-get-msg key))
10968 (put-text-property beg end 'point-entered #'js2-echo-error)))
10969
10970 (defun js2-remove-overlays ()
10971 "Remove overlays from buffer that have a `js2-error' property."
10972 (let ((beg (point-min))
10973 (end (point-max)))
10974 (save-excursion
10975 (dolist (o (overlays-in beg end))
10976 (when (overlay-get o 'js2-error)
10977 (delete-overlay o))))))
10978
10979 (defun js2-error-at-point (&optional pos)
10980 "Return non-nil if there's an error overlay at POS.
10981 Defaults to point."
10982 (loop with pos = (or pos (point))
10983 for o in (overlays-at pos)
10984 thereis (overlay-get o 'js2-error)))
10985
10986 (defun js2-mode-apply-deferred-properties ()
10987 "Apply fontifications and other text properties recorded during parsing."
10988 (when (plusp js2-highlight-level)
10989 ;; We defer clearing faces as long as possible to eliminate flashing.
10990 (js2-clear-face (point-min) (point-max))
10991 ;; Have to reverse the recorded fontifications list so that errors
10992 ;; and warnings overwrite the normal fontifications.
10993 (dolist (f (nreverse js2-mode-fontifications))
10994 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10995 (setq js2-mode-fontifications nil))
10996 (dolist (p js2-mode-deferred-properties)
10997 (apply #'put-text-property p))
10998 (setq js2-mode-deferred-properties nil))
10999
11000 (defun js2-mode-show-errors ()
11001 "Highlight syntax errors."
11002 (when js2-mode-show-parse-errors
11003 (dolist (e (js2-ast-root-errors js2-mode-ast))
11004 (js2-mode-show-warn-or-err e 'js2-error))))
11005
11006 (defun js2-mode-remove-suppressed-warnings ()
11007 "Take suppressed warnings out of the AST warnings list.
11008 This ensures that the counts and `next-error' are correct."
11009 (setf (js2-ast-root-warnings js2-mode-ast)
11010 (js2-delete-if
11011 (lambda (e)
11012 (let ((key (caar e)))
11013 (or
11014 (and (not js2-strict-trailing-comma-warning)
11015 (string-match "trailing\\.comma" key))
11016 (and (not js2-strict-cond-assign-warning)
11017 (string= key "msg.equal.as.assign"))
11018 (and js2-missing-semi-one-line-override
11019 (string= key "msg.missing.semi")
11020 (let* ((beg (second e))
11021 (node (js2-node-at-point beg))
11022 (fn (js2-mode-find-parent-fn node))
11023 (body (and fn (js2-function-node-body fn)))
11024 (lc (and body (js2-node-abs-pos body)))
11025 (rc (and lc (+ lc (js2-node-len body)))))
11026 (and fn
11027 (or (null body)
11028 (save-excursion
11029 (goto-char beg)
11030 (and (js2-same-line lc)
11031 (js2-same-line rc))))))))))
11032 (js2-ast-root-warnings js2-mode-ast))))
11033
11034 (defun js2-mode-show-warnings ()
11035 "Highlight strict-mode warnings."
11036 (when js2-mode-show-strict-warnings
11037 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11038 (js2-mode-show-warn-or-err e 'js2-warning))))
11039
11040 (defun js2-echo-error (_old-point new-point)
11041 "Called by point-motion hooks."
11042 (let ((msg (get-text-property new-point 'help-echo)))
11043 (when (and (stringp msg)
11044 (not (active-minibuffer-window))
11045 (not (current-message)))
11046 (message msg))))
11047
11048 (defalias 'js2-echo-help #'js2-echo-error)
11049
11050 (defun js2-line-break (&optional _soft)
11051 "Break line at point and indent, continuing comment if within one.
11052 If inside a string, and `js2-concat-multiline-strings' is not
11053 nil, turn it into concatenation."
11054 (interactive)
11055 (let ((parse-status (syntax-ppss)))
11056 (cond
11057 ;; Check if we're inside a string.
11058 ((nth 3 parse-status)
11059 (if js2-concat-multiline-strings
11060 (js2-mode-split-string parse-status)
11061 (insert "\n")))
11062 ;; Check if inside a block comment.
11063 ((nth 4 parse-status)
11064 (js2-mode-extend-comment (nth 8 parse-status)))
11065 (t
11066 (newline-and-indent)))))
11067
11068 (defun js2-mode-split-string (parse-status)
11069 "Turn a newline in mid-string into a string concatenation.
11070 PARSE-STATUS is as documented in `parse-partial-sexp'."
11071 (let* ((quote-char (nth 3 parse-status))
11072 (at-eol (eq js2-concat-multiline-strings 'eol)))
11073 (insert quote-char)
11074 (insert (if at-eol " +\n" "\n"))
11075 (unless at-eol
11076 (insert "+ "))
11077 (js2-indent-line)
11078 (insert quote-char)
11079 (when (eolp)
11080 (insert quote-char)
11081 (backward-char 1))))
11082
11083 (defun js2-mode-extend-comment (start-pos)
11084 "Indent the line and, when inside a comment block, add comment prefix."
11085 (let (star single col first-line needs-close)
11086 (save-excursion
11087 (back-to-indentation)
11088 (when (< (point) start-pos)
11089 (goto-char start-pos))
11090 (cond
11091 ((looking-at "\\*[^/]")
11092 (setq star t
11093 col (current-column)))
11094 ((looking-at "/\\*")
11095 (setq star t
11096 first-line t
11097 col (1+ (current-column))))
11098 ((looking-at "//")
11099 (setq single t
11100 col (current-column)))))
11101 ;; Heuristic for whether we need to close the comment:
11102 ;; if we've got a parse error here, assume it's an unterminated
11103 ;; comment.
11104 (setq needs-close
11105 (or
11106 (eq (get-text-property (1- (point)) 'point-entered)
11107 'js2-echo-error)
11108 ;; The heuristic above doesn't work well when we're
11109 ;; creating a comment and there's another one downstream,
11110 ;; as our parser thinks this one ends at the end of the
11111 ;; next one. (You can have a /* inside a js block comment.)
11112 ;; So just close it if the next non-ws char isn't a *.
11113 (and first-line
11114 (eolp)
11115 (save-excursion
11116 (skip-chars-forward " \t\r\n")
11117 (not (eq (char-after) ?*))))))
11118 (delete-horizontal-space)
11119 (insert "\n")
11120 (cond
11121 (star
11122 (indent-to col)
11123 (insert "* ")
11124 (if (and first-line needs-close)
11125 (save-excursion
11126 (insert "\n")
11127 (indent-to col)
11128 (insert "*/"))))
11129 ((and single
11130 (save-excursion
11131 (and (zerop (forward-line 1))
11132 (looking-at "\\s-*//"))))
11133 (indent-to col)
11134 (insert "// ")))
11135 ;; Don't need to extend the comment after all.
11136 (js2-indent-line)))
11137
11138 (defun js2-beginning-of-line ()
11139 "Toggle point between bol and first non-whitespace char in line.
11140 Also moves past comment delimiters when inside comments."
11141 (interactive)
11142 (let (node)
11143 (cond
11144 ((bolp)
11145 (back-to-indentation))
11146 ((looking-at "//")
11147 (skip-chars-forward "/ \t"))
11148 ((and (eq (char-after) ?*)
11149 (setq node (js2-comment-at-point))
11150 (memq (js2-comment-node-format node) '(jsdoc block))
11151 (save-excursion
11152 (skip-chars-backward " \t")
11153 (bolp)))
11154 (skip-chars-forward "\* \t"))
11155 (t
11156 (goto-char (point-at-bol))))))
11157
11158 (defun js2-end-of-line ()
11159 "Toggle point between eol and last non-whitespace char in line."
11160 (interactive)
11161 (if (eolp)
11162 (skip-chars-backward " \t")
11163 (goto-char (point-at-eol))))
11164
11165 (defun js2-mode-wait-for-parse (callback)
11166 "Invoke CALLBACK when parsing is finished.
11167 If parsing is already finished, calls CALLBACK immediately."
11168 (if (not js2-mode-buffer-dirty-p)
11169 (funcall callback)
11170 (push callback js2-mode-pending-parse-callbacks)
11171 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11172
11173 (defun js2-mode-parse-finished ()
11174 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11175 ;; We can't let errors propagate up, since it prevents the
11176 ;; `js2-parse' method from completing normally and returning
11177 ;; the ast, which makes things mysteriously not work right.
11178 (unwind-protect
11179 (dolist (cb js2-mode-pending-parse-callbacks)
11180 (condition-case err
11181 (funcall cb)
11182 (error (message "%s" err))))
11183 (setq js2-mode-pending-parse-callbacks nil)))
11184
11185 (defun js2-mode-flag-region (from to flag)
11186 "Hide or show text from FROM to TO, according to FLAG.
11187 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11188 Returns the created overlay if FLAG is non-nil."
11189 (remove-overlays from to 'invisible 'js2-outline)
11190 (when flag
11191 (let ((o (make-overlay from to)))
11192 (overlay-put o 'invisible 'js2-outline)
11193 (overlay-put o 'isearch-open-invisible
11194 'js2-isearch-open-invisible)
11195 o)))
11196
11197 ;; Function to be set as an outline-isearch-open-invisible' property
11198 ;; to the overlay that makes the outline invisible (see
11199 ;; `js2-mode-flag-region').
11200 (defun js2-isearch-open-invisible (_overlay)
11201 ;; We rely on the fact that isearch places point on the matched text.
11202 (js2-mode-show-element))
11203
11204 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11205 "Return cons cell of bounds of folding overlay at POS.
11206 Returns nil if not found."
11207 (let ((overlays (overlays-at (or pos (point))))
11208 o)
11209 (while (and overlays
11210 (not o))
11211 (if (overlay-get (car overlays) 'invisible)
11212 (setq o (car overlays))
11213 (setq overlays (cdr overlays))))
11214 (if o
11215 (cons (overlay-start o) (overlay-end o)))))
11216
11217 (defun js2-mode-function-at-point (&optional pos)
11218 "Return the innermost function node enclosing current point.
11219 Returns nil if point is not in a function."
11220 (let ((node (js2-node-at-point pos)))
11221 (while (and node (not (js2-function-node-p node)))
11222 (setq node (js2-node-parent node)))
11223 (if (js2-function-node-p node)
11224 node)))
11225
11226 (defun js2-mode-toggle-element ()
11227 "Hide or show the foldable element at the point."
11228 (interactive)
11229 (let (comment fn pos)
11230 (save-excursion
11231 (cond
11232 ;; /* ... */ comment?
11233 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11234 (if (js2-mode-invisible-overlay-bounds
11235 (setq pos (+ 3 (js2-node-abs-pos comment))))
11236 (progn
11237 (goto-char pos)
11238 (js2-mode-show-element))
11239 (js2-mode-hide-element)))
11240 ;; //-comment?
11241 ((save-excursion
11242 (back-to-indentation)
11243 (looking-at js2-mode-//-comment-re))
11244 (js2-mode-toggle-//-comment))
11245 ;; function?
11246 ((setq fn (js2-mode-function-at-point))
11247 (setq pos (and (js2-function-node-body fn)
11248 (js2-node-abs-pos (js2-function-node-body fn))))
11249 (goto-char (1+ pos))
11250 (if (js2-mode-invisible-overlay-bounds)
11251 (js2-mode-show-element)
11252 (js2-mode-hide-element)))
11253 (t
11254 (message "Nothing at point to hide or show"))))))
11255
11256 (defun js2-mode-hide-element ()
11257 "Fold/hide contents of a block, showing ellipses.
11258 Show the hidden text with \\[js2-mode-show-element]."
11259 (interactive)
11260 (if js2-mode-buffer-dirty-p
11261 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11262 (let (node body beg end)
11263 (cond
11264 ((js2-mode-invisible-overlay-bounds)
11265 (message "already hidden"))
11266 (t
11267 (setq node (js2-node-at-point))
11268 (cond
11269 ((js2-block-comment-p node)
11270 (js2-mode-hide-comment node))
11271 (t
11272 (while (and node (not (js2-function-node-p node)))
11273 (setq node (js2-node-parent node)))
11274 (if (and node
11275 (setq body (js2-function-node-body node)))
11276 (progn
11277 (setq beg (js2-node-abs-pos body)
11278 end (+ beg (js2-node-len body)))
11279 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11280 (message "No collapsable element found at point"))))))))
11281
11282 (defun js2-mode-show-element ()
11283 "Show the hidden element at current point."
11284 (interactive)
11285 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11286 (if bounds
11287 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11288 (message "Nothing to un-hide"))))
11289
11290 (defun js2-mode-show-all ()
11291 "Show all of the text in the buffer."
11292 (interactive)
11293 (js2-mode-flag-region (point-min) (point-max) nil))
11294
11295 (defun js2-mode-toggle-hide-functions ()
11296 (interactive)
11297 (if js2-mode-functions-hidden
11298 (js2-mode-show-functions)
11299 (js2-mode-hide-functions)))
11300
11301 (defun js2-mode-hide-functions ()
11302 "Hides all non-nested function bodies in the buffer.
11303 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11304 to open an individual entry."
11305 (interactive)
11306 (if js2-mode-buffer-dirty-p
11307 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11308 (if (null js2-mode-ast)
11309 (message "Oops - parsing failed")
11310 (setq js2-mode-functions-hidden t)
11311 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11312
11313 (defun js2-mode-function-hider (n endp)
11314 (when (not endp)
11315 (let ((tt (js2-node-type n))
11316 body beg end)
11317 (cond
11318 ((and (= tt js2-FUNCTION)
11319 (setq body (js2-function-node-body n)))
11320 (setq beg (js2-node-abs-pos body)
11321 end (+ beg (js2-node-len body)))
11322 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11323 nil) ; don't process children of function
11324 (t
11325 t))))) ; keep processing other AST nodes
11326
11327 (defun js2-mode-show-functions ()
11328 "Un-hide any folded function bodies in the buffer."
11329 (interactive)
11330 (setq js2-mode-functions-hidden nil)
11331 (save-excursion
11332 (goto-char (point-min))
11333 (while (/= (goto-char (next-overlay-change (point)))
11334 (point-max))
11335 (dolist (o (overlays-at (point)))
11336 (when (and (overlay-get o 'invisible)
11337 (not (overlay-get o 'comment)))
11338 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11339
11340 (defun js2-mode-hide-comment (n)
11341 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11342 3 ; /**
11343 2)) ; /*
11344 (beg (+ (js2-node-abs-pos n) head))
11345 (end (- (+ beg (js2-node-len n)) head 2))
11346 (o (js2-mode-flag-region beg end 'hide)))
11347 (overlay-put o 'comment t)))
11348
11349 (defun js2-mode-toggle-hide-comments ()
11350 "Folds all block comments in the buffer.
11351 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11352 to open an individual entry."
11353 (interactive)
11354 (if js2-mode-comments-hidden
11355 (js2-mode-show-comments)
11356 (js2-mode-hide-comments)))
11357
11358 (defun js2-mode-hide-comments ()
11359 (interactive)
11360 (if js2-mode-buffer-dirty-p
11361 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11362 (if (null js2-mode-ast)
11363 (message "Oops - parsing failed")
11364 (setq js2-mode-comments-hidden t)
11365 (dolist (n (js2-ast-root-comments js2-mode-ast))
11366 (when (js2-block-comment-p n)
11367 (js2-mode-hide-comment n)))
11368 (js2-mode-hide-//-comments)))
11369
11370 (defun js2-mode-extend-//-comment (direction)
11371 "Find start or end of a block of similar //-comment lines.
11372 DIRECTION is -1 to look back, 1 to look forward.
11373 INDENT is the indentation level to match.
11374 Returns the end-of-line position of the furthest adjacent
11375 //-comment line with the same indentation as the current line.
11376 If there is no such matching line, returns current end of line."
11377 (let ((pos (point-at-eol))
11378 (indent (current-indentation)))
11379 (save-excursion
11380 (while (and (zerop (forward-line direction))
11381 (looking-at js2-mode-//-comment-re)
11382 (eq indent (length (match-string 1))))
11383 (setq pos (point-at-eol)))
11384 pos)))
11385
11386 (defun js2-mode-hide-//-comments ()
11387 "Fold adjacent 1-line comments, showing only snippet of first one."
11388 (let (beg end)
11389 (save-excursion
11390 (goto-char (point-min))
11391 (while (re-search-forward js2-mode-//-comment-re nil t)
11392 (setq beg (point)
11393 end (js2-mode-extend-//-comment 1))
11394 (unless (eq beg end)
11395 (overlay-put (js2-mode-flag-region beg end 'hide)
11396 'comment t))
11397 (goto-char end)
11398 (forward-char 1)))))
11399
11400 (defun js2-mode-toggle-//-comment ()
11401 "Fold or un-fold any multi-line //-comment at point.
11402 Caller should have determined that this line starts with a //-comment."
11403 (let* ((beg (point-at-eol))
11404 (end beg))
11405 (save-excursion
11406 (goto-char end)
11407 (if (js2-mode-invisible-overlay-bounds)
11408 (js2-mode-show-element)
11409 ;; else hide the comment
11410 (setq beg (js2-mode-extend-//-comment -1)
11411 end (js2-mode-extend-//-comment 1))
11412 (unless (eq beg end)
11413 (overlay-put (js2-mode-flag-region beg end 'hide)
11414 'comment t))))))
11415
11416 (defun js2-mode-show-comments ()
11417 "Un-hide any hidden comments, leaving other hidden elements alone."
11418 (interactive)
11419 (setq js2-mode-comments-hidden nil)
11420 (save-excursion
11421 (goto-char (point-min))
11422 (while (/= (goto-char (next-overlay-change (point)))
11423 (point-max))
11424 (dolist (o (overlays-at (point)))
11425 (when (overlay-get o 'comment)
11426 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11427
11428 (defun js2-mode-display-warnings-and-errors ()
11429 "Turn on display of warnings and errors."
11430 (interactive)
11431 (setq js2-mode-show-parse-errors t
11432 js2-mode-show-strict-warnings t)
11433 (js2-reparse 'force))
11434
11435 (defun js2-mode-hide-warnings-and-errors ()
11436 "Turn off display of warnings and errors."
11437 (interactive)
11438 (setq js2-mode-show-parse-errors nil
11439 js2-mode-show-strict-warnings nil)
11440 (js2-reparse 'force))
11441
11442 (defun js2-mode-toggle-warnings-and-errors ()
11443 "Toggle the display of warnings and errors.
11444 Some users don't like having warnings/errors reported while they type."
11445 (interactive)
11446 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11447 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11448 (if (called-interactively-p 'any)
11449 (message "warnings and errors %s"
11450 (if js2-mode-show-parse-errors
11451 "enabled"
11452 "disabled")))
11453 (js2-reparse 'force))
11454
11455 (defun js2-mode-customize ()
11456 (interactive)
11457 (customize-group 'js2-mode))
11458
11459 (defun js2-mode-forward-sexp (&optional arg)
11460 "Move forward across one statement or balanced expression.
11461 With ARG, do it that many times. Negative arg -N means
11462 move backward across N balanced expressions."
11463 (interactive "p")
11464 (setq arg (or arg 1))
11465 (save-restriction
11466 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11467 (js2-reparse)
11468 (let (forward-sexp-function
11469 node (start (point)) pos lp rp child)
11470 (cond
11471 ;; backward-sexp
11472 ;; could probably make this better for some cases:
11473 ;; - if in statement block (e.g. function body), go to parent
11474 ;; - infix exprs like (foo in bar) - maybe go to beginning
11475 ;; of infix expr if in the right-side expression?
11476 ((and arg (minusp arg))
11477 (dotimes (_ (- arg))
11478 (js2-backward-sws)
11479 (forward-char -1) ; Enter the node we backed up to.
11480 (when (setq node (js2-node-at-point (point) t))
11481 (setq pos (js2-node-abs-pos node))
11482 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11483 (setq lp (car parens)
11484 rp (cdr parens)))
11485 (when (and lp (> start lp))
11486 (if (and rp (<= start rp))
11487 ;; Between parens, check if there's a child node we can jump.
11488 (when (setq child (js2-node-closest-child node (point) lp t))
11489 (setq pos (js2-node-abs-pos child)))
11490 ;; Before both parens.
11491 (setq pos lp)))
11492 (let ((state (parse-partial-sexp start pos)))
11493 (goto-char (if (not (zerop (car state)))
11494 ;; Stumble at the unbalanced paren if < 0, or
11495 ;; jump a bit further if > 0.
11496 (scan-sexps start -1)
11497 pos))))
11498 (unless pos (goto-char (point-min)))))
11499 (t
11500 ;; forward-sexp
11501 (dotimes (_ arg)
11502 (js2-forward-sws)
11503 (when (setq node (js2-node-at-point (point) t))
11504 (setq pos (js2-node-abs-pos node))
11505 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11506 (setq lp (car parens)
11507 rp (cdr parens)))
11508 (or
11509 (when (and rp (<= start rp))
11510 (if (> start lp)
11511 (when (setq child (js2-node-closest-child node (point) rp))
11512 (setq pos (js2-node-abs-end child)))
11513 (setq pos (1+ rp))))
11514 ;; No parens or child nodes, looks for the end of the curren node.
11515 (incf pos (js2-node-len
11516 (if (js2-expr-stmt-node-p (js2-node-parent node))
11517 ;; Stop after the semicolon.
11518 (js2-node-parent node)
11519 node))))
11520 (let ((state (save-excursion (parse-partial-sexp start pos))))
11521 (goto-char (if (not (zerop (car state)))
11522 (scan-sexps start 1)
11523 pos))))
11524 (unless pos (goto-char (point-max)))))))))
11525
11526 (defun js2-mode-forward-sexp-parens (node abs-pos)
11527 "Return a cons cell with positions of main parens in NODE."
11528 (cond
11529 ((or (js2-array-node-p node)
11530 (js2-object-node-p node)
11531 (js2-comp-node-p node)
11532 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11533 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11534 ((js2-paren-expr-node-p node)
11535 (let ((lp (js2-node-lp node))
11536 (rp (js2-node-rp node)))
11537 (cons (when lp (+ abs-pos lp))
11538 (when rp (+ abs-pos rp)))))))
11539
11540 (defun js2-node-closest-child (parent point limit &optional before)
11541 (let* ((parent-pos (js2-node-abs-pos parent))
11542 (rpoint (- point parent-pos))
11543 (rlimit (- limit parent-pos))
11544 (min (min rpoint rlimit))
11545 (max (max rpoint rlimit))
11546 found)
11547 (catch 'done
11548 (js2-visit-ast
11549 parent
11550 (lambda (node _end-p)
11551 (if (eq node parent)
11552 t
11553 (let ((pos (js2-node-pos node)) ;; Both relative values.
11554 (end (+ (js2-node-pos node) (js2-node-len node))))
11555 (when (and (>= pos min) (<= end max)
11556 (if before (< pos rpoint) (> end rpoint)))
11557 (setq found node))
11558 (when (> end rpoint)
11559 (throw 'done nil)))
11560 nil))))
11561 found))
11562
11563 (defun js2-errors ()
11564 "Return a list of errors found."
11565 (and js2-mode-ast
11566 (js2-ast-root-errors js2-mode-ast)))
11567
11568 (defun js2-warnings ()
11569 "Return a list of warnings found."
11570 (and js2-mode-ast
11571 (js2-ast-root-warnings js2-mode-ast)))
11572
11573 (defun js2-have-errors-p ()
11574 "Return non-nil if any parse errors or warnings were found."
11575 (or (js2-errors) (js2-warnings)))
11576
11577 (defun js2-errors-and-warnings ()
11578 "Return a copy of the concatenated errors and warnings lists.
11579 They are appended: first the errors, then the warnings.
11580 Entries are of the form (MSG BEG END)."
11581 (when js2-mode-ast
11582 (append (js2-ast-root-errors js2-mode-ast)
11583 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11584
11585 (defun js2-next-error (&optional arg reset)
11586 "Move to next parse error.
11587 Typically invoked via \\[next-error].
11588 ARG is the number of errors, forward or backward, to move.
11589 RESET means start over from the beginning."
11590 (interactive "p")
11591 (if (not (or (js2-errors) (js2-warnings)))
11592 (message "No errors")
11593 (when reset
11594 (goto-char (point-min)))
11595 (let* ((errs (js2-errors-and-warnings))
11596 (continue t)
11597 (start (point))
11598 (count (or arg 1))
11599 (backward (minusp count))
11600 (sorter (if backward '> '<))
11601 (stopper (if backward '< '>))
11602 (count (abs count))
11603 all-errs err)
11604 ;; Sort by start position.
11605 (setq errs (sort errs (lambda (e1 e2)
11606 (funcall sorter (second e1) (second e2))))
11607 all-errs errs)
11608 ;; Find nth error with pos > start.
11609 (while (and errs continue)
11610 (when (funcall stopper (cadar errs) start)
11611 (setq err (car errs))
11612 (if (zerop (decf count))
11613 (setq continue nil)))
11614 (setq errs (cdr errs)))
11615 ;; Clear for `js2-echo-error'.
11616 (message nil)
11617 (if err
11618 (goto-char (second err))
11619 ;; Wrap around to first error.
11620 (goto-char (second (car all-errs)))
11621 ;; If we were already on it, echo msg again.
11622 (if (= (point) start)
11623 (js2-echo-error (point) (point)))))))
11624
11625 (defun js2-down-mouse-3 ()
11626 "Make right-click move the point to the click location.
11627 This makes right-click context menu operations a bit more intuitive.
11628 The point will not move if the region is active, however, to avoid
11629 destroying the region selection."
11630 (interactive)
11631 (when (and js2-move-point-on-right-click
11632 (not mark-active))
11633 (let ((e last-input-event))
11634 (ignore-errors
11635 (goto-char (cadadr e))))))
11636
11637 (defun js2-mode-create-imenu-index ()
11638 "Return an alist for `imenu--index-alist'."
11639 ;; This is built up in `js2-parse-record-imenu' during parsing.
11640 (when js2-mode-ast
11641 ;; if we have an ast but no recorder, they're requesting a rescan
11642 (unless js2-imenu-recorder
11643 (js2-reparse 'force))
11644 (prog1
11645 (js2-build-imenu-index)
11646 (setq js2-imenu-recorder nil
11647 js2-imenu-function-map nil))))
11648
11649 (defun js2-mode-find-tag ()
11650 "Replacement for `find-tag-default'.
11651 `find-tag-default' returns a ridiculous answer inside comments."
11652 (let (beg end)
11653 (js2-with-underscore-as-word-syntax
11654 (save-excursion
11655 (if (and (not (looking-at "[[:alnum:]_$]"))
11656 (looking-back "[[:alnum:]_$]"))
11657 (setq beg (progn (forward-word -1) (point))
11658 end (progn (forward-word 1) (point)))
11659 (setq beg (progn (forward-word 1) (point))
11660 end (progn (forward-word -1) (point))))
11661 (replace-regexp-in-string
11662 "[\"']" ""
11663 (buffer-substring-no-properties beg end))))))
11664
11665 (defun js2-mode-forward-sibling ()
11666 "Move to the end of the sibling following point in parent.
11667 Returns non-nil if successful, or nil if there was no following sibling."
11668 (let* ((node (js2-node-at-point))
11669 (parent (js2-mode-find-enclosing-fn node))
11670 sib)
11671 (when (setq sib (js2-node-find-child-after (point) parent))
11672 (goto-char (+ (js2-node-abs-pos sib)
11673 (js2-node-len sib))))))
11674
11675 (defun js2-mode-backward-sibling ()
11676 "Move to the beginning of the sibling node preceding point in parent.
11677 Parent is defined as the enclosing script or function."
11678 (let* ((node (js2-node-at-point))
11679 (parent (js2-mode-find-enclosing-fn node))
11680 sib)
11681 (when (setq sib (js2-node-find-child-before (point) parent))
11682 (goto-char (js2-node-abs-pos sib)))))
11683
11684 (defun js2-beginning-of-defun (&optional arg)
11685 "Go to line on which current function starts, and return t on success.
11686 If we're not in a function or already at the beginning of one, go
11687 to beginning of previous script-level element.
11688 With ARG N, do that N times. If N is negative, move forward."
11689 (setq arg (or arg 1))
11690 (if (plusp arg)
11691 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11692 (when (cond
11693 ((js2-function-node-p parent)
11694 (goto-char (js2-node-abs-pos parent)))
11695 (t
11696 (js2-mode-backward-sibling)))
11697 (if (> arg 1)
11698 (js2-beginning-of-defun (1- arg))
11699 t)))
11700 (when (js2-end-of-defun)
11701 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11702
11703 (defun js2-end-of-defun ()
11704 "Go to the char after the last position of the current function
11705 or script-level element."
11706 (let* ((node (js2-node-at-point))
11707 (parent (or (and (js2-function-node-p node) node)
11708 (js2-node-parent-script-or-fn node)))
11709 script)
11710 (unless (js2-function-node-p parent)
11711 ;; Use current script-level node, or, if none, the next one.
11712 (setq script (or parent node)
11713 parent (js2-node-find-child-before (point) script))
11714 (when (or (null parent)
11715 (>= (point) (+ (js2-node-abs-pos parent)
11716 (js2-node-len parent))))
11717 (setq parent (js2-node-find-child-after (point) script))))
11718 (when parent
11719 (goto-char (+ (js2-node-abs-pos parent)
11720 (js2-node-len parent))))))
11721
11722 (defun js2-mark-defun (&optional allow-extend)
11723 "Put mark at end of this function, point at beginning.
11724 The function marked is the one that contains point.
11725
11726 Interactively, if this command is repeated,
11727 or (in Transient Mark mode) if the mark is active,
11728 it marks the next defun after the ones already marked."
11729 (interactive "p")
11730 (let (extended)
11731 (when (and allow-extend
11732 (or (and (eq last-command this-command) (mark t))
11733 (and transient-mark-mode mark-active)))
11734 (let ((sib (save-excursion
11735 (goto-char (mark))
11736 (if (js2-mode-forward-sibling)
11737 (point)))))
11738 (if sib
11739 (progn
11740 (set-mark sib)
11741 (setq extended t))
11742 ;; no more siblings - try extending to enclosing node
11743 (goto-char (mark t)))))
11744 (when (not extended)
11745 (let ((node (js2-node-at-point (point) t)) ; skip comments
11746 ast fn stmt parent beg end)
11747 (when (js2-ast-root-p node)
11748 (setq ast node
11749 node (or (js2-node-find-child-after (point) node)
11750 (js2-node-find-child-before (point) node))))
11751 ;; only mark whole buffer if we can't find any children
11752 (if (null node)
11753 (setq node ast))
11754 (if (js2-function-node-p node)
11755 (setq parent node)
11756 (setq fn (js2-mode-find-enclosing-fn node)
11757 stmt (if (or (null fn)
11758 (js2-ast-root-p fn))
11759 (js2-mode-find-first-stmt node))
11760 parent (or stmt fn)))
11761 (setq beg (js2-node-abs-pos parent)
11762 end (+ beg (js2-node-len parent)))
11763 (push-mark beg)
11764 (goto-char end)
11765 (exchange-point-and-mark)))))
11766
11767 (defun js2-narrow-to-defun ()
11768 "Narrow to the function enclosing point."
11769 (interactive)
11770 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11771 (fn (if (js2-script-node-p node)
11772 node
11773 (js2-mode-find-enclosing-fn node)))
11774 (beg (js2-node-abs-pos fn)))
11775 (unless (js2-ast-root-p fn)
11776 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11777
11778 (provide 'js2-mode)
11779
11780 ;;; js2-mode.el ends here