]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Do not declare fn expression's name in the enclosing scope
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2014 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20141118
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 (defvar js2-harmony-externs
207 (mapcar 'symbol-name
208 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
209 "ES6 externs. If `js2-include-browser-externs' is enabled and
210 `js2-language-version' is sufficiently high, these will be included.")
211
212 ;;; Variables
213
214 (defun js2-mark-safe-local (name pred)
215 "Make the variable NAME buffer-local and mark it as safe file-local
216 variable with predicate PRED."
217 (make-variable-buffer-local name)
218 (put name 'safe-local-variable pred))
219
220 (defcustom js2-highlight-level 2
221 "Amount of syntax highlighting to perform.
222 0 or a negative value means none.
223 1 adds basic syntax highlighting.
224 2 adds highlighting of some Ecma built-in properties.
225 3 adds highlighting of many Ecma built-in functions."
226 :group 'js2-mode
227 :type '(choice (const :tag "None" 0)
228 (const :tag "Basic" 1)
229 (const :tag "Include Properties" 2)
230 (const :tag "Include Functions" 3)))
231
232 (defvar js2-mode-dev-mode-p nil
233 "Non-nil if running in development mode. Normally nil.")
234
235 (defgroup js2-mode nil
236 "An improved JavaScript mode."
237 :group 'languages)
238
239 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
240 (numberp c-basic-offset))
241 c-basic-offset
242 4)
243 "Number of spaces to indent nested statements.
244 Similar to `c-basic-offset'."
245 :group 'js2-mode
246 :type 'integer)
247 (js2-mark-safe-local 'js2-basic-offset 'integerp)
248
249 (defcustom js2-bounce-indent-p nil
250 "Non-nil to have indent-line function choose among alternatives.
251 If nil, the indent-line function will indent to a predetermined column
252 based on heuristic guessing. If non-nil, then if the current line is
253 already indented to that predetermined column, indenting will choose
254 another likely column and indent to that spot. Repeated invocation of
255 the indent-line function will cycle among the computed alternatives.
256 See the function `js2-bounce-indent' for details. When it is non-nil,
257 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
258 :type 'boolean
259 :group 'js2-mode)
260
261 (defcustom js2-pretty-multiline-declarations t
262 "Non-nil to line up multiline declarations vertically:
263
264 var a = 10,
265 b = 20,
266 c = 30;
267
268 If the value is not `all', and the first assigned value in
269 declaration is a function/array/object literal spanning several
270 lines, it won't be indented additionally:
271
272 var o = { var bar = 2,
273 foo: 3 vs. o = {
274 }, foo: 3
275 bar = 2; };"
276 :group 'js2-mode
277 :type 'symbol)
278 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
279
280 (defcustom js2-indent-switch-body nil
281 "When nil, case labels are indented on the same level as the
282 containing switch statement. Otherwise, all lines inside
283 switch statement body are indented one additional level."
284 :type 'boolean
285 :group 'js2-mode)
286 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
287
288 (defcustom js2-idle-timer-delay 0.2
289 "Delay in secs before re-parsing after user makes changes.
290 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
291 :type 'number
292 :group 'js2-mode)
293 (make-variable-buffer-local 'js2-idle-timer-delay)
294
295 (defcustom js2-dynamic-idle-timer-adjust 0
296 "Positive to adjust `js2-idle-timer-delay' based on file size.
297 The idea is that for short files, parsing is faster so we can be
298 more responsive to user edits without interfering with editing.
299 The buffer length in characters (typically bytes) is divided by
300 this value and used to multiply `js2-idle-timer-delay' for the
301 buffer. For example, a 21k file and 10k adjust yields 21k/10k
302 == 2, so js2-idle-timer-delay is multiplied by 2.
303 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
304 `js2-idle-timer-delay' is not dependent on the file size."
305 :type 'number
306 :group 'js2-mode)
307
308 (defcustom js2-concat-multiline-strings t
309 "When non-nil, `js2-line-break' in mid-string will make it a
310 string concatenation. When `eol', the '+' will be inserted at the
311 end of the line, otherwise, at the beginning of the next line."
312 :type '(choice (const t) (const eol) (const nil))
313 :group 'js2-mode)
314
315 (defcustom js2-mode-show-parse-errors t
316 "True to highlight parse errors."
317 :type 'boolean
318 :group 'js2-mode)
319
320 (defcustom js2-mode-show-strict-warnings t
321 "Non-nil to emit Ecma strict-mode warnings.
322 Some of the warnings can be individually disabled by other flags,
323 even if this flag is non-nil."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-trailing-comma-warning t
328 "Non-nil to warn about trailing commas in array literals.
329 Ecma-262-5.1 allows them, but older versions of IE raise an error."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-var-redeclaration-warning t
366 "Non-nil to warn about redeclaring variables in a script or function."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-strict-var-hides-function-arg-warning t
371 "Non-nil to warn about a var decl hiding a function argument."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-skip-preprocessor-directives nil
376 "Non-nil to treat lines beginning with # as comments.
377 Useful for viewing Mozilla JavaScript source code."
378 :type 'boolean
379 :group 'js2-mode)
380
381 (defcustom js2-language-version 200
382 "Configures what JavaScript language version to recognize.
383 Currently versions 150, 160, 170, 180 and 200 are supported,
384 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
385 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
386 yield, and Array comprehensions, and 1.8 adds function closures."
387 :type 'integer
388 :group 'js2-mode)
389
390 (defcustom js2-instanceof-has-side-effects nil
391 "If non-nil, treats the instanceof operator as having side effects.
392 This is useful for xulrunner apps."
393 :type 'boolean
394 :group 'js2-mode)
395
396 (defcustom js2-move-point-on-right-click t
397 "Non-nil to move insertion point when you right-click.
398 This makes right-click context menu behavior a bit more intuitive,
399 since menu operations generally apply to the point. The exception
400 is if there is a region selection, in which case the point does -not-
401 move, so cut/copy/paste can work properly.
402
403 Note that IntelliJ moves the point, and Eclipse leaves it alone,
404 so this behavior is customizable."
405 :group 'js2-mode
406 :type 'boolean)
407
408 (defcustom js2-allow-rhino-new-expr-initializer t
409 "Non-nil to support a Rhino's experimental syntactic construct.
410
411 Rhino supports the ability to follow a `new' expression with an object
412 literal, which is used to set additional properties on the new object
413 after calling its constructor. Syntax:
414
415 new <expr> [ ( arglist ) ] [initializer]
416
417 Hence, this expression:
418
419 new Object {a: 1, b: 2}
420
421 results in an Object with properties a=1 and b=2. This syntax is
422 apparently not configurable in Rhino - it's currently always enabled,
423 as of Rhino version 1.7R2."
424 :type 'boolean
425 :group 'js2-mode)
426
427 (defcustom js2-allow-member-expr-as-function-name nil
428 "Non-nil to support experimental Rhino syntax for function names.
429
430 Rhino supports an experimental syntax configured via the Rhino Context
431 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
432
433 function <member-expr> ( [ arg-list ] ) { <body> }
434
435 Where member-expr is a non-parenthesized 'member expression', which
436 is anything at the grammar level of a new-expression or lower, meaning
437 any expression that does not involve infix or unary operators.
438
439 When <member-expr> is not a simple identifier, then it is syntactic
440 sugar for assigning the anonymous function to the <member-expr>. Hence,
441 this code:
442
443 function a.b().c[2] (x, y) { ... }
444
445 is rewritten as:
446
447 a.b().c[2] = function(x, y) {...}
448
449 which doesn't seem particularly useful, but Rhino permits it."
450 :type 'boolean
451 :group 'js2-mode)
452
453 ;; scanner variables
454
455 (defmacro js2-deflocal (name value &optional comment)
456 "Define a buffer-local variable NAME with VALUE and COMMENT."
457 `(progn
458 (defvar ,name ,value ,comment)
459 (make-variable-buffer-local ',name)))
460
461 (defvar js2-EOF_CHAR -1
462 "Represents end of stream. Distinct from js2-EOF token type.")
463
464 ;; I originally used symbols to represent tokens, but Rhino uses
465 ;; ints and then sets various flag bits in them, so ints it is.
466 ;; The upshot is that we need a `js2-' prefix in front of each name.
467 (defvar js2-ERROR -1)
468 (defvar js2-EOF 0)
469 (defvar js2-EOL 1)
470 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
471 (defvar js2-LEAVEWITH 3)
472 (defvar js2-RETURN 4)
473 (defvar js2-GOTO 5)
474 (defvar js2-IFEQ 6)
475 (defvar js2-IFNE 7)
476 (defvar js2-SETNAME 8)
477 (defvar js2-BITOR 9)
478 (defvar js2-BITXOR 10)
479 (defvar js2-BITAND 11)
480 (defvar js2-EQ 12)
481 (defvar js2-NE 13)
482 (defvar js2-LT 14)
483 (defvar js2-LE 15)
484 (defvar js2-GT 16)
485 (defvar js2-GE 17)
486 (defvar js2-LSH 18)
487 (defvar js2-RSH 19)
488 (defvar js2-URSH 20)
489 (defvar js2-ADD 21) ; infix plus
490 (defvar js2-SUB 22) ; infix minus
491 (defvar js2-MUL 23)
492 (defvar js2-DIV 24)
493 (defvar js2-MOD 25)
494 (defvar js2-NOT 26)
495 (defvar js2-BITNOT 27)
496 (defvar js2-POS 28) ; unary plus
497 (defvar js2-NEG 29) ; unary minus
498 (defvar js2-NEW 30)
499 (defvar js2-DELPROP 31)
500 (defvar js2-TYPEOF 32)
501 (defvar js2-GETPROP 33)
502 (defvar js2-GETPROPNOWARN 34)
503 (defvar js2-SETPROP 35)
504 (defvar js2-GETELEM 36)
505 (defvar js2-SETELEM 37)
506 (defvar js2-CALL 38)
507 (defvar js2-NAME 39) ; an identifier
508 (defvar js2-NUMBER 40)
509 (defvar js2-STRING 41)
510 (defvar js2-NULL 42)
511 (defvar js2-THIS 43)
512 (defvar js2-FALSE 44)
513 (defvar js2-TRUE 45)
514 (defvar js2-SHEQ 46) ; shallow equality (===)
515 (defvar js2-SHNE 47) ; shallow inequality (!==)
516 (defvar js2-REGEXP 48)
517 (defvar js2-BINDNAME 49)
518 (defvar js2-THROW 50)
519 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
520 (defvar js2-IN 52)
521 (defvar js2-INSTANCEOF 53)
522 (defvar js2-LOCAL_LOAD 54)
523 (defvar js2-GETVAR 55)
524 (defvar js2-SETVAR 56)
525 (defvar js2-CATCH_SCOPE 57)
526 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
527 (defvar js2-ENUM_INIT_VALUES 59)
528 (defvar js2-ENUM_INIT_ARRAY 60)
529 (defvar js2-ENUM_NEXT 61)
530 (defvar js2-ENUM_ID 62)
531 (defvar js2-THISFN 63)
532 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
533 (defvar js2-ARRAYLIT 65) ; array literal
534 (defvar js2-OBJECTLIT 66) ; object literal
535 (defvar js2-GET_REF 67) ; *reference
536 (defvar js2-SET_REF 68) ; *reference = something
537 (defvar js2-DEL_REF 69) ; delete reference
538 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
539 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
540 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
541
542 ;; XML support
543 (defvar js2-DEFAULTNAMESPACE 73)
544 (defvar js2-ESCXMLATTR 74)
545 (defvar js2-ESCXMLTEXT 75)
546 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
547 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
548 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
549 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
550
551 (defvar js2-first-bytecode js2-ENTERWITH)
552 (defvar js2-last-bytecode js2-REF_NS_NAME)
553
554 (defvar js2-TRY 80)
555 (defvar js2-SEMI 81) ; semicolon
556 (defvar js2-LB 82) ; left and right brackets
557 (defvar js2-RB 83)
558 (defvar js2-LC 84) ; left and right curly-braces
559 (defvar js2-RC 85)
560 (defvar js2-LP 86) ; left and right parens
561 (defvar js2-RP 87)
562 (defvar js2-COMMA 88) ; comma operator
563
564 (defvar js2-ASSIGN 89) ; simple assignment (=)
565 (defvar js2-ASSIGN_BITOR 90) ; |=
566 (defvar js2-ASSIGN_BITXOR 91) ; ^=
567 (defvar js2-ASSIGN_BITAND 92) ; &=
568 (defvar js2-ASSIGN_LSH 93) ; <<=
569 (defvar js2-ASSIGN_RSH 94) ; >>=
570 (defvar js2-ASSIGN_URSH 95) ; >>>=
571 (defvar js2-ASSIGN_ADD 96) ; +=
572 (defvar js2-ASSIGN_SUB 97) ; -=
573 (defvar js2-ASSIGN_MUL 98) ; *=
574 (defvar js2-ASSIGN_DIV 99) ; /=
575 (defvar js2-ASSIGN_MOD 100) ; %=
576
577 (defvar js2-first-assign js2-ASSIGN)
578 (defvar js2-last-assign js2-ASSIGN_MOD)
579
580 (defvar js2-HOOK 101) ; conditional (?:)
581 (defvar js2-COLON 102)
582 (defvar js2-OR 103) ; logical or (||)
583 (defvar js2-AND 104) ; logical and (&&)
584 (defvar js2-INC 105) ; increment/decrement (++ --)
585 (defvar js2-DEC 106)
586 (defvar js2-DOT 107) ; member operator (.)
587 (defvar js2-FUNCTION 108) ; function keyword
588 (defvar js2-EXPORT 109) ; export keyword
589 (defvar js2-IMPORT 110) ; import keyword
590 (defvar js2-IF 111) ; if keyword
591 (defvar js2-ELSE 112) ; else keyword
592 (defvar js2-SWITCH 113) ; switch keyword
593 (defvar js2-CASE 114) ; case keyword
594 (defvar js2-DEFAULT 115) ; default keyword
595 (defvar js2-WHILE 116) ; while keyword
596 (defvar js2-DO 117) ; do keyword
597 (defvar js2-FOR 118) ; for keyword
598 (defvar js2-BREAK 119) ; break keyword
599 (defvar js2-CONTINUE 120) ; continue keyword
600 (defvar js2-VAR 121) ; var keyword
601 (defvar js2-WITH 122) ; with keyword
602 (defvar js2-CATCH 123) ; catch keyword
603 (defvar js2-FINALLY 124) ; finally keyword
604 (defvar js2-VOID 125) ; void keyword
605 (defvar js2-RESERVED 126) ; reserved keywords
606
607 (defvar js2-EMPTY 127)
608
609 ;; Types used for the parse tree - never returned by scanner.
610
611 (defvar js2-BLOCK 128) ; statement block
612 (defvar js2-LABEL 129) ; label
613 (defvar js2-TARGET 130)
614 (defvar js2-LOOP 131)
615 (defvar js2-EXPR_VOID 132) ; expression statement in functions
616 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
617 (defvar js2-JSR 134)
618 (defvar js2-SCRIPT 135) ; top-level node for entire script
619 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
620 (defvar js2-USE_STACK 137)
621 (defvar js2-SETPROP_OP 138) ; x.y op= something
622 (defvar js2-SETELEM_OP 139) ; x[y] op= something
623 (defvar js2-LOCAL_BLOCK 140)
624 (defvar js2-SET_REF_OP 141) ; *reference op= something
625
626 ;; For XML support:
627 (defvar js2-DOTDOT 142) ; member operator (..)
628 (defvar js2-COLONCOLON 143) ; namespace::name
629 (defvar js2-XML 144) ; XML type
630 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
631 (defvar js2-XMLATTR 146) ; @
632 (defvar js2-XMLEND 147)
633
634 ;; Optimizer-only tokens
635 (defvar js2-TO_OBJECT 148)
636 (defvar js2-TO_DOUBLE 149)
637
638 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
639 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
640 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
641 (defvar js2-CONST 153)
642 (defvar js2-SETCONST 154)
643 (defvar js2-SETCONSTVAR 155)
644 (defvar js2-ARRAYCOMP 156)
645 (defvar js2-LETEXPR 157)
646 (defvar js2-WITHEXPR 158)
647 (defvar js2-DEBUGGER 159)
648
649 (defvar js2-COMMENT 160)
650 (defvar js2-TRIPLEDOT 161) ; for rest parameter
651 (defvar js2-ARROW 162) ; function arrow (=>)
652 (defvar js2-CLASS 163)
653 (defvar js2-EXTENDS 164)
654 (defvar js2-STATIC 165)
655 (defvar js2-SUPER 166)
656 (defvar js2-TEMPLATE_HEAD 167) ; part of template literal before substitution
657 (defvar js2-NO_SUBS_TEMPLATE 168) ; template literal without substitutions
658 (defvar js2-TAGGED_TEMPLATE 169) ; tagged template literal
659
660 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
661
662 (defconst js2-debug-print-trees nil)
663
664 ;; Rhino accepts any string or stream as input. Emacs character
665 ;; processing works best in buffers, so we'll assume the input is a
666 ;; buffer. JavaScript strings can be copied into temp buffers before
667 ;; scanning them.
668
669 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
670 ;; They're the Emacs equivalent of instance variables, more or less.
671
672 (js2-deflocal js2-ts-dirty-line nil
673 "Token stream buffer-local variable.
674 Indicates stuff other than whitespace since start of line.")
675
676 (js2-deflocal js2-ts-hit-eof nil
677 "Token stream buffer-local variable.")
678
679 ;; FIXME: Unused.
680 (js2-deflocal js2-ts-line-start 0
681 "Token stream buffer-local variable.")
682
683 (js2-deflocal js2-ts-lineno 1
684 "Token stream buffer-local variable.")
685
686 ;; FIXME: Unused.
687 (js2-deflocal js2-ts-line-end-char -1
688 "Token stream buffer-local variable.")
689
690 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
691 "Token stream buffer-local variable.
692 Current scan position.")
693
694 ;; FIXME: Unused.
695 (js2-deflocal js2-ts-is-xml-attribute nil
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-xml-is-tag-content nil
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-xml-open-tags-count 0
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-string-buffer nil
705 "Token stream buffer-local variable.
706 List of chars built up while scanning various tokens.")
707
708 (defstruct (js2-token
709 (:constructor nil)
710 (:constructor make-js2-token (beg)))
711 "Value returned from the token stream."
712 (type js2-EOF)
713 (beg 1)
714 (end -1)
715 (string "")
716 number
717 regexp-flags
718 comment-type
719 follows-eol-p)
720
721 (defstruct (js2-ts-state
722 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
723 (cursor js2-ts-cursor)
724 (tokens (copy-sequence js2-ti-tokens))
725 (tokens-cursor js2-ti-tokens-cursor)
726 (lookahead js2-ti-lookahead))))
727 lineno
728 cursor
729 tokens
730 tokens-cursor
731 lookahead)
732
733 ;;; Parser variables
734
735 (js2-deflocal js2-parsed-errors nil
736 "List of errors produced during scanning/parsing.")
737
738 (js2-deflocal js2-parsed-warnings nil
739 "List of warnings produced during scanning/parsing.")
740
741 (js2-deflocal js2-recover-from-parse-errors t
742 "Non-nil to continue parsing after a syntax error.
743
744 In recovery mode, the AST will be built in full, and any error
745 nodes will be flagged with appropriate error information. If
746 this flag is nil, a syntax error will result in an error being
747 signaled.
748
749 The variable is automatically buffer-local, because different
750 modes that use the parser will need different settings.")
751
752 (js2-deflocal js2-parse-hook nil
753 "List of callbacks for receiving parsing progress.")
754
755 (defvar js2-parse-finished-hook nil
756 "List of callbacks to notify when parsing finishes.
757 Not called if parsing was interrupted.")
758
759 (js2-deflocal js2-is-eval-code nil
760 "True if we're evaluating code in a string.
761 If non-nil, the tokenizer will record the token text, and the AST nodes
762 will record their source text. Off by default for IDE modes, since the
763 text is available in the buffer.")
764
765 (defvar js2-parse-ide-mode t
766 "Non-nil if the parser is being used for `js2-mode'.
767 If non-nil, the parser will set text properties for fontification
768 and the syntax table. The value should be nil when using the
769 parser as a frontend to an interpreter or byte compiler.")
770
771 ;;; Parser instance variables (buffer-local vars for js2-parse)
772
773 (defconst js2-ti-after-eol (lsh 1 16)
774 "Flag: first token of the source line.")
775
776 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
777
778 (js2-deflocal js2-compiler-generate-debug-info t)
779 (js2-deflocal js2-compiler-use-dynamic-scope nil)
780 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
781 (js2-deflocal js2-compiler-xml-available t)
782 (js2-deflocal js2-compiler-optimization-level 0)
783 (js2-deflocal js2-compiler-generating-source t)
784 (js2-deflocal js2-compiler-strict-mode nil)
785 (js2-deflocal js2-compiler-report-warning-as-error nil)
786 (js2-deflocal js2-compiler-generate-observer-count nil)
787 (js2-deflocal js2-compiler-activation-names nil)
788
789 ;; SKIP: sourceURI
790
791 ;; There's a compileFunction method in Context.java - may need it.
792 (js2-deflocal js2-called-by-compile-function nil
793 "True if `js2-parse' was called by `js2-compile-function'.
794 Will only be used when we finish implementing the interpreter.")
795
796 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
797
798 ;; SKIP: node factory - we're going to just call functions directly,
799 ;; and eventually go to a unified AST format.
800
801 (js2-deflocal js2-nesting-of-function 0)
802
803 (js2-deflocal js2-recorded-identifiers nil
804 "Tracks identifiers found during parsing.")
805
806 (js2-deflocal js2-is-in-destructuring nil
807 "True while parsing destructuring expression.")
808
809 (defcustom js2-global-externs nil
810 "A list of any extern names you'd like to consider always declared.
811 This list is global and is used by all `js2-mode' files.
812 You can create buffer-local externs list using `js2-additional-externs'.
813
814 There is also a buffer-local variable `js2-default-externs',
815 which is initialized by default to include the Ecma-262 externs
816 and the standard browser externs. The three lists are all
817 checked during highlighting."
818 :type 'list
819 :group 'js2-mode)
820
821 (js2-deflocal js2-default-externs nil
822 "Default external declarations.
823
824 These are currently only used for highlighting undeclared variables,
825 which only worries about top-level (unqualified) references.
826 As js2-mode's processing improves, we will flesh out this list.
827
828 The initial value is set to `js2-ecma-262-externs', unless some
829 of the `js2-include-?-externs' variables are set to t, in which
830 case the browser, Rhino and/or Node.js externs are also included.
831
832 See `js2-additional-externs' for more information.")
833
834 (defcustom js2-include-browser-externs t
835 "Non-nil to include browser externs in the master externs list.
836 If you work on JavaScript files that are not intended for browsers,
837 such as Mozilla Rhino server-side JavaScript, set this to nil.
838 See `js2-additional-externs' for more information about externs."
839 :type 'boolean
840 :group 'js2-mode)
841
842 (defcustom js2-include-rhino-externs nil
843 "Non-nil to include Mozilla Rhino externs in the master externs list.
844 See `js2-additional-externs' for more information about externs."
845 :type 'boolean
846 :group 'js2-mode)
847
848 (defcustom js2-include-node-externs nil
849 "Non-nil to include Node.js externs in the master externs list.
850 See `js2-additional-externs' for more information about externs."
851 :type 'boolean
852 :group 'js2-mode)
853
854 (js2-deflocal js2-additional-externs nil
855 "A buffer-local list of additional external declarations.
856 It is used to decide whether variables are considered undeclared
857 for purposes of highlighting.
858
859 Each entry is a Lisp string. The string should be the fully qualified
860 name of an external entity. All externs should be added to this list,
861 so that as js2-mode's processing improves it can take advantage of them.
862
863 You may want to declare your externs in three ways.
864 First, you can add externs that are valid for all your JavaScript files.
865 You should probably do this by adding them to `js2-global-externs', which
866 is a global list used for all js2-mode files.
867
868 Next, you can add a function to `js2-init-hook' that adds additional
869 externs appropriate for the specific file, perhaps based on its path.
870 These should go in `js2-additional-externs', which is buffer-local.
871
872 Third, you can use JSLint's global declaration, as long as
873 `js2-include-jslint-globals' is non-nil, which see.
874
875 Finally, you can add a function to `js2-post-parse-callbacks',
876 which is called after parsing completes, and `js2-mode-ast' is bound to
877 the root of the parse tree. At this stage you can set up an AST
878 node visitor using `js2-visit-ast' and examine the parse tree
879 for specific import patterns that may imply the existence of
880 other externs, possibly tied to your build system. These should also
881 be added to `js2-additional-externs'.
882
883 Your post-parse callback may of course also use the simpler and
884 faster (but perhaps less robust) approach of simply scanning the
885 buffer text for your imports, using regular expressions.")
886
887 ;; SKIP: decompiler
888 ;; SKIP: encoded-source
889
890 ;;; The following variables are per-function and should be saved/restored
891 ;;; during function parsing...
892
893 (js2-deflocal js2-current-script-or-fn nil)
894 (js2-deflocal js2-current-scope nil)
895 (js2-deflocal js2-nesting-of-with 0)
896 (js2-deflocal js2-label-set nil
897 "An alist mapping label names to nodes.")
898
899 (js2-deflocal js2-loop-set nil)
900 (js2-deflocal js2-loop-and-switch-set nil)
901 (js2-deflocal js2-has-return-value nil)
902 (js2-deflocal js2-end-flags 0)
903
904 ;;; ...end of per function variables
905
906 ;; These flags enumerate the possible ways a statement/function can
907 ;; terminate. These flags are used by endCheck() and by the Parser to
908 ;; detect inconsistent return usage.
909 ;;
910 ;; END_UNREACHED is reserved for code paths that are assumed to always be
911 ;; able to execute (example: throw, continue)
912 ;;
913 ;; END_DROPS_OFF indicates if the statement can transfer control to the
914 ;; next one. Statement such as return dont. A compound statement may have
915 ;; some branch that drops off control to the next statement.
916 ;;
917 ;; END_RETURNS indicates that the statement can return (without arguments)
918 ;; END_RETURNS_VALUE indicates that the statement can return a value.
919 ;;
920 ;; A compound statement such as
921 ;; if (condition) {
922 ;; return value;
923 ;; }
924 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
925
926 (defconst js2-end-unreached #x0)
927 (defconst js2-end-drops-off #x1)
928 (defconst js2-end-returns #x2)
929 (defconst js2-end-returns-value #x4)
930
931 ;; Rhino awkwardly passes a statementLabel parameter to the
932 ;; statementHelper() function, the main statement parser, which
933 ;; is then used by quite a few of the sub-parsers. We just make
934 ;; it a buffer-local variable and make sure it's cleaned up properly.
935 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
936
937 ;; Similarly, Rhino passes an inForInit boolean through about half
938 ;; the expression parsers. We use a dynamically-scoped variable,
939 ;; which makes it easier to funcall the parsers individually without
940 ;; worrying about whether they take the parameter or not.
941 (js2-deflocal js2-in-for-init nil)
942 (js2-deflocal js2-temp-name-counter 0)
943 (js2-deflocal js2-parse-stmt-count 0)
944
945 (defsubst js2-get-next-temp-name ()
946 (format "$%d" (incf js2-temp-name-counter)))
947
948 (defvar js2-parse-interruptable-p t
949 "Set this to nil to force parse to continue until finished.
950 This will mostly be useful for interpreters.")
951
952 (defvar js2-statements-per-pause 50
953 "Pause after this many statements to check for user input.
954 If user input is pending, stop the parse and discard the tree.
955 This makes for a smoother user experience for large files.
956 You may have to wait a second or two before the highlighting
957 and error-reporting appear, but you can always type ahead if
958 you wish. This appears to be more or less how Eclipse, IntelliJ
959 and other editors work.")
960
961 (js2-deflocal js2-record-comments t
962 "Instructs the scanner to record comments in `js2-scanned-comments'.")
963
964 (js2-deflocal js2-scanned-comments nil
965 "List of all comments from the current parse.")
966
967 (defcustom js2-mode-indent-inhibit-undo nil
968 "Non-nil to disable collection of Undo information when indenting lines.
969 Some users have requested this behavior. It's nil by default because
970 other Emacs modes don't work this way."
971 :type 'boolean
972 :group 'js2-mode)
973
974 (defcustom js2-mode-indent-ignore-first-tab nil
975 "If non-nil, ignore first TAB keypress if we look indented properly.
976 It's fairly common for users to navigate to an already-indented line
977 and press TAB for reassurance that it's been indented. For this class
978 of users, we want the first TAB press on a line to be ignored if the
979 line is already indented to one of the precomputed alternatives.
980
981 This behavior is only partly implemented. If you TAB-indent a line,
982 navigate to another line, and then navigate back, it fails to clear
983 the last-indented variable, so it thinks you've already hit TAB once,
984 and performs the indent. A full solution would involve getting on the
985 point-motion hooks for the entire buffer. If we come across another
986 use cases that requires watching point motion, I'll consider doing it.
987
988 If you set this variable to nil, then the TAB key will always change
989 the indentation of the current line, if more than one alternative
990 indentation spot exists."
991 :type 'boolean
992 :group 'js2-mode)
993
994 (defvar js2-indent-hook nil
995 "A hook for user-defined indentation rules.
996
997 Functions on this hook should expect two arguments: (LIST INDEX)
998 The LIST argument is the list of computed indentation points for
999 the current line. INDEX is the list index of the indentation point
1000 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1001 indent function is not going to change the current line indentation.
1002
1003 If a hook function on this list returns a non-nil value, then
1004 `js2-bounce-indent' assumes the hook function has performed its own
1005 indentation, and will do nothing. If all hook functions on the list
1006 return nil, then `js2-bounce-indent' will use its computed indentation
1007 and reindent the line.
1008
1009 When hook functions on this hook list are called, the variable
1010 `js2-mode-ast' may or may not be set, depending on whether the
1011 parse tree is available. If the variable is nil, you can pass a
1012 callback to `js2-mode-wait-for-parse', and your callback will be
1013 called after the new parse tree is built. This can take some time
1014 in large files.")
1015
1016 (defface js2-warning
1017 `((((class color) (background light))
1018 (:underline "orange"))
1019 (((class color) (background dark))
1020 (:underline "orange"))
1021 (t (:underline t)))
1022 "Face for JavaScript warnings."
1023 :group 'js2-mode)
1024
1025 (defface js2-error
1026 `((((class color) (background light))
1027 (:foreground "red"))
1028 (((class color) (background dark))
1029 (:foreground "red"))
1030 (t (:foreground "red")))
1031 "Face for JavaScript errors."
1032 :group 'js2-mode)
1033
1034 (defface js2-jsdoc-tag
1035 '((t :foreground "SlateGray"))
1036 "Face used to highlight @whatever tags in jsdoc comments."
1037 :group 'js2-mode)
1038
1039 (defface js2-jsdoc-type
1040 '((t :foreground "SteelBlue"))
1041 "Face used to highlight {FooBar} types in jsdoc comments."
1042 :group 'js2-mode)
1043
1044 (defface js2-jsdoc-value
1045 '((t :foreground "PeachPuff3"))
1046 "Face used to highlight tag values in jsdoc comments."
1047 :group 'js2-mode)
1048
1049 (defface js2-function-param
1050 '((t :foreground "SeaGreen"))
1051 "Face used to highlight function parameters in javascript."
1052 :group 'js2-mode)
1053
1054 (defface js2-function-call
1055 '((t :inherit default))
1056 "Face used to highlight function name in calls."
1057 :group 'js2-mode)
1058
1059 (defface js2-instance-member
1060 '((t :foreground "DarkOrchid"))
1061 "Face used to highlight instance variables in javascript.
1062 Not currently used."
1063 :group 'js2-mode)
1064
1065 (defface js2-private-member
1066 '((t :foreground "PeachPuff3"))
1067 "Face used to highlight calls to private methods in javascript.
1068 Not currently used."
1069 :group 'js2-mode)
1070
1071 (defface js2-private-function-call
1072 '((t :foreground "goldenrod"))
1073 "Face used to highlight calls to private functions in javascript.
1074 Not currently used."
1075 :group 'js2-mode)
1076
1077 (defface js2-jsdoc-html-tag-name
1078 '((((class color) (min-colors 88) (background light))
1079 (:foreground "rosybrown"))
1080 (((class color) (min-colors 8) (background dark))
1081 (:foreground "yellow"))
1082 (((class color) (min-colors 8) (background light))
1083 (:foreground "magenta")))
1084 "Face used to highlight jsdoc html tag names"
1085 :group 'js2-mode)
1086
1087 (defface js2-jsdoc-html-tag-delimiter
1088 '((((class color) (min-colors 88) (background light))
1089 (:foreground "dark khaki"))
1090 (((class color) (min-colors 8) (background dark))
1091 (:foreground "green"))
1092 (((class color) (min-colors 8) (background light))
1093 (:foreground "green")))
1094 "Face used to highlight brackets in jsdoc html tags."
1095 :group 'js2-mode)
1096
1097 (defface js2-external-variable
1098 '((t :foreground "orange"))
1099 "Face used to highlight undeclared variable identifiers.")
1100
1101 (defcustom js2-init-hook nil
1102 "List of functions to be called after `js2-mode' or
1103 `js2-minor-mode' has initialized all variables, before parsing
1104 the buffer for the first time."
1105 :type 'hook
1106 :group 'js2-mode
1107 :version "20130608")
1108
1109 (defcustom js2-post-parse-callbacks nil
1110 "List of callback functions invoked after parsing finishes.
1111 Currently, the main use for this function is to add synthetic
1112 declarations to `js2-recorded-identifiers', which see."
1113 :type 'hook
1114 :group 'js2-mode)
1115
1116 (defcustom js2-build-imenu-callbacks nil
1117 "List of functions called during Imenu index generation.
1118 It's a good place to add additional entries to it, using
1119 `js2-record-imenu-entry'."
1120 :type 'hook
1121 :group 'js2-mode)
1122
1123 (defcustom js2-highlight-external-variables t
1124 "Non-nil to highlight undeclared variable identifiers.
1125 An undeclared variable is any variable not declared with var or let
1126 in the current scope or any lexically enclosing scope. If you use
1127 such a variable, then you are either expecting it to originate from
1128 another file, or you've got a potential bug."
1129 :type 'boolean
1130 :group 'js2-mode)
1131
1132 (defcustom js2-include-jslint-globals t
1133 "Non-nil to include the identifiers from JSLint global
1134 declaration (see http://www.jslint.com/lint.html#global) in the
1135 buffer-local externs list. See `js2-additional-externs' for more
1136 information."
1137 :type 'boolean
1138 :group 'js2-mode)
1139
1140 (defvar js2-mode-map
1141 (let ((map (make-sparse-keymap)))
1142 (define-key map [mouse-1] #'js2-mode-show-node)
1143 (define-key map (kbd "M-j") #'js2-line-break)
1144 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1145 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1146 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1147 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1148 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1149 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1150 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1151 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1152 (when js2-bounce-indent-p
1153 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1154
1155 (define-key map [menu-bar javascript]
1156 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1157
1158 (define-key map [menu-bar javascript customize-js2-mode]
1159 '(menu-item "Customize js2-mode" js2-mode-customize
1160 :help "Customize the behavior of this mode"))
1161
1162 (define-key map [menu-bar javascript js2-force-refresh]
1163 '(menu-item "Force buffer refresh" js2-mode-reset
1164 :help "Re-parse the buffer from scratch"))
1165
1166 (define-key map [menu-bar javascript separator-2]
1167 '("--"))
1168
1169 (define-key map [menu-bar javascript next-error]
1170 '(menu-item "Next warning or error" next-error
1171 :enabled (and js2-mode-ast
1172 (or (js2-ast-root-errors js2-mode-ast)
1173 (js2-ast-root-warnings js2-mode-ast)))
1174 :help "Move to next warning or error"))
1175
1176 (define-key map [menu-bar javascript display-errors]
1177 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1178 :visible (not js2-mode-show-parse-errors)
1179 :help "Turn on display of warnings and errors"))
1180
1181 (define-key map [menu-bar javascript hide-errors]
1182 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1183 :visible js2-mode-show-parse-errors
1184 :help "Turn off display of warnings and errors"))
1185
1186 (define-key map [menu-bar javascript separator-1]
1187 '("--"))
1188
1189 (define-key map [menu-bar javascript js2-toggle-function]
1190 '(menu-item "Show/collapse element" js2-mode-toggle-element
1191 :help "Hide or show function body or comment"))
1192
1193 (define-key map [menu-bar javascript show-comments]
1194 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1195 :visible js2-mode-comments-hidden
1196 :help "Expand all hidden block comments"))
1197
1198 (define-key map [menu-bar javascript hide-comments]
1199 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1200 :visible (not js2-mode-comments-hidden)
1201 :help "Show block comments as /*...*/"))
1202
1203 (define-key map [menu-bar javascript show-all-functions]
1204 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1205 :visible js2-mode-functions-hidden
1206 :help "Expand all hidden function bodies"))
1207
1208 (define-key map [menu-bar javascript hide-all-functions]
1209 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1210 :visible (not js2-mode-functions-hidden)
1211 :help "Show {...} for all top-level function bodies"))
1212
1213 map)
1214 "Keymap used in `js2-mode' buffers.")
1215
1216 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1217
1218 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1219 "Matches a //-comment line. Must be first non-whitespace on line.
1220 First match-group is the leading whitespace.")
1221
1222 (defvar js2-mode-hook nil)
1223
1224 (js2-deflocal js2-mode-ast nil "Private variable.")
1225 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1226 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1227 (js2-deflocal js2-mode-parsing nil "Private variable.")
1228 (js2-deflocal js2-mode-node-overlay nil)
1229
1230 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1231 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1232
1233 (js2-deflocal js2-mode-fontifications nil "Private variable")
1234 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1235 (js2-deflocal js2-imenu-recorder nil "Private variable")
1236 (js2-deflocal js2-imenu-function-map nil "Private variable")
1237
1238 (defvar js2-paragraph-start
1239 "\\(@[[:alpha:]]+\\>\\|$\\)")
1240
1241 ;; Note that we also set a 'c-in-sws text property in html comments,
1242 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1243 (defvar js2-syntactic-ws-start
1244 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1245
1246 (defvar js2-syntactic-ws-end
1247 "\\s \\|[\n\r/]\\|\\s!")
1248
1249 (defvar js2-syntactic-eol
1250 (concat "\\s *\\(/\\*[^*\n\r]*"
1251 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1252 "\\*+/\\s *\\)*"
1253 "\\(//\\|/\\*[^*\n\r]*"
1254 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1255 "\\|\\\\$\\|$\\)")
1256 "Copied from `java-mode'. Needed for some cc-engine functions.")
1257
1258 (defvar js2-comment-prefix-regexp
1259 "//+\\|\\**")
1260
1261 (defvar js2-comment-start-skip
1262 "\\(//+\\|/\\*+\\)\\s *")
1263
1264 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1265 "Non-nil to emit status messages during parsing.")
1266
1267 (defvar js2-mode-functions-hidden nil "Private variable.")
1268 (defvar js2-mode-comments-hidden nil "Private variable.")
1269
1270 (defvar js2-mode-syntax-table
1271 (let ((table (make-syntax-table)))
1272 (c-populate-syntax-table table)
1273 table)
1274 "Syntax table used in `js2-mode' buffers.")
1275
1276 (defvar js2-mode-abbrev-table nil
1277 "Abbrev table in use in `js2-mode' buffers.")
1278 (define-abbrev-table 'js2-mode-abbrev-table ())
1279
1280 (defvar js2-mode-pending-parse-callbacks nil
1281 "List of functions waiting to be notified that parse is finished.")
1282
1283 (defvar js2-mode-last-indented-line -1)
1284
1285 ;;; Localizable error and warning messages
1286
1287 ;; Messages are copied from Rhino's Messages.properties.
1288 ;; Many of the Java-specific messages have been elided.
1289 ;; Add any js2-specific ones at the end, so we can keep
1290 ;; this file synced with changes to Rhino's.
1291
1292 (defvar js2-message-table
1293 (make-hash-table :test 'equal :size 250)
1294 "Contains localized messages for `js2-mode'.")
1295
1296 ;; TODO(stevey): construct this table at compile-time.
1297 (defmacro js2-msg (key &rest strings)
1298 `(puthash ,key (concat ,@strings)
1299 js2-message-table))
1300
1301 (defun js2-get-msg (msg-key)
1302 "Look up a localized message.
1303 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1304 the correct number of ARGS must be provided."
1305 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1306 (args (if (listp msg-key) (cdr msg-key)))
1307 (msg (gethash key js2-message-table)))
1308 (if msg
1309 (apply #'format msg args)
1310 key))) ; default to showing the key
1311
1312 (js2-msg "msg.dup.parms"
1313 "Duplicate parameter name '%s'.")
1314
1315 (js2-msg "msg.too.big.jump"
1316 "Program too complex: jump offset too big.")
1317
1318 (js2-msg "msg.too.big.index"
1319 "Program too complex: internal index exceeds 64K limit.")
1320
1321 (js2-msg "msg.while.compiling.fn"
1322 "Encountered code generation error while compiling function '%s': %s")
1323
1324 (js2-msg "msg.while.compiling.script"
1325 "Encountered code generation error while compiling script: %s")
1326
1327 ;; Context
1328 (js2-msg "msg.ctor.not.found"
1329 "Constructor for '%s' not found.")
1330
1331 (js2-msg "msg.not.ctor"
1332 "'%s' is not a constructor.")
1333
1334 ;; FunctionObject
1335 (js2-msg "msg.varargs.ctor"
1336 "Method or constructor '%s' must be static "
1337 "with the signature (Context cx, Object[] args, "
1338 "Function ctorObj, boolean inNewExpr) "
1339 "to define a variable arguments constructor.")
1340
1341 (js2-msg "msg.varargs.fun"
1342 "Method '%s' must be static with the signature "
1343 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1344 "to define a variable arguments function.")
1345
1346 (js2-msg "msg.incompat.call"
1347 "Method '%s' called on incompatible object.")
1348
1349 (js2-msg "msg.bad.parms"
1350 "Unsupported parameter type '%s' in method '%s'.")
1351
1352 (js2-msg "msg.bad.method.return"
1353 "Unsupported return type '%s' in method '%s'.")
1354
1355 (js2-msg "msg.bad.ctor.return"
1356 "Construction of objects of type '%s' is not supported.")
1357
1358 (js2-msg "msg.no.overload"
1359 "Method '%s' occurs multiple times in class '%s'.")
1360
1361 (js2-msg "msg.method.not.found"
1362 "Method '%s' not found in '%s'.")
1363
1364 ;; IRFactory
1365
1366 (js2-msg "msg.bad.for.in.lhs"
1367 "Invalid left-hand side of for..in loop.")
1368
1369 (js2-msg "msg.mult.index"
1370 "Only one variable allowed in for..in loop.")
1371
1372 (js2-msg "msg.bad.for.in.destruct"
1373 "Left hand side of for..in loop must be an array of "
1374 "length 2 to accept key/value pair.")
1375
1376 (js2-msg "msg.cant.convert"
1377 "Can't convert to type '%s'.")
1378
1379 (js2-msg "msg.bad.assign.left"
1380 "Invalid assignment left-hand side.")
1381
1382 (js2-msg "msg.bad.decr"
1383 "Invalid decerement operand.")
1384
1385 (js2-msg "msg.bad.incr"
1386 "Invalid increment operand.")
1387
1388 (js2-msg "msg.bad.yield"
1389 "yield must be in a function.")
1390
1391 (js2-msg "msg.yield.parenthesized"
1392 "yield expression must be parenthesized.")
1393
1394 ;; NativeGlobal
1395 (js2-msg "msg.cant.call.indirect"
1396 "Function '%s' must be called directly, and not by way of a "
1397 "function of another name.")
1398
1399 (js2-msg "msg.eval.nonstring"
1400 "Calling eval() with anything other than a primitive "
1401 "string value will simply return the value. "
1402 "Is this what you intended?")
1403
1404 (js2-msg "msg.eval.nonstring.strict"
1405 "Calling eval() with anything other than a primitive "
1406 "string value is not allowed in strict mode.")
1407
1408 (js2-msg "msg.bad.destruct.op"
1409 "Invalid destructuring assignment operator")
1410
1411 ;; NativeCall
1412 (js2-msg "msg.only.from.new"
1413 "'%s' may only be invoked from a `new' expression.")
1414
1415 (js2-msg "msg.deprec.ctor"
1416 "The '%s' constructor is deprecated.")
1417
1418 ;; NativeFunction
1419 (js2-msg "msg.no.function.ref.found"
1420 "no source found to decompile function reference %s")
1421
1422 (js2-msg "msg.arg.isnt.array"
1423 "second argument to Function.prototype.apply must be an array")
1424
1425 ;; NativeGlobal
1426 (js2-msg "msg.bad.esc.mask"
1427 "invalid string escape mask")
1428
1429 ;; NativeRegExp
1430 (js2-msg "msg.bad.quant"
1431 "Invalid quantifier %s")
1432
1433 (js2-msg "msg.overlarge.backref"
1434 "Overly large back reference %s")
1435
1436 (js2-msg "msg.overlarge.min"
1437 "Overly large minimum %s")
1438
1439 (js2-msg "msg.overlarge.max"
1440 "Overly large maximum %s")
1441
1442 (js2-msg "msg.zero.quant"
1443 "Zero quantifier %s")
1444
1445 (js2-msg "msg.max.lt.min"
1446 "Maximum %s less than minimum")
1447
1448 (js2-msg "msg.unterm.quant"
1449 "Unterminated quantifier %s")
1450
1451 (js2-msg "msg.unterm.paren"
1452 "Unterminated parenthetical %s")
1453
1454 (js2-msg "msg.unterm.class"
1455 "Unterminated character class %s")
1456
1457 (js2-msg "msg.bad.range"
1458 "Invalid range in character class.")
1459
1460 (js2-msg "msg.trail.backslash"
1461 "Trailing \\ in regular expression.")
1462
1463 (js2-msg "msg.re.unmatched.right.paren"
1464 "unmatched ) in regular expression.")
1465
1466 (js2-msg "msg.no.regexp"
1467 "Regular expressions are not available.")
1468
1469 (js2-msg "msg.bad.backref"
1470 "back-reference exceeds number of capturing parentheses.")
1471
1472 (js2-msg "msg.bad.regexp.compile"
1473 "Only one argument may be specified if the first "
1474 "argument to RegExp.prototype.compile is a RegExp object.")
1475
1476 ;; Parser
1477 (js2-msg "msg.got.syntax.errors"
1478 "Compilation produced %s syntax errors.")
1479
1480 (js2-msg "msg.var.redecl"
1481 "TypeError: redeclaration of var %s.")
1482
1483 (js2-msg "msg.const.redecl"
1484 "TypeError: redeclaration of const %s.")
1485
1486 (js2-msg "msg.let.redecl"
1487 "TypeError: redeclaration of variable %s.")
1488
1489 (js2-msg "msg.parm.redecl"
1490 "TypeError: redeclaration of formal parameter %s.")
1491
1492 (js2-msg "msg.fn.redecl"
1493 "TypeError: redeclaration of function %s.")
1494
1495 (js2-msg "msg.let.decl.not.in.block"
1496 "SyntaxError: let declaration not directly within block")
1497
1498 ;; NodeTransformer
1499 (js2-msg "msg.dup.label"
1500 "duplicated label")
1501
1502 (js2-msg "msg.undef.label"
1503 "undefined label")
1504
1505 (js2-msg "msg.bad.break"
1506 "unlabelled break must be inside loop or switch")
1507
1508 (js2-msg "msg.continue.outside"
1509 "continue must be inside loop")
1510
1511 (js2-msg "msg.continue.nonloop"
1512 "continue can only use labels of iteration statements")
1513
1514 (js2-msg "msg.bad.throw.eol"
1515 "Line terminator is not allowed between the throw "
1516 "keyword and throw expression.")
1517
1518 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1519 "function statement requires a name")
1520
1521 (js2-msg "msg.no.paren.parms"
1522 "missing ( before function parameters.")
1523
1524 (js2-msg "msg.no.parm"
1525 "missing formal parameter")
1526
1527 (js2-msg "msg.no.paren.after.parms"
1528 "missing ) after formal parameters")
1529
1530 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1531 "parameter without default follows parameter with default")
1532
1533 (js2-msg "msg.param.after.rest" ; added by js2-mode
1534 "parameter after rest parameter")
1535
1536 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1537 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1538
1539 (js2-msg "msg.no.brace.body"
1540 "missing '{' before function body")
1541
1542 (js2-msg "msg.no.brace.after.body"
1543 "missing } after function body")
1544
1545 (js2-msg "msg.no.paren.cond"
1546 "missing ( before condition")
1547
1548 (js2-msg "msg.no.paren.after.cond"
1549 "missing ) after condition")
1550
1551 (js2-msg "msg.no.semi.stmt"
1552 "missing ; before statement")
1553
1554 (js2-msg "msg.missing.semi"
1555 "missing ; after statement")
1556
1557 (js2-msg "msg.no.name.after.dot"
1558 "missing name after . operator")
1559
1560 (js2-msg "msg.no.name.after.coloncolon"
1561 "missing name after :: operator")
1562
1563 (js2-msg "msg.no.name.after.dotdot"
1564 "missing name after .. operator")
1565
1566 (js2-msg "msg.no.name.after.xmlAttr"
1567 "missing name after .@")
1568
1569 (js2-msg "msg.no.bracket.index"
1570 "missing ] in index expression")
1571
1572 (js2-msg "msg.no.paren.switch"
1573 "missing ( before switch expression")
1574
1575 (js2-msg "msg.no.paren.after.switch"
1576 "missing ) after switch expression")
1577
1578 (js2-msg "msg.no.brace.switch"
1579 "missing '{' before switch body")
1580
1581 (js2-msg "msg.bad.switch"
1582 "invalid switch statement")
1583
1584 (js2-msg "msg.no.colon.case"
1585 "missing : after case expression")
1586
1587 (js2-msg "msg.double.switch.default"
1588 "double default label in the switch statement")
1589
1590 (js2-msg "msg.no.while.do"
1591 "missing while after do-loop body")
1592
1593 (js2-msg "msg.no.paren.for"
1594 "missing ( after for")
1595
1596 (js2-msg "msg.no.semi.for"
1597 "missing ; after for-loop initializer")
1598
1599 (js2-msg "msg.no.semi.for.cond"
1600 "missing ; after for-loop condition")
1601
1602 (js2-msg "msg.in.after.for.name"
1603 "missing in or of after for")
1604
1605 (js2-msg "msg.no.paren.for.ctrl"
1606 "missing ) after for-loop control")
1607
1608 (js2-msg "msg.no.paren.with"
1609 "missing ( before with-statement object")
1610
1611 (js2-msg "msg.no.paren.after.with"
1612 "missing ) after with-statement object")
1613
1614 (js2-msg "msg.no.paren.after.let"
1615 "missing ( after let")
1616
1617 (js2-msg "msg.no.paren.let"
1618 "missing ) after variable list")
1619
1620 (js2-msg "msg.no.curly.let"
1621 "missing } after let statement")
1622
1623 (js2-msg "msg.bad.return"
1624 "invalid return")
1625
1626 (js2-msg "msg.no.brace.block"
1627 "missing } in compound statement")
1628
1629 (js2-msg "msg.bad.label"
1630 "invalid label")
1631
1632 (js2-msg "msg.bad.var"
1633 "missing variable name")
1634
1635 (js2-msg "msg.bad.var.init"
1636 "invalid variable initialization")
1637
1638 (js2-msg "msg.no.colon.cond"
1639 "missing : in conditional expression")
1640
1641 (js2-msg "msg.no.paren.arg"
1642 "missing ) after argument list")
1643
1644 (js2-msg "msg.no.bracket.arg"
1645 "missing ] after element list")
1646
1647 (js2-msg "msg.bad.prop"
1648 "invalid property id")
1649
1650 (js2-msg "msg.no.colon.prop"
1651 "missing : after property id")
1652
1653 (js2-msg "msg.no.brace.prop"
1654 "missing } after property list")
1655
1656 (js2-msg "msg.no.paren"
1657 "missing ) in parenthetical")
1658
1659 (js2-msg "msg.reserved.id"
1660 "'%s' is a reserved identifier")
1661
1662 (js2-msg "msg.no.paren.catch"
1663 "missing ( before catch-block condition")
1664
1665 (js2-msg "msg.bad.catchcond"
1666 "invalid catch block condition")
1667
1668 (js2-msg "msg.catch.unreachable"
1669 "any catch clauses following an unqualified catch are unreachable")
1670
1671 (js2-msg "msg.no.brace.try"
1672 "missing '{' before try block")
1673
1674 (js2-msg "msg.no.brace.catchblock"
1675 "missing '{' before catch-block body")
1676
1677 (js2-msg "msg.try.no.catchfinally"
1678 "'try' without 'catch' or 'finally'")
1679
1680 (js2-msg "msg.no.return.value"
1681 "function %s does not always return a value")
1682
1683 (js2-msg "msg.anon.no.return.value"
1684 "anonymous function does not always return a value")
1685
1686 (js2-msg "msg.return.inconsistent"
1687 "return statement is inconsistent with previous usage")
1688
1689 (js2-msg "msg.generator.returns"
1690 "TypeError: legacy generator function '%s' returns a value")
1691
1692 (js2-msg "msg.anon.generator.returns"
1693 "TypeError: anonymous legacy generator function returns a value")
1694
1695 (js2-msg "msg.syntax"
1696 "syntax error")
1697
1698 (js2-msg "msg.unexpected.eof"
1699 "Unexpected end of file")
1700
1701 (js2-msg "msg.XML.bad.form"
1702 "illegally formed XML syntax")
1703
1704 (js2-msg "msg.XML.not.available"
1705 "XML runtime not available")
1706
1707 (js2-msg "msg.too.deep.parser.recursion"
1708 "Too deep recursion while parsing")
1709
1710 (js2-msg "msg.no.side.effects"
1711 "Code has no side effects")
1712
1713 (js2-msg "msg.extra.trailing.comma"
1714 "Trailing comma is not supported in some browsers")
1715
1716 (js2-msg "msg.array.trailing.comma"
1717 "Trailing comma yields different behavior across browsers")
1718
1719 (js2-msg "msg.equal.as.assign"
1720 (concat "Test for equality (==) mistyped as assignment (=)?"
1721 " (parenthesize to suppress warning)"))
1722
1723 (js2-msg "msg.var.hides.arg"
1724 "Variable %s hides argument")
1725
1726 (js2-msg "msg.destruct.assign.no.init"
1727 "Missing = in destructuring declaration")
1728
1729 ;; ScriptRuntime
1730 (js2-msg "msg.no.properties"
1731 "%s has no properties.")
1732
1733 (js2-msg "msg.invalid.iterator"
1734 "Invalid iterator value")
1735
1736 (js2-msg "msg.iterator.primitive"
1737 "__iterator__ returned a primitive value")
1738
1739 (js2-msg "msg.assn.create.strict"
1740 "Assignment to undeclared variable %s")
1741
1742 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1743 "Undeclared variable or function '%s'")
1744
1745 (js2-msg "msg.ref.undefined.prop"
1746 "Reference to undefined property '%s'")
1747
1748 (js2-msg "msg.prop.not.found"
1749 "Property %s not found.")
1750
1751 (js2-msg "msg.invalid.type"
1752 "Invalid JavaScript value of type %s")
1753
1754 (js2-msg "msg.primitive.expected"
1755 "Primitive type expected (had %s instead)")
1756
1757 (js2-msg "msg.namespace.expected"
1758 "Namespace object expected to left of :: (found %s instead)")
1759
1760 (js2-msg "msg.null.to.object"
1761 "Cannot convert null to an object.")
1762
1763 (js2-msg "msg.undef.to.object"
1764 "Cannot convert undefined to an object.")
1765
1766 (js2-msg "msg.cyclic.value"
1767 "Cyclic %s value not allowed.")
1768
1769 (js2-msg "msg.is.not.defined"
1770 "'%s' is not defined.")
1771
1772 (js2-msg "msg.undef.prop.read"
1773 "Cannot read property '%s' from %s")
1774
1775 (js2-msg "msg.undef.prop.write"
1776 "Cannot set property '%s' of %s to '%s'")
1777
1778 (js2-msg "msg.undef.prop.delete"
1779 "Cannot delete property '%s' of %s")
1780
1781 (js2-msg "msg.undef.method.call"
1782 "Cannot call method '%s' of %s")
1783
1784 (js2-msg "msg.undef.with"
1785 "Cannot apply 'with' to %s")
1786
1787 (js2-msg "msg.isnt.function"
1788 "%s is not a function, it is %s.")
1789
1790 (js2-msg "msg.isnt.function.in"
1791 "Cannot call property %s in object %s. "
1792 "It is not a function, it is '%s'.")
1793
1794 (js2-msg "msg.function.not.found"
1795 "Cannot find function %s.")
1796
1797 (js2-msg "msg.function.not.found.in"
1798 "Cannot find function %s in object %s.")
1799
1800 (js2-msg "msg.isnt.xml.object"
1801 "%s is not an xml object.")
1802
1803 (js2-msg "msg.no.ref.to.get"
1804 "%s is not a reference to read reference value.")
1805
1806 (js2-msg "msg.no.ref.to.set"
1807 "%s is not a reference to set reference value to %s.")
1808
1809 (js2-msg "msg.no.ref.from.function"
1810 "Function %s can not be used as the left-hand "
1811 "side of assignment or as an operand of ++ or -- operator.")
1812
1813 (js2-msg "msg.bad.default.value"
1814 "Object's getDefaultValue() method returned an object.")
1815
1816 (js2-msg "msg.instanceof.not.object"
1817 "Can't use instanceof on a non-object.")
1818
1819 (js2-msg "msg.instanceof.bad.prototype"
1820 "'prototype' property of %s is not an object.")
1821
1822 (js2-msg "msg.bad.radix"
1823 "illegal radix %s.")
1824
1825 ;; ScriptableObject
1826 (js2-msg "msg.default.value"
1827 "Cannot find default value for object.")
1828
1829 (js2-msg "msg.zero.arg.ctor"
1830 "Cannot load class '%s' which has no zero-parameter constructor.")
1831
1832 (js2-msg "msg.ctor.multiple.parms"
1833 "Can't define constructor or class %s since more than "
1834 "one constructor has multiple parameters.")
1835
1836 (js2-msg "msg.extend.scriptable"
1837 "%s must extend ScriptableObject in order to define property %s.")
1838
1839 (js2-msg "msg.bad.getter.parms"
1840 "In order to define a property, getter %s must have zero "
1841 "parameters or a single ScriptableObject parameter.")
1842
1843 (js2-msg "msg.obj.getter.parms"
1844 "Expected static or delegated getter %s to take "
1845 "a ScriptableObject parameter.")
1846
1847 (js2-msg "msg.getter.static"
1848 "Getter and setter must both be static or neither be static.")
1849
1850 (js2-msg "msg.setter.return"
1851 "Setter must have void return type: %s")
1852
1853 (js2-msg "msg.setter2.parms"
1854 "Two-parameter setter must take a ScriptableObject as "
1855 "its first parameter.")
1856
1857 (js2-msg "msg.setter1.parms"
1858 "Expected single parameter setter for %s")
1859
1860 (js2-msg "msg.setter2.expected"
1861 "Expected static or delegated setter %s to take two parameters.")
1862
1863 (js2-msg "msg.setter.parms"
1864 "Expected either one or two parameters for setter.")
1865
1866 (js2-msg "msg.setter.bad.type"
1867 "Unsupported parameter type '%s' in setter '%s'.")
1868
1869 (js2-msg "msg.add.sealed"
1870 "Cannot add a property to a sealed object: %s.")
1871
1872 (js2-msg "msg.remove.sealed"
1873 "Cannot remove a property from a sealed object: %s.")
1874
1875 (js2-msg "msg.modify.sealed"
1876 "Cannot modify a property of a sealed object: %s.")
1877
1878 (js2-msg "msg.modify.readonly"
1879 "Cannot modify readonly property: %s.")
1880
1881 ;; TokenStream
1882 (js2-msg "msg.missing.exponent"
1883 "missing exponent")
1884
1885 (js2-msg "msg.caught.nfe"
1886 "number format error")
1887
1888 (js2-msg "msg.unterminated.string.lit"
1889 "unterminated string literal")
1890
1891 (js2-msg "msg.unterminated.comment"
1892 "unterminated comment")
1893
1894 (js2-msg "msg.unterminated.re.lit"
1895 "unterminated regular expression literal")
1896
1897 (js2-msg "msg.invalid.re.flag"
1898 "invalid flag after regular expression")
1899
1900 (js2-msg "msg.no.re.input.for"
1901 "no input for %s")
1902
1903 (js2-msg "msg.illegal.character"
1904 "illegal character")
1905
1906 (js2-msg "msg.invalid.escape"
1907 "invalid Unicode escape sequence")
1908
1909 (js2-msg "msg.bad.namespace"
1910 "not a valid default namespace statement. "
1911 "Syntax is: default xml namespace = EXPRESSION;")
1912
1913 ;; TokensStream warnings
1914 (js2-msg "msg.bad.octal.literal"
1915 "illegal octal literal digit %s; "
1916 "interpreting it as a decimal digit")
1917
1918 (js2-msg "msg.missing.hex.digits"
1919 "missing hexadecimal digits after '0x'")
1920
1921 (js2-msg "msg.missing.binary.digits"
1922 "missing binary digits after '0b'")
1923
1924 (js2-msg "msg.missing.octal.digits"
1925 "missing octal digits after '0o'")
1926
1927 (js2-msg "msg.script.is.not.constructor"
1928 "Script objects are not constructors.")
1929
1930 ;; Arrays
1931 (js2-msg "msg.arraylength.bad"
1932 "Inappropriate array length.")
1933
1934 ;; Arrays
1935 (js2-msg "msg.arraylength.too.big"
1936 "Array length %s exceeds supported capacity limit.")
1937
1938 ;; URI
1939 (js2-msg "msg.bad.uri"
1940 "Malformed URI sequence.")
1941
1942 ;; Number
1943 (js2-msg "msg.bad.precision"
1944 "Precision %s out of range.")
1945
1946 ;; NativeGenerator
1947 (js2-msg "msg.send.newborn"
1948 "Attempt to send value to newborn generator")
1949
1950 (js2-msg "msg.already.exec.gen"
1951 "Already executing generator")
1952
1953 (js2-msg "msg.StopIteration.invalid"
1954 "StopIteration may not be changed to an arbitrary object.")
1955
1956 ;; Interpreter
1957 (js2-msg "msg.yield.closing"
1958 "Yield from closing generator")
1959
1960 ;; Classes
1961 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1962 "class statement requires a name")
1963
1964 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1965 "unexpected ',' between class properties")
1966
1967 (js2-msg "msg.unexpected.static" ; added by js2-mode
1968 "unexpected 'static'")
1969
1970 (js2-msg "msg.missing.extends" ; added by js2-mode
1971 "name is required after extends")
1972
1973 (js2-msg "msg.no.brace.class" ; added by js2-mode
1974 "missing '{' before class body")
1975
1976 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1977 "missing ']' after computed property expression")
1978
1979 ;;; Tokens Buffer
1980
1981 (defconst js2-ti-max-lookahead 2)
1982 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1983
1984 ;; Have to call `js2-init-scanner' to initialize the values.
1985 (js2-deflocal js2-ti-tokens nil)
1986 (js2-deflocal js2-ti-tokens-cursor nil)
1987 (js2-deflocal js2-ti-lookahead nil)
1988
1989 (defun js2-new-token (offset)
1990 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1991 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1992 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1993 token))
1994
1995 (defsubst js2-current-token ()
1996 (aref js2-ti-tokens js2-ti-tokens-cursor))
1997
1998 (defsubst js2-current-token-string ()
1999 (js2-token-string (js2-current-token)))
2000
2001 (defsubst js2-current-token-type ()
2002 (js2-token-type (js2-current-token)))
2003
2004 (defsubst js2-current-token-beg ()
2005 (js2-token-beg (js2-current-token)))
2006
2007 (defsubst js2-current-token-end ()
2008 (js2-token-end (js2-current-token)))
2009
2010 (defun js2-current-token-len ()
2011 (let ((token (js2-current-token)))
2012 (- (js2-token-end token)
2013 (js2-token-beg token))))
2014
2015 (defun js2-ts-seek (state)
2016 (setq js2-ts-lineno (js2-ts-state-lineno state)
2017 js2-ts-cursor (js2-ts-state-cursor state)
2018 js2-ti-tokens (js2-ts-state-tokens state)
2019 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2020 js2-ti-lookahead (js2-ts-state-lookahead state)))
2021
2022 ;;; Utilities
2023
2024 (defun js2-delete-if (predicate list)
2025 "Remove all items satisfying PREDICATE in LIST."
2026 (loop for item in list
2027 if (not (funcall predicate item))
2028 collect item))
2029
2030 (defun js2-position (element list)
2031 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2032 Returns nil if element is not found in the list."
2033 (let ((count 0)
2034 found)
2035 (while (and list (not found))
2036 (if (eq element (car list))
2037 (setq found t)
2038 (setq count (1+ count)
2039 list (cdr list))))
2040 (if found count)))
2041
2042 (defun js2-find-if (predicate list)
2043 "Find first item satisfying PREDICATE in LIST."
2044 (let (result)
2045 (while (and list (not result))
2046 (if (funcall predicate (car list))
2047 (setq result (car list)))
2048 (setq list (cdr list)))
2049 result))
2050
2051 (defmacro js2-time (form)
2052 "Evaluate FORM, discard result, and return elapsed time in sec."
2053 (declare (debug t))
2054 (let ((beg (make-symbol "--js2-time-beg--"))
2055 (delta (make-symbol "--js2-time-end--")))
2056 `(let ((,beg (current-time))
2057 ,delta)
2058 ,form
2059 (/ (truncate (* (- (float-time (current-time))
2060 (float-time ,beg))
2061 10000))
2062 10000.0))))
2063
2064 (defsubst js2-same-line (pos)
2065 "Return t if POS is on the same line as current point."
2066 (and (>= pos (point-at-bol))
2067 (<= pos (point-at-eol))))
2068
2069 (defun js2-code-bug ()
2070 "Signal an error when we encounter an unexpected code path."
2071 (error "failed assertion"))
2072
2073 (defsubst js2-record-text-property (beg end prop value)
2074 "Record a text property to set when parsing finishes."
2075 (push (list beg end prop value) js2-mode-deferred-properties))
2076
2077 ;; I'd like to associate errors with nodes, but for now the
2078 ;; easiest thing to do is get the context info from the last token.
2079 (defun js2-record-parse-error (msg &optional arg pos len)
2080 (push (list (list msg arg)
2081 (or pos (js2-current-token-beg))
2082 (or len (js2-current-token-len)))
2083 js2-parsed-errors))
2084
2085 (defun js2-report-error (msg &optional msg-arg pos len)
2086 "Signal a syntax error or record a parse error."
2087 (if js2-recover-from-parse-errors
2088 (js2-record-parse-error msg msg-arg pos len)
2089 (signal 'js2-syntax-error
2090 (list msg
2091 js2-ts-lineno
2092 (save-excursion
2093 (goto-char js2-ts-cursor)
2094 (current-column))
2095 js2-ts-hit-eof))))
2096
2097 (defun js2-report-warning (msg &optional msg-arg pos len face)
2098 (if js2-compiler-report-warning-as-error
2099 (js2-report-error msg msg-arg pos len)
2100 (push (list (list msg msg-arg)
2101 (or pos (js2-current-token-beg))
2102 (or len (js2-current-token-len))
2103 face)
2104 js2-parsed-warnings)))
2105
2106 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2107 (if js2-compiler-strict-mode
2108 (js2-report-warning msg-id msg-arg beg
2109 (and beg end (- end beg)))))
2110
2111 (put 'js2-syntax-error 'error-conditions
2112 '(error syntax-error js2-syntax-error))
2113 (put 'js2-syntax-error 'error-message "Syntax error")
2114
2115 (put 'js2-parse-error 'error-conditions
2116 '(error parse-error js2-parse-error))
2117 (put 'js2-parse-error 'error-message "Parse error")
2118
2119 (defmacro js2-clear-flag (flags flag)
2120 `(setq ,flags (logand ,flags (lognot ,flag))))
2121
2122 (defmacro js2-set-flag (flags flag)
2123 "Logical-or FLAG into FLAGS."
2124 `(setq ,flags (logior ,flags ,flag)))
2125
2126 (defsubst js2-flag-set-p (flags flag)
2127 (/= 0 (logand flags flag)))
2128
2129 (defsubst js2-flag-not-set-p (flags flag)
2130 (zerop (logand flags flag)))
2131
2132 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2133 "Evaluate BODY with the _ character set to be word-syntax."
2134 (declare (indent 0) (debug t))
2135 (let ((old-syntax (make-symbol "old-syntax")))
2136 `(let ((,old-syntax (string (char-syntax ?_))))
2137 (unwind-protect
2138 (progn
2139 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2140 ,@body)
2141 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2142
2143 ;;; AST struct and function definitions
2144
2145 ;; flags for ast node property 'member-type (used for e4x operators)
2146 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2147 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2148 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2149
2150 (defsubst js2-relpos (pos anchor)
2151 "Convert POS to be relative to ANCHOR.
2152 If POS is nil, returns nil."
2153 (and pos (- pos anchor)))
2154
2155 (defun js2-make-pad (indent)
2156 (if (zerop indent)
2157 ""
2158 (make-string (* indent js2-basic-offset) ? )))
2159
2160 (defun js2-visit-ast (node callback)
2161 "Visit every node in ast NODE with visitor CALLBACK.
2162
2163 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2164 called twice: once to visit the node, and again after all the node's
2165 children have been processed. The END-P argument is nil on the first
2166 call and non-nil on the second call. The return value of the callback
2167 affects the traversal: if non-nil, the children of NODE are processed.
2168 If the callback returns nil, or if the node has no children, then the
2169 callback is called immediately with a non-nil END-P argument.
2170
2171 The node traversal is approximately lexical-order, although there
2172 are currently no guarantees around this."
2173 (when node
2174 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2175 ;; visit the node
2176 (when (funcall callback node nil)
2177 ;; visit the kids
2178 (cond
2179 ((eq vfunc 'js2-visit-none)
2180 nil) ; don't even bother calling it
2181 ;; Each AST node type has to define a `js2-visitor' function
2182 ;; that takes a node and a callback, and calls `js2-visit-ast'
2183 ;; on each child of the node.
2184 (vfunc
2185 (funcall vfunc node callback))
2186 (t
2187 (error "%s does not define a visitor-traversal function"
2188 (aref node 0)))))
2189 ;; call the end-visit
2190 (funcall callback node t))))
2191
2192 (defstruct (js2-node
2193 (:constructor nil)) ; abstract
2194 "Base AST node type."
2195 (type -1) ; token type
2196 (pos -1) ; start position of this AST node in parsed input
2197 (len 1) ; num characters spanned by the node
2198 props ; optional node property list (an alist)
2199 parent) ; link to parent node; null for root
2200
2201 (defsubst js2-node-get-prop (node prop &optional default)
2202 (or (cadr (assoc prop (js2-node-props node))) default))
2203
2204 (defsubst js2-node-set-prop (node prop value)
2205 (setf (js2-node-props node)
2206 (cons (list prop value) (js2-node-props node))))
2207
2208 (defun js2-fixup-starts (n nodes)
2209 "Adjust the start positions of NODES to be relative to N.
2210 Any node in the list may be nil, for convenience."
2211 (dolist (node nodes)
2212 (when node
2213 (setf (js2-node-pos node) (- (js2-node-pos node)
2214 (js2-node-pos n))))))
2215
2216 (defun js2-node-add-children (parent &rest nodes)
2217 "Set parent node of NODES to PARENT, and return PARENT.
2218 Does nothing if we're not recording parent links.
2219 If any given node in NODES is nil, doesn't record that link."
2220 (js2-fixup-starts parent nodes)
2221 (dolist (node nodes)
2222 (and node
2223 (setf (js2-node-parent node) parent))))
2224
2225 ;; Non-recursive since it's called a frightening number of times.
2226 (defun js2-node-abs-pos (n)
2227 (let ((pos (js2-node-pos n)))
2228 (while (setq n (js2-node-parent n))
2229 (setq pos (+ pos (js2-node-pos n))))
2230 pos))
2231
2232 (defsubst js2-node-abs-end (n)
2233 "Return absolute buffer position of end of N."
2234 (+ (js2-node-abs-pos n) (js2-node-len n)))
2235
2236 ;; It's important to make sure block nodes have a Lisp list for the
2237 ;; child nodes, to limit printing recursion depth in an AST that
2238 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2239 ;; a sufficiently large vector tree.
2240
2241 (defstruct (js2-block-node
2242 (:include js2-node)
2243 (:constructor nil)
2244 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2245 (pos (js2-current-token-beg))
2246 len
2247 props
2248 kids)))
2249 "A block of statements."
2250 kids) ; a Lisp list of the child statement nodes
2251
2252 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2253 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2254
2255 (defun js2-visit-block (ast callback)
2256 "Visit the `js2-block-node' children of AST."
2257 (dolist (kid (js2-block-node-kids ast))
2258 (js2-visit-ast kid callback)))
2259
2260 (defun js2-print-block (n i)
2261 (let ((pad (js2-make-pad i)))
2262 (insert pad "{\n")
2263 (dolist (kid (js2-block-node-kids n))
2264 (js2-print-ast kid (1+ i)))
2265 (insert pad "}")))
2266
2267 (defstruct (js2-scope
2268 (:include js2-block-node)
2269 (:constructor nil)
2270 (:constructor make-js2-scope (&key (type js2-BLOCK)
2271 (pos (js2-current-token-beg))
2272 len
2273 kids)))
2274 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2275 ;; I don't have one of those handy, so I'll use an alist for now.
2276 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2277 ;; and is much lighter-weight to construct (both CPU and mem).
2278 ;; The keys are interned strings (symbols) for faster lookup.
2279 ;; Should switch to hybrid alist/hashtable eventually.
2280 symbol-table ; an alist of (symbol . js2-symbol)
2281 parent-scope ; a `js2-scope'
2282 top) ; top-level `js2-scope' (script/function)
2283
2284 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2285 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2286
2287 (defun js2-node-get-enclosing-scope (node)
2288 "Return the innermost `js2-scope' node surrounding NODE.
2289 Returns nil if there is no enclosing scope node."
2290 (let ((parent (js2-node-parent node)))
2291 (while (not (js2-scope-p parent))
2292 (setq parent (js2-node-parent parent)))
2293 parent))
2294
2295 (defun js2-get-defining-scope (scope name)
2296 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2297 Returns `js2-scope' in which NAME is defined, or nil if not found."
2298 (let ((sym (if (symbolp name)
2299 name
2300 (intern name)))
2301 table
2302 result
2303 (continue t))
2304 (while (and scope continue)
2305 (if (and (setq table (js2-scope-symbol-table scope))
2306 (assq sym table))
2307 (setq continue nil
2308 result scope)
2309 (setq scope (js2-scope-parent-scope scope))))
2310 result))
2311
2312 (defun js2-scope-get-symbol (scope name)
2313 "Return symbol table entry for NAME in SCOPE.
2314 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2315 (and (js2-scope-symbol-table scope)
2316 (cdr (assq (if (symbolp name)
2317 name
2318 (intern name))
2319 (js2-scope-symbol-table scope)))))
2320
2321 (defun js2-scope-put-symbol (scope name symbol)
2322 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2323 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2324 (let* ((table (js2-scope-symbol-table scope))
2325 (sym (if (symbolp name) name (intern name)))
2326 (entry (assq sym table)))
2327 (if entry
2328 (setcdr entry symbol)
2329 (push (cons sym symbol)
2330 (js2-scope-symbol-table scope)))))
2331
2332 (defstruct (js2-symbol
2333 (:constructor nil)
2334 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2335 "A symbol table entry."
2336 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2337 ;; js2-LET, or js2-CONST
2338 decl-type
2339 name ; string
2340 ast-node) ; a `js2-node'
2341
2342 (defstruct (js2-error-node
2343 (:include js2-node)
2344 (:constructor nil) ; silence emacs21 byte-compiler
2345 (:constructor make-js2-error-node (&key (type js2-ERROR)
2346 (pos (js2-current-token-beg))
2347 len)))
2348 "AST node representing a parse error.")
2349
2350 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2351 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2352
2353 (defstruct (js2-script-node
2354 (:include js2-scope)
2355 (:constructor nil)
2356 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2357 (pos (js2-current-token-beg))
2358 len
2359 ;; FIXME: What are those?
2360 var-decls
2361 fun-decls)))
2362 functions ; Lisp list of nested functions
2363 regexps ; Lisp list of (string . flags)
2364 symbols ; alist (every symbol gets unique index)
2365 (param-count 0)
2366 var-names ; vector of string names
2367 consts ; bool-vector matching var-decls
2368 (temp-number 0)) ; for generating temp variables
2369
2370 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2371 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2372
2373 (defun js2-print-script (node indent)
2374 (dolist (kid (js2-block-node-kids node))
2375 (js2-print-ast kid indent)))
2376
2377 (defstruct (js2-ast-root
2378 (:include js2-script-node)
2379 (:constructor nil)
2380 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2381 (pos (js2-current-token-beg))
2382 len
2383 buffer)))
2384 "The root node of a js2 AST."
2385 buffer ; the source buffer from which the code was parsed
2386 comments ; a Lisp list of comments, ordered by start position
2387 errors ; a Lisp list of errors found during parsing
2388 warnings ; a Lisp list of warnings found during parsing
2389 node-count) ; number of nodes in the tree, including the root
2390
2391 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2392 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2393
2394 (defun js2-visit-ast-root (ast callback)
2395 (dolist (kid (js2-ast-root-kids ast))
2396 (js2-visit-ast kid callback))
2397 (dolist (comment (js2-ast-root-comments ast))
2398 (js2-visit-ast comment callback)))
2399
2400 (defstruct (js2-comment-node
2401 (:include js2-node)
2402 (:constructor nil)
2403 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2404 (pos (js2-current-token-beg))
2405 len
2406 format)))
2407 format) ; 'line, 'block, 'jsdoc or 'html
2408
2409 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2410 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2411
2412 (defun js2-print-comment (n i)
2413 ;; We really ought to link end-of-line comments to their nodes.
2414 ;; Or maybe we could add a new comment type, 'endline.
2415 (insert (js2-make-pad i)
2416 (js2-node-string n)))
2417
2418 (defstruct (js2-expr-stmt-node
2419 (:include js2-node)
2420 (:constructor nil)
2421 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2422 (pos js2-ts-cursor)
2423 len
2424 expr)))
2425 "An expression statement."
2426 expr)
2427
2428 (defsubst js2-expr-stmt-node-set-has-result (node)
2429 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2430 (setf (js2-node-type node) js2-EXPR_RESULT))
2431
2432 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2433 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2434
2435 (defun js2-visit-expr-stmt-node (n v)
2436 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2437
2438 (defun js2-print-expr-stmt-node (n indent)
2439 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2440 (insert ";\n"))
2441
2442 (defstruct (js2-loop-node
2443 (:include js2-scope)
2444 (:constructor nil))
2445 "Abstract supertype of loop nodes."
2446 body ; a `js2-block-node'
2447 lp ; position of left-paren, nil if omitted
2448 rp) ; position of right-paren, nil if omitted
2449
2450 (defstruct (js2-do-node
2451 (:include js2-loop-node)
2452 (:constructor nil)
2453 (:constructor make-js2-do-node (&key (type js2-DO)
2454 (pos (js2-current-token-beg))
2455 len
2456 body
2457 condition
2458 while-pos
2459 lp
2460 rp)))
2461 "AST node for do-loop."
2462 condition ; while (expression)
2463 while-pos) ; buffer position of 'while' keyword
2464
2465 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2466 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2467
2468 (defun js2-visit-do-node (n v)
2469 (js2-visit-ast (js2-do-node-body n) v)
2470 (js2-visit-ast (js2-do-node-condition n) v))
2471
2472 (defun js2-print-do-node (n i)
2473 (let ((pad (js2-make-pad i)))
2474 (insert pad "do {\n")
2475 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2476 (js2-print-ast kid (1+ i)))
2477 (insert pad "} while (")
2478 (js2-print-ast (js2-do-node-condition n) 0)
2479 (insert ");\n")))
2480
2481 (defstruct (js2-while-node
2482 (:include js2-loop-node)
2483 (:constructor nil)
2484 (:constructor make-js2-while-node (&key (type js2-WHILE)
2485 (pos (js2-current-token-beg))
2486 len body
2487 condition lp
2488 rp)))
2489 "AST node for while-loop."
2490 condition) ; while-condition
2491
2492 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2493 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2494
2495 (defun js2-visit-while-node (n v)
2496 (js2-visit-ast (js2-while-node-condition n) v)
2497 (js2-visit-ast (js2-while-node-body n) v))
2498
2499 (defun js2-print-while-node (n i)
2500 (let ((pad (js2-make-pad i)))
2501 (insert pad "while (")
2502 (js2-print-ast (js2-while-node-condition n) 0)
2503 (insert ") {\n")
2504 (js2-print-body (js2-while-node-body n) (1+ i))
2505 (insert pad "}\n")))
2506
2507 (defstruct (js2-for-node
2508 (:include js2-loop-node)
2509 (:constructor nil)
2510 (:constructor make-js2-for-node (&key (type js2-FOR)
2511 (pos js2-ts-cursor)
2512 len body init
2513 condition
2514 update lp rp)))
2515 "AST node for a C-style for-loop."
2516 init ; initialization expression
2517 condition ; loop condition
2518 update) ; update clause
2519
2520 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2521 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2522
2523 (defun js2-visit-for-node (n v)
2524 (js2-visit-ast (js2-for-node-init n) v)
2525 (js2-visit-ast (js2-for-node-condition n) v)
2526 (js2-visit-ast (js2-for-node-update n) v)
2527 (js2-visit-ast (js2-for-node-body n) v))
2528
2529 (defun js2-print-for-node (n i)
2530 (let ((pad (js2-make-pad i)))
2531 (insert pad "for (")
2532 (js2-print-ast (js2-for-node-init n) 0)
2533 (insert "; ")
2534 (js2-print-ast (js2-for-node-condition n) 0)
2535 (insert "; ")
2536 (js2-print-ast (js2-for-node-update n) 0)
2537 (insert ") {\n")
2538 (js2-print-body (js2-for-node-body n) (1+ i))
2539 (insert pad "}\n")))
2540
2541 (defstruct (js2-for-in-node
2542 (:include js2-loop-node)
2543 (:constructor nil)
2544 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2545 (pos js2-ts-cursor)
2546 len body
2547 iterator
2548 object
2549 in-pos
2550 each-pos
2551 foreach-p forof-p
2552 lp rp)))
2553 "AST node for a for..in loop."
2554 iterator ; [var] foo in ...
2555 object ; object over which we're iterating
2556 in-pos ; buffer position of 'in' keyword
2557 each-pos ; buffer position of 'each' keyword, if foreach-p
2558 foreach-p ; t if it's a for-each loop
2559 forof-p) ; t if it's a for-of loop
2560
2561 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2562 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2563
2564 (defun js2-visit-for-in-node (n v)
2565 (js2-visit-ast (js2-for-in-node-iterator n) v)
2566 (js2-visit-ast (js2-for-in-node-object n) v)
2567 (js2-visit-ast (js2-for-in-node-body n) v))
2568
2569 (defun js2-print-for-in-node (n i)
2570 (let ((pad (js2-make-pad i))
2571 (foreach (js2-for-in-node-foreach-p n))
2572 (forof (js2-for-in-node-forof-p n)))
2573 (insert pad "for ")
2574 (if foreach
2575 (insert "each "))
2576 (insert "(")
2577 (js2-print-ast (js2-for-in-node-iterator n) 0)
2578 (insert (if forof " of " " in "))
2579 (js2-print-ast (js2-for-in-node-object n) 0)
2580 (insert ") {\n")
2581 (js2-print-body (js2-for-in-node-body n) (1+ i))
2582 (insert pad "}\n")))
2583
2584 (defstruct (js2-return-node
2585 (:include js2-node)
2586 (:constructor nil)
2587 (:constructor make-js2-return-node (&key (type js2-RETURN)
2588 (pos js2-ts-cursor)
2589 len
2590 retval)))
2591 "AST node for a return statement."
2592 retval) ; expression to return, or 'undefined
2593
2594 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2595 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2596
2597 (defun js2-visit-return-node (n v)
2598 (js2-visit-ast (js2-return-node-retval n) v))
2599
2600 (defun js2-print-return-node (n i)
2601 (insert (js2-make-pad i) "return")
2602 (when (js2-return-node-retval n)
2603 (insert " ")
2604 (js2-print-ast (js2-return-node-retval n) 0))
2605 (insert ";\n"))
2606
2607 (defstruct (js2-if-node
2608 (:include js2-node)
2609 (:constructor nil)
2610 (:constructor make-js2-if-node (&key (type js2-IF)
2611 (pos js2-ts-cursor)
2612 len condition
2613 then-part
2614 else-pos
2615 else-part lp
2616 rp)))
2617 "AST node for an if-statement."
2618 condition ; expression
2619 then-part ; statement or block
2620 else-pos ; optional buffer position of 'else' keyword
2621 else-part ; optional statement or block
2622 lp ; position of left-paren, nil if omitted
2623 rp) ; position of right-paren, nil if omitted
2624
2625 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2626 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2627
2628 (defun js2-visit-if-node (n v)
2629 (js2-visit-ast (js2-if-node-condition n) v)
2630 (js2-visit-ast (js2-if-node-then-part n) v)
2631 (js2-visit-ast (js2-if-node-else-part n) v))
2632
2633 (defun js2-print-if-node (n i)
2634 (let ((pad (js2-make-pad i))
2635 (then-part (js2-if-node-then-part n))
2636 (else-part (js2-if-node-else-part n)))
2637 (insert pad "if (")
2638 (js2-print-ast (js2-if-node-condition n) 0)
2639 (insert ") {\n")
2640 (js2-print-body then-part (1+ i))
2641 (insert pad "}")
2642 (cond
2643 ((not else-part)
2644 (insert "\n"))
2645 ((js2-if-node-p else-part)
2646 (insert " else ")
2647 (js2-print-body else-part i))
2648 (t
2649 (insert " else {\n")
2650 (js2-print-body else-part (1+ i))
2651 (insert pad "}\n")))))
2652
2653 (defstruct (js2-try-node
2654 (:include js2-node)
2655 (:constructor nil)
2656 (:constructor make-js2-try-node (&key (type js2-TRY)
2657 (pos js2-ts-cursor)
2658 len
2659 try-block
2660 catch-clauses
2661 finally-block)))
2662 "AST node for a try-statement."
2663 try-block
2664 catch-clauses ; a Lisp list of `js2-catch-node'
2665 finally-block) ; a `js2-finally-node'
2666
2667 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2668 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2669
2670 (defun js2-visit-try-node (n v)
2671 (js2-visit-ast (js2-try-node-try-block n) v)
2672 (dolist (clause (js2-try-node-catch-clauses n))
2673 (js2-visit-ast clause v))
2674 (js2-visit-ast (js2-try-node-finally-block n) v))
2675
2676 (defun js2-print-try-node (n i)
2677 (let ((pad (js2-make-pad i))
2678 (catches (js2-try-node-catch-clauses n))
2679 (finally (js2-try-node-finally-block n)))
2680 (insert pad "try {\n")
2681 (js2-print-body (js2-try-node-try-block n) (1+ i))
2682 (insert pad "}")
2683 (when catches
2684 (dolist (catch catches)
2685 (js2-print-ast catch i)))
2686 (if finally
2687 (js2-print-ast finally i)
2688 (insert "\n"))))
2689
2690 (defstruct (js2-catch-node
2691 (:include js2-node)
2692 (:constructor nil)
2693 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2694 (pos js2-ts-cursor)
2695 len
2696 param
2697 guard-kwd
2698 guard-expr
2699 block lp
2700 rp)))
2701 "AST node for a catch clause."
2702 param ; destructuring form or simple name node
2703 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2704 guard-expr ; catch condition, a `js2-node'
2705 block ; statements, a `js2-block-node'
2706 lp ; buffer position of left-paren, nil if omitted
2707 rp) ; buffer position of right-paren, nil if omitted
2708
2709 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2710 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2711
2712 (defun js2-visit-catch-node (n v)
2713 (js2-visit-ast (js2-catch-node-param n) v)
2714 (when (js2-catch-node-guard-kwd n)
2715 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2716 (js2-visit-ast (js2-catch-node-block n) v))
2717
2718 (defun js2-print-catch-node (n i)
2719 (let ((pad (js2-make-pad i))
2720 (guard-kwd (js2-catch-node-guard-kwd n))
2721 (guard-expr (js2-catch-node-guard-expr n)))
2722 (insert " catch (")
2723 (js2-print-ast (js2-catch-node-param n) 0)
2724 (when guard-kwd
2725 (insert " if ")
2726 (js2-print-ast guard-expr 0))
2727 (insert ") {\n")
2728 (js2-print-body (js2-catch-node-block n) (1+ i))
2729 (insert pad "}")))
2730
2731 (defstruct (js2-finally-node
2732 (:include js2-node)
2733 (:constructor nil)
2734 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2735 (pos js2-ts-cursor)
2736 len body)))
2737 "AST node for a finally clause."
2738 body) ; a `js2-node', often but not always a block node
2739
2740 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2741 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2742
2743 (defun js2-visit-finally-node (n v)
2744 (js2-visit-ast (js2-finally-node-body n) v))
2745
2746 (defun js2-print-finally-node (n i)
2747 (let ((pad (js2-make-pad i)))
2748 (insert " finally {\n")
2749 (js2-print-body (js2-finally-node-body n) (1+ i))
2750 (insert pad "}\n")))
2751
2752 (defstruct (js2-switch-node
2753 (:include js2-node)
2754 (:constructor nil)
2755 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2756 (pos js2-ts-cursor)
2757 len
2758 discriminant
2759 cases lp
2760 rp)))
2761 "AST node for a switch statement."
2762 discriminant ; a `js2-node' (switch expression)
2763 cases ; a Lisp list of `js2-case-node'
2764 lp ; position of open-paren for discriminant, nil if omitted
2765 rp) ; position of close-paren for discriminant, nil if omitted
2766
2767 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2768 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2769
2770 (defun js2-visit-switch-node (n v)
2771 (js2-visit-ast (js2-switch-node-discriminant n) v)
2772 (dolist (c (js2-switch-node-cases n))
2773 (js2-visit-ast c v)))
2774
2775 (defun js2-print-switch-node (n i)
2776 (let ((pad (js2-make-pad i))
2777 (cases (js2-switch-node-cases n)))
2778 (insert pad "switch (")
2779 (js2-print-ast (js2-switch-node-discriminant n) 0)
2780 (insert ") {\n")
2781 (dolist (case cases)
2782 (js2-print-ast case i))
2783 (insert pad "}\n")))
2784
2785 (defstruct (js2-case-node
2786 (:include js2-block-node)
2787 (:constructor nil)
2788 (:constructor make-js2-case-node (&key (type js2-CASE)
2789 (pos js2-ts-cursor)
2790 len kids expr)))
2791 "AST node for a case clause of a switch statement."
2792 expr) ; the case expression (nil for default)
2793
2794 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2795 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2796
2797 (defun js2-visit-case-node (n v)
2798 (js2-visit-ast (js2-case-node-expr n) v)
2799 (js2-visit-block n v))
2800
2801 (defun js2-print-case-node (n i)
2802 (let ((pad (js2-make-pad i))
2803 (expr (js2-case-node-expr n)))
2804 (insert pad)
2805 (if (null expr)
2806 (insert "default:\n")
2807 (insert "case ")
2808 (js2-print-ast expr 0)
2809 (insert ":\n"))
2810 (dolist (kid (js2-case-node-kids n))
2811 (js2-print-ast kid (1+ i)))))
2812
2813 (defstruct (js2-throw-node
2814 (:include js2-node)
2815 (:constructor nil)
2816 (:constructor make-js2-throw-node (&key (type js2-THROW)
2817 (pos js2-ts-cursor)
2818 len expr)))
2819 "AST node for a throw statement."
2820 expr) ; the expression to throw
2821
2822 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2823 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2824
2825 (defun js2-visit-throw-node (n v)
2826 (js2-visit-ast (js2-throw-node-expr n) v))
2827
2828 (defun js2-print-throw-node (n i)
2829 (insert (js2-make-pad i) "throw ")
2830 (js2-print-ast (js2-throw-node-expr n) 0)
2831 (insert ";\n"))
2832
2833 (defstruct (js2-with-node
2834 (:include js2-node)
2835 (:constructor nil)
2836 (:constructor make-js2-with-node (&key (type js2-WITH)
2837 (pos js2-ts-cursor)
2838 len object
2839 body lp rp)))
2840 "AST node for a with-statement."
2841 object
2842 body
2843 lp ; buffer position of left-paren around object, nil if omitted
2844 rp) ; buffer position of right-paren around object, nil if omitted
2845
2846 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2847 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2848
2849 (defun js2-visit-with-node (n v)
2850 (js2-visit-ast (js2-with-node-object n) v)
2851 (js2-visit-ast (js2-with-node-body n) v))
2852
2853 (defun js2-print-with-node (n i)
2854 (let ((pad (js2-make-pad i)))
2855 (insert pad "with (")
2856 (js2-print-ast (js2-with-node-object n) 0)
2857 (insert ") {\n")
2858 (js2-print-body (js2-with-node-body n) (1+ i))
2859 (insert pad "}\n")))
2860
2861 (defstruct (js2-label-node
2862 (:include js2-node)
2863 (:constructor nil)
2864 (:constructor make-js2-label-node (&key (type js2-LABEL)
2865 (pos js2-ts-cursor)
2866 len name)))
2867 "AST node for a statement label or case label."
2868 name ; a string
2869 loop) ; for validating and code-generating continue-to-label
2870
2871 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2872 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2873
2874 (defun js2-print-label (n i)
2875 (insert (js2-make-pad i)
2876 (js2-label-node-name n)
2877 ":\n"))
2878
2879 (defstruct (js2-labeled-stmt-node
2880 (:include js2-node)
2881 (:constructor nil)
2882 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2883 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2884 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2885 (pos js2-ts-cursor)
2886 len labels stmt)))
2887 "AST node for a statement with one or more labels.
2888 Multiple labels for a statement are collapsed into the labels field."
2889 labels ; Lisp list of `js2-label-node'
2890 stmt) ; the statement these labels are for
2891
2892 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2893 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2894
2895 (defun js2-get-label-by-name (lbl-stmt name)
2896 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2897 Returns nil if no such label is in the list."
2898 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2899 result)
2900 (while (and label-list (not result))
2901 (if (string= (js2-label-node-name (car label-list)) name)
2902 (setq result (car label-list))
2903 (setq label-list (cdr label-list))))
2904 result))
2905
2906 (defun js2-visit-labeled-stmt (n v)
2907 (dolist (label (js2-labeled-stmt-node-labels n))
2908 (js2-visit-ast label v))
2909 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2910
2911 (defun js2-print-labeled-stmt (n i)
2912 (dolist (label (js2-labeled-stmt-node-labels n))
2913 (js2-print-ast label i))
2914 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2915
2916 (defun js2-labeled-stmt-node-contains (node label)
2917 "Return t if NODE contains LABEL in its label set.
2918 NODE is a `js2-labels-node'. LABEL is an identifier."
2919 (loop for nl in (js2-labeled-stmt-node-labels node)
2920 if (string= label (js2-label-node-name nl))
2921 return t
2922 finally return nil))
2923
2924 (defsubst js2-labeled-stmt-node-add-label (node label)
2925 "Add a `js2-label-node' to the label set for this statement."
2926 (setf (js2-labeled-stmt-node-labels node)
2927 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2928
2929 (defstruct (js2-jump-node
2930 (:include js2-node)
2931 (:constructor nil))
2932 "Abstract supertype of break and continue nodes."
2933 label ; `js2-name-node' for location of label identifier, if present
2934 target) ; target js2-labels-node or loop/switch statement
2935
2936 (defun js2-visit-jump-node (n v)
2937 ;; We don't visit the target, since it's a back-link.
2938 (js2-visit-ast (js2-jump-node-label n) v))
2939
2940 (defstruct (js2-break-node
2941 (:include js2-jump-node)
2942 (:constructor nil)
2943 (:constructor make-js2-break-node (&key (type js2-BREAK)
2944 (pos js2-ts-cursor)
2945 len label target)))
2946 "AST node for a break statement.
2947 The label field is a `js2-name-node', possibly nil, for the named label
2948 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2949 is the target of the break - a label node or enclosing loop/switch statement.")
2950
2951 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2952 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2953
2954 (defun js2-print-break-node (n i)
2955 (insert (js2-make-pad i) "break")
2956 (when (js2-break-node-label n)
2957 (insert " ")
2958 (js2-print-ast (js2-break-node-label n) 0))
2959 (insert ";\n"))
2960
2961 (defstruct (js2-continue-node
2962 (:include js2-jump-node)
2963 (:constructor nil)
2964 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2965 (pos js2-ts-cursor)
2966 len label target)))
2967 "AST node for a continue statement.
2968 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2969 It is nil if continue specifies no label. The target field is the jump target:
2970 a `js2-label-node' or the innermost enclosing loop.")
2971
2972 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2973 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2974
2975 (defun js2-print-continue-node (n i)
2976 (insert (js2-make-pad i) "continue")
2977 (when (js2-continue-node-label n)
2978 (insert " ")
2979 (js2-print-ast (js2-continue-node-label n) 0))
2980 (insert ";\n"))
2981
2982 (defstruct (js2-function-node
2983 (:include js2-script-node)
2984 (:constructor nil)
2985 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2986 (pos js2-ts-cursor)
2987 len
2988 (ftype 'FUNCTION)
2989 (form 'FUNCTION_STATEMENT)
2990 (name "")
2991 params rest-p
2992 body
2993 generator-type
2994 lp rp)))
2995 "AST node for a function declaration.
2996 The `params' field is a Lisp list of nodes. Each node is either a simple
2997 `js2-name-node', or if it's a destructuring-assignment parameter, a
2998 `js2-array-node' or `js2-object-node'."
2999 ftype ; FUNCTION, GETTER or SETTER
3000 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3001 name ; function name (a `js2-name-node', or nil if anonymous)
3002 params ; a Lisp list of destructuring forms or simple name nodes
3003 rest-p ; if t, the last parameter is rest parameter
3004 body ; a `js2-block-node' or expression node (1.8 only)
3005 lp ; position of arg-list open-paren, or nil if omitted
3006 rp ; position of arg-list close-paren, or nil if omitted
3007 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3008 needs-activation ; t if we need an activation object for this frame
3009 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3010 member-expr) ; nonstandard Ecma extension from Rhino
3011
3012 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3013 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3014
3015 (defun js2-visit-function-node (n v)
3016 (js2-visit-ast (js2-function-node-name n) v)
3017 (dolist (p (js2-function-node-params n))
3018 (js2-visit-ast p v))
3019 (js2-visit-ast (js2-function-node-body n) v))
3020
3021 (defun js2-print-function-node (n i)
3022 (let* ((pad (js2-make-pad i))
3023 (getter (js2-node-get-prop n 'GETTER_SETTER))
3024 (name (or (js2-function-node-name n)
3025 (js2-function-node-member-expr n)))
3026 (params (js2-function-node-params n))
3027 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3028 (rest-p (js2-function-node-rest-p n))
3029 (body (js2-function-node-body n))
3030 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3031 (unless (or getter arrow)
3032 (insert pad "function")
3033 (when (eq (js2-function-node-generator-type n) 'STAR)
3034 (insert "*")))
3035 (when name
3036 (insert " ")
3037 (js2-print-ast name 0))
3038 (insert "(")
3039 (loop with len = (length params)
3040 for param in params
3041 for count from 1
3042 do
3043 (when (and rest-p (= count len))
3044 (insert "..."))
3045 (js2-print-ast param 0)
3046 (when (< count len)
3047 (insert ", ")))
3048 (insert ") ")
3049 (when arrow
3050 (insert "=> "))
3051 (insert "{")
3052 ;; TODO: fix this to be smarter about indenting, etc.
3053 (unless expr
3054 (insert "\n"))
3055 (if (js2-block-node-p body)
3056 (js2-print-body body (1+ i))
3057 (js2-print-ast body 0))
3058 (insert pad "}")
3059 (unless expr
3060 (insert "\n"))))
3061
3062 (defun js2-function-name (node)
3063 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3064 (and (js2-function-node-name node)
3065 (js2-name-node-name (js2-function-node-name node))))
3066
3067 ;; Having this be an expression node makes it more flexible.
3068 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3069 ;; that work better if you assume it's an expression. Whenever we have
3070 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3071 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3072 (defstruct (js2-var-decl-node
3073 (:include js2-node)
3074 (:constructor nil)
3075 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3076 (pos (js2-current-token-beg))
3077 len kids
3078 decl-type)))
3079 "AST node for a variable declaration list (VAR, CONST or LET).
3080 The node bounds differ depending on the declaration type. For VAR or
3081 CONST declarations, the bounds include the var/const keyword. For LET
3082 declarations, the node begins at the position of the first child."
3083 kids ; a Lisp list of `js2-var-init-node' structs.
3084 decl-type) ; js2-VAR, js2-CONST or js2-LET
3085
3086 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3087 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3088
3089 (defun js2-visit-var-decl (n v)
3090 (dolist (kid (js2-var-decl-node-kids n))
3091 (js2-visit-ast kid v)))
3092
3093 (defun js2-print-var-decl (n i)
3094 (let ((pad (js2-make-pad i))
3095 (tt (js2-var-decl-node-decl-type n)))
3096 (insert pad)
3097 (insert (cond
3098 ((= tt js2-VAR) "var ")
3099 ((= tt js2-LET) "let ")
3100 ((= tt js2-CONST) "const ")
3101 (t
3102 (error "malformed var-decl node"))))
3103 (loop with kids = (js2-var-decl-node-kids n)
3104 with len = (length kids)
3105 for kid in kids
3106 for count from 1
3107 do
3108 (js2-print-ast kid 0)
3109 (if (< count len)
3110 (insert ", ")))))
3111
3112 (defstruct (js2-var-init-node
3113 (:include js2-node)
3114 (:constructor nil)
3115 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3116 (pos js2-ts-cursor)
3117 len target
3118 initializer)))
3119 "AST node for a variable declaration.
3120 The type field will be js2-CONST for a const decl."
3121 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3122 initializer) ; initializer expression, a `js2-node'
3123
3124 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3125 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3126
3127 (defun js2-visit-var-init-node (n v)
3128 (js2-visit-ast (js2-var-init-node-target n) v)
3129 (js2-visit-ast (js2-var-init-node-initializer n) v))
3130
3131 (defun js2-print-var-init-node (n i)
3132 (let ((pad (js2-make-pad i))
3133 (name (js2-var-init-node-target n))
3134 (init (js2-var-init-node-initializer n)))
3135 (insert pad)
3136 (js2-print-ast name 0)
3137 (when init
3138 (insert " = ")
3139 (js2-print-ast init 0))))
3140
3141 (defstruct (js2-cond-node
3142 (:include js2-node)
3143 (:constructor nil)
3144 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3145 (pos js2-ts-cursor)
3146 len
3147 test-expr
3148 true-expr
3149 false-expr
3150 q-pos c-pos)))
3151 "AST node for the ternary operator"
3152 test-expr
3153 true-expr
3154 false-expr
3155 q-pos ; buffer position of ?
3156 c-pos) ; buffer position of :
3157
3158 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3159 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3160
3161 (defun js2-visit-cond-node (n v)
3162 (js2-visit-ast (js2-cond-node-test-expr n) v)
3163 (js2-visit-ast (js2-cond-node-true-expr n) v)
3164 (js2-visit-ast (js2-cond-node-false-expr n) v))
3165
3166 (defun js2-print-cond-node (n i)
3167 (let ((pad (js2-make-pad i)))
3168 (insert pad)
3169 (js2-print-ast (js2-cond-node-test-expr n) 0)
3170 (insert " ? ")
3171 (js2-print-ast (js2-cond-node-true-expr n) 0)
3172 (insert " : ")
3173 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3174
3175 (defstruct (js2-infix-node
3176 (:include js2-node)
3177 (:constructor nil)
3178 (:constructor make-js2-infix-node (&key type
3179 (pos js2-ts-cursor)
3180 len op-pos
3181 left right)))
3182 "Represents infix expressions.
3183 Includes assignment ops like `|=', and the comma operator.
3184 The type field inherited from `js2-node' holds the operator."
3185 op-pos ; buffer position where operator begins
3186 left ; any `js2-node'
3187 right) ; any `js2-node'
3188
3189 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3190 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3191
3192 (defun js2-visit-infix-node (n v)
3193 (js2-visit-ast (js2-infix-node-left n) v)
3194 (js2-visit-ast (js2-infix-node-right n) v))
3195
3196 (defconst js2-operator-tokens
3197 (let ((table (make-hash-table :test 'eq))
3198 (tokens
3199 (list (cons js2-IN "in")
3200 (cons js2-TYPEOF "typeof")
3201 (cons js2-INSTANCEOF "instanceof")
3202 (cons js2-DELPROP "delete")
3203 (cons js2-COMMA ",")
3204 (cons js2-COLON ":")
3205 (cons js2-OR "||")
3206 (cons js2-AND "&&")
3207 (cons js2-INC "++")
3208 (cons js2-DEC "--")
3209 (cons js2-BITOR "|")
3210 (cons js2-BITXOR "^")
3211 (cons js2-BITAND "&")
3212 (cons js2-EQ "==")
3213 (cons js2-NE "!=")
3214 (cons js2-LT "<")
3215 (cons js2-LE "<=")
3216 (cons js2-GT ">")
3217 (cons js2-GE ">=")
3218 (cons js2-LSH "<<")
3219 (cons js2-RSH ">>")
3220 (cons js2-URSH ">>>")
3221 (cons js2-ADD "+") ; infix plus
3222 (cons js2-SUB "-") ; infix minus
3223 (cons js2-MUL "*")
3224 (cons js2-DIV "/")
3225 (cons js2-MOD "%")
3226 (cons js2-NOT "!")
3227 (cons js2-BITNOT "~")
3228 (cons js2-POS "+") ; unary plus
3229 (cons js2-NEG "-") ; unary minus
3230 (cons js2-TRIPLEDOT "...")
3231 (cons js2-SHEQ "===") ; shallow equality
3232 (cons js2-SHNE "!==") ; shallow inequality
3233 (cons js2-ASSIGN "=")
3234 (cons js2-ASSIGN_BITOR "|=")
3235 (cons js2-ASSIGN_BITXOR "^=")
3236 (cons js2-ASSIGN_BITAND "&=")
3237 (cons js2-ASSIGN_LSH "<<=")
3238 (cons js2-ASSIGN_RSH ">>=")
3239 (cons js2-ASSIGN_URSH ">>>=")
3240 (cons js2-ASSIGN_ADD "+=")
3241 (cons js2-ASSIGN_SUB "-=")
3242 (cons js2-ASSIGN_MUL "*=")
3243 (cons js2-ASSIGN_DIV "/=")
3244 (cons js2-ASSIGN_MOD "%="))))
3245 (loop for (k . v) in tokens do
3246 (puthash k v table))
3247 table))
3248
3249 (defun js2-print-infix-node (n i)
3250 (let* ((tt (js2-node-type n))
3251 (op (gethash tt js2-operator-tokens)))
3252 (unless op
3253 (error "unrecognized infix operator %s" (js2-node-type n)))
3254 (insert (js2-make-pad i))
3255 (js2-print-ast (js2-infix-node-left n) 0)
3256 (unless (= tt js2-COMMA)
3257 (insert " "))
3258 (insert op)
3259 (insert " ")
3260 (js2-print-ast (js2-infix-node-right n) 0)))
3261
3262 (defstruct (js2-assign-node
3263 (:include js2-infix-node)
3264 (:constructor nil)
3265 (:constructor make-js2-assign-node (&key type
3266 (pos js2-ts-cursor)
3267 len op-pos
3268 left right)))
3269 "Represents any assignment.
3270 The type field holds the actual assignment operator.")
3271
3272 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3273 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3274
3275 (defstruct (js2-unary-node
3276 (:include js2-node)
3277 (:constructor nil)
3278 (:constructor make-js2-unary-node (&key type ; required
3279 (pos js2-ts-cursor)
3280 len operand)))
3281 "AST node type for unary operator nodes.
3282 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3283 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3284 property is added if the operator follows the operand."
3285 operand) ; a `js2-node' expression
3286
3287 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3288 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3289
3290 (defun js2-visit-unary-node (n v)
3291 (js2-visit-ast (js2-unary-node-operand n) v))
3292
3293 (defun js2-print-unary-node (n i)
3294 (let* ((tt (js2-node-type n))
3295 (op (gethash tt js2-operator-tokens))
3296 (postfix (js2-node-get-prop n 'postfix)))
3297 (unless op
3298 (error "unrecognized unary operator %s" tt))
3299 (insert (js2-make-pad i))
3300 (unless postfix
3301 (insert op))
3302 (if (or (= tt js2-TYPEOF)
3303 (= tt js2-DELPROP))
3304 (insert " "))
3305 (js2-print-ast (js2-unary-node-operand n) 0)
3306 (when postfix
3307 (insert op))))
3308
3309 (defstruct (js2-let-node
3310 (:include js2-scope)
3311 (:constructor nil)
3312 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3313 (pos (js2-current-token-beg))
3314 len vars body
3315 lp rp)))
3316 "AST node for a let expression or a let statement.
3317 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3318 vars ; a `js2-var-decl-node'
3319 body ; a `js2-node' representing the expression or body block
3320 lp
3321 rp)
3322
3323 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3324 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3325
3326 (defun js2-visit-let-node (n v)
3327 (js2-visit-ast (js2-let-node-vars n) v)
3328 (js2-visit-ast (js2-let-node-body n) v))
3329
3330 (defun js2-print-let-node (n i)
3331 (insert (js2-make-pad i) "let (")
3332 (let ((p (point)))
3333 (js2-print-ast (js2-let-node-vars n) 0)
3334 (delete-region p (+ p 4)))
3335 (insert ") ")
3336 (js2-print-ast (js2-let-node-body n) i))
3337
3338 (defstruct (js2-keyword-node
3339 (:include js2-node)
3340 (:constructor nil)
3341 (:constructor make-js2-keyword-node (&key type
3342 (pos (js2-current-token-beg))
3343 (len (- js2-ts-cursor pos)))))
3344 "AST node representing a literal keyword such as `null'.
3345 Used for `null', `this', `true', `false' and `debugger'.
3346 The node type is set to js2-NULL, js2-THIS, etc.")
3347
3348 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3349 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3350
3351 (defun js2-print-keyword-node (n i)
3352 (insert (js2-make-pad i)
3353 (let ((tt (js2-node-type n)))
3354 (cond
3355 ((= tt js2-THIS) "this")
3356 ((= tt js2-SUPER) "super")
3357 ((= tt js2-NULL) "null")
3358 ((= tt js2-TRUE) "true")
3359 ((= tt js2-FALSE) "false")
3360 ((= tt js2-DEBUGGER) "debugger")
3361 (t (error "Invalid keyword literal type: %d" tt))))))
3362
3363 (defsubst js2-this-or-super-node-p (node)
3364 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3365 (let ((type (js2-node-type node)))
3366 (or (eq type js2-THIS) (eq type js2-SUPER))))
3367
3368 (defstruct (js2-new-node
3369 (:include js2-node)
3370 (:constructor nil)
3371 (:constructor make-js2-new-node (&key (type js2-NEW)
3372 (pos (js2-current-token-beg))
3373 len target
3374 args initializer
3375 lp rp)))
3376 "AST node for new-expression such as new Foo()."
3377 target ; an identifier or reference
3378 args ; a Lisp list of argument nodes
3379 lp ; position of left-paren, nil if omitted
3380 rp ; position of right-paren, nil if omitted
3381 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3382
3383 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3384 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3385
3386 (defun js2-visit-new-node (n v)
3387 (js2-visit-ast (js2-new-node-target n) v)
3388 (dolist (arg (js2-new-node-args n))
3389 (js2-visit-ast arg v))
3390 (js2-visit-ast (js2-new-node-initializer n) v))
3391
3392 (defun js2-print-new-node (n i)
3393 (insert (js2-make-pad i) "new ")
3394 (js2-print-ast (js2-new-node-target n))
3395 (insert "(")
3396 (js2-print-list (js2-new-node-args n))
3397 (insert ")")
3398 (when (js2-new-node-initializer n)
3399 (insert " ")
3400 (js2-print-ast (js2-new-node-initializer n))))
3401
3402 (defstruct (js2-name-node
3403 (:include js2-node)
3404 (:constructor nil)
3405 (:constructor make-js2-name-node (&key (type js2-NAME)
3406 (pos (js2-current-token-beg))
3407 (len (- js2-ts-cursor
3408 (js2-current-token-beg)))
3409 (name (js2-current-token-string)))))
3410 "AST node for a JavaScript identifier"
3411 name ; a string
3412 scope) ; a `js2-scope' (optional, used for codegen)
3413
3414 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3415 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3416
3417 (defun js2-print-name-node (n i)
3418 (insert (js2-make-pad i)
3419 (js2-name-node-name n)))
3420
3421 (defsubst js2-name-node-length (node)
3422 "Return identifier length of NODE, a `js2-name-node'.
3423 Returns 0 if NODE is nil or its identifier field is nil."
3424 (if node
3425 (length (js2-name-node-name node))
3426 0))
3427
3428 (defstruct (js2-number-node
3429 (:include js2-node)
3430 (:constructor nil)
3431 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3432 (pos (js2-current-token-beg))
3433 (len (- js2-ts-cursor
3434 (js2-current-token-beg)))
3435 (value (js2-current-token-string))
3436 (num-value (js2-token-number
3437 (js2-current-token))))))
3438 "AST node for a number literal."
3439 value ; the original string, e.g. "6.02e23"
3440 num-value) ; the parsed number value
3441
3442 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3443 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3444
3445 (defun js2-print-number-node (n i)
3446 (insert (js2-make-pad i)
3447 (number-to-string (js2-number-node-num-value n))))
3448
3449 (defstruct (js2-regexp-node
3450 (:include js2-node)
3451 (:constructor nil)
3452 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3453 (pos (js2-current-token-beg))
3454 (len (- js2-ts-cursor
3455 (js2-current-token-beg)))
3456 value flags)))
3457 "AST node for a regular expression literal."
3458 value ; the regexp string, without // delimiters
3459 flags) ; a string of flags, e.g. `mi'.
3460
3461 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3462 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3463
3464 (defun js2-print-regexp (n i)
3465 (insert (js2-make-pad i)
3466 "/"
3467 (js2-regexp-node-value n)
3468 "/")
3469 (if (js2-regexp-node-flags n)
3470 (insert (js2-regexp-node-flags n))))
3471
3472 (defstruct (js2-string-node
3473 (:include js2-node)
3474 (:constructor nil)
3475 (:constructor make-js2-string-node (&key (type js2-STRING)
3476 (pos (js2-current-token-beg))
3477 (len (- js2-ts-cursor
3478 (js2-current-token-beg)))
3479 (value (js2-current-token-string)))))
3480 "String literal.
3481 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3482 You can tell the quote type by looking at the first character."
3483 value) ; the characters of the string, including the quotes
3484
3485 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3486 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3487
3488 (defun js2-print-string-node (n i)
3489 (insert (js2-make-pad i)
3490 (js2-node-string n)))
3491
3492 (defstruct (js2-template-node
3493 (:include js2-node)
3494 (:constructor nil)
3495 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3496 beg len kids)))
3497 "Template literal."
3498 kids) ; `js2-string-node' is used for string segments, other nodes
3499 ; for substitutions inside.
3500
3501 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3502 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3503
3504 (defun js2-visit-template (n callback)
3505 (dolist (kid (js2-template-node-kids n))
3506 (js2-visit-ast kid callback)))
3507
3508 (defun js2-print-template (n i)
3509 (insert (js2-make-pad i))
3510 (dolist (kid (js2-template-node-kids n))
3511 (if (js2-string-node-p kid)
3512 (insert (js2-node-string kid))
3513 (js2-print-ast kid))))
3514
3515 (defstruct (js2-tagged-template-node
3516 (:include js2-node)
3517 (:constructor nil)
3518 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3519 beg len tag template)))
3520 "Tagged template literal."
3521 tag ; `js2-node' with the tag expression.
3522 template) ; `js2-template-node' with the template.
3523
3524 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3525 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3526
3527 (defun js2-visit-tagged-template (n callback)
3528 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3529 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3530
3531 (defun js2-print-tagged-template (n i)
3532 (insert (js2-make-pad i))
3533 (js2-print-ast (js2-tagged-template-node-tag n))
3534 (js2-print-ast (js2-tagged-template-node-template n)))
3535
3536 (defstruct (js2-array-node
3537 (:include js2-node)
3538 (:constructor nil)
3539 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3540 (pos js2-ts-cursor)
3541 len elems)))
3542 "AST node for an array literal."
3543 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3544
3545 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3546 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3547
3548 (defun js2-visit-array-node (n v)
3549 (dolist (e (js2-array-node-elems n))
3550 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3551
3552 (defun js2-print-array-node (n i)
3553 (insert (js2-make-pad i) "[")
3554 (let ((elems (js2-array-node-elems n)))
3555 (js2-print-list elems)
3556 (when (and elems (null (car (last elems))))
3557 (insert ",")))
3558 (insert "]"))
3559
3560 (defstruct (js2-class-node
3561 (:include js2-node)
3562 (:constructor nil)
3563 (:constructor make-js2-class-node (&key (type js2-CLASS)
3564 (pos js2-ts-cursor)
3565 (form 'CLASS_STATEMENT)
3566 (name "")
3567 extends len elems)))
3568 "AST node for an class expression.
3569 `elems' is a list of `js2-object-prop-node', and `extends' is an
3570 optional `js2-expr-node'"
3571 form ; CLASS_{STATEMENT|EXPRESSION}
3572 name ; class name (a `js2-node-name', or nil if anonymous)
3573 extends ; class heritage (a `js2-expr-node', or nil if none)
3574 elems)
3575
3576 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3577 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3578
3579 (defun js2-visit-class-node (n v)
3580 (js2-visit-ast (js2-class-node-name n) v)
3581 (js2-visit-ast (js2-class-node-extends n) v)
3582 (dolist (e (js2-class-node-elems n))
3583 (js2-visit-ast e v)))
3584
3585 (defun js2-print-class-node (n i)
3586 (let* ((pad (js2-make-pad i))
3587 (name (js2-class-node-name n))
3588 (extends (js2-class-node-extends n))
3589 (elems (js2-class-node-elems n)))
3590 (insert pad "class")
3591 (when name
3592 (insert " ")
3593 (js2-print-ast name 0))
3594 (when extends
3595 (insert " extends ")
3596 (js2-print-ast extends))
3597 (insert " {")
3598 (dolist (elem elems)
3599 (insert "\n")
3600 (if (js2-node-get-prop elem 'STATIC)
3601 (progn (insert (js2-make-pad (1+ i)) "static ")
3602 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3603 (js2-print-ast elem (1+ i))))
3604 (insert "\n" pad "}")))
3605
3606 (defstruct (js2-object-node
3607 (:include js2-node)
3608 (:constructor nil)
3609 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3610 (pos js2-ts-cursor)
3611 len
3612 elems)))
3613 "AST node for an object literal expression.
3614 `elems' is a list of `js2-object-prop-node'."
3615 elems)
3616
3617 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3618 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3619
3620 (defun js2-visit-object-node (n v)
3621 (dolist (e (js2-object-node-elems n))
3622 (js2-visit-ast e v)))
3623
3624 (defun js2-print-object-node (n i)
3625 (insert (js2-make-pad i) "{")
3626 (js2-print-list (js2-object-node-elems n))
3627 (insert "}"))
3628
3629 (defstruct (js2-object-prop-node
3630 (:include js2-infix-node)
3631 (:constructor nil)
3632 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3633 (pos js2-ts-cursor)
3634 len left
3635 right op-pos)))
3636 "AST node for an object literal prop:value entry.
3637 The `left' field is the property: a name node, string node or number node.
3638 The `right' field is a `js2-node' representing the initializer value.
3639 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3640 and both fields have the same value.")
3641
3642 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3643 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3644
3645 (defun js2-print-object-prop-node (n i)
3646 (let* ((left (js2-object-prop-node-left n))
3647 (computed (not (or (js2-string-node-p left)
3648 (js2-number-node-p left)
3649 (js2-name-node-p left)))))
3650 (insert (js2-make-pad i))
3651 (if computed
3652 (insert "["))
3653 (js2-print-ast left 0)
3654 (if computed
3655 (insert "]"))
3656 (if (not (js2-node-get-prop n 'SHORTHAND))
3657 (progn
3658 (insert ": ")
3659 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3660
3661 (defstruct (js2-getter-setter-node
3662 (:include js2-infix-node)
3663 (:constructor nil)
3664 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3665 (pos js2-ts-cursor)
3666 len left right)))
3667 "AST node for a getter/setter property in an object literal.
3668 The `left' field is the `js2-name-node' naming the getter/setter prop.
3669 The `right' field is always an anonymous `js2-function-node' with a node
3670 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3671
3672 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3673 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3674
3675 (defun js2-print-getter-setter (n i)
3676 (let ((pad (js2-make-pad i))
3677 (left (js2-getter-setter-node-left n))
3678 (right (js2-getter-setter-node-right n)))
3679 (insert pad)
3680 (if (/= (js2-node-type n) js2-FUNCTION)
3681 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3682 (js2-print-ast left 0)
3683 (js2-print-ast right 0)))
3684
3685 (defstruct (js2-prop-get-node
3686 (:include js2-infix-node)
3687 (:constructor nil)
3688 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3689 (pos js2-ts-cursor)
3690 len left right)))
3691 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3692
3693 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3694 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3695
3696 (defun js2-visit-prop-get-node (n v)
3697 (js2-visit-ast (js2-prop-get-node-left n) v)
3698 (js2-visit-ast (js2-prop-get-node-right n) v))
3699
3700 (defun js2-print-prop-get-node (n i)
3701 (insert (js2-make-pad i))
3702 (js2-print-ast (js2-prop-get-node-left n) 0)
3703 (insert ".")
3704 (js2-print-ast (js2-prop-get-node-right n) 0))
3705
3706 (defstruct (js2-elem-get-node
3707 (:include js2-node)
3708 (:constructor nil)
3709 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3710 (pos js2-ts-cursor)
3711 len target element
3712 lb rb)))
3713 "AST node for an array index expression such as foo[bar]."
3714 target ; a `js2-node' - the expression preceding the "."
3715 element ; a `js2-node' - the expression in brackets
3716 lb ; position of left-bracket, nil if omitted
3717 rb) ; position of right-bracket, nil if omitted
3718
3719 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3720 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3721
3722 (defun js2-visit-elem-get-node (n v)
3723 (js2-visit-ast (js2-elem-get-node-target n) v)
3724 (js2-visit-ast (js2-elem-get-node-element n) v))
3725
3726 (defun js2-print-elem-get-node (n i)
3727 (insert (js2-make-pad i))
3728 (js2-print-ast (js2-elem-get-node-target n) 0)
3729 (insert "[")
3730 (js2-print-ast (js2-elem-get-node-element n) 0)
3731 (insert "]"))
3732
3733 (defstruct (js2-call-node
3734 (:include js2-node)
3735 (:constructor nil)
3736 (:constructor make-js2-call-node (&key (type js2-CALL)
3737 (pos js2-ts-cursor)
3738 len target args
3739 lp rp)))
3740 "AST node for a JavaScript function call."
3741 target ; a `js2-node' evaluating to the function to call
3742 args ; a Lisp list of `js2-node' arguments
3743 lp ; position of open-paren, or nil if missing
3744 rp) ; position of close-paren, or nil if missing
3745
3746 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3747 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3748
3749 (defun js2-visit-call-node (n v)
3750 (js2-visit-ast (js2-call-node-target n) v)
3751 (dolist (arg (js2-call-node-args n))
3752 (js2-visit-ast arg v)))
3753
3754 (defun js2-print-call-node (n i)
3755 (insert (js2-make-pad i))
3756 (js2-print-ast (js2-call-node-target n) 0)
3757 (insert "(")
3758 (js2-print-list (js2-call-node-args n))
3759 (insert ")"))
3760
3761 (defstruct (js2-yield-node
3762 (:include js2-node)
3763 (:constructor nil)
3764 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3765 (pos js2-ts-cursor)
3766 len value star-p)))
3767 "AST node for yield statement or expression."
3768 star-p ; whether it's yield*
3769 value) ; optional: value to be yielded
3770
3771 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3772 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3773
3774 (defun js2-visit-yield-node (n v)
3775 (js2-visit-ast (js2-yield-node-value n) v))
3776
3777 (defun js2-print-yield-node (n i)
3778 (insert (js2-make-pad i))
3779 (insert "yield")
3780 (when (js2-yield-node-star-p n)
3781 (insert "*"))
3782 (when (js2-yield-node-value n)
3783 (insert " ")
3784 (js2-print-ast (js2-yield-node-value n) 0)))
3785
3786 (defstruct (js2-paren-node
3787 (:include js2-node)
3788 (:constructor nil)
3789 (:constructor make-js2-paren-node (&key (type js2-LP)
3790 (pos js2-ts-cursor)
3791 len expr)))
3792 "AST node for a parenthesized expression.
3793 In particular, used when the parens are syntactically optional,
3794 as opposed to required parens such as those enclosing an if-conditional."
3795 expr) ; `js2-node'
3796
3797 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3798 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3799
3800 (defun js2-visit-paren-node (n v)
3801 (js2-visit-ast (js2-paren-node-expr n) v))
3802
3803 (defun js2-print-paren-node (n i)
3804 (insert (js2-make-pad i))
3805 (insert "(")
3806 (js2-print-ast (js2-paren-node-expr n) 0)
3807 (insert ")"))
3808
3809 (defstruct (js2-comp-node
3810 (:include js2-scope)
3811 (:constructor nil)
3812 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3813 (pos js2-ts-cursor)
3814 len result
3815 loops filters
3816 form)))
3817 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3818 result ; result expression (just after left-bracket)
3819 loops ; a Lisp list of `js2-comp-loop-node'
3820 filters ; a Lisp list of guard/filter expressions
3821 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3822 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3823 )
3824
3825 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3826 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3827
3828 (defun js2-visit-comp-node (n v)
3829 (js2-visit-ast (js2-comp-node-result n) v)
3830 (dolist (l (js2-comp-node-loops n))
3831 (js2-visit-ast l v))
3832 (dolist (f (js2-comp-node-filters n))
3833 (js2-visit-ast f v)))
3834
3835 (defun js2-print-comp-node (n i)
3836 (let ((pad (js2-make-pad i))
3837 (result (js2-comp-node-result n))
3838 (loops (js2-comp-node-loops n))
3839 (filters (js2-comp-node-filters n))
3840 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3841 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3842 (insert pad (if gen-p "(" "["))
3843 (when legacy-p
3844 (js2-print-ast result 0))
3845 (dolist (l loops)
3846 (when legacy-p
3847 (insert " "))
3848 (js2-print-ast l 0)
3849 (unless legacy-p
3850 (insert " ")))
3851 (dolist (f filters)
3852 (when legacy-p
3853 (insert " "))
3854 (insert "if (")
3855 (js2-print-ast f 0)
3856 (insert ")")
3857 (unless legacy-p
3858 (insert " ")))
3859 (unless legacy-p
3860 (js2-print-ast result 0))
3861 (insert (if gen-p ")" "]"))))
3862
3863 (defstruct (js2-comp-loop-node
3864 (:include js2-for-in-node)
3865 (:constructor nil)
3866 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3867 (pos js2-ts-cursor)
3868 len iterator
3869 object in-pos
3870 foreach-p
3871 each-pos
3872 forof-p
3873 lp rp)))
3874 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3875
3876 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3877 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3878
3879 (defun js2-visit-comp-loop (n v)
3880 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3881 (js2-visit-ast (js2-comp-loop-node-object n) v))
3882
3883 (defun js2-print-comp-loop (n _i)
3884 (insert "for ")
3885 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3886 (insert "(")
3887 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3888 (insert (if (js2-comp-loop-node-forof-p n)
3889 " of " " in "))
3890 (js2-print-ast (js2-comp-loop-node-object n) 0)
3891 (insert ")"))
3892
3893 (defstruct (js2-empty-expr-node
3894 (:include js2-node)
3895 (:constructor nil)
3896 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3897 (pos (js2-current-token-beg))
3898 len)))
3899 "AST node for an empty expression.")
3900
3901 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3902 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3903
3904 (defstruct (js2-xml-node
3905 (:include js2-block-node)
3906 (:constructor nil)
3907 (:constructor make-js2-xml-node (&key (type js2-XML)
3908 (pos (js2-current-token-beg))
3909 len kids)))
3910 "AST node for initial parse of E4X literals.
3911 The kids field is a list of XML fragments, each a `js2-string-node' or
3912 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3913
3914 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3915 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3916
3917 (defun js2-print-xml-node (n i)
3918 (dolist (kid (js2-xml-node-kids n))
3919 (js2-print-ast kid i)))
3920
3921 (defstruct (js2-xml-js-expr-node
3922 (:include js2-xml-node)
3923 (:constructor nil)
3924 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3925 (pos js2-ts-cursor)
3926 len expr)))
3927 "AST node for an embedded JavaScript {expression} in an E4X literal.
3928 The start and end fields correspond to the curly-braces."
3929 expr) ; a `js2-expr-node' of some sort
3930
3931 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3932 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3933
3934 (defun js2-visit-xml-js-expr (n v)
3935 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3936
3937 (defun js2-print-xml-js-expr (n i)
3938 (insert (js2-make-pad i))
3939 (insert "{")
3940 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3941 (insert "}"))
3942
3943 (defstruct (js2-xml-dot-query-node
3944 (:include js2-infix-node)
3945 (:constructor nil)
3946 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3947 (pos js2-ts-cursor)
3948 op-pos len left
3949 right rp)))
3950 "AST node for an E4X foo.(bar) filter expression.
3951 Note that the left-paren is automatically the character immediately
3952 following the dot (.) in the operator. No whitespace is permitted
3953 between the dot and the lp by the scanner."
3954 rp)
3955
3956 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3957 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3958
3959 (defun js2-print-xml-dot-query (n i)
3960 (insert (js2-make-pad i))
3961 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3962 (insert ".(")
3963 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3964 (insert ")"))
3965
3966 (defstruct (js2-xml-ref-node
3967 (:include js2-node)
3968 (:constructor nil)) ; abstract
3969 "Base type for E4X XML attribute-access or property-get expressions.
3970 Such expressions can take a variety of forms. The general syntax has
3971 three parts:
3972
3973 - (optional) an @ (specifying an attribute access)
3974 - (optional) a namespace (a `js2-name-node') and double-colon
3975 - (required) either a `js2-name-node' or a bracketed [expression]
3976
3977 The property-name expressions (examples: ns::name, @name) are
3978 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3979 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3980
3981 This node type (or more specifically, its subclasses) will sometimes
3982 be the right-hand child of a `js2-prop-get-node' or a
3983 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3984 The `js2-xml-ref-node' may also be a standalone primary expression with
3985 no explicit target, which is valid in certain expression contexts such as
3986
3987 company..employee.(@id < 100)
3988
3989 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3990 expression whose parent is a `js2-xml-dot-query-node'."
3991 namespace
3992 at-pos
3993 colon-pos)
3994
3995 (defsubst js2-xml-ref-node-attr-access-p (node)
3996 "Return non-nil if this expression began with an @-token."
3997 (and (numberp (js2-xml-ref-node-at-pos node))
3998 (plusp (js2-xml-ref-node-at-pos node))))
3999
4000 (defstruct (js2-xml-prop-ref-node
4001 (:include js2-xml-ref-node)
4002 (:constructor nil)
4003 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4004 (pos (js2-current-token-beg))
4005 len propname
4006 namespace at-pos
4007 colon-pos)))
4008 "AST node for an E4X XML [expr] property-ref expression.
4009 The JavaScript syntax is an optional @, an optional ns::, and a name.
4010
4011 [ '@' ] [ name '::' ] name
4012
4013 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4014 @ns::*, @*::attr, @*::*, and @*.
4015
4016 The node starts at the @ token, if present. Otherwise it starts at the
4017 namespace name. The node bounds extend through the closing right-bracket,
4018 or if it is missing due to a syntax error, through the end of the index
4019 expression."
4020 propname)
4021
4022 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4023 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4024
4025 (defun js2-visit-xml-prop-ref-node (n v)
4026 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4027 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4028
4029 (defun js2-print-xml-prop-ref-node (n i)
4030 (insert (js2-make-pad i))
4031 (if (js2-xml-ref-node-attr-access-p n)
4032 (insert "@"))
4033 (when (js2-xml-prop-ref-node-namespace n)
4034 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4035 (insert "::"))
4036 (if (js2-xml-prop-ref-node-propname n)
4037 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4038
4039 (defstruct (js2-xml-elem-ref-node
4040 (:include js2-xml-ref-node)
4041 (:constructor nil)
4042 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4043 (pos (js2-current-token-beg))
4044 len expr lb rb
4045 namespace at-pos
4046 colon-pos)))
4047 "AST node for an E4X XML [expr] member-ref expression.
4048 Syntax:
4049
4050 [ '@' ] [ name '::' ] '[' expr ']'
4051
4052 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4053
4054 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4055 is not a legal E4X XML element-ref expression, since it's already used
4056 for standard JavaScript element-get array indexing. Hence, a
4057 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4058 non-nil namespace node, or both.
4059
4060 The node starts at the @ token, if present. Otherwise it starts
4061 at the namespace name. The node bounds extend through the closing
4062 right-bracket, or if it is missing due to a syntax error, through the
4063 end of the index expression."
4064 expr ; the bracketed index expression
4065 lb
4066 rb)
4067
4068 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4069 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4070
4071 (defun js2-visit-xml-elem-ref-node (n v)
4072 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4073 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4074
4075 (defun js2-print-xml-elem-ref-node (n i)
4076 (insert (js2-make-pad i))
4077 (if (js2-xml-ref-node-attr-access-p n)
4078 (insert "@"))
4079 (when (js2-xml-elem-ref-node-namespace n)
4080 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4081 (insert "::"))
4082 (insert "[")
4083 (if (js2-xml-elem-ref-node-expr n)
4084 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4085 (insert "]"))
4086
4087 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4088
4089 (defstruct (js2-xml-start-tag-node
4090 (:include js2-xml-node)
4091 (:constructor nil)
4092 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4093 (pos js2-ts-cursor)
4094 len name attrs kids
4095 empty-p)))
4096 "AST node for an XML start-tag. Not currently used.
4097 The `kids' field is a Lisp list of child content nodes."
4098 name ; a `js2-xml-name-node'
4099 attrs ; a Lisp list of `js2-xml-attr-node'
4100 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4101
4102 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4103 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4104
4105 (defun js2-visit-xml-start-tag (n v)
4106 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4107 (dolist (attr (js2-xml-start-tag-node-attrs n))
4108 (js2-visit-ast attr v))
4109 (js2-visit-block n v))
4110
4111 (defun js2-print-xml-start-tag (n i)
4112 (insert (js2-make-pad i) "<")
4113 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4114 (when (js2-xml-start-tag-node-attrs n)
4115 (insert " ")
4116 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4117 (insert ">"))
4118
4119 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4120 ;; and add the end-tag to the kids list of the parent as well.
4121 (defstruct (js2-xml-end-tag-node
4122 (:include js2-xml-node)
4123 (:constructor nil)
4124 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4125 (pos js2-ts-cursor)
4126 len name)))
4127 "AST node for an XML end-tag. Not currently used."
4128 name) ; a `js2-xml-name-node'
4129
4130 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4131 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4132
4133 (defun js2-visit-xml-end-tag (n v)
4134 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4135
4136 (defun js2-print-xml-end-tag (n i)
4137 (insert (js2-make-pad i))
4138 (insert "</")
4139 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4140 (insert ">"))
4141
4142 (defstruct (js2-xml-name-node
4143 (:include js2-xml-node)
4144 (:constructor nil)
4145 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4146 (pos js2-ts-cursor)
4147 len namespace kids)))
4148 "AST node for an E4X XML name. Not currently used.
4149 Any XML name can be qualified with a namespace, hence the namespace field.
4150 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4151 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4152 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4153 namespace) ; a `js2-string-node'
4154
4155 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4156 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4157
4158 (defun js2-visit-xml-name-node (n v)
4159 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4160
4161 (defun js2-print-xml-name-node (n i)
4162 (insert (js2-make-pad i))
4163 (when (js2-xml-name-node-namespace n)
4164 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4165 (insert "::"))
4166 (dolist (kid (js2-xml-name-node-kids n))
4167 (js2-print-ast kid 0)))
4168
4169 (defstruct (js2-xml-pi-node
4170 (:include js2-xml-node)
4171 (:constructor nil)
4172 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4173 (pos js2-ts-cursor)
4174 len name attrs)))
4175 "AST node for an E4X XML processing instruction. Not currently used."
4176 name ; a `js2-xml-name-node'
4177 attrs) ; a list of `js2-xml-attr-node'
4178
4179 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4180 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4181
4182 (defun js2-visit-xml-pi-node (n v)
4183 (js2-visit-ast (js2-xml-pi-node-name n) v)
4184 (dolist (attr (js2-xml-pi-node-attrs n))
4185 (js2-visit-ast attr v)))
4186
4187 (defun js2-print-xml-pi-node (n i)
4188 (insert (js2-make-pad i) "<?")
4189 (js2-print-ast (js2-xml-pi-node-name n))
4190 (when (js2-xml-pi-node-attrs n)
4191 (insert " ")
4192 (js2-print-list (js2-xml-pi-node-attrs n)))
4193 (insert "?>"))
4194
4195 (defstruct (js2-xml-cdata-node
4196 (:include js2-xml-node)
4197 (:constructor nil)
4198 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4199 (pos js2-ts-cursor)
4200 len content)))
4201 "AST node for a CDATA escape section. Not currently used."
4202 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4203
4204 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4205 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4206
4207 (defun js2-visit-xml-cdata-node (n v)
4208 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4209
4210 (defun js2-print-xml-cdata-node (n i)
4211 (insert (js2-make-pad i))
4212 (js2-print-ast (js2-xml-cdata-node-content n)))
4213
4214 (defstruct (js2-xml-attr-node
4215 (:include js2-xml-node)
4216 (:constructor nil)
4217 (:constructor make-js2-attr-node (&key (type js2-XML)
4218 (pos js2-ts-cursor)
4219 len name value
4220 eq-pos quote-type)))
4221 "AST node representing a foo='bar' XML attribute value. Not yet used."
4222 name ; a `js2-xml-name-node'
4223 value ; a `js2-xml-name-node'
4224 eq-pos ; buffer position of "=" sign
4225 quote-type) ; 'single or 'double
4226
4227 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4228 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4229
4230 (defun js2-visit-xml-attr-node (n v)
4231 (js2-visit-ast (js2-xml-attr-node-name n) v)
4232 (js2-visit-ast (js2-xml-attr-node-value n) v))
4233
4234 (defun js2-print-xml-attr-node (n i)
4235 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4236 "'"
4237 "\"")))
4238 (insert (js2-make-pad i))
4239 (js2-print-ast (js2-xml-attr-node-name n) 0)
4240 (insert "=" quote)
4241 (js2-print-ast (js2-xml-attr-node-value n) 0)
4242 (insert quote)))
4243
4244 (defstruct (js2-xml-text-node
4245 (:include js2-xml-node)
4246 (:constructor nil)
4247 (:constructor make-js2-text-node (&key (type js2-XML)
4248 (pos js2-ts-cursor)
4249 len content)))
4250 "AST node for an E4X XML text node. Not currently used."
4251 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4252
4253 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4254 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4255
4256 (defun js2-visit-xml-text-node (n v)
4257 (js2-visit-ast (js2-xml-text-node-content n) v))
4258
4259 (defun js2-print-xml-text-node (n i)
4260 (insert (js2-make-pad i))
4261 (dolist (kid (js2-xml-text-node-content n))
4262 (js2-print-ast kid)))
4263
4264 (defstruct (js2-xml-comment-node
4265 (:include js2-xml-node)
4266 (:constructor nil)
4267 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4268 (pos js2-ts-cursor)
4269 len)))
4270 "AST node for E4X XML comment. Not currently used.")
4271
4272 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4273 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4274
4275 (defun js2-print-xml-comment (n i)
4276 (insert (js2-make-pad i)
4277 (js2-node-string n)))
4278
4279 ;;; Node utilities
4280
4281 (defsubst js2-node-line (n)
4282 "Fetch the source line number at the start of node N.
4283 This is O(n) in the length of the source buffer; use prudently."
4284 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4285
4286 (defsubst js2-block-node-kid (n i)
4287 "Return child I of node N, or nil if there aren't that many."
4288 (nth i (js2-block-node-kids n)))
4289
4290 (defsubst js2-block-node-first (n)
4291 "Return first child of block node N, or nil if there is none."
4292 (first (js2-block-node-kids n)))
4293
4294 (defun js2-node-root (n)
4295 "Return the root of the AST containing N.
4296 If N has no parent pointer, returns N."
4297 (let ((parent (js2-node-parent n)))
4298 (if parent
4299 (js2-node-root parent)
4300 n)))
4301
4302 (defsubst js2-node-short-name (n)
4303 "Return the short name of node N as a string, e.g. `js2-if-node'."
4304 (substring (symbol-name (aref n 0))
4305 (length "cl-struct-")))
4306
4307 (defun js2-node-child-list (node)
4308 "Return the child list for NODE, a Lisp list of nodes.
4309 Works for block nodes, array nodes, obj literals, funarg lists,
4310 var decls and try nodes (for catch clauses). Note that you should call
4311 `js2-block-node-kids' on the function body for the body statements.
4312 Returns nil for zero-length child lists or unsupported nodes."
4313 (cond
4314 ((js2-function-node-p node)
4315 (js2-function-node-params node))
4316 ((js2-block-node-p node)
4317 (js2-block-node-kids node))
4318 ((js2-try-node-p node)
4319 (js2-try-node-catch-clauses node))
4320 ((js2-array-node-p node)
4321 (js2-array-node-elems node))
4322 ((js2-object-node-p node)
4323 (js2-object-node-elems node))
4324 ((js2-call-node-p node)
4325 (js2-call-node-args node))
4326 ((js2-new-node-p node)
4327 (js2-new-node-args node))
4328 ((js2-var-decl-node-p node)
4329 (js2-var-decl-node-kids node))
4330 (t
4331 nil)))
4332
4333 (defun js2-node-set-child-list (node kids)
4334 "Set the child list for NODE to KIDS."
4335 (cond
4336 ((js2-function-node-p node)
4337 (setf (js2-function-node-params node) kids))
4338 ((js2-block-node-p node)
4339 (setf (js2-block-node-kids node) kids))
4340 ((js2-try-node-p node)
4341 (setf (js2-try-node-catch-clauses node) kids))
4342 ((js2-array-node-p node)
4343 (setf (js2-array-node-elems node) kids))
4344 ((js2-object-node-p node)
4345 (setf (js2-object-node-elems node) kids))
4346 ((js2-call-node-p node)
4347 (setf (js2-call-node-args node) kids))
4348 ((js2-new-node-p node)
4349 (setf (js2-new-node-args node) kids))
4350 ((js2-var-decl-node-p node)
4351 (setf (js2-var-decl-node-kids node) kids))
4352 (t
4353 (error "Unsupported node type: %s" (js2-node-short-name node))))
4354 kids)
4355
4356 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4357 (defconst js2-paren-expr-nodes
4358 '(cl-struct-js2-comp-loop-node
4359 cl-struct-js2-comp-node
4360 cl-struct-js2-call-node
4361 cl-struct-js2-catch-node
4362 cl-struct-js2-do-node
4363 cl-struct-js2-elem-get-node
4364 cl-struct-js2-for-in-node
4365 cl-struct-js2-for-node
4366 cl-struct-js2-function-node
4367 cl-struct-js2-if-node
4368 cl-struct-js2-let-node
4369 cl-struct-js2-new-node
4370 cl-struct-js2-paren-node
4371 cl-struct-js2-switch-node
4372 cl-struct-js2-while-node
4373 cl-struct-js2-with-node
4374 cl-struct-js2-xml-dot-query-node)
4375 "Node types that can have a parenthesized child expression.
4376 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4377
4378 (defsubst js2-paren-expr-node-p (node)
4379 "Return t for nodes that typically have a parenthesized child expression.
4380 Useful for computing the indentation anchors for arg-lists and conditions.
4381 Note that it may return a false positive, for instance when NODE is
4382 a `js2-new-node' and there are no arguments or parentheses."
4383 (memq (aref node 0) js2-paren-expr-nodes))
4384
4385 ;; Fake polymorphism... yech.
4386 (defun js2-node-lp (node)
4387 "Return relative left-paren position for NODE, if applicable.
4388 For `js2-elem-get-node' structs, returns left-bracket position.
4389 Note that the position may be nil in the case of a parse error."
4390 (cond
4391 ((js2-elem-get-node-p node)
4392 (js2-elem-get-node-lb node))
4393 ((js2-loop-node-p node)
4394 (js2-loop-node-lp node))
4395 ((js2-function-node-p node)
4396 (js2-function-node-lp node))
4397 ((js2-if-node-p node)
4398 (js2-if-node-lp node))
4399 ((js2-new-node-p node)
4400 (js2-new-node-lp node))
4401 ((js2-call-node-p node)
4402 (js2-call-node-lp node))
4403 ((js2-paren-node-p node)
4404 0)
4405 ((js2-switch-node-p node)
4406 (js2-switch-node-lp node))
4407 ((js2-catch-node-p node)
4408 (js2-catch-node-lp node))
4409 ((js2-let-node-p node)
4410 (js2-let-node-lp node))
4411 ((js2-comp-node-p node)
4412 0)
4413 ((js2-with-node-p node)
4414 (js2-with-node-lp node))
4415 ((js2-xml-dot-query-node-p node)
4416 (1+ (js2-infix-node-op-pos node)))
4417 (t
4418 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4419
4420 ;; Fake polymorphism... blech.
4421 (defun js2-node-rp (node)
4422 "Return relative right-paren position for NODE, if applicable.
4423 For `js2-elem-get-node' structs, returns right-bracket position.
4424 Note that the position may be nil in the case of a parse error."
4425 (cond
4426 ((js2-elem-get-node-p node)
4427 (js2-elem-get-node-rb node))
4428 ((js2-loop-node-p node)
4429 (js2-loop-node-rp node))
4430 ((js2-function-node-p node)
4431 (js2-function-node-rp node))
4432 ((js2-if-node-p node)
4433 (js2-if-node-rp node))
4434 ((js2-new-node-p node)
4435 (js2-new-node-rp node))
4436 ((js2-call-node-p node)
4437 (js2-call-node-rp node))
4438 ((js2-paren-node-p node)
4439 (1- (js2-node-len node)))
4440 ((js2-switch-node-p node)
4441 (js2-switch-node-rp node))
4442 ((js2-catch-node-p node)
4443 (js2-catch-node-rp node))
4444 ((js2-let-node-p node)
4445 (js2-let-node-rp node))
4446 ((js2-comp-node-p node)
4447 (1- (js2-node-len node)))
4448 ((js2-with-node-p node)
4449 (js2-with-node-rp node))
4450 ((js2-xml-dot-query-node-p node)
4451 (1+ (js2-xml-dot-query-node-rp node)))
4452 (t
4453 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4454
4455 (defsubst js2-node-first-child (node)
4456 "Return the first element of `js2-node-child-list' for NODE."
4457 (car (js2-node-child-list node)))
4458
4459 (defsubst js2-node-last-child (node)
4460 "Return the last element of `js2-node-last-child' for NODE."
4461 (car (last (js2-node-child-list node))))
4462
4463 (defun js2-node-prev-sibling (node)
4464 "Return the previous statement in parent.
4465 Works for parents supported by `js2-node-child-list'.
4466 Returns nil if NODE is not in the parent, or PARENT is
4467 not a supported node, or if NODE is the first child."
4468 (let* ((p (js2-node-parent node))
4469 (kids (js2-node-child-list p))
4470 (sib (car kids)))
4471 (while (and kids
4472 (not (eq node (cadr kids))))
4473 (setq kids (cdr kids)
4474 sib (car kids)))
4475 sib))
4476
4477 (defun js2-node-next-sibling (node)
4478 "Return the next statement in parent block.
4479 Returns nil if NODE is not in the block, or PARENT is not
4480 a block node, or if NODE is the last statement."
4481 (let* ((p (js2-node-parent node))
4482 (kids (js2-node-child-list p)))
4483 (while (and kids
4484 (not (eq node (car kids))))
4485 (setq kids (cdr kids)))
4486 (cadr kids)))
4487
4488 (defun js2-node-find-child-before (pos parent &optional after)
4489 "Find the last child that starts before POS in parent.
4490 If AFTER is non-nil, returns first child starting after POS.
4491 POS is an absolute buffer position. PARENT is any node
4492 supported by `js2-node-child-list'.
4493 Returns nil if no applicable child is found."
4494 (let ((kids (if (js2-function-node-p parent)
4495 (js2-block-node-kids (js2-function-node-body parent))
4496 (js2-node-child-list parent)))
4497 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4498 (js2-function-node-body parent)
4499 parent)))
4500 kid result fn
4501 (continue t))
4502 (setq fn (if after '>= '<))
4503 (while (and kids continue)
4504 (setq kid (car kids))
4505 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4506 (setq result kid
4507 continue (not after))
4508 (setq continue after))
4509 (setq kids (cdr kids)))
4510 result))
4511
4512 (defun js2-node-find-child-after (pos parent)
4513 "Find first child that starts after POS in parent.
4514 POS is an absolute buffer position. PARENT is any node
4515 supported by `js2-node-child-list'.
4516 Returns nil if no applicable child is found."
4517 (js2-node-find-child-before pos parent 'after))
4518
4519 (defun js2-node-replace-child (pos parent new-node)
4520 "Replace node at index POS in PARENT with NEW-NODE.
4521 Only works for parents supported by `js2-node-child-list'."
4522 (let ((kids (js2-node-child-list parent))
4523 (i 0))
4524 (while (< i pos)
4525 (setq kids (cdr kids)
4526 i (1+ i)))
4527 (setcar kids new-node)
4528 (js2-node-add-children parent new-node)))
4529
4530 (defun js2-node-buffer (n)
4531 "Return the buffer associated with AST N.
4532 Returns nil if the buffer is not set as a property on the root
4533 node, or if parent links were not recorded during parsing."
4534 (let ((root (js2-node-root n)))
4535 (and root
4536 (js2-ast-root-p root)
4537 (js2-ast-root-buffer root))))
4538
4539 (defun js2-block-node-push (n kid)
4540 "Push js2-node KID onto the end of js2-block-node N's child list.
4541 KID is always added to the -end- of the kids list.
4542 Function also calls `js2-node-add-children' to add the parent link."
4543 (let ((kids (js2-node-child-list n)))
4544 (if kids
4545 (setcdr kids (nconc (cdr kids) (list kid)))
4546 (js2-node-set-child-list n (list kid)))
4547 (js2-node-add-children n kid)))
4548
4549 (defun js2-node-string (node)
4550 (with-current-buffer (or (js2-node-buffer node)
4551 (error "No buffer available for node %s" node))
4552 (let ((pos (js2-node-abs-pos node)))
4553 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4554
4555 ;; Container for storing the node we're looking for in a traversal.
4556 (js2-deflocal js2-discovered-node nil)
4557
4558 ;; Keep track of absolute node position during traversals.
4559 (js2-deflocal js2-visitor-offset nil)
4560
4561 (js2-deflocal js2-node-search-point nil)
4562
4563 (when js2-mode-dev-mode-p
4564 (defun js2-find-node-at-point ()
4565 (interactive)
4566 (let ((node (js2-node-at-point)))
4567 (message "%s" (or node "No node found at point"))))
4568 (defun js2-node-name-at-point ()
4569 (interactive)
4570 (let ((node (js2-node-at-point)))
4571 (message "%s" (if node
4572 (js2-node-short-name node)
4573 "No node found at point.")))))
4574
4575 (defun js2-node-at-point (&optional pos skip-comments)
4576 "Return AST node at POS, a buffer position, defaulting to current point.
4577 The `js2-mode-ast' variable must be set to the current parse tree.
4578 Signals an error if the AST (`js2-mode-ast') is nil.
4579 Always returns a node - if it can't find one, it returns the root.
4580 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4581 (let ((ast js2-mode-ast)
4582 result)
4583 (unless ast
4584 (error "No JavaScript AST available"))
4585 ;; Look through comments first, since they may be inside nodes that
4586 ;; would otherwise report a match.
4587 (setq pos (or pos (point))
4588 result (if (> pos (js2-node-abs-end ast))
4589 ast
4590 (if (not skip-comments)
4591 (js2-comment-at-point pos))))
4592 (unless result
4593 (setq js2-discovered-node nil
4594 js2-visitor-offset 0
4595 js2-node-search-point pos)
4596 (unwind-protect
4597 (catch 'js2-visit-done
4598 (js2-visit-ast ast #'js2-node-at-point-visitor))
4599 (setq js2-visitor-offset nil
4600 js2-node-search-point nil))
4601 (setq result js2-discovered-node))
4602 ;; may have found a comment beyond end of last child node,
4603 ;; since visiting the ast-root looks at the comment-list last.
4604 (if (and skip-comments
4605 (js2-comment-node-p result))
4606 (setq result nil))
4607 (or result js2-mode-ast)))
4608
4609 (defun js2-node-at-point-visitor (node end-p)
4610 (let ((rel-pos (js2-node-pos node))
4611 abs-pos
4612 abs-end
4613 (point js2-node-search-point))
4614 (cond
4615 (end-p
4616 ;; this evaluates to a non-nil return value, even if it's zero
4617 (decf js2-visitor-offset rel-pos))
4618 ;; we already looked for comments before visiting, and don't want them now
4619 ((js2-comment-node-p node)
4620 nil)
4621 (t
4622 (setq abs-pos (incf js2-visitor-offset rel-pos)
4623 ;; we only want to use the node if the point is before
4624 ;; the last character position in the node, so we decrement
4625 ;; the absolute end by 1.
4626 abs-end (+ abs-pos (js2-node-len node) -1))
4627 (cond
4628 ;; If this node starts after search-point, stop the search.
4629 ((> abs-pos point)
4630 (throw 'js2-visit-done nil))
4631 ;; If this node ends before the search-point, don't check kids.
4632 ((> point abs-end)
4633 nil)
4634 (t
4635 ;; Otherwise point is within this node, possibly in a child.
4636 (setq js2-discovered-node node)
4637 t)))))) ; keep processing kids to look for more specific match
4638
4639 (defsubst js2-block-comment-p (node)
4640 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4641 (and (js2-comment-node-p node)
4642 (memq (js2-comment-node-format node) '(jsdoc block))))
4643
4644 ;; TODO: put the comments in a vector and binary-search them instead
4645 (defun js2-comment-at-point (&optional pos)
4646 "Look through scanned comment nodes for one containing POS.
4647 POS is a buffer position that defaults to current point.
4648 Function returns nil if POS was not in any comment node."
4649 (let ((ast js2-mode-ast)
4650 (x (or pos (point)))
4651 beg end)
4652 (unless ast
4653 (error "No JavaScript AST available"))
4654 (catch 'done
4655 ;; Comments are stored in lexical order.
4656 (dolist (comment (js2-ast-root-comments ast) nil)
4657 (setq beg (js2-node-abs-pos comment)
4658 end (+ beg (js2-node-len comment)))
4659 (if (and (>= x beg)
4660 (<= x end))
4661 (throw 'done comment))))))
4662
4663 (defun js2-mode-find-parent-fn (node)
4664 "Find function enclosing NODE.
4665 Returns nil if NODE is not inside a function."
4666 (setq node (js2-node-parent node))
4667 (while (and node (not (js2-function-node-p node)))
4668 (setq node (js2-node-parent node)))
4669 (and (js2-function-node-p node) node))
4670
4671 (defun js2-mode-find-enclosing-fn (node)
4672 "Find function or root enclosing NODE."
4673 (if (js2-ast-root-p node)
4674 node
4675 (setq node (js2-node-parent node))
4676 (while (not (or (js2-ast-root-p node)
4677 (js2-function-node-p node)))
4678 (setq node (js2-node-parent node)))
4679 node))
4680
4681 (defun js2-mode-find-enclosing-node (beg end)
4682 "Find node fully enclosing BEG and END."
4683 (let ((node (js2-node-at-point beg))
4684 pos
4685 (continue t))
4686 (while continue
4687 (if (or (js2-ast-root-p node)
4688 (and
4689 (<= (setq pos (js2-node-abs-pos node)) beg)
4690 (>= (+ pos (js2-node-len node)) end)))
4691 (setq continue nil)
4692 (setq node (js2-node-parent node))))
4693 node))
4694
4695 (defun js2-node-parent-script-or-fn (node)
4696 "Find script or function immediately enclosing NODE.
4697 If NODE is the ast-root, returns nil."
4698 (if (js2-ast-root-p node)
4699 nil
4700 (setq node (js2-node-parent node))
4701 (while (and node (not (or (js2-function-node-p node)
4702 (js2-script-node-p node))))
4703 (setq node (js2-node-parent node)))
4704 node))
4705
4706 (defun js2-node-is-descendant (node ancestor)
4707 "Return t if NODE is a descendant of ANCESTOR."
4708 (while (and node
4709 (not (eq node ancestor)))
4710 (setq node (js2-node-parent node)))
4711 node)
4712
4713 ;;; visitor infrastructure
4714
4715 (defun js2-visit-none (_node _callback)
4716 "Visitor for AST node that have no node children."
4717 nil)
4718
4719 (defun js2-print-none (_node _indent)
4720 "Visitor for AST node with no printed representation.")
4721
4722 (defun js2-print-body (node indent)
4723 "Print a statement, or a block without braces."
4724 (if (js2-block-node-p node)
4725 (dolist (kid (js2-block-node-kids node))
4726 (js2-print-ast kid indent))
4727 (js2-print-ast node indent)))
4728
4729 (defun js2-print-list (args &optional delimiter)
4730 (loop with len = (length args)
4731 for arg in args
4732 for count from 1
4733 do
4734 (when arg (js2-print-ast arg 0))
4735 (if (< count len)
4736 (insert (or delimiter ", ")))))
4737
4738 (defun js2-print-tree (ast)
4739 "Prints an AST to the current buffer.
4740 Makes `js2-ast-parent-nodes' available to the printer functions."
4741 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4742 (js2-print-ast ast)))
4743
4744 (defun js2-print-ast (node &optional indent)
4745 "Helper function for printing AST nodes.
4746 Requires `js2-ast-parent-nodes' to be non-nil.
4747 You should use `js2-print-tree' instead of this function."
4748 (let ((printer (get (aref node 0) 'js2-printer))
4749 (i (or indent 0)))
4750 ;; TODO: wedge comments in here somewhere
4751 (if printer
4752 (funcall printer node i))))
4753
4754 (defconst js2-side-effecting-tokens
4755 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4756 (dolist (tt (list js2-ASSIGN
4757 js2-ASSIGN_ADD
4758 js2-ASSIGN_BITAND
4759 js2-ASSIGN_BITOR
4760 js2-ASSIGN_BITXOR
4761 js2-ASSIGN_DIV
4762 js2-ASSIGN_LSH
4763 js2-ASSIGN_MOD
4764 js2-ASSIGN_MUL
4765 js2-ASSIGN_RSH
4766 js2-ASSIGN_SUB
4767 js2-ASSIGN_URSH
4768 js2-BLOCK
4769 js2-BREAK
4770 js2-CALL
4771 js2-CATCH
4772 js2-CATCH_SCOPE
4773 js2-CLASS
4774 js2-CONST
4775 js2-CONTINUE
4776 js2-DEBUGGER
4777 js2-DEC
4778 js2-DELPROP
4779 js2-DEL_REF
4780 js2-DO
4781 js2-ELSE
4782 js2-EMPTY
4783 js2-ENTERWITH
4784 js2-EXPORT
4785 js2-EXPR_RESULT
4786 js2-FINALLY
4787 js2-FOR
4788 js2-FUNCTION
4789 js2-GOTO
4790 js2-IF
4791 js2-IFEQ
4792 js2-IFNE
4793 js2-IMPORT
4794 js2-INC
4795 js2-JSR
4796 js2-LABEL
4797 js2-LEAVEWITH
4798 js2-LET
4799 js2-LETEXPR
4800 js2-LOCAL_BLOCK
4801 js2-LOOP
4802 js2-NEW
4803 js2-REF_CALL
4804 js2-RETHROW
4805 js2-RETURN
4806 js2-RETURN_RESULT
4807 js2-SEMI
4808 js2-SETELEM
4809 js2-SETELEM_OP
4810 js2-SETNAME
4811 js2-SETPROP
4812 js2-SETPROP_OP
4813 js2-SETVAR
4814 js2-SET_REF
4815 js2-SET_REF_OP
4816 js2-SWITCH
4817 js2-TARGET
4818 js2-THROW
4819 js2-TRY
4820 js2-VAR
4821 js2-WHILE
4822 js2-WITH
4823 js2-WITHEXPR
4824 js2-YIELD))
4825 (aset tokens tt t))
4826 (if js2-instanceof-has-side-effects
4827 (aset tokens js2-INSTANCEOF t))
4828 tokens))
4829
4830 (defun js2-node-has-side-effects (node)
4831 "Return t if NODE has side effects."
4832 (when node ; makes it easier to handle malformed expressions
4833 (let ((tt (js2-node-type node)))
4834 (cond
4835 ;; This doubtless needs some work, since EXPR_VOID is used
4836 ;; in several ways in Rhino and I may not have caught them all.
4837 ;; I'll wait for people to notice incorrect warnings.
4838 ((and (= tt js2-EXPR_VOID)
4839 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4840 (let ((expr (js2-expr-stmt-node-expr node)))
4841 (or (js2-node-has-side-effects expr)
4842 (when (js2-string-node-p expr)
4843 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4844 ((= tt js2-COMMA)
4845 (js2-node-has-side-effects (js2-infix-node-right node)))
4846 ((or (= tt js2-AND)
4847 (= tt js2-OR))
4848 (or (js2-node-has-side-effects (js2-infix-node-right node))
4849 (js2-node-has-side-effects (js2-infix-node-left node))))
4850 ((= tt js2-HOOK)
4851 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4852 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4853 ((js2-paren-node-p node)
4854 (js2-node-has-side-effects (js2-paren-node-expr node)))
4855 ((= tt js2-ERROR) ; avoid cascaded error messages
4856 nil)
4857 (t
4858 (aref js2-side-effecting-tokens tt))))))
4859
4860 (defconst js2-stmt-node-types
4861 (list js2-BLOCK
4862 js2-BREAK
4863 js2-CONTINUE
4864 js2-DEFAULT ; e4x "default xml namespace" statement
4865 js2-DO
4866 js2-EXPR_RESULT
4867 js2-EXPR_VOID
4868 js2-FOR
4869 js2-IF
4870 js2-RETURN
4871 js2-SWITCH
4872 js2-THROW
4873 js2-TRY
4874 js2-WHILE
4875 js2-WITH)
4876 "Node types that only appear in statement contexts.
4877 The list does not include nodes that always appear as the child
4878 of another specific statement type, such as switch-cases,
4879 catch and finally blocks, and else-clauses. The list also excludes
4880 nodes like yield, let and var, which may appear in either expression
4881 or statement context, and in the latter context always have a
4882 `js2-expr-stmt-node' parent. Finally, the list does not include
4883 functions or scripts, which are treated separately from statements
4884 by the JavaScript parser and runtime.")
4885
4886 (defun js2-stmt-node-p (node)
4887 "Heuristic for figuring out if NODE is a statement.
4888 Some node types can appear in either an expression context or a
4889 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4890 For these node types in a statement context, the parent will be a
4891 `js2-expr-stmt-node'.
4892 Functions aren't included in the check."
4893 (memq (js2-node-type node) js2-stmt-node-types))
4894
4895 (defun js2-mode-find-first-stmt (node)
4896 "Search upward starting from NODE looking for a statement.
4897 For purposes of this function, a `js2-function-node' counts."
4898 (while (not (or (js2-stmt-node-p node)
4899 (js2-function-node-p node)))
4900 (setq node (js2-node-parent node)))
4901 node)
4902
4903 (defun js2-node-parent-stmt (node)
4904 "Return the node's first ancestor that is a statement.
4905 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4906 appearing in a statement context will have a parent that is a
4907 `js2-expr-stmt-node' that will be returned by this function."
4908 (let ((parent (js2-node-parent node)))
4909 (if (or (null parent)
4910 (js2-stmt-node-p parent)
4911 (and (js2-function-node-p parent)
4912 (not (eq (js2-function-node-form parent)
4913 'FUNCTION_EXPRESSION))))
4914 parent
4915 (js2-node-parent-stmt parent))))
4916
4917 ;; In the Mozilla Rhino sources, Roshan James writes:
4918 ;; Does consistent-return analysis on the function body when strict mode is
4919 ;; enabled.
4920 ;;
4921 ;; function (x) { return (x+1) }
4922 ;;
4923 ;; is ok, but
4924 ;;
4925 ;; function (x) { if (x < 0) return (x+1); }
4926 ;;
4927 ;; is not because the function can potentially return a value when the
4928 ;; condition is satisfied and if not, the function does not explicitly
4929 ;; return a value.
4930 ;;
4931 ;; This extends to checking mismatches such as "return" and "return <value>"
4932 ;; used in the same function. Warnings are not emitted if inconsistent
4933 ;; returns exist in code that can be statically shown to be unreachable.
4934 ;; Ex.
4935 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4936 ;;
4937 ;; emits no warning. However if the loop had a break statement, then a
4938 ;; warning would be emitted.
4939 ;;
4940 ;; The consistency analysis looks at control structures such as loops, ifs,
4941 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4942 ;; warns the user about an inconsistent set of termination possibilities.
4943 ;;
4944 ;; These flags enumerate the possible ways a statement/function can
4945 ;; terminate. These flags are used by endCheck() and by the Parser to
4946 ;; detect inconsistent return usage.
4947 ;;
4948 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4949 ;; able to execute (example: throw, continue)
4950 ;;
4951 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4952 ;; next one. Statement such as return dont. A compound statement may have
4953 ;; some branch that drops off control to the next statement.
4954 ;;
4955 ;; END_RETURNS indicates that the statement can return with no value.
4956 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4957 ;;
4958 ;; A compound statement such as
4959 ;; if (condition) {
4960 ;; return value;
4961 ;; }
4962 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4963
4964 (defconst js2-END_UNREACHED 0)
4965 (defconst js2-END_DROPS_OFF 1)
4966 (defconst js2-END_RETURNS 2)
4967 (defconst js2-END_RETURNS_VALUE 4)
4968 (defconst js2-END_YIELDS 8)
4969
4970 (defun js2-has-consistent-return-usage (node)
4971 "Check that every return usage in a function body is consistent.
4972 Returns t if the function satisfies strict mode requirement."
4973 (let ((n (js2-end-check node)))
4974 ;; either it doesn't return a value in any branch...
4975 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4976 ;; or it returns a value (or is unreached) at every branch
4977 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4978 js2-END_RETURNS
4979 js2-END_YIELDS)))))
4980
4981 (defun js2-end-check-if (node)
4982 "Ensure that return usage in then/else blocks is consistent.
4983 If there is no else block, then the return statement can fall through.
4984 Returns logical OR of END_* flags"
4985 (let ((th (js2-if-node-then-part node))
4986 (el (js2-if-node-else-part node)))
4987 (if (null th)
4988 js2-END_UNREACHED
4989 (logior (js2-end-check th) (if el
4990 (js2-end-check el)
4991 js2-END_DROPS_OFF)))))
4992
4993 (defun js2-end-check-switch (node)
4994 "Consistency of return statements is checked between the case statements.
4995 If there is no default, then the switch can fall through. If there is a
4996 default, we check to see if all code paths in the default return or if
4997 there is a code path that can fall through.
4998 Returns logical OR of END_* flags."
4999 (let ((rv js2-END_UNREACHED)
5000 default-case)
5001 ;; examine the cases
5002 (catch 'break
5003 (dolist (c (js2-switch-node-cases node))
5004 (if (js2-case-node-expr c)
5005 (js2-set-flag rv (js2-end-check-block c))
5006 (setq default-case c)
5007 (throw 'break nil))))
5008 ;; we don't care how the cases drop into each other
5009 (js2-clear-flag rv js2-END_DROPS_OFF)
5010 ;; examine the default
5011 (js2-set-flag rv (if default-case
5012 (js2-end-check default-case)
5013 js2-END_DROPS_OFF))
5014 rv))
5015
5016 (defun js2-end-check-try (node)
5017 "If the block has a finally, return consistency is checked in the
5018 finally block. If all code paths in the finally return, then the
5019 returns in the try-catch blocks don't matter. If there is a code path
5020 that does not return or if there is no finally block, the returns
5021 of the try and catch blocks are checked for mismatch.
5022 Returns logical OR of END_* flags."
5023 (let ((finally (js2-try-node-finally-block node))
5024 rv)
5025 ;; check the finally if it exists
5026 (setq rv (if finally
5027 (js2-end-check (js2-finally-node-body finally))
5028 js2-END_DROPS_OFF))
5029 ;; If the finally block always returns, then none of the returns
5030 ;; in the try or catch blocks matter.
5031 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5032 (js2-clear-flag rv js2-END_DROPS_OFF)
5033 ;; examine the try block
5034 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5035 ;; check each catch block
5036 (dolist (cb (js2-try-node-catch-clauses node))
5037 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5038 rv))
5039
5040 (defun js2-end-check-loop (node)
5041 "Return statement in the loop body must be consistent.
5042 The default assumption for any kind of a loop is that it will eventually
5043 terminate. The only exception is a loop with a constant true condition.
5044 Code that follows such a loop is examined only if one can determine
5045 statically that there is a break out of the loop.
5046
5047 for(... ; ... ; ...) {}
5048 for(... in ... ) {}
5049 while(...) { }
5050 do { } while(...)
5051
5052 Returns logical OR of END_* flags."
5053 (let ((rv (js2-end-check (js2-loop-node-body node)))
5054 (condition (cond
5055 ((js2-while-node-p node)
5056 (js2-while-node-condition node))
5057 ((js2-do-node-p node)
5058 (js2-do-node-condition node))
5059 ((js2-for-node-p node)
5060 (js2-for-node-condition node)))))
5061
5062 ;; check to see if the loop condition is always true
5063 (if (and condition
5064 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5065 (js2-clear-flag rv js2-END_DROPS_OFF))
5066
5067 ;; look for effect of breaks
5068 (js2-set-flag rv (js2-node-get-prop node
5069 'CONTROL_BLOCK_PROP
5070 js2-END_UNREACHED))
5071 rv))
5072
5073 (defun js2-end-check-block (node)
5074 "A general block of code is examined statement by statement.
5075 If any statement (even a compound one) returns in all branches, then
5076 subsequent statements are not examined.
5077 Returns logical OR of END_* flags."
5078 (let* ((rv js2-END_DROPS_OFF)
5079 (kids (js2-block-node-kids node))
5080 (n (car kids)))
5081 ;; Check each statment. If the statement can continue onto the next
5082 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5083 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5084 (js2-clear-flag rv js2-END_DROPS_OFF)
5085 (js2-set-flag rv (js2-end-check n))
5086 (setq kids (cdr kids)
5087 n (car kids)))
5088 rv))
5089
5090 (defun js2-end-check-label (node)
5091 "A labeled statement implies that there may be a break to the label.
5092 The function processes the labeled statement and then checks the
5093 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5094 particular label.
5095 Returns logical OR of END_* flags."
5096 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5097 (logior rv (js2-node-get-prop node
5098 'CONTROL_BLOCK_PROP
5099 js2-END_UNREACHED))))
5100
5101 (defun js2-end-check-break (node)
5102 "When a break is encountered annotate the statement being broken
5103 out of by setting its CONTROL_BLOCK_PROP property.
5104 Returns logical OR of END_* flags."
5105 (and (js2-break-node-target node)
5106 (js2-node-set-prop (js2-break-node-target node)
5107 'CONTROL_BLOCK_PROP
5108 js2-END_DROPS_OFF))
5109 js2-END_UNREACHED)
5110
5111 (defun js2-end-check (node)
5112 "Examine the body of a function, doing a basic reachability analysis.
5113 Returns a combination of flags END_* flags that indicate
5114 how the function execution can terminate. These constitute only the
5115 pessimistic set of termination conditions. It is possible that at
5116 runtime certain code paths will never be actually taken. Hence this
5117 analysis will flag errors in cases where there may not be errors.
5118 Returns logical OR of END_* flags"
5119 (let (kid)
5120 (cond
5121 ((js2-break-node-p node)
5122 (js2-end-check-break node))
5123 ((js2-expr-stmt-node-p node)
5124 (if (setq kid (js2-expr-stmt-node-expr node))
5125 (js2-end-check kid)
5126 js2-END_DROPS_OFF))
5127 ((or (js2-continue-node-p node)
5128 (js2-throw-node-p node))
5129 js2-END_UNREACHED)
5130 ((js2-return-node-p node)
5131 (if (setq kid (js2-return-node-retval node))
5132 js2-END_RETURNS_VALUE
5133 js2-END_RETURNS))
5134 ((js2-loop-node-p node)
5135 (js2-end-check-loop node))
5136 ((js2-switch-node-p node)
5137 (js2-end-check-switch node))
5138 ((js2-labeled-stmt-node-p node)
5139 (js2-end-check-label node))
5140 ((js2-if-node-p node)
5141 (js2-end-check-if node))
5142 ((js2-try-node-p node)
5143 (js2-end-check-try node))
5144 ((js2-block-node-p node)
5145 (if (null (js2-block-node-kids node))
5146 js2-END_DROPS_OFF
5147 (js2-end-check-block node)))
5148 ((js2-yield-node-p node)
5149 js2-END_YIELDS)
5150 (t
5151 js2-END_DROPS_OFF))))
5152
5153 (defun js2-always-defined-boolean-p (node)
5154 "Check if NODE always evaluates to true or false in boolean context.
5155 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5156 nor always false."
5157 (let ((tt (js2-node-type node))
5158 num)
5159 (cond
5160 ((or (= tt js2-FALSE) (= tt js2-NULL))
5161 'ALWAYS_FALSE)
5162 ((= tt js2-TRUE)
5163 'ALWAYS_TRUE)
5164 ((= tt js2-NUMBER)
5165 (setq num (js2-number-node-num-value node))
5166 (if (and (not (eq num 0.0e+NaN))
5167 (not (zerop num)))
5168 'ALWAYS_TRUE
5169 'ALWAYS_FALSE))
5170 (t
5171 nil))))
5172
5173 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5174 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5175
5176 (defvar js2-tokens nil
5177 "List of all defined token names.") ; initialized in `js2-token-names'
5178
5179 (defconst js2-token-names
5180 (let* ((names (make-vector js2-num-tokens -1))
5181 (case-fold-search nil) ; only match js2-UPPER_CASE
5182 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5183 (loop for sym in syms
5184 for i from 0
5185 do
5186 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5187 (not (boundp sym)))
5188 (aset names (symbol-value sym) ; code, e.g. 152
5189 (downcase
5190 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5191 (push sym js2-tokens)))
5192 names)
5193 "Vector mapping int values to token string names, sans `js2-' prefix.")
5194
5195 (defun js2-tt-name (tok)
5196 "Return a string name for TOK, a token symbol or code.
5197 Signals an error if it's not a recognized token."
5198 (let ((code tok))
5199 (if (symbolp tok)
5200 (setq code (symbol-value tok)))
5201 (if (eq code -1)
5202 "ERROR"
5203 (if (and (numberp code)
5204 (not (minusp code))
5205 (< code js2-num-tokens))
5206 (aref js2-token-names code)
5207 (error "Invalid token: %s" code)))))
5208
5209 (defsubst js2-tt-sym (tok)
5210 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5211 (intern (js2-tt-name tok)))
5212
5213 (defconst js2-token-codes
5214 (let ((table (make-hash-table :test 'eq :size 256)))
5215 (loop for name across js2-token-names
5216 for sym = (intern (concat "js2-" (upcase name)))
5217 do
5218 (puthash sym (symbol-value sym) table))
5219 ;; clean up a few that are "wrong" in Rhino's token codes
5220 (puthash 'js2-DELETE js2-DELPROP table)
5221 table)
5222 "Hashtable mapping token type symbols to their bytecodes.")
5223
5224 (defsubst js2-tt-code (sym)
5225 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5226 (or (gethash sym js2-token-codes)
5227 (error "Invalid token symbol: %s " sym))) ; signal code bug
5228
5229 (defun js2-report-scan-error (msg &optional no-throw beg len)
5230 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5231 (js2-report-error msg nil
5232 (or beg (js2-current-token-beg))
5233 (or len (js2-current-token-len)))
5234 (unless no-throw
5235 (throw 'return js2-ERROR)))
5236
5237 (defun js2-set-string-from-buffer (token)
5238 "Set `string' and `end' slots for TOKEN, return the string."
5239 (setf (js2-token-end token) js2-ts-cursor
5240 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5241
5242 ;; TODO: could potentially avoid a lot of consing by allocating a
5243 ;; char buffer the way Rhino does.
5244 (defsubst js2-add-to-string (c)
5245 (push c js2-ts-string-buffer))
5246
5247 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5248 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5249 ;; any other character: when it's not part of the current token, we
5250 ;; unget it, allowing it to be read again by the following call.
5251 (defsubst js2-unget-char ()
5252 (decf js2-ts-cursor))
5253
5254 ;; Rhino distinguishes \r and \n line endings. We don't need to
5255 ;; because we only scan from Emacs buffers, which always use \n.
5256 (defun js2-get-char ()
5257 "Read and return the next character from the input buffer.
5258 Increments `js2-ts-lineno' if the return value is a newline char.
5259 Updates `js2-ts-cursor' to the point after the returned char.
5260 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5261 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5262 (let (c)
5263 ;; check for end of buffer
5264 (if (>= js2-ts-cursor (point-max))
5265 (setq js2-ts-hit-eof t
5266 js2-ts-cursor (1+ js2-ts-cursor)
5267 c js2-EOF_CHAR) ; return value
5268 ;; otherwise read next char
5269 (setq c (char-before (incf js2-ts-cursor)))
5270 ;; if we read a newline, update counters
5271 (if (= c ?\n)
5272 (setq js2-ts-line-start js2-ts-cursor
5273 js2-ts-lineno (1+ js2-ts-lineno)))
5274 ;; TODO: skip over format characters
5275 c)))
5276
5277 (defun js2-read-unicode-escape ()
5278 "Read a \\uNNNN sequence from the input.
5279 Assumes the ?\ and ?u have already been read.
5280 Returns the unicode character, or nil if it wasn't a valid character.
5281 Doesn't change the values of any scanner variables."
5282 ;; I really wish I knew a better way to do this, but I can't
5283 ;; find the Emacs function that takes a 16-bit int and converts
5284 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5285 ;; Have to first check that it's 4 hex characters or it may stop
5286 ;; the read early.
5287 (ignore-errors
5288 (let ((s (buffer-substring-no-properties js2-ts-cursor
5289 (+ 4 js2-ts-cursor))))
5290 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5291 (read (concat "?\\u" s))))))
5292
5293 (defun js2-match-char (test)
5294 "Consume and return next character if it matches TEST, a character.
5295 Returns nil and consumes nothing if TEST is not the next character."
5296 (let ((c (js2-get-char)))
5297 (if (eq c test)
5298 t
5299 (js2-unget-char)
5300 nil)))
5301
5302 (defun js2-peek-char ()
5303 (prog1
5304 (js2-get-char)
5305 (js2-unget-char)))
5306
5307 (defun js2-identifier-start-p (c)
5308 "Is C a valid start to an ES5 Identifier?
5309 See http://es5.github.io/#x7.6"
5310 (or
5311 (memq c '(?$ ?_))
5312 (memq (get-char-code-property c 'general-category)
5313 ;; Letters
5314 '(Lu Ll Lt Lm Lo Nl))))
5315
5316 (defun js2-identifier-part-p (c)
5317 "Is C a valid part of an ES5 Identifier?
5318 See http://es5.github.io/#x7.6"
5319 (or
5320 (memq c '(?$ ?_ ?\u200c ?\u200d))
5321 (memq (get-char-code-property c 'general-category)
5322 '(;; Letters
5323 Lu Ll Lt Lm Lo Nl
5324 ;; Combining Marks
5325 Mn Mc
5326 ;; Digits
5327 Nd
5328 ;; Connector Punctuation
5329 Pc))))
5330
5331 (defun js2-alpha-p (c)
5332 (cond ((and (<= ?A c) (<= c ?Z)) t)
5333 ((and (<= ?a c) (<= c ?z)) t)
5334 (t nil)))
5335
5336 (defsubst js2-digit-p (c)
5337 (and (<= ?0 c) (<= c ?9)))
5338
5339 (defun js2-js-space-p (c)
5340 (if (<= c 127)
5341 (memq c '(#x20 #x9 #xB #xC #xD))
5342 (or
5343 (eq c #xA0)
5344 ;; TODO: change this nil to check for Unicode space character
5345 nil)))
5346
5347 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5348
5349 (defun js2-skip-line ()
5350 "Skip to end of line."
5351 (while (not (memq (js2-get-char) js2-eol-chars)))
5352 (js2-unget-char)
5353 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5354 (setq js2-token-end js2-ts-cursor))
5355
5356 (defun js2-init-scanner (&optional buf line)
5357 "Create token stream for BUF starting on LINE.
5358 BUF defaults to `current-buffer' and LINE defaults to 1.
5359
5360 A buffer can only have one scanner active at a time, which yields
5361 dramatically simpler code than using a defstruct. If you need to
5362 have simultaneous scanners in a buffer, copy the regions to scan
5363 into temp buffers."
5364 (with-current-buffer (or buf (current-buffer))
5365 (setq js2-ts-dirty-line nil
5366 js2-ts-hit-eof nil
5367 js2-ts-line-start 0
5368 js2-ts-lineno (or line 1)
5369 js2-ts-line-end-char -1
5370 js2-ts-cursor (point-min)
5371 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5372 js2-ti-tokens-cursor 0
5373 js2-ti-lookahead 0
5374 js2-ts-is-xml-attribute nil
5375 js2-ts-xml-is-tag-content nil
5376 js2-ts-xml-open-tags-count 0
5377 js2-ts-string-buffer nil)))
5378
5379 ;; This function uses the cached op, string and number fields in
5380 ;; TokenStream; if getToken has been called since the passed token
5381 ;; was scanned, the op or string printed may be incorrect.
5382 (defun js2-token-to-string (token)
5383 ;; Not sure where this function is used in Rhino. Not tested.
5384 (if (not js2-debug-print-trees)
5385 ""
5386 (let ((name (js2-tt-name token)))
5387 (cond
5388 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5389 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5390 (concat name " `" (js2-current-token-string) "'"))
5391 ((eq token js2-NUMBER)
5392 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5393 (t
5394 name)))))
5395
5396 (defconst js2-keywords
5397 '(break
5398 case catch class const continue
5399 debugger default delete do
5400 else extends
5401 false finally for function
5402 if in instanceof import
5403 let
5404 new null
5405 return
5406 static super switch
5407 this throw true try typeof
5408 var void
5409 while with
5410 yield))
5411
5412 ;; Token names aren't exactly the same as the keywords, unfortunately.
5413 ;; E.g. delete is js2-DELPROP.
5414 (defconst js2-kwd-tokens
5415 (let ((table (make-vector js2-num-tokens nil))
5416 (tokens
5417 (list js2-BREAK
5418 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5419 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5420 js2-ELSE js2-EXTENDS
5421 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5422 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5423 js2-LET
5424 js2-NEW js2-NULL
5425 js2-RETURN
5426 js2-STATIC js2-SUPER js2-SWITCH
5427 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5428 js2-VAR
5429 js2-WHILE js2-WITH
5430 js2-YIELD)))
5431 (dolist (i tokens)
5432 (aset table i 'font-lock-keyword-face))
5433 (aset table js2-STRING 'font-lock-string-face)
5434 (aset table js2-REGEXP 'font-lock-string-face)
5435 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5436 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5437 (aset table js2-COMMENT 'font-lock-comment-face)
5438 (aset table js2-THIS 'font-lock-builtin-face)
5439 (aset table js2-SUPER 'font-lock-builtin-face)
5440 (aset table js2-VOID 'font-lock-constant-face)
5441 (aset table js2-NULL 'font-lock-constant-face)
5442 (aset table js2-TRUE 'font-lock-constant-face)
5443 (aset table js2-FALSE 'font-lock-constant-face)
5444 (aset table js2-NOT 'font-lock-negation-char-face)
5445 table)
5446 "Vector whose values are non-nil for tokens that are keywords.
5447 The values are default faces to use for highlighting the keywords.")
5448
5449 ;; FIXME: Support strict mode-only future reserved words, after we know
5450 ;; which parts scopes are in strict mode, and which are not.
5451 (defconst js2-reserved-words '(class enum export extends import super)
5452 "Future reserved keywords in ECMAScript 5.1.")
5453
5454 (defconst js2-keyword-names
5455 (let ((table (make-hash-table :test 'equal)))
5456 (loop for k in js2-keywords
5457 do (puthash
5458 (symbol-name k) ; instanceof
5459 (intern (concat "js2-"
5460 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5461 table))
5462 table)
5463 "JavaScript keywords by name, mapped to their symbols.")
5464
5465 (defconst js2-reserved-word-names
5466 (let ((table (make-hash-table :test 'equal)))
5467 (loop for k in js2-reserved-words
5468 do
5469 (puthash (symbol-name k) 'js2-RESERVED table))
5470 table)
5471 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5472
5473 (defun js2-collect-string (buf)
5474 "Convert BUF, a list of chars, to a string.
5475 Reverses BUF before converting."
5476 (if buf
5477 (apply #'string (nreverse buf))
5478 ""))
5479
5480 (defun js2-string-to-keyword (s)
5481 "Return token for S, a string, if S is a keyword or reserved word.
5482 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5483 (or (gethash s js2-keyword-names)
5484 (gethash s js2-reserved-word-names)))
5485
5486 (defsubst js2-ts-set-char-token-bounds (token)
5487 "Used when next token is one character."
5488 (setf (js2-token-beg token) (1- js2-ts-cursor)
5489 (js2-token-end token) js2-ts-cursor))
5490
5491 (defsubst js2-ts-return (token type)
5492 "Update the `end' and `type' slots of TOKEN,
5493 then throw `return' with value TYPE."
5494 (setf (js2-token-end token) js2-ts-cursor
5495 (js2-token-type token) type)
5496 (throw 'return type))
5497
5498 (defun js2-x-digit-to-int (c accumulator)
5499 "Build up a hex number.
5500 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5501 corresponding number. Otherwise return -1."
5502 (catch 'return
5503 (catch 'check
5504 ;; Use 0..9 < A..Z < a..z
5505 (cond
5506 ((<= c ?9)
5507 (decf c ?0)
5508 (if (<= 0 c)
5509 (throw 'check nil)))
5510 ((<= c ?F)
5511 (when (<= ?A c)
5512 (decf c (- ?A 10))
5513 (throw 'check nil)))
5514 ((<= c ?f)
5515 (when (<= ?a c)
5516 (decf c (- ?a 10))
5517 (throw 'check nil))))
5518 (throw 'return -1))
5519 (logior c (lsh accumulator 4))))
5520
5521 (defun js2-get-token (&optional modifier)
5522 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5523 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5524 next saved token.
5525
5526 This function will not return a newline (js2-EOL) - instead, it
5527 gobbles newlines until it finds a non-newline token. Call
5528 `js2-peek-token-or-eol' when you care about newlines.
5529
5530 This function will also not return a js2-COMMENT. Instead, it
5531 records comments found in `js2-scanned-comments'. If the token
5532 returned by this function immediately follows a jsdoc comment,
5533 the token is flagged as such."
5534 (if (zerop js2-ti-lookahead)
5535 (js2-get-token-internal modifier)
5536 (decf js2-ti-lookahead)
5537 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5538 (let ((tt (js2-current-token-type)))
5539 (assert (not (= tt js2-EOL)))
5540 tt)))
5541
5542 (defun js2-unget-token ()
5543 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5544 (incf js2-ti-lookahead)
5545 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5546
5547 (defun js2-get-token-internal (modifier)
5548 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5549 (tt (js2-token-type token))
5550 saw-eol
5551 face)
5552 ;; process comments
5553 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5554 (if (= tt js2-EOL)
5555 (setq saw-eol t)
5556 (setq saw-eol nil)
5557 (when js2-record-comments
5558 (js2-record-comment token)))
5559 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5560 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5561 tt (js2-token-type token)))
5562
5563 (when saw-eol
5564 (setf (js2-token-follows-eol-p token) t))
5565
5566 ;; perform lexical fontification as soon as token is scanned
5567 (when js2-parse-ide-mode
5568 (cond
5569 ((minusp tt)
5570 (js2-record-face 'js2-error token))
5571 ((setq face (aref js2-kwd-tokens tt))
5572 (js2-record-face face token))
5573 ((and (= tt js2-NAME)
5574 (equal (js2-token-string token) "undefined"))
5575 (js2-record-face 'font-lock-constant-face token))))
5576 tt))
5577
5578 (defun js2-get-token-internal-1 (modifier)
5579 "Return next JavaScript token type, an int such as js2-RETURN.
5580 During operation, creates an instance of `js2-token' struct, sets
5581 its relevant fields and puts it into `js2-ti-tokens'."
5582 (let (c c1 identifier-start is-unicode-escape-start
5583 contains-escape escape-val str result base
5584 quote-char val look-for-slash continue tt
5585 (token (js2-new-token 0)))
5586 (setq
5587 tt
5588 (catch 'return
5589 (when (eq modifier 'TEMPLATE_TAIL)
5590 (setf (js2-token-beg token) (1- js2-ts-cursor))
5591 (throw 'return (js2-get-string-or-template-token ?` token)))
5592 (while t
5593 ;; Eat whitespace, possibly sensitive to newlines.
5594 (setq continue t)
5595 (while continue
5596 (setq c (js2-get-char))
5597 (cond
5598 ((eq c js2-EOF_CHAR)
5599 (js2-unget-char)
5600 (js2-ts-set-char-token-bounds token)
5601 (throw 'return js2-EOF))
5602 ((eq c ?\n)
5603 (js2-ts-set-char-token-bounds token)
5604 (setq js2-ts-dirty-line nil)
5605 (throw 'return js2-EOL))
5606 ((not (js2-js-space-p c))
5607 (if (/= c ?-) ; in case end of HTML comment
5608 (setq js2-ts-dirty-line t))
5609 (setq continue nil))))
5610 ;; Assume the token will be 1 char - fixed up below.
5611 (js2-ts-set-char-token-bounds token)
5612 (when (eq c ?@)
5613 (throw 'return js2-XMLATTR))
5614 ;; identifier/keyword/instanceof?
5615 ;; watch out for starting with a <backslash>
5616 (cond
5617 ((eq c ?\\)
5618 (setq c (js2-get-char))
5619 (if (eq c ?u)
5620 (setq identifier-start t
5621 is-unicode-escape-start t
5622 js2-ts-string-buffer nil)
5623 (setq identifier-start nil)
5624 (js2-unget-char)
5625 (setq c ?\\)))
5626 (t
5627 (when (setq identifier-start (js2-identifier-start-p c))
5628 (setq js2-ts-string-buffer nil)
5629 (js2-add-to-string c))))
5630 (when identifier-start
5631 (setq contains-escape is-unicode-escape-start)
5632 (catch 'break
5633 (while t
5634 (if is-unicode-escape-start
5635 ;; strictly speaking we should probably push-back
5636 ;; all the bad characters if the <backslash>uXXXX
5637 ;; sequence is malformed. But since there isn't a
5638 ;; correct context(is there?) for a bad Unicode
5639 ;; escape sequence in an identifier, we can report
5640 ;; an error here.
5641 (progn
5642 (setq escape-val 0)
5643 (dotimes (_ 4)
5644 (setq c (js2-get-char)
5645 escape-val (js2-x-digit-to-int c escape-val))
5646 ;; Next check takes care of c < 0 and bad escape
5647 (if (minusp escape-val)
5648 (throw 'break nil)))
5649 (if (minusp escape-val)
5650 (js2-report-scan-error "msg.invalid.escape" t))
5651 (js2-add-to-string escape-val)
5652 (setq is-unicode-escape-start nil))
5653 (setq c (js2-get-char))
5654 (cond
5655 ((eq c ?\\)
5656 (setq c (js2-get-char))
5657 (if (eq c ?u)
5658 (setq is-unicode-escape-start t
5659 contains-escape t)
5660 (js2-report-scan-error "msg.illegal.character" t)))
5661 (t
5662 (if (or (eq c js2-EOF_CHAR)
5663 (not (js2-identifier-part-p c)))
5664 (throw 'break nil))
5665 (js2-add-to-string c))))))
5666 (js2-unget-char)
5667 (setf str (js2-collect-string js2-ts-string-buffer)
5668 (js2-token-end token) js2-ts-cursor)
5669 ;; FIXME: Invalid in ES5 and ES6, see
5670 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5671 ;; Probably should just drop this conditional.
5672 (unless contains-escape
5673 ;; OPT we shouldn't have to make a string (object!) to
5674 ;; check if it's a keyword.
5675 ;; Return the corresponding token if it's a keyword
5676 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5677 (setq result (js2-string-to-keyword str)))
5678 (if (and (< js2-language-version 170)
5679 (memq result '(js2-LET js2-YIELD)))
5680 ;; LET and YIELD are tokens only in 1.7 and later
5681 (setq result 'js2-NAME))
5682 (when (eq result 'js2-RESERVED)
5683 (setf (js2-token-string token) str))
5684 (throw 'return (js2-tt-code result))))
5685 ;; If we want to intern these as Rhino does, just use (intern str)
5686 (setf (js2-token-string token) str)
5687 (throw 'return js2-NAME)) ; end identifier/kwd check
5688 ;; is it a number?
5689 (when (or (js2-digit-p c)
5690 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5691 (setq js2-ts-string-buffer nil
5692 base 10)
5693 (when (eq c ?0)
5694 (setq c (js2-get-char))
5695 (cond
5696 ((or (eq c ?x) (eq c ?X))
5697 (setq base 16)
5698 (setq c (js2-get-char)))
5699 ((and (or (eq c ?b) (eq c ?B))
5700 (>= js2-language-version 200))
5701 (setq base 2)
5702 (setq c (js2-get-char)))
5703 ((and (or (eq c ?o) (eq c ?O))
5704 (>= js2-language-version 200))
5705 (setq base 8)
5706 (setq c (js2-get-char)))
5707 ((js2-digit-p c)
5708 (setq base 'maybe-8))
5709 (t
5710 (js2-add-to-string ?0))))
5711 (cond
5712 ((eq base 16)
5713 (if (> 0 (js2-x-digit-to-int c 0))
5714 (js2-report-scan-error "msg.missing.hex.digits")
5715 (while (<= 0 (js2-x-digit-to-int c 0))
5716 (js2-add-to-string c)
5717 (setq c (js2-get-char)))))
5718 ((eq base 2)
5719 (if (not (memq c '(?0 ?1)))
5720 (js2-report-scan-error "msg.missing.binary.digits")
5721 (while (memq c '(?0 ?1))
5722 (js2-add-to-string c)
5723 (setq c (js2-get-char)))))
5724 ((eq base 8)
5725 (if (or (> ?0 c) (< ?7 c))
5726 (js2-report-scan-error "msg.missing.octal.digits")
5727 (while (and (<= ?0 c) (>= ?7 c))
5728 (js2-add-to-string c)
5729 (setq c (js2-get-char)))))
5730 (t
5731 (while (and (<= ?0 c) (<= c ?9))
5732 ;; We permit 08 and 09 as decimal numbers, which
5733 ;; makes our behavior a superset of the ECMA
5734 ;; numeric grammar. We might not always be so
5735 ;; permissive, so we warn about it.
5736 (when (and (eq base 'maybe-8) (>= c ?8))
5737 (js2-report-warning "msg.bad.octal.literal"
5738 (if (eq c ?8) "8" "9"))
5739 (setq base 10))
5740 (js2-add-to-string c)
5741 (setq c (js2-get-char)))
5742 (when (eq base 'maybe-8)
5743 (setq base 8))))
5744 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5745 (when (eq c ?.)
5746 (loop do
5747 (js2-add-to-string c)
5748 (setq c (js2-get-char))
5749 while (js2-digit-p c)))
5750 (when (memq c '(?e ?E))
5751 (js2-add-to-string c)
5752 (setq c (js2-get-char))
5753 (when (memq c '(?+ ?-))
5754 (js2-add-to-string c)
5755 (setq c (js2-get-char)))
5756 (unless (js2-digit-p c)
5757 (js2-report-scan-error "msg.missing.exponent" t))
5758 (loop do
5759 (js2-add-to-string c)
5760 (setq c (js2-get-char))
5761 while (js2-digit-p c))))
5762 (js2-unget-char)
5763 (let ((str (js2-set-string-from-buffer token)))
5764 (setf (js2-token-number token)
5765 (js2-string-to-number str base)))
5766 (throw 'return js2-NUMBER))
5767 ;; is it a string?
5768 (when (or (memq c '(?\" ?\'))
5769 (and (>= js2-language-version 200)
5770 (= c ?`)))
5771 (throw 'return
5772 (js2-get-string-or-template-token c token)))
5773 (js2-ts-return token
5774 (case c
5775 (?\;
5776 (throw 'return js2-SEMI))
5777 (?\[
5778 (throw 'return js2-LB))
5779 (?\]
5780 (throw 'return js2-RB))
5781 (?{
5782 (throw 'return js2-LC))
5783 (?}
5784 (throw 'return js2-RC))
5785 (?\(
5786 (throw 'return js2-LP))
5787 (?\)
5788 (throw 'return js2-RP))
5789 (?,
5790 (throw 'return js2-COMMA))
5791 (??
5792 (throw 'return js2-HOOK))
5793 (?:
5794 (if (js2-match-char ?:)
5795 js2-COLONCOLON
5796 (throw 'return js2-COLON)))
5797 (?.
5798 (if (js2-match-char ?.)
5799 (if (js2-match-char ?.)
5800 js2-TRIPLEDOT js2-DOTDOT)
5801 (if (js2-match-char ?\()
5802 js2-DOTQUERY
5803 (throw 'return js2-DOT))))
5804 (?|
5805 (if (js2-match-char ?|)
5806 (throw 'return js2-OR)
5807 (if (js2-match-char ?=)
5808 js2-ASSIGN_BITOR
5809 (throw 'return js2-BITOR))))
5810 (?^
5811 (if (js2-match-char ?=)
5812 js2-ASSIGN_BITOR
5813 (throw 'return js2-BITXOR)))
5814 (?&
5815 (if (js2-match-char ?&)
5816 (throw 'return js2-AND)
5817 (if (js2-match-char ?=)
5818 js2-ASSIGN_BITAND
5819 (throw 'return js2-BITAND))))
5820 (?=
5821 (if (js2-match-char ?=)
5822 (if (js2-match-char ?=)
5823 js2-SHEQ
5824 (throw 'return js2-EQ))
5825 (if (js2-match-char ?>)
5826 (js2-ts-return token js2-ARROW)
5827 (throw 'return js2-ASSIGN))))
5828 (?!
5829 (if (js2-match-char ?=)
5830 (if (js2-match-char ?=)
5831 js2-SHNE
5832 js2-NE)
5833 (throw 'return js2-NOT)))
5834 (?<
5835 ;; NB:treat HTML begin-comment as comment-till-eol
5836 (when (js2-match-char ?!)
5837 (when (js2-match-char ?-)
5838 (when (js2-match-char ?-)
5839 (js2-skip-line)
5840 (setf (js2-token-comment-type (js2-current-token)) 'html)
5841 (throw 'return js2-COMMENT)))
5842 (js2-unget-char))
5843 (if (js2-match-char ?<)
5844 (if (js2-match-char ?=)
5845 js2-ASSIGN_LSH
5846 js2-LSH)
5847 (if (js2-match-char ?=)
5848 js2-LE
5849 (throw 'return js2-LT))))
5850 (?>
5851 (if (js2-match-char ?>)
5852 (if (js2-match-char ?>)
5853 (if (js2-match-char ?=)
5854 js2-ASSIGN_URSH
5855 js2-URSH)
5856 (if (js2-match-char ?=)
5857 js2-ASSIGN_RSH
5858 js2-RSH))
5859 (if (js2-match-char ?=)
5860 js2-GE
5861 (throw 'return js2-GT))))
5862 (?*
5863 (if (js2-match-char ?=)
5864 js2-ASSIGN_MUL
5865 (throw 'return js2-MUL)))
5866 (?/
5867 ;; is it a // comment?
5868 (when (js2-match-char ?/)
5869 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5870 (js2-skip-line)
5871 (setf (js2-token-comment-type token) 'line)
5872 ;; include newline so highlighting goes to end of window
5873 (incf (js2-token-end token))
5874 (throw 'return js2-COMMENT))
5875 ;; is it a /* comment?
5876 (when (js2-match-char ?*)
5877 (setf look-for-slash nil
5878 (js2-token-beg token) (- js2-ts-cursor 2)
5879 (js2-token-comment-type token)
5880 (if (js2-match-char ?*)
5881 (progn
5882 (setq look-for-slash t)
5883 'jsdoc)
5884 'block))
5885 (while t
5886 (setq c (js2-get-char))
5887 (cond
5888 ((eq c js2-EOF_CHAR)
5889 (setf (js2-token-end token) (1- js2-ts-cursor))
5890 (js2-report-error "msg.unterminated.comment")
5891 (throw 'return js2-COMMENT))
5892 ((eq c ?*)
5893 (setq look-for-slash t))
5894 ((eq c ?/)
5895 (if look-for-slash
5896 (js2-ts-return token js2-COMMENT)))
5897 (t
5898 (setf look-for-slash nil
5899 (js2-token-end token) js2-ts-cursor)))))
5900 (if (js2-match-char ?=)
5901 js2-ASSIGN_DIV
5902 (throw 'return js2-DIV)))
5903 (?#
5904 (when js2-skip-preprocessor-directives
5905 (js2-skip-line)
5906 (setf (js2-token-comment-type token) 'preprocessor
5907 (js2-token-end token) js2-ts-cursor)
5908 (throw 'return js2-COMMENT))
5909 (throw 'return js2-ERROR))
5910 (?%
5911 (if (js2-match-char ?=)
5912 js2-ASSIGN_MOD
5913 (throw 'return js2-MOD)))
5914 (?~
5915 (throw 'return js2-BITNOT))
5916 (?+
5917 (if (js2-match-char ?=)
5918 js2-ASSIGN_ADD
5919 (if (js2-match-char ?+)
5920 js2-INC
5921 (throw 'return js2-ADD))))
5922 (?-
5923 (cond
5924 ((js2-match-char ?=)
5925 (setq c js2-ASSIGN_SUB))
5926 ((js2-match-char ?-)
5927 (unless js2-ts-dirty-line
5928 ;; treat HTML end-comment after possible whitespace
5929 ;; after line start as comment-until-eol
5930 (when (js2-match-char ?>)
5931 (js2-skip-line)
5932 (setf (js2-token-comment-type (js2-current-token)) 'html)
5933 (throw 'return js2-COMMENT)))
5934 (setq c js2-DEC))
5935 (t
5936 (setq c js2-SUB)))
5937 (setq js2-ts-dirty-line t)
5938 c)
5939 (otherwise
5940 (js2-report-scan-error "msg.illegal.character")))))))
5941 (setf (js2-token-type token) tt)
5942 token))
5943
5944 (defun js2-get-string-or-template-token (quote-char token)
5945 ;; We attempt to accumulate a string the fast way, by
5946 ;; building it directly out of the reader. But if there
5947 ;; are any escaped characters in the string, we revert to
5948 ;; building it out of a string buffer.
5949 (let ((c (js2-get-char))
5950 js2-ts-string-buffer
5951 nc)
5952 (catch 'break
5953 (while (/= c quote-char)
5954 (catch 'continue
5955 (when (eq c js2-EOF_CHAR)
5956 (js2-unget-char)
5957 (js2-report-error "msg.unterminated.string.lit")
5958 (throw 'break nil))
5959 (when (and (eq c ?\n) (not (eq quote-char ?`)))
5960 (js2-unget-char)
5961 (js2-report-error "msg.unterminated.string.lit")
5962 (throw 'break nil))
5963 (when (eq c ?\\)
5964 ;; We've hit an escaped character
5965 (setq c (js2-get-char))
5966 (case c
5967 (?b (setq c ?\b))
5968 (?f (setq c ?\f))
5969 (?n (setq c ?\n))
5970 (?r (setq c ?\r))
5971 (?t (setq c ?\t))
5972 (?v (setq c ?\v))
5973 (?u
5974 (setq c1 (js2-read-unicode-escape))
5975 (if js2-parse-ide-mode
5976 (if c1
5977 (progn
5978 ;; just copy the string in IDE-mode
5979 (js2-add-to-string ?\\)
5980 (js2-add-to-string ?u)
5981 (dotimes (_ 3)
5982 (js2-add-to-string (js2-get-char)))
5983 (setq c (js2-get-char))) ; added at end of loop
5984 ;; flag it as an invalid escape
5985 (js2-report-warning "msg.invalid.escape"
5986 nil (- js2-ts-cursor 2) 6))
5987 ;; Get 4 hex digits; if the u escape is not
5988 ;; followed by 4 hex digits, use 'u' + the
5989 ;; literal character sequence that follows.
5990 (js2-add-to-string ?u)
5991 (setq escape-val 0)
5992 (dotimes (_ 4)
5993 (setq c (js2-get-char)
5994 escape-val (js2-x-digit-to-int c escape-val))
5995 (if (minusp escape-val)
5996 (throw 'continue nil))
5997 (js2-add-to-string c))
5998 ;; prepare for replace of stored 'u' sequence by escape value
5999 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6000 c escape-val)))
6001 (?x
6002 ;; Get 2 hex digits, defaulting to 'x'+literal
6003 ;; sequence, as above.
6004 (setq c (js2-get-char)
6005 escape-val (js2-x-digit-to-int c 0))
6006 (if (minusp escape-val)
6007 (progn
6008 (js2-add-to-string ?x)
6009 (throw 'continue nil))
6010 (setq c1 c
6011 c (js2-get-char)
6012 escape-val (js2-x-digit-to-int c escape-val))
6013 (if (minusp escape-val)
6014 (progn
6015 (js2-add-to-string ?x)
6016 (js2-add-to-string c1)
6017 (throw 'continue nil))
6018 ;; got 2 hex digits
6019 (setq c escape-val))))
6020 (?\n
6021 ;; Remove line terminator after escape to follow
6022 ;; SpiderMonkey and C/C++
6023 (setq c (js2-get-char))
6024 (throw 'continue nil))
6025 (t
6026 (when (and (<= ?0 c) (< c ?8))
6027 (setq val (- c ?0)
6028 c (js2-get-char))
6029 (when (and (<= ?0 c) (< c ?8))
6030 (setq val (- (+ (* 8 val) c) ?0)
6031 c (js2-get-char))
6032 (when (and (<= ?0 c)
6033 (< c ?8)
6034 (< val #o37))
6035 ;; c is 3rd char of octal sequence only
6036 ;; if the resulting val <= 0377
6037 (setq val (- (+ (* 8 val) c) ?0)
6038 c (js2-get-char))))
6039 (js2-unget-char)
6040 (setq c val)))))
6041 (when (and (eq quote-char ?`) (eq c ?$))
6042 (when (eq (setq nc (js2-get-char)) ?\{)
6043 (throw 'break nil))
6044 (js2-unget-char))
6045 (js2-add-to-string c)
6046 (setq c (js2-get-char)))))
6047 (js2-set-string-from-buffer token)
6048 (if (not (eq quote-char ?`))
6049 js2-STRING
6050 (if (and (eq c ?$) (eq nc ?\{))
6051 js2-TEMPLATE_HEAD
6052 js2-NO_SUBS_TEMPLATE))))
6053
6054 (defsubst js2-string-to-number (str base)
6055 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
6056 (condition-case nil
6057 (string-to-number str base)
6058 (overflow-error -1)))
6059
6060 (defun js2-read-regexp (start-tt)
6061 "Called by parser when it gets / or /= in literal context."
6062 (let (c err
6063 in-class ; inside a '[' .. ']' character-class
6064 flags
6065 (continue t)
6066 (token (js2-new-token 0)))
6067 (setq js2-ts-string-buffer nil)
6068 (if (eq start-tt js2-ASSIGN_DIV)
6069 ;; mis-scanned /=
6070 (js2-add-to-string ?=)
6071 (if (not (eq start-tt js2-DIV))
6072 (error "failed assertion")))
6073 (while (and (not err)
6074 (or (/= (setq c (js2-get-char)) ?/)
6075 in-class))
6076 (cond
6077 ((or (= c ?\n)
6078 (= c js2-EOF_CHAR))
6079 (setf (js2-token-end token) (1- js2-ts-cursor)
6080 err t
6081 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6082 (js2-report-error "msg.unterminated.re.lit"))
6083 (t (cond
6084 ((= c ?\\)
6085 (js2-add-to-string c)
6086 (setq c (js2-get-char)))
6087 ((= c ?\[)
6088 (setq in-class t))
6089 ((= c ?\])
6090 (setq in-class nil)))
6091 (js2-add-to-string c))))
6092 (unless err
6093 (while continue
6094 (cond
6095 ((js2-match-char ?g)
6096 (push ?g flags))
6097 ((js2-match-char ?i)
6098 (push ?i flags))
6099 ((js2-match-char ?m)
6100 (push ?m flags))
6101 ((and (js2-match-char ?u)
6102 (>= js2-language-version 200))
6103 (push ?u flags))
6104 ((and (js2-match-char ?y)
6105 (>= js2-language-version 200))
6106 (push ?y flags))
6107 (t
6108 (setq continue nil))))
6109 (if (js2-alpha-p (js2-peek-char))
6110 (js2-report-scan-error "msg.invalid.re.flag" t
6111 js2-ts-cursor 1))
6112 (js2-set-string-from-buffer token))
6113 (js2-collect-string flags)))
6114
6115 (defun js2-get-first-xml-token ()
6116 (setq js2-ts-xml-open-tags-count 0
6117 js2-ts-is-xml-attribute nil
6118 js2-ts-xml-is-tag-content nil)
6119 (js2-unget-char)
6120 (js2-get-next-xml-token))
6121
6122 (defun js2-xml-discard-string (token)
6123 "Throw away the string in progress and flag an XML parse error."
6124 (setf js2-ts-string-buffer nil
6125 (js2-token-string token) nil)
6126 (js2-report-scan-error "msg.XML.bad.form" t))
6127
6128 (defun js2-get-next-xml-token ()
6129 (setq js2-ts-string-buffer nil) ; for recording the XML
6130 (let ((token (js2-new-token 0))
6131 c result)
6132 (setq result
6133 (catch 'return
6134 (while t
6135 (setq c (js2-get-char))
6136 (cond
6137 ((= c js2-EOF_CHAR)
6138 (throw 'return js2-ERROR))
6139 (js2-ts-xml-is-tag-content
6140 (case c
6141 (?>
6142 (js2-add-to-string c)
6143 (setq js2-ts-xml-is-tag-content nil
6144 js2-ts-is-xml-attribute nil))
6145 (?/
6146 (js2-add-to-string c)
6147 (when (eq ?> (js2-peek-char))
6148 (setq c (js2-get-char))
6149 (js2-add-to-string c)
6150 (setq js2-ts-xml-is-tag-content nil)
6151 (decf js2-ts-xml-open-tags-count)))
6152 (?{
6153 (js2-unget-char)
6154 (js2-set-string-from-buffer token)
6155 (throw 'return js2-XML))
6156 ((?\' ?\")
6157 (js2-add-to-string c)
6158 (unless (js2-read-quoted-string c token)
6159 (throw 'return js2-ERROR)))
6160 (?=
6161 (js2-add-to-string c)
6162 (setq js2-ts-is-xml-attribute t))
6163 ((? ?\t ?\r ?\n)
6164 (js2-add-to-string c))
6165 (t
6166 (js2-add-to-string c)
6167 (setq js2-ts-is-xml-attribute nil)))
6168 (when (and (not js2-ts-xml-is-tag-content)
6169 (zerop js2-ts-xml-open-tags-count))
6170 (js2-set-string-from-buffer token)
6171 (throw 'return js2-XMLEND)))
6172 (t
6173 ;; else not tag content
6174 (case c
6175 (?<
6176 (js2-add-to-string c)
6177 (setq c (js2-peek-char))
6178 (case c
6179 (?!
6180 (setq c (js2-get-char)) ;; skip !
6181 (js2-add-to-string c)
6182 (setq c (js2-peek-char))
6183 (case c
6184 (?-
6185 (setq c (js2-get-char)) ;; skip -
6186 (js2-add-to-string c)
6187 (if (eq c ?-)
6188 (progn
6189 (js2-add-to-string c)
6190 (unless (js2-read-xml-comment token)
6191 (throw 'return js2-ERROR)))
6192 (js2-xml-discard-string token)
6193 (throw 'return js2-ERROR)))
6194 (?\[
6195 (setq c (js2-get-char)) ;; skip [
6196 (js2-add-to-string c)
6197 (if (and (= (js2-get-char) ?C)
6198 (= (js2-get-char) ?D)
6199 (= (js2-get-char) ?A)
6200 (= (js2-get-char) ?T)
6201 (= (js2-get-char) ?A)
6202 (= (js2-get-char) ?\[))
6203 (progn
6204 (js2-add-to-string ?C)
6205 (js2-add-to-string ?D)
6206 (js2-add-to-string ?A)
6207 (js2-add-to-string ?T)
6208 (js2-add-to-string ?A)
6209 (js2-add-to-string ?\[)
6210 (unless (js2-read-cdata token)
6211 (throw 'return js2-ERROR)))
6212 (js2-xml-discard-string token)
6213 (throw 'return js2-ERROR)))
6214 (t
6215 (unless (js2-read-entity token)
6216 (throw 'return js2-ERROR))))
6217 ;; Allow bare CDATA section, e.g.:
6218 ;; let xml = <![CDATA[ foo bar baz ]]>;
6219 (when (zerop js2-ts-xml-open-tags-count)
6220 (throw 'return js2-XMLEND)))
6221 (??
6222 (setq c (js2-get-char)) ;; skip ?
6223 (js2-add-to-string c)
6224 (unless (js2-read-PI token)
6225 (throw 'return js2-ERROR)))
6226 (?/
6227 ;; end tag
6228 (setq c (js2-get-char)) ;; skip /
6229 (js2-add-to-string c)
6230 (when (zerop js2-ts-xml-open-tags-count)
6231 (js2-xml-discard-string token)
6232 (throw 'return js2-ERROR))
6233 (setq js2-ts-xml-is-tag-content t)
6234 (decf js2-ts-xml-open-tags-count))
6235 (t
6236 ;; start tag
6237 (setq js2-ts-xml-is-tag-content t)
6238 (incf js2-ts-xml-open-tags-count))))
6239 (?{
6240 (js2-unget-char)
6241 (js2-set-string-from-buffer token)
6242 (throw 'return js2-XML))
6243 (t
6244 (js2-add-to-string c))))))))
6245 (setf (js2-token-end token) js2-ts-cursor)
6246 (setf (js2-token-type token) result)
6247 result))
6248
6249 (defun js2-read-quoted-string (quote token)
6250 (let (c)
6251 (catch 'return
6252 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6253 (js2-add-to-string c)
6254 (if (eq c quote)
6255 (throw 'return t)))
6256 (js2-xml-discard-string token) ;; throw away string in progress
6257 nil)))
6258
6259 (defun js2-read-xml-comment (token)
6260 (let ((c (js2-get-char)))
6261 (catch 'return
6262 (while (/= c js2-EOF_CHAR)
6263 (catch 'continue
6264 (js2-add-to-string c)
6265 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6266 (setq c (js2-get-char))
6267 (js2-add-to-string c)
6268 (if (eq (js2-peek-char) ?>)
6269 (progn
6270 (setq c (js2-get-char)) ;; skip >
6271 (js2-add-to-string c)
6272 (throw 'return t))
6273 (throw 'continue nil)))
6274 (setq c (js2-get-char))))
6275 (js2-xml-discard-string token)
6276 nil)))
6277
6278 (defun js2-read-cdata (token)
6279 (let ((c (js2-get-char)))
6280 (catch 'return
6281 (while (/= c js2-EOF_CHAR)
6282 (catch 'continue
6283 (js2-add-to-string c)
6284 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6285 (setq c (js2-get-char))
6286 (js2-add-to-string c)
6287 (if (eq (js2-peek-char) ?>)
6288 (progn
6289 (setq c (js2-get-char)) ;; Skip >
6290 (js2-add-to-string c)
6291 (throw 'return t))
6292 (throw 'continue nil)))
6293 (setq c (js2-get-char))))
6294 (js2-xml-discard-string token)
6295 nil)))
6296
6297 (defun js2-read-entity (token)
6298 (let ((decl-tags 1)
6299 c)
6300 (catch 'return
6301 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6302 (js2-add-to-string c)
6303 (case c
6304 (?<
6305 (incf decl-tags))
6306 (?>
6307 (decf decl-tags)
6308 (if (zerop decl-tags)
6309 (throw 'return t)))))
6310 (js2-xml-discard-string token)
6311 nil)))
6312
6313 (defun js2-read-PI (token)
6314 "Scan an XML processing instruction."
6315 (let (c)
6316 (catch 'return
6317 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6318 (js2-add-to-string c)
6319 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6320 (setq c (js2-get-char)) ;; Skip >
6321 (js2-add-to-string c)
6322 (throw 'return t)))
6323 (js2-xml-discard-string token)
6324 nil)))
6325
6326 ;;; Highlighting
6327
6328 (defun js2-set-face (beg end face &optional record)
6329 "Fontify a region. If RECORD is non-nil, record for later."
6330 (when (plusp js2-highlight-level)
6331 (setq beg (min (point-max) beg)
6332 beg (max (point-min) beg)
6333 end (min (point-max) end)
6334 end (max (point-min) end))
6335 (if record
6336 (push (list beg end face) js2-mode-fontifications)
6337 (put-text-property beg end 'font-lock-face face))))
6338
6339 (defsubst js2-clear-face (beg end)
6340 (remove-text-properties beg end '(font-lock-face nil
6341 help-echo nil
6342 point-entered nil
6343 c-in-sws nil)))
6344
6345 (defconst js2-ecma-global-props
6346 (concat "^"
6347 (regexp-opt
6348 '("Infinity" "NaN" "undefined" "arguments") t)
6349 "$")
6350 "Value properties of the Ecma-262 Global Object.
6351 Shown at or above `js2-highlight-level' 2.")
6352
6353 ;; might want to add the name "arguments" to this list?
6354 (defconst js2-ecma-object-props
6355 (concat "^"
6356 (regexp-opt
6357 '("prototype" "__proto__" "__parent__") t)
6358 "$")
6359 "Value properties of the Ecma-262 Object constructor.
6360 Shown at or above `js2-highlight-level' 2.")
6361
6362 (defconst js2-ecma-global-funcs
6363 (concat
6364 "^"
6365 (regexp-opt
6366 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6367 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6368 "$")
6369 "Function properties of the Ecma-262 Global object.
6370 Shown at or above `js2-highlight-level' 2.")
6371
6372 (defconst js2-ecma-number-props
6373 (concat "^"
6374 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6375 "NEGATIVE_INFINITY"
6376 "POSITIVE_INFINITY") t)
6377 "$")
6378 "Properties of the Ecma-262 Number constructor.
6379 Shown at or above `js2-highlight-level' 2.")
6380
6381 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6382 "Properties of the Ecma-262 Date constructor.
6383 Shown at or above `js2-highlight-level' 2.")
6384
6385 (defconst js2-ecma-math-props
6386 (concat "^"
6387 (regexp-opt
6388 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6389 t)
6390 "$")
6391 "Properties of the Ecma-262 Math object.
6392 Shown at or above `js2-highlight-level' 2.")
6393
6394 (defconst js2-ecma-math-funcs
6395 (concat "^"
6396 (regexp-opt
6397 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6398 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6399 "$")
6400 "Function properties of the Ecma-262 Math object.
6401 Shown at or above `js2-highlight-level' 2.")
6402
6403 (defconst js2-ecma-function-props
6404 (concat
6405 "^"
6406 (regexp-opt
6407 '(;; properties of the Object prototype object
6408 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6409 "toLocaleString" "toString" "valueOf"
6410 ;; properties of the Function prototype object
6411 "apply" "call"
6412 ;; properties of the Array prototype object
6413 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6414 "splice" "unshift"
6415 ;; properties of the String prototype object
6416 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6417 "localeCompare" "match" "replace" "search" "split" "substring"
6418 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6419 "toUpperCase"
6420 ;; properties of the Number prototype object
6421 "toExponential" "toFixed" "toPrecision"
6422 ;; properties of the Date prototype object
6423 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6424 "getMinutes" "getMonth" "getSeconds" "getTime"
6425 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6426 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6427 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6428 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6429 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6430 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6431 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6432 "toTimeString" "toUTCString"
6433 ;; properties of the RegExp prototype object
6434 "exec" "test"
6435 ;; properties of the JSON prototype object
6436 "parse" "stringify"
6437 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6438 "toSource" "__defineGetter__" "__defineSetter__"
6439 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6440 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6441 t)
6442 "$")
6443 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6444 Shown at or above `js2-highlight-level' 3.")
6445
6446 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6447 (let ((target-name (and target
6448 (js2-name-node-p target)
6449 (js2-name-node-name target)))
6450 (prop-name (if prop (js2-name-node-name prop)))
6451 (level2 (>= js2-highlight-level 2))
6452 (level3 (>= js2-highlight-level 3)))
6453 (when level2
6454 (let ((face
6455 (if call-p
6456 (cond
6457 ((and target prop)
6458 (cond
6459 ((and level3 (string-match js2-ecma-function-props prop-name))
6460 'font-lock-builtin-face)
6461 ((and target-name prop)
6462 (cond
6463 ((string= target-name "Date")
6464 (if (string-match js2-ecma-date-props prop-name)
6465 'font-lock-builtin-face))
6466 ((string= target-name "Math")
6467 (if (string-match js2-ecma-math-funcs prop-name)
6468 'font-lock-builtin-face))))))
6469 (prop
6470 (if (string-match js2-ecma-global-funcs prop-name)
6471 'font-lock-builtin-face)))
6472 (cond
6473 ((and target prop)
6474 (cond
6475 ((string= target-name "Number")
6476 (if (string-match js2-ecma-number-props prop-name)
6477 'font-lock-constant-face))
6478 ((string= target-name "Math")
6479 (if (string-match js2-ecma-math-props prop-name)
6480 'font-lock-constant-face))))
6481 (prop
6482 (if (string-match js2-ecma-object-props prop-name)
6483 'font-lock-constant-face))))))
6484 (when face
6485 (let ((pos (+ (js2-node-pos parent) ; absolute
6486 (js2-node-pos prop)))) ; relative
6487 (js2-set-face pos
6488 (+ pos (js2-node-len prop))
6489 face 'record)))))))
6490
6491 (defun js2-parse-highlight-member-expr-node (node)
6492 "Perform syntax highlighting of EcmaScript built-in properties.
6493 The variable `js2-highlight-level' governs this highighting."
6494 (let (face target prop name pos end parent call-p callee)
6495 (cond
6496 ;; case 1: simple name, e.g. foo
6497 ((js2-name-node-p node)
6498 (setq name (js2-name-node-name node))
6499 ;; possible for name to be nil in rare cases - saw it when
6500 ;; running js2-mode on an elisp buffer. Might as well try to
6501 ;; make it so js2-mode never barfs.
6502 (when name
6503 (setq face (if (string-match js2-ecma-global-props name)
6504 'font-lock-constant-face))
6505 (when face
6506 (setq pos (js2-node-pos node)
6507 end (+ pos (js2-node-len node)))
6508 (js2-set-face pos end face 'record))))
6509 ;; case 2: property access or function call
6510 ((or (js2-prop-get-node-p node)
6511 ;; highlight function call if expr is a prop-get node
6512 ;; or a plain name (i.e. unqualified function call)
6513 (and (setq call-p (js2-call-node-p node))
6514 (setq callee (js2-call-node-target node)) ; separate setq!
6515 (or (js2-prop-get-node-p callee)
6516 (js2-name-node-p callee))))
6517 (setq parent node
6518 node (if call-p callee node))
6519 (if (and call-p (js2-name-node-p callee))
6520 (setq prop callee)
6521 (setq target (js2-prop-get-node-left node)
6522 prop (js2-prop-get-node-right node)))
6523 (cond
6524 ((js2-name-node-p prop)
6525 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6526 (js2-parse-highlight-prop-get parent target prop call-p))
6527 ((js2-name-node-p target)
6528 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6529 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6530
6531 (defun js2-parse-highlight-member-expr-fn-name (expr)
6532 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6533 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6534 We currently only handle the case where the last component is a prop-get
6535 of a simple name. Called before EXPR has a parent node."
6536 (let (pos
6537 (name (and (js2-prop-get-node-p expr)
6538 (js2-prop-get-node-right expr))))
6539 (when (js2-name-node-p name)
6540 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6541 (js2-node-pos name)))
6542 (+ pos (js2-node-len name))
6543 'font-lock-function-name-face
6544 'record))))
6545
6546 ;; source: http://jsdoc.sourceforge.net/
6547 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6548 ;; allows type specifications, and needs work before entering the wild.
6549
6550 (defconst js2-jsdoc-param-tag-regexp
6551 (concat "^\\s-*\\*+\\s-*\\(@"
6552 "\\(?:param\\|argument\\)"
6553 "\\)"
6554 "\\s-*\\({[^}]+}\\)?" ; optional type
6555 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6556 "\\>")
6557 "Matches jsdoc tags with optional type and optional param name.")
6558
6559 (defconst js2-jsdoc-typed-tag-regexp
6560 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6561 (regexp-opt
6562 '("enum"
6563 "extends"
6564 "field"
6565 "id"
6566 "implements"
6567 "lends"
6568 "mods"
6569 "requires"
6570 "return"
6571 "returns"
6572 "throw"
6573 "throws"))
6574 "\\)\\)\\s-*\\({[^}]+}\\)?")
6575 "Matches jsdoc tags with optional type.")
6576
6577 (defconst js2-jsdoc-arg-tag-regexp
6578 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6579 (regexp-opt
6580 '("alias"
6581 "augments"
6582 "borrows"
6583 "bug"
6584 "base"
6585 "config"
6586 "default"
6587 "define"
6588 "exception"
6589 "function"
6590 "member"
6591 "memberOf"
6592 "name"
6593 "namespace"
6594 "property"
6595 "since"
6596 "suppress"
6597 "this"
6598 "throws"
6599 "type"
6600 "version"))
6601 "\\)\\)\\s-+\\([^ \t]+\\)")
6602 "Matches jsdoc tags with a single argument.")
6603
6604 (defconst js2-jsdoc-empty-tag-regexp
6605 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6606 (regexp-opt
6607 '("addon"
6608 "author"
6609 "class"
6610 "const"
6611 "constant"
6612 "constructor"
6613 "constructs"
6614 "deprecated"
6615 "desc"
6616 "description"
6617 "event"
6618 "example"
6619 "exec"
6620 "export"
6621 "fileoverview"
6622 "final"
6623 "function"
6624 "hidden"
6625 "ignore"
6626 "implicitCast"
6627 "inheritDoc"
6628 "inner"
6629 "interface"
6630 "license"
6631 "noalias"
6632 "noshadow"
6633 "notypecheck"
6634 "override"
6635 "owner"
6636 "preserve"
6637 "preserveTry"
6638 "private"
6639 "protected"
6640 "public"
6641 "static"
6642 "supported"
6643 ))
6644 "\\)\\)\\s-*")
6645 "Matches empty jsdoc tags.")
6646
6647 (defconst js2-jsdoc-link-tag-regexp
6648 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6649 "Matches a jsdoc link or code tag.")
6650
6651 (defconst js2-jsdoc-see-tag-regexp
6652 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6653 "Matches a jsdoc @see tag.")
6654
6655 (defconst js2-jsdoc-html-tag-regexp
6656 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6657 "Matches a simple (no attributes) html start- or end-tag.")
6658
6659 (defun js2-jsdoc-highlight-helper ()
6660 (js2-set-face (match-beginning 1)
6661 (match-end 1)
6662 'js2-jsdoc-tag)
6663 (if (match-beginning 2)
6664 (if (save-excursion
6665 (goto-char (match-beginning 2))
6666 (= (char-after) ?{))
6667 (js2-set-face (1+ (match-beginning 2))
6668 (1- (match-end 2))
6669 'js2-jsdoc-type)
6670 (js2-set-face (match-beginning 2)
6671 (match-end 2)
6672 'js2-jsdoc-value)))
6673 (if (match-beginning 3)
6674 (js2-set-face (match-beginning 3)
6675 (match-end 3)
6676 'js2-jsdoc-value)))
6677
6678 (defun js2-highlight-jsdoc (ast)
6679 "Highlight doc comment tags."
6680 (let ((comments (js2-ast-root-comments ast))
6681 beg end)
6682 (save-excursion
6683 (dolist (node comments)
6684 (when (eq (js2-comment-node-format node) 'jsdoc)
6685 (setq beg (js2-node-abs-pos node)
6686 end (+ beg (js2-node-len node)))
6687 (save-restriction
6688 (narrow-to-region beg end)
6689 (dolist (re (list js2-jsdoc-param-tag-regexp
6690 js2-jsdoc-typed-tag-regexp
6691 js2-jsdoc-arg-tag-regexp
6692 js2-jsdoc-link-tag-regexp
6693 js2-jsdoc-see-tag-regexp
6694 js2-jsdoc-empty-tag-regexp))
6695 (goto-char beg)
6696 (while (re-search-forward re nil t)
6697 (js2-jsdoc-highlight-helper)))
6698 ;; simple highlighting for html tags
6699 (goto-char beg)
6700 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6701 (js2-set-face (match-beginning 1)
6702 (match-end 1)
6703 'js2-jsdoc-html-tag-delimiter)
6704 (js2-set-face (match-beginning 2)
6705 (match-end 2)
6706 'js2-jsdoc-html-tag-name)
6707 (js2-set-face (match-beginning 3)
6708 (match-end 3)
6709 'js2-jsdoc-html-tag-delimiter))))))))
6710
6711 (defun js2-highlight-assign-targets (_node left right)
6712 "Highlight function properties and external variables."
6713 (let (leftpos name)
6714 ;; highlight vars and props assigned function values
6715 (when (or (js2-function-node-p right)
6716 (js2-class-node-p right))
6717 (cond
6718 ;; var foo = function() {...}
6719 ((js2-name-node-p left)
6720 (setq name left))
6721 ;; foo.bar.baz = function() {...}
6722 ((and (js2-prop-get-node-p left)
6723 (js2-name-node-p (js2-prop-get-node-right left)))
6724 (setq name (js2-prop-get-node-right left))))
6725 (when name
6726 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6727 (+ leftpos (js2-node-len name))
6728 'font-lock-function-name-face
6729 'record)))))
6730
6731 (defun js2-record-name-node (node)
6732 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6733 later. NODE must be a name node."
6734 (let ((leftpos (js2-node-abs-pos node)))
6735 (push (list node js2-current-scope
6736 leftpos
6737 (+ leftpos (js2-node-len node)))
6738 js2-recorded-identifiers)))
6739
6740 (defun js2-highlight-undeclared-vars ()
6741 "After entire parse is finished, look for undeclared variable references.
6742 We have to wait until entire buffer is parsed, since JavaScript permits var
6743 decls to occur after they're used.
6744
6745 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6746 it is considered declared."
6747 (let (name)
6748 (dolist (entry js2-recorded-identifiers)
6749 (destructuring-bind (name-node scope pos end) entry
6750 (setq name (js2-name-node-name name-node))
6751 (unless (or (member name js2-global-externs)
6752 (member name js2-default-externs)
6753 (member name js2-additional-externs)
6754 (js2-get-defining-scope scope name))
6755 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6756 'js2-external-variable))))
6757 (setq js2-recorded-identifiers nil)))
6758
6759 (defun js2-set-default-externs ()
6760 "Set the value of `js2-default-externs' based on the various
6761 `js2-include-?-externs' variables."
6762 (setq js2-default-externs
6763 (append js2-ecma-262-externs
6764 (if js2-include-browser-externs js2-browser-externs)
6765 (if (and js2-include-browser-externs
6766 (>= js2-language-version 200)) js2-harmony-externs)
6767 (if js2-include-rhino-externs js2-rhino-externs)
6768 (if js2-include-node-externs js2-node-externs)
6769 (if (or js2-include-browser-externs js2-include-node-externs)
6770 js2-typed-array-externs))))
6771
6772 (defun js2-apply-jslint-globals ()
6773 (setq js2-additional-externs
6774 (nconc (js2-get-jslint-globals)
6775 js2-additional-externs)))
6776
6777 (defun js2-get-jslint-globals ()
6778 (loop for node in (js2-ast-root-comments js2-mode-ast)
6779 when (and (eq 'block (js2-comment-node-format node))
6780 (save-excursion
6781 (goto-char (js2-node-abs-pos node))
6782 (looking-at "/\\*global ")))
6783 append (js2-get-jslint-globals-in
6784 (match-end 0)
6785 (js2-node-abs-end node))))
6786
6787 (defun js2-get-jslint-globals-in (beg end)
6788 (let (res)
6789 (save-excursion
6790 (goto-char beg)
6791 (while (re-search-forward js2-mode-identifier-re end t)
6792 (let ((match (match-string 0)))
6793 (unless (member match '("true" "false"))
6794 (push match res)))))
6795 (nreverse res)))
6796
6797 ;;; IMenu support
6798
6799 ;; We currently only support imenu, but eventually should support speedbar and
6800 ;; possibly other browsing mechanisms.
6801
6802 ;; The basic strategy is to identify function assignment targets of the form
6803 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6804 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6805 ;; for imenu after parsing is finished.
6806
6807 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6808 ;; JavaScript, and the general problem is undecidable. However, several forms
6809 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6810 ;; include:
6811
6812 ;; function foo() -- function declaration
6813 ;; foo = function() -- function expression assigned to variable
6814 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6815 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6816 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6817 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6818 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6819 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6820 ;; function foo() {function bar() {...}} -- nested function
6821 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6822
6823 ;; This list boils down to a few forms that can be combined recursively.
6824 ;; Top-level named function declarations include both the left-hand (name)
6825 ;; and the right-hand (function value) expressions needed to produce an imenu
6826 ;; entry. The other "right-hand" forms we need to look for are:
6827 ;; - functions declared as props/getters/setters in object literals
6828 ;; - nested named function declarations
6829 ;; The "left-hand" expressions that functions can be assigned to include:
6830 ;; - local/global variables
6831 ;; - nested property-get expressions like a.b.c.d
6832 ;; - element gets like foo[10] or foo['bar'] where the index
6833 ;; expression can be trivially converted to a property name. They
6834 ;; effectively then become property gets.
6835
6836 ;; All the different definition types are canonicalized into the form
6837 ;; foo.bar.baz = position-of-function-keyword
6838
6839 ;; We need to build a trie-like structure for imenu. As an example,
6840 ;; consider the following JavaScript code:
6841
6842 ;; a = function() {...} // function at position 5
6843 ;; b = function() {...} // function at position 25
6844 ;; foo = function() {...} // function at position 100
6845 ;; foo.bar = function() {...} // function at position 200
6846 ;; foo.bar.baz = function() {...} // function at position 300
6847 ;; foo.bar.zab = function() {...} // function at position 400
6848
6849 ;; During parsing we accumulate an entry for each definition in
6850 ;; the variable `js2-imenu-recorder', like so:
6851
6852 ;; '((fn a 5)
6853 ;; (fn b 25)
6854 ;; (fn foo 100)
6855 ;; (fn foo bar 200)
6856 ;; (fn foo bar baz 300)
6857 ;; (fn foo bar zab 400))
6858
6859 ;; Where 'fn' is the respective function node.
6860 ;; After parsing these entries are merged into this alist-trie:
6861
6862 ;; '((a . 1)
6863 ;; (b . 2)
6864 ;; (foo (<definition> . 3)
6865 ;; (bar (<definition> . 6)
6866 ;; (baz . 100)
6867 ;; (zab . 200))))
6868
6869 ;; Note the wacky need for a <definition> name. The token can be anything
6870 ;; that isn't a valid JavaScript identifier, because you might make foo
6871 ;; a function and then start setting properties on it that are also functions.
6872
6873 (defun js2-prop-node-name (node)
6874 "Return the name of a node that may be a property-get/property-name.
6875 If NODE is not a valid name-node, string-node or integral number-node,
6876 returns nil. Otherwise returns the string name/value of the node."
6877 (cond
6878 ((js2-name-node-p node)
6879 (js2-name-node-name node))
6880 ((js2-string-node-p node)
6881 (js2-string-node-value node))
6882 ((and (js2-number-node-p node)
6883 (string-match "^[0-9]+$" (js2-number-node-value node)))
6884 (js2-number-node-value node))
6885 ((eq (js2-node-type node) js2-THIS)
6886 "this")
6887 ((eq (js2-node-type node) js2-SUPER)
6888 "super")))
6889
6890 (defun js2-node-qname-component (node)
6891 "Return the name of this node, if it contributes to a qname.
6892 Returns nil if the node doesn't contribute."
6893 (copy-sequence
6894 (or (js2-prop-node-name node)
6895 (if (and (js2-function-node-p node)
6896 (js2-function-node-name node))
6897 (js2-name-node-name (js2-function-node-name node))))))
6898
6899 (defun js2-record-imenu-entry (fn-node qname pos)
6900 "Add an entry to `js2-imenu-recorder'.
6901 FN-NODE should be the current item's function node.
6902
6903 Associate FN-NODE with its QNAME for later lookup.
6904 This is used in postprocessing the chain list. For each chain, we find
6905 the parent function, look up its qname, then prepend a copy of it to the chain."
6906 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6907 (unless js2-imenu-function-map
6908 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6909 (puthash fn-node qname js2-imenu-function-map))
6910
6911 (defun js2-record-imenu-functions (node &optional var)
6912 "Record function definitions for imenu.
6913 NODE is a function node or an object literal.
6914 VAR, if non-nil, is the expression that NODE is being assigned to.
6915 When passed arguments of wrong type, does nothing."
6916 (when js2-parse-ide-mode
6917 (let ((fun-p (js2-function-node-p node))
6918 qname fname-node)
6919 (cond
6920 ;; non-anonymous function declaration?
6921 ((and fun-p
6922 (not var)
6923 (setq fname-node (js2-function-node-name node)))
6924 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6925 ;; for remaining forms, compute left-side tree branch first
6926 ((and var (setq qname (js2-compute-nested-prop-get var)))
6927 (cond
6928 ;; foo.bar.baz = function
6929 (fun-p
6930 (js2-record-imenu-entry node qname (js2-node-pos node)))
6931 ;; foo.bar.baz = object-literal
6932 ;; look for nested functions: {a: {b: function() {...} }}
6933 ((js2-object-node-p node)
6934 ;; Node position here is still absolute, since the parser
6935 ;; passes the assignment target and value expressions
6936 ;; to us before they are added as children of the assignment node.
6937 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6938
6939 (defun js2-compute-nested-prop-get (node)
6940 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6941 component nodes as a list. Otherwise return nil. Element-gets are treated
6942 as property-gets if the index expression is a string, or a positive integer."
6943 (let (left right head)
6944 (cond
6945 ((or (js2-name-node-p node)
6946 (js2-this-or-super-node-p node))
6947 (list node))
6948 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6949 ((js2-prop-get-node-p node) ; foo.bar
6950 (setq left (js2-prop-get-node-left node)
6951 right (js2-prop-get-node-right node))
6952 (if (setq head (js2-compute-nested-prop-get left))
6953 (nconc head (list right))))
6954 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6955 (setq left (js2-elem-get-node-target node)
6956 right (js2-elem-get-node-element node))
6957 (if (or (js2-string-node-p right) ; ['bar']
6958 (and (js2-number-node-p right) ; [10]
6959 (string-match "^[0-9]+$"
6960 (js2-number-node-value right))))
6961 (if (setq head (js2-compute-nested-prop-get left))
6962 (nconc head (list right))))))))
6963
6964 (defun js2-record-object-literal (node qname pos)
6965 "Recursively process an object literal looking for functions.
6966 NODE is an object literal that is the right-hand child of an assignment
6967 expression. QNAME is a list of nodes representing the assignment target,
6968 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6969 POS is the absolute position of the node.
6970 We do a depth-first traversal of NODE. For any functions we find,
6971 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6972 (let (right)
6973 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6974 (let ((left (js2-infix-node-left e))
6975 ;; Element positions are relative to the parent position.
6976 (pos (+ pos (js2-node-pos e))))
6977 (cond
6978 ;; foo: function() {...}
6979 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6980 (when (js2-prop-node-name left)
6981 ;; As a policy decision, we record the position of the property,
6982 ;; not the position of the `function' keyword, since the property
6983 ;; is effectively the name of the function.
6984 (js2-record-imenu-entry right (append qname (list left)) pos)))
6985 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6986 ((js2-object-node-p right)
6987 (js2-record-object-literal right
6988 (append qname (list (js2-infix-node-left e)))
6989 (+ pos (js2-node-pos right)))))))))
6990
6991 (defun js2-node-top-level-decl-p (node)
6992 "Return t if NODE's name is defined in the top-level scope.
6993 Also returns t if NODE's name is not defined in any scope, since it implies
6994 that it's an external variable, which must also be in the top-level scope."
6995 (let* ((name (js2-prop-node-name node))
6996 (this-scope (js2-node-get-enclosing-scope node))
6997 defining-scope)
6998 (cond
6999 ((js2-this-or-super-node-p node)
7000 nil)
7001 ((null this-scope)
7002 t)
7003 ((setq defining-scope (js2-get-defining-scope this-scope name))
7004 (js2-ast-root-p defining-scope))
7005 (t t))))
7006
7007 (defun js2-wrapper-function-p (node)
7008 "Return t if NODE is a function expression that's immediately invoked.
7009 NODE must be `js2-function-node'."
7010 (let ((parent (js2-node-parent node)))
7011 (or
7012 ;; function(){...}();
7013 (and (js2-call-node-p parent)
7014 (eq node (js2-call-node-target parent)))
7015 (and (js2-paren-node-p parent)
7016 ;; (function(){...})();
7017 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7018 ;; (function(){...}).call(this);
7019 (and (js2-prop-get-node-p parent)
7020 (member (js2-name-node-name (js2-prop-get-node-right parent))
7021 '("call" "apply"))
7022 (js2-call-node-p (js2-node-parent parent))))))))
7023
7024 (defun js2-browse-postprocess-chains ()
7025 "Modify function-declaration name chains after parsing finishes.
7026 Some of the information is only available after the parse tree is complete.
7027 For instance, processing a nested scope requires a parent function node."
7028 (let (result fn parent-qname p elem)
7029 (dolist (entry js2-imenu-recorder)
7030 ;; function node goes first
7031 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7032 ;; Examine head's defining scope:
7033 ;; Pre-processed chain, or top-level/external, keep as-is.
7034 (if (or (stringp head) (js2-node-top-level-decl-p head))
7035 (push chain result)
7036 (when (js2-this-or-super-node-p head)
7037 (setq chain (cdr chain))) ; discard this-node
7038 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7039 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7040 (when (eq parent-qname 'not-found)
7041 ;; anonymous function expressions are not recorded
7042 ;; during the parse, so we need to handle this case here
7043 (setq parent-qname
7044 (if (js2-wrapper-function-p fn)
7045 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7046 (if (js2-ast-root-p grandparent)
7047 nil
7048 (gethash grandparent js2-imenu-function-map 'skip)))
7049 'skip))
7050 (puthash fn parent-qname js2-imenu-function-map))
7051 (if (eq parent-qname 'skip)
7052 ;; We don't show it, let's record that fact.
7053 (remhash current-fn js2-imenu-function-map)
7054 ;; Prepend parent fn qname to this chain.
7055 (let ((qname (append parent-qname chain)))
7056 (puthash current-fn (butlast qname) js2-imenu-function-map)
7057 (push qname result)))))))
7058 ;; Collect chains obtained by third-party code.
7059 (let (js2-imenu-recorder)
7060 (run-hooks 'js2-build-imenu-callbacks)
7061 (dolist (entry js2-imenu-recorder)
7062 (push (cdr entry) result)))
7063 ;; Finally replace each node in each chain with its name.
7064 (dolist (chain result)
7065 (setq p chain)
7066 (while p
7067 (if (js2-node-p (setq elem (car p)))
7068 (setcar p (js2-node-qname-component elem)))
7069 (setq p (cdr p))))
7070 result))
7071
7072 ;; Merge name chains into a trie-like tree structure of nested lists.
7073 ;; To simplify construction of the trie, we first build it out using the rule
7074 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7075 ;; [key, num-or-list]. The second element can be a number; if so, this key
7076 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7077 ;; associated with the key at this level.) Otherwise the second element is
7078 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7079 ;; a simple recursive formulation.
7080 ;;
7081 ;; js2-mode is building the data structure for imenu. The imenu documentation
7082 ;; claims that it's the structure above, but in practice it wants the children
7083 ;; at the same list level as the key for that level, which is how I've drawn
7084 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7085 ;; list wrapper around the children at each level.
7086 ;;
7087 ;; A completed nested imenu-alist entry looks like this:
7088 ;; '(("foo"
7089 ;; ("<definition>" . 7)
7090 ;; ("bar"
7091 ;; ("a" . 40)
7092 ;; ("b" . 60))))
7093 ;;
7094 ;; In particular, the documentation for `imenu--index-alist' says that
7095 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7096 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7097
7098 (defun js2-treeify (lst)
7099 "Convert (a b c d) to (a ((b ((c d)))))."
7100 (if (null (cddr lst)) ; list length <= 2
7101 lst
7102 (list (car lst) (list (js2-treeify (cdr lst))))))
7103
7104 (defun js2-build-alist-trie (chains trie)
7105 "Merge declaration name chains into a trie-like alist structure for imenu.
7106 CHAINS is the qname chain list produced during parsing. TRIE is a
7107 list of elements built up so far."
7108 (let (head tail pos branch kids)
7109 (dolist (chain chains)
7110 (setq head (car chain)
7111 tail (cdr chain)
7112 pos (if (numberp (car tail)) (car tail))
7113 branch (js2-find-if (lambda (n)
7114 (string= (car n) head))
7115 trie)
7116 kids (second branch))
7117 (cond
7118 ;; case 1: this key isn't in the trie yet
7119 ((null branch)
7120 (if trie
7121 (setcdr (last trie) (list (js2-treeify chain)))
7122 (setq trie (list (js2-treeify chain)))))
7123 ;; case 2: key is present with a single number entry: replace w/ list
7124 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7125 ;; ("<definition>" 20)))
7126 ((numberp kids)
7127 (setcar (cdr branch)
7128 (list (list "<definition-1>" kids)
7129 (if pos
7130 (list "<definition-2>" pos)
7131 (js2-treeify tail)))))
7132 ;; case 3: key is there (with kids), and we're a number entry
7133 (pos
7134 (setcdr (last kids)
7135 (list
7136 (list (format "<definition-%d>"
7137 (1+ (loop for kid in kids
7138 count (eq ?< (aref (car kid) 0)))))
7139 pos))))
7140 ;; case 4: key is there with kids, need to merge in our chain
7141 (t
7142 (js2-build-alist-trie (list tail) kids))))
7143 trie))
7144
7145 (defun js2-flatten-trie (trie)
7146 "Convert TRIE to imenu-format.
7147 Recurses through nodes, and for each one whose second element is a list,
7148 appends the list's flattened elements to the current element. Also
7149 changes the tails into conses. For instance, this pre-flattened trie
7150
7151 '(a ((b 20)
7152 (c ((d 30)
7153 (e 40)))))
7154
7155 becomes
7156
7157 '(a (b . 20)
7158 (c (d . 30)
7159 (e . 40)))
7160
7161 Note that the root of the trie has no key, just a list of chains.
7162 This is also true for the value of any key with multiple children,
7163 e.g. key 'c' in the example above."
7164 (cond
7165 ((listp (car trie))
7166 (mapcar #'js2-flatten-trie trie))
7167 (t
7168 (if (numberp (second trie))
7169 (cons (car trie) (second trie))
7170 ;; else pop list and append its kids
7171 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7172
7173 (defun js2-build-imenu-index ()
7174 "Turn `js2-imenu-recorder' into an imenu data structure."
7175 (when (eq js2-imenu-recorder 'empty)
7176 (setq js2-imenu-recorder nil))
7177 (let* ((chains (js2-browse-postprocess-chains))
7178 (result (js2-build-alist-trie chains nil)))
7179 (js2-flatten-trie result)))
7180
7181 (defun js2-test-print-chains (chains)
7182 "Print a list of qname chains.
7183 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7184 i.e. one or more nodes, and an integer position as the list tail."
7185 (mapconcat (lambda (chain)
7186 (concat "("
7187 (mapconcat (lambda (elem)
7188 (if (js2-node-p elem)
7189 (or (js2-node-qname-component elem)
7190 "nil")
7191 (number-to-string elem)))
7192 chain
7193 " ")
7194 ")"))
7195 chains
7196 "\n"))
7197
7198 ;;; Parser
7199
7200 (defconst js2-version "1.8.5"
7201 "Version of JavaScript supported.")
7202
7203 (defun js2-record-face (face &optional token)
7204 "Record a style run of FACE for TOKEN or the current token."
7205 (unless token (setq token (js2-current-token)))
7206 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7207
7208 (defsubst js2-node-end (n)
7209 "Computes the absolute end of node N.
7210 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7211 is only true until the node is added to its parent; i.e., while parsing."
7212 (+ (js2-node-pos n)
7213 (js2-node-len n)))
7214
7215 (defun js2-record-comment (token)
7216 "Record a comment in `js2-scanned-comments'."
7217 (let ((ct (js2-token-comment-type token))
7218 (beg (js2-token-beg token))
7219 (end (js2-token-end token)))
7220 (push (make-js2-comment-node :len (- end beg)
7221 :format ct)
7222 js2-scanned-comments)
7223 (when js2-parse-ide-mode
7224 (js2-record-face (if (eq ct 'jsdoc)
7225 'font-lock-doc-face
7226 'font-lock-comment-face)
7227 token)
7228 (when (memq ct '(html preprocessor))
7229 ;; Tell cc-engine the bounds of the comment.
7230 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7231
7232 (defun js2-peek-token ()
7233 "Return the next token type without consuming it.
7234 If `js2-ti-lookahead' is positive, return the type of next token
7235 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7236 (if (not (zerop js2-ti-lookahead))
7237 (js2-token-type
7238 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7239 (let ((tt (js2-get-token-internal nil)))
7240 (js2-unget-token)
7241 tt)))
7242
7243 (defalias 'js2-next-token 'js2-get-token)
7244
7245 (defun js2-match-token (match &optional dont-unget)
7246 "Get next token and return t if it matches MATCH, a bytecode.
7247 Returns nil and consumes nothing if MATCH is not the next token."
7248 (if (/= (js2-get-token) match)
7249 (ignore (unless dont-unget (js2-unget-token)))
7250 t))
7251
7252 (defun js2-match-contextual-kwd (name)
7253 "Consume and return t if next token is `js2-NAME', and its
7254 string is NAME. Returns nil and keeps current token otherwise."
7255 (if (or (/= (js2-get-token) js2-NAME)
7256 (not (string= (js2-current-token-string) name)))
7257 (progn
7258 (js2-unget-token)
7259 nil)
7260 (js2-record-face 'font-lock-keyword-face)
7261 t))
7262
7263 (defun js2-get-prop-name-token ()
7264 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7265
7266 (defun js2-match-prop-name ()
7267 "Consume token and return t if next token is a valid property name.
7268 If `js2-language-version' is >= 180, a keyword or reserved word
7269 is considered valid name as well."
7270 (if (eq js2-NAME (js2-get-prop-name-token))
7271 t
7272 (js2-unget-token)
7273 nil))
7274
7275 (defun js2-must-match-prop-name (msg-id &optional pos len)
7276 (if (js2-match-prop-name)
7277 t
7278 (js2-report-error msg-id nil pos len)
7279 nil))
7280
7281 (defun js2-peek-token-or-eol ()
7282 "Return js2-EOL if the next token immediately follows a newline.
7283 Else returns the next token. Used in situations where we don't
7284 consider certain token types valid if they are preceded by a newline.
7285 One example is the postfix ++ or -- operator, which has to be on the
7286 same line as its operand."
7287 (let ((tt (js2-get-token))
7288 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7289 (js2-unget-token)
7290 (if follows-eol
7291 js2-EOL
7292 tt)))
7293
7294 (defun js2-must-match (token msg-id &optional pos len)
7295 "Match next token to token code TOKEN, or record a syntax error.
7296 MSG-ID is the error message to report if the match fails.
7297 Returns t on match, nil if no match."
7298 (if (js2-match-token token t)
7299 t
7300 (js2-report-error msg-id nil pos len)
7301 (js2-unget-token)
7302 nil))
7303
7304 (defun js2-must-match-name (msg-id)
7305 (if (js2-match-token js2-NAME t)
7306 t
7307 (if (eq (js2-current-token-type) js2-RESERVED)
7308 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7309 (js2-report-error msg-id)
7310 (js2-unget-token))
7311 nil))
7312
7313 (defsubst js2-inside-function ()
7314 (plusp js2-nesting-of-function))
7315
7316 (defun js2-set-requires-activation ()
7317 (if (js2-function-node-p js2-current-script-or-fn)
7318 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7319
7320 (defun js2-check-activation-name (name _token)
7321 (when (js2-inside-function)
7322 ;; skip language-version 1.2 check from Rhino
7323 (if (or (string= "arguments" name)
7324 (and js2-compiler-activation-names ; only used in codegen
7325 (gethash name js2-compiler-activation-names)))
7326 (js2-set-requires-activation))))
7327
7328 (defun js2-set-is-generator ()
7329 (let ((fn-node js2-current-script-or-fn))
7330 (when (and (js2-function-node-p fn-node)
7331 (not (js2-function-node-generator-type fn-node)))
7332 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7333
7334 (defun js2-must-have-xml ()
7335 (unless js2-compiler-xml-available
7336 (js2-report-error "msg.XML.not.available")))
7337
7338 (defun js2-push-scope (scope)
7339 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7340 (assert (js2-scope-p scope))
7341 (assert (null (js2-scope-parent-scope scope)))
7342 (assert (not (eq js2-current-scope scope)))
7343 (setf (js2-scope-parent-scope scope) js2-current-scope
7344 js2-current-scope scope))
7345
7346 (defsubst js2-pop-scope ()
7347 (setq js2-current-scope
7348 (js2-scope-parent-scope js2-current-scope)))
7349
7350 (defun js2-enter-loop (loop-node)
7351 (push loop-node js2-loop-set)
7352 (push loop-node js2-loop-and-switch-set)
7353 (js2-push-scope loop-node)
7354 ;; Tell the current labeled statement (if any) its statement,
7355 ;; and set the jump target of the first label to the loop.
7356 ;; These are used in `js2-parse-continue' to verify that the
7357 ;; continue target is an actual labeled loop. (And for codegen.)
7358 (when js2-labeled-stmt
7359 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7360 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7361 js2-labeled-stmt))) loop-node)))
7362
7363 (defun js2-exit-loop ()
7364 (pop js2-loop-set)
7365 (pop js2-loop-and-switch-set)
7366 (js2-pop-scope))
7367
7368 (defsubst js2-enter-switch (switch-node)
7369 (push switch-node js2-loop-and-switch-set))
7370
7371 (defsubst js2-exit-switch ()
7372 (pop js2-loop-and-switch-set))
7373
7374 (defun js2-parse (&optional buf cb)
7375 "Tell the js2 parser to parse a region of JavaScript.
7376
7377 BUF is a buffer or buffer name containing the code to parse.
7378 Call `narrow-to-region' first to parse only part of the buffer.
7379
7380 The returned AST root node is given some additional properties:
7381 `node-count' - total number of nodes in the AST
7382 `buffer' - BUF. The buffer it refers to may change or be killed,
7383 so the value is not necessarily reliable.
7384
7385 An optional callback CB can be specified to report parsing
7386 progress. If `(functionp CB)' returns t, it will be called with
7387 the current line number once before parsing begins, then again
7388 each time the lexer reaches a new line number.
7389
7390 CB can also be a list of the form `(symbol cb ...)' to specify
7391 multiple callbacks with different criteria. Each symbol is a
7392 criterion keyword, and the following element is the callback to
7393 call
7394
7395 :line - called whenever the line number changes
7396 :token - called for each new token consumed
7397
7398 The list of criteria could be extended to include entering or
7399 leaving a statement, an expression, or a function definition."
7400 (if (and cb (not (functionp cb)))
7401 (error "criteria callbacks not yet implemented"))
7402 (let ((inhibit-point-motion-hooks t)
7403 (js2-compiler-xml-available (>= js2-language-version 160))
7404 ;; This is a recursive-descent parser, so give it a big stack.
7405 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7406 (max-specpdl-size (max max-specpdl-size 3000))
7407 (case-fold-search nil)
7408 ast)
7409 (with-current-buffer (or buf (current-buffer))
7410 (setq js2-scanned-comments nil
7411 js2-parsed-errors nil
7412 js2-parsed-warnings nil
7413 js2-imenu-recorder nil
7414 js2-imenu-function-map nil
7415 js2-label-set nil)
7416 (js2-init-scanner)
7417 (setq ast (with-silent-modifications
7418 (js2-do-parse)))
7419 (unless js2-ts-hit-eof
7420 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7421 (setf (js2-ast-root-errors ast) js2-parsed-errors
7422 (js2-ast-root-warnings ast) js2-parsed-warnings)
7423 ;; if we didn't find any declarations, put a dummy in this list so we
7424 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7425 (unless js2-imenu-recorder
7426 (setq js2-imenu-recorder 'empty))
7427 (run-hooks 'js2-parse-finished-hook)
7428 ast)))
7429
7430 ;; Corresponds to Rhino's Parser.parse() method.
7431 (defun js2-do-parse ()
7432 "Parse current buffer starting from current point.
7433 Scanner should be initialized."
7434 (let ((pos js2-ts-cursor)
7435 (end js2-ts-cursor) ; in case file is empty
7436 root n tt)
7437 ;; initialize buffer-local parsing vars
7438 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7439 js2-current-script-or-fn root
7440 js2-current-scope root
7441 js2-nesting-of-function 0
7442 js2-labeled-stmt nil
7443 js2-recorded-identifiers nil) ; for js2-highlight
7444 (while (/= (setq tt (js2-get-token)) js2-EOF)
7445 (if (= tt js2-FUNCTION)
7446 (progn
7447 (setq n (if js2-called-by-compile-function
7448 (js2-parse-function-expr)
7449 (js2-parse-function-stmt))))
7450 ;; not a function - parse a statement
7451 (js2-unget-token)
7452 (setq n (js2-parse-statement)))
7453 ;; add function or statement to script
7454 (setq end (js2-node-end n))
7455 (js2-block-node-push root n))
7456 ;; add comments to root in lexical order
7457 (when js2-scanned-comments
7458 ;; if we find a comment beyond end of normal kids, use its end
7459 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7460 (dolist (comment js2-scanned-comments)
7461 (push comment (js2-ast-root-comments root))
7462 (js2-node-add-children root comment)))
7463 (setf (js2-node-len root) (- end pos))
7464 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7465 ;; Give extensions a chance to muck with things before highlighting starts.
7466 (let ((js2-additional-externs js2-additional-externs))
7467 (save-excursion
7468 (run-hooks 'js2-post-parse-callbacks))
7469 (js2-highlight-undeclared-vars))
7470 root))
7471
7472 (defun js2-parse-function-closure-body (fn-node)
7473 "Parse a JavaScript 1.8 function closure body."
7474 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7475 (if js2-ts-hit-eof
7476 (js2-report-error "msg.no.brace.body" nil
7477 (js2-node-pos fn-node)
7478 (- js2-ts-cursor (js2-node-pos fn-node)))
7479 (js2-node-add-children fn-node
7480 (setf (js2-function-node-body fn-node)
7481 (js2-parse-expr t))))))
7482
7483 (defun js2-parse-function-body (fn-node)
7484 (js2-must-match js2-LC "msg.no.brace.body"
7485 (js2-node-pos fn-node)
7486 (- js2-ts-cursor (js2-node-pos fn-node)))
7487 (let ((pos (js2-current-token-beg)) ; LC position
7488 (pn (make-js2-block-node)) ; starts at LC position
7489 tt
7490 end)
7491 (incf js2-nesting-of-function)
7492 (unwind-protect
7493 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7494 (= tt js2-EOF)
7495 (= tt js2-RC)))
7496 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7497 (js2-parse-statement)
7498 (js2-get-token)
7499 (js2-parse-function-stmt))))
7500 (decf js2-nesting-of-function))
7501 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7502 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7503 (setq end (js2-current-token-end)))
7504 (setf (js2-node-pos pn) pos
7505 (js2-node-len pn) (- end pos))
7506 (setf (js2-function-node-body fn-node) pn)
7507 (js2-node-add-children fn-node pn)
7508 pn))
7509
7510 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7511 "Declare and fontify destructuring parameters inside NODE.
7512 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7513 (cond
7514 ((js2-name-node-p node)
7515 (let (leftpos)
7516 (js2-define-symbol decl-type (js2-name-node-name node)
7517 node ignore-not-in-block)
7518 (when face
7519 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7520 (+ leftpos (js2-node-len node))
7521 face 'record))))
7522 ((js2-object-node-p node)
7523 (dolist (elem (js2-object-node-elems node))
7524 (js2-define-destruct-symbols
7525 ;; In abbreviated destructuring {a, b}, right == left.
7526 (js2-object-prop-node-right elem)
7527 decl-type face ignore-not-in-block)))
7528 ((js2-array-node-p node)
7529 (dolist (elem (js2-array-node-elems node))
7530 (when elem
7531 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7532 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7533 (js2-node-len node)))))
7534
7535 (defun js2-parse-function-params (function-type fn-node pos)
7536 (if (js2-match-token js2-RP)
7537 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7538 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7539 (eq (js2-current-token-type) js2-NAME)))
7540 params param default-found rest-param-at)
7541 (when paren-free-arrow
7542 (js2-unget-token))
7543 (loop for tt = (js2-peek-token)
7544 do
7545 (cond
7546 ;; destructuring param
7547 ((and (not paren-free-arrow)
7548 (or (= tt js2-LB) (= tt js2-LC)))
7549 (js2-get-token)
7550 (when default-found
7551 (js2-report-error "msg.no.default.after.default.param"))
7552 (setq param (js2-parse-destruct-primary-expr))
7553 (js2-define-destruct-symbols param
7554 js2-LP
7555 'js2-function-param)
7556 (push param params))
7557 ;; variable name
7558 (t
7559 (when (and (>= js2-language-version 200)
7560 (not paren-free-arrow)
7561 (js2-match-token js2-TRIPLEDOT)
7562 (not rest-param-at))
7563 ;; to report errors if there are more parameters
7564 (setq rest-param-at (length params)))
7565 (js2-must-match-name "msg.no.parm")
7566 (js2-record-face 'js2-function-param)
7567 (setq param (js2-create-name-node))
7568 (js2-define-symbol js2-LP (js2-current-token-string) param)
7569 ;; default parameter value
7570 (when (or (and default-found
7571 (not rest-param-at)
7572 (js2-must-match js2-ASSIGN
7573 "msg.no.default.after.default.param"
7574 (js2-node-pos param)
7575 (js2-node-len param)))
7576 (and (>= js2-language-version 200)
7577 (js2-match-token js2-ASSIGN)))
7578 (assert (not paren-free-arrow))
7579 (let* ((pos (js2-node-pos param))
7580 (tt (js2-current-token-type))
7581 (op-pos (- (js2-current-token-beg) pos))
7582 (left param)
7583 (right (js2-parse-assign-expr))
7584 (len (- (js2-node-end right) pos)))
7585 (setq param (make-js2-assign-node
7586 :type tt :pos pos :len len :op-pos op-pos
7587 :left left :right right)
7588 default-found t)
7589 (js2-node-add-children param left right)))
7590 (push param params)))
7591 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7592 (js2-report-error "msg.param.after.rest" nil
7593 (js2-node-pos param) (js2-node-len param)))
7594 while
7595 (js2-match-token js2-COMMA))
7596 (when (and (not paren-free-arrow)
7597 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7598 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7599 (when rest-param-at
7600 (setf (js2-function-node-rest-p fn-node) t))
7601 (dolist (p params)
7602 (js2-node-add-children fn-node p)
7603 (push p (js2-function-node-params fn-node))))))
7604
7605 (defun js2-check-inconsistent-return-warning (fn-node name)
7606 "Possibly show inconsistent-return warning.
7607 Last token scanned is the close-curly for the function body."
7608 (when (and js2-mode-show-strict-warnings
7609 js2-strict-inconsistent-return-warning
7610 (not (js2-has-consistent-return-usage
7611 (js2-function-node-body fn-node))))
7612 ;; Have it extend from close-curly to bol or beginning of block.
7613 (let ((pos (save-excursion
7614 (goto-char (js2-current-token-end))
7615 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7616 (point-at-bol))))
7617 (end (js2-current-token-end)))
7618 (if (plusp (js2-name-node-length name))
7619 (js2-add-strict-warning "msg.no.return.value"
7620 (js2-name-node-name name) pos end)
7621 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7622
7623 (defun js2-parse-function-stmt ()
7624 (let ((pos (js2-current-token-beg))
7625 (star-p (js2-match-token js2-MUL)))
7626 (js2-must-match-name "msg.unnamed.function.stmt")
7627 (let ((name (js2-create-name-node t))
7628 pn member-expr)
7629 (cond
7630 ((js2-match-token js2-LP)
7631 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7632 (js2-allow-member-expr-as-function-name
7633 (setq member-expr (js2-parse-member-expr-tail nil name))
7634 (js2-parse-highlight-member-expr-fn-name member-expr)
7635 (js2-must-match js2-LP "msg.no.paren.parms")
7636 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7637 (js2-function-node-member-expr pn) member-expr)
7638 pn)
7639 (t
7640 (js2-report-error "msg.no.paren.parms")
7641 (make-js2-error-node))))))
7642
7643 (defun js2-parse-function-expr ()
7644 (let ((pos (js2-current-token-beg))
7645 (star-p (js2-match-token js2-MUL))
7646 name)
7647 (when (js2-match-token js2-NAME)
7648 (setq name (js2-create-name-node t)))
7649 (js2-must-match js2-LP "msg.no.paren.parms")
7650 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7651
7652 (defun js2-parse-function (function-type pos star-p &optional name)
7653 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7654 beginning of the first token (function keyword, unless it's an
7655 arrow function), NAME is js2-name-node."
7656 (let (fn-node lp)
7657 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7658 (setq lp (js2-current-token-beg)))
7659 (setf fn-node (make-js2-function-node :pos pos
7660 :name name
7661 :form function-type
7662 :lp (if lp (- lp pos))
7663 :generator-type (and star-p 'STAR)))
7664 (when name
7665 (js2-set-face (js2-node-pos name) (js2-node-end name)
7666 'font-lock-function-name-face 'record)
7667 (when (and (eq function-type 'FUNCTION_STATEMENT)
7668 (plusp (js2-name-node-length name)))
7669 ;; Function statements define a symbol in the enclosing scope
7670 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7671 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7672 ;; 1. Nested functions are not affected by the dynamic scope flag
7673 ;; as dynamic scope is already a parent of their scope.
7674 ;; 2. Functions defined under the with statement also immune to
7675 ;; this setup, in which case dynamic scope is ignored in favor
7676 ;; of the with object.
7677 (setf (js2-function-node-ignore-dynamic fn-node) t))
7678 ;; dynamically bind all the per-function variables
7679 (let ((js2-current-script-or-fn fn-node)
7680 (js2-current-scope fn-node)
7681 (js2-nesting-of-with 0)
7682 (js2-end-flags 0)
7683 js2-label-set
7684 js2-loop-set
7685 js2-loop-and-switch-set)
7686 (js2-parse-function-params function-type fn-node pos)
7687 (when (eq function-type 'FUNCTION_ARROW)
7688 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7689 (if (and (>= js2-language-version 180)
7690 (/= (js2-peek-token) js2-LC))
7691 (js2-parse-function-closure-body fn-node)
7692 (js2-parse-function-body fn-node))
7693 (js2-check-inconsistent-return-warning fn-node name)
7694
7695 (when name
7696 (js2-node-add-children fn-node name)
7697 ;; Function expressions define a name only in the body of the
7698 ;; function, and only if not hidden by a parameter name
7699 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7700 (null (js2-scope-get-symbol js2-current-scope
7701 (js2-name-node-name name))))
7702 (js2-define-symbol js2-FUNCTION
7703 (js2-name-node-name name)
7704 fn-node))
7705 (when (eq function-type 'FUNCTION_STATEMENT)
7706 (js2-record-imenu-functions fn-node))))
7707
7708 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7709 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7710 ;; We wait until after parsing the function to set its parent scope,
7711 ;; since `js2-define-symbol' needs the defining-scope check to stop
7712 ;; at the function boundary when checking for redeclarations.
7713 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7714 fn-node))
7715
7716 (defun js2-parse-statements (&optional parent)
7717 "Parse a statement list. Last token consumed must be js2-LC.
7718
7719 PARENT can be a `js2-block-node', in which case the statements are
7720 appended to PARENT. Otherwise a new `js2-block-node' is created
7721 and returned.
7722
7723 This function does not match the closing js2-RC: the caller
7724 matches the RC so it can provide a suitable error message if not
7725 matched. This means it's up to the caller to set the length of
7726 the node to include the closing RC. The node start pos is set to
7727 the absolute buffer start position, and the caller should fix it
7728 up to be relative to the parent node. All children of this block
7729 node are given relative start positions and correct lengths."
7730 (let ((pn (or parent (make-js2-block-node)))
7731 tt)
7732 (setf (js2-node-pos pn) (js2-current-token-beg))
7733 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7734 (/= tt js2-RC))
7735 (js2-block-node-push pn (js2-parse-statement)))
7736 pn))
7737
7738 (defun js2-parse-statement ()
7739 (let (pn beg end)
7740 ;; coarse-grained user-interrupt check - needs work
7741 (and js2-parse-interruptable-p
7742 (zerop (% (incf js2-parse-stmt-count)
7743 js2-statements-per-pause))
7744 (input-pending-p)
7745 (throw 'interrupted t))
7746 (setq pn (js2-statement-helper))
7747 ;; no-side-effects warning check
7748 (unless (js2-node-has-side-effects pn)
7749 (setq end (js2-node-end pn))
7750 (save-excursion
7751 (goto-char end)
7752 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7753 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7754 pn))
7755
7756 ;; These correspond to the switch cases in Parser.statementHelper
7757 (defconst js2-parsers
7758 (let ((parsers (make-vector js2-num-tokens
7759 #'js2-parse-expr-stmt)))
7760 (aset parsers js2-BREAK #'js2-parse-break)
7761 (aset parsers js2-CLASS #'js2-parse-class-stmt)
7762 (aset parsers js2-CONST #'js2-parse-const-var)
7763 (aset parsers js2-CONTINUE #'js2-parse-continue)
7764 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7765 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7766 (aset parsers js2-DO #'js2-parse-do)
7767 (aset parsers js2-FOR #'js2-parse-for)
7768 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7769 (aset parsers js2-IF #'js2-parse-if)
7770 (aset parsers js2-LC #'js2-parse-block)
7771 (aset parsers js2-LET #'js2-parse-let-stmt)
7772 (aset parsers js2-NAME #'js2-parse-name-or-label)
7773 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7774 (aset parsers js2-SEMI #'js2-parse-semi)
7775 (aset parsers js2-SWITCH #'js2-parse-switch)
7776 (aset parsers js2-THROW #'js2-parse-throw)
7777 (aset parsers js2-TRY #'js2-parse-try)
7778 (aset parsers js2-VAR #'js2-parse-const-var)
7779 (aset parsers js2-WHILE #'js2-parse-while)
7780 (aset parsers js2-WITH #'js2-parse-with)
7781 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7782 parsers)
7783 "A vector mapping token types to parser functions.")
7784
7785 (defun js2-parse-warn-missing-semi (beg end)
7786 (and js2-mode-show-strict-warnings
7787 js2-strict-missing-semi-warning
7788 (js2-add-strict-warning
7789 "msg.missing.semi" nil
7790 ;; back up to beginning of statement or line
7791 (max beg (save-excursion
7792 (goto-char end)
7793 (point-at-bol)))
7794 end)))
7795
7796 (defconst js2-no-semi-insertion
7797 (list js2-IF
7798 js2-SWITCH
7799 js2-WHILE
7800 js2-DO
7801 js2-FOR
7802 js2-TRY
7803 js2-WITH
7804 js2-LC
7805 js2-ERROR
7806 js2-SEMI
7807 js2-CLASS
7808 js2-FUNCTION)
7809 "List of tokens that don't do automatic semicolon insertion.")
7810
7811 (defconst js2-autoinsert-semi-and-warn
7812 (list js2-ERROR js2-EOF js2-RC))
7813
7814 (defun js2-statement-helper ()
7815 (let* ((tt (js2-get-token))
7816 (first-tt tt)
7817 (parser (if (= tt js2-ERROR)
7818 #'js2-parse-semi
7819 (aref js2-parsers tt)))
7820 pn)
7821 ;; If the statement is set, then it's been told its label by now.
7822 (and js2-labeled-stmt
7823 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7824 (setq js2-labeled-stmt nil))
7825 (setq pn (funcall parser))
7826 ;; Don't do auto semi insertion for certain statement types.
7827 (unless (or (memq first-tt js2-no-semi-insertion)
7828 (js2-labeled-stmt-node-p pn))
7829 (js2-auto-insert-semicolon pn))
7830 pn))
7831
7832 (defun js2-auto-insert-semicolon (pn)
7833 (let* ((tt (js2-get-token))
7834 (pos (js2-node-pos pn)))
7835 (cond
7836 ((= tt js2-SEMI)
7837 ;; extend the node bounds to include the semicolon.
7838 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7839 ((memq tt js2-autoinsert-semi-and-warn)
7840 (js2-unget-token) ; Not ';', do not consume.
7841 ;; Autoinsert ;
7842 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7843 (t
7844 (if (not (js2-token-follows-eol-p (js2-current-token)))
7845 ;; Report error if no EOL or autoinsert ';' otherwise
7846 (js2-report-error "msg.no.semi.stmt")
7847 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7848 (js2-unget-token) ; Not ';', do not consume.
7849 ))))
7850
7851 (defun js2-parse-condition ()
7852 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7853 The parens are discarded and the expression node is returned.
7854 The `pos' field of the return value is set to an absolute position
7855 that must be fixed up by the caller.
7856 Return value is a list (EXPR LP RP), with absolute paren positions."
7857 (let (pn lp rp)
7858 (if (js2-must-match js2-LP "msg.no.paren.cond")
7859 (setq lp (js2-current-token-beg)))
7860 (setq pn (js2-parse-expr))
7861 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7862 (setq rp (js2-current-token-beg)))
7863 ;; Report strict warning on code like "if (a = 7) ..."
7864 (if (and js2-strict-cond-assign-warning
7865 (js2-assign-node-p pn))
7866 (js2-add-strict-warning "msg.equal.as.assign" nil
7867 (js2-node-pos pn)
7868 (+ (js2-node-pos pn)
7869 (js2-node-len pn))))
7870 (list pn lp rp)))
7871
7872 (defun js2-parse-if ()
7873 "Parser for if-statement. Last matched token must be js2-IF."
7874 (let ((pos (js2-current-token-beg))
7875 cond if-true if-false else-pos end pn)
7876 (setq cond (js2-parse-condition)
7877 if-true (js2-parse-statement)
7878 if-false (if (js2-match-token js2-ELSE)
7879 (progn
7880 (setq else-pos (- (js2-current-token-beg) pos))
7881 (js2-parse-statement)))
7882 end (js2-node-end (or if-false if-true))
7883 pn (make-js2-if-node :pos pos
7884 :len (- end pos)
7885 :condition (car cond)
7886 :then-part if-true
7887 :else-part if-false
7888 :else-pos else-pos
7889 :lp (js2-relpos (second cond) pos)
7890 :rp (js2-relpos (third cond) pos)))
7891 (js2-node-add-children pn (car cond) if-true if-false)
7892 pn))
7893
7894 (defun js2-parse-switch ()
7895 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7896 (let ((pos (js2-current-token-beg))
7897 tt pn discriminant has-default case-expr case-node
7898 case-pos cases stmt lp)
7899 (if (js2-must-match js2-LP "msg.no.paren.switch")
7900 (setq lp (js2-current-token-beg)))
7901 (setq discriminant (js2-parse-expr)
7902 pn (make-js2-switch-node :discriminant discriminant
7903 :pos pos
7904 :lp (js2-relpos lp pos)))
7905 (js2-node-add-children pn discriminant)
7906 (js2-enter-switch pn)
7907 (unwind-protect
7908 (progn
7909 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7910 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7911 (js2-must-match js2-LC "msg.no.brace.switch")
7912 (catch 'break
7913 (while t
7914 (setq tt (js2-next-token)
7915 case-pos (js2-current-token-beg))
7916 (cond
7917 ((= tt js2-RC)
7918 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7919 (throw 'break nil)) ; done
7920 ((= tt js2-CASE)
7921 (setq case-expr (js2-parse-expr))
7922 (js2-must-match js2-COLON "msg.no.colon.case"))
7923 ((= tt js2-DEFAULT)
7924 (if has-default
7925 (js2-report-error "msg.double.switch.default"))
7926 (setq has-default t
7927 case-expr nil)
7928 (js2-must-match js2-COLON "msg.no.colon.case"))
7929 (t
7930 (js2-report-error "msg.bad.switch")
7931 (throw 'break nil)))
7932 (setq case-node (make-js2-case-node :pos case-pos
7933 :len (- (js2-current-token-end) case-pos)
7934 :expr case-expr))
7935 (js2-node-add-children case-node case-expr)
7936 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7937 (/= tt js2-CASE)
7938 (/= tt js2-DEFAULT)
7939 (/= tt js2-EOF))
7940 (setf stmt (js2-parse-statement)
7941 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7942 (js2-block-node-push case-node stmt))
7943 (push case-node cases)))
7944 ;; add cases last, as pushing reverses the order to be correct
7945 (dolist (kid cases)
7946 (js2-node-add-children pn kid)
7947 (push kid (js2-switch-node-cases pn)))
7948 pn) ; return value
7949 (js2-exit-switch))))
7950
7951 (defun js2-parse-while ()
7952 "Parser for while-statement. Last matched token must be js2-WHILE."
7953 (let ((pos (js2-current-token-beg))
7954 (pn (make-js2-while-node))
7955 cond body)
7956 (js2-enter-loop pn)
7957 (unwind-protect
7958 (progn
7959 (setf cond (js2-parse-condition)
7960 (js2-while-node-condition pn) (car cond)
7961 body (js2-parse-statement)
7962 (js2-while-node-body pn) body
7963 (js2-node-len pn) (- (js2-node-end body) pos)
7964 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7965 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7966 (js2-node-add-children pn body (car cond)))
7967 (js2-exit-loop))
7968 pn))
7969
7970 (defun js2-parse-do ()
7971 "Parser for do-statement. Last matched token must be js2-DO."
7972 (let ((pos (js2-current-token-beg))
7973 (pn (make-js2-do-node))
7974 cond body end)
7975 (js2-enter-loop pn)
7976 (unwind-protect
7977 (progn
7978 (setq body (js2-parse-statement))
7979 (js2-must-match js2-WHILE "msg.no.while.do")
7980 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7981 cond (js2-parse-condition)
7982 (js2-do-node-condition pn) (car cond)
7983 (js2-do-node-body pn) body
7984 end js2-ts-cursor
7985 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7986 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7987 (js2-node-add-children pn (car cond) body))
7988 (js2-exit-loop))
7989 ;; Always auto-insert semicolon to follow SpiderMonkey:
7990 ;; It is required by ECMAScript but is ignored by the rest of
7991 ;; world; see bug 238945
7992 (if (js2-match-token js2-SEMI)
7993 (setq end js2-ts-cursor))
7994 (setf (js2-node-len pn) (- end pos))
7995 pn))
7996
7997 (defun js2-parse-for ()
7998 "Parser for for-statement. Last matched token must be js2-FOR.
7999 Parses for, for-in, and for each-in statements."
8000 (let ((for-pos (js2-current-token-beg))
8001 pn is-for-each is-for-in-or-of is-for-of
8002 in-pos each-pos tmp-pos
8003 init ; Node init is also foo in 'foo in object'
8004 cond ; Node cond is also object in 'foo in object'
8005 incr ; 3rd section of for-loop initializer
8006 body tt lp rp)
8007 ;; See if this is a for each () instead of just a for ()
8008 (when (js2-match-token js2-NAME)
8009 (if (string= "each" (js2-current-token-string))
8010 (progn
8011 (setq is-for-each t
8012 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8013 (js2-record-face 'font-lock-keyword-face))
8014 (js2-report-error "msg.no.paren.for")))
8015 (if (js2-must-match js2-LP "msg.no.paren.for")
8016 (setq lp (- (js2-current-token-beg) for-pos)))
8017 (setq tt (js2-get-token))
8018 ;; 'for' makes local scope
8019 (js2-push-scope (make-js2-scope))
8020 (unwind-protect
8021 ;; parse init clause
8022 (let ((js2-in-for-init t)) ; set as dynamic variable
8023 (cond
8024 ((= tt js2-SEMI)
8025 (js2-unget-token)
8026 (setq init (make-js2-empty-expr-node)))
8027 ((or (= tt js2-VAR) (= tt js2-LET))
8028 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8029 (t
8030 (js2-unget-token)
8031 (setq init (js2-parse-expr)))))
8032 (if (or (js2-match-token js2-IN)
8033 (and (>= js2-language-version 200)
8034 (js2-match-contextual-kwd "of")
8035 (setq is-for-of t)))
8036 (setq is-for-in-or-of t
8037 in-pos (- (js2-current-token-beg) for-pos)
8038 ;; scope of iteration target object is not the scope we've created above.
8039 ;; stash current scope temporary.
8040 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8041 (js2-parse-expr))) ; object over which we're iterating
8042 ;; else ordinary for loop - parse cond and incr
8043 (js2-must-match js2-SEMI "msg.no.semi.for")
8044 (setq cond (if (= (js2-peek-token) js2-SEMI)
8045 (make-js2-empty-expr-node) ; no loop condition
8046 (js2-parse-expr)))
8047 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8048 (setq tmp-pos (js2-current-token-end)
8049 incr (if (= (js2-peek-token) js2-RP)
8050 (make-js2-empty-expr-node :pos tmp-pos)
8051 (js2-parse-expr))))
8052 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8053 (setq rp (- (js2-current-token-beg) for-pos)))
8054 (if (not is-for-in-or-of)
8055 (setq pn (make-js2-for-node :init init
8056 :condition cond
8057 :update incr
8058 :lp lp
8059 :rp rp))
8060 ;; cond could be null if 'in obj' got eaten by the init node.
8061 (if (js2-infix-node-p init)
8062 ;; it was (foo in bar) instead of (var foo in bar)
8063 (setq cond (js2-infix-node-right init)
8064 init (js2-infix-node-left init))
8065 (if (and (js2-var-decl-node-p init)
8066 (> (length (js2-var-decl-node-kids init)) 1))
8067 (js2-report-error "msg.mult.index")))
8068 (setq pn (make-js2-for-in-node :iterator init
8069 :object cond
8070 :in-pos in-pos
8071 :foreach-p is-for-each
8072 :each-pos each-pos
8073 :forof-p is-for-of
8074 :lp lp
8075 :rp rp)))
8076 (unwind-protect
8077 (progn
8078 (js2-enter-loop pn)
8079 ;; We have to parse the body -after- creating the loop node,
8080 ;; so that the loop node appears in the js2-loop-set, allowing
8081 ;; break/continue statements to find the enclosing loop.
8082 (setf body (js2-parse-statement)
8083 (js2-loop-node-body pn) body
8084 (js2-node-pos pn) for-pos
8085 (js2-node-len pn) (- (js2-node-end body) for-pos))
8086 (js2-node-add-children pn init cond incr body))
8087 ;; finally
8088 (js2-exit-loop))
8089 (js2-pop-scope))
8090 pn))
8091
8092 (defun js2-parse-try ()
8093 "Parser for try-statement. Last matched token must be js2-TRY."
8094 (let ((try-pos (js2-current-token-beg))
8095 try-end
8096 try-block
8097 catch-blocks
8098 finally-block
8099 saw-default-catch
8100 peek
8101 param
8102 catch-cond
8103 catch-node
8104 guard-kwd
8105 catch-pos
8106 finally-pos
8107 pn
8108 block
8109 lp
8110 rp)
8111 (if (/= (js2-peek-token) js2-LC)
8112 (js2-report-error "msg.no.brace.try"))
8113 (setq try-block (js2-parse-statement)
8114 try-end (js2-node-end try-block)
8115 peek (js2-peek-token))
8116 (cond
8117 ((= peek js2-CATCH)
8118 (while (js2-match-token js2-CATCH)
8119 (setq catch-pos (js2-current-token-beg)
8120 guard-kwd nil
8121 catch-cond nil
8122 lp nil
8123 rp nil)
8124 (if saw-default-catch
8125 (js2-report-error "msg.catch.unreachable"))
8126 (if (js2-must-match js2-LP "msg.no.paren.catch")
8127 (setq lp (- (js2-current-token-beg) catch-pos)))
8128 (js2-push-scope (make-js2-scope))
8129 (let ((tt (js2-peek-token)))
8130 (cond
8131 ;; destructuring pattern
8132 ;; catch ({ message, file }) { ... }
8133 ((or (= tt js2-LB) (= tt js2-LC))
8134 (js2-get-token)
8135 (setq param (js2-parse-destruct-primary-expr))
8136 (js2-define-destruct-symbols param js2-LET nil))
8137 ;; simple name
8138 (t
8139 (js2-must-match-name "msg.bad.catchcond")
8140 (setq param (js2-create-name-node))
8141 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8142 ;; pattern guard
8143 (if (js2-match-token js2-IF)
8144 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8145 catch-cond (js2-parse-expr))
8146 (setq saw-default-catch t))
8147 (if (js2-must-match js2-RP "msg.bad.catchcond")
8148 (setq rp (- (js2-current-token-beg) catch-pos)))
8149 (js2-must-match js2-LC "msg.no.brace.catchblock")
8150 (setq block (js2-parse-statements)
8151 try-end (js2-node-end block)
8152 catch-node (make-js2-catch-node :pos catch-pos
8153 :param param
8154 :guard-expr catch-cond
8155 :guard-kwd guard-kwd
8156 :block block
8157 :lp lp
8158 :rp rp))
8159 (js2-pop-scope)
8160 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8161 (setq try-end (js2-current-token-beg)))
8162 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8163 (js2-node-len catch-node) (- try-end catch-pos))
8164 (js2-node-add-children catch-node param catch-cond block)
8165 (push catch-node catch-blocks)))
8166 ((/= peek js2-FINALLY)
8167 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8168 (js2-node-pos try-block)
8169 (- (setq try-end (js2-node-end try-block))
8170 (js2-node-pos try-block)))))
8171 (when (js2-match-token js2-FINALLY)
8172 (setq finally-pos (js2-current-token-beg)
8173 block (js2-parse-statement)
8174 try-end (js2-node-end block)
8175 finally-block (make-js2-finally-node :pos finally-pos
8176 :len (- try-end finally-pos)
8177 :body block))
8178 (js2-node-add-children finally-block block))
8179 (setq pn (make-js2-try-node :pos try-pos
8180 :len (- try-end try-pos)
8181 :try-block try-block
8182 :finally-block finally-block))
8183 (js2-node-add-children pn try-block finally-block)
8184 ;; push them onto the try-node, which reverses and corrects their order
8185 (dolist (cb catch-blocks)
8186 (js2-node-add-children pn cb)
8187 (push cb (js2-try-node-catch-clauses pn)))
8188 pn))
8189
8190 (defun js2-parse-throw ()
8191 "Parser for throw-statement. Last matched token must be js2-THROW."
8192 (let ((pos (js2-current-token-beg))
8193 expr pn)
8194 (if (= (js2-peek-token-or-eol) js2-EOL)
8195 ;; ECMAScript does not allow new lines before throw expression,
8196 ;; see bug 256617
8197 (js2-report-error "msg.bad.throw.eol"))
8198 (setq expr (js2-parse-expr)
8199 pn (make-js2-throw-node :pos pos
8200 :len (- (js2-node-end expr) pos)
8201 :expr expr))
8202 (js2-node-add-children pn expr)
8203 pn))
8204
8205 (defun js2-match-jump-label-name (label-name)
8206 "If break/continue specified a label, return that label's labeled stmt.
8207 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8208 does not match an existing label, reports an error and returns nil."
8209 (let ((bundle (cdr (assoc label-name js2-label-set))))
8210 (if (null bundle)
8211 (js2-report-error "msg.undef.label"))
8212 bundle))
8213
8214 (defun js2-parse-break ()
8215 "Parser for break-statement. Last matched token must be js2-BREAK."
8216 (let ((pos (js2-current-token-beg))
8217 (end (js2-current-token-end))
8218 break-target ; statement to break from
8219 break-label ; in "break foo", name-node representing the foo
8220 labels ; matching labeled statement to break to
8221 pn)
8222 (when (eq (js2-peek-token-or-eol) js2-NAME)
8223 (js2-get-token)
8224 (setq break-label (js2-create-name-node)
8225 end (js2-node-end break-label)
8226 ;; matchJumpLabelName only matches if there is one
8227 labels (js2-match-jump-label-name (js2-current-token-string))
8228 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8229 (unless (or break-target break-label)
8230 ;; no break target specified - try for innermost enclosing loop/switch
8231 (if (null js2-loop-and-switch-set)
8232 (unless break-label
8233 (js2-report-error "msg.bad.break" nil pos (length "break")))
8234 (setq break-target (car js2-loop-and-switch-set))))
8235 (setq pn (make-js2-break-node :pos pos
8236 :len (- end pos)
8237 :label break-label
8238 :target break-target))
8239 (js2-node-add-children pn break-label) ; but not break-target
8240 pn))
8241
8242 (defun js2-parse-continue ()
8243 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8244 (let ((pos (js2-current-token-beg))
8245 (end (js2-current-token-end))
8246 label ; optional user-specified label, a `js2-name-node'
8247 labels ; current matching labeled stmt, if any
8248 target ; the `js2-loop-node' target of this continue stmt
8249 pn)
8250 (when (= (js2-peek-token-or-eol) js2-NAME)
8251 (js2-get-token)
8252 (setq label (js2-create-name-node)
8253 end (js2-node-end label)
8254 ;; matchJumpLabelName only matches if there is one
8255 labels (js2-match-jump-label-name (js2-current-token-string))))
8256 (cond
8257 ((null labels) ; no current label to go to
8258 (if (null js2-loop-set) ; no loop to continue to
8259 (js2-report-error "msg.continue.outside" nil pos
8260 (length "continue"))
8261 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8262 (t
8263 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8264 (setq target (js2-labeled-stmt-node-stmt labels))
8265 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8266 (setq pn (make-js2-continue-node :pos pos
8267 :len (- end pos)
8268 :label label
8269 :target target))
8270 (js2-node-add-children pn label) ; but not target - it's not our child
8271 pn))
8272
8273 (defun js2-parse-with ()
8274 "Parser for with-statement. Last matched token must be js2-WITH."
8275 (let ((pos (js2-current-token-beg))
8276 obj body pn lp rp)
8277 (if (js2-must-match js2-LP "msg.no.paren.with")
8278 (setq lp (js2-current-token-beg)))
8279 (setq obj (js2-parse-expr))
8280 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8281 (setq rp (js2-current-token-beg)))
8282 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8283 (setq body (js2-parse-statement)))
8284 (setq pn (make-js2-with-node :pos pos
8285 :len (- (js2-node-end body) pos)
8286 :object obj
8287 :body body
8288 :lp (js2-relpos lp pos)
8289 :rp (js2-relpos rp pos)))
8290 (js2-node-add-children pn obj body)
8291 pn))
8292
8293 (defun js2-parse-const-var ()
8294 "Parser for var- or const-statement.
8295 Last matched token must be js2-CONST or js2-VAR."
8296 (let ((tt (js2-current-token-type))
8297 (pos (js2-current-token-beg))
8298 expr pn)
8299 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8300 pn (make-js2-expr-stmt-node :pos pos
8301 :len (- (js2-node-end expr) pos)
8302 :expr expr))
8303 (js2-node-add-children pn expr)
8304 pn))
8305
8306 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8307 (let ((pn (make-js2-expr-stmt-node :pos pos
8308 :len (js2-node-len expr)
8309 :type (if (js2-inside-function)
8310 js2-EXPR_VOID
8311 js2-EXPR_RESULT)
8312 :expr expr)))
8313 (if add-child
8314 (js2-node-add-children pn expr))
8315 pn))
8316
8317 (defun js2-parse-let-stmt ()
8318 "Parser for let-statement. Last matched token must be js2-LET."
8319 (let ((pos (js2-current-token-beg))
8320 expr pn)
8321 (if (= (js2-peek-token) js2-LP)
8322 ;; let expression in statement context
8323 (setq expr (js2-parse-let pos 'statement)
8324 pn (js2-wrap-with-expr-stmt pos expr t))
8325 ;; else we're looking at a statement like let x=6, y=7;
8326 (setf expr (js2-parse-variables js2-LET pos)
8327 pn (js2-wrap-with-expr-stmt pos expr t)
8328 (js2-node-type pn) js2-EXPR_RESULT))
8329 pn))
8330
8331 (defun js2-parse-ret-yield ()
8332 (js2-parse-return-or-yield (js2-current-token-type) nil))
8333
8334 (defconst js2-parse-return-stmt-enders
8335 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8336
8337 (defsubst js2-now-all-set (before after mask)
8338 "Return whether or not the bits in the mask have changed to all set.
8339 BEFORE is bits before change, AFTER is bits after change, and MASK is
8340 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8341 but not BEFORE."
8342 (and (/= (logand before mask) mask)
8343 (= (logand after mask) mask)))
8344
8345 (defun js2-parse-return-or-yield (tt expr-context)
8346 (let* ((pos (js2-current-token-beg))
8347 (end (js2-current-token-end))
8348 (before js2-end-flags)
8349 (inside-function (js2-inside-function))
8350 (gen-type (and inside-function (js2-function-node-generator-type
8351 js2-current-script-or-fn)))
8352 e ret name yield-star-p)
8353 (unless inside-function
8354 (js2-report-error (if (eq tt js2-RETURN)
8355 "msg.bad.return"
8356 "msg.bad.yield")))
8357 (when (and inside-function
8358 (eq gen-type 'STAR)
8359 (js2-match-token js2-MUL))
8360 (setq yield-star-p t))
8361 ;; This is ugly, but we don't want to require a semicolon.
8362 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8363 (setq e (js2-parse-expr)
8364 end (js2-node-end e)))
8365 (cond
8366 ((eq tt js2-RETURN)
8367 (js2-set-flag js2-end-flags (if (null e)
8368 js2-end-returns
8369 js2-end-returns-value))
8370 (setq ret (make-js2-return-node :pos pos
8371 :len (- end pos)
8372 :retval e))
8373 (js2-node-add-children ret e)
8374 ;; See if we need a strict mode warning.
8375 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8376 ;; more thorough and accurate than this before/after flag check.
8377 ;; E.g. if there's a finally-block that always returns, we shouldn't
8378 ;; show a warning generated by inconsistent returns in the catch blocks.
8379 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8380 ;; so we know which returns/yields to highlight, and we should get rid of
8381 ;; all the checking in `js2-parse-return-or-yield'.
8382 (if (and js2-strict-inconsistent-return-warning
8383 (js2-now-all-set before js2-end-flags
8384 (logior js2-end-returns js2-end-returns-value)))
8385 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8386 ((eq gen-type 'COMPREHENSION)
8387 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8388 ;; like SpiderMonkey does.
8389 (js2-report-error "msg.syntax" nil pos 5))
8390 (t
8391 (setq ret (make-js2-yield-node :pos pos
8392 :len (- end pos)
8393 :value e
8394 :star-p yield-star-p))
8395 (js2-node-add-children ret e)
8396 (unless expr-context
8397 (setq e ret
8398 ret (js2-wrap-with-expr-stmt pos e t))
8399 (js2-set-requires-activation)
8400 (js2-set-is-generator))))
8401 ;; see if we are mixing yields and value returns.
8402 (when (and inside-function
8403 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8404 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8405 'LEGACY))
8406 (setq name (js2-function-name js2-current-script-or-fn))
8407 (if (zerop (length name))
8408 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8409 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8410 ret))
8411
8412 (defun js2-parse-debugger ()
8413 (make-js2-keyword-node :type js2-DEBUGGER))
8414
8415 (defun js2-parse-block ()
8416 "Parser for a curly-delimited statement block.
8417 Last token matched must be `js2-LC'."
8418 (let ((pos (js2-current-token-beg))
8419 (pn (make-js2-scope)))
8420 (js2-push-scope pn)
8421 (unwind-protect
8422 (progn
8423 (js2-parse-statements pn)
8424 (js2-must-match js2-RC "msg.no.brace.block")
8425 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8426 (js2-pop-scope))
8427 pn))
8428
8429 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8430 (defun js2-parse-semi ()
8431 "Parse a statement or handle an error.
8432 Current token type is `js2-SEMI' or `js2-ERROR'."
8433 (let ((tt (js2-current-token-type)) pos len)
8434 (if (eq tt js2-SEMI)
8435 (make-js2-empty-expr-node :len 1)
8436 (setq pos (js2-current-token-beg)
8437 len (- (js2-current-token-end) pos))
8438 (js2-report-error "msg.syntax" nil pos len)
8439 (make-js2-error-node :pos pos :len len))))
8440
8441 (defun js2-parse-default-xml-namespace ()
8442 "Parse a `default xml namespace = <expr>' e4x statement."
8443 (let ((pos (js2-current-token-beg))
8444 end len expr unary)
8445 (js2-must-have-xml)
8446 (js2-set-requires-activation)
8447 (setq len (- js2-ts-cursor pos))
8448 (unless (and (js2-match-token js2-NAME)
8449 (string= (js2-current-token-string) "xml"))
8450 (js2-report-error "msg.bad.namespace" nil pos len))
8451 (unless (and (js2-match-token js2-NAME)
8452 (string= (js2-current-token-string) "namespace"))
8453 (js2-report-error "msg.bad.namespace" nil pos len))
8454 (unless (js2-match-token js2-ASSIGN)
8455 (js2-report-error "msg.bad.namespace" nil pos len))
8456 (setq expr (js2-parse-expr)
8457 end (js2-node-end expr)
8458 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8459 :pos pos
8460 :len (- end pos)
8461 :operand expr))
8462 (js2-node-add-children unary expr)
8463 (make-js2-expr-stmt-node :pos pos
8464 :len (- end pos)
8465 :expr unary)))
8466
8467 (defun js2-record-label (label bundle)
8468 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8469 (js2-get-token)
8470 (let ((name (js2-label-node-name label))
8471 labeled-stmt
8472 dup)
8473 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8474 ;; flag both labels if possible when used in editing mode
8475 (if (and js2-parse-ide-mode
8476 (setq dup (js2-get-label-by-name labeled-stmt name)))
8477 (js2-report-error "msg.dup.label" nil
8478 (js2-node-abs-pos dup) (js2-node-len dup)))
8479 (js2-report-error "msg.dup.label" nil
8480 (js2-node-pos label) (js2-node-len label)))
8481 (js2-labeled-stmt-node-add-label bundle label)
8482 (js2-node-add-children bundle label)
8483 ;; Add one reference to the bundle per label in `js2-label-set'
8484 (push (cons name bundle) js2-label-set)))
8485
8486 (defun js2-parse-name-or-label ()
8487 "Parser for identifier or label. Last token matched must be js2-NAME.
8488 Called when we found a name in a statement context. If it's a label, we gather
8489 up any following labels and the next non-label statement into a
8490 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8491 expression and return it wrapped in a `js2-expr-stmt-node'."
8492 (let ((pos (js2-current-token-beg))
8493 expr stmt bundle
8494 (continue t))
8495 ;; set check for label and call down to `js2-parse-primary-expr'
8496 (setq expr (js2-maybe-parse-label))
8497 (if (null expr)
8498 ;; Parse the non-label expression and wrap with expression stmt.
8499 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8500 ;; else parsed a label
8501 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8502 (js2-record-label expr bundle)
8503 ;; look for more labels
8504 (while (and continue (= (js2-get-token) js2-NAME))
8505 (if (setq expr (js2-maybe-parse-label))
8506 (js2-record-label expr bundle)
8507 (setq expr (js2-parse-expr)
8508 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8509 continue nil)
8510 (js2-auto-insert-semicolon stmt)))
8511 ;; no more labels; now parse the labeled statement
8512 (unwind-protect
8513 (unless stmt
8514 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8515 (js2-unget-token)
8516 (setq stmt (js2-statement-helper))))
8517 ;; remove the labels for this statement from the global set
8518 (dolist (label (js2-labeled-stmt-node-labels bundle))
8519 (setq js2-label-set (remove label js2-label-set))))
8520 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8521 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8522 (js2-node-add-children bundle stmt)
8523 bundle)))
8524
8525 (defun js2-maybe-parse-label ()
8526 (assert (= (js2-current-token-type) js2-NAME))
8527 (let (label-pos
8528 (next-tt (js2-get-token))
8529 (label-end (js2-current-token-end)))
8530 ;; Do not consume colon, it is used as unwind indicator
8531 ;; to return to statementHelper.
8532 (js2-unget-token)
8533 (if (= next-tt js2-COLON)
8534 (prog2
8535 (setq label-pos (js2-current-token-beg))
8536 (make-js2-label-node :pos label-pos
8537 :len (- label-end label-pos)
8538 :name (js2-current-token-string))
8539 (js2-set-face label-pos
8540 label-end
8541 'font-lock-variable-name-face 'record))
8542 ;; Backtrack from the name token, too.
8543 (js2-unget-token)
8544 nil)))
8545
8546 (defun js2-parse-expr-stmt ()
8547 "Default parser in statement context, if no recognized statement found."
8548 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8549 (progn
8550 (js2-unget-token)
8551 (js2-parse-expr)) t))
8552
8553 (defun js2-parse-variables (decl-type pos)
8554 "Parse a comma-separated list of variable declarations.
8555 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8556
8557 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8558 For 'var' or 'const', the keyword should be the token last scanned.
8559
8560 POS is the position where the node should start. It's sometimes the
8561 var/const/let keyword, and other times the beginning of the first token
8562 in the first variable declaration.
8563
8564 Returns the parsed `js2-var-decl-node' expression node."
8565 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8566 :pos pos))
8567 destructuring kid-pos tt init name end nbeg nend vi
8568 (continue t))
8569 ;; Example:
8570 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8571 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8572 ;; var {a, b} = baz;
8573 (while continue
8574 (setq destructuring nil
8575 name nil
8576 tt (js2-get-token)
8577 kid-pos (js2-current-token-beg)
8578 end (js2-current-token-end)
8579 init nil)
8580 (if (or (= tt js2-LB) (= tt js2-LC))
8581 ;; Destructuring assignment, e.g., var [a, b] = ...
8582 (setq destructuring (js2-parse-destruct-primary-expr)
8583 end (js2-node-end destructuring))
8584 ;; Simple variable name
8585 (js2-unget-token)
8586 (when (js2-must-match-name "msg.bad.var")
8587 (setq name (js2-create-name-node)
8588 nbeg (js2-current-token-beg)
8589 nend (js2-current-token-end)
8590 end nend)
8591 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8592 (when (js2-match-token js2-ASSIGN)
8593 (setq init (js2-parse-assign-expr)
8594 end (js2-node-end init))
8595 (js2-record-imenu-functions init name))
8596 (when name
8597 (js2-set-face nbeg nend (if (js2-function-node-p init)
8598 'font-lock-function-name-face
8599 'font-lock-variable-name-face)
8600 'record))
8601 (setq vi (make-js2-var-init-node :pos kid-pos
8602 :len (- end kid-pos)
8603 :type decl-type))
8604 (if destructuring
8605 (progn
8606 (if (and (null init) (not js2-in-for-init))
8607 (js2-report-error "msg.destruct.assign.no.init"))
8608 (js2-define-destruct-symbols destructuring
8609 decl-type
8610 'font-lock-variable-name-face)
8611 (setf (js2-var-init-node-target vi) destructuring))
8612 (setf (js2-var-init-node-target vi) name))
8613 (setf (js2-var-init-node-initializer vi) init)
8614 (js2-node-add-children vi name destructuring init)
8615 (js2-block-node-push result vi)
8616 (unless (js2-match-token js2-COMMA)
8617 (setq continue nil)))
8618 (setf (js2-node-len result) (- end pos))
8619 result))
8620
8621 (defun js2-parse-let (pos &optional stmt-p)
8622 "Parse a let expression or statement.
8623 A let-expression is of the form `let (vars) expr'.
8624 A let-statment is of the form `let (vars) {statements}'.
8625 The third form of let is a variable declaration list, handled
8626 by `js2-parse-variables'."
8627 (let ((pn (make-js2-let-node :pos pos))
8628 beg vars body)
8629 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8630 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8631 (js2-push-scope pn)
8632 (unwind-protect
8633 (progn
8634 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8635 (if (js2-must-match js2-RP "msg.no.paren.let")
8636 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8637 (if (and stmt-p (js2-match-token js2-LC))
8638 ;; let statement
8639 (progn
8640 (setf beg (js2-current-token-beg) ; position stmt at LC
8641 body (js2-parse-statements))
8642 (js2-must-match js2-RC "msg.no.curly.let")
8643 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8644 (js2-node-len pn) (- (js2-current-token-end) pos)
8645 (js2-let-node-body pn) body
8646 (js2-node-type pn) js2-LET))
8647 ;; let expression
8648 (setf body (js2-parse-expr)
8649 (js2-node-len pn) (- (js2-node-end body) pos)
8650 (js2-let-node-body pn) body))
8651 (setf (js2-let-node-vars pn) vars)
8652 (js2-node-add-children pn vars body))
8653 (js2-pop-scope))
8654 pn))
8655
8656 (defun js2-define-new-symbol (decl-type name node &optional scope)
8657 (js2-scope-put-symbol (or scope js2-current-scope)
8658 name
8659 (make-js2-symbol decl-type name node)))
8660
8661 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8662 "Define a symbol in the current scope.
8663 If NODE is non-nil, it is the AST node associated with the symbol."
8664 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8665 (symbol (if defining-scope
8666 (js2-scope-get-symbol defining-scope name)))
8667 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8668 (cond
8669 ((and symbol ; already defined
8670 (or (= sdt js2-CONST) ; old version is const
8671 (= decl-type js2-CONST) ; new version is const
8672 ;; two let-bound vars in this block have same name
8673 (and (= sdt js2-LET)
8674 (eq defining-scope js2-current-scope))))
8675 (js2-report-error
8676 (cond
8677 ((= sdt js2-CONST) "msg.const.redecl")
8678 ((= sdt js2-LET) "msg.let.redecl")
8679 ((= sdt js2-VAR) "msg.var.redecl")
8680 ((= sdt js2-FUNCTION) "msg.function.redecl")
8681 (t "msg.parm.redecl"))
8682 name))
8683 ((= decl-type js2-LET)
8684 (if (and (not ignore-not-in-block)
8685 (or (= (js2-node-type js2-current-scope) js2-IF)
8686 (js2-loop-node-p js2-current-scope)))
8687 (js2-report-error "msg.let.decl.not.in.block")
8688 (js2-define-new-symbol decl-type name node)))
8689 ((or (= decl-type js2-VAR)
8690 (= decl-type js2-CONST)
8691 (= decl-type js2-FUNCTION))
8692 (if symbol
8693 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8694 (js2-add-strict-warning "msg.var.redecl" name)
8695 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8696 (js2-add-strict-warning "msg.var.hides.arg" name)))
8697 (js2-define-new-symbol decl-type name node
8698 js2-current-script-or-fn)))
8699 ((= decl-type js2-LP)
8700 (if symbol
8701 ;; must be duplicate parameter. Second parameter hides the
8702 ;; first, so go ahead and add the second pararameter
8703 (js2-report-warning "msg.dup.parms" name))
8704 (js2-define-new-symbol decl-type name node))
8705 (t (js2-code-bug)))))
8706
8707 (defun js2-parse-paren-expr-or-generator-comp ()
8708 (let ((px-pos (js2-current-token-beg)))
8709 (if (and (>= js2-language-version 200)
8710 (js2-match-token js2-FOR))
8711 (js2-parse-generator-comp px-pos)
8712 (let* ((js2-in-for-init nil)
8713 (expr (js2-parse-expr))
8714 (pn (make-js2-paren-node :pos px-pos
8715 :expr expr
8716 :len (- (js2-current-token-end)
8717 px-pos))))
8718 (js2-node-add-children pn (js2-paren-node-expr pn))
8719 (js2-must-match js2-RP "msg.no.paren")
8720 pn))))
8721
8722 (defun js2-parse-expr (&optional oneshot)
8723 (let* ((pn (js2-parse-assign-expr))
8724 (pos (js2-node-pos pn))
8725 left
8726 right
8727 op-pos)
8728 (while (and (not oneshot)
8729 (js2-match-token js2-COMMA))
8730 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8731 (if (= (js2-peek-token) js2-YIELD)
8732 (js2-report-error "msg.yield.parenthesized"))
8733 (setq right (js2-parse-assign-expr)
8734 left pn
8735 pn (make-js2-infix-node :type js2-COMMA
8736 :pos pos
8737 :len (- js2-ts-cursor pos)
8738 :op-pos op-pos
8739 :left left
8740 :right right))
8741 (js2-node-add-children pn left right))
8742 pn))
8743
8744 (defun js2-parse-assign-expr ()
8745 (let ((tt (js2-get-token))
8746 (pos (js2-current-token-beg))
8747 pn left right op-pos
8748 ts-state recorded-identifiers parsed-errors)
8749 (if (= tt js2-YIELD)
8750 (js2-parse-return-or-yield tt t)
8751 ;; Save the tokenizer state in case we find an arrow function
8752 ;; and have to rewind.
8753 (setq ts-state (make-js2-ts-state)
8754 recorded-identifiers js2-recorded-identifiers
8755 parsed-errors js2-parsed-errors)
8756 ;; not yield - parse assignment expression
8757 (setq pn (js2-parse-cond-expr)
8758 tt (js2-get-token))
8759 (cond
8760 ((and (<= js2-first-assign tt)
8761 (<= tt js2-last-assign))
8762 ;; tt express assignment (=, |=, ^=, ..., %=)
8763 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8764 left pn)
8765 (setq right (js2-parse-assign-expr)
8766 pn (make-js2-assign-node :type tt
8767 :pos pos
8768 :len (- (js2-node-end right) pos)
8769 :op-pos op-pos
8770 :left left
8771 :right right))
8772 (when js2-parse-ide-mode
8773 (js2-highlight-assign-targets pn left right)
8774 (js2-record-imenu-functions right left))
8775 ;; do this last so ide checks above can use absolute positions
8776 (js2-node-add-children pn left right))
8777 ((and (= tt js2-ARROW)
8778 (>= js2-language-version 200))
8779 (js2-ts-seek ts-state)
8780 (setq js2-recorded-identifiers recorded-identifiers
8781 js2-parsed-errors parsed-errors)
8782 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8783 (t
8784 (js2-unget-token)))
8785 pn)))
8786
8787 (defun js2-parse-cond-expr ()
8788 (let ((pos (js2-current-token-beg))
8789 (pn (js2-parse-or-expr))
8790 test-expr
8791 if-true
8792 if-false
8793 q-pos
8794 c-pos)
8795 (when (js2-match-token js2-HOOK)
8796 (setq q-pos (- (js2-current-token-beg) pos)
8797 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8798 (js2-must-match js2-COLON "msg.no.colon.cond")
8799 (setq c-pos (- (js2-current-token-beg) pos)
8800 if-false (js2-parse-assign-expr)
8801 test-expr pn
8802 pn (make-js2-cond-node :pos pos
8803 :len (- (js2-node-end if-false) pos)
8804 :test-expr test-expr
8805 :true-expr if-true
8806 :false-expr if-false
8807 :q-pos q-pos
8808 :c-pos c-pos))
8809 (js2-node-add-children pn test-expr if-true if-false))
8810 pn))
8811
8812 (defun js2-make-binary (type left parser)
8813 "Helper for constructing a binary-operator AST node.
8814 LEFT is the left-side-expression, already parsed, and the
8815 binary operator should have just been matched.
8816 PARSER is a function to call to parse the right operand,
8817 or a `js2-node' struct if it has already been parsed.
8818 FIXME: The latter option is unused?"
8819 (let* ((pos (js2-node-pos left))
8820 (op-pos (- (js2-current-token-beg) pos))
8821 (right (if (js2-node-p parser)
8822 parser
8823 (js2-get-token)
8824 (funcall parser)))
8825 (pn (make-js2-infix-node :type type
8826 :pos pos
8827 :len (- (js2-node-end right) pos)
8828 :op-pos op-pos
8829 :left left
8830 :right right)))
8831 (js2-node-add-children pn left right)
8832 pn))
8833
8834 (defun js2-parse-or-expr ()
8835 (let ((pn (js2-parse-and-expr)))
8836 (when (js2-match-token js2-OR)
8837 (setq pn (js2-make-binary js2-OR
8838 pn
8839 'js2-parse-or-expr)))
8840 pn))
8841
8842 (defun js2-parse-and-expr ()
8843 (let ((pn (js2-parse-bit-or-expr)))
8844 (when (js2-match-token js2-AND)
8845 (setq pn (js2-make-binary js2-AND
8846 pn
8847 'js2-parse-and-expr)))
8848 pn))
8849
8850 (defun js2-parse-bit-or-expr ()
8851 (let ((pn (js2-parse-bit-xor-expr)))
8852 (while (js2-match-token js2-BITOR)
8853 (setq pn (js2-make-binary js2-BITOR
8854 pn
8855 'js2-parse-bit-xor-expr)))
8856 pn))
8857
8858 (defun js2-parse-bit-xor-expr ()
8859 (let ((pn (js2-parse-bit-and-expr)))
8860 (while (js2-match-token js2-BITXOR)
8861 (setq pn (js2-make-binary js2-BITXOR
8862 pn
8863 'js2-parse-bit-and-expr)))
8864 pn))
8865
8866 (defun js2-parse-bit-and-expr ()
8867 (let ((pn (js2-parse-eq-expr)))
8868 (while (js2-match-token js2-BITAND)
8869 (setq pn (js2-make-binary js2-BITAND
8870 pn
8871 'js2-parse-eq-expr)))
8872 pn))
8873
8874 (defconst js2-parse-eq-ops
8875 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8876
8877 (defun js2-parse-eq-expr ()
8878 (let ((pn (js2-parse-rel-expr))
8879 tt)
8880 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8881 (setq pn (js2-make-binary tt
8882 pn
8883 'js2-parse-rel-expr)))
8884 (js2-unget-token)
8885 pn))
8886
8887 (defconst js2-parse-rel-ops
8888 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8889
8890 (defun js2-parse-rel-expr ()
8891 (let ((pn (js2-parse-shift-expr))
8892 (continue t)
8893 tt)
8894 (while continue
8895 (setq tt (js2-get-token))
8896 (cond
8897 ((and js2-in-for-init (= tt js2-IN))
8898 (js2-unget-token)
8899 (setq continue nil))
8900 ((memq tt js2-parse-rel-ops)
8901 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8902 (t
8903 (js2-unget-token)
8904 (setq continue nil))))
8905 pn))
8906
8907 (defconst js2-parse-shift-ops
8908 (list js2-LSH js2-URSH js2-RSH))
8909
8910 (defun js2-parse-shift-expr ()
8911 (let ((pn (js2-parse-add-expr))
8912 tt
8913 (continue t))
8914 (while continue
8915 (setq tt (js2-get-token))
8916 (if (memq tt js2-parse-shift-ops)
8917 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8918 (js2-unget-token)
8919 (setq continue nil)))
8920 pn))
8921
8922 (defun js2-parse-add-expr ()
8923 (let ((pn (js2-parse-mul-expr))
8924 tt
8925 (continue t))
8926 (while continue
8927 (setq tt (js2-get-token))
8928 (if (or (= tt js2-ADD) (= tt js2-SUB))
8929 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8930 (js2-unget-token)
8931 (setq continue nil)))
8932 pn))
8933
8934 (defconst js2-parse-mul-ops
8935 (list js2-MUL js2-DIV js2-MOD))
8936
8937 (defun js2-parse-mul-expr ()
8938 (let ((pn (js2-parse-unary-expr))
8939 tt
8940 (continue t))
8941 (while continue
8942 (setq tt (js2-get-token))
8943 (if (memq tt js2-parse-mul-ops)
8944 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8945 (js2-unget-token)
8946 (setq continue nil)))
8947 pn))
8948
8949 (defun js2-make-unary (type parser &rest args)
8950 "Make a unary node of type TYPE.
8951 PARSER is either a node (for postfix operators) or a function to call
8952 to parse the operand (for prefix operators)."
8953 (let* ((pos (js2-current-token-beg))
8954 (postfix (js2-node-p parser))
8955 (expr (if postfix
8956 parser
8957 (apply parser args)))
8958 end
8959 pn)
8960 (if postfix ; e.g. i++
8961 (setq pos (js2-node-pos expr)
8962 end (js2-current-token-end))
8963 (setq end (js2-node-end expr)))
8964 (setq pn (make-js2-unary-node :type type
8965 :pos pos
8966 :len (- end pos)
8967 :operand expr))
8968 (js2-node-add-children pn expr)
8969 pn))
8970
8971 (defconst js2-incrementable-node-types
8972 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8973 "Node types that can be the operand of a ++ or -- operator.")
8974
8975 (defun js2-check-bad-inc-dec (tt beg end unary)
8976 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8977 js2-incrementable-node-types)
8978 (js2-report-error (if (= tt js2-INC)
8979 "msg.bad.incr"
8980 "msg.bad.decr")
8981 nil beg (- end beg))))
8982
8983 (defun js2-parse-unary-expr ()
8984 (let ((tt (js2-current-token-type))
8985 pn expr beg end)
8986 (cond
8987 ((or (= tt js2-VOID)
8988 (= tt js2-NOT)
8989 (= tt js2-BITNOT)
8990 (= tt js2-TYPEOF))
8991 (js2-get-token)
8992 (js2-make-unary tt 'js2-parse-unary-expr))
8993 ((= tt js2-ADD)
8994 (js2-get-token)
8995 ;; Convert to special POS token in decompiler and parse tree
8996 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8997 ((= tt js2-SUB)
8998 (js2-get-token)
8999 ;; Convert to special NEG token in decompiler and parse tree
9000 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9001 ((or (= tt js2-INC)
9002 (= tt js2-DEC))
9003 (js2-get-token)
9004 (prog1
9005 (setq beg (js2-current-token-beg)
9006 end (js2-current-token-end)
9007 expr (js2-make-unary tt 'js2-parse-member-expr t))
9008 (js2-check-bad-inc-dec tt beg end expr)))
9009 ((= tt js2-DELPROP)
9010 (js2-get-token)
9011 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9012 ((= tt js2-ERROR)
9013 (js2-get-token)
9014 (make-js2-error-node)) ; try to continue
9015 ((and (= tt js2-LT)
9016 js2-compiler-xml-available)
9017 ;; XML stream encountered in expression.
9018 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9019 (t
9020 (setq pn (js2-parse-member-expr t)
9021 ;; Don't look across a newline boundary for a postfix incop.
9022 tt (js2-peek-token-or-eol))
9023 (when (or (= tt js2-INC) (= tt js2-DEC))
9024 (js2-get-token)
9025 (setf expr pn
9026 pn (js2-make-unary tt expr))
9027 (js2-node-set-prop pn 'postfix t)
9028 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9029 pn))))
9030
9031 (defun js2-parse-xml-initializer ()
9032 "Parse an E4X XML initializer.
9033 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9034 Then I'll postprocess the result, depending on whether we're in IDE
9035 mode or codegen mode, and generate the appropriate rewritten AST.
9036 IDE mode uses a rich AST that models the XML structure. Codegen mode
9037 just concatenates everything and makes a new XML or XMLList out of it."
9038 (let ((tt (js2-get-first-xml-token))
9039 pn-xml pn expr kids expr-pos
9040 (continue t)
9041 (first-token t))
9042 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9043 (js2-report-error "msg.syntax"))
9044 (setq pn-xml (make-js2-xml-node))
9045 (while continue
9046 (if first-token
9047 (setq first-token nil)
9048 (setq tt (js2-get-next-xml-token)))
9049 (cond
9050 ;; js2-XML means we found a {expr} in the XML stream.
9051 ;; The token string is the XML up to the left-curly.
9052 ((= tt js2-XML)
9053 (push (make-js2-string-node :pos (js2-current-token-beg)
9054 :len (- js2-ts-cursor (js2-current-token-beg)))
9055 kids)
9056 (js2-must-match js2-LC "msg.syntax")
9057 (setq expr-pos js2-ts-cursor
9058 expr (if (eq (js2-peek-token) js2-RC)
9059 (make-js2-empty-expr-node :pos expr-pos)
9060 (js2-parse-expr)))
9061 (js2-must-match js2-RC "msg.syntax")
9062 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9063 :len (js2-node-len expr)
9064 :expr expr))
9065 (js2-node-add-children pn expr)
9066 (push pn kids))
9067 ;; a js2-XMLEND token means we hit the final close-tag.
9068 ((= tt js2-XMLEND)
9069 (push (make-js2-string-node :pos (js2-current-token-beg)
9070 :len (- js2-ts-cursor (js2-current-token-beg)))
9071 kids)
9072 (dolist (kid (nreverse kids))
9073 (js2-block-node-push pn-xml kid))
9074 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9075 (js2-node-pos pn-xml))
9076 continue nil))
9077 (t
9078 (js2-report-error "msg.syntax")
9079 (setq continue nil))))
9080 pn-xml))
9081
9082
9083 (defun js2-parse-argument-list ()
9084 "Parse an argument list and return it as a Lisp list of nodes.
9085 Returns the list in reverse order. Consumes the right-paren token."
9086 (let (result)
9087 (unless (js2-match-token js2-RP)
9088 (loop do
9089 (let ((tt (js2-get-token)))
9090 (if (= tt js2-YIELD)
9091 (js2-report-error "msg.yield.parenthesized"))
9092 (if (and (= tt js2-TRIPLEDOT)
9093 (>= js2-language-version 200))
9094 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9095 (js2-unget-token)
9096 (push (js2-parse-assign-expr) result)))
9097 while
9098 (js2-match-token js2-COMMA))
9099 (js2-must-match js2-RP "msg.no.paren.arg")
9100 result)))
9101
9102 (defun js2-parse-member-expr (&optional allow-call-syntax)
9103 (let ((tt (js2-current-token-type))
9104 pn pos target args beg end init)
9105 (if (/= tt js2-NEW)
9106 (setq pn (js2-parse-primary-expr))
9107 ;; parse a 'new' expression
9108 (js2-get-token)
9109 (setq pos (js2-current-token-beg)
9110 beg pos
9111 target (js2-parse-member-expr)
9112 end (js2-node-end target)
9113 pn (make-js2-new-node :pos pos
9114 :target target
9115 :len (- end pos)))
9116 (js2-highlight-function-call (js2-current-token))
9117 (js2-node-add-children pn target)
9118 (when (js2-match-token js2-LP)
9119 ;; Add the arguments to pn, if any are supplied.
9120 (setf beg pos ; start of "new" keyword
9121 pos (js2-current-token-beg)
9122 args (nreverse (js2-parse-argument-list))
9123 (js2-new-node-args pn) args
9124 end (js2-current-token-end)
9125 (js2-new-node-lp pn) (- pos beg)
9126 (js2-new-node-rp pn) (- end 1 beg))
9127 (apply #'js2-node-add-children pn args))
9128 (when (and js2-allow-rhino-new-expr-initializer
9129 (js2-match-token js2-LC))
9130 (setf init (js2-parse-object-literal)
9131 end (js2-node-end init)
9132 (js2-new-node-initializer pn) init)
9133 (js2-node-add-children pn init))
9134 (setf (js2-node-len pn) (- end beg))) ; end outer if
9135 (js2-parse-member-expr-tail allow-call-syntax pn)))
9136
9137 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9138 "Parse a chain of property/array accesses or function calls.
9139 Includes parsing for E4X operators like `..' and `.@'.
9140 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9141 Returns an expression tree that includes PN, the parent node."
9142 (let (tt
9143 (continue t))
9144 (while continue
9145 (setq tt (js2-get-token))
9146 (cond
9147 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9148 (setq pn (js2-parse-property-access tt pn)))
9149 ((= tt js2-DOTQUERY)
9150 (setq pn (js2-parse-dot-query pn)))
9151 ((= tt js2-LB)
9152 (setq pn (js2-parse-element-get pn)))
9153 ((= tt js2-LP)
9154 (js2-unget-token)
9155 (if allow-call-syntax
9156 (setq pn (js2-parse-function-call pn))
9157 (setq continue nil)))
9158 ((= tt js2-TEMPLATE_HEAD)
9159 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9160 ((= tt js2-NO_SUBS_TEMPLATE)
9161 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9162 (t
9163 (js2-unget-token)
9164 (setq continue nil))))
9165 (if (>= js2-highlight-level 2)
9166 (js2-parse-highlight-member-expr-node pn))
9167 pn))
9168
9169 (defun js2-parse-tagged-template (tag-node tpl-node)
9170 "Parse tagged template expression."
9171 (let* ((beg (js2-node-pos tag-node))
9172 (pn (make-js2-tagged-template-node :beg beg
9173 :len (- (js2-current-token-end) beg)
9174 :tag tag-node
9175 :template tpl-node)))
9176 (js2-node-add-children pn tag-node tpl-node)
9177 pn))
9178
9179 (defun js2-parse-dot-query (pn)
9180 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9181 Last token parsed must be `js2-DOTQUERY'."
9182 (let ((pos (js2-node-pos pn))
9183 op-pos expr end)
9184 (js2-must-have-xml)
9185 (js2-set-requires-activation)
9186 (setq op-pos (js2-current-token-beg)
9187 expr (js2-parse-expr)
9188 end (js2-node-end expr)
9189 pn (make-js2-xml-dot-query-node :left pn
9190 :pos pos
9191 :op-pos op-pos
9192 :right expr))
9193 (js2-node-add-children pn
9194 (js2-xml-dot-query-node-left pn)
9195 (js2-xml-dot-query-node-right pn))
9196 (if (js2-must-match js2-RP "msg.no.paren")
9197 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9198 end (js2-current-token-end)))
9199 (setf (js2-node-len pn) (- end pos))
9200 pn))
9201
9202 (defun js2-parse-element-get (pn)
9203 "Parse an element-get expression, e.g. foo[bar].
9204 Last token parsed must be `js2-RB'."
9205 (let ((lb (js2-current-token-beg))
9206 (pos (js2-node-pos pn))
9207 rb expr)
9208 (setq expr (js2-parse-expr))
9209 (if (js2-must-match js2-RB "msg.no.bracket.index")
9210 (setq rb (js2-current-token-beg)))
9211 (setq pn (make-js2-elem-get-node :target pn
9212 :pos pos
9213 :element expr
9214 :lb (js2-relpos lb pos)
9215 :rb (js2-relpos rb pos)
9216 :len (- (js2-current-token-end) pos)))
9217 (js2-node-add-children pn
9218 (js2-elem-get-node-target pn)
9219 (js2-elem-get-node-element pn))
9220 pn))
9221
9222 (defun js2-highlight-function-call (token)
9223 (when (eq (js2-token-type token) js2-NAME)
9224 (js2-record-face 'js2-function-call token)))
9225
9226 (defun js2-parse-function-call (pn)
9227 (js2-highlight-function-call (js2-current-token))
9228 (js2-get-token)
9229 (let (args
9230 (pos (js2-node-pos pn)))
9231 (setq pn (make-js2-call-node :pos pos
9232 :target pn
9233 :lp (- (js2-current-token-beg) pos)))
9234 (js2-node-add-children pn (js2-call-node-target pn))
9235 ;; Add the arguments to pn, if any are supplied.
9236 (setf args (nreverse (js2-parse-argument-list))
9237 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9238 (js2-call-node-args pn) args)
9239 (apply #'js2-node-add-children pn args)
9240 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9241 pn))
9242
9243 (defun js2-parse-property-access (tt pn)
9244 "Parse a property access, XML descendants access, or XML attr access."
9245 (let ((member-type-flags 0)
9246 (dot-pos (js2-current-token-beg))
9247 (dot-len (if (= tt js2-DOTDOT) 2 1))
9248 name
9249 ref ; right side of . or .. operator
9250 result)
9251 (when (= tt js2-DOTDOT)
9252 (js2-must-have-xml)
9253 (setq member-type-flags js2-descendants-flag))
9254 (if (not js2-compiler-xml-available)
9255 (progn
9256 (js2-must-match-prop-name "msg.no.name.after.dot")
9257 (setq name (js2-create-name-node t js2-GETPROP)
9258 result (make-js2-prop-get-node :left pn
9259 :pos (js2-current-token-beg)
9260 :right name
9261 :len (js2-current-token-len)))
9262 (js2-node-add-children result pn name)
9263 result)
9264 ;; otherwise look for XML operators
9265 (setf result (if (= tt js2-DOT)
9266 (make-js2-prop-get-node)
9267 (make-js2-infix-node :type js2-DOTDOT))
9268 (js2-node-pos result) (js2-node-pos pn)
9269 (js2-infix-node-op-pos result) dot-pos
9270 (js2-infix-node-left result) pn ; do this after setting position
9271 tt (js2-get-prop-name-token))
9272 (cond
9273 ;; handles: name, ns::name, ns::*, ns::[expr]
9274 ((= tt js2-NAME)
9275 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9276 ;; handles: *, *::name, *::*, *::[expr]
9277 ((= tt js2-MUL)
9278 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9279 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9280 ((= tt js2-XMLATTR)
9281 (setq result (js2-parse-attribute-access)))
9282 (t
9283 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9284 (if ref
9285 (setf (js2-node-len result) (- (js2-node-end ref)
9286 (js2-node-pos result))
9287 (js2-infix-node-right result) ref))
9288 (if (js2-infix-node-p result)
9289 (js2-node-add-children result
9290 (js2-infix-node-left result)
9291 (js2-infix-node-right result)))
9292 result)))
9293
9294 (defun js2-parse-attribute-access ()
9295 "Parse an E4X XML attribute expression.
9296 This includes expressions of the forms:
9297
9298 @attr @ns::attr @ns::*
9299 @* @*::attr @*::*
9300 @[expr] @*::[expr] @ns::[expr]
9301
9302 Called if we peeked an '@' token."
9303 (let ((tt (js2-get-prop-name-token))
9304 (at-pos (js2-current-token-beg)))
9305 (cond
9306 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9307 ((= tt js2-NAME)
9308 (js2-parse-property-name at-pos nil 0))
9309 ;; handles: @*, @*::name, @*::*, @*::[expr]
9310 ((= tt js2-MUL)
9311 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9312 ;; handles @[expr]
9313 ((= tt js2-LB)
9314 (js2-parse-xml-elem-ref at-pos))
9315 (t
9316 (js2-report-error "msg.no.name.after.xmlAttr")
9317 ;; Avoid cascaded errors that happen if we make an error node here.
9318 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9319
9320 (defun js2-parse-property-name (at-pos s member-type-flags)
9321 "Check if :: follows name in which case it becomes qualified name.
9322
9323 AT-POS is a natural number if we just read an '@' token, else nil.
9324 S is the name or string that was matched: an identifier, 'throw' or '*'.
9325 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9326
9327 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9328 operator, or the name is followed by ::. For a plain name, returns a
9329 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9330 (let ((pos (or at-pos (js2-current-token-beg)))
9331 colon-pos
9332 (name (js2-create-name-node t (js2-current-token-type) s))
9333 ns tt pn)
9334 (catch 'return
9335 (when (js2-match-token js2-COLONCOLON)
9336 (setq ns name
9337 colon-pos (js2-current-token-beg)
9338 tt (js2-get-prop-name-token))
9339 (cond
9340 ;; handles name::name
9341 ((= tt js2-NAME)
9342 (setq name (js2-create-name-node)))
9343 ;; handles name::*
9344 ((= tt js2-MUL)
9345 (setq name (js2-create-name-node nil nil "*")))
9346 ;; handles name::[expr]
9347 ((= tt js2-LB)
9348 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9349 (t
9350 (js2-report-error "msg.no.name.after.coloncolon"))))
9351 (if (and (null ns) (zerop member-type-flags))
9352 name
9353 (prog1
9354 (setq pn
9355 (make-js2-xml-prop-ref-node :pos pos
9356 :len (- (js2-node-end name) pos)
9357 :at-pos at-pos
9358 :colon-pos colon-pos
9359 :propname name))
9360 (js2-node-add-children pn name))))))
9361
9362 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9363 "Parse the [expr] portion of an xml element reference.
9364 For instance, @[expr], @*::[expr], or ns::[expr]."
9365 (let* ((lb (js2-current-token-beg))
9366 (pos (or at-pos lb))
9367 rb
9368 (expr (js2-parse-expr))
9369 (end (js2-node-end expr))
9370 pn)
9371 (if (js2-must-match js2-RB "msg.no.bracket.index")
9372 (setq rb (js2-current-token-beg)
9373 end (js2-current-token-end)))
9374 (prog1
9375 (setq pn
9376 (make-js2-xml-elem-ref-node :pos pos
9377 :len (- end pos)
9378 :namespace namespace
9379 :colon-pos colon-pos
9380 :at-pos at-pos
9381 :expr expr
9382 :lb (js2-relpos lb pos)
9383 :rb (js2-relpos rb pos)))
9384 (js2-node-add-children pn namespace expr))))
9385
9386 (defun js2-parse-destruct-primary-expr ()
9387 (let ((js2-is-in-destructuring t))
9388 (js2-parse-primary-expr)))
9389
9390 (defun js2-parse-primary-expr ()
9391 "Parse a literal (leaf) expression of some sort.
9392 Includes complex literals such as functions, object-literals,
9393 array-literals, array comprehensions and regular expressions."
9394 (let (pn ; parent node (usually return value)
9395 tt)
9396 (setq tt (js2-current-token-type))
9397 (cond
9398 ((= tt js2-CLASS)
9399 (js2-parse-class-expr))
9400 ((= tt js2-FUNCTION)
9401 (js2-parse-function-expr))
9402 ((= tt js2-LB)
9403 (js2-parse-array-comp-or-literal))
9404 ((= tt js2-LC)
9405 (js2-parse-object-literal))
9406 ((= tt js2-LET)
9407 (js2-parse-let (js2-current-token-beg)))
9408 ((= tt js2-LP)
9409 (js2-parse-paren-expr-or-generator-comp))
9410 ((= tt js2-XMLATTR)
9411 (js2-must-have-xml)
9412 (js2-parse-attribute-access))
9413 ((= tt js2-NAME)
9414 (js2-parse-name tt))
9415 ((= tt js2-NUMBER)
9416 (make-js2-number-node))
9417 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9418 (make-js2-string-node :type tt))
9419 ((= tt js2-TEMPLATE_HEAD)
9420 (js2-parse-template-literal))
9421 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9422 ;; Got / or /= which in this context means a regexp literal
9423 (let ((px-pos (js2-current-token-beg))
9424 (flags (js2-read-regexp tt))
9425 (end (js2-current-token-end)))
9426 (prog1
9427 (make-js2-regexp-node :pos px-pos
9428 :len (- end px-pos)
9429 :value (js2-current-token-string)
9430 :flags flags)
9431 (js2-set-face px-pos end 'font-lock-string-face 'record)
9432 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9433 ((or (= tt js2-NULL)
9434 (= tt js2-THIS)
9435 (= tt js2-SUPER)
9436 (= tt js2-FALSE)
9437 (= tt js2-TRUE))
9438 (make-js2-keyword-node :type tt))
9439 ((= tt js2-RP)
9440 ;; Not valid expression syntax, but this is valid in an arrow
9441 ;; function with no params: () => body.
9442 (if (eq (js2-peek-token) js2-ARROW)
9443 (progn
9444 (js2-unget-token) ; Put back the right paren.
9445 ;; Return whatever, it will hopefully be rewinded and
9446 ;; reparsed when we reach the =>.
9447 (make-js2-keyword-node :type js2-NULL))
9448 (js2-report-error "msg.syntax")
9449 (make-js2-error-node)))
9450 ((= tt js2-TRIPLEDOT)
9451 ;; Likewise, only valid in an arrow function with a rest param.
9452 (if (and (js2-match-token js2-NAME)
9453 (js2-match-token js2-RP)
9454 (eq (js2-peek-token) js2-ARROW))
9455 (progn
9456 (js2-unget-token) ; Put back the right paren.
9457 ;; See the previous case.
9458 (make-js2-keyword-node :type js2-NULL))
9459 (js2-report-error "msg.syntax")
9460 (make-js2-error-node)))
9461 ((= tt js2-RESERVED)
9462 (js2-report-error "msg.reserved.id")
9463 (make-js2-name-node))
9464 ((= tt js2-ERROR)
9465 ;; the scanner or one of its subroutines reported the error.
9466 (make-js2-error-node))
9467 ((= tt js2-EOF)
9468 (let* ((px-pos (point-at-bol))
9469 (len (- js2-ts-cursor px-pos)))
9470 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9471 (make-js2-error-node :pos (1- js2-ts-cursor)))
9472 (t
9473 (js2-report-error "msg.syntax")
9474 (make-js2-error-node)))))
9475
9476 (defun js2-parse-template-literal ()
9477 (let ((beg (js2-current-token-beg))
9478 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
9479 (tt js2-TEMPLATE_HEAD))
9480 (while (eq tt js2-TEMPLATE_HEAD)
9481 (push (js2-parse-expr) kids)
9482 (js2-must-match js2-RC "msg.syntax")
9483 (setq tt (js2-get-token 'TEMPLATE_TAIL))
9484 (push (make-js2-string-node :type tt) kids))
9485 (setq kids (nreverse kids))
9486 (let ((tpl (make-js2-template-node :beg beg
9487 :len (- (js2-current-token-end) beg)
9488 :kids kids)))
9489 (apply #'js2-node-add-children tpl kids)
9490 tpl)))
9491
9492 (defun js2-parse-name (_tt)
9493 (let ((name (js2-current-token-string))
9494 node)
9495 (setq node (if js2-compiler-xml-available
9496 (js2-parse-property-name nil name 0)
9497 (js2-create-name-node 'check-activation nil name)))
9498 (if js2-highlight-external-variables
9499 (js2-record-name-node node))
9500 node))
9501
9502 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9503 (js2-add-strict-warning
9504 msg nil
9505 ;; back up from comma to beginning of line or array/objlit
9506 (max (if elems
9507 (js2-node-pos (car elems))
9508 pos)
9509 (save-excursion
9510 (goto-char comma-pos)
9511 (back-to-indentation)
9512 (point)))
9513 comma-pos))
9514
9515 (defun js2-parse-array-comp-or-literal ()
9516 (let ((pos (js2-current-token-beg)))
9517 (if (and (>= js2-language-version 200)
9518 (js2-match-token js2-FOR))
9519 (js2-parse-array-comp pos)
9520 (js2-parse-array-literal pos))))
9521
9522 (defun js2-parse-array-literal (pos)
9523 (let ((after-lb-or-comma t)
9524 after-comma tt elems pn
9525 (continue t))
9526 (unless js2-is-in-destructuring
9527 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9528 (while continue
9529 (setq tt (js2-get-token))
9530 (cond
9531 ;; comma
9532 ((= tt js2-COMMA)
9533 (setq after-comma (js2-current-token-end))
9534 (if (not after-lb-or-comma)
9535 (setq after-lb-or-comma t)
9536 (push nil elems)))
9537 ;; end of array
9538 ((or (= tt js2-RB)
9539 (= tt js2-EOF)) ; prevent infinite loop
9540 (if (= tt js2-EOF)
9541 (js2-report-error "msg.no.bracket.arg" nil pos))
9542 (when (and after-comma (< js2-language-version 170))
9543 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9544 pos (remove nil elems) after-comma))
9545 (setq continue nil
9546 pn (make-js2-array-node :pos pos
9547 :len (- js2-ts-cursor pos)
9548 :elems (nreverse elems)))
9549 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9550 ;; destructuring binding
9551 (js2-is-in-destructuring
9552 (push (if (or (= tt js2-LC)
9553 (= tt js2-LB)
9554 (= tt js2-NAME))
9555 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9556 (js2-parse-destruct-primary-expr)
9557 ;; invalid pattern
9558 (js2-report-error "msg.bad.var")
9559 (make-js2-error-node))
9560 elems)
9561 (setq after-lb-or-comma nil
9562 after-comma nil))
9563 ;; array comp
9564 ((and (>= js2-language-version 170)
9565 (= tt js2-FOR) ; check for array comprehension
9566 (not after-lb-or-comma) ; "for" can't follow a comma
9567 elems ; must have at least 1 element
9568 (not (cdr elems))) ; but no 2nd element
9569 (js2-unget-token)
9570 (setf continue nil
9571 pn (js2-parse-legacy-array-comp (car elems) pos)))
9572 ;; another element
9573 (t
9574 (unless after-lb-or-comma
9575 (js2-report-error "msg.no.bracket.arg"))
9576 (if (and (= tt js2-TRIPLEDOT)
9577 (>= js2-language-version 200))
9578 ;; spread operator
9579 (push (js2-make-unary tt 'js2-parse-assign-expr)
9580 elems)
9581 (js2-unget-token)
9582 (push (js2-parse-assign-expr) elems))
9583 (setq after-lb-or-comma nil
9584 after-comma nil))))
9585 (unless js2-is-in-destructuring
9586 (js2-pop-scope))
9587 pn))
9588
9589 (defun js2-parse-legacy-array-comp (expr pos)
9590 "Parse a legacy array comprehension (JavaScript 1.7).
9591 EXPR is the first expression after the opening left-bracket.
9592 POS is the beginning of the LB token preceding EXPR.
9593 We should have just parsed the 'for' keyword before calling this function."
9594 (let ((current-scope js2-current-scope)
9595 loops first filter result)
9596 (unwind-protect
9597 (progn
9598 (while (js2-match-token js2-FOR)
9599 (let ((loop (make-js2-comp-loop-node)))
9600 (js2-push-scope loop)
9601 (push loop loops)
9602 (js2-parse-comp-loop loop)))
9603 ;; First loop takes expr scope's parent.
9604 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9605 (js2-scope-parent-scope current-scope))
9606 ;; Set expr scope's parent to the last loop.
9607 (setf (js2-scope-parent-scope current-scope) (car loops))
9608 (if (/= (js2-get-token) js2-IF)
9609 (js2-unget-token)
9610 (setq filter (js2-parse-condition))))
9611 (dotimes (_ (1- (length loops)))
9612 (js2-pop-scope)))
9613 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9614 (setq result (make-js2-comp-node :pos pos
9615 :len (- js2-ts-cursor pos)
9616 :result expr
9617 :loops (nreverse loops)
9618 :filters (and filter (list (car filter)))
9619 :form 'LEGACY_ARRAY))
9620 (apply #'js2-node-add-children result expr (car filter)
9621 (js2-comp-node-loops result))
9622 result))
9623
9624 (defun js2-parse-array-comp (pos)
9625 "Parse an ES6 array comprehension.
9626 POS is the beginning of the LB token.
9627 We should have just parsed the 'for' keyword before calling this function."
9628 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9629 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9630 pn))
9631
9632 (defun js2-parse-generator-comp (pos)
9633 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9634 (js2-current-script-or-fn
9635 (make-js2-function-node :generator-type 'COMPREHENSION))
9636 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9637 (js2-must-match js2-RP "msg.no.paren" pos)
9638 pn))
9639
9640 (defun js2-parse-comprehension (pos form)
9641 (let (loops filters expr result)
9642 (unwind-protect
9643 (progn
9644 (js2-unget-token)
9645 (while (js2-match-token js2-FOR)
9646 (let ((loop (make-js2-comp-loop-node)))
9647 (js2-push-scope loop)
9648 (push loop loops)
9649 (js2-parse-comp-loop loop)))
9650 (while (js2-match-token js2-IF)
9651 (push (car (js2-parse-condition)) filters))
9652 (setq expr (js2-parse-assign-expr)))
9653 (dolist (_ loops)
9654 (js2-pop-scope)))
9655 (setq result (make-js2-comp-node :pos pos
9656 :len (- js2-ts-cursor pos)
9657 :result expr
9658 :loops (nreverse loops)
9659 :filters (nreverse filters)
9660 :form form))
9661 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9662 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9663 result))
9664
9665 (defun js2-parse-comp-loop (pn &optional only-of-p)
9666 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9667 The current token should be the initial FOR.
9668 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9669 (let ((pos (js2-comp-loop-node-pos pn))
9670 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9671 (when (and (not only-of-p) (js2-match-token js2-NAME))
9672 (if (string= (js2-current-token-string) "each")
9673 (progn
9674 (setq foreach-p t
9675 each-pos (- (js2-current-token-beg) pos)) ; relative
9676 (js2-record-face 'font-lock-keyword-face))
9677 (js2-report-error "msg.no.paren.for")))
9678 (if (js2-must-match js2-LP "msg.no.paren.for")
9679 (setq lp (- (js2-current-token-beg) pos)))
9680 (setq tt (js2-peek-token))
9681 (cond
9682 ((or (= tt js2-LB)
9683 (= tt js2-LC))
9684 (js2-get-token)
9685 (setq iter (js2-parse-destruct-primary-expr))
9686 (js2-define-destruct-symbols iter js2-LET
9687 'font-lock-variable-name-face t))
9688 ((js2-match-token js2-NAME)
9689 (setq iter (js2-create-name-node)))
9690 (t
9691 (js2-report-error "msg.bad.var")))
9692 ;; Define as a let since we want the scope of the variable to
9693 ;; be restricted to the array comprehension
9694 (if (js2-name-node-p iter)
9695 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9696 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9697 (and (>= js2-language-version 200)
9698 (js2-match-contextual-kwd "of")
9699 (setq forof-p t)))
9700 (setq in-pos (- (js2-current-token-beg) pos))
9701 (js2-report-error "msg.in.after.for.name"))
9702 (setq obj (js2-parse-expr))
9703 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9704 (setq rp (- (js2-current-token-beg) pos)))
9705 (setf (js2-node-pos pn) pos
9706 (js2-node-len pn) (- js2-ts-cursor pos)
9707 (js2-comp-loop-node-iterator pn) iter
9708 (js2-comp-loop-node-object pn) obj
9709 (js2-comp-loop-node-in-pos pn) in-pos
9710 (js2-comp-loop-node-each-pos pn) each-pos
9711 (js2-comp-loop-node-foreach-p pn) foreach-p
9712 (js2-comp-loop-node-forof-p pn) forof-p
9713 (js2-comp-loop-node-lp pn) lp
9714 (js2-comp-loop-node-rp pn) rp)
9715 (js2-node-add-children pn iter obj)
9716 pn))
9717
9718 (defun js2-parse-class-stmt ()
9719 (let ((pos (js2-current-token-beg)))
9720 (js2-must-match-name "msg.unnamed.class.stmt")
9721 (js2-parse-class pos 'CLASS_STATEMENT (js2-create-name-node t))))
9722
9723 (defun js2-parse-class-expr ()
9724 (let ((pos (js2-current-token-beg))
9725 name)
9726 (when (js2-match-token js2-NAME)
9727 (setq name (js2-create-name-node t)))
9728 (js2-parse-class pos 'CLASS_EXPRESSION name)))
9729
9730 (defun js2-parse-class (pos form name)
9731 ;; class X [extends ...] {
9732 (let (pn elems extends)
9733 (when name
9734 (js2-set-face (js2-node-pos name) (js2-node-end name)
9735 'font-lock-function-name-face 'record))
9736 (if (js2-match-token js2-EXTENDS)
9737 (if (= (js2-peek-token) js2-LC)
9738 (js2-report-error "msg.missing.extends")
9739 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
9740 (setq extends (js2-parse-assign-expr))
9741 (if (not extends)
9742 (js2-report-error "msg.bad.extends"))))
9743 (js2-must-match js2-LC "msg.no.brace.class")
9744 (setq elems (js2-parse-object-literal-elems t)
9745 pn (make-js2-class-node :pos pos
9746 :len (- js2-ts-cursor pos)
9747 :form form
9748 :name name
9749 :extends extends
9750 :elems elems))
9751 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
9752 pn))
9753
9754 (defun js2-parse-object-literal ()
9755 (let* ((pos (js2-current-token-beg))
9756 (elems (js2-parse-object-literal-elems))
9757 (result (make-js2-object-node :pos pos
9758 :len (- js2-ts-cursor pos)
9759 :elems elems)))
9760 (apply #'js2-node-add-children result (js2-object-node-elems result))
9761 result))
9762
9763 (defun js2-parse-object-literal-elems (&optional class-p)
9764 (let ((pos (js2-current-token-beg))
9765 (static nil)
9766 (continue t)
9767 tt elems elem after-comma)
9768 (while continue
9769 (setq static (and class-p (js2-match-token js2-STATIC))
9770 tt (js2-get-prop-name-token)
9771 elem nil)
9772 (cond
9773 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9774 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
9775 ;; TODO(sdh): support *foo() {...}
9776 ((or (= js2-NAME tt)
9777 (= tt js2-STRING))
9778 (setq after-comma nil
9779 elem (js2-parse-named-prop tt))
9780 (if (and (null elem)
9781 (not js2-recover-from-parse-errors))
9782 (setq continue nil)))
9783 ;; {[Symbol.iterator]: ...}
9784 ((and (= tt js2-LB)
9785 (>= js2-language-version 200))
9786 (let ((expr (js2-parse-expr)))
9787 (js2-must-match js2-RB "msg.missing.computed.rb")
9788 (setq after-comma nil
9789 elem (js2-parse-plain-property expr))))
9790 ;; {12: x} or {10.7: x}
9791 ((= tt js2-NUMBER)
9792 (setq after-comma nil
9793 elem (js2-parse-plain-property (make-js2-number-node))))
9794 ;; Break out of loop, and handle trailing commas.
9795 ((or (= tt js2-RC)
9796 (= tt js2-EOF))
9797 (js2-unget-token)
9798 (setq continue nil)
9799 (if after-comma
9800 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9801 pos elems after-comma)))
9802 (t
9803 (js2-report-error "msg.bad.prop")
9804 (unless js2-recover-from-parse-errors
9805 (setq continue nil)))) ; end switch
9806 ;; Handle static for classes' codegen.
9807 (if static
9808 (if elem (js2-node-set-prop elem 'STATIC t)
9809 (js2-report-error "msg.unexpected.static")))
9810 ;; Handle commas, depending on class-p.
9811 (let ((comma (js2-match-token js2-COMMA)))
9812 (if class-p
9813 (if comma
9814 (js2-report-error "msg.class.unexpected.comma"))
9815 (if comma
9816 (setq after-comma (js2-current-token-end))
9817 (setq continue nil))))
9818 ;; Append any parsed element.
9819 (if elem (push elem elems))) ; end loop
9820 (js2-must-match js2-RC "msg.no.brace.prop")
9821 (nreverse elems)))
9822
9823 (defun js2-parse-named-prop (tt)
9824 "Parse a name, string, or getter/setter object property.
9825 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9826 (let ((string-prop (and (= tt js2-STRING)
9827 (make-js2-string-node)))
9828 expr
9829 (ppos (js2-current-token-beg))
9830 (pend (js2-current-token-end))
9831 (name (js2-create-name-node))
9832 (prop (js2-current-token-string)))
9833 (cond
9834 ;; getter/setter prop
9835 ((and (= tt js2-NAME)
9836 (= (js2-peek-token) js2-NAME)
9837 (or (string= prop "get")
9838 (string= prop "set")))
9839 (js2-get-token)
9840 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9841 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9842 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9843 (js2-parse-getter-setter-prop ppos name prop))
9844 ;; method definition: {f() {...}}
9845 ((and (= (js2-peek-token) js2-LP)
9846 (>= js2-language-version 200))
9847 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; name
9848 (js2-parse-getter-setter-prop ppos name ""))
9849 ;; regular prop
9850 (t
9851 (prog1
9852 (setq expr (js2-parse-plain-property (or string-prop name)))
9853 (when (and (not string-prop)
9854 (not js2-is-in-destructuring)
9855 js2-highlight-external-variables
9856 (js2-node-get-prop expr 'SHORTHAND))
9857 (js2-record-name-node name))
9858 (js2-set-face ppos pend
9859 (if (js2-function-node-p
9860 (js2-object-prop-node-right expr))
9861 'font-lock-function-name-face
9862 'font-lock-variable-name-face)
9863 'record))))))
9864
9865 (defun js2-parse-plain-property (prop)
9866 "Parse a non-getter/setter property in an object literal.
9867 PROP is the node representing the property: a number, name or string."
9868 (let* ((tt (js2-get-token))
9869 (pos (js2-node-pos prop))
9870 colon expr result)
9871 (cond
9872 ;; Abbreviated property, as in {foo, bar}
9873 ((and (>= js2-language-version 200)
9874 (or (= tt js2-COMMA)
9875 (= tt js2-RC))
9876 (not (js2-number-node-p prop)))
9877 (js2-unget-token)
9878 (setq result (make-js2-object-prop-node
9879 :pos pos
9880 :left prop
9881 :right prop
9882 :op-pos (js2-current-token-len)))
9883 (js2-node-add-children result prop)
9884 (js2-node-set-prop result 'SHORTHAND t)
9885 result)
9886 ;; Normal property
9887 (t
9888 (if (= tt js2-COLON)
9889 (setq colon (- (js2-current-token-beg) pos)
9890 expr (js2-parse-assign-expr))
9891 (js2-report-error "msg.no.colon.prop")
9892 (setq expr (make-js2-error-node)))
9893 (setq result (make-js2-object-prop-node
9894 :pos pos
9895 ;; don't include last consumed token in length
9896 :len (- (+ (js2-node-pos expr)
9897 (js2-node-len expr))
9898 pos)
9899 :left prop
9900 :right expr
9901 :op-pos colon))
9902 (js2-node-add-children result prop expr)
9903 result))))
9904
9905 (defun js2-parse-getter-setter-prop (pos prop type-string)
9906 "Parse getter or setter property in an object literal.
9907 JavaScript syntax is:
9908
9909 { get foo() {...}, set foo(x) {...} }
9910
9911 and expression closure style is also supported
9912
9913 { get foo() x, set foo(x) _x = x }
9914
9915 POS is the start position of the `get' or `set' keyword.
9916 PROP is the `js2-name-node' representing the property name.
9917 GET-P is non-nil if the keyword was `get'."
9918 (let ((type (cond
9919 ((string= "get" type-string) js2-GET)
9920 ((string= "set" type-string) js2-SET)
9921 (t js2-FUNCTION)))
9922 result end
9923 (fn (js2-parse-function-expr)))
9924 ;; it has to be an anonymous function, as we already parsed the name
9925 (if (/= (js2-node-type fn) js2-FUNCTION)
9926 (js2-report-error "msg.bad.prop")
9927 (if (plusp (length (js2-function-name fn)))
9928 (js2-report-error "msg.bad.prop")))
9929 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9930 (setq end (js2-node-end fn)
9931 result (make-js2-getter-setter-node :type type
9932 :pos pos
9933 :len (- end pos)
9934 :left prop
9935 :right fn))
9936 (js2-node-add-children result prop fn)
9937 result))
9938
9939 (defun js2-create-name-node (&optional check-activation-p token string)
9940 "Create a name node using the current token and, optionally, STRING.
9941 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9942 (let* ((beg (js2-current-token-beg))
9943 (tt (js2-current-token-type))
9944 (s (or string
9945 (if (= js2-NAME tt)
9946 (js2-current-token-string)
9947 (js2-tt-name tt))))
9948 name)
9949 (setq name (make-js2-name-node :pos beg
9950 :name s
9951 :len (length s)))
9952 (if check-activation-p
9953 (js2-check-activation-name s (or token js2-NAME)))
9954 name))
9955
9956 ;;; Indentation support
9957
9958 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9959 ;; Karl cleverly deduces that the desired indentation level is often a
9960 ;; function of paren/bracket/brace nesting depth, which can be determined
9961 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9962 ;; then does some equally clever checks to see if we're in the context of a
9963 ;; substatement of a possibly braceless statement keyword such as if, while,
9964 ;; or finally. This approach yields pretty good results.
9965
9966 ;; The indenter is often "wrong", however, and needs to be overridden.
9967 ;; The right long-term solution is probably to emulate (or integrate
9968 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9969 ;; parse tree from `js2-parse' is present, which is not true at the
9970 ;; moment the user is typing, computing indentation is still thousands
9971 ;; of lines of code to handle every possible syntactic edge case.
9972
9973 ;; In the meantime, the compromise solution is that we offer a "bounce
9974 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9975 ;; current line indent among various likely guess points. This approach
9976 ;; is far from perfect, but should at least make it slightly easier to
9977 ;; move the line towards its desired indentation when manually
9978 ;; overriding Karl's heuristic nesting guesser.
9979
9980 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9981 ;; extensions such as `let' and Array comprehensions. Major kudos to
9982 ;; Karl for coming up with the initial approach, which packs a lot of
9983 ;; punch for so little code.
9984
9985 (defconst js2-possibly-braceless-keywords-re
9986 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9987 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9988 "try" "while" "with" "let")))
9989 "Regular expression matching keywords that are optionally
9990 followed by an opening brace.")
9991
9992 (defconst js2-indent-operator-re
9993 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9994 (regexp-opt '("in" "instanceof") 'words))
9995 "Regular expression matching operators that affect indentation
9996 of continued expressions.")
9997
9998 (defconst js2-declaration-keyword-re
9999 (regexp-opt '("var" "let" "const") 'words)
10000 "Regular expression matching variable declaration keywords.")
10001
10002 (defun js2-re-search-forward-inner (regexp &optional bound count)
10003 "Auxiliary function for `js2-re-search-forward'."
10004 (let (parse saved-point)
10005 (while (> count 0)
10006 (re-search-forward regexp bound)
10007 (setq parse (if saved-point
10008 (parse-partial-sexp saved-point (point))
10009 (syntax-ppss (point))))
10010 (cond ((nth 3 parse)
10011 (re-search-forward
10012 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10013 (save-excursion (end-of-line) (point)) t))
10014 ((nth 7 parse)
10015 (forward-line))
10016 ((or (nth 4 parse)
10017 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10018 (re-search-forward "\\*/"))
10019 (t
10020 (setq count (1- count))))
10021 (setq saved-point (point))))
10022 (point))
10023
10024 (defun js2-re-search-forward (regexp &optional bound noerror count)
10025 "Search forward but ignore strings and comments.
10026 Invokes `re-search-forward' but treats the buffer as if strings
10027 and comments have been removed."
10028 (let ((saved-point (point)))
10029 (condition-case err
10030 (cond ((null count)
10031 (js2-re-search-forward-inner regexp bound 1))
10032 ((< count 0)
10033 (js2-re-search-backward-inner regexp bound (- count)))
10034 ((> count 0)
10035 (js2-re-search-forward-inner regexp bound count)))
10036 (search-failed
10037 (goto-char saved-point)
10038 (unless noerror
10039 (error (error-message-string err)))))))
10040
10041 (defun js2-re-search-backward-inner (regexp &optional bound count)
10042 "Auxiliary function for `js2-re-search-backward'."
10043 (let (parse)
10044 (while (> count 0)
10045 (re-search-backward regexp bound)
10046 (setq parse (syntax-ppss (point)))
10047 (cond ((nth 3 parse)
10048 (re-search-backward
10049 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10050 (line-beginning-position) t))
10051 ((nth 7 parse)
10052 (goto-char (nth 8 parse)))
10053 ((or (nth 4 parse)
10054 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10055 (re-search-backward "/\\*"))
10056 (t
10057 (setq count (1- count))))))
10058 (point))
10059
10060 (defun js2-re-search-backward (regexp &optional bound noerror count)
10061 "Search backward but ignore strings and comments.
10062 Invokes `re-search-backward' but treats the buffer as if strings
10063 and comments have been removed."
10064 (let ((saved-point (point)))
10065 (condition-case err
10066 (cond ((null count)
10067 (js2-re-search-backward-inner regexp bound 1))
10068 ((< count 0)
10069 (js2-re-search-forward-inner regexp bound (- count)))
10070 ((> count 0)
10071 (js2-re-search-backward-inner regexp bound count)))
10072 (search-failed
10073 (goto-char saved-point)
10074 (unless noerror
10075 (error (error-message-string err)))))))
10076
10077 (defun js2-looking-at-operator-p ()
10078 "Return non-nil if text after point is a non-comma operator."
10079 (and (looking-at js2-indent-operator-re)
10080 (or (not (looking-at ":"))
10081 (save-excursion
10082 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10083 (looking-at "?"))))))
10084
10085 (defun js2-continued-expression-p ()
10086 "Return non-nil if the current line continues an expression."
10087 (save-excursion
10088 (back-to-indentation)
10089 (or (js2-looking-at-operator-p)
10090 (when (catch 'found
10091 (while (and (re-search-backward "\n" nil t)
10092 (let ((state (syntax-ppss)))
10093 (when (nth 4 state)
10094 (goto-char (nth 8 state))) ;; skip comments
10095 (skip-chars-backward " \t")
10096 (if (bolp)
10097 t
10098 (throw 'found t))))))
10099 (backward-char)
10100 (when (js2-looking-at-operator-p)
10101 (backward-char)
10102 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10103
10104 (defun js2-end-of-do-while-loop-p ()
10105 "Return non-nil if word after point is `while' of a do-while
10106 statement, else returns nil. A braceless do-while statement
10107 spanning several lines requires that the start of the loop is
10108 indented to the same column as the current line."
10109 (interactive)
10110 (save-excursion
10111 (when (looking-at "\\s-*\\<while\\>")
10112 (if (save-excursion
10113 (skip-chars-backward "[ \t\n]*}")
10114 (looking-at "[ \t\n]*}"))
10115 (save-excursion
10116 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10117 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10118 (or (looking-at "\\<do\\>")
10119 (let ((saved-indent (current-indentation)))
10120 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10121 (/= (current-indentation) saved-indent)))
10122 (and (looking-at "[ \t]*\\<do\\>")
10123 (not (js2-re-search-forward
10124 "\\<while\\>" (point-at-eol) t))
10125 (= (current-indentation) saved-indent))))))))
10126
10127 (defun js2-multiline-decl-indentation ()
10128 "Return the declaration indentation column if the current line belongs
10129 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10130 (let (forward-sexp-function ; use Lisp version
10131 at-opening-bracket)
10132 (save-excursion
10133 (back-to-indentation)
10134 (when (not (looking-at js2-declaration-keyword-re))
10135 (when (looking-at js2-indent-operator-re)
10136 (goto-char (match-end 0))) ; continued expressions are ok
10137 (while (and (not at-opening-bracket)
10138 (not (bobp))
10139 (let ((pos (point)))
10140 (save-excursion
10141 (js2-backward-sws)
10142 (or (eq (char-before) ?,)
10143 (and (not (eq (char-before) ?\;))
10144 (prog2 (skip-syntax-backward ".")
10145 (looking-at js2-indent-operator-re)
10146 (js2-backward-sws))
10147 (not (eq (char-before) ?\;)))
10148 (js2-same-line pos)))))
10149 (condition-case _
10150 (backward-sexp)
10151 (scan-error (setq at-opening-bracket t))))
10152 (when (looking-at js2-declaration-keyword-re)
10153 (goto-char (match-end 0))
10154 (1+ (current-column)))))))
10155
10156 (defun js2-ctrl-statement-indentation ()
10157 "Return the proper indentation of current line if it is a control statement.
10158 Returns an indentation if this line starts the body of a control
10159 statement without braces, else returns nil."
10160 (let (forward-sexp-function)
10161 (save-excursion
10162 (back-to-indentation)
10163 (when (and (not (js2-same-line (point-min)))
10164 (not (looking-at "{"))
10165 (js2-re-search-backward "[[:graph:]]" nil t)
10166 (not (looking-at "[{([]"))
10167 (progn
10168 (forward-char)
10169 (when (= (char-before) ?\))
10170 ;; scan-sexps sometimes throws an error
10171 (ignore-errors (backward-sexp))
10172 (skip-chars-backward " \t" (point-at-bol)))
10173 (let ((pt (point)))
10174 (back-to-indentation)
10175 (when (looking-at "}[ \t]*")
10176 (goto-char (match-end 0)))
10177 (and (looking-at js2-possibly-braceless-keywords-re)
10178 (= (match-end 0) pt)
10179 (not (js2-end-of-do-while-loop-p))))))
10180 (+ (current-indentation) js2-basic-offset)))))
10181
10182 (defun js2-indent-in-array-comp (parse-status)
10183 "Return non-nil if we think we're in an array comprehension.
10184 In particular, return the buffer position of the first `for' kwd."
10185 (let ((bracket (nth 1 parse-status))
10186 (end (point)))
10187 (when bracket
10188 (save-excursion
10189 (goto-char bracket)
10190 (when (looking-at "\\[")
10191 (forward-char 1)
10192 (js2-forward-sws)
10193 (if (looking-at "[[{]")
10194 (let (forward-sexp-function) ; use Lisp version
10195 (forward-sexp) ; skip destructuring form
10196 (js2-forward-sws)
10197 (if (and (/= (char-after) ?,) ; regular array
10198 (looking-at "for"))
10199 (match-beginning 0)))
10200 ;; to skip arbitrary expressions we need the parser,
10201 ;; so we'll just guess at it.
10202 (if (and (> end (point)) ; not empty literal
10203 (re-search-forward "[^,]]* \\(for\\) " end t)
10204 ;; not inside comment or string literal
10205 (let ((state (parse-partial-sexp bracket (point))))
10206 (not (or (nth 3 state) (nth 4 state)))))
10207 (match-beginning 1))))))))
10208
10209 (defun js2-array-comp-indentation (parse-status for-kwd)
10210 (if (js2-same-line for-kwd)
10211 ;; first continuation line
10212 (save-excursion
10213 (goto-char (nth 1 parse-status))
10214 (forward-char 1)
10215 (skip-chars-forward " \t")
10216 (current-column))
10217 (save-excursion
10218 (goto-char for-kwd)
10219 (current-column))))
10220
10221 (defun js2-proper-indentation (parse-status)
10222 "Return the proper indentation for the current line."
10223 (save-excursion
10224 (back-to-indentation)
10225 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10226 (at-closing-bracket (looking-at "[]})]"))
10227 (same-indent-p (or at-closing-bracket
10228 (looking-at "\\<case\\>[^:]")
10229 (and (looking-at "\\<default:")
10230 (save-excursion
10231 (js2-backward-sws)
10232 (not (memq (char-before) '(?, ?{)))))))
10233 (continued-expr-p (js2-continued-expression-p))
10234 (declaration-indent (and js2-pretty-multiline-declarations
10235 (js2-multiline-decl-indentation)))
10236 (bracket (nth 1 parse-status))
10237 beg indent)
10238 (cond
10239 ;; indent array comprehension continuation lines specially
10240 ((and bracket
10241 (>= js2-language-version 170)
10242 (not (js2-same-line bracket))
10243 (setq beg (js2-indent-in-array-comp parse-status))
10244 (>= (point) (save-excursion
10245 (goto-char beg)
10246 (point-at-bol)))) ; at or after first loop?
10247 (js2-array-comp-indentation parse-status beg))
10248
10249 (ctrl-stmt-indent)
10250
10251 ((and declaration-indent continued-expr-p)
10252 (+ declaration-indent js2-basic-offset))
10253
10254 (declaration-indent)
10255
10256 (bracket
10257 (goto-char bracket)
10258 (cond
10259 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10260 (when (save-excursion (skip-chars-backward " \t)")
10261 (looking-at ")"))
10262 (backward-list))
10263 (back-to-indentation)
10264 (and (eq js2-pretty-multiline-declarations 'all)
10265 (looking-at js2-declaration-keyword-re)
10266 (goto-char (1+ (match-end 0))))
10267 (setq indent
10268 (cond (same-indent-p
10269 (current-column))
10270 (continued-expr-p
10271 (+ (current-column) (* 2 js2-basic-offset)))
10272 (t
10273 (+ (current-column) js2-basic-offset))))
10274 (if (and js2-indent-switch-body
10275 (not at-closing-bracket)
10276 (looking-at "\\_<switch\\_>"))
10277 (+ indent js2-basic-offset)
10278 indent))
10279 (t
10280 (unless same-indent-p
10281 (forward-char)
10282 (skip-chars-forward " \t"))
10283 (current-column))))
10284
10285 (continued-expr-p js2-basic-offset)
10286
10287 (t 0)))))
10288
10289 (defun js2-lineup-comment (parse-status)
10290 "Indent a multi-line block comment continuation line."
10291 (let* ((beg (nth 8 parse-status))
10292 (first-line (js2-same-line beg))
10293 (offset (save-excursion
10294 (goto-char beg)
10295 (if (looking-at "/\\*")
10296 (+ 1 (current-column))
10297 0))))
10298 (unless first-line
10299 (indent-line-to offset))))
10300
10301 (defun js2-backward-sws ()
10302 "Move backward through whitespace and comments."
10303 (interactive)
10304 (while (forward-comment -1)))
10305
10306 (defun js2-forward-sws ()
10307 "Move forward through whitespace and comments."
10308 (interactive)
10309 (while (forward-comment 1)))
10310
10311 (defun js2-current-indent (&optional pos)
10312 "Return column of indentation on current line.
10313 If POS is non-nil, go to that point and return indentation for that line."
10314 (save-excursion
10315 (if pos
10316 (goto-char pos))
10317 (back-to-indentation)
10318 (current-column)))
10319
10320 (defun js2-arglist-close ()
10321 "Return non-nil if we're on a line beginning with a close-paren/brace."
10322 (save-excursion
10323 (goto-char (point-at-bol))
10324 (js2-forward-sws)
10325 (looking-at "[])}]")))
10326
10327 (defun js2-indent-looks-like-label-p ()
10328 (goto-char (point-at-bol))
10329 (js2-forward-sws)
10330 (looking-at (concat js2-mode-identifier-re ":")))
10331
10332 (defun js2-indent-in-objlit-p (parse-status)
10333 "Return non-nil if this looks like an object-literal entry."
10334 (let ((start (nth 1 parse-status)))
10335 (and
10336 start
10337 (save-excursion
10338 (and (zerop (forward-line -1))
10339 (not (< (point) start)) ; crossed a {} boundary
10340 (js2-indent-looks-like-label-p)))
10341 (save-excursion
10342 (js2-indent-looks-like-label-p)))))
10343
10344 ;; If prev line looks like foobar({ then we're passing an object
10345 ;; literal to a function call, and people pretty much always want to
10346 ;; de-dent back to the previous line, so move the 'basic-offset'
10347 ;; position to the front.
10348 (defun js2-indent-objlit-arg-p (parse-status)
10349 (save-excursion
10350 (back-to-indentation)
10351 (js2-backward-sws)
10352 (and (eq (1- (point)) (nth 1 parse-status))
10353 (eq (char-before) ?{)
10354 (progn
10355 (forward-char -1)
10356 (skip-chars-backward " \t")
10357 (eq (char-before) ?\()))))
10358
10359 (defun js2-indent-case-block-p ()
10360 (save-excursion
10361 (back-to-indentation)
10362 (js2-backward-sws)
10363 (goto-char (point-at-bol))
10364 (skip-chars-forward " \t")
10365 (looking-at "case\\s-.+:")))
10366
10367 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10368 "Cycle among alternate computed indentation positions.
10369 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10370 of the buffer to the current point. NORMAL-COL is the indentation
10371 column computed by the heuristic guesser based on current paren,
10372 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10373 in reverse."
10374 (let ((cur-indent (js2-current-indent))
10375 (old-buffer-undo-list buffer-undo-list)
10376 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10377 (current-line (save-excursion
10378 (forward-line 0) ; move to bol
10379 (1+ (count-lines (point-min) (point)))))
10380 positions pos main-pos anchor arglist-cont same-indent
10381 basic-offset computed-pos)
10382 ;; temporarily don't record undo info, if user requested this
10383 (when js2-mode-indent-inhibit-undo
10384 (setq buffer-undo-list t))
10385 (unwind-protect
10386 (progn
10387 ;; First likely point: indent from beginning of previous code line
10388 (push (setq basic-offset
10389 (+ (save-excursion
10390 (back-to-indentation)
10391 (js2-backward-sws)
10392 (back-to-indentation)
10393 (current-column))
10394 js2-basic-offset))
10395 positions)
10396
10397 ;; (First + epsilon) likely point: indent 2x from beginning of
10398 ;; previous code line. Google does it this way.
10399 (push (setq basic-offset
10400 (+ (save-excursion
10401 (back-to-indentation)
10402 (js2-backward-sws)
10403 (back-to-indentation)
10404 (current-column))
10405 (* 2 js2-basic-offset)))
10406 positions)
10407
10408 ;; Second likely point: indent from assign-expr RHS. This
10409 ;; is just a crude guess based on finding " = " on the previous
10410 ;; line containing actual code.
10411 (setq pos (save-excursion
10412 (forward-line -1)
10413 (goto-char (point-at-bol))
10414 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10415 (point-at-eol) t)
10416 (goto-char (match-end 1))
10417 (skip-chars-forward " \t\r\n")
10418 (current-column))))
10419 (when pos
10420 (incf pos js2-basic-offset)
10421 (push pos positions))
10422
10423 ;; Third likely point: same indent as previous line of code.
10424 ;; Make it the first likely point if we're not on an
10425 ;; arglist-close line and previous line ends in a comma, or
10426 ;; both this line and prev line look like object-literal
10427 ;; elements.
10428 (setq pos (save-excursion
10429 (goto-char (point-at-bol))
10430 (js2-backward-sws)
10431 (back-to-indentation)
10432 (prog1
10433 (current-column)
10434 ;; while we're here, look for trailing comma
10435 (if (save-excursion
10436 (goto-char (point-at-eol))
10437 (js2-backward-sws)
10438 (eq (char-before) ?,))
10439 (setq arglist-cont (1- (point)))))))
10440 (when pos
10441 (if (and (or arglist-cont
10442 (js2-indent-in-objlit-p parse-status))
10443 (not (js2-arglist-close)))
10444 (setq same-indent pos))
10445 (push pos positions))
10446
10447 ;; Fourth likely point: first preceding code with less indentation.
10448 ;; than the immediately preceding code line.
10449 (setq pos (save-excursion
10450 (back-to-indentation)
10451 (js2-backward-sws)
10452 (back-to-indentation)
10453 (setq anchor (current-column))
10454 (while (and (zerop (forward-line -1))
10455 (>= (progn
10456 (back-to-indentation)
10457 (current-column))
10458 anchor)))
10459 (setq pos (current-column))))
10460 (push pos positions)
10461
10462 ;; nesting-heuristic position, main by default
10463 (push (setq main-pos normal-col) positions)
10464
10465 ;; delete duplicates and sort positions list
10466 (setq positions (sort (delete-dups positions) '<))
10467
10468 ;; comma-list continuation lines: prev line indent takes precedence
10469 (if same-indent
10470 (setq main-pos same-indent))
10471
10472 ;; common special cases where we want to indent in from previous line
10473 (if (or (js2-indent-case-block-p)
10474 (js2-indent-objlit-arg-p parse-status))
10475 (setq main-pos basic-offset))
10476
10477 ;; if bouncing backwards, reverse positions list
10478 (if backwards
10479 (setq positions (reverse positions)))
10480
10481 ;; record whether we're already sitting on one of the alternatives
10482 (setq pos (member cur-indent positions))
10483
10484 (cond
10485 ;; case 0: we're one one of the alternatives and this is the
10486 ;; first time they've pressed TAB on this line (best-guess).
10487 ((and js2-mode-indent-ignore-first-tab
10488 pos
10489 ;; first time pressing TAB on this line?
10490 (not (eq js2-mode-last-indented-line current-line)))
10491 ;; do nothing
10492 (setq computed-pos nil))
10493 ;; case 1: only one computed position => use it
10494 ((null (cdr positions))
10495 (setq computed-pos 0))
10496 ;; case 2: not on any of the computed spots => use main spot
10497 ((not pos)
10498 (setq computed-pos (js2-position main-pos positions)))
10499 ;; case 3: on last position: cycle to first position
10500 ((null (cdr pos))
10501 (setq computed-pos 0))
10502 ;; case 4: on intermediate position: cycle to next position
10503 (t
10504 (setq computed-pos (js2-position (second pos) positions))))
10505
10506 ;; see if any hooks want to indent; otherwise we do it
10507 (loop with result = nil
10508 for hook in js2-indent-hook
10509 while (null result)
10510 do
10511 (setq result (funcall hook positions computed-pos))
10512 finally do
10513 (unless (or result (null computed-pos))
10514 (indent-line-to (nth computed-pos positions)))))
10515
10516 ;; finally
10517 (if js2-mode-indent-inhibit-undo
10518 (setq buffer-undo-list old-buffer-undo-list))
10519 ;; see commentary for `js2-mode-last-indented-line'
10520 (setq js2-mode-last-indented-line current-line))))
10521
10522 (defun js2-indent-bounce-backwards ()
10523 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10524 cycles between the computed indentation positions in reverse order."
10525 (interactive)
10526 (js2-indent-line t))
10527
10528 (defun js2-1-line-comment-continuation-p ()
10529 "Return t if we're in a 1-line comment continuation.
10530 If so, we don't ever want to use bounce-indent."
10531 (save-excursion
10532 (and (progn
10533 (forward-line 0)
10534 (looking-at "\\s-*//"))
10535 (progn
10536 (forward-line -1)
10537 (forward-line 0)
10538 (when (looking-at "\\s-*$")
10539 (js2-backward-sws)
10540 (forward-line 0))
10541 (looking-at "\\s-*//")))))
10542
10543 (defun js2-indent-line (&optional bounce-backwards)
10544 "Indent the current line as JavaScript source text."
10545 (interactive)
10546 (let (parse-status offset indent-col
10547 ;; Don't whine about errors/warnings when we're indenting.
10548 ;; This has to be set before calling parse-partial-sexp below.
10549 (inhibit-point-motion-hooks t))
10550 (setq parse-status (save-excursion
10551 (syntax-ppss (point-at-bol)))
10552 offset (- (point) (save-excursion
10553 (back-to-indentation)
10554 (point))))
10555 (js2-with-underscore-as-word-syntax
10556 (if (nth 4 parse-status)
10557 (js2-lineup-comment parse-status)
10558 (setq indent-col (js2-proper-indentation parse-status))
10559 ;; See comments below about `js2-mode-last-indented-line'.
10560 (cond
10561 ;; bounce-indenting is disabled during electric-key indent.
10562 ;; It doesn't work well on first line of buffer.
10563 ((and js2-bounce-indent-p
10564 (not (js2-same-line (point-min)))
10565 (not (js2-1-line-comment-continuation-p)))
10566 (js2-bounce-indent indent-col parse-status bounce-backwards))
10567 ;; just indent to the guesser's likely spot
10568 (t (indent-line-to indent-col))))
10569 (when (plusp offset)
10570 (forward-char offset)))))
10571
10572 (defun js2-indent-region (start end)
10573 "Indent the region, but don't use bounce indenting."
10574 (let ((js2-bounce-indent-p nil)
10575 (indent-region-function nil)
10576 (after-change-functions (remq 'js2-mode-edit
10577 after-change-functions)))
10578 (indent-region start end nil) ; nil for byte-compiler
10579 (js2-mode-edit start end (- end start))))
10580
10581 (defvar js2-minor-mode-map
10582 (let ((map (make-sparse-keymap)))
10583 (define-key map (kbd "C-c C-`") #'js2-next-error)
10584 (define-key map [mouse-1] #'js2-mode-show-node)
10585 map)
10586 "Keymap used when `js2-minor-mode' is active.")
10587
10588 ;;;###autoload
10589 (define-minor-mode js2-minor-mode
10590 "Minor mode for running js2 as a background linter.
10591 This allows you to use a different major mode for JavaScript editing,
10592 such as `js-mode', while retaining the asynchronous error/warning
10593 highlighting features of `js2-mode'."
10594 :group 'js2-mode
10595 :lighter " js-lint"
10596 (if js2-minor-mode
10597 (js2-minor-mode-enter)
10598 (js2-minor-mode-exit)))
10599
10600 (defun js2-minor-mode-enter ()
10601 "Initialization for `js2-minor-mode'."
10602 (set (make-local-variable 'max-lisp-eval-depth)
10603 (max max-lisp-eval-depth 3000))
10604 (setq next-error-function #'js2-next-error)
10605 (js2-set-default-externs)
10606 ;; Experiment: make reparse-delay longer for longer files.
10607 (if (plusp js2-dynamic-idle-timer-adjust)
10608 (setq js2-idle-timer-delay
10609 (* js2-idle-timer-delay
10610 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10611 (setq js2-mode-buffer-dirty-p t
10612 js2-mode-parsing nil)
10613 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10614 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10615 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10616 (when js2-include-jslint-globals
10617 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10618 (run-hooks 'js2-init-hook)
10619 (js2-reparse))
10620
10621 (defun js2-minor-mode-exit ()
10622 "Turn off `js2-minor-mode'."
10623 (setq next-error-function nil)
10624 (remove-hook 'after-change-functions #'js2-mode-edit t)
10625 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10626 (when js2-mode-node-overlay
10627 (delete-overlay js2-mode-node-overlay)
10628 (setq js2-mode-node-overlay nil))
10629 (js2-remove-overlays)
10630 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10631 (setq js2-mode-ast nil))
10632
10633 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10634 (make-variable-buffer-local 'js2-source-buffer)
10635
10636 (defun* js2-display-error-list ()
10637 "Display a navigable buffer listing parse errors/warnings."
10638 (interactive)
10639 (unless (js2-have-errors-p)
10640 (message "No errors")
10641 (return-from js2-display-error-list))
10642 (labels ((annotate-list
10643 (lst type)
10644 "Add diagnostic TYPE and line number to errs list"
10645 (mapcar (lambda (err)
10646 (list err type (line-number-at-pos (nth 1 err))))
10647 lst)))
10648 (let* ((srcbuf (current-buffer))
10649 (errbuf (get-buffer-create "*js-lint*"))
10650 (errors (annotate-list
10651 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10652 'js2-error)) ; must be a valid face name
10653 (warnings (annotate-list
10654 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10655 'js2-warning)) ; must be a valid face name
10656 (all-errs (sort (append errors warnings)
10657 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10658 (with-current-buffer errbuf
10659 (let ((inhibit-read-only t))
10660 (erase-buffer)
10661 (dolist (err all-errs)
10662 (destructuring-bind ((msg-key beg _end &rest) type line) err
10663 (insert-text-button
10664 (format "line %d: %s" line (js2-get-msg msg-key))
10665 'face type
10666 'follow-link "\C-m"
10667 'action 'js2-error-buffer-jump
10668 'js2-msg (js2-get-msg msg-key)
10669 'js2-pos beg)
10670 (insert "\n"))))
10671 (js2-error-buffer-mode)
10672 (setq js2-source-buffer srcbuf)
10673 (pop-to-buffer errbuf)
10674 (goto-char (point-min))
10675 (unless (eobp)
10676 (js2-error-buffer-view))))))
10677
10678 (defvar js2-error-buffer-mode-map
10679 (let ((map (make-sparse-keymap)))
10680 (define-key map "n" #'js2-error-buffer-next)
10681 (define-key map "p" #'js2-error-buffer-prev)
10682 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10683 (define-key map "o" #'js2-error-buffer-view)
10684 (define-key map "q" #'js2-error-buffer-quit)
10685 map)
10686 "Keymap used for js2 diagnostics buffers.")
10687
10688 (defun js2-error-buffer-mode ()
10689 "Major mode for js2 diagnostics buffers.
10690 Selecting an error will jump it to the corresponding source-buffer error.
10691 \\{js2-error-buffer-mode-map}"
10692 (interactive)
10693 (setq major-mode 'js2-error-buffer-mode
10694 mode-name "JS Lint Diagnostics")
10695 (use-local-map js2-error-buffer-mode-map)
10696 (setq truncate-lines t)
10697 (set-buffer-modified-p nil)
10698 (setq buffer-read-only t)
10699 (run-hooks 'js2-error-buffer-mode-hook))
10700
10701 (defun js2-error-buffer-next ()
10702 "Move to next error and view it."
10703 (interactive)
10704 (when (zerop (forward-line 1))
10705 (js2-error-buffer-view)))
10706
10707 (defun js2-error-buffer-prev ()
10708 "Move to previous error and view it."
10709 (interactive)
10710 (when (zerop (forward-line -1))
10711 (js2-error-buffer-view)))
10712
10713 (defun js2-error-buffer-quit ()
10714 "Kill the current buffer."
10715 (interactive)
10716 (kill-buffer))
10717
10718 (defun js2-error-buffer-jump (&rest ignored)
10719 "Jump cursor to current error in source buffer."
10720 (interactive)
10721 (when (js2-error-buffer-view)
10722 (pop-to-buffer js2-source-buffer)))
10723
10724 (defun js2-error-buffer-view ()
10725 "Scroll source buffer to show error at current line."
10726 (interactive)
10727 (cond
10728 ((not (eq major-mode 'js2-error-buffer-mode))
10729 (message "Not in a js2 errors buffer"))
10730 ((not (buffer-live-p js2-source-buffer))
10731 (message "Source buffer has been killed"))
10732 ((not (wholenump (get-text-property (point) 'js2-pos)))
10733 (message "There does not seem to be an error here"))
10734 (t
10735 (let ((pos (get-text-property (point) 'js2-pos))
10736 (msg (get-text-property (point) 'js2-msg)))
10737 (save-selected-window
10738 (pop-to-buffer js2-source-buffer)
10739 (goto-char pos)
10740 (message msg))))))
10741
10742 ;;;###autoload
10743 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10744 ;; FIXME: Should derive from js-mode.
10745 "Major mode for editing JavaScript code."
10746 ;; Used by comment-region; don't change it.
10747 (set (make-local-variable 'comment-start) "//")
10748 (set (make-local-variable 'comment-end) "")
10749 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10750 (set (make-local-variable 'max-lisp-eval-depth)
10751 (max max-lisp-eval-depth 3000))
10752 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10753 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10754 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10755 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10756 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10757 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10758 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10759 ;; for characters inside regexp literals.
10760 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10761 ;; this is necessary to make `show-paren-function' work properly
10762 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10763 ;; needed for M-x rgrep, among other things
10764 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10765
10766 (set (make-local-variable 'electric-indent-chars)
10767 (append "{}()[]:;,*." electric-indent-chars))
10768 (set (make-local-variable 'electric-layout-rules)
10769 '((?\; . after) (?\{ . after) (?\} . before)))
10770
10771 ;; some variables needed by cc-engine for paragraph-fill, etc.
10772 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10773 c-comment-start-regexp "/[*/]\\|\\s|"
10774 c-line-comment-starter "//"
10775 c-paragraph-start js2-paragraph-start
10776 c-paragraph-separate "$"
10777 c-syntactic-ws-start js2-syntactic-ws-start
10778 c-syntactic-ws-end js2-syntactic-ws-end
10779 c-syntactic-eol js2-syntactic-eol)
10780
10781 (let ((c-buffer-is-cc-mode t))
10782 ;; Copied from `js-mode'. Also see Bug#6071.
10783 (make-local-variable 'paragraph-start)
10784 (make-local-variable 'paragraph-separate)
10785 (make-local-variable 'paragraph-ignore-fill-prefix)
10786 (make-local-variable 'adaptive-fill-mode)
10787 (make-local-variable 'adaptive-fill-regexp)
10788 (c-setup-paragraph-variables))
10789
10790 (setq font-lock-defaults '(nil t))
10791
10792 ;; Experiment: make reparse-delay longer for longer files.
10793 (when (plusp js2-dynamic-idle-timer-adjust)
10794 (setq js2-idle-timer-delay
10795 (* js2-idle-timer-delay
10796 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10797
10798 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10799 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10800 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10801 (setq next-error-function #'js2-next-error)
10802 (imenu-add-to-menubar (concat "IM-" mode-name))
10803 (add-to-invisibility-spec '(js2-outline . t))
10804 (set (make-local-variable 'line-move-ignore-invisible) t)
10805 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10806
10807 (setq js2-mode-functions-hidden nil
10808 js2-mode-comments-hidden nil
10809 js2-mode-buffer-dirty-p t
10810 js2-mode-parsing nil)
10811
10812 (js2-set-default-externs)
10813
10814 (when js2-include-jslint-globals
10815 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10816
10817 (run-hooks 'js2-init-hook)
10818
10819 (js2-reparse))
10820
10821 (defun js2-mode-exit ()
10822 "Exit `js2-mode' and clean up."
10823 (interactive)
10824 (when js2-mode-node-overlay
10825 (delete-overlay js2-mode-node-overlay)
10826 (setq js2-mode-node-overlay nil))
10827 (js2-remove-overlays)
10828 (setq js2-mode-ast nil)
10829 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10830 (remove-from-invisibility-spec '(js2-outline . t))
10831 (js2-mode-show-all)
10832 (with-silent-modifications
10833 (js2-clear-face (point-min) (point-max))))
10834
10835 (defun js2-mode-reset-timer ()
10836 "Cancel any existing parse timer and schedule a new one."
10837 (if js2-mode-parse-timer
10838 (cancel-timer js2-mode-parse-timer))
10839 (setq js2-mode-parsing nil)
10840 (let ((timer (timer-create)))
10841 (setq js2-mode-parse-timer timer)
10842 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10843 (timer-set-idle-time timer js2-idle-timer-delay)
10844 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10845 (timer-activate-when-idle timer nil)))
10846
10847 (defun js2-mode-idle-reparse (buffer)
10848 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10849 it to be reparsed when the buffer is selected."
10850 (cond ((eq buffer (current-buffer))
10851 (js2-reparse))
10852 ((buffer-live-p buffer)
10853 ;; reparse when the buffer is selected again
10854 (with-current-buffer buffer
10855 (add-hook 'window-configuration-change-hook
10856 #'js2-mode-idle-reparse-inner
10857 nil t)))))
10858
10859 (defun js2-mode-idle-reparse-inner ()
10860 (remove-hook 'window-configuration-change-hook
10861 #'js2-mode-idle-reparse-inner
10862 t)
10863 (js2-reparse))
10864
10865 (defun js2-mode-edit (_beg _end _len)
10866 "Schedule a new parse after buffer is edited.
10867 Buffer edit spans from BEG to END and is of length LEN."
10868 (setq js2-mode-buffer-dirty-p t)
10869 (js2-mode-hide-overlay)
10870 (js2-mode-reset-timer))
10871
10872 (defun js2-minor-mode-edit (_beg _end _len)
10873 "Callback for buffer edits in `js2-mode'.
10874 Schedules a new parse after buffer is edited.
10875 Buffer edit spans from BEG to END and is of length LEN."
10876 (setq js2-mode-buffer-dirty-p t)
10877 (js2-mode-hide-overlay)
10878 (js2-mode-reset-timer))
10879
10880 (defun js2-reparse (&optional force)
10881 "Re-parse current buffer after user finishes some data entry.
10882 If we get any user input while parsing, including cursor motion,
10883 we discard the parse and reschedule it. If FORCE is nil, then the
10884 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10885 (let (time
10886 interrupted-p
10887 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10888 (unless js2-mode-parsing
10889 (setq js2-mode-parsing t)
10890 (unwind-protect
10891 (when (or js2-mode-buffer-dirty-p force)
10892 (js2-remove-overlays)
10893 (with-silent-modifications
10894 (setq js2-mode-buffer-dirty-p nil
10895 js2-mode-fontifications nil
10896 js2-mode-deferred-properties nil)
10897 (if js2-mode-verbose-parse-p
10898 (message "parsing..."))
10899 (setq time
10900 (js2-time
10901 (setq interrupted-p
10902 (catch 'interrupted
10903 (js2-parse)
10904 ;; if parsing is interrupted, comments and regex
10905 ;; literals stay ignored by `parse-partial-sexp'
10906 (remove-text-properties (point-min) (point-max)
10907 '(syntax-table))
10908 (js2-mode-apply-deferred-properties)
10909 (js2-mode-remove-suppressed-warnings)
10910 (js2-mode-show-warnings)
10911 (js2-mode-show-errors)
10912 (if (>= js2-highlight-level 1)
10913 (js2-highlight-jsdoc js2-mode-ast))
10914 nil))))
10915 (if interrupted-p
10916 (progn
10917 ;; unfinished parse => try again
10918 (setq js2-mode-buffer-dirty-p t)
10919 (js2-mode-reset-timer))
10920 (if js2-mode-verbose-parse-p
10921 (message "Parse time: %s" time)))))
10922 (setq js2-mode-parsing nil)
10923 (unless interrupted-p
10924 (setq js2-mode-parse-timer nil))))))
10925
10926 (defun js2-mode-show-node (event)
10927 "Debugging aid: highlight selected AST node on mouse click."
10928 (interactive "e")
10929 (mouse-set-point event)
10930 (setq deactivate-mark t)
10931 (when js2-mode-show-overlay
10932 (let ((node (js2-node-at-point))
10933 beg end)
10934 (if (null node)
10935 (message "No node found at location %s" (point))
10936 (setq beg (js2-node-abs-pos node)
10937 end (+ beg (js2-node-len node)))
10938 (if js2-mode-node-overlay
10939 (move-overlay js2-mode-node-overlay beg end)
10940 (setq js2-mode-node-overlay (make-overlay beg end))
10941 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10942 (with-silent-modifications
10943 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10944 (message "%s, parent: %s"
10945 (js2-node-short-name node)
10946 (if (js2-node-parent node)
10947 (js2-node-short-name (js2-node-parent node))
10948 "nil"))))))
10949
10950 (defun js2-mode-hide-overlay (&optional _p1 p2)
10951 "Remove the debugging overlay when the point moves.
10952 P1 and P2 are the old and new values of point, respectively."
10953 (when js2-mode-node-overlay
10954 (let ((beg (overlay-start js2-mode-node-overlay))
10955 (end (overlay-end js2-mode-node-overlay)))
10956 ;; Sometimes we're called spuriously.
10957 (unless (and p2
10958 (>= p2 beg)
10959 (<= p2 end))
10960 (with-silent-modifications
10961 (remove-text-properties beg end '(point-left nil)))
10962 (delete-overlay js2-mode-node-overlay)
10963 (setq js2-mode-node-overlay nil)))))
10964
10965 (defun js2-mode-reset ()
10966 "Debugging helper: reset everything."
10967 (interactive)
10968 (js2-mode-exit)
10969 (js2-mode))
10970
10971 (defun js2-mode-show-warn-or-err (e face)
10972 "Highlight a warning or error E with FACE.
10973 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10974 The last element is optional. When present, use instead of FACE."
10975 (let* ((key (first e))
10976 (beg (second e))
10977 (end (+ beg (third e)))
10978 ;; Don't inadvertently go out of bounds.
10979 (beg (max (point-min) (min beg (point-max))))
10980 (end (max (point-min) (min end (point-max))))
10981 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10982 (ovl (make-overlay beg end)))
10983 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10984 (overlay-put ovl 'js2-error t)
10985 (put-text-property beg end 'help-echo (js2-get-msg key))
10986 (put-text-property beg end 'point-entered #'js2-echo-error)))
10987
10988 (defun js2-remove-overlays ()
10989 "Remove overlays from buffer that have a `js2-error' property."
10990 (let ((beg (point-min))
10991 (end (point-max)))
10992 (save-excursion
10993 (dolist (o (overlays-in beg end))
10994 (when (overlay-get o 'js2-error)
10995 (delete-overlay o))))))
10996
10997 (defun js2-error-at-point (&optional pos)
10998 "Return non-nil if there's an error overlay at POS.
10999 Defaults to point."
11000 (loop with pos = (or pos (point))
11001 for o in (overlays-at pos)
11002 thereis (overlay-get o 'js2-error)))
11003
11004 (defun js2-mode-apply-deferred-properties ()
11005 "Apply fontifications and other text properties recorded during parsing."
11006 (when (plusp js2-highlight-level)
11007 ;; We defer clearing faces as long as possible to eliminate flashing.
11008 (js2-clear-face (point-min) (point-max))
11009 ;; Have to reverse the recorded fontifications list so that errors
11010 ;; and warnings overwrite the normal fontifications.
11011 (dolist (f (nreverse js2-mode-fontifications))
11012 (put-text-property (first f) (second f) 'font-lock-face (third f)))
11013 (setq js2-mode-fontifications nil))
11014 (dolist (p js2-mode-deferred-properties)
11015 (apply #'put-text-property p))
11016 (setq js2-mode-deferred-properties nil))
11017
11018 (defun js2-mode-show-errors ()
11019 "Highlight syntax errors."
11020 (when js2-mode-show-parse-errors
11021 (dolist (e (js2-ast-root-errors js2-mode-ast))
11022 (js2-mode-show-warn-or-err e 'js2-error))))
11023
11024 (defun js2-mode-remove-suppressed-warnings ()
11025 "Take suppressed warnings out of the AST warnings list.
11026 This ensures that the counts and `next-error' are correct."
11027 (setf (js2-ast-root-warnings js2-mode-ast)
11028 (js2-delete-if
11029 (lambda (e)
11030 (let ((key (caar e)))
11031 (or
11032 (and (not js2-strict-trailing-comma-warning)
11033 (string-match "trailing\\.comma" key))
11034 (and (not js2-strict-cond-assign-warning)
11035 (string= key "msg.equal.as.assign"))
11036 (and js2-missing-semi-one-line-override
11037 (string= key "msg.missing.semi")
11038 (let* ((beg (second e))
11039 (node (js2-node-at-point beg))
11040 (fn (js2-mode-find-parent-fn node))
11041 (body (and fn (js2-function-node-body fn)))
11042 (lc (and body (js2-node-abs-pos body)))
11043 (rc (and lc (+ lc (js2-node-len body)))))
11044 (and fn
11045 (or (null body)
11046 (save-excursion
11047 (goto-char beg)
11048 (and (js2-same-line lc)
11049 (js2-same-line rc))))))))))
11050 (js2-ast-root-warnings js2-mode-ast))))
11051
11052 (defun js2-mode-show-warnings ()
11053 "Highlight strict-mode warnings."
11054 (when js2-mode-show-strict-warnings
11055 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11056 (js2-mode-show-warn-or-err e 'js2-warning))))
11057
11058 (defun js2-echo-error (_old-point new-point)
11059 "Called by point-motion hooks."
11060 (let ((msg (get-text-property new-point 'help-echo)))
11061 (when (and (stringp msg)
11062 (not (active-minibuffer-window))
11063 (not (current-message)))
11064 (message msg))))
11065
11066 (defalias 'js2-echo-help #'js2-echo-error)
11067
11068 (defun js2-line-break (&optional _soft)
11069 "Break line at point and indent, continuing comment if within one.
11070 If inside a string, and `js2-concat-multiline-strings' is not
11071 nil, turn it into concatenation."
11072 (interactive)
11073 (let ((parse-status (syntax-ppss)))
11074 (cond
11075 ;; Check if we're inside a string.
11076 ((nth 3 parse-status)
11077 (if js2-concat-multiline-strings
11078 (js2-mode-split-string parse-status)
11079 (insert "\n")))
11080 ;; Check if inside a block comment.
11081 ((nth 4 parse-status)
11082 (js2-mode-extend-comment (nth 8 parse-status)))
11083 (t
11084 (newline-and-indent)))))
11085
11086 (defun js2-mode-split-string (parse-status)
11087 "Turn a newline in mid-string into a string concatenation.
11088 PARSE-STATUS is as documented in `parse-partial-sexp'."
11089 (let* ((quote-char (nth 3 parse-status))
11090 (at-eol (eq js2-concat-multiline-strings 'eol)))
11091 (insert quote-char)
11092 (insert (if at-eol " +\n" "\n"))
11093 (unless at-eol
11094 (insert "+ "))
11095 (js2-indent-line)
11096 (insert quote-char)
11097 (when (eolp)
11098 (insert quote-char)
11099 (backward-char 1))))
11100
11101 (defun js2-mode-extend-comment (start-pos)
11102 "Indent the line and, when inside a comment block, add comment prefix."
11103 (let (star single col first-line needs-close)
11104 (save-excursion
11105 (back-to-indentation)
11106 (when (< (point) start-pos)
11107 (goto-char start-pos))
11108 (cond
11109 ((looking-at "\\*[^/]")
11110 (setq star t
11111 col (current-column)))
11112 ((looking-at "/\\*")
11113 (setq star t
11114 first-line t
11115 col (1+ (current-column))))
11116 ((looking-at "//")
11117 (setq single t
11118 col (current-column)))))
11119 ;; Heuristic for whether we need to close the comment:
11120 ;; if we've got a parse error here, assume it's an unterminated
11121 ;; comment.
11122 (setq needs-close
11123 (or
11124 (eq (get-text-property (1- (point)) 'point-entered)
11125 'js2-echo-error)
11126 ;; The heuristic above doesn't work well when we're
11127 ;; creating a comment and there's another one downstream,
11128 ;; as our parser thinks this one ends at the end of the
11129 ;; next one. (You can have a /* inside a js block comment.)
11130 ;; So just close it if the next non-ws char isn't a *.
11131 (and first-line
11132 (eolp)
11133 (save-excursion
11134 (skip-chars-forward " \t\r\n")
11135 (not (eq (char-after) ?*))))))
11136 (delete-horizontal-space)
11137 (insert "\n")
11138 (cond
11139 (star
11140 (indent-to col)
11141 (insert "* ")
11142 (if (and first-line needs-close)
11143 (save-excursion
11144 (insert "\n")
11145 (indent-to col)
11146 (insert "*/"))))
11147 ((and single
11148 (save-excursion
11149 (and (zerop (forward-line 1))
11150 (looking-at "\\s-*//"))))
11151 (indent-to col)
11152 (insert "// ")))
11153 ;; Don't need to extend the comment after all.
11154 (js2-indent-line)))
11155
11156 (defun js2-beginning-of-line ()
11157 "Toggle point between bol and first non-whitespace char in line.
11158 Also moves past comment delimiters when inside comments."
11159 (interactive)
11160 (let (node)
11161 (cond
11162 ((bolp)
11163 (back-to-indentation))
11164 ((looking-at "//")
11165 (skip-chars-forward "/ \t"))
11166 ((and (eq (char-after) ?*)
11167 (setq node (js2-comment-at-point))
11168 (memq (js2-comment-node-format node) '(jsdoc block))
11169 (save-excursion
11170 (skip-chars-backward " \t")
11171 (bolp)))
11172 (skip-chars-forward "\* \t"))
11173 (t
11174 (goto-char (point-at-bol))))))
11175
11176 (defun js2-end-of-line ()
11177 "Toggle point between eol and last non-whitespace char in line."
11178 (interactive)
11179 (if (eolp)
11180 (skip-chars-backward " \t")
11181 (goto-char (point-at-eol))))
11182
11183 (defun js2-mode-wait-for-parse (callback)
11184 "Invoke CALLBACK when parsing is finished.
11185 If parsing is already finished, calls CALLBACK immediately."
11186 (if (not js2-mode-buffer-dirty-p)
11187 (funcall callback)
11188 (push callback js2-mode-pending-parse-callbacks)
11189 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11190
11191 (defun js2-mode-parse-finished ()
11192 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11193 ;; We can't let errors propagate up, since it prevents the
11194 ;; `js2-parse' method from completing normally and returning
11195 ;; the ast, which makes things mysteriously not work right.
11196 (unwind-protect
11197 (dolist (cb js2-mode-pending-parse-callbacks)
11198 (condition-case err
11199 (funcall cb)
11200 (error (message "%s" err))))
11201 (setq js2-mode-pending-parse-callbacks nil)))
11202
11203 (defun js2-mode-flag-region (from to flag)
11204 "Hide or show text from FROM to TO, according to FLAG.
11205 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11206 Returns the created overlay if FLAG is non-nil."
11207 (remove-overlays from to 'invisible 'js2-outline)
11208 (when flag
11209 (let ((o (make-overlay from to)))
11210 (overlay-put o 'invisible 'js2-outline)
11211 (overlay-put o 'isearch-open-invisible
11212 'js2-isearch-open-invisible)
11213 o)))
11214
11215 ;; Function to be set as an outline-isearch-open-invisible' property
11216 ;; to the overlay that makes the outline invisible (see
11217 ;; `js2-mode-flag-region').
11218 (defun js2-isearch-open-invisible (_overlay)
11219 ;; We rely on the fact that isearch places point on the matched text.
11220 (js2-mode-show-element))
11221
11222 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11223 "Return cons cell of bounds of folding overlay at POS.
11224 Returns nil if not found."
11225 (let ((overlays (overlays-at (or pos (point))))
11226 o)
11227 (while (and overlays
11228 (not o))
11229 (if (overlay-get (car overlays) 'invisible)
11230 (setq o (car overlays))
11231 (setq overlays (cdr overlays))))
11232 (if o
11233 (cons (overlay-start o) (overlay-end o)))))
11234
11235 (defun js2-mode-function-at-point (&optional pos)
11236 "Return the innermost function node enclosing current point.
11237 Returns nil if point is not in a function."
11238 (let ((node (js2-node-at-point pos)))
11239 (while (and node (not (js2-function-node-p node)))
11240 (setq node (js2-node-parent node)))
11241 (if (js2-function-node-p node)
11242 node)))
11243
11244 (defun js2-mode-toggle-element ()
11245 "Hide or show the foldable element at the point."
11246 (interactive)
11247 (let (comment fn pos)
11248 (save-excursion
11249 (cond
11250 ;; /* ... */ comment?
11251 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11252 (if (js2-mode-invisible-overlay-bounds
11253 (setq pos (+ 3 (js2-node-abs-pos comment))))
11254 (progn
11255 (goto-char pos)
11256 (js2-mode-show-element))
11257 (js2-mode-hide-element)))
11258 ;; //-comment?
11259 ((save-excursion
11260 (back-to-indentation)
11261 (looking-at js2-mode-//-comment-re))
11262 (js2-mode-toggle-//-comment))
11263 ;; function?
11264 ((setq fn (js2-mode-function-at-point))
11265 (setq pos (and (js2-function-node-body fn)
11266 (js2-node-abs-pos (js2-function-node-body fn))))
11267 (goto-char (1+ pos))
11268 (if (js2-mode-invisible-overlay-bounds)
11269 (js2-mode-show-element)
11270 (js2-mode-hide-element)))
11271 (t
11272 (message "Nothing at point to hide or show"))))))
11273
11274 (defun js2-mode-hide-element ()
11275 "Fold/hide contents of a block, showing ellipses.
11276 Show the hidden text with \\[js2-mode-show-element]."
11277 (interactive)
11278 (if js2-mode-buffer-dirty-p
11279 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11280 (let (node body beg end)
11281 (cond
11282 ((js2-mode-invisible-overlay-bounds)
11283 (message "already hidden"))
11284 (t
11285 (setq node (js2-node-at-point))
11286 (cond
11287 ((js2-block-comment-p node)
11288 (js2-mode-hide-comment node))
11289 (t
11290 (while (and node (not (js2-function-node-p node)))
11291 (setq node (js2-node-parent node)))
11292 (if (and node
11293 (setq body (js2-function-node-body node)))
11294 (progn
11295 (setq beg (js2-node-abs-pos body)
11296 end (+ beg (js2-node-len body)))
11297 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11298 (message "No collapsable element found at point"))))))))
11299
11300 (defun js2-mode-show-element ()
11301 "Show the hidden element at current point."
11302 (interactive)
11303 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11304 (if bounds
11305 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11306 (message "Nothing to un-hide"))))
11307
11308 (defun js2-mode-show-all ()
11309 "Show all of the text in the buffer."
11310 (interactive)
11311 (js2-mode-flag-region (point-min) (point-max) nil))
11312
11313 (defun js2-mode-toggle-hide-functions ()
11314 (interactive)
11315 (if js2-mode-functions-hidden
11316 (js2-mode-show-functions)
11317 (js2-mode-hide-functions)))
11318
11319 (defun js2-mode-hide-functions ()
11320 "Hides all non-nested function bodies in the buffer.
11321 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11322 to open an individual entry."
11323 (interactive)
11324 (if js2-mode-buffer-dirty-p
11325 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11326 (if (null js2-mode-ast)
11327 (message "Oops - parsing failed")
11328 (setq js2-mode-functions-hidden t)
11329 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11330
11331 (defun js2-mode-function-hider (n endp)
11332 (when (not endp)
11333 (let ((tt (js2-node-type n))
11334 body beg end)
11335 (cond
11336 ((and (= tt js2-FUNCTION)
11337 (setq body (js2-function-node-body n)))
11338 (setq beg (js2-node-abs-pos body)
11339 end (+ beg (js2-node-len body)))
11340 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11341 nil) ; don't process children of function
11342 (t
11343 t))))) ; keep processing other AST nodes
11344
11345 (defun js2-mode-show-functions ()
11346 "Un-hide any folded function bodies in the buffer."
11347 (interactive)
11348 (setq js2-mode-functions-hidden nil)
11349 (save-excursion
11350 (goto-char (point-min))
11351 (while (/= (goto-char (next-overlay-change (point)))
11352 (point-max))
11353 (dolist (o (overlays-at (point)))
11354 (when (and (overlay-get o 'invisible)
11355 (not (overlay-get o 'comment)))
11356 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11357
11358 (defun js2-mode-hide-comment (n)
11359 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11360 3 ; /**
11361 2)) ; /*
11362 (beg (+ (js2-node-abs-pos n) head))
11363 (end (- (+ beg (js2-node-len n)) head 2))
11364 (o (js2-mode-flag-region beg end 'hide)))
11365 (overlay-put o 'comment t)))
11366
11367 (defun js2-mode-toggle-hide-comments ()
11368 "Folds all block comments in the buffer.
11369 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11370 to open an individual entry."
11371 (interactive)
11372 (if js2-mode-comments-hidden
11373 (js2-mode-show-comments)
11374 (js2-mode-hide-comments)))
11375
11376 (defun js2-mode-hide-comments ()
11377 (interactive)
11378 (if js2-mode-buffer-dirty-p
11379 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11380 (if (null js2-mode-ast)
11381 (message "Oops - parsing failed")
11382 (setq js2-mode-comments-hidden t)
11383 (dolist (n (js2-ast-root-comments js2-mode-ast))
11384 (when (js2-block-comment-p n)
11385 (js2-mode-hide-comment n)))
11386 (js2-mode-hide-//-comments)))
11387
11388 (defun js2-mode-extend-//-comment (direction)
11389 "Find start or end of a block of similar //-comment lines.
11390 DIRECTION is -1 to look back, 1 to look forward.
11391 INDENT is the indentation level to match.
11392 Returns the end-of-line position of the furthest adjacent
11393 //-comment line with the same indentation as the current line.
11394 If there is no such matching line, returns current end of line."
11395 (let ((pos (point-at-eol))
11396 (indent (current-indentation)))
11397 (save-excursion
11398 (while (and (zerop (forward-line direction))
11399 (looking-at js2-mode-//-comment-re)
11400 (eq indent (length (match-string 1))))
11401 (setq pos (point-at-eol)))
11402 pos)))
11403
11404 (defun js2-mode-hide-//-comments ()
11405 "Fold adjacent 1-line comments, showing only snippet of first one."
11406 (let (beg end)
11407 (save-excursion
11408 (goto-char (point-min))
11409 (while (re-search-forward js2-mode-//-comment-re nil t)
11410 (setq beg (point)
11411 end (js2-mode-extend-//-comment 1))
11412 (unless (eq beg end)
11413 (overlay-put (js2-mode-flag-region beg end 'hide)
11414 'comment t))
11415 (goto-char end)
11416 (forward-char 1)))))
11417
11418 (defun js2-mode-toggle-//-comment ()
11419 "Fold or un-fold any multi-line //-comment at point.
11420 Caller should have determined that this line starts with a //-comment."
11421 (let* ((beg (point-at-eol))
11422 (end beg))
11423 (save-excursion
11424 (goto-char end)
11425 (if (js2-mode-invisible-overlay-bounds)
11426 (js2-mode-show-element)
11427 ;; else hide the comment
11428 (setq beg (js2-mode-extend-//-comment -1)
11429 end (js2-mode-extend-//-comment 1))
11430 (unless (eq beg end)
11431 (overlay-put (js2-mode-flag-region beg end 'hide)
11432 'comment t))))))
11433
11434 (defun js2-mode-show-comments ()
11435 "Un-hide any hidden comments, leaving other hidden elements alone."
11436 (interactive)
11437 (setq js2-mode-comments-hidden nil)
11438 (save-excursion
11439 (goto-char (point-min))
11440 (while (/= (goto-char (next-overlay-change (point)))
11441 (point-max))
11442 (dolist (o (overlays-at (point)))
11443 (when (overlay-get o 'comment)
11444 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11445
11446 (defun js2-mode-display-warnings-and-errors ()
11447 "Turn on display of warnings and errors."
11448 (interactive)
11449 (setq js2-mode-show-parse-errors t
11450 js2-mode-show-strict-warnings t)
11451 (js2-reparse 'force))
11452
11453 (defun js2-mode-hide-warnings-and-errors ()
11454 "Turn off display of warnings and errors."
11455 (interactive)
11456 (setq js2-mode-show-parse-errors nil
11457 js2-mode-show-strict-warnings nil)
11458 (js2-reparse 'force))
11459
11460 (defun js2-mode-toggle-warnings-and-errors ()
11461 "Toggle the display of warnings and errors.
11462 Some users don't like having warnings/errors reported while they type."
11463 (interactive)
11464 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11465 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11466 (if (called-interactively-p 'any)
11467 (message "warnings and errors %s"
11468 (if js2-mode-show-parse-errors
11469 "enabled"
11470 "disabled")))
11471 (js2-reparse 'force))
11472
11473 (defun js2-mode-customize ()
11474 (interactive)
11475 (customize-group 'js2-mode))
11476
11477 (defun js2-mode-forward-sexp (&optional arg)
11478 "Move forward across one statement or balanced expression.
11479 With ARG, do it that many times. Negative arg -N means
11480 move backward across N balanced expressions."
11481 (interactive "p")
11482 (setq arg (or arg 1))
11483 (save-restriction
11484 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11485 (js2-reparse)
11486 (let (forward-sexp-function
11487 node (start (point)) pos lp rp child)
11488 (cond
11489 ;; backward-sexp
11490 ;; could probably make this better for some cases:
11491 ;; - if in statement block (e.g. function body), go to parent
11492 ;; - infix exprs like (foo in bar) - maybe go to beginning
11493 ;; of infix expr if in the right-side expression?
11494 ((and arg (minusp arg))
11495 (dotimes (_ (- arg))
11496 (js2-backward-sws)
11497 (forward-char -1) ; Enter the node we backed up to.
11498 (when (setq node (js2-node-at-point (point) t))
11499 (setq pos (js2-node-abs-pos node))
11500 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11501 (setq lp (car parens)
11502 rp (cdr parens)))
11503 (when (and lp (> start lp))
11504 (if (and rp (<= start rp))
11505 ;; Between parens, check if there's a child node we can jump.
11506 (when (setq child (js2-node-closest-child node (point) lp t))
11507 (setq pos (js2-node-abs-pos child)))
11508 ;; Before both parens.
11509 (setq pos lp)))
11510 (let ((state (parse-partial-sexp start pos)))
11511 (goto-char (if (not (zerop (car state)))
11512 ;; Stumble at the unbalanced paren if < 0, or
11513 ;; jump a bit further if > 0.
11514 (scan-sexps start -1)
11515 pos))))
11516 (unless pos (goto-char (point-min)))))
11517 (t
11518 ;; forward-sexp
11519 (dotimes (_ arg)
11520 (js2-forward-sws)
11521 (when (setq node (js2-node-at-point (point) t))
11522 (setq pos (js2-node-abs-pos node))
11523 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11524 (setq lp (car parens)
11525 rp (cdr parens)))
11526 (or
11527 (when (and rp (<= start rp))
11528 (if (> start lp)
11529 (when (setq child (js2-node-closest-child node (point) rp))
11530 (setq pos (js2-node-abs-end child)))
11531 (setq pos (1+ rp))))
11532 ;; No parens or child nodes, looks for the end of the curren node.
11533 (incf pos (js2-node-len
11534 (if (js2-expr-stmt-node-p (js2-node-parent node))
11535 ;; Stop after the semicolon.
11536 (js2-node-parent node)
11537 node))))
11538 (let ((state (save-excursion (parse-partial-sexp start pos))))
11539 (goto-char (if (not (zerop (car state)))
11540 (scan-sexps start 1)
11541 pos))))
11542 (unless pos (goto-char (point-max)))))))))
11543
11544 (defun js2-mode-forward-sexp-parens (node abs-pos)
11545 "Return a cons cell with positions of main parens in NODE."
11546 (cond
11547 ((or (js2-array-node-p node)
11548 (js2-object-node-p node)
11549 (js2-comp-node-p node)
11550 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11551 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11552 ((js2-paren-expr-node-p node)
11553 (let ((lp (js2-node-lp node))
11554 (rp (js2-node-rp node)))
11555 (cons (when lp (+ abs-pos lp))
11556 (when rp (+ abs-pos rp)))))))
11557
11558 (defun js2-node-closest-child (parent point limit &optional before)
11559 (let* ((parent-pos (js2-node-abs-pos parent))
11560 (rpoint (- point parent-pos))
11561 (rlimit (- limit parent-pos))
11562 (min (min rpoint rlimit))
11563 (max (max rpoint rlimit))
11564 found)
11565 (catch 'done
11566 (js2-visit-ast
11567 parent
11568 (lambda (node _end-p)
11569 (if (eq node parent)
11570 t
11571 (let ((pos (js2-node-pos node)) ;; Both relative values.
11572 (end (+ (js2-node-pos node) (js2-node-len node))))
11573 (when (and (>= pos min) (<= end max)
11574 (if before (< pos rpoint) (> end rpoint)))
11575 (setq found node))
11576 (when (> end rpoint)
11577 (throw 'done nil)))
11578 nil))))
11579 found))
11580
11581 (defun js2-errors ()
11582 "Return a list of errors found."
11583 (and js2-mode-ast
11584 (js2-ast-root-errors js2-mode-ast)))
11585
11586 (defun js2-warnings ()
11587 "Return a list of warnings found."
11588 (and js2-mode-ast
11589 (js2-ast-root-warnings js2-mode-ast)))
11590
11591 (defun js2-have-errors-p ()
11592 "Return non-nil if any parse errors or warnings were found."
11593 (or (js2-errors) (js2-warnings)))
11594
11595 (defun js2-errors-and-warnings ()
11596 "Return a copy of the concatenated errors and warnings lists.
11597 They are appended: first the errors, then the warnings.
11598 Entries are of the form (MSG BEG END)."
11599 (when js2-mode-ast
11600 (append (js2-ast-root-errors js2-mode-ast)
11601 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11602
11603 (defun js2-next-error (&optional arg reset)
11604 "Move to next parse error.
11605 Typically invoked via \\[next-error].
11606 ARG is the number of errors, forward or backward, to move.
11607 RESET means start over from the beginning."
11608 (interactive "p")
11609 (if (not (or (js2-errors) (js2-warnings)))
11610 (message "No errors")
11611 (when reset
11612 (goto-char (point-min)))
11613 (let* ((errs (js2-errors-and-warnings))
11614 (continue t)
11615 (start (point))
11616 (count (or arg 1))
11617 (backward (minusp count))
11618 (sorter (if backward '> '<))
11619 (stopper (if backward '< '>))
11620 (count (abs count))
11621 all-errs err)
11622 ;; Sort by start position.
11623 (setq errs (sort errs (lambda (e1 e2)
11624 (funcall sorter (second e1) (second e2))))
11625 all-errs errs)
11626 ;; Find nth error with pos > start.
11627 (while (and errs continue)
11628 (when (funcall stopper (cadar errs) start)
11629 (setq err (car errs))
11630 (if (zerop (decf count))
11631 (setq continue nil)))
11632 (setq errs (cdr errs)))
11633 ;; Clear for `js2-echo-error'.
11634 (message nil)
11635 (if err
11636 (goto-char (second err))
11637 ;; Wrap around to first error.
11638 (goto-char (second (car all-errs)))
11639 ;; If we were already on it, echo msg again.
11640 (if (= (point) start)
11641 (js2-echo-error (point) (point)))))))
11642
11643 (defun js2-down-mouse-3 ()
11644 "Make right-click move the point to the click location.
11645 This makes right-click context menu operations a bit more intuitive.
11646 The point will not move if the region is active, however, to avoid
11647 destroying the region selection."
11648 (interactive)
11649 (when (and js2-move-point-on-right-click
11650 (not mark-active))
11651 (let ((e last-input-event))
11652 (ignore-errors
11653 (goto-char (cadadr e))))))
11654
11655 (defun js2-mode-create-imenu-index ()
11656 "Return an alist for `imenu--index-alist'."
11657 ;; This is built up in `js2-parse-record-imenu' during parsing.
11658 (when js2-mode-ast
11659 ;; if we have an ast but no recorder, they're requesting a rescan
11660 (unless js2-imenu-recorder
11661 (js2-reparse 'force))
11662 (prog1
11663 (js2-build-imenu-index)
11664 (setq js2-imenu-recorder nil
11665 js2-imenu-function-map nil))))
11666
11667 (defun js2-mode-find-tag ()
11668 "Replacement for `find-tag-default'.
11669 `find-tag-default' returns a ridiculous answer inside comments."
11670 (let (beg end)
11671 (js2-with-underscore-as-word-syntax
11672 (save-excursion
11673 (if (and (not (looking-at "[[:alnum:]_$]"))
11674 (looking-back "[[:alnum:]_$]"))
11675 (setq beg (progn (forward-word -1) (point))
11676 end (progn (forward-word 1) (point)))
11677 (setq beg (progn (forward-word 1) (point))
11678 end (progn (forward-word -1) (point))))
11679 (replace-regexp-in-string
11680 "[\"']" ""
11681 (buffer-substring-no-properties beg end))))))
11682
11683 (defun js2-mode-forward-sibling ()
11684 "Move to the end of the sibling following point in parent.
11685 Returns non-nil if successful, or nil if there was no following sibling."
11686 (let* ((node (js2-node-at-point))
11687 (parent (js2-mode-find-enclosing-fn node))
11688 sib)
11689 (when (setq sib (js2-node-find-child-after (point) parent))
11690 (goto-char (+ (js2-node-abs-pos sib)
11691 (js2-node-len sib))))))
11692
11693 (defun js2-mode-backward-sibling ()
11694 "Move to the beginning of the sibling node preceding point in parent.
11695 Parent is defined as the enclosing script or function."
11696 (let* ((node (js2-node-at-point))
11697 (parent (js2-mode-find-enclosing-fn node))
11698 sib)
11699 (when (setq sib (js2-node-find-child-before (point) parent))
11700 (goto-char (js2-node-abs-pos sib)))))
11701
11702 (defun js2-beginning-of-defun (&optional arg)
11703 "Go to line on which current function starts, and return t on success.
11704 If we're not in a function or already at the beginning of one, go
11705 to beginning of previous script-level element.
11706 With ARG N, do that N times. If N is negative, move forward."
11707 (setq arg (or arg 1))
11708 (if (plusp arg)
11709 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11710 (when (cond
11711 ((js2-function-node-p parent)
11712 (goto-char (js2-node-abs-pos parent)))
11713 (t
11714 (js2-mode-backward-sibling)))
11715 (if (> arg 1)
11716 (js2-beginning-of-defun (1- arg))
11717 t)))
11718 (when (js2-end-of-defun)
11719 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11720
11721 (defun js2-end-of-defun ()
11722 "Go to the char after the last position of the current function
11723 or script-level element."
11724 (let* ((node (js2-node-at-point))
11725 (parent (or (and (js2-function-node-p node) node)
11726 (js2-node-parent-script-or-fn node)))
11727 script)
11728 (unless (js2-function-node-p parent)
11729 ;; Use current script-level node, or, if none, the next one.
11730 (setq script (or parent node)
11731 parent (js2-node-find-child-before (point) script))
11732 (when (or (null parent)
11733 (>= (point) (+ (js2-node-abs-pos parent)
11734 (js2-node-len parent))))
11735 (setq parent (js2-node-find-child-after (point) script))))
11736 (when parent
11737 (goto-char (+ (js2-node-abs-pos parent)
11738 (js2-node-len parent))))))
11739
11740 (defun js2-mark-defun (&optional allow-extend)
11741 "Put mark at end of this function, point at beginning.
11742 The function marked is the one that contains point.
11743
11744 Interactively, if this command is repeated,
11745 or (in Transient Mark mode) if the mark is active,
11746 it marks the next defun after the ones already marked."
11747 (interactive "p")
11748 (let (extended)
11749 (when (and allow-extend
11750 (or (and (eq last-command this-command) (mark t))
11751 (and transient-mark-mode mark-active)))
11752 (let ((sib (save-excursion
11753 (goto-char (mark))
11754 (if (js2-mode-forward-sibling)
11755 (point)))))
11756 (if sib
11757 (progn
11758 (set-mark sib)
11759 (setq extended t))
11760 ;; no more siblings - try extending to enclosing node
11761 (goto-char (mark t)))))
11762 (when (not extended)
11763 (let ((node (js2-node-at-point (point) t)) ; skip comments
11764 ast fn stmt parent beg end)
11765 (when (js2-ast-root-p node)
11766 (setq ast node
11767 node (or (js2-node-find-child-after (point) node)
11768 (js2-node-find-child-before (point) node))))
11769 ;; only mark whole buffer if we can't find any children
11770 (if (null node)
11771 (setq node ast))
11772 (if (js2-function-node-p node)
11773 (setq parent node)
11774 (setq fn (js2-mode-find-enclosing-fn node)
11775 stmt (if (or (null fn)
11776 (js2-ast-root-p fn))
11777 (js2-mode-find-first-stmt node))
11778 parent (or stmt fn)))
11779 (setq beg (js2-node-abs-pos parent)
11780 end (+ beg (js2-node-len parent)))
11781 (push-mark beg)
11782 (goto-char end)
11783 (exchange-point-and-mark)))))
11784
11785 (defun js2-narrow-to-defun ()
11786 "Narrow to the function enclosing point."
11787 (interactive)
11788 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11789 (fn (if (js2-script-node-p node)
11790 node
11791 (js2-mode-find-enclosing-fn node)))
11792 (beg (js2-node-abs-pos fn)))
11793 (unless (js2-ast-root-p fn)
11794 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11795
11796 (provide 'js2-mode)
11797
11798 ;;; js2-mode.el ends here