]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Parse tagged templates
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2014 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20141118
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 (defvar js2-harmony-externs
207 (mapcar 'symbol-name
208 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
209 "ES6 externs. If `js2-include-browser-externs' is enabled and
210 `js2-language-version' is sufficiently high, these will be included.")
211
212 ;;; Variables
213
214 (defun js2-mark-safe-local (name pred)
215 "Make the variable NAME buffer-local and mark it as safe file-local
216 variable with predicate PRED."
217 (make-variable-buffer-local name)
218 (put name 'safe-local-variable pred))
219
220 (defcustom js2-highlight-level 2
221 "Amount of syntax highlighting to perform.
222 0 or a negative value means none.
223 1 adds basic syntax highlighting.
224 2 adds highlighting of some Ecma built-in properties.
225 3 adds highlighting of many Ecma built-in functions."
226 :group 'js2-mode
227 :type '(choice (const :tag "None" 0)
228 (const :tag "Basic" 1)
229 (const :tag "Include Properties" 2)
230 (const :tag "Include Functions" 3)))
231
232 (defvar js2-mode-dev-mode-p nil
233 "Non-nil if running in development mode. Normally nil.")
234
235 (defgroup js2-mode nil
236 "An improved JavaScript mode."
237 :group 'languages)
238
239 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
240 (numberp c-basic-offset))
241 c-basic-offset
242 4)
243 "Number of spaces to indent nested statements.
244 Similar to `c-basic-offset'."
245 :group 'js2-mode
246 :type 'integer)
247 (js2-mark-safe-local 'js2-basic-offset 'integerp)
248
249 (defcustom js2-bounce-indent-p nil
250 "Non-nil to have indent-line function choose among alternatives.
251 If nil, the indent-line function will indent to a predetermined column
252 based on heuristic guessing. If non-nil, then if the current line is
253 already indented to that predetermined column, indenting will choose
254 another likely column and indent to that spot. Repeated invocation of
255 the indent-line function will cycle among the computed alternatives.
256 See the function `js2-bounce-indent' for details. When it is non-nil,
257 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
258 :type 'boolean
259 :group 'js2-mode)
260
261 (defcustom js2-pretty-multiline-declarations t
262 "Non-nil to line up multiline declarations vertically:
263
264 var a = 10,
265 b = 20,
266 c = 30;
267
268 If the value is not `all', and the first assigned value in
269 declaration is a function/array/object literal spanning several
270 lines, it won't be indented additionally:
271
272 var o = { var bar = 2,
273 foo: 3 vs. o = {
274 }, foo: 3
275 bar = 2; };"
276 :group 'js2-mode
277 :type 'symbol)
278 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
279
280 (defcustom js2-indent-switch-body nil
281 "When nil, case labels are indented on the same level as the
282 containing switch statement. Otherwise, all lines inside
283 switch statement body are indented one additional level."
284 :type 'boolean
285 :group 'js2-mode)
286 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
287
288 (defcustom js2-idle-timer-delay 0.2
289 "Delay in secs before re-parsing after user makes changes.
290 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
291 :type 'number
292 :group 'js2-mode)
293 (make-variable-buffer-local 'js2-idle-timer-delay)
294
295 (defcustom js2-dynamic-idle-timer-adjust 0
296 "Positive to adjust `js2-idle-timer-delay' based on file size.
297 The idea is that for short files, parsing is faster so we can be
298 more responsive to user edits without interfering with editing.
299 The buffer length in characters (typically bytes) is divided by
300 this value and used to multiply `js2-idle-timer-delay' for the
301 buffer. For example, a 21k file and 10k adjust yields 21k/10k
302 == 2, so js2-idle-timer-delay is multiplied by 2.
303 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
304 `js2-idle-timer-delay' is not dependent on the file size."
305 :type 'number
306 :group 'js2-mode)
307
308 (defcustom js2-concat-multiline-strings t
309 "When non-nil, `js2-line-break' in mid-string will make it a
310 string concatenation. When `eol', the '+' will be inserted at the
311 end of the line, otherwise, at the beginning of the next line."
312 :type '(choice (const t) (const eol) (const nil))
313 :group 'js2-mode)
314
315 (defcustom js2-mode-show-parse-errors t
316 "True to highlight parse errors."
317 :type 'boolean
318 :group 'js2-mode)
319
320 (defcustom js2-mode-show-strict-warnings t
321 "Non-nil to emit Ecma strict-mode warnings.
322 Some of the warnings can be individually disabled by other flags,
323 even if this flag is non-nil."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-trailing-comma-warning t
328 "Non-nil to warn about trailing commas in array literals.
329 Ecma-262-5.1 allows them, but older versions of IE raise an error."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-var-redeclaration-warning t
366 "Non-nil to warn about redeclaring variables in a script or function."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-strict-var-hides-function-arg-warning t
371 "Non-nil to warn about a var decl hiding a function argument."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-skip-preprocessor-directives nil
376 "Non-nil to treat lines beginning with # as comments.
377 Useful for viewing Mozilla JavaScript source code."
378 :type 'boolean
379 :group 'js2-mode)
380
381 (defcustom js2-language-version 200
382 "Configures what JavaScript language version to recognize.
383 Currently versions 150, 160, 170, 180 and 200 are supported,
384 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
385 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
386 yield, and Array comprehensions, and 1.8 adds function closures."
387 :type 'integer
388 :group 'js2-mode)
389
390 (defcustom js2-allow-keywords-as-property-names t
391 "If non-nil, you can use JavaScript keywords as object property names.
392 Examples:
393
394 var foo = {int: 5, while: 6, continue: 7};
395 foo.return = 8;
396
397 Ecma-262 5.1 allows this syntax, but some engines still don't."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-instanceof-has-side-effects nil
402 "If non-nil, treats the instanceof operator as having side effects.
403 This is useful for xulrunner apps."
404 :type 'boolean
405 :group 'js2-mode)
406
407 (defcustom js2-move-point-on-right-click t
408 "Non-nil to move insertion point when you right-click.
409 This makes right-click context menu behavior a bit more intuitive,
410 since menu operations generally apply to the point. The exception
411 is if there is a region selection, in which case the point does -not-
412 move, so cut/copy/paste can work properly.
413
414 Note that IntelliJ moves the point, and Eclipse leaves it alone,
415 so this behavior is customizable."
416 :group 'js2-mode
417 :type 'boolean)
418
419 (defcustom js2-allow-rhino-new-expr-initializer t
420 "Non-nil to support a Rhino's experimental syntactic construct.
421
422 Rhino supports the ability to follow a `new' expression with an object
423 literal, which is used to set additional properties on the new object
424 after calling its constructor. Syntax:
425
426 new <expr> [ ( arglist ) ] [initializer]
427
428 Hence, this expression:
429
430 new Object {a: 1, b: 2}
431
432 results in an Object with properties a=1 and b=2. This syntax is
433 apparently not configurable in Rhino - it's currently always enabled,
434 as of Rhino version 1.7R2."
435 :type 'boolean
436 :group 'js2-mode)
437
438 (defcustom js2-allow-member-expr-as-function-name nil
439 "Non-nil to support experimental Rhino syntax for function names.
440
441 Rhino supports an experimental syntax configured via the Rhino Context
442 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
443
444 function <member-expr> ( [ arg-list ] ) { <body> }
445
446 Where member-expr is a non-parenthesized 'member expression', which
447 is anything at the grammar level of a new-expression or lower, meaning
448 any expression that does not involve infix or unary operators.
449
450 When <member-expr> is not a simple identifier, then it is syntactic
451 sugar for assigning the anonymous function to the <member-expr>. Hence,
452 this code:
453
454 function a.b().c[2] (x, y) { ... }
455
456 is rewritten as:
457
458 a.b().c[2] = function(x, y) {...}
459
460 which doesn't seem particularly useful, but Rhino permits it."
461 :type 'boolean
462 :group 'js2-mode)
463
464 ;; scanner variables
465
466 (defmacro js2-deflocal (name value &optional comment)
467 "Define a buffer-local variable NAME with VALUE and COMMENT."
468 `(progn
469 (defvar ,name ,value ,comment)
470 (make-variable-buffer-local ',name)))
471
472 (defvar js2-EOF_CHAR -1
473 "Represents end of stream. Distinct from js2-EOF token type.")
474
475 ;; I originally used symbols to represent tokens, but Rhino uses
476 ;; ints and then sets various flag bits in them, so ints it is.
477 ;; The upshot is that we need a `js2-' prefix in front of each name.
478 (defvar js2-ERROR -1)
479 (defvar js2-EOF 0)
480 (defvar js2-EOL 1)
481 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
482 (defvar js2-LEAVEWITH 3)
483 (defvar js2-RETURN 4)
484 (defvar js2-GOTO 5)
485 (defvar js2-IFEQ 6)
486 (defvar js2-IFNE 7)
487 (defvar js2-SETNAME 8)
488 (defvar js2-BITOR 9)
489 (defvar js2-BITXOR 10)
490 (defvar js2-BITAND 11)
491 (defvar js2-EQ 12)
492 (defvar js2-NE 13)
493 (defvar js2-LT 14)
494 (defvar js2-LE 15)
495 (defvar js2-GT 16)
496 (defvar js2-GE 17)
497 (defvar js2-LSH 18)
498 (defvar js2-RSH 19)
499 (defvar js2-URSH 20)
500 (defvar js2-ADD 21) ; infix plus
501 (defvar js2-SUB 22) ; infix minus
502 (defvar js2-MUL 23)
503 (defvar js2-DIV 24)
504 (defvar js2-MOD 25)
505 (defvar js2-NOT 26)
506 (defvar js2-BITNOT 27)
507 (defvar js2-POS 28) ; unary plus
508 (defvar js2-NEG 29) ; unary minus
509 (defvar js2-NEW 30)
510 (defvar js2-DELPROP 31)
511 (defvar js2-TYPEOF 32)
512 (defvar js2-GETPROP 33)
513 (defvar js2-GETPROPNOWARN 34)
514 (defvar js2-SETPROP 35)
515 (defvar js2-GETELEM 36)
516 (defvar js2-SETELEM 37)
517 (defvar js2-CALL 38)
518 (defvar js2-NAME 39) ; an identifier
519 (defvar js2-NUMBER 40)
520 (defvar js2-STRING 41)
521 (defvar js2-NULL 42)
522 (defvar js2-THIS 43)
523 (defvar js2-FALSE 44)
524 (defvar js2-TRUE 45)
525 (defvar js2-SHEQ 46) ; shallow equality (===)
526 (defvar js2-SHNE 47) ; shallow inequality (!==)
527 (defvar js2-REGEXP 48)
528 (defvar js2-BINDNAME 49)
529 (defvar js2-THROW 50)
530 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
531 (defvar js2-IN 52)
532 (defvar js2-INSTANCEOF 53)
533 (defvar js2-LOCAL_LOAD 54)
534 (defvar js2-GETVAR 55)
535 (defvar js2-SETVAR 56)
536 (defvar js2-CATCH_SCOPE 57)
537 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
538 (defvar js2-ENUM_INIT_VALUES 59)
539 (defvar js2-ENUM_INIT_ARRAY 60)
540 (defvar js2-ENUM_NEXT 61)
541 (defvar js2-ENUM_ID 62)
542 (defvar js2-THISFN 63)
543 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
544 (defvar js2-ARRAYLIT 65) ; array literal
545 (defvar js2-OBJECTLIT 66) ; object literal
546 (defvar js2-GET_REF 67) ; *reference
547 (defvar js2-SET_REF 68) ; *reference = something
548 (defvar js2-DEL_REF 69) ; delete reference
549 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
550 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
551 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
552
553 ;; XML support
554 (defvar js2-DEFAULTNAMESPACE 73)
555 (defvar js2-ESCXMLATTR 74)
556 (defvar js2-ESCXMLTEXT 75)
557 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
558 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
559 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
560 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
561
562 (defvar js2-first-bytecode js2-ENTERWITH)
563 (defvar js2-last-bytecode js2-REF_NS_NAME)
564
565 (defvar js2-TRY 80)
566 (defvar js2-SEMI 81) ; semicolon
567 (defvar js2-LB 82) ; left and right brackets
568 (defvar js2-RB 83)
569 (defvar js2-LC 84) ; left and right curly-braces
570 (defvar js2-RC 85)
571 (defvar js2-LP 86) ; left and right parens
572 (defvar js2-RP 87)
573 (defvar js2-COMMA 88) ; comma operator
574
575 (defvar js2-ASSIGN 89) ; simple assignment (=)
576 (defvar js2-ASSIGN_BITOR 90) ; |=
577 (defvar js2-ASSIGN_BITXOR 91) ; ^=
578 (defvar js2-ASSIGN_BITAND 92) ; &=
579 (defvar js2-ASSIGN_LSH 93) ; <<=
580 (defvar js2-ASSIGN_RSH 94) ; >>=
581 (defvar js2-ASSIGN_URSH 95) ; >>>=
582 (defvar js2-ASSIGN_ADD 96) ; +=
583 (defvar js2-ASSIGN_SUB 97) ; -=
584 (defvar js2-ASSIGN_MUL 98) ; *=
585 (defvar js2-ASSIGN_DIV 99) ; /=
586 (defvar js2-ASSIGN_MOD 100) ; %=
587
588 (defvar js2-first-assign js2-ASSIGN)
589 (defvar js2-last-assign js2-ASSIGN_MOD)
590
591 (defvar js2-HOOK 101) ; conditional (?:)
592 (defvar js2-COLON 102)
593 (defvar js2-OR 103) ; logical or (||)
594 (defvar js2-AND 104) ; logical and (&&)
595 (defvar js2-INC 105) ; increment/decrement (++ --)
596 (defvar js2-DEC 106)
597 (defvar js2-DOT 107) ; member operator (.)
598 (defvar js2-FUNCTION 108) ; function keyword
599 (defvar js2-EXPORT 109) ; export keyword
600 (defvar js2-IMPORT 110) ; import keyword
601 (defvar js2-IF 111) ; if keyword
602 (defvar js2-ELSE 112) ; else keyword
603 (defvar js2-SWITCH 113) ; switch keyword
604 (defvar js2-CASE 114) ; case keyword
605 (defvar js2-DEFAULT 115) ; default keyword
606 (defvar js2-WHILE 116) ; while keyword
607 (defvar js2-DO 117) ; do keyword
608 (defvar js2-FOR 118) ; for keyword
609 (defvar js2-BREAK 119) ; break keyword
610 (defvar js2-CONTINUE 120) ; continue keyword
611 (defvar js2-VAR 121) ; var keyword
612 (defvar js2-WITH 122) ; with keyword
613 (defvar js2-CATCH 123) ; catch keyword
614 (defvar js2-FINALLY 124) ; finally keyword
615 (defvar js2-VOID 125) ; void keyword
616 (defvar js2-RESERVED 126) ; reserved keywords
617
618 (defvar js2-EMPTY 127)
619
620 ;; Types used for the parse tree - never returned by scanner.
621
622 (defvar js2-BLOCK 128) ; statement block
623 (defvar js2-LABEL 129) ; label
624 (defvar js2-TARGET 130)
625 (defvar js2-LOOP 131)
626 (defvar js2-EXPR_VOID 132) ; expression statement in functions
627 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
628 (defvar js2-JSR 134)
629 (defvar js2-SCRIPT 135) ; top-level node for entire script
630 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
631 (defvar js2-USE_STACK 137)
632 (defvar js2-SETPROP_OP 138) ; x.y op= something
633 (defvar js2-SETELEM_OP 139) ; x[y] op= something
634 (defvar js2-LOCAL_BLOCK 140)
635 (defvar js2-SET_REF_OP 141) ; *reference op= something
636
637 ;; For XML support:
638 (defvar js2-DOTDOT 142) ; member operator (..)
639 (defvar js2-COLONCOLON 143) ; namespace::name
640 (defvar js2-XML 144) ; XML type
641 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
642 (defvar js2-XMLATTR 146) ; @
643 (defvar js2-XMLEND 147)
644
645 ;; Optimizer-only tokens
646 (defvar js2-TO_OBJECT 148)
647 (defvar js2-TO_DOUBLE 149)
648
649 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
650 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
651 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
652 (defvar js2-CONST 153)
653 (defvar js2-SETCONST 154)
654 (defvar js2-SETCONSTVAR 155)
655 (defvar js2-ARRAYCOMP 156)
656 (defvar js2-LETEXPR 157)
657 (defvar js2-WITHEXPR 158)
658 (defvar js2-DEBUGGER 159)
659
660 (defvar js2-COMMENT 160)
661 (defvar js2-TRIPLEDOT 161) ; for rest parameter
662 (defvar js2-ARROW 162) ; function arrow (=>)
663 (defvar js2-CLASS 163)
664 (defvar js2-EXTENDS 164)
665 (defvar js2-STATIC 165)
666 (defvar js2-SUPER 166)
667 (defvar js2-TEMPLATE_HEAD 167) ; part of template literal before substitution
668 (defvar js2-NO_SUBS_TEMPLATE 168) ; template literal without substitutions
669 (defvar js2-TAGGED_TEMPLATE 169) ; tagged template literal
670
671 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
672
673 (defconst js2-debug-print-trees nil)
674
675 ;; Rhino accepts any string or stream as input. Emacs character
676 ;; processing works best in buffers, so we'll assume the input is a
677 ;; buffer. JavaScript strings can be copied into temp buffers before
678 ;; scanning them.
679
680 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
681 ;; They're the Emacs equivalent of instance variables, more or less.
682
683 (js2-deflocal js2-ts-dirty-line nil
684 "Token stream buffer-local variable.
685 Indicates stuff other than whitespace since start of line.")
686
687 (js2-deflocal js2-ts-hit-eof nil
688 "Token stream buffer-local variable.")
689
690 ;; FIXME: Unused.
691 (js2-deflocal js2-ts-line-start 0
692 "Token stream buffer-local variable.")
693
694 (js2-deflocal js2-ts-lineno 1
695 "Token stream buffer-local variable.")
696
697 ;; FIXME: Unused.
698 (js2-deflocal js2-ts-line-end-char -1
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
702 "Token stream buffer-local variable.
703 Current scan position.")
704
705 ;; FIXME: Unused.
706 (js2-deflocal js2-ts-is-xml-attribute nil
707 "Token stream buffer-local variable.")
708
709 (js2-deflocal js2-ts-xml-is-tag-content nil
710 "Token stream buffer-local variable.")
711
712 (js2-deflocal js2-ts-xml-open-tags-count 0
713 "Token stream buffer-local variable.")
714
715 (js2-deflocal js2-ts-string-buffer nil
716 "Token stream buffer-local variable.
717 List of chars built up while scanning various tokens.")
718
719 (defstruct (js2-token
720 (:constructor nil)
721 (:constructor make-js2-token (beg)))
722 "Value returned from the token stream."
723 (type js2-EOF)
724 (beg 1)
725 (end -1)
726 (string "")
727 number
728 regexp-flags
729 comment-type
730 follows-eol-p)
731
732 (defstruct (js2-ts-state
733 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
734 (cursor js2-ts-cursor)
735 (tokens (copy-sequence js2-ti-tokens))
736 (tokens-cursor js2-ti-tokens-cursor)
737 (lookahead js2-ti-lookahead))))
738 lineno
739 cursor
740 tokens
741 tokens-cursor
742 lookahead)
743
744 ;;; Parser variables
745
746 (js2-deflocal js2-parsed-errors nil
747 "List of errors produced during scanning/parsing.")
748
749 (js2-deflocal js2-parsed-warnings nil
750 "List of warnings produced during scanning/parsing.")
751
752 (js2-deflocal js2-recover-from-parse-errors t
753 "Non-nil to continue parsing after a syntax error.
754
755 In recovery mode, the AST will be built in full, and any error
756 nodes will be flagged with appropriate error information. If
757 this flag is nil, a syntax error will result in an error being
758 signaled.
759
760 The variable is automatically buffer-local, because different
761 modes that use the parser will need different settings.")
762
763 (js2-deflocal js2-parse-hook nil
764 "List of callbacks for receiving parsing progress.")
765
766 (defvar js2-parse-finished-hook nil
767 "List of callbacks to notify when parsing finishes.
768 Not called if parsing was interrupted.")
769
770 (js2-deflocal js2-is-eval-code nil
771 "True if we're evaluating code in a string.
772 If non-nil, the tokenizer will record the token text, and the AST nodes
773 will record their source text. Off by default for IDE modes, since the
774 text is available in the buffer.")
775
776 (defvar js2-parse-ide-mode t
777 "Non-nil if the parser is being used for `js2-mode'.
778 If non-nil, the parser will set text properties for fontification
779 and the syntax table. The value should be nil when using the
780 parser as a frontend to an interpreter or byte compiler.")
781
782 ;;; Parser instance variables (buffer-local vars for js2-parse)
783
784 (defconst js2-ti-after-eol (lsh 1 16)
785 "Flag: first token of the source line.")
786
787 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
788
789 (js2-deflocal js2-compiler-generate-debug-info t)
790 (js2-deflocal js2-compiler-use-dynamic-scope nil)
791 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
792 (js2-deflocal js2-compiler-xml-available t)
793 (js2-deflocal js2-compiler-optimization-level 0)
794 (js2-deflocal js2-compiler-generating-source t)
795 (js2-deflocal js2-compiler-strict-mode nil)
796 (js2-deflocal js2-compiler-report-warning-as-error nil)
797 (js2-deflocal js2-compiler-generate-observer-count nil)
798 (js2-deflocal js2-compiler-activation-names nil)
799
800 ;; SKIP: sourceURI
801
802 ;; There's a compileFunction method in Context.java - may need it.
803 (js2-deflocal js2-called-by-compile-function nil
804 "True if `js2-parse' was called by `js2-compile-function'.
805 Will only be used when we finish implementing the interpreter.")
806
807 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
808
809 ;; SKIP: node factory - we're going to just call functions directly,
810 ;; and eventually go to a unified AST format.
811
812 (js2-deflocal js2-nesting-of-function 0)
813
814 (js2-deflocal js2-recorded-identifiers nil
815 "Tracks identifiers found during parsing.")
816
817 (js2-deflocal js2-is-in-destructuring nil
818 "True while parsing destructuring expression.")
819
820 (defcustom js2-global-externs nil
821 "A list of any extern names you'd like to consider always declared.
822 This list is global and is used by all `js2-mode' files.
823 You can create buffer-local externs list using `js2-additional-externs'.
824
825 There is also a buffer-local variable `js2-default-externs',
826 which is initialized by default to include the Ecma-262 externs
827 and the standard browser externs. The three lists are all
828 checked during highlighting."
829 :type 'list
830 :group 'js2-mode)
831
832 (js2-deflocal js2-default-externs nil
833 "Default external declarations.
834
835 These are currently only used for highlighting undeclared variables,
836 which only worries about top-level (unqualified) references.
837 As js2-mode's processing improves, we will flesh out this list.
838
839 The initial value is set to `js2-ecma-262-externs', unless some
840 of the `js2-include-?-externs' variables are set to t, in which
841 case the browser, Rhino and/or Node.js externs are also included.
842
843 See `js2-additional-externs' for more information.")
844
845 (defcustom js2-include-browser-externs t
846 "Non-nil to include browser externs in the master externs list.
847 If you work on JavaScript files that are not intended for browsers,
848 such as Mozilla Rhino server-side JavaScript, set this to nil.
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (defcustom js2-include-rhino-externs nil
854 "Non-nil to include Mozilla Rhino externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
856 :type 'boolean
857 :group 'js2-mode)
858
859 (defcustom js2-include-node-externs nil
860 "Non-nil to include Node.js externs in the master externs list.
861 See `js2-additional-externs' for more information about externs."
862 :type 'boolean
863 :group 'js2-mode)
864
865 (js2-deflocal js2-additional-externs nil
866 "A buffer-local list of additional external declarations.
867 It is used to decide whether variables are considered undeclared
868 for purposes of highlighting.
869
870 Each entry is a Lisp string. The string should be the fully qualified
871 name of an external entity. All externs should be added to this list,
872 so that as js2-mode's processing improves it can take advantage of them.
873
874 You may want to declare your externs in three ways.
875 First, you can add externs that are valid for all your JavaScript files.
876 You should probably do this by adding them to `js2-global-externs', which
877 is a global list used for all js2-mode files.
878
879 Next, you can add a function to `js2-init-hook' that adds additional
880 externs appropriate for the specific file, perhaps based on its path.
881 These should go in `js2-additional-externs', which is buffer-local.
882
883 Third, you can use JSLint's global declaration, as long as
884 `js2-include-jslint-globals' is non-nil, which see.
885
886 Finally, you can add a function to `js2-post-parse-callbacks',
887 which is called after parsing completes, and `js2-mode-ast' is bound to
888 the root of the parse tree. At this stage you can set up an AST
889 node visitor using `js2-visit-ast' and examine the parse tree
890 for specific import patterns that may imply the existence of
891 other externs, possibly tied to your build system. These should also
892 be added to `js2-additional-externs'.
893
894 Your post-parse callback may of course also use the simpler and
895 faster (but perhaps less robust) approach of simply scanning the
896 buffer text for your imports, using regular expressions.")
897
898 ;; SKIP: decompiler
899 ;; SKIP: encoded-source
900
901 ;;; The following variables are per-function and should be saved/restored
902 ;;; during function parsing...
903
904 (js2-deflocal js2-current-script-or-fn nil)
905 (js2-deflocal js2-current-scope nil)
906 (js2-deflocal js2-nesting-of-with 0)
907 (js2-deflocal js2-label-set nil
908 "An alist mapping label names to nodes.")
909
910 (js2-deflocal js2-loop-set nil)
911 (js2-deflocal js2-loop-and-switch-set nil)
912 (js2-deflocal js2-has-return-value nil)
913 (js2-deflocal js2-end-flags 0)
914
915 ;;; ...end of per function variables
916
917 ;; These flags enumerate the possible ways a statement/function can
918 ;; terminate. These flags are used by endCheck() and by the Parser to
919 ;; detect inconsistent return usage.
920 ;;
921 ;; END_UNREACHED is reserved for code paths that are assumed to always be
922 ;; able to execute (example: throw, continue)
923 ;;
924 ;; END_DROPS_OFF indicates if the statement can transfer control to the
925 ;; next one. Statement such as return dont. A compound statement may have
926 ;; some branch that drops off control to the next statement.
927 ;;
928 ;; END_RETURNS indicates that the statement can return (without arguments)
929 ;; END_RETURNS_VALUE indicates that the statement can return a value.
930 ;;
931 ;; A compound statement such as
932 ;; if (condition) {
933 ;; return value;
934 ;; }
935 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
936
937 (defconst js2-end-unreached #x0)
938 (defconst js2-end-drops-off #x1)
939 (defconst js2-end-returns #x2)
940 (defconst js2-end-returns-value #x4)
941
942 ;; Rhino awkwardly passes a statementLabel parameter to the
943 ;; statementHelper() function, the main statement parser, which
944 ;; is then used by quite a few of the sub-parsers. We just make
945 ;; it a buffer-local variable and make sure it's cleaned up properly.
946 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
947
948 ;; Similarly, Rhino passes an inForInit boolean through about half
949 ;; the expression parsers. We use a dynamically-scoped variable,
950 ;; which makes it easier to funcall the parsers individually without
951 ;; worrying about whether they take the parameter or not.
952 (js2-deflocal js2-in-for-init nil)
953 (js2-deflocal js2-temp-name-counter 0)
954 (js2-deflocal js2-parse-stmt-count 0)
955
956 (defsubst js2-get-next-temp-name ()
957 (format "$%d" (incf js2-temp-name-counter)))
958
959 (defvar js2-parse-interruptable-p t
960 "Set this to nil to force parse to continue until finished.
961 This will mostly be useful for interpreters.")
962
963 (defvar js2-statements-per-pause 50
964 "Pause after this many statements to check for user input.
965 If user input is pending, stop the parse and discard the tree.
966 This makes for a smoother user experience for large files.
967 You may have to wait a second or two before the highlighting
968 and error-reporting appear, but you can always type ahead if
969 you wish. This appears to be more or less how Eclipse, IntelliJ
970 and other editors work.")
971
972 (js2-deflocal js2-record-comments t
973 "Instructs the scanner to record comments in `js2-scanned-comments'.")
974
975 (js2-deflocal js2-scanned-comments nil
976 "List of all comments from the current parse.")
977
978 (defcustom js2-mode-indent-inhibit-undo nil
979 "Non-nil to disable collection of Undo information when indenting lines.
980 Some users have requested this behavior. It's nil by default because
981 other Emacs modes don't work this way."
982 :type 'boolean
983 :group 'js2-mode)
984
985 (defcustom js2-mode-indent-ignore-first-tab nil
986 "If non-nil, ignore first TAB keypress if we look indented properly.
987 It's fairly common for users to navigate to an already-indented line
988 and press TAB for reassurance that it's been indented. For this class
989 of users, we want the first TAB press on a line to be ignored if the
990 line is already indented to one of the precomputed alternatives.
991
992 This behavior is only partly implemented. If you TAB-indent a line,
993 navigate to another line, and then navigate back, it fails to clear
994 the last-indented variable, so it thinks you've already hit TAB once,
995 and performs the indent. A full solution would involve getting on the
996 point-motion hooks for the entire buffer. If we come across another
997 use cases that requires watching point motion, I'll consider doing it.
998
999 If you set this variable to nil, then the TAB key will always change
1000 the indentation of the current line, if more than one alternative
1001 indentation spot exists."
1002 :type 'boolean
1003 :group 'js2-mode)
1004
1005 (defvar js2-indent-hook nil
1006 "A hook for user-defined indentation rules.
1007
1008 Functions on this hook should expect two arguments: (LIST INDEX)
1009 The LIST argument is the list of computed indentation points for
1010 the current line. INDEX is the list index of the indentation point
1011 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1012 indent function is not going to change the current line indentation.
1013
1014 If a hook function on this list returns a non-nil value, then
1015 `js2-bounce-indent' assumes the hook function has performed its own
1016 indentation, and will do nothing. If all hook functions on the list
1017 return nil, then `js2-bounce-indent' will use its computed indentation
1018 and reindent the line.
1019
1020 When hook functions on this hook list are called, the variable
1021 `js2-mode-ast' may or may not be set, depending on whether the
1022 parse tree is available. If the variable is nil, you can pass a
1023 callback to `js2-mode-wait-for-parse', and your callback will be
1024 called after the new parse tree is built. This can take some time
1025 in large files.")
1026
1027 (defface js2-warning
1028 `((((class color) (background light))
1029 (:underline "orange"))
1030 (((class color) (background dark))
1031 (:underline "orange"))
1032 (t (:underline t)))
1033 "Face for JavaScript warnings."
1034 :group 'js2-mode)
1035
1036 (defface js2-error
1037 `((((class color) (background light))
1038 (:foreground "red"))
1039 (((class color) (background dark))
1040 (:foreground "red"))
1041 (t (:foreground "red")))
1042 "Face for JavaScript errors."
1043 :group 'js2-mode)
1044
1045 (defface js2-jsdoc-tag
1046 '((t :foreground "SlateGray"))
1047 "Face used to highlight @whatever tags in jsdoc comments."
1048 :group 'js2-mode)
1049
1050 (defface js2-jsdoc-type
1051 '((t :foreground "SteelBlue"))
1052 "Face used to highlight {FooBar} types in jsdoc comments."
1053 :group 'js2-mode)
1054
1055 (defface js2-jsdoc-value
1056 '((t :foreground "PeachPuff3"))
1057 "Face used to highlight tag values in jsdoc comments."
1058 :group 'js2-mode)
1059
1060 (defface js2-function-param
1061 '((t :foreground "SeaGreen"))
1062 "Face used to highlight function parameters in javascript."
1063 :group 'js2-mode)
1064
1065 (defface js2-function-call
1066 '((t :inherit default))
1067 "Face used to highlight function name in calls."
1068 :group 'js2-mode)
1069
1070 (defface js2-instance-member
1071 '((t :foreground "DarkOrchid"))
1072 "Face used to highlight instance variables in javascript.
1073 Not currently used."
1074 :group 'js2-mode)
1075
1076 (defface js2-private-member
1077 '((t :foreground "PeachPuff3"))
1078 "Face used to highlight calls to private methods in javascript.
1079 Not currently used."
1080 :group 'js2-mode)
1081
1082 (defface js2-private-function-call
1083 '((t :foreground "goldenrod"))
1084 "Face used to highlight calls to private functions in javascript.
1085 Not currently used."
1086 :group 'js2-mode)
1087
1088 (defface js2-jsdoc-html-tag-name
1089 '((((class color) (min-colors 88) (background light))
1090 (:foreground "rosybrown"))
1091 (((class color) (min-colors 8) (background dark))
1092 (:foreground "yellow"))
1093 (((class color) (min-colors 8) (background light))
1094 (:foreground "magenta")))
1095 "Face used to highlight jsdoc html tag names"
1096 :group 'js2-mode)
1097
1098 (defface js2-jsdoc-html-tag-delimiter
1099 '((((class color) (min-colors 88) (background light))
1100 (:foreground "dark khaki"))
1101 (((class color) (min-colors 8) (background dark))
1102 (:foreground "green"))
1103 (((class color) (min-colors 8) (background light))
1104 (:foreground "green")))
1105 "Face used to highlight brackets in jsdoc html tags."
1106 :group 'js2-mode)
1107
1108 (defface js2-external-variable
1109 '((t :foreground "orange"))
1110 "Face used to highlight undeclared variable identifiers.")
1111
1112 (defcustom js2-init-hook nil
1113 "List of functions to be called after `js2-mode' or
1114 `js2-minor-mode' has initialized all variables, before parsing
1115 the buffer for the first time."
1116 :type 'hook
1117 :group 'js2-mode
1118 :version "20130608")
1119
1120 (defcustom js2-post-parse-callbacks nil
1121 "List of callback functions invoked after parsing finishes.
1122 Currently, the main use for this function is to add synthetic
1123 declarations to `js2-recorded-identifiers', which see."
1124 :type 'hook
1125 :group 'js2-mode)
1126
1127 (defcustom js2-build-imenu-callbacks nil
1128 "List of functions called during Imenu index generation.
1129 It's a good place to add additional entries to it, using
1130 `js2-record-imenu-entry'."
1131 :type 'hook
1132 :group 'js2-mode)
1133
1134 (defcustom js2-highlight-external-variables t
1135 "Non-nil to highlight undeclared variable identifiers.
1136 An undeclared variable is any variable not declared with var or let
1137 in the current scope or any lexically enclosing scope. If you use
1138 such a variable, then you are either expecting it to originate from
1139 another file, or you've got a potential bug."
1140 :type 'boolean
1141 :group 'js2-mode)
1142
1143 (defcustom js2-include-jslint-globals t
1144 "Non-nil to include the identifiers from JSLint global
1145 declaration (see http://www.jslint.com/lint.html#global) in the
1146 buffer-local externs list. See `js2-additional-externs' for more
1147 information."
1148 :type 'boolean
1149 :group 'js2-mode)
1150
1151 (defvar js2-mode-map
1152 (let ((map (make-sparse-keymap)))
1153 (define-key map [mouse-1] #'js2-mode-show-node)
1154 (define-key map (kbd "M-j") #'js2-line-break)
1155 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1156 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1157 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1158 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1159 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1160 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1161 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1162 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1163 (when js2-bounce-indent-p
1164 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1165
1166 (define-key map [menu-bar javascript]
1167 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1168
1169 (define-key map [menu-bar javascript customize-js2-mode]
1170 '(menu-item "Customize js2-mode" js2-mode-customize
1171 :help "Customize the behavior of this mode"))
1172
1173 (define-key map [menu-bar javascript js2-force-refresh]
1174 '(menu-item "Force buffer refresh" js2-mode-reset
1175 :help "Re-parse the buffer from scratch"))
1176
1177 (define-key map [menu-bar javascript separator-2]
1178 '("--"))
1179
1180 (define-key map [menu-bar javascript next-error]
1181 '(menu-item "Next warning or error" next-error
1182 :enabled (and js2-mode-ast
1183 (or (js2-ast-root-errors js2-mode-ast)
1184 (js2-ast-root-warnings js2-mode-ast)))
1185 :help "Move to next warning or error"))
1186
1187 (define-key map [menu-bar javascript display-errors]
1188 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1189 :visible (not js2-mode-show-parse-errors)
1190 :help "Turn on display of warnings and errors"))
1191
1192 (define-key map [menu-bar javascript hide-errors]
1193 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1194 :visible js2-mode-show-parse-errors
1195 :help "Turn off display of warnings and errors"))
1196
1197 (define-key map [menu-bar javascript separator-1]
1198 '("--"))
1199
1200 (define-key map [menu-bar javascript js2-toggle-function]
1201 '(menu-item "Show/collapse element" js2-mode-toggle-element
1202 :help "Hide or show function body or comment"))
1203
1204 (define-key map [menu-bar javascript show-comments]
1205 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1206 :visible js2-mode-comments-hidden
1207 :help "Expand all hidden block comments"))
1208
1209 (define-key map [menu-bar javascript hide-comments]
1210 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1211 :visible (not js2-mode-comments-hidden)
1212 :help "Show block comments as /*...*/"))
1213
1214 (define-key map [menu-bar javascript show-all-functions]
1215 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1216 :visible js2-mode-functions-hidden
1217 :help "Expand all hidden function bodies"))
1218
1219 (define-key map [menu-bar javascript hide-all-functions]
1220 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1221 :visible (not js2-mode-functions-hidden)
1222 :help "Show {...} for all top-level function bodies"))
1223
1224 map)
1225 "Keymap used in `js2-mode' buffers.")
1226
1227 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1228
1229 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1230 "Matches a //-comment line. Must be first non-whitespace on line.
1231 First match-group is the leading whitespace.")
1232
1233 (defvar js2-mode-hook nil)
1234
1235 (js2-deflocal js2-mode-ast nil "Private variable.")
1236 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1237 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1238 (js2-deflocal js2-mode-parsing nil "Private variable.")
1239 (js2-deflocal js2-mode-node-overlay nil)
1240
1241 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1242 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1243
1244 (js2-deflocal js2-mode-fontifications nil "Private variable")
1245 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1246 (js2-deflocal js2-imenu-recorder nil "Private variable")
1247 (js2-deflocal js2-imenu-function-map nil "Private variable")
1248
1249 (defvar js2-paragraph-start
1250 "\\(@[[:alpha:]]+\\>\\|$\\)")
1251
1252 ;; Note that we also set a 'c-in-sws text property in html comments,
1253 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1254 (defvar js2-syntactic-ws-start
1255 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1256
1257 (defvar js2-syntactic-ws-end
1258 "\\s \\|[\n\r/]\\|\\s!")
1259
1260 (defvar js2-syntactic-eol
1261 (concat "\\s *\\(/\\*[^*\n\r]*"
1262 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1263 "\\*+/\\s *\\)*"
1264 "\\(//\\|/\\*[^*\n\r]*"
1265 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1266 "\\|\\\\$\\|$\\)")
1267 "Copied from `java-mode'. Needed for some cc-engine functions.")
1268
1269 (defvar js2-comment-prefix-regexp
1270 "//+\\|\\**")
1271
1272 (defvar js2-comment-start-skip
1273 "\\(//+\\|/\\*+\\)\\s *")
1274
1275 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1276 "Non-nil to emit status messages during parsing.")
1277
1278 (defvar js2-mode-functions-hidden nil "Private variable.")
1279 (defvar js2-mode-comments-hidden nil "Private variable.")
1280
1281 (defvar js2-mode-syntax-table
1282 (let ((table (make-syntax-table)))
1283 (c-populate-syntax-table table)
1284 table)
1285 "Syntax table used in `js2-mode' buffers.")
1286
1287 (defvar js2-mode-abbrev-table nil
1288 "Abbrev table in use in `js2-mode' buffers.")
1289 (define-abbrev-table 'js2-mode-abbrev-table ())
1290
1291 (defvar js2-mode-pending-parse-callbacks nil
1292 "List of functions waiting to be notified that parse is finished.")
1293
1294 (defvar js2-mode-last-indented-line -1)
1295
1296 ;;; Localizable error and warning messages
1297
1298 ;; Messages are copied from Rhino's Messages.properties.
1299 ;; Many of the Java-specific messages have been elided.
1300 ;; Add any js2-specific ones at the end, so we can keep
1301 ;; this file synced with changes to Rhino's.
1302
1303 (defvar js2-message-table
1304 (make-hash-table :test 'equal :size 250)
1305 "Contains localized messages for `js2-mode'.")
1306
1307 ;; TODO(stevey): construct this table at compile-time.
1308 (defmacro js2-msg (key &rest strings)
1309 `(puthash ,key (concat ,@strings)
1310 js2-message-table))
1311
1312 (defun js2-get-msg (msg-key)
1313 "Look up a localized message.
1314 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1315 the correct number of ARGS must be provided."
1316 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1317 (args (if (listp msg-key) (cdr msg-key)))
1318 (msg (gethash key js2-message-table)))
1319 (if msg
1320 (apply #'format msg args)
1321 key))) ; default to showing the key
1322
1323 (js2-msg "msg.dup.parms"
1324 "Duplicate parameter name '%s'.")
1325
1326 (js2-msg "msg.too.big.jump"
1327 "Program too complex: jump offset too big.")
1328
1329 (js2-msg "msg.too.big.index"
1330 "Program too complex: internal index exceeds 64K limit.")
1331
1332 (js2-msg "msg.while.compiling.fn"
1333 "Encountered code generation error while compiling function '%s': %s")
1334
1335 (js2-msg "msg.while.compiling.script"
1336 "Encountered code generation error while compiling script: %s")
1337
1338 ;; Context
1339 (js2-msg "msg.ctor.not.found"
1340 "Constructor for '%s' not found.")
1341
1342 (js2-msg "msg.not.ctor"
1343 "'%s' is not a constructor.")
1344
1345 ;; FunctionObject
1346 (js2-msg "msg.varargs.ctor"
1347 "Method or constructor '%s' must be static "
1348 "with the signature (Context cx, Object[] args, "
1349 "Function ctorObj, boolean inNewExpr) "
1350 "to define a variable arguments constructor.")
1351
1352 (js2-msg "msg.varargs.fun"
1353 "Method '%s' must be static with the signature "
1354 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1355 "to define a variable arguments function.")
1356
1357 (js2-msg "msg.incompat.call"
1358 "Method '%s' called on incompatible object.")
1359
1360 (js2-msg "msg.bad.parms"
1361 "Unsupported parameter type '%s' in method '%s'.")
1362
1363 (js2-msg "msg.bad.method.return"
1364 "Unsupported return type '%s' in method '%s'.")
1365
1366 (js2-msg "msg.bad.ctor.return"
1367 "Construction of objects of type '%s' is not supported.")
1368
1369 (js2-msg "msg.no.overload"
1370 "Method '%s' occurs multiple times in class '%s'.")
1371
1372 (js2-msg "msg.method.not.found"
1373 "Method '%s' not found in '%s'.")
1374
1375 ;; IRFactory
1376
1377 (js2-msg "msg.bad.for.in.lhs"
1378 "Invalid left-hand side of for..in loop.")
1379
1380 (js2-msg "msg.mult.index"
1381 "Only one variable allowed in for..in loop.")
1382
1383 (js2-msg "msg.bad.for.in.destruct"
1384 "Left hand side of for..in loop must be an array of "
1385 "length 2 to accept key/value pair.")
1386
1387 (js2-msg "msg.cant.convert"
1388 "Can't convert to type '%s'.")
1389
1390 (js2-msg "msg.bad.assign.left"
1391 "Invalid assignment left-hand side.")
1392
1393 (js2-msg "msg.bad.decr"
1394 "Invalid decerement operand.")
1395
1396 (js2-msg "msg.bad.incr"
1397 "Invalid increment operand.")
1398
1399 (js2-msg "msg.bad.yield"
1400 "yield must be in a function.")
1401
1402 (js2-msg "msg.yield.parenthesized"
1403 "yield expression must be parenthesized.")
1404
1405 ;; NativeGlobal
1406 (js2-msg "msg.cant.call.indirect"
1407 "Function '%s' must be called directly, and not by way of a "
1408 "function of another name.")
1409
1410 (js2-msg "msg.eval.nonstring"
1411 "Calling eval() with anything other than a primitive "
1412 "string value will simply return the value. "
1413 "Is this what you intended?")
1414
1415 (js2-msg "msg.eval.nonstring.strict"
1416 "Calling eval() with anything other than a primitive "
1417 "string value is not allowed in strict mode.")
1418
1419 (js2-msg "msg.bad.destruct.op"
1420 "Invalid destructuring assignment operator")
1421
1422 ;; NativeCall
1423 (js2-msg "msg.only.from.new"
1424 "'%s' may only be invoked from a `new' expression.")
1425
1426 (js2-msg "msg.deprec.ctor"
1427 "The '%s' constructor is deprecated.")
1428
1429 ;; NativeFunction
1430 (js2-msg "msg.no.function.ref.found"
1431 "no source found to decompile function reference %s")
1432
1433 (js2-msg "msg.arg.isnt.array"
1434 "second argument to Function.prototype.apply must be an array")
1435
1436 ;; NativeGlobal
1437 (js2-msg "msg.bad.esc.mask"
1438 "invalid string escape mask")
1439
1440 ;; NativeRegExp
1441 (js2-msg "msg.bad.quant"
1442 "Invalid quantifier %s")
1443
1444 (js2-msg "msg.overlarge.backref"
1445 "Overly large back reference %s")
1446
1447 (js2-msg "msg.overlarge.min"
1448 "Overly large minimum %s")
1449
1450 (js2-msg "msg.overlarge.max"
1451 "Overly large maximum %s")
1452
1453 (js2-msg "msg.zero.quant"
1454 "Zero quantifier %s")
1455
1456 (js2-msg "msg.max.lt.min"
1457 "Maximum %s less than minimum")
1458
1459 (js2-msg "msg.unterm.quant"
1460 "Unterminated quantifier %s")
1461
1462 (js2-msg "msg.unterm.paren"
1463 "Unterminated parenthetical %s")
1464
1465 (js2-msg "msg.unterm.class"
1466 "Unterminated character class %s")
1467
1468 (js2-msg "msg.bad.range"
1469 "Invalid range in character class.")
1470
1471 (js2-msg "msg.trail.backslash"
1472 "Trailing \\ in regular expression.")
1473
1474 (js2-msg "msg.re.unmatched.right.paren"
1475 "unmatched ) in regular expression.")
1476
1477 (js2-msg "msg.no.regexp"
1478 "Regular expressions are not available.")
1479
1480 (js2-msg "msg.bad.backref"
1481 "back-reference exceeds number of capturing parentheses.")
1482
1483 (js2-msg "msg.bad.regexp.compile"
1484 "Only one argument may be specified if the first "
1485 "argument to RegExp.prototype.compile is a RegExp object.")
1486
1487 ;; Parser
1488 (js2-msg "msg.got.syntax.errors"
1489 "Compilation produced %s syntax errors.")
1490
1491 (js2-msg "msg.var.redecl"
1492 "TypeError: redeclaration of var %s.")
1493
1494 (js2-msg "msg.const.redecl"
1495 "TypeError: redeclaration of const %s.")
1496
1497 (js2-msg "msg.let.redecl"
1498 "TypeError: redeclaration of variable %s.")
1499
1500 (js2-msg "msg.parm.redecl"
1501 "TypeError: redeclaration of formal parameter %s.")
1502
1503 (js2-msg "msg.fn.redecl"
1504 "TypeError: redeclaration of function %s.")
1505
1506 (js2-msg "msg.let.decl.not.in.block"
1507 "SyntaxError: let declaration not directly within block")
1508
1509 ;; NodeTransformer
1510 (js2-msg "msg.dup.label"
1511 "duplicated label")
1512
1513 (js2-msg "msg.undef.label"
1514 "undefined label")
1515
1516 (js2-msg "msg.bad.break"
1517 "unlabelled break must be inside loop or switch")
1518
1519 (js2-msg "msg.continue.outside"
1520 "continue must be inside loop")
1521
1522 (js2-msg "msg.continue.nonloop"
1523 "continue can only use labels of iteration statements")
1524
1525 (js2-msg "msg.bad.throw.eol"
1526 "Line terminator is not allowed between the throw "
1527 "keyword and throw expression.")
1528
1529 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1530 "function statement requires a name")
1531
1532 (js2-msg "msg.no.paren.parms"
1533 "missing ( before function parameters.")
1534
1535 (js2-msg "msg.no.parm"
1536 "missing formal parameter")
1537
1538 (js2-msg "msg.no.paren.after.parms"
1539 "missing ) after formal parameters")
1540
1541 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1542 "parameter without default follows parameter with default")
1543
1544 (js2-msg "msg.param.after.rest" ; added by js2-mode
1545 "parameter after rest parameter")
1546
1547 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1548 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1549
1550 (js2-msg "msg.no.brace.body"
1551 "missing '{' before function body")
1552
1553 (js2-msg "msg.no.brace.after.body"
1554 "missing } after function body")
1555
1556 (js2-msg "msg.no.paren.cond"
1557 "missing ( before condition")
1558
1559 (js2-msg "msg.no.paren.after.cond"
1560 "missing ) after condition")
1561
1562 (js2-msg "msg.no.semi.stmt"
1563 "missing ; before statement")
1564
1565 (js2-msg "msg.missing.semi"
1566 "missing ; after statement")
1567
1568 (js2-msg "msg.no.name.after.dot"
1569 "missing name after . operator")
1570
1571 (js2-msg "msg.no.name.after.coloncolon"
1572 "missing name after :: operator")
1573
1574 (js2-msg "msg.no.name.after.dotdot"
1575 "missing name after .. operator")
1576
1577 (js2-msg "msg.no.name.after.xmlAttr"
1578 "missing name after .@")
1579
1580 (js2-msg "msg.no.bracket.index"
1581 "missing ] in index expression")
1582
1583 (js2-msg "msg.no.paren.switch"
1584 "missing ( before switch expression")
1585
1586 (js2-msg "msg.no.paren.after.switch"
1587 "missing ) after switch expression")
1588
1589 (js2-msg "msg.no.brace.switch"
1590 "missing '{' before switch body")
1591
1592 (js2-msg "msg.bad.switch"
1593 "invalid switch statement")
1594
1595 (js2-msg "msg.no.colon.case"
1596 "missing : after case expression")
1597
1598 (js2-msg "msg.double.switch.default"
1599 "double default label in the switch statement")
1600
1601 (js2-msg "msg.no.while.do"
1602 "missing while after do-loop body")
1603
1604 (js2-msg "msg.no.paren.for"
1605 "missing ( after for")
1606
1607 (js2-msg "msg.no.semi.for"
1608 "missing ; after for-loop initializer")
1609
1610 (js2-msg "msg.no.semi.for.cond"
1611 "missing ; after for-loop condition")
1612
1613 (js2-msg "msg.in.after.for.name"
1614 "missing in or of after for")
1615
1616 (js2-msg "msg.no.paren.for.ctrl"
1617 "missing ) after for-loop control")
1618
1619 (js2-msg "msg.no.paren.with"
1620 "missing ( before with-statement object")
1621
1622 (js2-msg "msg.no.paren.after.with"
1623 "missing ) after with-statement object")
1624
1625 (js2-msg "msg.no.paren.after.let"
1626 "missing ( after let")
1627
1628 (js2-msg "msg.no.paren.let"
1629 "missing ) after variable list")
1630
1631 (js2-msg "msg.no.curly.let"
1632 "missing } after let statement")
1633
1634 (js2-msg "msg.bad.return"
1635 "invalid return")
1636
1637 (js2-msg "msg.no.brace.block"
1638 "missing } in compound statement")
1639
1640 (js2-msg "msg.bad.label"
1641 "invalid label")
1642
1643 (js2-msg "msg.bad.var"
1644 "missing variable name")
1645
1646 (js2-msg "msg.bad.var.init"
1647 "invalid variable initialization")
1648
1649 (js2-msg "msg.no.colon.cond"
1650 "missing : in conditional expression")
1651
1652 (js2-msg "msg.no.paren.arg"
1653 "missing ) after argument list")
1654
1655 (js2-msg "msg.no.bracket.arg"
1656 "missing ] after element list")
1657
1658 (js2-msg "msg.bad.prop"
1659 "invalid property id")
1660
1661 (js2-msg "msg.no.colon.prop"
1662 "missing : after property id")
1663
1664 (js2-msg "msg.no.brace.prop"
1665 "missing } after property list")
1666
1667 (js2-msg "msg.no.paren"
1668 "missing ) in parenthetical")
1669
1670 (js2-msg "msg.reserved.id"
1671 "'%s' is a reserved identifier")
1672
1673 (js2-msg "msg.no.paren.catch"
1674 "missing ( before catch-block condition")
1675
1676 (js2-msg "msg.bad.catchcond"
1677 "invalid catch block condition")
1678
1679 (js2-msg "msg.catch.unreachable"
1680 "any catch clauses following an unqualified catch are unreachable")
1681
1682 (js2-msg "msg.no.brace.try"
1683 "missing '{' before try block")
1684
1685 (js2-msg "msg.no.brace.catchblock"
1686 "missing '{' before catch-block body")
1687
1688 (js2-msg "msg.try.no.catchfinally"
1689 "'try' without 'catch' or 'finally'")
1690
1691 (js2-msg "msg.no.return.value"
1692 "function %s does not always return a value")
1693
1694 (js2-msg "msg.anon.no.return.value"
1695 "anonymous function does not always return a value")
1696
1697 (js2-msg "msg.return.inconsistent"
1698 "return statement is inconsistent with previous usage")
1699
1700 (js2-msg "msg.generator.returns"
1701 "TypeError: legacy generator function '%s' returns a value")
1702
1703 (js2-msg "msg.anon.generator.returns"
1704 "TypeError: anonymous legacy generator function returns a value")
1705
1706 (js2-msg "msg.syntax"
1707 "syntax error")
1708
1709 (js2-msg "msg.unexpected.eof"
1710 "Unexpected end of file")
1711
1712 (js2-msg "msg.XML.bad.form"
1713 "illegally formed XML syntax")
1714
1715 (js2-msg "msg.XML.not.available"
1716 "XML runtime not available")
1717
1718 (js2-msg "msg.too.deep.parser.recursion"
1719 "Too deep recursion while parsing")
1720
1721 (js2-msg "msg.no.side.effects"
1722 "Code has no side effects")
1723
1724 (js2-msg "msg.extra.trailing.comma"
1725 "Trailing comma is not supported in some browsers")
1726
1727 (js2-msg "msg.array.trailing.comma"
1728 "Trailing comma yields different behavior across browsers")
1729
1730 (js2-msg "msg.equal.as.assign"
1731 (concat "Test for equality (==) mistyped as assignment (=)?"
1732 " (parenthesize to suppress warning)"))
1733
1734 (js2-msg "msg.var.hides.arg"
1735 "Variable %s hides argument")
1736
1737 (js2-msg "msg.destruct.assign.no.init"
1738 "Missing = in destructuring declaration")
1739
1740 ;; ScriptRuntime
1741 (js2-msg "msg.no.properties"
1742 "%s has no properties.")
1743
1744 (js2-msg "msg.invalid.iterator"
1745 "Invalid iterator value")
1746
1747 (js2-msg "msg.iterator.primitive"
1748 "__iterator__ returned a primitive value")
1749
1750 (js2-msg "msg.assn.create.strict"
1751 "Assignment to undeclared variable %s")
1752
1753 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1754 "Undeclared variable or function '%s'")
1755
1756 (js2-msg "msg.ref.undefined.prop"
1757 "Reference to undefined property '%s'")
1758
1759 (js2-msg "msg.prop.not.found"
1760 "Property %s not found.")
1761
1762 (js2-msg "msg.invalid.type"
1763 "Invalid JavaScript value of type %s")
1764
1765 (js2-msg "msg.primitive.expected"
1766 "Primitive type expected (had %s instead)")
1767
1768 (js2-msg "msg.namespace.expected"
1769 "Namespace object expected to left of :: (found %s instead)")
1770
1771 (js2-msg "msg.null.to.object"
1772 "Cannot convert null to an object.")
1773
1774 (js2-msg "msg.undef.to.object"
1775 "Cannot convert undefined to an object.")
1776
1777 (js2-msg "msg.cyclic.value"
1778 "Cyclic %s value not allowed.")
1779
1780 (js2-msg "msg.is.not.defined"
1781 "'%s' is not defined.")
1782
1783 (js2-msg "msg.undef.prop.read"
1784 "Cannot read property '%s' from %s")
1785
1786 (js2-msg "msg.undef.prop.write"
1787 "Cannot set property '%s' of %s to '%s'")
1788
1789 (js2-msg "msg.undef.prop.delete"
1790 "Cannot delete property '%s' of %s")
1791
1792 (js2-msg "msg.undef.method.call"
1793 "Cannot call method '%s' of %s")
1794
1795 (js2-msg "msg.undef.with"
1796 "Cannot apply 'with' to %s")
1797
1798 (js2-msg "msg.isnt.function"
1799 "%s is not a function, it is %s.")
1800
1801 (js2-msg "msg.isnt.function.in"
1802 "Cannot call property %s in object %s. "
1803 "It is not a function, it is '%s'.")
1804
1805 (js2-msg "msg.function.not.found"
1806 "Cannot find function %s.")
1807
1808 (js2-msg "msg.function.not.found.in"
1809 "Cannot find function %s in object %s.")
1810
1811 (js2-msg "msg.isnt.xml.object"
1812 "%s is not an xml object.")
1813
1814 (js2-msg "msg.no.ref.to.get"
1815 "%s is not a reference to read reference value.")
1816
1817 (js2-msg "msg.no.ref.to.set"
1818 "%s is not a reference to set reference value to %s.")
1819
1820 (js2-msg "msg.no.ref.from.function"
1821 "Function %s can not be used as the left-hand "
1822 "side of assignment or as an operand of ++ or -- operator.")
1823
1824 (js2-msg "msg.bad.default.value"
1825 "Object's getDefaultValue() method returned an object.")
1826
1827 (js2-msg "msg.instanceof.not.object"
1828 "Can't use instanceof on a non-object.")
1829
1830 (js2-msg "msg.instanceof.bad.prototype"
1831 "'prototype' property of %s is not an object.")
1832
1833 (js2-msg "msg.bad.radix"
1834 "illegal radix %s.")
1835
1836 ;; ScriptableObject
1837 (js2-msg "msg.default.value"
1838 "Cannot find default value for object.")
1839
1840 (js2-msg "msg.zero.arg.ctor"
1841 "Cannot load class '%s' which has no zero-parameter constructor.")
1842
1843 (js2-msg "msg.ctor.multiple.parms"
1844 "Can't define constructor or class %s since more than "
1845 "one constructor has multiple parameters.")
1846
1847 (js2-msg "msg.extend.scriptable"
1848 "%s must extend ScriptableObject in order to define property %s.")
1849
1850 (js2-msg "msg.bad.getter.parms"
1851 "In order to define a property, getter %s must have zero "
1852 "parameters or a single ScriptableObject parameter.")
1853
1854 (js2-msg "msg.obj.getter.parms"
1855 "Expected static or delegated getter %s to take "
1856 "a ScriptableObject parameter.")
1857
1858 (js2-msg "msg.getter.static"
1859 "Getter and setter must both be static or neither be static.")
1860
1861 (js2-msg "msg.setter.return"
1862 "Setter must have void return type: %s")
1863
1864 (js2-msg "msg.setter2.parms"
1865 "Two-parameter setter must take a ScriptableObject as "
1866 "its first parameter.")
1867
1868 (js2-msg "msg.setter1.parms"
1869 "Expected single parameter setter for %s")
1870
1871 (js2-msg "msg.setter2.expected"
1872 "Expected static or delegated setter %s to take two parameters.")
1873
1874 (js2-msg "msg.setter.parms"
1875 "Expected either one or two parameters for setter.")
1876
1877 (js2-msg "msg.setter.bad.type"
1878 "Unsupported parameter type '%s' in setter '%s'.")
1879
1880 (js2-msg "msg.add.sealed"
1881 "Cannot add a property to a sealed object: %s.")
1882
1883 (js2-msg "msg.remove.sealed"
1884 "Cannot remove a property from a sealed object: %s.")
1885
1886 (js2-msg "msg.modify.sealed"
1887 "Cannot modify a property of a sealed object: %s.")
1888
1889 (js2-msg "msg.modify.readonly"
1890 "Cannot modify readonly property: %s.")
1891
1892 ;; TokenStream
1893 (js2-msg "msg.missing.exponent"
1894 "missing exponent")
1895
1896 (js2-msg "msg.caught.nfe"
1897 "number format error")
1898
1899 (js2-msg "msg.unterminated.string.lit"
1900 "unterminated string literal")
1901
1902 (js2-msg "msg.unterminated.comment"
1903 "unterminated comment")
1904
1905 (js2-msg "msg.unterminated.re.lit"
1906 "unterminated regular expression literal")
1907
1908 (js2-msg "msg.invalid.re.flag"
1909 "invalid flag after regular expression")
1910
1911 (js2-msg "msg.no.re.input.for"
1912 "no input for %s")
1913
1914 (js2-msg "msg.illegal.character"
1915 "illegal character")
1916
1917 (js2-msg "msg.invalid.escape"
1918 "invalid Unicode escape sequence")
1919
1920 (js2-msg "msg.bad.namespace"
1921 "not a valid default namespace statement. "
1922 "Syntax is: default xml namespace = EXPRESSION;")
1923
1924 ;; TokensStream warnings
1925 (js2-msg "msg.bad.octal.literal"
1926 "illegal octal literal digit %s; "
1927 "interpreting it as a decimal digit")
1928
1929 (js2-msg "msg.missing.hex.digits"
1930 "missing hexadecimal digits after '0x'")
1931
1932 (js2-msg "msg.missing.binary.digits"
1933 "missing binary digits after '0b'")
1934
1935 (js2-msg "msg.missing.octal.digits"
1936 "missing octal digits after '0o'")
1937
1938 (js2-msg "msg.script.is.not.constructor"
1939 "Script objects are not constructors.")
1940
1941 ;; Arrays
1942 (js2-msg "msg.arraylength.bad"
1943 "Inappropriate array length.")
1944
1945 ;; Arrays
1946 (js2-msg "msg.arraylength.too.big"
1947 "Array length %s exceeds supported capacity limit.")
1948
1949 ;; URI
1950 (js2-msg "msg.bad.uri"
1951 "Malformed URI sequence.")
1952
1953 ;; Number
1954 (js2-msg "msg.bad.precision"
1955 "Precision %s out of range.")
1956
1957 ;; NativeGenerator
1958 (js2-msg "msg.send.newborn"
1959 "Attempt to send value to newborn generator")
1960
1961 (js2-msg "msg.already.exec.gen"
1962 "Already executing generator")
1963
1964 (js2-msg "msg.StopIteration.invalid"
1965 "StopIteration may not be changed to an arbitrary object.")
1966
1967 ;; Interpreter
1968 (js2-msg "msg.yield.closing"
1969 "Yield from closing generator")
1970
1971 ;; Classes
1972 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1973 "class statement requires a name")
1974
1975 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1976 "unexpected ',' between class properties")
1977
1978 (js2-msg "msg.unexpected.static" ; added by js2-mode
1979 "unexpected 'static'")
1980
1981 (js2-msg "msg.missing.extends" ; added by js2-mode
1982 "name is required after extends")
1983
1984 (js2-msg "msg.no.brace.class" ; added by js2-mode
1985 "missing '{' before class body")
1986
1987 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1988 "missing ']' after computed property expression")
1989
1990 ;;; Tokens Buffer
1991
1992 (defconst js2-ti-max-lookahead 2)
1993 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1994
1995 ;; Have to call `js2-init-scanner' to initialize the values.
1996 (js2-deflocal js2-ti-tokens nil)
1997 (js2-deflocal js2-ti-tokens-cursor nil)
1998 (js2-deflocal js2-ti-lookahead nil)
1999
2000 (defun js2-new-token (offset)
2001 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2002 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2003 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2004 token))
2005
2006 (defsubst js2-current-token ()
2007 (aref js2-ti-tokens js2-ti-tokens-cursor))
2008
2009 (defsubst js2-current-token-string ()
2010 (js2-token-string (js2-current-token)))
2011
2012 (defsubst js2-current-token-type ()
2013 (js2-token-type (js2-current-token)))
2014
2015 (defsubst js2-current-token-beg ()
2016 (js2-token-beg (js2-current-token)))
2017
2018 (defsubst js2-current-token-end ()
2019 (js2-token-end (js2-current-token)))
2020
2021 (defun js2-current-token-len ()
2022 (let ((token (js2-current-token)))
2023 (- (js2-token-end token)
2024 (js2-token-beg token))))
2025
2026 (defun js2-ts-seek (state)
2027 (setq js2-ts-lineno (js2-ts-state-lineno state)
2028 js2-ts-cursor (js2-ts-state-cursor state)
2029 js2-ti-tokens (js2-ts-state-tokens state)
2030 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2031 js2-ti-lookahead (js2-ts-state-lookahead state)))
2032
2033 ;;; Utilities
2034
2035 (defun js2-delete-if (predicate list)
2036 "Remove all items satisfying PREDICATE in LIST."
2037 (loop for item in list
2038 if (not (funcall predicate item))
2039 collect item))
2040
2041 (defun js2-position (element list)
2042 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2043 Returns nil if element is not found in the list."
2044 (let ((count 0)
2045 found)
2046 (while (and list (not found))
2047 (if (eq element (car list))
2048 (setq found t)
2049 (setq count (1+ count)
2050 list (cdr list))))
2051 (if found count)))
2052
2053 (defun js2-find-if (predicate list)
2054 "Find first item satisfying PREDICATE in LIST."
2055 (let (result)
2056 (while (and list (not result))
2057 (if (funcall predicate (car list))
2058 (setq result (car list)))
2059 (setq list (cdr list)))
2060 result))
2061
2062 (defmacro js2-time (form)
2063 "Evaluate FORM, discard result, and return elapsed time in sec."
2064 (declare (debug t))
2065 (let ((beg (make-symbol "--js2-time-beg--"))
2066 (delta (make-symbol "--js2-time-end--")))
2067 `(let ((,beg (current-time))
2068 ,delta)
2069 ,form
2070 (/ (truncate (* (- (float-time (current-time))
2071 (float-time ,beg))
2072 10000))
2073 10000.0))))
2074
2075 (defsubst js2-same-line (pos)
2076 "Return t if POS is on the same line as current point."
2077 (and (>= pos (point-at-bol))
2078 (<= pos (point-at-eol))))
2079
2080 (defun js2-code-bug ()
2081 "Signal an error when we encounter an unexpected code path."
2082 (error "failed assertion"))
2083
2084 (defsubst js2-record-text-property (beg end prop value)
2085 "Record a text property to set when parsing finishes."
2086 (push (list beg end prop value) js2-mode-deferred-properties))
2087
2088 ;; I'd like to associate errors with nodes, but for now the
2089 ;; easiest thing to do is get the context info from the last token.
2090 (defun js2-record-parse-error (msg &optional arg pos len)
2091 (push (list (list msg arg)
2092 (or pos (js2-current-token-beg))
2093 (or len (js2-current-token-len)))
2094 js2-parsed-errors))
2095
2096 (defun js2-report-error (msg &optional msg-arg pos len)
2097 "Signal a syntax error or record a parse error."
2098 (if js2-recover-from-parse-errors
2099 (js2-record-parse-error msg msg-arg pos len)
2100 (signal 'js2-syntax-error
2101 (list msg
2102 js2-ts-lineno
2103 (save-excursion
2104 (goto-char js2-ts-cursor)
2105 (current-column))
2106 js2-ts-hit-eof))))
2107
2108 (defun js2-report-warning (msg &optional msg-arg pos len face)
2109 (if js2-compiler-report-warning-as-error
2110 (js2-report-error msg msg-arg pos len)
2111 (push (list (list msg msg-arg)
2112 (or pos (js2-current-token-beg))
2113 (or len (js2-current-token-len))
2114 face)
2115 js2-parsed-warnings)))
2116
2117 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2118 (if js2-compiler-strict-mode
2119 (js2-report-warning msg-id msg-arg beg
2120 (and beg end (- end beg)))))
2121
2122 (put 'js2-syntax-error 'error-conditions
2123 '(error syntax-error js2-syntax-error))
2124 (put 'js2-syntax-error 'error-message "Syntax error")
2125
2126 (put 'js2-parse-error 'error-conditions
2127 '(error parse-error js2-parse-error))
2128 (put 'js2-parse-error 'error-message "Parse error")
2129
2130 (defmacro js2-clear-flag (flags flag)
2131 `(setq ,flags (logand ,flags (lognot ,flag))))
2132
2133 (defmacro js2-set-flag (flags flag)
2134 "Logical-or FLAG into FLAGS."
2135 `(setq ,flags (logior ,flags ,flag)))
2136
2137 (defsubst js2-flag-set-p (flags flag)
2138 (/= 0 (logand flags flag)))
2139
2140 (defsubst js2-flag-not-set-p (flags flag)
2141 (zerop (logand flags flag)))
2142
2143 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2144 "Evaluate BODY with the _ character set to be word-syntax."
2145 (declare (indent 0) (debug t))
2146 (let ((old-syntax (make-symbol "old-syntax")))
2147 `(let ((,old-syntax (string (char-syntax ?_))))
2148 (unwind-protect
2149 (progn
2150 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2151 ,@body)
2152 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2153
2154 ;;; AST struct and function definitions
2155
2156 ;; flags for ast node property 'member-type (used for e4x operators)
2157 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2158 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2159 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2160
2161 (defsubst js2-relpos (pos anchor)
2162 "Convert POS to be relative to ANCHOR.
2163 If POS is nil, returns nil."
2164 (and pos (- pos anchor)))
2165
2166 (defun js2-make-pad (indent)
2167 (if (zerop indent)
2168 ""
2169 (make-string (* indent js2-basic-offset) ? )))
2170
2171 (defun js2-visit-ast (node callback)
2172 "Visit every node in ast NODE with visitor CALLBACK.
2173
2174 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2175 called twice: once to visit the node, and again after all the node's
2176 children have been processed. The END-P argument is nil on the first
2177 call and non-nil on the second call. The return value of the callback
2178 affects the traversal: if non-nil, the children of NODE are processed.
2179 If the callback returns nil, or if the node has no children, then the
2180 callback is called immediately with a non-nil END-P argument.
2181
2182 The node traversal is approximately lexical-order, although there
2183 are currently no guarantees around this."
2184 (when node
2185 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2186 ;; visit the node
2187 (when (funcall callback node nil)
2188 ;; visit the kids
2189 (cond
2190 ((eq vfunc 'js2-visit-none)
2191 nil) ; don't even bother calling it
2192 ;; Each AST node type has to define a `js2-visitor' function
2193 ;; that takes a node and a callback, and calls `js2-visit-ast'
2194 ;; on each child of the node.
2195 (vfunc
2196 (funcall vfunc node callback))
2197 (t
2198 (error "%s does not define a visitor-traversal function"
2199 (aref node 0)))))
2200 ;; call the end-visit
2201 (funcall callback node t))))
2202
2203 (defstruct (js2-node
2204 (:constructor nil)) ; abstract
2205 "Base AST node type."
2206 (type -1) ; token type
2207 (pos -1) ; start position of this AST node in parsed input
2208 (len 1) ; num characters spanned by the node
2209 props ; optional node property list (an alist)
2210 parent) ; link to parent node; null for root
2211
2212 (defsubst js2-node-get-prop (node prop &optional default)
2213 (or (cadr (assoc prop (js2-node-props node))) default))
2214
2215 (defsubst js2-node-set-prop (node prop value)
2216 (setf (js2-node-props node)
2217 (cons (list prop value) (js2-node-props node))))
2218
2219 (defun js2-fixup-starts (n nodes)
2220 "Adjust the start positions of NODES to be relative to N.
2221 Any node in the list may be nil, for convenience."
2222 (dolist (node nodes)
2223 (when node
2224 (setf (js2-node-pos node) (- (js2-node-pos node)
2225 (js2-node-pos n))))))
2226
2227 (defun js2-node-add-children (parent &rest nodes)
2228 "Set parent node of NODES to PARENT, and return PARENT.
2229 Does nothing if we're not recording parent links.
2230 If any given node in NODES is nil, doesn't record that link."
2231 (js2-fixup-starts parent nodes)
2232 (dolist (node nodes)
2233 (and node
2234 (setf (js2-node-parent node) parent))))
2235
2236 ;; Non-recursive since it's called a frightening number of times.
2237 (defun js2-node-abs-pos (n)
2238 (let ((pos (js2-node-pos n)))
2239 (while (setq n (js2-node-parent n))
2240 (setq pos (+ pos (js2-node-pos n))))
2241 pos))
2242
2243 (defsubst js2-node-abs-end (n)
2244 "Return absolute buffer position of end of N."
2245 (+ (js2-node-abs-pos n) (js2-node-len n)))
2246
2247 ;; It's important to make sure block nodes have a Lisp list for the
2248 ;; child nodes, to limit printing recursion depth in an AST that
2249 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2250 ;; a sufficiently large vector tree.
2251
2252 (defstruct (js2-block-node
2253 (:include js2-node)
2254 (:constructor nil)
2255 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2256 (pos (js2-current-token-beg))
2257 len
2258 props
2259 kids)))
2260 "A block of statements."
2261 kids) ; a Lisp list of the child statement nodes
2262
2263 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2264 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2265
2266 (defun js2-visit-block (ast callback)
2267 "Visit the `js2-block-node' children of AST."
2268 (dolist (kid (js2-block-node-kids ast))
2269 (js2-visit-ast kid callback)))
2270
2271 (defun js2-print-block (n i)
2272 (let ((pad (js2-make-pad i)))
2273 (insert pad "{\n")
2274 (dolist (kid (js2-block-node-kids n))
2275 (js2-print-ast kid (1+ i)))
2276 (insert pad "}")))
2277
2278 (defstruct (js2-scope
2279 (:include js2-block-node)
2280 (:constructor nil)
2281 (:constructor make-js2-scope (&key (type js2-BLOCK)
2282 (pos (js2-current-token-beg))
2283 len
2284 kids)))
2285 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2286 ;; I don't have one of those handy, so I'll use an alist for now.
2287 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2288 ;; and is much lighter-weight to construct (both CPU and mem).
2289 ;; The keys are interned strings (symbols) for faster lookup.
2290 ;; Should switch to hybrid alist/hashtable eventually.
2291 symbol-table ; an alist of (symbol . js2-symbol)
2292 parent-scope ; a `js2-scope'
2293 top) ; top-level `js2-scope' (script/function)
2294
2295 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2296 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2297
2298 (defun js2-node-get-enclosing-scope (node)
2299 "Return the innermost `js2-scope' node surrounding NODE.
2300 Returns nil if there is no enclosing scope node."
2301 (let ((parent (js2-node-parent node)))
2302 (while (not (js2-scope-p parent))
2303 (setq parent (js2-node-parent parent)))
2304 parent))
2305
2306 (defun js2-get-defining-scope (scope name)
2307 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2308 Returns `js2-scope' in which NAME is defined, or nil if not found."
2309 (let ((sym (if (symbolp name)
2310 name
2311 (intern name)))
2312 table
2313 result
2314 (continue t))
2315 (while (and scope continue)
2316 (if (and (setq table (js2-scope-symbol-table scope))
2317 (assq sym table))
2318 (setq continue nil
2319 result scope)
2320 (setq scope (js2-scope-parent-scope scope))))
2321 result))
2322
2323 (defun js2-scope-get-symbol (scope name)
2324 "Return symbol table entry for NAME in SCOPE.
2325 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2326 (and (js2-scope-symbol-table scope)
2327 (cdr (assq (if (symbolp name)
2328 name
2329 (intern name))
2330 (js2-scope-symbol-table scope)))))
2331
2332 (defun js2-scope-put-symbol (scope name symbol)
2333 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2334 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2335 (let* ((table (js2-scope-symbol-table scope))
2336 (sym (if (symbolp name) name (intern name)))
2337 (entry (assq sym table)))
2338 (if entry
2339 (setcdr entry symbol)
2340 (push (cons sym symbol)
2341 (js2-scope-symbol-table scope)))))
2342
2343 (defstruct (js2-symbol
2344 (:constructor nil)
2345 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2346 "A symbol table entry."
2347 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2348 ;; js2-LET, or js2-CONST
2349 decl-type
2350 name ; string
2351 ast-node) ; a `js2-node'
2352
2353 (defstruct (js2-error-node
2354 (:include js2-node)
2355 (:constructor nil) ; silence emacs21 byte-compiler
2356 (:constructor make-js2-error-node (&key (type js2-ERROR)
2357 (pos (js2-current-token-beg))
2358 len)))
2359 "AST node representing a parse error.")
2360
2361 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2362 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2363
2364 (defstruct (js2-script-node
2365 (:include js2-scope)
2366 (:constructor nil)
2367 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2368 (pos (js2-current-token-beg))
2369 len
2370 ;; FIXME: What are those?
2371 var-decls
2372 fun-decls)))
2373 functions ; Lisp list of nested functions
2374 regexps ; Lisp list of (string . flags)
2375 symbols ; alist (every symbol gets unique index)
2376 (param-count 0)
2377 var-names ; vector of string names
2378 consts ; bool-vector matching var-decls
2379 (temp-number 0)) ; for generating temp variables
2380
2381 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2382 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2383
2384 (defun js2-print-script (node indent)
2385 (dolist (kid (js2-block-node-kids node))
2386 (js2-print-ast kid indent)))
2387
2388 (defstruct (js2-ast-root
2389 (:include js2-script-node)
2390 (:constructor nil)
2391 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2392 (pos (js2-current-token-beg))
2393 len
2394 buffer)))
2395 "The root node of a js2 AST."
2396 buffer ; the source buffer from which the code was parsed
2397 comments ; a Lisp list of comments, ordered by start position
2398 errors ; a Lisp list of errors found during parsing
2399 warnings ; a Lisp list of warnings found during parsing
2400 node-count) ; number of nodes in the tree, including the root
2401
2402 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2403 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2404
2405 (defun js2-visit-ast-root (ast callback)
2406 (dolist (kid (js2-ast-root-kids ast))
2407 (js2-visit-ast kid callback))
2408 (dolist (comment (js2-ast-root-comments ast))
2409 (js2-visit-ast comment callback)))
2410
2411 (defstruct (js2-comment-node
2412 (:include js2-node)
2413 (:constructor nil)
2414 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2415 (pos (js2-current-token-beg))
2416 len
2417 format)))
2418 format) ; 'line, 'block, 'jsdoc or 'html
2419
2420 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2421 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2422
2423 (defun js2-print-comment (n i)
2424 ;; We really ought to link end-of-line comments to their nodes.
2425 ;; Or maybe we could add a new comment type, 'endline.
2426 (insert (js2-make-pad i)
2427 (js2-node-string n)))
2428
2429 (defstruct (js2-expr-stmt-node
2430 (:include js2-node)
2431 (:constructor nil)
2432 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2433 (pos js2-ts-cursor)
2434 len
2435 expr)))
2436 "An expression statement."
2437 expr)
2438
2439 (defsubst js2-expr-stmt-node-set-has-result (node)
2440 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2441 (setf (js2-node-type node) js2-EXPR_RESULT))
2442
2443 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2444 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2445
2446 (defun js2-visit-expr-stmt-node (n v)
2447 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2448
2449 (defun js2-print-expr-stmt-node (n indent)
2450 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2451 (insert ";\n"))
2452
2453 (defstruct (js2-loop-node
2454 (:include js2-scope)
2455 (:constructor nil))
2456 "Abstract supertype of loop nodes."
2457 body ; a `js2-block-node'
2458 lp ; position of left-paren, nil if omitted
2459 rp) ; position of right-paren, nil if omitted
2460
2461 (defstruct (js2-do-node
2462 (:include js2-loop-node)
2463 (:constructor nil)
2464 (:constructor make-js2-do-node (&key (type js2-DO)
2465 (pos (js2-current-token-beg))
2466 len
2467 body
2468 condition
2469 while-pos
2470 lp
2471 rp)))
2472 "AST node for do-loop."
2473 condition ; while (expression)
2474 while-pos) ; buffer position of 'while' keyword
2475
2476 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2477 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2478
2479 (defun js2-visit-do-node (n v)
2480 (js2-visit-ast (js2-do-node-body n) v)
2481 (js2-visit-ast (js2-do-node-condition n) v))
2482
2483 (defun js2-print-do-node (n i)
2484 (let ((pad (js2-make-pad i)))
2485 (insert pad "do {\n")
2486 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2487 (js2-print-ast kid (1+ i)))
2488 (insert pad "} while (")
2489 (js2-print-ast (js2-do-node-condition n) 0)
2490 (insert ");\n")))
2491
2492 (defstruct (js2-while-node
2493 (:include js2-loop-node)
2494 (:constructor nil)
2495 (:constructor make-js2-while-node (&key (type js2-WHILE)
2496 (pos (js2-current-token-beg))
2497 len body
2498 condition lp
2499 rp)))
2500 "AST node for while-loop."
2501 condition) ; while-condition
2502
2503 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2504 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2505
2506 (defun js2-visit-while-node (n v)
2507 (js2-visit-ast (js2-while-node-condition n) v)
2508 (js2-visit-ast (js2-while-node-body n) v))
2509
2510 (defun js2-print-while-node (n i)
2511 (let ((pad (js2-make-pad i)))
2512 (insert pad "while (")
2513 (js2-print-ast (js2-while-node-condition n) 0)
2514 (insert ") {\n")
2515 (js2-print-body (js2-while-node-body n) (1+ i))
2516 (insert pad "}\n")))
2517
2518 (defstruct (js2-for-node
2519 (:include js2-loop-node)
2520 (:constructor nil)
2521 (:constructor make-js2-for-node (&key (type js2-FOR)
2522 (pos js2-ts-cursor)
2523 len body init
2524 condition
2525 update lp rp)))
2526 "AST node for a C-style for-loop."
2527 init ; initialization expression
2528 condition ; loop condition
2529 update) ; update clause
2530
2531 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2532 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2533
2534 (defun js2-visit-for-node (n v)
2535 (js2-visit-ast (js2-for-node-init n) v)
2536 (js2-visit-ast (js2-for-node-condition n) v)
2537 (js2-visit-ast (js2-for-node-update n) v)
2538 (js2-visit-ast (js2-for-node-body n) v))
2539
2540 (defun js2-print-for-node (n i)
2541 (let ((pad (js2-make-pad i)))
2542 (insert pad "for (")
2543 (js2-print-ast (js2-for-node-init n) 0)
2544 (insert "; ")
2545 (js2-print-ast (js2-for-node-condition n) 0)
2546 (insert "; ")
2547 (js2-print-ast (js2-for-node-update n) 0)
2548 (insert ") {\n")
2549 (js2-print-body (js2-for-node-body n) (1+ i))
2550 (insert pad "}\n")))
2551
2552 (defstruct (js2-for-in-node
2553 (:include js2-loop-node)
2554 (:constructor nil)
2555 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2556 (pos js2-ts-cursor)
2557 len body
2558 iterator
2559 object
2560 in-pos
2561 each-pos
2562 foreach-p forof-p
2563 lp rp)))
2564 "AST node for a for..in loop."
2565 iterator ; [var] foo in ...
2566 object ; object over which we're iterating
2567 in-pos ; buffer position of 'in' keyword
2568 each-pos ; buffer position of 'each' keyword, if foreach-p
2569 foreach-p ; t if it's a for-each loop
2570 forof-p) ; t if it's a for-of loop
2571
2572 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2573 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2574
2575 (defun js2-visit-for-in-node (n v)
2576 (js2-visit-ast (js2-for-in-node-iterator n) v)
2577 (js2-visit-ast (js2-for-in-node-object n) v)
2578 (js2-visit-ast (js2-for-in-node-body n) v))
2579
2580 (defun js2-print-for-in-node (n i)
2581 (let ((pad (js2-make-pad i))
2582 (foreach (js2-for-in-node-foreach-p n))
2583 (forof (js2-for-in-node-forof-p n)))
2584 (insert pad "for ")
2585 (if foreach
2586 (insert "each "))
2587 (insert "(")
2588 (js2-print-ast (js2-for-in-node-iterator n) 0)
2589 (insert (if forof " of " " in "))
2590 (js2-print-ast (js2-for-in-node-object n) 0)
2591 (insert ") {\n")
2592 (js2-print-body (js2-for-in-node-body n) (1+ i))
2593 (insert pad "}\n")))
2594
2595 (defstruct (js2-return-node
2596 (:include js2-node)
2597 (:constructor nil)
2598 (:constructor make-js2-return-node (&key (type js2-RETURN)
2599 (pos js2-ts-cursor)
2600 len
2601 retval)))
2602 "AST node for a return statement."
2603 retval) ; expression to return, or 'undefined
2604
2605 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2606 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2607
2608 (defun js2-visit-return-node (n v)
2609 (js2-visit-ast (js2-return-node-retval n) v))
2610
2611 (defun js2-print-return-node (n i)
2612 (insert (js2-make-pad i) "return")
2613 (when (js2-return-node-retval n)
2614 (insert " ")
2615 (js2-print-ast (js2-return-node-retval n) 0))
2616 (insert ";\n"))
2617
2618 (defstruct (js2-if-node
2619 (:include js2-node)
2620 (:constructor nil)
2621 (:constructor make-js2-if-node (&key (type js2-IF)
2622 (pos js2-ts-cursor)
2623 len condition
2624 then-part
2625 else-pos
2626 else-part lp
2627 rp)))
2628 "AST node for an if-statement."
2629 condition ; expression
2630 then-part ; statement or block
2631 else-pos ; optional buffer position of 'else' keyword
2632 else-part ; optional statement or block
2633 lp ; position of left-paren, nil if omitted
2634 rp) ; position of right-paren, nil if omitted
2635
2636 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2637 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2638
2639 (defun js2-visit-if-node (n v)
2640 (js2-visit-ast (js2-if-node-condition n) v)
2641 (js2-visit-ast (js2-if-node-then-part n) v)
2642 (js2-visit-ast (js2-if-node-else-part n) v))
2643
2644 (defun js2-print-if-node (n i)
2645 (let ((pad (js2-make-pad i))
2646 (then-part (js2-if-node-then-part n))
2647 (else-part (js2-if-node-else-part n)))
2648 (insert pad "if (")
2649 (js2-print-ast (js2-if-node-condition n) 0)
2650 (insert ") {\n")
2651 (js2-print-body then-part (1+ i))
2652 (insert pad "}")
2653 (cond
2654 ((not else-part)
2655 (insert "\n"))
2656 ((js2-if-node-p else-part)
2657 (insert " else ")
2658 (js2-print-body else-part i))
2659 (t
2660 (insert " else {\n")
2661 (js2-print-body else-part (1+ i))
2662 (insert pad "}\n")))))
2663
2664 (defstruct (js2-try-node
2665 (:include js2-node)
2666 (:constructor nil)
2667 (:constructor make-js2-try-node (&key (type js2-TRY)
2668 (pos js2-ts-cursor)
2669 len
2670 try-block
2671 catch-clauses
2672 finally-block)))
2673 "AST node for a try-statement."
2674 try-block
2675 catch-clauses ; a Lisp list of `js2-catch-node'
2676 finally-block) ; a `js2-finally-node'
2677
2678 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2679 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2680
2681 (defun js2-visit-try-node (n v)
2682 (js2-visit-ast (js2-try-node-try-block n) v)
2683 (dolist (clause (js2-try-node-catch-clauses n))
2684 (js2-visit-ast clause v))
2685 (js2-visit-ast (js2-try-node-finally-block n) v))
2686
2687 (defun js2-print-try-node (n i)
2688 (let ((pad (js2-make-pad i))
2689 (catches (js2-try-node-catch-clauses n))
2690 (finally (js2-try-node-finally-block n)))
2691 (insert pad "try {\n")
2692 (js2-print-body (js2-try-node-try-block n) (1+ i))
2693 (insert pad "}")
2694 (when catches
2695 (dolist (catch catches)
2696 (js2-print-ast catch i)))
2697 (if finally
2698 (js2-print-ast finally i)
2699 (insert "\n"))))
2700
2701 (defstruct (js2-catch-node
2702 (:include js2-node)
2703 (:constructor nil)
2704 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2705 (pos js2-ts-cursor)
2706 len
2707 param
2708 guard-kwd
2709 guard-expr
2710 block lp
2711 rp)))
2712 "AST node for a catch clause."
2713 param ; destructuring form or simple name node
2714 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2715 guard-expr ; catch condition, a `js2-node'
2716 block ; statements, a `js2-block-node'
2717 lp ; buffer position of left-paren, nil if omitted
2718 rp) ; buffer position of right-paren, nil if omitted
2719
2720 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2721 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2722
2723 (defun js2-visit-catch-node (n v)
2724 (js2-visit-ast (js2-catch-node-param n) v)
2725 (when (js2-catch-node-guard-kwd n)
2726 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2727 (js2-visit-ast (js2-catch-node-block n) v))
2728
2729 (defun js2-print-catch-node (n i)
2730 (let ((pad (js2-make-pad i))
2731 (guard-kwd (js2-catch-node-guard-kwd n))
2732 (guard-expr (js2-catch-node-guard-expr n)))
2733 (insert " catch (")
2734 (js2-print-ast (js2-catch-node-param n) 0)
2735 (when guard-kwd
2736 (insert " if ")
2737 (js2-print-ast guard-expr 0))
2738 (insert ") {\n")
2739 (js2-print-body (js2-catch-node-block n) (1+ i))
2740 (insert pad "}")))
2741
2742 (defstruct (js2-finally-node
2743 (:include js2-node)
2744 (:constructor nil)
2745 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2746 (pos js2-ts-cursor)
2747 len body)))
2748 "AST node for a finally clause."
2749 body) ; a `js2-node', often but not always a block node
2750
2751 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2752 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2753
2754 (defun js2-visit-finally-node (n v)
2755 (js2-visit-ast (js2-finally-node-body n) v))
2756
2757 (defun js2-print-finally-node (n i)
2758 (let ((pad (js2-make-pad i)))
2759 (insert " finally {\n")
2760 (js2-print-body (js2-finally-node-body n) (1+ i))
2761 (insert pad "}\n")))
2762
2763 (defstruct (js2-switch-node
2764 (:include js2-node)
2765 (:constructor nil)
2766 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2767 (pos js2-ts-cursor)
2768 len
2769 discriminant
2770 cases lp
2771 rp)))
2772 "AST node for a switch statement."
2773 discriminant ; a `js2-node' (switch expression)
2774 cases ; a Lisp list of `js2-case-node'
2775 lp ; position of open-paren for discriminant, nil if omitted
2776 rp) ; position of close-paren for discriminant, nil if omitted
2777
2778 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2779 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2780
2781 (defun js2-visit-switch-node (n v)
2782 (js2-visit-ast (js2-switch-node-discriminant n) v)
2783 (dolist (c (js2-switch-node-cases n))
2784 (js2-visit-ast c v)))
2785
2786 (defun js2-print-switch-node (n i)
2787 (let ((pad (js2-make-pad i))
2788 (cases (js2-switch-node-cases n)))
2789 (insert pad "switch (")
2790 (js2-print-ast (js2-switch-node-discriminant n) 0)
2791 (insert ") {\n")
2792 (dolist (case cases)
2793 (js2-print-ast case i))
2794 (insert pad "}\n")))
2795
2796 (defstruct (js2-case-node
2797 (:include js2-block-node)
2798 (:constructor nil)
2799 (:constructor make-js2-case-node (&key (type js2-CASE)
2800 (pos js2-ts-cursor)
2801 len kids expr)))
2802 "AST node for a case clause of a switch statement."
2803 expr) ; the case expression (nil for default)
2804
2805 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2806 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2807
2808 (defun js2-visit-case-node (n v)
2809 (js2-visit-ast (js2-case-node-expr n) v)
2810 (js2-visit-block n v))
2811
2812 (defun js2-print-case-node (n i)
2813 (let ((pad (js2-make-pad i))
2814 (expr (js2-case-node-expr n)))
2815 (insert pad)
2816 (if (null expr)
2817 (insert "default:\n")
2818 (insert "case ")
2819 (js2-print-ast expr 0)
2820 (insert ":\n"))
2821 (dolist (kid (js2-case-node-kids n))
2822 (js2-print-ast kid (1+ i)))))
2823
2824 (defstruct (js2-throw-node
2825 (:include js2-node)
2826 (:constructor nil)
2827 (:constructor make-js2-throw-node (&key (type js2-THROW)
2828 (pos js2-ts-cursor)
2829 len expr)))
2830 "AST node for a throw statement."
2831 expr) ; the expression to throw
2832
2833 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2834 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2835
2836 (defun js2-visit-throw-node (n v)
2837 (js2-visit-ast (js2-throw-node-expr n) v))
2838
2839 (defun js2-print-throw-node (n i)
2840 (insert (js2-make-pad i) "throw ")
2841 (js2-print-ast (js2-throw-node-expr n) 0)
2842 (insert ";\n"))
2843
2844 (defstruct (js2-with-node
2845 (:include js2-node)
2846 (:constructor nil)
2847 (:constructor make-js2-with-node (&key (type js2-WITH)
2848 (pos js2-ts-cursor)
2849 len object
2850 body lp rp)))
2851 "AST node for a with-statement."
2852 object
2853 body
2854 lp ; buffer position of left-paren around object, nil if omitted
2855 rp) ; buffer position of right-paren around object, nil if omitted
2856
2857 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2858 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2859
2860 (defun js2-visit-with-node (n v)
2861 (js2-visit-ast (js2-with-node-object n) v)
2862 (js2-visit-ast (js2-with-node-body n) v))
2863
2864 (defun js2-print-with-node (n i)
2865 (let ((pad (js2-make-pad i)))
2866 (insert pad "with (")
2867 (js2-print-ast (js2-with-node-object n) 0)
2868 (insert ") {\n")
2869 (js2-print-body (js2-with-node-body n) (1+ i))
2870 (insert pad "}\n")))
2871
2872 (defstruct (js2-label-node
2873 (:include js2-node)
2874 (:constructor nil)
2875 (:constructor make-js2-label-node (&key (type js2-LABEL)
2876 (pos js2-ts-cursor)
2877 len name)))
2878 "AST node for a statement label or case label."
2879 name ; a string
2880 loop) ; for validating and code-generating continue-to-label
2881
2882 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2883 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2884
2885 (defun js2-print-label (n i)
2886 (insert (js2-make-pad i)
2887 (js2-label-node-name n)
2888 ":\n"))
2889
2890 (defstruct (js2-labeled-stmt-node
2891 (:include js2-node)
2892 (:constructor nil)
2893 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2894 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2895 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2896 (pos js2-ts-cursor)
2897 len labels stmt)))
2898 "AST node for a statement with one or more labels.
2899 Multiple labels for a statement are collapsed into the labels field."
2900 labels ; Lisp list of `js2-label-node'
2901 stmt) ; the statement these labels are for
2902
2903 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2904 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2905
2906 (defun js2-get-label-by-name (lbl-stmt name)
2907 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2908 Returns nil if no such label is in the list."
2909 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2910 result)
2911 (while (and label-list (not result))
2912 (if (string= (js2-label-node-name (car label-list)) name)
2913 (setq result (car label-list))
2914 (setq label-list (cdr label-list))))
2915 result))
2916
2917 (defun js2-visit-labeled-stmt (n v)
2918 (dolist (label (js2-labeled-stmt-node-labels n))
2919 (js2-visit-ast label v))
2920 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2921
2922 (defun js2-print-labeled-stmt (n i)
2923 (dolist (label (js2-labeled-stmt-node-labels n))
2924 (js2-print-ast label i))
2925 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2926
2927 (defun js2-labeled-stmt-node-contains (node label)
2928 "Return t if NODE contains LABEL in its label set.
2929 NODE is a `js2-labels-node'. LABEL is an identifier."
2930 (loop for nl in (js2-labeled-stmt-node-labels node)
2931 if (string= label (js2-label-node-name nl))
2932 return t
2933 finally return nil))
2934
2935 (defsubst js2-labeled-stmt-node-add-label (node label)
2936 "Add a `js2-label-node' to the label set for this statement."
2937 (setf (js2-labeled-stmt-node-labels node)
2938 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2939
2940 (defstruct (js2-jump-node
2941 (:include js2-node)
2942 (:constructor nil))
2943 "Abstract supertype of break and continue nodes."
2944 label ; `js2-name-node' for location of label identifier, if present
2945 target) ; target js2-labels-node or loop/switch statement
2946
2947 (defun js2-visit-jump-node (n v)
2948 ;; We don't visit the target, since it's a back-link.
2949 (js2-visit-ast (js2-jump-node-label n) v))
2950
2951 (defstruct (js2-break-node
2952 (:include js2-jump-node)
2953 (:constructor nil)
2954 (:constructor make-js2-break-node (&key (type js2-BREAK)
2955 (pos js2-ts-cursor)
2956 len label target)))
2957 "AST node for a break statement.
2958 The label field is a `js2-name-node', possibly nil, for the named label
2959 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2960 is the target of the break - a label node or enclosing loop/switch statement.")
2961
2962 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2963 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2964
2965 (defun js2-print-break-node (n i)
2966 (insert (js2-make-pad i) "break")
2967 (when (js2-break-node-label n)
2968 (insert " ")
2969 (js2-print-ast (js2-break-node-label n) 0))
2970 (insert ";\n"))
2971
2972 (defstruct (js2-continue-node
2973 (:include js2-jump-node)
2974 (:constructor nil)
2975 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2976 (pos js2-ts-cursor)
2977 len label target)))
2978 "AST node for a continue statement.
2979 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2980 It is nil if continue specifies no label. The target field is the jump target:
2981 a `js2-label-node' or the innermost enclosing loop.")
2982
2983 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2984 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2985
2986 (defun js2-print-continue-node (n i)
2987 (insert (js2-make-pad i) "continue")
2988 (when (js2-continue-node-label n)
2989 (insert " ")
2990 (js2-print-ast (js2-continue-node-label n) 0))
2991 (insert ";\n"))
2992
2993 (defstruct (js2-function-node
2994 (:include js2-script-node)
2995 (:constructor nil)
2996 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2997 (pos js2-ts-cursor)
2998 len
2999 (ftype 'FUNCTION)
3000 (form 'FUNCTION_STATEMENT)
3001 (name "")
3002 params rest-p
3003 body
3004 generator-type
3005 lp rp)))
3006 "AST node for a function declaration.
3007 The `params' field is a Lisp list of nodes. Each node is either a simple
3008 `js2-name-node', or if it's a destructuring-assignment parameter, a
3009 `js2-array-node' or `js2-object-node'."
3010 ftype ; FUNCTION, GETTER or SETTER
3011 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3012 name ; function name (a `js2-name-node', or nil if anonymous)
3013 params ; a Lisp list of destructuring forms or simple name nodes
3014 rest-p ; if t, the last parameter is rest parameter
3015 body ; a `js2-block-node' or expression node (1.8 only)
3016 lp ; position of arg-list open-paren, or nil if omitted
3017 rp ; position of arg-list close-paren, or nil if omitted
3018 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3019 needs-activation ; t if we need an activation object for this frame
3020 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3021 member-expr) ; nonstandard Ecma extension from Rhino
3022
3023 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3024 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3025
3026 (defun js2-visit-function-node (n v)
3027 (js2-visit-ast (js2-function-node-name n) v)
3028 (dolist (p (js2-function-node-params n))
3029 (js2-visit-ast p v))
3030 (js2-visit-ast (js2-function-node-body n) v))
3031
3032 (defun js2-print-function-node (n i)
3033 (let* ((pad (js2-make-pad i))
3034 (getter (js2-node-get-prop n 'GETTER_SETTER))
3035 (name (or (js2-function-node-name n)
3036 (js2-function-node-member-expr n)))
3037 (params (js2-function-node-params n))
3038 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3039 (rest-p (js2-function-node-rest-p n))
3040 (body (js2-function-node-body n))
3041 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3042 (unless (or getter arrow)
3043 (insert pad "function")
3044 (when (eq (js2-function-node-generator-type n) 'STAR)
3045 (insert "*")))
3046 (when name
3047 (insert " ")
3048 (js2-print-ast name 0))
3049 (insert "(")
3050 (loop with len = (length params)
3051 for param in params
3052 for count from 1
3053 do
3054 (when (and rest-p (= count len))
3055 (insert "..."))
3056 (js2-print-ast param 0)
3057 (when (< count len)
3058 (insert ", ")))
3059 (insert ") ")
3060 (when arrow
3061 (insert "=> "))
3062 (insert "{")
3063 ;; TODO: fix this to be smarter about indenting, etc.
3064 (unless expr
3065 (insert "\n"))
3066 (if (js2-block-node-p body)
3067 (js2-print-body body (1+ i))
3068 (js2-print-ast body 0))
3069 (insert pad "}")
3070 (unless expr
3071 (insert "\n"))))
3072
3073 (defun js2-function-name (node)
3074 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3075 (and (js2-function-node-name node)
3076 (js2-name-node-name (js2-function-node-name node))))
3077
3078 ;; Having this be an expression node makes it more flexible.
3079 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3080 ;; that work better if you assume it's an expression. Whenever we have
3081 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3082 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3083 (defstruct (js2-var-decl-node
3084 (:include js2-node)
3085 (:constructor nil)
3086 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3087 (pos (js2-current-token-beg))
3088 len kids
3089 decl-type)))
3090 "AST node for a variable declaration list (VAR, CONST or LET).
3091 The node bounds differ depending on the declaration type. For VAR or
3092 CONST declarations, the bounds include the var/const keyword. For LET
3093 declarations, the node begins at the position of the first child."
3094 kids ; a Lisp list of `js2-var-init-node' structs.
3095 decl-type) ; js2-VAR, js2-CONST or js2-LET
3096
3097 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3098 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3099
3100 (defun js2-visit-var-decl (n v)
3101 (dolist (kid (js2-var-decl-node-kids n))
3102 (js2-visit-ast kid v)))
3103
3104 (defun js2-print-var-decl (n i)
3105 (let ((pad (js2-make-pad i))
3106 (tt (js2-var-decl-node-decl-type n)))
3107 (insert pad)
3108 (insert (cond
3109 ((= tt js2-VAR) "var ")
3110 ((= tt js2-LET) "let ")
3111 ((= tt js2-CONST) "const ")
3112 (t
3113 (error "malformed var-decl node"))))
3114 (loop with kids = (js2-var-decl-node-kids n)
3115 with len = (length kids)
3116 for kid in kids
3117 for count from 1
3118 do
3119 (js2-print-ast kid 0)
3120 (if (< count len)
3121 (insert ", ")))))
3122
3123 (defstruct (js2-var-init-node
3124 (:include js2-node)
3125 (:constructor nil)
3126 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3127 (pos js2-ts-cursor)
3128 len target
3129 initializer)))
3130 "AST node for a variable declaration.
3131 The type field will be js2-CONST for a const decl."
3132 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3133 initializer) ; initializer expression, a `js2-node'
3134
3135 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3136 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3137
3138 (defun js2-visit-var-init-node (n v)
3139 (js2-visit-ast (js2-var-init-node-target n) v)
3140 (js2-visit-ast (js2-var-init-node-initializer n) v))
3141
3142 (defun js2-print-var-init-node (n i)
3143 (let ((pad (js2-make-pad i))
3144 (name (js2-var-init-node-target n))
3145 (init (js2-var-init-node-initializer n)))
3146 (insert pad)
3147 (js2-print-ast name 0)
3148 (when init
3149 (insert " = ")
3150 (js2-print-ast init 0))))
3151
3152 (defstruct (js2-cond-node
3153 (:include js2-node)
3154 (:constructor nil)
3155 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3156 (pos js2-ts-cursor)
3157 len
3158 test-expr
3159 true-expr
3160 false-expr
3161 q-pos c-pos)))
3162 "AST node for the ternary operator"
3163 test-expr
3164 true-expr
3165 false-expr
3166 q-pos ; buffer position of ?
3167 c-pos) ; buffer position of :
3168
3169 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3170 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3171
3172 (defun js2-visit-cond-node (n v)
3173 (js2-visit-ast (js2-cond-node-test-expr n) v)
3174 (js2-visit-ast (js2-cond-node-true-expr n) v)
3175 (js2-visit-ast (js2-cond-node-false-expr n) v))
3176
3177 (defun js2-print-cond-node (n i)
3178 (let ((pad (js2-make-pad i)))
3179 (insert pad)
3180 (js2-print-ast (js2-cond-node-test-expr n) 0)
3181 (insert " ? ")
3182 (js2-print-ast (js2-cond-node-true-expr n) 0)
3183 (insert " : ")
3184 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3185
3186 (defstruct (js2-infix-node
3187 (:include js2-node)
3188 (:constructor nil)
3189 (:constructor make-js2-infix-node (&key type
3190 (pos js2-ts-cursor)
3191 len op-pos
3192 left right)))
3193 "Represents infix expressions.
3194 Includes assignment ops like `|=', and the comma operator.
3195 The type field inherited from `js2-node' holds the operator."
3196 op-pos ; buffer position where operator begins
3197 left ; any `js2-node'
3198 right) ; any `js2-node'
3199
3200 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3201 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3202
3203 (defun js2-visit-infix-node (n v)
3204 (js2-visit-ast (js2-infix-node-left n) v)
3205 (js2-visit-ast (js2-infix-node-right n) v))
3206
3207 (defconst js2-operator-tokens
3208 (let ((table (make-hash-table :test 'eq))
3209 (tokens
3210 (list (cons js2-IN "in")
3211 (cons js2-TYPEOF "typeof")
3212 (cons js2-INSTANCEOF "instanceof")
3213 (cons js2-DELPROP "delete")
3214 (cons js2-COMMA ",")
3215 (cons js2-COLON ":")
3216 (cons js2-OR "||")
3217 (cons js2-AND "&&")
3218 (cons js2-INC "++")
3219 (cons js2-DEC "--")
3220 (cons js2-BITOR "|")
3221 (cons js2-BITXOR "^")
3222 (cons js2-BITAND "&")
3223 (cons js2-EQ "==")
3224 (cons js2-NE "!=")
3225 (cons js2-LT "<")
3226 (cons js2-LE "<=")
3227 (cons js2-GT ">")
3228 (cons js2-GE ">=")
3229 (cons js2-LSH "<<")
3230 (cons js2-RSH ">>")
3231 (cons js2-URSH ">>>")
3232 (cons js2-ADD "+") ; infix plus
3233 (cons js2-SUB "-") ; infix minus
3234 (cons js2-MUL "*")
3235 (cons js2-DIV "/")
3236 (cons js2-MOD "%")
3237 (cons js2-NOT "!")
3238 (cons js2-BITNOT "~")
3239 (cons js2-POS "+") ; unary plus
3240 (cons js2-NEG "-") ; unary minus
3241 (cons js2-TRIPLEDOT "...")
3242 (cons js2-SHEQ "===") ; shallow equality
3243 (cons js2-SHNE "!==") ; shallow inequality
3244 (cons js2-ASSIGN "=")
3245 (cons js2-ASSIGN_BITOR "|=")
3246 (cons js2-ASSIGN_BITXOR "^=")
3247 (cons js2-ASSIGN_BITAND "&=")
3248 (cons js2-ASSIGN_LSH "<<=")
3249 (cons js2-ASSIGN_RSH ">>=")
3250 (cons js2-ASSIGN_URSH ">>>=")
3251 (cons js2-ASSIGN_ADD "+=")
3252 (cons js2-ASSIGN_SUB "-=")
3253 (cons js2-ASSIGN_MUL "*=")
3254 (cons js2-ASSIGN_DIV "/=")
3255 (cons js2-ASSIGN_MOD "%="))))
3256 (loop for (k . v) in tokens do
3257 (puthash k v table))
3258 table))
3259
3260 (defun js2-print-infix-node (n i)
3261 (let* ((tt (js2-node-type n))
3262 (op (gethash tt js2-operator-tokens)))
3263 (unless op
3264 (error "unrecognized infix operator %s" (js2-node-type n)))
3265 (insert (js2-make-pad i))
3266 (js2-print-ast (js2-infix-node-left n) 0)
3267 (unless (= tt js2-COMMA)
3268 (insert " "))
3269 (insert op)
3270 (insert " ")
3271 (js2-print-ast (js2-infix-node-right n) 0)))
3272
3273 (defstruct (js2-assign-node
3274 (:include js2-infix-node)
3275 (:constructor nil)
3276 (:constructor make-js2-assign-node (&key type
3277 (pos js2-ts-cursor)
3278 len op-pos
3279 left right)))
3280 "Represents any assignment.
3281 The type field holds the actual assignment operator.")
3282
3283 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3284 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3285
3286 (defstruct (js2-unary-node
3287 (:include js2-node)
3288 (:constructor nil)
3289 (:constructor make-js2-unary-node (&key type ; required
3290 (pos js2-ts-cursor)
3291 len operand)))
3292 "AST node type for unary operator nodes.
3293 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3294 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3295 property is added if the operator follows the operand."
3296 operand) ; a `js2-node' expression
3297
3298 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3299 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3300
3301 (defun js2-visit-unary-node (n v)
3302 (js2-visit-ast (js2-unary-node-operand n) v))
3303
3304 (defun js2-print-unary-node (n i)
3305 (let* ((tt (js2-node-type n))
3306 (op (gethash tt js2-operator-tokens))
3307 (postfix (js2-node-get-prop n 'postfix)))
3308 (unless op
3309 (error "unrecognized unary operator %s" tt))
3310 (insert (js2-make-pad i))
3311 (unless postfix
3312 (insert op))
3313 (if (or (= tt js2-TYPEOF)
3314 (= tt js2-DELPROP))
3315 (insert " "))
3316 (js2-print-ast (js2-unary-node-operand n) 0)
3317 (when postfix
3318 (insert op))))
3319
3320 (defstruct (js2-let-node
3321 (:include js2-scope)
3322 (:constructor nil)
3323 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3324 (pos (js2-current-token-beg))
3325 len vars body
3326 lp rp)))
3327 "AST node for a let expression or a let statement.
3328 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3329 vars ; a `js2-var-decl-node'
3330 body ; a `js2-node' representing the expression or body block
3331 lp
3332 rp)
3333
3334 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3335 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3336
3337 (defun js2-visit-let-node (n v)
3338 (js2-visit-ast (js2-let-node-vars n) v)
3339 (js2-visit-ast (js2-let-node-body n) v))
3340
3341 (defun js2-print-let-node (n i)
3342 (insert (js2-make-pad i) "let (")
3343 (let ((p (point)))
3344 (js2-print-ast (js2-let-node-vars n) 0)
3345 (delete-region p (+ p 4)))
3346 (insert ") ")
3347 (js2-print-ast (js2-let-node-body n) i))
3348
3349 (defstruct (js2-keyword-node
3350 (:include js2-node)
3351 (:constructor nil)
3352 (:constructor make-js2-keyword-node (&key type
3353 (pos (js2-current-token-beg))
3354 (len (- js2-ts-cursor pos)))))
3355 "AST node representing a literal keyword such as `null'.
3356 Used for `null', `this', `true', `false' and `debugger'.
3357 The node type is set to js2-NULL, js2-THIS, etc.")
3358
3359 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3360 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3361
3362 (defun js2-print-keyword-node (n i)
3363 (insert (js2-make-pad i)
3364 (let ((tt (js2-node-type n)))
3365 (cond
3366 ((= tt js2-THIS) "this")
3367 ((= tt js2-SUPER) "super")
3368 ((= tt js2-NULL) "null")
3369 ((= tt js2-TRUE) "true")
3370 ((= tt js2-FALSE) "false")
3371 ((= tt js2-DEBUGGER) "debugger")
3372 (t (error "Invalid keyword literal type: %d" tt))))))
3373
3374 (defsubst js2-this-or-super-node-p (node)
3375 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3376 (let ((type (js2-node-type node)))
3377 (or (eq type js2-THIS) (eq type js2-SUPER))))
3378
3379 (defstruct (js2-new-node
3380 (:include js2-node)
3381 (:constructor nil)
3382 (:constructor make-js2-new-node (&key (type js2-NEW)
3383 (pos (js2-current-token-beg))
3384 len target
3385 args initializer
3386 lp rp)))
3387 "AST node for new-expression such as new Foo()."
3388 target ; an identifier or reference
3389 args ; a Lisp list of argument nodes
3390 lp ; position of left-paren, nil if omitted
3391 rp ; position of right-paren, nil if omitted
3392 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3393
3394 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3395 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3396
3397 (defun js2-visit-new-node (n v)
3398 (js2-visit-ast (js2-new-node-target n) v)
3399 (dolist (arg (js2-new-node-args n))
3400 (js2-visit-ast arg v))
3401 (js2-visit-ast (js2-new-node-initializer n) v))
3402
3403 (defun js2-print-new-node (n i)
3404 (insert (js2-make-pad i) "new ")
3405 (js2-print-ast (js2-new-node-target n))
3406 (insert "(")
3407 (js2-print-list (js2-new-node-args n))
3408 (insert ")")
3409 (when (js2-new-node-initializer n)
3410 (insert " ")
3411 (js2-print-ast (js2-new-node-initializer n))))
3412
3413 (defstruct (js2-name-node
3414 (:include js2-node)
3415 (:constructor nil)
3416 (:constructor make-js2-name-node (&key (type js2-NAME)
3417 (pos (js2-current-token-beg))
3418 (len (- js2-ts-cursor
3419 (js2-current-token-beg)))
3420 (name (js2-current-token-string)))))
3421 "AST node for a JavaScript identifier"
3422 name ; a string
3423 scope) ; a `js2-scope' (optional, used for codegen)
3424
3425 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3426 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3427
3428 (defun js2-print-name-node (n i)
3429 (insert (js2-make-pad i)
3430 (js2-name-node-name n)))
3431
3432 (defsubst js2-name-node-length (node)
3433 "Return identifier length of NODE, a `js2-name-node'.
3434 Returns 0 if NODE is nil or its identifier field is nil."
3435 (if node
3436 (length (js2-name-node-name node))
3437 0))
3438
3439 (defstruct (js2-number-node
3440 (:include js2-node)
3441 (:constructor nil)
3442 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3443 (pos (js2-current-token-beg))
3444 (len (- js2-ts-cursor
3445 (js2-current-token-beg)))
3446 (value (js2-current-token-string))
3447 (num-value (js2-token-number
3448 (js2-current-token))))))
3449 "AST node for a number literal."
3450 value ; the original string, e.g. "6.02e23"
3451 num-value) ; the parsed number value
3452
3453 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3454 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3455
3456 (defun js2-print-number-node (n i)
3457 (insert (js2-make-pad i)
3458 (number-to-string (js2-number-node-num-value n))))
3459
3460 (defstruct (js2-regexp-node
3461 (:include js2-node)
3462 (:constructor nil)
3463 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3464 (pos (js2-current-token-beg))
3465 (len (- js2-ts-cursor
3466 (js2-current-token-beg)))
3467 value flags)))
3468 "AST node for a regular expression literal."
3469 value ; the regexp string, without // delimiters
3470 flags) ; a string of flags, e.g. `mi'.
3471
3472 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3473 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3474
3475 (defun js2-print-regexp (n i)
3476 (insert (js2-make-pad i)
3477 "/"
3478 (js2-regexp-node-value n)
3479 "/")
3480 (if (js2-regexp-node-flags n)
3481 (insert (js2-regexp-node-flags n))))
3482
3483 (defstruct (js2-string-node
3484 (:include js2-node)
3485 (:constructor nil)
3486 (:constructor make-js2-string-node (&key (type js2-STRING)
3487 (pos (js2-current-token-beg))
3488 (len (- js2-ts-cursor
3489 (js2-current-token-beg)))
3490 (value (js2-current-token-string)))))
3491 "String literal.
3492 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3493 You can tell the quote type by looking at the first character."
3494 value) ; the characters of the string, including the quotes
3495
3496 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3497 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3498
3499 (defun js2-print-string-node (n i)
3500 (insert (js2-make-pad i)
3501 (js2-node-string n)))
3502
3503 (defstruct (js2-template-node
3504 (:include js2-node)
3505 (:constructor nil)
3506 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3507 beg len kids)))
3508 "Template literal."
3509 kids) ; `js2-string-node' is used for string segments, other nodes
3510 ; for substitutions inside.
3511
3512 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3513 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3514
3515 (defun js2-visit-template (n callback)
3516 (dolist (kid (js2-template-node-kids n))
3517 (js2-visit-ast kid callback)))
3518
3519 (defun js2-print-template (n i)
3520 (insert (js2-make-pad i))
3521 (dolist (kid (js2-template-node-kids n))
3522 (if (js2-string-node-p kid)
3523 (insert (js2-node-string kid))
3524 (js2-print-ast kid))))
3525
3526 (defstruct (js2-tagged-template-node
3527 (:include js2-node)
3528 (:constructor nil)
3529 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3530 beg len tag template)))
3531 "Tagged template literal."
3532 tag ; `js2-node' with the tag expression.
3533 template) ; `js2-template-node' with the template.
3534
3535 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3536 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3537
3538 (defun js2-visit-tagged-template (n callback)
3539 (js2-visit-ast (js2-tagged-template-node-tag n) kid callback)
3540 (js2-visit-ast (js2-tagged-template-node-template n) kid callback))
3541
3542 (defun js2-print-tagged-template (n i)
3543 (insert (js2-make-pad i))
3544 (js2-print-ast (js2-tagged-template-node-tag n))
3545 (js2-print-ast (js2-tagged-template-node-template n)))
3546
3547 (defstruct (js2-array-node
3548 (:include js2-node)
3549 (:constructor nil)
3550 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3551 (pos js2-ts-cursor)
3552 len elems)))
3553 "AST node for an array literal."
3554 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3555
3556 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3557 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3558
3559 (defun js2-visit-array-node (n v)
3560 (dolist (e (js2-array-node-elems n))
3561 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3562
3563 (defun js2-print-array-node (n i)
3564 (insert (js2-make-pad i) "[")
3565 (let ((elems (js2-array-node-elems n)))
3566 (js2-print-list elems)
3567 (when (and elems (null (car (last elems))))
3568 (insert ",")))
3569 (insert "]"))
3570
3571 (defstruct (js2-class-node
3572 (:include js2-node)
3573 (:constructor nil)
3574 (:constructor make-js2-class-node (&key (type js2-CLASS)
3575 (pos js2-ts-cursor)
3576 (form 'CLASS_STATEMENT)
3577 (name "")
3578 extends len elems)))
3579 "AST node for an class expression.
3580 `elems' is a list of `js2-object-prop-node', and `extends' is an
3581 optional `js2-expr-node'"
3582 form ; CLASS_{STATEMENT|EXPRESSION}
3583 name ; class name (a `js2-node-name', or nil if anonymous)
3584 extends ; class heritage (a `js2-expr-node', or nil if none)
3585 elems)
3586
3587 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3588 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3589
3590 (defun js2-visit-class-node (n v)
3591 (js2-visit-ast (js2-class-node-name n) v)
3592 (js2-visit-ast (js2-class-node-extends n) v)
3593 (dolist (e (js2-class-node-elems n))
3594 (js2-visit-ast e v)))
3595
3596 (defun js2-print-class-node (n i)
3597 (let* ((pad (js2-make-pad i))
3598 (name (js2-class-node-name n))
3599 (extends (js2-class-node-extends n))
3600 (elems (js2-class-node-elems n)))
3601 (insert pad "class")
3602 (when name
3603 (insert " ")
3604 (js2-print-ast name 0))
3605 (when extends
3606 (insert " extends ")
3607 (js2-print-ast extends))
3608 (insert " {")
3609 (dolist (elem elems)
3610 (insert "\n")
3611 (if (js2-node-get-prop elem 'STATIC)
3612 (progn (insert (js2-make-pad (1+ i)) "static ")
3613 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3614 (js2-print-ast elem (1+ i))))
3615 (insert "\n" pad "}")))
3616
3617 (defstruct (js2-object-node
3618 (:include js2-node)
3619 (:constructor nil)
3620 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3621 (pos js2-ts-cursor)
3622 len
3623 elems)))
3624 "AST node for an object literal expression.
3625 `elems' is a list of `js2-object-prop-node'."
3626 elems)
3627
3628 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3629 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3630
3631 (defun js2-visit-object-node (n v)
3632 (dolist (e (js2-object-node-elems n))
3633 (js2-visit-ast e v)))
3634
3635 (defun js2-print-object-node (n i)
3636 (insert (js2-make-pad i) "{")
3637 (js2-print-list (js2-object-node-elems n))
3638 (insert "}"))
3639
3640 (defstruct (js2-object-prop-node
3641 (:include js2-infix-node)
3642 (:constructor nil)
3643 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3644 (pos js2-ts-cursor)
3645 len left
3646 right op-pos)))
3647 "AST node for an object literal prop:value entry.
3648 The `left' field is the property: a name node, string node or number node.
3649 The `right' field is a `js2-node' representing the initializer value.
3650 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3651 and both fields have the same value.")
3652
3653 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3654 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3655
3656 (defun js2-print-object-prop-node (n i)
3657 (let* ((left (js2-object-prop-node-left n))
3658 (computed (not (or (js2-string-node-p left)
3659 (js2-number-node-p left)
3660 (js2-name-node-p left)))))
3661 (insert (js2-make-pad i))
3662 (if computed
3663 (insert "["))
3664 (js2-print-ast left 0)
3665 (if computed
3666 (insert "]"))
3667 (if (not (js2-node-get-prop n 'SHORTHAND))
3668 (progn
3669 (insert ": ")
3670 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3671
3672 (defstruct (js2-getter-setter-node
3673 (:include js2-infix-node)
3674 (:constructor nil)
3675 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3676 (pos js2-ts-cursor)
3677 len left right)))
3678 "AST node for a getter/setter property in an object literal.
3679 The `left' field is the `js2-name-node' naming the getter/setter prop.
3680 The `right' field is always an anonymous `js2-function-node' with a node
3681 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3682
3683 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3684 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3685
3686 (defun js2-print-getter-setter (n i)
3687 (let ((pad (js2-make-pad i))
3688 (left (js2-getter-setter-node-left n))
3689 (right (js2-getter-setter-node-right n)))
3690 (insert pad)
3691 (if (/= (js2-node-type n) js2-FUNCTION)
3692 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3693 (js2-print-ast left 0)
3694 (js2-print-ast right 0)))
3695
3696 (defstruct (js2-prop-get-node
3697 (:include js2-infix-node)
3698 (:constructor nil)
3699 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3700 (pos js2-ts-cursor)
3701 len left right)))
3702 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3703
3704 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3705 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3706
3707 (defun js2-visit-prop-get-node (n v)
3708 (js2-visit-ast (js2-prop-get-node-left n) v)
3709 (js2-visit-ast (js2-prop-get-node-right n) v))
3710
3711 (defun js2-print-prop-get-node (n i)
3712 (insert (js2-make-pad i))
3713 (js2-print-ast (js2-prop-get-node-left n) 0)
3714 (insert ".")
3715 (js2-print-ast (js2-prop-get-node-right n) 0))
3716
3717 (defstruct (js2-elem-get-node
3718 (:include js2-node)
3719 (:constructor nil)
3720 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3721 (pos js2-ts-cursor)
3722 len target element
3723 lb rb)))
3724 "AST node for an array index expression such as foo[bar]."
3725 target ; a `js2-node' - the expression preceding the "."
3726 element ; a `js2-node' - the expression in brackets
3727 lb ; position of left-bracket, nil if omitted
3728 rb) ; position of right-bracket, nil if omitted
3729
3730 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3731 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3732
3733 (defun js2-visit-elem-get-node (n v)
3734 (js2-visit-ast (js2-elem-get-node-target n) v)
3735 (js2-visit-ast (js2-elem-get-node-element n) v))
3736
3737 (defun js2-print-elem-get-node (n i)
3738 (insert (js2-make-pad i))
3739 (js2-print-ast (js2-elem-get-node-target n) 0)
3740 (insert "[")
3741 (js2-print-ast (js2-elem-get-node-element n) 0)
3742 (insert "]"))
3743
3744 (defstruct (js2-call-node
3745 (:include js2-node)
3746 (:constructor nil)
3747 (:constructor make-js2-call-node (&key (type js2-CALL)
3748 (pos js2-ts-cursor)
3749 len target args
3750 lp rp)))
3751 "AST node for a JavaScript function call."
3752 target ; a `js2-node' evaluating to the function to call
3753 args ; a Lisp list of `js2-node' arguments
3754 lp ; position of open-paren, or nil if missing
3755 rp) ; position of close-paren, or nil if missing
3756
3757 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3758 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3759
3760 (defun js2-visit-call-node (n v)
3761 (js2-visit-ast (js2-call-node-target n) v)
3762 (dolist (arg (js2-call-node-args n))
3763 (js2-visit-ast arg v)))
3764
3765 (defun js2-print-call-node (n i)
3766 (insert (js2-make-pad i))
3767 (js2-print-ast (js2-call-node-target n) 0)
3768 (insert "(")
3769 (js2-print-list (js2-call-node-args n))
3770 (insert ")"))
3771
3772 (defstruct (js2-yield-node
3773 (:include js2-node)
3774 (:constructor nil)
3775 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3776 (pos js2-ts-cursor)
3777 len value star-p)))
3778 "AST node for yield statement or expression."
3779 star-p ; whether it's yield*
3780 value) ; optional: value to be yielded
3781
3782 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3783 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3784
3785 (defun js2-visit-yield-node (n v)
3786 (js2-visit-ast (js2-yield-node-value n) v))
3787
3788 (defun js2-print-yield-node (n i)
3789 (insert (js2-make-pad i))
3790 (insert "yield")
3791 (when (js2-yield-node-star-p n)
3792 (insert "*"))
3793 (when (js2-yield-node-value n)
3794 (insert " ")
3795 (js2-print-ast (js2-yield-node-value n) 0)))
3796
3797 (defstruct (js2-paren-node
3798 (:include js2-node)
3799 (:constructor nil)
3800 (:constructor make-js2-paren-node (&key (type js2-LP)
3801 (pos js2-ts-cursor)
3802 len expr)))
3803 "AST node for a parenthesized expression.
3804 In particular, used when the parens are syntactically optional,
3805 as opposed to required parens such as those enclosing an if-conditional."
3806 expr) ; `js2-node'
3807
3808 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3809 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3810
3811 (defun js2-visit-paren-node (n v)
3812 (js2-visit-ast (js2-paren-node-expr n) v))
3813
3814 (defun js2-print-paren-node (n i)
3815 (insert (js2-make-pad i))
3816 (insert "(")
3817 (js2-print-ast (js2-paren-node-expr n) 0)
3818 (insert ")"))
3819
3820 (defstruct (js2-comp-node
3821 (:include js2-scope)
3822 (:constructor nil)
3823 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3824 (pos js2-ts-cursor)
3825 len result
3826 loops filters
3827 form)))
3828 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3829 result ; result expression (just after left-bracket)
3830 loops ; a Lisp list of `js2-comp-loop-node'
3831 filters ; a Lisp list of guard/filter expressions
3832 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3833 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3834 )
3835
3836 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3837 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3838
3839 (defun js2-visit-comp-node (n v)
3840 (js2-visit-ast (js2-comp-node-result n) v)
3841 (dolist (l (js2-comp-node-loops n))
3842 (js2-visit-ast l v))
3843 (dolist (f (js2-comp-node-filters n))
3844 (js2-visit-ast f v)))
3845
3846 (defun js2-print-comp-node (n i)
3847 (let ((pad (js2-make-pad i))
3848 (result (js2-comp-node-result n))
3849 (loops (js2-comp-node-loops n))
3850 (filters (js2-comp-node-filters n))
3851 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3852 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3853 (insert pad (if gen-p "(" "["))
3854 (when legacy-p
3855 (js2-print-ast result 0))
3856 (dolist (l loops)
3857 (when legacy-p
3858 (insert " "))
3859 (js2-print-ast l 0)
3860 (unless legacy-p
3861 (insert " ")))
3862 (dolist (f filters)
3863 (when legacy-p
3864 (insert " "))
3865 (insert "if (")
3866 (js2-print-ast f 0)
3867 (insert ")")
3868 (unless legacy-p
3869 (insert " ")))
3870 (unless legacy-p
3871 (js2-print-ast result 0))
3872 (insert (if gen-p ")" "]"))))
3873
3874 (defstruct (js2-comp-loop-node
3875 (:include js2-for-in-node)
3876 (:constructor nil)
3877 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3878 (pos js2-ts-cursor)
3879 len iterator
3880 object in-pos
3881 foreach-p
3882 each-pos
3883 forof-p
3884 lp rp)))
3885 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3886
3887 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3888 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3889
3890 (defun js2-visit-comp-loop (n v)
3891 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3892 (js2-visit-ast (js2-comp-loop-node-object n) v))
3893
3894 (defun js2-print-comp-loop (n _i)
3895 (insert "for ")
3896 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3897 (insert "(")
3898 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3899 (insert (if (js2-comp-loop-node-forof-p n)
3900 " of " " in "))
3901 (js2-print-ast (js2-comp-loop-node-object n) 0)
3902 (insert ")"))
3903
3904 (defstruct (js2-empty-expr-node
3905 (:include js2-node)
3906 (:constructor nil)
3907 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3908 (pos (js2-current-token-beg))
3909 len)))
3910 "AST node for an empty expression.")
3911
3912 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3913 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3914
3915 (defstruct (js2-xml-node
3916 (:include js2-block-node)
3917 (:constructor nil)
3918 (:constructor make-js2-xml-node (&key (type js2-XML)
3919 (pos (js2-current-token-beg))
3920 len kids)))
3921 "AST node for initial parse of E4X literals.
3922 The kids field is a list of XML fragments, each a `js2-string-node' or
3923 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3924
3925 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3926 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3927
3928 (defun js2-print-xml-node (n i)
3929 (dolist (kid (js2-xml-node-kids n))
3930 (js2-print-ast kid i)))
3931
3932 (defstruct (js2-xml-js-expr-node
3933 (:include js2-xml-node)
3934 (:constructor nil)
3935 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3936 (pos js2-ts-cursor)
3937 len expr)))
3938 "AST node for an embedded JavaScript {expression} in an E4X literal.
3939 The start and end fields correspond to the curly-braces."
3940 expr) ; a `js2-expr-node' of some sort
3941
3942 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3943 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3944
3945 (defun js2-visit-xml-js-expr (n v)
3946 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3947
3948 (defun js2-print-xml-js-expr (n i)
3949 (insert (js2-make-pad i))
3950 (insert "{")
3951 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3952 (insert "}"))
3953
3954 (defstruct (js2-xml-dot-query-node
3955 (:include js2-infix-node)
3956 (:constructor nil)
3957 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3958 (pos js2-ts-cursor)
3959 op-pos len left
3960 right rp)))
3961 "AST node for an E4X foo.(bar) filter expression.
3962 Note that the left-paren is automatically the character immediately
3963 following the dot (.) in the operator. No whitespace is permitted
3964 between the dot and the lp by the scanner."
3965 rp)
3966
3967 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3968 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3969
3970 (defun js2-print-xml-dot-query (n i)
3971 (insert (js2-make-pad i))
3972 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3973 (insert ".(")
3974 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3975 (insert ")"))
3976
3977 (defstruct (js2-xml-ref-node
3978 (:include js2-node)
3979 (:constructor nil)) ; abstract
3980 "Base type for E4X XML attribute-access or property-get expressions.
3981 Such expressions can take a variety of forms. The general syntax has
3982 three parts:
3983
3984 - (optional) an @ (specifying an attribute access)
3985 - (optional) a namespace (a `js2-name-node') and double-colon
3986 - (required) either a `js2-name-node' or a bracketed [expression]
3987
3988 The property-name expressions (examples: ns::name, @name) are
3989 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3990 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3991
3992 This node type (or more specifically, its subclasses) will sometimes
3993 be the right-hand child of a `js2-prop-get-node' or a
3994 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3995 The `js2-xml-ref-node' may also be a standalone primary expression with
3996 no explicit target, which is valid in certain expression contexts such as
3997
3998 company..employee.(@id < 100)
3999
4000 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4001 expression whose parent is a `js2-xml-dot-query-node'."
4002 namespace
4003 at-pos
4004 colon-pos)
4005
4006 (defsubst js2-xml-ref-node-attr-access-p (node)
4007 "Return non-nil if this expression began with an @-token."
4008 (and (numberp (js2-xml-ref-node-at-pos node))
4009 (plusp (js2-xml-ref-node-at-pos node))))
4010
4011 (defstruct (js2-xml-prop-ref-node
4012 (:include js2-xml-ref-node)
4013 (:constructor nil)
4014 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4015 (pos (js2-current-token-beg))
4016 len propname
4017 namespace at-pos
4018 colon-pos)))
4019 "AST node for an E4X XML [expr] property-ref expression.
4020 The JavaScript syntax is an optional @, an optional ns::, and a name.
4021
4022 [ '@' ] [ name '::' ] name
4023
4024 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4025 @ns::*, @*::attr, @*::*, and @*.
4026
4027 The node starts at the @ token, if present. Otherwise it starts at the
4028 namespace name. The node bounds extend through the closing right-bracket,
4029 or if it is missing due to a syntax error, through the end of the index
4030 expression."
4031 propname)
4032
4033 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4034 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4035
4036 (defun js2-visit-xml-prop-ref-node (n v)
4037 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4038 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4039
4040 (defun js2-print-xml-prop-ref-node (n i)
4041 (insert (js2-make-pad i))
4042 (if (js2-xml-ref-node-attr-access-p n)
4043 (insert "@"))
4044 (when (js2-xml-prop-ref-node-namespace n)
4045 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4046 (insert "::"))
4047 (if (js2-xml-prop-ref-node-propname n)
4048 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4049
4050 (defstruct (js2-xml-elem-ref-node
4051 (:include js2-xml-ref-node)
4052 (:constructor nil)
4053 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4054 (pos (js2-current-token-beg))
4055 len expr lb rb
4056 namespace at-pos
4057 colon-pos)))
4058 "AST node for an E4X XML [expr] member-ref expression.
4059 Syntax:
4060
4061 [ '@' ] [ name '::' ] '[' expr ']'
4062
4063 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4064
4065 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4066 is not a legal E4X XML element-ref expression, since it's already used
4067 for standard JavaScript element-get array indexing. Hence, a
4068 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4069 non-nil namespace node, or both.
4070
4071 The node starts at the @ token, if present. Otherwise it starts
4072 at the namespace name. The node bounds extend through the closing
4073 right-bracket, or if it is missing due to a syntax error, through the
4074 end of the index expression."
4075 expr ; the bracketed index expression
4076 lb
4077 rb)
4078
4079 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4080 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4081
4082 (defun js2-visit-xml-elem-ref-node (n v)
4083 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4084 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4085
4086 (defun js2-print-xml-elem-ref-node (n i)
4087 (insert (js2-make-pad i))
4088 (if (js2-xml-ref-node-attr-access-p n)
4089 (insert "@"))
4090 (when (js2-xml-elem-ref-node-namespace n)
4091 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4092 (insert "::"))
4093 (insert "[")
4094 (if (js2-xml-elem-ref-node-expr n)
4095 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4096 (insert "]"))
4097
4098 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4099
4100 (defstruct (js2-xml-start-tag-node
4101 (:include js2-xml-node)
4102 (:constructor nil)
4103 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4104 (pos js2-ts-cursor)
4105 len name attrs kids
4106 empty-p)))
4107 "AST node for an XML start-tag. Not currently used.
4108 The `kids' field is a Lisp list of child content nodes."
4109 name ; a `js2-xml-name-node'
4110 attrs ; a Lisp list of `js2-xml-attr-node'
4111 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4112
4113 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4114 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4115
4116 (defun js2-visit-xml-start-tag (n v)
4117 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4118 (dolist (attr (js2-xml-start-tag-node-attrs n))
4119 (js2-visit-ast attr v))
4120 (js2-visit-block n v))
4121
4122 (defun js2-print-xml-start-tag (n i)
4123 (insert (js2-make-pad i) "<")
4124 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4125 (when (js2-xml-start-tag-node-attrs n)
4126 (insert " ")
4127 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4128 (insert ">"))
4129
4130 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4131 ;; and add the end-tag to the kids list of the parent as well.
4132 (defstruct (js2-xml-end-tag-node
4133 (:include js2-xml-node)
4134 (:constructor nil)
4135 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4136 (pos js2-ts-cursor)
4137 len name)))
4138 "AST node for an XML end-tag. Not currently used."
4139 name) ; a `js2-xml-name-node'
4140
4141 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4142 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4143
4144 (defun js2-visit-xml-end-tag (n v)
4145 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4146
4147 (defun js2-print-xml-end-tag (n i)
4148 (insert (js2-make-pad i))
4149 (insert "</")
4150 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4151 (insert ">"))
4152
4153 (defstruct (js2-xml-name-node
4154 (:include js2-xml-node)
4155 (:constructor nil)
4156 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4157 (pos js2-ts-cursor)
4158 len namespace kids)))
4159 "AST node for an E4X XML name. Not currently used.
4160 Any XML name can be qualified with a namespace, hence the namespace field.
4161 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4162 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4163 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4164 namespace) ; a `js2-string-node'
4165
4166 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4167 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4168
4169 (defun js2-visit-xml-name-node (n v)
4170 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4171
4172 (defun js2-print-xml-name-node (n i)
4173 (insert (js2-make-pad i))
4174 (when (js2-xml-name-node-namespace n)
4175 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4176 (insert "::"))
4177 (dolist (kid (js2-xml-name-node-kids n))
4178 (js2-print-ast kid 0)))
4179
4180 (defstruct (js2-xml-pi-node
4181 (:include js2-xml-node)
4182 (:constructor nil)
4183 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4184 (pos js2-ts-cursor)
4185 len name attrs)))
4186 "AST node for an E4X XML processing instruction. Not currently used."
4187 name ; a `js2-xml-name-node'
4188 attrs) ; a list of `js2-xml-attr-node'
4189
4190 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4191 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4192
4193 (defun js2-visit-xml-pi-node (n v)
4194 (js2-visit-ast (js2-xml-pi-node-name n) v)
4195 (dolist (attr (js2-xml-pi-node-attrs n))
4196 (js2-visit-ast attr v)))
4197
4198 (defun js2-print-xml-pi-node (n i)
4199 (insert (js2-make-pad i) "<?")
4200 (js2-print-ast (js2-xml-pi-node-name n))
4201 (when (js2-xml-pi-node-attrs n)
4202 (insert " ")
4203 (js2-print-list (js2-xml-pi-node-attrs n)))
4204 (insert "?>"))
4205
4206 (defstruct (js2-xml-cdata-node
4207 (:include js2-xml-node)
4208 (:constructor nil)
4209 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4210 (pos js2-ts-cursor)
4211 len content)))
4212 "AST node for a CDATA escape section. Not currently used."
4213 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4214
4215 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4216 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4217
4218 (defun js2-visit-xml-cdata-node (n v)
4219 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4220
4221 (defun js2-print-xml-cdata-node (n i)
4222 (insert (js2-make-pad i))
4223 (js2-print-ast (js2-xml-cdata-node-content n)))
4224
4225 (defstruct (js2-xml-attr-node
4226 (:include js2-xml-node)
4227 (:constructor nil)
4228 (:constructor make-js2-attr-node (&key (type js2-XML)
4229 (pos js2-ts-cursor)
4230 len name value
4231 eq-pos quote-type)))
4232 "AST node representing a foo='bar' XML attribute value. Not yet used."
4233 name ; a `js2-xml-name-node'
4234 value ; a `js2-xml-name-node'
4235 eq-pos ; buffer position of "=" sign
4236 quote-type) ; 'single or 'double
4237
4238 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4239 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4240
4241 (defun js2-visit-xml-attr-node (n v)
4242 (js2-visit-ast (js2-xml-attr-node-name n) v)
4243 (js2-visit-ast (js2-xml-attr-node-value n) v))
4244
4245 (defun js2-print-xml-attr-node (n i)
4246 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4247 "'"
4248 "\"")))
4249 (insert (js2-make-pad i))
4250 (js2-print-ast (js2-xml-attr-node-name n) 0)
4251 (insert "=" quote)
4252 (js2-print-ast (js2-xml-attr-node-value n) 0)
4253 (insert quote)))
4254
4255 (defstruct (js2-xml-text-node
4256 (:include js2-xml-node)
4257 (:constructor nil)
4258 (:constructor make-js2-text-node (&key (type js2-XML)
4259 (pos js2-ts-cursor)
4260 len content)))
4261 "AST node for an E4X XML text node. Not currently used."
4262 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4263
4264 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4265 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4266
4267 (defun js2-visit-xml-text-node (n v)
4268 (js2-visit-ast (js2-xml-text-node-content n) v))
4269
4270 (defun js2-print-xml-text-node (n i)
4271 (insert (js2-make-pad i))
4272 (dolist (kid (js2-xml-text-node-content n))
4273 (js2-print-ast kid)))
4274
4275 (defstruct (js2-xml-comment-node
4276 (:include js2-xml-node)
4277 (:constructor nil)
4278 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4279 (pos js2-ts-cursor)
4280 len)))
4281 "AST node for E4X XML comment. Not currently used.")
4282
4283 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4284 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4285
4286 (defun js2-print-xml-comment (n i)
4287 (insert (js2-make-pad i)
4288 (js2-node-string n)))
4289
4290 ;;; Node utilities
4291
4292 (defsubst js2-node-line (n)
4293 "Fetch the source line number at the start of node N.
4294 This is O(n) in the length of the source buffer; use prudently."
4295 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4296
4297 (defsubst js2-block-node-kid (n i)
4298 "Return child I of node N, or nil if there aren't that many."
4299 (nth i (js2-block-node-kids n)))
4300
4301 (defsubst js2-block-node-first (n)
4302 "Return first child of block node N, or nil if there is none."
4303 (first (js2-block-node-kids n)))
4304
4305 (defun js2-node-root (n)
4306 "Return the root of the AST containing N.
4307 If N has no parent pointer, returns N."
4308 (let ((parent (js2-node-parent n)))
4309 (if parent
4310 (js2-node-root parent)
4311 n)))
4312
4313 (defsubst js2-node-short-name (n)
4314 "Return the short name of node N as a string, e.g. `js2-if-node'."
4315 (substring (symbol-name (aref n 0))
4316 (length "cl-struct-")))
4317
4318 (defun js2-node-child-list (node)
4319 "Return the child list for NODE, a Lisp list of nodes.
4320 Works for block nodes, array nodes, obj literals, funarg lists,
4321 var decls and try nodes (for catch clauses). Note that you should call
4322 `js2-block-node-kids' on the function body for the body statements.
4323 Returns nil for zero-length child lists or unsupported nodes."
4324 (cond
4325 ((js2-function-node-p node)
4326 (js2-function-node-params node))
4327 ((js2-block-node-p node)
4328 (js2-block-node-kids node))
4329 ((js2-try-node-p node)
4330 (js2-try-node-catch-clauses node))
4331 ((js2-array-node-p node)
4332 (js2-array-node-elems node))
4333 ((js2-object-node-p node)
4334 (js2-object-node-elems node))
4335 ((js2-call-node-p node)
4336 (js2-call-node-args node))
4337 ((js2-new-node-p node)
4338 (js2-new-node-args node))
4339 ((js2-var-decl-node-p node)
4340 (js2-var-decl-node-kids node))
4341 (t
4342 nil)))
4343
4344 (defun js2-node-set-child-list (node kids)
4345 "Set the child list for NODE to KIDS."
4346 (cond
4347 ((js2-function-node-p node)
4348 (setf (js2-function-node-params node) kids))
4349 ((js2-block-node-p node)
4350 (setf (js2-block-node-kids node) kids))
4351 ((js2-try-node-p node)
4352 (setf (js2-try-node-catch-clauses node) kids))
4353 ((js2-array-node-p node)
4354 (setf (js2-array-node-elems node) kids))
4355 ((js2-object-node-p node)
4356 (setf (js2-object-node-elems node) kids))
4357 ((js2-call-node-p node)
4358 (setf (js2-call-node-args node) kids))
4359 ((js2-new-node-p node)
4360 (setf (js2-new-node-args node) kids))
4361 ((js2-var-decl-node-p node)
4362 (setf (js2-var-decl-node-kids node) kids))
4363 (t
4364 (error "Unsupported node type: %s" (js2-node-short-name node))))
4365 kids)
4366
4367 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4368 (defconst js2-paren-expr-nodes
4369 '(cl-struct-js2-comp-loop-node
4370 cl-struct-js2-comp-node
4371 cl-struct-js2-call-node
4372 cl-struct-js2-catch-node
4373 cl-struct-js2-do-node
4374 cl-struct-js2-elem-get-node
4375 cl-struct-js2-for-in-node
4376 cl-struct-js2-for-node
4377 cl-struct-js2-function-node
4378 cl-struct-js2-if-node
4379 cl-struct-js2-let-node
4380 cl-struct-js2-new-node
4381 cl-struct-js2-paren-node
4382 cl-struct-js2-switch-node
4383 cl-struct-js2-while-node
4384 cl-struct-js2-with-node
4385 cl-struct-js2-xml-dot-query-node)
4386 "Node types that can have a parenthesized child expression.
4387 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4388
4389 (defsubst js2-paren-expr-node-p (node)
4390 "Return t for nodes that typically have a parenthesized child expression.
4391 Useful for computing the indentation anchors for arg-lists and conditions.
4392 Note that it may return a false positive, for instance when NODE is
4393 a `js2-new-node' and there are no arguments or parentheses."
4394 (memq (aref node 0) js2-paren-expr-nodes))
4395
4396 ;; Fake polymorphism... yech.
4397 (defun js2-node-lp (node)
4398 "Return relative left-paren position for NODE, if applicable.
4399 For `js2-elem-get-node' structs, returns left-bracket position.
4400 Note that the position may be nil in the case of a parse error."
4401 (cond
4402 ((js2-elem-get-node-p node)
4403 (js2-elem-get-node-lb node))
4404 ((js2-loop-node-p node)
4405 (js2-loop-node-lp node))
4406 ((js2-function-node-p node)
4407 (js2-function-node-lp node))
4408 ((js2-if-node-p node)
4409 (js2-if-node-lp node))
4410 ((js2-new-node-p node)
4411 (js2-new-node-lp node))
4412 ((js2-call-node-p node)
4413 (js2-call-node-lp node))
4414 ((js2-paren-node-p node)
4415 0)
4416 ((js2-switch-node-p node)
4417 (js2-switch-node-lp node))
4418 ((js2-catch-node-p node)
4419 (js2-catch-node-lp node))
4420 ((js2-let-node-p node)
4421 (js2-let-node-lp node))
4422 ((js2-comp-node-p node)
4423 0)
4424 ((js2-with-node-p node)
4425 (js2-with-node-lp node))
4426 ((js2-xml-dot-query-node-p node)
4427 (1+ (js2-infix-node-op-pos node)))
4428 (t
4429 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4430
4431 ;; Fake polymorphism... blech.
4432 (defun js2-node-rp (node)
4433 "Return relative right-paren position for NODE, if applicable.
4434 For `js2-elem-get-node' structs, returns right-bracket position.
4435 Note that the position may be nil in the case of a parse error."
4436 (cond
4437 ((js2-elem-get-node-p node)
4438 (js2-elem-get-node-rb node))
4439 ((js2-loop-node-p node)
4440 (js2-loop-node-rp node))
4441 ((js2-function-node-p node)
4442 (js2-function-node-rp node))
4443 ((js2-if-node-p node)
4444 (js2-if-node-rp node))
4445 ((js2-new-node-p node)
4446 (js2-new-node-rp node))
4447 ((js2-call-node-p node)
4448 (js2-call-node-rp node))
4449 ((js2-paren-node-p node)
4450 (1- (js2-node-len node)))
4451 ((js2-switch-node-p node)
4452 (js2-switch-node-rp node))
4453 ((js2-catch-node-p node)
4454 (js2-catch-node-rp node))
4455 ((js2-let-node-p node)
4456 (js2-let-node-rp node))
4457 ((js2-comp-node-p node)
4458 (1- (js2-node-len node)))
4459 ((js2-with-node-p node)
4460 (js2-with-node-rp node))
4461 ((js2-xml-dot-query-node-p node)
4462 (1+ (js2-xml-dot-query-node-rp node)))
4463 (t
4464 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4465
4466 (defsubst js2-node-first-child (node)
4467 "Return the first element of `js2-node-child-list' for NODE."
4468 (car (js2-node-child-list node)))
4469
4470 (defsubst js2-node-last-child (node)
4471 "Return the last element of `js2-node-last-child' for NODE."
4472 (car (last (js2-node-child-list node))))
4473
4474 (defun js2-node-prev-sibling (node)
4475 "Return the previous statement in parent.
4476 Works for parents supported by `js2-node-child-list'.
4477 Returns nil if NODE is not in the parent, or PARENT is
4478 not a supported node, or if NODE is the first child."
4479 (let* ((p (js2-node-parent node))
4480 (kids (js2-node-child-list p))
4481 (sib (car kids)))
4482 (while (and kids
4483 (not (eq node (cadr kids))))
4484 (setq kids (cdr kids)
4485 sib (car kids)))
4486 sib))
4487
4488 (defun js2-node-next-sibling (node)
4489 "Return the next statement in parent block.
4490 Returns nil if NODE is not in the block, or PARENT is not
4491 a block node, or if NODE is the last statement."
4492 (let* ((p (js2-node-parent node))
4493 (kids (js2-node-child-list p)))
4494 (while (and kids
4495 (not (eq node (car kids))))
4496 (setq kids (cdr kids)))
4497 (cadr kids)))
4498
4499 (defun js2-node-find-child-before (pos parent &optional after)
4500 "Find the last child that starts before POS in parent.
4501 If AFTER is non-nil, returns first child starting after POS.
4502 POS is an absolute buffer position. PARENT is any node
4503 supported by `js2-node-child-list'.
4504 Returns nil if no applicable child is found."
4505 (let ((kids (if (js2-function-node-p parent)
4506 (js2-block-node-kids (js2-function-node-body parent))
4507 (js2-node-child-list parent)))
4508 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4509 (js2-function-node-body parent)
4510 parent)))
4511 kid result fn
4512 (continue t))
4513 (setq fn (if after '>= '<))
4514 (while (and kids continue)
4515 (setq kid (car kids))
4516 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4517 (setq result kid
4518 continue (not after))
4519 (setq continue after))
4520 (setq kids (cdr kids)))
4521 result))
4522
4523 (defun js2-node-find-child-after (pos parent)
4524 "Find first child that starts after POS in parent.
4525 POS is an absolute buffer position. PARENT is any node
4526 supported by `js2-node-child-list'.
4527 Returns nil if no applicable child is found."
4528 (js2-node-find-child-before pos parent 'after))
4529
4530 (defun js2-node-replace-child (pos parent new-node)
4531 "Replace node at index POS in PARENT with NEW-NODE.
4532 Only works for parents supported by `js2-node-child-list'."
4533 (let ((kids (js2-node-child-list parent))
4534 (i 0))
4535 (while (< i pos)
4536 (setq kids (cdr kids)
4537 i (1+ i)))
4538 (setcar kids new-node)
4539 (js2-node-add-children parent new-node)))
4540
4541 (defun js2-node-buffer (n)
4542 "Return the buffer associated with AST N.
4543 Returns nil if the buffer is not set as a property on the root
4544 node, or if parent links were not recorded during parsing."
4545 (let ((root (js2-node-root n)))
4546 (and root
4547 (js2-ast-root-p root)
4548 (js2-ast-root-buffer root))))
4549
4550 (defun js2-block-node-push (n kid)
4551 "Push js2-node KID onto the end of js2-block-node N's child list.
4552 KID is always added to the -end- of the kids list.
4553 Function also calls `js2-node-add-children' to add the parent link."
4554 (let ((kids (js2-node-child-list n)))
4555 (if kids
4556 (setcdr kids (nconc (cdr kids) (list kid)))
4557 (js2-node-set-child-list n (list kid)))
4558 (js2-node-add-children n kid)))
4559
4560 (defun js2-node-string (node)
4561 (with-current-buffer (or (js2-node-buffer node)
4562 (error "No buffer available for node %s" node))
4563 (let ((pos (js2-node-abs-pos node)))
4564 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4565
4566 ;; Container for storing the node we're looking for in a traversal.
4567 (js2-deflocal js2-discovered-node nil)
4568
4569 ;; Keep track of absolute node position during traversals.
4570 (js2-deflocal js2-visitor-offset nil)
4571
4572 (js2-deflocal js2-node-search-point nil)
4573
4574 (when js2-mode-dev-mode-p
4575 (defun js2-find-node-at-point ()
4576 (interactive)
4577 (let ((node (js2-node-at-point)))
4578 (message "%s" (or node "No node found at point"))))
4579 (defun js2-node-name-at-point ()
4580 (interactive)
4581 (let ((node (js2-node-at-point)))
4582 (message "%s" (if node
4583 (js2-node-short-name node)
4584 "No node found at point.")))))
4585
4586 (defun js2-node-at-point (&optional pos skip-comments)
4587 "Return AST node at POS, a buffer position, defaulting to current point.
4588 The `js2-mode-ast' variable must be set to the current parse tree.
4589 Signals an error if the AST (`js2-mode-ast') is nil.
4590 Always returns a node - if it can't find one, it returns the root.
4591 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4592 (let ((ast js2-mode-ast)
4593 result)
4594 (unless ast
4595 (error "No JavaScript AST available"))
4596 ;; Look through comments first, since they may be inside nodes that
4597 ;; would otherwise report a match.
4598 (setq pos (or pos (point))
4599 result (if (> pos (js2-node-abs-end ast))
4600 ast
4601 (if (not skip-comments)
4602 (js2-comment-at-point pos))))
4603 (unless result
4604 (setq js2-discovered-node nil
4605 js2-visitor-offset 0
4606 js2-node-search-point pos)
4607 (unwind-protect
4608 (catch 'js2-visit-done
4609 (js2-visit-ast ast #'js2-node-at-point-visitor))
4610 (setq js2-visitor-offset nil
4611 js2-node-search-point nil))
4612 (setq result js2-discovered-node))
4613 ;; may have found a comment beyond end of last child node,
4614 ;; since visiting the ast-root looks at the comment-list last.
4615 (if (and skip-comments
4616 (js2-comment-node-p result))
4617 (setq result nil))
4618 (or result js2-mode-ast)))
4619
4620 (defun js2-node-at-point-visitor (node end-p)
4621 (let ((rel-pos (js2-node-pos node))
4622 abs-pos
4623 abs-end
4624 (point js2-node-search-point))
4625 (cond
4626 (end-p
4627 ;; this evaluates to a non-nil return value, even if it's zero
4628 (decf js2-visitor-offset rel-pos))
4629 ;; we already looked for comments before visiting, and don't want them now
4630 ((js2-comment-node-p node)
4631 nil)
4632 (t
4633 (setq abs-pos (incf js2-visitor-offset rel-pos)
4634 ;; we only want to use the node if the point is before
4635 ;; the last character position in the node, so we decrement
4636 ;; the absolute end by 1.
4637 abs-end (+ abs-pos (js2-node-len node) -1))
4638 (cond
4639 ;; If this node starts after search-point, stop the search.
4640 ((> abs-pos point)
4641 (throw 'js2-visit-done nil))
4642 ;; If this node ends before the search-point, don't check kids.
4643 ((> point abs-end)
4644 nil)
4645 (t
4646 ;; Otherwise point is within this node, possibly in a child.
4647 (setq js2-discovered-node node)
4648 t)))))) ; keep processing kids to look for more specific match
4649
4650 (defsubst js2-block-comment-p (node)
4651 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4652 (and (js2-comment-node-p node)
4653 (memq (js2-comment-node-format node) '(jsdoc block))))
4654
4655 ;; TODO: put the comments in a vector and binary-search them instead
4656 (defun js2-comment-at-point (&optional pos)
4657 "Look through scanned comment nodes for one containing POS.
4658 POS is a buffer position that defaults to current point.
4659 Function returns nil if POS was not in any comment node."
4660 (let ((ast js2-mode-ast)
4661 (x (or pos (point)))
4662 beg end)
4663 (unless ast
4664 (error "No JavaScript AST available"))
4665 (catch 'done
4666 ;; Comments are stored in lexical order.
4667 (dolist (comment (js2-ast-root-comments ast) nil)
4668 (setq beg (js2-node-abs-pos comment)
4669 end (+ beg (js2-node-len comment)))
4670 (if (and (>= x beg)
4671 (<= x end))
4672 (throw 'done comment))))))
4673
4674 (defun js2-mode-find-parent-fn (node)
4675 "Find function enclosing NODE.
4676 Returns nil if NODE is not inside a function."
4677 (setq node (js2-node-parent node))
4678 (while (and node (not (js2-function-node-p node)))
4679 (setq node (js2-node-parent node)))
4680 (and (js2-function-node-p node) node))
4681
4682 (defun js2-mode-find-enclosing-fn (node)
4683 "Find function or root enclosing NODE."
4684 (if (js2-ast-root-p node)
4685 node
4686 (setq node (js2-node-parent node))
4687 (while (not (or (js2-ast-root-p node)
4688 (js2-function-node-p node)))
4689 (setq node (js2-node-parent node)))
4690 node))
4691
4692 (defun js2-mode-find-enclosing-node (beg end)
4693 "Find node fully enclosing BEG and END."
4694 (let ((node (js2-node-at-point beg))
4695 pos
4696 (continue t))
4697 (while continue
4698 (if (or (js2-ast-root-p node)
4699 (and
4700 (<= (setq pos (js2-node-abs-pos node)) beg)
4701 (>= (+ pos (js2-node-len node)) end)))
4702 (setq continue nil)
4703 (setq node (js2-node-parent node))))
4704 node))
4705
4706 (defun js2-node-parent-script-or-fn (node)
4707 "Find script or function immediately enclosing NODE.
4708 If NODE is the ast-root, returns nil."
4709 (if (js2-ast-root-p node)
4710 nil
4711 (setq node (js2-node-parent node))
4712 (while (and node (not (or (js2-function-node-p node)
4713 (js2-script-node-p node))))
4714 (setq node (js2-node-parent node)))
4715 node))
4716
4717 (defun js2-node-is-descendant (node ancestor)
4718 "Return t if NODE is a descendant of ANCESTOR."
4719 (while (and node
4720 (not (eq node ancestor)))
4721 (setq node (js2-node-parent node)))
4722 node)
4723
4724 ;;; visitor infrastructure
4725
4726 (defun js2-visit-none (_node _callback)
4727 "Visitor for AST node that have no node children."
4728 nil)
4729
4730 (defun js2-print-none (_node _indent)
4731 "Visitor for AST node with no printed representation.")
4732
4733 (defun js2-print-body (node indent)
4734 "Print a statement, or a block without braces."
4735 (if (js2-block-node-p node)
4736 (dolist (kid (js2-block-node-kids node))
4737 (js2-print-ast kid indent))
4738 (js2-print-ast node indent)))
4739
4740 (defun js2-print-list (args &optional delimiter)
4741 (loop with len = (length args)
4742 for arg in args
4743 for count from 1
4744 do
4745 (when arg (js2-print-ast arg 0))
4746 (if (< count len)
4747 (insert (or delimiter ", ")))))
4748
4749 (defun js2-print-tree (ast)
4750 "Prints an AST to the current buffer.
4751 Makes `js2-ast-parent-nodes' available to the printer functions."
4752 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4753 (js2-print-ast ast)))
4754
4755 (defun js2-print-ast (node &optional indent)
4756 "Helper function for printing AST nodes.
4757 Requires `js2-ast-parent-nodes' to be non-nil.
4758 You should use `js2-print-tree' instead of this function."
4759 (let ((printer (get (aref node 0) 'js2-printer))
4760 (i (or indent 0)))
4761 ;; TODO: wedge comments in here somewhere
4762 (if printer
4763 (funcall printer node i))))
4764
4765 (defconst js2-side-effecting-tokens
4766 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4767 (dolist (tt (list js2-ASSIGN
4768 js2-ASSIGN_ADD
4769 js2-ASSIGN_BITAND
4770 js2-ASSIGN_BITOR
4771 js2-ASSIGN_BITXOR
4772 js2-ASSIGN_DIV
4773 js2-ASSIGN_LSH
4774 js2-ASSIGN_MOD
4775 js2-ASSIGN_MUL
4776 js2-ASSIGN_RSH
4777 js2-ASSIGN_SUB
4778 js2-ASSIGN_URSH
4779 js2-BLOCK
4780 js2-BREAK
4781 js2-CALL
4782 js2-CATCH
4783 js2-CATCH_SCOPE
4784 js2-CLASS
4785 js2-CONST
4786 js2-CONTINUE
4787 js2-DEBUGGER
4788 js2-DEC
4789 js2-DELPROP
4790 js2-DEL_REF
4791 js2-DO
4792 js2-ELSE
4793 js2-EMPTY
4794 js2-ENTERWITH
4795 js2-EXPORT
4796 js2-EXPR_RESULT
4797 js2-FINALLY
4798 js2-FOR
4799 js2-FUNCTION
4800 js2-GOTO
4801 js2-IF
4802 js2-IFEQ
4803 js2-IFNE
4804 js2-IMPORT
4805 js2-INC
4806 js2-JSR
4807 js2-LABEL
4808 js2-LEAVEWITH
4809 js2-LET
4810 js2-LETEXPR
4811 js2-LOCAL_BLOCK
4812 js2-LOOP
4813 js2-NEW
4814 js2-REF_CALL
4815 js2-RETHROW
4816 js2-RETURN
4817 js2-RETURN_RESULT
4818 js2-SEMI
4819 js2-SETELEM
4820 js2-SETELEM_OP
4821 js2-SETNAME
4822 js2-SETPROP
4823 js2-SETPROP_OP
4824 js2-SETVAR
4825 js2-SET_REF
4826 js2-SET_REF_OP
4827 js2-SWITCH
4828 js2-TARGET
4829 js2-THROW
4830 js2-TRY
4831 js2-VAR
4832 js2-WHILE
4833 js2-WITH
4834 js2-WITHEXPR
4835 js2-YIELD))
4836 (aset tokens tt t))
4837 (if js2-instanceof-has-side-effects
4838 (aset tokens js2-INSTANCEOF t))
4839 tokens))
4840
4841 (defun js2-node-has-side-effects (node)
4842 "Return t if NODE has side effects."
4843 (when node ; makes it easier to handle malformed expressions
4844 (let ((tt (js2-node-type node)))
4845 (cond
4846 ;; This doubtless needs some work, since EXPR_VOID is used
4847 ;; in several ways in Rhino and I may not have caught them all.
4848 ;; I'll wait for people to notice incorrect warnings.
4849 ((and (= tt js2-EXPR_VOID)
4850 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4851 (let ((expr (js2-expr-stmt-node-expr node)))
4852 (or (js2-node-has-side-effects expr)
4853 (when (js2-string-node-p expr)
4854 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4855 ((= tt js2-COMMA)
4856 (js2-node-has-side-effects (js2-infix-node-right node)))
4857 ((or (= tt js2-AND)
4858 (= tt js2-OR))
4859 (or (js2-node-has-side-effects (js2-infix-node-right node))
4860 (js2-node-has-side-effects (js2-infix-node-left node))))
4861 ((= tt js2-HOOK)
4862 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4863 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4864 ((js2-paren-node-p node)
4865 (js2-node-has-side-effects (js2-paren-node-expr node)))
4866 ((= tt js2-ERROR) ; avoid cascaded error messages
4867 nil)
4868 (t
4869 (aref js2-side-effecting-tokens tt))))))
4870
4871 (defconst js2-stmt-node-types
4872 (list js2-BLOCK
4873 js2-BREAK
4874 js2-CONTINUE
4875 js2-DEFAULT ; e4x "default xml namespace" statement
4876 js2-DO
4877 js2-EXPR_RESULT
4878 js2-EXPR_VOID
4879 js2-FOR
4880 js2-IF
4881 js2-RETURN
4882 js2-SWITCH
4883 js2-THROW
4884 js2-TRY
4885 js2-WHILE
4886 js2-WITH)
4887 "Node types that only appear in statement contexts.
4888 The list does not include nodes that always appear as the child
4889 of another specific statement type, such as switch-cases,
4890 catch and finally blocks, and else-clauses. The list also excludes
4891 nodes like yield, let and var, which may appear in either expression
4892 or statement context, and in the latter context always have a
4893 `js2-expr-stmt-node' parent. Finally, the list does not include
4894 functions or scripts, which are treated separately from statements
4895 by the JavaScript parser and runtime.")
4896
4897 (defun js2-stmt-node-p (node)
4898 "Heuristic for figuring out if NODE is a statement.
4899 Some node types can appear in either an expression context or a
4900 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4901 For these node types in a statement context, the parent will be a
4902 `js2-expr-stmt-node'.
4903 Functions aren't included in the check."
4904 (memq (js2-node-type node) js2-stmt-node-types))
4905
4906 (defun js2-mode-find-first-stmt (node)
4907 "Search upward starting from NODE looking for a statement.
4908 For purposes of this function, a `js2-function-node' counts."
4909 (while (not (or (js2-stmt-node-p node)
4910 (js2-function-node-p node)))
4911 (setq node (js2-node-parent node)))
4912 node)
4913
4914 (defun js2-node-parent-stmt (node)
4915 "Return the node's first ancestor that is a statement.
4916 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4917 appearing in a statement context will have a parent that is a
4918 `js2-expr-stmt-node' that will be returned by this function."
4919 (let ((parent (js2-node-parent node)))
4920 (if (or (null parent)
4921 (js2-stmt-node-p parent)
4922 (and (js2-function-node-p parent)
4923 (not (eq (js2-function-node-form parent)
4924 'FUNCTION_EXPRESSION))))
4925 parent
4926 (js2-node-parent-stmt parent))))
4927
4928 ;; In the Mozilla Rhino sources, Roshan James writes:
4929 ;; Does consistent-return analysis on the function body when strict mode is
4930 ;; enabled.
4931 ;;
4932 ;; function (x) { return (x+1) }
4933 ;;
4934 ;; is ok, but
4935 ;;
4936 ;; function (x) { if (x < 0) return (x+1); }
4937 ;;
4938 ;; is not because the function can potentially return a value when the
4939 ;; condition is satisfied and if not, the function does not explicitly
4940 ;; return a value.
4941 ;;
4942 ;; This extends to checking mismatches such as "return" and "return <value>"
4943 ;; used in the same function. Warnings are not emitted if inconsistent
4944 ;; returns exist in code that can be statically shown to be unreachable.
4945 ;; Ex.
4946 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4947 ;;
4948 ;; emits no warning. However if the loop had a break statement, then a
4949 ;; warning would be emitted.
4950 ;;
4951 ;; The consistency analysis looks at control structures such as loops, ifs,
4952 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4953 ;; warns the user about an inconsistent set of termination possibilities.
4954 ;;
4955 ;; These flags enumerate the possible ways a statement/function can
4956 ;; terminate. These flags are used by endCheck() and by the Parser to
4957 ;; detect inconsistent return usage.
4958 ;;
4959 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4960 ;; able to execute (example: throw, continue)
4961 ;;
4962 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4963 ;; next one. Statement such as return dont. A compound statement may have
4964 ;; some branch that drops off control to the next statement.
4965 ;;
4966 ;; END_RETURNS indicates that the statement can return with no value.
4967 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4968 ;;
4969 ;; A compound statement such as
4970 ;; if (condition) {
4971 ;; return value;
4972 ;; }
4973 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4974
4975 (defconst js2-END_UNREACHED 0)
4976 (defconst js2-END_DROPS_OFF 1)
4977 (defconst js2-END_RETURNS 2)
4978 (defconst js2-END_RETURNS_VALUE 4)
4979 (defconst js2-END_YIELDS 8)
4980
4981 (defun js2-has-consistent-return-usage (node)
4982 "Check that every return usage in a function body is consistent.
4983 Returns t if the function satisfies strict mode requirement."
4984 (let ((n (js2-end-check node)))
4985 ;; either it doesn't return a value in any branch...
4986 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4987 ;; or it returns a value (or is unreached) at every branch
4988 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4989 js2-END_RETURNS
4990 js2-END_YIELDS)))))
4991
4992 (defun js2-end-check-if (node)
4993 "Ensure that return usage in then/else blocks is consistent.
4994 If there is no else block, then the return statement can fall through.
4995 Returns logical OR of END_* flags"
4996 (let ((th (js2-if-node-then-part node))
4997 (el (js2-if-node-else-part node)))
4998 (if (null th)
4999 js2-END_UNREACHED
5000 (logior (js2-end-check th) (if el
5001 (js2-end-check el)
5002 js2-END_DROPS_OFF)))))
5003
5004 (defun js2-end-check-switch (node)
5005 "Consistency of return statements is checked between the case statements.
5006 If there is no default, then the switch can fall through. If there is a
5007 default, we check to see if all code paths in the default return or if
5008 there is a code path that can fall through.
5009 Returns logical OR of END_* flags."
5010 (let ((rv js2-END_UNREACHED)
5011 default-case)
5012 ;; examine the cases
5013 (catch 'break
5014 (dolist (c (js2-switch-node-cases node))
5015 (if (js2-case-node-expr c)
5016 (js2-set-flag rv (js2-end-check-block c))
5017 (setq default-case c)
5018 (throw 'break nil))))
5019 ;; we don't care how the cases drop into each other
5020 (js2-clear-flag rv js2-END_DROPS_OFF)
5021 ;; examine the default
5022 (js2-set-flag rv (if default-case
5023 (js2-end-check default-case)
5024 js2-END_DROPS_OFF))
5025 rv))
5026
5027 (defun js2-end-check-try (node)
5028 "If the block has a finally, return consistency is checked in the
5029 finally block. If all code paths in the finally return, then the
5030 returns in the try-catch blocks don't matter. If there is a code path
5031 that does not return or if there is no finally block, the returns
5032 of the try and catch blocks are checked for mismatch.
5033 Returns logical OR of END_* flags."
5034 (let ((finally (js2-try-node-finally-block node))
5035 rv)
5036 ;; check the finally if it exists
5037 (setq rv (if finally
5038 (js2-end-check (js2-finally-node-body finally))
5039 js2-END_DROPS_OFF))
5040 ;; If the finally block always returns, then none of the returns
5041 ;; in the try or catch blocks matter.
5042 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5043 (js2-clear-flag rv js2-END_DROPS_OFF)
5044 ;; examine the try block
5045 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5046 ;; check each catch block
5047 (dolist (cb (js2-try-node-catch-clauses node))
5048 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5049 rv))
5050
5051 (defun js2-end-check-loop (node)
5052 "Return statement in the loop body must be consistent.
5053 The default assumption for any kind of a loop is that it will eventually
5054 terminate. The only exception is a loop with a constant true condition.
5055 Code that follows such a loop is examined only if one can determine
5056 statically that there is a break out of the loop.
5057
5058 for(... ; ... ; ...) {}
5059 for(... in ... ) {}
5060 while(...) { }
5061 do { } while(...)
5062
5063 Returns logical OR of END_* flags."
5064 (let ((rv (js2-end-check (js2-loop-node-body node)))
5065 (condition (cond
5066 ((js2-while-node-p node)
5067 (js2-while-node-condition node))
5068 ((js2-do-node-p node)
5069 (js2-do-node-condition node))
5070 ((js2-for-node-p node)
5071 (js2-for-node-condition node)))))
5072
5073 ;; check to see if the loop condition is always true
5074 (if (and condition
5075 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5076 (js2-clear-flag rv js2-END_DROPS_OFF))
5077
5078 ;; look for effect of breaks
5079 (js2-set-flag rv (js2-node-get-prop node
5080 'CONTROL_BLOCK_PROP
5081 js2-END_UNREACHED))
5082 rv))
5083
5084 (defun js2-end-check-block (node)
5085 "A general block of code is examined statement by statement.
5086 If any statement (even a compound one) returns in all branches, then
5087 subsequent statements are not examined.
5088 Returns logical OR of END_* flags."
5089 (let* ((rv js2-END_DROPS_OFF)
5090 (kids (js2-block-node-kids node))
5091 (n (car kids)))
5092 ;; Check each statment. If the statement can continue onto the next
5093 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5094 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5095 (js2-clear-flag rv js2-END_DROPS_OFF)
5096 (js2-set-flag rv (js2-end-check n))
5097 (setq kids (cdr kids)
5098 n (car kids)))
5099 rv))
5100
5101 (defun js2-end-check-label (node)
5102 "A labeled statement implies that there may be a break to the label.
5103 The function processes the labeled statement and then checks the
5104 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5105 particular label.
5106 Returns logical OR of END_* flags."
5107 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5108 (logior rv (js2-node-get-prop node
5109 'CONTROL_BLOCK_PROP
5110 js2-END_UNREACHED))))
5111
5112 (defun js2-end-check-break (node)
5113 "When a break is encountered annotate the statement being broken
5114 out of by setting its CONTROL_BLOCK_PROP property.
5115 Returns logical OR of END_* flags."
5116 (and (js2-break-node-target node)
5117 (js2-node-set-prop (js2-break-node-target node)
5118 'CONTROL_BLOCK_PROP
5119 js2-END_DROPS_OFF))
5120 js2-END_UNREACHED)
5121
5122 (defun js2-end-check (node)
5123 "Examine the body of a function, doing a basic reachability analysis.
5124 Returns a combination of flags END_* flags that indicate
5125 how the function execution can terminate. These constitute only the
5126 pessimistic set of termination conditions. It is possible that at
5127 runtime certain code paths will never be actually taken. Hence this
5128 analysis will flag errors in cases where there may not be errors.
5129 Returns logical OR of END_* flags"
5130 (let (kid)
5131 (cond
5132 ((js2-break-node-p node)
5133 (js2-end-check-break node))
5134 ((js2-expr-stmt-node-p node)
5135 (if (setq kid (js2-expr-stmt-node-expr node))
5136 (js2-end-check kid)
5137 js2-END_DROPS_OFF))
5138 ((or (js2-continue-node-p node)
5139 (js2-throw-node-p node))
5140 js2-END_UNREACHED)
5141 ((js2-return-node-p node)
5142 (if (setq kid (js2-return-node-retval node))
5143 js2-END_RETURNS_VALUE
5144 js2-END_RETURNS))
5145 ((js2-loop-node-p node)
5146 (js2-end-check-loop node))
5147 ((js2-switch-node-p node)
5148 (js2-end-check-switch node))
5149 ((js2-labeled-stmt-node-p node)
5150 (js2-end-check-label node))
5151 ((js2-if-node-p node)
5152 (js2-end-check-if node))
5153 ((js2-try-node-p node)
5154 (js2-end-check-try node))
5155 ((js2-block-node-p node)
5156 (if (null (js2-block-node-kids node))
5157 js2-END_DROPS_OFF
5158 (js2-end-check-block node)))
5159 ((js2-yield-node-p node)
5160 js2-END_YIELDS)
5161 (t
5162 js2-END_DROPS_OFF))))
5163
5164 (defun js2-always-defined-boolean-p (node)
5165 "Check if NODE always evaluates to true or false in boolean context.
5166 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5167 nor always false."
5168 (let ((tt (js2-node-type node))
5169 num)
5170 (cond
5171 ((or (= tt js2-FALSE) (= tt js2-NULL))
5172 'ALWAYS_FALSE)
5173 ((= tt js2-TRUE)
5174 'ALWAYS_TRUE)
5175 ((= tt js2-NUMBER)
5176 (setq num (js2-number-node-num-value node))
5177 (if (and (not (eq num 0.0e+NaN))
5178 (not (zerop num)))
5179 'ALWAYS_TRUE
5180 'ALWAYS_FALSE))
5181 (t
5182 nil))))
5183
5184 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5185 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5186
5187 (defvar js2-tokens nil
5188 "List of all defined token names.") ; initialized in `js2-token-names'
5189
5190 (defconst js2-token-names
5191 (let* ((names (make-vector js2-num-tokens -1))
5192 (case-fold-search nil) ; only match js2-UPPER_CASE
5193 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5194 (loop for sym in syms
5195 for i from 0
5196 do
5197 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5198 (not (boundp sym)))
5199 (aset names (symbol-value sym) ; code, e.g. 152
5200 (downcase
5201 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5202 (push sym js2-tokens)))
5203 names)
5204 "Vector mapping int values to token string names, sans `js2-' prefix.")
5205
5206 (defun js2-tt-name (tok)
5207 "Return a string name for TOK, a token symbol or code.
5208 Signals an error if it's not a recognized token."
5209 (let ((code tok))
5210 (if (symbolp tok)
5211 (setq code (symbol-value tok)))
5212 (if (eq code -1)
5213 "ERROR"
5214 (if (and (numberp code)
5215 (not (minusp code))
5216 (< code js2-num-tokens))
5217 (aref js2-token-names code)
5218 (error "Invalid token: %s" code)))))
5219
5220 (defsubst js2-tt-sym (tok)
5221 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5222 (intern (js2-tt-name tok)))
5223
5224 (defconst js2-token-codes
5225 (let ((table (make-hash-table :test 'eq :size 256)))
5226 (loop for name across js2-token-names
5227 for sym = (intern (concat "js2-" (upcase name)))
5228 do
5229 (puthash sym (symbol-value sym) table))
5230 ;; clean up a few that are "wrong" in Rhino's token codes
5231 (puthash 'js2-DELETE js2-DELPROP table)
5232 table)
5233 "Hashtable mapping token type symbols to their bytecodes.")
5234
5235 (defsubst js2-tt-code (sym)
5236 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5237 (or (gethash sym js2-token-codes)
5238 (error "Invalid token symbol: %s " sym))) ; signal code bug
5239
5240 (defun js2-report-scan-error (msg &optional no-throw beg len)
5241 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5242 (js2-report-error msg nil
5243 (or beg (js2-current-token-beg))
5244 (or len (js2-current-token-len)))
5245 (unless no-throw
5246 (throw 'return js2-ERROR)))
5247
5248 (defun js2-set-string-from-buffer (token)
5249 "Set `string' and `end' slots for TOKEN, return the string."
5250 (setf (js2-token-end token) js2-ts-cursor
5251 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5252
5253 ;; TODO: could potentially avoid a lot of consing by allocating a
5254 ;; char buffer the way Rhino does.
5255 (defsubst js2-add-to-string (c)
5256 (push c js2-ts-string-buffer))
5257
5258 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5259 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5260 ;; any other character: when it's not part of the current token, we
5261 ;; unget it, allowing it to be read again by the following call.
5262 (defsubst js2-unget-char ()
5263 (decf js2-ts-cursor))
5264
5265 ;; Rhino distinguishes \r and \n line endings. We don't need to
5266 ;; because we only scan from Emacs buffers, which always use \n.
5267 (defun js2-get-char ()
5268 "Read and return the next character from the input buffer.
5269 Increments `js2-ts-lineno' if the return value is a newline char.
5270 Updates `js2-ts-cursor' to the point after the returned char.
5271 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5272 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5273 (let (c)
5274 ;; check for end of buffer
5275 (if (>= js2-ts-cursor (point-max))
5276 (setq js2-ts-hit-eof t
5277 js2-ts-cursor (1+ js2-ts-cursor)
5278 c js2-EOF_CHAR) ; return value
5279 ;; otherwise read next char
5280 (setq c (char-before (incf js2-ts-cursor)))
5281 ;; if we read a newline, update counters
5282 (if (= c ?\n)
5283 (setq js2-ts-line-start js2-ts-cursor
5284 js2-ts-lineno (1+ js2-ts-lineno)))
5285 ;; TODO: skip over format characters
5286 c)))
5287
5288 (defun js2-read-unicode-escape ()
5289 "Read a \\uNNNN sequence from the input.
5290 Assumes the ?\ and ?u have already been read.
5291 Returns the unicode character, or nil if it wasn't a valid character.
5292 Doesn't change the values of any scanner variables."
5293 ;; I really wish I knew a better way to do this, but I can't
5294 ;; find the Emacs function that takes a 16-bit int and converts
5295 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5296 ;; Have to first check that it's 4 hex characters or it may stop
5297 ;; the read early.
5298 (ignore-errors
5299 (let ((s (buffer-substring-no-properties js2-ts-cursor
5300 (+ 4 js2-ts-cursor))))
5301 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5302 (read (concat "?\\u" s))))))
5303
5304 (defun js2-match-char (test)
5305 "Consume and return next character if it matches TEST, a character.
5306 Returns nil and consumes nothing if TEST is not the next character."
5307 (let ((c (js2-get-char)))
5308 (if (eq c test)
5309 t
5310 (js2-unget-char)
5311 nil)))
5312
5313 (defun js2-peek-char ()
5314 (prog1
5315 (js2-get-char)
5316 (js2-unget-char)))
5317
5318 (defun js2-identifier-start-p (c)
5319 "Is C a valid start to an ES5 Identifier?
5320 See http://es5.github.io/#x7.6"
5321 (or
5322 (memq c '(?$ ?_))
5323 (memq (get-char-code-property c 'general-category)
5324 ;; Letters
5325 '(Lu Ll Lt Lm Lo Nl))))
5326
5327 (defun js2-identifier-part-p (c)
5328 "Is C a valid part of an ES5 Identifier?
5329 See http://es5.github.io/#x7.6"
5330 (or
5331 (memq c '(?$ ?_ ?\u200c ?\u200d))
5332 (memq (get-char-code-property c 'general-category)
5333 '(;; Letters
5334 Lu Ll Lt Lm Lo Nl
5335 ;; Combining Marks
5336 Mn Mc
5337 ;; Digits
5338 Nd
5339 ;; Connector Punctuation
5340 Pc))))
5341
5342 (defun js2-alpha-p (c)
5343 (cond ((and (<= ?A c) (<= c ?Z)) t)
5344 ((and (<= ?a c) (<= c ?z)) t)
5345 (t nil)))
5346
5347 (defsubst js2-digit-p (c)
5348 (and (<= ?0 c) (<= c ?9)))
5349
5350 (defun js2-js-space-p (c)
5351 (if (<= c 127)
5352 (memq c '(#x20 #x9 #xB #xC #xD))
5353 (or
5354 (eq c #xA0)
5355 ;; TODO: change this nil to check for Unicode space character
5356 nil)))
5357
5358 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5359
5360 (defun js2-skip-line ()
5361 "Skip to end of line."
5362 (while (not (memq (js2-get-char) js2-eol-chars)))
5363 (js2-unget-char)
5364 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5365 (setq js2-token-end js2-ts-cursor))
5366
5367 (defun js2-init-scanner (&optional buf line)
5368 "Create token stream for BUF starting on LINE.
5369 BUF defaults to `current-buffer' and LINE defaults to 1.
5370
5371 A buffer can only have one scanner active at a time, which yields
5372 dramatically simpler code than using a defstruct. If you need to
5373 have simultaneous scanners in a buffer, copy the regions to scan
5374 into temp buffers."
5375 (with-current-buffer (or buf (current-buffer))
5376 (setq js2-ts-dirty-line nil
5377 js2-ts-hit-eof nil
5378 js2-ts-line-start 0
5379 js2-ts-lineno (or line 1)
5380 js2-ts-line-end-char -1
5381 js2-ts-cursor (point-min)
5382 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5383 js2-ti-tokens-cursor 0
5384 js2-ti-lookahead 0
5385 js2-ts-is-xml-attribute nil
5386 js2-ts-xml-is-tag-content nil
5387 js2-ts-xml-open-tags-count 0
5388 js2-ts-string-buffer nil)))
5389
5390 ;; This function uses the cached op, string and number fields in
5391 ;; TokenStream; if getToken has been called since the passed token
5392 ;; was scanned, the op or string printed may be incorrect.
5393 (defun js2-token-to-string (token)
5394 ;; Not sure where this function is used in Rhino. Not tested.
5395 (if (not js2-debug-print-trees)
5396 ""
5397 (let ((name (js2-tt-name token)))
5398 (cond
5399 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5400 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5401 (concat name " `" (js2-current-token-string) "'"))
5402 ((eq token js2-NUMBER)
5403 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5404 (t
5405 name)))))
5406
5407 (defconst js2-keywords
5408 '(break
5409 case catch class const continue
5410 debugger default delete do
5411 else extends
5412 false finally for function
5413 if in instanceof import
5414 let
5415 new null
5416 return
5417 static super switch
5418 this throw true try typeof
5419 var void
5420 while with
5421 yield))
5422
5423 ;; Token names aren't exactly the same as the keywords, unfortunately.
5424 ;; E.g. delete is js2-DELPROP.
5425 (defconst js2-kwd-tokens
5426 (let ((table (make-vector js2-num-tokens nil))
5427 (tokens
5428 (list js2-BREAK
5429 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5430 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5431 js2-ELSE js2-EXTENDS
5432 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5433 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5434 js2-LET
5435 js2-NEW js2-NULL
5436 js2-RETURN
5437 js2-STATIC js2-SUPER js2-SWITCH
5438 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5439 js2-VAR
5440 js2-WHILE js2-WITH
5441 js2-YIELD)))
5442 (dolist (i tokens)
5443 (aset table i 'font-lock-keyword-face))
5444 (aset table js2-STRING 'font-lock-string-face)
5445 (aset table js2-REGEXP 'font-lock-string-face)
5446 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5447 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5448 (aset table js2-COMMENT 'font-lock-comment-face)
5449 (aset table js2-THIS 'font-lock-builtin-face)
5450 (aset table js2-SUPER 'font-lock-builtin-face)
5451 (aset table js2-VOID 'font-lock-constant-face)
5452 (aset table js2-NULL 'font-lock-constant-face)
5453 (aset table js2-TRUE 'font-lock-constant-face)
5454 (aset table js2-FALSE 'font-lock-constant-face)
5455 (aset table js2-NOT 'font-lock-negation-char-face)
5456 table)
5457 "Vector whose values are non-nil for tokens that are keywords.
5458 The values are default faces to use for highlighting the keywords.")
5459
5460 ;; FIXME: Support strict mode-only future reserved words, after we know
5461 ;; which parts scopes are in strict mode, and which are not.
5462 (defconst js2-reserved-words '(class enum export extends import super)
5463 "Future reserved keywords in ECMAScript 5.1.")
5464
5465 (defconst js2-keyword-names
5466 (let ((table (make-hash-table :test 'equal)))
5467 (loop for k in js2-keywords
5468 do (puthash
5469 (symbol-name k) ; instanceof
5470 (intern (concat "js2-"
5471 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5472 table))
5473 table)
5474 "JavaScript keywords by name, mapped to their symbols.")
5475
5476 (defconst js2-reserved-word-names
5477 (let ((table (make-hash-table :test 'equal)))
5478 (loop for k in js2-reserved-words
5479 do
5480 (puthash (symbol-name k) 'js2-RESERVED table))
5481 table)
5482 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5483
5484 (defun js2-collect-string (buf)
5485 "Convert BUF, a list of chars, to a string.
5486 Reverses BUF before converting."
5487 (if buf
5488 (apply #'string (nreverse buf))
5489 ""))
5490
5491 (defun js2-string-to-keyword (s)
5492 "Return token for S, a string, if S is a keyword or reserved word.
5493 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5494 (or (gethash s js2-keyword-names)
5495 (gethash s js2-reserved-word-names)))
5496
5497 (defsubst js2-ts-set-char-token-bounds (token)
5498 "Used when next token is one character."
5499 (setf (js2-token-beg token) (1- js2-ts-cursor)
5500 (js2-token-end token) js2-ts-cursor))
5501
5502 (defsubst js2-ts-return (token type)
5503 "Update the `end' and `type' slots of TOKEN,
5504 then throw `return' with value TYPE."
5505 (setf (js2-token-end token) js2-ts-cursor
5506 (js2-token-type token) type)
5507 (throw 'return type))
5508
5509 (defun js2-x-digit-to-int (c accumulator)
5510 "Build up a hex number.
5511 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5512 corresponding number. Otherwise return -1."
5513 (catch 'return
5514 (catch 'check
5515 ;; Use 0..9 < A..Z < a..z
5516 (cond
5517 ((<= c ?9)
5518 (decf c ?0)
5519 (if (<= 0 c)
5520 (throw 'check nil)))
5521 ((<= c ?F)
5522 (when (<= ?A c)
5523 (decf c (- ?A 10))
5524 (throw 'check nil)))
5525 ((<= c ?f)
5526 (when (<= ?a c)
5527 (decf c (- ?a 10))
5528 (throw 'check nil))))
5529 (throw 'return -1))
5530 (logior c (lsh accumulator 4))))
5531
5532 (defun js2-get-token (&optional modifier)
5533 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5534 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5535 next saved token.
5536
5537 This function will not return a newline (js2-EOL) - instead, it
5538 gobbles newlines until it finds a non-newline token. Call
5539 `js2-peek-token-or-eol' when you care about newlines.
5540
5541 This function will also not return a js2-COMMENT. Instead, it
5542 records comments found in `js2-scanned-comments'. If the token
5543 returned by this function immediately follows a jsdoc comment,
5544 the token is flagged as such."
5545 (if (zerop js2-ti-lookahead)
5546 (js2-get-token-internal modifier)
5547 (decf js2-ti-lookahead)
5548 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5549 (let ((tt (js2-current-token-type)))
5550 (assert (not (= tt js2-EOL)))
5551 tt)))
5552
5553 (defun js2-unget-token ()
5554 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5555 (incf js2-ti-lookahead)
5556 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5557
5558 (defun js2-get-token-internal (modifier)
5559 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5560 (tt (js2-token-type token))
5561 saw-eol
5562 face)
5563 ;; process comments
5564 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5565 (if (= tt js2-EOL)
5566 (setq saw-eol t)
5567 (setq saw-eol nil)
5568 (when js2-record-comments
5569 (js2-record-comment token)))
5570 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5571 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5572 tt (js2-token-type token)))
5573
5574 (when saw-eol
5575 (setf (js2-token-follows-eol-p token) t))
5576
5577 ;; perform lexical fontification as soon as token is scanned
5578 (when js2-parse-ide-mode
5579 (cond
5580 ((minusp tt)
5581 (js2-record-face 'js2-error token))
5582 ((setq face (aref js2-kwd-tokens tt))
5583 (js2-record-face face token))
5584 ((and (= tt js2-NAME)
5585 (equal (js2-token-string token) "undefined"))
5586 (js2-record-face 'font-lock-constant-face token))))
5587 tt))
5588
5589 (defun js2-get-token-internal-1 (modifier)
5590 "Return next JavaScript token type, an int such as js2-RETURN.
5591 During operation, creates an instance of `js2-token' struct, sets
5592 its relevant fields and puts it into `js2-ti-tokens'."
5593 (let (c c1 identifier-start is-unicode-escape-start
5594 contains-escape escape-val str result base
5595 quote-char val look-for-slash continue tt
5596 (token (js2-new-token 0)))
5597 (setq
5598 tt
5599 (catch 'return
5600 (when (eq modifier 'TEMPLATE_TAIL)
5601 (setf (js2-token-beg token) (1- js2-ts-cursor))
5602 (throw 'return (js2-get-string-or-template-token ?` token)))
5603 (while t
5604 ;; Eat whitespace, possibly sensitive to newlines.
5605 (setq continue t)
5606 (while continue
5607 (setq c (js2-get-char))
5608 (cond
5609 ((eq c js2-EOF_CHAR)
5610 (js2-unget-char)
5611 (js2-ts-set-char-token-bounds token)
5612 (throw 'return js2-EOF))
5613 ((eq c ?\n)
5614 (js2-ts-set-char-token-bounds token)
5615 (setq js2-ts-dirty-line nil)
5616 (throw 'return js2-EOL))
5617 ((not (js2-js-space-p c))
5618 (if (/= c ?-) ; in case end of HTML comment
5619 (setq js2-ts-dirty-line t))
5620 (setq continue nil))))
5621 ;; Assume the token will be 1 char - fixed up below.
5622 (js2-ts-set-char-token-bounds token)
5623 (when (eq c ?@)
5624 (throw 'return js2-XMLATTR))
5625 ;; identifier/keyword/instanceof?
5626 ;; watch out for starting with a <backslash>
5627 (cond
5628 ((eq c ?\\)
5629 (setq c (js2-get-char))
5630 (if (eq c ?u)
5631 (setq identifier-start t
5632 is-unicode-escape-start t
5633 js2-ts-string-buffer nil)
5634 (setq identifier-start nil)
5635 (js2-unget-char)
5636 (setq c ?\\)))
5637 (t
5638 (when (setq identifier-start (js2-identifier-start-p c))
5639 (setq js2-ts-string-buffer nil)
5640 (js2-add-to-string c))))
5641 (when identifier-start
5642 (setq contains-escape is-unicode-escape-start)
5643 (catch 'break
5644 (while t
5645 (if is-unicode-escape-start
5646 ;; strictly speaking we should probably push-back
5647 ;; all the bad characters if the <backslash>uXXXX
5648 ;; sequence is malformed. But since there isn't a
5649 ;; correct context(is there?) for a bad Unicode
5650 ;; escape sequence in an identifier, we can report
5651 ;; an error here.
5652 (progn
5653 (setq escape-val 0)
5654 (dotimes (_ 4)
5655 (setq c (js2-get-char)
5656 escape-val (js2-x-digit-to-int c escape-val))
5657 ;; Next check takes care of c < 0 and bad escape
5658 (if (minusp escape-val)
5659 (throw 'break nil)))
5660 (if (minusp escape-val)
5661 (js2-report-scan-error "msg.invalid.escape" t))
5662 (js2-add-to-string escape-val)
5663 (setq is-unicode-escape-start nil))
5664 (setq c (js2-get-char))
5665 (cond
5666 ((eq c ?\\)
5667 (setq c (js2-get-char))
5668 (if (eq c ?u)
5669 (setq is-unicode-escape-start t
5670 contains-escape t)
5671 (js2-report-scan-error "msg.illegal.character" t)))
5672 (t
5673 (if (or (eq c js2-EOF_CHAR)
5674 (not (js2-identifier-part-p c)))
5675 (throw 'break nil))
5676 (js2-add-to-string c))))))
5677 (js2-unget-char)
5678 (setf str (js2-collect-string js2-ts-string-buffer)
5679 (js2-token-end token) js2-ts-cursor)
5680 ;; FIXME: Invalid in ES5 and ES6, see
5681 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5682 ;; Probably should just drop this conditional.
5683 (unless contains-escape
5684 ;; OPT we shouldn't have to make a string (object!) to
5685 ;; check if it's a keyword.
5686 ;; Return the corresponding token if it's a keyword
5687 (when (setq result (js2-string-to-keyword str))
5688 (if (and (< js2-language-version 170)
5689 (memq result '(js2-LET js2-YIELD)))
5690 ;; LET and YIELD are tokens only in 1.7 and later
5691 (setq result 'js2-NAME))
5692 (when (eq result 'js2-RESERVED)
5693 (setf (js2-token-string token) str))
5694 (throw 'return (js2-tt-code result))))
5695 ;; If we want to intern these as Rhino does, just use (intern str)
5696 (setf (js2-token-string token) str)
5697 (throw 'return js2-NAME)) ; end identifier/kwd check
5698 ;; is it a number?
5699 (when (or (js2-digit-p c)
5700 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5701 (setq js2-ts-string-buffer nil
5702 base 10)
5703 (when (eq c ?0)
5704 (setq c (js2-get-char))
5705 (cond
5706 ((or (eq c ?x) (eq c ?X))
5707 (setq base 16)
5708 (setq c (js2-get-char)))
5709 ((and (or (eq c ?b) (eq c ?B))
5710 (>= js2-language-version 200))
5711 (setq base 2)
5712 (setq c (js2-get-char)))
5713 ((and (or (eq c ?o) (eq c ?O))
5714 (>= js2-language-version 200))
5715 (setq base 8)
5716 (setq c (js2-get-char)))
5717 ((js2-digit-p c)
5718 (setq base 'maybe-8))
5719 (t
5720 (js2-add-to-string ?0))))
5721 (cond
5722 ((eq base 16)
5723 (if (> 0 (js2-x-digit-to-int c 0))
5724 (js2-report-scan-error "msg.missing.hex.digits")
5725 (while (<= 0 (js2-x-digit-to-int c 0))
5726 (js2-add-to-string c)
5727 (setq c (js2-get-char)))))
5728 ((eq base 2)
5729 (if (not (memq c '(?0 ?1)))
5730 (js2-report-scan-error "msg.missing.binary.digits")
5731 (while (memq c '(?0 ?1))
5732 (js2-add-to-string c)
5733 (setq c (js2-get-char)))))
5734 ((eq base 8)
5735 (if (or (> ?0 c) (< ?7 c))
5736 (js2-report-scan-error "msg.missing.octal.digits")
5737 (while (and (<= ?0 c) (>= ?7 c))
5738 (js2-add-to-string c)
5739 (setq c (js2-get-char)))))
5740 (t
5741 (while (and (<= ?0 c) (<= c ?9))
5742 ;; We permit 08 and 09 as decimal numbers, which
5743 ;; makes our behavior a superset of the ECMA
5744 ;; numeric grammar. We might not always be so
5745 ;; permissive, so we warn about it.
5746 (when (and (eq base 'maybe-8) (>= c ?8))
5747 (js2-report-warning "msg.bad.octal.literal"
5748 (if (eq c ?8) "8" "9"))
5749 (setq base 10))
5750 (js2-add-to-string c)
5751 (setq c (js2-get-char)))
5752 (when (eq base 'maybe-8)
5753 (setq base 8))))
5754 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5755 (when (eq c ?.)
5756 (loop do
5757 (js2-add-to-string c)
5758 (setq c (js2-get-char))
5759 while (js2-digit-p c)))
5760 (when (memq c '(?e ?E))
5761 (js2-add-to-string c)
5762 (setq c (js2-get-char))
5763 (when (memq c '(?+ ?-))
5764 (js2-add-to-string c)
5765 (setq c (js2-get-char)))
5766 (unless (js2-digit-p c)
5767 (js2-report-scan-error "msg.missing.exponent" t))
5768 (loop do
5769 (js2-add-to-string c)
5770 (setq c (js2-get-char))
5771 while (js2-digit-p c))))
5772 (js2-unget-char)
5773 (let ((str (js2-set-string-from-buffer token)))
5774 (setf (js2-token-number token)
5775 (js2-string-to-number str base)))
5776 (throw 'return js2-NUMBER))
5777 ;; is it a string?
5778 (when (memq c '(?\" ?\' ?`))
5779 (throw 'return
5780 (js2-get-string-or-template-token c token)))
5781 (js2-ts-return token
5782 (case c
5783 (?\;
5784 (throw 'return js2-SEMI))
5785 (?\[
5786 (throw 'return js2-LB))
5787 (?\]
5788 (throw 'return js2-RB))
5789 (?{
5790 (throw 'return js2-LC))
5791 (?}
5792 (throw 'return js2-RC))
5793 (?\(
5794 (throw 'return js2-LP))
5795 (?\)
5796 (throw 'return js2-RP))
5797 (?,
5798 (throw 'return js2-COMMA))
5799 (??
5800 (throw 'return js2-HOOK))
5801 (?:
5802 (if (js2-match-char ?:)
5803 js2-COLONCOLON
5804 (throw 'return js2-COLON)))
5805 (?.
5806 (if (js2-match-char ?.)
5807 (if (js2-match-char ?.)
5808 js2-TRIPLEDOT js2-DOTDOT)
5809 (if (js2-match-char ?\()
5810 js2-DOTQUERY
5811 (throw 'return js2-DOT))))
5812 (?|
5813 (if (js2-match-char ?|)
5814 (throw 'return js2-OR)
5815 (if (js2-match-char ?=)
5816 js2-ASSIGN_BITOR
5817 (throw 'return js2-BITOR))))
5818 (?^
5819 (if (js2-match-char ?=)
5820 js2-ASSIGN_BITOR
5821 (throw 'return js2-BITXOR)))
5822 (?&
5823 (if (js2-match-char ?&)
5824 (throw 'return js2-AND)
5825 (if (js2-match-char ?=)
5826 js2-ASSIGN_BITAND
5827 (throw 'return js2-BITAND))))
5828 (?=
5829 (if (js2-match-char ?=)
5830 (if (js2-match-char ?=)
5831 js2-SHEQ
5832 (throw 'return js2-EQ))
5833 (if (js2-match-char ?>)
5834 (js2-ts-return token js2-ARROW)
5835 (throw 'return js2-ASSIGN))))
5836 (?!
5837 (if (js2-match-char ?=)
5838 (if (js2-match-char ?=)
5839 js2-SHNE
5840 js2-NE)
5841 (throw 'return js2-NOT)))
5842 (?<
5843 ;; NB:treat HTML begin-comment as comment-till-eol
5844 (when (js2-match-char ?!)
5845 (when (js2-match-char ?-)
5846 (when (js2-match-char ?-)
5847 (js2-skip-line)
5848 (setf (js2-token-comment-type (js2-current-token)) 'html)
5849 (throw 'return js2-COMMENT)))
5850 (js2-unget-char))
5851 (if (js2-match-char ?<)
5852 (if (js2-match-char ?=)
5853 js2-ASSIGN_LSH
5854 js2-LSH)
5855 (if (js2-match-char ?=)
5856 js2-LE
5857 (throw 'return js2-LT))))
5858 (?>
5859 (if (js2-match-char ?>)
5860 (if (js2-match-char ?>)
5861 (if (js2-match-char ?=)
5862 js2-ASSIGN_URSH
5863 js2-URSH)
5864 (if (js2-match-char ?=)
5865 js2-ASSIGN_RSH
5866 js2-RSH))
5867 (if (js2-match-char ?=)
5868 js2-GE
5869 (throw 'return js2-GT))))
5870 (?*
5871 (if (js2-match-char ?=)
5872 js2-ASSIGN_MUL
5873 (throw 'return js2-MUL)))
5874 (?/
5875 ;; is it a // comment?
5876 (when (js2-match-char ?/)
5877 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5878 (js2-skip-line)
5879 (setf (js2-token-comment-type token) 'line)
5880 ;; include newline so highlighting goes to end of window
5881 (incf (js2-token-end token))
5882 (throw 'return js2-COMMENT))
5883 ;; is it a /* comment?
5884 (when (js2-match-char ?*)
5885 (setf look-for-slash nil
5886 (js2-token-beg token) (- js2-ts-cursor 2)
5887 (js2-token-comment-type token)
5888 (if (js2-match-char ?*)
5889 (progn
5890 (setq look-for-slash t)
5891 'jsdoc)
5892 'block))
5893 (while t
5894 (setq c (js2-get-char))
5895 (cond
5896 ((eq c js2-EOF_CHAR)
5897 (setf (js2-token-end token) (1- js2-ts-cursor))
5898 (js2-report-error "msg.unterminated.comment")
5899 (throw 'return js2-COMMENT))
5900 ((eq c ?*)
5901 (setq look-for-slash t))
5902 ((eq c ?/)
5903 (if look-for-slash
5904 (js2-ts-return token js2-COMMENT)))
5905 (t
5906 (setf look-for-slash nil
5907 (js2-token-end token) js2-ts-cursor)))))
5908 (if (js2-match-char ?=)
5909 js2-ASSIGN_DIV
5910 (throw 'return js2-DIV)))
5911 (?#
5912 (when js2-skip-preprocessor-directives
5913 (js2-skip-line)
5914 (setf (js2-token-comment-type token) 'preprocessor
5915 (js2-token-end token) js2-ts-cursor)
5916 (throw 'return js2-COMMENT))
5917 (throw 'return js2-ERROR))
5918 (?%
5919 (if (js2-match-char ?=)
5920 js2-ASSIGN_MOD
5921 (throw 'return js2-MOD)))
5922 (?~
5923 (throw 'return js2-BITNOT))
5924 (?+
5925 (if (js2-match-char ?=)
5926 js2-ASSIGN_ADD
5927 (if (js2-match-char ?+)
5928 js2-INC
5929 (throw 'return js2-ADD))))
5930 (?-
5931 (cond
5932 ((js2-match-char ?=)
5933 (setq c js2-ASSIGN_SUB))
5934 ((js2-match-char ?-)
5935 (unless js2-ts-dirty-line
5936 ;; treat HTML end-comment after possible whitespace
5937 ;; after line start as comment-until-eol
5938 (when (js2-match-char ?>)
5939 (js2-skip-line)
5940 (setf (js2-token-comment-type (js2-current-token)) 'html)
5941 (throw 'return js2-COMMENT)))
5942 (setq c js2-DEC))
5943 (t
5944 (setq c js2-SUB)))
5945 (setq js2-ts-dirty-line t)
5946 c)
5947 (otherwise
5948 (js2-report-scan-error "msg.illegal.character")))))))
5949 (setf (js2-token-type token) tt)
5950 token))
5951
5952 (defun js2-get-string-or-template-token (quote-char token)
5953 ;; We attempt to accumulate a string the fast way, by
5954 ;; building it directly out of the reader. But if there
5955 ;; are any escaped characters in the string, we revert to
5956 ;; building it out of a string buffer.
5957 (let ((c (js2-get-char))
5958 js2-ts-string-buffer
5959 nc)
5960 (catch 'break
5961 (while (/= c quote-char)
5962 (catch 'continue
5963 (when (eq c js2-EOF_CHAR)
5964 (js2-unget-char)
5965 (js2-report-error "msg.unterminated.string.lit")
5966 (throw 'break nil))
5967 (when (and (eq c ?\n) (not (eq quote-char ?`)))
5968 (js2-unget-char)
5969 (js2-report-error "msg.unterminated.string.lit")
5970 (throw 'break nil))
5971 (when (eq c ?\\)
5972 ;; We've hit an escaped character
5973 (setq c (js2-get-char))
5974 (case c
5975 (?b (setq c ?\b))
5976 (?f (setq c ?\f))
5977 (?n (setq c ?\n))
5978 (?r (setq c ?\r))
5979 (?t (setq c ?\t))
5980 (?v (setq c ?\v))
5981 (?u
5982 (setq c1 (js2-read-unicode-escape))
5983 (if js2-parse-ide-mode
5984 (if c1
5985 (progn
5986 ;; just copy the string in IDE-mode
5987 (js2-add-to-string ?\\)
5988 (js2-add-to-string ?u)
5989 (dotimes (_ 3)
5990 (js2-add-to-string (js2-get-char)))
5991 (setq c (js2-get-char))) ; added at end of loop
5992 ;; flag it as an invalid escape
5993 (js2-report-warning "msg.invalid.escape"
5994 nil (- js2-ts-cursor 2) 6))
5995 ;; Get 4 hex digits; if the u escape is not
5996 ;; followed by 4 hex digits, use 'u' + the
5997 ;; literal character sequence that follows.
5998 (js2-add-to-string ?u)
5999 (setq escape-val 0)
6000 (dotimes (_ 4)
6001 (setq c (js2-get-char)
6002 escape-val (js2-x-digit-to-int c escape-val))
6003 (if (minusp escape-val)
6004 (throw 'continue nil))
6005 (js2-add-to-string c))
6006 ;; prepare for replace of stored 'u' sequence by escape value
6007 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6008 c escape-val)))
6009 (?x
6010 ;; Get 2 hex digits, defaulting to 'x'+literal
6011 ;; sequence, as above.
6012 (setq c (js2-get-char)
6013 escape-val (js2-x-digit-to-int c 0))
6014 (if (minusp escape-val)
6015 (progn
6016 (js2-add-to-string ?x)
6017 (throw 'continue nil))
6018 (setq c1 c
6019 c (js2-get-char)
6020 escape-val (js2-x-digit-to-int c escape-val))
6021 (if (minusp escape-val)
6022 (progn
6023 (js2-add-to-string ?x)
6024 (js2-add-to-string c1)
6025 (throw 'continue nil))
6026 ;; got 2 hex digits
6027 (setq c escape-val))))
6028 (?\n
6029 ;; Remove line terminator after escape to follow
6030 ;; SpiderMonkey and C/C++
6031 (setq c (js2-get-char))
6032 (throw 'continue nil))
6033 (t
6034 (when (and (<= ?0 c) (< c ?8))
6035 (setq val (- c ?0)
6036 c (js2-get-char))
6037 (when (and (<= ?0 c) (< c ?8))
6038 (setq val (- (+ (* 8 val) c) ?0)
6039 c (js2-get-char))
6040 (when (and (<= ?0 c)
6041 (< c ?8)
6042 (< val #o37))
6043 ;; c is 3rd char of octal sequence only
6044 ;; if the resulting val <= 0377
6045 (setq val (- (+ (* 8 val) c) ?0)
6046 c (js2-get-char))))
6047 (js2-unget-char)
6048 (setq c val)))))
6049 (when (and (eq quote-char ?`) (eq c ?$))
6050 (when (eq (setq nc (js2-get-char)) ?\{)
6051 (throw 'break nil))
6052 (js2-unget-char))
6053 (js2-add-to-string c)
6054 (setq c (js2-get-char)))))
6055 (js2-set-string-from-buffer token)
6056 (if (not (eq quote-char ?`))
6057 js2-STRING
6058 (if (and (eq c ?$) (eq nc ?\{))
6059 js2-TEMPLATE_HEAD
6060 js2-NO_SUBS_TEMPLATE))))
6061
6062 (defsubst js2-string-to-number (str base)
6063 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
6064 (condition-case nil
6065 (string-to-number str base)
6066 (overflow-error -1)))
6067
6068 (defun js2-read-regexp (start-tt)
6069 "Called by parser when it gets / or /= in literal context."
6070 (let (c err
6071 in-class ; inside a '[' .. ']' character-class
6072 flags
6073 (continue t)
6074 (token (js2-new-token 0)))
6075 (setq js2-ts-string-buffer nil)
6076 (if (eq start-tt js2-ASSIGN_DIV)
6077 ;; mis-scanned /=
6078 (js2-add-to-string ?=)
6079 (if (not (eq start-tt js2-DIV))
6080 (error "failed assertion")))
6081 (while (and (not err)
6082 (or (/= (setq c (js2-get-char)) ?/)
6083 in-class))
6084 (cond
6085 ((or (= c ?\n)
6086 (= c js2-EOF_CHAR))
6087 (setf (js2-token-end token) (1- js2-ts-cursor)
6088 err t
6089 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6090 (js2-report-error "msg.unterminated.re.lit"))
6091 (t (cond
6092 ((= c ?\\)
6093 (js2-add-to-string c)
6094 (setq c (js2-get-char)))
6095 ((= c ?\[)
6096 (setq in-class t))
6097 ((= c ?\])
6098 (setq in-class nil)))
6099 (js2-add-to-string c))))
6100 (unless err
6101 (while continue
6102 (cond
6103 ((js2-match-char ?g)
6104 (push ?g flags))
6105 ((js2-match-char ?i)
6106 (push ?i flags))
6107 ((js2-match-char ?m)
6108 (push ?m flags))
6109 ((and (js2-match-char ?u)
6110 (>= js2-language-version 200))
6111 (push ?u flags))
6112 ((and (js2-match-char ?y)
6113 (>= js2-language-version 200))
6114 (push ?y flags))
6115 (t
6116 (setq continue nil))))
6117 (if (js2-alpha-p (js2-peek-char))
6118 (js2-report-scan-error "msg.invalid.re.flag" t
6119 js2-ts-cursor 1))
6120 (js2-set-string-from-buffer token))
6121 (js2-collect-string flags)))
6122
6123 (defun js2-get-first-xml-token ()
6124 (setq js2-ts-xml-open-tags-count 0
6125 js2-ts-is-xml-attribute nil
6126 js2-ts-xml-is-tag-content nil)
6127 (js2-unget-char)
6128 (js2-get-next-xml-token))
6129
6130 (defun js2-xml-discard-string (token)
6131 "Throw away the string in progress and flag an XML parse error."
6132 (setf js2-ts-string-buffer nil
6133 (js2-token-string token) nil)
6134 (js2-report-scan-error "msg.XML.bad.form" t))
6135
6136 (defun js2-get-next-xml-token ()
6137 (setq js2-ts-string-buffer nil) ; for recording the XML
6138 (let ((token (js2-new-token 0))
6139 c result)
6140 (setq result
6141 (catch 'return
6142 (while t
6143 (setq c (js2-get-char))
6144 (cond
6145 ((= c js2-EOF_CHAR)
6146 (throw 'return js2-ERROR))
6147 (js2-ts-xml-is-tag-content
6148 (case c
6149 (?>
6150 (js2-add-to-string c)
6151 (setq js2-ts-xml-is-tag-content nil
6152 js2-ts-is-xml-attribute nil))
6153 (?/
6154 (js2-add-to-string c)
6155 (when (eq ?> (js2-peek-char))
6156 (setq c (js2-get-char))
6157 (js2-add-to-string c)
6158 (setq js2-ts-xml-is-tag-content nil)
6159 (decf js2-ts-xml-open-tags-count)))
6160 (?{
6161 (js2-unget-char)
6162 (js2-set-string-from-buffer token)
6163 (throw 'return js2-XML))
6164 ((?\' ?\")
6165 (js2-add-to-string c)
6166 (unless (js2-read-quoted-string c token)
6167 (throw 'return js2-ERROR)))
6168 (?=
6169 (js2-add-to-string c)
6170 (setq js2-ts-is-xml-attribute t))
6171 ((? ?\t ?\r ?\n)
6172 (js2-add-to-string c))
6173 (t
6174 (js2-add-to-string c)
6175 (setq js2-ts-is-xml-attribute nil)))
6176 (when (and (not js2-ts-xml-is-tag-content)
6177 (zerop js2-ts-xml-open-tags-count))
6178 (js2-set-string-from-buffer token)
6179 (throw 'return js2-XMLEND)))
6180 (t
6181 ;; else not tag content
6182 (case c
6183 (?<
6184 (js2-add-to-string c)
6185 (setq c (js2-peek-char))
6186 (case c
6187 (?!
6188 (setq c (js2-get-char)) ;; skip !
6189 (js2-add-to-string c)
6190 (setq c (js2-peek-char))
6191 (case c
6192 (?-
6193 (setq c (js2-get-char)) ;; skip -
6194 (js2-add-to-string c)
6195 (if (eq c ?-)
6196 (progn
6197 (js2-add-to-string c)
6198 (unless (js2-read-xml-comment token)
6199 (throw 'return js2-ERROR)))
6200 (js2-xml-discard-string token)
6201 (throw 'return js2-ERROR)))
6202 (?\[
6203 (setq c (js2-get-char)) ;; skip [
6204 (js2-add-to-string c)
6205 (if (and (= (js2-get-char) ?C)
6206 (= (js2-get-char) ?D)
6207 (= (js2-get-char) ?A)
6208 (= (js2-get-char) ?T)
6209 (= (js2-get-char) ?A)
6210 (= (js2-get-char) ?\[))
6211 (progn
6212 (js2-add-to-string ?C)
6213 (js2-add-to-string ?D)
6214 (js2-add-to-string ?A)
6215 (js2-add-to-string ?T)
6216 (js2-add-to-string ?A)
6217 (js2-add-to-string ?\[)
6218 (unless (js2-read-cdata token)
6219 (throw 'return js2-ERROR)))
6220 (js2-xml-discard-string token)
6221 (throw 'return js2-ERROR)))
6222 (t
6223 (unless (js2-read-entity token)
6224 (throw 'return js2-ERROR))))
6225 ;; Allow bare CDATA section, e.g.:
6226 ;; let xml = <![CDATA[ foo bar baz ]]>;
6227 (when (zerop js2-ts-xml-open-tags-count)
6228 (throw 'return js2-XMLEND)))
6229 (??
6230 (setq c (js2-get-char)) ;; skip ?
6231 (js2-add-to-string c)
6232 (unless (js2-read-PI token)
6233 (throw 'return js2-ERROR)))
6234 (?/
6235 ;; end tag
6236 (setq c (js2-get-char)) ;; skip /
6237 (js2-add-to-string c)
6238 (when (zerop js2-ts-xml-open-tags-count)
6239 (js2-xml-discard-string token)
6240 (throw 'return js2-ERROR))
6241 (setq js2-ts-xml-is-tag-content t)
6242 (decf js2-ts-xml-open-tags-count))
6243 (t
6244 ;; start tag
6245 (setq js2-ts-xml-is-tag-content t)
6246 (incf js2-ts-xml-open-tags-count))))
6247 (?{
6248 (js2-unget-char)
6249 (js2-set-string-from-buffer token)
6250 (throw 'return js2-XML))
6251 (t
6252 (js2-add-to-string c))))))))
6253 (setf (js2-token-end token) js2-ts-cursor)
6254 (setf (js2-token-type token) result)
6255 result))
6256
6257 (defun js2-read-quoted-string (quote token)
6258 (let (c)
6259 (catch 'return
6260 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6261 (js2-add-to-string c)
6262 (if (eq c quote)
6263 (throw 'return t)))
6264 (js2-xml-discard-string token) ;; throw away string in progress
6265 nil)))
6266
6267 (defun js2-read-xml-comment (token)
6268 (let ((c (js2-get-char)))
6269 (catch 'return
6270 (while (/= c js2-EOF_CHAR)
6271 (catch 'continue
6272 (js2-add-to-string c)
6273 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6274 (setq c (js2-get-char))
6275 (js2-add-to-string c)
6276 (if (eq (js2-peek-char) ?>)
6277 (progn
6278 (setq c (js2-get-char)) ;; skip >
6279 (js2-add-to-string c)
6280 (throw 'return t))
6281 (throw 'continue nil)))
6282 (setq c (js2-get-char))))
6283 (js2-xml-discard-string token)
6284 nil)))
6285
6286 (defun js2-read-cdata (token)
6287 (let ((c (js2-get-char)))
6288 (catch 'return
6289 (while (/= c js2-EOF_CHAR)
6290 (catch 'continue
6291 (js2-add-to-string c)
6292 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6293 (setq c (js2-get-char))
6294 (js2-add-to-string c)
6295 (if (eq (js2-peek-char) ?>)
6296 (progn
6297 (setq c (js2-get-char)) ;; Skip >
6298 (js2-add-to-string c)
6299 (throw 'return t))
6300 (throw 'continue nil)))
6301 (setq c (js2-get-char))))
6302 (js2-xml-discard-string token)
6303 nil)))
6304
6305 (defun js2-read-entity (token)
6306 (let ((decl-tags 1)
6307 c)
6308 (catch 'return
6309 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6310 (js2-add-to-string c)
6311 (case c
6312 (?<
6313 (incf decl-tags))
6314 (?>
6315 (decf decl-tags)
6316 (if (zerop decl-tags)
6317 (throw 'return t)))))
6318 (js2-xml-discard-string token)
6319 nil)))
6320
6321 (defun js2-read-PI (token)
6322 "Scan an XML processing instruction."
6323 (let (c)
6324 (catch 'return
6325 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6326 (js2-add-to-string c)
6327 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6328 (setq c (js2-get-char)) ;; Skip >
6329 (js2-add-to-string c)
6330 (throw 'return t)))
6331 (js2-xml-discard-string token)
6332 nil)))
6333
6334 ;;; Highlighting
6335
6336 (defun js2-set-face (beg end face &optional record)
6337 "Fontify a region. If RECORD is non-nil, record for later."
6338 (when (plusp js2-highlight-level)
6339 (setq beg (min (point-max) beg)
6340 beg (max (point-min) beg)
6341 end (min (point-max) end)
6342 end (max (point-min) end))
6343 (if record
6344 (push (list beg end face) js2-mode-fontifications)
6345 (put-text-property beg end 'font-lock-face face))))
6346
6347 (defsubst js2-clear-face (beg end)
6348 (remove-text-properties beg end '(font-lock-face nil
6349 help-echo nil
6350 point-entered nil
6351 c-in-sws nil)))
6352
6353 (defconst js2-ecma-global-props
6354 (concat "^"
6355 (regexp-opt
6356 '("Infinity" "NaN" "undefined" "arguments") t)
6357 "$")
6358 "Value properties of the Ecma-262 Global Object.
6359 Shown at or above `js2-highlight-level' 2.")
6360
6361 ;; might want to add the name "arguments" to this list?
6362 (defconst js2-ecma-object-props
6363 (concat "^"
6364 (regexp-opt
6365 '("prototype" "__proto__" "__parent__") t)
6366 "$")
6367 "Value properties of the Ecma-262 Object constructor.
6368 Shown at or above `js2-highlight-level' 2.")
6369
6370 (defconst js2-ecma-global-funcs
6371 (concat
6372 "^"
6373 (regexp-opt
6374 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6375 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6376 "$")
6377 "Function properties of the Ecma-262 Global object.
6378 Shown at or above `js2-highlight-level' 2.")
6379
6380 (defconst js2-ecma-number-props
6381 (concat "^"
6382 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6383 "NEGATIVE_INFINITY"
6384 "POSITIVE_INFINITY") t)
6385 "$")
6386 "Properties of the Ecma-262 Number constructor.
6387 Shown at or above `js2-highlight-level' 2.")
6388
6389 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6390 "Properties of the Ecma-262 Date constructor.
6391 Shown at or above `js2-highlight-level' 2.")
6392
6393 (defconst js2-ecma-math-props
6394 (concat "^"
6395 (regexp-opt
6396 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6397 t)
6398 "$")
6399 "Properties of the Ecma-262 Math object.
6400 Shown at or above `js2-highlight-level' 2.")
6401
6402 (defconst js2-ecma-math-funcs
6403 (concat "^"
6404 (regexp-opt
6405 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6406 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6407 "$")
6408 "Function properties of the Ecma-262 Math object.
6409 Shown at or above `js2-highlight-level' 2.")
6410
6411 (defconst js2-ecma-function-props
6412 (concat
6413 "^"
6414 (regexp-opt
6415 '(;; properties of the Object prototype object
6416 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6417 "toLocaleString" "toString" "valueOf"
6418 ;; properties of the Function prototype object
6419 "apply" "call"
6420 ;; properties of the Array prototype object
6421 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6422 "splice" "unshift"
6423 ;; properties of the String prototype object
6424 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6425 "localeCompare" "match" "replace" "search" "split" "substring"
6426 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6427 "toUpperCase"
6428 ;; properties of the Number prototype object
6429 "toExponential" "toFixed" "toPrecision"
6430 ;; properties of the Date prototype object
6431 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6432 "getMinutes" "getMonth" "getSeconds" "getTime"
6433 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6434 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6435 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6436 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6437 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6438 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6439 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6440 "toTimeString" "toUTCString"
6441 ;; properties of the RegExp prototype object
6442 "exec" "test"
6443 ;; properties of the JSON prototype object
6444 "parse" "stringify"
6445 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6446 "toSource" "__defineGetter__" "__defineSetter__"
6447 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6448 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6449 t)
6450 "$")
6451 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6452 Shown at or above `js2-highlight-level' 3.")
6453
6454 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6455 (let ((target-name (and target
6456 (js2-name-node-p target)
6457 (js2-name-node-name target)))
6458 (prop-name (if prop (js2-name-node-name prop)))
6459 (level2 (>= js2-highlight-level 2))
6460 (level3 (>= js2-highlight-level 3)))
6461 (when level2
6462 (let ((face
6463 (if call-p
6464 (cond
6465 ((and target prop)
6466 (cond
6467 ((and level3 (string-match js2-ecma-function-props prop-name))
6468 'font-lock-builtin-face)
6469 ((and target-name prop)
6470 (cond
6471 ((string= target-name "Date")
6472 (if (string-match js2-ecma-date-props prop-name)
6473 'font-lock-builtin-face))
6474 ((string= target-name "Math")
6475 (if (string-match js2-ecma-math-funcs prop-name)
6476 'font-lock-builtin-face))))))
6477 (prop
6478 (if (string-match js2-ecma-global-funcs prop-name)
6479 'font-lock-builtin-face)))
6480 (cond
6481 ((and target prop)
6482 (cond
6483 ((string= target-name "Number")
6484 (if (string-match js2-ecma-number-props prop-name)
6485 'font-lock-constant-face))
6486 ((string= target-name "Math")
6487 (if (string-match js2-ecma-math-props prop-name)
6488 'font-lock-constant-face))))
6489 (prop
6490 (if (string-match js2-ecma-object-props prop-name)
6491 'font-lock-constant-face))))))
6492 (when face
6493 (let ((pos (+ (js2-node-pos parent) ; absolute
6494 (js2-node-pos prop)))) ; relative
6495 (js2-set-face pos
6496 (+ pos (js2-node-len prop))
6497 face 'record)))))))
6498
6499 (defun js2-parse-highlight-member-expr-node (node)
6500 "Perform syntax highlighting of EcmaScript built-in properties.
6501 The variable `js2-highlight-level' governs this highighting."
6502 (let (face target prop name pos end parent call-p callee)
6503 (cond
6504 ;; case 1: simple name, e.g. foo
6505 ((js2-name-node-p node)
6506 (setq name (js2-name-node-name node))
6507 ;; possible for name to be nil in rare cases - saw it when
6508 ;; running js2-mode on an elisp buffer. Might as well try to
6509 ;; make it so js2-mode never barfs.
6510 (when name
6511 (setq face (if (string-match js2-ecma-global-props name)
6512 'font-lock-constant-face))
6513 (when face
6514 (setq pos (js2-node-pos node)
6515 end (+ pos (js2-node-len node)))
6516 (js2-set-face pos end face 'record))))
6517 ;; case 2: property access or function call
6518 ((or (js2-prop-get-node-p node)
6519 ;; highlight function call if expr is a prop-get node
6520 ;; or a plain name (i.e. unqualified function call)
6521 (and (setq call-p (js2-call-node-p node))
6522 (setq callee (js2-call-node-target node)) ; separate setq!
6523 (or (js2-prop-get-node-p callee)
6524 (js2-name-node-p callee))))
6525 (setq parent node
6526 node (if call-p callee node))
6527 (if (and call-p (js2-name-node-p callee))
6528 (setq prop callee)
6529 (setq target (js2-prop-get-node-left node)
6530 prop (js2-prop-get-node-right node)))
6531 (cond
6532 ((js2-name-node-p prop)
6533 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6534 (js2-parse-highlight-prop-get parent target prop call-p))
6535 ((js2-name-node-p target)
6536 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6537 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6538
6539 (defun js2-parse-highlight-member-expr-fn-name (expr)
6540 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6541 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6542 We currently only handle the case where the last component is a prop-get
6543 of a simple name. Called before EXPR has a parent node."
6544 (let (pos
6545 (name (and (js2-prop-get-node-p expr)
6546 (js2-prop-get-node-right expr))))
6547 (when (js2-name-node-p name)
6548 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6549 (js2-node-pos name)))
6550 (+ pos (js2-node-len name))
6551 'font-lock-function-name-face
6552 'record))))
6553
6554 ;; source: http://jsdoc.sourceforge.net/
6555 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6556 ;; allows type specifications, and needs work before entering the wild.
6557
6558 (defconst js2-jsdoc-param-tag-regexp
6559 (concat "^\\s-*\\*+\\s-*\\(@"
6560 "\\(?:param\\|argument\\)"
6561 "\\)"
6562 "\\s-*\\({[^}]+}\\)?" ; optional type
6563 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6564 "\\>")
6565 "Matches jsdoc tags with optional type and optional param name.")
6566
6567 (defconst js2-jsdoc-typed-tag-regexp
6568 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6569 (regexp-opt
6570 '("enum"
6571 "extends"
6572 "field"
6573 "id"
6574 "implements"
6575 "lends"
6576 "mods"
6577 "requires"
6578 "return"
6579 "returns"
6580 "throw"
6581 "throws"))
6582 "\\)\\)\\s-*\\({[^}]+}\\)?")
6583 "Matches jsdoc tags with optional type.")
6584
6585 (defconst js2-jsdoc-arg-tag-regexp
6586 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6587 (regexp-opt
6588 '("alias"
6589 "augments"
6590 "borrows"
6591 "bug"
6592 "base"
6593 "config"
6594 "default"
6595 "define"
6596 "exception"
6597 "function"
6598 "member"
6599 "memberOf"
6600 "name"
6601 "namespace"
6602 "property"
6603 "since"
6604 "suppress"
6605 "this"
6606 "throws"
6607 "type"
6608 "version"))
6609 "\\)\\)\\s-+\\([^ \t]+\\)")
6610 "Matches jsdoc tags with a single argument.")
6611
6612 (defconst js2-jsdoc-empty-tag-regexp
6613 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6614 (regexp-opt
6615 '("addon"
6616 "author"
6617 "class"
6618 "const"
6619 "constant"
6620 "constructor"
6621 "constructs"
6622 "deprecated"
6623 "desc"
6624 "description"
6625 "event"
6626 "example"
6627 "exec"
6628 "export"
6629 "fileoverview"
6630 "final"
6631 "function"
6632 "hidden"
6633 "ignore"
6634 "implicitCast"
6635 "inheritDoc"
6636 "inner"
6637 "interface"
6638 "license"
6639 "noalias"
6640 "noshadow"
6641 "notypecheck"
6642 "override"
6643 "owner"
6644 "preserve"
6645 "preserveTry"
6646 "private"
6647 "protected"
6648 "public"
6649 "static"
6650 "supported"
6651 ))
6652 "\\)\\)\\s-*")
6653 "Matches empty jsdoc tags.")
6654
6655 (defconst js2-jsdoc-link-tag-regexp
6656 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6657 "Matches a jsdoc link or code tag.")
6658
6659 (defconst js2-jsdoc-see-tag-regexp
6660 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6661 "Matches a jsdoc @see tag.")
6662
6663 (defconst js2-jsdoc-html-tag-regexp
6664 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6665 "Matches a simple (no attributes) html start- or end-tag.")
6666
6667 (defun js2-jsdoc-highlight-helper ()
6668 (js2-set-face (match-beginning 1)
6669 (match-end 1)
6670 'js2-jsdoc-tag)
6671 (if (match-beginning 2)
6672 (if (save-excursion
6673 (goto-char (match-beginning 2))
6674 (= (char-after) ?{))
6675 (js2-set-face (1+ (match-beginning 2))
6676 (1- (match-end 2))
6677 'js2-jsdoc-type)
6678 (js2-set-face (match-beginning 2)
6679 (match-end 2)
6680 'js2-jsdoc-value)))
6681 (if (match-beginning 3)
6682 (js2-set-face (match-beginning 3)
6683 (match-end 3)
6684 'js2-jsdoc-value)))
6685
6686 (defun js2-highlight-jsdoc (ast)
6687 "Highlight doc comment tags."
6688 (let ((comments (js2-ast-root-comments ast))
6689 beg end)
6690 (save-excursion
6691 (dolist (node comments)
6692 (when (eq (js2-comment-node-format node) 'jsdoc)
6693 (setq beg (js2-node-abs-pos node)
6694 end (+ beg (js2-node-len node)))
6695 (save-restriction
6696 (narrow-to-region beg end)
6697 (dolist (re (list js2-jsdoc-param-tag-regexp
6698 js2-jsdoc-typed-tag-regexp
6699 js2-jsdoc-arg-tag-regexp
6700 js2-jsdoc-link-tag-regexp
6701 js2-jsdoc-see-tag-regexp
6702 js2-jsdoc-empty-tag-regexp))
6703 (goto-char beg)
6704 (while (re-search-forward re nil t)
6705 (js2-jsdoc-highlight-helper)))
6706 ;; simple highlighting for html tags
6707 (goto-char beg)
6708 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6709 (js2-set-face (match-beginning 1)
6710 (match-end 1)
6711 'js2-jsdoc-html-tag-delimiter)
6712 (js2-set-face (match-beginning 2)
6713 (match-end 2)
6714 'js2-jsdoc-html-tag-name)
6715 (js2-set-face (match-beginning 3)
6716 (match-end 3)
6717 'js2-jsdoc-html-tag-delimiter))))))))
6718
6719 (defun js2-highlight-assign-targets (_node left right)
6720 "Highlight function properties and external variables."
6721 (let (leftpos name)
6722 ;; highlight vars and props assigned function values
6723 (when (or (js2-function-node-p right)
6724 (js2-class-node-p right))
6725 (cond
6726 ;; var foo = function() {...}
6727 ((js2-name-node-p left)
6728 (setq name left))
6729 ;; foo.bar.baz = function() {...}
6730 ((and (js2-prop-get-node-p left)
6731 (js2-name-node-p (js2-prop-get-node-right left)))
6732 (setq name (js2-prop-get-node-right left))))
6733 (when name
6734 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6735 (+ leftpos (js2-node-len name))
6736 'font-lock-function-name-face
6737 'record)))))
6738
6739 (defun js2-record-name-node (node)
6740 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6741 later. NODE must be a name node."
6742 (let ((leftpos (js2-node-abs-pos node)))
6743 (push (list node js2-current-scope
6744 leftpos
6745 (+ leftpos (js2-node-len node)))
6746 js2-recorded-identifiers)))
6747
6748 (defun js2-highlight-undeclared-vars ()
6749 "After entire parse is finished, look for undeclared variable references.
6750 We have to wait until entire buffer is parsed, since JavaScript permits var
6751 decls to occur after they're used.
6752
6753 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6754 it is considered declared."
6755 (let (name)
6756 (dolist (entry js2-recorded-identifiers)
6757 (destructuring-bind (name-node scope pos end) entry
6758 (setq name (js2-name-node-name name-node))
6759 (unless (or (member name js2-global-externs)
6760 (member name js2-default-externs)
6761 (member name js2-additional-externs)
6762 (js2-get-defining-scope scope name))
6763 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6764 'js2-external-variable))))
6765 (setq js2-recorded-identifiers nil)))
6766
6767 (defun js2-set-default-externs ()
6768 "Set the value of `js2-default-externs' based on the various
6769 `js2-include-?-externs' variables."
6770 (setq js2-default-externs
6771 (append js2-ecma-262-externs
6772 (if js2-include-browser-externs js2-browser-externs)
6773 (if (and js2-include-browser-externs
6774 (>= js2-language-version 200)) js2-harmony-externs)
6775 (if js2-include-rhino-externs js2-rhino-externs)
6776 (if js2-include-node-externs js2-node-externs)
6777 (if (or js2-include-browser-externs js2-include-node-externs)
6778 js2-typed-array-externs))))
6779
6780 (defun js2-apply-jslint-globals ()
6781 (setq js2-additional-externs
6782 (nconc (js2-get-jslint-globals)
6783 js2-additional-externs)))
6784
6785 (defun js2-get-jslint-globals ()
6786 (loop for node in (js2-ast-root-comments js2-mode-ast)
6787 when (and (eq 'block (js2-comment-node-format node))
6788 (save-excursion
6789 (goto-char (js2-node-abs-pos node))
6790 (looking-at "/\\*global ")))
6791 append (js2-get-jslint-globals-in
6792 (match-end 0)
6793 (js2-node-abs-end node))))
6794
6795 (defun js2-get-jslint-globals-in (beg end)
6796 (let (res)
6797 (save-excursion
6798 (goto-char beg)
6799 (while (re-search-forward js2-mode-identifier-re end t)
6800 (let ((match (match-string 0)))
6801 (unless (member match '("true" "false"))
6802 (push match res)))))
6803 (nreverse res)))
6804
6805 ;;; IMenu support
6806
6807 ;; We currently only support imenu, but eventually should support speedbar and
6808 ;; possibly other browsing mechanisms.
6809
6810 ;; The basic strategy is to identify function assignment targets of the form
6811 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6812 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6813 ;; for imenu after parsing is finished.
6814
6815 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6816 ;; JavaScript, and the general problem is undecidable. However, several forms
6817 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6818 ;; include:
6819
6820 ;; function foo() -- function declaration
6821 ;; foo = function() -- function expression assigned to variable
6822 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6823 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6824 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6825 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6826 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6827 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6828 ;; function foo() {function bar() {...}} -- nested function
6829 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6830
6831 ;; This list boils down to a few forms that can be combined recursively.
6832 ;; Top-level named function declarations include both the left-hand (name)
6833 ;; and the right-hand (function value) expressions needed to produce an imenu
6834 ;; entry. The other "right-hand" forms we need to look for are:
6835 ;; - functions declared as props/getters/setters in object literals
6836 ;; - nested named function declarations
6837 ;; The "left-hand" expressions that functions can be assigned to include:
6838 ;; - local/global variables
6839 ;; - nested property-get expressions like a.b.c.d
6840 ;; - element gets like foo[10] or foo['bar'] where the index
6841 ;; expression can be trivially converted to a property name. They
6842 ;; effectively then become property gets.
6843
6844 ;; All the different definition types are canonicalized into the form
6845 ;; foo.bar.baz = position-of-function-keyword
6846
6847 ;; We need to build a trie-like structure for imenu. As an example,
6848 ;; consider the following JavaScript code:
6849
6850 ;; a = function() {...} // function at position 5
6851 ;; b = function() {...} // function at position 25
6852 ;; foo = function() {...} // function at position 100
6853 ;; foo.bar = function() {...} // function at position 200
6854 ;; foo.bar.baz = function() {...} // function at position 300
6855 ;; foo.bar.zab = function() {...} // function at position 400
6856
6857 ;; During parsing we accumulate an entry for each definition in
6858 ;; the variable `js2-imenu-recorder', like so:
6859
6860 ;; '((fn a 5)
6861 ;; (fn b 25)
6862 ;; (fn foo 100)
6863 ;; (fn foo bar 200)
6864 ;; (fn foo bar baz 300)
6865 ;; (fn foo bar zab 400))
6866
6867 ;; Where 'fn' is the respective function node.
6868 ;; After parsing these entries are merged into this alist-trie:
6869
6870 ;; '((a . 1)
6871 ;; (b . 2)
6872 ;; (foo (<definition> . 3)
6873 ;; (bar (<definition> . 6)
6874 ;; (baz . 100)
6875 ;; (zab . 200))))
6876
6877 ;; Note the wacky need for a <definition> name. The token can be anything
6878 ;; that isn't a valid JavaScript identifier, because you might make foo
6879 ;; a function and then start setting properties on it that are also functions.
6880
6881 (defun js2-prop-node-name (node)
6882 "Return the name of a node that may be a property-get/property-name.
6883 If NODE is not a valid name-node, string-node or integral number-node,
6884 returns nil. Otherwise returns the string name/value of the node."
6885 (cond
6886 ((js2-name-node-p node)
6887 (js2-name-node-name node))
6888 ((js2-string-node-p node)
6889 (js2-string-node-value node))
6890 ((and (js2-number-node-p node)
6891 (string-match "^[0-9]+$" (js2-number-node-value node)))
6892 (js2-number-node-value node))
6893 ((eq (js2-node-type node) js2-THIS)
6894 "this")
6895 ((eq (js2-node-type node) js2-SUPER)
6896 "super")))
6897
6898 (defun js2-node-qname-component (node)
6899 "Return the name of this node, if it contributes to a qname.
6900 Returns nil if the node doesn't contribute."
6901 (copy-sequence
6902 (or (js2-prop-node-name node)
6903 (if (and (js2-function-node-p node)
6904 (js2-function-node-name node))
6905 (js2-name-node-name (js2-function-node-name node))))))
6906
6907 (defun js2-record-imenu-entry (fn-node qname pos)
6908 "Add an entry to `js2-imenu-recorder'.
6909 FN-NODE should be the current item's function node.
6910
6911 Associate FN-NODE with its QNAME for later lookup.
6912 This is used in postprocessing the chain list. For each chain, we find
6913 the parent function, look up its qname, then prepend a copy of it to the chain."
6914 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6915 (unless js2-imenu-function-map
6916 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6917 (puthash fn-node qname js2-imenu-function-map))
6918
6919 (defun js2-record-imenu-functions (node &optional var)
6920 "Record function definitions for imenu.
6921 NODE is a function node or an object literal.
6922 VAR, if non-nil, is the expression that NODE is being assigned to.
6923 When passed arguments of wrong type, does nothing."
6924 (when js2-parse-ide-mode
6925 (let ((fun-p (js2-function-node-p node))
6926 qname fname-node)
6927 (cond
6928 ;; non-anonymous function declaration?
6929 ((and fun-p
6930 (not var)
6931 (setq fname-node (js2-function-node-name node)))
6932 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6933 ;; for remaining forms, compute left-side tree branch first
6934 ((and var (setq qname (js2-compute-nested-prop-get var)))
6935 (cond
6936 ;; foo.bar.baz = function
6937 (fun-p
6938 (js2-record-imenu-entry node qname (js2-node-pos node)))
6939 ;; foo.bar.baz = object-literal
6940 ;; look for nested functions: {a: {b: function() {...} }}
6941 ((js2-object-node-p node)
6942 ;; Node position here is still absolute, since the parser
6943 ;; passes the assignment target and value expressions
6944 ;; to us before they are added as children of the assignment node.
6945 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6946
6947 (defun js2-compute-nested-prop-get (node)
6948 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6949 component nodes as a list. Otherwise return nil. Element-gets are treated
6950 as property-gets if the index expression is a string, or a positive integer."
6951 (let (left right head)
6952 (cond
6953 ((or (js2-name-node-p node)
6954 (js2-this-or-super-node-p node))
6955 (list node))
6956 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6957 ((js2-prop-get-node-p node) ; foo.bar
6958 (setq left (js2-prop-get-node-left node)
6959 right (js2-prop-get-node-right node))
6960 (if (setq head (js2-compute-nested-prop-get left))
6961 (nconc head (list right))))
6962 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6963 (setq left (js2-elem-get-node-target node)
6964 right (js2-elem-get-node-element node))
6965 (if (or (js2-string-node-p right) ; ['bar']
6966 (and (js2-number-node-p right) ; [10]
6967 (string-match "^[0-9]+$"
6968 (js2-number-node-value right))))
6969 (if (setq head (js2-compute-nested-prop-get left))
6970 (nconc head (list right))))))))
6971
6972 (defun js2-record-object-literal (node qname pos)
6973 "Recursively process an object literal looking for functions.
6974 NODE is an object literal that is the right-hand child of an assignment
6975 expression. QNAME is a list of nodes representing the assignment target,
6976 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6977 POS is the absolute position of the node.
6978 We do a depth-first traversal of NODE. For any functions we find,
6979 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6980 (let (right)
6981 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6982 (let ((left (js2-infix-node-left e))
6983 ;; Element positions are relative to the parent position.
6984 (pos (+ pos (js2-node-pos e))))
6985 (cond
6986 ;; foo: function() {...}
6987 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6988 (when (js2-prop-node-name left)
6989 ;; As a policy decision, we record the position of the property,
6990 ;; not the position of the `function' keyword, since the property
6991 ;; is effectively the name of the function.
6992 (js2-record-imenu-entry right (append qname (list left)) pos)))
6993 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6994 ((js2-object-node-p right)
6995 (js2-record-object-literal right
6996 (append qname (list (js2-infix-node-left e)))
6997 (+ pos (js2-node-pos right)))))))))
6998
6999 (defun js2-node-top-level-decl-p (node)
7000 "Return t if NODE's name is defined in the top-level scope.
7001 Also returns t if NODE's name is not defined in any scope, since it implies
7002 that it's an external variable, which must also be in the top-level scope."
7003 (let* ((name (js2-prop-node-name node))
7004 (this-scope (js2-node-get-enclosing-scope node))
7005 defining-scope)
7006 (cond
7007 ((js2-this-or-super-node-p node)
7008 nil)
7009 ((null this-scope)
7010 t)
7011 ((setq defining-scope (js2-get-defining-scope this-scope name))
7012 (js2-ast-root-p defining-scope))
7013 (t t))))
7014
7015 (defun js2-wrapper-function-p (node)
7016 "Return t if NODE is a function expression that's immediately invoked.
7017 NODE must be `js2-function-node'."
7018 (let ((parent (js2-node-parent node)))
7019 (or
7020 ;; function(){...}();
7021 (and (js2-call-node-p parent)
7022 (eq node (js2-call-node-target parent)))
7023 (and (js2-paren-node-p parent)
7024 ;; (function(){...})();
7025 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7026 ;; (function(){...}).call(this);
7027 (and (js2-prop-get-node-p parent)
7028 (member (js2-name-node-name (js2-prop-get-node-right parent))
7029 '("call" "apply"))
7030 (js2-call-node-p (js2-node-parent parent))))))))
7031
7032 (defun js2-browse-postprocess-chains ()
7033 "Modify function-declaration name chains after parsing finishes.
7034 Some of the information is only available after the parse tree is complete.
7035 For instance, processing a nested scope requires a parent function node."
7036 (let (result fn parent-qname p elem)
7037 (dolist (entry js2-imenu-recorder)
7038 ;; function node goes first
7039 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7040 ;; Examine head's defining scope:
7041 ;; Pre-processed chain, or top-level/external, keep as-is.
7042 (if (or (stringp head) (js2-node-top-level-decl-p head))
7043 (push chain result)
7044 (when (js2-this-or-super-node-p head)
7045 (setq chain (cdr chain))) ; discard this-node
7046 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7047 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7048 (when (eq parent-qname 'not-found)
7049 ;; anonymous function expressions are not recorded
7050 ;; during the parse, so we need to handle this case here
7051 (setq parent-qname
7052 (if (js2-wrapper-function-p fn)
7053 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7054 (if (js2-ast-root-p grandparent)
7055 nil
7056 (gethash grandparent js2-imenu-function-map 'skip)))
7057 'skip))
7058 (puthash fn parent-qname js2-imenu-function-map))
7059 (if (eq parent-qname 'skip)
7060 ;; We don't show it, let's record that fact.
7061 (remhash current-fn js2-imenu-function-map)
7062 ;; Prepend parent fn qname to this chain.
7063 (let ((qname (append parent-qname chain)))
7064 (puthash current-fn (butlast qname) js2-imenu-function-map)
7065 (push qname result)))))))
7066 ;; Collect chains obtained by third-party code.
7067 (let (js2-imenu-recorder)
7068 (run-hooks 'js2-build-imenu-callbacks)
7069 (dolist (entry js2-imenu-recorder)
7070 (push (cdr entry) result)))
7071 ;; Finally replace each node in each chain with its name.
7072 (dolist (chain result)
7073 (setq p chain)
7074 (while p
7075 (if (js2-node-p (setq elem (car p)))
7076 (setcar p (js2-node-qname-component elem)))
7077 (setq p (cdr p))))
7078 result))
7079
7080 ;; Merge name chains into a trie-like tree structure of nested lists.
7081 ;; To simplify construction of the trie, we first build it out using the rule
7082 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7083 ;; [key, num-or-list]. The second element can be a number; if so, this key
7084 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7085 ;; associated with the key at this level.) Otherwise the second element is
7086 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7087 ;; a simple recursive formulation.
7088 ;;
7089 ;; js2-mode is building the data structure for imenu. The imenu documentation
7090 ;; claims that it's the structure above, but in practice it wants the children
7091 ;; at the same list level as the key for that level, which is how I've drawn
7092 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7093 ;; list wrapper around the children at each level.
7094 ;;
7095 ;; A completed nested imenu-alist entry looks like this:
7096 ;; '(("foo"
7097 ;; ("<definition>" . 7)
7098 ;; ("bar"
7099 ;; ("a" . 40)
7100 ;; ("b" . 60))))
7101 ;;
7102 ;; In particular, the documentation for `imenu--index-alist' says that
7103 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7104 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7105
7106 (defun js2-treeify (lst)
7107 "Convert (a b c d) to (a ((b ((c d)))))."
7108 (if (null (cddr lst)) ; list length <= 2
7109 lst
7110 (list (car lst) (list (js2-treeify (cdr lst))))))
7111
7112 (defun js2-build-alist-trie (chains trie)
7113 "Merge declaration name chains into a trie-like alist structure for imenu.
7114 CHAINS is the qname chain list produced during parsing. TRIE is a
7115 list of elements built up so far."
7116 (let (head tail pos branch kids)
7117 (dolist (chain chains)
7118 (setq head (car chain)
7119 tail (cdr chain)
7120 pos (if (numberp (car tail)) (car tail))
7121 branch (js2-find-if (lambda (n)
7122 (string= (car n) head))
7123 trie)
7124 kids (second branch))
7125 (cond
7126 ;; case 1: this key isn't in the trie yet
7127 ((null branch)
7128 (if trie
7129 (setcdr (last trie) (list (js2-treeify chain)))
7130 (setq trie (list (js2-treeify chain)))))
7131 ;; case 2: key is present with a single number entry: replace w/ list
7132 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7133 ;; ("<definition>" 20)))
7134 ((numberp kids)
7135 (setcar (cdr branch)
7136 (list (list "<definition-1>" kids)
7137 (if pos
7138 (list "<definition-2>" pos)
7139 (js2-treeify tail)))))
7140 ;; case 3: key is there (with kids), and we're a number entry
7141 (pos
7142 (setcdr (last kids)
7143 (list
7144 (list (format "<definition-%d>"
7145 (1+ (loop for kid in kids
7146 count (eq ?< (aref (car kid) 0)))))
7147 pos))))
7148 ;; case 4: key is there with kids, need to merge in our chain
7149 (t
7150 (js2-build-alist-trie (list tail) kids))))
7151 trie))
7152
7153 (defun js2-flatten-trie (trie)
7154 "Convert TRIE to imenu-format.
7155 Recurses through nodes, and for each one whose second element is a list,
7156 appends the list's flattened elements to the current element. Also
7157 changes the tails into conses. For instance, this pre-flattened trie
7158
7159 '(a ((b 20)
7160 (c ((d 30)
7161 (e 40)))))
7162
7163 becomes
7164
7165 '(a (b . 20)
7166 (c (d . 30)
7167 (e . 40)))
7168
7169 Note that the root of the trie has no key, just a list of chains.
7170 This is also true for the value of any key with multiple children,
7171 e.g. key 'c' in the example above."
7172 (cond
7173 ((listp (car trie))
7174 (mapcar #'js2-flatten-trie trie))
7175 (t
7176 (if (numberp (second trie))
7177 (cons (car trie) (second trie))
7178 ;; else pop list and append its kids
7179 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7180
7181 (defun js2-build-imenu-index ()
7182 "Turn `js2-imenu-recorder' into an imenu data structure."
7183 (when (eq js2-imenu-recorder 'empty)
7184 (setq js2-imenu-recorder nil))
7185 (let* ((chains (js2-browse-postprocess-chains))
7186 (result (js2-build-alist-trie chains nil)))
7187 (js2-flatten-trie result)))
7188
7189 (defun js2-test-print-chains (chains)
7190 "Print a list of qname chains.
7191 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7192 i.e. one or more nodes, and an integer position as the list tail."
7193 (mapconcat (lambda (chain)
7194 (concat "("
7195 (mapconcat (lambda (elem)
7196 (if (js2-node-p elem)
7197 (or (js2-node-qname-component elem)
7198 "nil")
7199 (number-to-string elem)))
7200 chain
7201 " ")
7202 ")"))
7203 chains
7204 "\n"))
7205
7206 ;;; Parser
7207
7208 (defconst js2-version "1.8.5"
7209 "Version of JavaScript supported.")
7210
7211 (defun js2-record-face (face &optional token)
7212 "Record a style run of FACE for TOKEN or the current token."
7213 (unless token (setq token (js2-current-token)))
7214 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7215
7216 (defsubst js2-node-end (n)
7217 "Computes the absolute end of node N.
7218 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7219 is only true until the node is added to its parent; i.e., while parsing."
7220 (+ (js2-node-pos n)
7221 (js2-node-len n)))
7222
7223 (defun js2-record-comment (token)
7224 "Record a comment in `js2-scanned-comments'."
7225 (let ((ct (js2-token-comment-type token))
7226 (beg (js2-token-beg token))
7227 (end (js2-token-end token)))
7228 (push (make-js2-comment-node :len (- end beg)
7229 :format ct)
7230 js2-scanned-comments)
7231 (when js2-parse-ide-mode
7232 (js2-record-face (if (eq ct 'jsdoc)
7233 'font-lock-doc-face
7234 'font-lock-comment-face)
7235 token)
7236 (when (memq ct '(html preprocessor))
7237 ;; Tell cc-engine the bounds of the comment.
7238 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7239
7240 (defun js2-peek-token ()
7241 "Return the next token type without consuming it.
7242 If `js2-ti-lookahead' is positive, return the type of next token
7243 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7244 (if (not (zerop js2-ti-lookahead))
7245 (js2-token-type
7246 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7247 (let ((tt (js2-get-token-internal nil)))
7248 (js2-unget-token)
7249 tt)))
7250
7251 (defalias 'js2-next-token 'js2-get-token)
7252
7253 (defun js2-match-token (match &optional dont-unget)
7254 "Get next token and return t if it matches MATCH, a bytecode.
7255 Returns nil and consumes nothing if MATCH is not the next token."
7256 (if (/= (js2-get-token) match)
7257 (ignore (unless dont-unget (js2-unget-token)))
7258 t))
7259
7260 (defun js2-match-contextual-kwd (name)
7261 "Consume and return t if next token is `js2-NAME', and its
7262 string is NAME. Returns nil and keeps current token otherwise."
7263 (if (or (/= (js2-get-token) js2-NAME)
7264 (not (string= (js2-current-token-string) name)))
7265 (progn
7266 (js2-unget-token)
7267 nil)
7268 (js2-record-face 'font-lock-keyword-face)
7269 t))
7270
7271 (defun js2-valid-prop-name-token (tt)
7272 (or (= tt js2-NAME)
7273 (and js2-allow-keywords-as-property-names
7274 (plusp tt)
7275 (or (= tt js2-RESERVED)
7276 (aref js2-kwd-tokens tt)))))
7277
7278 (defun js2-match-prop-name ()
7279 "Consume token and return t if next token is a valid property name.
7280 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7281 is non-nil and it's a keyword token."
7282 (if (js2-valid-prop-name-token (js2-get-token))
7283 t
7284 (js2-unget-token)
7285 nil))
7286
7287 (defun js2-must-match-prop-name (msg-id &optional pos len)
7288 (if (js2-match-prop-name)
7289 t
7290 (js2-report-error msg-id nil pos len)
7291 nil))
7292
7293 (defun js2-peek-token-or-eol ()
7294 "Return js2-EOL if the next token immediately follows a newline.
7295 Else returns the next token. Used in situations where we don't
7296 consider certain token types valid if they are preceded by a newline.
7297 One example is the postfix ++ or -- operator, which has to be on the
7298 same line as its operand."
7299 (let ((tt (js2-get-token))
7300 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7301 (js2-unget-token)
7302 (if follows-eol
7303 js2-EOL
7304 tt)))
7305
7306 (defun js2-must-match (token msg-id &optional pos len)
7307 "Match next token to token code TOKEN, or record a syntax error.
7308 MSG-ID is the error message to report if the match fails.
7309 Returns t on match, nil if no match."
7310 (if (js2-match-token token t)
7311 t
7312 (js2-report-error msg-id nil pos len)
7313 (js2-unget-token)
7314 nil))
7315
7316 (defun js2-must-match-name (msg-id)
7317 (if (js2-match-token js2-NAME t)
7318 t
7319 (if (eq (js2-current-token-type) js2-RESERVED)
7320 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7321 (js2-report-error msg-id)
7322 (js2-unget-token))
7323 nil))
7324
7325 (defsubst js2-inside-function ()
7326 (plusp js2-nesting-of-function))
7327
7328 (defun js2-set-requires-activation ()
7329 (if (js2-function-node-p js2-current-script-or-fn)
7330 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7331
7332 (defun js2-check-activation-name (name _token)
7333 (when (js2-inside-function)
7334 ;; skip language-version 1.2 check from Rhino
7335 (if (or (string= "arguments" name)
7336 (and js2-compiler-activation-names ; only used in codegen
7337 (gethash name js2-compiler-activation-names)))
7338 (js2-set-requires-activation))))
7339
7340 (defun js2-set-is-generator ()
7341 (let ((fn-node js2-current-script-or-fn))
7342 (when (and (js2-function-node-p fn-node)
7343 (not (js2-function-node-generator-type fn-node)))
7344 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7345
7346 (defun js2-must-have-xml ()
7347 (unless js2-compiler-xml-available
7348 (js2-report-error "msg.XML.not.available")))
7349
7350 (defun js2-push-scope (scope)
7351 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7352 (assert (js2-scope-p scope))
7353 (assert (null (js2-scope-parent-scope scope)))
7354 (assert (not (eq js2-current-scope scope)))
7355 (setf (js2-scope-parent-scope scope) js2-current-scope
7356 js2-current-scope scope))
7357
7358 (defsubst js2-pop-scope ()
7359 (setq js2-current-scope
7360 (js2-scope-parent-scope js2-current-scope)))
7361
7362 (defun js2-enter-loop (loop-node)
7363 (push loop-node js2-loop-set)
7364 (push loop-node js2-loop-and-switch-set)
7365 (js2-push-scope loop-node)
7366 ;; Tell the current labeled statement (if any) its statement,
7367 ;; and set the jump target of the first label to the loop.
7368 ;; These are used in `js2-parse-continue' to verify that the
7369 ;; continue target is an actual labeled loop. (And for codegen.)
7370 (when js2-labeled-stmt
7371 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7372 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7373 js2-labeled-stmt))) loop-node)))
7374
7375 (defun js2-exit-loop ()
7376 (pop js2-loop-set)
7377 (pop js2-loop-and-switch-set)
7378 (js2-pop-scope))
7379
7380 (defsubst js2-enter-switch (switch-node)
7381 (push switch-node js2-loop-and-switch-set))
7382
7383 (defsubst js2-exit-switch ()
7384 (pop js2-loop-and-switch-set))
7385
7386 (defun js2-parse (&optional buf cb)
7387 "Tell the js2 parser to parse a region of JavaScript.
7388
7389 BUF is a buffer or buffer name containing the code to parse.
7390 Call `narrow-to-region' first to parse only part of the buffer.
7391
7392 The returned AST root node is given some additional properties:
7393 `node-count' - total number of nodes in the AST
7394 `buffer' - BUF. The buffer it refers to may change or be killed,
7395 so the value is not necessarily reliable.
7396
7397 An optional callback CB can be specified to report parsing
7398 progress. If `(functionp CB)' returns t, it will be called with
7399 the current line number once before parsing begins, then again
7400 each time the lexer reaches a new line number.
7401
7402 CB can also be a list of the form `(symbol cb ...)' to specify
7403 multiple callbacks with different criteria. Each symbol is a
7404 criterion keyword, and the following element is the callback to
7405 call
7406
7407 :line - called whenever the line number changes
7408 :token - called for each new token consumed
7409
7410 The list of criteria could be extended to include entering or
7411 leaving a statement, an expression, or a function definition."
7412 (if (and cb (not (functionp cb)))
7413 (error "criteria callbacks not yet implemented"))
7414 (let ((inhibit-point-motion-hooks t)
7415 (js2-compiler-xml-available (>= js2-language-version 160))
7416 ;; This is a recursive-descent parser, so give it a big stack.
7417 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7418 (max-specpdl-size (max max-specpdl-size 3000))
7419 (case-fold-search nil)
7420 ast)
7421 (with-current-buffer (or buf (current-buffer))
7422 (setq js2-scanned-comments nil
7423 js2-parsed-errors nil
7424 js2-parsed-warnings nil
7425 js2-imenu-recorder nil
7426 js2-imenu-function-map nil
7427 js2-label-set nil)
7428 (js2-init-scanner)
7429 (setq ast (with-silent-modifications
7430 (js2-do-parse)))
7431 (unless js2-ts-hit-eof
7432 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7433 (setf (js2-ast-root-errors ast) js2-parsed-errors
7434 (js2-ast-root-warnings ast) js2-parsed-warnings)
7435 ;; if we didn't find any declarations, put a dummy in this list so we
7436 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7437 (unless js2-imenu-recorder
7438 (setq js2-imenu-recorder 'empty))
7439 (run-hooks 'js2-parse-finished-hook)
7440 ast)))
7441
7442 ;; Corresponds to Rhino's Parser.parse() method.
7443 (defun js2-do-parse ()
7444 "Parse current buffer starting from current point.
7445 Scanner should be initialized."
7446 (let ((pos js2-ts-cursor)
7447 (end js2-ts-cursor) ; in case file is empty
7448 root n tt)
7449 ;; initialize buffer-local parsing vars
7450 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7451 js2-current-script-or-fn root
7452 js2-current-scope root
7453 js2-nesting-of-function 0
7454 js2-labeled-stmt nil
7455 js2-recorded-identifiers nil) ; for js2-highlight
7456 (while (/= (setq tt (js2-get-token)) js2-EOF)
7457 (if (= tt js2-FUNCTION)
7458 (progn
7459 (setq n (if js2-called-by-compile-function
7460 (js2-parse-function-expr)
7461 (js2-parse-function-stmt))))
7462 ;; not a function - parse a statement
7463 (js2-unget-token)
7464 (setq n (js2-parse-statement)))
7465 ;; add function or statement to script
7466 (setq end (js2-node-end n))
7467 (js2-block-node-push root n))
7468 ;; add comments to root in lexical order
7469 (when js2-scanned-comments
7470 ;; if we find a comment beyond end of normal kids, use its end
7471 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7472 (dolist (comment js2-scanned-comments)
7473 (push comment (js2-ast-root-comments root))
7474 (js2-node-add-children root comment)))
7475 (setf (js2-node-len root) (- end pos))
7476 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7477 ;; Give extensions a chance to muck with things before highlighting starts.
7478 (let ((js2-additional-externs js2-additional-externs))
7479 (save-excursion
7480 (run-hooks 'js2-post-parse-callbacks))
7481 (js2-highlight-undeclared-vars))
7482 root))
7483
7484 (defun js2-parse-function-closure-body (fn-node)
7485 "Parse a JavaScript 1.8 function closure body."
7486 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7487 (if js2-ts-hit-eof
7488 (js2-report-error "msg.no.brace.body" nil
7489 (js2-node-pos fn-node)
7490 (- js2-ts-cursor (js2-node-pos fn-node)))
7491 (js2-node-add-children fn-node
7492 (setf (js2-function-node-body fn-node)
7493 (js2-parse-expr t))))))
7494
7495 (defun js2-parse-function-body (fn-node)
7496 (js2-must-match js2-LC "msg.no.brace.body"
7497 (js2-node-pos fn-node)
7498 (- js2-ts-cursor (js2-node-pos fn-node)))
7499 (let ((pos (js2-current-token-beg)) ; LC position
7500 (pn (make-js2-block-node)) ; starts at LC position
7501 tt
7502 end)
7503 (incf js2-nesting-of-function)
7504 (unwind-protect
7505 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7506 (= tt js2-EOF)
7507 (= tt js2-RC)))
7508 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7509 (js2-parse-statement)
7510 (js2-get-token)
7511 (js2-parse-function-stmt))))
7512 (decf js2-nesting-of-function))
7513 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7514 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7515 (setq end (js2-current-token-end)))
7516 (setf (js2-node-pos pn) pos
7517 (js2-node-len pn) (- end pos))
7518 (setf (js2-function-node-body fn-node) pn)
7519 (js2-node-add-children fn-node pn)
7520 pn))
7521
7522 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7523 "Declare and fontify destructuring parameters inside NODE.
7524 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7525 (cond
7526 ((js2-name-node-p node)
7527 (let (leftpos)
7528 (js2-define-symbol decl-type (js2-name-node-name node)
7529 node ignore-not-in-block)
7530 (when face
7531 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7532 (+ leftpos (js2-node-len node))
7533 face 'record))))
7534 ((js2-object-node-p node)
7535 (dolist (elem (js2-object-node-elems node))
7536 (js2-define-destruct-symbols
7537 ;; In abbreviated destructuring {a, b}, right == left.
7538 (js2-object-prop-node-right elem)
7539 decl-type face ignore-not-in-block)))
7540 ((js2-array-node-p node)
7541 (dolist (elem (js2-array-node-elems node))
7542 (when elem
7543 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7544 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7545 (js2-node-len node)))))
7546
7547 (defun js2-parse-function-params (function-type fn-node pos)
7548 (if (js2-match-token js2-RP)
7549 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7550 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7551 (eq (js2-current-token-type) js2-NAME)))
7552 params param default-found rest-param-at)
7553 (when paren-free-arrow
7554 (js2-unget-token))
7555 (loop for tt = (js2-peek-token)
7556 do
7557 (cond
7558 ;; destructuring param
7559 ((and (not paren-free-arrow)
7560 (or (= tt js2-LB) (= tt js2-LC)))
7561 (js2-get-token)
7562 (when default-found
7563 (js2-report-error "msg.no.default.after.default.param"))
7564 (setq param (js2-parse-destruct-primary-expr))
7565 (js2-define-destruct-symbols param
7566 js2-LP
7567 'js2-function-param)
7568 (push param params))
7569 ;; variable name
7570 (t
7571 (when (and (>= js2-language-version 200)
7572 (not paren-free-arrow)
7573 (js2-match-token js2-TRIPLEDOT)
7574 (not rest-param-at))
7575 ;; to report errors if there are more parameters
7576 (setq rest-param-at (length params)))
7577 (js2-must-match-name "msg.no.parm")
7578 (js2-record-face 'js2-function-param)
7579 (setq param (js2-create-name-node))
7580 (js2-define-symbol js2-LP (js2-current-token-string) param)
7581 ;; default parameter value
7582 (when (or (and default-found
7583 (not rest-param-at)
7584 (js2-must-match js2-ASSIGN
7585 "msg.no.default.after.default.param"
7586 (js2-node-pos param)
7587 (js2-node-len param)))
7588 (and (>= js2-language-version 200)
7589 (js2-match-token js2-ASSIGN)))
7590 (assert (not paren-free-arrow))
7591 (let* ((pos (js2-node-pos param))
7592 (tt (js2-current-token-type))
7593 (op-pos (- (js2-current-token-beg) pos))
7594 (left param)
7595 (right (js2-parse-assign-expr))
7596 (len (- (js2-node-end right) pos)))
7597 (setq param (make-js2-assign-node
7598 :type tt :pos pos :len len :op-pos op-pos
7599 :left left :right right)
7600 default-found t)
7601 (js2-node-add-children param left right)))
7602 (push param params)))
7603 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7604 (js2-report-error "msg.param.after.rest" nil
7605 (js2-node-pos param) (js2-node-len param)))
7606 while
7607 (js2-match-token js2-COMMA))
7608 (when (and (not paren-free-arrow)
7609 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7610 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7611 (when rest-param-at
7612 (setf (js2-function-node-rest-p fn-node) t))
7613 (dolist (p params)
7614 (js2-node-add-children fn-node p)
7615 (push p (js2-function-node-params fn-node))))))
7616
7617 (defun js2-check-inconsistent-return-warning (fn-node name)
7618 "Possibly show inconsistent-return warning.
7619 Last token scanned is the close-curly for the function body."
7620 (when (and js2-mode-show-strict-warnings
7621 js2-strict-inconsistent-return-warning
7622 (not (js2-has-consistent-return-usage
7623 (js2-function-node-body fn-node))))
7624 ;; Have it extend from close-curly to bol or beginning of block.
7625 (let ((pos (save-excursion
7626 (goto-char (js2-current-token-end))
7627 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7628 (point-at-bol))))
7629 (end (js2-current-token-end)))
7630 (if (plusp (js2-name-node-length name))
7631 (js2-add-strict-warning "msg.no.return.value"
7632 (js2-name-node-name name) pos end)
7633 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7634
7635 (defun js2-parse-function-stmt ()
7636 (let ((pos (js2-current-token-beg))
7637 (star-p (js2-match-token js2-MUL)))
7638 (js2-must-match-name "msg.unnamed.function.stmt")
7639 (let ((name (js2-create-name-node t))
7640 pn member-expr)
7641 (cond
7642 ((js2-match-token js2-LP)
7643 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7644 (js2-allow-member-expr-as-function-name
7645 (setq member-expr (js2-parse-member-expr-tail nil name))
7646 (js2-parse-highlight-member-expr-fn-name member-expr)
7647 (js2-must-match js2-LP "msg.no.paren.parms")
7648 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7649 (js2-function-node-member-expr pn) member-expr)
7650 pn)
7651 (t
7652 (js2-report-error "msg.no.paren.parms")
7653 (make-js2-error-node))))))
7654
7655 (defun js2-parse-function-expr ()
7656 (let ((pos (js2-current-token-beg))
7657 (star-p (js2-match-token js2-MUL))
7658 name)
7659 (when (js2-match-token js2-NAME)
7660 (setq name (js2-create-name-node t)))
7661 (js2-must-match js2-LP "msg.no.paren.parms")
7662 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7663
7664 (defun js2-parse-function (function-type pos star-p &optional name)
7665 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7666 beginning of the first token (function keyword, unless it's an
7667 arrow function), NAME is js2-name-node."
7668 (let (fn-node lp)
7669 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7670 (setq lp (js2-current-token-beg)))
7671 (setf fn-node (make-js2-function-node :pos pos
7672 :name name
7673 :form function-type
7674 :lp (if lp (- lp pos))
7675 :generator-type (and star-p 'STAR)))
7676 (when name
7677 (js2-set-face (js2-node-pos name) (js2-node-end name)
7678 'font-lock-function-name-face 'record)
7679 (when (plusp (js2-name-node-length name))
7680 ;; Function statements define a symbol in the enclosing scope
7681 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7682 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7683 ;; 1. Nested functions are not affected by the dynamic scope flag
7684 ;; as dynamic scope is already a parent of their scope.
7685 ;; 2. Functions defined under the with statement also immune to
7686 ;; this setup, in which case dynamic scope is ignored in favor
7687 ;; of the with object.
7688 (setf (js2-function-node-ignore-dynamic fn-node) t))
7689 ;; dynamically bind all the per-function variables
7690 (let ((js2-current-script-or-fn fn-node)
7691 (js2-current-scope fn-node)
7692 (js2-nesting-of-with 0)
7693 (js2-end-flags 0)
7694 js2-label-set
7695 js2-loop-set
7696 js2-loop-and-switch-set)
7697 (js2-parse-function-params function-type fn-node pos)
7698 (when (eq function-type 'FUNCTION_ARROW)
7699 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7700 (if (and (>= js2-language-version 180)
7701 (/= (js2-peek-token) js2-LC))
7702 (js2-parse-function-closure-body fn-node)
7703 (js2-parse-function-body fn-node))
7704 (js2-check-inconsistent-return-warning fn-node name)
7705
7706 (when name
7707 (js2-node-add-children fn-node name)
7708 ;; Function expressions define a name only in the body of the
7709 ;; function, and only if not hidden by a parameter name
7710 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7711 (null (js2-scope-get-symbol js2-current-scope
7712 (js2-name-node-name name))))
7713 (js2-define-symbol js2-FUNCTION
7714 (js2-name-node-name name)
7715 fn-node))
7716 (when (eq function-type 'FUNCTION_STATEMENT)
7717 (js2-record-imenu-functions fn-node))))
7718
7719 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7720 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7721 ;; We wait until after parsing the function to set its parent scope,
7722 ;; since `js2-define-symbol' needs the defining-scope check to stop
7723 ;; at the function boundary when checking for redeclarations.
7724 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7725 fn-node))
7726
7727 (defun js2-parse-statements (&optional parent)
7728 "Parse a statement list. Last token consumed must be js2-LC.
7729
7730 PARENT can be a `js2-block-node', in which case the statements are
7731 appended to PARENT. Otherwise a new `js2-block-node' is created
7732 and returned.
7733
7734 This function does not match the closing js2-RC: the caller
7735 matches the RC so it can provide a suitable error message if not
7736 matched. This means it's up to the caller to set the length of
7737 the node to include the closing RC. The node start pos is set to
7738 the absolute buffer start position, and the caller should fix it
7739 up to be relative to the parent node. All children of this block
7740 node are given relative start positions and correct lengths."
7741 (let ((pn (or parent (make-js2-block-node)))
7742 tt)
7743 (setf (js2-node-pos pn) (js2-current-token-beg))
7744 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7745 (/= tt js2-RC))
7746 (js2-block-node-push pn (js2-parse-statement)))
7747 pn))
7748
7749 (defun js2-parse-statement ()
7750 (let (pn beg end)
7751 ;; coarse-grained user-interrupt check - needs work
7752 (and js2-parse-interruptable-p
7753 (zerop (% (incf js2-parse-stmt-count)
7754 js2-statements-per-pause))
7755 (input-pending-p)
7756 (throw 'interrupted t))
7757 (setq pn (js2-statement-helper))
7758 ;; no-side-effects warning check
7759 (unless (js2-node-has-side-effects pn)
7760 (setq end (js2-node-end pn))
7761 (save-excursion
7762 (goto-char end)
7763 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7764 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7765 pn))
7766
7767 ;; These correspond to the switch cases in Parser.statementHelper
7768 (defconst js2-parsers
7769 (let ((parsers (make-vector js2-num-tokens
7770 #'js2-parse-expr-stmt)))
7771 (aset parsers js2-BREAK #'js2-parse-break)
7772 (aset parsers js2-CLASS #'js2-parse-class-stmt)
7773 (aset parsers js2-CONST #'js2-parse-const-var)
7774 (aset parsers js2-CONTINUE #'js2-parse-continue)
7775 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7776 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7777 (aset parsers js2-DO #'js2-parse-do)
7778 (aset parsers js2-FOR #'js2-parse-for)
7779 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7780 (aset parsers js2-IF #'js2-parse-if)
7781 (aset parsers js2-LC #'js2-parse-block)
7782 (aset parsers js2-LET #'js2-parse-let-stmt)
7783 (aset parsers js2-NAME #'js2-parse-name-or-label)
7784 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7785 (aset parsers js2-SEMI #'js2-parse-semi)
7786 (aset parsers js2-SWITCH #'js2-parse-switch)
7787 (aset parsers js2-THROW #'js2-parse-throw)
7788 (aset parsers js2-TRY #'js2-parse-try)
7789 (aset parsers js2-VAR #'js2-parse-const-var)
7790 (aset parsers js2-WHILE #'js2-parse-while)
7791 (aset parsers js2-WITH #'js2-parse-with)
7792 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7793 parsers)
7794 "A vector mapping token types to parser functions.")
7795
7796 (defun js2-parse-warn-missing-semi (beg end)
7797 (and js2-mode-show-strict-warnings
7798 js2-strict-missing-semi-warning
7799 (js2-add-strict-warning
7800 "msg.missing.semi" nil
7801 ;; back up to beginning of statement or line
7802 (max beg (save-excursion
7803 (goto-char end)
7804 (point-at-bol)))
7805 end)))
7806
7807 (defconst js2-no-semi-insertion
7808 (list js2-IF
7809 js2-SWITCH
7810 js2-WHILE
7811 js2-DO
7812 js2-FOR
7813 js2-TRY
7814 js2-WITH
7815 js2-LC
7816 js2-ERROR
7817 js2-SEMI
7818 js2-CLASS
7819 js2-FUNCTION)
7820 "List of tokens that don't do automatic semicolon insertion.")
7821
7822 (defconst js2-autoinsert-semi-and-warn
7823 (list js2-ERROR js2-EOF js2-RC))
7824
7825 (defun js2-statement-helper ()
7826 (let* ((tt (js2-get-token))
7827 (first-tt tt)
7828 (parser (if (= tt js2-ERROR)
7829 #'js2-parse-semi
7830 (aref js2-parsers tt)))
7831 pn)
7832 ;; If the statement is set, then it's been told its label by now.
7833 (and js2-labeled-stmt
7834 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7835 (setq js2-labeled-stmt nil))
7836 (setq pn (funcall parser))
7837 ;; Don't do auto semi insertion for certain statement types.
7838 (unless (or (memq first-tt js2-no-semi-insertion)
7839 (js2-labeled-stmt-node-p pn))
7840 (js2-auto-insert-semicolon pn))
7841 pn))
7842
7843 (defun js2-auto-insert-semicolon (pn)
7844 (let* ((tt (js2-get-token))
7845 (pos (js2-node-pos pn)))
7846 (cond
7847 ((= tt js2-SEMI)
7848 ;; extend the node bounds to include the semicolon.
7849 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7850 ((memq tt js2-autoinsert-semi-and-warn)
7851 (js2-unget-token) ; Not ';', do not consume.
7852 ;; Autoinsert ;
7853 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7854 (t
7855 (if (not (js2-token-follows-eol-p (js2-current-token)))
7856 ;; Report error if no EOL or autoinsert ';' otherwise
7857 (js2-report-error "msg.no.semi.stmt")
7858 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7859 (js2-unget-token) ; Not ';', do not consume.
7860 ))))
7861
7862 (defun js2-parse-condition ()
7863 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7864 The parens are discarded and the expression node is returned.
7865 The `pos' field of the return value is set to an absolute position
7866 that must be fixed up by the caller.
7867 Return value is a list (EXPR LP RP), with absolute paren positions."
7868 (let (pn lp rp)
7869 (if (js2-must-match js2-LP "msg.no.paren.cond")
7870 (setq lp (js2-current-token-beg)))
7871 (setq pn (js2-parse-expr))
7872 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7873 (setq rp (js2-current-token-beg)))
7874 ;; Report strict warning on code like "if (a = 7) ..."
7875 (if (and js2-strict-cond-assign-warning
7876 (js2-assign-node-p pn))
7877 (js2-add-strict-warning "msg.equal.as.assign" nil
7878 (js2-node-pos pn)
7879 (+ (js2-node-pos pn)
7880 (js2-node-len pn))))
7881 (list pn lp rp)))
7882
7883 (defun js2-parse-if ()
7884 "Parser for if-statement. Last matched token must be js2-IF."
7885 (let ((pos (js2-current-token-beg))
7886 cond if-true if-false else-pos end pn)
7887 (setq cond (js2-parse-condition)
7888 if-true (js2-parse-statement)
7889 if-false (if (js2-match-token js2-ELSE)
7890 (progn
7891 (setq else-pos (- (js2-current-token-beg) pos))
7892 (js2-parse-statement)))
7893 end (js2-node-end (or if-false if-true))
7894 pn (make-js2-if-node :pos pos
7895 :len (- end pos)
7896 :condition (car cond)
7897 :then-part if-true
7898 :else-part if-false
7899 :else-pos else-pos
7900 :lp (js2-relpos (second cond) pos)
7901 :rp (js2-relpos (third cond) pos)))
7902 (js2-node-add-children pn (car cond) if-true if-false)
7903 pn))
7904
7905 (defun js2-parse-switch ()
7906 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7907 (let ((pos (js2-current-token-beg))
7908 tt pn discriminant has-default case-expr case-node
7909 case-pos cases stmt lp)
7910 (if (js2-must-match js2-LP "msg.no.paren.switch")
7911 (setq lp (js2-current-token-beg)))
7912 (setq discriminant (js2-parse-expr)
7913 pn (make-js2-switch-node :discriminant discriminant
7914 :pos pos
7915 :lp (js2-relpos lp pos)))
7916 (js2-node-add-children pn discriminant)
7917 (js2-enter-switch pn)
7918 (unwind-protect
7919 (progn
7920 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7921 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7922 (js2-must-match js2-LC "msg.no.brace.switch")
7923 (catch 'break
7924 (while t
7925 (setq tt (js2-next-token)
7926 case-pos (js2-current-token-beg))
7927 (cond
7928 ((= tt js2-RC)
7929 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7930 (throw 'break nil)) ; done
7931 ((= tt js2-CASE)
7932 (setq case-expr (js2-parse-expr))
7933 (js2-must-match js2-COLON "msg.no.colon.case"))
7934 ((= tt js2-DEFAULT)
7935 (if has-default
7936 (js2-report-error "msg.double.switch.default"))
7937 (setq has-default t
7938 case-expr nil)
7939 (js2-must-match js2-COLON "msg.no.colon.case"))
7940 (t
7941 (js2-report-error "msg.bad.switch")
7942 (throw 'break nil)))
7943 (setq case-node (make-js2-case-node :pos case-pos
7944 :len (- (js2-current-token-end) case-pos)
7945 :expr case-expr))
7946 (js2-node-add-children case-node case-expr)
7947 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7948 (/= tt js2-CASE)
7949 (/= tt js2-DEFAULT)
7950 (/= tt js2-EOF))
7951 (setf stmt (js2-parse-statement)
7952 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7953 (js2-block-node-push case-node stmt))
7954 (push case-node cases)))
7955 ;; add cases last, as pushing reverses the order to be correct
7956 (dolist (kid cases)
7957 (js2-node-add-children pn kid)
7958 (push kid (js2-switch-node-cases pn)))
7959 pn) ; return value
7960 (js2-exit-switch))))
7961
7962 (defun js2-parse-while ()
7963 "Parser for while-statement. Last matched token must be js2-WHILE."
7964 (let ((pos (js2-current-token-beg))
7965 (pn (make-js2-while-node))
7966 cond body)
7967 (js2-enter-loop pn)
7968 (unwind-protect
7969 (progn
7970 (setf cond (js2-parse-condition)
7971 (js2-while-node-condition pn) (car cond)
7972 body (js2-parse-statement)
7973 (js2-while-node-body pn) body
7974 (js2-node-len pn) (- (js2-node-end body) pos)
7975 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7976 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7977 (js2-node-add-children pn body (car cond)))
7978 (js2-exit-loop))
7979 pn))
7980
7981 (defun js2-parse-do ()
7982 "Parser for do-statement. Last matched token must be js2-DO."
7983 (let ((pos (js2-current-token-beg))
7984 (pn (make-js2-do-node))
7985 cond body end)
7986 (js2-enter-loop pn)
7987 (unwind-protect
7988 (progn
7989 (setq body (js2-parse-statement))
7990 (js2-must-match js2-WHILE "msg.no.while.do")
7991 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7992 cond (js2-parse-condition)
7993 (js2-do-node-condition pn) (car cond)
7994 (js2-do-node-body pn) body
7995 end js2-ts-cursor
7996 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7997 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7998 (js2-node-add-children pn (car cond) body))
7999 (js2-exit-loop))
8000 ;; Always auto-insert semicolon to follow SpiderMonkey:
8001 ;; It is required by ECMAScript but is ignored by the rest of
8002 ;; world; see bug 238945
8003 (if (js2-match-token js2-SEMI)
8004 (setq end js2-ts-cursor))
8005 (setf (js2-node-len pn) (- end pos))
8006 pn))
8007
8008 (defun js2-parse-for ()
8009 "Parser for for-statement. Last matched token must be js2-FOR.
8010 Parses for, for-in, and for each-in statements."
8011 (let ((for-pos (js2-current-token-beg))
8012 pn is-for-each is-for-in-or-of is-for-of
8013 in-pos each-pos tmp-pos
8014 init ; Node init is also foo in 'foo in object'
8015 cond ; Node cond is also object in 'foo in object'
8016 incr ; 3rd section of for-loop initializer
8017 body tt lp rp)
8018 ;; See if this is a for each () instead of just a for ()
8019 (when (js2-match-token js2-NAME)
8020 (if (string= "each" (js2-current-token-string))
8021 (progn
8022 (setq is-for-each t
8023 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8024 (js2-record-face 'font-lock-keyword-face))
8025 (js2-report-error "msg.no.paren.for")))
8026 (if (js2-must-match js2-LP "msg.no.paren.for")
8027 (setq lp (- (js2-current-token-beg) for-pos)))
8028 (setq tt (js2-get-token))
8029 ;; 'for' makes local scope
8030 (js2-push-scope (make-js2-scope))
8031 (unwind-protect
8032 ;; parse init clause
8033 (let ((js2-in-for-init t)) ; set as dynamic variable
8034 (cond
8035 ((= tt js2-SEMI)
8036 (js2-unget-token)
8037 (setq init (make-js2-empty-expr-node)))
8038 ((or (= tt js2-VAR) (= tt js2-LET))
8039 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8040 (t
8041 (js2-unget-token)
8042 (setq init (js2-parse-expr)))))
8043 (if (or (js2-match-token js2-IN)
8044 (and (>= js2-language-version 200)
8045 (js2-match-contextual-kwd "of")
8046 (setq is-for-of t)))
8047 (setq is-for-in-or-of t
8048 in-pos (- (js2-current-token-beg) for-pos)
8049 ;; scope of iteration target object is not the scope we've created above.
8050 ;; stash current scope temporary.
8051 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8052 (js2-parse-expr))) ; object over which we're iterating
8053 ;; else ordinary for loop - parse cond and incr
8054 (js2-must-match js2-SEMI "msg.no.semi.for")
8055 (setq cond (if (= (js2-peek-token) js2-SEMI)
8056 (make-js2-empty-expr-node) ; no loop condition
8057 (js2-parse-expr)))
8058 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8059 (setq tmp-pos (js2-current-token-end)
8060 incr (if (= (js2-peek-token) js2-RP)
8061 (make-js2-empty-expr-node :pos tmp-pos)
8062 (js2-parse-expr))))
8063 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8064 (setq rp (- (js2-current-token-beg) for-pos)))
8065 (if (not is-for-in-or-of)
8066 (setq pn (make-js2-for-node :init init
8067 :condition cond
8068 :update incr
8069 :lp lp
8070 :rp rp))
8071 ;; cond could be null if 'in obj' got eaten by the init node.
8072 (if (js2-infix-node-p init)
8073 ;; it was (foo in bar) instead of (var foo in bar)
8074 (setq cond (js2-infix-node-right init)
8075 init (js2-infix-node-left init))
8076 (if (and (js2-var-decl-node-p init)
8077 (> (length (js2-var-decl-node-kids init)) 1))
8078 (js2-report-error "msg.mult.index")))
8079 (setq pn (make-js2-for-in-node :iterator init
8080 :object cond
8081 :in-pos in-pos
8082 :foreach-p is-for-each
8083 :each-pos each-pos
8084 :forof-p is-for-of
8085 :lp lp
8086 :rp rp)))
8087 (unwind-protect
8088 (progn
8089 (js2-enter-loop pn)
8090 ;; We have to parse the body -after- creating the loop node,
8091 ;; so that the loop node appears in the js2-loop-set, allowing
8092 ;; break/continue statements to find the enclosing loop.
8093 (setf body (js2-parse-statement)
8094 (js2-loop-node-body pn) body
8095 (js2-node-pos pn) for-pos
8096 (js2-node-len pn) (- (js2-node-end body) for-pos))
8097 (js2-node-add-children pn init cond incr body))
8098 ;; finally
8099 (js2-exit-loop))
8100 (js2-pop-scope))
8101 pn))
8102
8103 (defun js2-parse-try ()
8104 "Parser for try-statement. Last matched token must be js2-TRY."
8105 (let ((try-pos (js2-current-token-beg))
8106 try-end
8107 try-block
8108 catch-blocks
8109 finally-block
8110 saw-default-catch
8111 peek
8112 param
8113 catch-cond
8114 catch-node
8115 guard-kwd
8116 catch-pos
8117 finally-pos
8118 pn
8119 block
8120 lp
8121 rp)
8122 (if (/= (js2-peek-token) js2-LC)
8123 (js2-report-error "msg.no.brace.try"))
8124 (setq try-block (js2-parse-statement)
8125 try-end (js2-node-end try-block)
8126 peek (js2-peek-token))
8127 (cond
8128 ((= peek js2-CATCH)
8129 (while (js2-match-token js2-CATCH)
8130 (setq catch-pos (js2-current-token-beg)
8131 guard-kwd nil
8132 catch-cond nil
8133 lp nil
8134 rp nil)
8135 (if saw-default-catch
8136 (js2-report-error "msg.catch.unreachable"))
8137 (if (js2-must-match js2-LP "msg.no.paren.catch")
8138 (setq lp (- (js2-current-token-beg) catch-pos)))
8139 (js2-push-scope (make-js2-scope))
8140 (let ((tt (js2-peek-token)))
8141 (cond
8142 ;; destructuring pattern
8143 ;; catch ({ message, file }) { ... }
8144 ((or (= tt js2-LB) (= tt js2-LC))
8145 (js2-get-token)
8146 (setq param (js2-parse-destruct-primary-expr))
8147 (js2-define-destruct-symbols param js2-LET nil))
8148 ;; simple name
8149 (t
8150 (js2-must-match-name "msg.bad.catchcond")
8151 (setq param (js2-create-name-node))
8152 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8153 ;; pattern guard
8154 (if (js2-match-token js2-IF)
8155 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8156 catch-cond (js2-parse-expr))
8157 (setq saw-default-catch t))
8158 (if (js2-must-match js2-RP "msg.bad.catchcond")
8159 (setq rp (- (js2-current-token-beg) catch-pos)))
8160 (js2-must-match js2-LC "msg.no.brace.catchblock")
8161 (setq block (js2-parse-statements)
8162 try-end (js2-node-end block)
8163 catch-node (make-js2-catch-node :pos catch-pos
8164 :param param
8165 :guard-expr catch-cond
8166 :guard-kwd guard-kwd
8167 :block block
8168 :lp lp
8169 :rp rp))
8170 (js2-pop-scope)
8171 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8172 (setq try-end (js2-current-token-beg)))
8173 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8174 (js2-node-len catch-node) (- try-end catch-pos))
8175 (js2-node-add-children catch-node param catch-cond block)
8176 (push catch-node catch-blocks)))
8177 ((/= peek js2-FINALLY)
8178 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8179 (js2-node-pos try-block)
8180 (- (setq try-end (js2-node-end try-block))
8181 (js2-node-pos try-block)))))
8182 (when (js2-match-token js2-FINALLY)
8183 (setq finally-pos (js2-current-token-beg)
8184 block (js2-parse-statement)
8185 try-end (js2-node-end block)
8186 finally-block (make-js2-finally-node :pos finally-pos
8187 :len (- try-end finally-pos)
8188 :body block))
8189 (js2-node-add-children finally-block block))
8190 (setq pn (make-js2-try-node :pos try-pos
8191 :len (- try-end try-pos)
8192 :try-block try-block
8193 :finally-block finally-block))
8194 (js2-node-add-children pn try-block finally-block)
8195 ;; push them onto the try-node, which reverses and corrects their order
8196 (dolist (cb catch-blocks)
8197 (js2-node-add-children pn cb)
8198 (push cb (js2-try-node-catch-clauses pn)))
8199 pn))
8200
8201 (defun js2-parse-throw ()
8202 "Parser for throw-statement. Last matched token must be js2-THROW."
8203 (let ((pos (js2-current-token-beg))
8204 expr pn)
8205 (if (= (js2-peek-token-or-eol) js2-EOL)
8206 ;; ECMAScript does not allow new lines before throw expression,
8207 ;; see bug 256617
8208 (js2-report-error "msg.bad.throw.eol"))
8209 (setq expr (js2-parse-expr)
8210 pn (make-js2-throw-node :pos pos
8211 :len (- (js2-node-end expr) pos)
8212 :expr expr))
8213 (js2-node-add-children pn expr)
8214 pn))
8215
8216 (defun js2-match-jump-label-name (label-name)
8217 "If break/continue specified a label, return that label's labeled stmt.
8218 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8219 does not match an existing label, reports an error and returns nil."
8220 (let ((bundle (cdr (assoc label-name js2-label-set))))
8221 (if (null bundle)
8222 (js2-report-error "msg.undef.label"))
8223 bundle))
8224
8225 (defun js2-parse-break ()
8226 "Parser for break-statement. Last matched token must be js2-BREAK."
8227 (let ((pos (js2-current-token-beg))
8228 (end (js2-current-token-end))
8229 break-target ; statement to break from
8230 break-label ; in "break foo", name-node representing the foo
8231 labels ; matching labeled statement to break to
8232 pn)
8233 (when (eq (js2-peek-token-or-eol) js2-NAME)
8234 (js2-get-token)
8235 (setq break-label (js2-create-name-node)
8236 end (js2-node-end break-label)
8237 ;; matchJumpLabelName only matches if there is one
8238 labels (js2-match-jump-label-name (js2-current-token-string))
8239 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8240 (unless (or break-target break-label)
8241 ;; no break target specified - try for innermost enclosing loop/switch
8242 (if (null js2-loop-and-switch-set)
8243 (unless break-label
8244 (js2-report-error "msg.bad.break" nil pos (length "break")))
8245 (setq break-target (car js2-loop-and-switch-set))))
8246 (setq pn (make-js2-break-node :pos pos
8247 :len (- end pos)
8248 :label break-label
8249 :target break-target))
8250 (js2-node-add-children pn break-label) ; but not break-target
8251 pn))
8252
8253 (defun js2-parse-continue ()
8254 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8255 (let ((pos (js2-current-token-beg))
8256 (end (js2-current-token-end))
8257 label ; optional user-specified label, a `js2-name-node'
8258 labels ; current matching labeled stmt, if any
8259 target ; the `js2-loop-node' target of this continue stmt
8260 pn)
8261 (when (= (js2-peek-token-or-eol) js2-NAME)
8262 (js2-get-token)
8263 (setq label (js2-create-name-node)
8264 end (js2-node-end label)
8265 ;; matchJumpLabelName only matches if there is one
8266 labels (js2-match-jump-label-name (js2-current-token-string))))
8267 (cond
8268 ((null labels) ; no current label to go to
8269 (if (null js2-loop-set) ; no loop to continue to
8270 (js2-report-error "msg.continue.outside" nil pos
8271 (length "continue"))
8272 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8273 (t
8274 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8275 (setq target (js2-labeled-stmt-node-stmt labels))
8276 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8277 (setq pn (make-js2-continue-node :pos pos
8278 :len (- end pos)
8279 :label label
8280 :target target))
8281 (js2-node-add-children pn label) ; but not target - it's not our child
8282 pn))
8283
8284 (defun js2-parse-with ()
8285 "Parser for with-statement. Last matched token must be js2-WITH."
8286 (let ((pos (js2-current-token-beg))
8287 obj body pn lp rp)
8288 (if (js2-must-match js2-LP "msg.no.paren.with")
8289 (setq lp (js2-current-token-beg)))
8290 (setq obj (js2-parse-expr))
8291 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8292 (setq rp (js2-current-token-beg)))
8293 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8294 (setq body (js2-parse-statement)))
8295 (setq pn (make-js2-with-node :pos pos
8296 :len (- (js2-node-end body) pos)
8297 :object obj
8298 :body body
8299 :lp (js2-relpos lp pos)
8300 :rp (js2-relpos rp pos)))
8301 (js2-node-add-children pn obj body)
8302 pn))
8303
8304 (defun js2-parse-const-var ()
8305 "Parser for var- or const-statement.
8306 Last matched token must be js2-CONST or js2-VAR."
8307 (let ((tt (js2-current-token-type))
8308 (pos (js2-current-token-beg))
8309 expr pn)
8310 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8311 pn (make-js2-expr-stmt-node :pos pos
8312 :len (- (js2-node-end expr) pos)
8313 :expr expr))
8314 (js2-node-add-children pn expr)
8315 pn))
8316
8317 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8318 (let ((pn (make-js2-expr-stmt-node :pos pos
8319 :len (js2-node-len expr)
8320 :type (if (js2-inside-function)
8321 js2-EXPR_VOID
8322 js2-EXPR_RESULT)
8323 :expr expr)))
8324 (if add-child
8325 (js2-node-add-children pn expr))
8326 pn))
8327
8328 (defun js2-parse-let-stmt ()
8329 "Parser for let-statement. Last matched token must be js2-LET."
8330 (let ((pos (js2-current-token-beg))
8331 expr pn)
8332 (if (= (js2-peek-token) js2-LP)
8333 ;; let expression in statement context
8334 (setq expr (js2-parse-let pos 'statement)
8335 pn (js2-wrap-with-expr-stmt pos expr t))
8336 ;; else we're looking at a statement like let x=6, y=7;
8337 (setf expr (js2-parse-variables js2-LET pos)
8338 pn (js2-wrap-with-expr-stmt pos expr t)
8339 (js2-node-type pn) js2-EXPR_RESULT))
8340 pn))
8341
8342 (defun js2-parse-ret-yield ()
8343 (js2-parse-return-or-yield (js2-current-token-type) nil))
8344
8345 (defconst js2-parse-return-stmt-enders
8346 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8347
8348 (defsubst js2-now-all-set (before after mask)
8349 "Return whether or not the bits in the mask have changed to all set.
8350 BEFORE is bits before change, AFTER is bits after change, and MASK is
8351 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8352 but not BEFORE."
8353 (and (/= (logand before mask) mask)
8354 (= (logand after mask) mask)))
8355
8356 (defun js2-parse-return-or-yield (tt expr-context)
8357 (let* ((pos (js2-current-token-beg))
8358 (end (js2-current-token-end))
8359 (before js2-end-flags)
8360 (inside-function (js2-inside-function))
8361 (gen-type (and inside-function (js2-function-node-generator-type
8362 js2-current-script-or-fn)))
8363 e ret name yield-star-p)
8364 (unless inside-function
8365 (js2-report-error (if (eq tt js2-RETURN)
8366 "msg.bad.return"
8367 "msg.bad.yield")))
8368 (when (and inside-function
8369 (eq gen-type 'STAR)
8370 (js2-match-token js2-MUL))
8371 (setq yield-star-p t))
8372 ;; This is ugly, but we don't want to require a semicolon.
8373 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8374 (setq e (js2-parse-expr)
8375 end (js2-node-end e)))
8376 (cond
8377 ((eq tt js2-RETURN)
8378 (js2-set-flag js2-end-flags (if (null e)
8379 js2-end-returns
8380 js2-end-returns-value))
8381 (setq ret (make-js2-return-node :pos pos
8382 :len (- end pos)
8383 :retval e))
8384 (js2-node-add-children ret e)
8385 ;; See if we need a strict mode warning.
8386 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8387 ;; more thorough and accurate than this before/after flag check.
8388 ;; E.g. if there's a finally-block that always returns, we shouldn't
8389 ;; show a warning generated by inconsistent returns in the catch blocks.
8390 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8391 ;; so we know which returns/yields to highlight, and we should get rid of
8392 ;; all the checking in `js2-parse-return-or-yield'.
8393 (if (and js2-strict-inconsistent-return-warning
8394 (js2-now-all-set before js2-end-flags
8395 (logior js2-end-returns js2-end-returns-value)))
8396 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8397 ((eq gen-type 'COMPREHENSION)
8398 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8399 ;; like SpiderMonkey does.
8400 (js2-report-error "msg.syntax" nil pos 5))
8401 (t
8402 (setq ret (make-js2-yield-node :pos pos
8403 :len (- end pos)
8404 :value e
8405 :star-p yield-star-p))
8406 (js2-node-add-children ret e)
8407 (unless expr-context
8408 (setq e ret
8409 ret (js2-wrap-with-expr-stmt pos e t))
8410 (js2-set-requires-activation)
8411 (js2-set-is-generator))))
8412 ;; see if we are mixing yields and value returns.
8413 (when (and inside-function
8414 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8415 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8416 'LEGACY))
8417 (setq name (js2-function-name js2-current-script-or-fn))
8418 (if (zerop (length name))
8419 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8420 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8421 ret))
8422
8423 (defun js2-parse-debugger ()
8424 (make-js2-keyword-node :type js2-DEBUGGER))
8425
8426 (defun js2-parse-block ()
8427 "Parser for a curly-delimited statement block.
8428 Last token matched must be `js2-LC'."
8429 (let ((pos (js2-current-token-beg))
8430 (pn (make-js2-scope)))
8431 (js2-push-scope pn)
8432 (unwind-protect
8433 (progn
8434 (js2-parse-statements pn)
8435 (js2-must-match js2-RC "msg.no.brace.block")
8436 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8437 (js2-pop-scope))
8438 pn))
8439
8440 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8441 (defun js2-parse-semi ()
8442 "Parse a statement or handle an error.
8443 Current token type is `js2-SEMI' or `js2-ERROR'."
8444 (let ((tt (js2-current-token-type)) pos len)
8445 (if (eq tt js2-SEMI)
8446 (make-js2-empty-expr-node :len 1)
8447 (setq pos (js2-current-token-beg)
8448 len (- (js2-current-token-end) pos))
8449 (js2-report-error "msg.syntax" nil pos len)
8450 (make-js2-error-node :pos pos :len len))))
8451
8452 (defun js2-parse-default-xml-namespace ()
8453 "Parse a `default xml namespace = <expr>' e4x statement."
8454 (let ((pos (js2-current-token-beg))
8455 end len expr unary)
8456 (js2-must-have-xml)
8457 (js2-set-requires-activation)
8458 (setq len (- js2-ts-cursor pos))
8459 (unless (and (js2-match-token js2-NAME)
8460 (string= (js2-current-token-string) "xml"))
8461 (js2-report-error "msg.bad.namespace" nil pos len))
8462 (unless (and (js2-match-token js2-NAME)
8463 (string= (js2-current-token-string) "namespace"))
8464 (js2-report-error "msg.bad.namespace" nil pos len))
8465 (unless (js2-match-token js2-ASSIGN)
8466 (js2-report-error "msg.bad.namespace" nil pos len))
8467 (setq expr (js2-parse-expr)
8468 end (js2-node-end expr)
8469 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8470 :pos pos
8471 :len (- end pos)
8472 :operand expr))
8473 (js2-node-add-children unary expr)
8474 (make-js2-expr-stmt-node :pos pos
8475 :len (- end pos)
8476 :expr unary)))
8477
8478 (defun js2-record-label (label bundle)
8479 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8480 (js2-get-token)
8481 (let ((name (js2-label-node-name label))
8482 labeled-stmt
8483 dup)
8484 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8485 ;; flag both labels if possible when used in editing mode
8486 (if (and js2-parse-ide-mode
8487 (setq dup (js2-get-label-by-name labeled-stmt name)))
8488 (js2-report-error "msg.dup.label" nil
8489 (js2-node-abs-pos dup) (js2-node-len dup)))
8490 (js2-report-error "msg.dup.label" nil
8491 (js2-node-pos label) (js2-node-len label)))
8492 (js2-labeled-stmt-node-add-label bundle label)
8493 (js2-node-add-children bundle label)
8494 ;; Add one reference to the bundle per label in `js2-label-set'
8495 (push (cons name bundle) js2-label-set)))
8496
8497 (defun js2-parse-name-or-label ()
8498 "Parser for identifier or label. Last token matched must be js2-NAME.
8499 Called when we found a name in a statement context. If it's a label, we gather
8500 up any following labels and the next non-label statement into a
8501 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8502 expression and return it wrapped in a `js2-expr-stmt-node'."
8503 (let ((pos (js2-current-token-beg))
8504 expr stmt bundle
8505 (continue t))
8506 ;; set check for label and call down to `js2-parse-primary-expr'
8507 (setq expr (js2-maybe-parse-label))
8508 (if (null expr)
8509 ;; Parse the non-label expression and wrap with expression stmt.
8510 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8511 ;; else parsed a label
8512 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8513 (js2-record-label expr bundle)
8514 ;; look for more labels
8515 (while (and continue (= (js2-get-token) js2-NAME))
8516 (if (setq expr (js2-maybe-parse-label))
8517 (js2-record-label expr bundle)
8518 (setq expr (js2-parse-expr)
8519 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8520 continue nil)
8521 (js2-auto-insert-semicolon stmt)))
8522 ;; no more labels; now parse the labeled statement
8523 (unwind-protect
8524 (unless stmt
8525 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8526 (js2-unget-token)
8527 (setq stmt (js2-statement-helper))))
8528 ;; remove the labels for this statement from the global set
8529 (dolist (label (js2-labeled-stmt-node-labels bundle))
8530 (setq js2-label-set (remove label js2-label-set))))
8531 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8532 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8533 (js2-node-add-children bundle stmt)
8534 bundle)))
8535
8536 (defun js2-maybe-parse-label ()
8537 (assert (= (js2-current-token-type) js2-NAME))
8538 (let (label-pos
8539 (next-tt (js2-get-token))
8540 (label-end (js2-current-token-end)))
8541 ;; Do not consume colon, it is used as unwind indicator
8542 ;; to return to statementHelper.
8543 (js2-unget-token)
8544 (if (= next-tt js2-COLON)
8545 (prog2
8546 (setq label-pos (js2-current-token-beg))
8547 (make-js2-label-node :pos label-pos
8548 :len (- label-end label-pos)
8549 :name (js2-current-token-string))
8550 (js2-set-face label-pos
8551 label-end
8552 'font-lock-variable-name-face 'record))
8553 ;; Backtrack from the name token, too.
8554 (js2-unget-token)
8555 nil)))
8556
8557 (defun js2-parse-expr-stmt ()
8558 "Default parser in statement context, if no recognized statement found."
8559 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8560 (progn
8561 (js2-unget-token)
8562 (js2-parse-expr)) t))
8563
8564 (defun js2-parse-variables (decl-type pos)
8565 "Parse a comma-separated list of variable declarations.
8566 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8567
8568 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8569 For 'var' or 'const', the keyword should be the token last scanned.
8570
8571 POS is the position where the node should start. It's sometimes the
8572 var/const/let keyword, and other times the beginning of the first token
8573 in the first variable declaration.
8574
8575 Returns the parsed `js2-var-decl-node' expression node."
8576 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8577 :pos pos))
8578 destructuring kid-pos tt init name end nbeg nend vi
8579 (continue t))
8580 ;; Example:
8581 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8582 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8583 ;; var {a, b} = baz;
8584 (while continue
8585 (setq destructuring nil
8586 name nil
8587 tt (js2-get-token)
8588 kid-pos (js2-current-token-beg)
8589 end (js2-current-token-end)
8590 init nil)
8591 (if (or (= tt js2-LB) (= tt js2-LC))
8592 ;; Destructuring assignment, e.g., var [a, b] = ...
8593 (setq destructuring (js2-parse-destruct-primary-expr)
8594 end (js2-node-end destructuring))
8595 ;; Simple variable name
8596 (js2-unget-token)
8597 (when (js2-must-match-name "msg.bad.var")
8598 (setq name (js2-create-name-node)
8599 nbeg (js2-current-token-beg)
8600 nend (js2-current-token-end)
8601 end nend)
8602 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8603 (when (js2-match-token js2-ASSIGN)
8604 (setq init (js2-parse-assign-expr)
8605 end (js2-node-end init))
8606 (js2-record-imenu-functions init name))
8607 (when name
8608 (js2-set-face nbeg nend (if (js2-function-node-p init)
8609 'font-lock-function-name-face
8610 'font-lock-variable-name-face)
8611 'record))
8612 (setq vi (make-js2-var-init-node :pos kid-pos
8613 :len (- end kid-pos)
8614 :type decl-type))
8615 (if destructuring
8616 (progn
8617 (if (and (null init) (not js2-in-for-init))
8618 (js2-report-error "msg.destruct.assign.no.init"))
8619 (js2-define-destruct-symbols destructuring
8620 decl-type
8621 'font-lock-variable-name-face)
8622 (setf (js2-var-init-node-target vi) destructuring))
8623 (setf (js2-var-init-node-target vi) name))
8624 (setf (js2-var-init-node-initializer vi) init)
8625 (js2-node-add-children vi name destructuring init)
8626 (js2-block-node-push result vi)
8627 (unless (js2-match-token js2-COMMA)
8628 (setq continue nil)))
8629 (setf (js2-node-len result) (- end pos))
8630 result))
8631
8632 (defun js2-parse-let (pos &optional stmt-p)
8633 "Parse a let expression or statement.
8634 A let-expression is of the form `let (vars) expr'.
8635 A let-statment is of the form `let (vars) {statements}'.
8636 The third form of let is a variable declaration list, handled
8637 by `js2-parse-variables'."
8638 (let ((pn (make-js2-let-node :pos pos))
8639 beg vars body)
8640 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8641 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8642 (js2-push-scope pn)
8643 (unwind-protect
8644 (progn
8645 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8646 (if (js2-must-match js2-RP "msg.no.paren.let")
8647 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8648 (if (and stmt-p (js2-match-token js2-LC))
8649 ;; let statement
8650 (progn
8651 (setf beg (js2-current-token-beg) ; position stmt at LC
8652 body (js2-parse-statements))
8653 (js2-must-match js2-RC "msg.no.curly.let")
8654 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8655 (js2-node-len pn) (- (js2-current-token-end) pos)
8656 (js2-let-node-body pn) body
8657 (js2-node-type pn) js2-LET))
8658 ;; let expression
8659 (setf body (js2-parse-expr)
8660 (js2-node-len pn) (- (js2-node-end body) pos)
8661 (js2-let-node-body pn) body))
8662 (setf (js2-let-node-vars pn) vars)
8663 (js2-node-add-children pn vars body))
8664 (js2-pop-scope))
8665 pn))
8666
8667 (defun js2-define-new-symbol (decl-type name node &optional scope)
8668 (js2-scope-put-symbol (or scope js2-current-scope)
8669 name
8670 (make-js2-symbol decl-type name node)))
8671
8672 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8673 "Define a symbol in the current scope.
8674 If NODE is non-nil, it is the AST node associated with the symbol."
8675 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8676 (symbol (if defining-scope
8677 (js2-scope-get-symbol defining-scope name)))
8678 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8679 (cond
8680 ((and symbol ; already defined
8681 (or (= sdt js2-CONST) ; old version is const
8682 (= decl-type js2-CONST) ; new version is const
8683 ;; two let-bound vars in this block have same name
8684 (and (= sdt js2-LET)
8685 (eq defining-scope js2-current-scope))))
8686 (js2-report-error
8687 (cond
8688 ((= sdt js2-CONST) "msg.const.redecl")
8689 ((= sdt js2-LET) "msg.let.redecl")
8690 ((= sdt js2-VAR) "msg.var.redecl")
8691 ((= sdt js2-FUNCTION) "msg.function.redecl")
8692 (t "msg.parm.redecl"))
8693 name))
8694 ((= decl-type js2-LET)
8695 (if (and (not ignore-not-in-block)
8696 (or (= (js2-node-type js2-current-scope) js2-IF)
8697 (js2-loop-node-p js2-current-scope)))
8698 (js2-report-error "msg.let.decl.not.in.block")
8699 (js2-define-new-symbol decl-type name node)))
8700 ((or (= decl-type js2-VAR)
8701 (= decl-type js2-CONST)
8702 (= decl-type js2-FUNCTION))
8703 (if symbol
8704 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8705 (js2-add-strict-warning "msg.var.redecl" name)
8706 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8707 (js2-add-strict-warning "msg.var.hides.arg" name)))
8708 (js2-define-new-symbol decl-type name node
8709 js2-current-script-or-fn)))
8710 ((= decl-type js2-LP)
8711 (if symbol
8712 ;; must be duplicate parameter. Second parameter hides the
8713 ;; first, so go ahead and add the second pararameter
8714 (js2-report-warning "msg.dup.parms" name))
8715 (js2-define-new-symbol decl-type name node))
8716 (t (js2-code-bug)))))
8717
8718 (defun js2-parse-paren-expr-or-generator-comp ()
8719 (let ((px-pos (js2-current-token-beg)))
8720 (if (and (>= js2-language-version 200)
8721 (js2-match-token js2-FOR))
8722 (js2-parse-generator-comp px-pos)
8723 (let* ((js2-in-for-init nil)
8724 (expr (js2-parse-expr))
8725 (pn (make-js2-paren-node :pos px-pos
8726 :expr expr
8727 :len (- (js2-current-token-end)
8728 px-pos))))
8729 (js2-node-add-children pn (js2-paren-node-expr pn))
8730 (js2-must-match js2-RP "msg.no.paren")
8731 pn))))
8732
8733 (defun js2-parse-expr (&optional oneshot)
8734 (let* ((pn (js2-parse-assign-expr))
8735 (pos (js2-node-pos pn))
8736 left
8737 right
8738 op-pos)
8739 (while (and (not oneshot)
8740 (js2-match-token js2-COMMA))
8741 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8742 (if (= (js2-peek-token) js2-YIELD)
8743 (js2-report-error "msg.yield.parenthesized"))
8744 (setq right (js2-parse-assign-expr)
8745 left pn
8746 pn (make-js2-infix-node :type js2-COMMA
8747 :pos pos
8748 :len (- js2-ts-cursor pos)
8749 :op-pos op-pos
8750 :left left
8751 :right right))
8752 (js2-node-add-children pn left right))
8753 pn))
8754
8755 (defun js2-parse-assign-expr ()
8756 (let ((tt (js2-get-token))
8757 (pos (js2-current-token-beg))
8758 pn left right op-pos
8759 ts-state recorded-identifiers parsed-errors)
8760 (if (= tt js2-YIELD)
8761 (js2-parse-return-or-yield tt t)
8762 ;; Save the tokenizer state in case we find an arrow function
8763 ;; and have to rewind.
8764 (setq ts-state (make-js2-ts-state)
8765 recorded-identifiers js2-recorded-identifiers
8766 parsed-errors js2-parsed-errors)
8767 ;; not yield - parse assignment expression
8768 (setq pn (js2-parse-cond-expr)
8769 tt (js2-get-token))
8770 (cond
8771 ((and (<= js2-first-assign tt)
8772 (<= tt js2-last-assign))
8773 ;; tt express assignment (=, |=, ^=, ..., %=)
8774 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8775 left pn)
8776 (setq right (js2-parse-assign-expr)
8777 pn (make-js2-assign-node :type tt
8778 :pos pos
8779 :len (- (js2-node-end right) pos)
8780 :op-pos op-pos
8781 :left left
8782 :right right))
8783 (when js2-parse-ide-mode
8784 (js2-highlight-assign-targets pn left right)
8785 (js2-record-imenu-functions right left))
8786 ;; do this last so ide checks above can use absolute positions
8787 (js2-node-add-children pn left right))
8788 ((and (= tt js2-ARROW)
8789 (>= js2-language-version 200))
8790 (js2-ts-seek ts-state)
8791 (setq js2-recorded-identifiers recorded-identifiers
8792 js2-parsed-errors parsed-errors)
8793 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8794 (t
8795 (js2-unget-token)))
8796 pn)))
8797
8798 (defun js2-parse-cond-expr ()
8799 (let ((pos (js2-current-token-beg))
8800 (pn (js2-parse-or-expr))
8801 test-expr
8802 if-true
8803 if-false
8804 q-pos
8805 c-pos)
8806 (when (js2-match-token js2-HOOK)
8807 (setq q-pos (- (js2-current-token-beg) pos)
8808 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8809 (js2-must-match js2-COLON "msg.no.colon.cond")
8810 (setq c-pos (- (js2-current-token-beg) pos)
8811 if-false (js2-parse-assign-expr)
8812 test-expr pn
8813 pn (make-js2-cond-node :pos pos
8814 :len (- (js2-node-end if-false) pos)
8815 :test-expr test-expr
8816 :true-expr if-true
8817 :false-expr if-false
8818 :q-pos q-pos
8819 :c-pos c-pos))
8820 (js2-node-add-children pn test-expr if-true if-false))
8821 pn))
8822
8823 (defun js2-make-binary (type left parser)
8824 "Helper for constructing a binary-operator AST node.
8825 LEFT is the left-side-expression, already parsed, and the
8826 binary operator should have just been matched.
8827 PARSER is a function to call to parse the right operand,
8828 or a `js2-node' struct if it has already been parsed.
8829 FIXME: The latter option is unused?"
8830 (let* ((pos (js2-node-pos left))
8831 (op-pos (- (js2-current-token-beg) pos))
8832 (right (if (js2-node-p parser)
8833 parser
8834 (js2-get-token)
8835 (funcall parser)))
8836 (pn (make-js2-infix-node :type type
8837 :pos pos
8838 :len (- (js2-node-end right) pos)
8839 :op-pos op-pos
8840 :left left
8841 :right right)))
8842 (js2-node-add-children pn left right)
8843 pn))
8844
8845 (defun js2-parse-or-expr ()
8846 (let ((pn (js2-parse-and-expr)))
8847 (when (js2-match-token js2-OR)
8848 (setq pn (js2-make-binary js2-OR
8849 pn
8850 'js2-parse-or-expr)))
8851 pn))
8852
8853 (defun js2-parse-and-expr ()
8854 (let ((pn (js2-parse-bit-or-expr)))
8855 (when (js2-match-token js2-AND)
8856 (setq pn (js2-make-binary js2-AND
8857 pn
8858 'js2-parse-and-expr)))
8859 pn))
8860
8861 (defun js2-parse-bit-or-expr ()
8862 (let ((pn (js2-parse-bit-xor-expr)))
8863 (while (js2-match-token js2-BITOR)
8864 (setq pn (js2-make-binary js2-BITOR
8865 pn
8866 'js2-parse-bit-xor-expr)))
8867 pn))
8868
8869 (defun js2-parse-bit-xor-expr ()
8870 (let ((pn (js2-parse-bit-and-expr)))
8871 (while (js2-match-token js2-BITXOR)
8872 (setq pn (js2-make-binary js2-BITXOR
8873 pn
8874 'js2-parse-bit-and-expr)))
8875 pn))
8876
8877 (defun js2-parse-bit-and-expr ()
8878 (let ((pn (js2-parse-eq-expr)))
8879 (while (js2-match-token js2-BITAND)
8880 (setq pn (js2-make-binary js2-BITAND
8881 pn
8882 'js2-parse-eq-expr)))
8883 pn))
8884
8885 (defconst js2-parse-eq-ops
8886 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8887
8888 (defun js2-parse-eq-expr ()
8889 (let ((pn (js2-parse-rel-expr))
8890 tt)
8891 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8892 (setq pn (js2-make-binary tt
8893 pn
8894 'js2-parse-rel-expr)))
8895 (js2-unget-token)
8896 pn))
8897
8898 (defconst js2-parse-rel-ops
8899 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8900
8901 (defun js2-parse-rel-expr ()
8902 (let ((pn (js2-parse-shift-expr))
8903 (continue t)
8904 tt)
8905 (while continue
8906 (setq tt (js2-get-token))
8907 (cond
8908 ((and js2-in-for-init (= tt js2-IN))
8909 (js2-unget-token)
8910 (setq continue nil))
8911 ((memq tt js2-parse-rel-ops)
8912 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8913 (t
8914 (js2-unget-token)
8915 (setq continue nil))))
8916 pn))
8917
8918 (defconst js2-parse-shift-ops
8919 (list js2-LSH js2-URSH js2-RSH))
8920
8921 (defun js2-parse-shift-expr ()
8922 (let ((pn (js2-parse-add-expr))
8923 tt
8924 (continue t))
8925 (while continue
8926 (setq tt (js2-get-token))
8927 (if (memq tt js2-parse-shift-ops)
8928 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8929 (js2-unget-token)
8930 (setq continue nil)))
8931 pn))
8932
8933 (defun js2-parse-add-expr ()
8934 (let ((pn (js2-parse-mul-expr))
8935 tt
8936 (continue t))
8937 (while continue
8938 (setq tt (js2-get-token))
8939 (if (or (= tt js2-ADD) (= tt js2-SUB))
8940 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8941 (js2-unget-token)
8942 (setq continue nil)))
8943 pn))
8944
8945 (defconst js2-parse-mul-ops
8946 (list js2-MUL js2-DIV js2-MOD))
8947
8948 (defun js2-parse-mul-expr ()
8949 (let ((pn (js2-parse-unary-expr))
8950 tt
8951 (continue t))
8952 (while continue
8953 (setq tt (js2-get-token))
8954 (if (memq tt js2-parse-mul-ops)
8955 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8956 (js2-unget-token)
8957 (setq continue nil)))
8958 pn))
8959
8960 (defun js2-make-unary (type parser &rest args)
8961 "Make a unary node of type TYPE.
8962 PARSER is either a node (for postfix operators) or a function to call
8963 to parse the operand (for prefix operators)."
8964 (let* ((pos (js2-current-token-beg))
8965 (postfix (js2-node-p parser))
8966 (expr (if postfix
8967 parser
8968 (apply parser args)))
8969 end
8970 pn)
8971 (if postfix ; e.g. i++
8972 (setq pos (js2-node-pos expr)
8973 end (js2-current-token-end))
8974 (setq end (js2-node-end expr)))
8975 (setq pn (make-js2-unary-node :type type
8976 :pos pos
8977 :len (- end pos)
8978 :operand expr))
8979 (js2-node-add-children pn expr)
8980 pn))
8981
8982 (defconst js2-incrementable-node-types
8983 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8984 "Node types that can be the operand of a ++ or -- operator.")
8985
8986 (defun js2-check-bad-inc-dec (tt beg end unary)
8987 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8988 js2-incrementable-node-types)
8989 (js2-report-error (if (= tt js2-INC)
8990 "msg.bad.incr"
8991 "msg.bad.decr")
8992 nil beg (- end beg))))
8993
8994 (defun js2-parse-unary-expr ()
8995 (let ((tt (js2-current-token-type))
8996 pn expr beg end)
8997 (cond
8998 ((or (= tt js2-VOID)
8999 (= tt js2-NOT)
9000 (= tt js2-BITNOT)
9001 (= tt js2-TYPEOF))
9002 (js2-get-token)
9003 (js2-make-unary tt 'js2-parse-unary-expr))
9004 ((= tt js2-ADD)
9005 (js2-get-token)
9006 ;; Convert to special POS token in decompiler and parse tree
9007 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9008 ((= tt js2-SUB)
9009 (js2-get-token)
9010 ;; Convert to special NEG token in decompiler and parse tree
9011 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9012 ((or (= tt js2-INC)
9013 (= tt js2-DEC))
9014 (js2-get-token)
9015 (prog1
9016 (setq beg (js2-current-token-beg)
9017 end (js2-current-token-end)
9018 expr (js2-make-unary tt 'js2-parse-member-expr t))
9019 (js2-check-bad-inc-dec tt beg end expr)))
9020 ((= tt js2-DELPROP)
9021 (js2-get-token)
9022 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9023 ((= tt js2-ERROR)
9024 (js2-get-token)
9025 (make-js2-error-node)) ; try to continue
9026 ((and (= tt js2-LT)
9027 js2-compiler-xml-available)
9028 ;; XML stream encountered in expression.
9029 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9030 (t
9031 (setq pn (js2-parse-member-expr t)
9032 ;; Don't look across a newline boundary for a postfix incop.
9033 tt (js2-peek-token-or-eol))
9034 (when (or (= tt js2-INC) (= tt js2-DEC))
9035 (js2-get-token)
9036 (setf expr pn
9037 pn (js2-make-unary tt expr))
9038 (js2-node-set-prop pn 'postfix t)
9039 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9040 pn))))
9041
9042 (defun js2-parse-xml-initializer ()
9043 "Parse an E4X XML initializer.
9044 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9045 Then I'll postprocess the result, depending on whether we're in IDE
9046 mode or codegen mode, and generate the appropriate rewritten AST.
9047 IDE mode uses a rich AST that models the XML structure. Codegen mode
9048 just concatenates everything and makes a new XML or XMLList out of it."
9049 (let ((tt (js2-get-first-xml-token))
9050 pn-xml pn expr kids expr-pos
9051 (continue t)
9052 (first-token t))
9053 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9054 (js2-report-error "msg.syntax"))
9055 (setq pn-xml (make-js2-xml-node))
9056 (while continue
9057 (if first-token
9058 (setq first-token nil)
9059 (setq tt (js2-get-next-xml-token)))
9060 (cond
9061 ;; js2-XML means we found a {expr} in the XML stream.
9062 ;; The token string is the XML up to the left-curly.
9063 ((= tt js2-XML)
9064 (push (make-js2-string-node :pos (js2-current-token-beg)
9065 :len (- js2-ts-cursor (js2-current-token-beg)))
9066 kids)
9067 (js2-must-match js2-LC "msg.syntax")
9068 (setq expr-pos js2-ts-cursor
9069 expr (if (eq (js2-peek-token) js2-RC)
9070 (make-js2-empty-expr-node :pos expr-pos)
9071 (js2-parse-expr)))
9072 (js2-must-match js2-RC "msg.syntax")
9073 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9074 :len (js2-node-len expr)
9075 :expr expr))
9076 (js2-node-add-children pn expr)
9077 (push pn kids))
9078 ;; a js2-XMLEND token means we hit the final close-tag.
9079 ((= tt js2-XMLEND)
9080 (push (make-js2-string-node :pos (js2-current-token-beg)
9081 :len (- js2-ts-cursor (js2-current-token-beg)))
9082 kids)
9083 (dolist (kid (nreverse kids))
9084 (js2-block-node-push pn-xml kid))
9085 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9086 (js2-node-pos pn-xml))
9087 continue nil))
9088 (t
9089 (js2-report-error "msg.syntax")
9090 (setq continue nil))))
9091 pn-xml))
9092
9093
9094 (defun js2-parse-argument-list ()
9095 "Parse an argument list and return it as a Lisp list of nodes.
9096 Returns the list in reverse order. Consumes the right-paren token."
9097 (let (result)
9098 (unless (js2-match-token js2-RP)
9099 (loop do
9100 (let ((tt (js2-get-token)))
9101 (if (= tt js2-YIELD)
9102 (js2-report-error "msg.yield.parenthesized"))
9103 (if (and (= tt js2-TRIPLEDOT)
9104 (>= js2-language-version 200))
9105 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9106 (js2-unget-token)
9107 (push (js2-parse-assign-expr) result)))
9108 while
9109 (js2-match-token js2-COMMA))
9110 (js2-must-match js2-RP "msg.no.paren.arg")
9111 result)))
9112
9113 (defun js2-parse-member-expr (&optional allow-call-syntax)
9114 (let ((tt (js2-current-token-type))
9115 pn pos target args beg end init)
9116 (if (/= tt js2-NEW)
9117 (setq pn (js2-parse-primary-expr))
9118 ;; parse a 'new' expression
9119 (js2-get-token)
9120 (setq pos (js2-current-token-beg)
9121 beg pos
9122 target (js2-parse-member-expr)
9123 end (js2-node-end target)
9124 pn (make-js2-new-node :pos pos
9125 :target target
9126 :len (- end pos)))
9127 (js2-highlight-function-call (js2-current-token))
9128 (js2-node-add-children pn target)
9129 (when (js2-match-token js2-LP)
9130 ;; Add the arguments to pn, if any are supplied.
9131 (setf beg pos ; start of "new" keyword
9132 pos (js2-current-token-beg)
9133 args (nreverse (js2-parse-argument-list))
9134 (js2-new-node-args pn) args
9135 end (js2-current-token-end)
9136 (js2-new-node-lp pn) (- pos beg)
9137 (js2-new-node-rp pn) (- end 1 beg))
9138 (apply #'js2-node-add-children pn args))
9139 (when (and js2-allow-rhino-new-expr-initializer
9140 (js2-match-token js2-LC))
9141 (setf init (js2-parse-object-literal)
9142 end (js2-node-end init)
9143 (js2-new-node-initializer pn) init)
9144 (js2-node-add-children pn init))
9145 (setf (js2-node-len pn) (- end beg))) ; end outer if
9146 (js2-parse-member-expr-tail allow-call-syntax pn)))
9147
9148 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9149 "Parse a chain of property/array accesses or function calls.
9150 Includes parsing for E4X operators like `..' and `.@'.
9151 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9152 Returns an expression tree that includes PN, the parent node."
9153 (let (tt
9154 (continue t))
9155 (while continue
9156 (setq tt (js2-get-token))
9157 (cond
9158 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9159 (setq pn (js2-parse-property-access tt pn)))
9160 ((= tt js2-DOTQUERY)
9161 (setq pn (js2-parse-dot-query pn)))
9162 ((= tt js2-LB)
9163 (setq pn (js2-parse-element-get pn)))
9164 ((= tt js2-LP)
9165 (js2-unget-token)
9166 (if allow-call-syntax
9167 (setq pn (js2-parse-function-call pn))
9168 (setq continue nil)))
9169 ((= tt js2-TEMPLATE_HEAD)
9170 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9171 ((= tt js2-NO_SUBS_TEMPLATE)
9172 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9173 (t
9174 (js2-unget-token)
9175 (setq continue nil))))
9176 (if (>= js2-highlight-level 2)
9177 (js2-parse-highlight-member-expr-node pn))
9178 pn))
9179
9180 (defun js2-parse-tagged-template (tag-node tpl-node)
9181 "Parse tagged template expression."
9182 (let* ((beg (js2-node-pos tag-node))
9183 (pn (make-js2-tagged-template-node :beg beg
9184 :len (- (js2-current-token-end) beg)
9185 :tag tag-node
9186 :template tpl-node)))
9187 (js2-node-add-children pn tag-node tpl-node)
9188 pn))
9189
9190 (defun js2-parse-dot-query (pn)
9191 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9192 Last token parsed must be `js2-DOTQUERY'."
9193 (let ((pos (js2-node-pos pn))
9194 op-pos expr end)
9195 (js2-must-have-xml)
9196 (js2-set-requires-activation)
9197 (setq op-pos (js2-current-token-beg)
9198 expr (js2-parse-expr)
9199 end (js2-node-end expr)
9200 pn (make-js2-xml-dot-query-node :left pn
9201 :pos pos
9202 :op-pos op-pos
9203 :right expr))
9204 (js2-node-add-children pn
9205 (js2-xml-dot-query-node-left pn)
9206 (js2-xml-dot-query-node-right pn))
9207 (if (js2-must-match js2-RP "msg.no.paren")
9208 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9209 end (js2-current-token-end)))
9210 (setf (js2-node-len pn) (- end pos))
9211 pn))
9212
9213 (defun js2-parse-element-get (pn)
9214 "Parse an element-get expression, e.g. foo[bar].
9215 Last token parsed must be `js2-RB'."
9216 (let ((lb (js2-current-token-beg))
9217 (pos (js2-node-pos pn))
9218 rb expr)
9219 (setq expr (js2-parse-expr))
9220 (if (js2-must-match js2-RB "msg.no.bracket.index")
9221 (setq rb (js2-current-token-beg)))
9222 (setq pn (make-js2-elem-get-node :target pn
9223 :pos pos
9224 :element expr
9225 :lb (js2-relpos lb pos)
9226 :rb (js2-relpos rb pos)
9227 :len (- (js2-current-token-end) pos)))
9228 (js2-node-add-children pn
9229 (js2-elem-get-node-target pn)
9230 (js2-elem-get-node-element pn))
9231 pn))
9232
9233 (defun js2-highlight-function-call (token)
9234 (when (eq (js2-token-type token) js2-NAME)
9235 (js2-record-face 'js2-function-call token)))
9236
9237 (defun js2-parse-function-call (pn)
9238 (js2-highlight-function-call (js2-current-token))
9239 (js2-get-token)
9240 (let (args
9241 (pos (js2-node-pos pn)))
9242 (setq pn (make-js2-call-node :pos pos
9243 :target pn
9244 :lp (- (js2-current-token-beg) pos)))
9245 (js2-node-add-children pn (js2-call-node-target pn))
9246 ;; Add the arguments to pn, if any are supplied.
9247 (setf args (nreverse (js2-parse-argument-list))
9248 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9249 (js2-call-node-args pn) args)
9250 (apply #'js2-node-add-children pn args)
9251 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9252 pn))
9253
9254 (defun js2-parse-property-access (tt pn)
9255 "Parse a property access, XML descendants access, or XML attr access."
9256 (let ((member-type-flags 0)
9257 (dot-pos (js2-current-token-beg))
9258 (dot-len (if (= tt js2-DOTDOT) 2 1))
9259 name
9260 ref ; right side of . or .. operator
9261 result)
9262 (when (= tt js2-DOTDOT)
9263 (js2-must-have-xml)
9264 (setq member-type-flags js2-descendants-flag))
9265 (if (not js2-compiler-xml-available)
9266 (progn
9267 (js2-must-match-prop-name "msg.no.name.after.dot")
9268 (setq name (js2-create-name-node t js2-GETPROP)
9269 result (make-js2-prop-get-node :left pn
9270 :pos (js2-current-token-beg)
9271 :right name
9272 :len (js2-current-token-len)))
9273 (js2-node-add-children result pn name)
9274 result)
9275 ;; otherwise look for XML operators
9276 (setf result (if (= tt js2-DOT)
9277 (make-js2-prop-get-node)
9278 (make-js2-infix-node :type js2-DOTDOT))
9279 (js2-node-pos result) (js2-node-pos pn)
9280 (js2-infix-node-op-pos result) dot-pos
9281 (js2-infix-node-left result) pn ; do this after setting position
9282 tt (js2-next-token))
9283 (cond
9284 ;; needed for generator.throw()
9285 ((= tt js2-THROW)
9286 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9287 ;; handles: name, ns::name, ns::*, ns::[expr]
9288 ((js2-valid-prop-name-token tt)
9289 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9290 ;; handles: *, *::name, *::*, *::[expr]
9291 ((= tt js2-MUL)
9292 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9293 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9294 ((= tt js2-XMLATTR)
9295 (setq result (js2-parse-attribute-access)))
9296 (t
9297 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9298 (if ref
9299 (setf (js2-node-len result) (- (js2-node-end ref)
9300 (js2-node-pos result))
9301 (js2-infix-node-right result) ref))
9302 (if (js2-infix-node-p result)
9303 (js2-node-add-children result
9304 (js2-infix-node-left result)
9305 (js2-infix-node-right result)))
9306 result)))
9307
9308 (defun js2-parse-attribute-access ()
9309 "Parse an E4X XML attribute expression.
9310 This includes expressions of the forms:
9311
9312 @attr @ns::attr @ns::*
9313 @* @*::attr @*::*
9314 @[expr] @*::[expr] @ns::[expr]
9315
9316 Called if we peeked an '@' token."
9317 (let ((tt (js2-next-token))
9318 (at-pos (js2-current-token-beg)))
9319 (cond
9320 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9321 ((js2-valid-prop-name-token tt)
9322 (js2-parse-property-name at-pos nil 0))
9323 ;; handles: @*, @*::name, @*::*, @*::[expr]
9324 ((= tt js2-MUL)
9325 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9326 ;; handles @[expr]
9327 ((= tt js2-LB)
9328 (js2-parse-xml-elem-ref at-pos))
9329 (t
9330 (js2-report-error "msg.no.name.after.xmlAttr")
9331 ;; Avoid cascaded errors that happen if we make an error node here.
9332 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9333
9334 (defun js2-parse-property-name (at-pos s member-type-flags)
9335 "Check if :: follows name in which case it becomes qualified name.
9336
9337 AT-POS is a natural number if we just read an '@' token, else nil.
9338 S is the name or string that was matched: an identifier, 'throw' or '*'.
9339 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9340
9341 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9342 operator, or the name is followed by ::. For a plain name, returns a
9343 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9344 (let ((pos (or at-pos (js2-current-token-beg)))
9345 colon-pos
9346 (name (js2-create-name-node t (js2-current-token-type) s))
9347 ns tt pn)
9348 (catch 'return
9349 (when (js2-match-token js2-COLONCOLON)
9350 (setq ns name
9351 colon-pos (js2-current-token-beg)
9352 tt (js2-next-token))
9353 (cond
9354 ;; handles name::name
9355 ((js2-valid-prop-name-token tt)
9356 (setq name (js2-create-name-node)))
9357 ;; handles name::*
9358 ((= tt js2-MUL)
9359 (setq name (js2-create-name-node nil nil "*")))
9360 ;; handles name::[expr]
9361 ((= tt js2-LB)
9362 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9363 (t
9364 (js2-report-error "msg.no.name.after.coloncolon"))))
9365 (if (and (null ns) (zerop member-type-flags))
9366 name
9367 (prog1
9368 (setq pn
9369 (make-js2-xml-prop-ref-node :pos pos
9370 :len (- (js2-node-end name) pos)
9371 :at-pos at-pos
9372 :colon-pos colon-pos
9373 :propname name))
9374 (js2-node-add-children pn name))))))
9375
9376 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9377 "Parse the [expr] portion of an xml element reference.
9378 For instance, @[expr], @*::[expr], or ns::[expr]."
9379 (let* ((lb (js2-current-token-beg))
9380 (pos (or at-pos lb))
9381 rb
9382 (expr (js2-parse-expr))
9383 (end (js2-node-end expr))
9384 pn)
9385 (if (js2-must-match js2-RB "msg.no.bracket.index")
9386 (setq rb (js2-current-token-beg)
9387 end (js2-current-token-end)))
9388 (prog1
9389 (setq pn
9390 (make-js2-xml-elem-ref-node :pos pos
9391 :len (- end pos)
9392 :namespace namespace
9393 :colon-pos colon-pos
9394 :at-pos at-pos
9395 :expr expr
9396 :lb (js2-relpos lb pos)
9397 :rb (js2-relpos rb pos)))
9398 (js2-node-add-children pn namespace expr))))
9399
9400 (defun js2-parse-destruct-primary-expr ()
9401 (let ((js2-is-in-destructuring t))
9402 (js2-parse-primary-expr)))
9403
9404 (defun js2-parse-primary-expr ()
9405 "Parse a literal (leaf) expression of some sort.
9406 Includes complex literals such as functions, object-literals,
9407 array-literals, array comprehensions and regular expressions."
9408 (let (pn ; parent node (usually return value)
9409 tt)
9410 (setq tt (js2-current-token-type))
9411 (cond
9412 ((= tt js2-CLASS)
9413 (js2-parse-class-expr))
9414 ((= tt js2-FUNCTION)
9415 (js2-parse-function-expr))
9416 ((= tt js2-LB)
9417 (js2-parse-array-comp-or-literal))
9418 ((= tt js2-LC)
9419 (js2-parse-object-literal))
9420 ((= tt js2-LET)
9421 (js2-parse-let (js2-current-token-beg)))
9422 ((= tt js2-LP)
9423 (js2-parse-paren-expr-or-generator-comp))
9424 ((= tt js2-XMLATTR)
9425 (js2-must-have-xml)
9426 (js2-parse-attribute-access))
9427 ((= tt js2-NAME)
9428 (js2-parse-name tt))
9429 ((= tt js2-NUMBER)
9430 (make-js2-number-node))
9431 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9432 (make-js2-string-node :type tt))
9433 ((= tt js2-TEMPLATE_HEAD)
9434 (js2-parse-template-literal))
9435 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9436 ;; Got / or /= which in this context means a regexp literal
9437 (let ((px-pos (js2-current-token-beg))
9438 (flags (js2-read-regexp tt))
9439 (end (js2-current-token-end)))
9440 (prog1
9441 (make-js2-regexp-node :pos px-pos
9442 :len (- end px-pos)
9443 :value (js2-current-token-string)
9444 :flags flags)
9445 (js2-set-face px-pos end 'font-lock-string-face 'record)
9446 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9447 ((or (= tt js2-NULL)
9448 (= tt js2-THIS)
9449 (= tt js2-SUPER)
9450 (= tt js2-FALSE)
9451 (= tt js2-TRUE))
9452 (make-js2-keyword-node :type tt))
9453 ((= tt js2-RP)
9454 ;; Not valid expression syntax, but this is valid in an arrow
9455 ;; function with no params: () => body.
9456 (if (eq (js2-peek-token) js2-ARROW)
9457 (progn
9458 (js2-unget-token) ; Put back the right paren.
9459 ;; Return whatever, it will hopefully be rewinded and
9460 ;; reparsed when we reach the =>.
9461 (make-js2-keyword-node :type js2-NULL))
9462 (js2-report-error "msg.syntax")
9463 (make-js2-error-node)))
9464 ((= tt js2-TRIPLEDOT)
9465 ;; Likewise, only valid in an arrow function with a rest param.
9466 (if (and (js2-match-token js2-NAME)
9467 (js2-match-token js2-RP)
9468 (eq (js2-peek-token) js2-ARROW))
9469 (progn
9470 (js2-unget-token) ; Put back the right paren.
9471 ;; See the previous case.
9472 (make-js2-keyword-node :type js2-NULL))
9473 (js2-report-error "msg.syntax")
9474 (make-js2-error-node)))
9475 ((= tt js2-RESERVED)
9476 (js2-report-error "msg.reserved.id")
9477 (make-js2-name-node))
9478 ((= tt js2-ERROR)
9479 ;; the scanner or one of its subroutines reported the error.
9480 (make-js2-error-node))
9481 ((= tt js2-EOF)
9482 (let* ((px-pos (point-at-bol))
9483 (len (- js2-ts-cursor px-pos)))
9484 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9485 (make-js2-error-node :pos (1- js2-ts-cursor)))
9486 (t
9487 (js2-report-error "msg.syntax")
9488 (make-js2-error-node)))))
9489
9490 (defun js2-parse-template-literal ()
9491 (let ((beg (js2-current-token-beg))
9492 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
9493 (tt js2-TEMPLATE_HEAD))
9494 (while (eq tt js2-TEMPLATE_HEAD)
9495 (push (js2-parse-expr) kids)
9496 (js2-must-match js2-RC "msg.syntax")
9497 (setq tt (js2-get-token 'TEMPLATE_TAIL))
9498 (push (make-js2-string-node :type tt) kids))
9499 (setq kids (nreverse kids))
9500 (let ((tpl (make-js2-template-node :beg beg
9501 :len (- (js2-current-token-end) beg)
9502 :kids kids)))
9503 (apply #'js2-node-add-children tpl kids)
9504 tpl)))
9505
9506 (defun js2-parse-name (_tt)
9507 (let ((name (js2-current-token-string))
9508 node)
9509 (setq node (if js2-compiler-xml-available
9510 (js2-parse-property-name nil name 0)
9511 (js2-create-name-node 'check-activation nil name)))
9512 (if js2-highlight-external-variables
9513 (js2-record-name-node node))
9514 node))
9515
9516 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9517 (js2-add-strict-warning
9518 msg nil
9519 ;; back up from comma to beginning of line or array/objlit
9520 (max (if elems
9521 (js2-node-pos (car elems))
9522 pos)
9523 (save-excursion
9524 (goto-char comma-pos)
9525 (back-to-indentation)
9526 (point)))
9527 comma-pos))
9528
9529 (defun js2-parse-array-comp-or-literal ()
9530 (let ((pos (js2-current-token-beg)))
9531 (if (and (>= js2-language-version 200)
9532 (js2-match-token js2-FOR))
9533 (js2-parse-array-comp pos)
9534 (js2-parse-array-literal pos))))
9535
9536 (defun js2-parse-array-literal (pos)
9537 (let ((after-lb-or-comma t)
9538 after-comma tt elems pn
9539 (continue t))
9540 (unless js2-is-in-destructuring
9541 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9542 (while continue
9543 (setq tt (js2-get-token))
9544 (cond
9545 ;; comma
9546 ((= tt js2-COMMA)
9547 (setq after-comma (js2-current-token-end))
9548 (if (not after-lb-or-comma)
9549 (setq after-lb-or-comma t)
9550 (push nil elems)))
9551 ;; end of array
9552 ((or (= tt js2-RB)
9553 (= tt js2-EOF)) ; prevent infinite loop
9554 (if (= tt js2-EOF)
9555 (js2-report-error "msg.no.bracket.arg" nil pos))
9556 (when (and after-comma (< js2-language-version 170))
9557 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9558 pos (remove nil elems) after-comma))
9559 (setq continue nil
9560 pn (make-js2-array-node :pos pos
9561 :len (- js2-ts-cursor pos)
9562 :elems (nreverse elems)))
9563 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9564 ;; destructuring binding
9565 (js2-is-in-destructuring
9566 (push (if (or (= tt js2-LC)
9567 (= tt js2-LB)
9568 (= tt js2-NAME))
9569 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9570 (js2-parse-destruct-primary-expr)
9571 ;; invalid pattern
9572 (js2-report-error "msg.bad.var")
9573 (make-js2-error-node))
9574 elems)
9575 (setq after-lb-or-comma nil
9576 after-comma nil))
9577 ;; array comp
9578 ((and (>= js2-language-version 170)
9579 (= tt js2-FOR) ; check for array comprehension
9580 (not after-lb-or-comma) ; "for" can't follow a comma
9581 elems ; must have at least 1 element
9582 (not (cdr elems))) ; but no 2nd element
9583 (js2-unget-token)
9584 (setf continue nil
9585 pn (js2-parse-legacy-array-comp (car elems) pos)))
9586 ;; another element
9587 (t
9588 (unless after-lb-or-comma
9589 (js2-report-error "msg.no.bracket.arg"))
9590 (if (and (= tt js2-TRIPLEDOT)
9591 (>= js2-language-version 200))
9592 ;; spread operator
9593 (push (js2-make-unary tt 'js2-parse-assign-expr)
9594 elems)
9595 (js2-unget-token)
9596 (push (js2-parse-assign-expr) elems))
9597 (setq after-lb-or-comma nil
9598 after-comma nil))))
9599 (unless js2-is-in-destructuring
9600 (js2-pop-scope))
9601 pn))
9602
9603 (defun js2-parse-legacy-array-comp (expr pos)
9604 "Parse a legacy array comprehension (JavaScript 1.7).
9605 EXPR is the first expression after the opening left-bracket.
9606 POS is the beginning of the LB token preceding EXPR.
9607 We should have just parsed the 'for' keyword before calling this function."
9608 (let ((current-scope js2-current-scope)
9609 loops first filter result)
9610 (unwind-protect
9611 (progn
9612 (while (js2-match-token js2-FOR)
9613 (let ((loop (make-js2-comp-loop-node)))
9614 (js2-push-scope loop)
9615 (push loop loops)
9616 (js2-parse-comp-loop loop)))
9617 ;; First loop takes expr scope's parent.
9618 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9619 (js2-scope-parent-scope current-scope))
9620 ;; Set expr scope's parent to the last loop.
9621 (setf (js2-scope-parent-scope current-scope) (car loops))
9622 (if (/= (js2-get-token) js2-IF)
9623 (js2-unget-token)
9624 (setq filter (js2-parse-condition))))
9625 (dotimes (_ (1- (length loops)))
9626 (js2-pop-scope)))
9627 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9628 (setq result (make-js2-comp-node :pos pos
9629 :len (- js2-ts-cursor pos)
9630 :result expr
9631 :loops (nreverse loops)
9632 :filters (and filter (list (car filter)))
9633 :form 'LEGACY_ARRAY))
9634 (apply #'js2-node-add-children result expr (car filter)
9635 (js2-comp-node-loops result))
9636 result))
9637
9638 (defun js2-parse-array-comp (pos)
9639 "Parse an ES6 array comprehension.
9640 POS is the beginning of the LB token.
9641 We should have just parsed the 'for' keyword before calling this function."
9642 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9643 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9644 pn))
9645
9646 (defun js2-parse-generator-comp (pos)
9647 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9648 (js2-current-script-or-fn
9649 (make-js2-function-node :generator-type 'COMPREHENSION))
9650 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9651 (js2-must-match js2-RP "msg.no.paren" pos)
9652 pn))
9653
9654 (defun js2-parse-comprehension (pos form)
9655 (let (loops filters expr result)
9656 (unwind-protect
9657 (progn
9658 (js2-unget-token)
9659 (while (js2-match-token js2-FOR)
9660 (let ((loop (make-js2-comp-loop-node)))
9661 (js2-push-scope loop)
9662 (push loop loops)
9663 (js2-parse-comp-loop loop)))
9664 (while (js2-match-token js2-IF)
9665 (push (car (js2-parse-condition)) filters))
9666 (setq expr (js2-parse-assign-expr)))
9667 (dolist (_ loops)
9668 (js2-pop-scope)))
9669 (setq result (make-js2-comp-node :pos pos
9670 :len (- js2-ts-cursor pos)
9671 :result expr
9672 :loops (nreverse loops)
9673 :filters (nreverse filters)
9674 :form form))
9675 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9676 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9677 result))
9678
9679 (defun js2-parse-comp-loop (pn &optional only-of-p)
9680 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9681 The current token should be the initial FOR.
9682 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9683 (let ((pos (js2-comp-loop-node-pos pn))
9684 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9685 (when (and (not only-of-p) (js2-match-token js2-NAME))
9686 (if (string= (js2-current-token-string) "each")
9687 (progn
9688 (setq foreach-p t
9689 each-pos (- (js2-current-token-beg) pos)) ; relative
9690 (js2-record-face 'font-lock-keyword-face))
9691 (js2-report-error "msg.no.paren.for")))
9692 (if (js2-must-match js2-LP "msg.no.paren.for")
9693 (setq lp (- (js2-current-token-beg) pos)))
9694 (setq tt (js2-peek-token))
9695 (cond
9696 ((or (= tt js2-LB)
9697 (= tt js2-LC))
9698 (js2-get-token)
9699 (setq iter (js2-parse-destruct-primary-expr))
9700 (js2-define-destruct-symbols iter js2-LET
9701 'font-lock-variable-name-face t))
9702 ((js2-match-token js2-NAME)
9703 (setq iter (js2-create-name-node)))
9704 (t
9705 (js2-report-error "msg.bad.var")))
9706 ;; Define as a let since we want the scope of the variable to
9707 ;; be restricted to the array comprehension
9708 (if (js2-name-node-p iter)
9709 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9710 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9711 (and (>= js2-language-version 200)
9712 (js2-match-contextual-kwd "of")
9713 (setq forof-p t)))
9714 (setq in-pos (- (js2-current-token-beg) pos))
9715 (js2-report-error "msg.in.after.for.name"))
9716 (setq obj (js2-parse-expr))
9717 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9718 (setq rp (- (js2-current-token-beg) pos)))
9719 (setf (js2-node-pos pn) pos
9720 (js2-node-len pn) (- js2-ts-cursor pos)
9721 (js2-comp-loop-node-iterator pn) iter
9722 (js2-comp-loop-node-object pn) obj
9723 (js2-comp-loop-node-in-pos pn) in-pos
9724 (js2-comp-loop-node-each-pos pn) each-pos
9725 (js2-comp-loop-node-foreach-p pn) foreach-p
9726 (js2-comp-loop-node-forof-p pn) forof-p
9727 (js2-comp-loop-node-lp pn) lp
9728 (js2-comp-loop-node-rp pn) rp)
9729 (js2-node-add-children pn iter obj)
9730 pn))
9731
9732 (defun js2-parse-class-stmt ()
9733 (let ((pos (js2-current-token-beg)))
9734 (js2-must-match-name "msg.unnamed.class.stmt")
9735 (js2-parse-class pos 'CLASS_STATEMENT (js2-create-name-node t))))
9736
9737 (defun js2-parse-class-expr ()
9738 (let ((pos (js2-current-token-beg))
9739 name)
9740 (when (js2-match-token js2-NAME)
9741 (setq name (js2-create-name-node t)))
9742 (js2-parse-class pos 'CLASS_EXPRESSION name)))
9743
9744 (defun js2-parse-class (pos form name)
9745 ;; class X [extends ...] {
9746 (let (pn elems extends)
9747 (when name
9748 (js2-set-face (js2-node-pos name) (js2-node-end name)
9749 'font-lock-function-name-face 'record))
9750 (if (js2-match-token js2-EXTENDS)
9751 (if (= (js2-peek-token) js2-LC)
9752 (js2-report-error "msg.missing.extends")
9753 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
9754 (setq extends (js2-parse-assign-expr))
9755 (if (not extends)
9756 (js2-report-error "msg.bad.extends"))))
9757 (js2-must-match js2-LC "msg.no.brace.class")
9758 (setq elems (js2-parse-object-literal-elems t)
9759 pn (make-js2-class-node :pos pos
9760 :len (- js2-ts-cursor pos)
9761 :form form
9762 :name name
9763 :extends extends
9764 :elems elems))
9765 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
9766 pn))
9767
9768 (defun js2-parse-object-literal ()
9769 (let* ((pos (js2-current-token-beg))
9770 (elems (js2-parse-object-literal-elems))
9771 (result (make-js2-object-node :pos pos
9772 :len (- js2-ts-cursor pos)
9773 :elems elems)))
9774 (apply #'js2-node-add-children result (js2-object-node-elems result))
9775 result))
9776
9777 (defun js2-parse-object-literal-elems (&optional class-p)
9778 (let ((pos (js2-current-token-beg))
9779 (static nil)
9780 (continue t)
9781 tt elems elem after-comma)
9782 (while continue
9783 (setq static (and class-p (js2-match-token js2-STATIC))
9784 tt (js2-get-token)
9785 elem nil)
9786 (cond
9787 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9788 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
9789 ;; TODO(sdh): support *foo() {...}
9790 ((or (js2-valid-prop-name-token tt)
9791 (= tt js2-STRING))
9792 (setq after-comma nil
9793 elem (js2-parse-named-prop tt))
9794 (if (and (null elem)
9795 (not js2-recover-from-parse-errors))
9796 (setq continue nil)))
9797 ;; {[Symbol.iterator]: ...}
9798 ((and (= tt js2-LB)
9799 (>= js2-language-version 200))
9800 (let ((expr (js2-parse-expr)))
9801 (js2-must-match js2-RB "msg.missing.computed.rb")
9802 (setq after-comma nil
9803 elem (js2-parse-plain-property expr))))
9804 ;; {12: x} or {10.7: x}
9805 ((= tt js2-NUMBER)
9806 (setq after-comma nil
9807 elem (js2-parse-plain-property (make-js2-number-node))))
9808 ;; Break out of loop, and handle trailing commas.
9809 ((or (= tt js2-RC)
9810 (= tt js2-EOF))
9811 (js2-unget-token)
9812 (setq continue nil)
9813 (if after-comma
9814 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9815 pos elems after-comma)))
9816 (t
9817 (js2-report-error "msg.bad.prop")
9818 (unless js2-recover-from-parse-errors
9819 (setq continue nil)))) ; end switch
9820 ;; Handle static for classes' codegen.
9821 (if static
9822 (if elem (js2-node-set-prop elem 'STATIC t)
9823 (js2-report-error "msg.unexpected.static")))
9824 ;; Handle commas, depending on class-p.
9825 (let ((comma (js2-match-token js2-COMMA)))
9826 (if class-p
9827 (if comma
9828 (js2-report-error "msg.class.unexpected.comma"))
9829 (if comma
9830 (setq after-comma (js2-current-token-end))
9831 (setq continue nil))))
9832 ;; Append any parsed element.
9833 (if elem (push elem elems))) ; end loop
9834 (js2-must-match js2-RC "msg.no.brace.prop")
9835 (nreverse elems)))
9836
9837 (defun js2-parse-named-prop (tt)
9838 "Parse a name, string, or getter/setter object property.
9839 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9840 (let ((string-prop (and (= tt js2-STRING)
9841 (make-js2-string-node)))
9842 expr
9843 (ppos (js2-current-token-beg))
9844 (pend (js2-current-token-end))
9845 (name (js2-create-name-node))
9846 (prop (js2-current-token-string)))
9847 (cond
9848 ;; getter/setter prop
9849 ((and (= tt js2-NAME)
9850 (= (js2-peek-token) js2-NAME)
9851 (or (string= prop "get")
9852 (string= prop "set")))
9853 (js2-get-token)
9854 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9855 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9856 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9857 (js2-parse-getter-setter-prop ppos name prop))
9858 ;; method definition: {f() {...}}
9859 ((and (= (js2-peek-token) js2-LP)
9860 (>= js2-language-version 200))
9861 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; name
9862 (js2-parse-getter-setter-prop ppos name ""))
9863 ;; regular prop
9864 (t
9865 (prog1
9866 (setq expr (js2-parse-plain-property (or string-prop name)))
9867 (when (and (not string-prop)
9868 (not js2-is-in-destructuring)
9869 js2-highlight-external-variables
9870 (js2-node-get-prop expr 'SHORTHAND))
9871 (js2-record-name-node name))
9872 (js2-set-face ppos pend
9873 (if (js2-function-node-p
9874 (js2-object-prop-node-right expr))
9875 'font-lock-function-name-face
9876 'font-lock-variable-name-face)
9877 'record))))))
9878
9879 (defun js2-parse-plain-property (prop)
9880 "Parse a non-getter/setter property in an object literal.
9881 PROP is the node representing the property: a number, name or string."
9882 (let* ((tt (js2-get-token))
9883 (pos (js2-node-pos prop))
9884 colon expr result)
9885 (cond
9886 ;; Abbreviated property, as in {foo, bar}
9887 ((and (>= js2-language-version 200)
9888 (or (= tt js2-COMMA)
9889 (= tt js2-RC))
9890 (not (js2-number-node-p prop)))
9891 (js2-unget-token)
9892 (setq result (make-js2-object-prop-node
9893 :pos pos
9894 :left prop
9895 :right prop
9896 :op-pos (js2-current-token-len)))
9897 (js2-node-add-children result prop)
9898 (js2-node-set-prop result 'SHORTHAND t)
9899 result)
9900 ;; Normal property
9901 (t
9902 (if (= tt js2-COLON)
9903 (setq colon (- (js2-current-token-beg) pos)
9904 expr (js2-parse-assign-expr))
9905 (js2-report-error "msg.no.colon.prop")
9906 (setq expr (make-js2-error-node)))
9907 (setq result (make-js2-object-prop-node
9908 :pos pos
9909 ;; don't include last consumed token in length
9910 :len (- (+ (js2-node-pos expr)
9911 (js2-node-len expr))
9912 pos)
9913 :left prop
9914 :right expr
9915 :op-pos colon))
9916 (js2-node-add-children result prop expr)
9917 result))))
9918
9919 (defun js2-parse-getter-setter-prop (pos prop type-string)
9920 "Parse getter or setter property in an object literal.
9921 JavaScript syntax is:
9922
9923 { get foo() {...}, set foo(x) {...} }
9924
9925 and expression closure style is also supported
9926
9927 { get foo() x, set foo(x) _x = x }
9928
9929 POS is the start position of the `get' or `set' keyword.
9930 PROP is the `js2-name-node' representing the property name.
9931 GET-P is non-nil if the keyword was `get'."
9932 (let ((type (cond
9933 ((string= "get" type-string) js2-GET)
9934 ((string= "set" type-string) js2-SET)
9935 (t js2-FUNCTION)))
9936 result end
9937 (fn (js2-parse-function-expr)))
9938 ;; it has to be an anonymous function, as we already parsed the name
9939 (if (/= (js2-node-type fn) js2-FUNCTION)
9940 (js2-report-error "msg.bad.prop")
9941 (if (plusp (length (js2-function-name fn)))
9942 (js2-report-error "msg.bad.prop")))
9943 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9944 (setq end (js2-node-end fn)
9945 result (make-js2-getter-setter-node :type type
9946 :pos pos
9947 :len (- end pos)
9948 :left prop
9949 :right fn))
9950 (js2-node-add-children result prop fn)
9951 result))
9952
9953 (defun js2-create-name-node (&optional check-activation-p token string)
9954 "Create a name node using the current token and, optionally, STRING.
9955 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9956 (let* ((beg (js2-current-token-beg))
9957 (tt (js2-current-token-type))
9958 (s (or string
9959 (if (= js2-NAME tt)
9960 (js2-current-token-string)
9961 (js2-tt-name tt))))
9962 name)
9963 (setq name (make-js2-name-node :pos beg
9964 :name s
9965 :len (length s)))
9966 (if check-activation-p
9967 (js2-check-activation-name s (or token js2-NAME)))
9968 name))
9969
9970 ;;; Indentation support
9971
9972 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9973 ;; Karl cleverly deduces that the desired indentation level is often a
9974 ;; function of paren/bracket/brace nesting depth, which can be determined
9975 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9976 ;; then does some equally clever checks to see if we're in the context of a
9977 ;; substatement of a possibly braceless statement keyword such as if, while,
9978 ;; or finally. This approach yields pretty good results.
9979
9980 ;; The indenter is often "wrong", however, and needs to be overridden.
9981 ;; The right long-term solution is probably to emulate (or integrate
9982 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9983 ;; parse tree from `js2-parse' is present, which is not true at the
9984 ;; moment the user is typing, computing indentation is still thousands
9985 ;; of lines of code to handle every possible syntactic edge case.
9986
9987 ;; In the meantime, the compromise solution is that we offer a "bounce
9988 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9989 ;; current line indent among various likely guess points. This approach
9990 ;; is far from perfect, but should at least make it slightly easier to
9991 ;; move the line towards its desired indentation when manually
9992 ;; overriding Karl's heuristic nesting guesser.
9993
9994 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9995 ;; extensions such as `let' and Array comprehensions. Major kudos to
9996 ;; Karl for coming up with the initial approach, which packs a lot of
9997 ;; punch for so little code.
9998
9999 (defconst js2-possibly-braceless-keywords-re
10000 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10001 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10002 "try" "while" "with" "let")))
10003 "Regular expression matching keywords that are optionally
10004 followed by an opening brace.")
10005
10006 (defconst js2-indent-operator-re
10007 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10008 (regexp-opt '("in" "instanceof") 'words))
10009 "Regular expression matching operators that affect indentation
10010 of continued expressions.")
10011
10012 (defconst js2-declaration-keyword-re
10013 (regexp-opt '("var" "let" "const") 'words)
10014 "Regular expression matching variable declaration keywords.")
10015
10016 (defun js2-re-search-forward-inner (regexp &optional bound count)
10017 "Auxiliary function for `js2-re-search-forward'."
10018 (let (parse saved-point)
10019 (while (> count 0)
10020 (re-search-forward regexp bound)
10021 (setq parse (if saved-point
10022 (parse-partial-sexp saved-point (point))
10023 (syntax-ppss (point))))
10024 (cond ((nth 3 parse)
10025 (re-search-forward
10026 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10027 (save-excursion (end-of-line) (point)) t))
10028 ((nth 7 parse)
10029 (forward-line))
10030 ((or (nth 4 parse)
10031 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10032 (re-search-forward "\\*/"))
10033 (t
10034 (setq count (1- count))))
10035 (setq saved-point (point))))
10036 (point))
10037
10038 (defun js2-re-search-forward (regexp &optional bound noerror count)
10039 "Search forward but ignore strings and comments.
10040 Invokes `re-search-forward' but treats the buffer as if strings
10041 and comments have been removed."
10042 (let ((saved-point (point)))
10043 (condition-case err
10044 (cond ((null count)
10045 (js2-re-search-forward-inner regexp bound 1))
10046 ((< count 0)
10047 (js2-re-search-backward-inner regexp bound (- count)))
10048 ((> count 0)
10049 (js2-re-search-forward-inner regexp bound count)))
10050 (search-failed
10051 (goto-char saved-point)
10052 (unless noerror
10053 (error (error-message-string err)))))))
10054
10055 (defun js2-re-search-backward-inner (regexp &optional bound count)
10056 "Auxiliary function for `js2-re-search-backward'."
10057 (let (parse)
10058 (while (> count 0)
10059 (re-search-backward regexp bound)
10060 (setq parse (syntax-ppss (point)))
10061 (cond ((nth 3 parse)
10062 (re-search-backward
10063 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10064 (line-beginning-position) t))
10065 ((nth 7 parse)
10066 (goto-char (nth 8 parse)))
10067 ((or (nth 4 parse)
10068 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10069 (re-search-backward "/\\*"))
10070 (t
10071 (setq count (1- count))))))
10072 (point))
10073
10074 (defun js2-re-search-backward (regexp &optional bound noerror count)
10075 "Search backward but ignore strings and comments.
10076 Invokes `re-search-backward' but treats the buffer as if strings
10077 and comments have been removed."
10078 (let ((saved-point (point)))
10079 (condition-case err
10080 (cond ((null count)
10081 (js2-re-search-backward-inner regexp bound 1))
10082 ((< count 0)
10083 (js2-re-search-forward-inner regexp bound (- count)))
10084 ((> count 0)
10085 (js2-re-search-backward-inner regexp bound count)))
10086 (search-failed
10087 (goto-char saved-point)
10088 (unless noerror
10089 (error (error-message-string err)))))))
10090
10091 (defun js2-looking-at-operator-p ()
10092 "Return non-nil if text after point is a non-comma operator."
10093 (and (looking-at js2-indent-operator-re)
10094 (or (not (looking-at ":"))
10095 (save-excursion
10096 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10097 (looking-at "?"))))))
10098
10099 (defun js2-continued-expression-p ()
10100 "Return non-nil if the current line continues an expression."
10101 (save-excursion
10102 (back-to-indentation)
10103 (or (js2-looking-at-operator-p)
10104 (when (catch 'found
10105 (while (and (re-search-backward "\n" nil t)
10106 (let ((state (syntax-ppss)))
10107 (when (nth 4 state)
10108 (goto-char (nth 8 state))) ;; skip comments
10109 (skip-chars-backward " \t")
10110 (if (bolp)
10111 t
10112 (throw 'found t))))))
10113 (backward-char)
10114 (when (js2-looking-at-operator-p)
10115 (backward-char)
10116 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10117
10118 (defun js2-end-of-do-while-loop-p ()
10119 "Return non-nil if word after point is `while' of a do-while
10120 statement, else returns nil. A braceless do-while statement
10121 spanning several lines requires that the start of the loop is
10122 indented to the same column as the current line."
10123 (interactive)
10124 (save-excursion
10125 (when (looking-at "\\s-*\\<while\\>")
10126 (if (save-excursion
10127 (skip-chars-backward "[ \t\n]*}")
10128 (looking-at "[ \t\n]*}"))
10129 (save-excursion
10130 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10131 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10132 (or (looking-at "\\<do\\>")
10133 (let ((saved-indent (current-indentation)))
10134 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10135 (/= (current-indentation) saved-indent)))
10136 (and (looking-at "[ \t]*\\<do\\>")
10137 (not (js2-re-search-forward
10138 "\\<while\\>" (point-at-eol) t))
10139 (= (current-indentation) saved-indent))))))))
10140
10141 (defun js2-multiline-decl-indentation ()
10142 "Return the declaration indentation column if the current line belongs
10143 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10144 (let (forward-sexp-function ; use Lisp version
10145 at-opening-bracket)
10146 (save-excursion
10147 (back-to-indentation)
10148 (when (not (looking-at js2-declaration-keyword-re))
10149 (when (looking-at js2-indent-operator-re)
10150 (goto-char (match-end 0))) ; continued expressions are ok
10151 (while (and (not at-opening-bracket)
10152 (not (bobp))
10153 (let ((pos (point)))
10154 (save-excursion
10155 (js2-backward-sws)
10156 (or (eq (char-before) ?,)
10157 (and (not (eq (char-before) ?\;))
10158 (prog2 (skip-syntax-backward ".")
10159 (looking-at js2-indent-operator-re)
10160 (js2-backward-sws))
10161 (not (eq (char-before) ?\;)))
10162 (js2-same-line pos)))))
10163 (condition-case _
10164 (backward-sexp)
10165 (scan-error (setq at-opening-bracket t))))
10166 (when (looking-at js2-declaration-keyword-re)
10167 (goto-char (match-end 0))
10168 (1+ (current-column)))))))
10169
10170 (defun js2-ctrl-statement-indentation ()
10171 "Return the proper indentation of current line if it is a control statement.
10172 Returns an indentation if this line starts the body of a control
10173 statement without braces, else returns nil."
10174 (let (forward-sexp-function)
10175 (save-excursion
10176 (back-to-indentation)
10177 (when (and (not (js2-same-line (point-min)))
10178 (not (looking-at "{"))
10179 (js2-re-search-backward "[[:graph:]]" nil t)
10180 (not (looking-at "[{([]"))
10181 (progn
10182 (forward-char)
10183 (when (= (char-before) ?\))
10184 ;; scan-sexps sometimes throws an error
10185 (ignore-errors (backward-sexp))
10186 (skip-chars-backward " \t" (point-at-bol)))
10187 (let ((pt (point)))
10188 (back-to-indentation)
10189 (when (looking-at "}[ \t]*")
10190 (goto-char (match-end 0)))
10191 (and (looking-at js2-possibly-braceless-keywords-re)
10192 (= (match-end 0) pt)
10193 (not (js2-end-of-do-while-loop-p))))))
10194 (+ (current-indentation) js2-basic-offset)))))
10195
10196 (defun js2-indent-in-array-comp (parse-status)
10197 "Return non-nil if we think we're in an array comprehension.
10198 In particular, return the buffer position of the first `for' kwd."
10199 (let ((bracket (nth 1 parse-status))
10200 (end (point)))
10201 (when bracket
10202 (save-excursion
10203 (goto-char bracket)
10204 (when (looking-at "\\[")
10205 (forward-char 1)
10206 (js2-forward-sws)
10207 (if (looking-at "[[{]")
10208 (let (forward-sexp-function) ; use Lisp version
10209 (forward-sexp) ; skip destructuring form
10210 (js2-forward-sws)
10211 (if (and (/= (char-after) ?,) ; regular array
10212 (looking-at "for"))
10213 (match-beginning 0)))
10214 ;; to skip arbitrary expressions we need the parser,
10215 ;; so we'll just guess at it.
10216 (if (and (> end (point)) ; not empty literal
10217 (re-search-forward "[^,]]* \\(for\\) " end t)
10218 ;; not inside comment or string literal
10219 (let ((state (parse-partial-sexp bracket (point))))
10220 (not (or (nth 3 state) (nth 4 state)))))
10221 (match-beginning 1))))))))
10222
10223 (defun js2-array-comp-indentation (parse-status for-kwd)
10224 (if (js2-same-line for-kwd)
10225 ;; first continuation line
10226 (save-excursion
10227 (goto-char (nth 1 parse-status))
10228 (forward-char 1)
10229 (skip-chars-forward " \t")
10230 (current-column))
10231 (save-excursion
10232 (goto-char for-kwd)
10233 (current-column))))
10234
10235 (defun js2-proper-indentation (parse-status)
10236 "Return the proper indentation for the current line."
10237 (save-excursion
10238 (back-to-indentation)
10239 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10240 (at-closing-bracket (looking-at "[]})]"))
10241 (same-indent-p (or at-closing-bracket
10242 (looking-at "\\<case\\>[^:]")
10243 (and (looking-at "\\<default:")
10244 (save-excursion
10245 (js2-backward-sws)
10246 (not (memq (char-before) '(?, ?{)))))))
10247 (continued-expr-p (js2-continued-expression-p))
10248 (declaration-indent (and js2-pretty-multiline-declarations
10249 (js2-multiline-decl-indentation)))
10250 (bracket (nth 1 parse-status))
10251 beg indent)
10252 (cond
10253 ;; indent array comprehension continuation lines specially
10254 ((and bracket
10255 (>= js2-language-version 170)
10256 (not (js2-same-line bracket))
10257 (setq beg (js2-indent-in-array-comp parse-status))
10258 (>= (point) (save-excursion
10259 (goto-char beg)
10260 (point-at-bol)))) ; at or after first loop?
10261 (js2-array-comp-indentation parse-status beg))
10262
10263 (ctrl-stmt-indent)
10264
10265 ((and declaration-indent continued-expr-p)
10266 (+ declaration-indent js2-basic-offset))
10267
10268 (declaration-indent)
10269
10270 (bracket
10271 (goto-char bracket)
10272 (cond
10273 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10274 (when (save-excursion (skip-chars-backward " \t)")
10275 (looking-at ")"))
10276 (backward-list))
10277 (back-to-indentation)
10278 (and (eq js2-pretty-multiline-declarations 'all)
10279 (looking-at js2-declaration-keyword-re)
10280 (goto-char (1+ (match-end 0))))
10281 (setq indent
10282 (cond (same-indent-p
10283 (current-column))
10284 (continued-expr-p
10285 (+ (current-column) (* 2 js2-basic-offset)))
10286 (t
10287 (+ (current-column) js2-basic-offset))))
10288 (if (and js2-indent-switch-body
10289 (not at-closing-bracket)
10290 (looking-at "\\_<switch\\_>"))
10291 (+ indent js2-basic-offset)
10292 indent))
10293 (t
10294 (unless same-indent-p
10295 (forward-char)
10296 (skip-chars-forward " \t"))
10297 (current-column))))
10298
10299 (continued-expr-p js2-basic-offset)
10300
10301 (t 0)))))
10302
10303 (defun js2-lineup-comment (parse-status)
10304 "Indent a multi-line block comment continuation line."
10305 (let* ((beg (nth 8 parse-status))
10306 (first-line (js2-same-line beg))
10307 (offset (save-excursion
10308 (goto-char beg)
10309 (if (looking-at "/\\*")
10310 (+ 1 (current-column))
10311 0))))
10312 (unless first-line
10313 (indent-line-to offset))))
10314
10315 (defun js2-backward-sws ()
10316 "Move backward through whitespace and comments."
10317 (interactive)
10318 (while (forward-comment -1)))
10319
10320 (defun js2-forward-sws ()
10321 "Move forward through whitespace and comments."
10322 (interactive)
10323 (while (forward-comment 1)))
10324
10325 (defun js2-current-indent (&optional pos)
10326 "Return column of indentation on current line.
10327 If POS is non-nil, go to that point and return indentation for that line."
10328 (save-excursion
10329 (if pos
10330 (goto-char pos))
10331 (back-to-indentation)
10332 (current-column)))
10333
10334 (defun js2-arglist-close ()
10335 "Return non-nil if we're on a line beginning with a close-paren/brace."
10336 (save-excursion
10337 (goto-char (point-at-bol))
10338 (js2-forward-sws)
10339 (looking-at "[])}]")))
10340
10341 (defun js2-indent-looks-like-label-p ()
10342 (goto-char (point-at-bol))
10343 (js2-forward-sws)
10344 (looking-at (concat js2-mode-identifier-re ":")))
10345
10346 (defun js2-indent-in-objlit-p (parse-status)
10347 "Return non-nil if this looks like an object-literal entry."
10348 (let ((start (nth 1 parse-status)))
10349 (and
10350 start
10351 (save-excursion
10352 (and (zerop (forward-line -1))
10353 (not (< (point) start)) ; crossed a {} boundary
10354 (js2-indent-looks-like-label-p)))
10355 (save-excursion
10356 (js2-indent-looks-like-label-p)))))
10357
10358 ;; If prev line looks like foobar({ then we're passing an object
10359 ;; literal to a function call, and people pretty much always want to
10360 ;; de-dent back to the previous line, so move the 'basic-offset'
10361 ;; position to the front.
10362 (defun js2-indent-objlit-arg-p (parse-status)
10363 (save-excursion
10364 (back-to-indentation)
10365 (js2-backward-sws)
10366 (and (eq (1- (point)) (nth 1 parse-status))
10367 (eq (char-before) ?{)
10368 (progn
10369 (forward-char -1)
10370 (skip-chars-backward " \t")
10371 (eq (char-before) ?\()))))
10372
10373 (defun js2-indent-case-block-p ()
10374 (save-excursion
10375 (back-to-indentation)
10376 (js2-backward-sws)
10377 (goto-char (point-at-bol))
10378 (skip-chars-forward " \t")
10379 (looking-at "case\\s-.+:")))
10380
10381 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10382 "Cycle among alternate computed indentation positions.
10383 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10384 of the buffer to the current point. NORMAL-COL is the indentation
10385 column computed by the heuristic guesser based on current paren,
10386 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10387 in reverse."
10388 (let ((cur-indent (js2-current-indent))
10389 (old-buffer-undo-list buffer-undo-list)
10390 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10391 (current-line (save-excursion
10392 (forward-line 0) ; move to bol
10393 (1+ (count-lines (point-min) (point)))))
10394 positions pos main-pos anchor arglist-cont same-indent
10395 basic-offset computed-pos)
10396 ;; temporarily don't record undo info, if user requested this
10397 (when js2-mode-indent-inhibit-undo
10398 (setq buffer-undo-list t))
10399 (unwind-protect
10400 (progn
10401 ;; First likely point: indent from beginning of previous code line
10402 (push (setq basic-offset
10403 (+ (save-excursion
10404 (back-to-indentation)
10405 (js2-backward-sws)
10406 (back-to-indentation)
10407 (current-column))
10408 js2-basic-offset))
10409 positions)
10410
10411 ;; (First + epsilon) likely point: indent 2x from beginning of
10412 ;; previous code line. Google does it this way.
10413 (push (setq basic-offset
10414 (+ (save-excursion
10415 (back-to-indentation)
10416 (js2-backward-sws)
10417 (back-to-indentation)
10418 (current-column))
10419 (* 2 js2-basic-offset)))
10420 positions)
10421
10422 ;; Second likely point: indent from assign-expr RHS. This
10423 ;; is just a crude guess based on finding " = " on the previous
10424 ;; line containing actual code.
10425 (setq pos (save-excursion
10426 (forward-line -1)
10427 (goto-char (point-at-bol))
10428 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10429 (point-at-eol) t)
10430 (goto-char (match-end 1))
10431 (skip-chars-forward " \t\r\n")
10432 (current-column))))
10433 (when pos
10434 (incf pos js2-basic-offset)
10435 (push pos positions))
10436
10437 ;; Third likely point: same indent as previous line of code.
10438 ;; Make it the first likely point if we're not on an
10439 ;; arglist-close line and previous line ends in a comma, or
10440 ;; both this line and prev line look like object-literal
10441 ;; elements.
10442 (setq pos (save-excursion
10443 (goto-char (point-at-bol))
10444 (js2-backward-sws)
10445 (back-to-indentation)
10446 (prog1
10447 (current-column)
10448 ;; while we're here, look for trailing comma
10449 (if (save-excursion
10450 (goto-char (point-at-eol))
10451 (js2-backward-sws)
10452 (eq (char-before) ?,))
10453 (setq arglist-cont (1- (point)))))))
10454 (when pos
10455 (if (and (or arglist-cont
10456 (js2-indent-in-objlit-p parse-status))
10457 (not (js2-arglist-close)))
10458 (setq same-indent pos))
10459 (push pos positions))
10460
10461 ;; Fourth likely point: first preceding code with less indentation.
10462 ;; than the immediately preceding code line.
10463 (setq pos (save-excursion
10464 (back-to-indentation)
10465 (js2-backward-sws)
10466 (back-to-indentation)
10467 (setq anchor (current-column))
10468 (while (and (zerop (forward-line -1))
10469 (>= (progn
10470 (back-to-indentation)
10471 (current-column))
10472 anchor)))
10473 (setq pos (current-column))))
10474 (push pos positions)
10475
10476 ;; nesting-heuristic position, main by default
10477 (push (setq main-pos normal-col) positions)
10478
10479 ;; delete duplicates and sort positions list
10480 (setq positions (sort (delete-dups positions) '<))
10481
10482 ;; comma-list continuation lines: prev line indent takes precedence
10483 (if same-indent
10484 (setq main-pos same-indent))
10485
10486 ;; common special cases where we want to indent in from previous line
10487 (if (or (js2-indent-case-block-p)
10488 (js2-indent-objlit-arg-p parse-status))
10489 (setq main-pos basic-offset))
10490
10491 ;; if bouncing backwards, reverse positions list
10492 (if backwards
10493 (setq positions (reverse positions)))
10494
10495 ;; record whether we're already sitting on one of the alternatives
10496 (setq pos (member cur-indent positions))
10497
10498 (cond
10499 ;; case 0: we're one one of the alternatives and this is the
10500 ;; first time they've pressed TAB on this line (best-guess).
10501 ((and js2-mode-indent-ignore-first-tab
10502 pos
10503 ;; first time pressing TAB on this line?
10504 (not (eq js2-mode-last-indented-line current-line)))
10505 ;; do nothing
10506 (setq computed-pos nil))
10507 ;; case 1: only one computed position => use it
10508 ((null (cdr positions))
10509 (setq computed-pos 0))
10510 ;; case 2: not on any of the computed spots => use main spot
10511 ((not pos)
10512 (setq computed-pos (js2-position main-pos positions)))
10513 ;; case 3: on last position: cycle to first position
10514 ((null (cdr pos))
10515 (setq computed-pos 0))
10516 ;; case 4: on intermediate position: cycle to next position
10517 (t
10518 (setq computed-pos (js2-position (second pos) positions))))
10519
10520 ;; see if any hooks want to indent; otherwise we do it
10521 (loop with result = nil
10522 for hook in js2-indent-hook
10523 while (null result)
10524 do
10525 (setq result (funcall hook positions computed-pos))
10526 finally do
10527 (unless (or result (null computed-pos))
10528 (indent-line-to (nth computed-pos positions)))))
10529
10530 ;; finally
10531 (if js2-mode-indent-inhibit-undo
10532 (setq buffer-undo-list old-buffer-undo-list))
10533 ;; see commentary for `js2-mode-last-indented-line'
10534 (setq js2-mode-last-indented-line current-line))))
10535
10536 (defun js2-indent-bounce-backwards ()
10537 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10538 cycles between the computed indentation positions in reverse order."
10539 (interactive)
10540 (js2-indent-line t))
10541
10542 (defun js2-1-line-comment-continuation-p ()
10543 "Return t if we're in a 1-line comment continuation.
10544 If so, we don't ever want to use bounce-indent."
10545 (save-excursion
10546 (and (progn
10547 (forward-line 0)
10548 (looking-at "\\s-*//"))
10549 (progn
10550 (forward-line -1)
10551 (forward-line 0)
10552 (when (looking-at "\\s-*$")
10553 (js2-backward-sws)
10554 (forward-line 0))
10555 (looking-at "\\s-*//")))))
10556
10557 (defun js2-indent-line (&optional bounce-backwards)
10558 "Indent the current line as JavaScript source text."
10559 (interactive)
10560 (let (parse-status offset indent-col
10561 ;; Don't whine about errors/warnings when we're indenting.
10562 ;; This has to be set before calling parse-partial-sexp below.
10563 (inhibit-point-motion-hooks t))
10564 (setq parse-status (save-excursion
10565 (syntax-ppss (point-at-bol)))
10566 offset (- (point) (save-excursion
10567 (back-to-indentation)
10568 (point))))
10569 (js2-with-underscore-as-word-syntax
10570 (if (nth 4 parse-status)
10571 (js2-lineup-comment parse-status)
10572 (setq indent-col (js2-proper-indentation parse-status))
10573 ;; See comments below about `js2-mode-last-indented-line'.
10574 (cond
10575 ;; bounce-indenting is disabled during electric-key indent.
10576 ;; It doesn't work well on first line of buffer.
10577 ((and js2-bounce-indent-p
10578 (not (js2-same-line (point-min)))
10579 (not (js2-1-line-comment-continuation-p)))
10580 (js2-bounce-indent indent-col parse-status bounce-backwards))
10581 ;; just indent to the guesser's likely spot
10582 (t (indent-line-to indent-col))))
10583 (when (plusp offset)
10584 (forward-char offset)))))
10585
10586 (defun js2-indent-region (start end)
10587 "Indent the region, but don't use bounce indenting."
10588 (let ((js2-bounce-indent-p nil)
10589 (indent-region-function nil)
10590 (after-change-functions (remq 'js2-mode-edit
10591 after-change-functions)))
10592 (indent-region start end nil) ; nil for byte-compiler
10593 (js2-mode-edit start end (- end start))))
10594
10595 (defvar js2-minor-mode-map
10596 (let ((map (make-sparse-keymap)))
10597 (define-key map (kbd "C-c C-`") #'js2-next-error)
10598 (define-key map [mouse-1] #'js2-mode-show-node)
10599 map)
10600 "Keymap used when `js2-minor-mode' is active.")
10601
10602 ;;;###autoload
10603 (define-minor-mode js2-minor-mode
10604 "Minor mode for running js2 as a background linter.
10605 This allows you to use a different major mode for JavaScript editing,
10606 such as `js-mode', while retaining the asynchronous error/warning
10607 highlighting features of `js2-mode'."
10608 :group 'js2-mode
10609 :lighter " js-lint"
10610 (if js2-minor-mode
10611 (js2-minor-mode-enter)
10612 (js2-minor-mode-exit)))
10613
10614 (defun js2-minor-mode-enter ()
10615 "Initialization for `js2-minor-mode'."
10616 (set (make-local-variable 'max-lisp-eval-depth)
10617 (max max-lisp-eval-depth 3000))
10618 (setq next-error-function #'js2-next-error)
10619 (js2-set-default-externs)
10620 ;; Experiment: make reparse-delay longer for longer files.
10621 (if (plusp js2-dynamic-idle-timer-adjust)
10622 (setq js2-idle-timer-delay
10623 (* js2-idle-timer-delay
10624 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10625 (setq js2-mode-buffer-dirty-p t
10626 js2-mode-parsing nil)
10627 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10628 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10629 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10630 (when js2-include-jslint-globals
10631 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10632 (run-hooks 'js2-init-hook)
10633 (js2-reparse))
10634
10635 (defun js2-minor-mode-exit ()
10636 "Turn off `js2-minor-mode'."
10637 (setq next-error-function nil)
10638 (remove-hook 'after-change-functions #'js2-mode-edit t)
10639 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10640 (when js2-mode-node-overlay
10641 (delete-overlay js2-mode-node-overlay)
10642 (setq js2-mode-node-overlay nil))
10643 (js2-remove-overlays)
10644 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10645 (setq js2-mode-ast nil))
10646
10647 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10648 (make-variable-buffer-local 'js2-source-buffer)
10649
10650 (defun* js2-display-error-list ()
10651 "Display a navigable buffer listing parse errors/warnings."
10652 (interactive)
10653 (unless (js2-have-errors-p)
10654 (message "No errors")
10655 (return-from js2-display-error-list))
10656 (labels ((annotate-list
10657 (lst type)
10658 "Add diagnostic TYPE and line number to errs list"
10659 (mapcar (lambda (err)
10660 (list err type (line-number-at-pos (nth 1 err))))
10661 lst)))
10662 (let* ((srcbuf (current-buffer))
10663 (errbuf (get-buffer-create "*js-lint*"))
10664 (errors (annotate-list
10665 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10666 'js2-error)) ; must be a valid face name
10667 (warnings (annotate-list
10668 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10669 'js2-warning)) ; must be a valid face name
10670 (all-errs (sort (append errors warnings)
10671 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10672 (with-current-buffer errbuf
10673 (let ((inhibit-read-only t))
10674 (erase-buffer)
10675 (dolist (err all-errs)
10676 (destructuring-bind ((msg-key beg _end &rest) type line) err
10677 (insert-text-button
10678 (format "line %d: %s" line (js2-get-msg msg-key))
10679 'face type
10680 'follow-link "\C-m"
10681 'action 'js2-error-buffer-jump
10682 'js2-msg (js2-get-msg msg-key)
10683 'js2-pos beg)
10684 (insert "\n"))))
10685 (js2-error-buffer-mode)
10686 (setq js2-source-buffer srcbuf)
10687 (pop-to-buffer errbuf)
10688 (goto-char (point-min))
10689 (unless (eobp)
10690 (js2-error-buffer-view))))))
10691
10692 (defvar js2-error-buffer-mode-map
10693 (let ((map (make-sparse-keymap)))
10694 (define-key map "n" #'js2-error-buffer-next)
10695 (define-key map "p" #'js2-error-buffer-prev)
10696 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10697 (define-key map "o" #'js2-error-buffer-view)
10698 (define-key map "q" #'js2-error-buffer-quit)
10699 map)
10700 "Keymap used for js2 diagnostics buffers.")
10701
10702 (defun js2-error-buffer-mode ()
10703 "Major mode for js2 diagnostics buffers.
10704 Selecting an error will jump it to the corresponding source-buffer error.
10705 \\{js2-error-buffer-mode-map}"
10706 (interactive)
10707 (setq major-mode 'js2-error-buffer-mode
10708 mode-name "JS Lint Diagnostics")
10709 (use-local-map js2-error-buffer-mode-map)
10710 (setq truncate-lines t)
10711 (set-buffer-modified-p nil)
10712 (setq buffer-read-only t)
10713 (run-hooks 'js2-error-buffer-mode-hook))
10714
10715 (defun js2-error-buffer-next ()
10716 "Move to next error and view it."
10717 (interactive)
10718 (when (zerop (forward-line 1))
10719 (js2-error-buffer-view)))
10720
10721 (defun js2-error-buffer-prev ()
10722 "Move to previous error and view it."
10723 (interactive)
10724 (when (zerop (forward-line -1))
10725 (js2-error-buffer-view)))
10726
10727 (defun js2-error-buffer-quit ()
10728 "Kill the current buffer."
10729 (interactive)
10730 (kill-buffer))
10731
10732 (defun js2-error-buffer-jump (&rest ignored)
10733 "Jump cursor to current error in source buffer."
10734 (interactive)
10735 (when (js2-error-buffer-view)
10736 (pop-to-buffer js2-source-buffer)))
10737
10738 (defun js2-error-buffer-view ()
10739 "Scroll source buffer to show error at current line."
10740 (interactive)
10741 (cond
10742 ((not (eq major-mode 'js2-error-buffer-mode))
10743 (message "Not in a js2 errors buffer"))
10744 ((not (buffer-live-p js2-source-buffer))
10745 (message "Source buffer has been killed"))
10746 ((not (wholenump (get-text-property (point) 'js2-pos)))
10747 (message "There does not seem to be an error here"))
10748 (t
10749 (let ((pos (get-text-property (point) 'js2-pos))
10750 (msg (get-text-property (point) 'js2-msg)))
10751 (save-selected-window
10752 (pop-to-buffer js2-source-buffer)
10753 (goto-char pos)
10754 (message msg))))))
10755
10756 ;;;###autoload
10757 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10758 ;; FIXME: Should derive from js-mode.
10759 "Major mode for editing JavaScript code."
10760 ;; Used by comment-region; don't change it.
10761 (set (make-local-variable 'comment-start) "//")
10762 (set (make-local-variable 'comment-end) "")
10763 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10764 (set (make-local-variable 'max-lisp-eval-depth)
10765 (max max-lisp-eval-depth 3000))
10766 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10767 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10768 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10769 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10770 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10771 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10772 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10773 ;; for characters inside regexp literals.
10774 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10775 ;; this is necessary to make `show-paren-function' work properly
10776 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10777 ;; needed for M-x rgrep, among other things
10778 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10779
10780 (set (make-local-variable 'electric-indent-chars)
10781 (append "{}()[]:;,*." electric-indent-chars))
10782 (set (make-local-variable 'electric-layout-rules)
10783 '((?\; . after) (?\{ . after) (?\} . before)))
10784
10785 ;; some variables needed by cc-engine for paragraph-fill, etc.
10786 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10787 c-comment-start-regexp "/[*/]\\|\\s|"
10788 c-line-comment-starter "//"
10789 c-paragraph-start js2-paragraph-start
10790 c-paragraph-separate "$"
10791 c-syntactic-ws-start js2-syntactic-ws-start
10792 c-syntactic-ws-end js2-syntactic-ws-end
10793 c-syntactic-eol js2-syntactic-eol)
10794
10795 (let ((c-buffer-is-cc-mode t))
10796 ;; Copied from `js-mode'. Also see Bug#6071.
10797 (make-local-variable 'paragraph-start)
10798 (make-local-variable 'paragraph-separate)
10799 (make-local-variable 'paragraph-ignore-fill-prefix)
10800 (make-local-variable 'adaptive-fill-mode)
10801 (make-local-variable 'adaptive-fill-regexp)
10802 (c-setup-paragraph-variables))
10803
10804 (setq font-lock-defaults '(nil t))
10805
10806 ;; Experiment: make reparse-delay longer for longer files.
10807 (when (plusp js2-dynamic-idle-timer-adjust)
10808 (setq js2-idle-timer-delay
10809 (* js2-idle-timer-delay
10810 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10811
10812 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10813 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10814 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10815 (setq next-error-function #'js2-next-error)
10816 (imenu-add-to-menubar (concat "IM-" mode-name))
10817 (add-to-invisibility-spec '(js2-outline . t))
10818 (set (make-local-variable 'line-move-ignore-invisible) t)
10819 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10820
10821 (setq js2-mode-functions-hidden nil
10822 js2-mode-comments-hidden nil
10823 js2-mode-buffer-dirty-p t
10824 js2-mode-parsing nil)
10825
10826 (js2-set-default-externs)
10827
10828 (when js2-include-jslint-globals
10829 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10830
10831 (run-hooks 'js2-init-hook)
10832
10833 (js2-reparse))
10834
10835 (defun js2-mode-exit ()
10836 "Exit `js2-mode' and clean up."
10837 (interactive)
10838 (when js2-mode-node-overlay
10839 (delete-overlay js2-mode-node-overlay)
10840 (setq js2-mode-node-overlay nil))
10841 (js2-remove-overlays)
10842 (setq js2-mode-ast nil)
10843 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10844 (remove-from-invisibility-spec '(js2-outline . t))
10845 (js2-mode-show-all)
10846 (with-silent-modifications
10847 (js2-clear-face (point-min) (point-max))))
10848
10849 (defun js2-mode-reset-timer ()
10850 "Cancel any existing parse timer and schedule a new one."
10851 (if js2-mode-parse-timer
10852 (cancel-timer js2-mode-parse-timer))
10853 (setq js2-mode-parsing nil)
10854 (let ((timer (timer-create)))
10855 (setq js2-mode-parse-timer timer)
10856 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10857 (timer-set-idle-time timer js2-idle-timer-delay)
10858 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10859 (timer-activate-when-idle timer nil)))
10860
10861 (defun js2-mode-idle-reparse (buffer)
10862 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10863 it to be reparsed when the buffer is selected."
10864 (cond ((eq buffer (current-buffer))
10865 (js2-reparse))
10866 ((buffer-live-p buffer)
10867 ;; reparse when the buffer is selected again
10868 (with-current-buffer buffer
10869 (add-hook 'window-configuration-change-hook
10870 #'js2-mode-idle-reparse-inner
10871 nil t)))))
10872
10873 (defun js2-mode-idle-reparse-inner ()
10874 (remove-hook 'window-configuration-change-hook
10875 #'js2-mode-idle-reparse-inner
10876 t)
10877 (js2-reparse))
10878
10879 (defun js2-mode-edit (_beg _end _len)
10880 "Schedule a new parse after buffer is edited.
10881 Buffer edit spans from BEG to END and is of length LEN."
10882 (setq js2-mode-buffer-dirty-p t)
10883 (js2-mode-hide-overlay)
10884 (js2-mode-reset-timer))
10885
10886 (defun js2-minor-mode-edit (_beg _end _len)
10887 "Callback for buffer edits in `js2-mode'.
10888 Schedules a new parse after buffer is edited.
10889 Buffer edit spans from BEG to END and is of length LEN."
10890 (setq js2-mode-buffer-dirty-p t)
10891 (js2-mode-hide-overlay)
10892 (js2-mode-reset-timer))
10893
10894 (defun js2-reparse (&optional force)
10895 "Re-parse current buffer after user finishes some data entry.
10896 If we get any user input while parsing, including cursor motion,
10897 we discard the parse and reschedule it. If FORCE is nil, then the
10898 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10899 (let (time
10900 interrupted-p
10901 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10902 (unless js2-mode-parsing
10903 (setq js2-mode-parsing t)
10904 (unwind-protect
10905 (when (or js2-mode-buffer-dirty-p force)
10906 (js2-remove-overlays)
10907 (with-silent-modifications
10908 (setq js2-mode-buffer-dirty-p nil
10909 js2-mode-fontifications nil
10910 js2-mode-deferred-properties nil)
10911 (if js2-mode-verbose-parse-p
10912 (message "parsing..."))
10913 (setq time
10914 (js2-time
10915 (setq interrupted-p
10916 (catch 'interrupted
10917 (js2-parse)
10918 ;; if parsing is interrupted, comments and regex
10919 ;; literals stay ignored by `parse-partial-sexp'
10920 (remove-text-properties (point-min) (point-max)
10921 '(syntax-table))
10922 (js2-mode-apply-deferred-properties)
10923 (js2-mode-remove-suppressed-warnings)
10924 (js2-mode-show-warnings)
10925 (js2-mode-show-errors)
10926 (if (>= js2-highlight-level 1)
10927 (js2-highlight-jsdoc js2-mode-ast))
10928 nil))))
10929 (if interrupted-p
10930 (progn
10931 ;; unfinished parse => try again
10932 (setq js2-mode-buffer-dirty-p t)
10933 (js2-mode-reset-timer))
10934 (if js2-mode-verbose-parse-p
10935 (message "Parse time: %s" time)))))
10936 (setq js2-mode-parsing nil)
10937 (unless interrupted-p
10938 (setq js2-mode-parse-timer nil))))))
10939
10940 (defun js2-mode-show-node (event)
10941 "Debugging aid: highlight selected AST node on mouse click."
10942 (interactive "e")
10943 (mouse-set-point event)
10944 (setq deactivate-mark t)
10945 (when js2-mode-show-overlay
10946 (let ((node (js2-node-at-point))
10947 beg end)
10948 (if (null node)
10949 (message "No node found at location %s" (point))
10950 (setq beg (js2-node-abs-pos node)
10951 end (+ beg (js2-node-len node)))
10952 (if js2-mode-node-overlay
10953 (move-overlay js2-mode-node-overlay beg end)
10954 (setq js2-mode-node-overlay (make-overlay beg end))
10955 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10956 (with-silent-modifications
10957 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10958 (message "%s, parent: %s"
10959 (js2-node-short-name node)
10960 (if (js2-node-parent node)
10961 (js2-node-short-name (js2-node-parent node))
10962 "nil"))))))
10963
10964 (defun js2-mode-hide-overlay (&optional _p1 p2)
10965 "Remove the debugging overlay when the point moves.
10966 P1 and P2 are the old and new values of point, respectively."
10967 (when js2-mode-node-overlay
10968 (let ((beg (overlay-start js2-mode-node-overlay))
10969 (end (overlay-end js2-mode-node-overlay)))
10970 ;; Sometimes we're called spuriously.
10971 (unless (and p2
10972 (>= p2 beg)
10973 (<= p2 end))
10974 (with-silent-modifications
10975 (remove-text-properties beg end '(point-left nil)))
10976 (delete-overlay js2-mode-node-overlay)
10977 (setq js2-mode-node-overlay nil)))))
10978
10979 (defun js2-mode-reset ()
10980 "Debugging helper: reset everything."
10981 (interactive)
10982 (js2-mode-exit)
10983 (js2-mode))
10984
10985 (defun js2-mode-show-warn-or-err (e face)
10986 "Highlight a warning or error E with FACE.
10987 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10988 The last element is optional. When present, use instead of FACE."
10989 (let* ((key (first e))
10990 (beg (second e))
10991 (end (+ beg (third e)))
10992 ;; Don't inadvertently go out of bounds.
10993 (beg (max (point-min) (min beg (point-max))))
10994 (end (max (point-min) (min end (point-max))))
10995 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10996 (ovl (make-overlay beg end)))
10997 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10998 (overlay-put ovl 'js2-error t)
10999 (put-text-property beg end 'help-echo (js2-get-msg key))
11000 (put-text-property beg end 'point-entered #'js2-echo-error)))
11001
11002 (defun js2-remove-overlays ()
11003 "Remove overlays from buffer that have a `js2-error' property."
11004 (let ((beg (point-min))
11005 (end (point-max)))
11006 (save-excursion
11007 (dolist (o (overlays-in beg end))
11008 (when (overlay-get o 'js2-error)
11009 (delete-overlay o))))))
11010
11011 (defun js2-error-at-point (&optional pos)
11012 "Return non-nil if there's an error overlay at POS.
11013 Defaults to point."
11014 (loop with pos = (or pos (point))
11015 for o in (overlays-at pos)
11016 thereis (overlay-get o 'js2-error)))
11017
11018 (defun js2-mode-apply-deferred-properties ()
11019 "Apply fontifications and other text properties recorded during parsing."
11020 (when (plusp js2-highlight-level)
11021 ;; We defer clearing faces as long as possible to eliminate flashing.
11022 (js2-clear-face (point-min) (point-max))
11023 ;; Have to reverse the recorded fontifications list so that errors
11024 ;; and warnings overwrite the normal fontifications.
11025 (dolist (f (nreverse js2-mode-fontifications))
11026 (put-text-property (first f) (second f) 'font-lock-face (third f)))
11027 (setq js2-mode-fontifications nil))
11028 (dolist (p js2-mode-deferred-properties)
11029 (apply #'put-text-property p))
11030 (setq js2-mode-deferred-properties nil))
11031
11032 (defun js2-mode-show-errors ()
11033 "Highlight syntax errors."
11034 (when js2-mode-show-parse-errors
11035 (dolist (e (js2-ast-root-errors js2-mode-ast))
11036 (js2-mode-show-warn-or-err e 'js2-error))))
11037
11038 (defun js2-mode-remove-suppressed-warnings ()
11039 "Take suppressed warnings out of the AST warnings list.
11040 This ensures that the counts and `next-error' are correct."
11041 (setf (js2-ast-root-warnings js2-mode-ast)
11042 (js2-delete-if
11043 (lambda (e)
11044 (let ((key (caar e)))
11045 (or
11046 (and (not js2-strict-trailing-comma-warning)
11047 (string-match "trailing\\.comma" key))
11048 (and (not js2-strict-cond-assign-warning)
11049 (string= key "msg.equal.as.assign"))
11050 (and js2-missing-semi-one-line-override
11051 (string= key "msg.missing.semi")
11052 (let* ((beg (second e))
11053 (node (js2-node-at-point beg))
11054 (fn (js2-mode-find-parent-fn node))
11055 (body (and fn (js2-function-node-body fn)))
11056 (lc (and body (js2-node-abs-pos body)))
11057 (rc (and lc (+ lc (js2-node-len body)))))
11058 (and fn
11059 (or (null body)
11060 (save-excursion
11061 (goto-char beg)
11062 (and (js2-same-line lc)
11063 (js2-same-line rc))))))))))
11064 (js2-ast-root-warnings js2-mode-ast))))
11065
11066 (defun js2-mode-show-warnings ()
11067 "Highlight strict-mode warnings."
11068 (when js2-mode-show-strict-warnings
11069 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11070 (js2-mode-show-warn-or-err e 'js2-warning))))
11071
11072 (defun js2-echo-error (_old-point new-point)
11073 "Called by point-motion hooks."
11074 (let ((msg (get-text-property new-point 'help-echo)))
11075 (when (and (stringp msg)
11076 (not (active-minibuffer-window))
11077 (not (current-message)))
11078 (message msg))))
11079
11080 (defalias 'js2-echo-help #'js2-echo-error)
11081
11082 (defun js2-line-break (&optional _soft)
11083 "Break line at point and indent, continuing comment if within one.
11084 If inside a string, and `js2-concat-multiline-strings' is not
11085 nil, turn it into concatenation."
11086 (interactive)
11087 (let ((parse-status (syntax-ppss)))
11088 (cond
11089 ;; Check if we're inside a string.
11090 ((nth 3 parse-status)
11091 (if js2-concat-multiline-strings
11092 (js2-mode-split-string parse-status)
11093 (insert "\n")))
11094 ;; Check if inside a block comment.
11095 ((nth 4 parse-status)
11096 (js2-mode-extend-comment (nth 8 parse-status)))
11097 (t
11098 (newline-and-indent)))))
11099
11100 (defun js2-mode-split-string (parse-status)
11101 "Turn a newline in mid-string into a string concatenation.
11102 PARSE-STATUS is as documented in `parse-partial-sexp'."
11103 (let* ((quote-char (nth 3 parse-status))
11104 (at-eol (eq js2-concat-multiline-strings 'eol)))
11105 (insert quote-char)
11106 (insert (if at-eol " +\n" "\n"))
11107 (unless at-eol
11108 (insert "+ "))
11109 (js2-indent-line)
11110 (insert quote-char)
11111 (when (eolp)
11112 (insert quote-char)
11113 (backward-char 1))))
11114
11115 (defun js2-mode-extend-comment (start-pos)
11116 "Indent the line and, when inside a comment block, add comment prefix."
11117 (let (star single col first-line needs-close)
11118 (save-excursion
11119 (back-to-indentation)
11120 (when (< (point) start-pos)
11121 (goto-char start-pos))
11122 (cond
11123 ((looking-at "\\*[^/]")
11124 (setq star t
11125 col (current-column)))
11126 ((looking-at "/\\*")
11127 (setq star t
11128 first-line t
11129 col (1+ (current-column))))
11130 ((looking-at "//")
11131 (setq single t
11132 col (current-column)))))
11133 ;; Heuristic for whether we need to close the comment:
11134 ;; if we've got a parse error here, assume it's an unterminated
11135 ;; comment.
11136 (setq needs-close
11137 (or
11138 (eq (get-text-property (1- (point)) 'point-entered)
11139 'js2-echo-error)
11140 ;; The heuristic above doesn't work well when we're
11141 ;; creating a comment and there's another one downstream,
11142 ;; as our parser thinks this one ends at the end of the
11143 ;; next one. (You can have a /* inside a js block comment.)
11144 ;; So just close it if the next non-ws char isn't a *.
11145 (and first-line
11146 (eolp)
11147 (save-excursion
11148 (skip-chars-forward " \t\r\n")
11149 (not (eq (char-after) ?*))))))
11150 (delete-horizontal-space)
11151 (insert "\n")
11152 (cond
11153 (star
11154 (indent-to col)
11155 (insert "* ")
11156 (if (and first-line needs-close)
11157 (save-excursion
11158 (insert "\n")
11159 (indent-to col)
11160 (insert "*/"))))
11161 ((and single
11162 (save-excursion
11163 (and (zerop (forward-line 1))
11164 (looking-at "\\s-*//"))))
11165 (indent-to col)
11166 (insert "// ")))
11167 ;; Don't need to extend the comment after all.
11168 (js2-indent-line)))
11169
11170 (defun js2-beginning-of-line ()
11171 "Toggle point between bol and first non-whitespace char in line.
11172 Also moves past comment delimiters when inside comments."
11173 (interactive)
11174 (let (node)
11175 (cond
11176 ((bolp)
11177 (back-to-indentation))
11178 ((looking-at "//")
11179 (skip-chars-forward "/ \t"))
11180 ((and (eq (char-after) ?*)
11181 (setq node (js2-comment-at-point))
11182 (memq (js2-comment-node-format node) '(jsdoc block))
11183 (save-excursion
11184 (skip-chars-backward " \t")
11185 (bolp)))
11186 (skip-chars-forward "\* \t"))
11187 (t
11188 (goto-char (point-at-bol))))))
11189
11190 (defun js2-end-of-line ()
11191 "Toggle point between eol and last non-whitespace char in line."
11192 (interactive)
11193 (if (eolp)
11194 (skip-chars-backward " \t")
11195 (goto-char (point-at-eol))))
11196
11197 (defun js2-mode-wait-for-parse (callback)
11198 "Invoke CALLBACK when parsing is finished.
11199 If parsing is already finished, calls CALLBACK immediately."
11200 (if (not js2-mode-buffer-dirty-p)
11201 (funcall callback)
11202 (push callback js2-mode-pending-parse-callbacks)
11203 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11204
11205 (defun js2-mode-parse-finished ()
11206 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11207 ;; We can't let errors propagate up, since it prevents the
11208 ;; `js2-parse' method from completing normally and returning
11209 ;; the ast, which makes things mysteriously not work right.
11210 (unwind-protect
11211 (dolist (cb js2-mode-pending-parse-callbacks)
11212 (condition-case err
11213 (funcall cb)
11214 (error (message "%s" err))))
11215 (setq js2-mode-pending-parse-callbacks nil)))
11216
11217 (defun js2-mode-flag-region (from to flag)
11218 "Hide or show text from FROM to TO, according to FLAG.
11219 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11220 Returns the created overlay if FLAG is non-nil."
11221 (remove-overlays from to 'invisible 'js2-outline)
11222 (when flag
11223 (let ((o (make-overlay from to)))
11224 (overlay-put o 'invisible 'js2-outline)
11225 (overlay-put o 'isearch-open-invisible
11226 'js2-isearch-open-invisible)
11227 o)))
11228
11229 ;; Function to be set as an outline-isearch-open-invisible' property
11230 ;; to the overlay that makes the outline invisible (see
11231 ;; `js2-mode-flag-region').
11232 (defun js2-isearch-open-invisible (_overlay)
11233 ;; We rely on the fact that isearch places point on the matched text.
11234 (js2-mode-show-element))
11235
11236 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11237 "Return cons cell of bounds of folding overlay at POS.
11238 Returns nil if not found."
11239 (let ((overlays (overlays-at (or pos (point))))
11240 o)
11241 (while (and overlays
11242 (not o))
11243 (if (overlay-get (car overlays) 'invisible)
11244 (setq o (car overlays))
11245 (setq overlays (cdr overlays))))
11246 (if o
11247 (cons (overlay-start o) (overlay-end o)))))
11248
11249 (defun js2-mode-function-at-point (&optional pos)
11250 "Return the innermost function node enclosing current point.
11251 Returns nil if point is not in a function."
11252 (let ((node (js2-node-at-point pos)))
11253 (while (and node (not (js2-function-node-p node)))
11254 (setq node (js2-node-parent node)))
11255 (if (js2-function-node-p node)
11256 node)))
11257
11258 (defun js2-mode-toggle-element ()
11259 "Hide or show the foldable element at the point."
11260 (interactive)
11261 (let (comment fn pos)
11262 (save-excursion
11263 (cond
11264 ;; /* ... */ comment?
11265 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11266 (if (js2-mode-invisible-overlay-bounds
11267 (setq pos (+ 3 (js2-node-abs-pos comment))))
11268 (progn
11269 (goto-char pos)
11270 (js2-mode-show-element))
11271 (js2-mode-hide-element)))
11272 ;; //-comment?
11273 ((save-excursion
11274 (back-to-indentation)
11275 (looking-at js2-mode-//-comment-re))
11276 (js2-mode-toggle-//-comment))
11277 ;; function?
11278 ((setq fn (js2-mode-function-at-point))
11279 (setq pos (and (js2-function-node-body fn)
11280 (js2-node-abs-pos (js2-function-node-body fn))))
11281 (goto-char (1+ pos))
11282 (if (js2-mode-invisible-overlay-bounds)
11283 (js2-mode-show-element)
11284 (js2-mode-hide-element)))
11285 (t
11286 (message "Nothing at point to hide or show"))))))
11287
11288 (defun js2-mode-hide-element ()
11289 "Fold/hide contents of a block, showing ellipses.
11290 Show the hidden text with \\[js2-mode-show-element]."
11291 (interactive)
11292 (if js2-mode-buffer-dirty-p
11293 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11294 (let (node body beg end)
11295 (cond
11296 ((js2-mode-invisible-overlay-bounds)
11297 (message "already hidden"))
11298 (t
11299 (setq node (js2-node-at-point))
11300 (cond
11301 ((js2-block-comment-p node)
11302 (js2-mode-hide-comment node))
11303 (t
11304 (while (and node (not (js2-function-node-p node)))
11305 (setq node (js2-node-parent node)))
11306 (if (and node
11307 (setq body (js2-function-node-body node)))
11308 (progn
11309 (setq beg (js2-node-abs-pos body)
11310 end (+ beg (js2-node-len body)))
11311 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11312 (message "No collapsable element found at point"))))))))
11313
11314 (defun js2-mode-show-element ()
11315 "Show the hidden element at current point."
11316 (interactive)
11317 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11318 (if bounds
11319 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11320 (message "Nothing to un-hide"))))
11321
11322 (defun js2-mode-show-all ()
11323 "Show all of the text in the buffer."
11324 (interactive)
11325 (js2-mode-flag-region (point-min) (point-max) nil))
11326
11327 (defun js2-mode-toggle-hide-functions ()
11328 (interactive)
11329 (if js2-mode-functions-hidden
11330 (js2-mode-show-functions)
11331 (js2-mode-hide-functions)))
11332
11333 (defun js2-mode-hide-functions ()
11334 "Hides all non-nested function bodies in the buffer.
11335 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11336 to open an individual entry."
11337 (interactive)
11338 (if js2-mode-buffer-dirty-p
11339 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11340 (if (null js2-mode-ast)
11341 (message "Oops - parsing failed")
11342 (setq js2-mode-functions-hidden t)
11343 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11344
11345 (defun js2-mode-function-hider (n endp)
11346 (when (not endp)
11347 (let ((tt (js2-node-type n))
11348 body beg end)
11349 (cond
11350 ((and (= tt js2-FUNCTION)
11351 (setq body (js2-function-node-body n)))
11352 (setq beg (js2-node-abs-pos body)
11353 end (+ beg (js2-node-len body)))
11354 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11355 nil) ; don't process children of function
11356 (t
11357 t))))) ; keep processing other AST nodes
11358
11359 (defun js2-mode-show-functions ()
11360 "Un-hide any folded function bodies in the buffer."
11361 (interactive)
11362 (setq js2-mode-functions-hidden nil)
11363 (save-excursion
11364 (goto-char (point-min))
11365 (while (/= (goto-char (next-overlay-change (point)))
11366 (point-max))
11367 (dolist (o (overlays-at (point)))
11368 (when (and (overlay-get o 'invisible)
11369 (not (overlay-get o 'comment)))
11370 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11371
11372 (defun js2-mode-hide-comment (n)
11373 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11374 3 ; /**
11375 2)) ; /*
11376 (beg (+ (js2-node-abs-pos n) head))
11377 (end (- (+ beg (js2-node-len n)) head 2))
11378 (o (js2-mode-flag-region beg end 'hide)))
11379 (overlay-put o 'comment t)))
11380
11381 (defun js2-mode-toggle-hide-comments ()
11382 "Folds all block comments in the buffer.
11383 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11384 to open an individual entry."
11385 (interactive)
11386 (if js2-mode-comments-hidden
11387 (js2-mode-show-comments)
11388 (js2-mode-hide-comments)))
11389
11390 (defun js2-mode-hide-comments ()
11391 (interactive)
11392 (if js2-mode-buffer-dirty-p
11393 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11394 (if (null js2-mode-ast)
11395 (message "Oops - parsing failed")
11396 (setq js2-mode-comments-hidden t)
11397 (dolist (n (js2-ast-root-comments js2-mode-ast))
11398 (when (js2-block-comment-p n)
11399 (js2-mode-hide-comment n)))
11400 (js2-mode-hide-//-comments)))
11401
11402 (defun js2-mode-extend-//-comment (direction)
11403 "Find start or end of a block of similar //-comment lines.
11404 DIRECTION is -1 to look back, 1 to look forward.
11405 INDENT is the indentation level to match.
11406 Returns the end-of-line position of the furthest adjacent
11407 //-comment line with the same indentation as the current line.
11408 If there is no such matching line, returns current end of line."
11409 (let ((pos (point-at-eol))
11410 (indent (current-indentation)))
11411 (save-excursion
11412 (while (and (zerop (forward-line direction))
11413 (looking-at js2-mode-//-comment-re)
11414 (eq indent (length (match-string 1))))
11415 (setq pos (point-at-eol)))
11416 pos)))
11417
11418 (defun js2-mode-hide-//-comments ()
11419 "Fold adjacent 1-line comments, showing only snippet of first one."
11420 (let (beg end)
11421 (save-excursion
11422 (goto-char (point-min))
11423 (while (re-search-forward js2-mode-//-comment-re nil t)
11424 (setq beg (point)
11425 end (js2-mode-extend-//-comment 1))
11426 (unless (eq beg end)
11427 (overlay-put (js2-mode-flag-region beg end 'hide)
11428 'comment t))
11429 (goto-char end)
11430 (forward-char 1)))))
11431
11432 (defun js2-mode-toggle-//-comment ()
11433 "Fold or un-fold any multi-line //-comment at point.
11434 Caller should have determined that this line starts with a //-comment."
11435 (let* ((beg (point-at-eol))
11436 (end beg))
11437 (save-excursion
11438 (goto-char end)
11439 (if (js2-mode-invisible-overlay-bounds)
11440 (js2-mode-show-element)
11441 ;; else hide the comment
11442 (setq beg (js2-mode-extend-//-comment -1)
11443 end (js2-mode-extend-//-comment 1))
11444 (unless (eq beg end)
11445 (overlay-put (js2-mode-flag-region beg end 'hide)
11446 'comment t))))))
11447
11448 (defun js2-mode-show-comments ()
11449 "Un-hide any hidden comments, leaving other hidden elements alone."
11450 (interactive)
11451 (setq js2-mode-comments-hidden nil)
11452 (save-excursion
11453 (goto-char (point-min))
11454 (while (/= (goto-char (next-overlay-change (point)))
11455 (point-max))
11456 (dolist (o (overlays-at (point)))
11457 (when (overlay-get o 'comment)
11458 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11459
11460 (defun js2-mode-display-warnings-and-errors ()
11461 "Turn on display of warnings and errors."
11462 (interactive)
11463 (setq js2-mode-show-parse-errors t
11464 js2-mode-show-strict-warnings t)
11465 (js2-reparse 'force))
11466
11467 (defun js2-mode-hide-warnings-and-errors ()
11468 "Turn off display of warnings and errors."
11469 (interactive)
11470 (setq js2-mode-show-parse-errors nil
11471 js2-mode-show-strict-warnings nil)
11472 (js2-reparse 'force))
11473
11474 (defun js2-mode-toggle-warnings-and-errors ()
11475 "Toggle the display of warnings and errors.
11476 Some users don't like having warnings/errors reported while they type."
11477 (interactive)
11478 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11479 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11480 (if (called-interactively-p 'any)
11481 (message "warnings and errors %s"
11482 (if js2-mode-show-parse-errors
11483 "enabled"
11484 "disabled")))
11485 (js2-reparse 'force))
11486
11487 (defun js2-mode-customize ()
11488 (interactive)
11489 (customize-group 'js2-mode))
11490
11491 (defun js2-mode-forward-sexp (&optional arg)
11492 "Move forward across one statement or balanced expression.
11493 With ARG, do it that many times. Negative arg -N means
11494 move backward across N balanced expressions."
11495 (interactive "p")
11496 (setq arg (or arg 1))
11497 (save-restriction
11498 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11499 (js2-reparse)
11500 (let (forward-sexp-function
11501 node (start (point)) pos lp rp child)
11502 (cond
11503 ;; backward-sexp
11504 ;; could probably make this better for some cases:
11505 ;; - if in statement block (e.g. function body), go to parent
11506 ;; - infix exprs like (foo in bar) - maybe go to beginning
11507 ;; of infix expr if in the right-side expression?
11508 ((and arg (minusp arg))
11509 (dotimes (_ (- arg))
11510 (js2-backward-sws)
11511 (forward-char -1) ; Enter the node we backed up to.
11512 (when (setq node (js2-node-at-point (point) t))
11513 (setq pos (js2-node-abs-pos node))
11514 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11515 (setq lp (car parens)
11516 rp (cdr parens)))
11517 (when (and lp (> start lp))
11518 (if (and rp (<= start rp))
11519 ;; Between parens, check if there's a child node we can jump.
11520 (when (setq child (js2-node-closest-child node (point) lp t))
11521 (setq pos (js2-node-abs-pos child)))
11522 ;; Before both parens.
11523 (setq pos lp)))
11524 (let ((state (parse-partial-sexp start pos)))
11525 (goto-char (if (not (zerop (car state)))
11526 ;; Stumble at the unbalanced paren if < 0, or
11527 ;; jump a bit further if > 0.
11528 (scan-sexps start -1)
11529 pos))))
11530 (unless pos (goto-char (point-min)))))
11531 (t
11532 ;; forward-sexp
11533 (dotimes (_ arg)
11534 (js2-forward-sws)
11535 (when (setq node (js2-node-at-point (point) t))
11536 (setq pos (js2-node-abs-pos node))
11537 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11538 (setq lp (car parens)
11539 rp (cdr parens)))
11540 (or
11541 (when (and rp (<= start rp))
11542 (if (> start lp)
11543 (when (setq child (js2-node-closest-child node (point) rp))
11544 (setq pos (js2-node-abs-end child)))
11545 (setq pos (1+ rp))))
11546 ;; No parens or child nodes, looks for the end of the curren node.
11547 (incf pos (js2-node-len
11548 (if (js2-expr-stmt-node-p (js2-node-parent node))
11549 ;; Stop after the semicolon.
11550 (js2-node-parent node)
11551 node))))
11552 (let ((state (save-excursion (parse-partial-sexp start pos))))
11553 (goto-char (if (not (zerop (car state)))
11554 (scan-sexps start 1)
11555 pos))))
11556 (unless pos (goto-char (point-max)))))))))
11557
11558 (defun js2-mode-forward-sexp-parens (node abs-pos)
11559 "Return a cons cell with positions of main parens in NODE."
11560 (cond
11561 ((or (js2-array-node-p node)
11562 (js2-object-node-p node)
11563 (js2-comp-node-p node)
11564 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11565 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11566 ((js2-paren-expr-node-p node)
11567 (let ((lp (js2-node-lp node))
11568 (rp (js2-node-rp node)))
11569 (cons (when lp (+ abs-pos lp))
11570 (when rp (+ abs-pos rp)))))))
11571
11572 (defun js2-node-closest-child (parent point limit &optional before)
11573 (let* ((parent-pos (js2-node-abs-pos parent))
11574 (rpoint (- point parent-pos))
11575 (rlimit (- limit parent-pos))
11576 (min (min rpoint rlimit))
11577 (max (max rpoint rlimit))
11578 found)
11579 (catch 'done
11580 (js2-visit-ast
11581 parent
11582 (lambda (node _end-p)
11583 (if (eq node parent)
11584 t
11585 (let ((pos (js2-node-pos node)) ;; Both relative values.
11586 (end (+ (js2-node-pos node) (js2-node-len node))))
11587 (when (and (>= pos min) (<= end max)
11588 (if before (< pos rpoint) (> end rpoint)))
11589 (setq found node))
11590 (when (> end rpoint)
11591 (throw 'done nil)))
11592 nil))))
11593 found))
11594
11595 (defun js2-errors ()
11596 "Return a list of errors found."
11597 (and js2-mode-ast
11598 (js2-ast-root-errors js2-mode-ast)))
11599
11600 (defun js2-warnings ()
11601 "Return a list of warnings found."
11602 (and js2-mode-ast
11603 (js2-ast-root-warnings js2-mode-ast)))
11604
11605 (defun js2-have-errors-p ()
11606 "Return non-nil if any parse errors or warnings were found."
11607 (or (js2-errors) (js2-warnings)))
11608
11609 (defun js2-errors-and-warnings ()
11610 "Return a copy of the concatenated errors and warnings lists.
11611 They are appended: first the errors, then the warnings.
11612 Entries are of the form (MSG BEG END)."
11613 (when js2-mode-ast
11614 (append (js2-ast-root-errors js2-mode-ast)
11615 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11616
11617 (defun js2-next-error (&optional arg reset)
11618 "Move to next parse error.
11619 Typically invoked via \\[next-error].
11620 ARG is the number of errors, forward or backward, to move.
11621 RESET means start over from the beginning."
11622 (interactive "p")
11623 (if (not (or (js2-errors) (js2-warnings)))
11624 (message "No errors")
11625 (when reset
11626 (goto-char (point-min)))
11627 (let* ((errs (js2-errors-and-warnings))
11628 (continue t)
11629 (start (point))
11630 (count (or arg 1))
11631 (backward (minusp count))
11632 (sorter (if backward '> '<))
11633 (stopper (if backward '< '>))
11634 (count (abs count))
11635 all-errs err)
11636 ;; Sort by start position.
11637 (setq errs (sort errs (lambda (e1 e2)
11638 (funcall sorter (second e1) (second e2))))
11639 all-errs errs)
11640 ;; Find nth error with pos > start.
11641 (while (and errs continue)
11642 (when (funcall stopper (cadar errs) start)
11643 (setq err (car errs))
11644 (if (zerop (decf count))
11645 (setq continue nil)))
11646 (setq errs (cdr errs)))
11647 ;; Clear for `js2-echo-error'.
11648 (message nil)
11649 (if err
11650 (goto-char (second err))
11651 ;; Wrap around to first error.
11652 (goto-char (second (car all-errs)))
11653 ;; If we were already on it, echo msg again.
11654 (if (= (point) start)
11655 (js2-echo-error (point) (point)))))))
11656
11657 (defun js2-down-mouse-3 ()
11658 "Make right-click move the point to the click location.
11659 This makes right-click context menu operations a bit more intuitive.
11660 The point will not move if the region is active, however, to avoid
11661 destroying the region selection."
11662 (interactive)
11663 (when (and js2-move-point-on-right-click
11664 (not mark-active))
11665 (let ((e last-input-event))
11666 (ignore-errors
11667 (goto-char (cadadr e))))))
11668
11669 (defun js2-mode-create-imenu-index ()
11670 "Return an alist for `imenu--index-alist'."
11671 ;; This is built up in `js2-parse-record-imenu' during parsing.
11672 (when js2-mode-ast
11673 ;; if we have an ast but no recorder, they're requesting a rescan
11674 (unless js2-imenu-recorder
11675 (js2-reparse 'force))
11676 (prog1
11677 (js2-build-imenu-index)
11678 (setq js2-imenu-recorder nil
11679 js2-imenu-function-map nil))))
11680
11681 (defun js2-mode-find-tag ()
11682 "Replacement for `find-tag-default'.
11683 `find-tag-default' returns a ridiculous answer inside comments."
11684 (let (beg end)
11685 (js2-with-underscore-as-word-syntax
11686 (save-excursion
11687 (if (and (not (looking-at "[[:alnum:]_$]"))
11688 (looking-back "[[:alnum:]_$]"))
11689 (setq beg (progn (forward-word -1) (point))
11690 end (progn (forward-word 1) (point)))
11691 (setq beg (progn (forward-word 1) (point))
11692 end (progn (forward-word -1) (point))))
11693 (replace-regexp-in-string
11694 "[\"']" ""
11695 (buffer-substring-no-properties beg end))))))
11696
11697 (defun js2-mode-forward-sibling ()
11698 "Move to the end of the sibling following point in parent.
11699 Returns non-nil if successful, or nil if there was no following sibling."
11700 (let* ((node (js2-node-at-point))
11701 (parent (js2-mode-find-enclosing-fn node))
11702 sib)
11703 (when (setq sib (js2-node-find-child-after (point) parent))
11704 (goto-char (+ (js2-node-abs-pos sib)
11705 (js2-node-len sib))))))
11706
11707 (defun js2-mode-backward-sibling ()
11708 "Move to the beginning of the sibling node preceding point in parent.
11709 Parent is defined as the enclosing script or function."
11710 (let* ((node (js2-node-at-point))
11711 (parent (js2-mode-find-enclosing-fn node))
11712 sib)
11713 (when (setq sib (js2-node-find-child-before (point) parent))
11714 (goto-char (js2-node-abs-pos sib)))))
11715
11716 (defun js2-beginning-of-defun (&optional arg)
11717 "Go to line on which current function starts, and return t on success.
11718 If we're not in a function or already at the beginning of one, go
11719 to beginning of previous script-level element.
11720 With ARG N, do that N times. If N is negative, move forward."
11721 (setq arg (or arg 1))
11722 (if (plusp arg)
11723 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11724 (when (cond
11725 ((js2-function-node-p parent)
11726 (goto-char (js2-node-abs-pos parent)))
11727 (t
11728 (js2-mode-backward-sibling)))
11729 (if (> arg 1)
11730 (js2-beginning-of-defun (1- arg))
11731 t)))
11732 (when (js2-end-of-defun)
11733 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11734
11735 (defun js2-end-of-defun ()
11736 "Go to the char after the last position of the current function
11737 or script-level element."
11738 (let* ((node (js2-node-at-point))
11739 (parent (or (and (js2-function-node-p node) node)
11740 (js2-node-parent-script-or-fn node)))
11741 script)
11742 (unless (js2-function-node-p parent)
11743 ;; Use current script-level node, or, if none, the next one.
11744 (setq script (or parent node)
11745 parent (js2-node-find-child-before (point) script))
11746 (when (or (null parent)
11747 (>= (point) (+ (js2-node-abs-pos parent)
11748 (js2-node-len parent))))
11749 (setq parent (js2-node-find-child-after (point) script))))
11750 (when parent
11751 (goto-char (+ (js2-node-abs-pos parent)
11752 (js2-node-len parent))))))
11753
11754 (defun js2-mark-defun (&optional allow-extend)
11755 "Put mark at end of this function, point at beginning.
11756 The function marked is the one that contains point.
11757
11758 Interactively, if this command is repeated,
11759 or (in Transient Mark mode) if the mark is active,
11760 it marks the next defun after the ones already marked."
11761 (interactive "p")
11762 (let (extended)
11763 (when (and allow-extend
11764 (or (and (eq last-command this-command) (mark t))
11765 (and transient-mark-mode mark-active)))
11766 (let ((sib (save-excursion
11767 (goto-char (mark))
11768 (if (js2-mode-forward-sibling)
11769 (point)))))
11770 (if sib
11771 (progn
11772 (set-mark sib)
11773 (setq extended t))
11774 ;; no more siblings - try extending to enclosing node
11775 (goto-char (mark t)))))
11776 (when (not extended)
11777 (let ((node (js2-node-at-point (point) t)) ; skip comments
11778 ast fn stmt parent beg end)
11779 (when (js2-ast-root-p node)
11780 (setq ast node
11781 node (or (js2-node-find-child-after (point) node)
11782 (js2-node-find-child-before (point) node))))
11783 ;; only mark whole buffer if we can't find any children
11784 (if (null node)
11785 (setq node ast))
11786 (if (js2-function-node-p node)
11787 (setq parent node)
11788 (setq fn (js2-mode-find-enclosing-fn node)
11789 stmt (if (or (null fn)
11790 (js2-ast-root-p fn))
11791 (js2-mode-find-first-stmt node))
11792 parent (or stmt fn)))
11793 (setq beg (js2-node-abs-pos parent)
11794 end (+ beg (js2-node-len parent)))
11795 (push-mark beg)
11796 (goto-char end)
11797 (exchange-point-and-mark)))))
11798
11799 (defun js2-narrow-to-defun ()
11800 "Narrow to the function enclosing point."
11801 (interactive)
11802 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11803 (fn (if (js2-script-node-p node)
11804 node
11805 (js2-mode-find-enclosing-fn node)))
11806 (beg (js2-node-abs-pos fn)))
11807 (unless (js2-ast-root-p fn)
11808 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11809
11810 (provide 'js2-mode)
11811
11812 ;;; js2-mode.el ends here