]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Highlight methods with font-lock-function-name-face
[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 (js2-msg "msg.mod.import.decl.at.top.level"
1499 "SyntaxError: import declarations may only appear at the top level")
1500
1501 (js2-msg "msg.mod.as.after.reserved.word"
1502 "SyntaxError: missing keyword 'as' after reserved word %s")
1503
1504 (js2-msg "msg.mod.rc.after.import.spec.list"
1505 "SyntaxError: missing '}' after module specifier list")
1506
1507 (js2-msg "msg.mod.from.after.import.spec.set"
1508 "SyntaxError: missing keyword 'from' after import specifier set")
1509
1510 (js2-msg "msg.mod.declaration.after.import"
1511 "SyntaxError: missing declaration after 'import' keyword")
1512
1513 (js2-msg "msg.mod.spec.after.from"
1514 "SyntaxError: missing module specifier after 'from' keyword")
1515
1516 (js2-msg "msg.mod.export.decl.at.top.level"
1517 "SyntaxError: export declarations may only appear at top level")
1518
1519 (js2-msg "msg.mod.rc.after.export.spec.list"
1520 "SyntaxError: missing '}' after export specifier list")
1521
1522 ;; NodeTransformer
1523 (js2-msg "msg.dup.label"
1524 "duplicated label")
1525
1526 (js2-msg "msg.undef.label"
1527 "undefined label")
1528
1529 (js2-msg "msg.bad.break"
1530 "unlabelled break must be inside loop or switch")
1531
1532 (js2-msg "msg.continue.outside"
1533 "continue must be inside loop")
1534
1535 (js2-msg "msg.continue.nonloop"
1536 "continue can only use labels of iteration statements")
1537
1538 (js2-msg "msg.bad.throw.eol"
1539 "Line terminator is not allowed between the throw "
1540 "keyword and throw expression.")
1541
1542 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1543 "function statement requires a name")
1544
1545 (js2-msg "msg.no.paren.parms"
1546 "missing ( before function parameters.")
1547
1548 (js2-msg "msg.no.parm"
1549 "missing formal parameter")
1550
1551 (js2-msg "msg.no.paren.after.parms"
1552 "missing ) after formal parameters")
1553
1554 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1555 "parameter without default follows parameter with default")
1556
1557 (js2-msg "msg.param.after.rest" ; added by js2-mode
1558 "parameter after rest parameter")
1559
1560 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1561 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1562
1563 (js2-msg "msg.no.brace.body"
1564 "missing '{' before function body")
1565
1566 (js2-msg "msg.no.brace.after.body"
1567 "missing } after function body")
1568
1569 (js2-msg "msg.no.paren.cond"
1570 "missing ( before condition")
1571
1572 (js2-msg "msg.no.paren.after.cond"
1573 "missing ) after condition")
1574
1575 (js2-msg "msg.no.semi.stmt"
1576 "missing ; before statement")
1577
1578 (js2-msg "msg.missing.semi"
1579 "missing ; after statement")
1580
1581 (js2-msg "msg.no.name.after.dot"
1582 "missing name after . operator")
1583
1584 (js2-msg "msg.no.name.after.coloncolon"
1585 "missing name after :: operator")
1586
1587 (js2-msg "msg.no.name.after.dotdot"
1588 "missing name after .. operator")
1589
1590 (js2-msg "msg.no.name.after.xmlAttr"
1591 "missing name after .@")
1592
1593 (js2-msg "msg.no.bracket.index"
1594 "missing ] in index expression")
1595
1596 (js2-msg "msg.no.paren.switch"
1597 "missing ( before switch expression")
1598
1599 (js2-msg "msg.no.paren.after.switch"
1600 "missing ) after switch expression")
1601
1602 (js2-msg "msg.no.brace.switch"
1603 "missing '{' before switch body")
1604
1605 (js2-msg "msg.bad.switch"
1606 "invalid switch statement")
1607
1608 (js2-msg "msg.no.colon.case"
1609 "missing : after case expression")
1610
1611 (js2-msg "msg.double.switch.default"
1612 "double default label in the switch statement")
1613
1614 (js2-msg "msg.no.while.do"
1615 "missing while after do-loop body")
1616
1617 (js2-msg "msg.no.paren.for"
1618 "missing ( after for")
1619
1620 (js2-msg "msg.no.semi.for"
1621 "missing ; after for-loop initializer")
1622
1623 (js2-msg "msg.no.semi.for.cond"
1624 "missing ; after for-loop condition")
1625
1626 (js2-msg "msg.in.after.for.name"
1627 "missing in or of after for")
1628
1629 (js2-msg "msg.no.paren.for.ctrl"
1630 "missing ) after for-loop control")
1631
1632 (js2-msg "msg.no.paren.with"
1633 "missing ( before with-statement object")
1634
1635 (js2-msg "msg.no.paren.after.with"
1636 "missing ) after with-statement object")
1637
1638 (js2-msg "msg.no.paren.after.let"
1639 "missing ( after let")
1640
1641 (js2-msg "msg.no.paren.let"
1642 "missing ) after variable list")
1643
1644 (js2-msg "msg.no.curly.let"
1645 "missing } after let statement")
1646
1647 (js2-msg "msg.bad.return"
1648 "invalid return")
1649
1650 (js2-msg "msg.no.brace.block"
1651 "missing } in compound statement")
1652
1653 (js2-msg "msg.bad.label"
1654 "invalid label")
1655
1656 (js2-msg "msg.bad.var"
1657 "missing variable name")
1658
1659 (js2-msg "msg.bad.var.init"
1660 "invalid variable initialization")
1661
1662 (js2-msg "msg.no.colon.cond"
1663 "missing : in conditional expression")
1664
1665 (js2-msg "msg.no.paren.arg"
1666 "missing ) after argument list")
1667
1668 (js2-msg "msg.no.bracket.arg"
1669 "missing ] after element list")
1670
1671 (js2-msg "msg.bad.prop"
1672 "invalid property id")
1673
1674 (js2-msg "msg.no.colon.prop"
1675 "missing : after property id")
1676
1677 (js2-msg "msg.no.brace.prop"
1678 "missing } after property list")
1679
1680 (js2-msg "msg.no.paren"
1681 "missing ) in parenthetical")
1682
1683 (js2-msg "msg.reserved.id"
1684 "'%s' is a reserved identifier")
1685
1686 (js2-msg "msg.no.paren.catch"
1687 "missing ( before catch-block condition")
1688
1689 (js2-msg "msg.bad.catchcond"
1690 "invalid catch block condition")
1691
1692 (js2-msg "msg.catch.unreachable"
1693 "any catch clauses following an unqualified catch are unreachable")
1694
1695 (js2-msg "msg.no.brace.try"
1696 "missing '{' before try block")
1697
1698 (js2-msg "msg.no.brace.catchblock"
1699 "missing '{' before catch-block body")
1700
1701 (js2-msg "msg.try.no.catchfinally"
1702 "'try' without 'catch' or 'finally'")
1703
1704 (js2-msg "msg.no.return.value"
1705 "function %s does not always return a value")
1706
1707 (js2-msg "msg.anon.no.return.value"
1708 "anonymous function does not always return a value")
1709
1710 (js2-msg "msg.return.inconsistent"
1711 "return statement is inconsistent with previous usage")
1712
1713 (js2-msg "msg.generator.returns"
1714 "TypeError: legacy generator function '%s' returns a value")
1715
1716 (js2-msg "msg.anon.generator.returns"
1717 "TypeError: anonymous legacy generator function returns a value")
1718
1719 (js2-msg "msg.syntax"
1720 "syntax error")
1721
1722 (js2-msg "msg.unexpected.eof"
1723 "Unexpected end of file")
1724
1725 (js2-msg "msg.XML.bad.form"
1726 "illegally formed XML syntax")
1727
1728 (js2-msg "msg.XML.not.available"
1729 "XML runtime not available")
1730
1731 (js2-msg "msg.too.deep.parser.recursion"
1732 "Too deep recursion while parsing")
1733
1734 (js2-msg "msg.no.side.effects"
1735 "Code has no side effects")
1736
1737 (js2-msg "msg.extra.trailing.comma"
1738 "Trailing comma is not supported in some browsers")
1739
1740 (js2-msg "msg.array.trailing.comma"
1741 "Trailing comma yields different behavior across browsers")
1742
1743 (js2-msg "msg.equal.as.assign"
1744 (concat "Test for equality (==) mistyped as assignment (=)?"
1745 " (parenthesize to suppress warning)"))
1746
1747 (js2-msg "msg.var.hides.arg"
1748 "Variable %s hides argument")
1749
1750 (js2-msg "msg.destruct.assign.no.init"
1751 "Missing = in destructuring declaration")
1752
1753 ;; ScriptRuntime
1754 (js2-msg "msg.no.properties"
1755 "%s has no properties.")
1756
1757 (js2-msg "msg.invalid.iterator"
1758 "Invalid iterator value")
1759
1760 (js2-msg "msg.iterator.primitive"
1761 "__iterator__ returned a primitive value")
1762
1763 (js2-msg "msg.assn.create.strict"
1764 "Assignment to undeclared variable %s")
1765
1766 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1767 "Undeclared variable or function '%s'")
1768
1769 (js2-msg "msg.ref.undefined.prop"
1770 "Reference to undefined property '%s'")
1771
1772 (js2-msg "msg.prop.not.found"
1773 "Property %s not found.")
1774
1775 (js2-msg "msg.invalid.type"
1776 "Invalid JavaScript value of type %s")
1777
1778 (js2-msg "msg.primitive.expected"
1779 "Primitive type expected (had %s instead)")
1780
1781 (js2-msg "msg.namespace.expected"
1782 "Namespace object expected to left of :: (found %s instead)")
1783
1784 (js2-msg "msg.null.to.object"
1785 "Cannot convert null to an object.")
1786
1787 (js2-msg "msg.undef.to.object"
1788 "Cannot convert undefined to an object.")
1789
1790 (js2-msg "msg.cyclic.value"
1791 "Cyclic %s value not allowed.")
1792
1793 (js2-msg "msg.is.not.defined"
1794 "'%s' is not defined.")
1795
1796 (js2-msg "msg.undef.prop.read"
1797 "Cannot read property '%s' from %s")
1798
1799 (js2-msg "msg.undef.prop.write"
1800 "Cannot set property '%s' of %s to '%s'")
1801
1802 (js2-msg "msg.undef.prop.delete"
1803 "Cannot delete property '%s' of %s")
1804
1805 (js2-msg "msg.undef.method.call"
1806 "Cannot call method '%s' of %s")
1807
1808 (js2-msg "msg.undef.with"
1809 "Cannot apply 'with' to %s")
1810
1811 (js2-msg "msg.isnt.function"
1812 "%s is not a function, it is %s.")
1813
1814 (js2-msg "msg.isnt.function.in"
1815 "Cannot call property %s in object %s. "
1816 "It is not a function, it is '%s'.")
1817
1818 (js2-msg "msg.function.not.found"
1819 "Cannot find function %s.")
1820
1821 (js2-msg "msg.function.not.found.in"
1822 "Cannot find function %s in object %s.")
1823
1824 (js2-msg "msg.isnt.xml.object"
1825 "%s is not an xml object.")
1826
1827 (js2-msg "msg.no.ref.to.get"
1828 "%s is not a reference to read reference value.")
1829
1830 (js2-msg "msg.no.ref.to.set"
1831 "%s is not a reference to set reference value to %s.")
1832
1833 (js2-msg "msg.no.ref.from.function"
1834 "Function %s can not be used as the left-hand "
1835 "side of assignment or as an operand of ++ or -- operator.")
1836
1837 (js2-msg "msg.bad.default.value"
1838 "Object's getDefaultValue() method returned an object.")
1839
1840 (js2-msg "msg.instanceof.not.object"
1841 "Can't use instanceof on a non-object.")
1842
1843 (js2-msg "msg.instanceof.bad.prototype"
1844 "'prototype' property of %s is not an object.")
1845
1846 (js2-msg "msg.bad.radix"
1847 "illegal radix %s.")
1848
1849 ;; ScriptableObject
1850 (js2-msg "msg.default.value"
1851 "Cannot find default value for object.")
1852
1853 (js2-msg "msg.zero.arg.ctor"
1854 "Cannot load class '%s' which has no zero-parameter constructor.")
1855
1856 (js2-msg "msg.ctor.multiple.parms"
1857 "Can't define constructor or class %s since more than "
1858 "one constructor has multiple parameters.")
1859
1860 (js2-msg "msg.extend.scriptable"
1861 "%s must extend ScriptableObject in order to define property %s.")
1862
1863 (js2-msg "msg.bad.getter.parms"
1864 "In order to define a property, getter %s must have zero "
1865 "parameters or a single ScriptableObject parameter.")
1866
1867 (js2-msg "msg.obj.getter.parms"
1868 "Expected static or delegated getter %s to take "
1869 "a ScriptableObject parameter.")
1870
1871 (js2-msg "msg.getter.static"
1872 "Getter and setter must both be static or neither be static.")
1873
1874 (js2-msg "msg.setter.return"
1875 "Setter must have void return type: %s")
1876
1877 (js2-msg "msg.setter2.parms"
1878 "Two-parameter setter must take a ScriptableObject as "
1879 "its first parameter.")
1880
1881 (js2-msg "msg.setter1.parms"
1882 "Expected single parameter setter for %s")
1883
1884 (js2-msg "msg.setter2.expected"
1885 "Expected static or delegated setter %s to take two parameters.")
1886
1887 (js2-msg "msg.setter.parms"
1888 "Expected either one or two parameters for setter.")
1889
1890 (js2-msg "msg.setter.bad.type"
1891 "Unsupported parameter type '%s' in setter '%s'.")
1892
1893 (js2-msg "msg.add.sealed"
1894 "Cannot add a property to a sealed object: %s.")
1895
1896 (js2-msg "msg.remove.sealed"
1897 "Cannot remove a property from a sealed object: %s.")
1898
1899 (js2-msg "msg.modify.sealed"
1900 "Cannot modify a property of a sealed object: %s.")
1901
1902 (js2-msg "msg.modify.readonly"
1903 "Cannot modify readonly property: %s.")
1904
1905 ;; TokenStream
1906 (js2-msg "msg.missing.exponent"
1907 "missing exponent")
1908
1909 (js2-msg "msg.caught.nfe"
1910 "number format error")
1911
1912 (js2-msg "msg.unterminated.string.lit"
1913 "unterminated string literal")
1914
1915 (js2-msg "msg.unterminated.comment"
1916 "unterminated comment")
1917
1918 (js2-msg "msg.unterminated.re.lit"
1919 "unterminated regular expression literal")
1920
1921 (js2-msg "msg.invalid.re.flag"
1922 "invalid flag after regular expression")
1923
1924 (js2-msg "msg.no.re.input.for"
1925 "no input for %s")
1926
1927 (js2-msg "msg.illegal.character"
1928 "illegal character")
1929
1930 (js2-msg "msg.invalid.escape"
1931 "invalid Unicode escape sequence")
1932
1933 (js2-msg "msg.bad.namespace"
1934 "not a valid default namespace statement. "
1935 "Syntax is: default xml namespace = EXPRESSION;")
1936
1937 ;; TokensStream warnings
1938 (js2-msg "msg.bad.octal.literal"
1939 "illegal octal literal digit %s; "
1940 "interpreting it as a decimal digit")
1941
1942 (js2-msg "msg.missing.hex.digits"
1943 "missing hexadecimal digits after '0x'")
1944
1945 (js2-msg "msg.missing.binary.digits"
1946 "missing binary digits after '0b'")
1947
1948 (js2-msg "msg.missing.octal.digits"
1949 "missing octal digits after '0o'")
1950
1951 (js2-msg "msg.script.is.not.constructor"
1952 "Script objects are not constructors.")
1953
1954 ;; Arrays
1955 (js2-msg "msg.arraylength.bad"
1956 "Inappropriate array length.")
1957
1958 ;; Arrays
1959 (js2-msg "msg.arraylength.too.big"
1960 "Array length %s exceeds supported capacity limit.")
1961
1962 ;; URI
1963 (js2-msg "msg.bad.uri"
1964 "Malformed URI sequence.")
1965
1966 ;; Number
1967 (js2-msg "msg.bad.precision"
1968 "Precision %s out of range.")
1969
1970 ;; NativeGenerator
1971 (js2-msg "msg.send.newborn"
1972 "Attempt to send value to newborn generator")
1973
1974 (js2-msg "msg.already.exec.gen"
1975 "Already executing generator")
1976
1977 (js2-msg "msg.StopIteration.invalid"
1978 "StopIteration may not be changed to an arbitrary object.")
1979
1980 ;; Interpreter
1981 (js2-msg "msg.yield.closing"
1982 "Yield from closing generator")
1983
1984 ;; Classes
1985 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1986 "class statement requires a name")
1987
1988 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1989 "unexpected ',' between class properties")
1990
1991 (js2-msg "msg.unexpected.static" ; added by js2-mode
1992 "unexpected 'static'")
1993
1994 (js2-msg "msg.missing.extends" ; added by js2-mode
1995 "name is required after extends")
1996
1997 (js2-msg "msg.no.brace.class" ; added by js2-mode
1998 "missing '{' before class body")
1999
2000 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2001 "missing ']' after computed property expression")
2002
2003 ;;; Tokens Buffer
2004
2005 (defconst js2-ti-max-lookahead 2)
2006 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2007
2008 ;; Have to call `js2-init-scanner' to initialize the values.
2009 (js2-deflocal js2-ti-tokens nil)
2010 (js2-deflocal js2-ti-tokens-cursor nil)
2011 (js2-deflocal js2-ti-lookahead nil)
2012
2013 (defun js2-new-token (offset)
2014 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2015 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2016 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2017 token))
2018
2019 (defsubst js2-current-token ()
2020 (aref js2-ti-tokens js2-ti-tokens-cursor))
2021
2022 (defsubst js2-current-token-string ()
2023 (js2-token-string (js2-current-token)))
2024
2025 (defsubst js2-current-token-type ()
2026 (js2-token-type (js2-current-token)))
2027
2028 (defsubst js2-current-token-beg ()
2029 (js2-token-beg (js2-current-token)))
2030
2031 (defsubst js2-current-token-end ()
2032 (js2-token-end (js2-current-token)))
2033
2034 (defun js2-current-token-len ()
2035 (let ((token (js2-current-token)))
2036 (- (js2-token-end token)
2037 (js2-token-beg token))))
2038
2039 (defun js2-ts-seek (state)
2040 (setq js2-ts-lineno (js2-ts-state-lineno state)
2041 js2-ts-cursor (js2-ts-state-cursor state)
2042 js2-ti-tokens (js2-ts-state-tokens state)
2043 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2044 js2-ti-lookahead (js2-ts-state-lookahead state)))
2045
2046 ;;; Utilities
2047
2048 (defun js2-delete-if (predicate list)
2049 "Remove all items satisfying PREDICATE in LIST."
2050 (loop for item in list
2051 if (not (funcall predicate item))
2052 collect item))
2053
2054 (defun js2-position (element list)
2055 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2056 Returns nil if element is not found in the list."
2057 (let ((count 0)
2058 found)
2059 (while (and list (not found))
2060 (if (eq element (car list))
2061 (setq found t)
2062 (setq count (1+ count)
2063 list (cdr list))))
2064 (if found count)))
2065
2066 (defun js2-find-if (predicate list)
2067 "Find first item satisfying PREDICATE in LIST."
2068 (let (result)
2069 (while (and list (not result))
2070 (if (funcall predicate (car list))
2071 (setq result (car list)))
2072 (setq list (cdr list)))
2073 result))
2074
2075 (defmacro js2-time (form)
2076 "Evaluate FORM, discard result, and return elapsed time in sec."
2077 (declare (debug t))
2078 (let ((beg (make-symbol "--js2-time-beg--"))
2079 (delta (make-symbol "--js2-time-end--")))
2080 `(let ((,beg (current-time))
2081 ,delta)
2082 ,form
2083 (/ (truncate (* (- (float-time (current-time))
2084 (float-time ,beg))
2085 10000))
2086 10000.0))))
2087
2088 (defsubst js2-same-line (pos)
2089 "Return t if POS is on the same line as current point."
2090 (and (>= pos (point-at-bol))
2091 (<= pos (point-at-eol))))
2092
2093 (defun js2-code-bug ()
2094 "Signal an error when we encounter an unexpected code path."
2095 (error "failed assertion"))
2096
2097 (defsubst js2-record-text-property (beg end prop value)
2098 "Record a text property to set when parsing finishes."
2099 (push (list beg end prop value) js2-mode-deferred-properties))
2100
2101 ;; I'd like to associate errors with nodes, but for now the
2102 ;; easiest thing to do is get the context info from the last token.
2103 (defun js2-record-parse-error (msg &optional arg pos len)
2104 (push (list (list msg arg)
2105 (or pos (js2-current-token-beg))
2106 (or len (js2-current-token-len)))
2107 js2-parsed-errors))
2108
2109 (defun js2-report-error (msg &optional msg-arg pos len)
2110 "Signal a syntax error or record a parse error."
2111 (if js2-recover-from-parse-errors
2112 (js2-record-parse-error msg msg-arg pos len)
2113 (signal 'js2-syntax-error
2114 (list msg
2115 js2-ts-lineno
2116 (save-excursion
2117 (goto-char js2-ts-cursor)
2118 (current-column))
2119 js2-ts-hit-eof))))
2120
2121 (defun js2-report-warning (msg &optional msg-arg pos len face)
2122 (if js2-compiler-report-warning-as-error
2123 (js2-report-error msg msg-arg pos len)
2124 (push (list (list msg msg-arg)
2125 (or pos (js2-current-token-beg))
2126 (or len (js2-current-token-len))
2127 face)
2128 js2-parsed-warnings)))
2129
2130 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2131 (if js2-compiler-strict-mode
2132 (js2-report-warning msg-id msg-arg beg
2133 (and beg end (- end beg)))))
2134
2135 (put 'js2-syntax-error 'error-conditions
2136 '(error syntax-error js2-syntax-error))
2137 (put 'js2-syntax-error 'error-message "Syntax error")
2138
2139 (put 'js2-parse-error 'error-conditions
2140 '(error parse-error js2-parse-error))
2141 (put 'js2-parse-error 'error-message "Parse error")
2142
2143 (defmacro js2-clear-flag (flags flag)
2144 `(setq ,flags (logand ,flags (lognot ,flag))))
2145
2146 (defmacro js2-set-flag (flags flag)
2147 "Logical-or FLAG into FLAGS."
2148 `(setq ,flags (logior ,flags ,flag)))
2149
2150 (defsubst js2-flag-set-p (flags flag)
2151 (/= 0 (logand flags flag)))
2152
2153 (defsubst js2-flag-not-set-p (flags flag)
2154 (zerop (logand flags flag)))
2155
2156 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2157 "Evaluate BODY with the _ character set to be word-syntax."
2158 (declare (indent 0) (debug t))
2159 (let ((old-syntax (make-symbol "old-syntax")))
2160 `(let ((,old-syntax (string (char-syntax ?_))))
2161 (unwind-protect
2162 (progn
2163 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2164 ,@body)
2165 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2166
2167 ;;; AST struct and function definitions
2168
2169 ;; flags for ast node property 'member-type (used for e4x operators)
2170 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2171 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2172 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2173
2174 (defsubst js2-relpos (pos anchor)
2175 "Convert POS to be relative to ANCHOR.
2176 If POS is nil, returns nil."
2177 (and pos (- pos anchor)))
2178
2179 (defun js2-make-pad (indent)
2180 (if (zerop indent)
2181 ""
2182 (make-string (* indent js2-basic-offset) ? )))
2183
2184 (defun js2-visit-ast (node callback)
2185 "Visit every node in ast NODE with visitor CALLBACK.
2186
2187 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2188 called twice: once to visit the node, and again after all the node's
2189 children have been processed. The END-P argument is nil on the first
2190 call and non-nil on the second call. The return value of the callback
2191 affects the traversal: if non-nil, the children of NODE are processed.
2192 If the callback returns nil, or if the node has no children, then the
2193 callback is called immediately with a non-nil END-P argument.
2194
2195 The node traversal is approximately lexical-order, although there
2196 are currently no guarantees around this."
2197 (when node
2198 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2199 ;; visit the node
2200 (when (funcall callback node nil)
2201 ;; visit the kids
2202 (cond
2203 ((eq vfunc 'js2-visit-none)
2204 nil) ; don't even bother calling it
2205 ;; Each AST node type has to define a `js2-visitor' function
2206 ;; that takes a node and a callback, and calls `js2-visit-ast'
2207 ;; on each child of the node.
2208 (vfunc
2209 (funcall vfunc node callback))
2210 (t
2211 (error "%s does not define a visitor-traversal function"
2212 (aref node 0)))))
2213 ;; call the end-visit
2214 (funcall callback node t))))
2215
2216 (defstruct (js2-node
2217 (:constructor nil)) ; abstract
2218 "Base AST node type."
2219 (type -1) ; token type
2220 (pos -1) ; start position of this AST node in parsed input
2221 (len 1) ; num characters spanned by the node
2222 props ; optional node property list (an alist)
2223 parent) ; link to parent node; null for root
2224
2225 (defsubst js2-node-get-prop (node prop &optional default)
2226 (or (cadr (assoc prop (js2-node-props node))) default))
2227
2228 (defsubst js2-node-set-prop (node prop value)
2229 (setf (js2-node-props node)
2230 (cons (list prop value) (js2-node-props node))))
2231
2232 (defun js2-fixup-starts (n nodes)
2233 "Adjust the start positions of NODES to be relative to N.
2234 Any node in the list may be nil, for convenience."
2235 (dolist (node nodes)
2236 (when node
2237 (setf (js2-node-pos node) (- (js2-node-pos node)
2238 (js2-node-pos n))))))
2239
2240 (defun js2-node-add-children (parent &rest nodes)
2241 "Set parent node of NODES to PARENT, and return PARENT.
2242 Does nothing if we're not recording parent links.
2243 If any given node in NODES is nil, doesn't record that link."
2244 (js2-fixup-starts parent nodes)
2245 (dolist (node nodes)
2246 (and node
2247 (setf (js2-node-parent node) parent))))
2248
2249 ;; Non-recursive since it's called a frightening number of times.
2250 (defun js2-node-abs-pos (n)
2251 (let ((pos (js2-node-pos n)))
2252 (while (setq n (js2-node-parent n))
2253 (setq pos (+ pos (js2-node-pos n))))
2254 pos))
2255
2256 (defsubst js2-node-abs-end (n)
2257 "Return absolute buffer position of end of N."
2258 (+ (js2-node-abs-pos n) (js2-node-len n)))
2259
2260 ;; It's important to make sure block nodes have a Lisp list for the
2261 ;; child nodes, to limit printing recursion depth in an AST that
2262 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2263 ;; a sufficiently large vector tree.
2264
2265 (defstruct (js2-block-node
2266 (:include js2-node)
2267 (:constructor nil)
2268 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2269 (pos (js2-current-token-beg))
2270 len
2271 props
2272 kids)))
2273 "A block of statements."
2274 kids) ; a Lisp list of the child statement nodes
2275
2276 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2277 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2278
2279 (defun js2-visit-block (ast callback)
2280 "Visit the `js2-block-node' children of AST."
2281 (dolist (kid (js2-block-node-kids ast))
2282 (js2-visit-ast kid callback)))
2283
2284 (defun js2-print-block (n i)
2285 (let ((pad (js2-make-pad i)))
2286 (insert pad "{\n")
2287 (dolist (kid (js2-block-node-kids n))
2288 (js2-print-ast kid (1+ i)))
2289 (insert pad "}")))
2290
2291 (defstruct (js2-scope
2292 (:include js2-block-node)
2293 (:constructor nil)
2294 (:constructor make-js2-scope (&key (type js2-BLOCK)
2295 (pos (js2-current-token-beg))
2296 len
2297 kids)))
2298 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2299 ;; I don't have one of those handy, so I'll use an alist for now.
2300 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2301 ;; and is much lighter-weight to construct (both CPU and mem).
2302 ;; The keys are interned strings (symbols) for faster lookup.
2303 ;; Should switch to hybrid alist/hashtable eventually.
2304 symbol-table ; an alist of (symbol . js2-symbol)
2305 parent-scope ; a `js2-scope'
2306 top) ; top-level `js2-scope' (script/function)
2307
2308 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2309 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2310
2311 (defun js2-node-get-enclosing-scope (node)
2312 "Return the innermost `js2-scope' node surrounding NODE.
2313 Returns nil if there is no enclosing scope node."
2314 (let ((parent (js2-node-parent node)))
2315 (while (not (js2-scope-p parent))
2316 (setq parent (js2-node-parent parent)))
2317 parent))
2318
2319 (defun js2-get-defining-scope (scope name)
2320 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2321 Returns `js2-scope' in which NAME is defined, or nil if not found."
2322 (let ((sym (if (symbolp name)
2323 name
2324 (intern name)))
2325 table
2326 result
2327 (continue t))
2328 (while (and scope continue)
2329 (if (and (setq table (js2-scope-symbol-table scope))
2330 (assq sym table))
2331 (setq continue nil
2332 result scope)
2333 (setq scope (js2-scope-parent-scope scope))))
2334 result))
2335
2336 (defun js2-scope-get-symbol (scope name)
2337 "Return symbol table entry for NAME in SCOPE.
2338 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2339 (and (js2-scope-symbol-table scope)
2340 (cdr (assq (if (symbolp name)
2341 name
2342 (intern name))
2343 (js2-scope-symbol-table scope)))))
2344
2345 (defun js2-scope-put-symbol (scope name symbol)
2346 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2347 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2348 (let* ((table (js2-scope-symbol-table scope))
2349 (sym (if (symbolp name) name (intern name)))
2350 (entry (assq sym table)))
2351 (if entry
2352 (setcdr entry symbol)
2353 (push (cons sym symbol)
2354 (js2-scope-symbol-table scope)))))
2355
2356 (defstruct (js2-symbol
2357 (:constructor nil)
2358 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2359 "A symbol table entry."
2360 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2361 ;; js2-LET, or js2-CONST
2362 decl-type
2363 name ; string
2364 ast-node) ; a `js2-node'
2365
2366 (defstruct (js2-error-node
2367 (:include js2-node)
2368 (:constructor nil) ; silence emacs21 byte-compiler
2369 (:constructor make-js2-error-node (&key (type js2-ERROR)
2370 (pos (js2-current-token-beg))
2371 len)))
2372 "AST node representing a parse error.")
2373
2374 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2375 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2376
2377 (defstruct (js2-script-node
2378 (:include js2-scope)
2379 (:constructor nil)
2380 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2381 (pos (js2-current-token-beg))
2382 len
2383 ;; FIXME: What are those?
2384 var-decls
2385 fun-decls)))
2386 functions ; Lisp list of nested functions
2387 regexps ; Lisp list of (string . flags)
2388 symbols ; alist (every symbol gets unique index)
2389 (param-count 0)
2390 var-names ; vector of string names
2391 consts ; bool-vector matching var-decls
2392 (temp-number 0)) ; for generating temp variables
2393
2394 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2395 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2396
2397 (defun js2-print-script (node indent)
2398 (dolist (kid (js2-block-node-kids node))
2399 (js2-print-ast kid indent)))
2400
2401 (defstruct (js2-ast-root
2402 (:include js2-script-node)
2403 (:constructor nil)
2404 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2405 (pos (js2-current-token-beg))
2406 len
2407 buffer)))
2408 "The root node of a js2 AST."
2409 buffer ; the source buffer from which the code was parsed
2410 comments ; a Lisp list of comments, ordered by start position
2411 errors ; a Lisp list of errors found during parsing
2412 warnings ; a Lisp list of warnings found during parsing
2413 node-count) ; number of nodes in the tree, including the root
2414
2415 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2416 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2417
2418 (defun js2-visit-ast-root (ast callback)
2419 (dolist (kid (js2-ast-root-kids ast))
2420 (js2-visit-ast kid callback))
2421 (dolist (comment (js2-ast-root-comments ast))
2422 (js2-visit-ast comment callback)))
2423
2424 (defstruct (js2-comment-node
2425 (:include js2-node)
2426 (:constructor nil)
2427 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2428 (pos (js2-current-token-beg))
2429 len
2430 format)))
2431 format) ; 'line, 'block, 'jsdoc or 'html
2432
2433 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2434 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2435
2436 (defun js2-print-comment (n i)
2437 ;; We really ought to link end-of-line comments to their nodes.
2438 ;; Or maybe we could add a new comment type, 'endline.
2439 (insert (js2-make-pad i)
2440 (js2-node-string n)))
2441
2442 (defstruct (js2-expr-stmt-node
2443 (:include js2-node)
2444 (:constructor nil)
2445 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2446 (pos js2-ts-cursor)
2447 len
2448 expr)))
2449 "An expression statement."
2450 expr)
2451
2452 (defsubst js2-expr-stmt-node-set-has-result (node)
2453 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2454 (setf (js2-node-type node) js2-EXPR_RESULT))
2455
2456 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2457 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2458
2459 (defun js2-visit-expr-stmt-node (n v)
2460 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2461
2462 (defun js2-print-expr-stmt-node (n indent)
2463 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2464 (insert ";\n"))
2465
2466 (defstruct (js2-loop-node
2467 (:include js2-scope)
2468 (:constructor nil))
2469 "Abstract supertype of loop nodes."
2470 body ; a `js2-block-node'
2471 lp ; position of left-paren, nil if omitted
2472 rp) ; position of right-paren, nil if omitted
2473
2474 (defstruct (js2-do-node
2475 (:include js2-loop-node)
2476 (:constructor nil)
2477 (:constructor make-js2-do-node (&key (type js2-DO)
2478 (pos (js2-current-token-beg))
2479 len
2480 body
2481 condition
2482 while-pos
2483 lp
2484 rp)))
2485 "AST node for do-loop."
2486 condition ; while (expression)
2487 while-pos) ; buffer position of 'while' keyword
2488
2489 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2490 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2491
2492 (defun js2-visit-do-node (n v)
2493 (js2-visit-ast (js2-do-node-body n) v)
2494 (js2-visit-ast (js2-do-node-condition n) v))
2495
2496 (defun js2-print-do-node (n i)
2497 (let ((pad (js2-make-pad i)))
2498 (insert pad "do {\n")
2499 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2500 (js2-print-ast kid (1+ i)))
2501 (insert pad "} while (")
2502 (js2-print-ast (js2-do-node-condition n) 0)
2503 (insert ");\n")))
2504
2505 (defstruct (js2-export-node
2506 (:include js2-node)
2507 (:constructor nil)
2508 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2509 (pos) (js2-current-token-beg)
2510 len
2511 exports-list
2512 from-clause
2513 declaration
2514 default)))
2515 "AST node for an export statement. There are many things that can be exported,
2516 so many of its properties will be nil.
2517 "
2518 exports-list ; lisp list of js2-export-binding-node to export
2519 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2520 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2521 default) ; js2-function-node or js2-assign-node
2522
2523 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2524 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2525
2526 (defun js2-visit-export-node (n v)
2527 (let ((exports-list (js2-export-node-exports-list n))
2528 (from (js2-export-node-from-clause n))
2529 (declaration (js2-export-node-declaration n))
2530 (default (js2-export-node-default n)))
2531 (when exports-list
2532 (dolist (export exports-list)
2533 (js2-visit-ast export v)))
2534 (when from
2535 (js2-visit-ast from v))
2536 (when declaration
2537 (js2-visit-ast declaration v))
2538 (when default
2539 (js2-visit-ast default v))))
2540
2541 (defun js2-print-export-node (n i)
2542 (let ((pad (js2-make-pad i))
2543 (exports-list (js2-export-node-exports-list n))
2544 (from (js2-export-node-from-clause n))
2545 (declaration (js2-export-node-declaration n))
2546 (default (js2-export-node-default n)))
2547 (insert pad "export ")
2548 (cond
2549 (default
2550 (insert "default ")
2551 (js2-print-ast default i))
2552 (declaration
2553 (js2-print-ast declaration i))
2554 ((and exports-list from)
2555 (js2-print-named-imports exports-list)
2556 (insert " ")
2557 (js2-print-from-clause from))
2558 (from
2559 (insert "* ")
2560 (js2-print-from-clause from))
2561 (exports-list
2562 (js2-print-named-imports exports-list)))
2563 (insert ";\n")))
2564
2565 (defstruct (js2-while-node
2566 (:include js2-loop-node)
2567 (:constructor nil)
2568 (:constructor make-js2-while-node (&key (type js2-WHILE)
2569 (pos (js2-current-token-beg))
2570 len body
2571 condition lp
2572 rp)))
2573 "AST node for while-loop."
2574 condition) ; while-condition
2575
2576 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2577 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2578
2579 (defun js2-visit-while-node (n v)
2580 (js2-visit-ast (js2-while-node-condition n) v)
2581 (js2-visit-ast (js2-while-node-body n) v))
2582
2583 (defun js2-print-while-node (n i)
2584 (let ((pad (js2-make-pad i)))
2585 (insert pad "while (")
2586 (js2-print-ast (js2-while-node-condition n) 0)
2587 (insert ") {\n")
2588 (js2-print-body (js2-while-node-body n) (1+ i))
2589 (insert pad "}\n")))
2590
2591 (defstruct (js2-for-node
2592 (:include js2-loop-node)
2593 (:constructor nil)
2594 (:constructor make-js2-for-node (&key (type js2-FOR)
2595 (pos js2-ts-cursor)
2596 len body init
2597 condition
2598 update lp rp)))
2599 "AST node for a C-style for-loop."
2600 init ; initialization expression
2601 condition ; loop condition
2602 update) ; update clause
2603
2604 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2605 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2606
2607 (defun js2-visit-for-node (n v)
2608 (js2-visit-ast (js2-for-node-init n) v)
2609 (js2-visit-ast (js2-for-node-condition n) v)
2610 (js2-visit-ast (js2-for-node-update n) v)
2611 (js2-visit-ast (js2-for-node-body n) v))
2612
2613 (defun js2-print-for-node (n i)
2614 (let ((pad (js2-make-pad i)))
2615 (insert pad "for (")
2616 (js2-print-ast (js2-for-node-init n) 0)
2617 (insert "; ")
2618 (js2-print-ast (js2-for-node-condition n) 0)
2619 (insert "; ")
2620 (js2-print-ast (js2-for-node-update n) 0)
2621 (insert ") {\n")
2622 (js2-print-body (js2-for-node-body n) (1+ i))
2623 (insert pad "}\n")))
2624
2625 (defstruct (js2-for-in-node
2626 (:include js2-loop-node)
2627 (:constructor nil)
2628 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2629 (pos js2-ts-cursor)
2630 len body
2631 iterator
2632 object
2633 in-pos
2634 each-pos
2635 foreach-p forof-p
2636 lp rp)))
2637 "AST node for a for..in loop."
2638 iterator ; [var] foo in ...
2639 object ; object over which we're iterating
2640 in-pos ; buffer position of 'in' keyword
2641 each-pos ; buffer position of 'each' keyword, if foreach-p
2642 foreach-p ; t if it's a for-each loop
2643 forof-p) ; t if it's a for-of loop
2644
2645 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2646 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2647
2648 (defun js2-visit-for-in-node (n v)
2649 (js2-visit-ast (js2-for-in-node-iterator n) v)
2650 (js2-visit-ast (js2-for-in-node-object n) v)
2651 (js2-visit-ast (js2-for-in-node-body n) v))
2652
2653 (defun js2-print-for-in-node (n i)
2654 (let ((pad (js2-make-pad i))
2655 (foreach (js2-for-in-node-foreach-p n))
2656 (forof (js2-for-in-node-forof-p n)))
2657 (insert pad "for ")
2658 (if foreach
2659 (insert "each "))
2660 (insert "(")
2661 (js2-print-ast (js2-for-in-node-iterator n) 0)
2662 (insert (if forof " of " " in "))
2663 (js2-print-ast (js2-for-in-node-object n) 0)
2664 (insert ") {\n")
2665 (js2-print-body (js2-for-in-node-body n) (1+ i))
2666 (insert pad "}\n")))
2667
2668 (defstruct (js2-return-node
2669 (:include js2-node)
2670 (:constructor nil)
2671 (:constructor make-js2-return-node (&key (type js2-RETURN)
2672 (pos js2-ts-cursor)
2673 len
2674 retval)))
2675 "AST node for a return statement."
2676 retval) ; expression to return, or 'undefined
2677
2678 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2679 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2680
2681 (defun js2-visit-return-node (n v)
2682 (js2-visit-ast (js2-return-node-retval n) v))
2683
2684 (defun js2-print-return-node (n i)
2685 (insert (js2-make-pad i) "return")
2686 (when (js2-return-node-retval n)
2687 (insert " ")
2688 (js2-print-ast (js2-return-node-retval n) 0))
2689 (insert ";\n"))
2690
2691 (defstruct (js2-if-node
2692 (:include js2-node)
2693 (:constructor nil)
2694 (:constructor make-js2-if-node (&key (type js2-IF)
2695 (pos js2-ts-cursor)
2696 len condition
2697 then-part
2698 else-pos
2699 else-part lp
2700 rp)))
2701 "AST node for an if-statement."
2702 condition ; expression
2703 then-part ; statement or block
2704 else-pos ; optional buffer position of 'else' keyword
2705 else-part ; optional statement or block
2706 lp ; position of left-paren, nil if omitted
2707 rp) ; position of right-paren, nil if omitted
2708
2709 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2710 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2711
2712 (defun js2-visit-if-node (n v)
2713 (js2-visit-ast (js2-if-node-condition n) v)
2714 (js2-visit-ast (js2-if-node-then-part n) v)
2715 (js2-visit-ast (js2-if-node-else-part n) v))
2716
2717 (defun js2-print-if-node (n i)
2718 (let ((pad (js2-make-pad i))
2719 (then-part (js2-if-node-then-part n))
2720 (else-part (js2-if-node-else-part n)))
2721 (insert pad "if (")
2722 (js2-print-ast (js2-if-node-condition n) 0)
2723 (insert ") {\n")
2724 (js2-print-body then-part (1+ i))
2725 (insert pad "}")
2726 (cond
2727 ((not else-part)
2728 (insert "\n"))
2729 ((js2-if-node-p else-part)
2730 (insert " else ")
2731 (js2-print-body else-part i))
2732 (t
2733 (insert " else {\n")
2734 (js2-print-body else-part (1+ i))
2735 (insert pad "}\n")))))
2736
2737 (defstruct (js2-export-binding-node
2738 (:include js2-node)
2739 (:constructor nil)
2740 (:constructor make-js2-export-binding-node (&key (type -1)
2741 pos
2742 len
2743 local-name
2744 extern-name)))
2745 "AST node for an external symbol binding.
2746 It contains a local-name node which is the name of the value in the
2747 current scope, and extern-name which is the name of the value in the
2748 imported or exported scope. By default these are the same, but if the
2749 name is aliased as in {foo as bar}, it would have an extern-name node
2750 containing 'foo' and a local-name node containing 'bar'."
2751 local-name ; js2-name-node with the variable name in this scope
2752 extern-name) ; js2-name-node with the value name in the exporting module
2753
2754 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2755 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2756
2757 (defun js2-visit-extern-binding (n v)
2758 "Visit an extern binding node. First visit the local-name, and, if
2759 different, visit the extern-name."
2760 (let ((local-name (js2-export-binding-node-local-name n))
2761 (extern-name (js2-export-binding-node-extern-name n)))
2762 (when local-name
2763 (js2-visit-ast local-name v))
2764 (when (not (equal local-name extern-name))
2765 (js2-visit-ast extern-name v))))
2766
2767 (defun js2-print-extern-binding (n i)
2768 "Print a representation of a single extern binding. E.g. 'foo' or
2769 'foo as bar'."
2770 (let ((local-name (js2-export-binding-node-local-name n))
2771 (extern-name (js2-export-binding-node-extern-name n)))
2772 (insert (js2-name-node-name extern-name))
2773 (when (not (equal local-name extern-name))
2774 (insert " as ")
2775 (insert (js2-name-node-name local-name)))))
2776
2777
2778 (defstruct (js2-import-node
2779 (:include js2-node)
2780 (:constructor nil)
2781 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2782 (pos (js2-current-token-beg))
2783 len
2784 import
2785 from
2786 module-id)))
2787 "AST node for an import statement. It follows the form
2788
2789 import ModuleSpecifier;
2790 import ImportClause FromClause;"
2791 import ; js2-import-clause-node specifying which names are to imported.
2792 from ; js2-from-clause-node indicating the module from which to import.
2793 module-id) ; module-id of the import. E.g. 'src/mylib'.
2794
2795 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2796 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2797
2798 (defun js2-visit-import (n v)
2799 (let ((import-clause (js2-import-node-import n))
2800 (from-clause (js2-import-node-from n)))
2801 (when import-clause
2802 (js2-visit-ast import-clause v))
2803 (when from-clause
2804 (js2-visit-ast from-clause v))))
2805
2806 (defun js2-print-import (n i)
2807 "Prints a representation of the import node"
2808 (let ((pad (js2-make-pad i))
2809 (import-clause (js2-import-node-import n))
2810 (from-clause (js2-import-node-from n))
2811 (module-id (js2-import-node-module-id n)))
2812 (insert pad "import ")
2813 (if import-clause
2814 (progn
2815 (js2-print-import-clause import-clause)
2816 (insert " ")
2817 (js2-print-from-clause from-clause))
2818 (insert "'")
2819 (insert module-id)
2820 (insert "'"))
2821 (insert ";\n")))
2822
2823 (defstruct (js2-import-clause-node
2824 (:include js2-node)
2825 (:constructor nil)
2826 (:constructor make-js2-import-clause-node (&key (type -1)
2827 pos
2828 len
2829 namespace-import
2830 named-imports
2831 default-binding)))
2832 "AST node corresponding to the import clause of an import statement. This is
2833 the portion of the import that bindings names from the external context to the
2834 local context."
2835 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2836 named-imports ; lisp list of js2-export-binding-node for all named imports.
2837 default-binding) ; js2-export-binding-node for the default import binding
2838
2839 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2840 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2841
2842 (defun js2-visit-import-clause (n v)
2843 (let ((ns-import (js2-import-clause-node-namespace-import n))
2844 (named-imports (js2-import-clause-node-named-imports n))
2845 (default (js2-import-clause-node-default-binding n)))
2846 (when ns-import
2847 (js2-visit-ast ns-import v))
2848 (when named-imports
2849 (dolist (import named-imports)
2850 (js2-visit-ast import v)))
2851 (when default
2852 (js2-visit-ast default v))))
2853
2854 (defun js2-print-import-clause (n)
2855 (let ((ns-import (js2-import-clause-node-namespace-import n))
2856 (named-imports (js2-import-clause-node-named-imports n))
2857 (default (js2-import-clause-node-default-binding n)))
2858 (cond
2859 ((and default ns-import)
2860 (js2-print-ast default)
2861 (insert ", ")
2862 (js2-print-namespace-import ns-import))
2863 ((and default named-imports)
2864 (js2-print-ast default)
2865 (insert ", ")
2866 (js2-print-named-imports named-imports))
2867 (default
2868 (js2-print-ast default))
2869 (ns-import
2870 (js2-print-namespace-import ns-import))
2871 (named-imports
2872 (js2-print-named-imports named-imports)))))
2873
2874 (defun js2-print-namespace-import (node)
2875 (insert "* as ")
2876 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2877
2878 (defun js2-print-named-imports (imports)
2879 (insert "{")
2880 (let ((len (length imports))
2881 (n 0))
2882 (while (< n len)
2883 (js2-print-extern-binding (nth n imports) 0)
2884 (unless (= n (- len 1))
2885 (insert ", "))
2886 (setq n (+ n 1))))
2887 (insert "}"))
2888
2889 (defstruct (js2-namespace-import-node
2890 (:include js2-node)
2891 (:constructor nil)
2892 (:constructor make-js2-namespace-import-node (&key (type -1)
2893 pos
2894 len
2895 name)))
2896 "AST node for a complete namespace import.
2897 E.g. the '* as lib' expression in:
2898
2899 import * as lib from 'src/lib'
2900
2901 It contains a single name node referring to the bound name."
2902 name) ; js2-name-node of the bound name.
2903
2904 (defun js2-visit-namespace-import (n v)
2905 (js2-visit-ast (js2-namespace-import-node-name n) v))
2906
2907 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2908 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2909
2910 (defstruct (js2-from-clause-node
2911 (:include js2-node)
2912 (:constructor nil)
2913 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2914 pos
2915 len
2916 module-id
2917 metadata-p)))
2918 "AST node for the from clause in an import or export statement.
2919 E.g. from 'my/module'. It can refere to either an external module, or to the
2920 modules metadata itself."
2921 module-id ; string containing the module specifier.
2922 metadata-p) ; true if this clause refers to the module's metadata
2923
2924 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2925 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2926
2927 (defun js2-print-from-clause (n)
2928 (insert "from ")
2929 (if (js2-from-clause-node-metadata-p n)
2930 (insert "this module")
2931 (insert "'")
2932 (insert (js2-from-clause-node-module-id n))
2933 (insert "'")))
2934
2935 (defstruct (js2-try-node
2936 (:include js2-node)
2937 (:constructor nil)
2938 (:constructor make-js2-try-node (&key (type js2-TRY)
2939 (pos js2-ts-cursor)
2940 len
2941 try-block
2942 catch-clauses
2943 finally-block)))
2944 "AST node for a try-statement."
2945 try-block
2946 catch-clauses ; a Lisp list of `js2-catch-node'
2947 finally-block) ; a `js2-finally-node'
2948
2949 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2950 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2951
2952 (defun js2-visit-try-node (n v)
2953 (js2-visit-ast (js2-try-node-try-block n) v)
2954 (dolist (clause (js2-try-node-catch-clauses n))
2955 (js2-visit-ast clause v))
2956 (js2-visit-ast (js2-try-node-finally-block n) v))
2957
2958 (defun js2-print-try-node (n i)
2959 (let ((pad (js2-make-pad i))
2960 (catches (js2-try-node-catch-clauses n))
2961 (finally (js2-try-node-finally-block n)))
2962 (insert pad "try {\n")
2963 (js2-print-body (js2-try-node-try-block n) (1+ i))
2964 (insert pad "}")
2965 (when catches
2966 (dolist (catch catches)
2967 (js2-print-ast catch i)))
2968 (if finally
2969 (js2-print-ast finally i)
2970 (insert "\n"))))
2971
2972 (defstruct (js2-catch-node
2973 (:include js2-scope)
2974 (:constructor nil)
2975 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2976 (pos js2-ts-cursor)
2977 len
2978 param
2979 guard-kwd
2980 guard-expr
2981 lp rp)))
2982 "AST node for a catch clause."
2983 param ; destructuring form or simple name node
2984 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2985 guard-expr ; catch condition, a `js2-node'
2986 lp ; buffer position of left-paren, nil if omitted
2987 rp) ; buffer position of right-paren, nil if omitted
2988
2989 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2990 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2991
2992 (defun js2-visit-catch-node (n v)
2993 (js2-visit-ast (js2-catch-node-param n) v)
2994 (when (js2-catch-node-guard-kwd n)
2995 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2996 (js2-visit-block n v))
2997
2998 (defun js2-print-catch-node (n i)
2999 (let ((pad (js2-make-pad i))
3000 (guard-kwd (js2-catch-node-guard-kwd n))
3001 (guard-expr (js2-catch-node-guard-expr n)))
3002 (insert " catch (")
3003 (js2-print-ast (js2-catch-node-param n) 0)
3004 (when guard-kwd
3005 (insert " if ")
3006 (js2-print-ast guard-expr 0))
3007 (insert ") {\n")
3008 (js2-print-body n (1+ i))
3009 (insert pad "}")))
3010
3011 (defstruct (js2-finally-node
3012 (:include js2-node)
3013 (:constructor nil)
3014 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3015 (pos js2-ts-cursor)
3016 len body)))
3017 "AST node for a finally clause."
3018 body) ; a `js2-node', often but not always a block node
3019
3020 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3021 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3022
3023 (defun js2-visit-finally-node (n v)
3024 (js2-visit-ast (js2-finally-node-body n) v))
3025
3026 (defun js2-print-finally-node (n i)
3027 (let ((pad (js2-make-pad i)))
3028 (insert " finally {\n")
3029 (js2-print-body (js2-finally-node-body n) (1+ i))
3030 (insert pad "}\n")))
3031
3032 (defstruct (js2-switch-node
3033 (:include js2-node)
3034 (:constructor nil)
3035 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3036 (pos js2-ts-cursor)
3037 len
3038 discriminant
3039 cases lp
3040 rp)))
3041 "AST node for a switch statement."
3042 discriminant ; a `js2-node' (switch expression)
3043 cases ; a Lisp list of `js2-case-node'
3044 lp ; position of open-paren for discriminant, nil if omitted
3045 rp) ; position of close-paren for discriminant, nil if omitted
3046
3047 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3048 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3049
3050 (defun js2-visit-switch-node (n v)
3051 (js2-visit-ast (js2-switch-node-discriminant n) v)
3052 (dolist (c (js2-switch-node-cases n))
3053 (js2-visit-ast c v)))
3054
3055 (defun js2-print-switch-node (n i)
3056 (let ((pad (js2-make-pad i))
3057 (cases (js2-switch-node-cases n)))
3058 (insert pad "switch (")
3059 (js2-print-ast (js2-switch-node-discriminant n) 0)
3060 (insert ") {\n")
3061 (dolist (case cases)
3062 (js2-print-ast case i))
3063 (insert pad "}\n")))
3064
3065 (defstruct (js2-case-node
3066 (:include js2-block-node)
3067 (:constructor nil)
3068 (:constructor make-js2-case-node (&key (type js2-CASE)
3069 (pos js2-ts-cursor)
3070 len kids expr)))
3071 "AST node for a case clause of a switch statement."
3072 expr) ; the case expression (nil for default)
3073
3074 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3075 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3076
3077 (defun js2-visit-case-node (n v)
3078 (js2-visit-ast (js2-case-node-expr n) v)
3079 (js2-visit-block n v))
3080
3081 (defun js2-print-case-node (n i)
3082 (let ((pad (js2-make-pad i))
3083 (expr (js2-case-node-expr n)))
3084 (insert pad)
3085 (if (null expr)
3086 (insert "default:\n")
3087 (insert "case ")
3088 (js2-print-ast expr 0)
3089 (insert ":\n"))
3090 (dolist (kid (js2-case-node-kids n))
3091 (js2-print-ast kid (1+ i)))))
3092
3093 (defstruct (js2-throw-node
3094 (:include js2-node)
3095 (:constructor nil)
3096 (:constructor make-js2-throw-node (&key (type js2-THROW)
3097 (pos js2-ts-cursor)
3098 len expr)))
3099 "AST node for a throw statement."
3100 expr) ; the expression to throw
3101
3102 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3103 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3104
3105 (defun js2-visit-throw-node (n v)
3106 (js2-visit-ast (js2-throw-node-expr n) v))
3107
3108 (defun js2-print-throw-node (n i)
3109 (insert (js2-make-pad i) "throw ")
3110 (js2-print-ast (js2-throw-node-expr n) 0)
3111 (insert ";\n"))
3112
3113 (defstruct (js2-with-node
3114 (:include js2-node)
3115 (:constructor nil)
3116 (:constructor make-js2-with-node (&key (type js2-WITH)
3117 (pos js2-ts-cursor)
3118 len object
3119 body lp rp)))
3120 "AST node for a with-statement."
3121 object
3122 body
3123 lp ; buffer position of left-paren around object, nil if omitted
3124 rp) ; buffer position of right-paren around object, nil if omitted
3125
3126 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3127 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3128
3129 (defun js2-visit-with-node (n v)
3130 (js2-visit-ast (js2-with-node-object n) v)
3131 (js2-visit-ast (js2-with-node-body n) v))
3132
3133 (defun js2-print-with-node (n i)
3134 (let ((pad (js2-make-pad i)))
3135 (insert pad "with (")
3136 (js2-print-ast (js2-with-node-object n) 0)
3137 (insert ") {\n")
3138 (js2-print-body (js2-with-node-body n) (1+ i))
3139 (insert pad "}\n")))
3140
3141 (defstruct (js2-label-node
3142 (:include js2-node)
3143 (:constructor nil)
3144 (:constructor make-js2-label-node (&key (type js2-LABEL)
3145 (pos js2-ts-cursor)
3146 len name)))
3147 "AST node for a statement label or case label."
3148 name ; a string
3149 loop) ; for validating and code-generating continue-to-label
3150
3151 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3152 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3153
3154 (defun js2-print-label (n i)
3155 (insert (js2-make-pad i)
3156 (js2-label-node-name n)
3157 ":\n"))
3158
3159 (defstruct (js2-labeled-stmt-node
3160 (:include js2-node)
3161 (:constructor nil)
3162 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3163 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3164 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3165 (pos js2-ts-cursor)
3166 len labels stmt)))
3167 "AST node for a statement with one or more labels.
3168 Multiple labels for a statement are collapsed into the labels field."
3169 labels ; Lisp list of `js2-label-node'
3170 stmt) ; the statement these labels are for
3171
3172 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3173 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3174
3175 (defun js2-get-label-by-name (lbl-stmt name)
3176 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3177 Returns nil if no such label is in the list."
3178 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3179 result)
3180 (while (and label-list (not result))
3181 (if (string= (js2-label-node-name (car label-list)) name)
3182 (setq result (car label-list))
3183 (setq label-list (cdr label-list))))
3184 result))
3185
3186 (defun js2-visit-labeled-stmt (n v)
3187 (dolist (label (js2-labeled-stmt-node-labels n))
3188 (js2-visit-ast label v))
3189 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3190
3191 (defun js2-print-labeled-stmt (n i)
3192 (dolist (label (js2-labeled-stmt-node-labels n))
3193 (js2-print-ast label i))
3194 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3195
3196 (defun js2-labeled-stmt-node-contains (node label)
3197 "Return t if NODE contains LABEL in its label set.
3198 NODE is a `js2-labels-node'. LABEL is an identifier."
3199 (loop for nl in (js2-labeled-stmt-node-labels node)
3200 if (string= label (js2-label-node-name nl))
3201 return t
3202 finally return nil))
3203
3204 (defsubst js2-labeled-stmt-node-add-label (node label)
3205 "Add a `js2-label-node' to the label set for this statement."
3206 (setf (js2-labeled-stmt-node-labels node)
3207 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3208
3209 (defstruct (js2-jump-node
3210 (:include js2-node)
3211 (:constructor nil))
3212 "Abstract supertype of break and continue nodes."
3213 label ; `js2-name-node' for location of label identifier, if present
3214 target) ; target js2-labels-node or loop/switch statement
3215
3216 (defun js2-visit-jump-node (n v)
3217 ;; We don't visit the target, since it's a back-link.
3218 (js2-visit-ast (js2-jump-node-label n) v))
3219
3220 (defstruct (js2-break-node
3221 (:include js2-jump-node)
3222 (:constructor nil)
3223 (:constructor make-js2-break-node (&key (type js2-BREAK)
3224 (pos js2-ts-cursor)
3225 len label target)))
3226 "AST node for a break statement.
3227 The label field is a `js2-name-node', possibly nil, for the named label
3228 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3229 is the target of the break - a label node or enclosing loop/switch statement.")
3230
3231 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3232 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3233
3234 (defun js2-print-break-node (n i)
3235 (insert (js2-make-pad i) "break")
3236 (when (js2-break-node-label n)
3237 (insert " ")
3238 (js2-print-ast (js2-break-node-label n) 0))
3239 (insert ";\n"))
3240
3241 (defstruct (js2-continue-node
3242 (:include js2-jump-node)
3243 (:constructor nil)
3244 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3245 (pos js2-ts-cursor)
3246 len label target)))
3247 "AST node for a continue statement.
3248 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3249 It is nil if continue specifies no label. The target field is the jump target:
3250 a `js2-label-node' or the innermost enclosing loop.")
3251
3252 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3253 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3254
3255 (defun js2-print-continue-node (n i)
3256 (insert (js2-make-pad i) "continue")
3257 (when (js2-continue-node-label n)
3258 (insert " ")
3259 (js2-print-ast (js2-continue-node-label n) 0))
3260 (insert ";\n"))
3261
3262 (defstruct (js2-function-node
3263 (:include js2-script-node)
3264 (:constructor nil)
3265 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3266 (pos js2-ts-cursor)
3267 len
3268 (ftype 'FUNCTION)
3269 (form 'FUNCTION_STATEMENT)
3270 (name "")
3271 params rest-p
3272 body
3273 generator-type
3274 lp rp)))
3275 "AST node for a function declaration.
3276 The `params' field is a Lisp list of nodes. Each node is either a simple
3277 `js2-name-node', or if it's a destructuring-assignment parameter, a
3278 `js2-array-node' or `js2-object-node'."
3279 ftype ; FUNCTION, GETTER or SETTER
3280 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3281 name ; function name (a `js2-name-node', or nil if anonymous)
3282 params ; a Lisp list of destructuring forms or simple name nodes
3283 rest-p ; if t, the last parameter is rest parameter
3284 body ; a `js2-block-node' or expression node (1.8 only)
3285 lp ; position of arg-list open-paren, or nil if omitted
3286 rp ; position of arg-list close-paren, or nil if omitted
3287 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3288 needs-activation ; t if we need an activation object for this frame
3289 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3290 member-expr) ; nonstandard Ecma extension from Rhino
3291
3292 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3293 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3294
3295 (defun js2-visit-function-node (n v)
3296 (js2-visit-ast (js2-function-node-name n) v)
3297 (dolist (p (js2-function-node-params n))
3298 (js2-visit-ast p v))
3299 (js2-visit-ast (js2-function-node-body n) v))
3300
3301 (defun js2-print-function-node (n i)
3302 (let* ((pad (js2-make-pad i))
3303 (getter (js2-node-get-prop n 'GETTER_SETTER))
3304 (name (or (js2-function-node-name n)
3305 (js2-function-node-member-expr n)))
3306 (params (js2-function-node-params n))
3307 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3308 (rest-p (js2-function-node-rest-p n))
3309 (body (js2-function-node-body n))
3310 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3311 (unless (or getter arrow)
3312 (insert pad "function")
3313 (when (eq (js2-function-node-generator-type n) 'STAR)
3314 (insert "*")))
3315 (when name
3316 (insert " ")
3317 (js2-print-ast name 0))
3318 (insert "(")
3319 (loop with len = (length params)
3320 for param in params
3321 for count from 1
3322 do
3323 (when (and rest-p (= count len))
3324 (insert "..."))
3325 (js2-print-ast param 0)
3326 (when (< count len)
3327 (insert ", ")))
3328 (insert ") ")
3329 (when arrow
3330 (insert "=> "))
3331 (insert "{")
3332 ;; TODO: fix this to be smarter about indenting, etc.
3333 (unless expr
3334 (insert "\n"))
3335 (if (js2-block-node-p body)
3336 (js2-print-body body (1+ i))
3337 (js2-print-ast body 0))
3338 (insert pad "}")
3339 (unless expr
3340 (insert "\n"))))
3341
3342 (defun js2-function-name (node)
3343 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3344 (and (js2-function-node-name node)
3345 (js2-name-node-name (js2-function-node-name node))))
3346
3347 ;; Having this be an expression node makes it more flexible.
3348 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3349 ;; that work better if you assume it's an expression. Whenever we have
3350 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3351 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3352 (defstruct (js2-var-decl-node
3353 (:include js2-node)
3354 (:constructor nil)
3355 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3356 (pos (js2-current-token-beg))
3357 len kids
3358 decl-type)))
3359 "AST node for a variable declaration list (VAR, CONST or LET).
3360 The node bounds differ depending on the declaration type. For VAR or
3361 CONST declarations, the bounds include the var/const keyword. For LET
3362 declarations, the node begins at the position of the first child."
3363 kids ; a Lisp list of `js2-var-init-node' structs.
3364 decl-type) ; js2-VAR, js2-CONST or js2-LET
3365
3366 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3367 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3368
3369 (defun js2-visit-var-decl (n v)
3370 (dolist (kid (js2-var-decl-node-kids n))
3371 (js2-visit-ast kid v)))
3372
3373 (defun js2-print-var-decl (n i)
3374 (let ((pad (js2-make-pad i))
3375 (tt (js2-var-decl-node-decl-type n)))
3376 (insert pad)
3377 (insert (cond
3378 ((= tt js2-VAR) "var ")
3379 ((= tt js2-LET) "let ")
3380 ((= tt js2-CONST) "const ")
3381 (t
3382 (error "malformed var-decl node"))))
3383 (loop with kids = (js2-var-decl-node-kids n)
3384 with len = (length kids)
3385 for kid in kids
3386 for count from 1
3387 do
3388 (js2-print-ast kid 0)
3389 (if (< count len)
3390 (insert ", ")))))
3391
3392 (defstruct (js2-var-init-node
3393 (:include js2-node)
3394 (:constructor nil)
3395 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3396 (pos js2-ts-cursor)
3397 len target
3398 initializer)))
3399 "AST node for a variable declaration.
3400 The type field will be js2-CONST for a const decl."
3401 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3402 initializer) ; initializer expression, a `js2-node'
3403
3404 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3405 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3406
3407 (defun js2-visit-var-init-node (n v)
3408 (js2-visit-ast (js2-var-init-node-target n) v)
3409 (js2-visit-ast (js2-var-init-node-initializer n) v))
3410
3411 (defun js2-print-var-init-node (n i)
3412 (let ((pad (js2-make-pad i))
3413 (name (js2-var-init-node-target n))
3414 (init (js2-var-init-node-initializer n)))
3415 (insert pad)
3416 (js2-print-ast name 0)
3417 (when init
3418 (insert " = ")
3419 (js2-print-ast init 0))))
3420
3421 (defstruct (js2-cond-node
3422 (:include js2-node)
3423 (:constructor nil)
3424 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3425 (pos js2-ts-cursor)
3426 len
3427 test-expr
3428 true-expr
3429 false-expr
3430 q-pos c-pos)))
3431 "AST node for the ternary operator"
3432 test-expr
3433 true-expr
3434 false-expr
3435 q-pos ; buffer position of ?
3436 c-pos) ; buffer position of :
3437
3438 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3439 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3440
3441 (defun js2-visit-cond-node (n v)
3442 (js2-visit-ast (js2-cond-node-test-expr n) v)
3443 (js2-visit-ast (js2-cond-node-true-expr n) v)
3444 (js2-visit-ast (js2-cond-node-false-expr n) v))
3445
3446 (defun js2-print-cond-node (n i)
3447 (let ((pad (js2-make-pad i)))
3448 (insert pad)
3449 (js2-print-ast (js2-cond-node-test-expr n) 0)
3450 (insert " ? ")
3451 (js2-print-ast (js2-cond-node-true-expr n) 0)
3452 (insert " : ")
3453 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3454
3455 (defstruct (js2-infix-node
3456 (:include js2-node)
3457 (:constructor nil)
3458 (:constructor make-js2-infix-node (&key type
3459 (pos js2-ts-cursor)
3460 len op-pos
3461 left right)))
3462 "Represents infix expressions.
3463 Includes assignment ops like `|=', and the comma operator.
3464 The type field inherited from `js2-node' holds the operator."
3465 op-pos ; buffer position where operator begins
3466 left ; any `js2-node'
3467 right) ; any `js2-node'
3468
3469 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3470 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3471
3472 (defun js2-visit-infix-node (n v)
3473 (js2-visit-ast (js2-infix-node-left n) v)
3474 (js2-visit-ast (js2-infix-node-right n) v))
3475
3476 (defconst js2-operator-tokens
3477 (let ((table (make-hash-table :test 'eq))
3478 (tokens
3479 (list (cons js2-IN "in")
3480 (cons js2-TYPEOF "typeof")
3481 (cons js2-INSTANCEOF "instanceof")
3482 (cons js2-DELPROP "delete")
3483 (cons js2-COMMA ",")
3484 (cons js2-COLON ":")
3485 (cons js2-OR "||")
3486 (cons js2-AND "&&")
3487 (cons js2-INC "++")
3488 (cons js2-DEC "--")
3489 (cons js2-BITOR "|")
3490 (cons js2-BITXOR "^")
3491 (cons js2-BITAND "&")
3492 (cons js2-EQ "==")
3493 (cons js2-NE "!=")
3494 (cons js2-LT "<")
3495 (cons js2-LE "<=")
3496 (cons js2-GT ">")
3497 (cons js2-GE ">=")
3498 (cons js2-LSH "<<")
3499 (cons js2-RSH ">>")
3500 (cons js2-URSH ">>>")
3501 (cons js2-ADD "+") ; infix plus
3502 (cons js2-SUB "-") ; infix minus
3503 (cons js2-MUL "*")
3504 (cons js2-DIV "/")
3505 (cons js2-MOD "%")
3506 (cons js2-NOT "!")
3507 (cons js2-BITNOT "~")
3508 (cons js2-POS "+") ; unary plus
3509 (cons js2-NEG "-") ; unary minus
3510 (cons js2-TRIPLEDOT "...")
3511 (cons js2-SHEQ "===") ; shallow equality
3512 (cons js2-SHNE "!==") ; shallow inequality
3513 (cons js2-ASSIGN "=")
3514 (cons js2-ASSIGN_BITOR "|=")
3515 (cons js2-ASSIGN_BITXOR "^=")
3516 (cons js2-ASSIGN_BITAND "&=")
3517 (cons js2-ASSIGN_LSH "<<=")
3518 (cons js2-ASSIGN_RSH ">>=")
3519 (cons js2-ASSIGN_URSH ">>>=")
3520 (cons js2-ASSIGN_ADD "+=")
3521 (cons js2-ASSIGN_SUB "-=")
3522 (cons js2-ASSIGN_MUL "*=")
3523 (cons js2-ASSIGN_DIV "/=")
3524 (cons js2-ASSIGN_MOD "%="))))
3525 (loop for (k . v) in tokens do
3526 (puthash k v table))
3527 table))
3528
3529 (defun js2-print-infix-node (n i)
3530 (let* ((tt (js2-node-type n))
3531 (op (gethash tt js2-operator-tokens)))
3532 (unless op
3533 (error "unrecognized infix operator %s" (js2-node-type n)))
3534 (insert (js2-make-pad i))
3535 (js2-print-ast (js2-infix-node-left n) 0)
3536 (unless (= tt js2-COMMA)
3537 (insert " "))
3538 (insert op)
3539 (insert " ")
3540 (js2-print-ast (js2-infix-node-right n) 0)))
3541
3542 (defstruct (js2-assign-node
3543 (:include js2-infix-node)
3544 (:constructor nil)
3545 (:constructor make-js2-assign-node (&key type
3546 (pos js2-ts-cursor)
3547 len op-pos
3548 left right)))
3549 "Represents any assignment.
3550 The type field holds the actual assignment operator.")
3551
3552 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3553 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3554
3555 (defstruct (js2-unary-node
3556 (:include js2-node)
3557 (:constructor nil)
3558 (:constructor make-js2-unary-node (&key type ; required
3559 (pos js2-ts-cursor)
3560 len operand)))
3561 "AST node type for unary operator nodes.
3562 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3563 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3564 property is added if the operator follows the operand."
3565 operand) ; a `js2-node' expression
3566
3567 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3568 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3569
3570 (defun js2-visit-unary-node (n v)
3571 (js2-visit-ast (js2-unary-node-operand n) v))
3572
3573 (defun js2-print-unary-node (n i)
3574 (let* ((tt (js2-node-type n))
3575 (op (gethash tt js2-operator-tokens))
3576 (postfix (js2-node-get-prop n 'postfix)))
3577 (unless op
3578 (error "unrecognized unary operator %s" tt))
3579 (insert (js2-make-pad i))
3580 (unless postfix
3581 (insert op))
3582 (if (or (= tt js2-TYPEOF)
3583 (= tt js2-DELPROP))
3584 (insert " "))
3585 (js2-print-ast (js2-unary-node-operand n) 0)
3586 (when postfix
3587 (insert op))))
3588
3589 (defstruct (js2-let-node
3590 (:include js2-scope)
3591 (:constructor nil)
3592 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3593 (pos (js2-current-token-beg))
3594 len vars body
3595 lp rp)))
3596 "AST node for a let expression or a let statement.
3597 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3598 vars ; a `js2-var-decl-node'
3599 body ; a `js2-node' representing the expression or body block
3600 lp
3601 rp)
3602
3603 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3604 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3605
3606 (defun js2-visit-let-node (n v)
3607 (js2-visit-ast (js2-let-node-vars n) v)
3608 (js2-visit-ast (js2-let-node-body n) v))
3609
3610 (defun js2-print-let-node (n i)
3611 (insert (js2-make-pad i) "let (")
3612 (let ((p (point)))
3613 (js2-print-ast (js2-let-node-vars n) 0)
3614 (delete-region p (+ p 4)))
3615 (insert ") ")
3616 (js2-print-ast (js2-let-node-body n) i))
3617
3618 (defstruct (js2-keyword-node
3619 (:include js2-node)
3620 (:constructor nil)
3621 (:constructor make-js2-keyword-node (&key type
3622 (pos (js2-current-token-beg))
3623 (len (- js2-ts-cursor pos)))))
3624 "AST node representing a literal keyword such as `null'.
3625 Used for `null', `this', `true', `false' and `debugger'.
3626 The node type is set to js2-NULL, js2-THIS, etc.")
3627
3628 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3629 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3630
3631 (defun js2-print-keyword-node (n i)
3632 (insert (js2-make-pad i)
3633 (let ((tt (js2-node-type n)))
3634 (cond
3635 ((= tt js2-THIS) "this")
3636 ((= tt js2-SUPER) "super")
3637 ((= tt js2-NULL) "null")
3638 ((= tt js2-TRUE) "true")
3639 ((= tt js2-FALSE) "false")
3640 ((= tt js2-DEBUGGER) "debugger")
3641 (t (error "Invalid keyword literal type: %d" tt))))))
3642
3643 (defsubst js2-this-or-super-node-p (node)
3644 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3645 (let ((type (js2-node-type node)))
3646 (or (eq type js2-THIS) (eq type js2-SUPER))))
3647
3648 (defstruct (js2-new-node
3649 (:include js2-node)
3650 (:constructor nil)
3651 (:constructor make-js2-new-node (&key (type js2-NEW)
3652 (pos (js2-current-token-beg))
3653 len target
3654 args initializer
3655 lp rp)))
3656 "AST node for new-expression such as new Foo()."
3657 target ; an identifier or reference
3658 args ; a Lisp list of argument nodes
3659 lp ; position of left-paren, nil if omitted
3660 rp ; position of right-paren, nil if omitted
3661 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3662
3663 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3664 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3665
3666 (defun js2-visit-new-node (n v)
3667 (js2-visit-ast (js2-new-node-target n) v)
3668 (dolist (arg (js2-new-node-args n))
3669 (js2-visit-ast arg v))
3670 (js2-visit-ast (js2-new-node-initializer n) v))
3671
3672 (defun js2-print-new-node (n i)
3673 (insert (js2-make-pad i) "new ")
3674 (js2-print-ast (js2-new-node-target n))
3675 (insert "(")
3676 (js2-print-list (js2-new-node-args n))
3677 (insert ")")
3678 (when (js2-new-node-initializer n)
3679 (insert " ")
3680 (js2-print-ast (js2-new-node-initializer n))))
3681
3682 (defstruct (js2-name-node
3683 (:include js2-node)
3684 (:constructor nil)
3685 (:constructor make-js2-name-node (&key (type js2-NAME)
3686 (pos (js2-current-token-beg))
3687 (len (- js2-ts-cursor
3688 (js2-current-token-beg)))
3689 (name (js2-current-token-string)))))
3690 "AST node for a JavaScript identifier"
3691 name ; a string
3692 scope) ; a `js2-scope' (optional, used for codegen)
3693
3694 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3695 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3696
3697 (defun js2-print-name-node (n i)
3698 (insert (js2-make-pad i)
3699 (js2-name-node-name n)))
3700
3701 (defsubst js2-name-node-length (node)
3702 "Return identifier length of NODE, a `js2-name-node'.
3703 Returns 0 if NODE is nil or its identifier field is nil."
3704 (if node
3705 (length (js2-name-node-name node))
3706 0))
3707
3708 (defstruct (js2-number-node
3709 (:include js2-node)
3710 (:constructor nil)
3711 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3712 (pos (js2-current-token-beg))
3713 (len (- js2-ts-cursor
3714 (js2-current-token-beg)))
3715 (value (js2-current-token-string))
3716 (num-value (js2-token-number
3717 (js2-current-token))))))
3718 "AST node for a number literal."
3719 value ; the original string, e.g. "6.02e23"
3720 num-value) ; the parsed number value
3721
3722 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3723 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3724
3725 (defun js2-print-number-node (n i)
3726 (insert (js2-make-pad i)
3727 (number-to-string (js2-number-node-num-value n))))
3728
3729 (defstruct (js2-regexp-node
3730 (:include js2-node)
3731 (:constructor nil)
3732 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3733 (pos (js2-current-token-beg))
3734 (len (- js2-ts-cursor
3735 (js2-current-token-beg)))
3736 value flags)))
3737 "AST node for a regular expression literal."
3738 value ; the regexp string, without // delimiters
3739 flags) ; a string of flags, e.g. `mi'.
3740
3741 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3742 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3743
3744 (defun js2-print-regexp (n i)
3745 (insert (js2-make-pad i)
3746 "/"
3747 (js2-regexp-node-value n)
3748 "/")
3749 (if (js2-regexp-node-flags n)
3750 (insert (js2-regexp-node-flags n))))
3751
3752 (defstruct (js2-string-node
3753 (:include js2-node)
3754 (:constructor nil)
3755 (:constructor make-js2-string-node (&key (type js2-STRING)
3756 (pos (js2-current-token-beg))
3757 (len (- js2-ts-cursor
3758 (js2-current-token-beg)))
3759 (value (js2-current-token-string)))))
3760 "String literal.
3761 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3762 You can tell the quote type by looking at the first character."
3763 value) ; the characters of the string, including the quotes
3764
3765 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3766 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3767
3768 (defun js2-print-string-node (n i)
3769 (insert (js2-make-pad i)
3770 (js2-node-string n)))
3771
3772 (defstruct (js2-template-node
3773 (:include js2-node)
3774 (:constructor nil)
3775 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3776 beg len kids)))
3777 "Template literal."
3778 kids) ; `js2-string-node' is used for string segments, other nodes
3779 ; for substitutions inside.
3780
3781 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3782 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3783
3784 (defun js2-visit-template (n callback)
3785 (dolist (kid (js2-template-node-kids n))
3786 (js2-visit-ast kid callback)))
3787
3788 (defun js2-print-template (n i)
3789 (insert (js2-make-pad i))
3790 (dolist (kid (js2-template-node-kids n))
3791 (if (js2-string-node-p kid)
3792 (insert (js2-node-string kid))
3793 (js2-print-ast kid))))
3794
3795 (defstruct (js2-tagged-template-node
3796 (:include js2-node)
3797 (:constructor nil)
3798 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3799 beg len tag template)))
3800 "Tagged template literal."
3801 tag ; `js2-node' with the tag expression.
3802 template) ; `js2-template-node' with the template.
3803
3804 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3805 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3806
3807 (defun js2-visit-tagged-template (n callback)
3808 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3809 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3810
3811 (defun js2-print-tagged-template (n i)
3812 (insert (js2-make-pad i))
3813 (js2-print-ast (js2-tagged-template-node-tag n))
3814 (js2-print-ast (js2-tagged-template-node-template n)))
3815
3816 (defstruct (js2-array-node
3817 (:include js2-node)
3818 (:constructor nil)
3819 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3820 (pos js2-ts-cursor)
3821 len elems)))
3822 "AST node for an array literal."
3823 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3824
3825 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3826 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3827
3828 (defun js2-visit-array-node (n v)
3829 (dolist (e (js2-array-node-elems n))
3830 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3831
3832 (defun js2-print-array-node (n i)
3833 (insert (js2-make-pad i) "[")
3834 (let ((elems (js2-array-node-elems n)))
3835 (js2-print-list elems)
3836 (when (and elems (null (car (last elems))))
3837 (insert ",")))
3838 (insert "]"))
3839
3840 (defstruct (js2-class-node
3841 (:include js2-node)
3842 (:constructor nil)
3843 (:constructor make-js2-class-node (&key (type js2-CLASS)
3844 (pos js2-ts-cursor)
3845 (form 'CLASS_STATEMENT)
3846 (name "")
3847 extends len elems)))
3848 "AST node for an class expression.
3849 `elems' is a list of `js2-object-prop-node', and `extends' is an
3850 optional `js2-expr-node'"
3851 form ; CLASS_{STATEMENT|EXPRESSION}
3852 name ; class name (a `js2-node-name', or nil if anonymous)
3853 extends ; class heritage (a `js2-expr-node', or nil if none)
3854 elems)
3855
3856 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3857 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3858
3859 (defun js2-visit-class-node (n v)
3860 (js2-visit-ast (js2-class-node-name n) v)
3861 (js2-visit-ast (js2-class-node-extends n) v)
3862 (dolist (e (js2-class-node-elems n))
3863 (js2-visit-ast e v)))
3864
3865 (defun js2-print-class-node (n i)
3866 (let* ((pad (js2-make-pad i))
3867 (name (js2-class-node-name n))
3868 (extends (js2-class-node-extends n))
3869 (elems (js2-class-node-elems n)))
3870 (insert pad "class")
3871 (when name
3872 (insert " ")
3873 (js2-print-ast name 0))
3874 (when extends
3875 (insert " extends ")
3876 (js2-print-ast extends))
3877 (insert " {")
3878 (dolist (elem elems)
3879 (insert "\n")
3880 (if (js2-node-get-prop elem 'STATIC)
3881 (progn (insert (js2-make-pad (1+ i)) "static ")
3882 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3883 (js2-print-ast elem (1+ i))))
3884 (insert "\n" pad "}")))
3885
3886 (defstruct (js2-object-node
3887 (:include js2-node)
3888 (:constructor nil)
3889 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3890 (pos js2-ts-cursor)
3891 len
3892 elems)))
3893 "AST node for an object literal expression.
3894 `elems' is a list of `js2-object-prop-node'."
3895 elems)
3896
3897 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3898 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3899
3900 (defun js2-visit-object-node (n v)
3901 (dolist (e (js2-object-node-elems n))
3902 (js2-visit-ast e v)))
3903
3904 (defun js2-print-object-node (n i)
3905 (insert (js2-make-pad i) "{")
3906 (js2-print-list (js2-object-node-elems n))
3907 (insert "}"))
3908
3909 (defstruct (js2-object-prop-node
3910 (:include js2-infix-node)
3911 (:constructor nil)
3912 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3913 (pos js2-ts-cursor)
3914 len left
3915 right op-pos)))
3916 "AST node for an object literal prop:value entry.
3917 The `left' field is the property: a name node, string node or number node.
3918 The `right' field is a `js2-node' representing the initializer value.
3919 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3920 and both fields have the same value.")
3921
3922 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3923 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3924
3925 (defun js2-print-object-prop-node (n i)
3926 (let* ((left (js2-object-prop-node-left n))
3927 (computed (not (or (js2-string-node-p left)
3928 (js2-number-node-p left)
3929 (js2-name-node-p left)))))
3930 (insert (js2-make-pad i))
3931 (if computed
3932 (insert "["))
3933 (js2-print-ast left 0)
3934 (if computed
3935 (insert "]"))
3936 (if (not (js2-node-get-prop n 'SHORTHAND))
3937 (progn
3938 (insert ": ")
3939 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3940
3941 (defstruct (js2-getter-setter-node
3942 (:include js2-infix-node)
3943 (:constructor nil)
3944 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3945 (pos js2-ts-cursor)
3946 len left right)))
3947 "AST node for a getter/setter property in an object literal.
3948 The `left' field is the `js2-name-node' naming the getter/setter prop.
3949 The `right' field is always an anonymous `js2-function-node' with a node
3950 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3951
3952 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3953 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3954
3955 (defun js2-print-getter-setter (n i)
3956 (let ((pad (js2-make-pad i))
3957 (left (js2-getter-setter-node-left n))
3958 (right (js2-getter-setter-node-right n)))
3959 (insert pad)
3960 (if (/= (js2-node-type n) js2-FUNCTION)
3961 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3962 (js2-print-ast left 0)
3963 (js2-print-ast right 0)))
3964
3965 (defstruct (js2-prop-get-node
3966 (:include js2-infix-node)
3967 (:constructor nil)
3968 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3969 (pos js2-ts-cursor)
3970 len left right)))
3971 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3972
3973 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3974 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3975
3976 (defun js2-visit-prop-get-node (n v)
3977 (js2-visit-ast (js2-prop-get-node-left n) v)
3978 (js2-visit-ast (js2-prop-get-node-right n) v))
3979
3980 (defun js2-print-prop-get-node (n i)
3981 (insert (js2-make-pad i))
3982 (js2-print-ast (js2-prop-get-node-left n) 0)
3983 (insert ".")
3984 (js2-print-ast (js2-prop-get-node-right n) 0))
3985
3986 (defstruct (js2-elem-get-node
3987 (:include js2-node)
3988 (:constructor nil)
3989 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3990 (pos js2-ts-cursor)
3991 len target element
3992 lb rb)))
3993 "AST node for an array index expression such as foo[bar]."
3994 target ; a `js2-node' - the expression preceding the "."
3995 element ; a `js2-node' - the expression in brackets
3996 lb ; position of left-bracket, nil if omitted
3997 rb) ; position of right-bracket, nil if omitted
3998
3999 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4000 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4001
4002 (defun js2-visit-elem-get-node (n v)
4003 (js2-visit-ast (js2-elem-get-node-target n) v)
4004 (js2-visit-ast (js2-elem-get-node-element n) v))
4005
4006 (defun js2-print-elem-get-node (n i)
4007 (insert (js2-make-pad i))
4008 (js2-print-ast (js2-elem-get-node-target n) 0)
4009 (insert "[")
4010 (js2-print-ast (js2-elem-get-node-element n) 0)
4011 (insert "]"))
4012
4013 (defstruct (js2-call-node
4014 (:include js2-node)
4015 (:constructor nil)
4016 (:constructor make-js2-call-node (&key (type js2-CALL)
4017 (pos js2-ts-cursor)
4018 len target args
4019 lp rp)))
4020 "AST node for a JavaScript function call."
4021 target ; a `js2-node' evaluating to the function to call
4022 args ; a Lisp list of `js2-node' arguments
4023 lp ; position of open-paren, or nil if missing
4024 rp) ; position of close-paren, or nil if missing
4025
4026 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4027 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4028
4029 (defun js2-visit-call-node (n v)
4030 (js2-visit-ast (js2-call-node-target n) v)
4031 (dolist (arg (js2-call-node-args n))
4032 (js2-visit-ast arg v)))
4033
4034 (defun js2-print-call-node (n i)
4035 (insert (js2-make-pad i))
4036 (js2-print-ast (js2-call-node-target n) 0)
4037 (insert "(")
4038 (js2-print-list (js2-call-node-args n))
4039 (insert ")"))
4040
4041 (defstruct (js2-yield-node
4042 (:include js2-node)
4043 (:constructor nil)
4044 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4045 (pos js2-ts-cursor)
4046 len value star-p)))
4047 "AST node for yield statement or expression."
4048 star-p ; whether it's yield*
4049 value) ; optional: value to be yielded
4050
4051 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4052 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4053
4054 (defun js2-visit-yield-node (n v)
4055 (js2-visit-ast (js2-yield-node-value n) v))
4056
4057 (defun js2-print-yield-node (n i)
4058 (insert (js2-make-pad i))
4059 (insert "yield")
4060 (when (js2-yield-node-star-p n)
4061 (insert "*"))
4062 (when (js2-yield-node-value n)
4063 (insert " ")
4064 (js2-print-ast (js2-yield-node-value n) 0)))
4065
4066 (defstruct (js2-paren-node
4067 (:include js2-node)
4068 (:constructor nil)
4069 (:constructor make-js2-paren-node (&key (type js2-LP)
4070 (pos js2-ts-cursor)
4071 len expr)))
4072 "AST node for a parenthesized expression.
4073 In particular, used when the parens are syntactically optional,
4074 as opposed to required parens such as those enclosing an if-conditional."
4075 expr) ; `js2-node'
4076
4077 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4078 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4079
4080 (defun js2-visit-paren-node (n v)
4081 (js2-visit-ast (js2-paren-node-expr n) v))
4082
4083 (defun js2-print-paren-node (n i)
4084 (insert (js2-make-pad i))
4085 (insert "(")
4086 (js2-print-ast (js2-paren-node-expr n) 0)
4087 (insert ")"))
4088
4089 (defstruct (js2-comp-node
4090 (:include js2-scope)
4091 (:constructor nil)
4092 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4093 (pos js2-ts-cursor)
4094 len result
4095 loops filters
4096 form)))
4097 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4098 result ; result expression (just after left-bracket)
4099 loops ; a Lisp list of `js2-comp-loop-node'
4100 filters ; a Lisp list of guard/filter expressions
4101 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4102 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4103 )
4104
4105 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4106 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4107
4108 (defun js2-visit-comp-node (n v)
4109 (js2-visit-ast (js2-comp-node-result n) v)
4110 (dolist (l (js2-comp-node-loops n))
4111 (js2-visit-ast l v))
4112 (dolist (f (js2-comp-node-filters n))
4113 (js2-visit-ast f v)))
4114
4115 (defun js2-print-comp-node (n i)
4116 (let ((pad (js2-make-pad i))
4117 (result (js2-comp-node-result n))
4118 (loops (js2-comp-node-loops n))
4119 (filters (js2-comp-node-filters n))
4120 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4121 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4122 (insert pad (if gen-p "(" "["))
4123 (when legacy-p
4124 (js2-print-ast result 0))
4125 (dolist (l loops)
4126 (when legacy-p
4127 (insert " "))
4128 (js2-print-ast l 0)
4129 (unless legacy-p
4130 (insert " ")))
4131 (dolist (f filters)
4132 (when legacy-p
4133 (insert " "))
4134 (insert "if (")
4135 (js2-print-ast f 0)
4136 (insert ")")
4137 (unless legacy-p
4138 (insert " ")))
4139 (unless legacy-p
4140 (js2-print-ast result 0))
4141 (insert (if gen-p ")" "]"))))
4142
4143 (defstruct (js2-comp-loop-node
4144 (:include js2-for-in-node)
4145 (:constructor nil)
4146 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4147 (pos js2-ts-cursor)
4148 len iterator
4149 object in-pos
4150 foreach-p
4151 each-pos
4152 forof-p
4153 lp rp)))
4154 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4155
4156 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4157 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4158
4159 (defun js2-visit-comp-loop (n v)
4160 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4161 (js2-visit-ast (js2-comp-loop-node-object n) v))
4162
4163 (defun js2-print-comp-loop (n _i)
4164 (insert "for ")
4165 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4166 (insert "(")
4167 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4168 (insert (if (js2-comp-loop-node-forof-p n)
4169 " of " " in "))
4170 (js2-print-ast (js2-comp-loop-node-object n) 0)
4171 (insert ")"))
4172
4173 (defstruct (js2-empty-expr-node
4174 (:include js2-node)
4175 (:constructor nil)
4176 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4177 (pos (js2-current-token-beg))
4178 len)))
4179 "AST node for an empty expression.")
4180
4181 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4182 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4183
4184 (defstruct (js2-xml-node
4185 (:include js2-block-node)
4186 (:constructor nil)
4187 (:constructor make-js2-xml-node (&key (type js2-XML)
4188 (pos (js2-current-token-beg))
4189 len kids)))
4190 "AST node for initial parse of E4X literals.
4191 The kids field is a list of XML fragments, each a `js2-string-node' or
4192 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4193
4194 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4195 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4196
4197 (defun js2-print-xml-node (n i)
4198 (dolist (kid (js2-xml-node-kids n))
4199 (js2-print-ast kid i)))
4200
4201 (defstruct (js2-xml-js-expr-node
4202 (:include js2-xml-node)
4203 (:constructor nil)
4204 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4205 (pos js2-ts-cursor)
4206 len expr)))
4207 "AST node for an embedded JavaScript {expression} in an E4X literal.
4208 The start and end fields correspond to the curly-braces."
4209 expr) ; a `js2-expr-node' of some sort
4210
4211 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4212 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4213
4214 (defun js2-visit-xml-js-expr (n v)
4215 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4216
4217 (defun js2-print-xml-js-expr (n i)
4218 (insert (js2-make-pad i))
4219 (insert "{")
4220 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4221 (insert "}"))
4222
4223 (defstruct (js2-xml-dot-query-node
4224 (:include js2-infix-node)
4225 (:constructor nil)
4226 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4227 (pos js2-ts-cursor)
4228 op-pos len left
4229 right rp)))
4230 "AST node for an E4X foo.(bar) filter expression.
4231 Note that the left-paren is automatically the character immediately
4232 following the dot (.) in the operator. No whitespace is permitted
4233 between the dot and the lp by the scanner."
4234 rp)
4235
4236 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4237 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4238
4239 (defun js2-print-xml-dot-query (n i)
4240 (insert (js2-make-pad i))
4241 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4242 (insert ".(")
4243 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4244 (insert ")"))
4245
4246 (defstruct (js2-xml-ref-node
4247 (:include js2-node)
4248 (:constructor nil)) ; abstract
4249 "Base type for E4X XML attribute-access or property-get expressions.
4250 Such expressions can take a variety of forms. The general syntax has
4251 three parts:
4252
4253 - (optional) an @ (specifying an attribute access)
4254 - (optional) a namespace (a `js2-name-node') and double-colon
4255 - (required) either a `js2-name-node' or a bracketed [expression]
4256
4257 The property-name expressions (examples: ns::name, @name) are
4258 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4259 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4260
4261 This node type (or more specifically, its subclasses) will sometimes
4262 be the right-hand child of a `js2-prop-get-node' or a
4263 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4264 The `js2-xml-ref-node' may also be a standalone primary expression with
4265 no explicit target, which is valid in certain expression contexts such as
4266
4267 company..employee.(@id < 100)
4268
4269 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4270 expression whose parent is a `js2-xml-dot-query-node'."
4271 namespace
4272 at-pos
4273 colon-pos)
4274
4275 (defsubst js2-xml-ref-node-attr-access-p (node)
4276 "Return non-nil if this expression began with an @-token."
4277 (and (numberp (js2-xml-ref-node-at-pos node))
4278 (plusp (js2-xml-ref-node-at-pos node))))
4279
4280 (defstruct (js2-xml-prop-ref-node
4281 (:include js2-xml-ref-node)
4282 (:constructor nil)
4283 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4284 (pos (js2-current-token-beg))
4285 len propname
4286 namespace at-pos
4287 colon-pos)))
4288 "AST node for an E4X XML [expr] property-ref expression.
4289 The JavaScript syntax is an optional @, an optional ns::, and a name.
4290
4291 [ '@' ] [ name '::' ] name
4292
4293 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4294 @ns::*, @*::attr, @*::*, and @*.
4295
4296 The node starts at the @ token, if present. Otherwise it starts at the
4297 namespace name. The node bounds extend through the closing right-bracket,
4298 or if it is missing due to a syntax error, through the end of the index
4299 expression."
4300 propname)
4301
4302 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4303 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4304
4305 (defun js2-visit-xml-prop-ref-node (n v)
4306 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4307 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4308
4309 (defun js2-print-xml-prop-ref-node (n i)
4310 (insert (js2-make-pad i))
4311 (if (js2-xml-ref-node-attr-access-p n)
4312 (insert "@"))
4313 (when (js2-xml-prop-ref-node-namespace n)
4314 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4315 (insert "::"))
4316 (if (js2-xml-prop-ref-node-propname n)
4317 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4318
4319 (defstruct (js2-xml-elem-ref-node
4320 (:include js2-xml-ref-node)
4321 (:constructor nil)
4322 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4323 (pos (js2-current-token-beg))
4324 len expr lb rb
4325 namespace at-pos
4326 colon-pos)))
4327 "AST node for an E4X XML [expr] member-ref expression.
4328 Syntax:
4329
4330 [ '@' ] [ name '::' ] '[' expr ']'
4331
4332 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4333
4334 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4335 is not a legal E4X XML element-ref expression, since it's already used
4336 for standard JavaScript element-get array indexing. Hence, a
4337 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4338 non-nil namespace node, or both.
4339
4340 The node starts at the @ token, if present. Otherwise it starts
4341 at the namespace name. The node bounds extend through the closing
4342 right-bracket, or if it is missing due to a syntax error, through the
4343 end of the index expression."
4344 expr ; the bracketed index expression
4345 lb
4346 rb)
4347
4348 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4349 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4350
4351 (defun js2-visit-xml-elem-ref-node (n v)
4352 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4353 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4354
4355 (defun js2-print-xml-elem-ref-node (n i)
4356 (insert (js2-make-pad i))
4357 (if (js2-xml-ref-node-attr-access-p n)
4358 (insert "@"))
4359 (when (js2-xml-elem-ref-node-namespace n)
4360 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4361 (insert "::"))
4362 (insert "[")
4363 (if (js2-xml-elem-ref-node-expr n)
4364 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4365 (insert "]"))
4366
4367 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4368
4369 (defstruct (js2-xml-start-tag-node
4370 (:include js2-xml-node)
4371 (:constructor nil)
4372 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4373 (pos js2-ts-cursor)
4374 len name attrs kids
4375 empty-p)))
4376 "AST node for an XML start-tag. Not currently used.
4377 The `kids' field is a Lisp list of child content nodes."
4378 name ; a `js2-xml-name-node'
4379 attrs ; a Lisp list of `js2-xml-attr-node'
4380 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4381
4382 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4383 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4384
4385 (defun js2-visit-xml-start-tag (n v)
4386 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4387 (dolist (attr (js2-xml-start-tag-node-attrs n))
4388 (js2-visit-ast attr v))
4389 (js2-visit-block n v))
4390
4391 (defun js2-print-xml-start-tag (n i)
4392 (insert (js2-make-pad i) "<")
4393 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4394 (when (js2-xml-start-tag-node-attrs n)
4395 (insert " ")
4396 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4397 (insert ">"))
4398
4399 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4400 ;; and add the end-tag to the kids list of the parent as well.
4401 (defstruct (js2-xml-end-tag-node
4402 (:include js2-xml-node)
4403 (:constructor nil)
4404 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4405 (pos js2-ts-cursor)
4406 len name)))
4407 "AST node for an XML end-tag. Not currently used."
4408 name) ; a `js2-xml-name-node'
4409
4410 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4411 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4412
4413 (defun js2-visit-xml-end-tag (n v)
4414 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4415
4416 (defun js2-print-xml-end-tag (n i)
4417 (insert (js2-make-pad i))
4418 (insert "</")
4419 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4420 (insert ">"))
4421
4422 (defstruct (js2-xml-name-node
4423 (:include js2-xml-node)
4424 (:constructor nil)
4425 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4426 (pos js2-ts-cursor)
4427 len namespace kids)))
4428 "AST node for an E4X XML name. Not currently used.
4429 Any XML name can be qualified with a namespace, hence the namespace field.
4430 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4431 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4432 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4433 namespace) ; a `js2-string-node'
4434
4435 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4436 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4437
4438 (defun js2-visit-xml-name-node (n v)
4439 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4440
4441 (defun js2-print-xml-name-node (n i)
4442 (insert (js2-make-pad i))
4443 (when (js2-xml-name-node-namespace n)
4444 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4445 (insert "::"))
4446 (dolist (kid (js2-xml-name-node-kids n))
4447 (js2-print-ast kid 0)))
4448
4449 (defstruct (js2-xml-pi-node
4450 (:include js2-xml-node)
4451 (:constructor nil)
4452 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4453 (pos js2-ts-cursor)
4454 len name attrs)))
4455 "AST node for an E4X XML processing instruction. Not currently used."
4456 name ; a `js2-xml-name-node'
4457 attrs) ; a list of `js2-xml-attr-node'
4458
4459 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4460 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4461
4462 (defun js2-visit-xml-pi-node (n v)
4463 (js2-visit-ast (js2-xml-pi-node-name n) v)
4464 (dolist (attr (js2-xml-pi-node-attrs n))
4465 (js2-visit-ast attr v)))
4466
4467 (defun js2-print-xml-pi-node (n i)
4468 (insert (js2-make-pad i) "<?")
4469 (js2-print-ast (js2-xml-pi-node-name n))
4470 (when (js2-xml-pi-node-attrs n)
4471 (insert " ")
4472 (js2-print-list (js2-xml-pi-node-attrs n)))
4473 (insert "?>"))
4474
4475 (defstruct (js2-xml-cdata-node
4476 (:include js2-xml-node)
4477 (:constructor nil)
4478 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4479 (pos js2-ts-cursor)
4480 len content)))
4481 "AST node for a CDATA escape section. Not currently used."
4482 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4483
4484 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4485 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4486
4487 (defun js2-visit-xml-cdata-node (n v)
4488 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4489
4490 (defun js2-print-xml-cdata-node (n i)
4491 (insert (js2-make-pad i))
4492 (js2-print-ast (js2-xml-cdata-node-content n)))
4493
4494 (defstruct (js2-xml-attr-node
4495 (:include js2-xml-node)
4496 (:constructor nil)
4497 (:constructor make-js2-attr-node (&key (type js2-XML)
4498 (pos js2-ts-cursor)
4499 len name value
4500 eq-pos quote-type)))
4501 "AST node representing a foo='bar' XML attribute value. Not yet used."
4502 name ; a `js2-xml-name-node'
4503 value ; a `js2-xml-name-node'
4504 eq-pos ; buffer position of "=" sign
4505 quote-type) ; 'single or 'double
4506
4507 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4508 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4509
4510 (defun js2-visit-xml-attr-node (n v)
4511 (js2-visit-ast (js2-xml-attr-node-name n) v)
4512 (js2-visit-ast (js2-xml-attr-node-value n) v))
4513
4514 (defun js2-print-xml-attr-node (n i)
4515 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4516 "'"
4517 "\"")))
4518 (insert (js2-make-pad i))
4519 (js2-print-ast (js2-xml-attr-node-name n) 0)
4520 (insert "=" quote)
4521 (js2-print-ast (js2-xml-attr-node-value n) 0)
4522 (insert quote)))
4523
4524 (defstruct (js2-xml-text-node
4525 (:include js2-xml-node)
4526 (:constructor nil)
4527 (:constructor make-js2-text-node (&key (type js2-XML)
4528 (pos js2-ts-cursor)
4529 len content)))
4530 "AST node for an E4X XML text node. Not currently used."
4531 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4532
4533 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4534 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4535
4536 (defun js2-visit-xml-text-node (n v)
4537 (js2-visit-ast (js2-xml-text-node-content n) v))
4538
4539 (defun js2-print-xml-text-node (n i)
4540 (insert (js2-make-pad i))
4541 (dolist (kid (js2-xml-text-node-content n))
4542 (js2-print-ast kid)))
4543
4544 (defstruct (js2-xml-comment-node
4545 (:include js2-xml-node)
4546 (:constructor nil)
4547 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4548 (pos js2-ts-cursor)
4549 len)))
4550 "AST node for E4X XML comment. Not currently used.")
4551
4552 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4553 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4554
4555 (defun js2-print-xml-comment (n i)
4556 (insert (js2-make-pad i)
4557 (js2-node-string n)))
4558
4559 ;;; Node utilities
4560
4561 (defsubst js2-node-line (n)
4562 "Fetch the source line number at the start of node N.
4563 This is O(n) in the length of the source buffer; use prudently."
4564 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4565
4566 (defsubst js2-block-node-kid (n i)
4567 "Return child I of node N, or nil if there aren't that many."
4568 (nth i (js2-block-node-kids n)))
4569
4570 (defsubst js2-block-node-first (n)
4571 "Return first child of block node N, or nil if there is none."
4572 (first (js2-block-node-kids n)))
4573
4574 (defun js2-node-root (n)
4575 "Return the root of the AST containing N.
4576 If N has no parent pointer, returns N."
4577 (let ((parent (js2-node-parent n)))
4578 (if parent
4579 (js2-node-root parent)
4580 n)))
4581
4582 (defsubst js2-node-short-name (n)
4583 "Return the short name of node N as a string, e.g. `js2-if-node'."
4584 (substring (symbol-name (aref n 0))
4585 (length "cl-struct-")))
4586
4587 (defun js2-node-child-list (node)
4588 "Return the child list for NODE, a Lisp list of nodes.
4589 Works for block nodes, array nodes, obj literals, funarg lists,
4590 var decls and try nodes (for catch clauses). Note that you should call
4591 `js2-block-node-kids' on the function body for the body statements.
4592 Returns nil for zero-length child lists or unsupported nodes."
4593 (cond
4594 ((js2-function-node-p node)
4595 (js2-function-node-params node))
4596 ((js2-block-node-p node)
4597 (js2-block-node-kids node))
4598 ((js2-try-node-p node)
4599 (js2-try-node-catch-clauses node))
4600 ((js2-array-node-p node)
4601 (js2-array-node-elems node))
4602 ((js2-object-node-p node)
4603 (js2-object-node-elems node))
4604 ((js2-call-node-p node)
4605 (js2-call-node-args node))
4606 ((js2-new-node-p node)
4607 (js2-new-node-args node))
4608 ((js2-var-decl-node-p node)
4609 (js2-var-decl-node-kids node))
4610 (t
4611 nil)))
4612
4613 (defun js2-node-set-child-list (node kids)
4614 "Set the child list for NODE to KIDS."
4615 (cond
4616 ((js2-function-node-p node)
4617 (setf (js2-function-node-params node) kids))
4618 ((js2-block-node-p node)
4619 (setf (js2-block-node-kids node) kids))
4620 ((js2-try-node-p node)
4621 (setf (js2-try-node-catch-clauses node) kids))
4622 ((js2-array-node-p node)
4623 (setf (js2-array-node-elems node) kids))
4624 ((js2-object-node-p node)
4625 (setf (js2-object-node-elems node) kids))
4626 ((js2-call-node-p node)
4627 (setf (js2-call-node-args node) kids))
4628 ((js2-new-node-p node)
4629 (setf (js2-new-node-args node) kids))
4630 ((js2-var-decl-node-p node)
4631 (setf (js2-var-decl-node-kids node) kids))
4632 (t
4633 (error "Unsupported node type: %s" (js2-node-short-name node))))
4634 kids)
4635
4636 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4637 (defconst js2-paren-expr-nodes
4638 '(cl-struct-js2-comp-loop-node
4639 cl-struct-js2-comp-node
4640 cl-struct-js2-call-node
4641 cl-struct-js2-catch-node
4642 cl-struct-js2-do-node
4643 cl-struct-js2-elem-get-node
4644 cl-struct-js2-for-in-node
4645 cl-struct-js2-for-node
4646 cl-struct-js2-function-node
4647 cl-struct-js2-if-node
4648 cl-struct-js2-let-node
4649 cl-struct-js2-new-node
4650 cl-struct-js2-paren-node
4651 cl-struct-js2-switch-node
4652 cl-struct-js2-while-node
4653 cl-struct-js2-with-node
4654 cl-struct-js2-xml-dot-query-node)
4655 "Node types that can have a parenthesized child expression.
4656 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4657
4658 (defsubst js2-paren-expr-node-p (node)
4659 "Return t for nodes that typically have a parenthesized child expression.
4660 Useful for computing the indentation anchors for arg-lists and conditions.
4661 Note that it may return a false positive, for instance when NODE is
4662 a `js2-new-node' and there are no arguments or parentheses."
4663 (memq (aref node 0) js2-paren-expr-nodes))
4664
4665 ;; Fake polymorphism... yech.
4666 (defun js2-node-lp (node)
4667 "Return relative left-paren position for NODE, if applicable.
4668 For `js2-elem-get-node' structs, returns left-bracket position.
4669 Note that the position may be nil in the case of a parse error."
4670 (cond
4671 ((js2-elem-get-node-p node)
4672 (js2-elem-get-node-lb node))
4673 ((js2-loop-node-p node)
4674 (js2-loop-node-lp node))
4675 ((js2-function-node-p node)
4676 (js2-function-node-lp node))
4677 ((js2-if-node-p node)
4678 (js2-if-node-lp node))
4679 ((js2-new-node-p node)
4680 (js2-new-node-lp node))
4681 ((js2-call-node-p node)
4682 (js2-call-node-lp node))
4683 ((js2-paren-node-p node)
4684 0)
4685 ((js2-switch-node-p node)
4686 (js2-switch-node-lp node))
4687 ((js2-catch-node-p node)
4688 (js2-catch-node-lp node))
4689 ((js2-let-node-p node)
4690 (js2-let-node-lp node))
4691 ((js2-comp-node-p node)
4692 0)
4693 ((js2-with-node-p node)
4694 (js2-with-node-lp node))
4695 ((js2-xml-dot-query-node-p node)
4696 (1+ (js2-infix-node-op-pos node)))
4697 (t
4698 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4699
4700 ;; Fake polymorphism... blech.
4701 (defun js2-node-rp (node)
4702 "Return relative right-paren position for NODE, if applicable.
4703 For `js2-elem-get-node' structs, returns right-bracket position.
4704 Note that the position may be nil in the case of a parse error."
4705 (cond
4706 ((js2-elem-get-node-p node)
4707 (js2-elem-get-node-rb node))
4708 ((js2-loop-node-p node)
4709 (js2-loop-node-rp node))
4710 ((js2-function-node-p node)
4711 (js2-function-node-rp node))
4712 ((js2-if-node-p node)
4713 (js2-if-node-rp node))
4714 ((js2-new-node-p node)
4715 (js2-new-node-rp node))
4716 ((js2-call-node-p node)
4717 (js2-call-node-rp node))
4718 ((js2-paren-node-p node)
4719 (1- (js2-node-len node)))
4720 ((js2-switch-node-p node)
4721 (js2-switch-node-rp node))
4722 ((js2-catch-node-p node)
4723 (js2-catch-node-rp node))
4724 ((js2-let-node-p node)
4725 (js2-let-node-rp node))
4726 ((js2-comp-node-p node)
4727 (1- (js2-node-len node)))
4728 ((js2-with-node-p node)
4729 (js2-with-node-rp node))
4730 ((js2-xml-dot-query-node-p node)
4731 (1+ (js2-xml-dot-query-node-rp node)))
4732 (t
4733 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4734
4735 (defsubst js2-node-first-child (node)
4736 "Return the first element of `js2-node-child-list' for NODE."
4737 (car (js2-node-child-list node)))
4738
4739 (defsubst js2-node-last-child (node)
4740 "Return the last element of `js2-node-last-child' for NODE."
4741 (car (last (js2-node-child-list node))))
4742
4743 (defun js2-node-prev-sibling (node)
4744 "Return the previous statement in parent.
4745 Works for parents supported by `js2-node-child-list'.
4746 Returns nil if NODE is not in the parent, or PARENT is
4747 not a supported node, or if NODE is the first child."
4748 (let* ((p (js2-node-parent node))
4749 (kids (js2-node-child-list p))
4750 (sib (car kids)))
4751 (while (and kids
4752 (not (eq node (cadr kids))))
4753 (setq kids (cdr kids)
4754 sib (car kids)))
4755 sib))
4756
4757 (defun js2-node-next-sibling (node)
4758 "Return the next statement in parent block.
4759 Returns nil if NODE is not in the block, or PARENT is not
4760 a block node, or if NODE is the last statement."
4761 (let* ((p (js2-node-parent node))
4762 (kids (js2-node-child-list p)))
4763 (while (and kids
4764 (not (eq node (car kids))))
4765 (setq kids (cdr kids)))
4766 (cadr kids)))
4767
4768 (defun js2-node-find-child-before (pos parent &optional after)
4769 "Find the last child that starts before POS in parent.
4770 If AFTER is non-nil, returns first child starting after POS.
4771 POS is an absolute buffer position. PARENT is any node
4772 supported by `js2-node-child-list'.
4773 Returns nil if no applicable child is found."
4774 (let ((kids (if (js2-function-node-p parent)
4775 (js2-block-node-kids (js2-function-node-body parent))
4776 (js2-node-child-list parent)))
4777 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4778 (js2-function-node-body parent)
4779 parent)))
4780 kid result fn
4781 (continue t))
4782 (setq fn (if after '>= '<))
4783 (while (and kids continue)
4784 (setq kid (car kids))
4785 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4786 (setq result kid
4787 continue (not after))
4788 (setq continue after))
4789 (setq kids (cdr kids)))
4790 result))
4791
4792 (defun js2-node-find-child-after (pos parent)
4793 "Find first child that starts after POS in parent.
4794 POS is an absolute buffer position. PARENT is any node
4795 supported by `js2-node-child-list'.
4796 Returns nil if no applicable child is found."
4797 (js2-node-find-child-before pos parent 'after))
4798
4799 (defun js2-node-replace-child (pos parent new-node)
4800 "Replace node at index POS in PARENT with NEW-NODE.
4801 Only works for parents supported by `js2-node-child-list'."
4802 (let ((kids (js2-node-child-list parent))
4803 (i 0))
4804 (while (< i pos)
4805 (setq kids (cdr kids)
4806 i (1+ i)))
4807 (setcar kids new-node)
4808 (js2-node-add-children parent new-node)))
4809
4810 (defun js2-node-buffer (n)
4811 "Return the buffer associated with AST N.
4812 Returns nil if the buffer is not set as a property on the root
4813 node, or if parent links were not recorded during parsing."
4814 (let ((root (js2-node-root n)))
4815 (and root
4816 (js2-ast-root-p root)
4817 (js2-ast-root-buffer root))))
4818
4819 (defun js2-block-node-push (n kid)
4820 "Push js2-node KID onto the end of js2-block-node N's child list.
4821 KID is always added to the -end- of the kids list.
4822 Function also calls `js2-node-add-children' to add the parent link."
4823 (let ((kids (js2-node-child-list n)))
4824 (if kids
4825 (setcdr kids (nconc (cdr kids) (list kid)))
4826 (js2-node-set-child-list n (list kid)))
4827 (js2-node-add-children n kid)))
4828
4829 (defun js2-node-string (node)
4830 (with-current-buffer (or (js2-node-buffer node)
4831 (error "No buffer available for node %s" node))
4832 (let ((pos (js2-node-abs-pos node)))
4833 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4834
4835 ;; Container for storing the node we're looking for in a traversal.
4836 (js2-deflocal js2-discovered-node nil)
4837
4838 ;; Keep track of absolute node position during traversals.
4839 (js2-deflocal js2-visitor-offset nil)
4840
4841 (js2-deflocal js2-node-search-point nil)
4842
4843 (when js2-mode-dev-mode-p
4844 (defun js2-find-node-at-point ()
4845 (interactive)
4846 (let ((node (js2-node-at-point)))
4847 (message "%s" (or node "No node found at point"))))
4848 (defun js2-node-name-at-point ()
4849 (interactive)
4850 (let ((node (js2-node-at-point)))
4851 (message "%s" (if node
4852 (js2-node-short-name node)
4853 "No node found at point.")))))
4854
4855 (defun js2-node-at-point (&optional pos skip-comments)
4856 "Return AST node at POS, a buffer position, defaulting to current point.
4857 The `js2-mode-ast' variable must be set to the current parse tree.
4858 Signals an error if the AST (`js2-mode-ast') is nil.
4859 Always returns a node - if it can't find one, it returns the root.
4860 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4861 (let ((ast js2-mode-ast)
4862 result)
4863 (unless ast
4864 (error "No JavaScript AST available"))
4865 ;; Look through comments first, since they may be inside nodes that
4866 ;; would otherwise report a match.
4867 (setq pos (or pos (point))
4868 result (if (> pos (js2-node-abs-end ast))
4869 ast
4870 (if (not skip-comments)
4871 (js2-comment-at-point pos))))
4872 (unless result
4873 (setq js2-discovered-node nil
4874 js2-visitor-offset 0
4875 js2-node-search-point pos)
4876 (unwind-protect
4877 (catch 'js2-visit-done
4878 (js2-visit-ast ast #'js2-node-at-point-visitor))
4879 (setq js2-visitor-offset nil
4880 js2-node-search-point nil))
4881 (setq result js2-discovered-node))
4882 ;; may have found a comment beyond end of last child node,
4883 ;; since visiting the ast-root looks at the comment-list last.
4884 (if (and skip-comments
4885 (js2-comment-node-p result))
4886 (setq result nil))
4887 (or result js2-mode-ast)))
4888
4889 (defun js2-node-at-point-visitor (node end-p)
4890 (let ((rel-pos (js2-node-pos node))
4891 abs-pos
4892 abs-end
4893 (point js2-node-search-point))
4894 (cond
4895 (end-p
4896 ;; this evaluates to a non-nil return value, even if it's zero
4897 (decf js2-visitor-offset rel-pos))
4898 ;; we already looked for comments before visiting, and don't want them now
4899 ((js2-comment-node-p node)
4900 nil)
4901 (t
4902 (setq abs-pos (incf js2-visitor-offset rel-pos)
4903 ;; we only want to use the node if the point is before
4904 ;; the last character position in the node, so we decrement
4905 ;; the absolute end by 1.
4906 abs-end (+ abs-pos (js2-node-len node) -1))
4907 (cond
4908 ;; If this node starts after search-point, stop the search.
4909 ((> abs-pos point)
4910 (throw 'js2-visit-done nil))
4911 ;; If this node ends before the search-point, don't check kids.
4912 ((> point abs-end)
4913 nil)
4914 (t
4915 ;; Otherwise point is within this node, possibly in a child.
4916 (setq js2-discovered-node node)
4917 t)))))) ; keep processing kids to look for more specific match
4918
4919 (defsubst js2-block-comment-p (node)
4920 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4921 (and (js2-comment-node-p node)
4922 (memq (js2-comment-node-format node) '(jsdoc block))))
4923
4924 ;; TODO: put the comments in a vector and binary-search them instead
4925 (defun js2-comment-at-point (&optional pos)
4926 "Look through scanned comment nodes for one containing POS.
4927 POS is a buffer position that defaults to current point.
4928 Function returns nil if POS was not in any comment node."
4929 (let ((ast js2-mode-ast)
4930 (x (or pos (point)))
4931 beg end)
4932 (unless ast
4933 (error "No JavaScript AST available"))
4934 (catch 'done
4935 ;; Comments are stored in lexical order.
4936 (dolist (comment (js2-ast-root-comments ast) nil)
4937 (setq beg (js2-node-abs-pos comment)
4938 end (+ beg (js2-node-len comment)))
4939 (if (and (>= x beg)
4940 (<= x end))
4941 (throw 'done comment))))))
4942
4943 (defun js2-mode-find-parent-fn (node)
4944 "Find function enclosing NODE.
4945 Returns nil if NODE is not inside a function."
4946 (setq node (js2-node-parent node))
4947 (while (and node (not (js2-function-node-p node)))
4948 (setq node (js2-node-parent node)))
4949 (and (js2-function-node-p node) node))
4950
4951 (defun js2-mode-find-enclosing-fn (node)
4952 "Find function or root enclosing NODE."
4953 (if (js2-ast-root-p node)
4954 node
4955 (setq node (js2-node-parent node))
4956 (while (not (or (js2-ast-root-p node)
4957 (js2-function-node-p node)))
4958 (setq node (js2-node-parent node)))
4959 node))
4960
4961 (defun js2-mode-find-enclosing-node (beg end)
4962 "Find node fully enclosing BEG and END."
4963 (let ((node (js2-node-at-point beg))
4964 pos
4965 (continue t))
4966 (while continue
4967 (if (or (js2-ast-root-p node)
4968 (and
4969 (<= (setq pos (js2-node-abs-pos node)) beg)
4970 (>= (+ pos (js2-node-len node)) end)))
4971 (setq continue nil)
4972 (setq node (js2-node-parent node))))
4973 node))
4974
4975 (defun js2-node-parent-script-or-fn (node)
4976 "Find script or function immediately enclosing NODE.
4977 If NODE is the ast-root, returns nil."
4978 (if (js2-ast-root-p node)
4979 nil
4980 (setq node (js2-node-parent node))
4981 (while (and node (not (or (js2-function-node-p node)
4982 (js2-script-node-p node))))
4983 (setq node (js2-node-parent node)))
4984 node))
4985
4986 (defun js2-node-is-descendant (node ancestor)
4987 "Return t if NODE is a descendant of ANCESTOR."
4988 (while (and node
4989 (not (eq node ancestor)))
4990 (setq node (js2-node-parent node)))
4991 node)
4992
4993 ;;; visitor infrastructure
4994
4995 (defun js2-visit-none (_node _callback)
4996 "Visitor for AST node that have no node children."
4997 nil)
4998
4999 (defun js2-print-none (_node _indent)
5000 "Visitor for AST node with no printed representation.")
5001
5002 (defun js2-print-body (node indent)
5003 "Print a statement, or a block without braces."
5004 (if (js2-block-node-p node)
5005 (dolist (kid (js2-block-node-kids node))
5006 (js2-print-ast kid indent))
5007 (js2-print-ast node indent)))
5008
5009 (defun js2-print-list (args &optional delimiter)
5010 (loop with len = (length args)
5011 for arg in args
5012 for count from 1
5013 do
5014 (when arg (js2-print-ast arg 0))
5015 (if (< count len)
5016 (insert (or delimiter ", ")))))
5017
5018 (defun js2-print-tree (ast)
5019 "Prints an AST to the current buffer.
5020 Makes `js2-ast-parent-nodes' available to the printer functions."
5021 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5022 (js2-print-ast ast)))
5023
5024 (defun js2-print-ast (node &optional indent)
5025 "Helper function for printing AST nodes.
5026 Requires `js2-ast-parent-nodes' to be non-nil.
5027 You should use `js2-print-tree' instead of this function."
5028 (let ((printer (get (aref node 0) 'js2-printer))
5029 (i (or indent 0)))
5030 ;; TODO: wedge comments in here somewhere
5031 (if printer
5032 (funcall printer node i))))
5033
5034 (defconst js2-side-effecting-tokens
5035 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5036 (dolist (tt (list js2-ASSIGN
5037 js2-ASSIGN_ADD
5038 js2-ASSIGN_BITAND
5039 js2-ASSIGN_BITOR
5040 js2-ASSIGN_BITXOR
5041 js2-ASSIGN_DIV
5042 js2-ASSIGN_LSH
5043 js2-ASSIGN_MOD
5044 js2-ASSIGN_MUL
5045 js2-ASSIGN_RSH
5046 js2-ASSIGN_SUB
5047 js2-ASSIGN_URSH
5048 js2-BLOCK
5049 js2-BREAK
5050 js2-CALL
5051 js2-CATCH
5052 js2-CATCH_SCOPE
5053 js2-CLASS
5054 js2-CONST
5055 js2-CONTINUE
5056 js2-DEBUGGER
5057 js2-DEC
5058 js2-DELPROP
5059 js2-DEL_REF
5060 js2-DO
5061 js2-ELSE
5062 js2-EMPTY
5063 js2-ENTERWITH
5064 js2-EXPORT
5065 js2-EXPR_RESULT
5066 js2-FINALLY
5067 js2-FOR
5068 js2-FUNCTION
5069 js2-GOTO
5070 js2-IF
5071 js2-IFEQ
5072 js2-IFNE
5073 js2-IMPORT
5074 js2-INC
5075 js2-JSR
5076 js2-LABEL
5077 js2-LEAVEWITH
5078 js2-LET
5079 js2-LETEXPR
5080 js2-LOCAL_BLOCK
5081 js2-LOOP
5082 js2-NEW
5083 js2-REF_CALL
5084 js2-RETHROW
5085 js2-RETURN
5086 js2-RETURN_RESULT
5087 js2-SEMI
5088 js2-SETELEM
5089 js2-SETELEM_OP
5090 js2-SETNAME
5091 js2-SETPROP
5092 js2-SETPROP_OP
5093 js2-SETVAR
5094 js2-SET_REF
5095 js2-SET_REF_OP
5096 js2-SWITCH
5097 js2-TARGET
5098 js2-THROW
5099 js2-TRY
5100 js2-VAR
5101 js2-WHILE
5102 js2-WITH
5103 js2-WITHEXPR
5104 js2-YIELD))
5105 (aset tokens tt t))
5106 (if js2-instanceof-has-side-effects
5107 (aset tokens js2-INSTANCEOF t))
5108 tokens))
5109
5110 (defun js2-node-has-side-effects (node)
5111 "Return t if NODE has side effects."
5112 (when node ; makes it easier to handle malformed expressions
5113 (let ((tt (js2-node-type node)))
5114 (cond
5115 ;; This doubtless needs some work, since EXPR_VOID is used
5116 ;; in several ways in Rhino and I may not have caught them all.
5117 ;; I'll wait for people to notice incorrect warnings.
5118 ((and (= tt js2-EXPR_VOID)
5119 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5120 (let ((expr (js2-expr-stmt-node-expr node)))
5121 (or (js2-node-has-side-effects expr)
5122 (when (js2-string-node-p expr)
5123 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5124 ((= tt js2-COMMA)
5125 (js2-node-has-side-effects (js2-infix-node-right node)))
5126 ((or (= tt js2-AND)
5127 (= tt js2-OR))
5128 (or (js2-node-has-side-effects (js2-infix-node-right node))
5129 (js2-node-has-side-effects (js2-infix-node-left node))))
5130 ((= tt js2-HOOK)
5131 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5132 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5133 ((js2-paren-node-p node)
5134 (js2-node-has-side-effects (js2-paren-node-expr node)))
5135 ((= tt js2-ERROR) ; avoid cascaded error messages
5136 nil)
5137 (t
5138 (aref js2-side-effecting-tokens tt))))))
5139
5140 (defconst js2-stmt-node-types
5141 (list js2-BLOCK
5142 js2-BREAK
5143 js2-CONTINUE
5144 js2-DEFAULT ; e4x "default xml namespace" statement
5145 js2-DO
5146 js2-EXPORT
5147 js2-EXPR_RESULT
5148 js2-EXPR_VOID
5149 js2-FOR
5150 js2-IF
5151 js2-IMPORT
5152 js2-RETURN
5153 js2-SWITCH
5154 js2-THROW
5155 js2-TRY
5156 js2-WHILE
5157 js2-WITH)
5158 "Node types that only appear in statement contexts.
5159 The list does not include nodes that always appear as the child
5160 of another specific statement type, such as switch-cases,
5161 catch and finally blocks, and else-clauses. The list also excludes
5162 nodes like yield, let and var, which may appear in either expression
5163 or statement context, and in the latter context always have a
5164 `js2-expr-stmt-node' parent. Finally, the list does not include
5165 functions or scripts, which are treated separately from statements
5166 by the JavaScript parser and runtime.")
5167
5168 (defun js2-stmt-node-p (node)
5169 "Heuristic for figuring out if NODE is a statement.
5170 Some node types can appear in either an expression context or a
5171 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5172 For these node types in a statement context, the parent will be a
5173 `js2-expr-stmt-node'.
5174 Functions aren't included in the check."
5175 (memq (js2-node-type node) js2-stmt-node-types))
5176
5177 (defun js2-mode-find-first-stmt (node)
5178 "Search upward starting from NODE looking for a statement.
5179 For purposes of this function, a `js2-function-node' counts."
5180 (while (not (or (js2-stmt-node-p node)
5181 (js2-function-node-p node)))
5182 (setq node (js2-node-parent node)))
5183 node)
5184
5185 (defun js2-node-parent-stmt (node)
5186 "Return the node's first ancestor that is a statement.
5187 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5188 appearing in a statement context will have a parent that is a
5189 `js2-expr-stmt-node' that will be returned by this function."
5190 (let ((parent (js2-node-parent node)))
5191 (if (or (null parent)
5192 (js2-stmt-node-p parent)
5193 (and (js2-function-node-p parent)
5194 (not (eq (js2-function-node-form parent)
5195 'FUNCTION_EXPRESSION))))
5196 parent
5197 (js2-node-parent-stmt parent))))
5198
5199 ;; In the Mozilla Rhino sources, Roshan James writes:
5200 ;; Does consistent-return analysis on the function body when strict mode is
5201 ;; enabled.
5202 ;;
5203 ;; function (x) { return (x+1) }
5204 ;;
5205 ;; is ok, but
5206 ;;
5207 ;; function (x) { if (x < 0) return (x+1); }
5208 ;;
5209 ;; is not because the function can potentially return a value when the
5210 ;; condition is satisfied and if not, the function does not explicitly
5211 ;; return a value.
5212 ;;
5213 ;; This extends to checking mismatches such as "return" and "return <value>"
5214 ;; used in the same function. Warnings are not emitted if inconsistent
5215 ;; returns exist in code that can be statically shown to be unreachable.
5216 ;; Ex.
5217 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5218 ;;
5219 ;; emits no warning. However if the loop had a break statement, then a
5220 ;; warning would be emitted.
5221 ;;
5222 ;; The consistency analysis looks at control structures such as loops, ifs,
5223 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5224 ;; warns the user about an inconsistent set of termination possibilities.
5225 ;;
5226 ;; These flags enumerate the possible ways a statement/function can
5227 ;; terminate. These flags are used by endCheck() and by the Parser to
5228 ;; detect inconsistent return usage.
5229 ;;
5230 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5231 ;; able to execute (example: throw, continue)
5232 ;;
5233 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5234 ;; next one. Statement such as return dont. A compound statement may have
5235 ;; some branch that drops off control to the next statement.
5236 ;;
5237 ;; END_RETURNS indicates that the statement can return with no value.
5238 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5239 ;;
5240 ;; A compound statement such as
5241 ;; if (condition) {
5242 ;; return value;
5243 ;; }
5244 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5245
5246 (defconst js2-END_UNREACHED 0)
5247 (defconst js2-END_DROPS_OFF 1)
5248 (defconst js2-END_RETURNS 2)
5249 (defconst js2-END_RETURNS_VALUE 4)
5250 (defconst js2-END_YIELDS 8)
5251
5252 (defun js2-has-consistent-return-usage (node)
5253 "Check that every return usage in a function body is consistent.
5254 Returns t if the function satisfies strict mode requirement."
5255 (let ((n (js2-end-check node)))
5256 ;; either it doesn't return a value in any branch...
5257 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5258 ;; or it returns a value (or is unreached) at every branch
5259 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5260 js2-END_RETURNS
5261 js2-END_YIELDS)))))
5262
5263 (defun js2-end-check-if (node)
5264 "Ensure that return usage in then/else blocks is consistent.
5265 If there is no else block, then the return statement can fall through.
5266 Returns logical OR of END_* flags"
5267 (let ((th (js2-if-node-then-part node))
5268 (el (js2-if-node-else-part node)))
5269 (if (null th)
5270 js2-END_UNREACHED
5271 (logior (js2-end-check th) (if el
5272 (js2-end-check el)
5273 js2-END_DROPS_OFF)))))
5274
5275 (defun js2-end-check-switch (node)
5276 "Consistency of return statements is checked between the case statements.
5277 If there is no default, then the switch can fall through. If there is a
5278 default, we check to see if all code paths in the default return or if
5279 there is a code path that can fall through.
5280 Returns logical OR of END_* flags."
5281 (let ((rv js2-END_UNREACHED)
5282 default-case)
5283 ;; examine the cases
5284 (catch 'break
5285 (dolist (c (js2-switch-node-cases node))
5286 (if (js2-case-node-expr c)
5287 (js2-set-flag rv (js2-end-check-block c))
5288 (setq default-case c)
5289 (throw 'break nil))))
5290 ;; we don't care how the cases drop into each other
5291 (js2-clear-flag rv js2-END_DROPS_OFF)
5292 ;; examine the default
5293 (js2-set-flag rv (if default-case
5294 (js2-end-check default-case)
5295 js2-END_DROPS_OFF))
5296 rv))
5297
5298 (defun js2-end-check-try (node)
5299 "If the block has a finally, return consistency is checked in the
5300 finally block. If all code paths in the finally return, then the
5301 returns in the try-catch blocks don't matter. If there is a code path
5302 that does not return or if there is no finally block, the returns
5303 of the try and catch blocks are checked for mismatch.
5304 Returns logical OR of END_* flags."
5305 (let ((finally (js2-try-node-finally-block node))
5306 rv)
5307 ;; check the finally if it exists
5308 (setq rv (if finally
5309 (js2-end-check (js2-finally-node-body finally))
5310 js2-END_DROPS_OFF))
5311 ;; If the finally block always returns, then none of the returns
5312 ;; in the try or catch blocks matter.
5313 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5314 (js2-clear-flag rv js2-END_DROPS_OFF)
5315 ;; examine the try block
5316 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5317 ;; check each catch block
5318 (dolist (cb (js2-try-node-catch-clauses node))
5319 (js2-set-flag rv (js2-end-check cb))))
5320 rv))
5321
5322 (defun js2-end-check-loop (node)
5323 "Return statement in the loop body must be consistent.
5324 The default assumption for any kind of a loop is that it will eventually
5325 terminate. The only exception is a loop with a constant true condition.
5326 Code that follows such a loop is examined only if one can determine
5327 statically that there is a break out of the loop.
5328
5329 for(... ; ... ; ...) {}
5330 for(... in ... ) {}
5331 while(...) { }
5332 do { } while(...)
5333
5334 Returns logical OR of END_* flags."
5335 (let ((rv (js2-end-check (js2-loop-node-body node)))
5336 (condition (cond
5337 ((js2-while-node-p node)
5338 (js2-while-node-condition node))
5339 ((js2-do-node-p node)
5340 (js2-do-node-condition node))
5341 ((js2-for-node-p node)
5342 (js2-for-node-condition node)))))
5343
5344 ;; check to see if the loop condition is always true
5345 (if (and condition
5346 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5347 (js2-clear-flag rv js2-END_DROPS_OFF))
5348
5349 ;; look for effect of breaks
5350 (js2-set-flag rv (js2-node-get-prop node
5351 'CONTROL_BLOCK_PROP
5352 js2-END_UNREACHED))
5353 rv))
5354
5355 (defun js2-end-check-block (node)
5356 "A general block of code is examined statement by statement.
5357 If any statement (even a compound one) returns in all branches, then
5358 subsequent statements are not examined.
5359 Returns logical OR of END_* flags."
5360 (let* ((rv js2-END_DROPS_OFF)
5361 (kids (js2-block-node-kids node))
5362 (n (car kids)))
5363 ;; Check each statment. If the statement can continue onto the next
5364 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5365 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5366 (js2-clear-flag rv js2-END_DROPS_OFF)
5367 (js2-set-flag rv (js2-end-check n))
5368 (setq kids (cdr kids)
5369 n (car kids)))
5370 rv))
5371
5372 (defun js2-end-check-label (node)
5373 "A labeled statement implies that there may be a break to the label.
5374 The function processes the labeled statement and then checks the
5375 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5376 particular label.
5377 Returns logical OR of END_* flags."
5378 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5379 (logior rv (js2-node-get-prop node
5380 'CONTROL_BLOCK_PROP
5381 js2-END_UNREACHED))))
5382
5383 (defun js2-end-check-break (node)
5384 "When a break is encountered annotate the statement being broken
5385 out of by setting its CONTROL_BLOCK_PROP property.
5386 Returns logical OR of END_* flags."
5387 (and (js2-break-node-target node)
5388 (js2-node-set-prop (js2-break-node-target node)
5389 'CONTROL_BLOCK_PROP
5390 js2-END_DROPS_OFF))
5391 js2-END_UNREACHED)
5392
5393 (defun js2-end-check (node)
5394 "Examine the body of a function, doing a basic reachability analysis.
5395 Returns a combination of flags END_* flags that indicate
5396 how the function execution can terminate. These constitute only the
5397 pessimistic set of termination conditions. It is possible that at
5398 runtime certain code paths will never be actually taken. Hence this
5399 analysis will flag errors in cases where there may not be errors.
5400 Returns logical OR of END_* flags"
5401 (let (kid)
5402 (cond
5403 ((js2-break-node-p node)
5404 (js2-end-check-break node))
5405 ((js2-expr-stmt-node-p node)
5406 (if (setq kid (js2-expr-stmt-node-expr node))
5407 (js2-end-check kid)
5408 js2-END_DROPS_OFF))
5409 ((or (js2-continue-node-p node)
5410 (js2-throw-node-p node))
5411 js2-END_UNREACHED)
5412 ((js2-return-node-p node)
5413 (if (setq kid (js2-return-node-retval node))
5414 js2-END_RETURNS_VALUE
5415 js2-END_RETURNS))
5416 ((js2-loop-node-p node)
5417 (js2-end-check-loop node))
5418 ((js2-switch-node-p node)
5419 (js2-end-check-switch node))
5420 ((js2-labeled-stmt-node-p node)
5421 (js2-end-check-label node))
5422 ((js2-if-node-p node)
5423 (js2-end-check-if node))
5424 ((js2-try-node-p node)
5425 (js2-end-check-try node))
5426 ((js2-block-node-p node)
5427 (if (null (js2-block-node-kids node))
5428 js2-END_DROPS_OFF
5429 (js2-end-check-block node)))
5430 ((js2-yield-node-p node)
5431 js2-END_YIELDS)
5432 (t
5433 js2-END_DROPS_OFF))))
5434
5435 (defun js2-always-defined-boolean-p (node)
5436 "Check if NODE always evaluates to true or false in boolean context.
5437 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5438 nor always false."
5439 (let ((tt (js2-node-type node))
5440 num)
5441 (cond
5442 ((or (= tt js2-FALSE) (= tt js2-NULL))
5443 'ALWAYS_FALSE)
5444 ((= tt js2-TRUE)
5445 'ALWAYS_TRUE)
5446 ((= tt js2-NUMBER)
5447 (setq num (js2-number-node-num-value node))
5448 (if (and (not (eq num 0.0e+NaN))
5449 (not (zerop num)))
5450 'ALWAYS_TRUE
5451 'ALWAYS_FALSE))
5452 (t
5453 nil))))
5454
5455 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5456 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5457
5458 (defvar js2-tokens nil
5459 "List of all defined token names.") ; initialized in `js2-token-names'
5460
5461 (defconst js2-token-names
5462 (let* ((names (make-vector js2-num-tokens -1))
5463 (case-fold-search nil) ; only match js2-UPPER_CASE
5464 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5465 (loop for sym in syms
5466 for i from 0
5467 do
5468 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5469 (not (boundp sym)))
5470 (aset names (symbol-value sym) ; code, e.g. 152
5471 (downcase
5472 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5473 (push sym js2-tokens)))
5474 names)
5475 "Vector mapping int values to token string names, sans `js2-' prefix.")
5476
5477 (defun js2-tt-name (tok)
5478 "Return a string name for TOK, a token symbol or code.
5479 Signals an error if it's not a recognized token."
5480 (let ((code tok))
5481 (if (symbolp tok)
5482 (setq code (symbol-value tok)))
5483 (if (eq code -1)
5484 "ERROR"
5485 (if (and (numberp code)
5486 (not (minusp code))
5487 (< code js2-num-tokens))
5488 (aref js2-token-names code)
5489 (error "Invalid token: %s" code)))))
5490
5491 (defsubst js2-tt-sym (tok)
5492 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5493 (intern (js2-tt-name tok)))
5494
5495 (defconst js2-token-codes
5496 (let ((table (make-hash-table :test 'eq :size 256)))
5497 (loop for name across js2-token-names
5498 for sym = (intern (concat "js2-" (upcase name)))
5499 do
5500 (puthash sym (symbol-value sym) table))
5501 ;; clean up a few that are "wrong" in Rhino's token codes
5502 (puthash 'js2-DELETE js2-DELPROP table)
5503 table)
5504 "Hashtable mapping token type symbols to their bytecodes.")
5505
5506 (defsubst js2-tt-code (sym)
5507 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5508 (or (gethash sym js2-token-codes)
5509 (error "Invalid token symbol: %s " sym))) ; signal code bug
5510
5511 (defun js2-report-scan-error (msg &optional no-throw beg len)
5512 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5513 (js2-report-error msg nil
5514 (or beg (js2-current-token-beg))
5515 (or len (js2-current-token-len)))
5516 (unless no-throw
5517 (throw 'return js2-ERROR)))
5518
5519 (defun js2-set-string-from-buffer (token)
5520 "Set `string' and `end' slots for TOKEN, return the string."
5521 (setf (js2-token-end token) js2-ts-cursor
5522 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5523
5524 ;; TODO: could potentially avoid a lot of consing by allocating a
5525 ;; char buffer the way Rhino does.
5526 (defsubst js2-add-to-string (c)
5527 (push c js2-ts-string-buffer))
5528
5529 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5530 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5531 ;; any other character: when it's not part of the current token, we
5532 ;; unget it, allowing it to be read again by the following call.
5533 (defsubst js2-unget-char ()
5534 (decf js2-ts-cursor))
5535
5536 ;; Rhino distinguishes \r and \n line endings. We don't need to
5537 ;; because we only scan from Emacs buffers, which always use \n.
5538 (defun js2-get-char ()
5539 "Read and return the next character from the input buffer.
5540 Increments `js2-ts-lineno' if the return value is a newline char.
5541 Updates `js2-ts-cursor' to the point after the returned char.
5542 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5543 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5544 (let (c)
5545 ;; check for end of buffer
5546 (if (>= js2-ts-cursor (point-max))
5547 (setq js2-ts-hit-eof t
5548 js2-ts-cursor (1+ js2-ts-cursor)
5549 c js2-EOF_CHAR) ; return value
5550 ;; otherwise read next char
5551 (setq c (char-before (incf js2-ts-cursor)))
5552 ;; if we read a newline, update counters
5553 (if (= c ?\n)
5554 (setq js2-ts-line-start js2-ts-cursor
5555 js2-ts-lineno (1+ js2-ts-lineno)))
5556 ;; TODO: skip over format characters
5557 c)))
5558
5559 (defun js2-read-unicode-escape ()
5560 "Read a \\uNNNN sequence from the input.
5561 Assumes the ?\ and ?u have already been read.
5562 Returns the unicode character, or nil if it wasn't a valid character.
5563 Doesn't change the values of any scanner variables."
5564 ;; I really wish I knew a better way to do this, but I can't
5565 ;; find the Emacs function that takes a 16-bit int and converts
5566 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5567 ;; Have to first check that it's 4 hex characters or it may stop
5568 ;; the read early.
5569 (ignore-errors
5570 (let ((s (buffer-substring-no-properties js2-ts-cursor
5571 (+ 4 js2-ts-cursor))))
5572 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5573 (read (concat "?\\u" s))))))
5574
5575 (defun js2-match-char (test)
5576 "Consume and return next character if it matches TEST, a character.
5577 Returns nil and consumes nothing if TEST is not the next character."
5578 (let ((c (js2-get-char)))
5579 (if (eq c test)
5580 t
5581 (js2-unget-char)
5582 nil)))
5583
5584 (defun js2-peek-char ()
5585 (prog1
5586 (js2-get-char)
5587 (js2-unget-char)))
5588
5589 (defun js2-identifier-start-p (c)
5590 "Is C a valid start to an ES5 Identifier?
5591 See http://es5.github.io/#x7.6"
5592 (or
5593 (memq c '(?$ ?_))
5594 (memq (get-char-code-property c 'general-category)
5595 ;; Letters
5596 '(Lu Ll Lt Lm Lo Nl))))
5597
5598 (defun js2-identifier-part-p (c)
5599 "Is C a valid part of an ES5 Identifier?
5600 See http://es5.github.io/#x7.6"
5601 (or
5602 (memq c '(?$ ?_ ?\u200c ?\u200d))
5603 (memq (get-char-code-property c 'general-category)
5604 '(;; Letters
5605 Lu Ll Lt Lm Lo Nl
5606 ;; Combining Marks
5607 Mn Mc
5608 ;; Digits
5609 Nd
5610 ;; Connector Punctuation
5611 Pc))))
5612
5613 (defun js2-alpha-p (c)
5614 (cond ((and (<= ?A c) (<= c ?Z)) t)
5615 ((and (<= ?a c) (<= c ?z)) t)
5616 (t nil)))
5617
5618 (defsubst js2-digit-p (c)
5619 (and (<= ?0 c) (<= c ?9)))
5620
5621 (defun js2-js-space-p (c)
5622 (if (<= c 127)
5623 (memq c '(#x20 #x9 #xB #xC #xD))
5624 (or
5625 (eq c #xA0)
5626 ;; TODO: change this nil to check for Unicode space character
5627 nil)))
5628
5629 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5630
5631 (defun js2-skip-line ()
5632 "Skip to end of line."
5633 (while (not (memq (js2-get-char) js2-eol-chars)))
5634 (js2-unget-char)
5635 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5636 (setq js2-token-end js2-ts-cursor))
5637
5638 (defun js2-init-scanner (&optional buf line)
5639 "Create token stream for BUF starting on LINE.
5640 BUF defaults to `current-buffer' and LINE defaults to 1.
5641
5642 A buffer can only have one scanner active at a time, which yields
5643 dramatically simpler code than using a defstruct. If you need to
5644 have simultaneous scanners in a buffer, copy the regions to scan
5645 into temp buffers."
5646 (with-current-buffer (or buf (current-buffer))
5647 (setq js2-ts-dirty-line nil
5648 js2-ts-hit-eof nil
5649 js2-ts-line-start 0
5650 js2-ts-lineno (or line 1)
5651 js2-ts-line-end-char -1
5652 js2-ts-cursor (point-min)
5653 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5654 js2-ti-tokens-cursor 0
5655 js2-ti-lookahead 0
5656 js2-ts-is-xml-attribute nil
5657 js2-ts-xml-is-tag-content nil
5658 js2-ts-xml-open-tags-count 0
5659 js2-ts-string-buffer nil)))
5660
5661 ;; This function uses the cached op, string and number fields in
5662 ;; TokenStream; if getToken has been called since the passed token
5663 ;; was scanned, the op or string printed may be incorrect.
5664 (defun js2-token-to-string (token)
5665 ;; Not sure where this function is used in Rhino. Not tested.
5666 (if (not js2-debug-print-trees)
5667 ""
5668 (let ((name (js2-tt-name token)))
5669 (cond
5670 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5671 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5672 (concat name " `" (js2-current-token-string) "'"))
5673 ((eq token js2-NUMBER)
5674 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5675 (t
5676 name)))))
5677
5678 (defconst js2-keywords
5679 '(break
5680 case catch class const continue
5681 debugger default delete do
5682 else extends export
5683 false finally for function
5684 if in instanceof import
5685 let
5686 new null
5687 return
5688 static super switch
5689 this throw true try typeof
5690 var void
5691 while with
5692 yield))
5693
5694 ;; Token names aren't exactly the same as the keywords, unfortunately.
5695 ;; E.g. delete is js2-DELPROP.
5696 (defconst js2-kwd-tokens
5697 (let ((table (make-vector js2-num-tokens nil))
5698 (tokens
5699 (list js2-BREAK
5700 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5701 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5702 js2-ELSE js2-EXPORT
5703 js2-ELSE js2-EXTENDS js2-EXPORT
5704 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5705 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5706 js2-LET
5707 js2-NEW js2-NULL
5708 js2-RETURN
5709 js2-STATIC js2-SUPER js2-SWITCH
5710 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5711 js2-VAR
5712 js2-WHILE js2-WITH
5713 js2-YIELD)))
5714 (dolist (i tokens)
5715 (aset table i 'font-lock-keyword-face))
5716 (aset table js2-STRING 'font-lock-string-face)
5717 (aset table js2-REGEXP 'font-lock-string-face)
5718 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5719 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5720 (aset table js2-COMMENT 'font-lock-comment-face)
5721 (aset table js2-THIS 'font-lock-builtin-face)
5722 (aset table js2-SUPER 'font-lock-builtin-face)
5723 (aset table js2-VOID 'font-lock-constant-face)
5724 (aset table js2-NULL 'font-lock-constant-face)
5725 (aset table js2-TRUE 'font-lock-constant-face)
5726 (aset table js2-FALSE 'font-lock-constant-face)
5727 (aset table js2-NOT 'font-lock-negation-char-face)
5728 table)
5729 "Vector whose values are non-nil for tokens that are keywords.
5730 The values are default faces to use for highlighting the keywords.")
5731
5732 ;; FIXME: Support strict mode-only future reserved words, after we know
5733 ;; which parts scopes are in strict mode, and which are not.
5734 (defconst js2-reserved-words '(class enum export extends import super)
5735 "Future reserved keywords in ECMAScript 5.1.")
5736
5737 (defconst js2-keyword-names
5738 (let ((table (make-hash-table :test 'equal)))
5739 (loop for k in js2-keywords
5740 do (puthash
5741 (symbol-name k) ; instanceof
5742 (intern (concat "js2-"
5743 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5744 table))
5745 table)
5746 "JavaScript keywords by name, mapped to their symbols.")
5747
5748 (defconst js2-reserved-word-names
5749 (let ((table (make-hash-table :test 'equal)))
5750 (loop for k in js2-reserved-words
5751 do
5752 (puthash (symbol-name k) 'js2-RESERVED table))
5753 table)
5754 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5755
5756 (defun js2-collect-string (buf)
5757 "Convert BUF, a list of chars, to a string.
5758 Reverses BUF before converting."
5759 (if buf
5760 (apply #'string (nreverse buf))
5761 ""))
5762
5763 (defun js2-string-to-keyword (s)
5764 "Return token for S, a string, if S is a keyword or reserved word.
5765 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5766 (or (gethash s js2-keyword-names)
5767 (gethash s js2-reserved-word-names)))
5768
5769 (defsubst js2-ts-set-char-token-bounds (token)
5770 "Used when next token is one character."
5771 (setf (js2-token-beg token) (1- js2-ts-cursor)
5772 (js2-token-end token) js2-ts-cursor))
5773
5774 (defsubst js2-ts-return (token type)
5775 "Update the `end' and `type' slots of TOKEN,
5776 then throw `return' with value TYPE."
5777 (setf (js2-token-end token) js2-ts-cursor
5778 (js2-token-type token) type)
5779 (throw 'return type))
5780
5781 (defun js2-x-digit-to-int (c accumulator)
5782 "Build up a hex number.
5783 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5784 corresponding number. Otherwise return -1."
5785 (catch 'return
5786 (catch 'check
5787 ;; Use 0..9 < A..Z < a..z
5788 (cond
5789 ((<= c ?9)
5790 (decf c ?0)
5791 (if (<= 0 c)
5792 (throw 'check nil)))
5793 ((<= c ?F)
5794 (when (<= ?A c)
5795 (decf c (- ?A 10))
5796 (throw 'check nil)))
5797 ((<= c ?f)
5798 (when (<= ?a c)
5799 (decf c (- ?a 10))
5800 (throw 'check nil))))
5801 (throw 'return -1))
5802 (logior c (lsh accumulator 4))))
5803
5804 (defun js2-get-token (&optional modifier)
5805 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5806 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5807 next saved token.
5808
5809 This function will not return a newline (js2-EOL) - instead, it
5810 gobbles newlines until it finds a non-newline token. Call
5811 `js2-peek-token-or-eol' when you care about newlines.
5812
5813 This function will also not return a js2-COMMENT. Instead, it
5814 records comments found in `js2-scanned-comments'. If the token
5815 returned by this function immediately follows a jsdoc comment,
5816 the token is flagged as such."
5817 (if (zerop js2-ti-lookahead)
5818 (js2-get-token-internal modifier)
5819 (decf js2-ti-lookahead)
5820 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5821 (let ((tt (js2-current-token-type)))
5822 (assert (not (= tt js2-EOL)))
5823 tt)))
5824
5825 (defun js2-unget-token ()
5826 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5827 (incf js2-ti-lookahead)
5828 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5829
5830 (defun js2-get-token-internal (modifier)
5831 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5832 (tt (js2-token-type token))
5833 saw-eol
5834 face)
5835 ;; process comments
5836 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5837 (if (= tt js2-EOL)
5838 (setq saw-eol t)
5839 (setq saw-eol nil)
5840 (when js2-record-comments
5841 (js2-record-comment token)))
5842 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5843 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5844 tt (js2-token-type token)))
5845
5846 (when saw-eol
5847 (setf (js2-token-follows-eol-p token) t))
5848
5849 ;; perform lexical fontification as soon as token is scanned
5850 (when js2-parse-ide-mode
5851 (cond
5852 ((minusp tt)
5853 (js2-record-face 'js2-error token))
5854 ((setq face (aref js2-kwd-tokens tt))
5855 (js2-record-face face token))
5856 ((and (= tt js2-NAME)
5857 (equal (js2-token-string token) "undefined"))
5858 (js2-record-face 'font-lock-constant-face token))))
5859 tt))
5860
5861 (defun js2-get-token-internal-1 (modifier)
5862 "Return next JavaScript token type, an int such as js2-RETURN.
5863 During operation, creates an instance of `js2-token' struct, sets
5864 its relevant fields and puts it into `js2-ti-tokens'."
5865 (let (c c1 identifier-start is-unicode-escape-start
5866 contains-escape escape-val str result base
5867 quote-char val look-for-slash continue tt
5868 (token (js2-new-token 0)))
5869 (setq
5870 tt
5871 (catch 'return
5872 (when (eq modifier 'TEMPLATE_TAIL)
5873 (setf (js2-token-beg token) (1- js2-ts-cursor))
5874 (throw 'return (js2-get-string-or-template-token ?` token)))
5875 (while t
5876 ;; Eat whitespace, possibly sensitive to newlines.
5877 (setq continue t)
5878 (while continue
5879 (setq c (js2-get-char))
5880 (cond
5881 ((eq c js2-EOF_CHAR)
5882 (js2-unget-char)
5883 (js2-ts-set-char-token-bounds token)
5884 (throw 'return js2-EOF))
5885 ((eq c ?\n)
5886 (js2-ts-set-char-token-bounds token)
5887 (setq js2-ts-dirty-line nil)
5888 (throw 'return js2-EOL))
5889 ((not (js2-js-space-p c))
5890 (if (/= c ?-) ; in case end of HTML comment
5891 (setq js2-ts-dirty-line t))
5892 (setq continue nil))))
5893 ;; Assume the token will be 1 char - fixed up below.
5894 (js2-ts-set-char-token-bounds token)
5895 (when (eq c ?@)
5896 (throw 'return js2-XMLATTR))
5897 ;; identifier/keyword/instanceof?
5898 ;; watch out for starting with a <backslash>
5899 (cond
5900 ((eq c ?\\)
5901 (setq c (js2-get-char))
5902 (if (eq c ?u)
5903 (setq identifier-start t
5904 is-unicode-escape-start t
5905 js2-ts-string-buffer nil)
5906 (setq identifier-start nil)
5907 (js2-unget-char)
5908 (setq c ?\\)))
5909 (t
5910 (when (setq identifier-start (js2-identifier-start-p c))
5911 (setq js2-ts-string-buffer nil)
5912 (js2-add-to-string c))))
5913 (when identifier-start
5914 (setq contains-escape is-unicode-escape-start)
5915 (catch 'break
5916 (while t
5917 (if is-unicode-escape-start
5918 ;; strictly speaking we should probably push-back
5919 ;; all the bad characters if the <backslash>uXXXX
5920 ;; sequence is malformed. But since there isn't a
5921 ;; correct context(is there?) for a bad Unicode
5922 ;; escape sequence in an identifier, we can report
5923 ;; an error here.
5924 (progn
5925 (setq escape-val 0)
5926 (dotimes (_ 4)
5927 (setq c (js2-get-char)
5928 escape-val (js2-x-digit-to-int c escape-val))
5929 ;; Next check takes care of c < 0 and bad escape
5930 (if (minusp escape-val)
5931 (throw 'break nil)))
5932 (if (minusp escape-val)
5933 (js2-report-scan-error "msg.invalid.escape" t))
5934 (js2-add-to-string escape-val)
5935 (setq is-unicode-escape-start nil))
5936 (setq c (js2-get-char))
5937 (cond
5938 ((eq c ?\\)
5939 (setq c (js2-get-char))
5940 (if (eq c ?u)
5941 (setq is-unicode-escape-start t
5942 contains-escape t)
5943 (js2-report-scan-error "msg.illegal.character" t)))
5944 (t
5945 (if (or (eq c js2-EOF_CHAR)
5946 (not (js2-identifier-part-p c)))
5947 (throw 'break nil))
5948 (js2-add-to-string c))))))
5949 (js2-unget-char)
5950 (setf str (js2-collect-string js2-ts-string-buffer)
5951 (js2-token-end token) js2-ts-cursor)
5952 ;; FIXME: Invalid in ES5 and ES6, see
5953 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5954 ;; Probably should just drop this conditional.
5955 (unless contains-escape
5956 ;; OPT we shouldn't have to make a string (object!) to
5957 ;; check if it's a keyword.
5958 ;; Return the corresponding token if it's a keyword
5959 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5960 (setq result (js2-string-to-keyword str)))
5961 (if (and (< js2-language-version 170)
5962 (memq result '(js2-LET js2-YIELD)))
5963 ;; LET and YIELD are tokens only in 1.7 and later
5964 (setq result 'js2-NAME))
5965 (when (eq result 'js2-RESERVED)
5966 (setf (js2-token-string token) str))
5967 (throw 'return (js2-tt-code result))))
5968 ;; If we want to intern these as Rhino does, just use (intern str)
5969 (setf (js2-token-string token) str)
5970 (throw 'return js2-NAME)) ; end identifier/kwd check
5971 ;; is it a number?
5972 (when (or (js2-digit-p c)
5973 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5974 (setq js2-ts-string-buffer nil
5975 base 10)
5976 (when (eq c ?0)
5977 (setq c (js2-get-char))
5978 (cond
5979 ((or (eq c ?x) (eq c ?X))
5980 (setq base 16)
5981 (setq c (js2-get-char)))
5982 ((and (or (eq c ?b) (eq c ?B))
5983 (>= js2-language-version 200))
5984 (setq base 2)
5985 (setq c (js2-get-char)))
5986 ((and (or (eq c ?o) (eq c ?O))
5987 (>= js2-language-version 200))
5988 (setq base 8)
5989 (setq c (js2-get-char)))
5990 ((js2-digit-p c)
5991 (setq base 'maybe-8))
5992 (t
5993 (js2-add-to-string ?0))))
5994 (cond
5995 ((eq base 16)
5996 (if (> 0 (js2-x-digit-to-int c 0))
5997 (js2-report-scan-error "msg.missing.hex.digits")
5998 (while (<= 0 (js2-x-digit-to-int c 0))
5999 (js2-add-to-string c)
6000 (setq c (js2-get-char)))))
6001 ((eq base 2)
6002 (if (not (memq c '(?0 ?1)))
6003 (js2-report-scan-error "msg.missing.binary.digits")
6004 (while (memq c '(?0 ?1))
6005 (js2-add-to-string c)
6006 (setq c (js2-get-char)))))
6007 ((eq base 8)
6008 (if (or (> ?0 c) (< ?7 c))
6009 (js2-report-scan-error "msg.missing.octal.digits")
6010 (while (and (<= ?0 c) (>= ?7 c))
6011 (js2-add-to-string c)
6012 (setq c (js2-get-char)))))
6013 (t
6014 (while (and (<= ?0 c) (<= c ?9))
6015 ;; We permit 08 and 09 as decimal numbers, which
6016 ;; makes our behavior a superset of the ECMA
6017 ;; numeric grammar. We might not always be so
6018 ;; permissive, so we warn about it.
6019 (when (and (eq base 'maybe-8) (>= c ?8))
6020 (js2-report-warning "msg.bad.octal.literal"
6021 (if (eq c ?8) "8" "9"))
6022 (setq base 10))
6023 (js2-add-to-string c)
6024 (setq c (js2-get-char)))
6025 (when (eq base 'maybe-8)
6026 (setq base 8))))
6027 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6028 (when (eq c ?.)
6029 (loop do
6030 (js2-add-to-string c)
6031 (setq c (js2-get-char))
6032 while (js2-digit-p c)))
6033 (when (memq c '(?e ?E))
6034 (js2-add-to-string c)
6035 (setq c (js2-get-char))
6036 (when (memq c '(?+ ?-))
6037 (js2-add-to-string c)
6038 (setq c (js2-get-char)))
6039 (unless (js2-digit-p c)
6040 (js2-report-scan-error "msg.missing.exponent" t))
6041 (loop do
6042 (js2-add-to-string c)
6043 (setq c (js2-get-char))
6044 while (js2-digit-p c))))
6045 (js2-unget-char)
6046 (let ((str (js2-set-string-from-buffer token)))
6047 (setf (js2-token-number token)
6048 (js2-string-to-number str base)))
6049 (throw 'return js2-NUMBER))
6050 ;; is it a string?
6051 (when (or (memq c '(?\" ?\'))
6052 (and (>= js2-language-version 200)
6053 (= c ?`)))
6054 (throw 'return
6055 (js2-get-string-or-template-token c token)))
6056 (js2-ts-return token
6057 (case c
6058 (?\;
6059 (throw 'return js2-SEMI))
6060 (?\[
6061 (throw 'return js2-LB))
6062 (?\]
6063 (throw 'return js2-RB))
6064 (?{
6065 (throw 'return js2-LC))
6066 (?}
6067 (throw 'return js2-RC))
6068 (?\(
6069 (throw 'return js2-LP))
6070 (?\)
6071 (throw 'return js2-RP))
6072 (?,
6073 (throw 'return js2-COMMA))
6074 (??
6075 (throw 'return js2-HOOK))
6076 (?:
6077 (if (js2-match-char ?:)
6078 js2-COLONCOLON
6079 (throw 'return js2-COLON)))
6080 (?.
6081 (if (js2-match-char ?.)
6082 (if (js2-match-char ?.)
6083 js2-TRIPLEDOT js2-DOTDOT)
6084 (if (js2-match-char ?\()
6085 js2-DOTQUERY
6086 (throw 'return js2-DOT))))
6087 (?|
6088 (if (js2-match-char ?|)
6089 (throw 'return js2-OR)
6090 (if (js2-match-char ?=)
6091 js2-ASSIGN_BITOR
6092 (throw 'return js2-BITOR))))
6093 (?^
6094 (if (js2-match-char ?=)
6095 js2-ASSIGN_BITOR
6096 (throw 'return js2-BITXOR)))
6097 (?&
6098 (if (js2-match-char ?&)
6099 (throw 'return js2-AND)
6100 (if (js2-match-char ?=)
6101 js2-ASSIGN_BITAND
6102 (throw 'return js2-BITAND))))
6103 (?=
6104 (if (js2-match-char ?=)
6105 (if (js2-match-char ?=)
6106 js2-SHEQ
6107 (throw 'return js2-EQ))
6108 (if (js2-match-char ?>)
6109 (js2-ts-return token js2-ARROW)
6110 (throw 'return js2-ASSIGN))))
6111 (?!
6112 (if (js2-match-char ?=)
6113 (if (js2-match-char ?=)
6114 js2-SHNE
6115 js2-NE)
6116 (throw 'return js2-NOT)))
6117 (?<
6118 ;; NB:treat HTML begin-comment as comment-till-eol
6119 (when (js2-match-char ?!)
6120 (when (js2-match-char ?-)
6121 (when (js2-match-char ?-)
6122 (js2-skip-line)
6123 (setf (js2-token-comment-type (js2-current-token)) 'html)
6124 (throw 'return js2-COMMENT)))
6125 (js2-unget-char))
6126 (if (js2-match-char ?<)
6127 (if (js2-match-char ?=)
6128 js2-ASSIGN_LSH
6129 js2-LSH)
6130 (if (js2-match-char ?=)
6131 js2-LE
6132 (throw 'return js2-LT))))
6133 (?>
6134 (if (js2-match-char ?>)
6135 (if (js2-match-char ?>)
6136 (if (js2-match-char ?=)
6137 js2-ASSIGN_URSH
6138 js2-URSH)
6139 (if (js2-match-char ?=)
6140 js2-ASSIGN_RSH
6141 js2-RSH))
6142 (if (js2-match-char ?=)
6143 js2-GE
6144 (throw 'return js2-GT))))
6145 (?*
6146 (if (js2-match-char ?=)
6147 js2-ASSIGN_MUL
6148 (throw 'return js2-MUL)))
6149 (?/
6150 ;; is it a // comment?
6151 (when (js2-match-char ?/)
6152 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6153 (js2-skip-line)
6154 (setf (js2-token-comment-type token) 'line)
6155 ;; include newline so highlighting goes to end of window
6156 (incf (js2-token-end token))
6157 (throw 'return js2-COMMENT))
6158 ;; is it a /* comment?
6159 (when (js2-match-char ?*)
6160 (setf look-for-slash nil
6161 (js2-token-beg token) (- js2-ts-cursor 2)
6162 (js2-token-comment-type token)
6163 (if (js2-match-char ?*)
6164 (progn
6165 (setq look-for-slash t)
6166 'jsdoc)
6167 'block))
6168 (while t
6169 (setq c (js2-get-char))
6170 (cond
6171 ((eq c js2-EOF_CHAR)
6172 (setf (js2-token-end token) (1- js2-ts-cursor))
6173 (js2-report-error "msg.unterminated.comment")
6174 (throw 'return js2-COMMENT))
6175 ((eq c ?*)
6176 (setq look-for-slash t))
6177 ((eq c ?/)
6178 (if look-for-slash
6179 (js2-ts-return token js2-COMMENT)))
6180 (t
6181 (setf look-for-slash nil
6182 (js2-token-end token) js2-ts-cursor)))))
6183 (if (js2-match-char ?=)
6184 js2-ASSIGN_DIV
6185 (throw 'return js2-DIV)))
6186 (?#
6187 (when js2-skip-preprocessor-directives
6188 (js2-skip-line)
6189 (setf (js2-token-comment-type token) 'preprocessor
6190 (js2-token-end token) js2-ts-cursor)
6191 (throw 'return js2-COMMENT))
6192 (throw 'return js2-ERROR))
6193 (?%
6194 (if (js2-match-char ?=)
6195 js2-ASSIGN_MOD
6196 (throw 'return js2-MOD)))
6197 (?~
6198 (throw 'return js2-BITNOT))
6199 (?+
6200 (if (js2-match-char ?=)
6201 js2-ASSIGN_ADD
6202 (if (js2-match-char ?+)
6203 js2-INC
6204 (throw 'return js2-ADD))))
6205 (?-
6206 (cond
6207 ((js2-match-char ?=)
6208 (setq c js2-ASSIGN_SUB))
6209 ((js2-match-char ?-)
6210 (unless js2-ts-dirty-line
6211 ;; treat HTML end-comment after possible whitespace
6212 ;; after line start as comment-until-eol
6213 (when (js2-match-char ?>)
6214 (js2-skip-line)
6215 (setf (js2-token-comment-type (js2-current-token)) 'html)
6216 (throw 'return js2-COMMENT)))
6217 (setq c js2-DEC))
6218 (t
6219 (setq c js2-SUB)))
6220 (setq js2-ts-dirty-line t)
6221 c)
6222 (otherwise
6223 (js2-report-scan-error "msg.illegal.character")))))))
6224 (setf (js2-token-type token) tt)
6225 token))
6226
6227 (defun js2-get-string-or-template-token (quote-char token)
6228 ;; We attempt to accumulate a string the fast way, by
6229 ;; building it directly out of the reader. But if there
6230 ;; are any escaped characters in the string, we revert to
6231 ;; building it out of a string buffer.
6232 (let ((c (js2-get-char))
6233 js2-ts-string-buffer
6234 nc)
6235 (catch 'break
6236 (while (/= c quote-char)
6237 (catch 'continue
6238 (when (eq c js2-EOF_CHAR)
6239 (js2-unget-char)
6240 (js2-report-error "msg.unterminated.string.lit")
6241 (throw 'break nil))
6242 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6243 (js2-unget-char)
6244 (js2-report-error "msg.unterminated.string.lit")
6245 (throw 'break nil))
6246 (when (eq c ?\\)
6247 ;; We've hit an escaped character
6248 (setq c (js2-get-char))
6249 (case c
6250 (?b (setq c ?\b))
6251 (?f (setq c ?\f))
6252 (?n (setq c ?\n))
6253 (?r (setq c ?\r))
6254 (?t (setq c ?\t))
6255 (?v (setq c ?\v))
6256 (?u
6257 (setq c1 (js2-read-unicode-escape))
6258 (if js2-parse-ide-mode
6259 (if c1
6260 (progn
6261 ;; just copy the string in IDE-mode
6262 (js2-add-to-string ?\\)
6263 (js2-add-to-string ?u)
6264 (dotimes (_ 3)
6265 (js2-add-to-string (js2-get-char)))
6266 (setq c (js2-get-char))) ; added at end of loop
6267 ;; flag it as an invalid escape
6268 (js2-report-warning "msg.invalid.escape"
6269 nil (- js2-ts-cursor 2) 6))
6270 ;; Get 4 hex digits; if the u escape is not
6271 ;; followed by 4 hex digits, use 'u' + the
6272 ;; literal character sequence that follows.
6273 (js2-add-to-string ?u)
6274 (setq escape-val 0)
6275 (dotimes (_ 4)
6276 (setq c (js2-get-char)
6277 escape-val (js2-x-digit-to-int c escape-val))
6278 (if (minusp escape-val)
6279 (throw 'continue nil))
6280 (js2-add-to-string c))
6281 ;; prepare for replace of stored 'u' sequence by escape value
6282 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6283 c escape-val)))
6284 (?x
6285 ;; Get 2 hex digits, defaulting to 'x'+literal
6286 ;; sequence, as above.
6287 (setq c (js2-get-char)
6288 escape-val (js2-x-digit-to-int c 0))
6289 (if (minusp escape-val)
6290 (progn
6291 (js2-add-to-string ?x)
6292 (throw 'continue nil))
6293 (setq c1 c
6294 c (js2-get-char)
6295 escape-val (js2-x-digit-to-int c escape-val))
6296 (if (minusp escape-val)
6297 (progn
6298 (js2-add-to-string ?x)
6299 (js2-add-to-string c1)
6300 (throw 'continue nil))
6301 ;; got 2 hex digits
6302 (setq c escape-val))))
6303 (?\n
6304 ;; Remove line terminator after escape to follow
6305 ;; SpiderMonkey and C/C++
6306 (setq c (js2-get-char))
6307 (throw 'continue nil))
6308 (t
6309 (when (and (<= ?0 c) (< c ?8))
6310 (setq val (- c ?0)
6311 c (js2-get-char))
6312 (when (and (<= ?0 c) (< c ?8))
6313 (setq val (- (+ (* 8 val) c) ?0)
6314 c (js2-get-char))
6315 (when (and (<= ?0 c)
6316 (< c ?8)
6317 (< val #o37))
6318 ;; c is 3rd char of octal sequence only
6319 ;; if the resulting val <= 0377
6320 (setq val (- (+ (* 8 val) c) ?0)
6321 c (js2-get-char))))
6322 (js2-unget-char)
6323 (setq c val)))))
6324 (when (and (eq quote-char ?`) (eq c ?$))
6325 (when (eq (setq nc (js2-get-char)) ?\{)
6326 (throw 'break nil))
6327 (js2-unget-char))
6328 (js2-add-to-string c)
6329 (setq c (js2-get-char)))))
6330 (js2-set-string-from-buffer token)
6331 (if (not (eq quote-char ?`))
6332 js2-STRING
6333 (if (and (eq c ?$) (eq nc ?\{))
6334 js2-TEMPLATE_HEAD
6335 js2-NO_SUBS_TEMPLATE))))
6336
6337 (defsubst js2-string-to-number (str base)
6338 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
6339 (condition-case nil
6340 (string-to-number str base)
6341 (overflow-error -1)))
6342
6343 (defun js2-read-regexp (start-tt)
6344 "Called by parser when it gets / or /= in literal context."
6345 (let (c err
6346 in-class ; inside a '[' .. ']' character-class
6347 flags
6348 (continue t)
6349 (token (js2-new-token 0)))
6350 (setq js2-ts-string-buffer nil)
6351 (if (eq start-tt js2-ASSIGN_DIV)
6352 ;; mis-scanned /=
6353 (js2-add-to-string ?=)
6354 (if (not (eq start-tt js2-DIV))
6355 (error "failed assertion")))
6356 (while (and (not err)
6357 (or (/= (setq c (js2-get-char)) ?/)
6358 in-class))
6359 (cond
6360 ((or (= c ?\n)
6361 (= c js2-EOF_CHAR))
6362 (setf (js2-token-end token) (1- js2-ts-cursor)
6363 err t
6364 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6365 (js2-report-error "msg.unterminated.re.lit"))
6366 (t (cond
6367 ((= c ?\\)
6368 (js2-add-to-string c)
6369 (setq c (js2-get-char)))
6370 ((= c ?\[)
6371 (setq in-class t))
6372 ((= c ?\])
6373 (setq in-class nil)))
6374 (js2-add-to-string c))))
6375 (unless err
6376 (while continue
6377 (cond
6378 ((js2-match-char ?g)
6379 (push ?g flags))
6380 ((js2-match-char ?i)
6381 (push ?i flags))
6382 ((js2-match-char ?m)
6383 (push ?m flags))
6384 ((and (js2-match-char ?u)
6385 (>= js2-language-version 200))
6386 (push ?u flags))
6387 ((and (js2-match-char ?y)
6388 (>= js2-language-version 200))
6389 (push ?y flags))
6390 (t
6391 (setq continue nil))))
6392 (if (js2-alpha-p (js2-peek-char))
6393 (js2-report-scan-error "msg.invalid.re.flag" t
6394 js2-ts-cursor 1))
6395 (js2-set-string-from-buffer token))
6396 (js2-collect-string flags)))
6397
6398 (defun js2-get-first-xml-token ()
6399 (setq js2-ts-xml-open-tags-count 0
6400 js2-ts-is-xml-attribute nil
6401 js2-ts-xml-is-tag-content nil)
6402 (js2-unget-char)
6403 (js2-get-next-xml-token))
6404
6405 (defun js2-xml-discard-string (token)
6406 "Throw away the string in progress and flag an XML parse error."
6407 (setf js2-ts-string-buffer nil
6408 (js2-token-string token) nil)
6409 (js2-report-scan-error "msg.XML.bad.form" t))
6410
6411 (defun js2-get-next-xml-token ()
6412 (setq js2-ts-string-buffer nil) ; for recording the XML
6413 (let ((token (js2-new-token 0))
6414 c result)
6415 (setq result
6416 (catch 'return
6417 (while t
6418 (setq c (js2-get-char))
6419 (cond
6420 ((= c js2-EOF_CHAR)
6421 (throw 'return js2-ERROR))
6422 (js2-ts-xml-is-tag-content
6423 (case c
6424 (?>
6425 (js2-add-to-string c)
6426 (setq js2-ts-xml-is-tag-content nil
6427 js2-ts-is-xml-attribute nil))
6428 (?/
6429 (js2-add-to-string c)
6430 (when (eq ?> (js2-peek-char))
6431 (setq c (js2-get-char))
6432 (js2-add-to-string c)
6433 (setq js2-ts-xml-is-tag-content nil)
6434 (decf js2-ts-xml-open-tags-count)))
6435 (?{
6436 (js2-unget-char)
6437 (js2-set-string-from-buffer token)
6438 (throw 'return js2-XML))
6439 ((?\' ?\")
6440 (js2-add-to-string c)
6441 (unless (js2-read-quoted-string c token)
6442 (throw 'return js2-ERROR)))
6443 (?=
6444 (js2-add-to-string c)
6445 (setq js2-ts-is-xml-attribute t))
6446 ((? ?\t ?\r ?\n)
6447 (js2-add-to-string c))
6448 (t
6449 (js2-add-to-string c)
6450 (setq js2-ts-is-xml-attribute nil)))
6451 (when (and (not js2-ts-xml-is-tag-content)
6452 (zerop js2-ts-xml-open-tags-count))
6453 (js2-set-string-from-buffer token)
6454 (throw 'return js2-XMLEND)))
6455 (t
6456 ;; else not tag content
6457 (case c
6458 (?<
6459 (js2-add-to-string c)
6460 (setq c (js2-peek-char))
6461 (case c
6462 (?!
6463 (setq c (js2-get-char)) ;; skip !
6464 (js2-add-to-string c)
6465 (setq c (js2-peek-char))
6466 (case c
6467 (?-
6468 (setq c (js2-get-char)) ;; skip -
6469 (js2-add-to-string c)
6470 (if (eq c ?-)
6471 (progn
6472 (js2-add-to-string c)
6473 (unless (js2-read-xml-comment token)
6474 (throw 'return js2-ERROR)))
6475 (js2-xml-discard-string token)
6476 (throw 'return js2-ERROR)))
6477 (?\[
6478 (setq c (js2-get-char)) ;; skip [
6479 (js2-add-to-string c)
6480 (if (and (= (js2-get-char) ?C)
6481 (= (js2-get-char) ?D)
6482 (= (js2-get-char) ?A)
6483 (= (js2-get-char) ?T)
6484 (= (js2-get-char) ?A)
6485 (= (js2-get-char) ?\[))
6486 (progn
6487 (js2-add-to-string ?C)
6488 (js2-add-to-string ?D)
6489 (js2-add-to-string ?A)
6490 (js2-add-to-string ?T)
6491 (js2-add-to-string ?A)
6492 (js2-add-to-string ?\[)
6493 (unless (js2-read-cdata token)
6494 (throw 'return js2-ERROR)))
6495 (js2-xml-discard-string token)
6496 (throw 'return js2-ERROR)))
6497 (t
6498 (unless (js2-read-entity token)
6499 (throw 'return js2-ERROR))))
6500 ;; Allow bare CDATA section, e.g.:
6501 ;; let xml = <![CDATA[ foo bar baz ]]>;
6502 (when (zerop js2-ts-xml-open-tags-count)
6503 (throw 'return js2-XMLEND)))
6504 (??
6505 (setq c (js2-get-char)) ;; skip ?
6506 (js2-add-to-string c)
6507 (unless (js2-read-PI token)
6508 (throw 'return js2-ERROR)))
6509 (?/
6510 ;; end tag
6511 (setq c (js2-get-char)) ;; skip /
6512 (js2-add-to-string c)
6513 (when (zerop js2-ts-xml-open-tags-count)
6514 (js2-xml-discard-string token)
6515 (throw 'return js2-ERROR))
6516 (setq js2-ts-xml-is-tag-content t)
6517 (decf js2-ts-xml-open-tags-count))
6518 (t
6519 ;; start tag
6520 (setq js2-ts-xml-is-tag-content t)
6521 (incf js2-ts-xml-open-tags-count))))
6522 (?{
6523 (js2-unget-char)
6524 (js2-set-string-from-buffer token)
6525 (throw 'return js2-XML))
6526 (t
6527 (js2-add-to-string c))))))))
6528 (setf (js2-token-end token) js2-ts-cursor)
6529 (setf (js2-token-type token) result)
6530 result))
6531
6532 (defun js2-read-quoted-string (quote token)
6533 (let (c)
6534 (catch 'return
6535 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6536 (js2-add-to-string c)
6537 (if (eq c quote)
6538 (throw 'return t)))
6539 (js2-xml-discard-string token) ;; throw away string in progress
6540 nil)))
6541
6542 (defun js2-read-xml-comment (token)
6543 (let ((c (js2-get-char)))
6544 (catch 'return
6545 (while (/= c js2-EOF_CHAR)
6546 (catch 'continue
6547 (js2-add-to-string c)
6548 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6549 (setq c (js2-get-char))
6550 (js2-add-to-string c)
6551 (if (eq (js2-peek-char) ?>)
6552 (progn
6553 (setq c (js2-get-char)) ;; skip >
6554 (js2-add-to-string c)
6555 (throw 'return t))
6556 (throw 'continue nil)))
6557 (setq c (js2-get-char))))
6558 (js2-xml-discard-string token)
6559 nil)))
6560
6561 (defun js2-read-cdata (token)
6562 (let ((c (js2-get-char)))
6563 (catch 'return
6564 (while (/= c js2-EOF_CHAR)
6565 (catch 'continue
6566 (js2-add-to-string c)
6567 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6568 (setq c (js2-get-char))
6569 (js2-add-to-string c)
6570 (if (eq (js2-peek-char) ?>)
6571 (progn
6572 (setq c (js2-get-char)) ;; Skip >
6573 (js2-add-to-string c)
6574 (throw 'return t))
6575 (throw 'continue nil)))
6576 (setq c (js2-get-char))))
6577 (js2-xml-discard-string token)
6578 nil)))
6579
6580 (defun js2-read-entity (token)
6581 (let ((decl-tags 1)
6582 c)
6583 (catch 'return
6584 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6585 (js2-add-to-string c)
6586 (case c
6587 (?<
6588 (incf decl-tags))
6589 (?>
6590 (decf decl-tags)
6591 (if (zerop decl-tags)
6592 (throw 'return t)))))
6593 (js2-xml-discard-string token)
6594 nil)))
6595
6596 (defun js2-read-PI (token)
6597 "Scan an XML processing instruction."
6598 (let (c)
6599 (catch 'return
6600 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6601 (js2-add-to-string c)
6602 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6603 (setq c (js2-get-char)) ;; Skip >
6604 (js2-add-to-string c)
6605 (throw 'return t)))
6606 (js2-xml-discard-string token)
6607 nil)))
6608
6609 ;;; Highlighting
6610
6611 (defun js2-set-face (beg end face &optional record)
6612 "Fontify a region. If RECORD is non-nil, record for later."
6613 (when (plusp js2-highlight-level)
6614 (setq beg (min (point-max) beg)
6615 beg (max (point-min) beg)
6616 end (min (point-max) end)
6617 end (max (point-min) end))
6618 (if record
6619 (push (list beg end face) js2-mode-fontifications)
6620 (put-text-property beg end 'font-lock-face face))))
6621
6622 (defsubst js2-clear-face (beg end)
6623 (remove-text-properties beg end '(font-lock-face nil
6624 help-echo nil
6625 point-entered nil
6626 c-in-sws nil)))
6627
6628 (defconst js2-ecma-global-props
6629 (concat "^"
6630 (regexp-opt
6631 '("Infinity" "NaN" "undefined" "arguments") t)
6632 "$")
6633 "Value properties of the Ecma-262 Global Object.
6634 Shown at or above `js2-highlight-level' 2.")
6635
6636 ;; might want to add the name "arguments" to this list?
6637 (defconst js2-ecma-object-props
6638 (concat "^"
6639 (regexp-opt
6640 '("prototype" "__proto__" "__parent__") t)
6641 "$")
6642 "Value properties of the Ecma-262 Object constructor.
6643 Shown at or above `js2-highlight-level' 2.")
6644
6645 (defconst js2-ecma-global-funcs
6646 (concat
6647 "^"
6648 (regexp-opt
6649 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6650 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6651 "$")
6652 "Function properties of the Ecma-262 Global object.
6653 Shown at or above `js2-highlight-level' 2.")
6654
6655 (defconst js2-ecma-number-props
6656 (concat "^"
6657 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6658 "NEGATIVE_INFINITY"
6659 "POSITIVE_INFINITY") t)
6660 "$")
6661 "Properties of the Ecma-262 Number constructor.
6662 Shown at or above `js2-highlight-level' 2.")
6663
6664 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6665 "Properties of the Ecma-262 Date constructor.
6666 Shown at or above `js2-highlight-level' 2.")
6667
6668 (defconst js2-ecma-math-props
6669 (concat "^"
6670 (regexp-opt
6671 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6672 t)
6673 "$")
6674 "Properties of the Ecma-262 Math object.
6675 Shown at or above `js2-highlight-level' 2.")
6676
6677 (defconst js2-ecma-math-funcs
6678 (concat "^"
6679 (regexp-opt
6680 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6681 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6682 "$")
6683 "Function properties of the Ecma-262 Math object.
6684 Shown at or above `js2-highlight-level' 2.")
6685
6686 (defconst js2-ecma-function-props
6687 (concat
6688 "^"
6689 (regexp-opt
6690 '(;; properties of the Object prototype object
6691 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6692 "toLocaleString" "toString" "valueOf"
6693 ;; properties of the Function prototype object
6694 "apply" "call"
6695 ;; properties of the Array prototype object
6696 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6697 "splice" "unshift"
6698 ;; properties of the String prototype object
6699 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6700 "localeCompare" "match" "replace" "search" "split" "substring"
6701 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6702 "toUpperCase"
6703 ;; properties of the Number prototype object
6704 "toExponential" "toFixed" "toPrecision"
6705 ;; properties of the Date prototype object
6706 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6707 "getMinutes" "getMonth" "getSeconds" "getTime"
6708 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6709 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6710 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6711 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6712 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6713 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6714 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6715 "toTimeString" "toUTCString"
6716 ;; properties of the RegExp prototype object
6717 "exec" "test"
6718 ;; properties of the JSON prototype object
6719 "parse" "stringify"
6720 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6721 "toSource" "__defineGetter__" "__defineSetter__"
6722 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6723 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6724 t)
6725 "$")
6726 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6727 Shown at or above `js2-highlight-level' 3.")
6728
6729 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6730 (let ((target-name (and target
6731 (js2-name-node-p target)
6732 (js2-name-node-name target)))
6733 (prop-name (if prop (js2-name-node-name prop)))
6734 (level2 (>= js2-highlight-level 2))
6735 (level3 (>= js2-highlight-level 3)))
6736 (when level2
6737 (let ((face
6738 (if call-p
6739 (cond
6740 ((and target prop)
6741 (cond
6742 ((and level3 (string-match js2-ecma-function-props prop-name))
6743 'font-lock-builtin-face)
6744 ((and target-name prop)
6745 (cond
6746 ((string= target-name "Date")
6747 (if (string-match js2-ecma-date-props prop-name)
6748 'font-lock-builtin-face))
6749 ((string= target-name "Math")
6750 (if (string-match js2-ecma-math-funcs prop-name)
6751 'font-lock-builtin-face))))))
6752 (prop
6753 (if (string-match js2-ecma-global-funcs prop-name)
6754 'font-lock-builtin-face)))
6755 (cond
6756 ((and target prop)
6757 (cond
6758 ((string= target-name "Number")
6759 (if (string-match js2-ecma-number-props prop-name)
6760 'font-lock-constant-face))
6761 ((string= target-name "Math")
6762 (if (string-match js2-ecma-math-props prop-name)
6763 'font-lock-constant-face))))
6764 (prop
6765 (if (string-match js2-ecma-object-props prop-name)
6766 'font-lock-constant-face))))))
6767 (when face
6768 (let ((pos (+ (js2-node-pos parent) ; absolute
6769 (js2-node-pos prop)))) ; relative
6770 (js2-set-face pos
6771 (+ pos (js2-node-len prop))
6772 face 'record)))))))
6773
6774 (defun js2-parse-highlight-member-expr-node (node)
6775 "Perform syntax highlighting of EcmaScript built-in properties.
6776 The variable `js2-highlight-level' governs this highighting."
6777 (let (face target prop name pos end parent call-p callee)
6778 (cond
6779 ;; case 1: simple name, e.g. foo
6780 ((js2-name-node-p node)
6781 (setq name (js2-name-node-name node))
6782 ;; possible for name to be nil in rare cases - saw it when
6783 ;; running js2-mode on an elisp buffer. Might as well try to
6784 ;; make it so js2-mode never barfs.
6785 (when name
6786 (setq face (if (string-match js2-ecma-global-props name)
6787 'font-lock-constant-face))
6788 (when face
6789 (setq pos (js2-node-pos node)
6790 end (+ pos (js2-node-len node)))
6791 (js2-set-face pos end face 'record))))
6792 ;; case 2: property access or function call
6793 ((or (js2-prop-get-node-p node)
6794 ;; highlight function call if expr is a prop-get node
6795 ;; or a plain name (i.e. unqualified function call)
6796 (and (setq call-p (js2-call-node-p node))
6797 (setq callee (js2-call-node-target node)) ; separate setq!
6798 (or (js2-prop-get-node-p callee)
6799 (js2-name-node-p callee))))
6800 (setq parent node
6801 node (if call-p callee node))
6802 (if (and call-p (js2-name-node-p callee))
6803 (setq prop callee)
6804 (setq target (js2-prop-get-node-left node)
6805 prop (js2-prop-get-node-right node)))
6806 (cond
6807 ((js2-name-node-p prop)
6808 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6809 (js2-parse-highlight-prop-get parent target prop call-p))
6810 ((js2-name-node-p target)
6811 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6812 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6813
6814 (defun js2-parse-highlight-member-expr-fn-name (expr)
6815 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6816 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6817 We currently only handle the case where the last component is a prop-get
6818 of a simple name. Called before EXPR has a parent node."
6819 (let (pos
6820 (name (and (js2-prop-get-node-p expr)
6821 (js2-prop-get-node-right expr))))
6822 (when (js2-name-node-p name)
6823 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6824 (js2-node-pos name)))
6825 (+ pos (js2-node-len name))
6826 'font-lock-function-name-face
6827 'record))))
6828
6829 ;; source: http://jsdoc.sourceforge.net/
6830 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6831 ;; allows type specifications, and needs work before entering the wild.
6832
6833 (defconst js2-jsdoc-param-tag-regexp
6834 (concat "^\\s-*\\*+\\s-*\\(@"
6835 "\\(?:param\\|argument\\)"
6836 "\\)"
6837 "\\s-*\\({[^}]+}\\)?" ; optional type
6838 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6839 "\\>")
6840 "Matches jsdoc tags with optional type and optional param name.")
6841
6842 (defconst js2-jsdoc-typed-tag-regexp
6843 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6844 (regexp-opt
6845 '("enum"
6846 "extends"
6847 "field"
6848 "id"
6849 "implements"
6850 "lends"
6851 "mods"
6852 "requires"
6853 "return"
6854 "returns"
6855 "throw"
6856 "throws"))
6857 "\\)\\)\\s-*\\({[^}]+}\\)?")
6858 "Matches jsdoc tags with optional type.")
6859
6860 (defconst js2-jsdoc-arg-tag-regexp
6861 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6862 (regexp-opt
6863 '("alias"
6864 "augments"
6865 "borrows"
6866 "bug"
6867 "base"
6868 "config"
6869 "default"
6870 "define"
6871 "exception"
6872 "function"
6873 "member"
6874 "memberOf"
6875 "name"
6876 "namespace"
6877 "property"
6878 "since"
6879 "suppress"
6880 "this"
6881 "throws"
6882 "type"
6883 "version"))
6884 "\\)\\)\\s-+\\([^ \t]+\\)")
6885 "Matches jsdoc tags with a single argument.")
6886
6887 (defconst js2-jsdoc-empty-tag-regexp
6888 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6889 (regexp-opt
6890 '("addon"
6891 "author"
6892 "class"
6893 "const"
6894 "constant"
6895 "constructor"
6896 "constructs"
6897 "deprecated"
6898 "desc"
6899 "description"
6900 "event"
6901 "example"
6902 "exec"
6903 "export"
6904 "fileoverview"
6905 "final"
6906 "function"
6907 "hidden"
6908 "ignore"
6909 "implicitCast"
6910 "inheritDoc"
6911 "inner"
6912 "interface"
6913 "license"
6914 "noalias"
6915 "noshadow"
6916 "notypecheck"
6917 "override"
6918 "owner"
6919 "preserve"
6920 "preserveTry"
6921 "private"
6922 "protected"
6923 "public"
6924 "static"
6925 "supported"
6926 ))
6927 "\\)\\)\\s-*")
6928 "Matches empty jsdoc tags.")
6929
6930 (defconst js2-jsdoc-link-tag-regexp
6931 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6932 "Matches a jsdoc link or code tag.")
6933
6934 (defconst js2-jsdoc-see-tag-regexp
6935 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6936 "Matches a jsdoc @see tag.")
6937
6938 (defconst js2-jsdoc-html-tag-regexp
6939 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6940 "Matches a simple (no attributes) html start- or end-tag.")
6941
6942 (defun js2-jsdoc-highlight-helper ()
6943 (js2-set-face (match-beginning 1)
6944 (match-end 1)
6945 'js2-jsdoc-tag)
6946 (if (match-beginning 2)
6947 (if (save-excursion
6948 (goto-char (match-beginning 2))
6949 (= (char-after) ?{))
6950 (js2-set-face (1+ (match-beginning 2))
6951 (1- (match-end 2))
6952 'js2-jsdoc-type)
6953 (js2-set-face (match-beginning 2)
6954 (match-end 2)
6955 'js2-jsdoc-value)))
6956 (if (match-beginning 3)
6957 (js2-set-face (match-beginning 3)
6958 (match-end 3)
6959 'js2-jsdoc-value)))
6960
6961 (defun js2-highlight-jsdoc (ast)
6962 "Highlight doc comment tags."
6963 (let ((comments (js2-ast-root-comments ast))
6964 beg end)
6965 (save-excursion
6966 (dolist (node comments)
6967 (when (eq (js2-comment-node-format node) 'jsdoc)
6968 (setq beg (js2-node-abs-pos node)
6969 end (+ beg (js2-node-len node)))
6970 (save-restriction
6971 (narrow-to-region beg end)
6972 (dolist (re (list js2-jsdoc-param-tag-regexp
6973 js2-jsdoc-typed-tag-regexp
6974 js2-jsdoc-arg-tag-regexp
6975 js2-jsdoc-link-tag-regexp
6976 js2-jsdoc-see-tag-regexp
6977 js2-jsdoc-empty-tag-regexp))
6978 (goto-char beg)
6979 (while (re-search-forward re nil t)
6980 (js2-jsdoc-highlight-helper)))
6981 ;; simple highlighting for html tags
6982 (goto-char beg)
6983 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6984 (js2-set-face (match-beginning 1)
6985 (match-end 1)
6986 'js2-jsdoc-html-tag-delimiter)
6987 (js2-set-face (match-beginning 2)
6988 (match-end 2)
6989 'js2-jsdoc-html-tag-name)
6990 (js2-set-face (match-beginning 3)
6991 (match-end 3)
6992 'js2-jsdoc-html-tag-delimiter))))))))
6993
6994 (defun js2-highlight-assign-targets (_node left right)
6995 "Highlight function properties and external variables."
6996 (let (leftpos name)
6997 ;; highlight vars and props assigned function values
6998 (when (or (js2-function-node-p right)
6999 (js2-class-node-p right))
7000 (cond
7001 ;; var foo = function() {...}
7002 ((js2-name-node-p left)
7003 (setq name left))
7004 ;; foo.bar.baz = function() {...}
7005 ((and (js2-prop-get-node-p left)
7006 (js2-name-node-p (js2-prop-get-node-right left)))
7007 (setq name (js2-prop-get-node-right left))))
7008 (when name
7009 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7010 (+ leftpos (js2-node-len name))
7011 'font-lock-function-name-face
7012 'record)))))
7013
7014 (defun js2-record-name-node (node)
7015 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7016 later. NODE must be a name node."
7017 (let ((leftpos (js2-node-abs-pos node)))
7018 (push (list node js2-current-scope
7019 leftpos
7020 (+ leftpos (js2-node-len node)))
7021 js2-recorded-identifiers)))
7022
7023 (defun js2-highlight-undeclared-vars ()
7024 "After entire parse is finished, look for undeclared variable references.
7025 We have to wait until entire buffer is parsed, since JavaScript permits var
7026 decls to occur after they're used.
7027
7028 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7029 it is considered declared."
7030 (let (name)
7031 (dolist (entry js2-recorded-identifiers)
7032 (destructuring-bind (name-node scope pos end) entry
7033 (setq name (js2-name-node-name name-node))
7034 (unless (or (member name js2-global-externs)
7035 (member name js2-default-externs)
7036 (member name js2-additional-externs)
7037 (js2-get-defining-scope scope name))
7038 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7039 'js2-external-variable))))
7040 (setq js2-recorded-identifiers nil)))
7041
7042 (defun js2-set-default-externs ()
7043 "Set the value of `js2-default-externs' based on the various
7044 `js2-include-?-externs' variables."
7045 (setq js2-default-externs
7046 (append js2-ecma-262-externs
7047 (if js2-include-browser-externs js2-browser-externs)
7048 (if (and js2-include-browser-externs
7049 (>= js2-language-version 200)) js2-harmony-externs)
7050 (if js2-include-rhino-externs js2-rhino-externs)
7051 (if js2-include-node-externs js2-node-externs)
7052 (if (or js2-include-browser-externs js2-include-node-externs)
7053 js2-typed-array-externs))))
7054
7055 (defun js2-apply-jslint-globals ()
7056 (setq js2-additional-externs
7057 (nconc (js2-get-jslint-globals)
7058 js2-additional-externs)))
7059
7060 (defun js2-get-jslint-globals ()
7061 (loop for node in (js2-ast-root-comments js2-mode-ast)
7062 when (and (eq 'block (js2-comment-node-format node))
7063 (save-excursion
7064 (goto-char (js2-node-abs-pos node))
7065 (looking-at "/\\*global ")))
7066 append (js2-get-jslint-globals-in
7067 (match-end 0)
7068 (js2-node-abs-end node))))
7069
7070 (defun js2-get-jslint-globals-in (beg end)
7071 (let (res)
7072 (save-excursion
7073 (goto-char beg)
7074 (while (re-search-forward js2-mode-identifier-re end t)
7075 (let ((match (match-string 0)))
7076 (unless (member match '("true" "false"))
7077 (push match res)))))
7078 (nreverse res)))
7079
7080 ;;; IMenu support
7081
7082 ;; We currently only support imenu, but eventually should support speedbar and
7083 ;; possibly other browsing mechanisms.
7084
7085 ;; The basic strategy is to identify function assignment targets of the form
7086 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7087 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7088 ;; for imenu after parsing is finished.
7089
7090 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7091 ;; JavaScript, and the general problem is undecidable. However, several forms
7092 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7093 ;; include:
7094
7095 ;; function foo() -- function declaration
7096 ;; foo = function() -- function expression assigned to variable
7097 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7098 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7099 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7100 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7101 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7102 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7103 ;; function foo() {function bar() {...}} -- nested function
7104 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7105
7106 ;; This list boils down to a few forms that can be combined recursively.
7107 ;; Top-level named function declarations include both the left-hand (name)
7108 ;; and the right-hand (function value) expressions needed to produce an imenu
7109 ;; entry. The other "right-hand" forms we need to look for are:
7110 ;; - functions declared as props/getters/setters in object literals
7111 ;; - nested named function declarations
7112 ;; The "left-hand" expressions that functions can be assigned to include:
7113 ;; - local/global variables
7114 ;; - nested property-get expressions like a.b.c.d
7115 ;; - element gets like foo[10] or foo['bar'] where the index
7116 ;; expression can be trivially converted to a property name. They
7117 ;; effectively then become property gets.
7118
7119 ;; All the different definition types are canonicalized into the form
7120 ;; foo.bar.baz = position-of-function-keyword
7121
7122 ;; We need to build a trie-like structure for imenu. As an example,
7123 ;; consider the following JavaScript code:
7124
7125 ;; a = function() {...} // function at position 5
7126 ;; b = function() {...} // function at position 25
7127 ;; foo = function() {...} // function at position 100
7128 ;; foo.bar = function() {...} // function at position 200
7129 ;; foo.bar.baz = function() {...} // function at position 300
7130 ;; foo.bar.zab = function() {...} // function at position 400
7131
7132 ;; During parsing we accumulate an entry for each definition in
7133 ;; the variable `js2-imenu-recorder', like so:
7134
7135 ;; '((fn a 5)
7136 ;; (fn b 25)
7137 ;; (fn foo 100)
7138 ;; (fn foo bar 200)
7139 ;; (fn foo bar baz 300)
7140 ;; (fn foo bar zab 400))
7141
7142 ;; Where 'fn' is the respective function node.
7143 ;; After parsing these entries are merged into this alist-trie:
7144
7145 ;; '((a . 1)
7146 ;; (b . 2)
7147 ;; (foo (<definition> . 3)
7148 ;; (bar (<definition> . 6)
7149 ;; (baz . 100)
7150 ;; (zab . 200))))
7151
7152 ;; Note the wacky need for a <definition> name. The token can be anything
7153 ;; that isn't a valid JavaScript identifier, because you might make foo
7154 ;; a function and then start setting properties on it that are also functions.
7155
7156 (defun js2-prop-node-name (node)
7157 "Return the name of a node that may be a property-get/property-name.
7158 If NODE is not a valid name-node, string-node or integral number-node,
7159 returns nil. Otherwise returns the string name/value of the node."
7160 (cond
7161 ((js2-name-node-p node)
7162 (js2-name-node-name node))
7163 ((js2-string-node-p node)
7164 (js2-string-node-value node))
7165 ((and (js2-number-node-p node)
7166 (string-match "^[0-9]+$" (js2-number-node-value node)))
7167 (js2-number-node-value node))
7168 ((eq (js2-node-type node) js2-THIS)
7169 "this")
7170 ((eq (js2-node-type node) js2-SUPER)
7171 "super")))
7172
7173 (defun js2-node-qname-component (node)
7174 "Return the name of this node, if it contributes to a qname.
7175 Returns nil if the node doesn't contribute."
7176 (copy-sequence
7177 (or (js2-prop-node-name node)
7178 (if (and (js2-function-node-p node)
7179 (js2-function-node-name node))
7180 (js2-name-node-name (js2-function-node-name node))))))
7181
7182 (defun js2-record-imenu-entry (fn-node qname pos)
7183 "Add an entry to `js2-imenu-recorder'.
7184 FN-NODE should be the current item's function node.
7185
7186 Associate FN-NODE with its QNAME for later lookup.
7187 This is used in postprocessing the chain list. For each chain, we find
7188 the parent function, look up its qname, then prepend a copy of it to the chain."
7189 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7190 (unless js2-imenu-function-map
7191 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7192 (puthash fn-node qname js2-imenu-function-map))
7193
7194 (defun js2-record-imenu-functions (node &optional var)
7195 "Record function definitions for imenu.
7196 NODE is a function node or an object literal.
7197 VAR, if non-nil, is the expression that NODE is being assigned to.
7198 When passed arguments of wrong type, does nothing."
7199 (when js2-parse-ide-mode
7200 (let ((fun-p (js2-function-node-p node))
7201 qname fname-node)
7202 (cond
7203 ;; non-anonymous function declaration?
7204 ((and fun-p
7205 (not var)
7206 (setq fname-node (js2-function-node-name node)))
7207 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7208 ;; for remaining forms, compute left-side tree branch first
7209 ((and var (setq qname (js2-compute-nested-prop-get var)))
7210 (cond
7211 ;; foo.bar.baz = function
7212 (fun-p
7213 (js2-record-imenu-entry node qname (js2-node-pos node)))
7214 ;; foo.bar.baz = object-literal
7215 ;; look for nested functions: {a: {b: function() {...} }}
7216 ((js2-object-node-p node)
7217 ;; Node position here is still absolute, since the parser
7218 ;; passes the assignment target and value expressions
7219 ;; to us before they are added as children of the assignment node.
7220 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7221
7222 (defun js2-compute-nested-prop-get (node)
7223 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7224 component nodes as a list. Otherwise return nil. Element-gets are treated
7225 as property-gets if the index expression is a string, or a positive integer."
7226 (let (left right head)
7227 (cond
7228 ((or (js2-name-node-p node)
7229 (js2-this-or-super-node-p node))
7230 (list node))
7231 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7232 ((js2-prop-get-node-p node) ; foo.bar
7233 (setq left (js2-prop-get-node-left node)
7234 right (js2-prop-get-node-right node))
7235 (if (setq head (js2-compute-nested-prop-get left))
7236 (nconc head (list right))))
7237 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7238 (setq left (js2-elem-get-node-target node)
7239 right (js2-elem-get-node-element node))
7240 (if (or (js2-string-node-p right) ; ['bar']
7241 (and (js2-number-node-p right) ; [10]
7242 (string-match "^[0-9]+$"
7243 (js2-number-node-value right))))
7244 (if (setq head (js2-compute-nested-prop-get left))
7245 (nconc head (list right))))))))
7246
7247 (defun js2-record-object-literal (node qname pos)
7248 "Recursively process an object literal looking for functions.
7249 NODE is an object literal that is the right-hand child of an assignment
7250 expression. QNAME is a list of nodes representing the assignment target,
7251 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7252 POS is the absolute position of the node.
7253 We do a depth-first traversal of NODE. For any functions we find,
7254 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7255 (let (right)
7256 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7257 (let ((left (js2-infix-node-left e))
7258 ;; Element positions are relative to the parent position.
7259 (pos (+ pos (js2-node-pos e))))
7260 (cond
7261 ;; foo: function() {...}
7262 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7263 (when (js2-prop-node-name left)
7264 ;; As a policy decision, we record the position of the property,
7265 ;; not the position of the `function' keyword, since the property
7266 ;; is effectively the name of the function.
7267 (js2-record-imenu-entry right (append qname (list left)) pos)))
7268 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7269 ((js2-object-node-p right)
7270 (js2-record-object-literal right
7271 (append qname (list (js2-infix-node-left e)))
7272 (+ pos (js2-node-pos right)))))))))
7273
7274 (defun js2-node-top-level-decl-p (node)
7275 "Return t if NODE's name is defined in the top-level scope.
7276 Also returns t if NODE's name is not defined in any scope, since it implies
7277 that it's an external variable, which must also be in the top-level scope."
7278 (let* ((name (js2-prop-node-name node))
7279 (this-scope (js2-node-get-enclosing-scope node))
7280 defining-scope)
7281 (cond
7282 ((js2-this-or-super-node-p node)
7283 nil)
7284 ((null this-scope)
7285 t)
7286 ((setq defining-scope (js2-get-defining-scope this-scope name))
7287 (js2-ast-root-p defining-scope))
7288 (t t))))
7289
7290 (defun js2-wrapper-function-p (node)
7291 "Return t if NODE is a function expression that's immediately invoked.
7292 NODE must be `js2-function-node'."
7293 (let ((parent (js2-node-parent node)))
7294 (or
7295 ;; function(){...}();
7296 (and (js2-call-node-p parent)
7297 (eq node (js2-call-node-target parent)))
7298 (and (js2-paren-node-p parent)
7299 ;; (function(){...})();
7300 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7301 ;; (function(){...}).call(this);
7302 (and (js2-prop-get-node-p parent)
7303 (member (js2-name-node-name (js2-prop-get-node-right parent))
7304 '("call" "apply"))
7305 (js2-call-node-p (js2-node-parent parent))))))))
7306
7307 (defun js2-browse-postprocess-chains ()
7308 "Modify function-declaration name chains after parsing finishes.
7309 Some of the information is only available after the parse tree is complete.
7310 For instance, processing a nested scope requires a parent function node."
7311 (let (result fn parent-qname p elem)
7312 (dolist (entry js2-imenu-recorder)
7313 ;; function node goes first
7314 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7315 ;; Examine head's defining scope:
7316 ;; Pre-processed chain, or top-level/external, keep as-is.
7317 (if (or (stringp head) (js2-node-top-level-decl-p head))
7318 (push chain result)
7319 (when (js2-this-or-super-node-p head)
7320 (setq chain (cdr chain))) ; discard this-node
7321 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7322 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7323 (when (eq parent-qname 'not-found)
7324 ;; anonymous function expressions are not recorded
7325 ;; during the parse, so we need to handle this case here
7326 (setq parent-qname
7327 (if (js2-wrapper-function-p fn)
7328 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7329 (if (js2-ast-root-p grandparent)
7330 nil
7331 (gethash grandparent js2-imenu-function-map 'skip)))
7332 'skip))
7333 (puthash fn parent-qname js2-imenu-function-map))
7334 (if (eq parent-qname 'skip)
7335 ;; We don't show it, let's record that fact.
7336 (remhash current-fn js2-imenu-function-map)
7337 ;; Prepend parent fn qname to this chain.
7338 (let ((qname (append parent-qname chain)))
7339 (puthash current-fn (butlast qname) js2-imenu-function-map)
7340 (push qname result)))))))
7341 ;; Collect chains obtained by third-party code.
7342 (let (js2-imenu-recorder)
7343 (run-hooks 'js2-build-imenu-callbacks)
7344 (dolist (entry js2-imenu-recorder)
7345 (push (cdr entry) result)))
7346 ;; Finally replace each node in each chain with its name.
7347 (dolist (chain result)
7348 (setq p chain)
7349 (while p
7350 (if (js2-node-p (setq elem (car p)))
7351 (setcar p (js2-node-qname-component elem)))
7352 (setq p (cdr p))))
7353 result))
7354
7355 ;; Merge name chains into a trie-like tree structure of nested lists.
7356 ;; To simplify construction of the trie, we first build it out using the rule
7357 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7358 ;; [key, num-or-list]. The second element can be a number; if so, this key
7359 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7360 ;; associated with the key at this level.) Otherwise the second element is
7361 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7362 ;; a simple recursive formulation.
7363 ;;
7364 ;; js2-mode is building the data structure for imenu. The imenu documentation
7365 ;; claims that it's the structure above, but in practice it wants the children
7366 ;; at the same list level as the key for that level, which is how I've drawn
7367 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7368 ;; list wrapper around the children at each level.
7369 ;;
7370 ;; A completed nested imenu-alist entry looks like this:
7371 ;; '(("foo"
7372 ;; ("<definition>" . 7)
7373 ;; ("bar"
7374 ;; ("a" . 40)
7375 ;; ("b" . 60))))
7376 ;;
7377 ;; In particular, the documentation for `imenu--index-alist' says that
7378 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7379 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7380
7381 (defun js2-treeify (lst)
7382 "Convert (a b c d) to (a ((b ((c d)))))."
7383 (if (null (cddr lst)) ; list length <= 2
7384 lst
7385 (list (car lst) (list (js2-treeify (cdr lst))))))
7386
7387 (defun js2-build-alist-trie (chains trie)
7388 "Merge declaration name chains into a trie-like alist structure for imenu.
7389 CHAINS is the qname chain list produced during parsing. TRIE is a
7390 list of elements built up so far."
7391 (let (head tail pos branch kids)
7392 (dolist (chain chains)
7393 (setq head (car chain)
7394 tail (cdr chain)
7395 pos (if (numberp (car tail)) (car tail))
7396 branch (js2-find-if (lambda (n)
7397 (string= (car n) head))
7398 trie)
7399 kids (second branch))
7400 (cond
7401 ;; case 1: this key isn't in the trie yet
7402 ((null branch)
7403 (if trie
7404 (setcdr (last trie) (list (js2-treeify chain)))
7405 (setq trie (list (js2-treeify chain)))))
7406 ;; case 2: key is present with a single number entry: replace w/ list
7407 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7408 ;; ("<definition>" 20)))
7409 ((numberp kids)
7410 (setcar (cdr branch)
7411 (list (list "<definition-1>" kids)
7412 (if pos
7413 (list "<definition-2>" pos)
7414 (js2-treeify tail)))))
7415 ;; case 3: key is there (with kids), and we're a number entry
7416 (pos
7417 (setcdr (last kids)
7418 (list
7419 (list (format "<definition-%d>"
7420 (1+ (loop for kid in kids
7421 count (eq ?< (aref (car kid) 0)))))
7422 pos))))
7423 ;; case 4: key is there with kids, need to merge in our chain
7424 (t
7425 (js2-build-alist-trie (list tail) kids))))
7426 trie))
7427
7428 (defun js2-flatten-trie (trie)
7429 "Convert TRIE to imenu-format.
7430 Recurses through nodes, and for each one whose second element is a list,
7431 appends the list's flattened elements to the current element. Also
7432 changes the tails into conses. For instance, this pre-flattened trie
7433
7434 '(a ((b 20)
7435 (c ((d 30)
7436 (e 40)))))
7437
7438 becomes
7439
7440 '(a (b . 20)
7441 (c (d . 30)
7442 (e . 40)))
7443
7444 Note that the root of the trie has no key, just a list of chains.
7445 This is also true for the value of any key with multiple children,
7446 e.g. key 'c' in the example above."
7447 (cond
7448 ((listp (car trie))
7449 (mapcar #'js2-flatten-trie trie))
7450 (t
7451 (if (numberp (second trie))
7452 (cons (car trie) (second trie))
7453 ;; else pop list and append its kids
7454 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7455
7456 (defun js2-build-imenu-index ()
7457 "Turn `js2-imenu-recorder' into an imenu data structure."
7458 (when (eq js2-imenu-recorder 'empty)
7459 (setq js2-imenu-recorder nil))
7460 (let* ((chains (js2-browse-postprocess-chains))
7461 (result (js2-build-alist-trie chains nil)))
7462 (js2-flatten-trie result)))
7463
7464 (defun js2-test-print-chains (chains)
7465 "Print a list of qname chains.
7466 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7467 i.e. one or more nodes, and an integer position as the list tail."
7468 (mapconcat (lambda (chain)
7469 (concat "("
7470 (mapconcat (lambda (elem)
7471 (if (js2-node-p elem)
7472 (or (js2-node-qname-component elem)
7473 "nil")
7474 (number-to-string elem)))
7475 chain
7476 " ")
7477 ")"))
7478 chains
7479 "\n"))
7480
7481 ;;; Parser
7482
7483 (defconst js2-version "1.8.5"
7484 "Version of JavaScript supported.")
7485
7486 (defun js2-record-face (face &optional token)
7487 "Record a style run of FACE for TOKEN or the current token."
7488 (unless token (setq token (js2-current-token)))
7489 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7490
7491 (defsubst js2-node-end (n)
7492 "Computes the absolute end of node N.
7493 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7494 is only true until the node is added to its parent; i.e., while parsing."
7495 (+ (js2-node-pos n)
7496 (js2-node-len n)))
7497
7498 (defun js2-record-comment (token)
7499 "Record a comment in `js2-scanned-comments'."
7500 (let ((ct (js2-token-comment-type token))
7501 (beg (js2-token-beg token))
7502 (end (js2-token-end token)))
7503 (push (make-js2-comment-node :len (- end beg)
7504 :format ct)
7505 js2-scanned-comments)
7506 (when js2-parse-ide-mode
7507 (js2-record-face (if (eq ct 'jsdoc)
7508 'font-lock-doc-face
7509 'font-lock-comment-face)
7510 token)
7511 (when (memq ct '(html preprocessor))
7512 ;; Tell cc-engine the bounds of the comment.
7513 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7514
7515 (defun js2-peek-token ()
7516 "Return the next token type without consuming it.
7517 If `js2-ti-lookahead' is positive, return the type of next token
7518 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7519 (if (not (zerop js2-ti-lookahead))
7520 (js2-token-type
7521 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7522 (let ((tt (js2-get-token-internal nil)))
7523 (js2-unget-token)
7524 tt)))
7525
7526 (defalias 'js2-next-token 'js2-get-token)
7527
7528 (defun js2-match-token (match &optional dont-unget)
7529 "Get next token and return t if it matches MATCH, a bytecode.
7530 Returns nil and consumes nothing if MATCH is not the next token."
7531 (if (/= (js2-get-token) match)
7532 (ignore (unless dont-unget (js2-unget-token)))
7533 t))
7534
7535 (defun js2-match-contextual-kwd (name)
7536 "Consume and return t if next token is `js2-NAME', and its
7537 string is NAME. Returns nil and keeps current token otherwise."
7538 (if (or (/= (js2-get-token) js2-NAME)
7539 (not (string= (js2-current-token-string) name)))
7540 (progn
7541 (js2-unget-token)
7542 nil)
7543 (js2-record-face 'font-lock-keyword-face)
7544 t))
7545
7546 (defun js2-get-prop-name-token ()
7547 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7548
7549 (defun js2-match-prop-name ()
7550 "Consume token and return t if next token is a valid property name.
7551 If `js2-language-version' is >= 180, a keyword or reserved word
7552 is considered valid name as well."
7553 (if (eq js2-NAME (js2-get-prop-name-token))
7554 t
7555 (js2-unget-token)
7556 nil))
7557
7558 (defun js2-must-match-prop-name (msg-id &optional pos len)
7559 (if (js2-match-prop-name)
7560 t
7561 (js2-report-error msg-id nil pos len)
7562 nil))
7563
7564 (defun js2-peek-token-or-eol ()
7565 "Return js2-EOL if the next token immediately follows a newline.
7566 Else returns the next token. Used in situations where we don't
7567 consider certain token types valid if they are preceded by a newline.
7568 One example is the postfix ++ or -- operator, which has to be on the
7569 same line as its operand."
7570 (let ((tt (js2-get-token))
7571 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7572 (js2-unget-token)
7573 (if follows-eol
7574 js2-EOL
7575 tt)))
7576
7577 (defun js2-must-match (token msg-id &optional pos len)
7578 "Match next token to token code TOKEN, or record a syntax error.
7579 MSG-ID is the error message to report if the match fails.
7580 Returns t on match, nil if no match."
7581 (if (js2-match-token token t)
7582 t
7583 (js2-report-error msg-id nil pos len)
7584 (js2-unget-token)
7585 nil))
7586
7587 (defun js2-must-match-name (msg-id)
7588 (if (js2-match-token js2-NAME t)
7589 t
7590 (if (eq (js2-current-token-type) js2-RESERVED)
7591 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7592 (js2-report-error msg-id)
7593 (js2-unget-token))
7594 nil))
7595
7596 (defsubst js2-inside-function ()
7597 (plusp js2-nesting-of-function))
7598
7599 (defun js2-set-requires-activation ()
7600 (if (js2-function-node-p js2-current-script-or-fn)
7601 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7602
7603 (defun js2-check-activation-name (name _token)
7604 (when (js2-inside-function)
7605 ;; skip language-version 1.2 check from Rhino
7606 (if (or (string= "arguments" name)
7607 (and js2-compiler-activation-names ; only used in codegen
7608 (gethash name js2-compiler-activation-names)))
7609 (js2-set-requires-activation))))
7610
7611 (defun js2-set-is-generator ()
7612 (let ((fn-node js2-current-script-or-fn))
7613 (when (and (js2-function-node-p fn-node)
7614 (not (js2-function-node-generator-type fn-node)))
7615 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7616
7617 (defun js2-must-have-xml ()
7618 (unless js2-compiler-xml-available
7619 (js2-report-error "msg.XML.not.available")))
7620
7621 (defun js2-push-scope (scope)
7622 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7623 (assert (js2-scope-p scope))
7624 (assert (null (js2-scope-parent-scope scope)))
7625 (assert (not (eq js2-current-scope scope)))
7626 (setf (js2-scope-parent-scope scope) js2-current-scope
7627 js2-current-scope scope))
7628
7629 (defsubst js2-pop-scope ()
7630 (setq js2-current-scope
7631 (js2-scope-parent-scope js2-current-scope)))
7632
7633 (defun js2-enter-loop (loop-node)
7634 (push loop-node js2-loop-set)
7635 (push loop-node js2-loop-and-switch-set)
7636 (js2-push-scope loop-node)
7637 ;; Tell the current labeled statement (if any) its statement,
7638 ;; and set the jump target of the first label to the loop.
7639 ;; These are used in `js2-parse-continue' to verify that the
7640 ;; continue target is an actual labeled loop. (And for codegen.)
7641 (when js2-labeled-stmt
7642 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7643 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7644 js2-labeled-stmt))) loop-node)))
7645
7646 (defun js2-exit-loop ()
7647 (pop js2-loop-set)
7648 (pop js2-loop-and-switch-set)
7649 (js2-pop-scope))
7650
7651 (defsubst js2-enter-switch (switch-node)
7652 (push switch-node js2-loop-and-switch-set))
7653
7654 (defsubst js2-exit-switch ()
7655 (pop js2-loop-and-switch-set))
7656
7657 (defun js2-parse (&optional buf cb)
7658 "Tell the js2 parser to parse a region of JavaScript.
7659
7660 BUF is a buffer or buffer name containing the code to parse.
7661 Call `narrow-to-region' first to parse only part of the buffer.
7662
7663 The returned AST root node is given some additional properties:
7664 `node-count' - total number of nodes in the AST
7665 `buffer' - BUF. The buffer it refers to may change or be killed,
7666 so the value is not necessarily reliable.
7667
7668 An optional callback CB can be specified to report parsing
7669 progress. If `(functionp CB)' returns t, it will be called with
7670 the current line number once before parsing begins, then again
7671 each time the lexer reaches a new line number.
7672
7673 CB can also be a list of the form `(symbol cb ...)' to specify
7674 multiple callbacks with different criteria. Each symbol is a
7675 criterion keyword, and the following element is the callback to
7676 call
7677
7678 :line - called whenever the line number changes
7679 :token - called for each new token consumed
7680
7681 The list of criteria could be extended to include entering or
7682 leaving a statement, an expression, or a function definition."
7683 (if (and cb (not (functionp cb)))
7684 (error "criteria callbacks not yet implemented"))
7685 (let ((inhibit-point-motion-hooks t)
7686 (js2-compiler-xml-available (>= js2-language-version 160))
7687 ;; This is a recursive-descent parser, so give it a big stack.
7688 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7689 (max-specpdl-size (max max-specpdl-size 3000))
7690 (case-fold-search nil)
7691 ast)
7692 (with-current-buffer (or buf (current-buffer))
7693 (setq js2-scanned-comments nil
7694 js2-parsed-errors nil
7695 js2-parsed-warnings nil
7696 js2-imenu-recorder nil
7697 js2-imenu-function-map nil
7698 js2-label-set nil)
7699 (js2-init-scanner)
7700 (setq ast (js2-do-parse))
7701 (unless js2-ts-hit-eof
7702 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7703 (setf (js2-ast-root-errors ast) js2-parsed-errors
7704 (js2-ast-root-warnings ast) js2-parsed-warnings)
7705 ;; if we didn't find any declarations, put a dummy in this list so we
7706 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7707 (unless js2-imenu-recorder
7708 (setq js2-imenu-recorder 'empty))
7709 (run-hooks 'js2-parse-finished-hook)
7710 ast)))
7711
7712 ;; Corresponds to Rhino's Parser.parse() method.
7713 (defun js2-do-parse ()
7714 "Parse current buffer starting from current point.
7715 Scanner should be initialized."
7716 (let ((pos js2-ts-cursor)
7717 (end js2-ts-cursor) ; in case file is empty
7718 root n tt)
7719 ;; initialize buffer-local parsing vars
7720 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7721 js2-current-script-or-fn root
7722 js2-current-scope root
7723 js2-nesting-of-function 0
7724 js2-labeled-stmt nil
7725 js2-recorded-identifiers nil) ; for js2-highlight
7726 (while (/= (setq tt (js2-get-token)) js2-EOF)
7727 (if (= tt js2-FUNCTION)
7728 (progn
7729 (setq n (if js2-called-by-compile-function
7730 (js2-parse-function-expr)
7731 (js2-parse-function-stmt))))
7732 ;; not a function - parse a statement
7733 (js2-unget-token)
7734 (setq n (js2-parse-statement)))
7735 ;; add function or statement to script
7736 (setq end (js2-node-end n))
7737 (js2-block-node-push root n))
7738 ;; add comments to root in lexical order
7739 (when js2-scanned-comments
7740 ;; if we find a comment beyond end of normal kids, use its end
7741 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7742 (dolist (comment js2-scanned-comments)
7743 (push comment (js2-ast-root-comments root))
7744 (js2-node-add-children root comment)))
7745 (setf (js2-node-len root) (- end pos))
7746 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7747 ;; Give extensions a chance to muck with things before highlighting starts.
7748 (let ((js2-additional-externs js2-additional-externs))
7749 (save-excursion
7750 (run-hooks 'js2-post-parse-callbacks))
7751 (js2-highlight-undeclared-vars))
7752 root))
7753
7754 (defun js2-parse-function-closure-body (fn-node)
7755 "Parse a JavaScript 1.8 function closure body."
7756 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7757 (if js2-ts-hit-eof
7758 (js2-report-error "msg.no.brace.body" nil
7759 (js2-node-pos fn-node)
7760 (- js2-ts-cursor (js2-node-pos fn-node)))
7761 (js2-node-add-children fn-node
7762 (setf (js2-function-node-body fn-node)
7763 (js2-parse-expr t))))))
7764
7765 (defun js2-parse-function-body (fn-node)
7766 (js2-must-match js2-LC "msg.no.brace.body"
7767 (js2-node-pos fn-node)
7768 (- js2-ts-cursor (js2-node-pos fn-node)))
7769 (let ((pos (js2-current-token-beg)) ; LC position
7770 (pn (make-js2-block-node)) ; starts at LC position
7771 tt
7772 end)
7773 (incf js2-nesting-of-function)
7774 (unwind-protect
7775 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7776 (= tt js2-EOF)
7777 (= tt js2-RC)))
7778 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7779 (js2-parse-statement)
7780 (js2-get-token)
7781 (js2-parse-function-stmt))))
7782 (decf js2-nesting-of-function))
7783 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7784 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7785 (setq end (js2-current-token-end)))
7786 (setf (js2-node-pos pn) pos
7787 (js2-node-len pn) (- end pos))
7788 (setf (js2-function-node-body fn-node) pn)
7789 (js2-node-add-children fn-node pn)
7790 pn))
7791
7792 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7793 "Declare and fontify destructuring parameters inside NODE.
7794 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7795 (cond
7796 ((js2-name-node-p node)
7797 (let (leftpos)
7798 (js2-define-symbol decl-type (js2-name-node-name node)
7799 node ignore-not-in-block)
7800 (when face
7801 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7802 (+ leftpos (js2-node-len node))
7803 face 'record))))
7804 ((js2-object-node-p node)
7805 (dolist (elem (js2-object-node-elems node))
7806 (js2-define-destruct-symbols
7807 ;; In abbreviated destructuring {a, b}, right == left.
7808 (js2-object-prop-node-right elem)
7809 decl-type face ignore-not-in-block)))
7810 ((js2-array-node-p node)
7811 (dolist (elem (js2-array-node-elems node))
7812 (when elem
7813 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7814 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7815 (js2-node-len node)))))
7816
7817 (defun js2-parse-function-params (function-type fn-node pos)
7818 (if (js2-match-token js2-RP)
7819 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7820 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7821 (eq (js2-current-token-type) js2-NAME)))
7822 params param default-found rest-param-at)
7823 (when paren-free-arrow
7824 (js2-unget-token))
7825 (loop for tt = (js2-peek-token)
7826 do
7827 (cond
7828 ;; destructuring param
7829 ((and (not paren-free-arrow)
7830 (or (= tt js2-LB) (= tt js2-LC)))
7831 (js2-get-token)
7832 (when default-found
7833 (js2-report-error "msg.no.default.after.default.param"))
7834 (setq param (js2-parse-destruct-primary-expr))
7835 (js2-define-destruct-symbols param
7836 js2-LP
7837 'js2-function-param)
7838 (push param params))
7839 ;; variable name
7840 (t
7841 (when (and (>= js2-language-version 200)
7842 (not paren-free-arrow)
7843 (js2-match-token js2-TRIPLEDOT)
7844 (not rest-param-at))
7845 ;; to report errors if there are more parameters
7846 (setq rest-param-at (length params)))
7847 (js2-must-match-name "msg.no.parm")
7848 (js2-record-face 'js2-function-param)
7849 (setq param (js2-create-name-node))
7850 (js2-define-symbol js2-LP (js2-current-token-string) param)
7851 ;; default parameter value
7852 (when (or (and default-found
7853 (not rest-param-at)
7854 (js2-must-match js2-ASSIGN
7855 "msg.no.default.after.default.param"
7856 (js2-node-pos param)
7857 (js2-node-len param)))
7858 (and (>= js2-language-version 200)
7859 (js2-match-token js2-ASSIGN)))
7860 (assert (not paren-free-arrow))
7861 (let* ((pos (js2-node-pos param))
7862 (tt (js2-current-token-type))
7863 (op-pos (- (js2-current-token-beg) pos))
7864 (left param)
7865 (right (js2-parse-assign-expr))
7866 (len (- (js2-node-end right) pos)))
7867 (setq param (make-js2-assign-node
7868 :type tt :pos pos :len len :op-pos op-pos
7869 :left left :right right)
7870 default-found t)
7871 (js2-node-add-children param left right)))
7872 (push param params)))
7873 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7874 (js2-report-error "msg.param.after.rest" nil
7875 (js2-node-pos param) (js2-node-len param)))
7876 while
7877 (js2-match-token js2-COMMA))
7878 (when (and (not paren-free-arrow)
7879 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7880 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7881 (when rest-param-at
7882 (setf (js2-function-node-rest-p fn-node) t))
7883 (dolist (p params)
7884 (js2-node-add-children fn-node p)
7885 (push p (js2-function-node-params fn-node))))))
7886
7887 (defun js2-check-inconsistent-return-warning (fn-node name)
7888 "Possibly show inconsistent-return warning.
7889 Last token scanned is the close-curly for the function body."
7890 (when (and js2-mode-show-strict-warnings
7891 js2-strict-inconsistent-return-warning
7892 (not (js2-has-consistent-return-usage
7893 (js2-function-node-body fn-node))))
7894 ;; Have it extend from close-curly to bol or beginning of block.
7895 (let ((pos (save-excursion
7896 (goto-char (js2-current-token-end))
7897 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7898 (point-at-bol))))
7899 (end (js2-current-token-end)))
7900 (if (plusp (js2-name-node-length name))
7901 (js2-add-strict-warning "msg.no.return.value"
7902 (js2-name-node-name name) pos end)
7903 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7904
7905 (defun js2-parse-function-stmt ()
7906 (let ((pos (js2-current-token-beg))
7907 (star-p (js2-match-token js2-MUL)))
7908 (js2-must-match-name "msg.unnamed.function.stmt")
7909 (let ((name (js2-create-name-node t))
7910 pn member-expr)
7911 (cond
7912 ((js2-match-token js2-LP)
7913 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7914 (js2-allow-member-expr-as-function-name
7915 (setq member-expr (js2-parse-member-expr-tail nil name))
7916 (js2-parse-highlight-member-expr-fn-name member-expr)
7917 (js2-must-match js2-LP "msg.no.paren.parms")
7918 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7919 (js2-function-node-member-expr pn) member-expr)
7920 pn)
7921 (t
7922 (js2-report-error "msg.no.paren.parms")
7923 (make-js2-error-node))))))
7924
7925 (defun js2-parse-function-expr ()
7926 (let ((pos (js2-current-token-beg))
7927 (star-p (js2-match-token js2-MUL))
7928 name)
7929 (when (js2-match-token js2-NAME)
7930 (setq name (js2-create-name-node t)))
7931 (js2-must-match js2-LP "msg.no.paren.parms")
7932 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7933
7934 (defun js2-parse-function (function-type pos star-p &optional name)
7935 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7936 beginning of the first token (function keyword, unless it's an
7937 arrow function), NAME is js2-name-node."
7938 (let (fn-node lp)
7939 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7940 (setq lp (js2-current-token-beg)))
7941 (setf fn-node (make-js2-function-node :pos pos
7942 :name name
7943 :form function-type
7944 :lp (if lp (- lp pos))
7945 :generator-type (and star-p 'STAR)))
7946 (when name
7947 (js2-set-face (js2-node-pos name) (js2-node-end name)
7948 'font-lock-function-name-face 'record)
7949 (when (and (eq function-type 'FUNCTION_STATEMENT)
7950 (plusp (js2-name-node-length name)))
7951 ;; Function statements define a symbol in the enclosing scope
7952 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7953 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7954 ;; 1. Nested functions are not affected by the dynamic scope flag
7955 ;; as dynamic scope is already a parent of their scope.
7956 ;; 2. Functions defined under the with statement also immune to
7957 ;; this setup, in which case dynamic scope is ignored in favor
7958 ;; of the with object.
7959 (setf (js2-function-node-ignore-dynamic fn-node) t))
7960 ;; dynamically bind all the per-function variables
7961 (let ((js2-current-script-or-fn fn-node)
7962 (js2-current-scope fn-node)
7963 (js2-nesting-of-with 0)
7964 (js2-end-flags 0)
7965 js2-label-set
7966 js2-loop-set
7967 js2-loop-and-switch-set)
7968 (js2-parse-function-params function-type fn-node pos)
7969 (when (eq function-type 'FUNCTION_ARROW)
7970 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7971 (if (and (>= js2-language-version 180)
7972 (/= (js2-peek-token) js2-LC))
7973 (js2-parse-function-closure-body fn-node)
7974 (js2-parse-function-body fn-node))
7975 (js2-check-inconsistent-return-warning fn-node name)
7976
7977 (when name
7978 (js2-node-add-children fn-node name)
7979 ;; Function expressions define a name only in the body of the
7980 ;; function, and only if not hidden by a parameter name
7981 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7982 (null (js2-scope-get-symbol js2-current-scope
7983 (js2-name-node-name name))))
7984 (js2-define-symbol js2-FUNCTION
7985 (js2-name-node-name name)
7986 fn-node))
7987 (when (eq function-type 'FUNCTION_STATEMENT)
7988 (js2-record-imenu-functions fn-node))))
7989
7990 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7991 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7992 ;; We wait until after parsing the function to set its parent scope,
7993 ;; since `js2-define-symbol' needs the defining-scope check to stop
7994 ;; at the function boundary when checking for redeclarations.
7995 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7996 fn-node))
7997
7998 (defun js2-parse-statements (&optional parent)
7999 "Parse a statement list. Last token consumed must be js2-LC.
8000
8001 PARENT can be a `js2-block-node', in which case the statements are
8002 appended to PARENT. Otherwise a new `js2-block-node' is created
8003 and returned.
8004
8005 This function does not match the closing js2-RC: the caller
8006 matches the RC so it can provide a suitable error message if not
8007 matched. This means it's up to the caller to set the length of
8008 the node to include the closing RC. The node start pos is set to
8009 the absolute buffer start position, and the caller should fix it
8010 up to be relative to the parent node. All children of this block
8011 node are given relative start positions and correct lengths."
8012 (let ((pn (or parent (make-js2-block-node)))
8013 tt)
8014 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8015 (/= tt js2-RC))
8016 (js2-block-node-push pn (js2-parse-statement)))
8017 pn))
8018
8019 (defun js2-parse-statement ()
8020 (let (pn beg end)
8021 ;; coarse-grained user-interrupt check - needs work
8022 (and js2-parse-interruptable-p
8023 (zerop (% (incf js2-parse-stmt-count)
8024 js2-statements-per-pause))
8025 (input-pending-p)
8026 (throw 'interrupted t))
8027 (setq pn (js2-statement-helper))
8028 ;; no-side-effects warning check
8029 (unless (js2-node-has-side-effects pn)
8030 (setq end (js2-node-end pn))
8031 (save-excursion
8032 (goto-char end)
8033 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8034 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8035 pn))
8036
8037 ;; These correspond to the switch cases in Parser.statementHelper
8038 (defconst js2-parsers
8039 (let ((parsers (make-vector js2-num-tokens
8040 #'js2-parse-expr-stmt)))
8041 (aset parsers js2-BREAK #'js2-parse-break)
8042 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8043 (aset parsers js2-CONST #'js2-parse-const-var)
8044 (aset parsers js2-CONTINUE #'js2-parse-continue)
8045 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8046 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8047 (aset parsers js2-DO #'js2-parse-do)
8048 (aset parsers js2-EXPORT #'js2-parse-export)
8049 (aset parsers js2-FOR #'js2-parse-for)
8050 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8051 (aset parsers js2-IF #'js2-parse-if)
8052 (aset parsers js2-IMPORT #'js2-parse-import)
8053 (aset parsers js2-LC #'js2-parse-block)
8054 (aset parsers js2-LET #'js2-parse-let-stmt)
8055 (aset parsers js2-NAME #'js2-parse-name-or-label)
8056 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8057 (aset parsers js2-SEMI #'js2-parse-semi)
8058 (aset parsers js2-SWITCH #'js2-parse-switch)
8059 (aset parsers js2-THROW #'js2-parse-throw)
8060 (aset parsers js2-TRY #'js2-parse-try)
8061 (aset parsers js2-VAR #'js2-parse-const-var)
8062 (aset parsers js2-WHILE #'js2-parse-while)
8063 (aset parsers js2-WITH #'js2-parse-with)
8064 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8065 parsers)
8066 "A vector mapping token types to parser functions.")
8067
8068 (defun js2-parse-warn-missing-semi (beg end)
8069 (and js2-mode-show-strict-warnings
8070 js2-strict-missing-semi-warning
8071 (js2-add-strict-warning
8072 "msg.missing.semi" nil
8073 ;; back up to beginning of statement or line
8074 (max beg (save-excursion
8075 (goto-char end)
8076 (point-at-bol)))
8077 end)))
8078
8079 (defconst js2-no-semi-insertion
8080 (list js2-IF
8081 js2-SWITCH
8082 js2-WHILE
8083 js2-DO
8084 js2-FOR
8085 js2-TRY
8086 js2-WITH
8087 js2-LC
8088 js2-ERROR
8089 js2-SEMI
8090 js2-CLASS
8091 js2-FUNCTION)
8092 "List of tokens that don't do automatic semicolon insertion.")
8093
8094 (defconst js2-autoinsert-semi-and-warn
8095 (list js2-ERROR js2-EOF js2-RC))
8096
8097 (defun js2-statement-helper ()
8098 (let* ((tt (js2-get-token))
8099 (first-tt tt)
8100 (parser (if (= tt js2-ERROR)
8101 #'js2-parse-semi
8102 (aref js2-parsers tt)))
8103 pn)
8104 ;; If the statement is set, then it's been told its label by now.
8105 (and js2-labeled-stmt
8106 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8107 (setq js2-labeled-stmt nil))
8108 (setq pn (funcall parser))
8109 ;; Don't do auto semi insertion for certain statement types.
8110 (unless (or (memq first-tt js2-no-semi-insertion)
8111 (js2-labeled-stmt-node-p pn))
8112 (js2-auto-insert-semicolon pn))
8113 pn))
8114
8115 (defun js2-auto-insert-semicolon (pn)
8116 (let* ((tt (js2-get-token))
8117 (pos (js2-node-pos pn)))
8118 (cond
8119 ((= tt js2-SEMI)
8120 ;; extend the node bounds to include the semicolon.
8121 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8122 ((memq tt js2-autoinsert-semi-and-warn)
8123 (js2-unget-token) ; Not ';', do not consume.
8124 ;; Autoinsert ;
8125 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8126 (t
8127 (if (not (js2-token-follows-eol-p (js2-current-token)))
8128 ;; Report error if no EOL or autoinsert ';' otherwise
8129 (js2-report-error "msg.no.semi.stmt")
8130 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8131 (js2-unget-token) ; Not ';', do not consume.
8132 ))))
8133
8134 (defun js2-parse-condition ()
8135 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8136 The parens are discarded and the expression node is returned.
8137 The `pos' field of the return value is set to an absolute position
8138 that must be fixed up by the caller.
8139 Return value is a list (EXPR LP RP), with absolute paren positions."
8140 (let (pn lp rp)
8141 (if (js2-must-match js2-LP "msg.no.paren.cond")
8142 (setq lp (js2-current-token-beg)))
8143 (setq pn (js2-parse-expr))
8144 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8145 (setq rp (js2-current-token-beg)))
8146 ;; Report strict warning on code like "if (a = 7) ..."
8147 (if (and js2-strict-cond-assign-warning
8148 (js2-assign-node-p pn))
8149 (js2-add-strict-warning "msg.equal.as.assign" nil
8150 (js2-node-pos pn)
8151 (+ (js2-node-pos pn)
8152 (js2-node-len pn))))
8153 (list pn lp rp)))
8154
8155 (defun js2-parse-if ()
8156 "Parser for if-statement. Last matched token must be js2-IF."
8157 (let ((pos (js2-current-token-beg))
8158 cond if-true if-false else-pos end pn)
8159 (setq cond (js2-parse-condition)
8160 if-true (js2-parse-statement)
8161 if-false (if (js2-match-token js2-ELSE)
8162 (progn
8163 (setq else-pos (- (js2-current-token-beg) pos))
8164 (js2-parse-statement)))
8165 end (js2-node-end (or if-false if-true))
8166 pn (make-js2-if-node :pos pos
8167 :len (- end pos)
8168 :condition (car cond)
8169 :then-part if-true
8170 :else-part if-false
8171 :else-pos else-pos
8172 :lp (js2-relpos (second cond) pos)
8173 :rp (js2-relpos (third cond) pos)))
8174 (js2-node-add-children pn (car cond) if-true if-false)
8175 pn))
8176
8177 (defun js2-parse-import ()
8178 "Parse import statement. The current token must be js2-IMPORT."
8179 (unless (js2-ast-root-p js2-current-scope)
8180 (js2-report-error "msg.mod.import.decl.at.top.level"))
8181 (let ((beg (js2-current-token-beg)))
8182 (cond ((js2-match-token js2-STRING)
8183 (make-js2-import-node
8184 :pos beg
8185 :len (- (js2-current-token-end) beg)
8186 :module-id (js2-current-token-string)))
8187 (t
8188 (let* ((import-clause (js2-parse-import-clause))
8189 (from-clause (and import-clause (js2-parse-from-clause)))
8190 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8191 (node (make-js2-import-node
8192 :pos beg
8193 :len (- (js2-current-token-end) beg)
8194 :import import-clause
8195 :from from-clause
8196 :module-id module-id)))
8197 (when import-clause
8198 (js2-node-add-children node import-clause))
8199 (when from-clause
8200 (js2-node-add-children node from-clause))
8201 node)))))
8202
8203 (defun js2-parse-import-clause ()
8204 "Parse the bindings in an import statement.
8205 This can take many forms:
8206
8207 ImportedDefaultBinding -> 'foo'
8208 NameSpaceImport -> '* as lib'
8209 NamedImports -> '{foo as bar, bang}'
8210 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8211 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8212
8213 Try to match namespace imports and named imports first because nothing can
8214 come after them. If it is an imported default binding, then it could have named
8215 imports or a namespace import that follows it.
8216 "
8217 (let* ((beg (js2-current-token-beg))
8218 (clause (make-js2-import-clause-node
8219 :pos beg))
8220 (children (list)))
8221 (cond
8222 ((js2-match-token js2-MUL)
8223 (let ((ns-import (js2-parse-namespace-import)))
8224 (when ns-import
8225 (let ((name-node (js2-namespace-import-node-name ns-import)))
8226 (js2-define-symbol
8227 js2-LET (js2-name-node-name name-node) name-node t)))
8228 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8229 (push ns-import children)))
8230 ((js2-match-token js2-LC)
8231 (let ((imports (js2-parse-export-bindings t)))
8232 (setf (js2-import-clause-node-named-imports clause) imports)
8233 (dolist (import imports)
8234 (push import children)
8235 (let ((name-node (js2-export-binding-node-local-name import)))
8236 (when name-node
8237 (js2-define-symbol
8238 js2-LET (js2-name-node-name name-node) name-node t))))))
8239 ((= (js2-peek-token) js2-NAME)
8240 (let ((binding (js2-maybe-parse-export-binding)))
8241 (let ((node-name (js2-export-binding-node-local-name binding)))
8242 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8243 (setf (js2-import-clause-node-default-binding clause) binding)
8244 (push binding children))
8245 (when (js2-match-token js2-COMMA)
8246 (cond
8247 ((js2-match-token js2-MUL)
8248 (let ((ns-import (js2-parse-namespace-import)))
8249 (let ((name-node (js2-namespace-import-node-name ns-import)))
8250 (js2-define-symbol
8251 js2-LET (js2-name-node-name name-node) name-node t))
8252 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8253 (push ns-import children)))
8254 ((js2-match-token js2-LC)
8255 (let ((imports (js2-parse-export-bindings t)))
8256 (setf (js2-import-clause-node-named-imports clause) imports)
8257 (dolist (import imports)
8258 (push import children)
8259 (let ((name-node (js2-export-binding-node-local-name import)))
8260 (when name-node
8261 (js2-define-symbol
8262 js2-LET (js2-name-node-name name-node) name-node t))))))
8263 (t (js2-report-error "msg.syntax")))))
8264 (t (js2-report-error "msg.mod.declaration.after.import")))
8265 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8266 (apply #'js2-node-add-children clause children)
8267 clause))
8268
8269 (defun js2-parse-namespace-import ()
8270 "Parse a namespace import expression such as '* as bar'.
8271 The current token must be js2-MUL."
8272 (let ((beg (js2-current-token-beg)))
8273 (when (js2-must-match js2-NAME "msg.syntax")
8274 (if (equal "as" (js2-current-token-string))
8275 (when (js2-must-match-prop-name "msg.syntax")
8276 (let ((node (make-js2-namespace-import-node
8277 :pos beg
8278 :len (- (js2-current-token-end) beg)
8279 :name (make-js2-name-node
8280 :pos (js2-current-token-beg)
8281 :len (js2-current-token-end)
8282 :name (js2-current-token-string)))))
8283 (js2-node-add-children node (js2-namespace-import-node-name node))
8284 node))
8285 (js2-unget-token)
8286 (js2-report-error "msg.syntax")))))
8287
8288
8289 (defun js2-parse-from-clause ()
8290 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8291 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8292 (let ((beg (js2-current-token-beg)))
8293 (if (equal "from" (js2-current-token-string))
8294 (cond
8295 ((js2-match-token js2-STRING)
8296 (make-js2-from-clause-node
8297 :pos beg
8298 :len (- (js2-current-token-end) beg)
8299 :module-id (js2-current-token-string)
8300 :metadata-p nil))
8301 ((js2-match-token js2-THIS)
8302 (when (js2-must-match-name "msg.mod.spec.after.from")
8303 (if (equal "module" (js2-current-token-string))
8304 (make-js2-from-clause-node
8305 :pos beg
8306 :len (- (js2-current-token-end) beg)
8307 :module-id "this"
8308 :metadata-p t)
8309 (js2-unget-token)
8310 (js2-unget-token)
8311 (js2-report-error "msg.mod.spec.after.from")
8312 nil)))
8313 (t (js2-report-error "msg.mod.spec.after.from") nil))
8314 (js2-unget-token)
8315 (js2-report-error "msg.mod.from.after.import.spec.set")
8316 nil))))
8317
8318 (defun js2-parse-export-bindings (&optional import-p)
8319 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8320 {foo as bar, baz as bang}. The current token must be
8321 js2-LC. Return a lisp list of js2-export-binding-node"
8322 (let ((bindings (list)))
8323 (while
8324 (let ((binding (js2-maybe-parse-export-binding)))
8325 (when binding
8326 (push binding bindings))
8327 (js2-match-token js2-COMMA)))
8328 (when (js2-must-match js2-RC (if import-p
8329 "msg.mod.rc.after.import.spec.list"
8330 "msg.mod.rc.after.export.spec.list"))
8331 (reverse bindings))))
8332
8333 (defun js2-maybe-parse-export-binding ()
8334 "Attempt to parse a binding expression found inside an import/export statement.
8335 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8336 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8337 js2-export-binding-node and consume all the tokens. If it does not match, it
8338 consumes no tokens."
8339 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8340 (beg (js2-current-token-beg))
8341 (extern-name-len (js2-current-token-len))
8342 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8343 (aref js2-kwd-tokens (js2-current-token-type)))))
8344 (if extern-name
8345 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8346 (if (and as (equal "as" (js2-current-token-string)))
8347 (let ((name
8348 (or
8349 (and (js2-match-token js2-DEFAULT) "default")
8350 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8351 (if name
8352 (let ((node (make-js2-export-binding-node
8353 :pos beg
8354 :len (- (js2-current-token-end) beg)
8355 :local-name (make-js2-name-node
8356 :name name
8357 :pos (js2-current-token-beg)
8358 :len (js2-current-token-len))
8359 :extern-name (make-js2-name-node
8360 :name extern-name
8361 :pos beg
8362 :len extern-name-len))))
8363 (js2-node-add-children
8364 node
8365 (js2-export-binding-node-local-name node)
8366 (js2-export-binding-node-extern-name node))
8367 node)
8368 (js2-unget-token)
8369 nil))
8370 (when as (js2-unget-token))
8371 (let* ((name-node (make-js2-name-node
8372 :name (js2-current-token-string)
8373 :pos (js2-current-token-beg)
8374 :len (js2-current-token-len)))
8375 (node (make-js2-export-binding-node
8376 :pos (js2-current-token-beg)
8377 :len (js2-current-token-len)
8378 :local-name name-node
8379 :extern-name name-node)))
8380 (when is-reserved-name
8381 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8382 (js2-node-add-children node name-node)
8383 node)))
8384 nil)))
8385
8386 (defun js2-parse-switch ()
8387 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8388 (let ((pos (js2-current-token-beg))
8389 tt pn discriminant has-default case-expr case-node
8390 case-pos cases stmt lp)
8391 (if (js2-must-match js2-LP "msg.no.paren.switch")
8392 (setq lp (js2-current-token-beg)))
8393 (setq discriminant (js2-parse-expr)
8394 pn (make-js2-switch-node :discriminant discriminant
8395 :pos pos
8396 :lp (js2-relpos lp pos)))
8397 (js2-node-add-children pn discriminant)
8398 (js2-enter-switch pn)
8399 (unwind-protect
8400 (progn
8401 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8402 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8403 (js2-must-match js2-LC "msg.no.brace.switch")
8404 (catch 'break
8405 (while t
8406 (setq tt (js2-next-token)
8407 case-pos (js2-current-token-beg))
8408 (cond
8409 ((= tt js2-RC)
8410 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8411 (throw 'break nil)) ; done
8412 ((= tt js2-CASE)
8413 (setq case-expr (js2-parse-expr))
8414 (js2-must-match js2-COLON "msg.no.colon.case"))
8415 ((= tt js2-DEFAULT)
8416 (if has-default
8417 (js2-report-error "msg.double.switch.default"))
8418 (setq has-default t
8419 case-expr nil)
8420 (js2-must-match js2-COLON "msg.no.colon.case"))
8421 (t
8422 (js2-report-error "msg.bad.switch")
8423 (throw 'break nil)))
8424 (setq case-node (make-js2-case-node :pos case-pos
8425 :len (- (js2-current-token-end) case-pos)
8426 :expr case-expr))
8427 (js2-node-add-children case-node case-expr)
8428 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8429 (/= tt js2-CASE)
8430 (/= tt js2-DEFAULT)
8431 (/= tt js2-EOF))
8432 (setf stmt (js2-parse-statement)
8433 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8434 (js2-block-node-push case-node stmt))
8435 (push case-node cases)))
8436 ;; add cases last, as pushing reverses the order to be correct
8437 (dolist (kid cases)
8438 (js2-node-add-children pn kid)
8439 (push kid (js2-switch-node-cases pn)))
8440 pn) ; return value
8441 (js2-exit-switch))))
8442
8443 (defun js2-parse-while ()
8444 "Parser for while-statement. Last matched token must be js2-WHILE."
8445 (let ((pos (js2-current-token-beg))
8446 (pn (make-js2-while-node))
8447 cond body)
8448 (js2-enter-loop pn)
8449 (unwind-protect
8450 (progn
8451 (setf cond (js2-parse-condition)
8452 (js2-while-node-condition pn) (car cond)
8453 body (js2-parse-statement)
8454 (js2-while-node-body pn) body
8455 (js2-node-len pn) (- (js2-node-end body) pos)
8456 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
8457 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
8458 (js2-node-add-children pn body (car cond)))
8459 (js2-exit-loop))
8460 pn))
8461
8462 (defun js2-parse-do ()
8463 "Parser for do-statement. Last matched token must be js2-DO."
8464 (let ((pos (js2-current-token-beg))
8465 (pn (make-js2-do-node))
8466 cond body end)
8467 (js2-enter-loop pn)
8468 (unwind-protect
8469 (progn
8470 (setq body (js2-parse-statement))
8471 (js2-must-match js2-WHILE "msg.no.while.do")
8472 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8473 cond (js2-parse-condition)
8474 (js2-do-node-condition pn) (car cond)
8475 (js2-do-node-body pn) body
8476 end js2-ts-cursor
8477 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
8478 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
8479 (js2-node-add-children pn (car cond) body))
8480 (js2-exit-loop))
8481 ;; Always auto-insert semicolon to follow SpiderMonkey:
8482 ;; It is required by ECMAScript but is ignored by the rest of
8483 ;; world; see bug 238945
8484 (if (js2-match-token js2-SEMI)
8485 (setq end js2-ts-cursor))
8486 (setf (js2-node-len pn) (- end pos))
8487 pn))
8488
8489 (defun js2-parse-export ()
8490 "Parse an export statement.
8491 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8492 expressions should only be either hoistable expressions (function or generator)
8493 or assignment expressions, but there is no checking to enforce that and so it
8494 will parse without error a small subset of
8495 invalid export statements."
8496 (unless (js2-ast-root-p js2-current-scope)
8497 (js2-report-error "msg.mod.export.decl.at.top.level"))
8498 (let ((beg (js2-current-token-beg))
8499 (children (list))
8500 exports-list from-clause declaration default)
8501 (cond
8502 ((js2-match-token js2-MUL)
8503 (setq from-clause (js2-parse-from-clause))
8504 (when from-clause
8505 (push from-clause children)))
8506 ((js2-match-token js2-LC)
8507 (setq exports-list (js2-parse-export-bindings))
8508 (when exports-list
8509 (dolist (export exports-list)
8510 (push export children)))
8511 (when (js2-match-token js2-NAME)
8512 (if (equal "from" (js2-current-token-string))
8513 (progn
8514 (js2-unget-token)
8515 (setq from-clause (js2-parse-from-clause)))
8516 (js2-unget-token))))
8517 ((js2-match-token js2-DEFAULT)
8518 (setq default (js2-parse-expr)))
8519 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8520 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8521 (t
8522 (setq declaration (js2-parse-expr))))
8523 (when from-clause
8524 (push from-clause children))
8525 (when declaration
8526 (push declaration children))
8527 (when default
8528 (push default children))
8529 (let ((node (make-js2-export-node
8530 :pos beg
8531 :len (- (js2-current-token-end) beg)
8532 :exports-list exports-list
8533 :from-clause from-clause
8534 :declaration declaration
8535 :default default)))
8536 (apply #'js2-node-add-children node children)
8537 node)))
8538
8539 (defun js2-parse-for ()
8540 "Parse a for, for-in or for each-in statement.
8541 Last matched token must be js2-FOR."
8542 (let ((for-pos (js2-current-token-beg))
8543 pn is-for-each is-for-in-or-of is-for-of
8544 in-pos each-pos tmp-pos
8545 init ; Node init is also foo in 'foo in object'.
8546 cond ; Node cond is also object in 'foo in object'.
8547 incr ; 3rd section of for-loop initializer.
8548 body tt lp rp)
8549 ;; See if this is a for each () instead of just a for ()
8550 (when (js2-match-token js2-NAME)
8551 (if (string= "each" (js2-current-token-string))
8552 (progn
8553 (setq is-for-each t
8554 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8555 (js2-record-face 'font-lock-keyword-face))
8556 (js2-report-error "msg.no.paren.for")))
8557 (if (js2-must-match js2-LP "msg.no.paren.for")
8558 (setq lp (- (js2-current-token-beg) for-pos)))
8559 (setq tt (js2-get-token))
8560 ;; 'for' makes local scope
8561 (js2-push-scope (make-js2-scope))
8562 (unwind-protect
8563 ;; parse init clause
8564 (let ((js2-in-for-init t)) ; set as dynamic variable
8565 (cond
8566 ((= tt js2-SEMI)
8567 (js2-unget-token)
8568 (setq init (make-js2-empty-expr-node)))
8569 ((or (= tt js2-VAR) (= tt js2-LET))
8570 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8571 (t
8572 (js2-unget-token)
8573 (setq init (js2-parse-expr)))))
8574 (if (or (js2-match-token js2-IN)
8575 (and (>= js2-language-version 200)
8576 (js2-match-contextual-kwd "of")
8577 (setq is-for-of t)))
8578 (setq is-for-in-or-of t
8579 in-pos (- (js2-current-token-beg) for-pos)
8580 ;; scope of iteration target object is not the scope we've created above.
8581 ;; stash current scope temporary.
8582 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8583 (js2-parse-expr))) ; object over which we're iterating
8584 ;; else ordinary for loop - parse cond and incr
8585 (js2-must-match js2-SEMI "msg.no.semi.for")
8586 (setq cond (if (= (js2-peek-token) js2-SEMI)
8587 (make-js2-empty-expr-node) ; no loop condition
8588 (js2-parse-expr)))
8589 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8590 (setq tmp-pos (js2-current-token-end)
8591 incr (if (= (js2-peek-token) js2-RP)
8592 (make-js2-empty-expr-node :pos tmp-pos)
8593 (js2-parse-expr))))
8594 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8595 (setq rp (- (js2-current-token-beg) for-pos)))
8596 (if (not is-for-in-or-of)
8597 (setq pn (make-js2-for-node :init init
8598 :condition cond
8599 :update incr
8600 :lp lp
8601 :rp rp))
8602 ;; cond could be null if 'in obj' got eaten by the init node.
8603 (if (js2-infix-node-p init)
8604 ;; it was (foo in bar) instead of (var foo in bar)
8605 (setq cond (js2-infix-node-right init)
8606 init (js2-infix-node-left init))
8607 (if (and (js2-var-decl-node-p init)
8608 (> (length (js2-var-decl-node-kids init)) 1))
8609 (js2-report-error "msg.mult.index")))
8610 (setq pn (make-js2-for-in-node :iterator init
8611 :object cond
8612 :in-pos in-pos
8613 :foreach-p is-for-each
8614 :each-pos each-pos
8615 :forof-p is-for-of
8616 :lp lp
8617 :rp rp)))
8618 (unwind-protect
8619 (progn
8620 (js2-enter-loop pn)
8621 ;; We have to parse the body -after- creating the loop node,
8622 ;; so that the loop node appears in the js2-loop-set, allowing
8623 ;; break/continue statements to find the enclosing loop.
8624 (setf body (js2-parse-statement)
8625 (js2-loop-node-body pn) body
8626 (js2-node-pos pn) for-pos
8627 (js2-node-len pn) (- (js2-node-end body) for-pos))
8628 (js2-node-add-children pn init cond incr body))
8629 ;; finally
8630 (js2-exit-loop))
8631 (js2-pop-scope))
8632 pn))
8633
8634 (defun js2-parse-try ()
8635 "Parse a try statement. Last matched token must be js2-TRY."
8636 (let ((try-pos (js2-current-token-beg))
8637 try-end
8638 try-block
8639 catch-blocks
8640 finally-block
8641 saw-default-catch
8642 peek)
8643 (if (/= (js2-peek-token) js2-LC)
8644 (js2-report-error "msg.no.brace.try"))
8645 (setq try-block (js2-parse-statement)
8646 try-end (js2-node-end try-block)
8647 peek (js2-peek-token))
8648 (cond
8649 ((= peek js2-CATCH)
8650 (while (js2-match-token js2-CATCH)
8651 (let* ((catch-pos (js2-current-token-beg))
8652 (catch-node (make-js2-catch-node :pos catch-pos))
8653 param
8654 guard-kwd
8655 catch-cond
8656 lp rp)
8657 (if saw-default-catch
8658 (js2-report-error "msg.catch.unreachable"))
8659 (if (js2-must-match js2-LP "msg.no.paren.catch")
8660 (setq lp (- (js2-current-token-beg) catch-pos)))
8661 (js2-push-scope catch-node)
8662 (let ((tt (js2-peek-token)))
8663 (cond
8664 ;; Destructuring pattern:
8665 ;; catch ({ message, file }) { ... }
8666 ((or (= tt js2-LB) (= tt js2-LC))
8667 (js2-get-token)
8668 (setq param (js2-parse-destruct-primary-expr))
8669 (js2-define-destruct-symbols param js2-LET nil))
8670 ;; Simple name.
8671 (t
8672 (js2-must-match-name "msg.bad.catchcond")
8673 (setq param (js2-create-name-node))
8674 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8675 ;; Catch condition.
8676 (if (js2-match-token js2-IF)
8677 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8678 catch-cond (js2-parse-expr))
8679 (setq saw-default-catch t))
8680 (if (js2-must-match js2-RP "msg.bad.catchcond")
8681 (setq rp (- (js2-current-token-beg) catch-pos)))
8682 (js2-must-match js2-LC "msg.no.brace.catchblock")
8683 (js2-parse-statements catch-node)
8684 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8685 (setq try-end (js2-current-token-end)))
8686 (js2-pop-scope)
8687 (setf (js2-node-len catch-node) (- try-end catch-pos)
8688 (js2-catch-node-param catch-node) param
8689 (js2-catch-node-guard-expr catch-node) catch-cond
8690 (js2-catch-node-guard-kwd catch-node) guard-kwd
8691 (js2-catch-node-lp catch-node) lp
8692 (js2-catch-node-rp catch-node) rp)
8693 (js2-node-add-children catch-node param catch-cond)
8694 (push catch-node catch-blocks))))
8695 ((/= peek js2-FINALLY)
8696 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8697 (js2-node-pos try-block)
8698 (- (setq try-end (js2-node-end try-block))
8699 (js2-node-pos try-block)))))
8700 (when (js2-match-token js2-FINALLY)
8701 (let ((finally-pos (js2-current-token-beg))
8702 (block (js2-parse-statement)))
8703 (setq try-end (js2-node-end block)
8704 finally-block (make-js2-finally-node :pos finally-pos
8705 :len (- try-end finally-pos)
8706 :body block))
8707 (js2-node-add-children finally-block block)))
8708 (let ((pn (make-js2-try-node :pos try-pos
8709 :len (- try-end try-pos)
8710 :try-block try-block
8711 :finally-block finally-block)))
8712 (js2-node-add-children pn try-block finally-block)
8713 ;; Push them onto the try-node, which reverses and corrects their order.
8714 (dolist (cb catch-blocks)
8715 (js2-node-add-children pn cb)
8716 (push cb (js2-try-node-catch-clauses pn)))
8717 pn)))
8718
8719 (defun js2-parse-throw ()
8720 "Parser for throw-statement. Last matched token must be js2-THROW."
8721 (let ((pos (js2-current-token-beg))
8722 expr pn)
8723 (if (= (js2-peek-token-or-eol) js2-EOL)
8724 ;; ECMAScript does not allow new lines before throw expression,
8725 ;; see bug 256617
8726 (js2-report-error "msg.bad.throw.eol"))
8727 (setq expr (js2-parse-expr)
8728 pn (make-js2-throw-node :pos pos
8729 :len (- (js2-node-end expr) pos)
8730 :expr expr))
8731 (js2-node-add-children pn expr)
8732 pn))
8733
8734 (defun js2-match-jump-label-name (label-name)
8735 "If break/continue specified a label, return that label's labeled stmt.
8736 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8737 does not match an existing label, reports an error and returns nil."
8738 (let ((bundle (cdr (assoc label-name js2-label-set))))
8739 (if (null bundle)
8740 (js2-report-error "msg.undef.label"))
8741 bundle))
8742
8743 (defun js2-parse-break ()
8744 "Parser for break-statement. Last matched token must be js2-BREAK."
8745 (let ((pos (js2-current-token-beg))
8746 (end (js2-current-token-end))
8747 break-target ; statement to break from
8748 break-label ; in "break foo", name-node representing the foo
8749 labels ; matching labeled statement to break to
8750 pn)
8751 (when (eq (js2-peek-token-or-eol) js2-NAME)
8752 (js2-get-token)
8753 (setq break-label (js2-create-name-node)
8754 end (js2-node-end break-label)
8755 ;; matchJumpLabelName only matches if there is one
8756 labels (js2-match-jump-label-name (js2-current-token-string))
8757 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8758 (unless (or break-target break-label)
8759 ;; no break target specified - try for innermost enclosing loop/switch
8760 (if (null js2-loop-and-switch-set)
8761 (unless break-label
8762 (js2-report-error "msg.bad.break" nil pos (length "break")))
8763 (setq break-target (car js2-loop-and-switch-set))))
8764 (setq pn (make-js2-break-node :pos pos
8765 :len (- end pos)
8766 :label break-label
8767 :target break-target))
8768 (js2-node-add-children pn break-label) ; but not break-target
8769 pn))
8770
8771 (defun js2-parse-continue ()
8772 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8773 (let ((pos (js2-current-token-beg))
8774 (end (js2-current-token-end))
8775 label ; optional user-specified label, a `js2-name-node'
8776 labels ; current matching labeled stmt, if any
8777 target ; the `js2-loop-node' target of this continue stmt
8778 pn)
8779 (when (= (js2-peek-token-or-eol) js2-NAME)
8780 (js2-get-token)
8781 (setq label (js2-create-name-node)
8782 end (js2-node-end label)
8783 ;; matchJumpLabelName only matches if there is one
8784 labels (js2-match-jump-label-name (js2-current-token-string))))
8785 (cond
8786 ((null labels) ; no current label to go to
8787 (if (null js2-loop-set) ; no loop to continue to
8788 (js2-report-error "msg.continue.outside" nil pos
8789 (length "continue"))
8790 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8791 (t
8792 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8793 (setq target (js2-labeled-stmt-node-stmt labels))
8794 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8795 (setq pn (make-js2-continue-node :pos pos
8796 :len (- end pos)
8797 :label label
8798 :target target))
8799 (js2-node-add-children pn label) ; but not target - it's not our child
8800 pn))
8801
8802 (defun js2-parse-with ()
8803 "Parser for with-statement. Last matched token must be js2-WITH."
8804 (let ((pos (js2-current-token-beg))
8805 obj body pn lp rp)
8806 (if (js2-must-match js2-LP "msg.no.paren.with")
8807 (setq lp (js2-current-token-beg)))
8808 (setq obj (js2-parse-expr))
8809 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8810 (setq rp (js2-current-token-beg)))
8811 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8812 (setq body (js2-parse-statement)))
8813 (setq pn (make-js2-with-node :pos pos
8814 :len (- (js2-node-end body) pos)
8815 :object obj
8816 :body body
8817 :lp (js2-relpos lp pos)
8818 :rp (js2-relpos rp pos)))
8819 (js2-node-add-children pn obj body)
8820 pn))
8821
8822 (defun js2-parse-const-var ()
8823 "Parser for var- or const-statement.
8824 Last matched token must be js2-CONST or js2-VAR."
8825 (let ((tt (js2-current-token-type))
8826 (pos (js2-current-token-beg))
8827 expr pn)
8828 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8829 pn (make-js2-expr-stmt-node :pos pos
8830 :len (- (js2-node-end expr) pos)
8831 :expr expr))
8832 (js2-node-add-children pn expr)
8833 pn))
8834
8835 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8836 (let ((pn (make-js2-expr-stmt-node :pos pos
8837 :len (js2-node-len expr)
8838 :type (if (js2-inside-function)
8839 js2-EXPR_VOID
8840 js2-EXPR_RESULT)
8841 :expr expr)))
8842 (if add-child
8843 (js2-node-add-children pn expr))
8844 pn))
8845
8846 (defun js2-parse-let-stmt ()
8847 "Parser for let-statement. Last matched token must be js2-LET."
8848 (let ((pos (js2-current-token-beg))
8849 expr pn)
8850 (if (= (js2-peek-token) js2-LP)
8851 ;; let expression in statement context
8852 (setq expr (js2-parse-let pos 'statement)
8853 pn (js2-wrap-with-expr-stmt pos expr t))
8854 ;; else we're looking at a statement like let x=6, y=7;
8855 (setf expr (js2-parse-variables js2-LET pos)
8856 pn (js2-wrap-with-expr-stmt pos expr t)
8857 (js2-node-type pn) js2-EXPR_RESULT))
8858 pn))
8859
8860 (defun js2-parse-ret-yield ()
8861 (js2-parse-return-or-yield (js2-current-token-type) nil))
8862
8863 (defconst js2-parse-return-stmt-enders
8864 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8865
8866 (defsubst js2-now-all-set (before after mask)
8867 "Return whether or not the bits in the mask have changed to all set.
8868 BEFORE is bits before change, AFTER is bits after change, and MASK is
8869 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8870 but not BEFORE."
8871 (and (/= (logand before mask) mask)
8872 (= (logand after mask) mask)))
8873
8874 (defun js2-parse-return-or-yield (tt expr-context)
8875 (let* ((pos (js2-current-token-beg))
8876 (end (js2-current-token-end))
8877 (before js2-end-flags)
8878 (inside-function (js2-inside-function))
8879 (gen-type (and inside-function (js2-function-node-generator-type
8880 js2-current-script-or-fn)))
8881 e ret name yield-star-p)
8882 (unless inside-function
8883 (js2-report-error (if (eq tt js2-RETURN)
8884 "msg.bad.return"
8885 "msg.bad.yield")))
8886 (when (and inside-function
8887 (eq gen-type 'STAR)
8888 (js2-match-token js2-MUL))
8889 (setq yield-star-p t))
8890 ;; This is ugly, but we don't want to require a semicolon.
8891 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8892 (setq e (js2-parse-expr)
8893 end (js2-node-end e)))
8894 (cond
8895 ((eq tt js2-RETURN)
8896 (js2-set-flag js2-end-flags (if (null e)
8897 js2-end-returns
8898 js2-end-returns-value))
8899 (setq ret (make-js2-return-node :pos pos
8900 :len (- end pos)
8901 :retval e))
8902 (js2-node-add-children ret e)
8903 ;; See if we need a strict mode warning.
8904 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8905 ;; more thorough and accurate than this before/after flag check.
8906 ;; E.g. if there's a finally-block that always returns, we shouldn't
8907 ;; show a warning generated by inconsistent returns in the catch blocks.
8908 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8909 ;; so we know which returns/yields to highlight, and we should get rid of
8910 ;; all the checking in `js2-parse-return-or-yield'.
8911 (if (and js2-strict-inconsistent-return-warning
8912 (js2-now-all-set before js2-end-flags
8913 (logior js2-end-returns js2-end-returns-value)))
8914 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8915 ((eq gen-type 'COMPREHENSION)
8916 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8917 ;; like SpiderMonkey does.
8918 (js2-report-error "msg.syntax" nil pos 5))
8919 (t
8920 (setq ret (make-js2-yield-node :pos pos
8921 :len (- end pos)
8922 :value e
8923 :star-p yield-star-p))
8924 (js2-node-add-children ret e)
8925 (unless expr-context
8926 (setq e ret
8927 ret (js2-wrap-with-expr-stmt pos e t))
8928 (js2-set-requires-activation)
8929 (js2-set-is-generator))))
8930 ;; see if we are mixing yields and value returns.
8931 (when (and inside-function
8932 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8933 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8934 'LEGACY))
8935 (setq name (js2-function-name js2-current-script-or-fn))
8936 (if (zerop (length name))
8937 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8938 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8939 ret))
8940
8941 (defun js2-parse-debugger ()
8942 (make-js2-keyword-node :type js2-DEBUGGER))
8943
8944 (defun js2-parse-block ()
8945 "Parser for a curly-delimited statement block.
8946 Last token matched must be `js2-LC'."
8947 (let ((pos (js2-current-token-beg))
8948 (pn (make-js2-scope)))
8949 (js2-push-scope pn)
8950 (unwind-protect
8951 (progn
8952 (js2-parse-statements pn)
8953 (js2-must-match js2-RC "msg.no.brace.block")
8954 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8955 (js2-pop-scope))
8956 pn))
8957
8958 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8959 (defun js2-parse-semi ()
8960 "Parse a statement or handle an error.
8961 Current token type is `js2-SEMI' or `js2-ERROR'."
8962 (let ((tt (js2-current-token-type)) pos len)
8963 (if (eq tt js2-SEMI)
8964 (make-js2-empty-expr-node :len 1)
8965 (setq pos (js2-current-token-beg)
8966 len (- (js2-current-token-end) pos))
8967 (js2-report-error "msg.syntax" nil pos len)
8968 (make-js2-error-node :pos pos :len len))))
8969
8970 (defun js2-parse-default-xml-namespace ()
8971 "Parse a `default xml namespace = <expr>' e4x statement."
8972 (let ((pos (js2-current-token-beg))
8973 end len expr unary)
8974 (js2-must-have-xml)
8975 (js2-set-requires-activation)
8976 (setq len (- js2-ts-cursor pos))
8977 (unless (and (js2-match-token js2-NAME)
8978 (string= (js2-current-token-string) "xml"))
8979 (js2-report-error "msg.bad.namespace" nil pos len))
8980 (unless (and (js2-match-token js2-NAME)
8981 (string= (js2-current-token-string) "namespace"))
8982 (js2-report-error "msg.bad.namespace" nil pos len))
8983 (unless (js2-match-token js2-ASSIGN)
8984 (js2-report-error "msg.bad.namespace" nil pos len))
8985 (setq expr (js2-parse-expr)
8986 end (js2-node-end expr)
8987 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8988 :pos pos
8989 :len (- end pos)
8990 :operand expr))
8991 (js2-node-add-children unary expr)
8992 (make-js2-expr-stmt-node :pos pos
8993 :len (- end pos)
8994 :expr unary)))
8995
8996 (defun js2-record-label (label bundle)
8997 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8998 (js2-get-token)
8999 (let ((name (js2-label-node-name label))
9000 labeled-stmt
9001 dup)
9002 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9003 ;; flag both labels if possible when used in editing mode
9004 (if (and js2-parse-ide-mode
9005 (setq dup (js2-get-label-by-name labeled-stmt name)))
9006 (js2-report-error "msg.dup.label" nil
9007 (js2-node-abs-pos dup) (js2-node-len dup)))
9008 (js2-report-error "msg.dup.label" nil
9009 (js2-node-pos label) (js2-node-len label)))
9010 (js2-labeled-stmt-node-add-label bundle label)
9011 (js2-node-add-children bundle label)
9012 ;; Add one reference to the bundle per label in `js2-label-set'
9013 (push (cons name bundle) js2-label-set)))
9014
9015 (defun js2-parse-name-or-label ()
9016 "Parser for identifier or label. Last token matched must be js2-NAME.
9017 Called when we found a name in a statement context. If it's a label, we gather
9018 up any following labels and the next non-label statement into a
9019 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9020 expression and return it wrapped in a `js2-expr-stmt-node'."
9021 (let ((pos (js2-current-token-beg))
9022 expr stmt bundle
9023 (continue t))
9024 ;; set check for label and call down to `js2-parse-primary-expr'
9025 (setq expr (js2-maybe-parse-label))
9026 (if (null expr)
9027 ;; Parse the non-label expression and wrap with expression stmt.
9028 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9029 ;; else parsed a label
9030 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9031 (js2-record-label expr bundle)
9032 ;; look for more labels
9033 (while (and continue (= (js2-get-token) js2-NAME))
9034 (if (setq expr (js2-maybe-parse-label))
9035 (js2-record-label expr bundle)
9036 (setq expr (js2-parse-expr)
9037 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9038 continue nil)
9039 (js2-auto-insert-semicolon stmt)))
9040 ;; no more labels; now parse the labeled statement
9041 (unwind-protect
9042 (unless stmt
9043 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9044 (js2-unget-token)
9045 (setq stmt (js2-statement-helper))))
9046 ;; remove the labels for this statement from the global set
9047 (dolist (label (js2-labeled-stmt-node-labels bundle))
9048 (setq js2-label-set (remove label js2-label-set))))
9049 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9050 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9051 (js2-node-add-children bundle stmt)
9052 bundle)))
9053
9054 (defun js2-maybe-parse-label ()
9055 (assert (= (js2-current-token-type) js2-NAME))
9056 (let (label-pos
9057 (next-tt (js2-get-token))
9058 (label-end (js2-current-token-end)))
9059 ;; Do not consume colon, it is used as unwind indicator
9060 ;; to return to statementHelper.
9061 (js2-unget-token)
9062 (if (= next-tt js2-COLON)
9063 (prog2
9064 (setq label-pos (js2-current-token-beg))
9065 (make-js2-label-node :pos label-pos
9066 :len (- label-end label-pos)
9067 :name (js2-current-token-string))
9068 (js2-set-face label-pos
9069 label-end
9070 'font-lock-variable-name-face 'record))
9071 ;; Backtrack from the name token, too.
9072 (js2-unget-token)
9073 nil)))
9074
9075 (defun js2-parse-expr-stmt ()
9076 "Default parser in statement context, if no recognized statement found."
9077 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9078 (progn
9079 (js2-unget-token)
9080 (js2-parse-expr)) t))
9081
9082 (defun js2-parse-variables (decl-type pos)
9083 "Parse a comma-separated list of variable declarations.
9084 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9085
9086 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9087 For 'var' or 'const', the keyword should be the token last scanned.
9088
9089 POS is the position where the node should start. It's sometimes the
9090 var/const/let keyword, and other times the beginning of the first token
9091 in the first variable declaration.
9092
9093 Returns the parsed `js2-var-decl-node' expression node."
9094 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9095 :pos pos))
9096 destructuring kid-pos tt init name end nbeg nend vi
9097 (continue t))
9098 ;; Example:
9099 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9100 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9101 ;; var {a, b} = baz;
9102 (while continue
9103 (setq destructuring nil
9104 name nil
9105 tt (js2-get-token)
9106 kid-pos (js2-current-token-beg)
9107 end (js2-current-token-end)
9108 init nil)
9109 (if (or (= tt js2-LB) (= tt js2-LC))
9110 ;; Destructuring assignment, e.g., var [a, b] = ...
9111 (setq destructuring (js2-parse-destruct-primary-expr)
9112 end (js2-node-end destructuring))
9113 ;; Simple variable name
9114 (js2-unget-token)
9115 (when (js2-must-match-name "msg.bad.var")
9116 (setq name (js2-create-name-node)
9117 nbeg (js2-current-token-beg)
9118 nend (js2-current-token-end)
9119 end nend)
9120 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9121 (when (js2-match-token js2-ASSIGN)
9122 (setq init (js2-parse-assign-expr)
9123 end (js2-node-end init))
9124 (js2-record-imenu-functions init name))
9125 (when name
9126 (js2-set-face nbeg nend (if (js2-function-node-p init)
9127 'font-lock-function-name-face
9128 'font-lock-variable-name-face)
9129 'record))
9130 (setq vi (make-js2-var-init-node :pos kid-pos
9131 :len (- end kid-pos)
9132 :type decl-type))
9133 (if destructuring
9134 (progn
9135 (if (and (null init) (not js2-in-for-init))
9136 (js2-report-error "msg.destruct.assign.no.init"))
9137 (js2-define-destruct-symbols destructuring
9138 decl-type
9139 'font-lock-variable-name-face)
9140 (setf (js2-var-init-node-target vi) destructuring))
9141 (setf (js2-var-init-node-target vi) name))
9142 (setf (js2-var-init-node-initializer vi) init)
9143 (js2-node-add-children vi name destructuring init)
9144 (js2-block-node-push result vi)
9145 (unless (js2-match-token js2-COMMA)
9146 (setq continue nil)))
9147 (setf (js2-node-len result) (- end pos))
9148 result))
9149
9150 (defun js2-parse-let (pos &optional stmt-p)
9151 "Parse a let expression or statement.
9152 A let-expression is of the form `let (vars) expr'.
9153 A let-statment is of the form `let (vars) {statements}'.
9154 The third form of let is a variable declaration list, handled
9155 by `js2-parse-variables'."
9156 (let ((pn (make-js2-let-node :pos pos))
9157 beg vars body)
9158 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9159 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9160 (js2-push-scope pn)
9161 (unwind-protect
9162 (progn
9163 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9164 (if (js2-must-match js2-RP "msg.no.paren.let")
9165 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9166 (if (and stmt-p (js2-match-token js2-LC))
9167 ;; let statement
9168 (progn
9169 (setf beg (js2-current-token-beg) ; position stmt at LC
9170 body (js2-parse-statements))
9171 (js2-must-match js2-RC "msg.no.curly.let")
9172 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9173 (js2-node-len pn) (- (js2-current-token-end) pos)
9174 (js2-let-node-body pn) body
9175 (js2-node-type pn) js2-LET))
9176 ;; let expression
9177 (setf body (js2-parse-expr)
9178 (js2-node-len pn) (- (js2-node-end body) pos)
9179 (js2-let-node-body pn) body))
9180 (setf (js2-let-node-vars pn) vars)
9181 (js2-node-add-children pn vars body))
9182 (js2-pop-scope))
9183 pn))
9184
9185 (defun js2-define-new-symbol (decl-type name node &optional scope)
9186 (js2-scope-put-symbol (or scope js2-current-scope)
9187 name
9188 (make-js2-symbol decl-type name node)))
9189
9190 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9191 "Define a symbol in the current scope.
9192 If NODE is non-nil, it is the AST node associated with the symbol."
9193 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9194 (symbol (if defining-scope
9195 (js2-scope-get-symbol defining-scope name)))
9196 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9197 (pos (if node (js2-node-abs-pos node)))
9198 (len (if node (js2-node-len node))))
9199 (cond
9200 ((and symbol ; already defined
9201 (or (= sdt js2-CONST) ; old version is const
9202 (= decl-type js2-CONST) ; new version is const
9203 ;; two let-bound vars in this block have same name
9204 (and (= sdt js2-LET)
9205 (eq defining-scope js2-current-scope))))
9206 (js2-report-error
9207 (cond
9208 ((= sdt js2-CONST) "msg.const.redecl")
9209 ((= sdt js2-LET) "msg.let.redecl")
9210 ((= sdt js2-VAR) "msg.var.redecl")
9211 ((= sdt js2-FUNCTION) "msg.function.redecl")
9212 (t "msg.parm.redecl"))
9213 name pos len))
9214 ((= decl-type js2-LET)
9215 (if (and (not ignore-not-in-block)
9216 (or (= (js2-node-type js2-current-scope) js2-IF)
9217 (js2-loop-node-p js2-current-scope)))
9218 (js2-report-error "msg.let.decl.not.in.block")
9219 (js2-define-new-symbol decl-type name node)))
9220 ((or (= decl-type js2-VAR)
9221 (= decl-type js2-CONST)
9222 (= decl-type js2-FUNCTION))
9223 (if symbol
9224 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9225 (js2-add-strict-warning "msg.var.redecl" name)
9226 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9227 (js2-add-strict-warning "msg.var.hides.arg" name)))
9228 (js2-define-new-symbol decl-type name node
9229 js2-current-script-or-fn)))
9230 ((= decl-type js2-LP)
9231 (if symbol
9232 ;; must be duplicate parameter. Second parameter hides the
9233 ;; first, so go ahead and add the second pararameter
9234 (js2-report-warning "msg.dup.parms" name))
9235 (js2-define-new-symbol decl-type name node))
9236 (t (js2-code-bug)))))
9237
9238 (defun js2-parse-paren-expr-or-generator-comp ()
9239 (let ((px-pos (js2-current-token-beg)))
9240 (if (and (>= js2-language-version 200)
9241 (js2-match-token js2-FOR))
9242 (js2-parse-generator-comp px-pos)
9243 (let* ((js2-in-for-init nil)
9244 (expr (js2-parse-expr))
9245 (pn (make-js2-paren-node :pos px-pos
9246 :expr expr
9247 :len (- (js2-current-token-end)
9248 px-pos))))
9249 (js2-node-add-children pn (js2-paren-node-expr pn))
9250 (js2-must-match js2-RP "msg.no.paren")
9251 pn))))
9252
9253 (defun js2-parse-expr (&optional oneshot)
9254 (let* ((pn (js2-parse-assign-expr))
9255 (pos (js2-node-pos pn))
9256 left
9257 right
9258 op-pos)
9259 (while (and (not oneshot)
9260 (js2-match-token js2-COMMA))
9261 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9262 (if (= (js2-peek-token) js2-YIELD)
9263 (js2-report-error "msg.yield.parenthesized"))
9264 (setq right (js2-parse-assign-expr)
9265 left pn
9266 pn (make-js2-infix-node :type js2-COMMA
9267 :pos pos
9268 :len (- js2-ts-cursor pos)
9269 :op-pos op-pos
9270 :left left
9271 :right right))
9272 (js2-node-add-children pn left right))
9273 pn))
9274
9275 (defun js2-parse-assign-expr ()
9276 (let ((tt (js2-get-token))
9277 (pos (js2-current-token-beg))
9278 pn left right op-pos
9279 ts-state recorded-identifiers parsed-errors)
9280 (if (= tt js2-YIELD)
9281 (js2-parse-return-or-yield tt t)
9282 ;; Save the tokenizer state in case we find an arrow function
9283 ;; and have to rewind.
9284 (setq ts-state (make-js2-ts-state)
9285 recorded-identifiers js2-recorded-identifiers
9286 parsed-errors js2-parsed-errors)
9287 ;; not yield - parse assignment expression
9288 (setq pn (js2-parse-cond-expr)
9289 tt (js2-get-token))
9290 (cond
9291 ((and (<= js2-first-assign tt)
9292 (<= tt js2-last-assign))
9293 ;; tt express assignment (=, |=, ^=, ..., %=)
9294 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9295 left pn)
9296 (setq right (js2-parse-assign-expr)
9297 pn (make-js2-assign-node :type tt
9298 :pos pos
9299 :len (- (js2-node-end right) pos)
9300 :op-pos op-pos
9301 :left left
9302 :right right))
9303 (when js2-parse-ide-mode
9304 (js2-highlight-assign-targets pn left right)
9305 (js2-record-imenu-functions right left))
9306 ;; do this last so ide checks above can use absolute positions
9307 (js2-node-add-children pn left right))
9308 ((and (= tt js2-ARROW)
9309 (>= js2-language-version 200))
9310 (js2-ts-seek ts-state)
9311 (setq js2-recorded-identifiers recorded-identifiers
9312 js2-parsed-errors parsed-errors)
9313 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9314 (t
9315 (js2-unget-token)))
9316 pn)))
9317
9318 (defun js2-parse-cond-expr ()
9319 (let ((pos (js2-current-token-beg))
9320 (pn (js2-parse-or-expr))
9321 test-expr
9322 if-true
9323 if-false
9324 q-pos
9325 c-pos)
9326 (when (js2-match-token js2-HOOK)
9327 (setq q-pos (- (js2-current-token-beg) pos)
9328 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9329 (js2-must-match js2-COLON "msg.no.colon.cond")
9330 (setq c-pos (- (js2-current-token-beg) pos)
9331 if-false (js2-parse-assign-expr)
9332 test-expr pn
9333 pn (make-js2-cond-node :pos pos
9334 :len (- (js2-node-end if-false) pos)
9335 :test-expr test-expr
9336 :true-expr if-true
9337 :false-expr if-false
9338 :q-pos q-pos
9339 :c-pos c-pos))
9340 (js2-node-add-children pn test-expr if-true if-false))
9341 pn))
9342
9343 (defun js2-make-binary (type left parser)
9344 "Helper for constructing a binary-operator AST node.
9345 LEFT is the left-side-expression, already parsed, and the
9346 binary operator should have just been matched.
9347 PARSER is a function to call to parse the right operand,
9348 or a `js2-node' struct if it has already been parsed.
9349 FIXME: The latter option is unused?"
9350 (let* ((pos (js2-node-pos left))
9351 (op-pos (- (js2-current-token-beg) pos))
9352 (right (if (js2-node-p parser)
9353 parser
9354 (js2-get-token)
9355 (funcall parser)))
9356 (pn (make-js2-infix-node :type type
9357 :pos pos
9358 :len (- (js2-node-end right) pos)
9359 :op-pos op-pos
9360 :left left
9361 :right right)))
9362 (js2-node-add-children pn left right)
9363 pn))
9364
9365 (defun js2-parse-or-expr ()
9366 (let ((pn (js2-parse-and-expr)))
9367 (when (js2-match-token js2-OR)
9368 (setq pn (js2-make-binary js2-OR
9369 pn
9370 'js2-parse-or-expr)))
9371 pn))
9372
9373 (defun js2-parse-and-expr ()
9374 (let ((pn (js2-parse-bit-or-expr)))
9375 (when (js2-match-token js2-AND)
9376 (setq pn (js2-make-binary js2-AND
9377 pn
9378 'js2-parse-and-expr)))
9379 pn))
9380
9381 (defun js2-parse-bit-or-expr ()
9382 (let ((pn (js2-parse-bit-xor-expr)))
9383 (while (js2-match-token js2-BITOR)
9384 (setq pn (js2-make-binary js2-BITOR
9385 pn
9386 'js2-parse-bit-xor-expr)))
9387 pn))
9388
9389 (defun js2-parse-bit-xor-expr ()
9390 (let ((pn (js2-parse-bit-and-expr)))
9391 (while (js2-match-token js2-BITXOR)
9392 (setq pn (js2-make-binary js2-BITXOR
9393 pn
9394 'js2-parse-bit-and-expr)))
9395 pn))
9396
9397 (defun js2-parse-bit-and-expr ()
9398 (let ((pn (js2-parse-eq-expr)))
9399 (while (js2-match-token js2-BITAND)
9400 (setq pn (js2-make-binary js2-BITAND
9401 pn
9402 'js2-parse-eq-expr)))
9403 pn))
9404
9405 (defconst js2-parse-eq-ops
9406 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9407
9408 (defun js2-parse-eq-expr ()
9409 (let ((pn (js2-parse-rel-expr))
9410 tt)
9411 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9412 (setq pn (js2-make-binary tt
9413 pn
9414 'js2-parse-rel-expr)))
9415 (js2-unget-token)
9416 pn))
9417
9418 (defconst js2-parse-rel-ops
9419 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9420
9421 (defun js2-parse-rel-expr ()
9422 (let ((pn (js2-parse-shift-expr))
9423 (continue t)
9424 tt)
9425 (while continue
9426 (setq tt (js2-get-token))
9427 (cond
9428 ((and js2-in-for-init (= tt js2-IN))
9429 (js2-unget-token)
9430 (setq continue nil))
9431 ((memq tt js2-parse-rel-ops)
9432 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9433 (t
9434 (js2-unget-token)
9435 (setq continue nil))))
9436 pn))
9437
9438 (defconst js2-parse-shift-ops
9439 (list js2-LSH js2-URSH js2-RSH))
9440
9441 (defun js2-parse-shift-expr ()
9442 (let ((pn (js2-parse-add-expr))
9443 tt
9444 (continue t))
9445 (while continue
9446 (setq tt (js2-get-token))
9447 (if (memq tt js2-parse-shift-ops)
9448 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9449 (js2-unget-token)
9450 (setq continue nil)))
9451 pn))
9452
9453 (defun js2-parse-add-expr ()
9454 (let ((pn (js2-parse-mul-expr))
9455 tt
9456 (continue t))
9457 (while continue
9458 (setq tt (js2-get-token))
9459 (if (or (= tt js2-ADD) (= tt js2-SUB))
9460 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9461 (js2-unget-token)
9462 (setq continue nil)))
9463 pn))
9464
9465 (defconst js2-parse-mul-ops
9466 (list js2-MUL js2-DIV js2-MOD))
9467
9468 (defun js2-parse-mul-expr ()
9469 (let ((pn (js2-parse-unary-expr))
9470 tt
9471 (continue t))
9472 (while continue
9473 (setq tt (js2-get-token))
9474 (if (memq tt js2-parse-mul-ops)
9475 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9476 (js2-unget-token)
9477 (setq continue nil)))
9478 pn))
9479
9480 (defun js2-make-unary (type parser &rest args)
9481 "Make a unary node of type TYPE.
9482 PARSER is either a node (for postfix operators) or a function to call
9483 to parse the operand (for prefix operators)."
9484 (let* ((pos (js2-current-token-beg))
9485 (postfix (js2-node-p parser))
9486 (expr (if postfix
9487 parser
9488 (apply parser args)))
9489 end
9490 pn)
9491 (if postfix ; e.g. i++
9492 (setq pos (js2-node-pos expr)
9493 end (js2-current-token-end))
9494 (setq end (js2-node-end expr)))
9495 (setq pn (make-js2-unary-node :type type
9496 :pos pos
9497 :len (- end pos)
9498 :operand expr))
9499 (js2-node-add-children pn expr)
9500 pn))
9501
9502 (defconst js2-incrementable-node-types
9503 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9504 "Node types that can be the operand of a ++ or -- operator.")
9505
9506 (defun js2-check-bad-inc-dec (tt beg end unary)
9507 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9508 js2-incrementable-node-types)
9509 (js2-report-error (if (= tt js2-INC)
9510 "msg.bad.incr"
9511 "msg.bad.decr")
9512 nil beg (- end beg))))
9513
9514 (defun js2-parse-unary-expr ()
9515 (let ((tt (js2-current-token-type))
9516 pn expr beg end)
9517 (cond
9518 ((or (= tt js2-VOID)
9519 (= tt js2-NOT)
9520 (= tt js2-BITNOT)
9521 (= tt js2-TYPEOF))
9522 (js2-get-token)
9523 (js2-make-unary tt 'js2-parse-unary-expr))
9524 ((= tt js2-ADD)
9525 (js2-get-token)
9526 ;; Convert to special POS token in decompiler and parse tree
9527 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9528 ((= tt js2-SUB)
9529 (js2-get-token)
9530 ;; Convert to special NEG token in decompiler and parse tree
9531 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9532 ((or (= tt js2-INC)
9533 (= tt js2-DEC))
9534 (js2-get-token)
9535 (prog1
9536 (setq beg (js2-current-token-beg)
9537 end (js2-current-token-end)
9538 expr (js2-make-unary tt 'js2-parse-member-expr t))
9539 (js2-check-bad-inc-dec tt beg end expr)))
9540 ((= tt js2-DELPROP)
9541 (js2-get-token)
9542 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9543 ((= tt js2-ERROR)
9544 (js2-get-token)
9545 (make-js2-error-node)) ; try to continue
9546 ((and (= tt js2-LT)
9547 js2-compiler-xml-available)
9548 ;; XML stream encountered in expression.
9549 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9550 (t
9551 (setq pn (js2-parse-member-expr t)
9552 ;; Don't look across a newline boundary for a postfix incop.
9553 tt (js2-peek-token-or-eol))
9554 (when (or (= tt js2-INC) (= tt js2-DEC))
9555 (js2-get-token)
9556 (setf expr pn
9557 pn (js2-make-unary tt expr))
9558 (js2-node-set-prop pn 'postfix t)
9559 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9560 pn))))
9561
9562 (defun js2-parse-xml-initializer ()
9563 "Parse an E4X XML initializer.
9564 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9565 Then I'll postprocess the result, depending on whether we're in IDE
9566 mode or codegen mode, and generate the appropriate rewritten AST.
9567 IDE mode uses a rich AST that models the XML structure. Codegen mode
9568 just concatenates everything and makes a new XML or XMLList out of it."
9569 (let ((tt (js2-get-first-xml-token))
9570 pn-xml pn expr kids expr-pos
9571 (continue t)
9572 (first-token t))
9573 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9574 (js2-report-error "msg.syntax"))
9575 (setq pn-xml (make-js2-xml-node))
9576 (while continue
9577 (if first-token
9578 (setq first-token nil)
9579 (setq tt (js2-get-next-xml-token)))
9580 (cond
9581 ;; js2-XML means we found a {expr} in the XML stream.
9582 ;; The token string is the XML up to the left-curly.
9583 ((= tt js2-XML)
9584 (push (make-js2-string-node :pos (js2-current-token-beg)
9585 :len (- js2-ts-cursor (js2-current-token-beg)))
9586 kids)
9587 (js2-must-match js2-LC "msg.syntax")
9588 (setq expr-pos js2-ts-cursor
9589 expr (if (eq (js2-peek-token) js2-RC)
9590 (make-js2-empty-expr-node :pos expr-pos)
9591 (js2-parse-expr)))
9592 (js2-must-match js2-RC "msg.syntax")
9593 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9594 :len (js2-node-len expr)
9595 :expr expr))
9596 (js2-node-add-children pn expr)
9597 (push pn kids))
9598 ;; a js2-XMLEND token means we hit the final close-tag.
9599 ((= tt js2-XMLEND)
9600 (push (make-js2-string-node :pos (js2-current-token-beg)
9601 :len (- js2-ts-cursor (js2-current-token-beg)))
9602 kids)
9603 (dolist (kid (nreverse kids))
9604 (js2-block-node-push pn-xml kid))
9605 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9606 (js2-node-pos pn-xml))
9607 continue nil))
9608 (t
9609 (js2-report-error "msg.syntax")
9610 (setq continue nil))))
9611 pn-xml))
9612
9613
9614 (defun js2-parse-argument-list ()
9615 "Parse an argument list and return it as a Lisp list of nodes.
9616 Returns the list in reverse order. Consumes the right-paren token."
9617 (let (result)
9618 (unless (js2-match-token js2-RP)
9619 (loop do
9620 (let ((tt (js2-get-token)))
9621 (if (= tt js2-YIELD)
9622 (js2-report-error "msg.yield.parenthesized"))
9623 (if (and (= tt js2-TRIPLEDOT)
9624 (>= js2-language-version 200))
9625 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9626 (js2-unget-token)
9627 (push (js2-parse-assign-expr) result)))
9628 while
9629 (js2-match-token js2-COMMA))
9630 (js2-must-match js2-RP "msg.no.paren.arg")
9631 result)))
9632
9633 (defun js2-parse-member-expr (&optional allow-call-syntax)
9634 (let ((tt (js2-current-token-type))
9635 pn pos target args beg end init)
9636 (if (/= tt js2-NEW)
9637 (setq pn (js2-parse-primary-expr))
9638 ;; parse a 'new' expression
9639 (js2-get-token)
9640 (setq pos (js2-current-token-beg)
9641 beg pos
9642 target (js2-parse-member-expr)
9643 end (js2-node-end target)
9644 pn (make-js2-new-node :pos pos
9645 :target target
9646 :len (- end pos)))
9647 (js2-highlight-function-call (js2-current-token))
9648 (js2-node-add-children pn target)
9649 (when (js2-match-token js2-LP)
9650 ;; Add the arguments to pn, if any are supplied.
9651 (setf beg pos ; start of "new" keyword
9652 pos (js2-current-token-beg)
9653 args (nreverse (js2-parse-argument-list))
9654 (js2-new-node-args pn) args
9655 end (js2-current-token-end)
9656 (js2-new-node-lp pn) (- pos beg)
9657 (js2-new-node-rp pn) (- end 1 beg))
9658 (apply #'js2-node-add-children pn args))
9659 (when (and js2-allow-rhino-new-expr-initializer
9660 (js2-match-token js2-LC))
9661 (setf init (js2-parse-object-literal)
9662 end (js2-node-end init)
9663 (js2-new-node-initializer pn) init)
9664 (js2-node-add-children pn init))
9665 (setf (js2-node-len pn) (- end beg))) ; end outer if
9666 (js2-parse-member-expr-tail allow-call-syntax pn)))
9667
9668 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9669 "Parse a chain of property/array accesses or function calls.
9670 Includes parsing for E4X operators like `..' and `.@'.
9671 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9672 Returns an expression tree that includes PN, the parent node."
9673 (let (tt
9674 (continue t))
9675 (while continue
9676 (setq tt (js2-get-token))
9677 (cond
9678 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9679 (setq pn (js2-parse-property-access tt pn)))
9680 ((= tt js2-DOTQUERY)
9681 (setq pn (js2-parse-dot-query pn)))
9682 ((= tt js2-LB)
9683 (setq pn (js2-parse-element-get pn)))
9684 ((= tt js2-LP)
9685 (js2-unget-token)
9686 (if allow-call-syntax
9687 (setq pn (js2-parse-function-call pn))
9688 (setq continue nil)))
9689 ((= tt js2-TEMPLATE_HEAD)
9690 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9691 ((= tt js2-NO_SUBS_TEMPLATE)
9692 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9693 (t
9694 (js2-unget-token)
9695 (setq continue nil))))
9696 (if (>= js2-highlight-level 2)
9697 (js2-parse-highlight-member-expr-node pn))
9698 pn))
9699
9700 (defun js2-parse-tagged-template (tag-node tpl-node)
9701 "Parse tagged template expression."
9702 (let* ((beg (js2-node-pos tag-node))
9703 (pn (make-js2-tagged-template-node :beg beg
9704 :len (- (js2-current-token-end) beg)
9705 :tag tag-node
9706 :template tpl-node)))
9707 (js2-node-add-children pn tag-node tpl-node)
9708 pn))
9709
9710 (defun js2-parse-dot-query (pn)
9711 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9712 Last token parsed must be `js2-DOTQUERY'."
9713 (let ((pos (js2-node-pos pn))
9714 op-pos expr end)
9715 (js2-must-have-xml)
9716 (js2-set-requires-activation)
9717 (setq op-pos (js2-current-token-beg)
9718 expr (js2-parse-expr)
9719 end (js2-node-end expr)
9720 pn (make-js2-xml-dot-query-node :left pn
9721 :pos pos
9722 :op-pos op-pos
9723 :right expr))
9724 (js2-node-add-children pn
9725 (js2-xml-dot-query-node-left pn)
9726 (js2-xml-dot-query-node-right pn))
9727 (if (js2-must-match js2-RP "msg.no.paren")
9728 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9729 end (js2-current-token-end)))
9730 (setf (js2-node-len pn) (- end pos))
9731 pn))
9732
9733 (defun js2-parse-element-get (pn)
9734 "Parse an element-get expression, e.g. foo[bar].
9735 Last token parsed must be `js2-RB'."
9736 (let ((lb (js2-current-token-beg))
9737 (pos (js2-node-pos pn))
9738 rb expr)
9739 (setq expr (js2-parse-expr))
9740 (if (js2-must-match js2-RB "msg.no.bracket.index")
9741 (setq rb (js2-current-token-beg)))
9742 (setq pn (make-js2-elem-get-node :target pn
9743 :pos pos
9744 :element expr
9745 :lb (js2-relpos lb pos)
9746 :rb (js2-relpos rb pos)
9747 :len (- (js2-current-token-end) pos)))
9748 (js2-node-add-children pn
9749 (js2-elem-get-node-target pn)
9750 (js2-elem-get-node-element pn))
9751 pn))
9752
9753 (defun js2-highlight-function-call (token)
9754 (when (eq (js2-token-type token) js2-NAME)
9755 (js2-record-face 'js2-function-call token)))
9756
9757 (defun js2-parse-function-call (pn)
9758 (js2-highlight-function-call (js2-current-token))
9759 (js2-get-token)
9760 (let (args
9761 (pos (js2-node-pos pn)))
9762 (setq pn (make-js2-call-node :pos pos
9763 :target pn
9764 :lp (- (js2-current-token-beg) pos)))
9765 (js2-node-add-children pn (js2-call-node-target pn))
9766 ;; Add the arguments to pn, if any are supplied.
9767 (setf args (nreverse (js2-parse-argument-list))
9768 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9769 (js2-call-node-args pn) args)
9770 (apply #'js2-node-add-children pn args)
9771 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9772 pn))
9773
9774 (defun js2-parse-property-access (tt pn)
9775 "Parse a property access, XML descendants access, or XML attr access."
9776 (let ((member-type-flags 0)
9777 (dot-pos (js2-current-token-beg))
9778 (dot-len (if (= tt js2-DOTDOT) 2 1))
9779 name
9780 ref ; right side of . or .. operator
9781 result)
9782 (when (= tt js2-DOTDOT)
9783 (js2-must-have-xml)
9784 (setq member-type-flags js2-descendants-flag))
9785 (if (not js2-compiler-xml-available)
9786 (progn
9787 (js2-must-match-prop-name "msg.no.name.after.dot")
9788 (setq name (js2-create-name-node t js2-GETPROP)
9789 result (make-js2-prop-get-node :left pn
9790 :pos (js2-current-token-beg)
9791 :right name
9792 :len (js2-current-token-len)))
9793 (js2-node-add-children result pn name)
9794 result)
9795 ;; otherwise look for XML operators
9796 (setf result (if (= tt js2-DOT)
9797 (make-js2-prop-get-node)
9798 (make-js2-infix-node :type js2-DOTDOT))
9799 (js2-node-pos result) (js2-node-pos pn)
9800 (js2-infix-node-op-pos result) dot-pos
9801 (js2-infix-node-left result) pn ; do this after setting position
9802 tt (js2-get-prop-name-token))
9803 (cond
9804 ;; handles: name, ns::name, ns::*, ns::[expr]
9805 ((= tt js2-NAME)
9806 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9807 ;; handles: *, *::name, *::*, *::[expr]
9808 ((= tt js2-MUL)
9809 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9810 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9811 ((= tt js2-XMLATTR)
9812 (setq result (js2-parse-attribute-access)))
9813 (t
9814 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9815 (if ref
9816 (setf (js2-node-len result) (- (js2-node-end ref)
9817 (js2-node-pos result))
9818 (js2-infix-node-right result) ref))
9819 (if (js2-infix-node-p result)
9820 (js2-node-add-children result
9821 (js2-infix-node-left result)
9822 (js2-infix-node-right result)))
9823 result)))
9824
9825 (defun js2-parse-attribute-access ()
9826 "Parse an E4X XML attribute expression.
9827 This includes expressions of the forms:
9828
9829 @attr @ns::attr @ns::*
9830 @* @*::attr @*::*
9831 @[expr] @*::[expr] @ns::[expr]
9832
9833 Called if we peeked an '@' token."
9834 (let ((tt (js2-get-prop-name-token))
9835 (at-pos (js2-current-token-beg)))
9836 (cond
9837 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9838 ((= tt js2-NAME)
9839 (js2-parse-property-name at-pos nil 0))
9840 ;; handles: @*, @*::name, @*::*, @*::[expr]
9841 ((= tt js2-MUL)
9842 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9843 ;; handles @[expr]
9844 ((= tt js2-LB)
9845 (js2-parse-xml-elem-ref at-pos))
9846 (t
9847 (js2-report-error "msg.no.name.after.xmlAttr")
9848 ;; Avoid cascaded errors that happen if we make an error node here.
9849 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9850
9851 (defun js2-parse-property-name (at-pos s member-type-flags)
9852 "Check if :: follows name in which case it becomes qualified name.
9853
9854 AT-POS is a natural number if we just read an '@' token, else nil.
9855 S is the name or string that was matched: an identifier, 'throw' or '*'.
9856 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9857
9858 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9859 operator, or the name is followed by ::. For a plain name, returns a
9860 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9861 (let ((pos (or at-pos (js2-current-token-beg)))
9862 colon-pos
9863 (name (js2-create-name-node t (js2-current-token-type) s))
9864 ns tt pn)
9865 (catch 'return
9866 (when (js2-match-token js2-COLONCOLON)
9867 (setq ns name
9868 colon-pos (js2-current-token-beg)
9869 tt (js2-get-prop-name-token))
9870 (cond
9871 ;; handles name::name
9872 ((= tt js2-NAME)
9873 (setq name (js2-create-name-node)))
9874 ;; handles name::*
9875 ((= tt js2-MUL)
9876 (setq name (js2-create-name-node nil nil "*")))
9877 ;; handles name::[expr]
9878 ((= tt js2-LB)
9879 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9880 (t
9881 (js2-report-error "msg.no.name.after.coloncolon"))))
9882 (if (and (null ns) (zerop member-type-flags))
9883 name
9884 (prog1
9885 (setq pn
9886 (make-js2-xml-prop-ref-node :pos pos
9887 :len (- (js2-node-end name) pos)
9888 :at-pos at-pos
9889 :colon-pos colon-pos
9890 :propname name))
9891 (js2-node-add-children pn name))))))
9892
9893 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9894 "Parse the [expr] portion of an xml element reference.
9895 For instance, @[expr], @*::[expr], or ns::[expr]."
9896 (let* ((lb (js2-current-token-beg))
9897 (pos (or at-pos lb))
9898 rb
9899 (expr (js2-parse-expr))
9900 (end (js2-node-end expr))
9901 pn)
9902 (if (js2-must-match js2-RB "msg.no.bracket.index")
9903 (setq rb (js2-current-token-beg)
9904 end (js2-current-token-end)))
9905 (prog1
9906 (setq pn
9907 (make-js2-xml-elem-ref-node :pos pos
9908 :len (- end pos)
9909 :namespace namespace
9910 :colon-pos colon-pos
9911 :at-pos at-pos
9912 :expr expr
9913 :lb (js2-relpos lb pos)
9914 :rb (js2-relpos rb pos)))
9915 (js2-node-add-children pn namespace expr))))
9916
9917 (defun js2-parse-destruct-primary-expr ()
9918 (let ((js2-is-in-destructuring t))
9919 (js2-parse-primary-expr)))
9920
9921 (defun js2-parse-primary-expr ()
9922 "Parse a literal (leaf) expression of some sort.
9923 Includes complex literals such as functions, object-literals,
9924 array-literals, array comprehensions and regular expressions."
9925 (let (pn ; parent node (usually return value)
9926 tt)
9927 (setq tt (js2-current-token-type))
9928 (cond
9929 ((= tt js2-CLASS)
9930 (js2-parse-class-expr))
9931 ((= tt js2-FUNCTION)
9932 (js2-parse-function-expr))
9933 ((= tt js2-LB)
9934 (js2-parse-array-comp-or-literal))
9935 ((= tt js2-LC)
9936 (js2-parse-object-literal))
9937 ((= tt js2-LET)
9938 (js2-parse-let (js2-current-token-beg)))
9939 ((= tt js2-LP)
9940 (js2-parse-paren-expr-or-generator-comp))
9941 ((= tt js2-XMLATTR)
9942 (js2-must-have-xml)
9943 (js2-parse-attribute-access))
9944 ((= tt js2-NAME)
9945 (js2-parse-name tt))
9946 ((= tt js2-NUMBER)
9947 (make-js2-number-node))
9948 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9949 (make-js2-string-node :type tt))
9950 ((= tt js2-TEMPLATE_HEAD)
9951 (js2-parse-template-literal))
9952 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9953 ;; Got / or /= which in this context means a regexp literal
9954 (let ((px-pos (js2-current-token-beg))
9955 (flags (js2-read-regexp tt))
9956 (end (js2-current-token-end)))
9957 (prog1
9958 (make-js2-regexp-node :pos px-pos
9959 :len (- end px-pos)
9960 :value (js2-current-token-string)
9961 :flags flags)
9962 (js2-set-face px-pos end 'font-lock-string-face 'record)
9963 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9964 ((or (= tt js2-NULL)
9965 (= tt js2-THIS)
9966 (= tt js2-SUPER)
9967 (= tt js2-FALSE)
9968 (= tt js2-TRUE))
9969 (make-js2-keyword-node :type tt))
9970 ((= tt js2-RP)
9971 ;; Not valid expression syntax, but this is valid in an arrow
9972 ;; function with no params: () => body.
9973 (if (eq (js2-peek-token) js2-ARROW)
9974 (progn
9975 (js2-unget-token) ; Put back the right paren.
9976 ;; Return whatever, it will hopefully be rewinded and
9977 ;; reparsed when we reach the =>.
9978 (make-js2-keyword-node :type js2-NULL))
9979 (js2-report-error "msg.syntax")
9980 (make-js2-error-node)))
9981 ((= tt js2-TRIPLEDOT)
9982 ;; Likewise, only valid in an arrow function with a rest param.
9983 (if (and (js2-match-token js2-NAME)
9984 (js2-match-token js2-RP)
9985 (eq (js2-peek-token) js2-ARROW))
9986 (progn
9987 (js2-unget-token) ; Put back the right paren.
9988 ;; See the previous case.
9989 (make-js2-keyword-node :type js2-NULL))
9990 (js2-report-error "msg.syntax")
9991 (make-js2-error-node)))
9992 ((= tt js2-RESERVED)
9993 (js2-report-error "msg.reserved.id")
9994 (make-js2-name-node))
9995 ((= tt js2-ERROR)
9996 ;; the scanner or one of its subroutines reported the error.
9997 (make-js2-error-node))
9998 ((= tt js2-EOF)
9999 (let* ((px-pos (point-at-bol))
10000 (len (- js2-ts-cursor px-pos)))
10001 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10002 (make-js2-error-node :pos (1- js2-ts-cursor)))
10003 (t
10004 (js2-report-error "msg.syntax")
10005 (make-js2-error-node)))))
10006
10007 (defun js2-parse-template-literal ()
10008 (let ((beg (js2-current-token-beg))
10009 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10010 (tt js2-TEMPLATE_HEAD))
10011 (while (eq tt js2-TEMPLATE_HEAD)
10012 (push (js2-parse-expr) kids)
10013 (js2-must-match js2-RC "msg.syntax")
10014 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10015 (push (make-js2-string-node :type tt) kids))
10016 (setq kids (nreverse kids))
10017 (let ((tpl (make-js2-template-node :beg beg
10018 :len (- (js2-current-token-end) beg)
10019 :kids kids)))
10020 (apply #'js2-node-add-children tpl kids)
10021 tpl)))
10022
10023 (defun js2-parse-name (_tt)
10024 (let ((name (js2-current-token-string))
10025 node)
10026 (setq node (if js2-compiler-xml-available
10027 (js2-parse-property-name nil name 0)
10028 (js2-create-name-node 'check-activation nil name)))
10029 (if js2-highlight-external-variables
10030 (js2-record-name-node node))
10031 node))
10032
10033 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10034 (js2-add-strict-warning
10035 msg nil
10036 ;; back up from comma to beginning of line or array/objlit
10037 (max (if elems
10038 (js2-node-pos (car elems))
10039 pos)
10040 (save-excursion
10041 (goto-char comma-pos)
10042 (back-to-indentation)
10043 (point)))
10044 comma-pos))
10045
10046 (defun js2-parse-array-comp-or-literal ()
10047 (let ((pos (js2-current-token-beg)))
10048 (if (and (>= js2-language-version 200)
10049 (js2-match-token js2-FOR))
10050 (js2-parse-array-comp pos)
10051 (js2-parse-array-literal pos))))
10052
10053 (defun js2-parse-array-literal (pos)
10054 (let ((after-lb-or-comma t)
10055 after-comma tt elems pn
10056 (continue t))
10057 (unless js2-is-in-destructuring
10058 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10059 (while continue
10060 (setq tt (js2-get-token))
10061 (cond
10062 ;; comma
10063 ((= tt js2-COMMA)
10064 (setq after-comma (js2-current-token-end))
10065 (if (not after-lb-or-comma)
10066 (setq after-lb-or-comma t)
10067 (push nil elems)))
10068 ;; end of array
10069 ((or (= tt js2-RB)
10070 (= tt js2-EOF)) ; prevent infinite loop
10071 (if (= tt js2-EOF)
10072 (js2-report-error "msg.no.bracket.arg" nil pos))
10073 (when (and after-comma (< js2-language-version 170))
10074 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10075 pos (remove nil elems) after-comma))
10076 (setq continue nil
10077 pn (make-js2-array-node :pos pos
10078 :len (- js2-ts-cursor pos)
10079 :elems (nreverse elems)))
10080 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10081 ;; destructuring binding
10082 (js2-is-in-destructuring
10083 (push (if (or (= tt js2-LC)
10084 (= tt js2-LB)
10085 (= tt js2-NAME))
10086 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10087 (js2-parse-destruct-primary-expr)
10088 ;; invalid pattern
10089 (js2-report-error "msg.bad.var")
10090 (make-js2-error-node))
10091 elems)
10092 (setq after-lb-or-comma nil
10093 after-comma nil))
10094 ;; array comp
10095 ((and (>= js2-language-version 170)
10096 (= tt js2-FOR) ; check for array comprehension
10097 (not after-lb-or-comma) ; "for" can't follow a comma
10098 elems ; must have at least 1 element
10099 (not (cdr elems))) ; but no 2nd element
10100 (js2-unget-token)
10101 (setf continue nil
10102 pn (js2-parse-legacy-array-comp (car elems) pos)))
10103 ;; another element
10104 (t
10105 (unless after-lb-or-comma
10106 (js2-report-error "msg.no.bracket.arg"))
10107 (if (and (= tt js2-TRIPLEDOT)
10108 (>= js2-language-version 200))
10109 ;; spread operator
10110 (push (js2-make-unary tt 'js2-parse-assign-expr)
10111 elems)
10112 (js2-unget-token)
10113 (push (js2-parse-assign-expr) elems))
10114 (setq after-lb-or-comma nil
10115 after-comma nil))))
10116 (unless js2-is-in-destructuring
10117 (js2-pop-scope))
10118 pn))
10119
10120 (defun js2-parse-legacy-array-comp (expr pos)
10121 "Parse a legacy array comprehension (JavaScript 1.7).
10122 EXPR is the first expression after the opening left-bracket.
10123 POS is the beginning of the LB token preceding EXPR.
10124 We should have just parsed the 'for' keyword before calling this function."
10125 (let ((current-scope js2-current-scope)
10126 loops first filter result)
10127 (unwind-protect
10128 (progn
10129 (while (js2-match-token js2-FOR)
10130 (let ((loop (make-js2-comp-loop-node)))
10131 (js2-push-scope loop)
10132 (push loop loops)
10133 (js2-parse-comp-loop loop)))
10134 ;; First loop takes expr scope's parent.
10135 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10136 (js2-scope-parent-scope current-scope))
10137 ;; Set expr scope's parent to the last loop.
10138 (setf (js2-scope-parent-scope current-scope) (car loops))
10139 (if (/= (js2-get-token) js2-IF)
10140 (js2-unget-token)
10141 (setq filter (js2-parse-condition))))
10142 (dotimes (_ (1- (length loops)))
10143 (js2-pop-scope)))
10144 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10145 (setq result (make-js2-comp-node :pos pos
10146 :len (- js2-ts-cursor pos)
10147 :result expr
10148 :loops (nreverse loops)
10149 :filters (and filter (list (car filter)))
10150 :form 'LEGACY_ARRAY))
10151 (apply #'js2-node-add-children result expr (car filter)
10152 (js2-comp-node-loops result))
10153 result))
10154
10155 (defun js2-parse-array-comp (pos)
10156 "Parse an ES6 array comprehension.
10157 POS is the beginning of the LB token.
10158 We should have just parsed the 'for' keyword before calling this function."
10159 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10160 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10161 pn))
10162
10163 (defun js2-parse-generator-comp (pos)
10164 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10165 (js2-current-script-or-fn
10166 (make-js2-function-node :generator-type 'COMPREHENSION))
10167 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10168 (js2-must-match js2-RP "msg.no.paren" pos)
10169 pn))
10170
10171 (defun js2-parse-comprehension (pos form)
10172 (let (loops filters expr result)
10173 (unwind-protect
10174 (progn
10175 (js2-unget-token)
10176 (while (js2-match-token js2-FOR)
10177 (let ((loop (make-js2-comp-loop-node)))
10178 (js2-push-scope loop)
10179 (push loop loops)
10180 (js2-parse-comp-loop loop)))
10181 (while (js2-match-token js2-IF)
10182 (push (car (js2-parse-condition)) filters))
10183 (setq expr (js2-parse-assign-expr)))
10184 (dolist (_ loops)
10185 (js2-pop-scope)))
10186 (setq result (make-js2-comp-node :pos pos
10187 :len (- js2-ts-cursor pos)
10188 :result expr
10189 :loops (nreverse loops)
10190 :filters (nreverse filters)
10191 :form form))
10192 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10193 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10194 result))
10195
10196 (defun js2-parse-comp-loop (pn &optional only-of-p)
10197 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10198 The current token should be the initial FOR.
10199 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10200 (let ((pos (js2-comp-loop-node-pos pn))
10201 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10202 (when (and (not only-of-p) (js2-match-token js2-NAME))
10203 (if (string= (js2-current-token-string) "each")
10204 (progn
10205 (setq foreach-p t
10206 each-pos (- (js2-current-token-beg) pos)) ; relative
10207 (js2-record-face 'font-lock-keyword-face))
10208 (js2-report-error "msg.no.paren.for")))
10209 (if (js2-must-match js2-LP "msg.no.paren.for")
10210 (setq lp (- (js2-current-token-beg) pos)))
10211 (setq tt (js2-peek-token))
10212 (cond
10213 ((or (= tt js2-LB)
10214 (= tt js2-LC))
10215 (js2-get-token)
10216 (setq iter (js2-parse-destruct-primary-expr))
10217 (js2-define-destruct-symbols iter js2-LET
10218 'font-lock-variable-name-face t))
10219 ((js2-match-token js2-NAME)
10220 (setq iter (js2-create-name-node)))
10221 (t
10222 (js2-report-error "msg.bad.var")))
10223 ;; Define as a let since we want the scope of the variable to
10224 ;; be restricted to the array comprehension
10225 (if (js2-name-node-p iter)
10226 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10227 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10228 (and (>= js2-language-version 200)
10229 (js2-match-contextual-kwd "of")
10230 (setq forof-p t)))
10231 (setq in-pos (- (js2-current-token-beg) pos))
10232 (js2-report-error "msg.in.after.for.name"))
10233 (setq obj (js2-parse-expr))
10234 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10235 (setq rp (- (js2-current-token-beg) pos)))
10236 (setf (js2-node-pos pn) pos
10237 (js2-node-len pn) (- js2-ts-cursor pos)
10238 (js2-comp-loop-node-iterator pn) iter
10239 (js2-comp-loop-node-object pn) obj
10240 (js2-comp-loop-node-in-pos pn) in-pos
10241 (js2-comp-loop-node-each-pos pn) each-pos
10242 (js2-comp-loop-node-foreach-p pn) foreach-p
10243 (js2-comp-loop-node-forof-p pn) forof-p
10244 (js2-comp-loop-node-lp pn) lp
10245 (js2-comp-loop-node-rp pn) rp)
10246 (js2-node-add-children pn iter obj)
10247 pn))
10248
10249 (defun js2-parse-class-stmt ()
10250 (let ((pos (js2-current-token-beg)))
10251 (js2-must-match-name "msg.unnamed.class.stmt")
10252 (js2-parse-class pos 'CLASS_STATEMENT (js2-create-name-node t))))
10253
10254 (defun js2-parse-class-expr ()
10255 (let ((pos (js2-current-token-beg))
10256 name)
10257 (when (js2-match-token js2-NAME)
10258 (setq name (js2-create-name-node t)))
10259 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10260
10261 (defun js2-parse-class (pos form name)
10262 ;; class X [extends ...] {
10263 (let (pn elems extends)
10264 (when name
10265 (js2-set-face (js2-node-pos name) (js2-node-end name)
10266 'font-lock-function-name-face 'record))
10267 (if (js2-match-token js2-EXTENDS)
10268 (if (= (js2-peek-token) js2-LC)
10269 (js2-report-error "msg.missing.extends")
10270 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10271 (setq extends (js2-parse-assign-expr))
10272 (if (not extends)
10273 (js2-report-error "msg.bad.extends"))))
10274 (js2-must-match js2-LC "msg.no.brace.class")
10275 (setq elems (js2-parse-object-literal-elems t)
10276 pn (make-js2-class-node :pos pos
10277 :len (- js2-ts-cursor pos)
10278 :form form
10279 :name name
10280 :extends extends
10281 :elems elems))
10282 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10283 pn))
10284
10285 (defun js2-parse-object-literal ()
10286 (let* ((pos (js2-current-token-beg))
10287 (elems (js2-parse-object-literal-elems))
10288 (result (make-js2-object-node :pos pos
10289 :len (- js2-ts-cursor pos)
10290 :elems elems)))
10291 (apply #'js2-node-add-children result (js2-object-node-elems result))
10292 result))
10293
10294 (defun js2-parse-object-literal-elems (&optional class-p)
10295 (let ((pos (js2-current-token-beg))
10296 (static nil)
10297 (continue t)
10298 tt elems elem after-comma)
10299 (while continue
10300 (setq static (and class-p (js2-match-token js2-STATIC))
10301 tt (js2-get-prop-name-token)
10302 elem nil)
10303 (cond
10304 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
10305 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
10306 ;; TODO(sdh): support *foo() {...}
10307 ((or (= js2-NAME tt)
10308 (= tt js2-STRING))
10309 (setq after-comma nil
10310 elem (js2-parse-named-prop tt))
10311 (if (and (null elem)
10312 (not js2-recover-from-parse-errors))
10313 (setq continue nil)))
10314 ;; {[Symbol.iterator]: ...}
10315 ((and (= tt js2-LB)
10316 (>= js2-language-version 200))
10317 (let ((expr (js2-parse-expr)))
10318 (js2-must-match js2-RB "msg.missing.computed.rb")
10319 (setq after-comma nil
10320 elem (js2-parse-plain-property expr))))
10321 ;; {12: x} or {10.7: x}
10322 ((= tt js2-NUMBER)
10323 (setq after-comma nil
10324 elem (js2-parse-plain-property (make-js2-number-node))))
10325 ;; Break out of loop, and handle trailing commas.
10326 ((or (= tt js2-RC)
10327 (= tt js2-EOF))
10328 (js2-unget-token)
10329 (setq continue nil)
10330 (if after-comma
10331 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10332 pos elems after-comma)))
10333 (t
10334 (js2-report-error "msg.bad.prop")
10335 (unless js2-recover-from-parse-errors
10336 (setq continue nil)))) ; end switch
10337 ;; Handle static for classes' codegen.
10338 (if static
10339 (if elem (js2-node-set-prop elem 'STATIC t)
10340 (js2-report-error "msg.unexpected.static")))
10341 ;; Handle commas, depending on class-p.
10342 (let ((comma (js2-match-token js2-COMMA)))
10343 (if class-p
10344 (if comma
10345 (js2-report-error "msg.class.unexpected.comma"))
10346 (if comma
10347 (setq after-comma (js2-current-token-end))
10348 (setq continue nil))))
10349 ;; Append any parsed element.
10350 (if elem (push elem elems))) ; end loop
10351 (js2-must-match js2-RC "msg.no.brace.prop")
10352 (nreverse elems)))
10353
10354 (defun js2-parse-named-prop (tt)
10355 "Parse a name, string, or getter/setter object property.
10356 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10357 (let ((string-prop (and (= tt js2-STRING)
10358 (make-js2-string-node)))
10359 expr
10360 (ppos (js2-current-token-beg))
10361 (pend (js2-current-token-end))
10362 (name (js2-create-name-node))
10363 (prop (js2-current-token-string)))
10364 (cond
10365 ;; getter/setter prop
10366 ((and (= tt js2-NAME)
10367 (= (js2-peek-token) js2-NAME)
10368 (or (string= prop "get")
10369 (string= prop "set")))
10370 (js2-get-token)
10371 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
10372 (js2-record-face 'font-lock-function-name-face) ; for peeked name
10373 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
10374 (js2-parse-getter-setter-prop ppos name prop))
10375 ;; method definition: {f() {...}}
10376 ((and (= (js2-peek-token) js2-LP)
10377 (>= js2-language-version 200))
10378 (js2-record-face 'font-lock-function-name-face) ; name
10379 (js2-parse-getter-setter-prop ppos name ""))
10380 ;; regular prop
10381 (t
10382 (prog1
10383 (setq expr (js2-parse-plain-property (or string-prop name)))
10384 (when (and (not string-prop)
10385 (not js2-is-in-destructuring)
10386 js2-highlight-external-variables
10387 (js2-node-get-prop expr 'SHORTHAND))
10388 (js2-record-name-node name))
10389 (js2-set-face ppos pend
10390 (if (js2-function-node-p
10391 (js2-object-prop-node-right expr))
10392 'font-lock-function-name-face
10393 'font-lock-variable-name-face)
10394 'record))))))
10395
10396 (defun js2-parse-plain-property (prop)
10397 "Parse a non-getter/setter property in an object literal.
10398 PROP is the node representing the property: a number, name or string."
10399 (let* ((tt (js2-get-token))
10400 (pos (js2-node-pos prop))
10401 colon expr result)
10402 (cond
10403 ;; Abbreviated property, as in {foo, bar}
10404 ((and (>= js2-language-version 200)
10405 (or (= tt js2-COMMA)
10406 (= tt js2-RC))
10407 (not (js2-number-node-p prop)))
10408 (js2-unget-token)
10409 (setq result (make-js2-object-prop-node
10410 :pos pos
10411 :left prop
10412 :right prop
10413 :op-pos (js2-current-token-len)))
10414 (js2-node-add-children result prop)
10415 (js2-node-set-prop result 'SHORTHAND t)
10416 result)
10417 ;; Normal property
10418 (t
10419 (if (= tt js2-COLON)
10420 (setq colon (- (js2-current-token-beg) pos)
10421 expr (js2-parse-assign-expr))
10422 (js2-report-error "msg.no.colon.prop")
10423 (setq expr (make-js2-error-node)))
10424 (setq result (make-js2-object-prop-node
10425 :pos pos
10426 ;; don't include last consumed token in length
10427 :len (- (+ (js2-node-pos expr)
10428 (js2-node-len expr))
10429 pos)
10430 :left prop
10431 :right expr
10432 :op-pos colon))
10433 (js2-node-add-children result prop expr)
10434 result))))
10435
10436 (defun js2-parse-getter-setter-prop (pos prop type-string)
10437 "Parse getter or setter property in an object literal.
10438 JavaScript syntax is:
10439
10440 { get foo() {...}, set foo(x) {...} }
10441
10442 and expression closure style is also supported
10443
10444 { get foo() x, set foo(x) _x = x }
10445
10446 POS is the start position of the `get' or `set' keyword.
10447 PROP is the `js2-name-node' representing the property name.
10448 GET-P is non-nil if the keyword was `get'."
10449 (let ((type (cond
10450 ((string= "get" type-string) js2-GET)
10451 ((string= "set" type-string) js2-SET)
10452 (t js2-FUNCTION)))
10453 result end
10454 (fn (js2-parse-function-expr)))
10455 ;; it has to be an anonymous function, as we already parsed the name
10456 (if (/= (js2-node-type fn) js2-FUNCTION)
10457 (js2-report-error "msg.bad.prop")
10458 (if (plusp (length (js2-function-name fn)))
10459 (js2-report-error "msg.bad.prop")))
10460 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10461 (setq end (js2-node-end fn)
10462 result (make-js2-getter-setter-node :type type
10463 :pos pos
10464 :len (- end pos)
10465 :left prop
10466 :right fn))
10467 (js2-node-add-children result prop fn)
10468 result))
10469
10470 (defun js2-create-name-node (&optional check-activation-p token string)
10471 "Create a name node using the current token and, optionally, STRING.
10472 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10473 (let* ((beg (js2-current-token-beg))
10474 (tt (js2-current-token-type))
10475 (s (or string
10476 (if (= js2-NAME tt)
10477 (js2-current-token-string)
10478 (js2-tt-name tt))))
10479 name)
10480 (setq name (make-js2-name-node :pos beg
10481 :name s
10482 :len (length s)))
10483 (if check-activation-p
10484 (js2-check-activation-name s (or token js2-NAME)))
10485 name))
10486
10487 ;;; Indentation support
10488
10489 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10490 ;; Karl cleverly deduces that the desired indentation level is often a
10491 ;; function of paren/bracket/brace nesting depth, which can be determined
10492 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10493 ;; then does some equally clever checks to see if we're in the context of a
10494 ;; substatement of a possibly braceless statement keyword such as if, while,
10495 ;; or finally. This approach yields pretty good results.
10496
10497 ;; The indenter is often "wrong", however, and needs to be overridden.
10498 ;; The right long-term solution is probably to emulate (or integrate
10499 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10500 ;; parse tree from `js2-parse' is present, which is not true at the
10501 ;; moment the user is typing, computing indentation is still thousands
10502 ;; of lines of code to handle every possible syntactic edge case.
10503
10504 ;; In the meantime, the compromise solution is that we offer a "bounce
10505 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10506 ;; current line indent among various likely guess points. This approach
10507 ;; is far from perfect, but should at least make it slightly easier to
10508 ;; move the line towards its desired indentation when manually
10509 ;; overriding Karl's heuristic nesting guesser.
10510
10511 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10512 ;; extensions such as `let' and Array comprehensions. Major kudos to
10513 ;; Karl for coming up with the initial approach, which packs a lot of
10514 ;; punch for so little code.
10515
10516 (defconst js2-possibly-braceless-keywords-re
10517 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10518 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10519 "try" "while" "with" "let")))
10520 "Regular expression matching keywords that are optionally
10521 followed by an opening brace.")
10522
10523 (defconst js2-indent-operator-re
10524 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10525 (regexp-opt '("in" "instanceof") 'words))
10526 "Regular expression matching operators that affect indentation
10527 of continued expressions.")
10528
10529 (defconst js2-declaration-keyword-re
10530 (regexp-opt '("var" "let" "const") 'words)
10531 "Regular expression matching variable declaration keywords.")
10532
10533 (defun js2-re-search-forward-inner (regexp &optional bound count)
10534 "Auxiliary function for `js2-re-search-forward'."
10535 (let (parse saved-point)
10536 (while (> count 0)
10537 (re-search-forward regexp bound)
10538 (setq parse (if saved-point
10539 (parse-partial-sexp saved-point (point))
10540 (syntax-ppss (point))))
10541 (cond ((nth 3 parse)
10542 (re-search-forward
10543 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10544 (save-excursion (end-of-line) (point)) t))
10545 ((nth 7 parse)
10546 (forward-line))
10547 ((or (nth 4 parse)
10548 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10549 (re-search-forward "\\*/"))
10550 (t
10551 (setq count (1- count))))
10552 (setq saved-point (point))))
10553 (point))
10554
10555 (defun js2-re-search-forward (regexp &optional bound noerror count)
10556 "Search forward but ignore strings and comments.
10557 Invokes `re-search-forward' but treats the buffer as if strings
10558 and comments have been removed."
10559 (let ((saved-point (point)))
10560 (condition-case err
10561 (cond ((null count)
10562 (js2-re-search-forward-inner regexp bound 1))
10563 ((< count 0)
10564 (js2-re-search-backward-inner regexp bound (- count)))
10565 ((> count 0)
10566 (js2-re-search-forward-inner regexp bound count)))
10567 (search-failed
10568 (goto-char saved-point)
10569 (unless noerror
10570 (error (error-message-string err)))))))
10571
10572 (defun js2-re-search-backward-inner (regexp &optional bound count)
10573 "Auxiliary function for `js2-re-search-backward'."
10574 (let (parse)
10575 (while (> count 0)
10576 (re-search-backward regexp bound)
10577 (setq parse (syntax-ppss (point)))
10578 (cond ((nth 3 parse)
10579 (re-search-backward
10580 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10581 (line-beginning-position) t))
10582 ((nth 7 parse)
10583 (goto-char (nth 8 parse)))
10584 ((or (nth 4 parse)
10585 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10586 (re-search-backward "/\\*"))
10587 (t
10588 (setq count (1- count))))))
10589 (point))
10590
10591 (defun js2-re-search-backward (regexp &optional bound noerror count)
10592 "Search backward but ignore strings and comments.
10593 Invokes `re-search-backward' but treats the buffer as if strings
10594 and comments have been removed."
10595 (let ((saved-point (point)))
10596 (condition-case err
10597 (cond ((null count)
10598 (js2-re-search-backward-inner regexp bound 1))
10599 ((< count 0)
10600 (js2-re-search-forward-inner regexp bound (- count)))
10601 ((> count 0)
10602 (js2-re-search-backward-inner regexp bound count)))
10603 (search-failed
10604 (goto-char saved-point)
10605 (unless noerror
10606 (error (error-message-string err)))))))
10607
10608 (defun js2-looking-at-operator-p ()
10609 "Return non-nil if text after point is a non-comma operator."
10610 (and (looking-at js2-indent-operator-re)
10611 (or (not (looking-at ":"))
10612 (save-excursion
10613 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10614 (looking-at "?"))))))
10615
10616 (defun js2-continued-expression-p ()
10617 "Return non-nil if the current line continues an expression."
10618 (save-excursion
10619 (back-to-indentation)
10620 (or (js2-looking-at-operator-p)
10621 (when (catch 'found
10622 (while (and (re-search-backward "\n" nil t)
10623 (let ((state (syntax-ppss)))
10624 (when (nth 4 state)
10625 (goto-char (nth 8 state))) ;; skip comments
10626 (skip-chars-backward " \t")
10627 (if (bolp)
10628 t
10629 (throw 'found t))))))
10630 (backward-char)
10631 (when (js2-looking-at-operator-p)
10632 (backward-char)
10633 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10634
10635 (defun js2-end-of-do-while-loop-p ()
10636 "Return non-nil if word after point is `while' of a do-while
10637 statement, else returns nil. A braceless do-while statement
10638 spanning several lines requires that the start of the loop is
10639 indented to the same column as the current line."
10640 (interactive)
10641 (save-excursion
10642 (when (looking-at "\\s-*\\<while\\>")
10643 (if (save-excursion
10644 (skip-chars-backward "[ \t\n]*}")
10645 (looking-at "[ \t\n]*}"))
10646 (save-excursion
10647 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10648 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10649 (or (looking-at "\\<do\\>")
10650 (let ((saved-indent (current-indentation)))
10651 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10652 (/= (current-indentation) saved-indent)))
10653 (and (looking-at "[ \t]*\\<do\\>")
10654 (not (js2-re-search-forward
10655 "\\<while\\>" (point-at-eol) t))
10656 (= (current-indentation) saved-indent))))))))
10657
10658 (defun js2-multiline-decl-indentation ()
10659 "Return the declaration indentation column if the current line belongs
10660 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10661 (let (forward-sexp-function ; use Lisp version
10662 at-opening-bracket)
10663 (save-excursion
10664 (back-to-indentation)
10665 (when (not (looking-at js2-declaration-keyword-re))
10666 (when (looking-at js2-indent-operator-re)
10667 (goto-char (match-end 0))) ; continued expressions are ok
10668 (while (and (not at-opening-bracket)
10669 (not (bobp))
10670 (let ((pos (point)))
10671 (save-excursion
10672 (js2-backward-sws)
10673 (or (eq (char-before) ?,)
10674 (and (not (eq (char-before) ?\;))
10675 (prog2 (skip-syntax-backward ".")
10676 (looking-at js2-indent-operator-re)
10677 (js2-backward-sws))
10678 (not (eq (char-before) ?\;)))
10679 (js2-same-line pos)))))
10680 (condition-case _
10681 (backward-sexp)
10682 (scan-error (setq at-opening-bracket t))))
10683 (when (looking-at js2-declaration-keyword-re)
10684 (goto-char (match-end 0))
10685 (1+ (current-column)))))))
10686
10687 (defun js2-ctrl-statement-indentation ()
10688 "Return the proper indentation of current line if it is a control statement.
10689 Returns an indentation if this line starts the body of a control
10690 statement without braces, else returns nil."
10691 (let (forward-sexp-function)
10692 (save-excursion
10693 (back-to-indentation)
10694 (when (and (not (js2-same-line (point-min)))
10695 (not (looking-at "{"))
10696 (js2-re-search-backward "[[:graph:]]" nil t)
10697 (not (looking-at "[{([]"))
10698 (progn
10699 (forward-char)
10700 (when (= (char-before) ?\))
10701 ;; scan-sexps sometimes throws an error
10702 (ignore-errors (backward-sexp))
10703 (skip-chars-backward " \t" (point-at-bol)))
10704 (let ((pt (point)))
10705 (back-to-indentation)
10706 (when (looking-at "}[ \t]*")
10707 (goto-char (match-end 0)))
10708 (and (looking-at js2-possibly-braceless-keywords-re)
10709 (= (match-end 0) pt)
10710 (not (js2-end-of-do-while-loop-p))))))
10711 (+ (current-indentation) js2-basic-offset)))))
10712
10713 (defun js2-indent-in-array-comp (parse-status)
10714 "Return non-nil if we think we're in an array comprehension.
10715 In particular, return the buffer position of the first `for' kwd."
10716 (let ((bracket (nth 1 parse-status))
10717 (end (point)))
10718 (when bracket
10719 (save-excursion
10720 (goto-char bracket)
10721 (when (looking-at "\\[")
10722 (forward-char 1)
10723 (js2-forward-sws)
10724 (if (looking-at "[[{]")
10725 (let (forward-sexp-function) ; use Lisp version
10726 (forward-sexp) ; skip destructuring form
10727 (js2-forward-sws)
10728 (if (and (/= (char-after) ?,) ; regular array
10729 (looking-at "for"))
10730 (match-beginning 0)))
10731 ;; to skip arbitrary expressions we need the parser,
10732 ;; so we'll just guess at it.
10733 (if (and (> end (point)) ; not empty literal
10734 (re-search-forward "[^,]]* \\(for\\) " end t)
10735 ;; not inside comment or string literal
10736 (let ((state (parse-partial-sexp bracket (point))))
10737 (not (or (nth 3 state) (nth 4 state)))))
10738 (match-beginning 1))))))))
10739
10740 (defun js2-array-comp-indentation (parse-status for-kwd)
10741 (if (js2-same-line for-kwd)
10742 ;; first continuation line
10743 (save-excursion
10744 (goto-char (nth 1 parse-status))
10745 (forward-char 1)
10746 (skip-chars-forward " \t")
10747 (current-column))
10748 (save-excursion
10749 (goto-char for-kwd)
10750 (current-column))))
10751
10752 (defun js2-proper-indentation (parse-status)
10753 "Return the proper indentation for the current line."
10754 (save-excursion
10755 (back-to-indentation)
10756 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10757 (at-closing-bracket (looking-at "[]})]"))
10758 (same-indent-p (or at-closing-bracket
10759 (looking-at "\\<case\\>[^:]")
10760 (and (looking-at "\\<default:")
10761 (save-excursion
10762 (js2-backward-sws)
10763 (not (memq (char-before) '(?, ?{)))))))
10764 (continued-expr-p (js2-continued-expression-p))
10765 (declaration-indent (and js2-pretty-multiline-declarations
10766 (js2-multiline-decl-indentation)))
10767 (bracket (nth 1 parse-status))
10768 beg indent)
10769 (cond
10770 ;; indent array comprehension continuation lines specially
10771 ((and bracket
10772 (>= js2-language-version 170)
10773 (not (js2-same-line bracket))
10774 (setq beg (js2-indent-in-array-comp parse-status))
10775 (>= (point) (save-excursion
10776 (goto-char beg)
10777 (point-at-bol)))) ; at or after first loop?
10778 (js2-array-comp-indentation parse-status beg))
10779
10780 (ctrl-stmt-indent)
10781
10782 ((and declaration-indent continued-expr-p)
10783 (+ declaration-indent js2-basic-offset))
10784
10785 (declaration-indent)
10786
10787 (bracket
10788 (goto-char bracket)
10789 (cond
10790 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10791 (when (save-excursion (skip-chars-backward " \t)")
10792 (looking-at ")"))
10793 (backward-list))
10794 (back-to-indentation)
10795 (and (eq js2-pretty-multiline-declarations 'all)
10796 (looking-at js2-declaration-keyword-re)
10797 (goto-char (1+ (match-end 0))))
10798 (setq indent
10799 (cond (same-indent-p
10800 (current-column))
10801 (continued-expr-p
10802 (+ (current-column) (* 2 js2-basic-offset)))
10803 (t
10804 (+ (current-column) js2-basic-offset))))
10805 (if (and js2-indent-switch-body
10806 (not at-closing-bracket)
10807 (looking-at "\\_<switch\\_>"))
10808 (+ indent js2-basic-offset)
10809 indent))
10810 (t
10811 (unless same-indent-p
10812 (forward-char)
10813 (skip-chars-forward " \t"))
10814 (current-column))))
10815
10816 (continued-expr-p js2-basic-offset)
10817
10818 (t 0)))))
10819
10820 (defun js2-lineup-comment (parse-status)
10821 "Indent a multi-line block comment continuation line."
10822 (let* ((beg (nth 8 parse-status))
10823 (first-line (js2-same-line beg))
10824 (offset (save-excursion
10825 (goto-char beg)
10826 (if (looking-at "/\\*")
10827 (+ 1 (current-column))
10828 0))))
10829 (unless first-line
10830 (indent-line-to offset))))
10831
10832 (defun js2-backward-sws ()
10833 "Move backward through whitespace and comments."
10834 (interactive)
10835 (while (forward-comment -1)))
10836
10837 (defun js2-forward-sws ()
10838 "Move forward through whitespace and comments."
10839 (interactive)
10840 (while (forward-comment 1)))
10841
10842 (defun js2-current-indent (&optional pos)
10843 "Return column of indentation on current line.
10844 If POS is non-nil, go to that point and return indentation for that line."
10845 (save-excursion
10846 (if pos
10847 (goto-char pos))
10848 (back-to-indentation)
10849 (current-column)))
10850
10851 (defun js2-arglist-close ()
10852 "Return non-nil if we're on a line beginning with a close-paren/brace."
10853 (save-excursion
10854 (goto-char (point-at-bol))
10855 (js2-forward-sws)
10856 (looking-at "[])}]")))
10857
10858 (defun js2-indent-looks-like-label-p ()
10859 (goto-char (point-at-bol))
10860 (js2-forward-sws)
10861 (looking-at (concat js2-mode-identifier-re ":")))
10862
10863 (defun js2-indent-in-objlit-p (parse-status)
10864 "Return non-nil if this looks like an object-literal entry."
10865 (let ((start (nth 1 parse-status)))
10866 (and
10867 start
10868 (save-excursion
10869 (and (zerop (forward-line -1))
10870 (not (< (point) start)) ; crossed a {} boundary
10871 (js2-indent-looks-like-label-p)))
10872 (save-excursion
10873 (js2-indent-looks-like-label-p)))))
10874
10875 ;; If prev line looks like foobar({ then we're passing an object
10876 ;; literal to a function call, and people pretty much always want to
10877 ;; de-dent back to the previous line, so move the 'basic-offset'
10878 ;; position to the front.
10879 (defun js2-indent-objlit-arg-p (parse-status)
10880 (save-excursion
10881 (back-to-indentation)
10882 (js2-backward-sws)
10883 (and (eq (1- (point)) (nth 1 parse-status))
10884 (eq (char-before) ?{)
10885 (progn
10886 (forward-char -1)
10887 (skip-chars-backward " \t")
10888 (eq (char-before) ?\()))))
10889
10890 (defun js2-indent-case-block-p ()
10891 (save-excursion
10892 (back-to-indentation)
10893 (js2-backward-sws)
10894 (goto-char (point-at-bol))
10895 (skip-chars-forward " \t")
10896 (looking-at "case\\s-.+:")))
10897
10898 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10899 "Cycle among alternate computed indentation positions.
10900 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10901 of the buffer to the current point. NORMAL-COL is the indentation
10902 column computed by the heuristic guesser based on current paren,
10903 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10904 in reverse."
10905 (let ((cur-indent (js2-current-indent))
10906 (old-buffer-undo-list buffer-undo-list)
10907 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10908 (current-line (save-excursion
10909 (forward-line 0) ; move to bol
10910 (1+ (count-lines (point-min) (point)))))
10911 positions pos main-pos anchor arglist-cont same-indent
10912 basic-offset computed-pos)
10913 ;; temporarily don't record undo info, if user requested this
10914 (when js2-mode-indent-inhibit-undo
10915 (setq buffer-undo-list t))
10916 (unwind-protect
10917 (progn
10918 ;; First likely point: indent from beginning of previous code line
10919 (push (setq basic-offset
10920 (+ (save-excursion
10921 (back-to-indentation)
10922 (js2-backward-sws)
10923 (back-to-indentation)
10924 (current-column))
10925 js2-basic-offset))
10926 positions)
10927
10928 ;; (First + epsilon) likely point: indent 2x from beginning of
10929 ;; previous code line. Google does it this way.
10930 (push (setq basic-offset
10931 (+ (save-excursion
10932 (back-to-indentation)
10933 (js2-backward-sws)
10934 (back-to-indentation)
10935 (current-column))
10936 (* 2 js2-basic-offset)))
10937 positions)
10938
10939 ;; Second likely point: indent from assign-expr RHS. This
10940 ;; is just a crude guess based on finding " = " on the previous
10941 ;; line containing actual code.
10942 (setq pos (save-excursion
10943 (forward-line -1)
10944 (goto-char (point-at-bol))
10945 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10946 (point-at-eol) t)
10947 (goto-char (match-end 1))
10948 (skip-chars-forward " \t\r\n")
10949 (current-column))))
10950 (when pos
10951 (incf pos js2-basic-offset)
10952 (push pos positions))
10953
10954 ;; Third likely point: same indent as previous line of code.
10955 ;; Make it the first likely point if we're not on an
10956 ;; arglist-close line and previous line ends in a comma, or
10957 ;; both this line and prev line look like object-literal
10958 ;; elements.
10959 (setq pos (save-excursion
10960 (goto-char (point-at-bol))
10961 (js2-backward-sws)
10962 (back-to-indentation)
10963 (prog1
10964 (current-column)
10965 ;; while we're here, look for trailing comma
10966 (if (save-excursion
10967 (goto-char (point-at-eol))
10968 (js2-backward-sws)
10969 (eq (char-before) ?,))
10970 (setq arglist-cont (1- (point)))))))
10971 (when pos
10972 (if (and (or arglist-cont
10973 (js2-indent-in-objlit-p parse-status))
10974 (not (js2-arglist-close)))
10975 (setq same-indent pos))
10976 (push pos positions))
10977
10978 ;; Fourth likely point: first preceding code with less indentation.
10979 ;; than the immediately preceding code line.
10980 (setq pos (save-excursion
10981 (back-to-indentation)
10982 (js2-backward-sws)
10983 (back-to-indentation)
10984 (setq anchor (current-column))
10985 (while (and (zerop (forward-line -1))
10986 (>= (progn
10987 (back-to-indentation)
10988 (current-column))
10989 anchor)))
10990 (setq pos (current-column))))
10991 (push pos positions)
10992
10993 ;; nesting-heuristic position, main by default
10994 (push (setq main-pos normal-col) positions)
10995
10996 ;; delete duplicates and sort positions list
10997 (setq positions (sort (delete-dups positions) '<))
10998
10999 ;; comma-list continuation lines: prev line indent takes precedence
11000 (if same-indent
11001 (setq main-pos same-indent))
11002
11003 ;; common special cases where we want to indent in from previous line
11004 (if (or (js2-indent-case-block-p)
11005 (js2-indent-objlit-arg-p parse-status))
11006 (setq main-pos basic-offset))
11007
11008 ;; if bouncing backwards, reverse positions list
11009 (if backwards
11010 (setq positions (reverse positions)))
11011
11012 ;; record whether we're already sitting on one of the alternatives
11013 (setq pos (member cur-indent positions))
11014
11015 (cond
11016 ;; case 0: we're one one of the alternatives and this is the
11017 ;; first time they've pressed TAB on this line (best-guess).
11018 ((and js2-mode-indent-ignore-first-tab
11019 pos
11020 ;; first time pressing TAB on this line?
11021 (not (eq js2-mode-last-indented-line current-line)))
11022 ;; do nothing
11023 (setq computed-pos nil))
11024 ;; case 1: only one computed position => use it
11025 ((null (cdr positions))
11026 (setq computed-pos 0))
11027 ;; case 2: not on any of the computed spots => use main spot
11028 ((not pos)
11029 (setq computed-pos (js2-position main-pos positions)))
11030 ;; case 3: on last position: cycle to first position
11031 ((null (cdr pos))
11032 (setq computed-pos 0))
11033 ;; case 4: on intermediate position: cycle to next position
11034 (t
11035 (setq computed-pos (js2-position (second pos) positions))))
11036
11037 ;; see if any hooks want to indent; otherwise we do it
11038 (loop with result = nil
11039 for hook in js2-indent-hook
11040 while (null result)
11041 do
11042 (setq result (funcall hook positions computed-pos))
11043 finally do
11044 (unless (or result (null computed-pos))
11045 (indent-line-to (nth computed-pos positions)))))
11046
11047 ;; finally
11048 (if js2-mode-indent-inhibit-undo
11049 (setq buffer-undo-list old-buffer-undo-list))
11050 ;; see commentary for `js2-mode-last-indented-line'
11051 (setq js2-mode-last-indented-line current-line))))
11052
11053 (defun js2-indent-bounce-backwards ()
11054 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11055 cycles between the computed indentation positions in reverse order."
11056 (interactive)
11057 (js2-indent-line t))
11058
11059 (defun js2-1-line-comment-continuation-p ()
11060 "Return t if we're in a 1-line comment continuation.
11061 If so, we don't ever want to use bounce-indent."
11062 (save-excursion
11063 (and (progn
11064 (forward-line 0)
11065 (looking-at "\\s-*//"))
11066 (progn
11067 (forward-line -1)
11068 (forward-line 0)
11069 (when (looking-at "\\s-*$")
11070 (js2-backward-sws)
11071 (forward-line 0))
11072 (looking-at "\\s-*//")))))
11073
11074 (defun js2-indent-line (&optional bounce-backwards)
11075 "Indent the current line as JavaScript source text."
11076 (interactive)
11077 (let (parse-status offset indent-col
11078 ;; Don't whine about errors/warnings when we're indenting.
11079 ;; This has to be set before calling parse-partial-sexp below.
11080 (inhibit-point-motion-hooks t))
11081 (setq parse-status (save-excursion
11082 (syntax-ppss (point-at-bol)))
11083 offset (- (point) (save-excursion
11084 (back-to-indentation)
11085 (point))))
11086 (js2-with-underscore-as-word-syntax
11087 (if (nth 4 parse-status)
11088 (js2-lineup-comment parse-status)
11089 (setq indent-col (js2-proper-indentation parse-status))
11090 ;; See comments below about `js2-mode-last-indented-line'.
11091 (cond
11092 ;; bounce-indenting is disabled during electric-key indent.
11093 ;; It doesn't work well on first line of buffer.
11094 ((and js2-bounce-indent-p
11095 (not (js2-same-line (point-min)))
11096 (not (js2-1-line-comment-continuation-p)))
11097 (js2-bounce-indent indent-col parse-status bounce-backwards))
11098 ;; just indent to the guesser's likely spot
11099 (t (indent-line-to indent-col))))
11100 (when (plusp offset)
11101 (forward-char offset)))))
11102
11103 (defun js2-indent-region (start end)
11104 "Indent the region, but don't use bounce indenting."
11105 (let ((js2-bounce-indent-p nil)
11106 (indent-region-function nil)
11107 (after-change-functions (remq 'js2-mode-edit
11108 after-change-functions)))
11109 (indent-region start end nil) ; nil for byte-compiler
11110 (js2-mode-edit start end (- end start))))
11111
11112 (defvar js2-minor-mode-map
11113 (let ((map (make-sparse-keymap)))
11114 (define-key map (kbd "C-c C-`") #'js2-next-error)
11115 (define-key map [mouse-1] #'js2-mode-show-node)
11116 map)
11117 "Keymap used when `js2-minor-mode' is active.")
11118
11119 ;;;###autoload
11120 (define-minor-mode js2-minor-mode
11121 "Minor mode for running js2 as a background linter.
11122 This allows you to use a different major mode for JavaScript editing,
11123 such as `js-mode', while retaining the asynchronous error/warning
11124 highlighting features of `js2-mode'."
11125 :group 'js2-mode
11126 :lighter " js-lint"
11127 (if js2-minor-mode
11128 (js2-minor-mode-enter)
11129 (js2-minor-mode-exit)))
11130
11131 (defun js2-minor-mode-enter ()
11132 "Initialization for `js2-minor-mode'."
11133 (set (make-local-variable 'max-lisp-eval-depth)
11134 (max max-lisp-eval-depth 3000))
11135 (setq next-error-function #'js2-next-error)
11136 (js2-set-default-externs)
11137 ;; Experiment: make reparse-delay longer for longer files.
11138 (if (plusp js2-dynamic-idle-timer-adjust)
11139 (setq js2-idle-timer-delay
11140 (* js2-idle-timer-delay
11141 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11142 (setq js2-mode-buffer-dirty-p t
11143 js2-mode-parsing nil)
11144 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11145 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11146 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11147 (when js2-include-jslint-globals
11148 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11149 (run-hooks 'js2-init-hook)
11150 (js2-reparse))
11151
11152 (defun js2-minor-mode-exit ()
11153 "Turn off `js2-minor-mode'."
11154 (setq next-error-function nil)
11155 (remove-hook 'after-change-functions #'js2-mode-edit t)
11156 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11157 (when js2-mode-node-overlay
11158 (delete-overlay js2-mode-node-overlay)
11159 (setq js2-mode-node-overlay nil))
11160 (js2-remove-overlays)
11161 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11162 (setq js2-mode-ast nil))
11163
11164 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11165 (make-variable-buffer-local 'js2-source-buffer)
11166
11167 (defun* js2-display-error-list ()
11168 "Display a navigable buffer listing parse errors/warnings."
11169 (interactive)
11170 (unless (js2-have-errors-p)
11171 (message "No errors")
11172 (return-from js2-display-error-list))
11173 (labels ((annotate-list
11174 (lst type)
11175 "Add diagnostic TYPE and line number to errs list"
11176 (mapcar (lambda (err)
11177 (list err type (line-number-at-pos (nth 1 err))))
11178 lst)))
11179 (let* ((srcbuf (current-buffer))
11180 (errbuf (get-buffer-create "*js-lint*"))
11181 (errors (annotate-list
11182 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11183 'js2-error)) ; must be a valid face name
11184 (warnings (annotate-list
11185 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11186 'js2-warning)) ; must be a valid face name
11187 (all-errs (sort (append errors warnings)
11188 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
11189 (with-current-buffer errbuf
11190 (let ((inhibit-read-only t))
11191 (erase-buffer)
11192 (dolist (err all-errs)
11193 (destructuring-bind ((msg-key beg _end &rest) type line) err
11194 (insert-text-button
11195 (format "line %d: %s" line (js2-get-msg msg-key))
11196 'face type
11197 'follow-link "\C-m"
11198 'action 'js2-error-buffer-jump
11199 'js2-msg (js2-get-msg msg-key)
11200 'js2-pos beg)
11201 (insert "\n"))))
11202 (js2-error-buffer-mode)
11203 (setq js2-source-buffer srcbuf)
11204 (pop-to-buffer errbuf)
11205 (goto-char (point-min))
11206 (unless (eobp)
11207 (js2-error-buffer-view))))))
11208
11209 (defvar js2-error-buffer-mode-map
11210 (let ((map (make-sparse-keymap)))
11211 (define-key map "n" #'js2-error-buffer-next)
11212 (define-key map "p" #'js2-error-buffer-prev)
11213 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11214 (define-key map "o" #'js2-error-buffer-view)
11215 (define-key map "q" #'js2-error-buffer-quit)
11216 map)
11217 "Keymap used for js2 diagnostics buffers.")
11218
11219 (defun js2-error-buffer-mode ()
11220 "Major mode for js2 diagnostics buffers.
11221 Selecting an error will jump it to the corresponding source-buffer error.
11222 \\{js2-error-buffer-mode-map}"
11223 (interactive)
11224 (setq major-mode 'js2-error-buffer-mode
11225 mode-name "JS Lint Diagnostics")
11226 (use-local-map js2-error-buffer-mode-map)
11227 (setq truncate-lines t)
11228 (set-buffer-modified-p nil)
11229 (setq buffer-read-only t)
11230 (run-hooks 'js2-error-buffer-mode-hook))
11231
11232 (defun js2-error-buffer-next ()
11233 "Move to next error and view it."
11234 (interactive)
11235 (when (zerop (forward-line 1))
11236 (js2-error-buffer-view)))
11237
11238 (defun js2-error-buffer-prev ()
11239 "Move to previous error and view it."
11240 (interactive)
11241 (when (zerop (forward-line -1))
11242 (js2-error-buffer-view)))
11243
11244 (defun js2-error-buffer-quit ()
11245 "Kill the current buffer."
11246 (interactive)
11247 (kill-buffer))
11248
11249 (defun js2-error-buffer-jump (&rest ignored)
11250 "Jump cursor to current error in source buffer."
11251 (interactive)
11252 (when (js2-error-buffer-view)
11253 (pop-to-buffer js2-source-buffer)))
11254
11255 (defun js2-error-buffer-view ()
11256 "Scroll source buffer to show error at current line."
11257 (interactive)
11258 (cond
11259 ((not (eq major-mode 'js2-error-buffer-mode))
11260 (message "Not in a js2 errors buffer"))
11261 ((not (buffer-live-p js2-source-buffer))
11262 (message "Source buffer has been killed"))
11263 ((not (wholenump (get-text-property (point) 'js2-pos)))
11264 (message "There does not seem to be an error here"))
11265 (t
11266 (let ((pos (get-text-property (point) 'js2-pos))
11267 (msg (get-text-property (point) 'js2-msg)))
11268 (save-selected-window
11269 (pop-to-buffer js2-source-buffer)
11270 (goto-char pos)
11271 (message msg))))))
11272
11273 ;;;###autoload
11274 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11275 ;; FIXME: Should derive from js-mode.
11276 "Major mode for editing JavaScript code."
11277 ;; Used by comment-region; don't change it.
11278 (set (make-local-variable 'comment-start) "//")
11279 (set (make-local-variable 'comment-end) "")
11280 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11281 (set (make-local-variable 'max-lisp-eval-depth)
11282 (max max-lisp-eval-depth 3000))
11283 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11284 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11285 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11286 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11287 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11288 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11289 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11290 ;; for characters inside regexp literals.
11291 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11292 ;; this is necessary to make `show-paren-function' work properly
11293 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11294 ;; needed for M-x rgrep, among other things
11295 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11296
11297 (set (make-local-variable 'electric-indent-chars)
11298 (append "{}()[]:;,*." electric-indent-chars))
11299 (set (make-local-variable 'electric-layout-rules)
11300 '((?\; . after) (?\{ . after) (?\} . before)))
11301
11302 ;; some variables needed by cc-engine for paragraph-fill, etc.
11303 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11304 c-comment-start-regexp "/[*/]\\|\\s|"
11305 c-line-comment-starter "//"
11306 c-paragraph-start js2-paragraph-start
11307 c-paragraph-separate "$"
11308 c-syntactic-ws-start js2-syntactic-ws-start
11309 c-syntactic-ws-end js2-syntactic-ws-end
11310 c-syntactic-eol js2-syntactic-eol)
11311
11312 (let ((c-buffer-is-cc-mode t))
11313 ;; Copied from `js-mode'. Also see Bug#6071.
11314 (make-local-variable 'paragraph-start)
11315 (make-local-variable 'paragraph-separate)
11316 (make-local-variable 'paragraph-ignore-fill-prefix)
11317 (make-local-variable 'adaptive-fill-mode)
11318 (make-local-variable 'adaptive-fill-regexp)
11319 (c-setup-paragraph-variables))
11320
11321 (setq font-lock-defaults '(nil t))
11322
11323 ;; Experiment: make reparse-delay longer for longer files.
11324 (when (plusp js2-dynamic-idle-timer-adjust)
11325 (setq js2-idle-timer-delay
11326 (* js2-idle-timer-delay
11327 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11328
11329 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11330 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11331 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11332 (setq next-error-function #'js2-next-error)
11333 (imenu-add-to-menubar (concat "IM-" mode-name))
11334 (add-to-invisibility-spec '(js2-outline . t))
11335 (set (make-local-variable 'line-move-ignore-invisible) t)
11336 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11337
11338 (setq js2-mode-functions-hidden nil
11339 js2-mode-comments-hidden nil
11340 js2-mode-buffer-dirty-p t
11341 js2-mode-parsing nil)
11342
11343 (js2-set-default-externs)
11344
11345 (when js2-include-jslint-globals
11346 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11347
11348 (run-hooks 'js2-init-hook)
11349
11350 (js2-reparse))
11351
11352 (defun js2-mode-exit ()
11353 "Exit `js2-mode' and clean up."
11354 (interactive)
11355 (when js2-mode-node-overlay
11356 (delete-overlay js2-mode-node-overlay)
11357 (setq js2-mode-node-overlay nil))
11358 (js2-remove-overlays)
11359 (setq js2-mode-ast nil)
11360 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11361 (remove-from-invisibility-spec '(js2-outline . t))
11362 (js2-mode-show-all)
11363 (with-silent-modifications
11364 (js2-clear-face (point-min) (point-max))))
11365
11366 (defun js2-mode-reset-timer ()
11367 "Cancel any existing parse timer and schedule a new one."
11368 (if js2-mode-parse-timer
11369 (cancel-timer js2-mode-parse-timer))
11370 (setq js2-mode-parsing nil)
11371 (let ((timer (timer-create)))
11372 (setq js2-mode-parse-timer timer)
11373 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11374 (timer-set-idle-time timer js2-idle-timer-delay)
11375 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11376 (timer-activate-when-idle timer nil)))
11377
11378 (defun js2-mode-idle-reparse (buffer)
11379 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11380 it to be reparsed when the buffer is selected."
11381 (cond ((eq buffer (current-buffer))
11382 (js2-reparse))
11383 ((buffer-live-p buffer)
11384 ;; reparse when the buffer is selected again
11385 (with-current-buffer buffer
11386 (add-hook 'window-configuration-change-hook
11387 #'js2-mode-idle-reparse-inner
11388 nil t)))))
11389
11390 (defun js2-mode-idle-reparse-inner ()
11391 (remove-hook 'window-configuration-change-hook
11392 #'js2-mode-idle-reparse-inner
11393 t)
11394 (js2-reparse))
11395
11396 (defun js2-mode-edit (_beg _end _len)
11397 "Schedule a new parse after buffer is edited.
11398 Buffer edit spans from BEG to END and is of length LEN."
11399 (setq js2-mode-buffer-dirty-p t)
11400 (js2-mode-hide-overlay)
11401 (js2-mode-reset-timer))
11402
11403 (defun js2-minor-mode-edit (_beg _end _len)
11404 "Callback for buffer edits in `js2-mode'.
11405 Schedules a new parse after buffer is edited.
11406 Buffer edit spans from BEG to END and is of length LEN."
11407 (setq js2-mode-buffer-dirty-p t)
11408 (js2-mode-hide-overlay)
11409 (js2-mode-reset-timer))
11410
11411 (defun js2-reparse (&optional force)
11412 "Re-parse current buffer after user finishes some data entry.
11413 If we get any user input while parsing, including cursor motion,
11414 we discard the parse and reschedule it. If FORCE is nil, then the
11415 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11416 (let (time
11417 interrupted-p
11418 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11419 (unless js2-mode-parsing
11420 (setq js2-mode-parsing t)
11421 (unwind-protect
11422 (when (or js2-mode-buffer-dirty-p force)
11423 (js2-remove-overlays)
11424 (setq js2-mode-buffer-dirty-p nil
11425 js2-mode-fontifications nil
11426 js2-mode-deferred-properties nil)
11427 (if js2-mode-verbose-parse-p
11428 (message "parsing..."))
11429 (setq time
11430 (js2-time
11431 (setq interrupted-p
11432 (catch 'interrupted
11433 (js2-parse)
11434 (with-silent-modifications
11435 ;; if parsing is interrupted, comments and regex
11436 ;; literals stay ignored by `parse-partial-sexp'
11437 (remove-text-properties (point-min) (point-max)
11438 '(syntax-table))
11439 (js2-mode-apply-deferred-properties)
11440 (js2-mode-remove-suppressed-warnings)
11441 (js2-mode-show-warnings)
11442 (js2-mode-show-errors)
11443 (if (>= js2-highlight-level 1)
11444 (js2-highlight-jsdoc js2-mode-ast)))
11445 nil))))
11446 (if interrupted-p
11447 (progn
11448 ;; unfinished parse => try again
11449 (setq js2-mode-buffer-dirty-p t)
11450 (js2-mode-reset-timer))
11451 (if js2-mode-verbose-parse-p
11452 (message "Parse time: %s" time))))
11453 (setq js2-mode-parsing nil)
11454 (unless interrupted-p
11455 (setq js2-mode-parse-timer nil))))))
11456
11457 (defun js2-mode-show-node (event)
11458 "Debugging aid: highlight selected AST node on mouse click."
11459 (interactive "e")
11460 (mouse-set-point event)
11461 (setq deactivate-mark t)
11462 (when js2-mode-show-overlay
11463 (let ((node (js2-node-at-point))
11464 beg end)
11465 (if (null node)
11466 (message "No node found at location %s" (point))
11467 (setq beg (js2-node-abs-pos node)
11468 end (+ beg (js2-node-len node)))
11469 (if js2-mode-node-overlay
11470 (move-overlay js2-mode-node-overlay beg end)
11471 (setq js2-mode-node-overlay (make-overlay beg end))
11472 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11473 (with-silent-modifications
11474 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
11475 (message "%s, parent: %s"
11476 (js2-node-short-name node)
11477 (if (js2-node-parent node)
11478 (js2-node-short-name (js2-node-parent node))
11479 "nil"))))))
11480
11481 (defun js2-mode-hide-overlay (&optional _p1 p2)
11482 "Remove the debugging overlay when the point moves.
11483 P1 and P2 are the old and new values of point, respectively."
11484 (when js2-mode-node-overlay
11485 (let ((beg (overlay-start js2-mode-node-overlay))
11486 (end (overlay-end js2-mode-node-overlay)))
11487 ;; Sometimes we're called spuriously.
11488 (unless (and p2
11489 (>= p2 beg)
11490 (<= p2 end))
11491 (with-silent-modifications
11492 (remove-text-properties beg end '(point-left nil)))
11493 (delete-overlay js2-mode-node-overlay)
11494 (setq js2-mode-node-overlay nil)))))
11495
11496 (defun js2-mode-reset ()
11497 "Debugging helper: reset everything."
11498 (interactive)
11499 (js2-mode-exit)
11500 (js2-mode))
11501
11502 (defun js2-mode-show-warn-or-err (e face)
11503 "Highlight a warning or error E with FACE.
11504 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11505 The last element is optional. When present, use instead of FACE."
11506 (let* ((key (first e))
11507 (beg (second e))
11508 (end (+ beg (third e)))
11509 ;; Don't inadvertently go out of bounds.
11510 (beg (max (point-min) (min beg (point-max))))
11511 (end (max (point-min) (min end (point-max))))
11512 (ovl (make-overlay beg end)))
11513 (overlay-put ovl 'font-lock-face (or (fourth e) face))
11514 (overlay-put ovl 'js2-error t)
11515 (put-text-property beg end 'help-echo (js2-get-msg key))
11516 (put-text-property beg end 'point-entered #'js2-echo-error)))
11517
11518 (defun js2-remove-overlays ()
11519 "Remove overlays from buffer that have a `js2-error' property."
11520 (let ((beg (point-min))
11521 (end (point-max)))
11522 (save-excursion
11523 (dolist (o (overlays-in beg end))
11524 (when (overlay-get o 'js2-error)
11525 (delete-overlay o))))))
11526
11527 (defun js2-error-at-point (&optional pos)
11528 "Return non-nil if there's an error overlay at POS.
11529 Defaults to point."
11530 (loop with pos = (or pos (point))
11531 for o in (overlays-at pos)
11532 thereis (overlay-get o 'js2-error)))
11533
11534 (defun js2-mode-apply-deferred-properties ()
11535 "Apply fontifications and other text properties recorded during parsing."
11536 (when (plusp js2-highlight-level)
11537 ;; We defer clearing faces as long as possible to eliminate flashing.
11538 (js2-clear-face (point-min) (point-max))
11539 ;; Have to reverse the recorded fontifications list so that errors
11540 ;; and warnings overwrite the normal fontifications.
11541 (dolist (f (nreverse js2-mode-fontifications))
11542 (put-text-property (first f) (second f) 'font-lock-face (third f)))
11543 (setq js2-mode-fontifications nil))
11544 (dolist (p js2-mode-deferred-properties)
11545 (apply #'put-text-property p))
11546 (setq js2-mode-deferred-properties nil))
11547
11548 (defun js2-mode-show-errors ()
11549 "Highlight syntax errors."
11550 (when js2-mode-show-parse-errors
11551 (dolist (e (js2-ast-root-errors js2-mode-ast))
11552 (js2-mode-show-warn-or-err e 'js2-error))))
11553
11554 (defun js2-mode-remove-suppressed-warnings ()
11555 "Take suppressed warnings out of the AST warnings list.
11556 This ensures that the counts and `next-error' are correct."
11557 (setf (js2-ast-root-warnings js2-mode-ast)
11558 (js2-delete-if
11559 (lambda (e)
11560 (let ((key (caar e)))
11561 (or
11562 (and (not js2-strict-trailing-comma-warning)
11563 (string-match "trailing\\.comma" key))
11564 (and (not js2-strict-cond-assign-warning)
11565 (string= key "msg.equal.as.assign"))
11566 (and js2-missing-semi-one-line-override
11567 (string= key "msg.missing.semi")
11568 (let* ((beg (second e))
11569 (node (js2-node-at-point beg))
11570 (fn (js2-mode-find-parent-fn node))
11571 (body (and fn (js2-function-node-body fn)))
11572 (lc (and body (js2-node-abs-pos body)))
11573 (rc (and lc (+ lc (js2-node-len body)))))
11574 (and fn
11575 (or (null body)
11576 (save-excursion
11577 (goto-char beg)
11578 (and (js2-same-line lc)
11579 (js2-same-line rc))))))))))
11580 (js2-ast-root-warnings js2-mode-ast))))
11581
11582 (defun js2-mode-show-warnings ()
11583 "Highlight strict-mode warnings."
11584 (when js2-mode-show-strict-warnings
11585 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11586 (js2-mode-show-warn-or-err e 'js2-warning))))
11587
11588 (defun js2-echo-error (_old-point new-point)
11589 "Called by point-motion hooks."
11590 (let ((msg (get-text-property new-point 'help-echo)))
11591 (when (and (stringp msg)
11592 (not (active-minibuffer-window))
11593 (not (current-message)))
11594 (message msg))))
11595
11596 (defalias 'js2-echo-help #'js2-echo-error)
11597
11598 (defun js2-line-break (&optional _soft)
11599 "Break line at point and indent, continuing comment if within one.
11600 If inside a string, and `js2-concat-multiline-strings' is not
11601 nil, turn it into concatenation."
11602 (interactive)
11603 (let ((parse-status (syntax-ppss)))
11604 (cond
11605 ;; Check if we're inside a string.
11606 ((nth 3 parse-status)
11607 (if js2-concat-multiline-strings
11608 (js2-mode-split-string parse-status)
11609 (insert "\n")))
11610 ;; Check if inside a block comment.
11611 ((nth 4 parse-status)
11612 (js2-mode-extend-comment (nth 8 parse-status)))
11613 (t
11614 (newline-and-indent)))))
11615
11616 (defun js2-mode-split-string (parse-status)
11617 "Turn a newline in mid-string into a string concatenation.
11618 PARSE-STATUS is as documented in `parse-partial-sexp'."
11619 (let* ((quote-char (nth 3 parse-status))
11620 (at-eol (eq js2-concat-multiline-strings 'eol)))
11621 (insert quote-char)
11622 (insert (if at-eol " +\n" "\n"))
11623 (unless at-eol
11624 (insert "+ "))
11625 (js2-indent-line)
11626 (insert quote-char)
11627 (when (eolp)
11628 (insert quote-char)
11629 (backward-char 1))))
11630
11631 (defun js2-mode-extend-comment (start-pos)
11632 "Indent the line and, when inside a comment block, add comment prefix."
11633 (let (star single col first-line needs-close)
11634 (save-excursion
11635 (back-to-indentation)
11636 (when (< (point) start-pos)
11637 (goto-char start-pos))
11638 (cond
11639 ((looking-at "\\*[^/]")
11640 (setq star t
11641 col (current-column)))
11642 ((looking-at "/\\*")
11643 (setq star t
11644 first-line t
11645 col (1+ (current-column))))
11646 ((looking-at "//")
11647 (setq single t
11648 col (current-column)))))
11649 ;; Heuristic for whether we need to close the comment:
11650 ;; if we've got a parse error here, assume it's an unterminated
11651 ;; comment.
11652 (setq needs-close
11653 (or
11654 (eq (get-text-property (1- (point)) 'point-entered)
11655 'js2-echo-error)
11656 ;; The heuristic above doesn't work well when we're
11657 ;; creating a comment and there's another one downstream,
11658 ;; as our parser thinks this one ends at the end of the
11659 ;; next one. (You can have a /* inside a js block comment.)
11660 ;; So just close it if the next non-ws char isn't a *.
11661 (and first-line
11662 (eolp)
11663 (save-excursion
11664 (skip-chars-forward " \t\r\n")
11665 (not (eq (char-after) ?*))))))
11666 (delete-horizontal-space)
11667 (insert "\n")
11668 (cond
11669 (star
11670 (indent-to col)
11671 (insert "* ")
11672 (if (and first-line needs-close)
11673 (save-excursion
11674 (insert "\n")
11675 (indent-to col)
11676 (insert "*/"))))
11677 ((and single
11678 (save-excursion
11679 (and (zerop (forward-line 1))
11680 (looking-at "\\s-*//"))))
11681 (indent-to col)
11682 (insert "// ")))
11683 ;; Don't need to extend the comment after all.
11684 (js2-indent-line)))
11685
11686 (defun js2-beginning-of-line ()
11687 "Toggle point between bol and first non-whitespace char in line.
11688 Also moves past comment delimiters when inside comments."
11689 (interactive)
11690 (let (node)
11691 (cond
11692 ((bolp)
11693 (back-to-indentation))
11694 ((looking-at "//")
11695 (skip-chars-forward "/ \t"))
11696 ((and (eq (char-after) ?*)
11697 (setq node (js2-comment-at-point))
11698 (memq (js2-comment-node-format node) '(jsdoc block))
11699 (save-excursion
11700 (skip-chars-backward " \t")
11701 (bolp)))
11702 (skip-chars-forward "\* \t"))
11703 (t
11704 (goto-char (point-at-bol))))))
11705
11706 (defun js2-end-of-line ()
11707 "Toggle point between eol and last non-whitespace char in line."
11708 (interactive)
11709 (if (eolp)
11710 (skip-chars-backward " \t")
11711 (goto-char (point-at-eol))))
11712
11713 (defun js2-mode-wait-for-parse (callback)
11714 "Invoke CALLBACK when parsing is finished.
11715 If parsing is already finished, calls CALLBACK immediately."
11716 (if (not js2-mode-buffer-dirty-p)
11717 (funcall callback)
11718 (push callback js2-mode-pending-parse-callbacks)
11719 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11720
11721 (defun js2-mode-parse-finished ()
11722 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11723 ;; We can't let errors propagate up, since it prevents the
11724 ;; `js2-parse' method from completing normally and returning
11725 ;; the ast, which makes things mysteriously not work right.
11726 (unwind-protect
11727 (dolist (cb js2-mode-pending-parse-callbacks)
11728 (condition-case err
11729 (funcall cb)
11730 (error (message "%s" err))))
11731 (setq js2-mode-pending-parse-callbacks nil)))
11732
11733 (defun js2-mode-flag-region (from to flag)
11734 "Hide or show text from FROM to TO, according to FLAG.
11735 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11736 Returns the created overlay if FLAG is non-nil."
11737 (remove-overlays from to 'invisible 'js2-outline)
11738 (when flag
11739 (let ((o (make-overlay from to)))
11740 (overlay-put o 'invisible 'js2-outline)
11741 (overlay-put o 'isearch-open-invisible
11742 'js2-isearch-open-invisible)
11743 o)))
11744
11745 ;; Function to be set as an outline-isearch-open-invisible' property
11746 ;; to the overlay that makes the outline invisible (see
11747 ;; `js2-mode-flag-region').
11748 (defun js2-isearch-open-invisible (_overlay)
11749 ;; We rely on the fact that isearch places point on the matched text.
11750 (js2-mode-show-element))
11751
11752 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11753 "Return cons cell of bounds of folding overlay at POS.
11754 Returns nil if not found."
11755 (let ((overlays (overlays-at (or pos (point))))
11756 o)
11757 (while (and overlays
11758 (not o))
11759 (if (overlay-get (car overlays) 'invisible)
11760 (setq o (car overlays))
11761 (setq overlays (cdr overlays))))
11762 (if o
11763 (cons (overlay-start o) (overlay-end o)))))
11764
11765 (defun js2-mode-function-at-point (&optional pos)
11766 "Return the innermost function node enclosing current point.
11767 Returns nil if point is not in a function."
11768 (let ((node (js2-node-at-point pos)))
11769 (while (and node (not (js2-function-node-p node)))
11770 (setq node (js2-node-parent node)))
11771 (if (js2-function-node-p node)
11772 node)))
11773
11774 (defun js2-mode-toggle-element ()
11775 "Hide or show the foldable element at the point."
11776 (interactive)
11777 (let (comment fn pos)
11778 (save-excursion
11779 (cond
11780 ;; /* ... */ comment?
11781 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11782 (if (js2-mode-invisible-overlay-bounds
11783 (setq pos (+ 3 (js2-node-abs-pos comment))))
11784 (progn
11785 (goto-char pos)
11786 (js2-mode-show-element))
11787 (js2-mode-hide-element)))
11788 ;; //-comment?
11789 ((save-excursion
11790 (back-to-indentation)
11791 (looking-at js2-mode-//-comment-re))
11792 (js2-mode-toggle-//-comment))
11793 ;; function?
11794 ((setq fn (js2-mode-function-at-point))
11795 (setq pos (and (js2-function-node-body fn)
11796 (js2-node-abs-pos (js2-function-node-body fn))))
11797 (goto-char (1+ pos))
11798 (if (js2-mode-invisible-overlay-bounds)
11799 (js2-mode-show-element)
11800 (js2-mode-hide-element)))
11801 (t
11802 (message "Nothing at point to hide or show"))))))
11803
11804 (defun js2-mode-hide-element ()
11805 "Fold/hide contents of a block, showing ellipses.
11806 Show the hidden text with \\[js2-mode-show-element]."
11807 (interactive)
11808 (if js2-mode-buffer-dirty-p
11809 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11810 (let (node body beg end)
11811 (cond
11812 ((js2-mode-invisible-overlay-bounds)
11813 (message "already hidden"))
11814 (t
11815 (setq node (js2-node-at-point))
11816 (cond
11817 ((js2-block-comment-p node)
11818 (js2-mode-hide-comment node))
11819 (t
11820 (while (and node (not (js2-function-node-p node)))
11821 (setq node (js2-node-parent node)))
11822 (if (and node
11823 (setq body (js2-function-node-body node)))
11824 (progn
11825 (setq beg (js2-node-abs-pos body)
11826 end (+ beg (js2-node-len body)))
11827 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11828 (message "No collapsable element found at point"))))))))
11829
11830 (defun js2-mode-show-element ()
11831 "Show the hidden element at current point."
11832 (interactive)
11833 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11834 (if bounds
11835 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11836 (message "Nothing to un-hide"))))
11837
11838 (defun js2-mode-show-all ()
11839 "Show all of the text in the buffer."
11840 (interactive)
11841 (js2-mode-flag-region (point-min) (point-max) nil))
11842
11843 (defun js2-mode-toggle-hide-functions ()
11844 (interactive)
11845 (if js2-mode-functions-hidden
11846 (js2-mode-show-functions)
11847 (js2-mode-hide-functions)))
11848
11849 (defun js2-mode-hide-functions ()
11850 "Hides all non-nested function bodies in the buffer.
11851 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11852 to open an individual entry."
11853 (interactive)
11854 (if js2-mode-buffer-dirty-p
11855 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11856 (if (null js2-mode-ast)
11857 (message "Oops - parsing failed")
11858 (setq js2-mode-functions-hidden t)
11859 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11860
11861 (defun js2-mode-function-hider (n endp)
11862 (when (not endp)
11863 (let ((tt (js2-node-type n))
11864 body beg end)
11865 (cond
11866 ((and (= tt js2-FUNCTION)
11867 (setq body (js2-function-node-body n)))
11868 (setq beg (js2-node-abs-pos body)
11869 end (+ beg (js2-node-len body)))
11870 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11871 nil) ; don't process children of function
11872 (t
11873 t))))) ; keep processing other AST nodes
11874
11875 (defun js2-mode-show-functions ()
11876 "Un-hide any folded function bodies in the buffer."
11877 (interactive)
11878 (setq js2-mode-functions-hidden nil)
11879 (save-excursion
11880 (goto-char (point-min))
11881 (while (/= (goto-char (next-overlay-change (point)))
11882 (point-max))
11883 (dolist (o (overlays-at (point)))
11884 (when (and (overlay-get o 'invisible)
11885 (not (overlay-get o 'comment)))
11886 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11887
11888 (defun js2-mode-hide-comment (n)
11889 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11890 3 ; /**
11891 2)) ; /*
11892 (beg (+ (js2-node-abs-pos n) head))
11893 (end (- (+ beg (js2-node-len n)) head 2))
11894 (o (js2-mode-flag-region beg end 'hide)))
11895 (overlay-put o 'comment t)))
11896
11897 (defun js2-mode-toggle-hide-comments ()
11898 "Folds all block comments in the buffer.
11899 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11900 to open an individual entry."
11901 (interactive)
11902 (if js2-mode-comments-hidden
11903 (js2-mode-show-comments)
11904 (js2-mode-hide-comments)))
11905
11906 (defun js2-mode-hide-comments ()
11907 (interactive)
11908 (if js2-mode-buffer-dirty-p
11909 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11910 (if (null js2-mode-ast)
11911 (message "Oops - parsing failed")
11912 (setq js2-mode-comments-hidden t)
11913 (dolist (n (js2-ast-root-comments js2-mode-ast))
11914 (when (js2-block-comment-p n)
11915 (js2-mode-hide-comment n)))
11916 (js2-mode-hide-//-comments)))
11917
11918 (defun js2-mode-extend-//-comment (direction)
11919 "Find start or end of a block of similar //-comment lines.
11920 DIRECTION is -1 to look back, 1 to look forward.
11921 INDENT is the indentation level to match.
11922 Returns the end-of-line position of the furthest adjacent
11923 //-comment line with the same indentation as the current line.
11924 If there is no such matching line, returns current end of line."
11925 (let ((pos (point-at-eol))
11926 (indent (current-indentation)))
11927 (save-excursion
11928 (while (and (zerop (forward-line direction))
11929 (looking-at js2-mode-//-comment-re)
11930 (eq indent (length (match-string 1))))
11931 (setq pos (point-at-eol)))
11932 pos)))
11933
11934 (defun js2-mode-hide-//-comments ()
11935 "Fold adjacent 1-line comments, showing only snippet of first one."
11936 (let (beg end)
11937 (save-excursion
11938 (goto-char (point-min))
11939 (while (re-search-forward js2-mode-//-comment-re nil t)
11940 (setq beg (point)
11941 end (js2-mode-extend-//-comment 1))
11942 (unless (eq beg end)
11943 (overlay-put (js2-mode-flag-region beg end 'hide)
11944 'comment t))
11945 (goto-char end)
11946 (forward-char 1)))))
11947
11948 (defun js2-mode-toggle-//-comment ()
11949 "Fold or un-fold any multi-line //-comment at point.
11950 Caller should have determined that this line starts with a //-comment."
11951 (let* ((beg (point-at-eol))
11952 (end beg))
11953 (save-excursion
11954 (goto-char end)
11955 (if (js2-mode-invisible-overlay-bounds)
11956 (js2-mode-show-element)
11957 ;; else hide the comment
11958 (setq beg (js2-mode-extend-//-comment -1)
11959 end (js2-mode-extend-//-comment 1))
11960 (unless (eq beg end)
11961 (overlay-put (js2-mode-flag-region beg end 'hide)
11962 'comment t))))))
11963
11964 (defun js2-mode-show-comments ()
11965 "Un-hide any hidden comments, leaving other hidden elements alone."
11966 (interactive)
11967 (setq js2-mode-comments-hidden nil)
11968 (save-excursion
11969 (goto-char (point-min))
11970 (while (/= (goto-char (next-overlay-change (point)))
11971 (point-max))
11972 (dolist (o (overlays-at (point)))
11973 (when (overlay-get o 'comment)
11974 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11975
11976 (defun js2-mode-display-warnings-and-errors ()
11977 "Turn on display of warnings and errors."
11978 (interactive)
11979 (setq js2-mode-show-parse-errors t
11980 js2-mode-show-strict-warnings t)
11981 (js2-reparse 'force))
11982
11983 (defun js2-mode-hide-warnings-and-errors ()
11984 "Turn off display of warnings and errors."
11985 (interactive)
11986 (setq js2-mode-show-parse-errors nil
11987 js2-mode-show-strict-warnings nil)
11988 (js2-reparse 'force))
11989
11990 (defun js2-mode-toggle-warnings-and-errors ()
11991 "Toggle the display of warnings and errors.
11992 Some users don't like having warnings/errors reported while they type."
11993 (interactive)
11994 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11995 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11996 (if (called-interactively-p 'any)
11997 (message "warnings and errors %s"
11998 (if js2-mode-show-parse-errors
11999 "enabled"
12000 "disabled")))
12001 (js2-reparse 'force))
12002
12003 (defun js2-mode-customize ()
12004 (interactive)
12005 (customize-group 'js2-mode))
12006
12007 (defun js2-mode-forward-sexp (&optional arg)
12008 "Move forward across one statement or balanced expression.
12009 With ARG, do it that many times. Negative arg -N means
12010 move backward across N balanced expressions."
12011 (interactive "p")
12012 (setq arg (or arg 1))
12013 (save-restriction
12014 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12015 (js2-reparse)
12016 (let (forward-sexp-function
12017 node (start (point)) pos lp rp child)
12018 (cond
12019 ;; backward-sexp
12020 ;; could probably make this better for some cases:
12021 ;; - if in statement block (e.g. function body), go to parent
12022 ;; - infix exprs like (foo in bar) - maybe go to beginning
12023 ;; of infix expr if in the right-side expression?
12024 ((and arg (minusp arg))
12025 (dotimes (_ (- arg))
12026 (js2-backward-sws)
12027 (forward-char -1) ; Enter the node we backed up to.
12028 (when (setq node (js2-node-at-point (point) t))
12029 (setq pos (js2-node-abs-pos node))
12030 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12031 (setq lp (car parens)
12032 rp (cdr parens)))
12033 (when (and lp (> start lp))
12034 (if (and rp (<= start rp))
12035 ;; Between parens, check if there's a child node we can jump.
12036 (when (setq child (js2-node-closest-child node (point) lp t))
12037 (setq pos (js2-node-abs-pos child)))
12038 ;; Before both parens.
12039 (setq pos lp)))
12040 (let ((state (parse-partial-sexp start pos)))
12041 (goto-char (if (not (zerop (car state)))
12042 ;; Stumble at the unbalanced paren if < 0, or
12043 ;; jump a bit further if > 0.
12044 (scan-sexps start -1)
12045 pos))))
12046 (unless pos (goto-char (point-min)))))
12047 (t
12048 ;; forward-sexp
12049 (dotimes (_ arg)
12050 (js2-forward-sws)
12051 (when (setq node (js2-node-at-point (point) t))
12052 (setq pos (js2-node-abs-pos node))
12053 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12054 (setq lp (car parens)
12055 rp (cdr parens)))
12056 (or
12057 (when (and rp (<= start rp))
12058 (if (> start lp)
12059 (when (setq child (js2-node-closest-child node (point) rp))
12060 (setq pos (js2-node-abs-end child)))
12061 (setq pos (1+ rp))))
12062 ;; No parens or child nodes, looks for the end of the curren node.
12063 (incf pos (js2-node-len
12064 (if (js2-expr-stmt-node-p (js2-node-parent node))
12065 ;; Stop after the semicolon.
12066 (js2-node-parent node)
12067 node))))
12068 (let ((state (save-excursion (parse-partial-sexp start pos))))
12069 (goto-char (if (not (zerop (car state)))
12070 (scan-sexps start 1)
12071 pos))))
12072 (unless pos (goto-char (point-max)))))))))
12073
12074 (defun js2-mode-forward-sexp-parens (node abs-pos)
12075 "Return a cons cell with positions of main parens in NODE."
12076 (cond
12077 ((or (js2-array-node-p node)
12078 (js2-object-node-p node)
12079 (js2-comp-node-p node)
12080 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12081 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12082 ((js2-paren-expr-node-p node)
12083 (let ((lp (js2-node-lp node))
12084 (rp (js2-node-rp node)))
12085 (cons (when lp (+ abs-pos lp))
12086 (when rp (+ abs-pos rp)))))))
12087
12088 (defun js2-node-closest-child (parent point limit &optional before)
12089 (let* ((parent-pos (js2-node-abs-pos parent))
12090 (rpoint (- point parent-pos))
12091 (rlimit (- limit parent-pos))
12092 (min (min rpoint rlimit))
12093 (max (max rpoint rlimit))
12094 found)
12095 (catch 'done
12096 (js2-visit-ast
12097 parent
12098 (lambda (node _end-p)
12099 (if (eq node parent)
12100 t
12101 (let ((pos (js2-node-pos node)) ;; Both relative values.
12102 (end (+ (js2-node-pos node) (js2-node-len node))))
12103 (when (and (>= pos min) (<= end max)
12104 (if before (< pos rpoint) (> end rpoint)))
12105 (setq found node))
12106 (when (> end rpoint)
12107 (throw 'done nil)))
12108 nil))))
12109 found))
12110
12111 (defun js2-errors ()
12112 "Return a list of errors found."
12113 (and js2-mode-ast
12114 (js2-ast-root-errors js2-mode-ast)))
12115
12116 (defun js2-warnings ()
12117 "Return a list of warnings found."
12118 (and js2-mode-ast
12119 (js2-ast-root-warnings js2-mode-ast)))
12120
12121 (defun js2-have-errors-p ()
12122 "Return non-nil if any parse errors or warnings were found."
12123 (or (js2-errors) (js2-warnings)))
12124
12125 (defun js2-errors-and-warnings ()
12126 "Return a copy of the concatenated errors and warnings lists.
12127 They are appended: first the errors, then the warnings.
12128 Entries are of the form (MSG BEG END)."
12129 (when js2-mode-ast
12130 (append (js2-ast-root-errors js2-mode-ast)
12131 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12132
12133 (defun js2-next-error (&optional arg reset)
12134 "Move to next parse error.
12135 Typically invoked via \\[next-error].
12136 ARG is the number of errors, forward or backward, to move.
12137 RESET means start over from the beginning."
12138 (interactive "p")
12139 (if (not (or (js2-errors) (js2-warnings)))
12140 (message "No errors")
12141 (when reset
12142 (goto-char (point-min)))
12143 (let* ((errs (js2-errors-and-warnings))
12144 (continue t)
12145 (start (point))
12146 (count (or arg 1))
12147 (backward (minusp count))
12148 (sorter (if backward '> '<))
12149 (stopper (if backward '< '>))
12150 (count (abs count))
12151 all-errs err)
12152 ;; Sort by start position.
12153 (setq errs (sort errs (lambda (e1 e2)
12154 (funcall sorter (second e1) (second e2))))
12155 all-errs errs)
12156 ;; Find nth error with pos > start.
12157 (while (and errs continue)
12158 (when (funcall stopper (cadar errs) start)
12159 (setq err (car errs))
12160 (if (zerop (decf count))
12161 (setq continue nil)))
12162 (setq errs (cdr errs)))
12163 ;; Clear for `js2-echo-error'.
12164 (message nil)
12165 (if err
12166 (goto-char (second err))
12167 ;; Wrap around to first error.
12168 (goto-char (second (car all-errs)))
12169 ;; If we were already on it, echo msg again.
12170 (if (= (point) start)
12171 (js2-echo-error (point) (point)))))))
12172
12173 (defun js2-down-mouse-3 ()
12174 "Make right-click move the point to the click location.
12175 This makes right-click context menu operations a bit more intuitive.
12176 The point will not move if the region is active, however, to avoid
12177 destroying the region selection."
12178 (interactive)
12179 (when (and js2-move-point-on-right-click
12180 (not mark-active))
12181 (let ((e last-input-event))
12182 (ignore-errors
12183 (goto-char (cadadr e))))))
12184
12185 (defun js2-mode-create-imenu-index ()
12186 "Return an alist for `imenu--index-alist'."
12187 ;; This is built up in `js2-parse-record-imenu' during parsing.
12188 (when js2-mode-ast
12189 ;; if we have an ast but no recorder, they're requesting a rescan
12190 (unless js2-imenu-recorder
12191 (js2-reparse 'force))
12192 (prog1
12193 (js2-build-imenu-index)
12194 (setq js2-imenu-recorder nil
12195 js2-imenu-function-map nil))))
12196
12197 (defun js2-mode-find-tag ()
12198 "Replacement for `find-tag-default'.
12199 `find-tag-default' returns a ridiculous answer inside comments."
12200 (let (beg end)
12201 (js2-with-underscore-as-word-syntax
12202 (save-excursion
12203 (if (and (not (looking-at "[[:alnum:]_$]"))
12204 (looking-back "[[:alnum:]_$]"))
12205 (setq beg (progn (forward-word -1) (point))
12206 end (progn (forward-word 1) (point)))
12207 (setq beg (progn (forward-word 1) (point))
12208 end (progn (forward-word -1) (point))))
12209 (replace-regexp-in-string
12210 "[\"']" ""
12211 (buffer-substring-no-properties beg end))))))
12212
12213 (defun js2-mode-forward-sibling ()
12214 "Move to the end of the sibling following point in parent.
12215 Returns non-nil if successful, or nil if there was no following sibling."
12216 (let* ((node (js2-node-at-point))
12217 (parent (js2-mode-find-enclosing-fn node))
12218 sib)
12219 (when (setq sib (js2-node-find-child-after (point) parent))
12220 (goto-char (+ (js2-node-abs-pos sib)
12221 (js2-node-len sib))))))
12222
12223 (defun js2-mode-backward-sibling ()
12224 "Move to the beginning of the sibling node preceding point in parent.
12225 Parent is defined as the enclosing script or function."
12226 (let* ((node (js2-node-at-point))
12227 (parent (js2-mode-find-enclosing-fn node))
12228 sib)
12229 (when (setq sib (js2-node-find-child-before (point) parent))
12230 (goto-char (js2-node-abs-pos sib)))))
12231
12232 (defun js2-beginning-of-defun (&optional arg)
12233 "Go to line on which current function starts, and return t on success.
12234 If we're not in a function or already at the beginning of one, go
12235 to beginning of previous script-level element.
12236 With ARG N, do that N times. If N is negative, move forward."
12237 (setq arg (or arg 1))
12238 (if (plusp arg)
12239 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12240 (when (cond
12241 ((js2-function-node-p parent)
12242 (goto-char (js2-node-abs-pos parent)))
12243 (t
12244 (js2-mode-backward-sibling)))
12245 (if (> arg 1)
12246 (js2-beginning-of-defun (1- arg))
12247 t)))
12248 (when (js2-end-of-defun)
12249 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12250
12251 (defun js2-end-of-defun ()
12252 "Go to the char after the last position of the current function
12253 or script-level element."
12254 (let* ((node (js2-node-at-point))
12255 (parent (or (and (js2-function-node-p node) node)
12256 (js2-node-parent-script-or-fn node)))
12257 script)
12258 (unless (js2-function-node-p parent)
12259 ;; Use current script-level node, or, if none, the next one.
12260 (setq script (or parent node)
12261 parent (js2-node-find-child-before (point) script))
12262 (when (or (null parent)
12263 (>= (point) (+ (js2-node-abs-pos parent)
12264 (js2-node-len parent))))
12265 (setq parent (js2-node-find-child-after (point) script))))
12266 (when parent
12267 (goto-char (+ (js2-node-abs-pos parent)
12268 (js2-node-len parent))))))
12269
12270 (defun js2-mark-defun (&optional allow-extend)
12271 "Put mark at end of this function, point at beginning.
12272 The function marked is the one that contains point.
12273
12274 Interactively, if this command is repeated,
12275 or (in Transient Mark mode) if the mark is active,
12276 it marks the next defun after the ones already marked."
12277 (interactive "p")
12278 (let (extended)
12279 (when (and allow-extend
12280 (or (and (eq last-command this-command) (mark t))
12281 (and transient-mark-mode mark-active)))
12282 (let ((sib (save-excursion
12283 (goto-char (mark))
12284 (if (js2-mode-forward-sibling)
12285 (point)))))
12286 (if sib
12287 (progn
12288 (set-mark sib)
12289 (setq extended t))
12290 ;; no more siblings - try extending to enclosing node
12291 (goto-char (mark t)))))
12292 (when (not extended)
12293 (let ((node (js2-node-at-point (point) t)) ; skip comments
12294 ast fn stmt parent beg end)
12295 (when (js2-ast-root-p node)
12296 (setq ast node
12297 node (or (js2-node-find-child-after (point) node)
12298 (js2-node-find-child-before (point) node))))
12299 ;; only mark whole buffer if we can't find any children
12300 (if (null node)
12301 (setq node ast))
12302 (if (js2-function-node-p node)
12303 (setq parent node)
12304 (setq fn (js2-mode-find-enclosing-fn node)
12305 stmt (if (or (null fn)
12306 (js2-ast-root-p fn))
12307 (js2-mode-find-first-stmt node))
12308 parent (or stmt fn)))
12309 (setq beg (js2-node-abs-pos parent)
12310 end (+ beg (js2-node-len parent)))
12311 (push-mark beg)
12312 (goto-char end)
12313 (exchange-point-and-mark)))))
12314
12315 (defun js2-narrow-to-defun ()
12316 "Narrow to the function enclosing point."
12317 (interactive)
12318 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12319 (fn (if (js2-script-node-p node)
12320 node
12321 (js2-mode-find-enclosing-fn node)))
12322 (beg (js2-node-abs-pos fn)))
12323 (unless (js2-ast-root-p fn)
12324 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12325
12326 (provide 'js2-mode)
12327
12328 ;;; js2-mode.el ends here